Insert an Element with all the Required Content
Question
I am inserting a DITA image element using the API that points to a certain
resource and has required content. Can the required content be automatically inserted by the
application?
Answer
The API
ro.sync.ecss.extensions.api.AuthorSchemaManager can propose valid
elements that can be inserted at the specific offset. Using the method
AuthorSchemaManager.createAuthorDocumentFragment(CIElement), you can
convert the proposed elements to document
fragments (which have all the required content filled in) that can then be
inserted in the
document. AuthorSchemaManager schemaManager =
this.authorAccess.getDocumentController().getAuthorSchemaManager();
WhatElementsCanGoHereContext context =
schemaManager.createWhatElementsCanGoHereContext
(this.authorAccess.getEditorAccess().getCaretOffset());
List<CIElement> possibleElementsAtCaretPosition =
schemaManager.whatElementsCanGoHere(context);
loop: for (int i = 0; i < possibleElementsAtCaretPosition.size(); i++) {
CIElement possibleElement = possibleElementsAtCaretPosition.get(i);
List<CIAttribute> attrs = possibleElement.getAttributes();
if(attrs != null) {
for (int j = 0; j < attrs.size(); j++) {
CIAttribute ciAttribute = attrs.get(j);
if (ciAttribute.getName().equals("class")) {
if (ciAttribute.getDefaultValue() != null
&& ciAttribute.getDefaultValue().contains(" topic/image ")) {
//Found a CIElement for image
//Create a fragment that contains all required child elements already built.
AuthorDocumentFragment frag =
schemaManager.createAuthorDocumentFragment(possibleElement);
//Now set the @href to it.
//Ask the user and obtain a value for the @href
//Then:
String href = "test.png";
List<AuthorNode> nodes = frag.getContentNodes();
if(!nodes.isEmpty()) {
AuthorElement imageEl = (AuthorElement) nodes.get(0);
imageEl.setAttribute("href", new AttrValue(href));
}
//And insert the fragment.
this.authorAccess.getDocumentController().insertFragment
(this.authorAccess.getEditorAccess().getCaretOffset(), frag);
break loop;
}
}
}
}
}