App.tsx

53.6 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);167  // Set on popup boot when peach_recovery_pending flag is found in session168  // storage — instructs LockView to skip the unlock UI and open the recovery169  // words confirmation surface instead. Cleared via handleUnlock once the170  // user has typed the 3 confirmation words.171  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);172173  let contentPhaseTimer: number | undefined;174175  function applyAccent(name: AccentColorName) {176    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;177    const hex = color.hex;178    document.documentElement.style.setProperty("--peach-accent", hex);179    // Ambient surface variables — derived from the accent so surfaces shift180    // subtly toward the accent hue rather than staying fixed warm-brown.181    document.documentElement.style.setProperty("--peach-glow", hex + "2A");182    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");183    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");184  }185186  createEffect(() => {187    applyAccent(accentColor());188  });189190  createEffect(() => {191    document.documentElement.classList.toggle("light", theme() === "light");192    document.body.classList.toggle("light", theme() === "light");193  });194195  createEffect(() => {196    document.documentElement.setAttribute("data-display-font", displayFont());197  });198199  createEffect(() => {200    document.documentElement.setAttribute("data-text-size", textSize());201  });202203  createEffect(() => {204    if (reduceMotion()) {205      document.documentElement.setAttribute("data-motion", "reduce");206    } else {207      document.documentElement.removeAttribute("data-motion");208    }209  });210211  const selectedIndex = createMemo(() => {212    const currentId = selectedEntry()?.id;213    if (!currentId) return entries().length > 0 ? 0 : -1;214    return entries().findIndex((entry) => entry.id === currentId);215  });216217  async function applyAccentColor(name: AccentColorName) {218    applyAccent(name);219    setAccentColor(name);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });221  }222223  async function applyTheme(t: "dark" | "light") {224    setTheme(t);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });226  }227228  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {229    setDisplayFont(f);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });231  }232233  async function applyTextSize(size: "small" | "medium" | "large") {234    setTextSize(size);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });236  }237238  async function applyReduceMotion(enabled: boolean) {239    setReduceMotion(enabled);240    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });241  }242243  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload244  // small and lets future default updates land for actions the user hasn't245  // touched. Settings sends us the full active map; we filter and store.246  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {247    setShortcutBindings(active);248    const overrides: Record<string, Keybinding> = {};249    for (const action of Object.keys(active) as ShortcutAction[]) {250      const a = active[action];251      const d = DEFAULT_BINDINGS[action];252      const same = a.key === d.key253        && Boolean(a.ctrl)  === Boolean(d.ctrl)254        && Boolean(a.meta)  === Boolean(d.meta)255        && Boolean(a.shift) === Boolean(d.shift)256        && Boolean(a.alt)   === Boolean(d.alt);257      if (!same) overrides[action] = a;258    }259    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });260  }261262  async function applyLockOnClose(enabled: boolean) {263    setLockOnClose(enabled);264    await sendMessage({265      type: "UPDATE_SETTINGS",266      payload: { lockOnClose: enabled },267    });268  }269270  async function applyAutoLockMinutes(minutes: number) {271    setAutoLockMinutes(minutes);272    await sendMessage({273      type: "UPDATE_SETTINGS",274      payload: { autoLockMinutes: minutes },275    });276  }277278  async function applyBreachMonitoring(enabled: boolean) {279    setBreachMonitoring(enabled);280    await sendMessage({281      type: "UPDATE_SETTINGS",282      payload: { breachMonitoring: enabled },283    });284  }285286  onMount(async () => {287    // Resolve the active tab in parallel with the unlock/has-vault queries —288    // openVault()'s smart selection picks the entry matching currentTabDomain,289    // so it must be populated before openVault runs. Previously refreshCurrentTab290    // ran after openVault, leaving popups that booted already-unlocked falling291    // back to loadedEntries[0] instead of the domain match.292    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([293      sendMessage({ type: "IS_UNLOCKED" }),294      sendMessage({ type: "HAS_VAULT" }),295      refreshCurrentTab(),296      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),297    ]);298    const unlocked = Boolean(299      (unlockResponse as { ok: boolean; data?: boolean }).data300    );301    const vaultExists = Boolean(302      (vaultResponse as { ok: boolean; data?: boolean }).data303    );304    const shouldCelebrate = Boolean(305      (celebrationResponse as { ok: boolean; data?: boolean }).data306    );307    setHasVault(vaultExists);308    // Onboarding gate — show once on first install, never again. Existing309    // users (vaultExists) are auto-marked onboarded so they skip the flow310    // even on the very first popup open after this feature ships.311    try {312      const onboarded = await storageGet("peach_onboarded");313      const seen = onboarded === "true";314      if (vaultExists && !seen) {315        await storageSet("peach_onboarded", "true");316        setOnboarded(true);317      } else {318        setOnboarded(seen);319      }320    } catch {321      // storage unavailable — default to onboarded so we never block boot322      setOnboarded(true);323    }324    await Promise.all([restoreSettings(), refreshProStatus()]);325326    // Mark played before any animation so a crash mid-sequence never replays it327    if (shouldCelebrate) {328      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });329    }330331    // If the user created a vault but hasn't yet confirmed their recovery332    // words, route back to the recovery-words screen instead of opening the333    // entries view. The SW suppresses lock-on-close while this flag is set334    // so the in-memory key needed to re-derive the words survives the popup335    // close → reopen round-trip. Cleared when confirmation succeeds.336    let recoveryPending = false;337    try {338      const out = await chrome.storage.session?.get("peach_recovery_pending");339      recoveryPending = out?.peach_recovery_pending === "1";340    } catch { /* best-effort */ }341342    if (recoveryPending && unlocked) {343      // LockView's <Match when={showRecoveryWords() && !props.hasVault}>344      // gates on hasVault being false. We pass hasVault=false to the lock345      // view so the recovery match fires; the actual vault state in346      // background is untouched.347      setHasVault(false);348      // Pass a hint so LockView force-shows the recovery display on mount.349      setForceRecoveryWords(true);350    } else if (unlocked && vaultExists) {351      await openVault(undefined, shouldCelebrate);352      if (shouldCelebrate) {353        setView("pro-celebration");354        window.setTimeout(() => setView("entry"), 2500);355      }356    } else if (shouldCelebrate) {357      setPendingCelebration(true);358    }359360    await refreshPendingPasskey();361    await refreshIncomingPairing();362    await consumeRecentPairing();363364    // Track tab changes so smart sort stays current365    const handleTabActivated = () => { void refreshCurrentTab(); };366    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {367      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();368    };369    try {370      chrome.tabs.onActivated.addListener(handleTabActivated);371      chrome.tabs.onUpdated.addListener(handleTabUpdated);372      onCleanup(() => {373        chrome.tabs.onActivated.removeListener(handleTabActivated);374        chrome.tabs.onUpdated.removeListener(handleTabUpdated);375      });376    } catch {377      // tabs permission may not be available in all contexts378    }379380    setBootState("ready");381    document.getElementById("pre-lock")?.setAttribute("hidden", "true");382383    // Check for pending session-storage notices from the background.384    if (chrome.storage.session) {385      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as386        Record<string, { feature?: string } | undefined>;387      if (session.pendingProGate?.feature) {388        await chrome.storage.session.remove("pendingProGate");389        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);390        setSettingsInitialSection("license");391        setView("settings");392      } else if (session.pendingProNotice?.feature) {393        await chrome.storage.session.remove("pendingProNotice");394        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });395      }396    }397398    // Warm the lazy-module cache so the Suspense fallback never shows for399    // locally-bundled extension views. Without this, the first navigation to400    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which401    // covers the shell and absorbs clicks on the header.402    void Promise.all([403      import("./views/Settings").catch(() => {}),404      import("./views/Import").catch(() => {}),405      import("./views/Export").catch(() => {}),406      import("./views/Health").catch(() => {}),407      import("./views/TrashView").catch(() => {}),408    ]);409410    // Lock-on-close via a persistent port. sendMessage in pagehide is411    // unreliable — the popup context tears down before the message lands.412    // The SW's onConnect listener locks when this port disconnects.413    let popupPort: chrome.runtime.Port | null = null;414    try {415      popupPort = chrome.runtime.connect({ name: "popup" });416    } catch { /* extension context invalidated — ignore */ }417    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });418419    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale420    // entries instead of waiting for the next GET_ENTRIES round-trip.421    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {422      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();423      if (msg?.type === "PRO_GATE_TRIGGERED") {424        setUpgradeHighlight(msg.payload?.feature ?? null);425        setSettingsInitialSection("license");426        setView("settings");427      }428      if (msg?.type === "INCOMING_PAIRING_REQUEST") {429        void refreshIncomingPairing();430      }431    };432    chrome.runtime.onMessage.addListener(handleRuntimeMessage);433    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));434435    // Action handlers — keyed by ShortcutAction. The dispatcher below tests436    // each binding against the event and runs the matching handler. New437    // shortcuts only need an entry here; the binding is data, not code.438    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {439      copy_password: () => {440        const entry = selectedEntry();441        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });442      },443      copy_username: () => {444        const entry = selectedEntry();445        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });446      },447      copy_totp: () => {448        const entry = selectedEntry();449        if (!entry?.totp) return;450        try {451          const { code } = generateTOTP(entry.totp);452          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });453        } catch { /* invalid TOTP secret — silent */ }454      },455      new_entry: () => handleAdd(),456      edit_entry: () => {457        const entry = selectedEntry();458        // Passkey-only entries have nothing user-editable in the Add view; the459        // passkey credential itself is opaque. Skip the edit action for them.460        if (!entry || isPasskeyOnly(entry)) return;461        setEditEntry(entry);462        setView("add");463      },464      delete_entry: () => {465        if (selectedEntry()) void handleDelete();466      },467      lock_vault: () => { void handleHeaderLock(); },468      search: () => openList(),469      nav_prev: () => navigate(-1),470      nav_next: () => navigate(1),471      jump_vault: () => setView("entry"),472      jump_settings: () => setView("settings"),473      show_help: () => setShowShortcutsHelp(true),474    };475476    // Actions that are MEANINGFUL only on the entry-detail view. Outside477    // that scope the binding is dormant — pressing C while on Settings478    // does nothing rather than awkwardly copying from a now-stale entry.479    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([480      "copy_password", "copy_username", "copy_totp",481      "edit_entry", "delete_entry", "nav_prev", "nav_next",482    ]);483484    const handleGlobalKeydown = (e: KeyboardEvent) => {485      const v = view();486      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"487        || (e.target as HTMLElement)?.tagName === "TEXTAREA"488        || (e.target as HTMLElement)?.isContentEditable;489      const isPrintableSearchKey =490        e.key.length === 1 &&491        !e.ctrlKey &&492        !e.metaKey &&493        !e.altKey;494495      // No input during the pro celebration sequence496      if (v === "pro-celebration") return;497498      // Help dialog: Escape closes it; eat the keypress so it doesn't499      // also navigate away from the underlying view.500      if (showShortcutsHelp()) {501        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }502        return;503      }504505      // ── Escape — fixed binding (not user-customizable) ───────506      if (e.key === "Escape") {507        if (v === "list") { setView("entry"); return; }508        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }509        if (v === "sync-pairing") { setView("settings"); return; }510      }511512      // Bindings-driven dispatch. Single-key letter bindings without513      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is514      // inside an input, so users can type into search/forms normally.515      const bindings = shortcutBindings();516      for (const action of Object.keys(bindings) as ShortcutAction[]) {517        const binding = bindings[action];518        if (!matchKeybinding(e, binding)) continue;519        // Single-key letter bindings need the input-focus guard. Bindings520        // with any modifier are safe — Ctrl+L doesn't conflict with typing.521        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;522        if (!hasMod && binding.key.length === 1 && inInput) return;523        if (ENTRY_SCOPED.has(action) && v !== "entry") return;524        e.preventDefault();525        SHORTCUT_HANDLERS[action]?.();526        return;527      }528529      // Type-to-search: in entry view, any printable key not consumed by a530      // shortcut above primes the list search seed and opens the list.531      // Kept outside the bindings table because it's a behavior, not a532      // discrete action — every printable character can trigger it.533      if (v === "entry" && !inInput && isPrintableSearchKey) {534        e.preventDefault();535        primeListSearch(e.key);536        return;537      }538    };539    window.addEventListener("keydown", handleGlobalKeydown);540    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));541542    const handleStorageChanged = (543      changes: Record<string, chrome.storage.StorageChange>,544      areaName: string545    ) => {546      if (areaName !== "session") return;547      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {548        return;549      }550      void refreshPendingPasskey();551    };552    chrome.storage.onChanged.addListener(handleStorageChanged);553    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));554  });555556  async function refreshCurrentTab() {557    try {558      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });559      const url = tab?.url ?? tab?.pendingUrl ?? "";560      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");561      // Skip extension/internal URLs — adding chrome://, about:, or562      // chrome-extension:// to a vault entry is never what the user wants.563      const isWebUrl = /^https?:\/\//i.test(url);564      setCurrentTabUrl(isWebUrl ? url : "");565    } catch {566      setCurrentTabDomain("");567      setCurrentTabUrl("");568    }569  }570571  async function refreshPendingPasskey() {572    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });573    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);574  }575576  async function refreshIncomingPairing() {577    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });578    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;579    setIncomingPair(data);580  }581582  // Drains a single one-shot record left by the background when 6-digit583  // pairing succeeded while the popup was closed (or the SyncPairing view was584  // navigated away from before it could show its own success card).585  async function consumeRecentPairing() {586    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });587    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;588    if (data?.deviceName) {589      setRecentPairToast(data.deviceName);590      window.setTimeout(() => setRecentPairToast(null), 4000);591    }592  }593594  async function respondIncomingPairing(accept: boolean) {595    if (incomingPairResponding()) return;596    setIncomingPairResponding(true);597    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });598    setIncomingPair(null);599    setIncomingPairResponding(false);600  }601602  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a603  // request appears, ticks once per second, and clears the banner if the604  // request expires while the popup is open.605  createEffect(() => {606    const req = incomingPair();607    if (!req) return;608    const handle = window.setInterval(() => {609      setIncomingPairTick((tick) => tick + 1);610      if (Date.now() >= req.expiresAt) {611        setIncomingPair(null);612        window.clearInterval(handle);613      }614    }, 1000);615    onCleanup(() => window.clearInterval(handle));616  });617618  async function refreshProStatus() {619    const res = await sendMessage({ type: "GET_LICENSE" });620    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;621    setProStatus(Boolean(data?.valid && data?.plan === "pro"));622  }623624  async function restoreSettings() {625    const res = await sendMessage({ type: "GET_SETTINGS" });626    const s = (res as { ok: boolean; data?: any }).data ?? {};627    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {628      setAccentColor(s.accentColor as AccentColorName);629    }630    setTheme(s.theme === "light" ? "light" : "dark");631    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {632      setDisplayFont(s.displayFont);633    } else {634      setDisplayFont("cormorant-italic");635    }636    if (s.textSize === "small" || s.textSize === "large") {637      setTextSize(s.textSize);638    } else {639      setTextSize("medium");640    }641    setReduceMotion(s.reduceMotion === true);642    setLockOnClose(s.lockOnClose !== false);643    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);644    setBreachMonitoring(s.breachMonitoring !== false);645    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);646    setShortcutBindings(getActiveBindings(s.shortcuts));647  }648649  async function applyTrashRetention(days: number) {650    setTrashRetentionDays(days);651    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });652  }653654  function primeListSearch(seed: string) {655    setListSearchSeed(seed);656    setListSearchSeedNonce((value) => value + 1);657    openList();658  }659660  // Returns null when it detected a dead service worker and triggered handleLock().661  // Callers that need to abort (e.g. openVault) check for null rather than relying662  // on view() state, which may already be "lock" during normal startup flows.663  async function loadEntries(): Promise<VaultEntry[] | null> {664    const response = await sendMessage({ type: "GET_ENTRIES" });665    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };666667    // If the service worker was killed and restarted (MV3 workers sleep), the668    // vault will be locked again — or the worker may not respond at all.669    // In either case, send the user to the lock screen rather than silently670    // showing an empty vault (which looks like data loss).671    if (!res.ok) {672      if (673        res.error === "vault locked" ||674        res.error === "SERVICE_WORKER_UNAVAILABLE" ||675        (typeof res.error === "string" && res.error.includes("locked"))676      ) {677        handleLock();678        return null; // signal emergency lock to callers679      }680      return [];681    }682683    const loadedEntries = res.data ?? [];684    setEntries(loadedEntries);685686    const currentId = selectedEntry()?.id;687    if (currentId) {688      setSelectedEntry(689        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null690      );691    }692693    return loadedEntries;694  }695696  async function openVault(preferredEntryId?: string, skipViewSet = false) {697    // Purge expired trash entries on each vault open698    const retDays = trashRetentionDays();699    if (retDays > 0) {700      void sendMessage({701        type: "PURGE_EXPIRED_TRASH",702        payload: { retentionMs: retDays * 86_400_000 },703      });704    }705706    const loadedEntries = await loadEntries();707708    // null means loadEntries() triggered an emergency lock (service worker died).709    // Don't override it by setting view back to "entry" with an empty vault.710    if (loadedEntries === null) return;711712    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry713    let nextSelectedEntry: VaultEntry | null = null;714    if (preferredEntryId) {715      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;716    }717    if (!nextSelectedEntry) {718      const tabDomain = currentTabDomain();719      if (tabDomain) {720        nextSelectedEntry = loadedEntries.find((e) => {721          if (e.type === "login") {722            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;723            for (const extra of e.additionalUrls ?? []) {724              if ((extractDomain(extra) ?? "") === tabDomain) return true;725            }726            return false;727          }728          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;729          return false;730        }) ?? null;731      }732    }733    nextSelectedEntry ??= loadedEntries[0] ?? null;734735    setSelectedEntry(nextSelectedEntry);736    setEditEntry(undefined);737    setContentTransitioning(false);738    setContentPhase("enter");739    queueContentIdle();740    if (!skipViewSet) setView("entry");741  }742743  async function handleUnlock() {744    setHasVault(true);745    triggerPipPulse();746    await restoreSettings();747    const celebrating = pendingCelebration();748    if (celebrating) {749      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });750      setPendingCelebration(false);751    }752    await openVault(undefined, celebrating);753    if (celebrating) {754      setView("pro-celebration");755      window.setTimeout(() => setView("entry"), 2500);756    }757  }758759  function handleSelectEntry(entry: VaultEntry) {760    setSelectedEntry(entry);761    setContentTransitioning(false);762    setContentPhase("enter");763    queueContentIdle();764    setView("entry");765  }766767  function handleAdd() {768    setEditEntry(undefined);769    setView("add");770  }771772  async function handleDelete() {773    const entry = selectedEntry();774    if (!entry) return;775    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });776    const loadedEntries = await loadEntries() ?? [];777    setSelectedEntry(loadedEntries[0] ?? null);778    setView("entry");779  }780781  async function handleDeleteMany(ids: string[]) {782    for (const id of ids) {783      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });784    }785    const loadedEntries = await loadEntries() ?? [];786    // If the currently selected entry was among the deleted, move to first787    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);788    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);789  }790791  async function handleSave(savedEntry?: VaultEntry) {792    await openVault(savedEntry?.id);793  }794795  function handleBack() {796    setEditEntry(undefined);797    setView("entry");798  }799800  function handleLock() {801    clearCanarySuppressions();802    setEntries([]);803    setSelectedEntry(null);804    setEditEntry(undefined);805    setContentPhase("idle");806    setView("lock");807  }808809  function handleHeaderLock() {810    // Lock the UI immediately — do not wait for the service worker. If the SW811    // is dead or slow, the 5s sendMessage timeout would create a dead-click812    // window. The SW will lock on its next wake regardless.813    handleLock();814    void sendMessage({ type: "LOCK" });815  }816817  function navigate(dir: number) {818    const allEntries = entries();819    if (allEntries.length === 0) return;820    const currentIndex = selectedIndex();821    const baseIndex = currentIndex >= 0 ? currentIndex : 0;822    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;823    setSelectedEntry(allEntries[nextIndex]);824    setContentPhase("enter");825    queueContentIdle();826  }827828  function openList() {829    setView("list");830  }831832  function openHealth() {833    setEditEntry(undefined);834    setView("health");835  }836837  function handleOpenFileImport() {838    setRestoreView("file");839  }840841  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;842843  function handleFixEntry(entry: VaultEntry) {844    // Passkey-only entries have no editable surface — drop into view mode845    // instead of opening the Add editor.846    if (isPasskeyOnly(entry)) {847      setSelectedEntry(entry);848      setView("entry");849      return;850    }851    setEditEntry(entry);852    setView("add");853  }854855  const isLockedView = () => view() === "lock";856857  async function handleApprovePendingPasskey() {858    const pending = pendingPasskey();859    if (!pending) return;860    if (pending.browser === "firefox" && pending.type === "create") {861      // Firefox path: popup itself runs navigator.credentials.create. The862      // background never approved/rejected anything — it just stashed863      // intent. After the popup-driven flow resolves (success or cancel),864      // clear the pending key so the popup doesn't re-show this on next open.865      const { createFirefoxPasskey } = await import("./firefox-passkey");866      const result = await createFirefoxPasskey(pending);867      if (!result.ok) {868        console.warn("Peach Firefox passkey create failed:", result.error);869      }870      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });871      setPendingPasskey(null);872      void loadEntries();873      return;874    }875    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });876    setPendingPasskey(null);877  }878879  async function handleDenyPendingPasskey() {880    const pending = pendingPasskey();881    if (!pending) return;882    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });883    setPendingPasskey(null);884  }885886  function queueContentIdle(after?: () => void) {887    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);888    contentPhaseTimer = window.setTimeout(() => {889      setContentPhase("idle");890      after?.();891    }, ENTRY_TRANSITION_SETTLE_MS);892  }893894  return (895    <div class="popup-root peach-theme">896      <Show when={bootState() === "ready"}>897        <Show898          when={!pendingPasskey()}899          fallback={900            <PasskeyApprovalView901              type={pendingPasskey()!.type}902              rpName={pendingPasskey()!.rpName}903              rpId={pendingPasskey()!.rpId}904              userName={pendingPasskey()!.userName}905              userDisplayName={pendingPasskey()!.userDisplayName}906              onApprove={handleApprovePendingPasskey}907              onDeny={handleDenyPendingPasskey}908            />909          }910        >911          <Show912            when={!isLockedView()}913            fallback={914              <Show915                when={onboarded() || hasVault()}916                fallback={917                  <Onboarding918                    onComplete={() => { setOnboarded(true); }}919                  />920                }921              >922                <LockView923                  hasVault={hasVault()}924                  ready={bootState() === "ready"}925                  isPro={proStatus()}926                  forceRecoveryWords={forceRecoveryWords()}927                  onUnlock={() => {928                    // After recovery words are confirmed, restore real vault929                    // state and proceed through the normal unlock path.930                    if (forceRecoveryWords()) {931                      setForceRecoveryWords(false);932                      setHasVault(true);933                    }934                    return handleUnlock();935                  }}936                  onBackToOnboarding={937                    !hasVault()938                      ? () => setOnboarded(false)939                      : undefined940                  }941                />942              </Show>943            }944          >945            <Show946              when={view() !== "pro-celebration"}947              fallback={<ProCelebration />}948            >949            <section950              id="hd-shell"951              class="peach-shell peach-theme"952              data-surface="extension"953            >954            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>955              <PeachWordmark unlocked />956              <div class="peach-chrome-actions">957                <button958                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"959                  onClick={() => setView("settings")}960                  aria-label="Settings"961                >962                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">963                    <path964                      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"965                      stroke="currentColor"966                      stroke-width="0.9"967                    />968                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />969                  </svg>970                </button>971                <button972                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"973                  onClick={handleAdd}974                  aria-label="New entry"975                >976                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">977                    <path d="M5.5 1v9M1 5.5h9" />978                  </svg>979                </button>980                <button981                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"982                  onClick={() => void handleHeaderLock()}983                  aria-label="Lock vault"984                >985                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">986                    <path987                      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"988                      stroke="currentColor"989                      stroke-width="1"990                      stroke-linecap="round"991                    />992                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />993                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />994                  </svg>995                </button>996              </div>997            </header>998999            <Show when={recentPairToast()}>1000              <div class="peach-pair-toast" role="status" aria-live="polite">1001                Paired with <strong>{recentPairToast()}</strong>1002              </div>1003            </Show>10041005            <Show when={incomingPair() !== null}>1006              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1007                <div class="peach-pair-request-header">1008                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1009                  <span class="peach-pair-request-title">Pairing request</span>1010                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1011                </div>1012                <p class="peach-pair-request-body">1013                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1014                </p>1015                <div class="peach-pair-request-actions">1016                  <button1017                    class="peach-btn peach-btn--ghost peach-btn--sm"1018                    onClick={() => void respondIncomingPairing(false)}1019                    disabled={incomingPairResponding()}1020                  >1021                    Reject1022                  </button>1023                  <button1024                    class="peach-btn peach-btn--accent peach-btn--sm"1025                    onClick={() => void respondIncomingPairing(true)}1026                    disabled={incomingPairResponding()}1027                  >1028                    Accept1029                  </button>1030                </div>1031              </div>1032            </Show>10331034            <Show when={pendingProNotice() !== null}>1035              <div class="peach-pro-notice-banner">1036                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1037                <button1038                  class="peach-pro-notice-link"1039                  onClick={() => {1040                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1041                    setSettingsInitialSection("license");1042                    setView("settings");1043                    setPendingProNotice(null);1044                  }}1045                >1046                  Learn more →1047                </button>1048                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1049              </div>1050            </Show>10511052            <div class="peach-shell-body">1053              <div class="peach-shell-veil"></div>1054              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1055                <EntryView1056                  entry={selectedEntry()}1057                  currentTabUrl={currentTabUrl()}1058                  onDelete={handleDelete}1059                  onFieldSaved={() => void loadEntries()}1060                  onEscape={() => { setView("list"); }}1061                />1062              </div>10631064              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1065                <div class="peach-search-bar">1066                  <span class="peach-search-icon">1067                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1068                      <circle cx="5.5" cy="5.5" r="3.75" />1069                      <path d="M8.75 8.75L11.5 11.5" />1070                    </svg>1071                  </span>1072                  <input1073                    class="peach-search-input"1074                    placeholder="search vault..."1075                    autocomplete="off"1076                    aria-label="Search vault entries"1077                    onClick={openList}1078                    onFocus={openList}1079                    readOnly1080                  />1081                  <div class="peach-search-meta">1082                    <span class="peach-search-counter">1083                      {entries().length > 01084                        ? `${selectedIndex() + 1} / ${entries().length}`1085                        : "0 entries"}1086                    </span>1087                    <span class="peach-divider"></span>1088                    <button1089                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1090                      onClick={() => navigate(-1)}1091                      aria-label="Previous entry"1092                      disabled={entries().length === 0}1093                    >1094                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1095                        <path d="M5 1L1 5.5L5 10" />1096                      </svg>1097                    </button>1098                    <button1099                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1100                      onClick={() => navigate(1)}1101                      aria-label="Next entry"1102                      disabled={entries().length === 0}1103                    >1104                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1105                        <path d="M1 1L5 5.5L1 10" />1106                      </svg>1107                    </button>1108                  </div>1109                </div>1110              </section>1111            </div>11121113            <Show when={view() === "list"}>1114              <VaultView1115                entries={entries()}1116                selectedEntryId={selectedEntry()?.id}1117                currentTabDomain={currentTabDomain()}1118                sortOrder={sortOrder()}1119                searchSeed={listSearchSeed()}1120                searchSeedNonce={listSearchSeedNonce()}1121                onSelectEntry={handleSelectEntry}1122                onSortOrderChange={setSortOrder}1123                onAdd={handleAdd}1124                onClose={() => setView("entry")}1125                onOpenTrash={() => setView("trash")}1126                onDeleteMany={handleDeleteMany}1127              />1128            </Show>1129            <Show when={view() === "settings"}>1130              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1131                <SettingsView1132                  entriesCount={entries().length}1133                  breachMonitoring={breachMonitoring()}1134                  lockOnClose={lockOnClose()}1135                  autoLockMinutes={autoLockMinutes()}1136                  trashRetentionDays={trashRetentionDays()}1137                  theme={theme()}1138                  accentColor={accentColor()}1139                  displayFont={displayFont()}1140                  textSize={textSize()}1141                  reduceMotion={reduceMotion()}1142                  isPro={proStatus()}1143                  initialSection={settingsInitialSection()}1144                  upgradeHighlight={upgradeHighlight()}1145                  onBreachMonitoringChange={applyBreachMonitoring}1146                  onLockOnCloseChange={applyLockOnClose}1147                  onAutoLockMinutesChange={applyAutoLockMinutes}1148                  onTrashRetentionChange={applyTrashRetention}1149                  onThemeChange={applyTheme}1150                  onAccentChange={applyAccentColor}1151                  onDisplayFontChange={applyDisplayFont}1152                  onTextSizeChange={applyTextSize}1153                  onReduceMotionChange={applyReduceMotion}1154                  shortcuts={shortcutBindings()}1155                  onShortcutsChange={applyShortcuts}1156                  onLicenseChange={async () => {1157                    // After activation/deactivation: refresh Pro status,1158                    // re-load entries (defensive — signal state can drift if1159                    // the SW briefly restarts during the verify+save round-trip),1160                    // and replay the Pro celebration if this is the first time1161                    // a valid Pro license is seen on this device.1162                    await refreshProStatus();1163                    void loadEntries();1164                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1165                    if ((should as { ok: boolean; data?: boolean }).data === true) {1166                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1167                      setView("pro-celebration");1168                      window.setTimeout(() => setView("settings"), 2500);1169                    }1170                  }}1171                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1172                  onImport={() => setView("import")}1173                  onExport={() => setView("export")}1174                  onBreachCheckDone={loadEntries}1175                  onOpenHealth={openHealth}1176                  onOpenSyncPairing={() => setView("sync-pairing")}1177                  onOpenFileImport={handleOpenFileImport}1178                  onOpenPanic={() => setView("panic")}1179                />1180              </Suspense>1181            </Show>1182            <Show when={view() === "sync-pairing"}>1183              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1184                <SyncPairingView1185                  onClose={() => setView("settings")}1186                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1187                />1188              </Suspense>1189            </Show>1190            <Show when={view() === "add"}>1191              <AddView1192                entry={editEntry()}1193                entries={entries()}1194                onBack={handleBack}1195                onSave={handleSave}1196              />1197            </Show>1198            <Show when={view() === "import"}>1199              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1200                <ImportView onBack={handleBack} onImport={handleSave} />1201              </Suspense>1202            </Show>1203            <Show when={view() === "export"}>1204              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1205                <ExportView1206                  onBack={() => {1207                    if (returnToPanic()) {1208                      setReturnToPanic(false);1209                      setView("panic");1210                    } else {1211                      handleBack();1212                    }1213                  }}1214                />1215              </Suspense>1216            </Show>1217            <Show when={view() === "panic"}>1218              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1219                <PanicView1220                  onCancel={() => setView("settings")}1221                  onOpenExport={() => {1222                    setReturnToPanic(true);1223                    setView("export");1224                  }}1225                  onDestroyed={async () => {1226                    clearCanarySuppressions();1227                    setEntries([]);1228                    setSelectedEntry(null);1229                    setEditEntry(undefined);1230                    setHasVault(false);1231                    setOnboarded(false);1232                    setProStatus(false);1233                    setPendingPasskey(null);1234                    setUpgradeHighlight(null);1235                    setSettingsInitialSection(null);1236                    setPendingProNotice(null);1237                    setPendingCelebration(false);1238                    setReturnToPanic(false);1239                    setContentPhase("idle");1240                    setView("lock");1241                  }}1242                />1243              </Suspense>1244            </Show>1245            <Show when={view() === "health"}>1246              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1247                <HealthView1248                  entries={entries()}1249                  isPro={proStatus()}1250                  onFixEntry={handleFixEntry}1251                  onBack={() => setView("settings")}1252                  onRefresh={loadEntries}1253                />1254              </Suspense>1255            </Show>1256            <Show when={view() === "trash"}>1257              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1258                <TrashView1259                  onBack={() => setView("list")}1260                  onRestored={() => void loadEntries()}1261                />1262              </Suspense>1263            </Show>1264            <Show when={restoreView() === "file"}>1265              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1266                <ImportView1267                  mode="onboarding"1268                  replacesExistingVault={true}1269                  onBack={() => setRestoreView(null)}1270                  onImport={async () => {1271                    setRestoreView(null);1272                    await handleUnlock();1273                  }}1274                />1275              </Suspense>1276            </Show>1277            </section>1278            </Show>1279          </Show>1280        </Show>1281      </Show>1282      <Show when={showShortcutsHelp()}>1283        <ShortcutsHelpOverlay1284          bindings={shortcutBindings()}1285          onClose={() => setShowShortcutsHelp(false)}1286        />1287      </Show>1288    </div>1289  );1290}12911292function ShortcutsHelpOverlay(props: {1293  bindings: Record<ShortcutAction, Keybinding>;1294  onClose: () => void;1295}) {1296  return (1297    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1298      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1299        <div class="peach-shortcuts-help-head">1300          <h3>Keyboard shortcuts</h3>1301          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1302        </div>1303        <div class="peach-shortcuts-help-body">1304          <p class="peach-settings-sub-label">ENTRY VIEW</p>1305          <ul>1306            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1307              <li>1308                <span>{d.label}</span>1309                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1310              </li>1311            ))}1312          </ul>1313          <p class="peach-settings-sub-label">ANYWHERE</p>1314          <ul>1315            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1316              <li>1317                <span>{d.label}</span>1318                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1319              </li>1320            ))}1321          </ul>1322        </div>1323      </div>1324    </div>1325  );1326}