Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
6.5 KB
Raw Blame
"use client";

import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { defaultStorage } from "../platform/storage";
import {
  SHORTCUT_ACTIONS,
  SHORTCUT_ACTION_BY_ID,
  isShortcutAllowedForAction,
  parseLegacyShortcut,
  shortcutChordEquals,
  shortcutFirstStep,
  shortcutMatchesEvent,
  type ShortcutActionId,
  type ShortcutChord,
} from "./definitions";

export type ShortcutOverrides = Partial<Record<ShortcutActionId, ShortcutChord | null>>;

const SHORTCUT_ACTION_IDS = new Set<string>(
  SHORTCUT_ACTIONS.map((action) => action.id),
);

function isRecord(value: unknown): value is Record<string, unknown> {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function sanitizeShortcutChord(value: unknown, depth = 0): ShortcutChord | null | undefined {
  if (value === null) return null;
  if (!isRecord(value) || typeof value.key !== "string" || value.key.length === 0) {
    return undefined;
  }
  const modifiers = value.modifiers;
  if (!isRecord(modifiers)) return undefined;
  const { primary, control, meta, alt, shift } = modifiers;
  if (
    typeof primary !== "boolean" ||
    typeof control !== "boolean" ||
    typeof meta !== "boolean" ||
    typeof alt !== "boolean" ||
    typeof shift !== "boolean"
  ) {
    return undefined;
  }
  const chord: ShortcutChord = {
    key: value.key,
    modifiers: {
      primary,
      control,
      meta,
      alt,
      shift,
    },
  };
  // A sequence has two steps, never more.
  if (value.then !== undefined) {
    const then = depth === 0 ? sanitizeShortcutChord(value.then, 1) : undefined;
    if (!then) return undefined;
    chord.then = then;
  }
  return chord;
}

/** Drop unknown actions and malformed chords instead of letting storage crash matching/UI. */
export function sanitizeShortcutOverrides(value: unknown): ShortcutOverrides {
  if (!isRecord(value)) return {};
  const overrides: ShortcutOverrides = {};
  for (const [actionId, rawShortcut] of Object.entries(value)) {
    if (!SHORTCUT_ACTION_IDS.has(actionId)) continue;
    const shortcut = sanitizeShortcutChord(rawShortcut);
    if (
      shortcut !== undefined &&
      (shortcut === null || isShortcutAllowedForAction(
        actionId as ShortcutActionId,
        shortcut,
      ))
    ) {
      overrides[actionId as ShortcutActionId] = shortcut;
    }
  }
  return overrides;
}

interface ShortcutState {
  overrides: ShortcutOverrides;
  setShortcut: (actionId: ShortcutActionId, shortcut: ShortcutChord | null) => void;
  resetShortcut: (actionId: ShortcutActionId) => void;
  resetAll: () => void;
}

export function migrateShortcutState(
  persisted: unknown,
  version: number,
): { overrides: ShortcutOverrides } {
  if (version >= 2) {
    const current = isRecord(persisted) ? persisted : undefined;
    return { overrides: sanitizeShortcutOverrides(current?.overrides) };
  }
  const previous = isRecord(persisted) && isRecord(persisted.overrides)
    ? persisted.overrides
    : {};
  const overrides: ShortcutOverrides = {};
  for (const [actionId, value] of Object.entries(previous)) {
    if (!SHORTCUT_ACTION_IDS.has(actionId)) continue;
    if (value === null) {
      overrides[actionId as ShortcutActionId] = null;
      continue;
    }
    if (typeof value !== "string") continue;
    const shortcut = parseLegacyShortcut(value);
    // Invalid old data means "use the default", not "disable the action".
    if (shortcut) overrides[actionId as ShortcutActionId] = shortcut;
  }
  return { overrides: sanitizeShortcutOverrides(overrides) };
}

export const useShortcutStore = create<ShortcutState>()(
  persist(
    (set) => ({
      overrides: {},
      setShortcut: (actionId, shortcut) =>
        set((state) => {
          if (shortcut && !isShortcutAllowedForAction(actionId, shortcut)) {
            return state;
          }
          const next = { ...state.overrides };
          if (shortcutChordEquals(shortcut, SHORTCUT_ACTION_BY_ID[actionId].defaultShortcut)) {
            delete next[actionId];
          } else {
            next[actionId] = shortcut;
          }
          return { overrides: next };
        }),
      resetShortcut: (actionId) =>
        set((state) => {
          const next = { ...state.overrides };
          delete next[actionId];
          return { overrides: next };
        }),
      resetAll: () => set({ overrides: {} }),
    }),
    {
      name: "multica_keyboard_shortcuts",
      storage: createJSONStorage(() => defaultStorage),
      partialize: (state) => ({ overrides: state.overrides }),
      version: 2,
      migrate: migrateShortcutState,
      // Zustand only calls `migrate` when versions differ. Sanitize during
      // every hydration as well so corrupt current-version storage is safe.
      merge: (persisted, current) => {
        const stored = isRecord(persisted) ? persisted : undefined;
        return {
          ...current,
          overrides: sanitizeShortcutOverrides(stored?.overrides),
        };
      },
    },
  ),
);

export function resolveShortcut(
  overrides: ShortcutOverrides,
  actionId: ShortcutActionId,
): ShortcutChord | null {
  return Object.prototype.hasOwnProperty.call(overrides, actionId)
    ? overrides[actionId] ?? null
    : SHORTCUT_ACTION_BY_ID[actionId].defaultShortcut;
}

export function useShortcut(actionId: ShortcutActionId): ShortcutChord | null {
  return useShortcutStore((state) => resolveShortcut(state.overrides, actionId));
}

export function getShortcut(actionId: ShortcutActionId): ShortcutChord | null {
  return resolveShortcut(useShortcutStore.getState().overrides, actionId);
}

/**
 * Pass the recorded `event` so bindings stored in an older form that the same
 * keypress would also trigger (an Option chord saved as "©") count as taken.
 * A key that starts another action's sequence is taken too, and so is a
 * sequence whose first key is another action's: either would never fire.
 */
export function findShortcutConflict(
  actionId: ShortcutActionId,
  shortcut: ShortcutChord,
  event?: KeyboardEvent,
): ShortcutActionId | null {
  for (const action of SHORTCUT_ACTIONS) {
    if (action.id === actionId) continue;
    const existing = getShortcut(action.id);
    if (!existing) continue;
    if (
      shortcutChordEquals(existing, shortcut) ||
      (event !== undefined && !shortcut.then && shortcutMatchesEvent(existing, event)) ||
      (!!existing.then !== !!shortcut.then &&
        shortcutChordEquals(shortcutFirstStep(existing), shortcutFirstStep(shortcut)))
    ) {
      return action.id;
    }
  }
  return null;
}