Search code examples
ckeditorckeditor5

How implement FocusCycler/FocusTracker in a ckeditor5 plugin


I'm developing a plugin using ckeditor5. I did schema, converters, events, commands to insert the plugin block (a table) on editor, and it is working right, but I'm lost about implement FocusCycler/FocusTracker to change cells focus following a determinate order using TAB or ENTER. Where I do it? What the best way to do?


Solution

  • Following the tip of @oleq, I found the solution using the Position and TreeWalker classes:

    import {keyCodes} from '@ckeditor/ckeditor5-utils/src/keyboard';
    import ViewPosition from '@ckeditor/ckeditor5-engine/src/view/position';
    import ViewTreeWalker from '@ckeditor/ckeditor5-engine/src/view/treewalker';
    
    editor.editing.view.document.on('keydown', (evt, data) => {
        evt.stop();
        if ( data.keyCode === keyCodes.enter ) {
            let current = editor.editing.view.document.selection.getFirstRange();
            let position = new ViewPosition(current.start.parent);
            let walker = new ViewTreeWalker({startPosition: position});
            for (let element of walker) {
                if ( element.type === 'elementStart' && element.item._attrs.get('editableElement') === 'true') {
                    editor.editing.view.change(writer => {
                        writer.setSelection(element.item, 'in');
                    });
                    return;
                }
            }
        }
    });