问题
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