File size: 1,248 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { cn } from "@reactive-resume/utils";
import { useEffect } from "react";
import { useBoolean } from "usehooks-ts";

// Keyboard Icons
// Shift ⇧
// Control ⌃
// Option ⌥
// Command ⌘

type KeyboardShortcutProps = Omit<React.HTMLAttributes<HTMLSpanElement>, "defaultValue"> & {
  defaultValue?: boolean;
};

export const KeyboardShortcut = ({
  className,
  defaultValue = false,
  ...props
}: KeyboardShortcutProps) => {
  const { value, setValue } = useBoolean(defaultValue);

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      e.key === "Control" && setValue(true);
    };

    const onKeyUp = (e: KeyboardEvent) => {
      e.key === "Control" && setValue(false);
    };

    document.addEventListener("keydown", onKeyDown);
    document.addEventListener("keyup", onKeyUp);

    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.removeEventListener("keyup", onKeyUp);
    };
  }, [setValue]);

  return (
    <span
      className={cn(
        "ml-auto text-xs tracking-widest transition-opacity",
        value ? "scale-100 opacity-60" : "scale-0 opacity-0",
        className,
      )}
      {...props}
    />
  );
};

KeyboardShortcut.displayName = "KeyboardShortcut";