After 1.0.0-beta (March 2018):
To insert some data into an editor, simply use a "change block":
editor.model.change( writer => {
const insertPosition = editor.model.document.selection.getFirstPosition();
writer.insertText( linkText, { linkHref: linkUrl }, insertPosition );
} );
where linkText
and linkUrl
are variables that you should provide from your custom UI.
The above will work well for collapsed selection. The linked text will be inserted at caret position.
The big difference introduced in 1.0.0-beta is that we are providing the writer
object in change()
calls, so you don't need to (and should not) use framework classes constructors directly.
You can also use editor.model.insertContent
in a similar way that you proposed:
editor.model.change( writer => {
const linkedText = writer.createText( linkText, { linkHref: linkUrl } );
editor.model.insertContent( linkedText, editor.model.document.selection );
} );
This will work properly also if the selection is not collapsed, as insertContent
does a little bit more (for example, if selection was not collapsed and was between two paragraphs, selection contents will be removed and paragraphs merged).
Before 1.0.0-beta
DataController#insertContent()
accepts model's DocumentFragment
or Node
(so Element
or Text
– I've just noticed that this info is missing in the API docs).
Unfortunately, right now you need to have access to Element
's or Text
's constructors in order to create them. This means that you need to build CKEditor 5 from source instead of using existing builds. This isn't hard, but it's indeed an overkill. Therefore, we're working now on exposing a sufficient part of the API in the existing classes so that you could write simple integration code like this without building CKEditor 5 into your app.
Anyway, if you'll configure webpack (or simply fork an existing build) you can write a simple function for inserting a linked text:
import Text from '@ckeditor/ckeditor5-engine/src/model/text';
function insertLink( linkText, linkHref ) {
const text = new Text( linkText, { linkHref } );
editor.document.enqueueChanges( () => {
editor.data.insertContent( text, editor.document.selection );
} );
}