App.tsx

63.1 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import type { IncomingPairingRequest } from "../shared/sync-types";8import { isPasskeyOnly } from "../shared/types";9import { LockView } from "./views/Lock";10import { Onboarding } from "./views/Onboarding";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachMark, PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));4041type View =42  | "lock"43  | "pro-celebration"44  | "entry"45  | "list"46  | "add"47  | "settings"48  | "sync-pairing"49  | "import"50  | "export"51  | "health"52  | "trash"53  | "panic";54type BootState = "loading" | "ready";5556const canarySuppressMap = new Map<string, boolean>();57let shellRingAnimation: Animation | null = null;5859export function isCanarySuppressed(entryId: string): boolean {60  return canarySuppressMap.get(entryId) ?? false;61}6263export function setCanarySuppressed(entryId: string, suppressed: boolean): void {64  canarySuppressMap.set(entryId, suppressed);65}6667export function clearCanarySuppressions(): void {68  canarySuppressMap.clear();69}7071export function triggerRing() {72  const shell = document.getElementById("hd-shell");73  if (!shell) return;7475  shellRingAnimation?.cancel();76  shell.dataset.glowing = "true";77  const animation = shell.animate(78    [79      { offset: 0, boxShadow: "var(--copy-shadow)" },80      {81        offset: 0.3,82        boxShadow:83          "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)",84      },85      { offset: 1, boxShadow: "var(--copy-shadow)" },86    ],87    {88      duration: 720,89      easing: "cubic-bezier(0.4, 0, 0.2, 1)",90      fill: "none",91    }92  );93  shellRingAnimation = animation;94  const clearGlow = () => {95    if (shellRingAnimation !== animation) return;96    shellRingAnimation = null;97    delete shell.dataset.glowing;98  };99  animation.onfinish = clearGlow;100  animation.oncancel = clearGlow;101}102103104export function triggerPipPulse() {105  const pip = document.querySelector(".peach-status-pip, .pip");106  if (pip) {107    pip.classList.remove("pulse");108    void (pip as HTMLElement).offsetWidth;109    pip.classList.add("pulse");110  }111}112113const ENTRY_TRANSITION_EXIT_MS = 95;114const ENTRY_TRANSITION_SETTLE_MS = 135;115116export default function App() {117  const [bootState, setBootState] = createSignal<BootState>("loading");118  const [view, setView] = createSignal<View>("lock");119  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,120  // CSS transition takes over for snap animation).121  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);122  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(123    "enter"124  );125  const [contentTransitioning, setContentTransitioning] = createSignal(false);126  const [hasVault, setHasVault] = createSignal(false);127  const [onboarded, setOnboarded] = createSignal(true);128  const [entries, setEntries] = createSignal<VaultEntry[]>([]);129  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);130  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);131  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");132  const [theme, setTheme] = createSignal<"dark" | "light">("dark");133  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");134  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");135  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);136  const [lockOnClose, setLockOnClose] = createSignal(true);137  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);138  const [breachMonitoring, setBreachMonitoring] = createSignal(true);139  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);140  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);141  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);142  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);143  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);144  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");145  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");146  // Cached Pro status — synchronous for render paths. Background's147  // GET_LICENSE is async, but render-time reads of isPro() must not block.148  // Refreshed at boot, after activate/deactivate, and whenever the popup149  // re-opens onto a stored license that has changed via another window.150  const [proStatus, setProStatus] = createSignal(false);151  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);152  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);153  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");154  const [listSearchSeed, setListSearchSeed] = createSignal("");155  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);156  const [pendingCelebration, setPendingCelebration] = createSignal(false);157  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);158  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);159  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);160  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);161  const [incomingPairTick, setIncomingPairTick] = createSignal(0);162  const incomingPairSecondsLeft = () => {163    void incomingPairTick();164    const req = incomingPair();165    if (!req) return 0;166    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));167  };168  // True while Panic Step 1 has bounced the user out to Export. When Export's169  // onBack fires we return to Panic instead of Settings so the user keeps the170  // destruction context they came from.171  const [returnToPanic, setReturnToPanic] = createSignal(false);172  // Set on popup boot when peach_recovery_pending flag is found in session173  // storage — instructs LockView to skip the unlock UI and open the recovery174  // words confirmation surface instead. Cleared via handleUnlock once the175  // user has typed the 3 confirmation words.176  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);177178  let contentPhaseTimer: number | undefined;179180  function applyAccent(name: AccentColorName) {181    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;182    const hex = color.hex;183    document.documentElement.style.setProperty("--peach-accent", hex);184    // Ambient surface variables — derived from the accent so surfaces shift185    // subtly toward the accent hue rather than staying fixed warm-brown.186    document.documentElement.style.setProperty("--peach-glow", hex + "2A");187    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");188    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");189  }190191  createEffect(() => {192    applyAccent(accentColor());193  });194195  createEffect(() => {196    document.documentElement.classList.toggle("light", theme() === "light");197    document.body.classList.toggle("light", theme() === "light");198  });199200  createEffect(() => {201    document.documentElement.setAttribute("data-display-font", displayFont());202  });203204  createEffect(() => {205    document.documentElement.setAttribute("data-text-size", textSize());206  });207208  createEffect(() => {209    if (reduceMotion()) {210      document.documentElement.setAttribute("data-motion", "reduce");211    } else {212      document.documentElement.removeAttribute("data-motion");213    }214  });215216  const selectedIndex = createMemo(() => {217    const currentId = selectedEntry()?.id;218    if (!currentId) return entries().length > 0 ? 0 : -1;219    return entries().findIndex((entry) => entry.id === currentId);220  });221222  async function applyAccentColor(name: AccentColorName) {223    applyAccent(name);224    setAccentColor(name);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });226  }227228  async function applyTheme(t: "dark" | "light") {229    setTheme(t);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });231  }232233  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {234    setDisplayFont(f);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });236  }237238  async function applyTextSize(size: "small" | "medium" | "large") {239    setTextSize(size);240    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });241  }242243  async function applyReduceMotion(enabled: boolean) {244    setReduceMotion(enabled);245    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });246  }247248  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload249  // small and lets future default updates land for actions the user hasn't250  // touched. Settings sends us the full active map; we filter and store.251  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {252    setShortcutBindings(active);253    const overrides: Record<string, Keybinding> = {};254    for (const action of Object.keys(active) as ShortcutAction[]) {255      const a = active[action];256      const d = DEFAULT_BINDINGS[action];257      const same = a.key === d.key258        && Boolean(a.ctrl)  === Boolean(d.ctrl)259        && Boolean(a.meta)  === Boolean(d.meta)260        && Boolean(a.shift) === Boolean(d.shift)261        && Boolean(a.alt)   === Boolean(d.alt);262      if (!same) overrides[action] = a;263    }264    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });265  }266267  async function applyLockOnClose(enabled: boolean) {268    setLockOnClose(enabled);269    await sendMessage({270      type: "UPDATE_SETTINGS",271      payload: { lockOnClose: enabled },272    });273  }274275  async function applyAutoLockMinutes(minutes: number) {276    setAutoLockMinutes(minutes);277    await sendMessage({278      type: "UPDATE_SETTINGS",279      payload: { autoLockMinutes: minutes },280    });281  }282283  async function applyBreachMonitoring(enabled: boolean) {284    setBreachMonitoring(enabled);285    await sendMessage({286      type: "UPDATE_SETTINGS",287      payload: { breachMonitoring: enabled },288    });289  }290291  onMount(async () => {292    // Resolve the active tab in parallel with the unlock/has-vault queries —293    // openVault()'s smart selection picks the entry matching currentTabDomain,294    // so it must be populated before openVault runs. Previously refreshCurrentTab295    // ran after openVault, leaving popups that booted already-unlocked falling296    // back to loadedEntries[0] instead of the domain match.297    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([298      sendMessage({ type: "IS_UNLOCKED" }),299      sendMessage({ type: "HAS_VAULT" }),300      refreshCurrentTab(),301      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),302    ]);303    const unlocked = Boolean(304      (unlockResponse as { ok: boolean; data?: boolean }).data305    );306    const vaultExists = Boolean(307      (vaultResponse as { ok: boolean; data?: boolean }).data308    );309    const shouldCelebrate = Boolean(310      (celebrationResponse as { ok: boolean; data?: boolean }).data311    );312    setHasVault(vaultExists);313    // Onboarding gate — show once on first install, never again. Existing314    // users (vaultExists) are auto-marked onboarded so they skip the flow315    // even on the very first popup open after this feature ships.316    try {317      const onboarded = await storageGet("peach_onboarded");318      const seen = onboarded === "true";319      if (vaultExists && !seen) {320        await storageSet("peach_onboarded", "true");321        setOnboarded(true);322      } else {323        setOnboarded(seen);324      }325    } catch {326      // storage unavailable — default to onboarded so we never block boot327      setOnboarded(true);328    }329    await Promise.all([restoreSettings(), refreshProStatus()]);330331    // Mark played before any animation so a crash mid-sequence never replays it332    if (shouldCelebrate) {333      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });334    }335336    // If the user created a vault but hasn't yet confirmed their recovery337    // words, route back to the recovery-words screen instead of opening the338    // entries view. The flag lives in chrome.storage.local so it survives339    // both popup close (SW suppresses lock-on-close) and full browser340    // restart (handleUnlock checks the same flag after a fresh password341    // unlock). Cleared when confirmation succeeds.342    let recoveryPending = false;343    try {344      const out = await chrome.storage.local?.get("peach_recovery_pending");345      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";346    } catch { /* best-effort */ }347348    // Native: closing the app before recovery-words confirmation means the349    // user didn't finish vault creation. Throw the partial vault away and350    // restart onboarding rather than asking them to unlock a vault they351    // never finished creating. Desktop keeps the existing "unlock to352    // resume" flow because closing the popup there is much more casual.353    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {354      try {355        await chrome.storage.local?.remove([356          "peach_vault_a",357          "peach_vault_b",358          "peach_recovery_pending",359          "peach_onboarded",360          "peach_vault_history",361        ]);362      } catch { /* best-effort */ }363      setHasVault(false);364      setOnboarded(false);365      setView("lock");366      setBootState("ready");367      document.getElementById("pre-lock")?.setAttribute("hidden", "true");368      return;369    }370371    if (recoveryPending && unlocked) {372      // forceRecoveryWords overrides LockView's hasVault gate so the373      // recovery surface renders even though the vault now exists.374      setForceRecoveryWords(true);375      setView("lock");376    } else if (unlocked && vaultExists) {377      await openVault(undefined, shouldCelebrate);378      if (shouldCelebrate) {379        setView("pro-celebration");380        window.setTimeout(() => setView("entry"), 2500);381      }382    } else if (shouldCelebrate) {383      setPendingCelebration(true);384    }385386    await refreshPendingPasskey();387    await refreshIncomingPairing();388    await consumeRecentPairing();389390    // Track tab changes so smart sort stays current391    const handleTabActivated = () => { void refreshCurrentTab(); };392    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {393      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();394    };395    try {396      chrome.tabs.onActivated.addListener(handleTabActivated);397      chrome.tabs.onUpdated.addListener(handleTabUpdated);398      onCleanup(() => {399        chrome.tabs.onActivated.removeListener(handleTabActivated);400        chrome.tabs.onUpdated.removeListener(handleTabUpdated);401      });402    } catch {403      // tabs permission may not be available in all contexts404    }405406    setBootState("ready");407    document.getElementById("pre-lock")?.setAttribute("hidden", "true");408409    // Check for pending session-storage notices from the background.410    if (chrome.storage.session) {411      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as412        Record<string, { feature?: string } | undefined>;413      if (session.pendingProGate?.feature) {414        await chrome.storage.session.remove("pendingProGate");415        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);416        setSettingsInitialSection("license");417        setView("settings");418      } else if (session.pendingProNotice?.feature) {419        await chrome.storage.session.remove("pendingProNotice");420        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });421      }422    }423424    // Warm the lazy-module cache so the Suspense fallback never shows for425    // locally-bundled extension views. Without this, the first navigation to426    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which427    // covers the shell and absorbs clicks on the header.428    void Promise.all([429      import("./views/Settings").catch(() => {}),430      import("./views/Import").catch(() => {}),431      import("./views/Export").catch(() => {}),432      import("./views/Health").catch(() => {}),433      import("./views/TrashView").catch(() => {}),434    ]);435436    // Lock-on-close via a persistent port. sendMessage in pagehide is437    // unreliable — the popup context tears down before the message lands.438    // The SW's onConnect listener locks when this port disconnects.439    let popupPort: chrome.runtime.Port | null = null;440    try {441      popupPort = chrome.runtime.connect({ name: "popup" });442    } catch { /* extension context invalidated — ignore */ }443    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });444445    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only446    // reliable signal is appStateChange — setTimeout is killed when the OS447    // backgrounds the app. We measure elapsed background time on resume.448    if (isNativePlatform()) {449      let backgroundedAt: number | null = null;450      const CapApp = nativePlugin<{451        addListener: (452          ev: string,453          cb: (s: { isActive: boolean }) => void,454        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };455      }>("App");456      if (CapApp?.addListener) {457        const sub = CapApp.addListener(458          "appStateChange",459          ({ isActive }: { isActive: boolean }) => {460            if (!isActive) {461              backgroundedAt = Date.now();462              return;463            }464            if (backgroundedAt !== null && autoLockMinutes() > 0) {465              const elapsed = Date.now() - backgroundedAt;466              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();467            }468            backgroundedAt = null;469          }470        );471        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.472        onCleanup(() => {473          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});474        });475      }476    }477478    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale479    // entries instead of waiting for the next GET_ENTRIES round-trip.480    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {481      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();482      if (msg?.type === "PRO_GATE_TRIGGERED") {483        setUpgradeHighlight(msg.payload?.feature ?? null);484        setSettingsInitialSection("license");485        setView("settings");486      }487      if (msg?.type === "INCOMING_PAIRING_REQUEST") {488        void refreshIncomingPairing();489      }490    };491    chrome.runtime.onMessage.addListener(handleRuntimeMessage);492    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));493494    // Android hardware/gesture back. MainActivity fires peach:back; the popup495    // decides what "back" means per surface. Lock+no-vault is the common case496    // — return to onboarding rather than letting the OS dismiss the activity.497    const handlePeachBack = () => {498      const v = view();499      if (v === "lock" && !hasVault() && onboarded()) {500        setOnboarded(false);501        return;502      }503      if (v === "list") { setView("entry"); return; }504      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {505        handleBack();506        return;507      }508      if (v === "sync-pairing") { setView("settings"); return; }509    };510    window.addEventListener("peach:back", handlePeachBack);511    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));512513    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that514    // peeks from the bottom (search bar handle visible) and drags up to fill515    // the screen. dragOffset is the LIVE finger offset during a drag, in px,516    // 0 when no drag in progress. The wrapper element computes transform =517    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.518    if (isNativePlatform()) {519      let touchStartY = 0;520      let touchStartX = 0;521      let lastY = 0;522      let lastT = 0;523      let dragging = false;524      let captured = false;525      const HORIZONTAL_TOLERANCE = 16;526      const ACTIVATION_DY = 8;527528      const onTouchStart = (e: TouchEvent) => {529        const t = e.touches[0];530        if (!t) return;531        const v = view();532        if (v !== "entry" && v !== "list") return;533        // Entry view: only intercept drags starting in the bottom 40%.534        // List view: intercept drags starting in the top 35% (the search/handle row).535        const inBand = v === "entry"536          ? t.clientY > window.innerHeight * 0.6537          : t.clientY < window.innerHeight * 0.35;538        if (!inBand) return;539        touchStartY = lastY = t.clientY;540        touchStartX = t.clientX;541        lastT = e.timeStamp;542        dragging = true;543        captured = false;544      };545546      const onTouchMove = (e: TouchEvent) => {547        if (!dragging) return;548        const t = e.touches[0];549        if (!t) return;550        const dy = t.clientY - touchStartY;551        const dx = Math.abs(t.clientX - touchStartX);552553        if (!captured) {554          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {555            // Looks like a horizontal swipe — release.556            dragging = false;557            return;558          }559          if (Math.abs(dy) < ACTIVATION_DY) return;560          captured = true;561        }562563        // Translate the sheet by dy from its rest position. At rest the sheet564        // is fully off-screen (translateY = viewport height). Open is 0.565        const v = view();566        const restClosed = window.innerHeight;567        const baseTranslate = v === "list" ? 0 : restClosed;568        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));569        setSheetTranslate(next);570        lastY = t.clientY;571        lastT = e.timeStamp;572      };573574      const onTouchEnd = (e: TouchEvent) => {575        if (!dragging) { return; }576        const t = e.changedTouches[0];577        const elapsed = Math.max(1, e.timeStamp - lastT);578        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms579        const wasCaptured = captured;580        dragging = false;581        captured = false;582583        if (!wasCaptured) {584          // It was a tap, not a drag. Let the underlying click handler run.585          setSheetTranslate(null);586          return;587        }588589        const restClosed = window.innerHeight;590        const current = sheetTranslate() ?? restClosed;591        const v = view();592593        // Snap rules:594        //   - Strong upward velocity → open595        //   - Strong downward velocity → close596        //   - Otherwise snap to whichever rest is closer597        let nextOpen: boolean;598        if (velocity < -0.4) nextOpen = true;599        else if (velocity > 0.4) nextOpen = false;600        else nextOpen = current < restClosed * 0.5;601602        if (nextOpen && v !== "list") setView("list");603        if (!nextOpen && v !== "entry") setView("entry");604        // Release the live offset so CSS transition handles the snap.605        setSheetTranslate(null);606      };607608      document.addEventListener("touchstart", onTouchStart, { passive: true });609      document.addEventListener("touchmove",  onTouchMove,  { passive: true });610      document.addEventListener("touchend",   onTouchEnd,   { passive: true });611      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });612      onCleanup(() => {613        document.removeEventListener("touchstart", onTouchStart);614        document.removeEventListener("touchmove",  onTouchMove);615        document.removeEventListener("touchend",   onTouchEnd);616      });617    }618619    // Action handlers — keyed by ShortcutAction. The dispatcher below tests620    // each binding against the event and runs the matching handler. New621    // shortcuts only need an entry here; the binding is data, not code.622    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {623      copy_password: () => {624        const entry = selectedEntry();625        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });626      },627      copy_username: () => {628        const entry = selectedEntry();629        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });630      },631      copy_totp: () => {632        const entry = selectedEntry();633        if (!entry?.totp) return;634        try {635          const { code } = generateTOTP(entry.totp);636          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });637        } catch { /* invalid TOTP secret — silent */ }638      },639      new_entry: () => handleAdd(),640      edit_entry: () => {641        const entry = selectedEntry();642        // Passkey-only entries have nothing user-editable in the Add view; the643        // passkey credential itself is opaque. Skip the edit action for them.644        if (!entry || isPasskeyOnly(entry)) return;645        setEditEntry(entry);646        setView("add");647      },648      delete_entry: () => {649        if (selectedEntry()) void handleDelete();650      },651      lock_vault: () => { void handleHeaderLock(); },652      search: () => openList(),653      nav_prev: () => navigate(-1),654      nav_next: () => navigate(1),655      jump_vault: () => setView("entry"),656      jump_settings: () => setView("settings"),657      show_help: () => setShowShortcutsHelp(true),658    };659660    // Actions that are MEANINGFUL only on the entry-detail view. Outside661    // that scope the binding is dormant — pressing C while on Settings662    // does nothing rather than awkwardly copying from a now-stale entry.663    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([664      "copy_password", "copy_username", "copy_totp",665      "edit_entry", "delete_entry", "nav_prev", "nav_next",666    ]);667668    const handleGlobalKeydown = (e: KeyboardEvent) => {669      const v = view();670      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"671        || (e.target as HTMLElement)?.tagName === "TEXTAREA"672        || (e.target as HTMLElement)?.isContentEditable;673      const isPrintableSearchKey =674        e.key.length === 1 &&675        !e.ctrlKey &&676        !e.metaKey &&677        !e.altKey;678679      // No input during the pro celebration sequence680      if (v === "pro-celebration") return;681682      // Help dialog: Escape closes it; eat the keypress so it doesn't683      // also navigate away from the underlying view.684      if (showShortcutsHelp()) {685        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }686        return;687      }688689      // ── Escape — fixed binding (not user-customizable) ───────690      if (e.key === "Escape") {691        if (v === "list") { setView("entry"); return; }692        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }693        if (v === "sync-pairing") { setView("settings"); return; }694      }695696      // Bindings-driven dispatch. Single-key letter bindings without697      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is698      // inside an input, so users can type into search/forms normally.699      const bindings = shortcutBindings();700      for (const action of Object.keys(bindings) as ShortcutAction[]) {701        const binding = bindings[action];702        if (!matchKeybinding(e, binding)) continue;703        // Single-key letter bindings need the input-focus guard. Bindings704        // with any modifier are safe — Ctrl+L doesn't conflict with typing.705        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;706        if (!hasMod && binding.key.length === 1 && inInput) return;707        if (ENTRY_SCOPED.has(action) && v !== "entry") return;708        e.preventDefault();709        SHORTCUT_HANDLERS[action]?.();710        return;711      }712713      // Type-to-search: in entry view, any printable key not consumed by a714      // shortcut above primes the list search seed and opens the list.715      // Kept outside the bindings table because it's a behavior, not a716      // discrete action — every printable character can trigger it.717      if (v === "entry" && !inInput && isPrintableSearchKey) {718        e.preventDefault();719        primeListSearch(e.key);720        return;721      }722    };723    window.addEventListener("keydown", handleGlobalKeydown);724    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));725726    const handleStorageChanged = (727      changes: Record<string, chrome.storage.StorageChange>,728      areaName: string729    ) => {730      if (areaName !== "session") return;731      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {732        return;733      }734      void refreshPendingPasskey();735    };736    chrome.storage.onChanged.addListener(handleStorageChanged);737    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));738  });739740  async function refreshCurrentTab() {741    try {742      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });743      const url = tab?.url ?? tab?.pendingUrl ?? "";744      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");745      // Skip extension/internal URLs — adding chrome://, about:, or746      // chrome-extension:// to a vault entry is never what the user wants.747      const isWebUrl = /^https?:\/\//i.test(url);748      setCurrentTabUrl(isWebUrl ? url : "");749    } catch {750      setCurrentTabDomain("");751      setCurrentTabUrl("");752    }753  }754755  async function refreshPendingPasskey() {756    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });757    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);758  }759760  async function refreshIncomingPairing() {761    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });762    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;763    setIncomingPair(data);764  }765766  // Drains a single one-shot record left by the background when 6-digit767  // pairing succeeded while the popup was closed (or the SyncPairing view was768  // navigated away from before it could show its own success card).769  async function consumeRecentPairing() {770    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });771    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;772    if (data?.deviceName) {773      setRecentPairToast(data.deviceName);774      window.setTimeout(() => setRecentPairToast(null), 4000);775    }776  }777778  async function respondIncomingPairing(accept: boolean) {779    if (incomingPairResponding()) return;780    setIncomingPairResponding(true);781    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });782    setIncomingPair(null);783    setIncomingPairResponding(false);784  }785786  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a787  // request appears, ticks once per second, and clears the banner if the788  // request expires while the popup is open.789  createEffect(() => {790    const req = incomingPair();791    if (!req) return;792    const handle = window.setInterval(() => {793      setIncomingPairTick((tick) => tick + 1);794      if (Date.now() >= req.expiresAt) {795        setIncomingPair(null);796        window.clearInterval(handle);797      }798    }, 1000);799    onCleanup(() => window.clearInterval(handle));800  });801802  async function refreshProStatus() {803    const res = await sendMessage({ type: "GET_LICENSE" });804    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;805    setProStatus(Boolean(data?.valid && data?.plan === "pro"));806  }807808  async function restoreSettings() {809    const res = await sendMessage({ type: "GET_SETTINGS" });810    const s = (res as { ok: boolean; data?: any }).data ?? {};811    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {812      setAccentColor(s.accentColor as AccentColorName);813    }814    setTheme(s.theme === "light" ? "light" : "dark");815    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {816      setDisplayFont(s.displayFont);817    } else {818      setDisplayFont("cormorant-italic");819    }820    if (s.textSize === "small" || s.textSize === "large") {821      setTextSize(s.textSize);822    } else {823      setTextSize("medium");824    }825    setReduceMotion(s.reduceMotion === true);826    setLockOnClose(s.lockOnClose !== false);827    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);828    setBreachMonitoring(s.breachMonitoring !== false);829    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);830    setShortcutBindings(getActiveBindings(s.shortcuts));831  }832833  async function applyTrashRetention(days: number) {834    setTrashRetentionDays(days);835    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });836  }837838  function primeListSearch(seed: string) {839    setListSearchSeed(seed);840    setListSearchSeedNonce((value) => value + 1);841    openList();842  }843844  // Returns null when it detected a dead service worker and triggered handleLock().845  // Callers that need to abort (e.g. openVault) check for null rather than relying846  // on view() state, which may already be "lock" during normal startup flows.847  async function loadEntries(): Promise<VaultEntry[] | null> {848    const response = await sendMessage({ type: "GET_ENTRIES" });849    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };850851    // If the service worker was killed and restarted (MV3 workers sleep), the852    // vault will be locked again — or the worker may not respond at all.853    // In either case, send the user to the lock screen rather than silently854    // showing an empty vault (which looks like data loss).855    if (!res.ok) {856      if (857        res.error === "vault locked" ||858        res.error === "SERVICE_WORKER_UNAVAILABLE" ||859        (typeof res.error === "string" && res.error.includes("locked"))860      ) {861        handleLock();862        return null; // signal emergency lock to callers863      }864      return [];865    }866867    const loadedEntries = res.data ?? [];868    setEntries(loadedEntries);869870    const currentId = selectedEntry()?.id;871    if (currentId) {872      setSelectedEntry(873        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null874      );875    }876877    return loadedEntries;878  }879880  async function openVault(preferredEntryId?: string, skipViewSet = false) {881    // Purge expired trash entries on each vault open882    const retDays = trashRetentionDays();883    if (retDays > 0) {884      void sendMessage({885        type: "PURGE_EXPIRED_TRASH",886        payload: { retentionMs: retDays * 86_400_000 },887      });888    }889890    const loadedEntries = await loadEntries();891892    // null means loadEntries() triggered an emergency lock (service worker died).893    // Don't override it by setting view back to "entry" with an empty vault.894    if (loadedEntries === null) return;895896    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry897    let nextSelectedEntry: VaultEntry | null = null;898    if (preferredEntryId) {899      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;900    }901    if (!nextSelectedEntry) {902      const tabDomain = currentTabDomain();903      if (tabDomain) {904        nextSelectedEntry = loadedEntries.find((e) => {905          if (e.type === "login") {906            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;907            for (const extra of e.additionalUrls ?? []) {908              if ((extractDomain(extra) ?? "") === tabDomain) return true;909            }910            return false;911          }912          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;913          return false;914        }) ?? null;915      }916    }917    nextSelectedEntry ??= loadedEntries[0] ?? null;918919    setSelectedEntry(nextSelectedEntry);920    setEditEntry(undefined);921    setContentTransitioning(false);922    setContentPhase("enter");923    queueContentIdle();924    if (!skipViewSet) setView("entry");925  }926927  async function handleUnlock() {928    // If the user previously created a vault but hadn't yet confirmed their929    // recovery words (and the browser was closed before they could), the930    // peach_recovery_pending flag is still set in storage.local. Re-route931    // back to the recovery surface so they finish the confirmation step932    // before reaching the entries view — the words can be re-derived now933    // that the vault is unlocked again.934    let recoveryPending = false;935    try {936      const out = await chrome.storage.local?.get("peach_recovery_pending");937      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";938    } catch { /* best-effort */ }939    if (recoveryPending) {940      setForceRecoveryWords(true);941      setView("lock");942      triggerPipPulse();943      await restoreSettings();944      return;945    }946    setHasVault(true);947    triggerPipPulse();948    await restoreSettings();949    const celebrating = pendingCelebration();950    if (celebrating) {951      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });952      setPendingCelebration(false);953    }954    await openVault(undefined, celebrating);955    if (celebrating) {956      setView("pro-celebration");957      window.setTimeout(() => setView("entry"), 2500);958    }959  }960961  function handleSelectEntry(entry: VaultEntry) {962    setSelectedEntry(entry);963    setContentTransitioning(false);964    setContentPhase("enter");965    queueContentIdle();966    setView("entry");967  }968969  function handleAdd() {970    setEditEntry(undefined);971    setView("add");972  }973974  async function handleDelete() {975    const entry = selectedEntry();976    if (!entry) return;977    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });978    const loadedEntries = await loadEntries() ?? [];979    setSelectedEntry(loadedEntries[0] ?? null);980    setView("entry");981  }982983  async function handleDeleteMany(ids: string[]) {984    for (const id of ids) {985      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });986    }987    const loadedEntries = await loadEntries() ?? [];988    // If the currently selected entry was among the deleted, move to first989    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);990    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);991  }992993  async function handleSave(savedEntry?: VaultEntry) {994    await openVault(savedEntry?.id);995  }996997  function handleBack() {998    setEditEntry(undefined);999    setView("entry");1000  }10011002  function handleLock() {1003    clearCanarySuppressions();1004    setEntries([]);1005    setSelectedEntry(null);1006    setEditEntry(undefined);1007    setContentPhase("idle");1008    setView("lock");1009  }10101011  function handleHeaderLock() {1012    // Lock the UI immediately — do not wait for the service worker. If the SW1013    // is dead or slow, the 5s sendMessage timeout would create a dead-click1014    // window. The SW will lock on its next wake regardless.1015    handleLock();1016    void sendMessage({ type: "LOCK" });1017  }10181019  function navigate(dir: number) {1020    const allEntries = entries();1021    if (allEntries.length === 0) return;1022    const currentIndex = selectedIndex();1023    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1024    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1025    setSelectedEntry(allEntries[nextIndex]);1026    setContentPhase("enter");1027    queueContentIdle();1028  }10291030  function openList() {1031    setView("list");1032  }10331034  function openHealth() {1035    setEditEntry(undefined);1036    setView("health");1037  }10381039  function handleOpenFileImport() {1040    setRestoreView("file");1041  }10421043  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10441045  function handleFixEntry(entry: VaultEntry) {1046    // Passkey-only entries have no editable surface — drop into view mode1047    // instead of opening the Add editor.1048    if (isPasskeyOnly(entry)) {1049      setSelectedEntry(entry);1050      setView("entry");1051      return;1052    }1053    setEditEntry(entry);1054    setView("add");1055  }10561057  const isLockedView = () => view() === "lock";10581059  async function handleApprovePendingPasskey() {1060    const pending = pendingPasskey();1061    if (!pending) return;1062    if (pending.browser === "firefox" && pending.type === "create") {1063      // Firefox path: popup itself runs navigator.credentials.create. The1064      // background never approved/rejected anything — it just stashed1065      // intent. After the popup-driven flow resolves (success or cancel),1066      // clear the pending key so the popup doesn't re-show this on next open.1067      const { createFirefoxPasskey } = await import("./firefox-passkey");1068      const result = await createFirefoxPasskey(pending);1069      if (!result.ok) {1070        console.warn("Peach Firefox passkey create failed:", result.error);1071      }1072      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1073      setPendingPasskey(null);1074      void loadEntries();1075      return;1076    }1077    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1078    setPendingPasskey(null);1079  }10801081  async function handleDenyPendingPasskey() {1082    const pending = pendingPasskey();1083    if (!pending) return;1084    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1085    setPendingPasskey(null);1086  }10871088  function queueContentIdle(after?: () => void) {1089    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1090    contentPhaseTimer = window.setTimeout(() => {1091      setContentPhase("idle");1092      after?.();1093    }, ENTRY_TRANSITION_SETTLE_MS);1094  }10951096  return (1097    <div class="popup-root peach-theme">1098      <Show when={bootState() === "ready"}>1099        <Show1100          when={!pendingPasskey()}1101          fallback={1102            <PasskeyApprovalView1103              type={pendingPasskey()!.type}1104              rpName={pendingPasskey()!.rpName}1105              rpId={pendingPasskey()!.rpId}1106              userName={pendingPasskey()!.userName}1107              userDisplayName={pendingPasskey()!.userDisplayName}1108              onApprove={handleApprovePendingPasskey}1109              onDeny={handleDenyPendingPasskey}1110            />1111          }1112        >1113          <Show1114            when={!isLockedView()}1115            fallback={1116              <Show1117                when={onboarded() || hasVault()}1118                fallback={1119                  <Onboarding1120                    onComplete={() => { setOnboarded(true); }}1121                  />1122                }1123              >1124                <LockView1125                  hasVault={hasVault()}1126                  ready={bootState() === "ready"}1127                  isPro={proStatus()}1128                  forceRecoveryWords={forceRecoveryWords()}1129                  onUnlock={() => {1130                    // RecoveryWordDisplay clears the storage flag before1131                    // calling onDone, so handleUnlock will see no pending1132                    // confirmation and proceed through the normal path.1133                    if (forceRecoveryWords()) setForceRecoveryWords(false);1134                    return handleUnlock();1135                  }}1136                  onBackToOnboarding={1137                    !hasVault()1138                      ? () => setOnboarded(false)1139                      : undefined1140                  }1141                />1142              </Show>1143            }1144          >1145            <Show1146              when={view() !== "pro-celebration"}1147              fallback={<ProCelebration />}1148            >1149            <section1150              id="hd-shell"1151              class="peach-shell peach-theme"1152              data-surface="extension"1153            >1154            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1155              <PeachWordmark unlocked />1156              <div class="peach-chrome-actions">1157                <button1158                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1159                  onClick={() => { console.log("[peach] settings tap"); setView("settings"); }}1160                  aria-label="Settings"1161                >1162                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1163                    <path1164                      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"1165                      stroke="currentColor"1166                      stroke-width="0.9"1167                    />1168                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1169                  </svg>1170                </button>1171                <button1172                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1173                  onClick={handleAdd}1174                  aria-label="New entry"1175                >1176                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1177                    <path d="M5.5 1v9M1 5.5h9" />1178                  </svg>1179                </button>1180                <button1181                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1182                  onClick={() => void handleHeaderLock()}1183                  aria-label="Lock vault"1184                >1185                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1186                    <path1187                      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"1188                      stroke="currentColor"1189                      stroke-width="1"1190                      stroke-linecap="round"1191                    />1192                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1193                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1194                  </svg>1195                </button>1196              </div>1197            </header>11981199            <Show when={recentPairToast()}>1200              <div class="peach-pair-toast" role="status" aria-live="polite">1201                Paired with <strong>{recentPairToast()}</strong>1202              </div>1203            </Show>12041205            <Show when={incomingPair() !== null}>1206              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1207                <div class="peach-pair-request-header">1208                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1209                  <span class="peach-pair-request-title">Pairing request</span>1210                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1211                </div>1212                <p class="peach-pair-request-body">1213                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1214                </p>1215                <div class="peach-pair-request-actions">1216                  <button1217                    class="peach-btn peach-btn--ghost peach-btn--sm"1218                    onClick={() => void respondIncomingPairing(false)}1219                    disabled={incomingPairResponding()}1220                  >1221                    Reject1222                  </button>1223                  <button1224                    class="peach-btn peach-btn--accent peach-btn--sm"1225                    onClick={() => void respondIncomingPairing(true)}1226                    disabled={incomingPairResponding()}1227                  >1228                    Accept1229                  </button>1230                </div>1231              </div>1232            </Show>12331234            <Show when={pendingProNotice() !== null}>1235              <div class="peach-pro-notice-banner">1236                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1237                <button1238                  class="peach-pro-notice-link"1239                  onClick={() => {1240                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1241                    setSettingsInitialSection("license");1242                    setView("settings");1243                    setPendingProNotice(null);1244                  }}1245                >1246                  Learn more →1247                </button>1248                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1249              </div>1250            </Show>12511252            <div class="peach-shell-body">1253              <div class="peach-shell-veil"></div>1254              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1255                <EntryView1256                  entry={selectedEntry()}1257                  currentTabUrl={currentTabUrl()}1258                  onDelete={handleDelete}1259                  onFieldSaved={() => void loadEntries()}1260                  onEscape={() => { setView("list"); }}1261                />1262              </div>12631264              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1265                <div class="peach-search-bar">1266                  <span class="peach-search-icon">1267                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1268                      <circle cx="5.5" cy="5.5" r="3.75" />1269                      <path d="M8.75 8.75L11.5 11.5" />1270                    </svg>1271                  </span>1272                  <input1273                    class="peach-search-input"1274                    placeholder="search vault..."1275                    autocomplete="off"1276                    aria-label="Search vault entries"1277                    onClick={openList}1278                    onFocus={openList}1279                    readOnly1280                  />1281                  <div class="peach-search-meta">1282                    <span class="peach-search-counter">1283                      {entries().length > 01284                        ? `${selectedIndex() + 1} / ${entries().length}`1285                        : "0 entries"}1286                    </span>1287                    <span class="peach-divider"></span>1288                    <button1289                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1290                      onClick={() => navigate(-1)}1291                      aria-label="Previous entry"1292                      disabled={entries().length === 0}1293                    >1294                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1295                        <path d="M5 1L1 5.5L5 10" />1296                      </svg>1297                    </button>1298                    <button1299                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1300                      onClick={() => navigate(1)}1301                      aria-label="Next entry"1302                      disabled={entries().length === 0}1303                    >1304                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1305                        <path d="M1 1L5 5.5L1 10" />1306                      </svg>1307                    </button>1308                  </div>1309                </div>1310              </section>1311            </div>13121313            {/* Desktop: shown on demand via Show. Native sheet is rendered1314                via Portal below at the document root so its position:fixed1315                isn't trapped by .peach-shell's transform-based animations. */}1316            <Show when={!isNativePlatform() && view() === "list"}>1317              <VaultView1318                entries={entries()}1319                selectedEntryId={selectedEntry()?.id}1320                currentTabDomain={currentTabDomain()}1321                sortOrder={sortOrder()}1322                searchSeed={listSearchSeed()}1323                searchSeedNonce={listSearchSeedNonce()}1324                onSelectEntry={handleSelectEntry}1325                onSortOrderChange={setSortOrder}1326                onAdd={handleAdd}1327                onClose={() => setView("entry")}1328                onOpenTrash={() => setView("trash")}1329                onDeleteMany={handleDeleteMany}1330              />1331            </Show>1332            <Show when={isNativePlatform() && hasVault()}>1333              <Portal>1334                <div1335                  class="peach-vault-sheet"1336                  classList={{ "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1337                  style={(() => {1338                    const live = sheetTranslate();1339                    if (live === null) return undefined;1340                    return { transform: `translateY(${live}px)` };1341                  })()}1342                >1343                  <VaultView1344                    entries={entries()}1345                    selectedEntryId={selectedEntry()?.id}1346                    currentTabDomain={currentTabDomain()}1347                    sortOrder={sortOrder()}1348                    searchSeed={listSearchSeed()}1349                    searchSeedNonce={listSearchSeedNonce()}1350                    onSelectEntry={handleSelectEntry}1351                    onSortOrderChange={setSortOrder}1352                    onAdd={handleAdd}1353                    onClose={() => setView("entry")}1354                    onOpenTrash={() => setView("trash")}1355                    onDeleteMany={handleDeleteMany}1356                  />1357                </div>1358              </Portal>1359            </Show>1360            <Show when={view() === "settings"}>1361              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1362                <SettingsView1363                  entriesCount={entries().length}1364                  breachMonitoring={breachMonitoring()}1365                  lockOnClose={lockOnClose()}1366                  autoLockMinutes={autoLockMinutes()}1367                  trashRetentionDays={trashRetentionDays()}1368                  theme={theme()}1369                  accentColor={accentColor()}1370                  displayFont={displayFont()}1371                  textSize={textSize()}1372                  reduceMotion={reduceMotion()}1373                  isPro={proStatus()}1374                  initialSection={settingsInitialSection()}1375                  upgradeHighlight={upgradeHighlight()}1376                  onBreachMonitoringChange={applyBreachMonitoring}1377                  onLockOnCloseChange={applyLockOnClose}1378                  onAutoLockMinutesChange={applyAutoLockMinutes}1379                  onTrashRetentionChange={applyTrashRetention}1380                  onThemeChange={applyTheme}1381                  onAccentChange={applyAccentColor}1382                  onDisplayFontChange={applyDisplayFont}1383                  onTextSizeChange={applyTextSize}1384                  onReduceMotionChange={applyReduceMotion}1385                  shortcuts={shortcutBindings()}1386                  onShortcutsChange={applyShortcuts}1387                  onLicenseChange={async () => {1388                    // After activation/deactivation: refresh Pro status,1389                    // re-load entries (defensive — signal state can drift if1390                    // the SW briefly restarts during the verify+save round-trip),1391                    // and replay the Pro celebration if this is the first time1392                    // a valid Pro license is seen on this device.1393                    await refreshProStatus();1394                    void loadEntries();1395                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1396                    if ((should as { ok: boolean; data?: boolean }).data === true) {1397                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1398                      setView("pro-celebration");1399                      window.setTimeout(() => setView("settings"), 2500);1400                    }1401                  }}1402                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1403                  onImport={() => setView("import")}1404                  onExport={() => setView("export")}1405                  onBreachCheckDone={loadEntries}1406                  onOpenHealth={openHealth}1407                  onOpenSyncPairing={() => setView("sync-pairing")}1408                  onOpenFileImport={handleOpenFileImport}1409                  onOpenPanic={() => setView("panic")}1410                />1411              </Suspense>1412            </Show>1413            <Show when={view() === "sync-pairing"}>1414              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1415                <SyncPairingView1416                  onClose={() => setView("settings")}1417                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1418                />1419              </Suspense>1420            </Show>1421            <Show when={view() === "add"}>1422              <AddView1423                entry={editEntry()}1424                entries={entries()}1425                onBack={handleBack}1426                onSave={handleSave}1427              />1428            </Show>1429            <Show when={view() === "import"}>1430              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1431                <ImportView onBack={handleBack} onImport={handleSave} />1432              </Suspense>1433            </Show>1434            <Show when={view() === "export"}>1435              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1436                <ExportView1437                  onBack={() => {1438                    if (returnToPanic()) {1439                      setReturnToPanic(false);1440                      setView("panic");1441                    } else {1442                      handleBack();1443                    }1444                  }}1445                />1446              </Suspense>1447            </Show>1448            <Show when={view() === "panic"}>1449              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1450                <PanicView1451                  onCancel={() => setView("settings")}1452                  onOpenExport={() => {1453                    setReturnToPanic(true);1454                    setView("export");1455                  }}1456                  onDestroyed={async () => {1457                    clearCanarySuppressions();1458                    setEntries([]);1459                    setSelectedEntry(null);1460                    setEditEntry(undefined);1461                    setHasVault(false);1462                    setOnboarded(false);1463                    setProStatus(false);1464                    setPendingPasskey(null);1465                    setUpgradeHighlight(null);1466                    setSettingsInitialSection(null);1467                    setPendingProNotice(null);1468                    setPendingCelebration(false);1469                    setReturnToPanic(false);1470                    setContentPhase("idle");1471                    setView("lock");1472                  }}1473                />1474              </Suspense>1475            </Show>1476            <Show when={view() === "health"}>1477              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1478                <HealthView1479                  entries={entries()}1480                  isPro={proStatus()}1481                  onFixEntry={handleFixEntry}1482                  onBack={() => setView("settings")}1483                  onRefresh={loadEntries}1484                />1485              </Suspense>1486            </Show>1487            <Show when={view() === "trash"}>1488              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1489                <TrashView1490                  onBack={() => setView("list")}1491                  onRestored={() => void loadEntries()}1492                />1493              </Suspense>1494            </Show>1495            <Show when={restoreView() === "file"}>1496              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1497                <ImportView1498                  mode="onboarding"1499                  replacesExistingVault={true}1500                  onBack={() => setRestoreView(null)}1501                  onImport={async () => {1502                    setRestoreView(null);1503                    await handleUnlock();1504                  }}1505                />1506              </Suspense>1507            </Show>1508            </section>1509            </Show>1510          </Show>1511        </Show>1512      </Show>1513      <Show when={showShortcutsHelp()}>1514        <ShortcutsHelpOverlay1515          bindings={shortcutBindings()}1516          onClose={() => setShowShortcutsHelp(false)}1517        />1518      </Show>1519    </div>1520  );1521}15221523function ShortcutsHelpOverlay(props: {1524  bindings: Record<ShortcutAction, Keybinding>;1525  onClose: () => void;1526}) {1527  return (1528    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1529      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1530        <div class="peach-shortcuts-help-head">1531          <h3>Keyboard shortcuts</h3>1532          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1533        </div>1534        <div class="peach-shortcuts-help-body">1535          <p class="peach-settings-sub-label">ENTRY VIEW</p>1536          <ul>1537            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1538              <li>1539                <span>{d.label}</span>1540                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1541              </li>1542            ))}1543          </ul>1544          <p class="peach-settings-sub-label">ANYWHERE</p>1545          <ul>1546            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1547              <li>1548                <span>{d.label}</span>1549                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1550              </li>1551            ))}1552          </ul>1553        </div>1554      </div>1555    </div>1556  );1557}