Last updatedNov 4, 2020

Rate this page:

Use content actions to count the macros in a Confluence page

This tutorial describes how to create a Forge app that displays the number of macros in a Confluence page. The app retrieves the body of the page, counts the number of macros, then displays the result in a modal dialog. A user triggers the action from an entry in the more actions (...) menu.

The final app looks like the following:

Confluence page showing a modal dialog with macros used in this page.

Before you begin

This tutorial assumes you're already familiar with developing on Forge. If this is your first time using Forge, see Getting started for step-by-step instructions on setting up Forge.

To complete this tutorial, you need the following:

  • The latest version of Forge CLI. To update your CLI version, run npm install -g @forge/cli@latest on the command line.
  • The latest version of the UI kit. To update your version, navigate to the app's top-level directory, and run npm install @forge/ui@latest --save on the command line.
  • An Atlassian cloud site with Confluence where you can install your app. You need to be an admin on the site to install the app.

Create your app

The app retrieves the body of the page, counts the number of macros, then displays the result in a modal dialog.

  1. Navigate to the directory where you want to create the app.
  2. Create your app by running:
    1
    forge create
    1. Enter a name for the app. For example, macro-counter.
    2. Select the confluence-macro template from the list.
  3. Open the app directory to see the app files.

Update the manifest

To register the functionality of your app, add confluence:contentAction and function modules to the manifest. The confluence:contentAction module adds an entry to the more actions (...) menu, with the value of title. The function module contains the logic to count and display the number of macros.

  1. In the app's top-level directory, open the manifest.yml file.
  2. Replace the macro entry under modules with the following confluence:contentAction.
    1
    2
    3
    4
    confluence:contentAction:
      - key: macro-counter
        title: Macro count
        function: main

Your manifest.yml should look like the following, with your value for the app ID:

1
2
3
4
5
6
7
8
9
10
11
modules:
  confluence:contentAction:
    - key: macro-counter
      title: Macro count
      function: main
  function:
    - key: main
      handler: index.run
app:
  id: '<your-app-id>'
  name: macro-counter

Build, deploy, and install

Build, deploy, and install the app to see it in your Confluence site.

  1. Navigate to the app's top-level directory and deploy your app by running:

    1
    forge deploy
  2. Install your app by running:

    1
    forge install
    1. Select your Atlassian product using the arrow keys and press the enter key.

      Note: Running the forge install command only installs your app onto the selected product. To install onto multiple products, repeat these steps again, selecting another product each time.

    2. Enter the URL for your development site. For example, example.atlassian.net.

      View a list of your active sites at Atlassian administration.

Once the successful installation message appears, your app is installed and ready to use on the specified site. You can always delete your app from the site by running the forge uninstall command.

View the app

With the app installed, it's time to see the entry in the more actions (...) menu.

  1. Navigate to your Confluence Cloud site, then open a page.
  2. Select the more actions (...) menu.

You'll see the Count macros entry from the app.

Note, if you select the menu item, the following error displays because you haven't implemented the app logic yet. You'll do this in the next step.

1
You must have a <ContentAction> at the root.

Implement the front end

Add the UI kit components that render when a user views the app. You'll use a static value for the number of macros in the page.

  1. In terminal, navigate to the app's top-level directory and install the runtime API package by running:
    1
    npm install @forge/api
  2. Start tunneling to view your local changes by running:
    1
    forge tunnel
  3. Open the src/index.jsx file.
  4. Replace the contents of the file with:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    // Import required components from the UI kit
    import ForgeUI, { ContentAction, ModalDialog, render, Text, useAction, useProductContext, useState } from "@forge/ui";
    import api from "@forge/api";
    
    // You'll implement getContent and countMacros later
    const getContent = async (contentId) => {
        return {};
    };
    
    const countMacros = (data) => {
        return 10;
    };
    
    const App = () => {
        const [isOpen, setOpen] = useState(true);
        if (!isOpen) {
            return null;
        }
    
        const { contentId } = useProductContext();
        const [data] = useAction(
            () => null,
            async () => await getContent(contentId)
        );
    
        const macroCount = countMacros(data);
    
        return (
            <ModalDialog header="Macro count" onClose={() => setOpen(false)}>
                <Text>{`Number of macros on this page: ${macroCount}`}</Text>
            </ModalDialog>
        );
    };
    
    export const run = render(
        <ContentAction>
            <App/>
        </ContentAction>
    );
  5. Refresh a Confluence page on your site, open the more actions (...) menu, and select Count macros.

    A modal dialog displays with:

    1
    Number of macros on this page: 10

In the code from this step:

  • The import statement lists the components to use from the UI kit. See UI kit components to learn more about these components.
  • isOpen keeps the state of ModalDialog, setOpen is called when the ModalDialog closes.
  • useAction awaits the asynchronous getContent function to complete. See UI kit hooks to learn more about useState, useAction, and useProductContext.
  • The getContent function gets the contents of a page from Confluence.
  • The countMacros function returns the number of macros in the page. At this stage, the function always returns 10.
  • ModalDialog displays the number of macros in the page.
  • Exporting the run constant provides the mechanism that renders the app.

Call the Confluence REST API

Turn the static app into a dynamic app by making an API call to Confluence to retrieve the contents of the page.

  1. Check the tunnel is still running. If it's not, start the tunnel again.
  2. Open the src/index.jsx file.
  3. Get the contents of the page by replacing the getContent function with:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    const getContent = async (contentId) => {
        const response = await api.asApp().requestConfluence(`/rest/api/content/${contentId}?expand=body.atlas_doc_format`);
    
        if (!response.ok) {
            const err = `Error while getContent with contentId ${contentId}: ${response.status} ${response.statusText}`;
            console.error(err);
            throw new Error(err);
        }
    
        return await response.json();
    };
  4. Count the number of macros by replacing the countMacros function with:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    const countMacros = (data) => {
        if (!data || !data.body || !data.body.atlas_doc_format || !data.body.atlas_doc_format.value) {
            return 0;
        }
    
        const { body: { atlas_doc_format: { value } } } = data;
        const { content: contentList } = JSON.parse(value);
    
        const macros = contentList.filter((content) => {
            return content.type === "extension";
        });
    
        return macros.length;
    };
  5. Refresh the Confluence page, open the more actions (...) menu, and select Count macros. The modal dialog shows the number of macros in the page.

Edit the page to add macros and select Count macros again to see the number update.

Close the tunnel and deploy the app

After confirming the app works locally, deploy the app so that it continues to work when you close the tunnel.

  1. Close your tunnel by pressing Ctrl+C.
  2. Deploy your app by running:
    1
    forge deploy

That’s it. You've built an app that retrieves the contents of a page, counts the number of macros, then displays the result in a modal dialog.

Next steps

Check out an example app, continue to one of the other tutorials, or read through the reference pages to learn more.

Rate this page: