Use my existing Rich Text UI with CKEditor APIs

2019-02-19 19:41发布

问题:

I have an existing Rich Text UI that I'd like to use with CKEditor. Basically, I want CKEditor to handle the complicated parts of applying styles, formats, filtering, and normalizing inserted content. My existing UI needs to drive the interaction and show state based on selection (ie. selecting bold text should be reflected in the state of my 'Bold' button in the UI.

I have got the integration to a point where I can apply bold, italic, and underline formats, change font size, and add styles.

For bold, italic, and underline:

var editor = this.getEditor();

        editor.execCommand('underline'); // bold, italic

(Note, I added config.extraAllowedContent = 'strong;u;em'; in config.js to enable underline)

For changing font size:

var editor = this.getEditor();
        var style = new CKEDITOR.style({
            element: 'span',
            styles: { 'font-size': fontSize + 'px' },
            overrides: [{
                element: 'font', attributes: { 'size': null }
            },{
                element: 'span', attributes: { 'class': null }
            }]
        });

        editor.applyStyle(style);

For toggling between styles (css classes):

var editor = this.getEditor();

        _.each(this.textStyleChoices, function(styleChoice) {
            var style = new CKEDITOR.style({
                element: 'span',
                attributes: { 'class': styleChoice.style }
            });

            if(styleChoice.style === textStyle && !style.checkActive(editor.elementPath(), editor)) {
                editor.applyStyle(style);
            } else {
                editor.removeStyle(style);
            }
        });

Now, I believe I am going about this in the wrong way, as with this approach I am clearly going to run into some css specificity issues. Note, my css classes for my 'styles' contains attributes such as color, font-size, etc. So, if I apply a style that has font size 40px to my selection:

This is my [selected text]

And then change the font size of that selection to 10px, then this is the resulting html:

This is my [<span style="font-size:10px;"><span class="style1">selected text</span></span>]

Which results in the selected text having a font size of 40px.

If the two spans were merged, then the font size would be correctly set at 10px. Obviously, this is a simple example; there are more complicated scenarios that would be much more difficult to solve I'm sure.

So, if I have my own UI and want to call into existing functionality to change formatting (bold, underline, italic, text alignment), font size, and add styles, how can this be done? Is this possible? Are there any examples or docs that I can look at that would get me started in the right direction?

As per @Reinmar, I am looking into the Advanced Content Filter, but so far am a bit lost.

Thanks for your help.