Core Concepts

Context Object Reference

From version 3.5.0, Methode Swing introduces a new Context Object. Such Context Object works in Methode Prime, Methode Swing, and Methode Swing App unless specified otherwise.

Old context objects methods will be still available until version 4 of Methode Swing. Please update your code accordingly, and file requests in a new API is missing. Refer to Old Context Object methods reference in order to find the documentation for the old methods

Please notice that Editor APIs will still be available as always.

The Context Object is a Javascript object available throughout the Swing Extensions. In every extension point, the context object can be accessed and its methods called.

The Context Object is composed of public methods (see Public methods), object-specific methods (see Object class methods), and user-specific methods (see User class methods). If the context object is referred to a specific object, an activeObject property is available (see activeObject). If the context object is inside a supported Editor, the activeDocument property is available (see activeDocument).

Public methods

List of methods

Table 1. Parameters

Name

Description

Obtains the application info.

Obtains the area info.

Obtains the communication status.

Obtains the component info.

Reads a file given its filename, and returns it in a particular format.

Executes a Methode query.

Reads a user data content given its filename.

Adds a new JSON object to the specified user data content.

Set a new JSON array to the specified user data content.

Obtains a content of a document, given its path

Obtains the current user

Obtains a Methode object, given its id

Obtains a Methode object, given its path

Obtains the Platform information

Obtains a user, given its name

Obtains the list of member names, given a group name

Open a Methode document, given its id

Open the new content dialog, with the selected options

Open a Methode document, given its id, in readonly mode

Opens a popup panel

getApplicationInfo

Retrieves the application info and returns a JSON object containing the context and the name of the application.

    {
        context: "/swing",
        name: "Swing"
    }
Syntax
ctx.getApplicationInfo()
Returns

Type

Description

{JSON Object}

A json object containing the context and the name of the application.

Example
var applicationInfo = ctx.getApplicationInfo();

getAreaInfo

Retrieves the area info and returns a JSON object containing the area type and the area name.

    {
        name: "story",
        type: "editor"
    }
Syntax
ctx.getAreaInfo()
Returns

Type

Description

{JSON Object}

A json object containing the area type and the area name.

Example
var areaInfo = ctx.getAreaInfo();

getCommunicationStatus

Retrieves the communication status of the application (useful when working in offline mode). The object returned contains the following fields:

  • applicationOnline: true if the application is in online mode, false otherwise.

  • isOnline: true if the application reaches the server and the application is in online mode, false otherwise.

  • offlineServer: enabled : true if the offline server is available, enabled: false otherwise.

  • serverReachable: true if the server is reachable, false otherwise.

    {
        applicationOnline: true,
        isOnline: true,
        offlineServer: {
            enabled: false
        },
        serverReachable: true
    }
Syntax
ctx.getCommunicationStatus()
Returns

Type

Description

{JSON Object}

A json object containing the communication status of the application.

Example
var communicationStatus = ctx.getCommunicationStatus();

getComponentInfo

Retrievest the conponent info and returns a JSON object containing the type and the subType of the current component. e.g.

    {
        type: "objectpanel",
        subType: ""
    }
Syntax
ctx.getComponentInfo()
Returns

Type

Description

{JSON Object}

A json object containing the type and the subType of the current component.

Example
var componentInfo = ctx.getComponentInfo();

readFile

Reads a file given its filename, and returns it in a particular format.

Syntax
ctx.readFile( options, callback )
Parameters
Table 2. Parameters

Name

Type

Required

Description

options

{Object}

No

An optional list of options. See below

callback

{Function}

No

A callback function. See Callback definition for further information.

The options object is a Javascript object with the following properties:

  • filename - The path to the file to read. (Physical path in Méthode, e.g. /SysConfig/Common/Data/Sections.xml).

  • format (default is json) - The format of the returned content, Available formats: json, xml.

Returns

Type

Description

{JSON} or {XML}

The content of the object in the format specified in the options parameter.

Example
var file = ctx.readFile( { 'filename': '/SysConfig/Common/Data/Sections.xml',
 'format': 'json'
});

executeQuery

Executes a Methode query given the query content as String, and returns a query result as JSON.

Syntax
ctx.executeQuery( settings, callback )
Parameters
Table 3. Parameters

Name

Type

Required

Description

settings

{String or Object}

Yes

If a string is passed, it represents the query content to be executed. Else, represents a set of arguments.

callback

{Function}

No

A callback function. See Callback definition for further information.

settings can be either a string or a Javascript Object. If it is a string, it represents the query content to be executed. Elsewhere, if a Javascript object is passed, the following properties are supported:

  • query: the query string in Methode format to be executed.

  • limit: The max number of items.

  • view: Catalog view to applied to query result.

Returns

Type

Description

{JSON Object}

The query execution result.

Example
var settings = {
    "limit":70,
    "query":"<?xml version=\"1.0\" encoding=\"utf-8\"?><!DOCTYPE EOMSearch><EOMSearch version=\"1.0\" xmlns=\"http://EidosMedia.com/EOM/SearchEngine\" xmlns:se=\"http://EidosMedia.com/EOM/SearchEngine\" xmlns:q=\"http://EidosMedia.com/EOM/SearchEngine/query\" xmlns:qm=\"http://EidosMedia.com/EOM/SearchEngine/query/macro\" xmlns:qa=\"http://EidosMedia.com/EOM/SearchEngine/query/alias\" xmlns:qui=\"http://EidosMedia.com/EOM/SearchEngine/query/UI\" xmlns:i=\"http://EidosMedia.com/query/interpolate\"><q:Query type=\"INDEX\"><q:Properties><q:MaxResultItems value=\"70\"/><q:Sort on=\"ObjectInfo/created\" type=\"NDESCENDING\"/><q:Index name=\"@meth01_eomjse1\"/></q:Properties><q:Boolean><q:OR><se:Content q:op=\"INC\" xmlns=\"\">obama</se:Content><se:Attributes q:op=\"INC\">obama</se:Attributes></q:OR></q:Boolean></q:Query></EOMSearch>"
  }
var result = ctx.executeQuery(settings);

getUserData

Reads a user data content given its filename. If the file does not exist the system creates it in the following path "eomfs:/Configurations/Profiles/{currentUserName}/{filename}.json", and returns an empty JSON array.

Syntax
ctx.getUserData( filename, callback )
Parameters
Table 4. Parameters

Name

Type

Required

Description

filename

{String}

Yes

The user data file’s name without extension.
The following names are reserved for use by the Swing application. You cannot use these names in your custom code.
- latestqueries
- contacts
- uploads
- todolist
- recents
- favourites

callback

{Function}

No

A callback function. See Callback definition for further information.

Returns

Type

Description

{JSON Array}

The content of user’s data in JSON format or an empty JSON array if is a new file.

Example
var friends = ctx.getUserData('friends');

addUserData

Adds a new JSON object to the specified user data content, denoted by the filename input parameter.

Syntax
ctx.addUserData( filename, data, callback )
Parameters
Table 5. Parameters

Name

Type

Required

Description

filename

{String}

Yes

The user data file’s name without extension.

data

{JSON Object}

Yes

The data object to be added to the user data file.

callback

{Function}

No

A callback function. See Callback definition for further information.

Returns

Type

Description

{JSON Array}

The updated list with the new added data object.

Example
var friends = ctx.addUserData('friends',  {
                 'fullName': 'Carroll Walke'
             });

setUserData

Set a new JSON array to the specified user data content, denoted by the filename input parameter.

Syntax
ctx.setUserData( filename, list, callback )
Parameters
Table 6. Parameters

Name

Type

Required

Description

filename

{String}

Yes

The user data file’s name without extension.

list

{JSON Array}

Yes

The JSON array to replace the current user data content.

callback

{Function}

No

A callback function. See Callback definition for further information.

Returns

Type

Description

{JSON Array}

The updated list with the specified JSON array

Example
var friends = ctx.setUserData('friends', [
                {
                  "fullName": "Mitchell Henson"
                },
                {
                  "fullName": "Carroll Walker"
                },
                {
                  "fullName": "Carla Sargent"
                },
                {
                  "fullName": "Sara Savage"
                },
                {
                  "fullName": "Beach Workman"
                },
                {
                  "fullName": "Courtney Roberts"
                },
                {
                  "fullName": "Abby Hood"
                },
                {
                  "fullName": "Belinda Acosta"
                }
            ]);

getContentByPath

Obtains a content of a document, given its path.

Syntax
ctx.getContentByPath( path, options, callback )
Parameters
Table 7. Parameters

Name

Type

Required

Description

path

{Function}

Yes

The path of the object. E.g. 199$/SysConfig/columnCatalogCfg.swing.xml
For paths of databases other than the primary, the database Id must be specified.

options

{Object}

No

An optional list of options. See below

callback

{Function}

Yes

A callback function. See Callback definition for further information.

The options object is a Javascript object with the following properties:

  • cached (default is false). If true, the document xml is cached and the following times will be retrived from the internal cache.

Returns

Type

Description

{string}

The content of the object as a string.

Example
ctx.getContentByPath('199$/SysConfig/columnCfgCatalogs.swing.xml', { cached: true }, function(err, content) {
    if (err) {
        ctx.showError(err);
        return;
    }
    console.log(content);
});
Note

The method can also be called synchronously, but this usage is not recommended.

getCurrentUser

Obtains the current user.

Syntax
ctx.getCurrentUser( callback )
Parameters
Table 8. Parameters

Name

Type

Required

Description

callback

{Function}

Yes

A callback function. See Callback definition for further information.

Returns

Type

Description

{User object}

An instance of the User Class. See User class methods for further information on the methods available.

Example
ctx.getCurrentUser(function(err,User) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Do something with the user...
    alert(User.getName());
});
Note

The method can also be called synchronously, but this usage is not recommended.

getObject

Obtains a Methode object, given its id

Syntax
ctx.getObject( id, callback );
Parameters
Table 9. Parameters

Name

Type

Required

Description

id

{String}

Yes

The document id. Format is [<databaseId>$]<loid>.

callback

{Function}

Yes

A callback function. See Callback definition for further information.

Returns

Type

Description

{Object class}

An instance of the Object Class. See Object class methods for further information on the methods available.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Do something with the object...
    Obj.openReadonly();
});
Note

The method can also be called synchronously, but this usage is not recommended.

getObjectByPath

Obtains a Methode object, given its path

Syntax
ctx.getObjectByPath( path, callback );
Parameters
Table 10. Parameters

Name

Type

Required

Description

path

{String}

Yes

The document path.

callback

{Function}

Yes

A callback function. See Callback definition for further information.

Returns

Type

Description

{Object class}

An instance of the Object Class. See Object class methods for further information on the methods available.

Example
ctx.getObjectByPath('/Globe/Stories/Test.xml', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Do something with the object...
    Obj.openReadonly();
});
Note

The method can also be called synchronously, but this usage is not recommended.

getPlatformInfo

Obtains the Platform information

Syntax
ctx.getPlatformInfo();
Parameters

No parameters required.

Returns

Type

Description

{Object}

A generic Javascript Object containing the platform information. application: The name of the Application ('Swing', 'Prime', 'SwingApp')
copyright: The copyright information

Example
var platformInfo = ctx.getPlatformInfo();

if (platformInfo.application.indexOf('Swing') > -1) {
    // Do something only if it's Swing/SwingApp
}

getUserByName

Obtains a user, given its name.

Syntax
ctx.getUserByName( name, callback )
Parameters
Table 11. Parameters

Name

Type

Required

Description

name

{String}

Yes

The user name to look for.

callback

{Function}

Yes

A callback function. See Callback definition for further information.

Returns

Type

Description

{User object}

An instance of the User Class. See User class methods for further information on the methods available.

Example
ctx.getUserByName( 'user.test1', function(err,User) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Do something with the user...
    alert(User.getName());
});
Note

The method can also be called synchronously, but this usage is not recommended.

getGroupMembers

Obtains the list of member names, given a group name

Syntax
ctx.getGroupMembers( groupName, callback )
Parameters
Table 12. Parameters

Name

Type

Required

Description

groupName

{String}

Yes

The group name to look for.

callback

{Function}

Yes

A callback function. See Callback definition for further information.

Returns

Type

Description

{JSON Array}

The callback function will be called with the list of users belonging to the requested group, as an array of user names.

Example
ctx.getGroupMembers( 'group.test1', function(err, members) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Do something with the user names...
    for (var i = 0; i < members.length; i++) {
        console.log(members[i]);
    }
});

openDocument

Open a Methode document, given its id

Syntax
ctx.openDocument( id, callback )
Parameters
Table 13. Parameters

Name

Type

Required

Description

id

{String}

Yes

The document id to open. Format is [<databaseId>$]<loid>.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The methods does not return any information. The callback is called when the document is opened.

Example
ctx.openDocument( '199$1.0.893734064', function(err,User) {
    if (err) {
        ctx.showError(err);
        return;
    }

    // Document has opened correctly
});

openNewContentDialog

Open the new content dialog, with the selected options

Syntax
ctx.openNewContentDialog( options, callback )
Parameters
Table 14. Parameters

Name

Type

Required

Description

options

{Object}

Yes

The options with which the dialog is loaded.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

The options parameter is a javascript object in which it is possible to define:

  • contentType (available options are 'story', 'topic', 'dwp', 'dwc', 'topicplan')

  • name

  • channel

  • edition

  • team

  • issueDate

  • template

  • workfolder

Returns

The methods does not return any information. The callback is called when the document is created.

Example
ctx.openNewContentDialog( {
    template: '/SysConfig/Globe/Templates/poll.xml',
    contentType: 'story'
}, function(err,data) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Document has been created correctly
    alert( data.name );
});

openReadonly

Open a Methode document, given its id, in Readonly mode

Syntax
ctx.openReadonly( id, callback )
Parameters
Table 15. Parameters

Name

Type

Required

Description

id

{String}

Yes

The document id to open. Format is [<databaseId>$]<loid>.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The methods does not return any information. The callback is called when the document is opened.

Example
ctx.openReadonly( '199$1.0.893734064', function(err,data) {
    if (err) {
        ctx.showError(err);
        return;
    }

    // Document has opened correctly
});

openPopupPanel

Opens a custom HTML panel developed and specified by the user.

Syntax
ctx.openPopupPanel( panelName );
Table 16. Method information

Method

openPopupPanel

Parameter

{string} panelName - The string panel name.

Returns

undefined

Example
var panelName = 'myTestPanel';
ctx.openPopupPanel( panelName );
Registration of the custom panel

The custom panel must be registered via Javascript. The namespace of reference is the following:

eidosmedia.webclient.extensions.popups

A call to the register method must be done as follows:

eidosmedia.webclient.extensions.popups.register( name, settings );
  • {String} name: the name of the custom popup ( same as the one called from the ctx.openPopupPanel() method.

  • {Object} settings: a javascript object with the settings. It has the following parameters:

    • {String} icon: the icon css class.

    • {String} title: the title of the custom dialog.

    • {String} containerStyle: the style of the container. See info box below.

    • {String} template: the path to the HTML file. It is relative to the application context.

    • {Function} ready: a function which is called when the popup is loaded. The function is called with two parameters:

      • ctx - the Context Object ( with the activeDocument if you are in the Story Editor context )

      • $modal - the jQuery reference to identify the modal. The example below will show some possible uses.

eidosmedia.webclient.extensions.popups.register('testpopup', {
    icon: 'icon-plus',
    title: 'Custom panel title',
    containerStyle: 'background-color:red;',
    template: '/config/templates/customTemplates/testpopup.html',
    ready: function( ctx, $modal ) {
        // Popup is visible.
        console.log( ctx );

        // CUSTOM EXAMPLE
        /*
            In the footer example, we added a 'data-modal-action' to the OK button.
            We now intercept the click inside the modal.
        */

        // Add modal listeners.
        $modal.on('click', '[data-modal-action]', function( event ) {
            var action = $(this).attr('data-modal-action');
            switch(action) {
                case 'ok':
                    alert('Button clicked!');

                    // To close the modal, use $modal.modal('hide');
                    $modal.modal('hide');
                break;
            }
            event.preventDefault();
            event.stopPropagation();


        });

    }
});

The popup panel is built around a classical Bootstrap Modal. In particular, the HTML code in your template will be placed INSIDE the modal-body.

So, the modal will be basically created as follows:

<div class="modal-header">
  <!-- HEADER CREATED BY SWING -->
</div>
<div class="modal-body" style="<!-- containerStyle info here -->">
  <!-- CUSTOM HTML HERE -->
</div>

No predefined style is given for the footer, but it is recommended to be as follows:

<div class="modal-footer">
  <button class="btn btn-primary" data-modal-action="ok">OK</button>
    <button class="btn" data-dismiss="modal">Cancel</button>
</div>

So, considering that your code is wrapped inside the modal-body, if you want to use a footer, close a </div> and leave the footer html "unclosed".

Example:

My custom html here.
</div> <!--Here we close the modal-body -->
<div class="modal-footer">
    <button class="btn btn-primary" data-modal-action="ok">OK</button>
    <button class="btn" data-dismiss="modal">Cancel</button>
<!-- We don't close the footer since it is closed by the modal dialog. -->

IMPORTANT: as it is a bootstrap modal, by adding data-dismiss="modal" to a button, bootstrap will automatically close the modal.

Object class methods

List of methods

Table 17. Parameters

Name

Description

Add the collaborators to an object

Execute an EOMDB action for the current object

Returns the collaborators of an object

Returns the correlations of an object

Returns the object id

Returns the object info

In case of a report or a DWP, returns the documents linked.

Returns the object locker

Returns the metadata of the object

Returns the object name

Returns the object status information

Returns the system attributes of the object, in XML format

Returns the object type

Checks if the object is typeof the given type

Returns the usage tickets of the object

Returns the virtual attributes of the object, in XML format

Open the current object

Open the current object in Readonly mode

Register to all the EOMDB events of an item

Refresh the current object information

Remove the collaborators of an object

Set the metadata of an object

Update the status of the current object

Set the system attributes of an object

Gets the bundle information of the current object

Unset a metadata field of the current object

Gets the channel copies list of the current object - Restricted for EOM::CompoundStory objects

Create a channel copy of the current object - Restricted for EOM::CompoundStory objects

addCollaborators

Add the collaborators to an object

Parameters
Table 18. Parameters

Name

Type

Required

Description

collaborators

{String or Array}

Yes

A list made of user names.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Syntax
Object.addCollaborators(collaborators, callback)
Returns

The method returns the an array of collaborators as string.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    Obj.addCollaborators(['user.3', 'user.4'], function(err, data){
        if (err) {
            ctx.showError(err);
            return;
        }
        // data is now ['user.1', 'user.2', 'user.3', 'user.4'];
        var User = ctx.getUserByName(data[0]).getInfo()
    });
});

The method can also be called synchronously, but this usage is not recommended.

executeAction

Execute an EOMDB action for the current object

Syntax
Object.executeAction( settings, callback )
Parameters
Table 19. Parameters

Name

Type

Required

Description

settings

{String or Object}

Yes

If a string is passed, it represents the name of the action to execute. Else, represents a set of arguments.

callback

{Function}

Yes

A callback function. See Callback definition for further information.

settings can be either a string or a Javascript Object. If it is a string, it will interpreted as the actionId, and the action will be executed with no other params. Elsewhere, if a Javascript object is passed, the following properties are supported:

  • actionId: the action name. REQUIRED.

  • args: the arguments as a String.

Returns

The method returns the action response.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Or... Obj.executeAction({ actionId: 'postToTwitter', args: 'arguments here');
    Obj.executeAction('postToTwitter', function(err, data) {
        //.. Do something here.
    });
});

The method can also be called synchronously, but this usage is not recommended.

getId

Returns the object id

Syntax
Object.getId()
Returns

The method returns the object id as a string.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    // Well, we already knew that...
    var objectId = Obj.getId();
});

getCollaborators

Get the collaborators of an object

Syntax
Object.getCollaborators(callback)
Returns

The method returns the an array of collaborators as string.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    Obj.getCollaborators(function(err, data){
        if (err) {
            ctx.showError(err);
            return;
        }
        // data is now ['user.1', 'user.2'];
        var User! = ctx.getUserByName(data[0]).getInfo()
    });
});

The method can also be called synchronously, but this usage is not recommended.

getCorrelations

Get the correlations of an object

Syntax
Object.getCorrelations(linkName, callback)
Parameters
Table 20. Parameters

Name

Type

Required

Description

linkName

{String}

Optional

The name of the linkName to show.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The method returns the an array of correlations as Ctx Objects.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    // Without linkName
    Obj.getCorrelations(function(err, data){
    /*
    * With linkName,
    * Obj.getCorrelations('see_also', function(err, data){
    */
        if (err) {
            ctx.showError(err);
            return;
        }

        // data is an array of Objects
        for (var j = 0; j < data.length; j++) {
            console.log(data.getName());
        }
    });
});

The method can also be called synchronously, but this usage is not recommended.

getInfo

Returns the object info

Syntax
Object.getInfo()
Returns

The method returns the object information as JSON.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    var objInfo = Obj.getInfo();
    // Obj info is now a JSON containing all the information.
});

In case of a report or a DWP, returns the documents linked.

Syntax
Object.getLinks(callback)
Returns

The method returns the an array of links in the form of Object Class instances.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    Obj.getLinks(function(err, links){
        if (err) {
            ctx.showError(err);
            return;
        }
        // Each link is an Object Class instance.
        // So, it is possible to do so.
        for (var j = 0, ln = links.length; j < ln; j++) {
            console.log( links[j].getLocker() );
        }
    });
});

getLocker

Returns the object locker

Syntax
Object.getLocker()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var lockerBy = Obj.getLocker();
});

getMetadata

Returns the metadata of the object

Syntax
Object.getMetadata()
Returns

The method returns the metadata information as String

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var objMetadata = Obj.getMetadata();
    var $objMetadata = $.parseXML(objMetadata);
});

getName

Returns the object name

Syntax
Object.getName()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var name = Obj.getName();
});

getStatusInfo

Returns the object statusInformation

Syntax
Object.getStatusInfo()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var statusInfo = Obj.getStatusInfo();
    // Now
    // statusInfo.name is the status name
    // statusInfo.comment
    // statusInfo.identifier is the RGB color
});

getSystemAttributes

Returns the system attributes of the object, in XML format (as string)

Syntax
Object.getSystemAttributes()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var objSysAttr = Obj.getSystemAttributes();
    var $sysAttr = $.parseXML(objSysAttr);
});

Use the refresh method to get up to date object information before call this method.

getType

Returns the object type

Syntax
Object.getType()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var type = Obj.getType();
});

isType

Checks if the object is typeof the given type

Syntax
Object.isType(testtype)
Parameters
Table 21. Parameters

Name

Type

Required

Description

testtype

{String}

Yes

The type to test against the object type.

Returns

The method returns true if and only if the object type is type of the testtype else the method returns false.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var type = Obj.isType('EOM::Story');
});

getUsageTicket

Returns the usage tickets of the object, as an XML String

Syntax
Object.getUsageTicket()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var usageTicket = Obj.getUsageTicket();
    var $usageTicket = $.parseXML(usageTicket);
});

Use the refresh method to get up to date object information before call this method.

getVirtualAttributes

Returns the virtual attributes of the object, as an XML String

Syntax
Object.getVirtualAttributes()
Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    var virtualAttributes = Obj.getVirtualAttributes();
    var $virtualAttributes = $.parseXML(virtualAttributes);
});

Use the refresh method to get up to date object information before call this method.

open

Open the current object in editing mode

Syntax
Obj.open( id, callback )
Parameters
Table 22. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The methods does not return any information. The callback is called when the document is opened.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    Obj.open(function(err, data) {
        // Callback after the document is opened
    });
});

openReadonly

Open the current document in Readonly mode

Syntax
Obj.openReadonly( callback )
Parameters
Table 23. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The methods does not return any information. The callback is called when the document is opened.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    Obj.openReadonly(function(err, data) {
        // Callback after the document is opened
    });
});

registerToEvents

Register to all the EOMDB events of an item

Syntax
Obj.registerToEvents(eventCallback)
Parameters
Table 24. Parameters

Name

Type

Required

Description

eventCallback

{Function}

Yes

A callback function which is called at any event. See the example for further information.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    // Register to all the events.
    Obj.registerToEvents(function(eventName, data) {
        // eventName contains the name of the event
        // "unlock", "lock", "check in"...
        // data contains the information regarding the event.

        // Eventually, if needed, call a refresh for the object.

        Obj.refresh().getLocker();

    });


});

refresh

Refresh the current object information and returns a new Object class.

Syntax
Obj.refresh()
Returns

Type

Description

{Object class}

An instance of the Object Class. See Object class methods for further information on the methods available.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    // Perform very complex operations
    // Such as saving the document or setting the document metadata

    // To obtain the new metadata... do this.
    Obj = Obj.refresh();
    Obj.getMetadata();
});

removeCollaborators

Remove the collaborators from an object

Parameters
Table 25. Parameters

Name

Type

Required

Description

collaborators

{String or Array}

Yes

A list made of user names.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Syntax
Object.removeCollaborators(collaborators, callback)
Returns

The method returns the an array of collaborators as string.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }
    Obj.removeCollaborators(['user.1'], function(err, data){
        if (err) {
            ctx.showError(err);
            return;
        }
        // data is now ['user.1'];
        var User = ctx.getUserByName(data[0]).getInfo()
    });
});

The method can also be called synchronously, but this usage is not recommended.

setMetadata

Set the metadata of an object

Syntax
Obj.setMetadata(options, callback);
Parameters
Table 26. Parameters

Name

Type

Required

Description

options

{Object or Array}

Yes

An object made of xpath and content properties. Can be an array of those properties.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    var request = { xpath: '/ObjectMetadata/General/Priority', content: 'High title'};
    // Or an array
    // var request = [ { xpath: '/ObjectMetadata/General/Priority', content: 'High title'},
                        { xpath: '/ObjectMetadata/General/Priority2', content: 'High title2'}
                        { xpath: '/ObjectMetadata/General/Priority3', content: 'High title3'} ];
    Obj.setMetadata(request, function(err, data) {
        if (err) {
            ctx.showError(err);
            return;
        }
        // Success...
    });
});

The method can also be called synchronously, but this usage is not recommended.

setStatus

Update the status of the current object

Syntax
Obj.setStatus('NewsFlow/Editing', callback);
Obj.setStatus({ name: 'NewsFlow/Editing', comment: 'My comment'}, callback)
Returns

Type

Description

{Object class}

An instance of the Object Class. See Object class methods for further information on the methods available.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    Obj.setStatus('NewsFlow/Editing', function(err, data) {
        if (err) {
            ctx.showError(err);
            return;
        }
        // Success...
    });
});

The method can also be called synchronously, but this usage is not recommended.

setSystemAttributes

Set the system attributes of an object

Syntax
Obj.setSystemAttributes(options, callback);
Parameters
Table 27. Parameters

Name

Type

Required

Description

options

{Object or Array}

Yes

An object made of xpath and content properties. Can be an array of those properties.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    var request = { xpath: '/props/title/', content: 'High title'};
    // Or an array
    // var request = [ { xpath: '/props/title/', content: 'High title'},
                        { xpath: '/props/summary/', content: 'Summary'} ];
    Obj.setSystemAttributes(request, function(err, data) {
        if (err) {
            ctx.showError(err);
            return;
        }
        // Success...
    });
});

The method can also be called synchronously, but this usage is not recommended.

cleanMetadataField

Unset a metadata field of the current object

Syntax
Obj.cleanMetadataField(xpath, callback);
Parameters
Table 28. Parameters

Name

Type

Required

Description

option

{String}

Yes

A metadata field xpath to remove.

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Example
ctx.getObject('199$1.0.893734064', function(err, Obj) {
    if (err) {
        ctx.showError(err);
        return;
    }

    Obj.cleanMetadataField('/ObjectMetadata/General/Priority', function(err, data) {
        if (err) {
            ctx.showError(err);
            return;
        }
        // Success...
    });
});

The method can also be called synchronously, but this usage is not recommended.

getBundleInfo

Gets the bundle information of the current object

Syntax
Obj.getBundleInfo(callback);
Parameters
Table 29. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The bundle information:

[
  {
    "id": "99$1.0.287059148",
    "name": "Obama.xml",
    "baseName": "Obama",
    "path": "/Globe/Stories/Globe/Stories/Politics/2019-03-18/Politics/Obama.xml",
    "channel": "Globe-Web",
    "edition": null,
    "section": null,
    "issueDate": "20190318",
    "subFolder": null,
    "workFolder": "/Globe/Politics",
    "channelIdentifier": "Globe-Web"
  },
  {
    "id": "99$1.0.287059376",
    "name": "Obama@Globe-Print-USA.xml",
    "baseName": "Obama@Globe-Print-USA",
    "path": "/Globe/Stories/Globe/Stories/Politics/2019-03-18/Politics/Obama.xml/Obama@Globe-Print-USA.xml",
    "channel": "Globe-Print",
    "edition": "USA",
    "section": null,
    "issueDate": "20190318",
    "subFolder": null,
    "workFolder": "/Globe/Politics",
    "channelIdentifier": "Globe-Print/USA"
  }
]
Example
ctx.activeObject.getBundleInfo(function(err, list) {
    if (err) {
        ctx.showError(err);
        return;
    }
    //Success
});

The method can also be called synchronously, but this usage is not recommended.

getChannelCopiesList

Gets the channel copies list of the current object - Restricted for EOM::CompoundStory objects

Syntax
Obj.getChannelCopiesList(callback);
Parameters
Table 30. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The list of the created channel copies:

[
    {
        "id": "41$1.0.107332121",
        "channel": null,
        "info": {
            "id": "41$1.0.107332121",
            "name": "story.xml",
            "baseName": "story",
            "path": "/Globe/Stories/Art/story.xml",
            "channel": null,
            "edition": null,
            "section": null,
            "issueDate": "20190111",
            "subFolder": null,
            "workFolder": "/Globe/Art",
            "channelIdentifier": "none"
        },
        "master": true
    },
    {
        "id": "41$1.0.107314527",
        "channel": "Globe-Print",
        "info": {
            "id": "41$1.0.107314527",
            "name": "story@Globe-Print.xml",
            "baseName": "story@Globe-Print",
            "path": "/Globe/Stories/Art/story.xml/story@Globe-Print.xml",
            "channel": "Globe-Print",
            "edition": null,
            "section": null,
            "issueDate": "20190111",
            "subFolder": null,
            "workFolder": "/Globe/Art",
            "channelIdentifier": "Globe-Print"
        }
    }
]
Example
ctx.activeObj.getChannelCopiesList(function(err, list) {
    if (err) {
        ctx.showError(err);
        return;
    }
    //Success
});

The method can also be called synchronously, but this usage is not recommended.

createChannelCopy

Create a channel copy of the current object - Restricted for EOM::CompoundStory objects

Syntax
Obj.createChannelCopy(channel, callback);
Parameters
Table 31. Parameters

Name

Type

Required

Description

channel

{String}

Yes

A string containing the channel in form of "Product/Edition".

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The method returns the object information of the new channel copy as JSON.

Example
ctx.activeObj.createChannelCopy('Product/Edition', function(err) {
    if (err) {
        ctx.showError(err);
        return;
    }
    //Success
});

The method can also be called synchronously, but this usage is not recommended.

User class methods

List of methods

Table 32. Parameters

Name

Description

Returns the user groups

Returns the user info

Returns the usermetadata

Returns the username

Returns the system attributes of the user, in XML format

Returns the user teams.

Sets the system attributes of the user

Sets the metadata of the user

getGroups

Returns the groups which the user belongs to

The method returns an error for users other than the current one.

Syntax
User.getGroups( [callback] )
Parameters
Table 33. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Example
ctx.getCurrentUser(function(err,User) {
    var groups = User.getGroups();
    console.log(teams);
});

The method can be called either synchronously or asynchronously. It is indifferent.

getInfo

Returns the user info

Syntax
User.getInfo( [callback] )
Parameters
Table 34. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The user information in JSON.

{
  "name": "a.p",
  "description": "Eidosmedia R&D",
  "ucount": 13159,
  "databaseId": 199,
  "id": "1.0.532488046",
  "fullName": "Al Pi",
  "phoneNumber": "213213",
  "mobileNumber": "1111",
  "twitter": "alex89x",
  "facebook": "aaaa",
  "role": "alex",
  "homeEmail": "a@ierr.it",
  "businessEmail": "a.p@eidosmedia.com",
  "statusMessage": "I am available",
  "workDir": "workFolder:///Globe/Art",
  "location": "London",
  "lastLoggedOn": 1494418598,
  "initials": "AR",
  "signature": "A P",
  "homePath": "/Users/a.p",
  "calendars": [
    {
      "color": "#32AE0C",
      "id": "U12001806763ERC",
      "name": "UK Holidays",
      "url": "https://www.gov.uk/england-and-wales.ics",
      "icon": "icon-calendar",
      "private": false
    }
  ],
  "status": "busy",
  "disabled": false
}
Example
ctx.getCurrentUser(function(err,User) {
    var userInfo = User.getInfo();
    // Or, if you prefer,
    User.getInfo(function(err, userInfo){
        console.log(userInfo.name);
    });
});

The method can be called either synchronously or asynchronously. It is indifferent.

getMetadata

Returns the user metadata, as a string.

The method returns an error for users other than the current one.

Syntax
User.getMetadata( [callback] )
Parameters
Table 35. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Example
ctx.getCurrentUser(function(err,User) {
    var metadata = User.getMetadata();
    console.log(metadata);
});

The method can be called either synchronously or asynchronously. It is indifferent.

getName

Returns the user name

Syntax
User.getName( [callback] )
Parameters
Table 36. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The user name as string.

Example
ctx.getCurrentUser(function(err,User) {
    var userName = User.getName();
    console.log(userName);
});

The method can be called either synchronously or asynchronously. It is indifferent.

getSystemAttributes

Returns the system attributes of the user, in XML format (as string)

The method returns an error for users other than the current one.

Syntax
User.getSystemAttributesXML( [callback] )
Parameters
Table 37. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The system attributes of the User, as a XML string.

Example
ctx.getCurrentUser(function(err,User) {
    var systemAttributesXml = User.getSystemAttributes();
    var $sysAttr = $.parseXML(systemAttributesXml);
    console.log(systemAttributesXml);
});

The method can be called either synchronously or asynchronously. It is indifferent.

getTeams

Returns the teams which the user belongs to

The method returns an error for users other than the current one.

Syntax
User.getTeams( [callback] )
Parameters
Table 38. Parameters

Name

Type

Required

Description

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Example
ctx.getCurrentUser(function(err,User) {
    var teams = User.getTeams();
    console.log(teams);
});

The method can be called either synchronously or asynchronously. It is indifferent.

setSystemAttributes

Sets the system attributes of the user

The method returns an error for users other than the current one.

Syntax
User.setSystemAttributes( systemAttributes, [callback] )
Parameters
Table 39. Parameters

Name

Type

Required

Description

systemAttributes

{String or object}

Yes

A string or an object to represent the system attributes

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The system attributes of the User, as a XML string.

Example
ctx.getCurrentUser(function(err,User) {
    var systemAttributes = '<props><principalInfo><email type="business">alessandro.piana2@eidosmedia.comw</email><initials>AR</initials><signature>Alessandro Piana</signature><statusMessage>I am available</statusMessage><color type="revision" value="#008080"/><color type="annotation" value="#800000"/><location>London</location><email type="home">a@ierr.it</email><twitter>alex89x</twitter><facebook>aaaa</facebook><mobileNumber>1111</mobileNumber><phoneNumber>213213</phoneNumber><status>busy</status><workDir>workFolder:///Globe/Art</workDir><calendar><id>U12001806763ERC</id><icon>icon-calendar</icon><color>#32AE0C</color><name>UK Holidays</name><url>https://www.gov.uk/bank-holidays/england-and-wales.ics</url><private>false</private></calendar></principalInfo><role>alex</role><OutputChannels><channel name="Globe-Print"/></OutputChannels></props>';

    User.setSystemAttributes(systemAttributes, function(err, data) {
        if (err) {
            // Do something...
            return;
        }
    );

});

setMetadata

Sets the metadata of the user

The method returns an error for users other than the current one.

Syntax
User.setMetadata( metadata, [callback] )
Parameters
Table 40. Parameters

Name

Type

Required

Description

metadata

{String or object}

Yes

A string or an object to represent the metadata

callback

{Function}

Optional

A callback function. See Callback definition for further information.

Returns

The system attributes of the User, as a XML string.

Example
ctx.getCurrentUser(function(err,User) {
    var attributes = '<test><secondtest>hello</secondtest></test>';

    User.setMetadata(attributes, function(err, data) {
        if (err) {
            // Do something...
            return;
        }
    );

});

activeObject

In various contexts, such as the toolbars, editors, Diagram workflow, etc., there is an additional property available, named activeObject.

The activeObject is actually an instance of the Object Class and contains all methods of this class. See Object class methods for further information.

The old activeObj property is being discontinued from Swing 4 and will not be available in Prime. Please use the new activeObject property instead.

activeDocument

Inside the editor context, it is possible to access the activeDocument. Please refer to Editor API methods reference.

Callback definition

The callback parameter, when specified, is always defined as follows:

// Callback definition
function( err, response ) {
    // This is the "Node.js" callback style.
    // It forces the developer to manage the errors.

    if (err) {
        // Do something...
        return;
    }

    // Real implementation here

}

Custom menu and actions

In Methode Swing it is possible to configure custom menus and custom object actions.

Prepare the plugin to add menus and action

In general, all the extensions of Méthode Swing are places under

{SWING-APP}/plugins

So, all the Javascript described in the following sections should be placed under

{SWING-APP}/app/plugins/{EXTENSION-FOLDER}/{EXTENSION-NAME}.js

Do not use the word libs as an extension folder. The libs folder is reserved for loading external libs. See the proper documentation to obtain further info on the topic.

DEBUG MODE: by default, all plugins are aggregated into a single plugins.js file at the Tomcat startup. When creating a plugin, it may be frustrating to restart the Tomcat Server every time a change is made.

To avoid this, set the configuration property debugEnabled to true.

Then, that extension will be loaded on every refresh of the page.

Add a custom menu

In order to add a custom menu to Methode Swing, it is necessary to use the following namespace:

eidosmedia.webclient.extensions.header.newcontentmenu

New menus will be added in the next versions.

The syntax is the following:

eidosmedia.webclient.extensions.header.newcontentmenu.add(name, options);

Where:

  • name [string] is the name of the custom menu, alias a unique identifier.

  • options [optional, object] is a Javascript object containing the properties of the custom actions.

The options parameter can be omitted. In this case, Swing will use the previously registered command with the same name property. See example below.

If options is specified, it must follow the guidelines of a generic Swing command. See Commands documentation for further information.

Example

eidosmedia.webclient.commands.add({
    name: 'complex',
    icon: 'icon-compass',
    label: 'Perform some complex operation...',
    action: function( ctx, params, callback ) {
        if ( ctx.component.getType() === 'menu') {
            alert('hello menu');
            // perform same difficult operations...
            if (callbacks && callbacks.success) {
                callbacks.success( /*...*/ );
            }
        }

    }
});

eidosmedia.webclient.extensions.header.newcontentmenu.add('complex');

Add a custom action to an object

In a conceptually similar way, it is possible to add custom actions to objects. They will be shown in the search results, in the detailed preview of the object, and generally speaking everytime the object is available.

The syntax is the following:

eidosmedia.webclient.extensions.objectactions.add(name, options);

Where:

  • name [string] is the name of the custom menu, alias a unique identifier.

  • options [optional, object] is a Javascript object containing the properties of the custom actions.

The options parameter can be omitted. In this case, Swing will use the previously registered command with the same name property. See example below.

If options is specified, it must follow the guidelines of a generic Swing command. See Commands documentation for further information.

Example

eidosmedia.webclient.commands.add({
    name: 'complex',
    icon: 'icon-compass',
    label: 'Perform some complex operation...',
    isActive: function( ctx ) {
        // For some buttons ctx.activeObject is not available.
        return ctx.activeObject && ctx.activeObject.getType() === 'Image';
    },
    action: function( ctx, params, callback ) {
        if ( ctx.component.getType() === 'menu') {
            alert('hello menu');
            // perform same difficult operations...
            if (callbacks && callbacks.success) {
                callbacks.success( /*...*/ );
            }
        }

    }
});

eidosmedia.webclient.extensions.objectActions.add('complex');

Validators

Méthode Swing can be extended by providing the so called validators, that is a set of function to validate the input before it is sent to the Server to be saved.

Location of the Validators extensions

In general, all the extensions of Méthode Swing are places under

{SWING-APP}/plugins

So, all the Javascript described in the following sections should be placed under

{SWING-APP}/app/plugins/{EXTENSION-FOLDER}/{EXTENSION-NAME}.js

Do not use the word libs as an extension folder. The libs folder is reserved for loading external libs. See the proper documentation to obtain further info on the topic.

DEBUG MODE: by default, all plugins are aggregated into a single plugins.js file at the Tomcat startup. When creating a plugin, it may be frustrating to restart the Tomcat Server every time a change is made.

To avoid this, set the configuration property debugEnabled to true.

Then, that extension will be loaded on every refresh of the page.

Supported validators

With the evolution of Méthode Swing, more validators will be added. At the moment, the application supports the following validators.

renameFile validator

As the name suggests, the renameFile validator is called whenever the user tries to rename a file. This happens in an opened editor, or in the Explorer area, or during a Worflow/Release action.

To add a renameFile validator, it is necessary to register it inside Swing by calling the following Javascript function, inside your Javascript file:

eidosmedia.webclient.extensions.validators.addValidator('renameFile', function( ctx, onSuccess, onError ) { /* ... */ } );

The function requires three parameters:

  • ctx: The ctx is a JSON object which represents the object’s context. See Context Object (ctx parameter) for further details. See the code for further details on the available properties.

  • onSuccess: function to be called when the validation has passed. It wants a single parameter, newName, which is optional. See the code for further details on the parameters.

  • onError: function to be called when the validation failed. It wants a single parameter, errorMessage. See the code for further details.

Example and explanation of parameters

eidosmedia.webclient.extensions.validators.addValidator('renameFile', function( ctx, onSuccess, onError ) {
    // The ctx object contains the following properties.
    // context: 'application'
    // activeObj->getInfo() : {
    //    id: the story id,
    //    newName: the name specified by the user
    //    originalName: the originalName of the file
    // }

    // We obtain the information
    var info = ctx.activeObj.getInfo(); // { id, newName, originalName }

    // SAMPLE IMPLEMENTATION.

    if ( info.newName === "FORBIDDEN.xml" ) {

        // onError = function (errorMessage). Call it with the error message to be shown.
        onError( "This name is absolutely forbidden!" );
        return;
    } else {
        // The parameter is optional. If not passed, the document will be saved with the name specified
        // by the user. Passing the parameter, it is possible to change the name in the validator.
        onSuccess(); // Same as: onSuccess( info.newName );
        // OR
        onSuccess( "VALIDATED_" + info.newName );
    }
}

Editor URL Redirect validator

As the name suggests, the Editor URL Redirect validator is called whenever the user tries to add or edit a url in the Editor Url Redirect.

To add a Editor URL Redirect validator, it is necessary to register it inside Swing by calling the following Javascript function, inside your Javascript file:

eidosmedia.webclient.extensions.validators.addValidator('url-redirect', function( ctx, urlInfo, callback ) { /* ... */ } );

The function requires three parameters:

  • ctx: The ctx is a JSON object which represents the object’s context. See Context Object (ctx parameter) for further details. See the code for further details on the available properties.

  • urlInfo: a Javascript object containing all the information regarding the selected url. See the code for further details on the available properties.

  • callback: function to be called when the validation has been completed. See the code to know how to call it.

Example and explanation of parameters

eidosmedia.webclient.extensions.validators.addValidator('url-redirect', function( ctx, urlInfo, callback ) {
    // The ctx object contains the following properties.
    // context: 'editor'
    // area->getName: 'editor-url-redirect',
    // activeObj->getInfo() : the document information.

    // The urlInfo contains the following properties
    // urlInfo: {
    //  type: 'redirect' // or 'permanentredirect', or 'temporaryredirect' or 'forward'
    //  url: the starting url
    //  redirect: the target url
    //  isEditing: true / false ( if the url is a new one or not )
    //}

    // Perform the validation here...
    callback( true ); // Will tell the editor that the validation has passed.
    // callback() or callback( false ) or callback( any falsy value ) will tell the editor that the validation has failed.
}

Context Object (ctx parameter)

Basic structure of the Context Object

The Context object is made of a specific list of properties, and a number of publicly available methods.

{
    application: {
        getId: function()
    },
    area: {
        getType: function(),
        getName: function()
    },
    component: {
        getType: function()
    },
    activeObject: {
        // Methods of the single object.
    },
    selection: [ ] // Array of objects. See below.
}
Table 41. Parameters list
Parameter Value type Description Values

application.getId()

String

Returns the application Id.

"swing", …​

area.getType()

String

Returns the area type.

"main" (for the main views), "editor"

area.getName()

String

Returns the area name.

"explorer", "dashboard", "myarea" (for "main" areas). "story", "gallery" (for editors).

component.getType()

String

Returns the component type.

"toolbar", "grid", "objectpanel"…​

activeObj

Object

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

selection

Array of Object

Returns an array with the currently selected items. Each item has the same set of methods available. Refer to : Methods of the single object for the list of methods.

Each context has a different value for these properties.

Methods available in the Context Object

Further details on the methods available in the Context Object can be found in the Context Object Methods reference.

Editor Extensions

Commands configuration

Méthode Swing allows to add custom commands. Such commands can be launched in different situations, such as external DAM searches, custom Object Panels and widgets. Furthermore, M´thode Swing allows to configure such commands in specific parts of the User Interface (UI) such as, for example, the Toolbar inside the Explorer tab or the Explorer Grid (via Column Catalog).

Prepare the plugin to add commands

In general, all the extensions of Méthode Swing are places under

{SWING-APP}/plugins

So, all the Javascript described in the following sections should be placed under

{SWING-APP}/app/plugins/{EXTENSION-FOLDER}/{EXTENSION-NAME}.js

Do not use the word libs as an extension folder. The libs folder is reserved for loading external libs. See the proper documentation to obtain further info on the topic.

DEBUG MODE: by default, all plugins are aggregated into a single plugins.js file at the Tomcat startup. When creating a plugin, it may be frustrating to restart the Tomcat Server every time a change is made.

To avoid this, set the configuration property debugEnabled to true.

Then, that extension will be loaded on every refresh of the page.

Format of a command

A command is represented by a JSON object which should contain at least the following properties:

// Command options
{
    name: "" // commandName
    isActive: function( ctx ) { /* ... */ },
    isEnabled: function( ctx ) { /* ... */ },
    action: function( ctx, params, callback ) { /* ... */ },
    icon: 'icon-compass',
    label: 'My label'
}

name

The unique command name.

The command name is mandatory.

isActive

The isActive method is used to determine whether a command must be added to the context of reference. That is, for example, whether a custom button should be added to a toolbar.

The isActive method has the Context Object as the only parameters. See Basic structure of the Context Object for further details on the Context Object.

This is the best place to check for particular privileges.
Each default Swing context calls the isActive method with different parameters. See Swing default contexts to see the different parameters used by the different Swing contexts.

isEnabled

The isEnabled method is used to determine whether a command must be enabled and disabled according to the current situation. That is, for exable, whether a custom button in a toolbar should be enabled according to the current selection.

The isEnabled method has the Context Object as the only parameters. See Basic structure of the Context Object for further details on the Context Object.

This is the best place to check for the current selection ( selected items, text selection, etc. according to the context)
Each default Swing context calls the isEnabled method with different parameters. See Swing default contexts to see the different parameters used by the different Swing contexts.

action( ctx, params, callback )

The action property is a Javascript function which is called when a command is executed.

The parameters are the following:

  • ctx: the Context. See Basic structure of the Context Object for further details on the Context Object.

  • params: a list of params to be passed to the action.

  • callbacks: if available, it is an object containing the success and the error functions.

Every context inside Méthode Swing calls the commands with different values for the params and the callback arguments. See Swing default contexts to see the different parameters used by the different Swing contexts.

icon

Describes the icon associated with the command. See here for a list of available icons.

The icon property is optional.

label

Describes the label associated with the command.

The label property is optional.

Register, obtain and execute commands

Commands are, basically, functions that can be called in particular cases. The commands can be associated with specific Swing contexts (such as the Toolbars, or the Grid rows), or can be executed freely from inside the user plugins.

While the basic command format is equal for any case, the command registration is different according to the context of reference. The following paragraphs describe this concept in details.

"Free" command registration and execution

In this case, the user registers a command without associating it with a particular context. For this, all the methods to add, get and execute commands are within the following namespace:

eidosmedia.webclient.commands

Available methods are add, get, exec, defined as follows:

// Add a new command
eidosmedia.webclient.commands.add( command );

// Get the command object
eidosmedia.webclient.commands.get( commandName );

// Execute a command
eidosmedia.webclient.commands.exec( commandName, ... );

add( command )

Adds a command to Méthode Swing. It needs one parameter:

It is recommended not to use standard names such as edit, save, etc. because there is the risk to override standard Swing commands.
Example
eidosmedia.webclient.commands.add({
    name: 'myCustomCommand',
    icon: 'icon-compass',
    label: 'Perform some complex operation...',
    isActive: function( ctx ) {
        // check privileges...
        return true;
    },
    isEnabled: function( ctx ) {
        // check current selected items...
        return true;
    },
    action: function( ctx, params, callbacks ) {
        if ( ctx.component.getType() === 'toolbar') {
            // perform same difficult operations...
            if (callbacks && callbacks.success) {
                callbacks.success( /*...*/ );
            }
        }

    }
});

get( commandName )

Return a Javascript Object containing all the properties of the command, as defined in the previous set method.

Example
var cmd = eidosmedia.webclient.commands.get( 'myCustomCommand' );

/*
Now cmd is: {
    icon: 'icon-compass',
    label: 'Perform some complex operation...',
    isActive: function( ctx ) {
        // check privileges...
        return true;
    },
    isEnabled: function( ctx ) {
        // check current selected items...
        return true;
    },
    action: function( ctx, params, callback ) {
        if ( ctx.component.getType() === 'toolbar') {
            // perform same difficult operations...
            if (callbacks && callbacks.success) {
                callbacks.success( /*...*/ );
            }
        }

    }
*/

exec( commandName, …​ )

It is the method to execute a particular command.

var result = eidosemdia.webclient.commands.exec('myCustomCommand', ctx, params, callbacks );

The only mandatory param is commandName, which is the name of the command to execute. All the other parameters are passed as-is to the command.

As said above, Méthode Swing calls the custom commands with three parameters: ctx, params and callback. The nature of these parameters changes according to which context is using the command. See Swing default contexts to see the different parameters used by the different Swing contexts.

Of course, if the custom commands are used only within your extensions ( and not by default Swing contexts ), it is possible to use any parameter of choice.

Sample
/** in a custom widget, for example */

var btn = document.getElementById('myButton');

$(btn).on('click', function() {
    eidosmedia.webclient.commands.exec('myCustomCommand', 'all', 'my', 'parameters', 'here', true, [ { everything: 'ok' } ]);
});

Registration of a command to a context

See Swing default contexts for further info on how to register and work with different Swing contexts.

Basic structure of the Context Object

The Context object is made of a specific list of properties, and a number of publicly available methods.

{
    application: {
        getId: function()
    },
    area: {
        getType: function(),
        getName: function()
    },
    component: {
        getType: function()
    },
    activeObject: {
        // Methods of the single object.
    },
    selection: [ ] // Array of objects. See below.
}
Table 42. Parameters list
Parameter Value type Description Values

application.getId()

String

Returns the application Id.

"swing", …​

area.getType()

String

Returns the area type.

"main" (for the main views), "editor"

area.getName()

String

Returns the area name.

"explorer", "dashboard", "myarea" (for "main" areas). "story", "gallery" (for editors).

component.getType()

String

Returns the component type.

"toolbar", "grid", "objectpanel"…​

activeObj

Object

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

selection

Array of Object

Returns an array with the currently selected items. Each item has the same set of methods available. Refer to : Methods of the single object for the list of methods.

Each context has a different value for these properties.

Methods available in the Context Object

Further details on the methods available in the Context Object can be found in the Context Object Methods reference.

Swing default contexts

Explorer Toolbar

Context Object properties for the Explorer Toolbar

The Object Panel context has the following values:

Table 43. Parameters list
Parameter Values Description

area.getType()

"main"

area.getName()

"explorer"

component.getType()

"toolbar"

activeObj.getId()

String

Return the ID of the current folder / query opened in the Explorer.

activeObj.getInfo()

JSON

Return the info of the current folder / query opened in the Explorer.

activeObj.getType()

JSON

Return the type of the current folder / query opened in the Explorer.

activeObj.invalidate() (additional)

(void)

Invalidates all the changes and refresh the content of the current folder / query.

selection

JSON Array

Returns an array with the currently selected items in the folder/query. Each item has the same set of methods available. Refer to : Methods of the single object for the list of methods.

Associate commands to the toolbar

It is possible to register the command with the commands.add method ( see add( command ) for futher details ).

Then the commands must be associated to the toolbar as follows:

eidosmedia.webclient.actions.explorer.toolbar.addButton({
    action: "COMMAND NAME",
    label: "Label",
    icon: "Icon"
});

or, it is possible to pass directly the command object to the same function, e.g. :

eidosmedia.webclient.actions.explorer.toolbar.addButton({
    name: "cox.resetPriority",
    isActive: function( ctx ) { /* ... */ },
    isEnabled: function( ctx ) { /* ... */ },
    action: function( ctx, params, callbacks ) { /* ... */ },
    icon: 'icon-compass',
    label: 'My label'
});

The toolbar actions are called without a params and a callbacks parameter.

Grid Items

These values are valid for any grid. At the moment, only the Explorer grid is managed.

Context Object properties for the Grid Item

The Object Panel context has the following values:

Table 44. Parameters list
Parameter Values Description

component.getType()

"grid-item"

component.getId()

String

Not available

activeObj.getId()

String

Return the ID of the current item (grid row).

activeObj.getInfo()

JSON

Return the info of the current item (grid row).

activeObj.getType()

JSON

Return the type of the current item (grid row).

selection

JSON Array

Not available (empty array)

It is possible to register the command with the commands.add method ( see add( command ) for futher details ).

Then the commands must be associated to the grid item as follows:

eidosmedia.webclient.actions.explorer.grid.addEditor({
    action: "COMMAND NAME",
    label: "Label",
    icon: "Icon"
});

or, it is possible to pass directly the command object to the same function, e.g. :

eidosmedia.webclient.actions.explorer.grid.addEditor({
    name: "cox.resetPriority",
    isActive: function( ctx ) { /* ... */ },
    isEnabled: function( ctx ) { /* ... */ },
    action: function( ctx, params, callbacks ) { /* ... */ },
    icon: 'icon-compass',
    label: 'My label'
});

Object panel

Context Object properties for the ObjectPanel

The Object Panel context has the following values:

Table 45. Parameters list
Parameter Values Description

component.getType()

"objectpanel"

component.getId()

String

The id of the ObjectPanel DOM Element ( e.g. '#em-metadata-area' )

activeObj.getId()

String

Return the ID of the current object

activeObj.getInfo()

JSON

Return the info of the current object

activeObj.getType()

JSON

Return the type of the current object

selection

JSON Array

Not available (empty array)

Additional methods in the Context Object for Object Panel.
Table 46. Parameters list
Method Available in

activeObj.getUniqueMetadataId()

preFillForm - postFillForm - preSave - postSave - onClose

activeObj.setReadonly()

preFillForm - postFillForm - preSave - postSave - onClose

activeObj.showLoading()

preFillForm - postFillForm - preSave - postSave - onClose

activeObj.hideLoading()

preFillForm - postFillForm - preSave - postSave - onClose

activeObj.getMetadataXML()

preFillForm - postFillForm - preSave - validate - postSave - onClose

activeObj.setMetadataXML()

preFillForm - onClose

activeObj.refreshMetadata()

postFillForm - postSave - onClose

activeObj.saveMetadata()

preFillForm - postFillForm - onClose

activeObj.isMixedValue()

postFillForm (uploader)

getUniqueMetadataId()

Return the same unique id used in the HTML panel whenever a -<%=uniqueMetadataId%> has been used to generate a unique Id.

The syntax is the following:

var uniqueId = ctx.activeObj.getUniqueMetadataId(); // e.g "5";
var uniqueId = ctx.activeObj.getUniqueMetadataId(); // e.g "5";
// In this way we ensure that the only the current custom panel is referenced
$('#myCustomPanel-' + uniqueId) // ...
setReadonly()

Creates a readonly layer over the object Panel. The syntax is the following:

ctx.activeObj.setReadonly( [value] );

Value can be true (default) or false.

showLoading(), hideLoading()

Shows or hides a loading element. The syntax is the following:

ctx.activeObj.showLoading( );
ctx.activeObj.hideLoading( );

Value can be true (default) or false.

getMetadataXML()

Return the current metadata XML as a document object.

setMetadataXML( metadataXMO )

Sets the the new metadata XML ( only in the preFillForm and onClose method ).

refreshMetadata()

Refresh the current Metadata.

This will cause a reload of the objectPanel, and consequently a call to "preFillForm" and "postFillFrom" methods.

saveMetadata()

Saves the current Metadata. Before saving, the "preSave" method is called. After saving, the "postSave" method is called.

isMixedValue()

Check if the given value is the "Mixed" string.

Editor extensions

Méthode Swing Text editor can be extended in multiple parts by adding custom buttons and executing custom actions.

Location of the Editor extensions.

Editor extensions consist in a Javascript (*.js) file loaded with Swing.

In general, all the extensions of Méthode Swing are places under

{SWING-APP}/plugins

So, all the Javascript described in the following sections should be placed under

{SWING-APP}/app/plugins/{EXTENSION-FOLDER}/{EXTENSION-NAME}.js

Do not use the word libs as an extension folder. The libs folder is reserved for loading external libs. See the proper documentation to obtain further info on the topic.

DEBUG MODE: by default, all plugins are aggregated into a single plugins.js file at the Tomcat startup. When creating a plugin, it may be frustrating to restart the Tomcat Server every time a change is made.

To avoid this, set the configuration property debugEnabled to true.

Then, that extension will be loaded on every refresh of the page.

Namespaces of the editor extensions

Editor extensions are available under the following namespace:

eidosmedia.webclient.actions.editor

This namespace delves into more sub-namespaces, according to the part of the editor the user want to extend. At the moment, the following namespaces are supported:

eidosmedia.webclient.actions.editor.toolbar // To add buttons and actions in the editor toolbar

eidosmedia.webclient.actions.editor.components // To add buttons and actions in the swing components

The approach to use is the same throughout all the namespaces.

Configure editor actions

Throughout this document, the example will focus on the development of a simple custom command, named custom.PrependText, which will prepend a specific text to the current selection.

To add an editor action, then, it is necessary to follow the steps described below:

1. Add a custom command

The editor extensions follow the same approach of Swing commands.

See the Command configuration paragraph for further details.

Example

eidosmedia.webclient.commands.add({
    name: 'custom.PrependText',
    isActive: function( ctx ) {
        // check privileges...
        return true;
    },
    isEnabled: function( ctx ) {
        // check current selected items...
        return true;
    },
    action: function( ctx, params, callbacks ) {
        if ( ctx.component.getType() === 'toolbar') {
            // perform same difficult operations...
            if (callbacks && callbacks.success) {
                callbacks.success( /*...*/ );
            }
        }

    }
});

The details of the implementation of the isEnabled and isActive method will be explained later.

2. Register the commands in the different areas

As a second step, the newly created command must be associated to the specific areas of the editor.

2.a Editor toolbar and custom tabs

To add a button to the Editor toolbar, the following namespace must be used

eidosmedia.webclient.actions.editor.toolbar

The method to be used is addButton(settings). See the following example:

/**
 * We now register a new action in the editor toolbar using
 * the proper namespace. In this case we call the addButton
 * method for the toolbar visible in the editor instance. We
 * define a label and an icon for the button and more important
 * we tell the button which command has to trigger using the
 * action property
 */
eidosmedia.webclient.actions.editor.toolbar.addButton({
    action: "custom.PrependText",
    label: "Prepend Xml",
    icon: 'icon-edit',
    tabId: 'custom-tab-id'
});

The addButton method requires a single Javascript object ( settings ) as a parameter. This objects need to have the following properties:

  • action: the name of the previously registered command

  • label: the label associated with the command

  • icon: the icon associated with the command. See Icons supported by Swing for a comprehensive list of icons available in Swing.

Buttons can be placed under custom tabs. See Editor custom tabs for more information.

By defining an order property, it is possible to change the order of the buttons in the toolbar (only for the Editor).

If you need to use the call the same command from different parts of the editor ( e.g. the toolbar and some components ), or you need to differentiate the components for which the command is available, you can ( and should ) verify the origin of the action by checking the Context Object Component Type. This is detailed in the Verify the component type paragraph.

Editor custom tabs

Swing story editor toolbar is divided in tabs. By default, all the custom buttons are added to a specific "Custom Actions" tab. It is possible, though, to define multiple (2 at maximum) custom tabs and to place the custom buttons accordingly. To add a custom tab, write the following:

/**
 * We now register a new tab in the editor toolbar using
 * the proper namespace. The tab name must be used in the <tabId> property of the custom button.
 */
eidosmedia.webclient.extensions.editor.tabs.add({
    name: 'em-tab-custom',
    label: 'Swing custom actions'
});

To add the button to a tab, use the following syntax:

eidosmedia.webclient.actions.editor.toolbar.addButton({
    action: "custom.PrependText",
    label: "Prepend Xml",
    icon: 'icon-edit',
    tabId: 'em-tab-custom'
});
  • If the registered tab has no associated buttons, it will not be shown.

  • All the custom buttons who do not have a "tabId" property will be added to the usual "Custom Actions" tab.

2.b Editor components

To add a button to the Editor components, the following namespace must be used

eidosmedia.webclient.actions.editor.components

The method to be used is addButton(settings). See the following example:

/**
 * We now register a new action in the editor component using
 * the proper namespace. In this case we call the addButton
 * method for the components available in the editor instance. We
 * define a label and an icon for the button and more important
 * we tell the button which command has to trigger using the
 * action property
 */
eidosmedia.webclient.actions.editor.components.addButton({
    action: "custom.PrependText",
    label: "Prepend Xml",
    icon: 'icon-edit',
    allowReadOnly: false,
    singleItem: true
});

The addButton method requires a single Javascript object ( settings ) as a parameter. This objects need to have the following properties:

  • action: the name of the previously registered command

  • label: the label associated with the command

  • icon: the icon associated with the command. See Icons supported by Swing for a comprehensive list of icons available in Swing.

  • allowReadOnly: if true the button is visible in the component when the story is read only.

  • singleItem: if true the button is visible in a single element of a component with multiple items, for example Collection and Gallery component.

If you need to use the call the same command from different parts of the editor ( e.g. the toolbar and some components ), or you need to differentiate the components for which the command is available, you can ( and should ) verify the origin of the action by checking the Context Object Component Type. This is detailed in the Verify the component type paragraph.

singleItem attributte is available only for elements in a Collection and Gallery component. In the action method the second paramater contains the selectedItem object.

2.c Editor components Drop Down menu

It’s possible to add one or more buttons in a drop down menu. In this case the submenu property has to be added to the settings object:

  • submenu: the object containing the buttons to be added in the drop down menu

/**
 * We now register a new drop down menu action in the editor component using
 * the proper namespace. In this case we call the addButton
 * method for the components available in the editor instance. We
 * define a label and an icon for the drow down menu and more important
 * we set the submenu property that contains the button of the drop down menu
 */
eidosmedia.webclient.actions.editor.components.addButton({
    action: "example.customDropDown",
    label: "Custom popup",
    name: "submenu.customDropDown",
    icon: 'icon-copy',
    allowReadOnly: false,
    submenu: {
            videoPreview: {
                action: "example.openVideoPreview",
                label: "Open Video Preview",
                icon: 'fa fa-video-camera'
            },
            customEdit: {
                action: "example.customEditing",
                label: "Custom editing",
                icon: 'icon-edit',
            }
    }
});

Implementation of the editor extensions

The editor extensions are powerful because they make use of an editor-related version of the context object. See Context Object for the editor extensions for further details.

As of any command implementation, it is possible to specify the isActive, isEnabled and action methods.

  • isActive method is called in different points according to the editor part it refers to.

    • For the toolbar the method is called after the story is loaded to determine whether a custom action is available.

    • For the components the method is called when a new component is created ( or an existing one is loaded from the story )

  • isEnabled method is called in different points according to the editor part it refers to.

    • For the toolbar the method is called whenever the user changes the current selection or cursor position.

  • the action is called when the user clicks on the corresponding action button.

All the methods are called with the same Context Object ( ctx ), which is enhanced for the editor and allows to access the current document ( activeDocument ). See Context Object for the editor extensions foo further details.

Context Object for the editor extensions

Basic structure of the Context Object

The Context object is made of a specific list of properties, and a number of publicly available methods.

{
    application: {
        getId: function()
    },
    area: {
        getType: function(),
        getName: function()
    },
    component: {
        getType: function()
    },
    activeObject: {
        // Methods of the single object.
    },
    selection: [ ] // Array of objects. See below.
}
Table 47. Parameters list
Parameter Value type Description Values

application.getId()

String

Returns the application Id.

"swing", …​

area.getType()

String

Returns the area type.

"main" (for the main views), "editor"

area.getName()

String

Returns the area name.

"explorer", "dashboard", "myarea" (for "main" areas). "story", "gallery" (for editors).

component.getType()

String

Returns the component type.

"toolbar", "grid", "objectpanel"…​

activeObj

Object

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

selection

Array of Object

Returns an array with the currently selected items. Each item has the same set of methods available. Refer to : Methods of the single object for the list of methods.

Each context has a different value for these properties.

Methods available in the Context Object

Further details on the methods available in the Context Object can be found in the Context Object Methods reference.

In the Editor context, activeObj and selection are NOT available. The available methods are:

  • {ctx}.component.getType(), which returns one of the following values:

    • toolbar for the Editor toolbar

    • image for the Editor Component "Image"

    • video for the Editor Component "Video"

    • More to come…​

  • {ctx}.component.getSubType(), in case a component can embed, in addition to the main type, another type, which returns one of the following values:

    • video for the element "Video"

    • More to come…​

Example the image component can embed also a video element.

In addtion only in teh Editor context the following methods are available for the element info:

  • {ctx}.component.getXPath(), The xpath of the element info

  • {ctx}.component.getAttributes(), The attributes of the element info

The Editor Context Object is enriched by an additional object, named activeDocument, which contains a subset of methods to access the current document. These methods are described in the Dwp Editor API paragraph.

Editor API

Suggestions for the Editor extensions

Verify the component type

Since the Editor Context object contains a method

ctx.component.getType();

it is possible to use it in the isEnabled and isActive methods to check the kind of component which is calling the action.

    // EXCERPT FROM THE COMMAND CODE
    isActive: function( ctx ) {
        if ( ctx.component.getType() === 'toolbar') {
            return true;
        }
        return false;
    },
    isEnabled: function( ctx ) {
        // Enabling the action for the editable image only.
        if ( ctx.component.getType() === ctx.activeDocument.CONSTANTS.BLOCK_IMAGE) {
            return true;
        }
        return false;
    },

Checking the component type is mandatory in case of actions added to the Editor components namespace. Otherwise, the action will be available for all components. It’s possible to use some constants defined in the activeDocument:

ctx.activeDocument.CONSTANTS.BLOCK_IMAGE ctx.activeDocument.CONSTANTS.BLOCK_VIDEO

Use of Editor API and extensions in Object Panel

Only for the Object Panel of an opened story, the activeDocument object of the Dwp Editor API is available. So, it is possible, from the Object Panel, to call custom actions and manipulate the current document.

It is suggested, though, to verify if the {ctx}.activeDocument is available to show and hide editor-related parts in the Object Panel. See example below:

// From the object panel API
    ready: function( ctx ) {
        // some other code...
        if ( ctx.activeDocument ) {
            // We are in the Editor.
            $('.custom-editor-metadata-panel').show();

            // Use it to manipulate the document

            var sel = ctx.activeDocument.getSelection();
            // ...

        }
    }

To learn how to extend the Object Panel, see Object panel documentation.

Full example of Editor extension

eidosmedia.webclient.commands.add({
    name: "custom.PrependText",
    action: function(ctx, params, callback) {
        var editorApi = ctx.activeDocument;
        // Obtain the current selection
        var sel = editorApi.getSelection();
        // Supposedly check the current selection ( if it a Content Item, ... )
        sel.insertXml('<p>test</p>', 'insertBefore');
    },

    isActive: function( ctx ) {
        // Enables it only for toolbar or Editable Image
        var componentType = ctx.component.getType();
        if ( componentType === 'toolbar' || componentType === 'editableimage' )
            return true;
        else
            return false;
    },

    isEnabled: function( ctx ) {
        var selection = ctx.activeDocument.getSelection();
        var contentItem = sel.getContentItem();

        if ( contentItem ) {
            return true;
        }
        return false;
    }
});

/**
 * We now register a new action in the editor toolbar using
 * the proper namespace. In this case we call the addButton
 * method for the toolbar visible in the editor instance. We
 * define a label and an icon for the button and more important
 * we tell the button which command has to trigger using the
 * action property
 */
eidosmedia.webclient.actions.editor.toolbar.addButton({
    action: "custom.PrependText",
    label: "Prepend Xml",
    icon: 'icon-edit'
});

eidosmedia.webclient.actions.editor.components.addButton({
    action: "custom.PrependText",
    label: "Prepend Xml",
    icon: 'icon-gear'
});

// Example for custom action for a single element in a Collection or Gallery component
eidosmedia.webclient.commands.add({
    name: "example.openVideoPreview",
    action: function(ctx, params, callback) {

        // params contains the selectedItem
        var selectedItem = params.selectedItem;

        // checks selectedItem values

    },

    isActive: function( ctx ) {
        // Handle condition activation
        return true;
    },

    isEnabled: function( ctx ) {
        // Handle condition enable
        return true;
    }
});

/**
 * We now register a new action in the editor components using
 * the proper namespace. We tell the button which command has to trigger using the
 * action property
 */
eidosmedia.webclient.actions.editor.components.addButton({
    action: "example.openVideoPreview",
    label: "Open Video Preview",
    icon: 'icon-facetime-video',
    singleItem: true
});

Override editor’s default counter

Swing editor comes with a default counter for chars and words. On the one hand, it is possible to specify an additional counter under the Editor configuration ( see Story editor configuration for more details on that); on the other hand, it is possible to completely override the counter behaviour by defining the following function.

eidosmedia.webclient.editor.counter = function( counterInfo, storyInfo, userInfo ) { /* function here */ }
Table 48. Method information

Method

counter

Parameter

{object} counterInfo - An object containing the information about the counter.

  • {integer} chars - the number of chars in the relative contentItem ( the document, unless different configurations )

  • {integer} words - the number of words in the relative contentItem ( the document, unless different configurations )

  • {string} contentItemType - the name of the selected contentItem ( only in case of "contentItem" setting for Editor/Story/Count/Type ).

  • {string} xpath - the xpath of the selected item ( only in case of "contentItem" setting for Editor/Story/Count/Type and a list of conteintItems is configured Editor/Story/Count/contentItems).

  • {string} customLabel - the value for the custom label ( only if specified in the Story editor configuration )

  • {integer} customValue - the value for the custom value ( only if specified in the Story editor configuration )

  • {boolean} currentNodeEmpty - true if the current node is empty

  • {string} occupation - the task occupation value inherited by the document.

Parameter

{object} storyInfo - An object containing the information about the current document.

  • {string} channel - The story channel

  • {various info} - try to use a console.log(storyInfo) to see all the passed information. Please stick to the "classic" properties ( channel, id, name ) for the others may change in the future.

Parameter

{object} userInfo - An object containing the information about the current user.

  • {various info} - try to use a console.log(userInfo) to see all the passed information.

Returns

{String} - the function should return the HTML for the counter area.

So, if the user wants to override the counter behaviour, the eidosmedia.webclient.editor.counter method provides all the available information. The result of the function MUST be a valid HTML which is placed in the "counter area" of the Editor.

To create a separator, use an empty DIV with the class "em-info-separator" (see examples below).
If you need to use this features, you’ll probably need to change the Editor > Story > Count configuration to contentItem. See the Story Editor Configuration.

Full working example

The following example warns the user if the number of characters in a particular content item is reaching ( or above ) the maximum level. It only works with the "contentItem" configuration.

(function() {
    eidosmedia.webclient.editor.counter = function( countInfo, storyInfo, userInfo ) {
        var charsStyle = '';
        var html = '';

        var countLimits = {
            'headline': 50,
            'text': 1500
        };

        var countXpathLimits = {
            '/doc/story/grouphead/headline': 10,
        };
        var found = false;

        if (countInfo.xpath) {
            var MAX_CHARS_IN_XPATH = countXpathLimits[ countInfo.xpath ];
            found = MAX_CHARS_IN_XPATH != null;
            if ( MAX_CHARS_IN_XPATH &&
                 countInfo.chars > MAX_CHARS_IN_XPATH ) {
                 charsStyle = 'color: white; font-weight: bold; background-color: red;';
            } else if ( MAX_CHARS_IN_XPATH &&
                        countInfo.chars > (MAX_CHARS_IN_XPATH*0.75) ) {
                // We have gone over the 75% of the allowed number of characters
                charsStyle = 'color: black; font-weight: bold; background-color: orange;';
            }
        }

        if ( !found && countInfo.contentItemType ) {
            var MAX_CHARS_IN_CONTENTITEM = countLimits[ countInfo.contentItemType ];
            if ( MAX_CHARS_IN_CONTENTITEM &&
                 countInfo.chars > MAX_CHARS_IN_CONTENTITEM ) {
                charsStyle = 'color: white; font-weight: bold; background-color: red;';
            } else if ( MAX_CHARS_IN_CONTENTITEM &&
                        countInfo.chars > (MAX_CHARS_IN_CONTENTITEM*0.75) ) {
                // We have gone over the 75% of the allowed number of characters
                charsStyle = 'color: black; font-weight: bold; background-color: orange;';
            }
        }

        html += '<span class="em-info-container" style="' + charsStyle +
                '"><b>Chars:</b> <span id="chars_counter">' + (countInfo.chars || 0) +
                '</span></span>';
        html += '<span class="em-info-container" id="words_counter_box">' +
                '<b>Words:</b> <span id="words_counter">' + (countInfo.words || 0) +
                '</span></span>';

        if ( countInfo.customValue ) {
            html += '<span class="em-info-container"><b id="custom_counter_label">' +
                    countInfo.customLabel + '</b><span id="custom_counter">' +
                    countInfo.customValue + '</span></span>';
        }
        return html;
    }
})();

General information on the Editor API

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();
Table 49. Method information

Method

getXMLContent

Parameter

None

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 50. 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 51. 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 52. 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 53. 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).

  • 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
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 54. 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 55. Method information

Method

isReadonly

Parameter

None

Returns

{Boolean} true if the story is readonly

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

Execute the save of the current document.

It can be called as

ctx.activeDocument.saveDocument();
Table 56. 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 57. 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 58. 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, {});
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 59. 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 60. 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
};

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 61. 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 62. 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.

It can be called as

{SelectionObject}.insertXML(xml, insertOptions);
Table 63. 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).

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

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

sel.insertXml( xml, 'prepend' );
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 64. 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 65. 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 66. 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 67. 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 68. 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 69. 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 70. 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 71. 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);
}
setChannels

Set channels to a node.

It can be called as

{DocumentNode}.setChannels();
Table 72. 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 73. 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 74. 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 75. 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 76. 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 77. 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 78. 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 79. 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 80. 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 81. 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.

General information on the GalleryEditor API

GalleryEditor 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 Gallery.

GalleryEditor 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 GalleryEditor API. It contains a set of different methods to analyze 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();
Table 82. Method information

Method

getXMLContent

Parameter

None

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 );

// ...
getObjectsData

Returns an array containing the list of the data of each object present in the active document.

It can be called as

ctx.activeDocument.getObjectsData();
Table 83. Method information

Method

getObjectsData

Parameter

None

Returns

{Array} The array of data infornation of the all the objects present in the active document

The objects contained in the array are intended as "read only" objects. Any change made on them will not be reflected in the active document.

Example
// Obtains the current selection.
var objectsData = ctx.activeDocument.getObjectsData();
// objectsData is now an array of objects.

Here below an extract of the data contained in each returned object:

{
    "id": "199$1.0.624088073",
    "type": "Image",
    "name": "Official_portrait_of_Barack_Obama-U47037702204ISU-266x200@Globe-Web.jpg",
    "description": "",
    "owner": "user",
    "creator": "user",
    "created": 1457105152,
    "last_modifier": "user",
    "size": 125008,
    "system_attributes": {
        "workfolder": "",
        "template": "",
        "templateName": "",
        "summary": "",
        "wordCount": "",
        "sugCategory": "",
        "channel": "",
        "title": "...",
        "storyType": "",
        "productInfo": {
            "name": "",
            "issueDate": ""
        },
        "imageInfo": {
            "width": 266,
            "height": 200,
            "ptWidth": 63.84000015258789,
            "ptHeight": 48,
            "colorType": "RGB",
            "processTypes": ["resample"]
        },
        "priority": ""
    },
    "system_attributes_xml": "<props><process><type>resample</type></process><title>...</title><summary/><imageInfo>\n<width>266</width>\n<height>200</height>\n<ptWidth>63.84</ptWidth>\n<ptHeight>48.0</ptHeight>\n<xDim>22.52</xDim>\n<yDim>16.93</yDim>\n<dim>2.252cm x 1.693cm</dim>\n<xres>300.0</xres>\n<yres>300.0</yres>\n<colorType>RGB</colorType>\n<fileType>PNG</fileType>\n</imageInfo></props>",
    "usage_ticket": "<?xml version='1.0' encoding='UTF-8'?><tl></tl>"
}
isCroppedImage

Return a boolean value to check if the image is hard cropped.

It can be called as

ctx.activeDocument.isCroppedImage(loid);
Table 84. Method information

Method

isCroppedImage

Parameter

{String} - The loid of the image in the format: {dbId}${loid} (e.g. 199$1.0.624088073).

Returns

{Boolean} true if the image is hard cropped.

// Obtain the cropped information.
var isCropped = ctx.activeDocument.isCroppedImage(loid);

//check the isCropped variable
saveDocument

Execute the save of the current document.

It can be called as

ctx.activeDocument.saveDocument();
Table 85. 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.

Dwp Editor extensions

Méthode Swing DWP editor can be extended in multiple parts by adding custom buttons and executing custom actions, or configuring custom templates to render DWP linked objects.

Location of the DWP Editor extensions.

DWP Editor extensions consist in a Javascript (*.js) file loaded with Swing.

In general, all the extensions of Méthode Swing are places under

{SWING-APP}/plugins

So, all the Javascript described in the following sections should be placed under

{SWING-APP}/app/plugins/{EXTENSION-FOLDER}/{EXTENSION-NAME}.js

Do not use the word libs as an extension folder. The libs folder is reserved for loading external libs. See the proper documentation to obtain further info on the topic.

DEBUG MODE: by default, all plugins are aggregated into a single plugins.js file at the Tomcat startup. When creating a plugin, it may be frustrating to restart the Tomcat Server every time a change is made.

To avoid this, set the configuration property debugEnabled to true.

Then, that extension will be loaded on every refresh of the page.

Namespaces of the DWP editor extensions

DWP Editor extensions are available under the following namespace:

eidosmedia.webclient.actions.dwpeditor

Configure actions

Throughout this document, the example will focus on the development of a simple custom command, named custom.EditDwplink, which will edit a dwp link custom properties.

To add an action, then, it is necessary to follow the steps described below:

1. Add a custom command

The editor extensions follow the same approach of Swing commands.

See the Command configuration paragraph for further details.

Example

eidosmedia.webclient.commands.add({
    name: 'change.dwpLink',
    isActive: function( ctx ) {
        return true;
    },
    isEnabled: function( ctx ) {
        return true;
    },
    action: function( ctx, params, callbacks ) {
       if (callbacks && callbacks.success) {
          callbacks.success( /*...*/ );
       }
   }
});

The details of the implementation of the isEnabled and isActive method will be explained later.

2. Associated the commands to item toolbar

As a second step, the newly created command must be associated to the item toolbar. To add a button to the item toolbar, the following namespace must be used

eidosmedia.webclient.actions.dwpeditor

The method to be used is addButton(settings). See the following example:

/**
 * We now register a new action in the item toolbar using
 * the proper namespace. In this case we call the addButton
 * method, we define a label and an icon for the button and more important
 * we tell the button which command has to trigger using the
 * action property
 */
eidosmedia.webclient.actions.dwpeditor.addButton({
    action: "change.dwpLink",
    label: "Chane Dwp Link",
    icon: 'icon-globe'
});

The addButton method requires a single Javascript object ( settings ) as a parameter. This objects need to have the following properties:

  • action: the name of the previously registered command

  • label: the label associated with the command

  • icon: the icon associated with the command. See Icons supported by Swing for a comprehensive list of icons available in Swing.

Implementation of the DWP editor extensions

The editor extensions are powerful because they make use of an editor-related version of the context object. See Context Object for the editor extensions for further details.

As of any command implementation, it is possible to specify the isActive, isEnabled and action methods.

  • isActive method is called in different points according to the editor part it refers to.

    • For the toolbar the method is called after the story is loaded to determine whether a custom action is available.

    • For the components the method is called when a new component is created ( or an existing one is loaded from the story )

  • isEnabled method is called in different points according to the editor part it refers to.

    • For the toolbar the method is called whenever the user changes the current selection or cursor position.

  • the action is called when the user clicks on the corresponding action button.

All the methods are called with the same Context Object ( ctx ), which is enhanced for the editor and allows to access the active object ( activeObj ). See Context Object for the editor extensions for further details.

Context Object for the editor extensions

Basic structure of the Context Object

The Context object is made of a specific list of properties, and a number of publicly available methods.

{
    application: {
        getId: function()
    },
    area: {
        getType: function(),
        getName: function()
    },
    component: {
        getType: function()
    },
    activeObject: {
        // Methods of the single object.
    },
    selection: [ ] // Array of objects. See below.
}
Table 86. Parameters list
Parameter Value type Description Values

application.getId()

String

Returns the application Id.

"swing", …​

area.getType()

String

Returns the area type.

"main" (for the main views), "editor"

area.getName()

String

Returns the area name.

"explorer", "dashboard", "myarea" (for "main" areas). "story", "gallery" (for editors).

component.getType()

String

Returns the component type.

"toolbar", "grid", "objectpanel"…​

activeObj

Object

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

selection

Array of Object

Returns an array with the currently selected items. Each item has the same set of methods available. Refer to : Methods of the single object for the list of methods.

Each context has a different value for these properties.

Methods available in the Context Object

Further details on the methods available in the Context Object can be found in the Context Object Methods reference.

In the Editor context, activeDocument and selection are NOT available.

The Dwp Editor Context Object activeObj contains a subset of methods to access the current dwp link information. These methods are described in the Dwp Editor API paragraph.

Dwp Editor API

Returns dwp link information.

It can be called as

ctx.activeObj.getLink();
Table 87. Method information

Method

getLink

Parameter

None

Returns

{JSON Object} Dwp link information

Example
var info = ctx.activeObj.getLink();

// info is now:
{
    "name": "230-Short updates.dwc",
    "id": "1.0.36956807",
    "type": "EOM::WebContainer",
    "modified": {
        "type": "DATE",
        "format": "YYYYMMDDHHmmss",
        "value": "20160323133940"
    },
    "last_modifier": "Dario",
    "locked": {
        "type": "DATE",
        "format": "YYYYMMDDHHmmss",
        "value": "20160323133940"
    },
    "locker": "",
    "webType": "dwc-4stories-230",
    "styleSheet": "List",
    "templates": [
        "Grid",
        "List",
        "230-4rows1col"
    ],
    "status_info": {
        "name": "",
        "identifier": "",
        "comment": ""
    },
    "system_attributes": {
        "workfolder": "/Globe/Politics",
        "template": "",
        "templateName": "/SysConfig/Globe/Web/DwcTemplates/public/230/230-4rows1col.dwc",
        "summary": "",
        "wordCount": "",
        "sugCategory": "",
        "channel": "Globe-Web",
        "storyType": "",
        "productInfo": {
            "name": "Globe-Web",
            "issueDate": "20111005"
        },
        "priority": ""
    },
    "system_attributes_xml": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<props><productInfo><name>Globe-Web</name>\r\n<issueDate>20111005</issueDate>\r\n</productInfo>\r\n<workFolder>/Globe/Politics</workFolder>\r\n<templateName>/SysConfig/Globe/Web/DwcTemplates/public/230/230-4rows1col.dwc</templateName>\r\n</props>\r\n",
    "channel": "Globe-Web",
    "pstate": {
        "uuid": "f8c9bd50-ee54-11e0-b51c-542d5e32b6d1",
        "suid": "",
        "loid": "1.0.36956807",
        "retention_time": 0,
        "ucount": 44
    },
    "position": 1
}
getTemplates

Returns the list of dwp link available templates.

It can be called as

ctx.activeObj.getTemplates();
Table 88. Method information

Method

getTemplates

Parameter

None

Returns

{JSON Array} List of dwp link available templates

Example
var templates = ctx.activeObj.getTemplates();

// templates is now:
[{
        "value":"Grid",
        "selected":false
},{
        "value":"List",
        "selected":true
}, {
        "value":"230-4rows1col"
        ,"selected": false
}]
getCustomProperties

Returns the list of dwp link custom properties.

It can be called as

ctx.activeObj.getCustomProperties();
Table 89. Method information

Method

getCustomProperties

Parameter

None

Returns

{JSON Array} List of dwp link custom properties

Example
var properties = ctx.activeObj.getCustomProperties();

// properties is now:
[{
        "key": "customTitle",
        "value": "Alternate title"
}, {
        "key": "customDisplayLink",
        "value": "yes"
}, {
        "key": "customMaxResults",
        "value": "10"
}, {
        "key": "customTitleColor",
        "value": "gray"
}]
setCustomProperties

Set the list of dwp link custom properties.

It can be called as

ctx.activeObj.setCustomProperties(properties);
Table 90. Method information

Method

setCustomProperties

Parameter

{JSON Array} List of dwp link custom properties

Returns

None

Example
var properties = [{
        "key": "customTitle",
        "value": "Alternate title"
}, {
        "key": "customDisplayLink",
        "value": "yes"
}, {
        "key": "customMaxResults",
        "value": "10"
}, {
        "key": "customTitleColor",
        "value": "gray"
}];

ctx.activeObj.setCustomProperties(properties);

Custom DWP linked item templates

Méthode Swing DWP editor uses HTML templates to render linked objects. It is possible to configure custom templates to be used based on linked item type.

DWP Linked Item
Figure 1. DWP Linked Item

Editor configuration

In DWP editor configuration (see DWP editor configuration) can be specified which HTML template should be used to render a specific item linked type.

<WebClientConfiguration>
    ...
    <editor>
        ...
        <webpage>
            ...
            <linkedItemTemplates>
                <linkedItemTemplate>
                    <type>EOM::CompoundStory</type>
                    <template>dwp-story-template.html</template>
                </linkedItemTemplate>
                <linkedItemTemplate>
                    <type>EOM::WebContainer</type>
                    <template>dwp-dwc-template.html</template>
                </linkedItemTemplate>
            </linkedItemTemplates>
        </webpage>
    </editor>
<WebClientConfiguration><