App.tsx

51.8 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import type { IncomingPairingRequest } from "../shared/sync-types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { ProCelebration } from "./views/ProCelebration";11import { VaultView, type SortOrder } from "./views/Vault";12import { EntryView } from "./views/Entry";13import { AddView } from "./views/Add";14import { PeachMark, PeachWordmark } from "./components/PeachMark";15import { PasskeyApprovalView } from "./views/PasskeyApproval";16import { extractDomain } from "../shared/domain";17import { popupCopy } from "./copy";18import {19  DEFAULT_BINDINGS,20  formatKeybinding,21  getActiveBindings,22  matchKeybinding,23  SHORTCUT_DESCRIPTORS,24  type Keybinding,25  type ShortcutAction,26} from "../shared/shortcuts";27import { generateTOTP } from "../crypto/totp";2829export { sendMessage } from "../shared/bridge";3031const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));32const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));33const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));34const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));35const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));36const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));37const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));3839type View =40  | "lock"41  | "pro-celebration"42  | "entry"43  | "list"44  | "add"45  | "settings"46  | "sync-pairing"47  | "import"48  | "export"49  | "health"50  | "trash"51  | "panic";52type BootState = "loading" | "ready";5354const canarySuppressMap = new Map<string, boolean>();55let shellRingAnimation: Animation | null = null;5657export function isCanarySuppressed(entryId: string): boolean {58  return canarySuppressMap.get(entryId) ?? false;59}6061export function setCanarySuppressed(entryId: string, suppressed: boolean): void {62  canarySuppressMap.set(entryId, suppressed);63}6465export function clearCanarySuppressions(): void {66  canarySuppressMap.clear();67}6869export function triggerRing() {70  const shell = document.getElementById("hd-shell");71  if (!shell) return;7273  shellRingAnimation?.cancel();74  shell.dataset.glowing = "true";75  const animation = shell.animate(76    [77      { offset: 0, boxShadow: "var(--copy-shadow)" },78      {79        offset: 0.3,80        boxShadow:81          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",82      },83      { offset: 1, boxShadow: "var(--copy-shadow)" },84    ],85    {86      duration: 720,87      easing: "cubic-bezier(0.4, 0, 0.2, 1)",88      fill: "none",89    }90  );91  shellRingAnimation = animation;92  const clearGlow = () => {93    if (shellRingAnimation !== animation) return;94    shellRingAnimation = null;95    delete shell.dataset.glowing;96  };97  animation.onfinish = clearGlow;98  animation.oncancel = clearGlow;99}100101102export function triggerPipPulse() {103  const pip = document.querySelector(".peach-status-pip, .pip");104  if (pip) {105    pip.classList.remove("pulse");106    void (pip as HTMLElement).offsetWidth;107    pip.classList.add("pulse");108  }109}110111const ENTRY_TRANSITION_EXIT_MS = 95;112const ENTRY_TRANSITION_SETTLE_MS = 135;113114export default function App() {115  const [bootState, setBootState] = createSignal<BootState>("loading");116  const [view, setView] = createSignal<View>("lock");117  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(118    "enter"119  );120  const [contentTransitioning, setContentTransitioning] = createSignal(false);121  const [hasVault, setHasVault] = createSignal(false);122  const [onboarded, setOnboarded] = createSignal(true);123  const [entries, setEntries] = createSignal<VaultEntry[]>([]);124  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);125  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);126  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");127  const [theme, setTheme] = createSignal<"dark" | "light">("dark");128  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");129  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");130  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);131  const [lockOnClose, setLockOnClose] = createSignal(true);132  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);133  const [breachMonitoring, setBreachMonitoring] = createSignal(true);134  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);135  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);136  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);137  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);138  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);139  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");140  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");141  // Cached Pro status — synchronous for render paths. Background's142  // GET_LICENSE is async, but render-time reads of isPro() must not block.143  // Refreshed at boot, after activate/deactivate, and whenever the popup144  // re-opens onto a stored license that has changed via another window.145  const [proStatus, setProStatus] = createSignal(false);146  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);147  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);148  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");149  const [listSearchSeed, setListSearchSeed] = createSignal("");150  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);151  const [pendingCelebration, setPendingCelebration] = createSignal(false);152  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);153  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);154  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);155  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);156  const [incomingPairTick, setIncomingPairTick] = createSignal(0);157  const incomingPairSecondsLeft = () => {158    void incomingPairTick();159    const req = incomingPair();160    if (!req) return 0;161    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));162  };163  // True while Panic Step 1 has bounced the user out to Export. When Export's164  // onBack fires we return to Panic instead of Settings so the user keeps the165  // destruction context they came from.166  const [returnToPanic, setReturnToPanic] = createSignal(false);167168  let contentPhaseTimer: number | undefined;169170  function applyAccent(name: AccentColorName) {171    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;172    const hex = color.hex;173    document.documentElement.style.setProperty("--peach-accent", hex);174    // Ambient surface variables — derived from the accent so surfaces shift175    // subtly toward the accent hue rather than staying fixed warm-brown.176    document.documentElement.style.setProperty("--peach-glow", hex + "2A");177    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");178    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");179  }180181  createEffect(() => {182    applyAccent(accentColor());183  });184185  createEffect(() => {186    document.documentElement.classList.toggle("light", theme() === "light");187    document.body.classList.toggle("light", theme() === "light");188  });189190  createEffect(() => {191    document.documentElement.setAttribute("data-display-font", displayFont());192  });193194  createEffect(() => {195    document.documentElement.setAttribute("data-text-size", textSize());196  });197198  createEffect(() => {199    if (reduceMotion()) {200      document.documentElement.setAttribute("data-motion", "reduce");201    } else {202      document.documentElement.removeAttribute("data-motion");203    }204  });205206  const selectedIndex = createMemo(() => {207    const currentId = selectedEntry()?.id;208    if (!currentId) return entries().length > 0 ? 0 : -1;209    return entries().findIndex((entry) => entry.id === currentId);210  });211212  async function applyAccentColor(name: AccentColorName) {213    applyAccent(name);214    setAccentColor(name);215    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });216  }217218  async function applyTheme(t: "dark" | "light") {219    setTheme(t);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });221  }222223  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {224    setDisplayFont(f);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });226  }227228  async function applyTextSize(size: "small" | "medium" | "large") {229    setTextSize(size);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });231  }232233  async function applyReduceMotion(enabled: boolean) {234    setReduceMotion(enabled);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });236  }237238  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload239  // small and lets future default updates land for actions the user hasn't240  // touched. Settings sends us the full active map; we filter and store.241  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {242    setShortcutBindings(active);243    const overrides: Record<string, Keybinding> = {};244    for (const action of Object.keys(active) as ShortcutAction[]) {245      const a = active[action];246      const d = DEFAULT_BINDINGS[action];247      const same = a.key === d.key248        && Boolean(a.ctrl)  === Boolean(d.ctrl)249        && Boolean(a.meta)  === Boolean(d.meta)250        && Boolean(a.shift) === Boolean(d.shift)251        && Boolean(a.alt)   === Boolean(d.alt);252      if (!same) overrides[action] = a;253    }254    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });255  }256257  async function applyLockOnClose(enabled: boolean) {258    setLockOnClose(enabled);259    await sendMessage({260      type: "UPDATE_SETTINGS",261      payload: { lockOnClose: enabled },262    });263  }264265  async function applyAutoLockMinutes(minutes: number) {266    setAutoLockMinutes(minutes);267    await sendMessage({268      type: "UPDATE_SETTINGS",269      payload: { autoLockMinutes: minutes },270    });271  }272273  async function applyBreachMonitoring(enabled: boolean) {274    setBreachMonitoring(enabled);275    await sendMessage({276      type: "UPDATE_SETTINGS",277      payload: { breachMonitoring: enabled },278    });279  }280281  onMount(async () => {282    // Resolve the active tab in parallel with the unlock/has-vault queries —283    // openVault()'s smart selection picks the entry matching currentTabDomain,284    // so it must be populated before openVault runs. Previously refreshCurrentTab285    // ran after openVault, leaving popups that booted already-unlocked falling286    // back to loadedEntries[0] instead of the domain match.287    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([288      sendMessage({ type: "IS_UNLOCKED" }),289      sendMessage({ type: "HAS_VAULT" }),290      refreshCurrentTab(),291      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),292    ]);293    const unlocked = Boolean(294      (unlockResponse as { ok: boolean; data?: boolean }).data295    );296    const vaultExists = Boolean(297      (vaultResponse as { ok: boolean; data?: boolean }).data298    );299    const shouldCelebrate = Boolean(300      (celebrationResponse as { ok: boolean; data?: boolean }).data301    );302    setHasVault(vaultExists);303    // Onboarding gate — show once on first install, never again. Existing304    // users (vaultExists) are auto-marked onboarded so they skip the flow305    // even on the very first popup open after this feature ships.306    try {307      const onboarded = await storageGet("peach_onboarded");308      const seen = onboarded === "true";309      if (vaultExists && !seen) {310        await storageSet("peach_onboarded", "true");311        setOnboarded(true);312      } else {313        setOnboarded(seen);314      }315    } catch {316      // storage unavailable — default to onboarded so we never block boot317      setOnboarded(true);318    }319    await Promise.all([restoreSettings(), refreshProStatus()]);320321    // Mark played before any animation so a crash mid-sequence never replays it322    if (shouldCelebrate) {323      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });324    }325326    if (unlocked && vaultExists) {327      await openVault(undefined, shouldCelebrate);328      if (shouldCelebrate) {329        setView("pro-celebration");330        window.setTimeout(() => setView("entry"), 2500);331      }332    } else if (shouldCelebrate) {333      setPendingCelebration(true);334    }335336    await refreshPendingPasskey();337    await refreshIncomingPairing();338    await consumeRecentPairing();339340    // Track tab changes so smart sort stays current341    const handleTabActivated = () => { void refreshCurrentTab(); };342    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {343      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();344    };345    try {346      chrome.tabs.onActivated.addListener(handleTabActivated);347      chrome.tabs.onUpdated.addListener(handleTabUpdated);348      onCleanup(() => {349        chrome.tabs.onActivated.removeListener(handleTabActivated);350        chrome.tabs.onUpdated.removeListener(handleTabUpdated);351      });352    } catch {353      // tabs permission may not be available in all contexts354    }355356    setBootState("ready");357    document.getElementById("pre-lock")?.setAttribute("hidden", "true");358359    // Check for pending session-storage notices from the background.360    if (chrome.storage.session) {361      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as362        Record<string, { feature?: string } | undefined>;363      if (session.pendingProGate?.feature) {364        await chrome.storage.session.remove("pendingProGate");365        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);366        setSettingsInitialSection("license");367        setView("settings");368      } else if (session.pendingProNotice?.feature) {369        await chrome.storage.session.remove("pendingProNotice");370        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });371      }372    }373374    // Warm the lazy-module cache so the Suspense fallback never shows for375    // locally-bundled extension views. Without this, the first navigation to376    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which377    // covers the shell and absorbs clicks on the header.378    void Promise.all([379      import("./views/Settings").catch(() => {}),380      import("./views/Import").catch(() => {}),381      import("./views/Export").catch(() => {}),382      import("./views/Health").catch(() => {}),383      import("./views/TrashView").catch(() => {}),384    ]);385386    // Lock-on-close via a persistent port. sendMessage in pagehide is387    // unreliable — the popup context tears down before the message lands.388    // The SW's onConnect listener locks when this port disconnects.389    let popupPort: chrome.runtime.Port | null = null;390    try {391      popupPort = chrome.runtime.connect({ name: "popup" });392    } catch { /* extension context invalidated — ignore */ }393    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });394395    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale396    // entries instead of waiting for the next GET_ENTRIES round-trip.397    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {398      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();399      if (msg?.type === "PRO_GATE_TRIGGERED") {400        setUpgradeHighlight(msg.payload?.feature ?? null);401        setSettingsInitialSection("license");402        setView("settings");403      }404      if (msg?.type === "INCOMING_PAIRING_REQUEST") {405        void refreshIncomingPairing();406      }407    };408    chrome.runtime.onMessage.addListener(handleRuntimeMessage);409    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));410411    // Action handlers — keyed by ShortcutAction. The dispatcher below tests412    // each binding against the event and runs the matching handler. New413    // shortcuts only need an entry here; the binding is data, not code.414    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {415      copy_password: () => {416        const entry = selectedEntry();417        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });418      },419      copy_username: () => {420        const entry = selectedEntry();421        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });422      },423      copy_totp: () => {424        const entry = selectedEntry();425        if (!entry?.totp) return;426        try {427          const { code } = generateTOTP(entry.totp);428          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });429        } catch { /* invalid TOTP secret — silent */ }430      },431      new_entry: () => handleAdd(),432      edit_entry: () => {433        const entry = selectedEntry();434        // Passkey-only entries have nothing user-editable in the Add view; the435        // passkey credential itself is opaque. Skip the edit action for them.436        if (!entry || isPasskeyOnly(entry)) return;437        setEditEntry(entry);438        setView("add");439      },440      delete_entry: () => {441        if (selectedEntry()) void handleDelete();442      },443      lock_vault: () => { void handleHeaderLock(); },444      search: () => openList(),445      nav_prev: () => navigate(-1),446      nav_next: () => navigate(1),447      jump_vault: () => setView("entry"),448      jump_settings: () => setView("settings"),449      show_help: () => setShowShortcutsHelp(true),450    };451452    // Actions that are MEANINGFUL only on the entry-detail view. Outside453    // that scope the binding is dormant — pressing C while on Settings454    // does nothing rather than awkwardly copying from a now-stale entry.455    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([456      "copy_password", "copy_username", "copy_totp",457      "edit_entry", "delete_entry", "nav_prev", "nav_next",458    ]);459460    const handleGlobalKeydown = (e: KeyboardEvent) => {461      const v = view();462      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"463        || (e.target as HTMLElement)?.tagName === "TEXTAREA"464        || (e.target as HTMLElement)?.isContentEditable;465      const isPrintableSearchKey =466        e.key.length === 1 &&467        !e.ctrlKey &&468        !e.metaKey &&469        !e.altKey;470471      // No input during the pro celebration sequence472      if (v === "pro-celebration") return;473474      // Help dialog: Escape closes it; eat the keypress so it doesn't475      // also navigate away from the underlying view.476      if (showShortcutsHelp()) {477        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }478        return;479      }480481      // ── Escape — fixed binding (not user-customizable) ───────482      if (e.key === "Escape") {483        if (v === "list") { setView("entry"); return; }484        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }485        if (v === "sync-pairing") { setView("settings"); return; }486      }487488      // Bindings-driven dispatch. Single-key letter bindings without489      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is490      // inside an input, so users can type into search/forms normally.491      const bindings = shortcutBindings();492      for (const action of Object.keys(bindings) as ShortcutAction[]) {493        const binding = bindings[action];494        if (!matchKeybinding(e, binding)) continue;495        // Single-key letter bindings need the input-focus guard. Bindings496        // with any modifier are safe — Ctrl+L doesn't conflict with typing.497        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;498        if (!hasMod && binding.key.length === 1 && inInput) return;499        if (ENTRY_SCOPED.has(action) && v !== "entry") return;500        e.preventDefault();501        SHORTCUT_HANDLERS[action]?.();502        return;503      }504505      // Type-to-search: in entry view, any printable key not consumed by a506      // shortcut above primes the list search seed and opens the list.507      // Kept outside the bindings table because it's a behavior, not a508      // discrete action — every printable character can trigger it.509      if (v === "entry" && !inInput && isPrintableSearchKey) {510        e.preventDefault();511        primeListSearch(e.key);512        return;513      }514    };515    window.addEventListener("keydown", handleGlobalKeydown);516    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));517518    const handleStorageChanged = (519      changes: Record<string, chrome.storage.StorageChange>,520      areaName: string521    ) => {522      if (areaName !== "session") return;523      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {524        return;525      }526      void refreshPendingPasskey();527    };528    chrome.storage.onChanged.addListener(handleStorageChanged);529    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));530  });531532  async function refreshCurrentTab() {533    try {534      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });535      const url = tab?.url ?? tab?.pendingUrl ?? "";536      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");537      // Skip extension/internal URLs — adding chrome://, about:, or538      // chrome-extension:// to a vault entry is never what the user wants.539      const isWebUrl = /^https?:\/\//i.test(url);540      setCurrentTabUrl(isWebUrl ? url : "");541    } catch {542      setCurrentTabDomain("");543      setCurrentTabUrl("");544    }545  }546547  async function refreshPendingPasskey() {548    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });549    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);550  }551552  async function refreshIncomingPairing() {553    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });554    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;555    setIncomingPair(data);556  }557558  // Drains a single one-shot record left by the background when 6-digit559  // pairing succeeded while the popup was closed (or the SyncPairing view was560  // navigated away from before it could show its own success card).561  async function consumeRecentPairing() {562    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });563    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;564    if (data?.deviceName) {565      setRecentPairToast(data.deviceName);566      window.setTimeout(() => setRecentPairToast(null), 4000);567    }568  }569570  async function respondIncomingPairing(accept: boolean) {571    if (incomingPairResponding()) return;572    setIncomingPairResponding(true);573    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });574    setIncomingPair(null);575    setIncomingPairResponding(false);576  }577578  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a579  // request appears, ticks once per second, and clears the banner if the580  // request expires while the popup is open.581  createEffect(() => {582    const req = incomingPair();583    if (!req) return;584    const handle = window.setInterval(() => {585      setIncomingPairTick((tick) => tick + 1);586      if (Date.now() >= req.expiresAt) {587        setIncomingPair(null);588        window.clearInterval(handle);589      }590    }, 1000);591    onCleanup(() => window.clearInterval(handle));592  });593594  async function refreshProStatus() {595    const res = await sendMessage({ type: "GET_LICENSE" });596    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;597    setProStatus(Boolean(data?.valid && data?.plan === "pro"));598  }599600  async function restoreSettings() {601    const res = await sendMessage({ type: "GET_SETTINGS" });602    const s = (res as { ok: boolean; data?: any }).data ?? {};603    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {604      setAccentColor(s.accentColor as AccentColorName);605    }606    setTheme(s.theme === "light" ? "light" : "dark");607    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {608      setDisplayFont(s.displayFont);609    } else {610      setDisplayFont("cormorant-italic");611    }612    if (s.textSize === "small" || s.textSize === "large") {613      setTextSize(s.textSize);614    } else {615      setTextSize("medium");616    }617    setReduceMotion(s.reduceMotion === true);618    setLockOnClose(s.lockOnClose !== false);619    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);620    setBreachMonitoring(s.breachMonitoring !== false);621    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);622    setShortcutBindings(getActiveBindings(s.shortcuts));623  }624625  async function applyTrashRetention(days: number) {626    setTrashRetentionDays(days);627    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });628  }629630  function primeListSearch(seed: string) {631    setListSearchSeed(seed);632    setListSearchSeedNonce((value) => value + 1);633    openList();634  }635636  // Returns null when it detected a dead service worker and triggered handleLock().637  // Callers that need to abort (e.g. openVault) check for null rather than relying638  // on view() state, which may already be "lock" during normal startup flows.639  async function loadEntries(): Promise<VaultEntry[] | null> {640    const response = await sendMessage({ type: "GET_ENTRIES" });641    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };642643    // If the service worker was killed and restarted (MV3 workers sleep), the644    // vault will be locked again — or the worker may not respond at all.645    // In either case, send the user to the lock screen rather than silently646    // showing an empty vault (which looks like data loss).647    if (!res.ok) {648      if (649        res.error === "vault locked" ||650        res.error === "SERVICE_WORKER_UNAVAILABLE" ||651        (typeof res.error === "string" && res.error.includes("locked"))652      ) {653        handleLock();654        return null; // signal emergency lock to callers655      }656      return [];657    }658659    const loadedEntries = res.data ?? [];660    setEntries(loadedEntries);661662    const currentId = selectedEntry()?.id;663    if (currentId) {664      setSelectedEntry(665        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null666      );667    }668669    return loadedEntries;670  }671672  async function openVault(preferredEntryId?: string, skipViewSet = false) {673    // Purge expired trash entries on each vault open674    const retDays = trashRetentionDays();675    if (retDays > 0) {676      void sendMessage({677        type: "PURGE_EXPIRED_TRASH",678        payload: { retentionMs: retDays * 86_400_000 },679      });680    }681682    const loadedEntries = await loadEntries();683684    // null means loadEntries() triggered an emergency lock (service worker died).685    // Don't override it by setting view back to "entry" with an empty vault.686    if (loadedEntries === null) return;687688    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry689    let nextSelectedEntry: VaultEntry | null = null;690    if (preferredEntryId) {691      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;692    }693    if (!nextSelectedEntry) {694      const tabDomain = currentTabDomain();695      if (tabDomain) {696        nextSelectedEntry = loadedEntries.find((e) => {697          if (e.type === "login") {698            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;699            for (const extra of e.additionalUrls ?? []) {700              if ((extractDomain(extra) ?? "") === tabDomain) return true;701            }702            return false;703          }704          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;705          return false;706        }) ?? null;707      }708    }709    nextSelectedEntry ??= loadedEntries[0] ?? null;710711    setSelectedEntry(nextSelectedEntry);712    setEditEntry(undefined);713    setContentTransitioning(false);714    setContentPhase("enter");715    queueContentIdle();716    if (!skipViewSet) setView("entry");717  }718719  async function handleUnlock() {720    setHasVault(true);721    triggerPipPulse();722    await restoreSettings();723    const celebrating = pendingCelebration();724    if (celebrating) {725      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });726      setPendingCelebration(false);727    }728    await openVault(undefined, celebrating);729    if (celebrating) {730      setView("pro-celebration");731      window.setTimeout(() => setView("entry"), 2500);732    }733  }734735  function handleSelectEntry(entry: VaultEntry) {736    setSelectedEntry(entry);737    setContentTransitioning(false);738    setContentPhase("enter");739    queueContentIdle();740    setView("entry");741  }742743  function handleAdd() {744    setEditEntry(undefined);745    setView("add");746  }747748  async function handleDelete() {749    const entry = selectedEntry();750    if (!entry) return;751    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });752    const loadedEntries = await loadEntries() ?? [];753    setSelectedEntry(loadedEntries[0] ?? null);754    setView("entry");755  }756757  async function handleDeleteMany(ids: string[]) {758    for (const id of ids) {759      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });760    }761    const loadedEntries = await loadEntries() ?? [];762    // If the currently selected entry was among the deleted, move to first763    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);764    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);765  }766767  async function handleSave(savedEntry?: VaultEntry) {768    await openVault(savedEntry?.id);769  }770771  function handleBack() {772    setEditEntry(undefined);773    setView("entry");774  }775776  function handleLock() {777    clearCanarySuppressions();778    setEntries([]);779    setSelectedEntry(null);780    setEditEntry(undefined);781    setContentPhase("idle");782    setView("lock");783  }784785  function handleHeaderLock() {786    // Lock the UI immediately — do not wait for the service worker. If the SW787    // is dead or slow, the 5s sendMessage timeout would create a dead-click788    // window. The SW will lock on its next wake regardless.789    handleLock();790    void sendMessage({ type: "LOCK" });791  }792793  function navigate(dir: number) {794    const allEntries = entries();795    if (allEntries.length === 0) return;796    const currentIndex = selectedIndex();797    const baseIndex = currentIndex >= 0 ? currentIndex : 0;798    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;799    setSelectedEntry(allEntries[nextIndex]);800    setContentPhase("enter");801    queueContentIdle();802  }803804  function openList() {805    setView("list");806  }807808  function openHealth() {809    setEditEntry(undefined);810    setView("health");811  }812813  function handleOpenFileImport() {814    setRestoreView("file");815  }816817  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;818819  function handleFixEntry(entry: VaultEntry) {820    // Passkey-only entries have no editable surface — drop into view mode821    // instead of opening the Add editor.822    if (isPasskeyOnly(entry)) {823      setSelectedEntry(entry);824      setView("entry");825      return;826    }827    setEditEntry(entry);828    setView("add");829  }830831  const isLockedView = () => view() === "lock";832833  async function handleApprovePendingPasskey() {834    const pending = pendingPasskey();835    if (!pending) return;836    if (pending.browser === "firefox" && pending.type === "create") {837      // Firefox path: popup itself runs navigator.credentials.create. The838      // background never approved/rejected anything — it just stashed839      // intent. After the popup-driven flow resolves (success or cancel),840      // clear the pending key so the popup doesn't re-show this on next open.841      const { createFirefoxPasskey } = await import("./firefox-passkey");842      const result = await createFirefoxPasskey(pending);843      if (!result.ok) {844        console.warn("Peach Firefox passkey create failed:", result.error);845      }846      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });847      setPendingPasskey(null);848      void loadEntries();849      return;850    }851    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });852    setPendingPasskey(null);853  }854855  async function handleDenyPendingPasskey() {856    const pending = pendingPasskey();857    if (!pending) return;858    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });859    setPendingPasskey(null);860  }861862  function queueContentIdle(after?: () => void) {863    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);864    contentPhaseTimer = window.setTimeout(() => {865      setContentPhase("idle");866      after?.();867    }, ENTRY_TRANSITION_SETTLE_MS);868  }869870  return (871    <div class="popup-root peach-theme">872      <Show when={bootState() === "ready"}>873        <Show874          when={!pendingPasskey()}875          fallback={876            <PasskeyApprovalView877              type={pendingPasskey()!.type}878              rpName={pendingPasskey()!.rpName}879              rpId={pendingPasskey()!.rpId}880              userName={pendingPasskey()!.userName}881              userDisplayName={pendingPasskey()!.userDisplayName}882              onApprove={handleApprovePendingPasskey}883              onDeny={handleDenyPendingPasskey}884            />885          }886        >887          <Show888            when={!isLockedView()}889            fallback={890              <Show891                when={onboarded() || hasVault()}892                fallback={893                  <Onboarding894                    onComplete={() => { setOnboarded(true); }}895                  />896                }897              >898                <LockView899                  hasVault={hasVault()}900                  ready={bootState() === "ready"}901                  isPro={proStatus()}902                  onUnlock={handleUnlock}903                  onBackToOnboarding={904                    !hasVault()905                      ? () => setOnboarded(false)906                      : undefined907                  }908                />909              </Show>910            }911          >912            <Show913              when={view() !== "pro-celebration"}914              fallback={<ProCelebration />}915            >916            <section917              id="hd-shell"918              class="peach-shell peach-theme"919              data-surface="extension"920            >921            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>922              <PeachWordmark unlocked />923              <div class="peach-chrome-actions">924                <button925                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"926                  onClick={() => setView("settings")}927                  aria-label="Settings"928                >929                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">930                    <path931                      d="M5.91 1.11C6.38-.02 7.62-.02 8.09 1.11L8.31 1.64C8.48 2.05 8.91 2.27 9.34 2.17L9.9 2.04C11.1 1.76 11.98 2.64 11.7 3.84L11.57 4.4C11.47 4.83 11.69 5.26 12.1 5.43L12.63 5.65C13.76 6.12 13.76 7.36 12.63 7.83L12.1 8.05C11.69 8.22 11.47 8.65 11.57 9.08L11.7 9.64C11.98 10.84 11.1 11.72 9.9 11.44L9.34 11.31C8.91 11.21 8.48 11.43 8.31 11.84L8.09 12.37C7.62 13.5 6.38 13.5 5.91 12.37L5.69 11.84C5.52 11.43 5.09 11.21 4.66 11.31L4.1 11.44C2.9 11.72 2.02 10.84 2.3 9.64L2.43 9.08C2.53 8.65 2.31 8.22 1.9 8.05L1.37 7.83C.24 7.36.24 6.12 1.37 5.65L1.9 5.43C2.31 5.26 2.53 4.83 2.43 4.4L2.3 3.84C2.02 2.64 2.9 1.76 4.1 2.04L4.66 2.17C5.09 2.27 5.52 2.05 5.69 1.64L5.91 1.11Z"932                      stroke="currentColor"933                      stroke-width="0.9"934                    />935                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />936                  </svg>937                </button>938                <button939                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"940                  onClick={handleAdd}941                  aria-label="New entry"942                >943                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">944                    <path d="M5.5 1v9M1 5.5h9" />945                  </svg>946                </button>947                <button948                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"949                  onClick={() => void handleHeaderLock()}950                  aria-label="Lock vault"951                >952                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">953                    <path954                      d="M3.75 6V4.75C3.75 2.96 5.21 1.5 7 1.5C8.79 1.5 10.25 2.96 10.25 4.75V6"955                      stroke="currentColor"956                      stroke-width="1"957                      stroke-linecap="round"958                    />959                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />960                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />961                  </svg>962                </button>963              </div>964            </header>965966            <Show when={recentPairToast()}>967              <div class="peach-pair-toast" role="status" aria-live="polite">968                Paired with <strong>{recentPairToast()}</strong>969              </div>970            </Show>971972            <Show when={incomingPair() !== null}>973              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">974                <div class="peach-pair-request-header">975                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>976                  <span class="peach-pair-request-title">Pairing request</span>977                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>978                </div>979                <p class="peach-pair-request-body">980                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.981                </p>982                <div class="peach-pair-request-actions">983                  <button984                    class="peach-btn peach-btn--ghost peach-btn--sm"985                    onClick={() => void respondIncomingPairing(false)}986                    disabled={incomingPairResponding()}987                  >988                    Reject989                  </button>990                  <button991                    class="peach-btn peach-btn--accent peach-btn--sm"992                    onClick={() => void respondIncomingPairing(true)}993                    disabled={incomingPairResponding()}994                  >995                    Accept996                  </button>997                </div>998              </div>999            </Show>10001001            <Show when={pendingProNotice() !== null}>1002              <div class="peach-pro-notice-banner">1003                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1004                <button1005                  class="peach-pro-notice-link"1006                  onClick={() => {1007                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1008                    setSettingsInitialSection("license");1009                    setView("settings");1010                    setPendingProNotice(null);1011                  }}1012                >1013                  Learn more →1014                </button>1015                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1016              </div>1017            </Show>10181019            <div class="peach-shell-body">1020              <div class="peach-shell-veil"></div>1021              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1022                <EntryView1023                  entry={selectedEntry()}1024                  currentTabUrl={currentTabUrl()}1025                  onDelete={handleDelete}1026                  onFieldSaved={() => void loadEntries()}1027                  onEscape={() => { setView("list"); }}1028                />1029              </div>10301031              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1032                <div class="peach-search-bar">1033                  <span class="peach-search-icon">1034                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1035                      <circle cx="5.5" cy="5.5" r="3.75" />1036                      <path d="M8.75 8.75L11.5 11.5" />1037                    </svg>1038                  </span>1039                  <input1040                    class="peach-search-input"1041                    placeholder="search vault..."1042                    autocomplete="off"1043                    aria-label="Search vault entries"1044                    onClick={openList}1045                    onFocus={openList}1046                    readOnly1047                  />1048                  <div class="peach-search-meta">1049                    <span class="peach-search-counter">1050                      {entries().length > 01051                        ? `${selectedIndex() + 1} / ${entries().length}`1052                        : "0 entries"}1053                    </span>1054                    <span class="peach-divider"></span>1055                    <button1056                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1057                      onClick={() => navigate(-1)}1058                      aria-label="Previous entry"1059                      disabled={entries().length === 0}1060                    >1061                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1062                        <path d="M5 1L1 5.5L5 10" />1063                      </svg>1064                    </button>1065                    <button1066                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1067                      onClick={() => navigate(1)}1068                      aria-label="Next entry"1069                      disabled={entries().length === 0}1070                    >1071                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1072                        <path d="M1 1L5 5.5L1 10" />1073                      </svg>1074                    </button>1075                  </div>1076                </div>1077              </section>1078            </div>10791080            <Show when={view() === "list"}>1081              <VaultView1082                entries={entries()}1083                selectedEntryId={selectedEntry()?.id}1084                currentTabDomain={currentTabDomain()}1085                sortOrder={sortOrder()}1086                searchSeed={listSearchSeed()}1087                searchSeedNonce={listSearchSeedNonce()}1088                onSelectEntry={handleSelectEntry}1089                onSortOrderChange={setSortOrder}1090                onAdd={handleAdd}1091                onClose={() => setView("entry")}1092                onOpenTrash={() => setView("trash")}1093                onDeleteMany={handleDeleteMany}1094              />1095            </Show>1096            <Show when={view() === "settings"}>1097              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1098                <SettingsView1099                  entriesCount={entries().length}1100                  breachMonitoring={breachMonitoring()}1101                  lockOnClose={lockOnClose()}1102                  autoLockMinutes={autoLockMinutes()}1103                  trashRetentionDays={trashRetentionDays()}1104                  theme={theme()}1105                  accentColor={accentColor()}1106                  displayFont={displayFont()}1107                  textSize={textSize()}1108                  reduceMotion={reduceMotion()}1109                  isPro={proStatus()}1110                  initialSection={settingsInitialSection()}1111                  upgradeHighlight={upgradeHighlight()}1112                  onBreachMonitoringChange={applyBreachMonitoring}1113                  onLockOnCloseChange={applyLockOnClose}1114                  onAutoLockMinutesChange={applyAutoLockMinutes}1115                  onTrashRetentionChange={applyTrashRetention}1116                  onThemeChange={applyTheme}1117                  onAccentChange={applyAccentColor}1118                  onDisplayFontChange={applyDisplayFont}1119                  onTextSizeChange={applyTextSize}1120                  onReduceMotionChange={applyReduceMotion}1121                  shortcuts={shortcutBindings()}1122                  onShortcutsChange={applyShortcuts}1123                  onLicenseChange={async () => {1124                    // After activation/deactivation: refresh Pro status,1125                    // re-load entries (defensive — signal state can drift if1126                    // the SW briefly restarts during the verify+save round-trip),1127                    // and replay the Pro celebration if this is the first time1128                    // a valid Pro license is seen on this device.1129                    await refreshProStatus();1130                    void loadEntries();1131                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1132                    if ((should as { ok: boolean; data?: boolean }).data === true) {1133                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1134                      setView("pro-celebration");1135                      window.setTimeout(() => setView("settings"), 2500);1136                    }1137                  }}1138                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1139                  onImport={() => setView("import")}1140                  onExport={() => setView("export")}1141                  onBreachCheckDone={loadEntries}1142                  onOpenHealth={openHealth}1143                  onOpenSyncPairing={() => setView("sync-pairing")}1144                  onOpenFileImport={handleOpenFileImport}1145                  onOpenPanic={() => setView("panic")}1146                />1147              </Suspense>1148            </Show>1149            <Show when={view() === "sync-pairing"}>1150              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1151                <SyncPairingView1152                  onClose={() => setView("settings")}1153                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1154                />1155              </Suspense>1156            </Show>1157            <Show when={view() === "add"}>1158              <AddView1159                entry={editEntry()}1160                entries={entries()}1161                onBack={handleBack}1162                onSave={handleSave}1163              />1164            </Show>1165            <Show when={view() === "import"}>1166              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1167                <ImportView onBack={handleBack} onImport={handleSave} />1168              </Suspense>1169            </Show>1170            <Show when={view() === "export"}>1171              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1172                <ExportView1173                  onBack={() => {1174                    if (returnToPanic()) {1175                      setReturnToPanic(false);1176                      setView("panic");1177                    } else {1178                      handleBack();1179                    }1180                  }}1181                />1182              </Suspense>1183            </Show>1184            <Show when={view() === "panic"}>1185              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1186                <PanicView1187                  onCancel={() => setView("settings")}1188                  onOpenExport={() => {1189                    setReturnToPanic(true);1190                    setView("export");1191                  }}1192                  onDestroyed={async () => {1193                    clearCanarySuppressions();1194                    setEntries([]);1195                    setSelectedEntry(null);1196                    setEditEntry(undefined);1197                    setHasVault(false);1198                    setOnboarded(false);1199                    setProStatus(false);1200                    setPendingPasskey(null);1201                    setUpgradeHighlight(null);1202                    setSettingsInitialSection(null);1203                    setPendingProNotice(null);1204                    setPendingCelebration(false);1205                    setReturnToPanic(false);1206                    setContentPhase("idle");1207                    setView("lock");1208                  }}1209                />1210              </Suspense>1211            </Show>1212            <Show when={view() === "health"}>1213              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1214                <HealthView1215                  entries={entries()}1216                  isPro={proStatus()}1217                  onFixEntry={handleFixEntry}1218                  onBack={() => setView("settings")}1219                  onRefresh={loadEntries}1220                />1221              </Suspense>1222            </Show>1223            <Show when={view() === "trash"}>1224              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1225                <TrashView1226                  onBack={() => setView("list")}1227                  onRestored={() => void loadEntries()}1228                />1229              </Suspense>1230            </Show>1231            <Show when={restoreView() === "file"}>1232              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1233                <ImportView1234                  mode="onboarding"1235                  replacesExistingVault={true}1236                  onBack={() => setRestoreView(null)}1237                  onImport={async () => {1238                    setRestoreView(null);1239                    await handleUnlock();1240                  }}1241                />1242              </Suspense>1243            </Show>1244            </section>1245            </Show>1246          </Show>1247        </Show>1248      </Show>1249      <Show when={showShortcutsHelp()}>1250        <ShortcutsHelpOverlay1251          bindings={shortcutBindings()}1252          onClose={() => setShowShortcutsHelp(false)}1253        />1254      </Show>1255    </div>1256  );1257}12581259function ShortcutsHelpOverlay(props: {1260  bindings: Record<ShortcutAction, Keybinding>;1261  onClose: () => void;1262}) {1263  return (1264    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1265      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1266        <div class="peach-shortcuts-help-head">1267          <h3>Keyboard shortcuts</h3>1268          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1269        </div>1270        <div class="peach-shortcuts-help-body">1271          <p class="peach-settings-sub-label">ENTRY VIEW</p>1272          <ul>1273            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1274              <li>1275                <span>{d.label}</span>1276                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1277              </li>1278            ))}1279          </ul>1280          <p class="peach-settings-sub-label">ANYWHERE</p>1281          <ul>1282            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1283              <li>1284                <span>{d.label}</span>1285                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1286              </li>1287            ))}1288          </ul>1289        </div>1290      </div>1291    </div>1292  );1293}