Enable CKEditor toolbar button only with valid text selection?

前端 未结 3 1640
醉梦人生
醉梦人生 2021-01-21 13:04

I\'m working on a CKEditor plugin for annotating text and adding margin comments, but I\'d like some of my custom toolbar buttons to be enabled only when the user has already se

3条回答
  •  逝去的感伤
    2021-01-21 13:25

    Your case is a little tricky, because selection change event is not well implemented across browsers, FF is the main problem.

    In your case you'll going to need check selection changes very frequently, as you're interested in all selection changes therefore CKEditor selectionChange won't fit it.

    Fortunately there's a selectionCheck event in editor that fires much more frequently and is implemented for FF.

    Solution:

    Here you have init method of a plugin that I've mocked to solve your problem. It will disable / enable Source button the way you explained.

    I've already added throttling to this function, so that customers with less expansive machine can admire your feature :)

    init: function( editor ) {
        // Funciton depending on editor selection (taken from the scope) will set the state of our command.
        function RefreshState() {
            var editable = editor.editable(),
                // Command that we want to control.
                command = editor.getCommand( 'source' ),
                range,
                commandState;
    
            if ( !editable ) {
                // It might be a case that editable is not yet ready.
                return;
            }
    
            // We assume only one range.
            range = editable.getDocument().getSelection().getRanges()[ 0 ];
    
            // The state we're about to set for the command.
            commandState = ( range && !range.collapsed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED;
    
            command.setState( commandState );
        }
    
        // We'll use throttled function calls, because this event can be fired very, very frequently.
        var throttledFunction = CKEDITOR.tools.eventsBuffer( 250, RefreshState );
    
        // Now this is the event that detects all the selection changes.
        editor.on( 'selectionCheck', throttledFunction.input );
    
        // You'll most likely also want to execute this function as soon as editor is ready.
        editor.on( 'instanceReady', function( evt ) {
            // Also do state refresh on instanceReady.
            RefreshState();
        } );
    }
    

提交回复
热议问题