All files / roosterjs-content-model-plugins/lib/edit keyboardDelete.ts

96.08% Statements 49/51
89.04% Branches 65/73
100% Functions 7/7
95.92% Lines 47/49

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 1581x 1x 1x 1x 1x               1x         1x       1x                           1x     37x   20x 20x   20x 17x   11x           11x 11x         2x             20x       11x   11x 11x         11x     11x 11x                             20x   20x   20x 15x 13x     2x 2x   2x 2x           5x 5x 5x     5x                   5x 3x     2x   2x   1x   1x             1x     1x         4x    
import { deleteAllSegmentBefore } from './deleteSteps/deleteAllSegmentBefore';
import { deleteEmptyQuote } from './deleteSteps/deleteEmptyQuote';
import { deleteList } from './deleteSteps/deleteList';
import { deleteParagraphStyle } from './deleteSteps/deleteParagraphStyle';
import {
    ChangeSource,
    deleteSelection,
    isElementOfType,
    isLinkUndeletable,
    isModifierKey,
    isNodeOfType,
} from 'roosterjs-content-model-dom';
import {
    handleKeyboardEventResult,
    shouldDeleteAllSegmentsBefore,
    shouldDeleteWord,
} from './handleKeyboardEventCommon';
import {
    backwardDeleteWordSelection,
    forwardDeleteWordSelection,
} from './deleteSteps/deleteWordSelection';
import {
    backwardDeleteCollapsedSelection,
    forwardDeleteCollapsedSelection,
} from './deleteSteps/deleteCollapsedSelection';
import type { DOMSelection, DeleteSelectionStep, IEditor } from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Do keyboard event handling for DELETE/BACKSPACE key
 * @param editor The editor object
 * @param rawEvent DOM keyboard event
 * @param handleExpandedSelection Whether to handle expanded selection within a text node by CM
 * @returns True if the event is handled by content model, otherwise false
 */
export function keyboardDelete(
    editor: IEditor,
    rawEvent: KeyboardEvent,
    handleExpandedSelection: boolean = true
) {
    let handled = false;
    const selection = editor.getDOMSelection();
 
    if (shouldDeleteWithContentModel(selection, rawEvent, handleExpandedSelection)) {
        editor.formatContentModel(
            (model, context) => {
                const result = deleteSelection(
                    model,
                    getDeleteSteps(rawEvent, !!editor.getEnvironment().isMac),
                    context
                ).deleteResult;
 
                handled = handleKeyboardEventResult(editor, model, rawEvent, result, context);
                return handled;
            },
            {
                rawEvent,
                changeSource: ChangeSource.Keyboard,
                getChangeData: () => rawEvent.which,
                scrollCaretIntoView: true,
                apiName: rawEvent.key == 'Delete' ? 'handleDeleteKey' : 'handleBackspaceKey',
            }
        );
    }
 
    return handled;
}
 
function getDeleteSteps(rawEvent: KeyboardEvent, isMac: boolean): (DeleteSelectionStep | null)[] {
    const isForward = rawEvent.key == 'Delete';
    const deleteAllSegmentBeforeStep =
        shouldDeleteAllSegmentsBefore(rawEvent) && !isForward ? deleteAllSegmentBefore : null;
    const deleteWordSelection = shouldDeleteWord(rawEvent, isMac)
        ? isForward
            ? forwardDeleteWordSelection
            : backwardDeleteWordSelection
        : null;
    const deleteCollapsedSelection = isForward
        ? forwardDeleteCollapsedSelection
        : backwardDeleteCollapsedSelection;
    const deleteQuote = !isForward ? deleteEmptyQuote : null;
    return [
        deleteAllSegmentBeforeStep,
        deleteWordSelection,
        isForward ? null : deleteList,
        deleteCollapsedSelection,
        deleteQuote,
        deleteParagraphStyle,
    ];
}
 
function shouldDeleteWithContentModel(
    selection: DOMSelection | null,
    rawEvent: KeyboardEvent,
    handleExpandedSelection: boolean
) {
    Iif (!selection) {
        return false; // Nothing to delete
    } else Iif (selection.type != 'range') {
        return true;
    } else if (!selection.range.collapsed) {
        if (handleExpandedSelection) {
            return true; // Selection is not collapsed, need to delete all selections
        }
 
        const range = selection.range;
        const { startContainer, endContainer } = selection.range;
        const isInSameTextNode =
            startContainer === endContainer && isNodeOfType(startContainer, 'TEXT_NODE');
        return !(
            isInSameTextNode &&
            !isModifierKey(rawEvent) &&
            range.endOffset - range.startOffset < (startContainer.nodeValue?.length ?? 0)
        );
    } else {
        const range = selection.range;
        const startContainer = range.startContainer;
        const startOffset = range.startOffset;
 
        // When selection is collapsed and is in middle of text node, no need to use Content Model to delete
        return !(
            isNodeOfType(startContainer, 'TEXT_NODE') &&
            !isModifierKey(rawEvent) &&
            (canDeleteBefore(rawEvent, startContainer, startOffset) ||
                canDeleteAfter(rawEvent, startContainer, startOffset))
        );
    }
}
 
function canDeleteBefore(rawEvent: KeyboardEvent, text: Text, offset: number) {
    if (rawEvent.key != 'Backspace' || offset <= 1) {
        return false;
    }
 
    const length = text.nodeValue?.length ?? 0;
 
    if (offset == length) {
        // At the end of text, need to check if next segment is deletable
        const nextSibling = text.nextSibling;
        const isNextSiblingUndeletable =
            isNodeOfType(nextSibling, 'ELEMENT_NODE') &&
            isElementOfType(nextSibling, 'a') &&
            isLinkUndeletable(nextSibling) &&
            !nextSibling.firstChild;
 
        // If next sibling is undeletable, we cannot let browser handle it since it will remove the anchor
        // So we return false here to let Content Model handle it
        return !isNextSiblingUndeletable;
    } else {
        // In middle of text, we can safely let browser handle deletion
        return true;
    }
}
 
function canDeleteAfter(rawEvent: KeyboardEvent, text: Text, offset: number) {
    return rawEvent.key == 'Delete' && offset < (text.nodeValue?.length ?? 0) - 1;
}