Edit online

Obtain the Currently Selected Element Using the Author API

Use Case

In Author mode, if an element is fully selected, you want to perform an action on it. If not, you want to perform an action on the node that is located at the cursor position.

Solution

When an element is fully selected by the user the selection start and end offsets are actually outside of the node's offset bounds. So using AuthorDocumentController.getNodeAtOffset will actually return the parent of the selected node. A special API is available that makes it easier for you to determine this situation: WSAuthorEditorPageBase.getFullySelectedNode().

AuthorDocumentController controller = authorPageAccess.getDocumentController();
AuthorAccess authorAccess = authorPageAccess.getAuthorAccess();
int caretOffset = authorAccess.getEditorAccess().getCaretOffset();

    AuthorElement nodeAtCaret = 
(AuthorElement) authorAccess.getEditorAccess().getFullySelectedNode();
    if (nodeAtCaret == null) {
     //We have no fully selected node. We can look at the cursor offset.
     nodeAtCaret = (AuthorElement) 
authorAccess.getDocumentController().getNodeAtOffset(caretOffset);
    //Or we could look at the selection start and end, see which node is 
the parent of each offset and get the closest common ancestor.
}