App.tsx

58.4 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  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");152  // Cached Pro status — synchronous for render paths. Background's153  // GET_LICENSE is async, but render-time reads of isPro() must not block.154  // Refreshed at boot, after activate/deactivate, and whenever the popup155  // re-opens onto a stored license that has changed via another window.156  const [proStatus, setProStatus] = createSignal(false);157  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);158  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);159  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");160  const [listSearchSeed, setListSearchSeed] = createSignal("");161  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);162  const [pendingCelebration, setPendingCelebration] = createSignal(false);163  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);164  const [pendingAutofillSave, setPendingAutofillSave] = createSignal<{165    domain: string;166    username: string;167    password: string;168  } | null>(null);169  const [backExitNotice, setBackExitNotice] = createSignal(false);170  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);171  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);172  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);173  const [incomingPairTick, setIncomingPairTick] = createSignal(0);174  const incomingPairSecondsLeft = () => {175    void incomingPairTick();176    const req = incomingPair();177    if (!req) return 0;178    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));179  };180  // True while Panic Step 1 has bounced the user out to Export. When Export's181  // onBack fires we return to Panic instead of Settings so the user keeps the182  // destruction context they came from.183  const [returnToPanic, setReturnToPanic] = createSignal(false);184185  let contentPhaseTimer: number | undefined;186  let lastBackExitAt = 0;187188  function applyAccent(name: AccentColorName) {189    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;190    const hex = color.hex;191    document.documentElement.style.setProperty("--peach-accent", hex);192    // Ambient surface variables — derived from the accent so surfaces shift193    // subtly toward the accent hue rather than staying fixed warm-brown.194    document.documentElement.style.setProperty("--peach-glow", hex + "2A");195    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");196    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");197  }198199  createEffect(() => {200    applyAccent(accentColor());201  });202203  createEffect(() => {204    document.documentElement.classList.toggle("light", theme() === "light");205    document.body.classList.toggle("light", theme() === "light");206    if (Capacitor.isNativePlatform()) {207      void applyMobileStatusBar(theme());208    }209  });210211  createEffect(() => {212    document.documentElement.setAttribute("data-display-font", displayFont());213  });214215  createEffect(() => {216    document.documentElement.setAttribute("data-text-size", textSize());217  });218219  createEffect(() => {220    if (reduceMotion()) {221      document.documentElement.setAttribute("data-motion", "reduce");222    } else {223      document.documentElement.removeAttribute("data-motion");224    }225  });226227  const selectedIndex = createMemo(() => {228    const currentId = selectedEntry()?.id;229    if (!currentId) return entries().length > 0 ? 0 : -1;230    return entries().findIndex((entry) => entry.id === currentId);231  });232233  async function applyAccentColor(name: AccentColorName) {234    applyAccent(name);235    setAccentColor(name);236    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });237  }238239  async function applyTheme(t: "dark" | "light") {240    setTheme(t);241    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });242  }243244  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {245    setDisplayFont(f);246    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });247  }248249  async function applyTextSize(size: "small" | "medium" | "large") {250    setTextSize(size);251    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });252  }253254  async function applyReduceMotion(enabled: boolean) {255    setReduceMotion(enabled);256    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });257  }258259  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload260  // small and lets future default updates land for actions the user hasn't261  // touched. Settings sends us the full active map; we filter and store.262  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {263    setShortcutBindings(active);264    const overrides: Record<string, Keybinding> = {};265    for (const action of Object.keys(active) as ShortcutAction[]) {266      const a = active[action];267      const d = DEFAULT_BINDINGS[action];268      const same = a.key === d.key269        && Boolean(a.ctrl)  === Boolean(d.ctrl)270        && Boolean(a.meta)  === Boolean(d.meta)271        && Boolean(a.shift) === Boolean(d.shift)272        && Boolean(a.alt)   === Boolean(d.alt);273      if (!same) overrides[action] = a;274    }275    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });276  }277278  async function applyLockOnClose(enabled: boolean) {279    setLockOnClose(enabled);280    await sendMessage({281      type: "UPDATE_SETTINGS",282      payload: { lockOnClose: enabled },283    });284  }285286  async function applyAutoLockMinutes(minutes: number) {287    setAutoLockMinutes(minutes);288    await sendMessage({289      type: "UPDATE_SETTINGS",290      payload: { autoLockMinutes: minutes },291    });292  }293294  async function applyBreachMonitoring(enabled: boolean) {295    setBreachMonitoring(enabled);296    await sendMessage({297      type: "UPDATE_SETTINGS",298      payload: { breachMonitoring: enabled },299    });300  }301302  async function applyMobileStatusBar(nextTheme: "dark" | "light") {303    try {304      await StatusBar.setStyle({ style: nextTheme === "light" ? Style.Light : Style.Dark });305      await StatusBar.setBackgroundColor({306        color: nextTheme === "light" ? "#EEE3CC" : "#0C0A06",307      });308    } catch {309      // Status bar APIs are available only in the native shell.310    }311  }312313  function handleBackNavigation() {314    if (showShortcutsHelp()) {315      setShowShortcutsHelp(false);316      return;317    }318    if (restoreView() !== null) {319      setRestoreView(null);320      return;321    }322323    switch (view()) {324      case "list":325        setView("entry");326        return;327      case "settings":328      case "add":329      case "import":330        handleBack();331        return;332      case "export":333        if (returnToPanic()) {334          setReturnToPanic(false);335          setView("panic");336        } else {337          handleBack();338        }339        return;340      case "health":341      case "panic":342      case "sync-pairing":343        setView("settings");344        return;345      case "trash":346        setView("list");347        return;348      case "entry": {349        const now = Date.now();350        if (now - lastBackExitAt < 1600) {351          void CapacitorApp.exitApp();352          return;353        }354        lastBackExitAt = now;355        setBackExitNotice(true);356        window.setTimeout(() => setBackExitNotice(false), 1400);357        return;358      }359      default:360        void CapacitorApp.exitApp();361    }362  }363364  onMount(async () => {365    if (Capacitor.isNativePlatform()) {366      document.body.classList.add("peach-mobile");367      document.documentElement.classList.add("peach-mobile-root");368      void applyMobileStatusBar(theme());369370      const keyboardShow = await Keyboard.addListener("keyboardWillShow", (info) => {371        document.body.style.paddingBottom = `${info.keyboardHeight}px`;372      });373      const keyboardHide = await Keyboard.addListener("keyboardWillHide", () => {374        document.body.style.paddingBottom = "0";375      });376      const backButton = await CapacitorApp.addListener("backButton", () => {377        handleBackNavigation();378      });379380      let touchStartX = 0;381      let touchStartY = 0;382      const handleTouchStart = (event: TouchEvent) => {383        const touch = event.touches[0];384        if (!touch) return;385        touchStartX = touch.clientX;386        touchStartY = touch.clientY;387      };388      const handleTouchEnd = (event: TouchEvent) => {389        const touch = event.changedTouches[0];390        if (!touch) return;391        const dx = touch.clientX - touchStartX;392        const dy = Math.abs(touch.clientY - touchStartY);393        if (touchStartX < 30 && dx > 60 && dy < 40) {394          handleBackNavigation();395        }396      };397      document.addEventListener("touchstart", handleTouchStart, { passive: true });398      document.addEventListener("touchend", handleTouchEnd, { passive: true });399400      onCleanup(() => {401        void keyboardShow.remove();402        void keyboardHide.remove();403        void backButton.remove();404        document.removeEventListener("touchstart", handleTouchStart);405        document.removeEventListener("touchend", handleTouchEnd);406        document.body.style.paddingBottom = "0";407      });408    }409410    // Resolve the active tab in parallel with the unlock/has-vault queries —411    // openVault()'s smart selection picks the entry matching currentTabDomain,412    // so it must be populated before openVault runs. Previously refreshCurrentTab413    // ran after openVault, leaving popups that booted already-unlocked falling414    // back to loadedEntries[0] instead of the domain match.415    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([416      sendMessage({ type: "IS_UNLOCKED" }),417      sendMessage({ type: "HAS_VAULT" }),418      refreshCurrentTab(),419      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),420    ]);421    const unlocked = Boolean(422      (unlockResponse as { ok: boolean; data?: boolean }).data423    );424    const vaultExists = Boolean(425      (vaultResponse as { ok: boolean; data?: boolean }).data426    );427    const shouldCelebrate = Boolean(428      (celebrationResponse as { ok: boolean; data?: boolean }).data429    );430    setHasVault(vaultExists);431    // Onboarding gate — show once on first install, never again. Existing432    // users (vaultExists) are auto-marked onboarded so they skip the flow433    // even on the very first popup open after this feature ships.434    try {435      const onboarded = await storageGet("peach_onboarded");436      const seen = onboarded === "true";437      if (vaultExists && !seen) {438        await storageSet("peach_onboarded", "true");439        setOnboarded(true);440      } else {441        setOnboarded(seen);442      }443    } catch {444      // storage unavailable — default to onboarded so we never block boot445      setOnboarded(true);446    }447    await Promise.all([restoreSettings(), refreshProStatus()]);448449    // Mark played before any animation so a crash mid-sequence never replays it450    if (shouldCelebrate) {451      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });452    }453454    if (unlocked && vaultExists) {455      await openVault(undefined, shouldCelebrate);456      if (shouldCelebrate) {457        setView("pro-celebration");458        window.setTimeout(() => setView("entry"), 2500);459      }460    } else if (shouldCelebrate) {461      setPendingCelebration(true);462    }463464    await refreshPendingPasskey();465    await refreshIncomingPairing();466    await consumeRecentPairing();467468    // Track tab changes so smart sort stays current469    if (!Capacitor.isNativePlatform()) {470      const handleTabActivated = () => { void refreshCurrentTab(); };471      const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {472        if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();473      };474      try {475        chrome.tabs.onActivated.addListener(handleTabActivated);476        chrome.tabs.onUpdated.addListener(handleTabUpdated);477        onCleanup(() => {478          chrome.tabs.onActivated.removeListener(handleTabActivated);479          chrome.tabs.onUpdated.removeListener(handleTabUpdated);480        });481      } catch {482        // tabs permission may not be available in all contexts483      }484    }485486    setBootState("ready");487    document.getElementById("pre-lock")?.setAttribute("hidden", "true");488489    // Check for pending session-storage notices from the background.490    if (!Capacitor.isNativePlatform() && chrome.storage.session) {491      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as492        Record<string, { feature?: string } | undefined>;493      if (session.pendingProGate?.feature) {494        await chrome.storage.session.remove("pendingProGate");495        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);496        setSettingsInitialSection("license");497        setView("settings");498      } else if (session.pendingProNotice?.feature) {499        await chrome.storage.session.remove("pendingProNotice");500        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });501      }502    }503504    if (Capacitor.getPlatform() === "android") {505      try {506        const { pending } = await Autofill.checkPendingSave();507        if (pending) {508          const parsed = JSON.parse(pending) as {509            domain?: string;510            username?: string;511            password?: string;512          };513          if (parsed.username && parsed.password) {514            setPendingAutofillSave({515              domain: parsed.domain ?? "",516              username: parsed.username,517              password: parsed.password,518            });519          }520        }521      } catch {522        // Pending autofill saves are opportunistic; boot must continue.523      }524    }525526    // Warm the lazy-module cache so the Suspense fallback never shows for527    // locally-bundled extension views. Without this, the first navigation to528    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which529    // covers the shell and absorbs clicks on the header.530    void Promise.all([531      import("./views/Settings").catch(() => {}),532      import("./views/Import").catch(() => {}),533      import("./views/Export").catch(() => {}),534      import("./views/Health").catch(() => {}),535      import("./views/TrashView").catch(() => {}),536    ]);537538    // Lock-on-close via a persistent port. sendMessage in pagehide is539    // unreliable — the popup context tears down before the message lands.540    // The SW's onConnect listener locks when this port disconnects.541    if (!Capacitor.isNativePlatform()) {542      let popupPort: chrome.runtime.Port | null = null;543      try {544        popupPort = chrome.runtime.connect({ name: "popup" });545      } catch { /* extension context invalidated — ignore */ }546      onCleanup(() => { try { popupPort?.disconnect(); } catch {} });547548      // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale549      // entries instead of waiting for the next GET_ENTRIES round-trip.550      const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {551        if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();552        if (msg?.type === "PRO_GATE_TRIGGERED") {553          setUpgradeHighlight(msg.payload?.feature ?? null);554          setSettingsInitialSection("license");555          setView("settings");556        }557        if (msg?.type === "INCOMING_PAIRING_REQUEST") {558          void refreshIncomingPairing();559        }560      };561      chrome.runtime.onMessage.addListener(handleRuntimeMessage);562      onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));563    }564565    // Action handlers — keyed by ShortcutAction. The dispatcher below tests566    // each binding against the event and runs the matching handler. New567    // shortcuts only need an entry here; the binding is data, not code.568    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {569      copy_password: () => {570        const entry = selectedEntry();571        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });572      },573      copy_username: () => {574        const entry = selectedEntry();575        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });576      },577      copy_totp: () => {578        const entry = selectedEntry();579        if (!entry?.totp) return;580        try {581          const { code } = generateTOTP(entry.totp);582          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });583        } catch { /* invalid TOTP secret — silent */ }584      },585      new_entry: () => handleAdd(),586      edit_entry: () => {587        const entry = selectedEntry();588        // Passkey-only entries have nothing user-editable in the Add view; the589        // passkey credential itself is opaque. Skip the edit action for them.590        if (!entry || isPasskeyOnly(entry)) return;591        setEditEntry(entry);592        setView("add");593      },594      delete_entry: () => {595        if (selectedEntry()) void handleDelete();596      },597      lock_vault: () => { void handleHeaderLock(); },598      search: () => openList(),599      nav_prev: () => navigate(-1),600      nav_next: () => navigate(1),601      jump_vault: () => setView("entry"),602      jump_settings: () => setView("settings"),603      show_help: () => setShowShortcutsHelp(true),604    };605606    // Actions that are MEANINGFUL only on the entry-detail view. Outside607    // that scope the binding is dormant — pressing C while on Settings608    // does nothing rather than awkwardly copying from a now-stale entry.609    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([610      "copy_password", "copy_username", "copy_totp",611      "edit_entry", "delete_entry", "nav_prev", "nav_next",612    ]);613614    const handleGlobalKeydown = (e: KeyboardEvent) => {615      const v = view();616      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"617        || (e.target as HTMLElement)?.tagName === "TEXTAREA"618        || (e.target as HTMLElement)?.isContentEditable;619      const isPrintableSearchKey =620        e.key.length === 1 &&621        !e.ctrlKey &&622        !e.metaKey &&623        !e.altKey;624625      // No input during the pro celebration sequence626      if (v === "pro-celebration") return;627628      // Help dialog: Escape closes it; eat the keypress so it doesn't629      // also navigate away from the underlying view.630      if (showShortcutsHelp()) {631        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }632        return;633      }634635      // ── Escape — fixed binding (not user-customizable) ───────636      if (e.key === "Escape") {637        if (v === "list") { setView("entry"); return; }638        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }639        if (v === "sync-pairing") { setView("settings"); return; }640      }641642      // Bindings-driven dispatch. Single-key letter bindings without643      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is644      // inside an input, so users can type into search/forms normally.645      const bindings = shortcutBindings();646      for (const action of Object.keys(bindings) as ShortcutAction[]) {647        const binding = bindings[action];648        if (!matchKeybinding(e, binding)) continue;649        // Single-key letter bindings need the input-focus guard. Bindings650        // with any modifier are safe — Ctrl+L doesn't conflict with typing.651        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;652        if (!hasMod && binding.key.length === 1 && inInput) return;653        if (ENTRY_SCOPED.has(action) && v !== "entry") return;654        e.preventDefault();655        SHORTCUT_HANDLERS[action]?.();656        return;657      }658659      // Type-to-search: in entry view, any printable key not consumed by a660      // shortcut above primes the list search seed and opens the list.661      // Kept outside the bindings table because it's a behavior, not a662      // discrete action — every printable character can trigger it.663      if (v === "entry" && !inInput && isPrintableSearchKey) {664        e.preventDefault();665        primeListSearch(e.key);666        return;667      }668    };669    window.addEventListener("keydown", handleGlobalKeydown);670    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));671672    if (!Capacitor.isNativePlatform()) {673      const handleStorageChanged = (674        changes: Record<string, chrome.storage.StorageChange>,675        areaName: string676      ) => {677        if (areaName !== "session") return;678        if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {679          return;680        }681        void refreshPendingPasskey();682      };683      chrome.storage.onChanged.addListener(handleStorageChanged);684      onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));685    }686  });687688  async function refreshCurrentTab() {689    if (Capacitor.isNativePlatform()) return;690    try {691      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });692      const url = tab?.url ?? tab?.pendingUrl ?? "";693      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");694      // Skip extension/internal URLs — adding chrome://, about:, or695      // chrome-extension:// to a vault entry is never what the user wants.696      const isWebUrl = /^https?:\/\//i.test(url);697      setCurrentTabUrl(isWebUrl ? url : "");698    } catch {699      setCurrentTabDomain("");700      setCurrentTabUrl("");701    }702  }703704  async function refreshPendingPasskey() {705    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });706    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);707  }708709  async function refreshIncomingPairing() {710    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });711    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;712    setIncomingPair(data);713  }714715  // Drains a single one-shot record left by the background when 6-digit716  // pairing succeeded while the popup was closed (or the SyncPairing view was717  // navigated away from before it could show its own success card).718  async function consumeRecentPairing() {719    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });720    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;721    if (data?.deviceName) {722      setRecentPairToast(data.deviceName);723      window.setTimeout(() => setRecentPairToast(null), 4000);724    }725  }726727  async function respondIncomingPairing(accept: boolean) {728    if (incomingPairResponding()) return;729    setIncomingPairResponding(true);730    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });731    setIncomingPair(null);732    setIncomingPairResponding(false);733  }734735  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a736  // request appears, ticks once per second, and clears the banner if the737  // request expires while the popup is open.738  createEffect(() => {739    const req = incomingPair();740    if (!req) return;741    const handle = window.setInterval(() => {742      setIncomingPairTick((tick) => tick + 1);743      if (Date.now() >= req.expiresAt) {744        setIncomingPair(null);745        window.clearInterval(handle);746      }747    }, 1000);748    onCleanup(() => window.clearInterval(handle));749  });750751  async function refreshProStatus() {752    const res = await sendMessage({ type: "GET_LICENSE" });753    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;754    setProStatus(Boolean(data?.valid && data?.plan === "pro"));755  }756757  async function restoreSettings() {758    const res = await sendMessage({ type: "GET_SETTINGS" });759    const s = (res as { ok: boolean; data?: any }).data ?? {};760    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {761      setAccentColor(s.accentColor as AccentColorName);762    }763    setTheme(s.theme === "light" ? "light" : "dark");764    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {765      setDisplayFont(s.displayFont);766    } else {767      setDisplayFont("cormorant-italic");768    }769    if (s.textSize === "small" || s.textSize === "large") {770      setTextSize(s.textSize);771    } else {772      setTextSize("medium");773    }774    setReduceMotion(s.reduceMotion === true);775    setLockOnClose(s.lockOnClose !== false);776    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);777    setBreachMonitoring(s.breachMonitoring !== false);778    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);779    setShortcutBindings(getActiveBindings(s.shortcuts));780  }781782  async function applyTrashRetention(days: number) {783    setTrashRetentionDays(days);784    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });785  }786787  function primeListSearch(seed: string) {788    setListSearchSeed(seed);789    setListSearchSeedNonce((value) => value + 1);790    openList();791  }792793  // Returns null when it detected a dead service worker and triggered handleLock().794  // Callers that need to abort (e.g. openVault) check for null rather than relying795  // on view() state, which may already be "lock" during normal startup flows.796  async function loadEntries(): Promise<VaultEntry[] | null> {797    const response = await sendMessage({ type: "GET_ENTRIES" });798    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };799800    // If the service worker was killed and restarted (MV3 workers sleep), the801    // vault will be locked again — or the worker may not respond at all.802    // In either case, send the user to the lock screen rather than silently803    // showing an empty vault (which looks like data loss).804    if (!res.ok) {805      if (806        res.error === "vault locked" ||807        res.error === "SERVICE_WORKER_UNAVAILABLE" ||808        (typeof res.error === "string" && res.error.includes("locked"))809      ) {810        handleLock();811        return null; // signal emergency lock to callers812      }813      return [];814    }815816    const loadedEntries = res.data ?? [];817    setEntries(loadedEntries);818    void publishInMemoryVault(loadedEntries);819820    const currentId = selectedEntry()?.id;821    if (currentId) {822      setSelectedEntry(823        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null824      );825    }826827    return loadedEntries;828  }829830  async function openVault(preferredEntryId?: string, skipViewSet = false) {831    // Purge expired trash entries on each vault open832    const retDays = trashRetentionDays();833    if (retDays > 0) {834      void sendMessage({835        type: "PURGE_EXPIRED_TRASH",836        payload: { retentionMs: retDays * 86_400_000 },837      });838    }839840    const loadedEntries = await loadEntries();841842    // null means loadEntries() triggered an emergency lock (service worker died).843    // Don't override it by setting view back to "entry" with an empty vault.844    if (loadedEntries === null) return;845846    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry847    let nextSelectedEntry: VaultEntry | null = null;848    if (preferredEntryId) {849      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;850    }851    if (!nextSelectedEntry) {852      const tabDomain = currentTabDomain();853      if (tabDomain) {854        nextSelectedEntry = loadedEntries.find((e) => {855          if (e.type === "login") {856            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;857            for (const extra of e.additionalUrls ?? []) {858              if ((extractDomain(extra) ?? "") === tabDomain) return true;859            }860            return false;861          }862          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;863          return false;864        }) ?? null;865      }866    }867    nextSelectedEntry ??= loadedEntries[0] ?? null;868869    setSelectedEntry(nextSelectedEntry);870    setEditEntry(undefined);871    setContentTransitioning(false);872    setContentPhase("enter");873    queueContentIdle();874    if (!skipViewSet) setView("entry");875  }876877  async function handleUnlock() {878    setHasVault(true);879    triggerPipPulse();880    await restoreSettings();881    const celebrating = pendingCelebration();882    if (celebrating) {883      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });884      setPendingCelebration(false);885    }886    await openVault(undefined, celebrating);887    if (celebrating) {888      setView("pro-celebration");889      window.setTimeout(() => setView("entry"), 2500);890    }891  }892893  function handleSelectEntry(entry: VaultEntry) {894    setSelectedEntry(entry);895    setContentTransitioning(false);896    setContentPhase("enter");897    queueContentIdle();898    setView("entry");899  }900901  function handleAdd() {902    setEditEntry(undefined);903    setView("add");904  }905906  async function handleDelete() {907    const entry = selectedEntry();908    if (!entry) return;909    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });910    const loadedEntries = await loadEntries() ?? [];911    setSelectedEntry(loadedEntries[0] ?? null);912    setView("entry");913  }914915  async function handleDeleteMany(ids: string[]) {916    for (const id of ids) {917      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });918    }919    const loadedEntries = await loadEntries() ?? [];920    // If the currently selected entry was among the deleted, move to first921    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);922    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);923  }924925  async function handleSave(savedEntry?: VaultEntry) {926    await openVault(savedEntry?.id);927  }928929  async function savePendingAutofill() {930    const pending = pendingAutofillSave();931    if (!pending) return;932    const domain = pending.domain.trim();933    const response = await sendMessage({934      type: "ADD_ENTRY",935      payload: {936        type: "login",937        title: domain || "Saved login",938        url: domain ? `https://${domain}` : "",939        username: pending.username,940        password: pending.password,941      },942    });943    if ((response as { ok: boolean }).ok) {944      setPendingAutofillSave(null);945      await openVault((response as { data?: VaultEntry }).data?.id);946    }947  }948949  function handleBack() {950    setEditEntry(undefined);951    setView("entry");952  }953954  function handleLock() {955    clearCanarySuppressions();956    setEntries([]);957    setSelectedEntry(null);958    setEditEntry(undefined);959    setContentPhase("idle");960    setView("lock");961    void clearInMemoryVault();962  }963964  function handleHeaderLock() {965    // Lock the UI immediately — do not wait for the service worker. If the SW966    // is dead or slow, the 5s sendMessage timeout would create a dead-click967    // window. The SW will lock on its next wake regardless.968    handleLock();969    void sendMessage({ type: "LOCK" });970  }971972  function navigate(dir: number) {973    const allEntries = entries();974    if (allEntries.length === 0) return;975    const currentIndex = selectedIndex();976    const baseIndex = currentIndex >= 0 ? currentIndex : 0;977    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;978    setSelectedEntry(allEntries[nextIndex]);979    setContentPhase("enter");980    queueContentIdle();981  }982983  function openList() {984    setView("list");985  }986987  function openHealth() {988    setEditEntry(undefined);989    setView("health");990  }991992  function handleOpenFileImport() {993    setRestoreView("file");994  }995996  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;997998  function handleFixEntry(entry: VaultEntry) {999    // Passkey-only entries have no editable surface — drop into view mode1000    // instead of opening the Add editor.1001    if (isPasskeyOnly(entry)) {1002      setSelectedEntry(entry);1003      setView("entry");1004      return;1005    }1006    setEditEntry(entry);1007    setView("add");1008  }10091010  const isLockedView = () => view() === "lock";10111012  async function handleApprovePendingPasskey() {1013    const pending = pendingPasskey();1014    if (!pending) return;1015    if (pending.browser === "firefox" && pending.type === "create") {1016      // Firefox path: popup itself runs navigator.credentials.create. The1017      // background never approved/rejected anything — it just stashed1018      // intent. After the popup-driven flow resolves (success or cancel),1019      // clear the pending key so the popup doesn't re-show this on next open.1020      const { createFirefoxPasskey } = await import("./firefox-passkey");1021      const result = await createFirefoxPasskey(pending);1022      if (!result.ok) {1023        console.warn("Peach Firefox passkey create failed:", result.error);1024      }1025      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1026      setPendingPasskey(null);1027      void loadEntries();1028      return;1029    }1030    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1031    setPendingPasskey(null);1032  }10331034  async function handleDenyPendingPasskey() {1035    const pending = pendingPasskey();1036    if (!pending) return;1037    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1038    setPendingPasskey(null);1039  }10401041  function queueContentIdle(after?: () => void) {1042    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1043    contentPhaseTimer = window.setTimeout(() => {1044      setContentPhase("idle");1045      after?.();1046    }, ENTRY_TRANSITION_SETTLE_MS);1047  }10481049  return (1050    <div class="popup-root peach-theme">1051      <Show when={bootState() === "ready"}>1052        <Show1053          when={!pendingPasskey()}1054          fallback={1055            <PasskeyApprovalView1056              type={pendingPasskey()!.type}1057              rpName={pendingPasskey()!.rpName}1058              rpId={pendingPasskey()!.rpId}1059              userName={pendingPasskey()!.userName}1060              userDisplayName={pendingPasskey()!.userDisplayName}1061              onApprove={handleApprovePendingPasskey}1062              onDeny={handleDenyPendingPasskey}1063            />1064          }1065        >1066          <Show1067            when={!isLockedView()}1068            fallback={1069              <Show1070                when={onboarded() || hasVault()}1071                fallback={1072                  <Onboarding1073                    onComplete={() => { setOnboarded(true); }}1074                  />1075                }1076              >1077                <LockView1078                  hasVault={hasVault()}1079                  ready={bootState() === "ready"}1080                  isPro={proStatus()}1081                  onUnlock={handleUnlock}1082                  onBackToOnboarding={1083                    !hasVault()1084                      ? () => setOnboarded(false)1085                      : undefined1086                  }1087                />1088              </Show>1089            }1090          >1091            <Show1092              when={view() !== "pro-celebration"}1093              fallback={<ProCelebration />}1094            >1095            <section1096              id="hd-shell"1097              class="peach-shell peach-theme"1098              data-surface="extension"1099            >1100            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1101              <PeachWordmark unlocked />1102              <div class="peach-chrome-actions">1103                <button1104                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1105                  onClick={() => setView("settings")}1106                  aria-label="Settings"1107                >1108                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1109                    <path1110                      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"1111                      stroke="currentColor"1112                      stroke-width="0.9"1113                    />1114                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1115                  </svg>1116                </button>1117                <button1118                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1119                  onClick={handleAdd}1120                  aria-label="New entry"1121                >1122                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1123                    <path d="M5.5 1v9M1 5.5h9" />1124                  </svg>1125                </button>1126                <button1127                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1128                  onClick={() => void handleHeaderLock()}1129                  aria-label="Lock vault"1130                >1131                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1132                    <path1133                      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"1134                      stroke="currentColor"1135                      stroke-width="1"1136                      stroke-linecap="round"1137                    />1138                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1139                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1140                  </svg>1141                </button>1142              </div>1143            </header>11441145            <Show when={recentPairToast()}>1146              <div class="peach-pair-toast" role="status" aria-live="polite">1147                Paired with <strong>{recentPairToast()}</strong>1148              </div>1149            </Show>11501151            <Show when={incomingPair() !== null}>1152              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1153                <div class="peach-pair-request-header">1154                  <span class="peach-pair-request-mark">🍑</span>1155                  <span class="peach-pair-request-title">Pairing request</span>1156                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1157                </div>1158                <p class="peach-pair-request-body">1159                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1160                </p>1161                <div class="peach-pair-request-actions">1162                  <button1163                    class="peach-btn peach-btn--ghost peach-btn--sm"1164                    onClick={() => void respondIncomingPairing(false)}1165                    disabled={incomingPairResponding()}1166                  >1167                    Reject1168                  </button>1169                  <button1170                    class="peach-btn peach-btn--accent peach-btn--sm"1171                    onClick={() => void respondIncomingPairing(true)}1172                    disabled={incomingPairResponding()}1173                  >1174                    Accept1175                  </button>1176                </div>1177              </div>1178            </Show>11791180            <Show when={pendingProNotice() !== null}>1181              <div class="peach-pro-notice-banner">1182                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1183                <button1184                  class="peach-pro-notice-link"1185                  onClick={() => {1186                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1187                    setSettingsInitialSection("license");1188                    setView("settings");1189                    setPendingProNotice(null);1190                  }}1191                >1192                  Learn more →1193                </button>1194                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1195              </div>1196            </Show>11971198            <Show when={pendingAutofillSave() !== null && !isLockedView()}>1199              <div class="peach-pro-notice-banner peach-autofill-save-banner">1200                <span>1201                  Save login{pendingAutofillSave()?.domain ? ` for ${pendingAutofillSave()!.domain}` : ""}?1202                </span>1203                <button1204                  class="peach-pro-notice-link"1205                  onClick={() => void savePendingAutofill()}1206                >1207                  Save1208                </button>1209                <button1210                  class="peach-pro-notice-close"1211                  onClick={() => setPendingAutofillSave(null)}1212                  aria-label="Dismiss"1213                >1214                  x1215                </button>1216              </div>1217            </Show>12181219            <Show when={backExitNotice()}>1220              <div class="peach-pro-notice-banner peach-back-exit-banner">1221                <span>Tap back again to exit Peach</span>1222              </div>1223            </Show>12241225            <div class="peach-shell-body">1226              <div class="peach-shell-veil"></div>1227              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1228                <EntryView1229                  entry={selectedEntry()}1230                  currentTabUrl={currentTabUrl()}1231                  onDelete={handleDelete}1232                  onFieldSaved={() => void loadEntries()}1233                  onEscape={() => { setView("list"); }}1234                />1235              </div>12361237              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1238                <div class="peach-search-bar">1239                  <span class="peach-search-icon">1240                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1241                      <circle cx="5.5" cy="5.5" r="3.75" />1242                      <path d="M8.75 8.75L11.5 11.5" />1243                    </svg>1244                  </span>1245                  <input1246                    class="peach-search-input"1247                    placeholder="search vault..."1248                    autocomplete="off"1249                    aria-label="Search vault entries"1250                    onClick={openList}1251                    onFocus={openList}1252                    readOnly1253                  />1254                  <div class="peach-search-meta">1255                    <span class="peach-search-counter">1256                      {entries().length > 01257                        ? `${selectedIndex() + 1} / ${entries().length}`1258                        : "0 entries"}1259                    </span>1260                    <span class="peach-divider"></span>1261                    <button1262                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1263                      onClick={() => navigate(-1)}1264                      aria-label="Previous entry"1265                      disabled={entries().length === 0}1266                    >1267                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1268                        <path d="M5 1L1 5.5L5 10" />1269                      </svg>1270                    </button>1271                    <button1272                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1273                      onClick={() => navigate(1)}1274                      aria-label="Next entry"1275                      disabled={entries().length === 0}1276                    >1277                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1278                        <path d="M1 1L5 5.5L1 10" />1279                      </svg>1280                    </button>1281                  </div>1282                </div>1283              </section>1284            </div>12851286            <Show when={view() === "list"}>1287              <VaultView1288                entries={entries()}1289                selectedEntryId={selectedEntry()?.id}1290                currentTabDomain={currentTabDomain()}1291                sortOrder={sortOrder()}1292                searchSeed={listSearchSeed()}1293                searchSeedNonce={listSearchSeedNonce()}1294                onSelectEntry={handleSelectEntry}1295                onSortOrderChange={setSortOrder}1296                onAdd={handleAdd}1297                onClose={() => setView("entry")}1298                onOpenTrash={() => setView("trash")}1299                onDeleteMany={handleDeleteMany}1300              />1301            </Show>1302            <Show when={view() === "settings"}>1303              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1304                <SettingsView1305                  entriesCount={entries().length}1306                  breachMonitoring={breachMonitoring()}1307                  lockOnClose={lockOnClose()}1308                  autoLockMinutes={autoLockMinutes()}1309                  trashRetentionDays={trashRetentionDays()}1310                  theme={theme()}1311                  accentColor={accentColor()}1312                  displayFont={displayFont()}1313                  textSize={textSize()}1314                  reduceMotion={reduceMotion()}1315                  isPro={proStatus()}1316                  initialSection={settingsInitialSection()}1317                  upgradeHighlight={upgradeHighlight()}1318                  onBreachMonitoringChange={applyBreachMonitoring}1319                  onLockOnCloseChange={applyLockOnClose}1320                  onAutoLockMinutesChange={applyAutoLockMinutes}1321                  onTrashRetentionChange={applyTrashRetention}1322                  onThemeChange={applyTheme}1323                  onAccentChange={applyAccentColor}1324                  onDisplayFontChange={applyDisplayFont}1325                  onTextSizeChange={applyTextSize}1326                  onReduceMotionChange={applyReduceMotion}1327                  shortcuts={shortcutBindings()}1328                  onShortcutsChange={applyShortcuts}1329                  onLicenseChange={async () => {1330                    // After activation/deactivation: refresh Pro status,1331                    // re-load entries (defensive — signal state can drift if1332                    // the SW briefly restarts during the verify+save round-trip),1333                    // and replay the Pro celebration if this is the first time1334                    // a valid Pro license is seen on this device.1335                    await refreshProStatus();1336                    void loadEntries();1337                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1338                    if ((should as { ok: boolean; data?: boolean }).data === true) {1339                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1340                      setView("pro-celebration");1341                      window.setTimeout(() => setView("settings"), 2500);1342                    }1343                  }}1344                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1345                  onImport={() => setView("import")}1346                  onExport={() => setView("export")}1347                  onBreachCheckDone={loadEntries}1348                  onOpenHealth={openHealth}1349                  onOpenSyncPairing={() => setView("sync-pairing")}1350                  onOpenFileImport={handleOpenFileImport}1351                  onOpenPanic={() => setView("panic")}1352                />1353              </Suspense>1354            </Show>1355            <Show when={view() === "sync-pairing"}>1356              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1357                <SyncPairingView1358                  onClose={() => setView("settings")}1359                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1360                />1361              </Suspense>1362            </Show>1363            <Show when={view() === "add"}>1364              <AddView1365                entry={editEntry()}1366                entries={entries()}1367                onBack={handleBack}1368                onSave={handleSave}1369              />1370            </Show>1371            <Show when={view() === "import"}>1372              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1373                <ImportView onBack={handleBack} onImport={handleSave} />1374              </Suspense>1375            </Show>1376            <Show when={view() === "export"}>1377              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1378                <ExportView1379                  onBack={() => {1380                    if (returnToPanic()) {1381                      setReturnToPanic(false);1382                      setView("panic");1383                    } else {1384                      handleBack();1385                    }1386                  }}1387                />1388              </Suspense>1389            </Show>1390            <Show when={view() === "panic"}>1391              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1392                <PanicView1393                  onCancel={() => setView("settings")}1394                  onOpenExport={() => {1395                    setReturnToPanic(true);1396                    setView("export");1397                  }}1398                  onDestroyed={async () => {1399                    clearCanarySuppressions();1400                    setEntries([]);1401                    setSelectedEntry(null);1402                    setEditEntry(undefined);1403                    setHasVault(false);1404                    setOnboarded(false);1405                    setProStatus(false);1406                    setPendingPasskey(null);1407                    setUpgradeHighlight(null);1408                    setSettingsInitialSection(null);1409                    setPendingProNotice(null);1410                    setPendingCelebration(false);1411                    setReturnToPanic(false);1412                    setContentPhase("idle");1413                    setView("lock");1414                    void clearInMemoryVault();1415                  }}1416                />1417              </Suspense>1418            </Show>1419            <Show when={view() === "health"}>1420              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1421                <HealthView1422                  entries={entries()}1423                  isPro={proStatus()}1424                  onFixEntry={handleFixEntry}1425                  onBack={() => setView("settings")}1426                  onRefresh={loadEntries}1427                />1428              </Suspense>1429            </Show>1430            <Show when={view() === "trash"}>1431              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1432                <TrashView1433                  onBack={() => setView("list")}1434                  onRestored={() => void loadEntries()}1435                />1436              </Suspense>1437            </Show>1438            <Show when={restoreView() === "file"}>1439              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1440                <ImportView1441                  mode="onboarding"1442                  replacesExistingVault={true}1443                  onBack={() => setRestoreView(null)}1444                  onImport={async () => {1445                    setRestoreView(null);1446                    await handleUnlock();1447                  }}1448                />1449              </Suspense>1450            </Show>1451            </section>1452            </Show>1453          </Show>1454        </Show>1455      </Show>1456      <Show when={showShortcutsHelp()}>1457        <ShortcutsHelpOverlay1458          bindings={shortcutBindings()}1459          onClose={() => setShowShortcutsHelp(false)}1460        />1461      </Show>1462    </div>1463  );1464}14651466function ShortcutsHelpOverlay(props: {1467  bindings: Record<ShortcutAction, Keybinding>;1468  onClose: () => void;1469}) {1470  return (1471    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1472      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1473        <div class="peach-shortcuts-help-head">1474          <h3>Keyboard shortcuts</h3>1475          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1476        </div>1477        <div class="peach-shortcuts-help-body">1478          <p class="peach-settings-sub-label">ENTRY VIEW</p>1479          <ul>1480            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1481              <li>1482                <span>{d.label}</span>1483                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1484              </li>1485            ))}1486          </ul>1487          <p class="peach-settings-sub-label">ANYWHERE</p>1488          <ul>1489            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1490              <li>1491                <span>{d.label}</span>1492                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1493              </li>1494            ))}1495          </ul>1496        </div>1497      </div>1498    </div>1499  );1500}