All files / roosterjs-content-model-core/lib/corePlugin/cache areSameSelections.ts

100% Statements 22/22
100% Branches 18/18
100% Functions 6/6
100% Lines 21/21

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                        1x       179x 43x     136x   3x     11x       122x 115x   115x 154x   77x             38x     7x           168x     1x             1x         1x 9x           1x 113x           115x    
import type {
    CacheSelection,
    DOMSelection,
    RangeSelection,
    RangeSelectionForCache,
    TableSelection,
} from 'roosterjs-content-model-types';
 
/**
 * @internal
 * Check if the given selections are the same
 */
export function areSameSelections(
    sel1: DOMSelection,
    sel2: DOMSelection | CacheSelection
): boolean {
    if (sel1 == sel2) {
        return true;
    }
 
    switch (sel1.type) {
        case 'image':
            return sel2.type == 'image' && sel2.image == sel1.image;
 
        case 'table':
            return sel2.type == 'table' && areSameTableSelections(sel1, sel2);
 
        case 'range':
        default:
            if (sel2.type == 'range') {
                const range1 = sel1.range;
 
                if (isCacheSelection(sel2)) {
                    const { start, end } = sel2;
 
                    return (
                        range1.startContainer == start.node &&
                        range1.endContainer == end.node &&
                        range1.startOffset == start.offset &&
                        range1.endOffset == end.offset
                    );
                } else {
                    return areSameRanges(range1, sel2.range);
                }
            } else {
                return false;
            }
    }
}
 
function areSame<O>(o1: O, o2: O, keys: (keyof O)[]) {
    return keys.every(k => o1[k] == o2[k]);
}
 
const TableSelectionKeys: (keyof TableSelection)[] = [
    'table',
    'firstColumn',
    'lastColumn',
    'firstRow',
    'lastRow',
];
const RangeKeys: (keyof Range)[] = ['startContainer', 'endContainer', 'startOffset', 'endOffset'];
 
/**
 * @internal
 */
export function areSameTableSelections(t1: TableSelection, t2: TableSelection): boolean {
    return areSame(t1, t2, TableSelectionKeys);
}
 
/**
 * @internal
 */
export function areSameRanges(r1: Range, r2: Range): boolean {
    return areSame(r1, r2, RangeKeys);
}
 
function isCacheSelection(
    sel: RangeSelectionForCache | RangeSelection
): sel is RangeSelectionForCache {
    return !!(sel as RangeSelectionForCache).start;
}