All files / roosterjs-content-model-core/lib/corePlugin/selection SelectionPlugin.ts

95.33% Statements 306/321
82.98% Branches 351/423
93.1% Functions 27/29
95.13% Lines 293/308

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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 7571x 1x 1x 1x 1x                                         1x 1x 1x 1x 1x 1x 1x         1x       1x   1x 156x   156x 156x 156x 156x   156x 156x                                 1x       1x 156x   156x 2x         156x       2x                 156x 156x   156x 156x 156x 156x 11x         145x               1x 81x   81x 81x 81x     81x 81x     1x 147x     1x 435x       435x   15x 15x             24x 24x     57x 57x     2x 1x   2x       1x 15x       15x             4x     15x           2x             2x       13x 7x       13x   13x         4x   4x 1x           1x   1x 1x 1x       4x               156x 6x 6x 6x 6x   6x 6x   6x   6x                 6x 6x       6x 6x   6x 5x           5x   2x 2x     5x   5x 4x   1x   1x                       1x       156x 2x     24x 24x 24x 24x   24x   4x 3x 1x 1x 2x 2x       4x         1x 1x 1x                 4x     15x 13x 13x           13x 13x 5x 5x   8x       15x     4x 8x   4x   1x     1x       1x 3x 1x 1x 2x 1x 1x 1x       4x       1x 5x     1x     14x       14x 14x   14x   14x   28x 14x 14x 14x   14x 1x     13x 13x 13x   13x 13x 6x 6x 6x   6x   6x 3x   3x     3x       6x 1x         5x 3x             7x 5x 5x 5x 5x 5x       5x 3x 3x 1x 1x 2x 1x         1x   1x   3x   3x 3x 3x           3x 3x 3x       2x     13x             1x       13x 2x 2x         1x           4x 4x 3x 3x   3x   3x   3x 3x     1x   1x 1x     4x                   1x 2x 2x 2x 2x   2x 2x         1x           8x 8x 8x     8x 7x 7x         1x 1x   6x 6x     7x                     1x 16x   16x             156x       14x 14x                           156x 58x 43x     58x         58x 1x 1x 1x       156x 1x 1x     1x 1x       156x 1096x 8x     8x 8x 4x 4x 1x 1x             3x 1x                 8x 3x 3x           1x                 42x           35x   7x       1x 9x   9x 9x 9x 9x 9x 9x   9x 8x   8x                       8x       1x     1x       78x 78x     1x 83x 1x 1x     1x             1x     156x    
import { findCoordinate } from './findCoordinate';
import { findTableCellElement } from '../../coreApi/setDOMSelection/findTableCellElement';
import { isSingleImageInSelection } from './isSingleImageInSelection';
import { normalizePos } from './normalizePos';
import {
    isCharacterValue,
    isElementOfType,
    isModifierKey,
    isNodeOfType,
    parseTableCells,
    toArray,
} from 'roosterjs-content-model-dom';
import type {
    DOMSelection,
    IEditor,
    PluginEvent,
    PluginWithState,
    SelectionPluginState,
    EditorOptions,
    DOMHelper,
    ParsedTable,
    TableSelectionInfo,
    TableCellCoordinate,
} from 'roosterjs-content-model-types';
 
const MouseLeftButton = 0;
const MouseRightButton = 2;
const Up = 'ArrowUp';
const Down = 'ArrowDown';
const Left = 'ArrowLeft';
const Right = 'ArrowRight';
const Tab = 'Tab';
 
/**
 * @internal
 */
export const DEFAULT_SELECTION_BORDER_COLOR = '#DB626C';
/**
 * @internal
 */
export const DEFAULT_TABLE_CELL_SELECTION_BACKGROUND_COLOR = '#C6C6C6';
 
class SelectionPlugin implements PluginWithState<SelectionPluginState> {
    private editor: IEditor | null = null;
    private state: SelectionPluginState;
    private disposer: (() => void) | null = null;
    private isSafari = false;
    private isMac = false;
    private scrollTopCache: number = 0;
 
    constructor(options: EditorOptions) {
        this.state = {
            selection: null,
            tableSelection: null,
            imageSelectionBorderColor:
                options.imageSelectionBorderColor ?? DEFAULT_SELECTION_BORDER_COLOR,
            imageSelectionBorderColorDark: options.imageSelectionBorderColor
                ? undefined
                : DEFAULT_SELECTION_BORDER_COLOR,
            tableCellSelectionBackgroundColor:
                options.tableCellSelectionBackgroundColor ??
                DEFAULT_TABLE_CELL_SELECTION_BACKGROUND_COLOR,
            tableCellSelectionBackgroundColorDark: options.tableCellSelectionBackgroundColor
                ? undefined
                : DEFAULT_TABLE_CELL_SELECTION_BACKGROUND_COLOR,
        };
    }
 
    getName() {
        return 'Selection';
    }
 
    initialize(editor: IEditor) {
        this.editor = editor;
 
        if (!this.state.imageSelectionBorderColorDark && this.state.imageSelectionBorderColor) {
            this.state.imageSelectionBorderColorDark = editor
                .getColorManager()
                .getDarkColor(this.state.imageSelectionBorderColor, undefined, 'border');
        }
 
        if (
            !this.state.tableCellSelectionBackgroundColorDark &&
            this.state.tableCellSelectionBackgroundColor
        ) {
            this.state.tableCellSelectionBackgroundColorDark = editor
                .getColorManager()
                .getDarkColor(
                    this.state.tableCellSelectionBackgroundColor,
                    undefined,
                    'background'
                );
        }
 
        const env = this.editor.getEnvironment();
        const document = this.editor.getDocument();
 
        this.isSafari = !!env.isSafari;
        this.isMac = !!env.isMac;
        document.addEventListener('selectionchange', this.onSelectionChange);
        if (this.isSafari) {
            this.disposer = this.editor.attachDomEvent({
                focus: { beforeDispatch: this.onFocus },
                drop: { beforeDispatch: this.onDrop },
            });
        } else {
            this.disposer = this.editor.attachDomEvent({
                focus: { beforeDispatch: this.onFocus },
                blur: { beforeDispatch: this.onBlur },
                drop: { beforeDispatch: this.onDrop },
            });
        }
    }
 
    dispose() {
        this.editor?.getDocument().removeEventListener('selectionchange', this.onSelectionChange);
 
        Eif (this.disposer) {
            this.disposer();
            this.disposer = null;
        }
 
        this.detachMouseEvent();
        this.editor = null;
    }
 
    getState(): SelectionPluginState {
        return this.state;
    }
 
    onPluginEvent(event: PluginEvent) {
        Iif (!this.editor) {
            return;
        }
 
        switch (event.eventType) {
            case 'mouseDown':
                this.onMouseDown(this.editor, event.rawEvent);
                break;
 
            case 'mouseUp':
                this.onMouseUp();
                break;
 
            case 'keyDown':
                this.onKeyDown(this.editor, event.rawEvent);
                break;
 
            case 'contentChanged':
                this.state.tableSelection = null;
                break;
 
            case 'scroll':
                if (!this.editor.hasFocus()) {
                    this.scrollTopCache = event.scrollContainer.scrollTop;
                }
                break;
        }
    }
 
    private onMouseDown(editor: IEditor, rawEvent: MouseEvent) {
        const selection = editor.getDOMSelection();
        let image: HTMLImageElement | null;
 
        // Image selection
        if (
            selection?.type == 'image' &&
            (rawEvent.button == MouseLeftButton ||
                (rawEvent.button == MouseRightButton &&
                    !this.getClickingImage(rawEvent) &&
                    !this.getContainedTargetImage(rawEvent, selection)))
        ) {
            this.setDOMSelection(null /*domSelection*/, null /*tableSelection*/);
        }
 
        if (
            (image =
                this.getClickingImage(rawEvent) ??
                this.getContainedTargetImage(rawEvent, selection)) &&
            image.isContentEditable
        ) {
            this.setDOMSelection(
                {
                    type: 'image',
                    image: image,
                },
                null
            );
            return;
        }
 
        // Table selection
        if (selection?.type == 'table' && rawEvent.button == MouseLeftButton) {
            this.setDOMSelection(null /*domSelection*/, null /*tableSelection*/);
        }
 
        let tableSelection: TableSelectionInfo | null;
        const target = rawEvent.target as Node;
 
        if (
            target &&
            rawEvent.button == MouseLeftButton &&
            (tableSelection = this.parseTableSelection(target, target, editor.getDOMHelper()))
        ) {
            this.state.tableSelection = tableSelection;
 
            if (rawEvent.detail >= 3) {
                const lastCo = findCoordinate(
                    tableSelection.parsedTable,
                    rawEvent.target as Node,
                    editor.getDOMHelper()
                );
 
                Eif (lastCo) {
                    // Triple click, select the current cell
                    tableSelection.lastCo = lastCo;
                    this.updateTableSelection(lastCo);
                    rawEvent.preventDefault();
                }
            }
 
            this.state.mouseDisposer = editor.attachDomEvent({
                mousemove: {
                    beforeDispatch: this.onMouseMove,
                },
            });
        }
    }
 
    private onMouseMove = (event: Event) => {
        Eif (this.editor && this.state.tableSelection) {
            const hasTableSelection = !!this.state.tableSelection.lastCo;
            const currentNode = event.target as Node;
            const domHelper = this.editor.getDOMHelper();
 
            const range = this.editor.getDocument().createRange();
            const startNode = this.state.tableSelection.startNode;
            const isReverted =
                currentNode.compareDocumentPosition(startNode) == Node.DOCUMENT_POSITION_FOLLOWING;
 
            Iif (isReverted) {
                range.setStart(currentNode, 0);
                range.setEnd(
                    startNode,
                    isNodeOfType(startNode, 'TEXT_NODE')
                        ? startNode.nodeValue?.length ?? 0
                        : startNode.childNodes.length
                );
            } else {
                range.setStart(startNode, 0);
                range.setEnd(currentNode, 0);
            }
 
            // Use common container of the range to search a common table that covers both start and end node
            const tableStart = range.commonAncestorContainer;
            const newTableSelection = this.parseTableSelection(tableStart, startNode, domHelper);
 
            if (newTableSelection) {
                const lastCo = findCoordinate(
                    newTableSelection.parsedTable,
                    currentNode,
                    domHelper
                );
 
                if (newTableSelection.table != this.state.tableSelection.table) {
                    // Move mouse into another table (nest table scenario)
                    this.state.tableSelection = newTableSelection;
                    this.state.tableSelection.lastCo = lastCo ?? undefined;
                }
 
                const updated = lastCo && this.updateTableSelection(lastCo);
 
                if (hasTableSelection || updated) {
                    event.preventDefault();
                }
            } else Eif (this.editor.getDOMSelection()?.type == 'table') {
                // Move mouse out of table
                this.setDOMSelection(
                    {
                        type: 'range',
                        range,
                        isReverted,
                    },
                    this.state.tableSelection
                );
            }
        }
    };
 
    private onMouseUp() {
        this.detachMouseEvent();
    }
 
    private onDrop = () => {
        this.detachMouseEvent();
    };
 
    private onKeyDown(editor: IEditor, rawEvent: KeyboardEvent) {
        const key = rawEvent.key;
        const selection = editor.getDOMSelection();
        const win = editor.getDocument().defaultView;
 
        switch (selection?.type) {
            case 'image':
                if (!isModifierKey(rawEvent) && !rawEvent.shiftKey && selection.image.parentNode) {
                    if (key === 'Escape') {
                        this.selectBeforeOrAfterElement(editor, selection.image);
                        rawEvent.stopPropagation();
                    } else Eif (key !== 'Delete' && key !== 'Backspace') {
                        this.selectBeforeOrAfterElement(editor, selection.image);
                    }
                }
 
                if (
                    (isModifierKey(rawEvent) || rawEvent.shiftKey) &&
                    selection.image &&
                    !this.isSafari
                ) {
                    const range = selection.image.ownerDocument.createRange();
                    range.selectNode(selection.image);
                    this.setDOMSelection(
                        {
                            type: 'range',
                            range,
                            isReverted: false,
                        },
                        null /* tableSelection */
                    );
                }
                break;
 
            case 'range':
                if (key == Up || key == Down || key == Left || key == Right || key == Tab) {
                    const start = selection.range.startContainer;
                    this.state.tableSelection = this.parseTableSelection(
                        start,
                        start,
                        editor.getDOMHelper()
                    );
 
                    Eif (this.state.tableSelection && !rawEvent.defaultPrevented) {
                        if (key == Tab) {
                            this.handleSelectionInTable(this.getTabKey(rawEvent));
                            rawEvent.preventDefault();
                        } else {
                            win?.requestAnimationFrame(() => this.handleSelectionInTable(key));
                        }
                    }
                }
                break;
 
            case 'table':
                Eif (this.state.tableSelection?.lastCo) {
                    const { shiftKey, key } = rawEvent;
 
                    if (shiftKey && (key == Left || key == Right)) {
                        const isRtl =
                            win?.getComputedStyle(this.state.tableSelection.table).direction ==
                            'rtl';
 
                        this.updateTableSelectionFromKeyboard(
                            0,
                            (key == Left ? -1 : 1) * (isRtl ? -1 : 1)
                        );
                        rawEvent.preventDefault();
                    } else if (shiftKey && (key == Up || key == Down)) {
                        this.updateTableSelectionFromKeyboard(key == Up ? -1 : 1, 0);
                        rawEvent.preventDefault();
                    } else if (key != 'Shift' && !isCharacterValue(rawEvent)) {
                        Eif (key == Up || key == Down || key == Left || key == Right) {
                            this.setDOMSelection(null /*domSelection*/, this.state.tableSelection);
                            win?.requestAnimationFrame(() => this.handleSelectionInTable(key));
                        }
                    }
                }
                break;
        }
    }
 
    private getTabKey(rawEvent: KeyboardEvent) {
        return rawEvent.shiftKey ? 'TabLeft' : 'TabRight';
    }
 
    private handleSelectionInTable(
        key: 'ArrowUp' | 'ArrowDown' | 'ArrowLeft' | 'ArrowRight' | 'TabLeft' | 'TabRight'
    ) {
        Iif (!this.editor || !this.state.tableSelection) {
            return;
        }
 
        const selection = this.editor.getDOMSelection();
        const domHelper = this.editor.getDOMHelper();
 
        Eif (selection?.type == 'range') {
            const {
                range: { collapsed, startContainer, endContainer, commonAncestorContainer },
                isReverted,
            } = selection;
            const start = isReverted ? endContainer : startContainer;
            const end: Node | null = isReverted ? startContainer : endContainer;
            const tableSel = this.parseTableSelection(commonAncestorContainer, start, domHelper);
 
            if (!tableSel) {
                return;
            }
 
            let lastCo = findCoordinate(tableSel?.parsedTable, end, domHelper);
            let tabMove = false;
            const { parsedTable, firstCo: oldCo, table } = this.state.tableSelection;
 
            Eif (lastCo && tableSel.table == table) {
                if (lastCo.col != oldCo.col && (key == Up || key == Down)) {
                    const change = key == Up ? -1 : 1;
                    const originalTd = findTableCellElement(parsedTable, oldCo)?.cell;
                    let td: HTMLTableCellElement | null = null;
 
                    lastCo = { row: oldCo.row + change, col: oldCo.col };
 
                    while (lastCo.row >= 0 && lastCo.row < parsedTable.length) {
                        td = findTableCellElement(parsedTable, lastCo)?.cell || null;
 
                        Iif (td == originalTd) {
                            lastCo.row += change;
                        } else {
                            break;
                        }
                    }
 
                    if (collapsed && td) {
                        this.setRangeSelectionInTable(
                            td,
                            key == Up ? td.childNodes.length : 0,
                            this.editor
                        );
                    } else if (!td && (lastCo.row == -1 || lastCo.row <= parsedTable.length)) {
                        this.selectBeforeOrAfterElement(
                            this.editor,
                            table,
                            change == 1 /* after */,
                            change != 1 /* setSelectionInNextSiblingElement */
                        );
                    }
                } else if (key == 'TabLeft' || key == 'TabRight') {
                    const reverse = key == 'TabLeft';
                    for (
                        let step = reverse ? -1 : 1,
                            row = lastCo.row ?? 0,
                            col = (lastCo.col ?? 0) + step;
                        ;
                        col += step
                    ) {
                        if (col < 0 || col >= parsedTable[row].length) {
                            row += step;
                            if (row < 0) {
                                this.selectBeforeOrAfterElement(this.editor, tableSel.table);
                                break;
                            } else if (row >= parsedTable.length) {
                                this.selectBeforeOrAfterElement(
                                    this.editor,
                                    tableSel.table,
                                    true /*after*/
                                );
                                break;
                            }
                            col = reverse ? parsedTable[row].length - 1 : 0;
                        }
                        const cell = parsedTable[row][col];
 
                        Eif (typeof cell != 'string') {
                            tabMove = true;
                            this.setRangeSelectionInTable(
                                cell,
                                0,
                                this.editor,
                                true /* selectAll */
                            );
                            lastCo.row = row;
                            lastCo.col = col;
                            break;
                        }
                    }
                } else {
                    this.state.tableSelection = null;
                }
 
                if (
                    collapsed &&
                    (lastCo.col != oldCo.col || lastCo.row != oldCo.row) &&
                    lastCo.row >= 0 &&
                    lastCo.row == parsedTable.length - 1 &&
                    lastCo.col == parsedTable[lastCo.row]?.length - 1
                ) {
                    this.editor?.announce({ defaultStrings: 'announceOnFocusLastCell' });
                }
            }
 
            if (!collapsed && lastCo && !tabMove) {
                this.state.tableSelection = tableSel;
                this.updateTableSelection(lastCo);
            }
        }
    }
 
    private setRangeSelectionInTable(
        cell: Node,
        nodeOffset: number,
        editor: IEditor,
        selectAll?: boolean
    ) {
        const range = editor.getDocument().createRange();
        if (selectAll && cell.firstChild && cell.lastChild) {
            const cellStart = cell.firstChild;
            const cellEnd = cell.lastChild;
            // Get first deepest editable position in the cell
            const posStart = normalizePos(cellStart, 0);
            // Get last deepest editable position in the cell
            const posEnd = normalizePos(cellEnd, cellEnd.childNodes.length);
 
            range.setStart(posStart.node, posStart.offset);
            range.setEnd(posEnd.node, posEnd.offset);
        } else {
            // Get deepest editable position in the cell
            const { node, offset } = normalizePos(cell, nodeOffset);
 
            range.setStart(node, offset);
            range.collapse(true /* toStart */);
        }
 
        this.setDOMSelection(
            {
                type: 'range',
                range,
                isReverted: false,
            },
            null /*tableSelection*/
        );
    }
 
    private updateTableSelectionFromKeyboard(rowChange: number, colChange: number) {
        Eif (this.state.tableSelection?.lastCo && this.editor) {
            const { lastCo, parsedTable } = this.state.tableSelection;
            const row = lastCo.row + rowChange;
            const col = lastCo.col + colChange;
 
            Eif (row >= 0 && row < parsedTable.length && col >= 0 && col < parsedTable[row].length) {
                this.updateTableSelection({ row, col });
            }
        }
    }
 
    private selectBeforeOrAfterElement(
        editor: IEditor,
        element: HTMLElement,
        after?: boolean,
        setSelectionInNextSiblingElement?: boolean
    ) {
        const doc = editor.getDocument();
        const parent = element.parentNode;
        const index = parent && toArray(parent.childNodes).indexOf(element);
        let sibling: Element | undefined | null;
 
        if (parent && index !== null && index >= 0) {
            const range = doc.createRange();
            if (
                setSelectionInNextSiblingElement &&
                (sibling = after ? element.nextElementSibling : element.previousElementSibling) &&
                isNodeOfType(sibling, 'ELEMENT_NODE')
            ) {
                range.selectNodeContents(sibling);
                range.collapse(false /* toStart */);
            } else {
                range.setStart(parent, index + (after ? 1 : 0));
                range.collapse();
            }
 
            this.setDOMSelection(
                {
                    type: 'range',
                    range: range,
                    isReverted: false,
                },
                null /*tableSelection*/
            );
        }
    }
 
    private getClickingImage(event: UIEvent): HTMLImageElement | null {
        const target = event.target as Node;
 
        return isNodeOfType(target, 'ELEMENT_NODE') && isElementOfType(target, 'img')
            ? target
            : null;
    }
 
    // MacOS will not create a mouseUp event if contextMenu event is not prevent defaulted.
    // Make sure we capture image target even if image is wrapped
    private getContainedTargetImage = (
        event: MouseEvent,
        previousSelection: DOMSelection | null
    ): HTMLImageElement | null => {
        Eif (!this.isMac || !previousSelection || previousSelection.type !== 'image') {
            return null;
        }
 
        const target = event.target as Node;
        if (
            isNodeOfType(target, 'ELEMENT_NODE') &&
            isElementOfType(target, 'span') &&
            target.firstChild === previousSelection.image
        ) {
            return previousSelection.image;
        }
        return null;
    };
 
    private onFocus = () => {
        if (!this.state.skipReselectOnFocus && this.state.selection) {
            this.setDOMSelection(this.state.selection, this.state.tableSelection);
        }
 
        Iif (this.state.selection?.type == 'range' && !this.isSafari) {
            // Editor is focused, now we can get live selection. So no need to keep a selection if the selection type is range.
            this.state.selection = null;
        }
 
        if (this.scrollTopCache && this.editor) {
            const sc = this.editor.getScrollContainer();
            sc.scrollTop = this.scrollTopCache;
            this.scrollTopCache = 0;
        }
    };
 
    private onBlur = () => {
        Eif (this.editor) {
            Iif (!this.state.selection) {
                this.state.selection = this.editor.getDOMSelection();
            }
            const sc = this.editor.getScrollContainer();
            this.scrollTopCache = sc.scrollTop;
        }
    };
 
    private onSelectionChange = () => {
        if (this.editor?.hasFocus() && !this.editor.isInShadowEdit()) {
            const newSelection = this.editor.getDOMSelection();
 
            //If am image selection changed to a wider range due a keyboard event, we should update the selection
            const selection = this.editor.getDocument().getSelection();
            if (selection && selection.focusNode) {
                const image = isSingleImageInSelection(selection);
                if (newSelection?.type == 'image' && !image) {
                    const range = selection.getRangeAt(0);
                    this.editor.setDOMSelection({
                        type: 'range',
                        range,
                        isReverted:
                            selection.focusNode != range.endContainer ||
                            selection.focusOffset != range.endOffset,
                    });
                } else if (newSelection?.type !== 'image' && image) {
                    this.editor.setDOMSelection({
                        type: 'image',
                        image,
                    });
                }
            }
 
            // Safari has problem to handle onBlur event. When blur, we cannot get the original selection from editor.
            // So we always save a selection whenever editor has focus. Then after blur, we can still use this cached selection.
            if (newSelection?.type == 'range') {
                Eif (this.isSafari) {
                    this.state.selection = newSelection;
                }
            }
        }
    };
 
    private parseTableSelection(
        tableStart: Node,
        tdStart: Node,
        domHelper: DOMHelper
    ): TableSelectionInfo | null {
        let table: HTMLTableElement | null;
        let parsedTable: ParsedTable | null;
        let firstCo: TableCellCoordinate | null;
 
        if (
            (table = domHelper.findClosestElementAncestor(tableStart, 'table')) &&
            table.isContentEditable &&
            (parsedTable = parseTableCells(table)) &&
            (firstCo = findCoordinate(parsedTable, tdStart, domHelper))
        ) {
            return { table, parsedTable, firstCo, startNode: tdStart };
        } else {
            return null;
        }
    }
 
    private updateTableSelection(lastCo: TableCellCoordinate) {
        Eif (this.state.tableSelection && this.editor) {
            const {
                table,
                firstCo,
                parsedTable,
                startNode,
                lastCo: oldCo,
            } = this.state.tableSelection;
 
            if (oldCo || firstCo.row != lastCo.row || firstCo.col != lastCo.col) {
                this.state.tableSelection.lastCo = lastCo;
 
                this.setDOMSelection(
                    {
                        type: 'table',
                        table,
                        firstRow: firstCo.row,
                        firstColumn: firstCo.col,
                        lastRow: lastCo.row,
                        lastColumn: lastCo.col,
                    },
                    { table, firstCo, lastCo, parsedTable, startNode }
                );
 
                return true;
            }
        }
 
        return false;
    }
 
    private setDOMSelection(
        selection: DOMSelection | null,
        tableSelection: TableSelectionInfo | null
    ) {
        this.editor?.setDOMSelection(selection);
        this.state.tableSelection = tableSelection;
    }
 
    private detachMouseEvent() {
        if (this.state.mouseDisposer) {
            this.state.mouseDisposer();
            this.state.mouseDisposer = undefined;
        }
    }
}
 
/**
 * @internal
 * Create a new instance of SelectionPlugin.
 * @param option The editor option
 */
export function createSelectionPlugin(
    options: EditorOptions
): PluginWithState<SelectionPluginState> {
    return new SelectionPlugin(options);
}