All files on-keyboard-shortcut.ts

0% Statements 0/52
0% Branches 0/1
0% Functions 0/1
0% Lines 0/52

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                                                                                                         
/**
 * Copyright (c) OpenLens Authors. All rights reserved.
 * Licensed under MIT License. See LICENSE in root directory for more information.
 */

function parseKeyDownDescriptor(descriptor: string): (event: KeyboardEvent) => boolean {
  const parts = new Set((
    descriptor
      .split("+")
      .filter(Boolean)
      .map(part => part.toLowerCase())
  ));

  if (parts.size === 0) {
    return () => true;
  }

  const hasShift = parts.delete("shift");
  const hasAlt = parts.delete("alt");

  const rawHasCtrl = parts.delete("ctrl");
  const rawHasControl = parts.delete("control");
  const hasCtrl = rawHasCtrl || rawHasControl;

  const rawHasMeta = parts.delete("meta");
  const rawHasCmd = parts.delete("cmd");
  const hasMeta = rawHasCmd || rawHasMeta; // This means either matches

  const [key, ...rest] = [...parts];

  if (rest.length !== 0) {
    throw new Error("only single key combinations are currently supported");
  }

  return (event) => {
    return event.altKey === hasAlt
      && event.shiftKey === hasShift
      && event.ctrlKey === hasCtrl
      && event.metaKey === hasMeta
      && event.key.toLowerCase() === key.toLowerCase();
  };
}

export function onKeyboardShortcut(descriptor: string, action: () => void): (this: Window, ev: WindowEventMap["keydown"]) => any {
  const isMatchingEvent = parseKeyDownDescriptor(descriptor);

  return (event) => {
    if (isMatchingEvent(event)) {
      action();
    }
  };
}