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

跟風遠走 提交于 2020-01-25 00:27:26

问题


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?


回答1:


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
    } );
} );


来源:https://stackoverflow.com/questions/54982312/how-to-define-ckeditor5-two-way-converter-with-view-defined-as-regexp-or-functio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!