How to add automatic numbering to elements

This guide will help you set up basic numbering for elements. This numbering can be shown in places like widgets and in places where the element's titleQuery is used. This way of numbering elements will not change the content of the document. This guide uses the DITA figure element (<fig>) throughout its examples.

What you need

1

Create an XQuery module

The first step is to create an XQuery module. Create a file named figureNumbering.xqm in the src directory of a package. The XQuery module will be loaded automatically.

This XQuery module is used to declare a function which, in this case, returns a number for a given figure element.

Numbering callback defined in XQuery module

XQuery

module namespace app = "http://example.app/ns";

declare %public function app:figureNumberingCallback(
    $previousAccumulator as item()*,
    $relType as xs:string,
    $node as node(),
    $isUnloaded as xs:boolean
) as item()* {
    if ($relType eq "first") then
	    (: Return 1 for the first element, $previousAccumulator does not contain a value yet :)
        1
    else
	    (: Increment the accumulator :)
        $previousAccumulator + 1
};

The function shown in this example is a regular XQuery function. It needs to accept the four arguments required by the addReducer function.

2

Add the reducer

The second step is adding the reducer in a configureSxModule.ts file using the addReducer function.

Adding a reducer in a configureSxModule.ts file

TypeScript

import addReducer from 'fontoxml-indices/src/addReducer';

export default function configureSxModule(sxModule) {
    addReducer(
        // namespace and name of the reducer function being defined
        'http://example.app/ns',
        'getFigureNumber',
        // selector matching nodes that should be counted
        'self::fig',
        // namespace and name of the accumulator function we defined above
        'http://example.app/ns',
        'figureNumberingCallback'
    );
}

This example adds the reducer for fig elements.

3

Use the reducer in a label query widget

The reducer function added in the previous step can now be used in the element configuration everywhere XPath queries are allowed.

Using the reducer in a label query widget

TypeScript

// figure
configureAsFrame(sxModule, xq`self::fig`, 'figure', {
	blockHeaderRight: [
		createLabelQueryWidget(xq`
			import module namespace app = "http://example.app/ns";
			"Figure " || app:getFigureNumber(fonto:current-hierarchy-node-id(), .)
		`)
	]
});

A reducer expects the current hierarchy node identifier and a node as its arguments. It will return a number for the given element. The return value can be used in a title or label.

Your editor now shows a label widget in the top right corner of figure frames. The label shows the number of the figure element.

Frequently asked questions

How can automatic numbering be restarted per document or section?