All files / roosterjs-content-model-core/lib/coreApi/setDOMSelection setDOMSelection.ts

98.98% Statements 97/98
85.11% Branches 80/94
100% Functions 7/7
98.95% Lines 94/95

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 2691x 1x 1x 1x 1x 1x 1x                         1x 1x 1x 1x 1x 1x 1x         1x 173x   173x 80x         93x   93x 93x 93x 93x 93x   93x   93x 93x   7x   7x   7x       7x               7x             7x 7x   90x 18x 18x         18x         18x 18x   18x           1x     17x                 17x 17x     17x                         17x   17x     17x           17x             17x   17x   17x 17x             17x   59x   59x 59x     9x 9x     93x     92x 91x         91x                     11x       11x 11x     18x         14x           14x 14x     11x 34x     54x 34x   34x       34x 79x   79x 78x   78x           25x   25x           11x       24x 23x 23x   23x 23x 17x   6x 6x 6x             23x      
import { addRangeToSelection } from './addRangeToSelection';
import { areSameSelections } from '../../corePlugin/cache/areSameSelections';
import { ensureUniqueId } from '../setEditorStyle/ensureUniqueId';
import { findLastedCoInMergedCell } from './findLastedCoInMergedCell';
import { findTableCellElement } from './findTableCellElement';
import { toggleCaret } from './toggleCaret';
import {
    getSafeIdSelector,
    isNodeOfType,
    parseTableCells,
    toArray,
} from 'roosterjs-content-model-dom';
import type {
    ParsedTable,
    SelectionChangedEvent,
    SetDOMSelection,
    TableCellCoordinate,
} from 'roosterjs-content-model-types';
 
const DOM_SELECTION_CSS_KEY = '_DOMSelection';
const HIDE_SELECTION_CSS_KEY = '_DOMSelectionHideSelection';
const IMAGE_ID = 'image';
const TABLE_ID = 'table';
const TRANSPARENT_SELECTION_CSS_RULE = 'background-color: transparent !important;';
const SELECTION_SELECTOR = '*::selection';
const DEFAULT_SELECTION_BORDER_COLOR = '#DB626C';
 
/**
 * @internal
 */
export const setDOMSelection: SetDOMSelection = (core, selection, skipSelectionChangedEvent) => {
    const existingSelection = core.api.getDOMSelection(core);
 
    if (existingSelection && selection && areSameSelections(existingSelection, selection)) {
        return;
    }
 
    // We are applying a new selection, so we don't need to apply cached selection in DOMEventPlugin.
    // Set skipReselectOnFocus to skip this behavior
    const skipReselectOnFocus = core.selection.skipReselectOnFocus;
 
    const doc = core.physicalRoot.ownerDocument;
    const isDarkMode = core.lifecycle.isDarkMode;
    core.selection.skipReselectOnFocus = true;
    core.api.setEditorStyle(core, DOM_SELECTION_CSS_KEY, null /*cssRule*/);
    core.api.setEditorStyle(core, HIDE_SELECTION_CSS_KEY, null /*cssRule*/);
 
    toggleCaret(core, false /* hide */);
 
    try {
        switch (selection?.type) {
            case 'image':
                const image = selection.image;
 
                core.selection.selection = selection;
 
                const imageSelectionColor = isDarkMode
                    ? core.selection.imageSelectionBorderColorDark
                    : core.selection.imageSelectionBorderColor;
 
                core.api.setEditorStyle(
                    core,
                    DOM_SELECTION_CSS_KEY,
                    `outline-style:solid!important; outline-color:${
                        imageSelectionColor || DEFAULT_SELECTION_BORDER_COLOR
                    }!important;`,
                    [getSafeIdSelector(ensureUniqueId(image, IMAGE_ID))]
                );
                core.api.setEditorStyle(
                    core,
                    HIDE_SELECTION_CSS_KEY,
                    TRANSPARENT_SELECTION_CSS_RULE,
                    [SELECTION_SELECTOR]
                );
 
                setRangeSelection(doc, image, false /* collapse */);
                break;
            case 'table':
                const { table, firstColumn, firstRow, lastColumn, lastRow } = selection;
                const parsedTable = parseTableCells(selection.table);
                let firstCell = {
                    row: Math.min(firstRow, lastRow),
                    col: Math.min(firstColumn, lastColumn),
                    cell: <HTMLTableCellElement | null>null,
                };
                let lastCell = {
                    row: Math.max(firstRow, lastRow),
                    col: Math.max(firstColumn, lastColumn),
                };
 
                firstCell = findTableCellElement(parsedTable, firstCell) || firstCell;
                lastCell = findLastedCoInMergedCell(parsedTable, lastCell) || lastCell;
 
                if (
                    isNaN(firstCell.row) ||
                    isNaN(firstCell.col) ||
                    isNaN(lastCell.row) ||
                    isNaN(lastCell.col)
                ) {
                    return;
                }
 
                selection = {
                    type: 'table',
                    table,
                    firstRow: firstCell.row,
                    firstColumn: firstCell.col,
                    lastRow: lastCell.row,
                    lastColumn: lastCell.col,
                };
 
                const tableId = ensureUniqueId(table, TABLE_ID);
                const tableSelector = getSafeIdSelector(tableId);
 
                const tableSelectors =
                    firstCell.row == 0 &&
                    firstCell.col == 0 &&
                    lastCell.row == parsedTable.length - 1 &&
                    lastCell.col == (parsedTable[lastCell.row]?.length ?? 0) - 1
                        ? [tableSelector, `${tableSelector} *`]
                        : handleTableSelected(
                              parsedTable,
                              tableSelector,
                              table,
                              firstCell,
                              lastCell
                          );
 
                core.selection.selection = selection;
 
                const tableSelectionColor = isDarkMode
                    ? core.selection.tableCellSelectionBackgroundColorDark
                    : core.selection.tableCellSelectionBackgroundColor;
                core.api.setEditorStyle(
                    core,
                    DOM_SELECTION_CSS_KEY,
                    `background-color:${tableSelectionColor}!important;`,
                    tableSelectors
                );
                core.api.setEditorStyle(
                    core,
                    HIDE_SELECTION_CSS_KEY,
                    TRANSPARENT_SELECTION_CSS_RULE,
                    [SELECTION_SELECTOR]
                );
 
                toggleCaret(core, true /* hide */);
 
                const nodeToSelect = firstCell.cell?.firstElementChild || firstCell.cell;
 
                Eif (nodeToSelect) {
                    setRangeSelection(
                        doc,
                        (nodeToSelect as HTMLElement) || undefined,
                        true /* collapse */
                    );
                }
 
                break;
            case 'range':
                addRangeToSelection(doc, selection.range, selection.isReverted);
 
                core.selection.selection = core.domHelper.hasFocus() ? null : selection;
                break;
 
            default:
                core.selection.selection = null;
                break;
        }
    } finally {
        core.selection.skipReselectOnFocus = skipReselectOnFocus;
    }
 
    if (!skipSelectionChangedEvent) {
        const eventData: SelectionChangedEvent = {
            eventType: 'selectionChanged',
            newSelection: selection,
        };
 
        core.api.triggerEvent(core, eventData, true /*broadcast*/);
    }
};
 
function handleTableSelected(
    parsedTable: ParsedTable,
    tableSelector: string,
    table: HTMLTableElement,
    firstCell: TableCellCoordinate,
    lastCell: TableCellCoordinate
) {
    const selectors: string[] = [];
 
    // Get whether table has thead, tbody or tfoot, then Set the start and end of each of the table children,
    // so we can build the selector according the element between the table and the row.
    let cont = 0;
    const indexes = toArray(table.childNodes)
        .filter(
            (node): node is HTMLTableSectionElement =>
                ['THEAD', 'TBODY', 'TFOOT'].indexOf(
                    isNodeOfType(node, 'ELEMENT_NODE') ? node.tagName : ''
                ) > -1
        )
        .map(node => {
            const result = {
                el: node.tagName,
                start: cont,
                end: node.childNodes.length + cont,
            };
 
            cont = result.end;
            return result;
        });
 
    parsedTable.forEach((row, rowIndex) => {
        let tdCount = 0;
 
        //Get current TBODY/THEAD/TFOOT
        const midElement = indexes.filter(ind => ind.start <= rowIndex && ind.end > rowIndex)[0];
        const middleElSelector = midElement ? '>' + midElement.el + '>' : '>';
        const currentRow =
            midElement && rowIndex + 1 >= midElement.start
                ? rowIndex + 1 - midElement.start
                : rowIndex + 1;
 
        for (let cellIndex = 0; cellIndex < row.length; cellIndex++) {
            const cell = row[cellIndex];
 
            if (typeof cell == 'object') {
                tdCount++;
 
                if (
                    rowIndex >= firstCell.row &&
                    rowIndex <= lastCell.row &&
                    cellIndex >= firstCell.col &&
                    cellIndex <= lastCell.col
                ) {
                    const selector = `${tableSelector}${middleElSelector} tr:nth-child(${currentRow})>${cell.tagName}:nth-child(${tdCount})`;
 
                    selectors.push(selector, selector + ' *');
                }
            }
        }
    });
 
    return selectors;
}
 
function setRangeSelection(doc: Document, element: HTMLElement | undefined, collapse: boolean) {
    if (element && doc.contains(element)) {
        const range = doc.createRange();
        let isReverted: boolean | undefined = undefined;
 
        range.selectNode(element);
        if (collapse) {
            range.collapse();
        } else {
            const selection = doc.defaultView?.getSelection();
            const range = selection && selection.rangeCount > 0 && selection.getRangeAt(0);
            Iif (selection && range) {
                isReverted =
                    selection.focusNode != range.endContainer ||
                    selection.focusOffset != range.endOffset;
            }
        }
 
        addRangeToSelection(doc, range, isReverted);
    }
}