All files / roosterjs-content-model-plugins/lib/picker PickerPlugin.ts

93.55% Statements 87/93
82.05% Branches 96/117
83.33% Functions 10/12
93.26% Lines 83/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 2541x 1x 1x 1x                                   1x 59x 59x 59x             59x         1x               1x 59x 59x 59x           1x                         1x 3x                           1x 117x       117x   4x 3x 2x   1x     4x     53x 52x   53x     58x 1x   57x   58x     2x 1x   2x       1x 52x     10x 8x   8x 4x     8x     10x 10x       10x   10x 6x                       10x 10x     10x       10x 10x     20x 20x                   20x 20x   1x 1x 1x       1x 1x 1x       2x 2x   2x         2x   2x             2x 2x         2x             57x 57x 57x 57x 57x   57x         57x   57x             57x 57x 57x         57x       1x  
import { ChangeSource, isCursorMovingKey, isPunctuation } from 'roosterjs-content-model-dom';
import { formatTextSegmentBeforeSelectionMarker } from 'roosterjs-content-model-api';
import { getQueryString } from './getQueryString';
import { PickerHelperImpl } from './PickerHelperImpl';
import type { PickerHandler } from './PickerHandler';
import type {
    DOMInsertPoint,
    EditorPlugin,
    IEditor,
    PluginEvent,
} from 'roosterjs-content-model-types';
 
/**
 * PickerPlugin represents a plugin of editor which can handle picker related behaviors, including
 * - Show picker when special trigger key is pressed
 * - Hide picker
 * - Change selection in picker by Up/Down/Left/Right
 * - Apply selected item in picker
 *
 * PickerPlugin doesn't provide any UI, it just wraps related DOM events and invoke callback functions.
 */
export class PickerPlugin implements EditorPlugin {
    private isMac: boolean = false;
    private lastQueryString = '';
    private helper: PickerHelperImpl | null = null;
 
    /**
     * Construct a new instance of PickerPlugin class
     * @param triggerCharacter The character to trigger a picker to be shown
     * @param handler Picker handler for receiving picker state change events
     */
    constructor(private triggerCharacter: string, private readonly handler: PickerHandler) {}
 
    /**
     * Get a friendly name
     */
    getName() {
        return 'Picker';
    }
 
    /**
     * Initialize this plugin. This should only be called from Editor
     * @param editor Editor instance
     */
    initialize(editor: IEditor) {
        this.isMac = !!editor.getEnvironment().isMac;
        this.helper = new PickerHelperImpl(editor, this.handler, this.triggerCharacter);
        this.handler.onInitialize(this.helper);
    }
 
    /**
     * Dispose this plugin
     */
    dispose() {
        this.handler.onDispose();
        this.helper = null;
    }
 
    /**
     * Check if the plugin should handle the given event exclusively.
     * Handle an event exclusively means other plugin will not receive this event in
     * onPluginEvent method.
     * If two plugins will return true in willHandleEventExclusively() for the same event,
     * the final result depends on the order of the plugins are added into editor
     * @param event The event to check
     */
    willHandleEventExclusively(event: PluginEvent) {
        return (
            !!this.helper?.direction &&
            event.eventType == 'keyDown' &&
            (isCursorMovingKey(event.rawEvent) ||
                event.rawEvent.key == 'Enter' ||
                event.rawEvent.key == 'Tab' ||
                event.rawEvent.key == 'Escape')
        );
    }
 
    /**
     * Handle events triggered from editor
     * @param event PluginEvent object
     */
    onPluginEvent(event: PluginEvent) {
        Iif (!this.helper) {
            return;
        }
 
        switch (event.eventType) {
            case 'contentChanged':
                if (this.helper.direction) {
                    if (event.source == ChangeSource.SetContent) {
                        this.helper.closePicker();
                    } else {
                        this.onSuggestingInput(this.helper);
                    }
                }
                break;
 
            case 'keyDown':
                if (this.helper.direction) {
                    this.onSuggestingKeyDown(this.helper, event.rawEvent);
                }
                break;
 
            case 'input':
                if (this.helper.direction) {
                    this.onSuggestingInput(this.helper);
                } else {
                    this.onInput(this.helper, event.rawEvent);
                }
                break;
 
            case 'mouseUp':
                if (this.helper.direction) {
                    this.helper.closePicker();
                }
                break;
        }
    }
 
    private onSuggestingKeyDown(helper: PickerHelperImpl, event: KeyboardEvent) {
        switch (event.key) {
            case 'ArrowLeft':
            case 'ArrowRight':
                if (helper.direction == 'horizontal' || helper.direction == 'both') {
                    let isIncrement = event.key == 'ArrowRight';
 
                    if (helper.editor.getDOMHelper().isRightToLeft()) {
                        isIncrement = !isIncrement;
                    }
 
                    this.handler.onSelectionChanged?.(isIncrement ? 'next' : 'previous');
                }
 
                event.preventDefault();
                break;
            case 'ArrowUp':
            case 'ArrowDown':
                {
                    const isIncrement = event.key == 'ArrowDown';
 
                    if (helper.direction != 'horizontal') {
                        this.handler.onSelectionChanged?.(
                            helper.direction == 'both'
                                ? isIncrement
                                    ? 'nextRow'
                                    : 'previousRow'
                                : isIncrement
                                ? 'next'
                                : 'previous'
                        );
                    }
                }
 
                event.preventDefault();
                break;
            case 'PageUp':
            case 'PageDown':
                this.handler.onSelectionChanged?.(
                    event.key == 'PageDown' ? 'nextPage' : 'previousPage'
                );
 
                event.preventDefault();
                break;
            case 'Home':
            case 'End':
                const hasCtrl = this.isMac ? event.metaKey : event.ctrlKey;
                this.handler.onSelectionChanged?.(
                    event.key == 'Home'
                        ? hasCtrl
                            ? 'first'
                            : 'firstInRow'
                        : hasCtrl
                        ? 'last'
                        : 'lastInRow'
                );
 
                event.preventDefault();
                break;
            case 'Escape':
                helper.closePicker();
                event.preventDefault();
                break;
 
            case 'Enter':
            case 'Tab':
                this.handler.onSelect?.();
                event.preventDefault();
                break;
        }
    }
 
    private onSuggestingInput(helper: PickerHelperImpl) {
        Iif (
            !formatTextSegmentBeforeSelectionMarker(helper.editor, (_, segment, paragraph) => {
                const newQueryString = getQueryString(
                    this.triggerCharacter,
                    paragraph,
                    segment
                ).replace(/[\u0020\u00A0]/g, ' ');
                const oldQueryString = this.lastQueryString;
 
                Eif (
                    newQueryString &&
                    ((newQueryString.length >= oldQueryString.length &&
                        newQueryString.indexOf(oldQueryString) == 0) ||
                        (newQueryString.length < oldQueryString.length &&
                            oldQueryString.indexOf(newQueryString) == 0))
                ) {
                    this.lastQueryString = newQueryString;
                    this.handler.onQueryStringChanged?.(newQueryString);
                } else {
                    helper.closePicker();
                }
 
                return false;
            })
        ) {
            helper.closePicker();
        }
    }
 
    private onInput(helper: PickerHelperImpl, event: InputEvent) {
        Eif (event.inputType == 'insertText' && event.data == this.triggerCharacter) {
            formatTextSegmentBeforeSelectionMarker(helper.editor, (_, segment) => {
                Eif (segment.text.endsWith(this.triggerCharacter)) {
                    const charBeforeTrigger = segment.text[segment.text.length - 2];
 
                    Eif (
                        !charBeforeTrigger ||
                        !charBeforeTrigger.trim() ||
                        isPunctuation(charBeforeTrigger)
                    ) {
                        const selection = helper.editor.getDOMSelection();
                        const pos: DOMInsertPoint | null =
                            selection?.type == 'range' && selection.range.collapsed
                                ? {
                                      node: selection.range.startContainer,
                                      offset: selection.range.startOffset,
                                  }
                                : null;
 
                        Eif (pos) {
                            this.lastQueryString = this.triggerCharacter;
                            helper.direction = this.handler.onTrigger(this.lastQueryString, pos);
                        }
                    }
                }
 
                return false;
            });
        }
    }
}