Editor API allows the user to perform different operations on the currently opened document. They are available within the Context Object, when the user is editing a Story.

Editor API are to be considered as a feature in progress. Changes and additions may be made without warning.

In the source code, we will refer to the Context Object as a generic "ctx" object.

activeDocument

The activeDocument is the entry point of the Editor API. It contains a set of different methods to analyze and manage the currently opened document.

Methods of the activeDocument object

getXmlContent

Returns the complete XML content of the document.

It can be called as

ctx.activeDocument.getXmlContent(options);
Table 1. Method information

Method

getXmlContent

Parameter * Optional {object} options - An object containing optional criteria about the xml content:

  • Optional {boolean} includeInherited - if true the xml will contain inherited sections content in place of reference.

If options is not specied or if it’s an empty object the xml of the entire document will be returned.

Returns

{String} The XML document as a string.

Example
// Obtains the XML of the document.
var xml = ctx.activeDocument.getXmlContent();

// For example, we can parse the XML with jQuery and use it somehow.
var parsedXML = $.parseXML( xml );

// ...

getTextContent

Returns the complete text content of the document.

It can be called as

ctx.activeDocument.getTextContent(options);
Table 2. Method information

Method

getTextContent

Parameter

Optional {object} options - An object containing the some options. It can contains the following properties:

  • Optional {Boolean} includeWhitespaceNodes - true if you want to include the whitespace nodes.

Returns

{String} The text content of the document as a string.

Example
// Obtains the text content of the document.
var options = {};
// Uncomment this line if you want to include witespace nodes
options.includeWhitespaceNodes = true;

var text = ctx.activeDocument.getTextContent(options);

// ...

getMetadata

Returns the complete Metadata of the document as a string.

It can be called as

ctx.activeDocument.getMetadata( callbacks );
Table 3. Method information

Method

getMetadata

Parameter

{object} callbacks - An object containing the callbacks. It contains the following properties:

  • Required {Function} success - the function to be called when the Metadata is retrieved. It has a single parameter, the metadata as a string.

  • Optional {Function} error - the function to be called when an error occurred.

Returns

undefined

This call is asynchronous. The Metadata string is available only as the parameter of the success callback.

Example
// Obtains the Metadata of the document
ctx.activeDocument.getMetadata({
    success: function( metadata ) {
        // Do something with this...
    },
    error: function( err ) {
        // For example.
        ctx.showError( err.message );
    }
});

getSelection

Returns the current Selection in the active document.

The current selection is an object of type Selection. See Selection object for further information on available methods.

It can be called as

ctx.activeDocument.getSelection();
Table 4. Method information

Method

getSelection

Parameter

None

Returns

{Selection} The current selection object

Example
// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();

// sel is now a Selection object.
// For example, we can verify that the current selection is a ContentItem

var selNode = sel.getNode();

if ( selNode.nodeType === ctx.activeDocument.CONSTANTS.CONTENTITEM_TYPE ) {
    // Perform a specific action...
}

insertXML

Insert an XML in a specified part of the document.

It can be called as

ctx.activeDocument.insertXML(xml, xpathOptions, insertOptions);
Table 5. Method information

Method

insertXML

Parameter

{String} xml - The xml to insert, as a string.

e.g. <p>Append me</p>

Parameter

{object} xpathOptions - Contains the information on the XPath to append the XML to. It contains the following properties:

  • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

    • NOTE: if xpath is set to the value cursorPosition the new content will be inserted at the cursor position replacing the current selection if not collapsed.

  • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

    • {String} param the attribute to test (e.g. xsm-preserve). The eom-name is not a valid attribute if specified it will be ignored.

    • {String} condition the operator to use in the selector. Can be equal or contains.

    • {String} value the value to test for.

See example below.

Parameter

{object / string} insertOptions the options to insert the XML in the selected node. If used as an object, it contains the following properties:

  • Optional {String} insertType - determines where to insert the xml with respect to the node. Defaults to append, can be prepend or insertBefore (which both prepend the content to the selected node).

Otherwise, it is possible to directly pass the insertType as a string (append, prepend or insertBefore)

Returns

{Boolean} true if the operation was executed correctly

At the moment, if the specified xpath in the xpathOptions corresponds to more than one xPath, only the first is taken.

// Prepares the xml.
var xml = '<p>Prepend me</p>';

ctx.activeDocument.insertXml( xml, {
    xpath: 'doc/story/text/superbyline',
    criteria: {
        [
            param: 'xsm-preserve',
            condition: 'equal',
            value: 'true'
        ]
    } },
    'prepend' );

// the xml will be inserted only in the first superbyline tag that satisfy xpath and the additional (optional) criteria


// Prepares the xml.
var xml = '<h1><?EM-dummyText lorem ipsum?></h1>';

ctx.activeDocument.insertXml( xml, {xpath: 'cursorPosition'});

// the xml will be inserted at the cursor position, replacing the current selection if not collapsed.

getDocumentInfo

Returns a subset of information on the current document. The information includes the following information : channel, workfolder, issueDate, templateName, language.

It can be called as

ctx.activeDocument.getDocumentInfo();
Table 6. Method information

Method

getDocumentInfo

Parameter

None

Returns

{JSON Object} Information on the current document

Example
// Obtains the document information.
var documentInfo = ctx.activeDocument.getDocumentInfo();

/*
    documentInfo is now:
    {
        "id": "id",
        "readonly": true,
        "channel": "CHANNEL",
        "workfolder": "WORKFOLDER",
        "issueDate": "ISSUE DATE",
        "templateName": "TEMPLATE NAME",
        "language": "en/uk"
    }

*/

if ( documentInfo.channel === 'Globe-Web' ) {
    // ... do something, for example it can remove a specific custom button.
}

isReadonly

Returns the readonly status of the story

It can be called as

ctx.activeDocument.isReadonly();
Table 7. Method information

Method

isReadonly

Parameter

None

Returns

{Boolean} true if the story is readonly

Example
// Obtains the document information.
var isReadonly = ctx.activeDocument.isReadonly();

getSelectionPathInfo

Returns an object containing basic information on the selected path.

It can be called as

ctx.activeDocument.getSelectionPathInfo();
Table 8. Method information

Method

getSelectionPathInfo

Parameter

None

Returns

{Object} containing basic information on the selected path.

Example
// Obtains the document information.
var pathInfo = ctx.activeDocument.getSelectionPathInfo();

console.log(pathInfo);
->
{
    txtPath: "/doc/story/text/p",
    contentItem: "text",
    contentItemCfg: "text",
    editingType: "text",
    collapsed: true,
    isDummyText: false,
    isEmpty: false,
    isAnchor: false,
    isInCrossReference: false,
    isInTable: false,
    sameTable: false,
    isInContainer: false,
    isInComponent: false,
    isInSection: true,
    isNote: null,
    isInFootnote: false,
    annotationInfo: {
        isInAnnotation: false,
        content: ""
    },
    isEditingAllowed: true,
    isEditingCaption: false,
    isEditingCollage: false,
    isPictureDesk: false,
    isEditingGallery: false
}

saveDocument

Execute the save of the current document.

It can be called as

ctx.activeDocument.saveDocument();
Table 9. Method information

Method

saveDocument

Parameter

Optional {Function} callback - A function invoked if the the document is successfully saved

If the document is not dirty, the save is not executed, but the callback, if defined, is always invoked.

Example
// Save the current document.
ctx.activeDocument.saveDocument();

getNode

Returns a specific node, as a DocumentNode object, upon the information contained in the XPath

It can be called as

ctx.activeDocument.getNode(xpathOptions);
Table 10. Method information

Method

getNode

Parameter

{object} xpathOptions - Contains the information on the XPath to append the XML to. It contains the following properties:

  • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

  • Optional {object} absolute [default: false] - if true, the search is limited to the absolute XPath.

  • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

    • {String} param the attribute to test (e.g. eom-name, xsm-preserve)

    • {String} condition the operator to use in the selector. Can be equal or contains.

    • {String} value the value to test for.

Return

{DocumentNode} A document node object containing. See DocumentNode interface object for details on the Document Node object.

At the moment, if the specified xpath in the xpathOptions corresponds to more than one node, only the first is taken.

Example
// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/text',
    criteria: {
      [ param: 'channel',
        condition: 'equal',
        value: 'Globe-Print'
      ]
    }
};

// Obtains the node.
var node = ctx.activeDocument.getNode(xpathOptions);

// Perform actions on the found node
// ...
if (node) {
...

}

insertExternalUrl

Insert an external URL in the document, upon the information contained in the object to insert and in the provided options

It can be called as

ctx.activeDocument.insertExternalUrl(item, insertOptions);
Table 11. Method information

Method

insertExternalUrl

Parameter

{object} item - Contains the information about the object to insert. It contains the following properties:

  • Required {String} url - the url of the object to insert.

  • Required {String} type - the type of the object to insert. The suppoerted type are the following:

    • webimage insert the object in the EOMDB and try to insert the created object as image

    • externalwebpage insert the object as link in the opened document

    • embedurl insert the object as embed code bock if the provided url is a supported embed

Parameter

{object} insertOptions - Contains additional option to insert the object. Right now not used, for future purpose

Return

{Boolean} true if the object has been successfully inserted, false otherwise.

Example
// prepare the object to insert
var item = {
    'url': 'https://images-assets.nasa.gov/image/GSFC_20171208_Archive_e001240/GSFC_20171208_Archive_e001240~orig.jpg',
    'type': 'web::image'
};

// Perform the insert.
ctx.activeDocument.insertExternalUrl(item, {});

insertObject

Insert a list of Methode Object in the document, upon the information contained in the reference object to insert and in the provided insertOptions

It can be called as

ctx.activeDocument.insertObject(reference, insertOptions);
Table 12. Method information

Method

insertObject

Parameter

{object} reference - Contains the information about the object to insert. It contains the following properties:

  • Required {Boolean} full - if true the provided object list containing all the information about the objects to insert, if false, only an idntifier is provided (i.e. path or loid or uuid) and the information about the object is retrieved during insertion.

  • Optional {Boolean} withPath - if true the list of objects identifiers is composed of paths, otherwise of loid or uuid. This parameter is checked only whe the referenceListIds is provided

  • Optional {Array} referenceListIds - The list of objects identifiers to insert. It can be composed of paths, loids or uuids.

  • Optional {Array} referenceListObjects - The list of objects to insert. It is composed of the full object info.

    • NOTE: referenceListIds or referenceListObjects must be provided

Parameter

{object} insertOptions - Contains additional option to insert the object.

  • Required {String} insertionType [insert, embed, link] - The type of insertion that must be performed

  • Optional {Object} templateInfo - Info about the information of the template used to insert the object.

    • Optional {String} name name of the template to use, configured in the dtx. If not specified, the user can subsequently choose which template to use

    • Optional {String} type The type of the object to insert. If not specified it will be obtained from the type of objects to be inserted

Return

{Boolean} true if the objects has been successfully inserted, false otherwise.

Example
// prepare the object to insert
// Two image objects will be inserted using the paths
const reference = {
    full: false,
    referenceListIds: ['/Globe/Images/Foreign/11.obama_family.jpeg', '/Globe/Images/Foreign/1420087334.jpg'],
    withPath: true
}

// Example One
const insertOptionsOne = {
    insertiontype: "insert"
};

// Perform the insert.
ctx.activeDocument.insertObject(reference, insertOptionsOne);

// Example Two
const insertOptionsTwo = {
    insertiontype: "insert",
    templateInfo: {name: "", type: eomeditor.publicapi.TEMPLATE_TYPE.IMAGE}
};

// Perform the insert.
ctx.activeDocument.insertObject(reference, insertOptionsTwo);

// Example Three
const insertOptionsThree = {
    insertiontype: "insert",
    templateInfo: {name: "image web square", type: eomeditor.publicapi.TEMPLATE_TYPE.IMAGE}
};

// Perform the insert.
ctx.activeDocument.insertObject(reference, insertOptionsThree);

setDocumentToBeRefreshed

Some events in Swing are not handled. This API could be useful when some actions are fired and they change the document server side. This way, it’s possible to warn the user that the document should be refresh.

It can be called as

ctx.activeDocument.setDocumentToBeRefreshed(options);
Table 13. Method information

Method

setDocumentToBeRefreshed

Parameter

{object} options - Contains additional option. Right now not used, for future purpose

Return

{Boolean} true if the operation has been successfully executed, false otherwise.

Example
action: function(ctx, params, callback) {

    var editorApi = ctx.activeDocument;

    editorApi.setDocumentToBeRefreshed();
}

switchToChannel(channel)

Switch the document to the specified channel

It can be called as

ctx.activeDocument.getCollectionSelectedItems(attrOptions)
Table 14. Method information

Method

switchToChannel

Parameter

Required {String} channel - A string containing the channel in form of "Product/Edition".

// Switch to channel
ctx.activeDocument.switchToChannel(channel);

Constants of the activeDocument object

The activeDocument object comes with a set of constants to simplify the management of the return values of the different methods.

The constants are available under

activeDocument.CONSTANTS

Currently the following constants are visible:

ctx.activeDocument.CONSTANTS = {
    DUMMY_TYPE: 'DummyText', // Document Node type
    CONTENTITEM_TYPE: 'ContentItem', // Document Node type
    CONTENTBLOCK_TYPE: 'ContentBlock', // Document Node type
    CONTENTNODE_TYPE: 'ContentNode', // Document Node type,
    BLOCK_IMAGE: 'image', // ContentBlock of type Image
    BLOCK_VIDEO: 'video', // ContentBlock of type Video
};

activeDocumentV2

The activeDocumentV2 is an entry point of the Editor API starting form version 5.2020.11. It contains a set of different methods to analyze and manage the currently opened document in an asynchronous way that are cross platform compatible (Swing, Swing Mobile, Prime). Starting from the version 5.2020.11, we reccomend to use activeDocumentV2 and evaluating the migration for existing extensions.

Methods of the activeDocumentV2 object

getXmlContent

Returns the complete XML content of the document or a part of it based on the options parameter.

It can be called as

ctx.activeDocumentV2.getXmlContent(options);
Table 15. Method information

Method

getXmlContent

Parameter

  • Optional {object} options - An object containing optional criteria about the xml content:

    • Optional {boolean} uesSelection - if true the xml of the selected node will be returned.

    • Optional {boolean} includeInherited - if true the xml will contain inherited sections content in place of reference.

    • Optional {object} xpathOptions - if specified the xml of the idnetified node by information in xpath will be returned. For more info see the same API for the activeDocument object.

      • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

      • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

        • {String} param the attribute to test (e.g. xsm-preserve). The eom-name is not a valid attribute if specified it will be ignored.

        • {String} condition the operator to use in the selector. Can be equal or contains.

        • {String} value the value to test for.

If options is not specied or if it’s an empty object the xml of the entire document will be returned.

Returns

{Function} A promise function.

Example
// Obtains the XML of the document.
ctx.activeDocumentV2.getXmlContent({}).then(result => {
    console.log(`V2 async document result: ${result}`);
}).catch(error => {
    console.log(`V2 async document error: ${error}`);
});

// Obtains the XML of the current selection
ctx.activeDocumentV2.getXmlContent({useSelection: true}).then(result => {
    console.log(`V2 async result selection: ${result}`);
}).catch(error => {
    console.log(`V2 async error selection: ${error}`);
});

// Obtains the XML of a specific node
var xpathOptions = {
              'xpath': 'doc/story/text'
};

ctx.activeDocumentV2.getXmlContent({xpathOptions}).then(result => {
    console.log(`V2 async xpath result: ${result}`);
}).catch(error => {
    console.log(`V2 async xpath error: ${error}`);
});
// ...

getTextContent

Returns the complete text content of the document.

It can be called as

ctx.activeDocumentV2.getTextContent();
Table 16. Method information

Method

getTextContent

Returns

{Function} A promise function.

Example
// Obtains the text of the document.
ctx.activeDocumentV2.getTextContent().then(result => {
    console.log(`V2 async document result: ${result}`);
}).catch(error => {
    console.log(`V2 async document error: ${error}`);
});

// ...

replaceXmlContent

Replaces the XML content of a node.

It can be called as

ctx.activeDocumentV2.replaceXmlContent(options);
Table 17. Method information

Method

replaceXmlContent

Parameter

  • Required {object} options - An object containing the criteria of node on which to replace content:

    • Required {String} newContent - the xml content.

    • Required {object} xpathOptions - if specified the xml of the idnetified node by information in xpath will be returned.

      • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

      • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

        • {String} param the attribute to test (e.g. xsm-preserve). The eom-name is not a valid attribute if specified it will be ignored.

        • {String} condition the operator to use in the selector. Can be equal or contains.

        • {String} value the value to test for.

Return

{Function} A promise function

// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/summary',
    criteria: {
        [
            param: 'channel',
            condition: 'equal',
            value: 'Globe-Print'
        ]
    }
};

// REPLACE XML content
ctx.activeDocumentV2.getXmlContent({xpathOptions}).then( content => {
    var newContent = '<summary id="U26664270086oOb"><p>New summary content</p></summary>';
    ctx.activeDocumentV2.replaceXmlContent({newContent, xpathOptions}).then(result => {
        console.log('content replaced')
    });
})

...
//

saveDocument

Execute the save of the current document.

It can be called as

ctx.activeDocumentV2.saveDocument();
Table 18. Method information

Method

saveDocument

Return

{Function} A promise function

If the document is not dirty, the save is not executed, but the promise is always resolved.

Example
// Save the current document.
ctx.activeDocumentV2.saveDocument().then(result => {
    console.log(`save operation successfully excuted`);
}).catch(error => {
    console.log(`an error occurred saving the document`);
});

insertXmlContent

Insert an XML in a specified part of the document..

It can be called as

ctx.activeDocumentV2.insertXmlContent(options);
Table 19. Method information

Method

insertXmlContent

Parameter

  • Required {object} options - An object containing the criteria of node on which to replace content:

    • Required {String} xmlContent - the xml content to insert.

    • Required {object} xpathOptions - if specified the xml of the idnetified node by information in xpath will be returned.

      • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

      • NOTE: if xpath is set to the value cursorPosition the new content will be inserted at the cursor position replacing the current selection if not collapsed.

      • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

        • {String} param the attribute to test (e.g. xsm-preserve). The eom-name is not a valid attribute if specified it will be ignored.

        • {String} condition the operator to use in the selector. Can be equal or contains.

        • {String} value the value to test for.

Return

{Function} A promise function

var xpathOptions = {
    xpath: 'cursorPosition'
};
var xmlContent = '<h1><?EM-dummyText lorem ipsum?></h1>';
activeDocumentV2.insertXmlContent({xmlContent, xpathOptions}).then(result => {
    console.log('content has been inserted');
}).catch(error => {
    console.log('content has not been inserted');
});

...
//

Selection object

The Selection Object allows to manipulate the selection. It contains a set of properties and methods described below.

Methods

getNode

Returns the current selected node, as a DocumentNode object.

It can be called as

{SelectionObject}.getNode();
Table 20. Method information

Method

getNode

Parameter

Optional {Object} options Additional options to get the node.

- Set options.getWrappedSection = true if it’s needed to get the section wrapped node

Return

{DocumentNode} A document node object containing the current selection. See DocumentNode interface object for details on the Document Node object.

// Obtains the document selection
var sel = ctx.activeDocument.getSelection();

var selectedNode = sel.getNode();

// Perform actions on the selected node
// ...

getXmlContent

Returns the XML of the current Selection.

It can be called as

{SelectionObject}.getXmlContent();
Table 21. Method information

Method

getXmlContent

Parameter

None

Return

{String} The xml of the current selection as a String

// Obtains the document selection
var sel = ctx.activeDocument.getSelection();

var selectedXml = sel.getXmlContent();

// Perform actions on the selected node
// ...

Calling {Selection}.getXmlContent() when a ContentBlock node is selected is equal to call {ContentBlock}.getXmlContent() or {Selection}.getNode().getXmlContent().

insertXml

Insert an XML in a specified part of the current selection or replaces the current selection with the new XML.

It can be called as

{SelectionObject}.insertXML(xml, insertOptions);
Table 22. Method information

Method

insertXML

Parameter

{String} xml - The xml to insert, as a string.

e.g. <p>Append me</p>

Parameter

{object / string} insertOptions the options to insert the XML in the selected node. If used as an object, it contains the following properties:

  • Optional {String} insertType - determines where to insert the xml with respect to the node. Defaults to append, can be prepend or insertBefore (which both prepend the content to the selected node), replace (replace the content of the selected node with the provided xml).

  • Optional {String} closestContainer - indicates, if present, to go up to the container of the selected node, and if found use the container as insertion point. The only supported value right now is section. This is useful in case of the selcted node is wrapped by a more complex container that includes other nodes.

Otherwise, it is possible to directly pass the insertType as a string (append, prepend or insertBefore, replace)

Returns

{Boolean} true if the operation was executed correctly

// Obtains the document information.
var xml = '<p>Prepend me</p>';
var sel = ctx.activeDocument.getSelection();

sel.insertXml( xml, 'prepend' );

// Example with closestContainer
var xml = '<newsletter-widget><p>This is a new section part</p><p>Next paragraph content</p></newsletter-widget>';
var sel = ctx.activeDocument.getSelection();

sel.insertXml( xml, {insertionType: 'prepend', closestContainer: 'section'} );

prepend, append

Insert an XML in a specified part of the current selection. They are shortcuts method for insertXml.

It can be called as

{SelectionObject}.prepend(xml);
{SelectionObject}.append(xml);

See insertXml for further details.

getTextContent

Returns the text content of the current Selection.

It can be called as

{SelectionObject}.getTextContent();
Table 23. Method information

Method

getTextContent

Parameter

Optional {object} options - An object containing the some options. It can contains the following properties:

  • Optional {Boolean} includeWhitespaceNodes - true if you want to include the whitespace nodes.

Return

{String} The text content of the current selection as a String

// Obtains the document selection
var sel = ctx.activeDocument.getSelection();

var options = {};
// Uncomment this line if you want to include witespace nodes
// options.includeWhitespaceNodes = true;
var text = sel.getTextContent(options);

// ...

Calling {Selection}.getTextContent() when a ContentBlock node is selected an empty string will be returned.

DocumentNode interface

It is the lowest-level object available for manipulating the Active Document. It represents a node within the document. It contains different methods and properties to interact with the node.

The DocumentNode object is NOT a DOM node, so operation as $(<DocumentNode>) will not work.

Properties

nodeType

Return the node type. Can be one of the following:

  • ContentItem

  • ContentNode

  • ContentBlock

  • DummyText

Verify the value of this property against the Constants of the activeDocument object to perform the best check.

Each Document Node type has specific methods. See Types for details on each document node.

var sel = ctx.activeDocument.getSelection();
var selectedNode = sel.getNode();

if ( selectedNode.nodeType === ctx.activeDocument.CONSTANTS.DUMMY_TYPE ) {
    // It is a dummy text...
    sel.append('<p>New text here</p>');
}

contentItem

Returns the contentItem in which the element is contained. It can be one of two values:

  • null, if the element is not part of any contentItem, or it is a contentItem itself.

  • {DocumentNode} ContentItem the document node of type 'ContentItem'. See ContentItem for further details.

Methods

getXmlContent

Returns the XML of the node.

It can be called as

{DocumentNode}.getXmlContent();
Table 24. Method information

Method

getXmlContent

Parameter

None

Return

{String} The xml of the node as a String

// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/text',
    criteria: {
       [
        param: 'channel',
        condition: 'equal',
        value: 'Globe-Print'
        ]
    }
};

// Obtains the node.
var node = ctx.activeDocument.getNode(xpathOptions);

// Perform actions on the found node
// ...
if (node) {
    var xmlContent = node.getXmlContent();

}

replaceXmlContent

Replaces the XML content of the current node.

It can be called as

{DocumentNode}.replaceXmlContent();
Table 25. Method information

Method

replaceXmlContent

Parameter

{String} xml - The xml content that replaces the current content node.

Return

{Boolean} True if replacement succeeded

// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/summary',
    criteria: {
        [
            param: 'channel',
            condition: 'equal',
            value: 'Globe-Print'
        ]
    }
};

// Obtains the node.
var node = ctx.activeDocument.getNode(xpathOptions);

// Perform actions on the found node
// ...
if (node) {
    var repxml = '<summary id="U26664270086oOb"><p>New summary content</p></summary>';
    node.replaceXmlContent(repxml);
}

getTextContent

Returns the text content of the node.

It can be called as

{DocumentNode}.getTextContent();
Table 26. Method information

Method

getTextContent

Parameter

Optional {object} options - An object containing the some options. It can contains the following properties:

  • Optional {Boolean} includeWhitespaceNodes - true if you want to include the whitespace nodes.

Return

{String} The text content of the node as a String

// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/text',
    criteria: {
       [
        param: 'channel',
        condition: 'equal',
        value: 'Globe-Print'
        ]
    }
};

// Obtains the node.
var node = ctx.activeDocument.getNode(xpathOptions);

// Perform actions on the found node
// ...
if (node) {

    var options = {};
    // Uncomment this line if you want to include witespace nodes
    // options.includeWhitespaceNodes = true;

    var text = node.getTextContent(options);

    // ....

}

replaceTextContent

Replace the text of the node with another text.

It can be called as

{DocumentNode}.replaceTextContent(text);
Table 27. Method information

Method

replaceTextContent

Parameter

{String} text - The text to replace with.

Parameter

{object} replaceOptions - Contains additional information about the replace operation.

  • Options {String} format - the format of the string used to replace the selected text (e.g. 'xml')

Returns

{Boolean} true if the operation was executed correctly

Right now to execute the replace the API use the information in the current selection.
If a text node is selected the replace is executed with success, otherwise an exception is thrown.
It the selection is not collapsed the current selection is removed and the new text is inserted.
If the selection is collapsed the content of the parent node is checked.
If the text node is not the only child of the parent node the new text wil l be inserted at the cursor position.
Otherwise the entire content of the parent node will be replaced with the new text.

// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();
var selectedNode = sel.getNode();

// Replace the text of the current node with simple text
selectedNode.replaceTextContent( 'Simple text' );

// Replace the text of the current node with an xml format
selectedNode.replaceTextContent('<a href="http://www.eidosmedia.com" title="Eidosmedia">Eidosmedia</a>', {'format': 'xml'});

getContentInfo

Returns an object that contains a set of different methods to analyze and manage the current node.

This method is valid only for content nodes that refers to Methode Content: Images, External content items.
If the selected is not a valid one an exception is thrown.

API functions to get and set system attributes and metadata of an image linked to a story

It can be called as

{DocumentNode}.getContentInfo();
Table 28. Method information

Method

getContentInfo

Parameter

None

Return

{Object} Returns an object with a set of methods. Refer to : Methods of the single object for the list of methods.

// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();
var selectedNode = sel.getNode();

// Perform actions on the found node
// ...
if (selectedNode) {
    var ctx = selectedNode.getContentInfo();

    var id = ctx.getId();
    var type = ctx.getType();
    var sysAttributes = ctx.getSysAttributes();
    var usageTickets = ctx.getUsageTickets();
}

getAttributes

Get node attributes.

It can be called as

{DocumentNode}.getAttributes();
Table 29. Method information

Method

getAttributes

Parameter

None

Return

{Array} An array of objects {{name: String, value: String}} that represent all the attributes of the XML node that have a value.

// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();
var selectedNode = sel.getNode();

// Perform actions on the found node
if (selectedNode) {
    var attributes = selectedNode.getAttributes();

    // ...
}

setAttributes

Set attributes to a node.

It can be called as

{DocumentNode}.setAttributes();
Table 30. Method information

Method

setAttributes

Parameter

{Object} options - The object containing information about attributes to set.

  • Required {Array} attributes - an array of objects pair name/value. If the value is empty the attribute will be removed.

Return

{Boolean} True if replacement succeeded

Don’t use this API to set the channel attribute.
To set the channel attribute it’s mandatory to use the specific API setChannels

// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/summary',
    criteria: {
        [
            param: 'channel',
            condition: 'equal',
            value: 'Globe-Print'
        ]
    }
};

// Obtains the node by x path.
var node = ctx.activeDocument.getNode(xpathOptions);

// To obtain the node by selection uncomment the following lines
// var sel = editorApi.getSelection();
// var node = sel.getNode();

var attrOptions = {};
var attributes = [{'name': 'testattr', 'value': 'testvalue'}];
attrOptions.attributes = attributes;

// Perform actions on the found node
// ...
if (node) {
    node.setAttributes(attrOptions);
}

setExternalReference

Set a refence of a Methode object to a node.

It can be called as

{DocumentNode}.setExternalReference();
Table 31. Method information

Method

setExternalReference

Parameter

Required {String} reference - The object containing information about attributes to set.

Parameter

Optional {Object} settings - Additional options to use setting the reference.

  • Optional {Boolean} cover true the image cover the placeholder

  • Optional {Boolean} hardCrop true the image object is hard cropped

  • Optional {Object} tmx tmx information

  • Optional {Object} xtransform xtransform information

Return

{Boolean} True if replacement succeeded

cover, hardcrop, tmx and xtransform settings are used inserting only images or graphics

var editorApi = ctx.activeDocument;
var sel = editorApi.getSelection();
var node = sel.getNode();

var reference = path o loid of the objects to insert

const settings = {
        cover: true
        hardCrop: false
        tmx: null
        xtransform: null
}
node.setExternalReference( reference, settings );

setChannels

Set channels to a node.

It can be called as

{DocumentNode}.setChannels();
Table 32. Method information

Method

setChannels

Parameter

Required {Array} channels - The array containing the channels to set.

Return

{Boolean} True if set succeeded

// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/summary',
    criteria: {
        [
            param: 'highlight',
            condition: 'equal',
            value: 'yes'
        ]
    }
};

// Obtains the node by x path.
var node = ctx.activeDocument.getNode(xpathOptions);

// To obtain the node by selection uncomment the following lines
// var sel = editorApi.getSelection();
// var node = sel.getNode();

var channels = ['Globe-Web'];

// Perform actions on the found node
// ...
if (node) {
    node.setChannels(channels);
}

Types

There are four different DocumentNode types.

ContentItem

Its nodeType can be checked against ctx.activeDocument.CONSTANTS.CONTENTITEM_TYPE.

It has some specific methods:

duplicate

Duplicates a contentItem.

It can be called as

{ContentItem}.duplicate(channel);
Table 33. Method information

Method

duplicate

Parameter

{String} channel - The channel to duplicate the ContentItem to. To duplicate it in more channels, separate them with a comma.

e.g. Globe-Web,Globe-Print

Returns

{Boolean} true if the operation was executed correctly

// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();
var selectedNode = sel.getNode();

if ( selectedNode.nodeType === ctx.activeDocument.CONSTANTS.CONTENTITEM_TYPE ) {
    // it is a ContentItem node. Duplicate itself.
    selectedNode.duplicate( 'Globe-Web,Globe-Print' );
} else {
    // Duplicates the container ContentItem.
    selectedNode.contentItem.duplicate( 'Globe-Web,Globe-Print' );
}
duplicateContent

Copy the content of the ContentItem node into another node.

It can be called as

{ContentItem}.duplicateContent(xpathOptions);
Table 34. Method information

Method

duplicateContent

Parameter

{object} xpathOptions - Contains the information on the XPath to copy the XML to. It contains the following properties:

  • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

  • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

    • {String} param the attribute to test (e.g. eom-name, xsm-preserve)

    • {String} condition the operator to use in the selector. Can be equal or contains.

    • {String} value the value to test for.

See example below.

Returns

{Boolean} true if the operation was executed correctly

At the moment, if the specified xpath in the xpathOptions corresponds to more than one node, only the first is taken.

// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();
var selectedNode = sel.getNode();

var xpathOptions = {
    xpath: 'doc/story/text',
    criteria: {
        [
            param: 'xsm-preserve',
            condition: 'equal',
            value: 'true'
        ]
    }
};

if ( selectedNode.nodeType === ctx.activeDocument.CONSTANTS.CONTENTITEM_TYPE ) {
    // it is a ContentItem node. Duplicate its own content.
    selectedNode.duplicateContent( xpathOptions );
} else {
    // Duplicates the content of the container ContentItem.
    selectedNode.contentItem.duplicateContent( xpathOptions );
}

ContentNode

Its nodeType can be checked against ctx.activeDocument.CONSTANTS.CONTENTNODE_TYPE.

It has no specific methods at the moment.

ContentBlock

Its nodeType can be checked against ctx.activeDocument.CONSTANTS.CONTENTBLOCK_TYPE.

Its blockType can be checked against ctx.activeDocument.CONSTANTS.BLOCK_*.

Methods common to all the ContentBlocks
getXmlContent

Returns the XML of the current node.

It can be called as

{ContentBlock}.getXmlContent();
Table 35. Method information

Method

getXmlContent

Parameter

None

Return

{String} The xml of the current selection as a String

// Obtains the document selection
var sel = ctx.activeDocument.getSelection();
var selectedNode = self.getNode();

if ( selectedNode.nodeType === ctx.activeDocument.CONSTANTS.CONTENTITEM_TYPE ) {
    var xml = selectedNode.getXmlContent();
    // ...
}
replaceXmlContent

Replaces the XML content of the current node.

It can be called as

{ContentBlock}.replaceXmlContent();
Table 36. Method information

Method

replaceXmlContent

Parameter

{String} xml - The xml content that replaces the current content node.

Return

{Boolean} True if replacement succeeded

If the specified xml doesn’t contain a special element an error occurred. A block content can be replaced only with another block content. Right now we can replace only imageElement, videoElement and objectElement

// Obtains the document selection
var sel = ctx.activeDocument.getSelection();
var selectedNode = self.getNode();

if ( selectedNode.nodeType === ctx.activeDocument.CONSTANTS.CONTENTBLOCK_TYPE ) {

    var xml = '<photo-web><fw-photo width="200" height="200"></fw-photo>' +
    '<photo-caption channel="Globe-Web"><?EM-dummyText Insert caption first here?><p><?EM-dummyText Insert caption here?></p></photo-caption></photo-web>';

    var result = selectedNode.replaceXmlContent(xml);
    // ...
}
Image Block

It represents an Image Block. Its blockType can be checked against ctx.activeDocument.CONSTANTS.BLOCK_IMAGE.

copyImage( xpathOptions, settings )

Copies the image into other image elements, maintaining the crop and the transformation information.

It can be called as

{ContentBlock}.copyImage(xpathOptions, settings)
Table 37. Method information

Method

copyImage

Parameter

{object} xpathOptions - Contains the information on the XPath to copy the image to. It contains the following properties:

  • Required {String / Array} xpath - the xpath to append the xml to, as a string (single xpath) or array (multiple xpaths).

  • Optional {Array} criteria - an array of objects containing the criteria to further detail the node to select. Each object contains the following properties, all required:

    • {String} param the attribute to test (e.g. eom-name, xsm-preserve)

    • {String} condition the operator to use in the selector. Can be equal or contains.

    • {String} value the value to test for.

See example below.

Parameter

{object} settings additional options to change the copy Image behaviour.It contains the following properties:

  • Optional {Boolean} cover - If true, applies an effect similar to css background-size:cover property. If omitted, the default value is false.

  • Optional {Boolean} hardCrop - If true, applies the hardCrop parameter to the copied image. If omitted, the default value is false.

  • Optional {Boolean} copy - If true, create a copy of the object before linking the image to the selected placeholder. If omitted, the default value is false.

Returns

{Boolean} true if the operation was executed correctly

At the moment, if the specified xpath in the xpathOptions corresponds to more than one xPath, only the first is taken.

// Obtains the current selection
var sel = ctx.activeDocument.getSelection();
var selNode = sel.getNode();

// Check if it is an image block

if ( selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_IMAGE ) {

    var xpathOptions = {
      'xpath': 'doc/story/text/photo-web/fw-photo',
      'criteria': [
          {'param': 'eomattr',
          'condition': 'equal',
          'value': 'true'}
        ]
    };

    selNode.copyImage(xpathOptions, { 'cover': true, 'hardCrop': false, 'copy': true });
}
changeAlignment( align, settings )

Change the alignment of a block component.

It can be called as

{ContentBlock}.changeAlignment(align, settings)
Table 38. Method information

Method

changeAlignment

Parameter

Required {String} align - The align to set, allow values: left, right, center, fullwidth, background.

Parameter

Optional {object} settings Additional options right now not used for future purpose

See example below.

// Obtains the current selection
var sel = ctx.activeDocument.getSelection();
var selNode = sel.getNode();

// Check if it is an image block
if ( selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_IMAGE ) {
    selNode.changeAlignment('center');
}
changeBlockDimensions( dimensions, settings )

Change width and height of a block.

It can be called as

{ContentBlock}.changeBlockDimensions(xpathOptions, settings)
Table 39. Method information

Method

changeBlockDimensions

Parameter

Required {object} dimensions - Contains the width and height to set.

Parameter

Optional {object} settings Additional options right now not used for future purpose

See example below.

// Obtains the current selection
var sel = ctx.activeDocument.getSelection();
var selNode = sel.getNode();

// Check if it is an image block
if ( selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_IMAGE ) {
    var dimensions = {'width': 300, 'height': 300};
    selNode.changeBlockDimensions(dimensions);
}
Video Block

It has no specific methods at the moment.

Collection Block

It represents a Collection Block. It can be of three types: insert, embed or link. Its blockType can be checked against ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_INSERT, ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_EMBED, ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_LINK.

setItemAttributes(attrOptions)

Set attributes to an item of a collection .

It can be called as

{ContentBlock}.setItemAttributes(attrOptions)
Table 40. Method information

Method

setItemAttributes

Parameter

{object} attrOptions - Contains the information on the item and attributes to set. It contains the following properties:

  • Required {Array} attributes - an array of objects pair name/value. If the value is empty the attribute will be removed.

  • Optional {Boolean} selected - it true the attributes will be applied to the collection selected item.

  • Optional {Integer} index - the index of THE item to apply the attributes (the index is not zero-based):

Returns

{Boolean} true if the operation was executed correctly

At least selected or index must be specified, otherwise the attributes will be not applied.

// Obtains the current selection
var sel = ctx.activeDocument.getSelection();
var selNode = sel.getNode();

// Check if it is a collection block

if ( selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_INSERT ||
        selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_EMBED ||
        selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_LINK) {

    var options = {};
    var attributes = [{'name': 'eomtest', 'value': 'test'}, {'name': 'class', 'value': 'testclass'}];
    options.attributes = attributes;
    options.selected = true; // the attributes will be applied to the selected item

    selNode.setItemAttributes(options);
}
getCollectionSelectedItems(attrOptions)

Get the selected items of a collection .

It can be called as

{ContentBlock}.getCollectionSelectedItems(attrOptions)
Table 41. Method information

Method

getCollectionSelectedItems

Parameter

{object} attrOptions - Contains the information on the attributes to search. It contains the following properties:

  • Optional {Array} attributes - an array of objects pair name/value. If empty the selected items will be returned.

Returns

{Boolean} an index array of selected items

// Obtains the current selection
var sel = ctx.activeDocument.getSelection();
var selNode = sel.getNode();

// Check if it is a collection block

if ( selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_INSERT ||
        selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_EMBED ||
        selNode.blockType === ctx.activeDocument.CONSTANTS.BLOCK_COLLECTION_LINK) {

    var options = {};
    // Uncomment this lines if you want to get items with a specific attribute value
    /* var attributes = [{'name': 'lead', 'value': 'test'}];
    options.attributes = attributes; */

    var selectedItems = selNode.getCollectionSelectedItems(options);
}

DummyText

Its nodeType can be checked against ctx.activeDocument.CONSTANTS.DUMMY_TYPE.

It has no specific methods at the moment.

From activeDocument to activeDocumentV2

Follows some examples to compare the use of activeDocument and activeDocumentV2 to perform the same operation.

getXmlContent

Example

// ***** activeDocument ******
// Obtains the current selection.
var sel = ctx.activeDocument.getSelection();

// get the node
var selNode = sel.getNode();

var xmlContent = node.getXmlContent();

// ***** activeDocumentV2 ******
// Obtains the XML of the current selection
ctx.activeDocumentV2.getXmlContent({useSelection: true}).then(result => {
    console.log(`V2 async result selection: ${result}`);
}).catch(error => {
    console.log(`V2 async error selection: ${error}`);
});

// ...

getTextContent

Example

// ***** activeDocument ******
// Obtains the text
var textContent = ctx.activeDocument.getTextContent();

// ***** activeDocumentV2 ******
// Obtains the XML of the current selection
ctx.activeDocumentV2.getTextContent().then(result => {
    console.log(`V2 async result selection: ${result}`);
}).catch(error => {
    console.log(`V2 async error selection: ${error}`);
});

// ...

replaceXmlContent

Example

// ***** activeDocument ******
// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/summary',
    criteria: {
        [
            param: 'channel',
            condition: 'equal',
            value: 'Globe-Print'
        ]
    }
};

// Obtains the node.
var node = ctx.activeDocument.getNode(xpathOptions);

// Perform actions on the found node
// ...
if (node) {
    var repxml = '<summary id="U26664270086oOb"><p>New summary content</p></summary>';
    node.replaceXmlContent(repxml);
}

// ***** activeDocumentV2 ******
// prepare the xpath options
var xpathOptions = {
    xpath: 'doc/story/summary',
    criteria: {
        [
            param: 'channel',
            condition: 'equal',
            value: 'Globe-Print'
        ]
    }
};

// REPLACE XML content
ctx.activeDocumentV2.getXmlContent({xpathOptions}).then( content => {
    var newContent = '<summary id="U26664270086oOb"><p>New summary content</p></summary>';
    ctx.activeDocumentV2.replaceXmlContent({newContent, xpathOptions}).then(result => {
        console.log('content replaced')
    });
})

// ...

saveDocument

Example

// ***** activeDocument ******
ctx.activeDocument.saveDocument();

// ***** activeDocumentV2 ******
// Save the current document.
ctx.activeDocumentV2.saveDocument().then(result => {
    console.log(`save operation successfully excuted`);
}).catch(error => {
    console.log(`an error occurred saving the document`);
});

// ...

insertXmlContent

Example

// ***** activeDocument ******
var newXmlContent = '<h1><?EM-dummyText lorem ipsum?></h1>';
var retValue = ctx.activeDocument.insertXml(newXmlContent, {xpath: 'cursorPosition'});

// ***** activeDocumentV2 ******
var xpathOptions = {
    xpath: 'cursorPosition'
};
var xmlContent = '<h1><?EM-dummyText lorem ipsum?></h1>';
activeDocumentV2.insertXmlContent({xmlContent, xpathOptions}).then(result => {
    console.log(`content has not been inserted`);
}).catch(error => {
    console.log(`content has not been inserted ${error}`);
});

// ...