All files / json-crdt-peritext-ui/dom util.ts

23.8% Statements 5/21
13.33% Branches 2/15
0% Functions 0/5
20% Lines 3/15

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    1x                     1x                 1x                    
export type GetCursorPosition = (x: number, y: number) => null | [node: Node, offset: number];
 
export const getCursorPosition: GetCursorPosition =
  typeof document !== 'undefined' && (<any>document).caretPositionFromPoint
    ? (x, y) => {
        const range = (<any>document).caretPositionFromPoint(x, y);
        return range ? [range.offsetNode, range.offset] : null;
      }
    : (x, y) => {
        const range = document.caretRangeFromPoint(x, y);
        return range ? [range.startContainer, range.startOffset] : null;
      };
 
export const unit = (event: KeyboardEvent): '' | 'word' | 'line' =>
  event.metaKey ? 'line' : event.altKey || event.ctrlKey ? 'word' : '';
 
/**
 * Save the current browser selection, so that it can be restored later. Returns
 * a callback to restore the selection.
 *
 * @returns Callback to restore the selection.
 */
export const saveSelection = (): (() => void) | undefined => {
  const selection = window?.getSelection();
  Iif (!selection) return;
  const ranges: Range[] = [];
  for (let i = 0; i < selection.rangeCount; i++) ranges.push(selection.getRangeAt(i));
  return () => {
    selection.removeAllRanges();
    for (const range of ranges) selection.addRange(range);
  };
};