App.tsx

58.0 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { App as CapacitorApp } from "@capacitor/app";3import { Capacitor, registerPlugin } from "@capacitor/core";4import { Keyboard } from "@capacitor/keyboard";5import { StatusBar, Style } from "@capacitor/status-bar";6import { storageGet, storageSet } from "../shared/storage";7import { sendMessage } from "../shared/bridge";8import { clearInMemoryVault, publishInMemoryVault } from "../shared/in-memory-vault";9import { ACCENT_COLORS } from "../shared/types";10import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";11import type { IncomingPairingRequest } from "../shared/sync-types";12import { isPasskeyOnly } from "../shared/types";13import { LockView } from "./views/Lock";14import { Onboarding } from "./views/Onboarding";15import { ProCelebration } from "./views/ProCelebration";16import { VaultView, type SortOrder } from "./views/Vault";17import { EntryView } from "./views/Entry";18import { AddView } from "./views/Add";19import { PeachWordmark } from "./components/PeachMark";20import { PasskeyApprovalView } from "./views/PasskeyApproval";21import { extractDomain } from "../shared/domain";22import { popupCopy } from "./copy";23import {24  DEFAULT_BINDINGS,25  formatKeybinding,26  getActiveBindings,27  matchKeybinding,28  SHORTCUT_DESCRIPTORS,29  type Keybinding,30  type ShortcutAction,31} from "../shared/shortcuts";32import { generateTOTP } from "../crypto/totp";3334export { sendMessage } from "../shared/bridge";3536const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));37const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));38const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));39const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));40const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));41const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));42const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));4344const Autofill = registerPlugin<{45  checkPendingSave(): Promise<{ pending: string | null }>;46  openAutofillSettings(): Promise<void>;47  isEnabledAsAutofillService(): Promise<{ enabled: boolean }>;48}>("Autofill");4950type View =51  | "lock"52  | "pro-celebration"53  | "entry"54  | "list"55  | "add"56  | "settings"57  | "sync-pairing"58  | "import"59  | "export"60  | "health"61  | "trash"62  | "panic";63type BootState = "loading" | "ready";6465const canarySuppressMap = new Map<string, boolean>();66let shellRingAnimation: Animation | null = null;6768export function isCanarySuppressed(entryId: string): boolean {69  return canarySuppressMap.get(entryId) ?? false;70}7172export function setCanarySuppressed(entryId: string, suppressed: boolean): void {73  canarySuppressMap.set(entryId, suppressed);74}7576export function clearCanarySuppressions(): void {77  canarySuppressMap.clear();78}7980export function triggerRing() {81  const shell = document.getElementById("hd-shell");82  if (!shell) return;8384  shellRingAnimation?.cancel();85  shell.dataset.glowing = "true";86  const animation = shell.animate(87    [88      { offset: 0, boxShadow: "var(--copy-shadow)" },89      {90        offset: 0.3,91        boxShadow:92          "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)",93      },94      { offset: 1, boxShadow: "var(--copy-shadow)" },95    ],96    {97      duration: 720,98      easing: "cubic-bezier(0.4, 0, 0.2, 1)",99      fill: "none",100    }101  );102  shellRingAnimation = animation;103  const clearGlow = () => {104    if (shellRingAnimation !== animation) return;105    shellRingAnimation = null;106    delete shell.dataset.glowing;107  };108  animation.onfinish = clearGlow;109  animation.oncancel = clearGlow;110}111112113export function triggerPipPulse() {114  const pip = document.querySelector(".peach-status-pip, .pip");115  if (pip) {116    pip.classList.remove("pulse");117    void (pip as HTMLElement).offsetWidth;118    pip.classList.add("pulse");119  }120}121122const ENTRY_TRANSITION_EXIT_MS = 95;123const ENTRY_TRANSITION_SETTLE_MS = 135;124125export default function App() {126  const [bootState, setBootState] = createSignal<BootState>("loading");127  const [view, setView] = createSignal<View>("lock");128  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(129    "enter"130  );131  const [contentTransitioning, setContentTransitioning] = createSignal(false);132  const [hasVault, setHasVault] = createSignal(false);133  const [onboarded, setOnboarded] = createSignal(true);134  const [entries, setEntries] = createSignal<VaultEntry[]>([]);135  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);136  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);137  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");138  const [theme, setTheme] = createSignal<"dark" | "light">("dark");139  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");140  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");141  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);142  const [lockOnClose, setLockOnClose] = createSignal(true);143  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);144  const [breachMonitoring, setBreachMonitoring] = createSignal(true);145  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);146  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);147  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);148  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);149  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);150  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");151  // Cached Pro status — synchronous for render paths. Background's152  // GET_LICENSE is async, but render-time reads of isPro() must not block.153  // Refreshed at boot, after activate/deactivate, and whenever the popup154  // re-opens onto a stored license that has changed via another window.155  const [proStatus, setProStatus] = createSignal(false);156  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);157  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);158  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");159  const [listSearchSeed, setListSearchSeed] = createSignal("");160  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);161  const [pendingCelebration, setPendingCelebration] = createSignal(false);162  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);163  const [pendingAutofillSave, setPendingAutofillSave] = createSignal<{164    domain: string;165    username: string;166    password: string;167  } | null>(null);168  const [backExitNotice, setBackExitNotice] = createSignal(false);169  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);170  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);171  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);172  const [incomingPairTick, setIncomingPairTick] = createSignal(0);173  const incomingPairSecondsLeft = () => {174    void incomingPairTick();175    const req = incomingPair();176    if (!req) return 0;177    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));178  };179  // True while Panic Step 1 has bounced the user out to Export. When Export's180  // onBack fires we return to Panic instead of Settings so the user keeps the181  // destruction context they came from.182  const [returnToPanic, setReturnToPanic] = createSignal(false);183184  let contentPhaseTimer: number | undefined;185  let lastBackExitAt = 0;186187  function applyAccent(name: AccentColorName) {188    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;189    const hex = color.hex;190    document.documentElement.style.setProperty("--peach-accent", hex);191    // Ambient surface variables — derived from the accent so surfaces shift192    // subtly toward the accent hue rather than staying fixed warm-brown.193    document.documentElement.style.setProperty("--peach-glow", hex + "2A");194    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");195    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");196  }197198  createEffect(() => {199    applyAccent(accentColor());200  });201202  createEffect(() => {203    document.documentElement.classList.toggle("light", theme() === "light");204    document.body.classList.toggle("light", theme() === "light");205    if (Capacitor.isNativePlatform()) {206      void applyMobileStatusBar(theme());207    }208  });209210  createEffect(() => {211    document.documentElement.setAttribute("data-display-font", displayFont());212  });213214  createEffect(() => {215    document.documentElement.setAttribute("data-text-size", textSize());216  });217218  createEffect(() => {219    if (reduceMotion()) {220      document.documentElement.setAttribute("data-motion", "reduce");221    } else {222      document.documentElement.removeAttribute("data-motion");223    }224  });225226  const selectedIndex = createMemo(() => {227    const currentId = selectedEntry()?.id;228    if (!currentId) return entries().length > 0 ? 0 : -1;229    return entries().findIndex((entry) => entry.id === currentId);230  });231232  async function applyAccentColor(name: AccentColorName) {233    applyAccent(name);234    setAccentColor(name);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });236  }237238  async function applyTheme(t: "dark" | "light") {239    setTheme(t);240    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });241  }242243  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {244    setDisplayFont(f);245    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });246  }247248  async function applyTextSize(size: "small" | "medium" | "large") {249    setTextSize(size);250    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });251  }252253  async function applyReduceMotion(enabled: boolean) {254    setReduceMotion(enabled);255    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });256  }257258  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload259  // small and lets future default updates land for actions the user hasn't260  // touched. Settings sends us the full active map; we filter and store.261  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {262    setShortcutBindings(active);263    const overrides: Record<string, Keybinding> = {};264    for (const action of Object.keys(active) as ShortcutAction[]) {265      const a = active[action];266      const d = DEFAULT_BINDINGS[action];267      const same = a.key === d.key268        && Boolean(a.ctrl)  === Boolean(d.ctrl)269        && Boolean(a.meta)  === Boolean(d.meta)270        && Boolean(a.shift) === Boolean(d.shift)271        && Boolean(a.alt)   === Boolean(d.alt);272      if (!same) overrides[action] = a;273    }274    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });275  }276277  async function applyLockOnClose(enabled: boolean) {278    setLockOnClose(enabled);279    await sendMessage({280      type: "UPDATE_SETTINGS",281      payload: { lockOnClose: enabled },282    });283  }284285  async function applyAutoLockMinutes(minutes: number) {286    setAutoLockMinutes(minutes);287    await sendMessage({288      type: "UPDATE_SETTINGS",289      payload: { autoLockMinutes: minutes },290    });291  }292293  async function applyBreachMonitoring(enabled: boolean) {294    setBreachMonitoring(enabled);295    await sendMessage({296      type: "UPDATE_SETTINGS",297      payload: { breachMonitoring: enabled },298    });299  }300301  async function applyMobileStatusBar(nextTheme: "dark" | "light") {302    try {303      await StatusBar.setStyle({ style: nextTheme === "light" ? Style.Light : Style.Dark });304      await StatusBar.setBackgroundColor({305        color: nextTheme === "light" ? "#EEE3CC" : "#0C0A06",306      });307    } catch {308      // Status bar APIs are available only in the native shell.309    }310  }311312  function handleBackNavigation() {313    if (showShortcutsHelp()) {314      setShowShortcutsHelp(false);315      return;316    }317    if (restoreView() !== null) {318      setRestoreView(null);319      return;320    }321322    switch (view()) {323      case "list":324        setView("entry");325        return;326      case "settings":327      case "add":328      case "import":329        handleBack();330        return;331      case "export":332        if (returnToPanic()) {333          setReturnToPanic(false);334          setView("panic");335        } else {336          handleBack();337        }338        return;339      case "health":340      case "panic":341      case "sync-pairing":342        setView("settings");343        return;344      case "trash":345        setView("list");346        return;347      case "entry": {348        const now = Date.now();349        if (now - lastBackExitAt < 1600) {350          void CapacitorApp.exitApp();351          return;352        }353        lastBackExitAt = now;354        setBackExitNotice(true);355        window.setTimeout(() => setBackExitNotice(false), 1400);356        return;357      }358      default:359        void CapacitorApp.exitApp();360    }361  }362363  onMount(async () => {364    if (Capacitor.isNativePlatform()) {365      document.body.classList.add("peach-mobile");366      document.documentElement.classList.add("peach-mobile-root");367      void applyMobileStatusBar(theme());368369      const keyboardShow = await Keyboard.addListener("keyboardWillShow", (info) => {370        document.body.style.paddingBottom = `${info.keyboardHeight}px`;371      });372      const keyboardHide = await Keyboard.addListener("keyboardWillHide", () => {373        document.body.style.paddingBottom = "0";374      });375      const backButton = await CapacitorApp.addListener("backButton", () => {376        handleBackNavigation();377      });378379      let touchStartX = 0;380      let touchStartY = 0;381      const handleTouchStart = (event: TouchEvent) => {382        const touch = event.touches[0];383        if (!touch) return;384        touchStartX = touch.clientX;385        touchStartY = touch.clientY;386      };387      const handleTouchEnd = (event: TouchEvent) => {388        const touch = event.changedTouches[0];389        if (!touch) return;390        const dx = touch.clientX - touchStartX;391        const dy = Math.abs(touch.clientY - touchStartY);392        if (touchStartX < 30 && dx > 60 && dy < 40) {393          handleBackNavigation();394        }395      };396      document.addEventListener("touchstart", handleTouchStart, { passive: true });397      document.addEventListener("touchend", handleTouchEnd, { passive: true });398399      onCleanup(() => {400        void keyboardShow.remove();401        void keyboardHide.remove();402        void backButton.remove();403        document.removeEventListener("touchstart", handleTouchStart);404        document.removeEventListener("touchend", handleTouchEnd);405        document.body.style.paddingBottom = "0";406      });407    }408409    // Resolve the active tab in parallel with the unlock/has-vault queries —410    // openVault()'s smart selection picks the entry matching currentTabDomain,411    // so it must be populated before openVault runs. Previously refreshCurrentTab412    // ran after openVault, leaving popups that booted already-unlocked falling413    // back to loadedEntries[0] instead of the domain match.414    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([415      sendMessage({ type: "IS_UNLOCKED" }),416      sendMessage({ type: "HAS_VAULT" }),417      refreshCurrentTab(),418      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),419    ]);420    const unlocked = Boolean(421      (unlockResponse as { ok: boolean; data?: boolean }).data422    );423    const vaultExists = Boolean(424      (vaultResponse as { ok: boolean; data?: boolean }).data425    );426    const shouldCelebrate = Boolean(427      (celebrationResponse as { ok: boolean; data?: boolean }).data428    );429    setHasVault(vaultExists);430    // Onboarding gate — show once on first install, never again. Existing431    // users (vaultExists) are auto-marked onboarded so they skip the flow432    // even on the very first popup open after this feature ships.433    try {434      const onboarded = await storageGet("peach_onboarded");435      const seen = onboarded === "true";436      if (vaultExists && !seen) {437        await storageSet("peach_onboarded", "true");438        setOnboarded(true);439      } else {440        setOnboarded(seen);441      }442    } catch {443      // storage unavailable — default to onboarded so we never block boot444      setOnboarded(true);445    }446    await Promise.all([restoreSettings(), refreshProStatus()]);447448    // Mark played before any animation so a crash mid-sequence never replays it449    if (shouldCelebrate) {450      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });451    }452453    if (unlocked && vaultExists) {454      await openVault(undefined, shouldCelebrate);455      if (shouldCelebrate) {456        setView("pro-celebration");457        window.setTimeout(() => setView("entry"), 2500);458      }459    } else if (shouldCelebrate) {460      setPendingCelebration(true);461    }462463    await refreshPendingPasskey();464    await refreshIncomingPairing();465    await consumeRecentPairing();466467    // Track tab changes so smart sort stays current468    if (!Capacitor.isNativePlatform()) {469      const handleTabActivated = () => { void refreshCurrentTab(); };470      const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {471        if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();472      };473      try {474        chrome.tabs.onActivated.addListener(handleTabActivated);475        chrome.tabs.onUpdated.addListener(handleTabUpdated);476        onCleanup(() => {477          chrome.tabs.onActivated.removeListener(handleTabActivated);478          chrome.tabs.onUpdated.removeListener(handleTabUpdated);479        });480      } catch {481        // tabs permission may not be available in all contexts482      }483    }484485    setBootState("ready");486    document.getElementById("pre-lock")?.setAttribute("hidden", "true");487488    // Check for pending session-storage notices from the background.489    if (!Capacitor.isNativePlatform() && chrome.storage.session) {490      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as491        Record<string, { feature?: string } | undefined>;492      if (session.pendingProGate?.feature) {493        await chrome.storage.session.remove("pendingProGate");494        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);495        setSettingsInitialSection("license");496        setView("settings");497      } else if (session.pendingProNotice?.feature) {498        await chrome.storage.session.remove("pendingProNotice");499        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });500      }501    }502503    if (Capacitor.getPlatform() === "android") {504      try {505        const { pending } = await Autofill.checkPendingSave();506        if (pending) {507          const parsed = JSON.parse(pending) as {508            domain?: string;509            username?: string;510            password?: string;511          };512          if (parsed.username && parsed.password) {513            setPendingAutofillSave({514              domain: parsed.domain ?? "",515              username: parsed.username,516              password: parsed.password,517            });518          }519        }520      } catch {521        // Pending autofill saves are opportunistic; boot must continue.522      }523    }524525    // Warm the lazy-module cache so the Suspense fallback never shows for526    // locally-bundled extension views. Without this, the first navigation to527    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which528    // covers the shell and absorbs clicks on the header.529    void Promise.all([530      import("./views/Settings").catch(() => {}),531      import("./views/Import").catch(() => {}),532      import("./views/Export").catch(() => {}),533      import("./views/Health").catch(() => {}),534      import("./views/TrashView").catch(() => {}),535    ]);536537    // Lock-on-close via a persistent port. sendMessage in pagehide is538    // unreliable — the popup context tears down before the message lands.539    // The SW's onConnect listener locks when this port disconnects.540    if (!Capacitor.isNativePlatform()) {541      let popupPort: chrome.runtime.Port | null = null;542      try {543        popupPort = chrome.runtime.connect({ name: "popup" });544      } catch { /* extension context invalidated — ignore */ }545      onCleanup(() => { try { popupPort?.disconnect(); } catch {} });546547      // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale548      // entries instead of waiting for the next GET_ENTRIES round-trip.549      const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {550        if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();551        if (msg?.type === "PRO_GATE_TRIGGERED") {552          setUpgradeHighlight(msg.payload?.feature ?? null);553          setSettingsInitialSection("license");554          setView("settings");555        }556        if (msg?.type === "INCOMING_PAIRING_REQUEST") {557          void refreshIncomingPairing();558        }559      };560      chrome.runtime.onMessage.addListener(handleRuntimeMessage);561      onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));562    }563564    // Action handlers — keyed by ShortcutAction. The dispatcher below tests565    // each binding against the event and runs the matching handler. New566    // shortcuts only need an entry here; the binding is data, not code.567    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {568      copy_password: () => {569        const entry = selectedEntry();570        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });571      },572      copy_username: () => {573        const entry = selectedEntry();574        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });575      },576      copy_totp: () => {577        const entry = selectedEntry();578        if (!entry?.totp) return;579        try {580          const { code } = generateTOTP(entry.totp);581          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });582        } catch { /* invalid TOTP secret — silent */ }583      },584      new_entry: () => handleAdd(),585      edit_entry: () => {586        const entry = selectedEntry();587        // Passkey-only entries have nothing user-editable in the Add view; the588        // passkey credential itself is opaque. Skip the edit action for them.589        if (!entry || isPasskeyOnly(entry)) return;590        setEditEntry(entry);591        setView("add");592      },593      delete_entry: () => {594        if (selectedEntry()) void handleDelete();595      },596      lock_vault: () => { void handleHeaderLock(); },597      search: () => openList(),598      nav_prev: () => navigate(-1),599      nav_next: () => navigate(1),600      jump_vault: () => setView("entry"),601      jump_settings: () => setView("settings"),602      show_help: () => setShowShortcutsHelp(true),603    };604605    // Actions that are MEANINGFUL only on the entry-detail view. Outside606    // that scope the binding is dormant — pressing C while on Settings607    // does nothing rather than awkwardly copying from a now-stale entry.608    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([609      "copy_password", "copy_username", "copy_totp",610      "edit_entry", "delete_entry", "nav_prev", "nav_next",611    ]);612613    const handleGlobalKeydown = (e: KeyboardEvent) => {614      const v = view();615      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"616        || (e.target as HTMLElement)?.tagName === "TEXTAREA"617        || (e.target as HTMLElement)?.isContentEditable;618      const isPrintableSearchKey =619        e.key.length === 1 &&620        !e.ctrlKey &&621        !e.metaKey &&622        !e.altKey;623624      // No input during the pro celebration sequence625      if (v === "pro-celebration") return;626627      // Help dialog: Escape closes it; eat the keypress so it doesn't628      // also navigate away from the underlying view.629      if (showShortcutsHelp()) {630        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }631        return;632      }633634      // ── Escape — fixed binding (not user-customizable) ───────635      if (e.key === "Escape") {636        if (v === "list") { setView("entry"); return; }637        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }638        if (v === "sync-pairing") { setView("settings"); return; }639      }640641      // Bindings-driven dispatch. Single-key letter bindings without642      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is643      // inside an input, so users can type into search/forms normally.644      const bindings = shortcutBindings();645      for (const action of Object.keys(bindings) as ShortcutAction[]) {646        const binding = bindings[action];647        if (!matchKeybinding(e, binding)) continue;648        // Single-key letter bindings need the input-focus guard. Bindings649        // with any modifier are safe — Ctrl+L doesn't conflict with typing.650        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;651        if (!hasMod && binding.key.length === 1 && inInput) return;652        if (ENTRY_SCOPED.has(action) && v !== "entry") return;653        e.preventDefault();654        SHORTCUT_HANDLERS[action]?.();655        return;656      }657658      // Type-to-search: in entry view, any printable key not consumed by a659      // shortcut above primes the list search seed and opens the list.660      // Kept outside the bindings table because it's a behavior, not a661      // discrete action — every printable character can trigger it.662      if (v === "entry" && !inInput && isPrintableSearchKey) {663        e.preventDefault();664        primeListSearch(e.key);665        return;666      }667    };668    window.addEventListener("keydown", handleGlobalKeydown);669    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));670671    if (!Capacitor.isNativePlatform()) {672      const handleStorageChanged = (673        changes: Record<string, chrome.storage.StorageChange>,674        areaName: string675      ) => {676        if (areaName !== "session") return;677        if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {678          return;679        }680        void refreshPendingPasskey();681      };682      chrome.storage.onChanged.addListener(handleStorageChanged);683      onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));684    }685  });686687  async function refreshCurrentTab() {688    if (Capacitor.isNativePlatform()) return;689    try {690      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });691      const url = tab?.url ?? tab?.pendingUrl ?? "";692      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");693    } catch {694      setCurrentTabDomain("");695    }696  }697698  async function refreshPendingPasskey() {699    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });700    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);701  }702703  async function refreshIncomingPairing() {704    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });705    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;706    setIncomingPair(data);707  }708709  // Drains a single one-shot record left by the background when 6-digit710  // pairing succeeded while the popup was closed (or the SyncPairing view was711  // navigated away from before it could show its own success card).712  async function consumeRecentPairing() {713    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });714    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;715    if (data?.deviceName) {716      setRecentPairToast(data.deviceName);717      window.setTimeout(() => setRecentPairToast(null), 4000);718    }719  }720721  async function respondIncomingPairing(accept: boolean) {722    if (incomingPairResponding()) return;723    setIncomingPairResponding(true);724    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });725    setIncomingPair(null);726    setIncomingPairResponding(false);727  }728729  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a730  // request appears, ticks once per second, and clears the banner if the731  // request expires while the popup is open.732  createEffect(() => {733    const req = incomingPair();734    if (!req) return;735    const handle = window.setInterval(() => {736      setIncomingPairTick((tick) => tick + 1);737      if (Date.now() >= req.expiresAt) {738        setIncomingPair(null);739        window.clearInterval(handle);740      }741    }, 1000);742    onCleanup(() => window.clearInterval(handle));743  });744745  async function refreshProStatus() {746    const res = await sendMessage({ type: "GET_LICENSE" });747    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;748    setProStatus(Boolean(data?.valid && data?.plan === "pro"));749  }750751  async function restoreSettings() {752    const res = await sendMessage({ type: "GET_SETTINGS" });753    const s = (res as { ok: boolean; data?: any }).data ?? {};754    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {755      setAccentColor(s.accentColor as AccentColorName);756    }757    setTheme(s.theme === "light" ? "light" : "dark");758    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {759      setDisplayFont(s.displayFont);760    } else {761      setDisplayFont("cormorant-italic");762    }763    if (s.textSize === "small" || s.textSize === "large") {764      setTextSize(s.textSize);765    } else {766      setTextSize("medium");767    }768    setReduceMotion(s.reduceMotion === true);769    setLockOnClose(s.lockOnClose !== false);770    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);771    setBreachMonitoring(s.breachMonitoring !== false);772    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);773    setShortcutBindings(getActiveBindings(s.shortcuts));774  }775776  async function applyTrashRetention(days: number) {777    setTrashRetentionDays(days);778    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });779  }780781  function primeListSearch(seed: string) {782    setListSearchSeed(seed);783    setListSearchSeedNonce((value) => value + 1);784    openList();785  }786787  // Returns null when it detected a dead service worker and triggered handleLock().788  // Callers that need to abort (e.g. openVault) check for null rather than relying789  // on view() state, which may already be "lock" during normal startup flows.790  async function loadEntries(): Promise<VaultEntry[] | null> {791    const response = await sendMessage({ type: "GET_ENTRIES" });792    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };793794    // If the service worker was killed and restarted (MV3 workers sleep), the795    // vault will be locked again — or the worker may not respond at all.796    // In either case, send the user to the lock screen rather than silently797    // showing an empty vault (which looks like data loss).798    if (!res.ok) {799      if (800        res.error === "vault locked" ||801        res.error === "SERVICE_WORKER_UNAVAILABLE" ||802        (typeof res.error === "string" && res.error.includes("locked"))803      ) {804        handleLock();805        return null; // signal emergency lock to callers806      }807      return [];808    }809810    const loadedEntries = res.data ?? [];811    setEntries(loadedEntries);812    void publishInMemoryVault(loadedEntries);813814    const currentId = selectedEntry()?.id;815    if (currentId) {816      setSelectedEntry(817        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null818      );819    }820821    return loadedEntries;822  }823824  async function openVault(preferredEntryId?: string, skipViewSet = false) {825    // Purge expired trash entries on each vault open826    const retDays = trashRetentionDays();827    if (retDays > 0) {828      void sendMessage({829        type: "PURGE_EXPIRED_TRASH",830        payload: { retentionMs: retDays * 86_400_000 },831      });832    }833834    const loadedEntries = await loadEntries();835836    // null means loadEntries() triggered an emergency lock (service worker died).837    // Don't override it by setting view back to "entry" with an empty vault.838    if (loadedEntries === null) return;839840    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry841    let nextSelectedEntry: VaultEntry | null = null;842    if (preferredEntryId) {843      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;844    }845    if (!nextSelectedEntry) {846      const tabDomain = currentTabDomain();847      if (tabDomain) {848        nextSelectedEntry = loadedEntries.find((e) => {849          if (e.type === "login") {850            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;851            for (const extra of e.additionalUrls ?? []) {852              if ((extractDomain(extra) ?? "") === tabDomain) return true;853            }854            return false;855          }856          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;857          return false;858        }) ?? null;859      }860    }861    nextSelectedEntry ??= loadedEntries[0] ?? null;862863    setSelectedEntry(nextSelectedEntry);864    setEditEntry(undefined);865    setContentTransitioning(false);866    setContentPhase("enter");867    queueContentIdle();868    if (!skipViewSet) setView("entry");869  }870871  async function handleUnlock() {872    setHasVault(true);873    triggerPipPulse();874    await restoreSettings();875    const celebrating = pendingCelebration();876    if (celebrating) {877      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });878      setPendingCelebration(false);879    }880    await openVault(undefined, celebrating);881    if (celebrating) {882      setView("pro-celebration");883      window.setTimeout(() => setView("entry"), 2500);884    }885  }886887  function handleSelectEntry(entry: VaultEntry) {888    setSelectedEntry(entry);889    setContentTransitioning(false);890    setContentPhase("enter");891    queueContentIdle();892    setView("entry");893  }894895  function handleAdd() {896    setEditEntry(undefined);897    setView("add");898  }899900  async function handleDelete() {901    const entry = selectedEntry();902    if (!entry) return;903    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });904    const loadedEntries = await loadEntries() ?? [];905    setSelectedEntry(loadedEntries[0] ?? null);906    setView("entry");907  }908909  async function handleDeleteMany(ids: string[]) {910    for (const id of ids) {911      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });912    }913    const loadedEntries = await loadEntries() ?? [];914    // If the currently selected entry was among the deleted, move to first915    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);916    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);917  }918919  async function handleSave(savedEntry?: VaultEntry) {920    await openVault(savedEntry?.id);921  }922923  async function savePendingAutofill() {924    const pending = pendingAutofillSave();925    if (!pending) return;926    const domain = pending.domain.trim();927    const response = await sendMessage({928      type: "ADD_ENTRY",929      payload: {930        type: "login",931        title: domain || "Saved login",932        url: domain ? `https://${domain}` : "",933        username: pending.username,934        password: pending.password,935      },936    });937    if ((response as { ok: boolean }).ok) {938      setPendingAutofillSave(null);939      await openVault((response as { data?: VaultEntry }).data?.id);940    }941  }942943  function handleBack() {944    setEditEntry(undefined);945    setView("entry");946  }947948  function handleLock() {949    clearCanarySuppressions();950    setEntries([]);951    setSelectedEntry(null);952    setEditEntry(undefined);953    setContentPhase("idle");954    setView("lock");955    void clearInMemoryVault();956  }957958  function handleHeaderLock() {959    // Lock the UI immediately — do not wait for the service worker. If the SW960    // is dead or slow, the 5s sendMessage timeout would create a dead-click961    // window. The SW will lock on its next wake regardless.962    handleLock();963    void sendMessage({ type: "LOCK" });964  }965966  function navigate(dir: number) {967    const allEntries = entries();968    if (allEntries.length === 0) return;969    const currentIndex = selectedIndex();970    const baseIndex = currentIndex >= 0 ? currentIndex : 0;971    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;972    setSelectedEntry(allEntries[nextIndex]);973    setContentPhase("enter");974    queueContentIdle();975  }976977  function openList() {978    setView("list");979  }980981  function openHealth() {982    setEditEntry(undefined);983    setView("health");984  }985986  function handleOpenFileImport() {987    setRestoreView("file");988  }989990  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;991992  function handleFixEntry(entry: VaultEntry) {993    // Passkey-only entries have no editable surface — drop into view mode994    // instead of opening the Add editor.995    if (isPasskeyOnly(entry)) {996      setSelectedEntry(entry);997      setView("entry");998      return;999    }1000    setEditEntry(entry);1001    setView("add");1002  }10031004  const isLockedView = () => view() === "lock";10051006  async function handleApprovePendingPasskey() {1007    const pending = pendingPasskey();1008    if (!pending) return;1009    if (pending.browser === "firefox" && pending.type === "create") {1010      // Firefox path: popup itself runs navigator.credentials.create. The1011      // background never approved/rejected anything — it just stashed1012      // intent. After the popup-driven flow resolves (success or cancel),1013      // clear the pending key so the popup doesn't re-show this on next open.1014      const { createFirefoxPasskey } = await import("./firefox-passkey");1015      const result = await createFirefoxPasskey(pending);1016      if (!result.ok) {1017        console.warn("Peach Firefox passkey create failed:", result.error);1018      }1019      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1020      setPendingPasskey(null);1021      void loadEntries();1022      return;1023    }1024    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1025    setPendingPasskey(null);1026  }10271028  async function handleDenyPendingPasskey() {1029    const pending = pendingPasskey();1030    if (!pending) return;1031    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1032    setPendingPasskey(null);1033  }10341035  function queueContentIdle(after?: () => void) {1036    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1037    contentPhaseTimer = window.setTimeout(() => {1038      setContentPhase("idle");1039      after?.();1040    }, ENTRY_TRANSITION_SETTLE_MS);1041  }10421043  return (1044    <div class="popup-root peach-theme">1045      <Show when={bootState() === "ready"}>1046        <Show1047          when={!pendingPasskey()}1048          fallback={1049            <PasskeyApprovalView1050              type={pendingPasskey()!.type}1051              rpName={pendingPasskey()!.rpName}1052              rpId={pendingPasskey()!.rpId}1053              userName={pendingPasskey()!.userName}1054              userDisplayName={pendingPasskey()!.userDisplayName}1055              onApprove={handleApprovePendingPasskey}1056              onDeny={handleDenyPendingPasskey}1057            />1058          }1059        >1060          <Show1061            when={!isLockedView()}1062            fallback={1063              <Show1064                when={onboarded() || hasVault()}1065                fallback={1066                  <Onboarding1067                    onComplete={() => { setOnboarded(true); }}1068                  />1069                }1070              >1071                <LockView1072                  hasVault={hasVault()}1073                  ready={bootState() === "ready"}1074                  isPro={proStatus()}1075                  onUnlock={handleUnlock}1076                  onBackToOnboarding={1077                    !hasVault()1078                      ? () => setOnboarded(false)1079                      : undefined1080                  }1081                />1082              </Show>1083            }1084          >1085            <Show1086              when={view() !== "pro-celebration"}1087              fallback={<ProCelebration />}1088            >1089            <section1090              id="hd-shell"1091              class="peach-shell peach-theme"1092              data-surface="extension"1093            >1094            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1095              <PeachWordmark unlocked />1096              <div class="peach-chrome-actions">1097                <button1098                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1099                  onClick={() => setView("settings")}1100                  aria-label="Settings"1101                >1102                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1103                    <path1104                      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"1105                      stroke="currentColor"1106                      stroke-width="0.9"1107                    />1108                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1109                  </svg>1110                </button>1111                <button1112                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1113                  onClick={handleAdd}1114                  aria-label="New entry"1115                >1116                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1117                    <path d="M5.5 1v9M1 5.5h9" />1118                  </svg>1119                </button>1120                <button1121                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1122                  onClick={() => void handleHeaderLock()}1123                  aria-label="Lock vault"1124                >1125                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1126                    <path1127                      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"1128                      stroke="currentColor"1129                      stroke-width="1"1130                      stroke-linecap="round"1131                    />1132                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1133                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1134                  </svg>1135                </button>1136              </div>1137            </header>11381139            <Show when={recentPairToast()}>1140              <div class="peach-pair-toast" role="status" aria-live="polite">1141                Paired with <strong>{recentPairToast()}</strong>1142              </div>1143            </Show>11441145            <Show when={incomingPair() !== null}>1146              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1147                <div class="peach-pair-request-header">1148                  <span class="peach-pair-request-mark">🍑</span>1149                  <span class="peach-pair-request-title">Pairing request</span>1150                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1151                </div>1152                <p class="peach-pair-request-body">1153                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1154                </p>1155                <div class="peach-pair-request-actions">1156                  <button1157                    class="peach-btn peach-btn--ghost peach-btn--sm"1158                    onClick={() => void respondIncomingPairing(false)}1159                    disabled={incomingPairResponding()}1160                  >1161                    Reject1162                  </button>1163                  <button1164                    class="peach-btn peach-btn--accent peach-btn--sm"1165                    onClick={() => void respondIncomingPairing(true)}1166                    disabled={incomingPairResponding()}1167                  >1168                    Accept1169                  </button>1170                </div>1171              </div>1172            </Show>11731174            <Show when={pendingProNotice() !== null}>1175              <div class="peach-pro-notice-banner">1176                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1177                <button1178                  class="peach-pro-notice-link"1179                  onClick={() => {1180                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1181                    setSettingsInitialSection("license");1182                    setView("settings");1183                    setPendingProNotice(null);1184                  }}1185                >1186                  Learn more →1187                </button>1188                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1189              </div>1190            </Show>11911192            <Show when={pendingAutofillSave() !== null && !isLockedView()}>1193              <div class="peach-pro-notice-banner peach-autofill-save-banner">1194                <span>1195                  Save login{pendingAutofillSave()?.domain ? ` for ${pendingAutofillSave()!.domain}` : ""}?1196                </span>1197                <button1198                  class="peach-pro-notice-link"1199                  onClick={() => void savePendingAutofill()}1200                >1201                  Save1202                </button>1203                <button1204                  class="peach-pro-notice-close"1205                  onClick={() => setPendingAutofillSave(null)}1206                  aria-label="Dismiss"1207                >1208                  x1209                </button>1210              </div>1211            </Show>12121213            <Show when={backExitNotice()}>1214              <div class="peach-pro-notice-banner peach-back-exit-banner">1215                <span>Tap back again to exit Peach</span>1216              </div>1217            </Show>12181219            <div class="peach-shell-body">1220              <div class="peach-shell-veil"></div>1221              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1222                <EntryView1223                  entry={selectedEntry()}1224                  onDelete={handleDelete}1225                  onFieldSaved={() => void loadEntries()}1226                  onEscape={() => { setView("list"); }}1227                />1228              </div>12291230              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1231                <div class="peach-search-bar">1232                  <span class="peach-search-icon">1233                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1234                      <circle cx="5.5" cy="5.5" r="3.75" />1235                      <path d="M8.75 8.75L11.5 11.5" />1236                    </svg>1237                  </span>1238                  <input1239                    class="peach-search-input"1240                    placeholder="search vault..."1241                    autocomplete="off"1242                    aria-label="Search vault entries"1243                    onClick={openList}1244                    onFocus={openList}1245                    readOnly1246                  />1247                  <div class="peach-search-meta">1248                    <span class="peach-search-counter">1249                      {entries().length > 01250                        ? `${selectedIndex() + 1} / ${entries().length}`1251                        : "0 entries"}1252                    </span>1253                    <span class="peach-divider"></span>1254                    <button1255                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1256                      onClick={() => navigate(-1)}1257                      aria-label="Previous entry"1258                      disabled={entries().length === 0}1259                    >1260                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1261                        <path d="M5 1L1 5.5L5 10" />1262                      </svg>1263                    </button>1264                    <button1265                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1266                      onClick={() => navigate(1)}1267                      aria-label="Next entry"1268                      disabled={entries().length === 0}1269                    >1270                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1271                        <path d="M1 1L5 5.5L1 10" />1272                      </svg>1273                    </button>1274                  </div>1275                </div>1276              </section>1277            </div>12781279            <Show when={view() === "list"}>1280              <VaultView1281                entries={entries()}1282                selectedEntryId={selectedEntry()?.id}1283                currentTabDomain={currentTabDomain()}1284                sortOrder={sortOrder()}1285                searchSeed={listSearchSeed()}1286                searchSeedNonce={listSearchSeedNonce()}1287                onSelectEntry={handleSelectEntry}1288                onSortOrderChange={setSortOrder}1289                onAdd={handleAdd}1290                onClose={() => setView("entry")}1291                onOpenTrash={() => setView("trash")}1292                onDeleteMany={handleDeleteMany}1293              />1294            </Show>1295            <Show when={view() === "settings"}>1296              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1297                <SettingsView1298                  entriesCount={entries().length}1299                  breachMonitoring={breachMonitoring()}1300                  lockOnClose={lockOnClose()}1301                  autoLockMinutes={autoLockMinutes()}1302                  trashRetentionDays={trashRetentionDays()}1303                  theme={theme()}1304                  accentColor={accentColor()}1305                  displayFont={displayFont()}1306                  textSize={textSize()}1307                  reduceMotion={reduceMotion()}1308                  isPro={proStatus()}1309                  initialSection={settingsInitialSection()}1310                  upgradeHighlight={upgradeHighlight()}1311                  onBreachMonitoringChange={applyBreachMonitoring}1312                  onLockOnCloseChange={applyLockOnClose}1313                  onAutoLockMinutesChange={applyAutoLockMinutes}1314                  onTrashRetentionChange={applyTrashRetention}1315                  onThemeChange={applyTheme}1316                  onAccentChange={applyAccentColor}1317                  onDisplayFontChange={applyDisplayFont}1318                  onTextSizeChange={applyTextSize}1319                  onReduceMotionChange={applyReduceMotion}1320                  shortcuts={shortcutBindings()}1321                  onShortcutsChange={applyShortcuts}1322                  onLicenseChange={async () => {1323                    // After activation/deactivation: refresh Pro status,1324                    // re-load entries (defensive — signal state can drift if1325                    // the SW briefly restarts during the verify+save round-trip),1326                    // and replay the Pro celebration if this is the first time1327                    // a valid Pro license is seen on this device.1328                    await refreshProStatus();1329                    void loadEntries();1330                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1331                    if ((should as { ok: boolean; data?: boolean }).data === true) {1332                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1333                      setView("pro-celebration");1334                      window.setTimeout(() => setView("settings"), 2500);1335                    }1336                  }}1337                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1338                  onImport={() => setView("import")}1339                  onExport={() => setView("export")}1340                  onBreachCheckDone={loadEntries}1341                  onOpenHealth={openHealth}1342                  onOpenSyncPairing={() => setView("sync-pairing")}1343                  onOpenFileImport={handleOpenFileImport}1344                  onOpenPanic={() => setView("panic")}1345                />1346              </Suspense>1347            </Show>1348            <Show when={view() === "sync-pairing"}>1349              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1350                <SyncPairingView1351                  onClose={() => setView("settings")}1352                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1353                />1354              </Suspense>1355            </Show>1356            <Show when={view() === "add"}>1357              <AddView1358                entry={editEntry()}1359                entries={entries()}1360                onBack={handleBack}1361                onSave={handleSave}1362              />1363            </Show>1364            <Show when={view() === "import"}>1365              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1366                <ImportView onBack={handleBack} onImport={handleSave} />1367              </Suspense>1368            </Show>1369            <Show when={view() === "export"}>1370              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1371                <ExportView1372                  onBack={() => {1373                    if (returnToPanic()) {1374                      setReturnToPanic(false);1375                      setView("panic");1376                    } else {1377                      handleBack();1378                    }1379                  }}1380                />1381              </Suspense>1382            </Show>1383            <Show when={view() === "panic"}>1384              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1385                <PanicView1386                  onCancel={() => setView("settings")}1387                  onOpenExport={() => {1388                    setReturnToPanic(true);1389                    setView("export");1390                  }}1391                  onDestroyed={async () => {1392                    clearCanarySuppressions();1393                    setEntries([]);1394                    setSelectedEntry(null);1395                    setEditEntry(undefined);1396                    setHasVault(false);1397                    setOnboarded(false);1398                    setProStatus(false);1399                    setPendingPasskey(null);1400                    setUpgradeHighlight(null);1401                    setSettingsInitialSection(null);1402                    setPendingProNotice(null);1403                    setPendingCelebration(false);1404                    setReturnToPanic(false);1405                    setContentPhase("idle");1406                    setView("lock");1407                    void clearInMemoryVault();1408                  }}1409                />1410              </Suspense>1411            </Show>1412            <Show when={view() === "health"}>1413              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1414                <HealthView1415                  entries={entries()}1416                  isPro={proStatus()}1417                  onFixEntry={handleFixEntry}1418                  onBack={() => setView("settings")}1419                  onRefresh={loadEntries}1420                />1421              </Suspense>1422            </Show>1423            <Show when={view() === "trash"}>1424              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1425                <TrashView1426                  onBack={() => setView("list")}1427                  onRestored={() => void loadEntries()}1428                />1429              </Suspense>1430            </Show>1431            <Show when={restoreView() === "file"}>1432              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1433                <ImportView1434                  mode="onboarding"1435                  replacesExistingVault={true}1436                  onBack={() => setRestoreView(null)}1437                  onImport={async () => {1438                    setRestoreView(null);1439                    await handleUnlock();1440                  }}1441                />1442              </Suspense>1443            </Show>1444            </section>1445            </Show>1446          </Show>1447        </Show>1448      </Show>1449      <Show when={showShortcutsHelp()}>1450        <ShortcutsHelpOverlay1451          bindings={shortcutBindings()}1452          onClose={() => setShowShortcutsHelp(false)}1453        />1454      </Show>1455    </div>1456  );1457}14581459function ShortcutsHelpOverlay(props: {1460  bindings: Record<ShortcutAction, Keybinding>;1461  onClose: () => void;1462}) {1463  return (1464    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1465      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1466        <div class="peach-shortcuts-help-head">1467          <h3>Keyboard shortcuts</h3>1468          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1469        </div>1470        <div class="peach-shortcuts-help-body">1471          <p class="peach-settings-sub-label">ENTRY VIEW</p>1472          <ul>1473            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1474              <li>1475                <span>{d.label}</span>1476                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1477              </li>1478            ))}1479          </ul>1480          <p class="peach-settings-sub-label">ANYWHERE</p>1481          <ul>1482            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1483              <li>1484                <span>{d.label}</span>1485                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1486              </li>1487            ))}1488          </ul>1489        </div>1490      </div>1491    </div>1492  );1493}