ckeditor5

ckeditor5 create element "image" with attributes


I'm trying to create a custom plugin to insert an image from my already built media browser. I'd like to attach some attributes to the image. No matter what I try it only inserts the image with the src and alt attribute. In other words my image is always missing the data-source and class attribute. I've tried the data attribute key as dataSource but that also doesn't work.

const imageElement = writer.createElement( 'image',  {
    'src': src,
    'alt': alt,
    'data-sources': dataSources,
    'class': cls
} );
editor.model.insertContent( imageElement, editor.model.document.selection );

Any ideas or suggestions would be greatly appreciated.


Solution

  • You need to make 2 things to process new attributes of an image.

    First, you need to extend the schema with proper rules which inform model that given attributes are allowed in the editor.

    Second thing is to inform the editor how to convert given attribute to model structure and vice-versa with proper converters.

    Unfortunately, image converters are quite complicated, because the image is always wrapped with <figure>. Below you can find code and link to working sample how you can create such converters (converters are created based on the source code of the image plugin for CKEditor5). For the purpose of this sample, the data-source attribute is stored in the model as dSource attribute of an image element.

    editor.model.schema.extend("image", { allowAttributes: "dSource" });
    
    editor.conversion.for("upcast").attributeToAttribute({
      view: "data-source",
      model: "dSource",
    });
    
    editor.conversion.for("downcast").add((dispatcher) => {
      dispatcher.on("attribute:dSource:image", (evt, data, conversionApi) => {
        if (!conversionApi.consumable.consume(data.item, evt.name)) {
          return;
        }
    
        const viewWriter = conversionApi.writer;
        const figure = conversionApi.mapper.toViewElement(data.item);
        const img = figure.getChild(0);
    
        if (data.attributeNewValue !== null) {
          viewWriter.setAttribute("data-source", data.attributeNewValue, img);
        } else {
          viewWriter.removeAttribute("data-source", img);
        }
      });
    });
    

    Link to working sample: https://codepen.io/msamsel/pen/pXKRed?editors=1010