Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define CKEditor5 two-way converter with view defined as RegExp or function?

I'd like to create plugin which allows on many values, which are considered as range not a list. So I thought, that I could use attributeToElement, but it seems to accept only specific values, which are kept in object, what is not possible for my case. I wonder how to define view elements with entire range of possible values (in my case colors). I thought about matching them with some sort of RegExp or function. How can I achieve that?

like image 749
Mateusz Samsel Avatar asked Nov 30 '25 02:11

Mateusz Samsel


1 Answers

Actually it seems to be not possible to use attributeToElement converter provided with CKEditor5. This converter needs to have limited predefined amount of options provided for conversion, which will be used for both upcast and downcast.

From perspective of plugin which I want to write (color font) it's not sufficient. I don't want to limit model to accept only few colors and prevent of using different one.

To have more control over upcast and downcast is necessary to write own functions which will cover such cases. And which will be able to accept any color inserted to editor. To do so it's required to use for method. Below you can find some simple solution which will accept colors defined in hex and upcast it to model. And another function which will downcast it to view.

Upcast:

editor.conversion.for( 'upcast' ).elementToAttribute( {
    view: {
        name: 'span',
        styles: {
            'color': /#\d+/
        }
    },
    model: {
        key: 'color',
        value: viewElement => {
            const color = viewElement.getStyle( 'color' );
            return color.replace( '#', '' );
        }
    }
} );

Downcast:

editor.conversion.for( 'downcast' ).attributeToElement( {
    model: 'color',
    view: ( modelAttributeValue, viewWriter ) => viewWriter.createAttributeElement( 'span', {
        style: 'color:#' + modelAttributeValue
    } );
} );
like image 59
Mateusz Samsel Avatar answered Dec 02 '25 15:12

Mateusz Samsel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!