Getting the currently selected element in CKEditor 5 - ckeditor

I am creating a CKEditor 5 plugin for adding an id attribute to arbitary elements. I have taken a lot of inspiration from the TextAlternative plugin for Images (if you're not familiar with how it works I'd sugguest taking a look.
I am recieving the following error: Cannot read property 'is' of null.
As part of my UI class, I have the following:
if ( !this._isInBalloon ) {
this._balloon.add( {
view: this._form,
position: getBalloonPositionData( editor )
} );
}
With getBalloonPositionData being:
/**
* Returns the positioning options that control the geometry of the
* {#link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon} with respect
* to the selected element in the editor content.
*
* #param {module:core/editor/editor~Editor} editor The editor instance.
* #returns {module:utils/dom/position~Options}
*/
export function getBalloonPositionData( editor ) {
const editingView = editor.editing.view;
const defaultPositions = BalloonPanelView.defaultPositions;
const t = editor.model.document.selection.getSelectedElement(); // ISSUE STARTS HERE
return {
target: editingView.domConverter.viewToDom( t ),
positions: [
defaultPositions.northArrowSouth,
defaultPositions.northArrowSouthWest,
defaultPositions.northArrowSouthEast,
defaultPositions.southArrowNorth,
defaultPositions.southArrowNorthWest,
defaultPositions.southArrowNorthEast
]
};
}
The line:
const t = editor.model.document.selection.getSelectedElement(); is where the issue starts. This method of getting the selected element was taken from elsewhere and I've seen it used in many other plugins.
I have tested with different "elements" selected and it always gets assigned null.
The full code is available # https://github.com/rhysstubbs/ckeditor5-build-classic on the branch feature/add-id-attributes-to-elements.
Any help would be great, TIA.

Related

Passing parameters from Command to Converter

I defined a new type of model element as a plug-in; let's refer to it as Foo. A Foo node in the model should translate to a section element in the view. So far, so good. I managed to do that by defining simple conversion rules. I also managed to define a new FooCommand that transforms (renames) selected blocks to Foo.
I got stuck trying to have attributes on those Foo model nodes be translated to attributes on the view elements (and vice-versa). Suppose Foos have an attribute named fooClass which should map to the view element's class attribute.
<Foo fooClass="green-foo"> should map to/from <section class="green-foo">
I can successfully receive parameters in FooCommand, but I can't seem to set them on the blocks being processed by the command:
execute(options = {}) {
const document = this.editor.document;
const fooClass = options.fooClass;
document.enqueueChanges(() => {
const batch = options.batch || document.batch();
const blocks = (options.selection || document.selection).getSelectedBlocks();
for (const block of blocks) {
if (!block.is('foo')) {
batch.rename(block, 'foo');
batch.setAttribute(block, 'fooClass', fooClass);
}
}
});
}
Below is the code for the init function in the Foo plugin, including the model→view and view→model conversions:
init() {
const editor = this.editor;
const doc = editor.document;
const data = editor.data;
const editing = editor.editing;
editor.commands.add('foo', new FooCommand(editor));
doc.schema.registerItem('foo', '$block');
buildModelConverter().for(data.modelToView, editing.modelToView)
.fromElement('foo')
.toElement(modelElement => {
const fooClass = modelElement.item.getAttribute('fooClass'));
return new ContainerElement('section', {'class': fooClass});
});
buildViewConverter().for(data.viewToModel)
.fromElement('section')
.toElement(viewElement => {
let classes = Array.from(viewElement.getClassNames());
let modelElement = new ModelElement('foo', {'fooClass': classes[0]});
return modelElement;
});
}
When I try to run the command via
editor.execute('foo', { fooClass: 'green-foo' })
I can see that the green-foo value is available to FooCommand, but the modelElement in the model→view conversion, on the other hand, has no fooClass attribute.
I'm sure I'm missing the point here and misusing the APIs. I'd be really thankful if someone could shed some light on this issue. I can provide more details, as needed.
Follow-up after initial suggestions
Thanks to #Reinmar and #jodator for their suggestion regarding configuring the document schema to allow for the custom attribute. I really thought that would have taken care of it, but no. It may have been a necessary step anyway, but I'm still unable to get the attribute value from the model element during the model→view conversion.
First, let me add an important piece of information I had left out: the CKEditor5's version I'm working with is 1.0.0-alpha2. I am aware several of the APIs are bound to change, but I would still like to get things working with the present version.
Model→view conversion
If I understand it correctly, one can either pass a string or a function to the toElement call. A question about using the latter: what exactly are the parameters passed to the function? I assumed it would be the model element (node?) to be converted. Is that the case? If so, why is the attribute set on that node via batch.setAttribute (inside a document.enqueueChanges) not available when requested? Should it be?
A sequencing problem?
Additional testing seems to indicate there's some kind of order-of-execution issue happening. I've observed that, even though the attribute is not available when I first try to read it from the modelElement parameter, it will be so if I read it again later. Let me try to illustrate the situation below. First, I'll modify the conversion code to make it use some dummy value in case the attribute value is not available when read:
buildModelConverter().for(data.modelToView, editing.modelToView)
.fromElement('foo')
.toElement(modelElement => {
let fooClass = modelElement.item.getAttribute('fooClass') || 'naught';
let viewElement = new ContainerElement('section');
viewElement.setAttribute('class', fooClass);
return viewElement;
});
Now I reload the page and execute the following instructions on the console:
c = Array.from(editor.document.getRoot().getChildren());
c[1].is('paragraph'); // true
// Changing the node from 'paragraph' to 'foo' and adding an attribute
// 'fooClass' with value 'green-foo' to it.
editor.document.enqueueChanges(() => {
const batch = editor.document.batch();
batch.rename(c[1], 'foo');
batch.setAttribute(c[1], 'fooClass', 'green-foo');
return batch;
});
c[1].is('paragraph'); // false
c[1].is('foo'); // true
c[1].hasAttribute('fooClass'); // true
c[1].getAttribute('fooClass'); // 'green-foo'
Even though it looks like the expected output is being produced, a glance at the generated view element shows the problem:
<section class="naught"/>
Lastly, even if I try to reset the fooClass attribute on the model element, the change is not reflected on the view element. Why is that? Shouldn't changes made via enqueueChanges cause the view to update?
Sorry for the very long post, but I'm trying to convey as many details as I can. Here's hoping someone will spot my mistake or misunderstanding of how the CKEditor 5's API actually works.
View not updating?
I turned to Document's events and experimented with the changesDone event. It successfully addresses the "timing" issue, as it consistently triggers only after all changes have been processed. Still, the problem of the view not updating in response to a change in the model remains. To make it clear, the model does change, but the view does not reflect that. Here is the call:
editor.document.enqueueChanges(() => editor.document.batch().setAttribute(c[1], 'fooClass', 'red-foo'));
To be 100% sure I wrote the whole feature myself. I use the 1.0.0-beta.1 API which is completely different than what you had.
Basically – it works. It isn't 100% correct yet, but I'll get to that.
How to convert an element+attribute pair?
The thing when implementing a feature which needs to convert element + attribute is that it requires handling the element and attribute conversion separately as they are treated separately by CKEditor 5.
Therefore, in the code below you'll find that I used elementToElement():
editor.conversion.elementToElement( {
model: 'foo',
view: 'section'
} );
So a converter between model's <foo> element and view's <section> element. This is a two-way converter so it handles upcasting (view -> model) and downcasting (model -> view) conversion.
NOTE: It doesn't handle the attribute.
Theoretically, as the view property you could write a callback which would read the model element's attribute and create view element with this attribute set too. But that wouldn't work because such a configuration would only make sense in case of downcasting (model -> view). How could we use that callback to downcast a view structure?
NOTE: You can write converters for downcast and upcast pipelines separately (by using editor.conversion.for()), in which case you could really use callbacks. But it doesn't really make sense in this case.
The attribute may change independently!
The other problem is that let's say you wrote an element converter which sets the attribute at the same time. Tada, you load <section class=ohmy> and gets <foo class=ohmy> in your model.
But then... what if the attribute will change in the model?
In the downcast pipeline CKEditor 5 treats element changes separately from attribute changes. It fires them as separate events. So, when your FooCommand is executed on a heading it calls writer.rename() and we get the following events in DowncastDispatcher:
remove with <heading>
insert:section
But then the attribute is changed too (writer.setAttribute()), so we also get:
setAttibute:class:section
The elementToElement() conversion helper listens to insert:section event. So it's blind to setAttribute:class:selection.
Therefore, when you change the value of the attribute, you need the attributeToAttribute() conversion.
Sequencing
I didn't want to reply to your question before we released 1.0.0-beta.1 because 1.0.0-beta.1 brought the Differ.
Before 1.0.0-beta.1 all changes were converted immediately when they were applied. So, rename() would cause immediate remove and insert:section events. At this point, the element that you got in the latter one wouldn't have the class attribute set yet.
Thanks to the Differ we're able to start the conversion once all the changes are applied (after change() block is executed). This means that the insert:section event is fired once the model <foo> element has the class attribute set already. That's why you could write a callback-based converters... bur you shouldn't :D
The code
import { downcastAttributeToAttribute } from '#ckeditor/ckeditor5-engine/src/conversion/downcast-converters';
import { upcastAttributeToAttribute } from '#ckeditor/ckeditor5-engine/src/conversion/upcast-converters';
class FooCommand extends Command {
execute( options = {} ) {
const model = this.editor.model;
const fooClass = options.class;
model.change( writer => {
const blocks = model.document.selection.getSelectedBlocks();
for ( const block of blocks ) {
if ( !block.is( 'foo' ) ) {
writer.rename( block, 'foo' );
writer.setAttribute( 'class', fooClass, block );
}
}
} );
}
}
class FooPlugin extends Plugin {
init() {
const editor = this.editor;
editor.commands.add( 'foo', new FooCommand( editor ) );
editor.model.schema.register( 'foo', {
allowAttributes: 'class',
inheritAllFrom: '$block'
} );
editor.conversion.elementToElement( {
model: 'foo',
view: 'section'
} );
editor.conversion.for( 'upcast' ).add(
upcastAttributeToAttribute( {
model: 'class',
view: 'class'
} )
);
editor.conversion.for( 'downcast' ).add(
downcastAttributeToAttribute( {
model: 'class',
view: 'class'
} )
);
// This should work but it does not due to https://github.com/ckeditor/ckeditor5-engine/issues/1379 :(((
// EDIT: The above issue is fixed and will be released in 1.0.0-beta.2.
// editor.conversion.attributeToAttribute( {
// model: {
// name: 'foo',
// key: 'class'
// },
// view: {
// name: 'section',
// key: 'class'
// }
// } );
}
}
This code works quite well, except the fact that it converts the class attribute on any possible element that has it. That's because I had to use very generic downcastAttributeToAttribute() and upcastAttributeToAttribute() converters because of a bug that I found (EDIT: it's fixed and will be available in 1.0.0-beta.2). The commented out piece of code is how you it should be defined if everything worked fine and it will work in 1.0.0-beta.2.
It's sad that we missed such a simple case, but that's mainly due to the fact that all our features... are much more complicated than this.

Create From Grid in Same Window

I'm attempting to update the Add New button on a grid to open in the current window, rather than a new one. I've edited the ribbon XML, and I'm correctly getting this function called on click of the "+" icon:
export function createCase(selectedEntityTypeCode: number, parentEntityTypeCode: number, firstPrimaryItemId: string, primaryControl: string, selectedControl: string): void {
window.top.location.replace(CommonLib.getCreateEntityFromParentUrl(firstPrimaryItemId, parentEntityTypeCode, selectedEntityTypeCode));
}
The call to getCreateEntityFromParentUrl creates this string:
etc=112&extraqs=%3f_CreateFromId%3d%257b999BA23A-B07A-E611-80DD-FC15B4286CB8 %257d%26_CreateFromType%3d10010%26etc%3d112&newWindow=false&pagetype= entityrecord
Which opens a new Case form, with the correct Parent entity already populated, so I know it's reading from the CreateFromID and CreateFromType correctly.
If you don't actually create the Case, and click refresh in the browser, you're taken back to the parent entity (A Custom entity, "Location", in this case).
If you save create the Case, and then click refresh in the browser, you get this error:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault,
Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35]]: System.Web.HttpUnhandledException:
Microsoft Dynamics CRM has experienced an error. Reference number for
administrators or support: #5B02AEE3Detail:
-2147220970 System.Web.HttpUnhandledException: Microsoft Dynamics
CRM has experienced an error. Reference number for administrators or
support: #5B02AEE3
2016-09-15T04:30:58.0199249Z
-2147220969
allgnt_location With Id = 3e10a729-fd7a-e611-80dd-fc15b4286cb8 Does Not Exist
2016-09-15T04:30:58.0199249Z
You also get this error if you create a phone call from this entity, and click the Complete Call button in the Command bar.
The Id listed is an id for the Case, but apparently, CRM is trying to load it as the Location instead, which is obviously failing. Am I doing it wrong?
Thanks #Polshgiant for getting me started down the right track. I needed to call Xrm.Utility.openEntityForm. This Typescript function works for me!
/**
* Opens a create form for a child entity of a parent. Useful if a subgrid add new button should redirect to the new page, rather than the default open in a new window.
* #param parentEntityId Id of the parent entity
* #param parentEntityTypeCode Object Type Code of the parent Entity
* #param childLogicalName Child Logical Name
* #param parameters Object whos properties will be added to the extraQs parameters
*/
export function openCreateChildFormInCurrentWindow(parentEntityId: string, parentEntityTypeCode: number, childLogicalName: string, parameters?: any) {
const params = {
formid: null,
["_CreateFromId"]: parentEntityId,
["_CreateFromType"]: parentEntityTypeCode.toString()
} as Xrm.Utility.FormOpenParameters;
if (parameters) {
for (const param in parameters) {
if (parameters.hasOwnProperty(param)) {
params[param] = parameters[param];
}
}
}
Xrm.Utility.openEntityForm(childLogicalName, null, params, { openInNewWindow: false } as Xrm.Utility.WindowOptions);
}

How to call an EventType on a goog.ui.tree.Basenode?

I am constructing a tree using the Google Closure Library. Now I want the nodes to expand on a single mouseclick, but I seem not to get it working.
I've tried calling goog.ui.component.EventType.SELECT, but it won't work.
At my tree-component class I've added the following event:
goog.events.listen(item, [goog.ui.Component.EventType.SELECT, goog.ui.tree.BaseNode.EventType.EXPAND], this.dispatchEvent, false, this);
And at my class calling the function i've added:
goog.events.listen(this._tree, [goog.ui.Component.EventType.SELECT, goog.ui.tree.BaseNode.EventType.EXPAND], this.treeClick, false, this)
Any suggestions on how I could expand my node with a single click?
I see that BaseNode is screwing up any click events:
/**
* Handles a click event.
* #param {!goog.events.BrowserEvent} e The browser event.
* #protected
* #suppress {underscore}
*/
goog.ui.tree.BaseNode.prototype.onClick_ = goog.events.Event.preventDefault;
When adding this code to the goog/demos/tree/demo.html:
goog.ui.tree.BaseNode.prototype.onClick_ = function (e) {
var qq = this.expanded_?this.collapse():this.expand();
};
The tree control expands and collapses on one click.
Tried to extend goog.ui.tree.TreeControl and override createNode to return a custom goog.ui.tree.TreeNode that overrides onClick but could not do it without getting errors. In theory you could create your custom TreeControl that expands and collapses on one click.
If you want to support non collapsable content and other features I guess you have to trigger some sort of event instead of just extend or callapse the TreeNode.
[update]
After some fiddling I got it working by subclassing TreeControl and TreeNode added the following code to goog/demos/tree/demo.html
/**
* This creates a myTreeControl object. A tree control provides a way to
* view a hierarchical set of data.
* #param {string} html The HTML content of the node label.
* #param {Object=} opt_config The configuration for the tree. See
* goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config
* will be used.
* #param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* #constructor
* #extends {goog.ui.tree.BaseNode}
*/
var myTreeControl = function (html, opt_config, opt_domHelper) {
goog.ui.tree.TreeControl.call(this, html, opt_config, opt_domHelper);
};
goog.inherits(myTreeControl, goog.ui.tree.TreeControl);
/**
* Creates a new myTreeNode using the same config as the root.
* myTreeNode responds on single clicks
* #param {string} html The html content of the node label.
* #return {goog.ui.tree.TreeNode} The new item.
* #override
*/
myTreeControl.prototype.createNode = function (html) {
return new myTreeNode(html || '', this.getConfig(),
this.getDomHelper());
};
/**
* A single node in the myTreeControl.
* #param {string} html The html content of the node label.
* #param {Object=} opt_config The configuration for the tree. See
* goog.ui.tree.TreeControl.defaultConfig. If not specified, a default config
* will be used.
* #param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* #constructor
* #extends {goog.ui.tree.BaseNode}
*/
var myTreeNode = function (html, opt_config, opt_domHelper) {
goog.ui.tree.TreeNode.call(this,html, opt_config, opt_domHelper)
}
goog.inherits(myTreeNode, goog.ui.tree.TreeNode);
/**
* Handles a click event.
* #param {!goog.events.BrowserEvent} e The browser event.
* #override
*/
myTreeNode.prototype.onClick_ = function (e) {
goog.base(this, "onClick_", e);
this.onDoubleClick_(e);
};
Changed the creation of the tree variable:
tree = new myTreeControl('root', treeConfig);
Works on single clicks and have not noticed any other things breaking. I've added the annotations so it'll compile easier. You might put the declarations in a separate file with a goog.provide.
Too bad the handleMouseEvent_ of TreeControl is private or you'll just override that one but you can't without changing either TreeControl source or getting compile errors/warnings. Ach wel, jammer.

Create java-like document for function in IOS (Xcode)

I'm beginner with IOS developing and I'm using Xcode. In java (android), I can create document for a function like below:
/**
* Get the index object in list of object and try to catch
* {#link IndexOutOfBoundsException}
*
* #param list
* of object: {#link List}
* #param index
* of ojbect: {#link Integer}
* #return Object or null if {#link IndexOutOfBoundsException} occurs
*/
public static <T> T getIndexObject(List<T> list, int index) {
T object = null;
try {
object = list.get(index);
} catch (IndexOutOfBoundsException e) {
return null;
}
return object;
}
When I create document as above (in Java), every time when I hover the mouse over the function (used in every where), I will see the document of that function. How's about IOS in Xcode? I know Doxygen, but It only generate HTML files (that not what I want). I want document like default document of every function that provided by Apple (when Ctrl + click on a function of IOS SDK)? Can I do it? And how? Thanks!!
Use AppleDoc. They have an article on their site that explains how to integrate with Xcode: http://gentlebytes.com/appledoc-docs-examples-xcode/, basically, you use:
appledoc
--project-name appledoc
--project-company "Gentle Bytes"
--company-id com.gentlebytes
--output ~/help
--logformat xcode
.
to generate the documents. You can also do the normal HTML in addition. It's free and looks a lot like Apple's documentation.

play framework 2.0 - internationalization - how to translate a message

First question: how can I retrieve the translation of a text in a controller?
Second question: how can I retrieve the translation of a text in a template?
The api says that there is a .get method that translates a message:
http://www.playframework.org/documentation/api/2.0/java/play/i18n/Messages.html
However my application does not recognize this method. Opening in eclipse the Message.class shows that there is an .apply method in it, written in Scala and Java!?
object Messages {
/**
* Translates a message.
*
* Uses `java.text.MessageFormat` internally to format the message.
*
* #param key the message key
* #param args the message arguments
* #return the formatted message or a default rendering if the key wasn’t defined
*/
def apply(key: String, args: Any*)(implicit lang: Lang): String = {
Play.maybeApplication.flatMap { app =>
app.plugin[MessagesPlugin].map(_.api.translate(key, args)).getOrElse(throw new Exception("this plugin was not registered or disabled"))
}.getOrElse(noMatch(key, args))
}
Now eclipse tells me that I can invoke this method like this:
> String play.api.i18n.Messages.apply(String arg0, Seq<Object> arg1,
> Lang arg2)
But what should I enter as the "Seq" argument?
--The solution--
The problem was that I imported play.api.i18n.Messages instead of play.i18n.Messages ...
Having defined two message files (messages.de-DE and messages.en-UK) and using the following code everything works fine:
Controller:
import play.i18n.Messages;
import play.api.i18n.Lang;
Lang en = new Lang("en","GB");
play.i18n.Lang en_lang = new play.i18n.Lang(en);
Lang de = new Lang("de", "DE");
play.i18n.Lang de_lang = new play.i18n.Lang(de);
Logger.info(Messages.get("home.title"));
Logger.info(Messages.get(en_lang, "home.title"));
Logger.info(Messages.get(de_lang, "home.title"));
application.conf
application.langs="en-GB,de-DE"
Getting the translation inside the controller:
// in messages file
msg.key=Hello Translation
// in you controller
Messages.get("msg.key");
You can even pass parameters:
// in messages file
msg.key=Hello {0}, here is your translation
//in controller
Messages.get("msg.key", User.firstName);
From the view you can use: Messages("msg.key")
You can even apply HTML formatting (only applicable for views of course):
// in messages file
msg.key=Hello <strong>{0}</strong>, here is your translation
// in controller
Messages.get("msg.key", User.firstName);
//in view
#Html(objectInView)
Please note the following:
Currently it is not possible to define the language explicitly, see bug report: https://play.lighthouseapp.com/projects/82401/tickets/174-20-i18n-add-ability-to-define-implicit-lang-for-java-api
Similar question was asked before:
Access translated i18n messages from Scala templates (Play! Internationalization)
i18n error: controller and templates uses different implicit languages

Resources