Skip to content
Myr

keys.tsx

This file

Path

apps/web/src/features/shared/keys.tsx

537 lines · 12.8 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1/**2 * The switch turns every key but `?` off (WCAG 2.2 SC 2.1.4), and is on3 * whenever the storage cannot be read.4 */5import { Effect, Option, Result } from "effect";6import {7  createContext,8  useCallback,9  useContext,10  useEffect,11  useId,12  useMemo,13  useRef,14  useState,15} from "react";16import type { ReactNode } from "react";1718import { Kbd } from "../../components/ui/kbd.tsx";19import { browserStorage } from "./storage.ts";2021export interface KeyPress {22  readonly altKey: boolean;23  readonly ctrlKey: boolean;24  readonly inField: boolean;25  readonly key: string;26  readonly metaKey: boolean;27}2829export type KeyIntent =30  | { readonly index: number; readonly kind: "copy" }31  | {32      readonly kind:33        | "clear"34        | "keys"35        | "next"36        | "nextFile"37        | "previous"38        | "previousFile";39    };4041const MOVES = {42  J: "nextFile",43  K: "previousFile",44  j: "next",45  k: "previous",46} as const satisfies Record<string, KeyIntent["kind"]>;4748const DIGIT = /^[1-9]$/u;4950export const intentOf = (51  press: KeyPress,52  on: boolean53): KeyIntent | undefined => {54  if (press.inField || press.altKey || press.ctrlKey || press.metaKey) {55    return undefined;56  }5758  if (press.key === "?") {59    return { kind: "keys" };60  }6162  if (press.key === "Escape") {63    return { kind: "clear" };64  }6566  if (!on) {67    return undefined;68  }6970  if (DIGIT.test(press.key)) {71    return { index: Number(press.key), kind: "copy" };72  }7374  const move = Object.entries(MOVES).find(([key]) => key === press.key);7576  return move === undefined ? undefined : { kind: move[1] };77};7879const SWITCH = "keys.single";8081export const readShortcuts = (storage?: Storage): boolean =>82  storage === undefined ||83  Result.getOrElse(84    Result.try(() => storage.getItem(SWITCH) !== "off"),85    () => true86  );8788export const writeShortcuts = (storage: Storage | undefined, on: boolean) => {89  Result.try(() => storage?.setItem(SWITCH, on ? "on" : "off"));90};9192const KEYS = [93  { does: "Show these keys", keys: ["?"] },94  { does: "Next or previous row", keys: ["j", "k"] },95  { does: "Open the focused row", keys: ["Enter"] },96  { does: "Next or previous file", keys: ["J", "K"] },97  { does: "Go to file, in the Code tab", keys: ["t"] },98  { does: "Copy the page's numbered command", keys: ["1", "…", "9"] },99  { does: "Close, or clear the selection", keys: ["Esc"] },100] as const;101102const SETTINGS = [103  { label: "On", on: true },104  { label: "Off", on: false },105] as const;106107export const KeysHelp = ({108  on,109  onChange,110}: {111  readonly on: boolean;112  readonly onChange: (on: boolean) => void;113}) => (114  <div className="flex flex-col gap-5">115    <dl className="text-ui grid grid-cols-[auto_1fr] gap-x-4 gap-y-2.5">116      {KEYS.map(({ does, keys }) => (117        <div className="contents" key={does}>118          <dt className="flex items-center gap-1">119            {keys.map((key) =>120              key === "…" ? (121                <span className="text-muted-foreground" key={key}>122                  to123                </span>124              ) : (125                <Kbd key={key}>{key}</Kbd>126              )127            )}128          </dt>129          <dd>{does}</dd>130        </div>131      ))}132    </dl>133    <fieldset className="border-rule flex flex-wrap items-center justify-between gap-3 border-t pt-4">134      <legend className="text-ui float-left font-medium">135        Single-key shortcuts136      </legend>137      <div className="border-input flex border">138        {SETTINGS.map(({ label, on: setting }) => (139          <button140            aria-pressed={on === setting}141            className="text-ui aria-pressed:bg-foreground aria-pressed:text-background hover:bg-surface aria-pressed:hover:bg-foreground h-8 cursor-pointer px-3 font-medium transition-colors duration-150"142            key={label}143            onClick={() => {144              onChange(setting);145            }}146            type="button"147          >148            {label}149          </button>150        ))}151      </div>152    </fieldset>153    <p className="text-muted-foreground text-label">154      Off, only ? acts. No key acts while you type in a field.155    </p>156  </div>157);158159export type CommandSlot = "facts" | "main";160161const SlotContext = createContext<CommandSlot>("main");162163export const CommandSlotProvider = ({164  children,165  slot,166}: {167  readonly children: ReactNode;168  readonly slot: CommandSlot;169}) => <SlotContext value={slot}>{children}</SlotContext>;170171interface ListRegistration {172  readonly focus: (id: string) => void;173  readonly read: () => {174    readonly ids: readonly string[];175  };176  focused?: string;177}178179interface FileRegistration {180  readonly read: () => {181    readonly onMove: (path: string) => void;182    readonly paths: readonly string[];183  };184  at?: string;185}186187interface Command {188  readonly command: string;189  readonly id: string;190  readonly slot: CommandSlot;191}192193interface Registry {194  readonly clearers: Set<() => void>;195  readonly files: Set<FileRegistration>;196  readonly lists: Set<ListRegistration>;197  readonly register: (command: Command) => () => void;198}199200interface KeysState {201  readonly copied: string | undefined;202  readonly numbered: ReadonlyMap<string, number>;203  readonly on: boolean;204  readonly setOn: (on: boolean) => void;205}206207const RegistryContext = createContext<Registry | undefined>(undefined);208209const StateContext = createContext<KeysState | undefined>(undefined);210211export const useKeys = () => useContext(StateContext);212213const held = <A,>(set: Set<A>, item: A) => {214  set.add(item);215216  return () => {217    set.delete(item);218  };219};220221/** The page's own, over any that left late. */222const lastOf = <A,>(set: ReadonlySet<A>): A | undefined => [...set].at(-1);223224export const inField = (event: KeyboardEvent) => {225  const [target] = event.composedPath();226227  return (228    target instanceof HTMLElement &&229    (target.isContentEditable ||230      target.closest(231        "input, textarea, select, [role=combobox], [role=searchbox], [role=textbox], [data-keys-off]"232      ) !== null)233  );234};235236const numberOf = (237  commands: readonly Command[]238): ReadonlyMap<string, number> => {239  const ordered = [240    ...commands.filter(({ slot }) => slot === "facts"),241    ...commands.filter(({ slot }) => slot === "main"),242  ];243244  const unique = [...new Set(ordered.map(({ command }) => command))];245246  return new Map(247    unique.slice(0, 9).map((command, index) => [command, index + 1])248  );249};250251const copyNumbered = (command: string, shown: (copied?: string) => void) =>252  Effect.tryPromise(() => navigator.clipboard.writeText(command)).pipe(253    Effect.andThen(254      Effect.sync(() => {255        shown(command);256      })257    ),258    Effect.andThen(Effect.sleep("2 seconds")),259    Effect.andThen(260      Effect.sync(() => {261        shown();262      })263    ),264    Effect.ignore265  );266267const moveTo = (list: ListRegistration, step: 1 | -1) => {268  const { ids } = list.read();269  const at = list.focused === undefined ? -1 : ids.indexOf(list.focused);270271  const next =272    ids[273      Math.min(274        Math.max(at === -1 && step === -1 ? 0 : at + step, 0),275        ids.length - 1276      )277    ];278279  if (next === undefined) {280    return;281  }282283  list.focused = next;284  list.focus(next);285286  const row = document.querySelector(`[data-list-key="${CSS.escape(next)}"]`);287288  if (row instanceof HTMLElement) {289    row.focus({ preventScroll: true });290    row.scrollIntoView({ block: "nearest" });291  }292};293294const moveFile = (files: FileRegistration, step: 1 | -1) => {295  const { onMove, paths } = files.read();296  const at = files.at === undefined ? -1 : paths.indexOf(files.at);297  const next = paths[Math.min(Math.max(at + step, 0), paths.length - 1)];298299  if (next !== undefined) {300    files.at = next;301    onMove(next);302  }303};304305interface Pressing {306  readonly copy: (command: string) => void;307  readonly numbered: ReadonlyMap<string, number>;308  readonly on: boolean;309  readonly openDialog: () => void;310  readonly registry: Registry;311}312313const act = (intent: KeyIntent, now: Pressing): boolean => {314  const { registry } = now;315316  if (intent.kind === "keys") {317    now.openDialog();318319    return true;320  }321322  if (intent.kind === "clear") {323    // An open sheet or dialog closes itself on Escape.324    if (document.querySelector('[role="dialog"]') === null) {325      lastOf(registry.clearers)?.();326    }327328    return false;329  }330331  if (intent.kind === "copy") {332    const command = [...now.numbered].find(333      ([, index]) => index === intent.index334    )?.[0];335336    if (command !== undefined) {337      now.copy(command);338    }339340    return command !== undefined;341  }342343  if (intent.kind === "next" || intent.kind === "previous") {344    const list = lastOf(registry.lists);345346    if (list !== undefined) {347      moveTo(list, intent.kind === "next" ? 1 : -1);348    }349350    return list !== undefined;351  }352353  const files = lastOf(registry.files);354355  if (files !== undefined) {356    moveFile(files, intent.kind === "nextFile" ? 1 : -1);357  }358359  return files !== undefined;360};361362export const KeysProvider = ({363  children,364  openDialog,365}: {366  readonly children: ReactNode;367  readonly openDialog: () => void;368}) => {369  // The server has no storage and renders the keys on; nothing it renders370  // depends on them.371  const [on, setOn] = useState(() => readShortcuts(browserStorage()));372  const [commands, setCommands] = useState<readonly Command[]>([]);373  const [copied, setCopied] = useState<string>();374375  const registry = useMemo<Registry>(376    () => ({377      clearers: new Set(),378      files: new Set(),379      lists: new Set(),380      register: (command) => {381        setCommands((now) => [...now, command]);382383        return () => {384          setCommands((now) => now.filter(({ id }) => id !== command.id));385        };386      },387    }),388    []389  );390391  const turn = useCallback((next: boolean) => {392    setOn(next);393    writeShortcuts(browserStorage(), next);394  }, []);395396  const numbered = useMemo(() => numberOf(commands), [commands]);397398  const pressing = useRef<Pressing | null>(null);399400  useEffect(() => {401    pressing.current = {402      copy: (command) => {403        Effect.runFork(copyNumbered(command, setCopied));404      },405      numbered,406      on,407      openDialog,408      registry,409    };410  });411412  useEffect(() => {413    const onKey = (event: KeyboardEvent) => {414      const now = pressing.current;415416      if (now === null || event.defaultPrevented || event.repeat) {417        return;418      }419420      const intent = intentOf(421        {422          altKey: event.altKey,423          ctrlKey: event.ctrlKey,424          inField: inField(event),425          key: event.key,426          metaKey: event.metaKey,427        },428        now.on429      );430431      if (intent !== undefined && act(intent, now)) {432        event.preventDefault();433      }434    };435436    document.addEventListener("keydown", onKey);437438    return () => {439      document.removeEventListener("keydown", onKey);440    };441  }, []);442443  const state = useMemo(444    () => ({ copied, numbered, on, setOn: turn }),445    [copied, numbered, on, turn]446  );447448  return (449    <RegistryContext value={registry}>450      <StateContext value={state}>451        {children}452        <output aria-live="polite" className="sr-only">453          {copied === undefined ? "" : `Copied: ${copied}`}454        </output>455      </StateContext>456    </RegistryContext>457  );458};459460const useLatest = <A,>(value: A) => {461  const latest = useRef(value);462463  useEffect(() => {464    latest.current = value;465  });466467  return latest;468};469470export const useListKeys = (471  ids: readonly string[]472): { readonly focused?: string } => {473  const registry = useContext(RegistryContext);474  const [focused, setFocused] = useState<string>();475  const latest = useLatest({ ids });476477  useEffect(478    () =>479      registry === undefined480        ? undefined481        : held(registry.lists, {482            focus: setFocused,483            read: () => latest.current,484          }),485    [latest, registry]486  );487488  return focused === undefined ? {} : { focused };489};490491export const useFileKeys = (492  paths: readonly string[],493  onMove: (path: string) => void494): void => {495  const registry = useContext(RegistryContext);496  const latest = useLatest({ onMove, paths });497498  useEffect(499    () =>500      registry === undefined501        ? undefined502        : held(registry.files, { read: () => latest.current }),503    [latest, registry]504  );505};506507export const useNumberedCommand = (command: string): number | undefined => {508  const registry = useContext(RegistryContext);509  const state = useContext(StateContext);510  const slot = useContext(SlotContext);511  const id = useId();512513  useEffect(514    () => registry?.register({ command, id, slot }),515    [command, id, registry, slot]516  );517518  return state?.on === true ? state.numbered.get(command) : undefined;519};520521export const useCopiedCommand = (): Option.Option<string> =>522  Option.fromUndefinedOr(useContext(StateContext)?.copied);523524export const useEscapeClears = (clear: () => void): void => {525  const registry = useContext(RegistryContext);526  const latest = useLatest(clear);527528  useEffect(529    () =>530      registry === undefined531        ? undefined532        : held(registry.clearers, () => {533            latest.current();534          }),535    [latest, registry]536  );537};