App.tsx

59.0 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";28import { isNativePlatform, nativePlugin } from "../shared/native";2930export { sendMessage } from "../shared/bridge";3132const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));33const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));34const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));35const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));36const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));37const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));38const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));3940type View =41  | "lock"42  | "pro-celebration"43  | "entry"44  | "list"45  | "add"46  | "settings"47  | "sync-pairing"48  | "import"49  | "export"50  | "health"51  | "trash"52  | "panic";53type BootState = "loading" | "ready";5455const canarySuppressMap = new Map<string, boolean>();56let shellRingAnimation: Animation | null = null;5758export function isCanarySuppressed(entryId: string): boolean {59  return canarySuppressMap.get(entryId) ?? false;60}6162export function setCanarySuppressed(entryId: string, suppressed: boolean): void {63  canarySuppressMap.set(entryId, suppressed);64}6566export function clearCanarySuppressions(): void {67  canarySuppressMap.clear();68}6970export function triggerRing() {71  const shell = document.getElementById("hd-shell");72  if (!shell) return;7374  shellRingAnimation?.cancel();75  shell.dataset.glowing = "true";76  const animation = shell.animate(77    [78      { offset: 0, boxShadow: "var(--copy-shadow)" },79      {80        offset: 0.3,81        boxShadow:82          "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)",83      },84      { offset: 1, boxShadow: "var(--copy-shadow)" },85    ],86    {87      duration: 720,88      easing: "cubic-bezier(0.4, 0, 0.2, 1)",89      fill: "none",90    }91  );92  shellRingAnimation = animation;93  const clearGlow = () => {94    if (shellRingAnimation !== animation) return;95    shellRingAnimation = null;96    delete shell.dataset.glowing;97  };98  animation.onfinish = clearGlow;99  animation.oncancel = clearGlow;100}101102103export function triggerPipPulse() {104  const pip = document.querySelector(".peach-status-pip, .pip");105  if (pip) {106    pip.classList.remove("pulse");107    void (pip as HTMLElement).offsetWidth;108    pip.classList.add("pulse");109  }110}111112const ENTRY_TRANSITION_EXIT_MS = 95;113const ENTRY_TRANSITION_SETTLE_MS = 135;114115export default function App() {116  const [bootState, setBootState] = createSignal<BootState>("loading");117  const [view, setView] = createSignal<View>("lock");118  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(119    "enter"120  );121  const [contentTransitioning, setContentTransitioning] = createSignal(false);122  const [hasVault, setHasVault] = createSignal(false);123  const [onboarded, setOnboarded] = createSignal(true);124  const [entries, setEntries] = createSignal<VaultEntry[]>([]);125  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);126  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);127  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");128  const [theme, setTheme] = createSignal<"dark" | "light">("dark");129  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");130  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");131  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);132  const [lockOnClose, setLockOnClose] = createSignal(true);133  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);134  const [breachMonitoring, setBreachMonitoring] = createSignal(true);135  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);136  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);137  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);138  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);139  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);140  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");141  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");142  // Cached Pro status — synchronous for render paths. Background's143  // GET_LICENSE is async, but render-time reads of isPro() must not block.144  // Refreshed at boot, after activate/deactivate, and whenever the popup145  // re-opens onto a stored license that has changed via another window.146  const [proStatus, setProStatus] = createSignal(false);147  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);148  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);149  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");150  const [listSearchSeed, setListSearchSeed] = createSignal("");151  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);152  const [pendingCelebration, setPendingCelebration] = createSignal(false);153  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);154  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);155  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);156  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);157  const [incomingPairTick, setIncomingPairTick] = createSignal(0);158  const incomingPairSecondsLeft = () => {159    void incomingPairTick();160    const req = incomingPair();161    if (!req) return 0;162    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));163  };164  // True while Panic Step 1 has bounced the user out to Export. When Export's165  // onBack fires we return to Panic instead of Settings so the user keeps the166  // destruction context they came from.167  const [returnToPanic, setReturnToPanic] = createSignal(false);168  // Set on popup boot when peach_recovery_pending flag is found in session169  // storage — instructs LockView to skip the unlock UI and open the recovery170  // words confirmation surface instead. Cleared via handleUnlock once the171  // user has typed the 3 confirmation words.172  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);173174  let contentPhaseTimer: number | undefined;175176  function applyAccent(name: AccentColorName) {177    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;178    const hex = color.hex;179    document.documentElement.style.setProperty("--peach-accent", hex);180    // Ambient surface variables — derived from the accent so surfaces shift181    // subtly toward the accent hue rather than staying fixed warm-brown.182    document.documentElement.style.setProperty("--peach-glow", hex + "2A");183    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");184    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");185  }186187  createEffect(() => {188    applyAccent(accentColor());189  });190191  createEffect(() => {192    document.documentElement.classList.toggle("light", theme() === "light");193    document.body.classList.toggle("light", theme() === "light");194  });195196  createEffect(() => {197    document.documentElement.setAttribute("data-display-font", displayFont());198  });199200  createEffect(() => {201    document.documentElement.setAttribute("data-text-size", textSize());202  });203204  createEffect(() => {205    if (reduceMotion()) {206      document.documentElement.setAttribute("data-motion", "reduce");207    } else {208      document.documentElement.removeAttribute("data-motion");209    }210  });211212  const selectedIndex = createMemo(() => {213    const currentId = selectedEntry()?.id;214    if (!currentId) return entries().length > 0 ? 0 : -1;215    return entries().findIndex((entry) => entry.id === currentId);216  });217218  async function applyAccentColor(name: AccentColorName) {219    applyAccent(name);220    setAccentColor(name);221    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });222  }223224  async function applyTheme(t: "dark" | "light") {225    setTheme(t);226    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });227  }228229  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {230    setDisplayFont(f);231    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });232  }233234  async function applyTextSize(size: "small" | "medium" | "large") {235    setTextSize(size);236    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });237  }238239  async function applyReduceMotion(enabled: boolean) {240    setReduceMotion(enabled);241    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });242  }243244  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload245  // small and lets future default updates land for actions the user hasn't246  // touched. Settings sends us the full active map; we filter and store.247  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {248    setShortcutBindings(active);249    const overrides: Record<string, Keybinding> = {};250    for (const action of Object.keys(active) as ShortcutAction[]) {251      const a = active[action];252      const d = DEFAULT_BINDINGS[action];253      const same = a.key === d.key254        && Boolean(a.ctrl)  === Boolean(d.ctrl)255        && Boolean(a.meta)  === Boolean(d.meta)256        && Boolean(a.shift) === Boolean(d.shift)257        && Boolean(a.alt)   === Boolean(d.alt);258      if (!same) overrides[action] = a;259    }260    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });261  }262263  async function applyLockOnClose(enabled: boolean) {264    setLockOnClose(enabled);265    await sendMessage({266      type: "UPDATE_SETTINGS",267      payload: { lockOnClose: enabled },268    });269  }270271  async function applyAutoLockMinutes(minutes: number) {272    setAutoLockMinutes(minutes);273    await sendMessage({274      type: "UPDATE_SETTINGS",275      payload: { autoLockMinutes: minutes },276    });277  }278279  async function applyBreachMonitoring(enabled: boolean) {280    setBreachMonitoring(enabled);281    await sendMessage({282      type: "UPDATE_SETTINGS",283      payload: { breachMonitoring: enabled },284    });285  }286287  onMount(async () => {288    // Resolve the active tab in parallel with the unlock/has-vault queries —289    // openVault()'s smart selection picks the entry matching currentTabDomain,290    // so it must be populated before openVault runs. Previously refreshCurrentTab291    // ran after openVault, leaving popups that booted already-unlocked falling292    // back to loadedEntries[0] instead of the domain match.293    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([294      sendMessage({ type: "IS_UNLOCKED" }),295      sendMessage({ type: "HAS_VAULT" }),296      refreshCurrentTab(),297      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),298    ]);299    const unlocked = Boolean(300      (unlockResponse as { ok: boolean; data?: boolean }).data301    );302    const vaultExists = Boolean(303      (vaultResponse as { ok: boolean; data?: boolean }).data304    );305    const shouldCelebrate = Boolean(306      (celebrationResponse as { ok: boolean; data?: boolean }).data307    );308    setHasVault(vaultExists);309    // Onboarding gate — show once on first install, never again. Existing310    // users (vaultExists) are auto-marked onboarded so they skip the flow311    // even on the very first popup open after this feature ships.312    try {313      const onboarded = await storageGet("peach_onboarded");314      const seen = onboarded === "true";315      if (vaultExists && !seen) {316        await storageSet("peach_onboarded", "true");317        setOnboarded(true);318      } else {319        setOnboarded(seen);320      }321    } catch {322      // storage unavailable — default to onboarded so we never block boot323      setOnboarded(true);324    }325    await Promise.all([restoreSettings(), refreshProStatus()]);326327    // Mark played before any animation so a crash mid-sequence never replays it328    if (shouldCelebrate) {329      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });330    }331332    // If the user created a vault but hasn't yet confirmed their recovery333    // words, route back to the recovery-words screen instead of opening the334    // entries view. The flag lives in chrome.storage.local so it survives335    // both popup close (SW suppresses lock-on-close) and full browser336    // restart (handleUnlock checks the same flag after a fresh password337    // unlock). Cleared when confirmation succeeds.338    let recoveryPending = false;339    try {340      const out = await chrome.storage.local?.get("peach_recovery_pending");341      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";342    } catch { /* best-effort */ }343344    if (recoveryPending && unlocked) {345      // forceRecoveryWords overrides LockView's hasVault gate so the346      // recovery surface renders even though the vault now exists.347      setForceRecoveryWords(true);348      setView("lock");349    } else if (unlocked && vaultExists) {350      await openVault(undefined, shouldCelebrate);351      if (shouldCelebrate) {352        setView("pro-celebration");353        window.setTimeout(() => setView("entry"), 2500);354      }355    } else if (shouldCelebrate) {356      setPendingCelebration(true);357    }358359    await refreshPendingPasskey();360    await refreshIncomingPairing();361    await consumeRecentPairing();362363    // Track tab changes so smart sort stays current364    const handleTabActivated = () => { void refreshCurrentTab(); };365    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {366      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();367    };368    try {369      chrome.tabs.onActivated.addListener(handleTabActivated);370      chrome.tabs.onUpdated.addListener(handleTabUpdated);371      onCleanup(() => {372        chrome.tabs.onActivated.removeListener(handleTabActivated);373        chrome.tabs.onUpdated.removeListener(handleTabUpdated);374      });375    } catch {376      // tabs permission may not be available in all contexts377    }378379    setBootState("ready");380    document.getElementById("pre-lock")?.setAttribute("hidden", "true");381382    // Check for pending session-storage notices from the background.383    if (chrome.storage.session) {384      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as385        Record<string, { feature?: string } | undefined>;386      if (session.pendingProGate?.feature) {387        await chrome.storage.session.remove("pendingProGate");388        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);389        setSettingsInitialSection("license");390        setView("settings");391      } else if (session.pendingProNotice?.feature) {392        await chrome.storage.session.remove("pendingProNotice");393        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });394      }395    }396397    // Warm the lazy-module cache so the Suspense fallback never shows for398    // locally-bundled extension views. Without this, the first navigation to399    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which400    // covers the shell and absorbs clicks on the header.401    void Promise.all([402      import("./views/Settings").catch(() => {}),403      import("./views/Import").catch(() => {}),404      import("./views/Export").catch(() => {}),405      import("./views/Health").catch(() => {}),406      import("./views/TrashView").catch(() => {}),407    ]);408409    // Lock-on-close via a persistent port. sendMessage in pagehide is410    // unreliable — the popup context tears down before the message lands.411    // The SW's onConnect listener locks when this port disconnects.412    let popupPort: chrome.runtime.Port | null = null;413    try {414      popupPort = chrome.runtime.connect({ name: "popup" });415    } catch { /* extension context invalidated — ignore */ }416    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });417418    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only419    // reliable signal is appStateChange — setTimeout is killed when the OS420    // backgrounds the app. We measure elapsed background time on resume.421    if (isNativePlatform()) {422      let backgroundedAt: number | null = null;423      const CapApp = nativePlugin<{424        addListener: (425          ev: string,426          cb: (s: { isActive: boolean }) => void,427        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };428      }>("App");429      if (CapApp?.addListener) {430        const sub = CapApp.addListener(431          "appStateChange",432          ({ isActive }: { isActive: boolean }) => {433            if (!isActive) {434              backgroundedAt = Date.now();435              return;436            }437            if (backgroundedAt !== null && autoLockMinutes() > 0) {438              const elapsed = Date.now() - backgroundedAt;439              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();440            }441            backgroundedAt = null;442          }443        );444        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.445        onCleanup(() => {446          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});447        });448      }449    }450451    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale452    // entries instead of waiting for the next GET_ENTRIES round-trip.453    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {454      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();455      if (msg?.type === "PRO_GATE_TRIGGERED") {456        setUpgradeHighlight(msg.payload?.feature ?? null);457        setSettingsInitialSection("license");458        setView("settings");459      }460      if (msg?.type === "INCOMING_PAIRING_REQUEST") {461        void refreshIncomingPairing();462      }463    };464    chrome.runtime.onMessage.addListener(handleRuntimeMessage);465    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));466467    // Android hardware/gesture back. MainActivity fires peach:back; the popup468    // decides what "back" means per surface. Lock+no-vault is the common case469    // — return to onboarding rather than letting the OS dismiss the activity.470    const handlePeachBack = () => {471      const v = view();472      if (v === "lock" && !hasVault() && onboarded()) {473        setOnboarded(false);474        return;475      }476      if (v === "list") { setView("entry"); return; }477      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {478        handleBack();479        return;480      }481      if (v === "sync-pairing") { setView("settings"); return; }482    };483    window.addEventListener("peach:back", handlePeachBack);484    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));485486    // Mobile bottom-sheet gesture: swipe up from the bottom 40% of the screen487    // reveals the vault list; swipe down from the top of the list dismisses it.488    // Tracked at document level so the search bar input doesn't have to be the489    // touch target — anywhere in the lower band counts.490    if (isNativePlatform()) {491      let touchStartY = 0;492      let touchStartX = 0;493      let dragging = false;494      let startedInBand = false;495      const SWIPE_THRESHOLD = 60;496      const HORIZONTAL_TOLERANCE = 30;497498      const onTouchStart = (e: TouchEvent) => {499        const t = e.touches[0];500        if (!t) return;501        touchStartY = t.clientY;502        touchStartX = t.clientX;503        dragging = true;504        const v = view();505        if (v === "entry") {506          // Only count starts inside the bottom 40% band (top 60% reserved507          // for entry interactions, taps, swipes between entries).508          startedInBand = t.clientY > window.innerHeight * 0.6;509        } else if (v === "list") {510          // From list: any downward drag near the top of the list dismisses it.511          startedInBand = t.clientY < window.innerHeight * 0.35;512        } else {513          startedInBand = false;514        }515      };516517      const onTouchMove = (e: TouchEvent) => {518        if (!dragging || !startedInBand) return;519        const t = e.touches[0];520        if (!t) return;521        const dy = t.clientY - touchStartY;522        const dx = Math.abs(t.clientX - touchStartX);523        if (dx > HORIZONTAL_TOLERANCE) {524          // Treat as a horizontal swipe — give it back to the entry view.525          dragging = false;526          return;527        }528        const v = view();529        if (v === "entry" && dy < -SWIPE_THRESHOLD) {530          dragging = false;531          setView("list");532        } else if (v === "list" && dy > SWIPE_THRESHOLD) {533          dragging = false;534          setView("entry");535        }536      };537538      const onTouchEnd = () => { dragging = false; startedInBand = false; };539540      document.addEventListener("touchstart", onTouchStart, { passive: true });541      document.addEventListener("touchmove",  onTouchMove,  { passive: true });542      document.addEventListener("touchend",   onTouchEnd,   { passive: true });543      document.addEventListener("touchcancel", onTouchEnd,  { passive: true });544      onCleanup(() => {545        document.removeEventListener("touchstart", onTouchStart);546        document.removeEventListener("touchmove",  onTouchMove);547        document.removeEventListener("touchend",   onTouchEnd);548        document.removeEventListener("touchcancel", onTouchEnd);549      });550    }551552    // Action handlers — keyed by ShortcutAction. The dispatcher below tests553    // each binding against the event and runs the matching handler. New554    // shortcuts only need an entry here; the binding is data, not code.555    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {556      copy_password: () => {557        const entry = selectedEntry();558        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });559      },560      copy_username: () => {561        const entry = selectedEntry();562        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });563      },564      copy_totp: () => {565        const entry = selectedEntry();566        if (!entry?.totp) return;567        try {568          const { code } = generateTOTP(entry.totp);569          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });570        } catch { /* invalid TOTP secret — silent */ }571      },572      new_entry: () => handleAdd(),573      edit_entry: () => {574        const entry = selectedEntry();575        // Passkey-only entries have nothing user-editable in the Add view; the576        // passkey credential itself is opaque. Skip the edit action for them.577        if (!entry || isPasskeyOnly(entry)) return;578        setEditEntry(entry);579        setView("add");580      },581      delete_entry: () => {582        if (selectedEntry()) void handleDelete();583      },584      lock_vault: () => { void handleHeaderLock(); },585      search: () => openList(),586      nav_prev: () => navigate(-1),587      nav_next: () => navigate(1),588      jump_vault: () => setView("entry"),589      jump_settings: () => setView("settings"),590      show_help: () => setShowShortcutsHelp(true),591    };592593    // Actions that are MEANINGFUL only on the entry-detail view. Outside594    // that scope the binding is dormant — pressing C while on Settings595    // does nothing rather than awkwardly copying from a now-stale entry.596    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([597      "copy_password", "copy_username", "copy_totp",598      "edit_entry", "delete_entry", "nav_prev", "nav_next",599    ]);600601    const handleGlobalKeydown = (e: KeyboardEvent) => {602      const v = view();603      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"604        || (e.target as HTMLElement)?.tagName === "TEXTAREA"605        || (e.target as HTMLElement)?.isContentEditable;606      const isPrintableSearchKey =607        e.key.length === 1 &&608        !e.ctrlKey &&609        !e.metaKey &&610        !e.altKey;611612      // No input during the pro celebration sequence613      if (v === "pro-celebration") return;614615      // Help dialog: Escape closes it; eat the keypress so it doesn't616      // also navigate away from the underlying view.617      if (showShortcutsHelp()) {618        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }619        return;620      }621622      // ── Escape — fixed binding (not user-customizable) ───────623      if (e.key === "Escape") {624        if (v === "list") { setView("entry"); return; }625        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }626        if (v === "sync-pairing") { setView("settings"); return; }627      }628629      // Bindings-driven dispatch. Single-key letter bindings without630      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is631      // inside an input, so users can type into search/forms normally.632      const bindings = shortcutBindings();633      for (const action of Object.keys(bindings) as ShortcutAction[]) {634        const binding = bindings[action];635        if (!matchKeybinding(e, binding)) continue;636        // Single-key letter bindings need the input-focus guard. Bindings637        // with any modifier are safe — Ctrl+L doesn't conflict with typing.638        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;639        if (!hasMod && binding.key.length === 1 && inInput) return;640        if (ENTRY_SCOPED.has(action) && v !== "entry") return;641        e.preventDefault();642        SHORTCUT_HANDLERS[action]?.();643        return;644      }645646      // Type-to-search: in entry view, any printable key not consumed by a647      // shortcut above primes the list search seed and opens the list.648      // Kept outside the bindings table because it's a behavior, not a649      // discrete action — every printable character can trigger it.650      if (v === "entry" && !inInput && isPrintableSearchKey) {651        e.preventDefault();652        primeListSearch(e.key);653        return;654      }655    };656    window.addEventListener("keydown", handleGlobalKeydown);657    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));658659    const handleStorageChanged = (660      changes: Record<string, chrome.storage.StorageChange>,661      areaName: string662    ) => {663      if (areaName !== "session") return;664      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {665        return;666      }667      void refreshPendingPasskey();668    };669    chrome.storage.onChanged.addListener(handleStorageChanged);670    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));671  });672673  async function refreshCurrentTab() {674    try {675      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });676      const url = tab?.url ?? tab?.pendingUrl ?? "";677      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");678      // Skip extension/internal URLs — adding chrome://, about:, or679      // chrome-extension:// to a vault entry is never what the user wants.680      const isWebUrl = /^https?:\/\//i.test(url);681      setCurrentTabUrl(isWebUrl ? url : "");682    } catch {683      setCurrentTabDomain("");684      setCurrentTabUrl("");685    }686  }687688  async function refreshPendingPasskey() {689    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });690    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);691  }692693  async function refreshIncomingPairing() {694    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });695    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;696    setIncomingPair(data);697  }698699  // Drains a single one-shot record left by the background when 6-digit700  // pairing succeeded while the popup was closed (or the SyncPairing view was701  // navigated away from before it could show its own success card).702  async function consumeRecentPairing() {703    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });704    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;705    if (data?.deviceName) {706      setRecentPairToast(data.deviceName);707      window.setTimeout(() => setRecentPairToast(null), 4000);708    }709  }710711  async function respondIncomingPairing(accept: boolean) {712    if (incomingPairResponding()) return;713    setIncomingPairResponding(true);714    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });715    setIncomingPair(null);716    setIncomingPairResponding(false);717  }718719  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a720  // request appears, ticks once per second, and clears the banner if the721  // request expires while the popup is open.722  createEffect(() => {723    const req = incomingPair();724    if (!req) return;725    const handle = window.setInterval(() => {726      setIncomingPairTick((tick) => tick + 1);727      if (Date.now() >= req.expiresAt) {728        setIncomingPair(null);729        window.clearInterval(handle);730      }731    }, 1000);732    onCleanup(() => window.clearInterval(handle));733  });734735  async function refreshProStatus() {736    const res = await sendMessage({ type: "GET_LICENSE" });737    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;738    setProStatus(Boolean(data?.valid && data?.plan === "pro"));739  }740741  async function restoreSettings() {742    const res = await sendMessage({ type: "GET_SETTINGS" });743    const s = (res as { ok: boolean; data?: any }).data ?? {};744    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {745      setAccentColor(s.accentColor as AccentColorName);746    }747    setTheme(s.theme === "light" ? "light" : "dark");748    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {749      setDisplayFont(s.displayFont);750    } else {751      setDisplayFont("cormorant-italic");752    }753    if (s.textSize === "small" || s.textSize === "large") {754      setTextSize(s.textSize);755    } else {756      setTextSize("medium");757    }758    setReduceMotion(s.reduceMotion === true);759    setLockOnClose(s.lockOnClose !== false);760    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);761    setBreachMonitoring(s.breachMonitoring !== false);762    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);763    setShortcutBindings(getActiveBindings(s.shortcuts));764  }765766  async function applyTrashRetention(days: number) {767    setTrashRetentionDays(days);768    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });769  }770771  function primeListSearch(seed: string) {772    setListSearchSeed(seed);773    setListSearchSeedNonce((value) => value + 1);774    openList();775  }776777  // Returns null when it detected a dead service worker and triggered handleLock().778  // Callers that need to abort (e.g. openVault) check for null rather than relying779  // on view() state, which may already be "lock" during normal startup flows.780  async function loadEntries(): Promise<VaultEntry[] | null> {781    const response = await sendMessage({ type: "GET_ENTRIES" });782    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };783784    // If the service worker was killed and restarted (MV3 workers sleep), the785    // vault will be locked again — or the worker may not respond at all.786    // In either case, send the user to the lock screen rather than silently787    // showing an empty vault (which looks like data loss).788    if (!res.ok) {789      if (790        res.error === "vault locked" ||791        res.error === "SERVICE_WORKER_UNAVAILABLE" ||792        (typeof res.error === "string" && res.error.includes("locked"))793      ) {794        handleLock();795        return null; // signal emergency lock to callers796      }797      return [];798    }799800    const loadedEntries = res.data ?? [];801    setEntries(loadedEntries);802803    const currentId = selectedEntry()?.id;804    if (currentId) {805      setSelectedEntry(806        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null807      );808    }809810    return loadedEntries;811  }812813  async function openVault(preferredEntryId?: string, skipViewSet = false) {814    // Purge expired trash entries on each vault open815    const retDays = trashRetentionDays();816    if (retDays > 0) {817      void sendMessage({818        type: "PURGE_EXPIRED_TRASH",819        payload: { retentionMs: retDays * 86_400_000 },820      });821    }822823    const loadedEntries = await loadEntries();824825    // null means loadEntries() triggered an emergency lock (service worker died).826    // Don't override it by setting view back to "entry" with an empty vault.827    if (loadedEntries === null) return;828829    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry830    let nextSelectedEntry: VaultEntry | null = null;831    if (preferredEntryId) {832      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;833    }834    if (!nextSelectedEntry) {835      const tabDomain = currentTabDomain();836      if (tabDomain) {837        nextSelectedEntry = loadedEntries.find((e) => {838          if (e.type === "login") {839            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;840            for (const extra of e.additionalUrls ?? []) {841              if ((extractDomain(extra) ?? "") === tabDomain) return true;842            }843            return false;844          }845          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;846          return false;847        }) ?? null;848      }849    }850    nextSelectedEntry ??= loadedEntries[0] ?? null;851852    setSelectedEntry(nextSelectedEntry);853    setEditEntry(undefined);854    setContentTransitioning(false);855    setContentPhase("enter");856    queueContentIdle();857    if (!skipViewSet) setView("entry");858  }859860  async function handleUnlock() {861    // If the user previously created a vault but hadn't yet confirmed their862    // recovery words (and the browser was closed before they could), the863    // peach_recovery_pending flag is still set in storage.local. Re-route864    // back to the recovery surface so they finish the confirmation step865    // before reaching the entries view — the words can be re-derived now866    // that the vault is unlocked again.867    let recoveryPending = false;868    try {869      const out = await chrome.storage.local?.get("peach_recovery_pending");870      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";871    } catch { /* best-effort */ }872    if (recoveryPending) {873      setForceRecoveryWords(true);874      setView("lock");875      triggerPipPulse();876      await restoreSettings();877      return;878    }879    setHasVault(true);880    triggerPipPulse();881    await restoreSettings();882    const celebrating = pendingCelebration();883    if (celebrating) {884      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });885      setPendingCelebration(false);886    }887    await openVault(undefined, celebrating);888    if (celebrating) {889      setView("pro-celebration");890      window.setTimeout(() => setView("entry"), 2500);891    }892  }893894  function handleSelectEntry(entry: VaultEntry) {895    setSelectedEntry(entry);896    setContentTransitioning(false);897    setContentPhase("enter");898    queueContentIdle();899    setView("entry");900  }901902  function handleAdd() {903    setEditEntry(undefined);904    setView("add");905  }906907  async function handleDelete() {908    const entry = selectedEntry();909    if (!entry) return;910    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });911    const loadedEntries = await loadEntries() ?? [];912    setSelectedEntry(loadedEntries[0] ?? null);913    setView("entry");914  }915916  async function handleDeleteMany(ids: string[]) {917    for (const id of ids) {918      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });919    }920    const loadedEntries = await loadEntries() ?? [];921    // If the currently selected entry was among the deleted, move to first922    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);923    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);924  }925926  async function handleSave(savedEntry?: VaultEntry) {927    await openVault(savedEntry?.id);928  }929930  function handleBack() {931    setEditEntry(undefined);932    setView("entry");933  }934935  function handleLock() {936    clearCanarySuppressions();937    setEntries([]);938    setSelectedEntry(null);939    setEditEntry(undefined);940    setContentPhase("idle");941    setView("lock");942  }943944  function handleHeaderLock() {945    // Lock the UI immediately — do not wait for the service worker. If the SW946    // is dead or slow, the 5s sendMessage timeout would create a dead-click947    // window. The SW will lock on its next wake regardless.948    handleLock();949    void sendMessage({ type: "LOCK" });950  }951952  function navigate(dir: number) {953    const allEntries = entries();954    if (allEntries.length === 0) return;955    const currentIndex = selectedIndex();956    const baseIndex = currentIndex >= 0 ? currentIndex : 0;957    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;958    setSelectedEntry(allEntries[nextIndex]);959    setContentPhase("enter");960    queueContentIdle();961  }962963  function openList() {964    setView("list");965  }966967  function openHealth() {968    setEditEntry(undefined);969    setView("health");970  }971972  function handleOpenFileImport() {973    setRestoreView("file");974  }975976  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;977978  function handleFixEntry(entry: VaultEntry) {979    // Passkey-only entries have no editable surface — drop into view mode980    // instead of opening the Add editor.981    if (isPasskeyOnly(entry)) {982      setSelectedEntry(entry);983      setView("entry");984      return;985    }986    setEditEntry(entry);987    setView("add");988  }989990  const isLockedView = () => view() === "lock";991992  async function handleApprovePendingPasskey() {993    const pending = pendingPasskey();994    if (!pending) return;995    if (pending.browser === "firefox" && pending.type === "create") {996      // Firefox path: popup itself runs navigator.credentials.create. The997      // background never approved/rejected anything — it just stashed998      // intent. After the popup-driven flow resolves (success or cancel),999      // clear the pending key so the popup doesn't re-show this on next open.1000      const { createFirefoxPasskey } = await import("./firefox-passkey");1001      const result = await createFirefoxPasskey(pending);1002      if (!result.ok) {1003        console.warn("Peach Firefox passkey create failed:", result.error);1004      }1005      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1006      setPendingPasskey(null);1007      void loadEntries();1008      return;1009    }1010    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1011    setPendingPasskey(null);1012  }10131014  async function handleDenyPendingPasskey() {1015    const pending = pendingPasskey();1016    if (!pending) return;1017    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1018    setPendingPasskey(null);1019  }10201021  function queueContentIdle(after?: () => void) {1022    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1023    contentPhaseTimer = window.setTimeout(() => {1024      setContentPhase("idle");1025      after?.();1026    }, ENTRY_TRANSITION_SETTLE_MS);1027  }10281029  return (1030    <div class="popup-root peach-theme">1031      <Show when={bootState() === "ready"}>1032        <Show1033          when={!pendingPasskey()}1034          fallback={1035            <PasskeyApprovalView1036              type={pendingPasskey()!.type}1037              rpName={pendingPasskey()!.rpName}1038              rpId={pendingPasskey()!.rpId}1039              userName={pendingPasskey()!.userName}1040              userDisplayName={pendingPasskey()!.userDisplayName}1041              onApprove={handleApprovePendingPasskey}1042              onDeny={handleDenyPendingPasskey}1043            />1044          }1045        >1046          <Show1047            when={!isLockedView()}1048            fallback={1049              <Show1050                when={onboarded() || hasVault()}1051                fallback={1052                  <Onboarding1053                    onComplete={() => { setOnboarded(true); }}1054                  />1055                }1056              >1057                <LockView1058                  hasVault={hasVault()}1059                  ready={bootState() === "ready"}1060                  isPro={proStatus()}1061                  forceRecoveryWords={forceRecoveryWords()}1062                  onUnlock={() => {1063                    // RecoveryWordDisplay clears the storage flag before1064                    // calling onDone, so handleUnlock will see no pending1065                    // confirmation and proceed through the normal path.1066                    if (forceRecoveryWords()) setForceRecoveryWords(false);1067                    return handleUnlock();1068                  }}1069                  onBackToOnboarding={1070                    !hasVault()1071                      ? () => setOnboarded(false)1072                      : undefined1073                  }1074                />1075              </Show>1076            }1077          >1078            <Show1079              when={view() !== "pro-celebration"}1080              fallback={<ProCelebration />}1081            >1082            <section1083              id="hd-shell"1084              class="peach-shell peach-theme"1085              data-surface="extension"1086            >1087            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1088              <PeachWordmark unlocked />1089              <div class="peach-chrome-actions">1090                <button1091                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1092                  onClick={() => setView("settings")}1093                  aria-label="Settings"1094                >1095                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1096                    <path1097                      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"1098                      stroke="currentColor"1099                      stroke-width="0.9"1100                    />1101                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1102                  </svg>1103                </button>1104                <button1105                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1106                  onClick={handleAdd}1107                  aria-label="New entry"1108                >1109                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1110                    <path d="M5.5 1v9M1 5.5h9" />1111                  </svg>1112                </button>1113                <button1114                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1115                  onClick={() => void handleHeaderLock()}1116                  aria-label="Lock vault"1117                >1118                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1119                    <path1120                      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"1121                      stroke="currentColor"1122                      stroke-width="1"1123                      stroke-linecap="round"1124                    />1125                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1126                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1127                  </svg>1128                </button>1129              </div>1130            </header>11311132            <Show when={recentPairToast()}>1133              <div class="peach-pair-toast" role="status" aria-live="polite">1134                Paired with <strong>{recentPairToast()}</strong>1135              </div>1136            </Show>11371138            <Show when={incomingPair() !== null}>1139              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1140                <div class="peach-pair-request-header">1141                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1142                  <span class="peach-pair-request-title">Pairing request</span>1143                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1144                </div>1145                <p class="peach-pair-request-body">1146                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1147                </p>1148                <div class="peach-pair-request-actions">1149                  <button1150                    class="peach-btn peach-btn--ghost peach-btn--sm"1151                    onClick={() => void respondIncomingPairing(false)}1152                    disabled={incomingPairResponding()}1153                  >1154                    Reject1155                  </button>1156                  <button1157                    class="peach-btn peach-btn--accent peach-btn--sm"1158                    onClick={() => void respondIncomingPairing(true)}1159                    disabled={incomingPairResponding()}1160                  >1161                    Accept1162                  </button>1163                </div>1164              </div>1165            </Show>11661167            <Show when={pendingProNotice() !== null}>1168              <div class="peach-pro-notice-banner">1169                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1170                <button1171                  class="peach-pro-notice-link"1172                  onClick={() => {1173                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1174                    setSettingsInitialSection("license");1175                    setView("settings");1176                    setPendingProNotice(null);1177                  }}1178                >1179                  Learn more →1180                </button>1181                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1182              </div>1183            </Show>11841185            <div class="peach-shell-body">1186              <div class="peach-shell-veil"></div>1187              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1188                <EntryView1189                  entry={selectedEntry()}1190                  currentTabUrl={currentTabUrl()}1191                  onDelete={handleDelete}1192                  onFieldSaved={() => void loadEntries()}1193                  onEscape={() => { setView("list"); }}1194                />1195              </div>11961197              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1198                <div class="peach-search-bar">1199                  <span class="peach-search-icon">1200                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1201                      <circle cx="5.5" cy="5.5" r="3.75" />1202                      <path d="M8.75 8.75L11.5 11.5" />1203                    </svg>1204                  </span>1205                  <input1206                    class="peach-search-input"1207                    placeholder="search vault..."1208                    autocomplete="off"1209                    aria-label="Search vault entries"1210                    onClick={openList}1211                    onFocus={openList}1212                    readOnly1213                  />1214                  <div class="peach-search-meta">1215                    <span class="peach-search-counter">1216                      {entries().length > 01217                        ? `${selectedIndex() + 1} / ${entries().length}`1218                        : "0 entries"}1219                    </span>1220                    <span class="peach-divider"></span>1221                    <button1222                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1223                      onClick={() => navigate(-1)}1224                      aria-label="Previous entry"1225                      disabled={entries().length === 0}1226                    >1227                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1228                        <path d="M5 1L1 5.5L5 10" />1229                      </svg>1230                    </button>1231                    <button1232                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1233                      onClick={() => navigate(1)}1234                      aria-label="Next entry"1235                      disabled={entries().length === 0}1236                    >1237                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1238                        <path d="M1 1L5 5.5L1 10" />1239                      </svg>1240                    </button>1241                  </div>1242                </div>1243              </section>1244            </div>12451246            <Show when={view() === "list"}>1247              <VaultView1248                entries={entries()}1249                selectedEntryId={selectedEntry()?.id}1250                currentTabDomain={currentTabDomain()}1251                sortOrder={sortOrder()}1252                searchSeed={listSearchSeed()}1253                searchSeedNonce={listSearchSeedNonce()}1254                onSelectEntry={handleSelectEntry}1255                onSortOrderChange={setSortOrder}1256                onAdd={handleAdd}1257                onClose={() => setView("entry")}1258                onOpenTrash={() => setView("trash")}1259                onDeleteMany={handleDeleteMany}1260              />1261            </Show>1262            <Show when={view() === "settings"}>1263              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1264                <SettingsView1265                  entriesCount={entries().length}1266                  breachMonitoring={breachMonitoring()}1267                  lockOnClose={lockOnClose()}1268                  autoLockMinutes={autoLockMinutes()}1269                  trashRetentionDays={trashRetentionDays()}1270                  theme={theme()}1271                  accentColor={accentColor()}1272                  displayFont={displayFont()}1273                  textSize={textSize()}1274                  reduceMotion={reduceMotion()}1275                  isPro={proStatus()}1276                  initialSection={settingsInitialSection()}1277                  upgradeHighlight={upgradeHighlight()}1278                  onBreachMonitoringChange={applyBreachMonitoring}1279                  onLockOnCloseChange={applyLockOnClose}1280                  onAutoLockMinutesChange={applyAutoLockMinutes}1281                  onTrashRetentionChange={applyTrashRetention}1282                  onThemeChange={applyTheme}1283                  onAccentChange={applyAccentColor}1284                  onDisplayFontChange={applyDisplayFont}1285                  onTextSizeChange={applyTextSize}1286                  onReduceMotionChange={applyReduceMotion}1287                  shortcuts={shortcutBindings()}1288                  onShortcutsChange={applyShortcuts}1289                  onLicenseChange={async () => {1290                    // After activation/deactivation: refresh Pro status,1291                    // re-load entries (defensive — signal state can drift if1292                    // the SW briefly restarts during the verify+save round-trip),1293                    // and replay the Pro celebration if this is the first time1294                    // a valid Pro license is seen on this device.1295                    await refreshProStatus();1296                    void loadEntries();1297                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1298                    if ((should as { ok: boolean; data?: boolean }).data === true) {1299                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1300                      setView("pro-celebration");1301                      window.setTimeout(() => setView("settings"), 2500);1302                    }1303                  }}1304                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1305                  onImport={() => setView("import")}1306                  onExport={() => setView("export")}1307                  onBreachCheckDone={loadEntries}1308                  onOpenHealth={openHealth}1309                  onOpenSyncPairing={() => setView("sync-pairing")}1310                  onOpenFileImport={handleOpenFileImport}1311                  onOpenPanic={() => setView("panic")}1312                />1313              </Suspense>1314            </Show>1315            <Show when={view() === "sync-pairing"}>1316              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1317                <SyncPairingView1318                  onClose={() => setView("settings")}1319                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1320                />1321              </Suspense>1322            </Show>1323            <Show when={view() === "add"}>1324              <AddView1325                entry={editEntry()}1326                entries={entries()}1327                onBack={handleBack}1328                onSave={handleSave}1329              />1330            </Show>1331            <Show when={view() === "import"}>1332              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1333                <ImportView onBack={handleBack} onImport={handleSave} />1334              </Suspense>1335            </Show>1336            <Show when={view() === "export"}>1337              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1338                <ExportView1339                  onBack={() => {1340                    if (returnToPanic()) {1341                      setReturnToPanic(false);1342                      setView("panic");1343                    } else {1344                      handleBack();1345                    }1346                  }}1347                />1348              </Suspense>1349            </Show>1350            <Show when={view() === "panic"}>1351              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1352                <PanicView1353                  onCancel={() => setView("settings")}1354                  onOpenExport={() => {1355                    setReturnToPanic(true);1356                    setView("export");1357                  }}1358                  onDestroyed={async () => {1359                    clearCanarySuppressions();1360                    setEntries([]);1361                    setSelectedEntry(null);1362                    setEditEntry(undefined);1363                    setHasVault(false);1364                    setOnboarded(false);1365                    setProStatus(false);1366                    setPendingPasskey(null);1367                    setUpgradeHighlight(null);1368                    setSettingsInitialSection(null);1369                    setPendingProNotice(null);1370                    setPendingCelebration(false);1371                    setReturnToPanic(false);1372                    setContentPhase("idle");1373                    setView("lock");1374                  }}1375                />1376              </Suspense>1377            </Show>1378            <Show when={view() === "health"}>1379              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1380                <HealthView1381                  entries={entries()}1382                  isPro={proStatus()}1383                  onFixEntry={handleFixEntry}1384                  onBack={() => setView("settings")}1385                  onRefresh={loadEntries}1386                />1387              </Suspense>1388            </Show>1389            <Show when={view() === "trash"}>1390              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1391                <TrashView1392                  onBack={() => setView("list")}1393                  onRestored={() => void loadEntries()}1394                />1395              </Suspense>1396            </Show>1397            <Show when={restoreView() === "file"}>1398              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1399                <ImportView1400                  mode="onboarding"1401                  replacesExistingVault={true}1402                  onBack={() => setRestoreView(null)}1403                  onImport={async () => {1404                    setRestoreView(null);1405                    await handleUnlock();1406                  }}1407                />1408              </Suspense>1409            </Show>1410            </section>1411            </Show>1412          </Show>1413        </Show>1414      </Show>1415      <Show when={showShortcutsHelp()}>1416        <ShortcutsHelpOverlay1417          bindings={shortcutBindings()}1418          onClose={() => setShowShortcutsHelp(false)}1419        />1420      </Show>1421    </div>1422  );1423}14241425function ShortcutsHelpOverlay(props: {1426  bindings: Record<ShortcutAction, Keybinding>;1427  onClose: () => void;1428}) {1429  return (1430    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1431      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1432        <div class="peach-shortcuts-help-head">1433          <h3>Keyboard shortcuts</h3>1434          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1435        </div>1436        <div class="peach-shortcuts-help-body">1437          <p class="peach-settings-sub-label">ENTRY VIEW</p>1438          <ul>1439            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1440              <li>1441                <span>{d.label}</span>1442                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1443              </li>1444            ))}1445          </ul>1446          <p class="peach-settings-sub-label">ANYWHERE</p>1447          <ul>1448            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1449              <li>1450                <span>{d.label}</span>1451                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1452              </li>1453            ))}1454          </ul>1455        </div>1456      </div>1457    </div>1458  );1459}