How to programatically insert link at current position in CKEditor 5

后端 未结 1 989
眼角桃花
眼角桃花 2020-12-19 13:02

In my app, I have a specific dialog to create internal links. After user finishes filling the dialog I want to programatically insert generated link to current caret positio

相关标签:
1条回答
  • 2020-12-19 13:55

    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 );
        } );
    }
    
    0 讨论(0)
提交回复
热议问题