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    };488    chrome.runtime.onMessage.addListener(handleRuntimeMessage);489    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));490491    // Android hardware/gesture back. MainActivity fires peach:back; the popup492    // decides what "back" means per surface. Lock+no-vault is the common case493    // — return to onboarding rather than letting the OS dismiss the activity.494    const handlePeachBack = () => {495      const v = view();496      if (v === "lock" && !hasVault() && onboarded()) {497        setOnboarded(false);498        return;499      }500      if (v === "list") { setView("entry"); return; }501      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {502        handleBack();503        return;504      }505      if (v === "sync-pairing") { setView("settings"); return; }506    };507    window.addEventListener("peach:back", handlePeachBack);508    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));509510    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that511    // peeks from the bottom (search bar handle visible) and drags up to fill512    // the screen. dragOffset is the LIVE finger offset during a drag, in px,513    // 0 when no drag in progress. The wrapper element computes transform =514    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.515    if (isNativePlatform()) {516      let touchStartY = 0;517      let touchStartX = 0;518      let lastY = 0;519      let lastT = 0;520      let dragging = false;521      let captured = false;522      const HORIZONTAL_TOLERANCE = 16;523      const ACTIVATION_DY = 8;524      const PEEK_PX = 60;525526      const onTouchStart = (e: TouchEvent) => {527        const t = e.touches[0];528        if (!t) return;529        const v = view();530        if (v !== "entry" && v !== "list") return;531        // Entry view: only intercept drags starting in the bottom 40%.532        // List view: intercept drags starting in the top 35% (the search/handle row).533        const inBand = v === "entry"534          ? t.clientY > window.innerHeight * 0.6535          : t.clientY < window.innerHeight * 0.35;536        if (!inBand) return;537        touchStartY = lastY = t.clientY;538        touchStartX = t.clientX;539        lastT = e.timeStamp;540        dragging = true;541        captured = false;542      };543544      const onTouchMove = (e: TouchEvent) => {545        if (!dragging) return;546        const t = e.touches[0];547        if (!t) return;548        const dy = t.clientY - touchStartY;549        const dx = Math.abs(t.clientX - touchStartX);550551        if (!captured) {552          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {553            // Looks like a horizontal swipe — release.554            dragging = false;555            return;556          }557          if (Math.abs(dy) < ACTIVATION_DY) return;558          captured = true;559        }560561        // Translate the sheet by dy from its rest (peek) position. Peek is562        // (viewport height - PEEK_PX). Open is 0.563        const v = view();564        const restClosed = window.innerHeight - PEEK_PX;565        const baseTranslate = v === "list" ? 0 : restClosed;566        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));567        setSheetTranslate(next);568        lastY = t.clientY;569        lastT = e.timeStamp;570      };571572      const onTouchEnd = (e: TouchEvent) => {573        if (!dragging) { return; }574        const t = e.changedTouches[0];575        const elapsed = Math.max(1, e.timeStamp - lastT);576        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms577        const wasCaptured = captured;578        dragging = false;579        captured = false;580581        if (!wasCaptured) {582          // Tap in the peek strip while in entry view → open the vault list.583          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");584          setSheetTranslate(null);585          return;586        }587588        const restClosed = window.innerHeight - PEEK_PX;589        const current = sheetTranslate() ?? restClosed;590        const v = view();591592        // Snap rules:593        //   - Strong upward velocity → open594        //   - Strong downward velocity → close595        //   - Otherwise snap to whichever rest is closer596        let nextOpen: boolean;597        if (velocity < -0.05) nextOpen = true;598        else if (velocity > 0.05) nextOpen = false;599        else nextOpen = current < restClosed * 0.5;600601        if (nextOpen && v !== "list") setView("list");602        if (!nextOpen && v !== "entry") setView("entry");603        // Release the live offset so CSS transition handles the snap.604        setSheetTranslate(null);605      };606607      document.addEventListener("touchstart", onTouchStart, { passive: true });608      document.addEventListener("touchmove",  onTouchMove,  { passive: true });609      document.addEventListener("touchend",   onTouchEnd,   { passive: true });610      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });611      onCleanup(() => {612        document.removeEventListener("touchstart", onTouchStart);613        document.removeEventListener("touchmove",  onTouchMove);614        document.removeEventListener("touchend",   onTouchEnd);615      });616    }617618    // Action handlers — keyed by ShortcutAction. The dispatcher below tests619    // each binding against the event and runs the matching handler. New620    // shortcuts only need an entry here; the binding is data, not code.621    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {622      copy_password: () => {623        const entry = selectedEntry();624        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });625      },626      copy_username: () => {627        const entry = selectedEntry();628        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });629      },630      copy_totp: () => {631        const entry = selectedEntry();632        if (!entry?.totp) return;633        try {634          const { code } = generateTOTP(entry.totp);635          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });636        } catch { /* invalid TOTP secret — silent */ }637      },638      new_entry: () => handleAdd(),639      edit_entry: () => {640        const entry = selectedEntry();641        // Passkey-only entries have nothing user-editable in the Add view; the642        // passkey credential itself is opaque. Skip the edit action for them.643        if (!entry || isPasskeyOnly(entry)) return;644        setEditEntry(entry);645        setView("add");646      },647      delete_entry: () => {648        if (selectedEntry()) void handleDelete();649      },650      lock_vault: () => { void handleHeaderLock(); },651      search: () => openList(),652      nav_prev: () => navigate(-1),653      nav_next: () => navigate(1),654      jump_vault: () => setView("entry"),655      jump_settings: () => setView("settings"),656      show_help: () => setShowShortcutsHelp(true),657    };658659    // Actions that are MEANINGFUL only on the entry-detail view. Outside660    // that scope the binding is dormant — pressing C while on Settings661    // does nothing rather than awkwardly copying from a now-stale entry.662    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([663      "copy_password", "copy_username", "copy_totp",664      "edit_entry", "delete_entry", "nav_prev", "nav_next",665    ]);666667    const handleGlobalKeydown = (e: KeyboardEvent) => {668      const v = view();669      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"670        || (e.target as HTMLElement)?.tagName === "TEXTAREA"671        || (e.target as HTMLElement)?.isContentEditable;672      const isPrintableSearchKey =673        e.key.length === 1 &&674        !e.ctrlKey &&675        !e.metaKey &&676        !e.altKey;677678      // No input during the pro celebration sequence679      if (v === "pro-celebration") return;680681      // Help dialog: Escape closes it; eat the keypress so it doesn't682      // also navigate away from the underlying view.683      if (showShortcutsHelp()) {684        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }685        return;686      }687688      // ── Escape — fixed binding (not user-customizable) ───────689      if (e.key === "Escape") {690        if (v === "list") { setView("entry"); return; }691        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }692        if (v === "sync-pairing") { setView("settings"); return; }693      }694695      // Bindings-driven dispatch. Single-key letter bindings without696      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is697      // inside an input, so users can type into search/forms normally.698      const bindings = shortcutBindings();699      for (const action of Object.keys(bindings) as ShortcutAction[]) {700        const binding = bindings[action];701        if (!matchKeybinding(e, binding)) continue;702        // Single-key letter bindings need the input-focus guard. Bindings703        // with any modifier are safe — Ctrl+L doesn't conflict with typing.704        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;705        if (!hasMod && binding.key.length === 1 && inInput) return;706        if (ENTRY_SCOPED.has(action) && v !== "entry") return;707        e.preventDefault();708        SHORTCUT_HANDLERS[action]?.();709        return;710      }711712      // Type-to-search: in entry view, any printable key not consumed by a713      // shortcut above primes the list search seed and opens the list.714      // Kept outside the bindings table because it's a behavior, not a715      // discrete action — every printable character can trigger it.716      if (v === "entry" && !inInput && isPrintableSearchKey) {717        e.preventDefault();718        primeListSearch(e.key);719        return;720      }721    };722    window.addEventListener("keydown", handleGlobalKeydown);723    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));724725    const handleStorageChanged = (726      changes: Record<string, chrome.storage.StorageChange>,727      areaName: string728    ) => {729      if (areaName !== "session") return;730      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {731        return;732      }733      void refreshPendingPasskey();734    };735    chrome.storage.onChanged.addListener(handleStorageChanged);736    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));737  });738739  async function refreshCurrentTab() {740    try {741      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });742      const url = tab?.url ?? tab?.pendingUrl ?? "";743      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");744      // Skip extension/internal URLs — adding chrome://, about:, or745      // chrome-extension:// to a vault entry is never what the user wants.746      const isWebUrl = /^https?:\/\//i.test(url);747      setCurrentTabUrl(isWebUrl ? url : "");748    } catch {749      setCurrentTabDomain("");750      setCurrentTabUrl("");751    }752  }753754  async function refreshPendingPasskey() {755    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });756    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);757  }758759  async function refreshIncomingPairing() {760    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });761    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;762    setIncomingPair(data);763  }764765  // Drains a single one-shot record left by the background when 6-digit766  // pairing succeeded while the popup was closed (or the SyncPairing view was767  // navigated away from before it could show its own success card).768  async function consumeRecentPairing() {769    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });770    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;771    if (data?.deviceName) {772      setRecentPairToast(data.deviceName);773      window.setTimeout(() => setRecentPairToast(null), 4000);774    }775  }776777  async function respondIncomingPairing(accept: boolean) {778    if (incomingPairResponding()) return;779    setIncomingPairResponding(true);780    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });781    setIncomingPair(null);782    setIncomingPairResponding(false);783  }784785  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a786  // request appears, ticks once per second, and clears the banner if the787  // request expires while the popup is open.788  createEffect(() => {789    const req = incomingPair();790    if (!req) return;791    const handle = window.setInterval(() => {792      setIncomingPairTick((tick) => tick + 1);793      if (Date.now() >= req.expiresAt) {794        setIncomingPair(null);795        window.clearInterval(handle);796      }797    }, 1000);798    onCleanup(() => window.clearInterval(handle));799  });800801  async function refreshProStatus() {802    const res = await sendMessage({ type: "GET_LICENSE" });803    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;804    setProStatus(Boolean(data?.valid && data?.plan === "pro"));805  }806807  async function restoreSettings() {808    const res = await sendMessage({ type: "GET_SETTINGS" });809    const s = (res as { ok: boolean; data?: any }).data ?? {};810    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {811      setAccentColor(s.accentColor as AccentColorName);812    }813    setTheme(s.theme === "light" ? "light" : "dark");814    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {815      setDisplayFont(s.displayFont);816    } else {817      setDisplayFont("cormorant-italic");818    }819    if (s.textSize === "small" || s.textSize === "large") {820      setTextSize(s.textSize);821    } else {822      setTextSize("medium");823    }824    setReduceMotion(s.reduceMotion === true);825    setLockOnClose(s.lockOnClose !== false);826    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);827    setBreachMonitoring(s.breachMonitoring !== false);828    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);829    setShortcutBindings(getActiveBindings(s.shortcuts));830  }831832  async function applyTrashRetention(days: number) {833    setTrashRetentionDays(days);834    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });835  }836837  function primeListSearch(seed: string) {838    setListSearchSeed(seed);839    setListSearchSeedNonce((value) => value + 1);840    openList();841  }842843  // Returns null when it detected a dead service worker and triggered handleLock().844  // Callers that need to abort (e.g. openVault) check for null rather than relying845  // on view() state, which may already be "lock" during normal startup flows.846  async function loadEntries(): Promise<VaultEntry[] | null> {847    const response = await sendMessage({ type: "GET_ENTRIES" });848    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };849850    // If the service worker was killed and restarted (MV3 workers sleep), the851    // vault will be locked again — or the worker may not respond at all.852    // In either case, send the user to the lock screen rather than silently853    // showing an empty vault (which looks like data loss).854    if (!res.ok) {855      if (856        res.error === "vault locked" ||857        res.error === "SERVICE_WORKER_UNAVAILABLE" ||858        (typeof res.error === "string" && res.error.includes("locked"))859      ) {860        handleLock();861        return null; // signal emergency lock to callers862      }863      return [];864    }865866    const loadedEntries = res.data ?? [];867    setEntries(loadedEntries);868869    const currentId = selectedEntry()?.id;870    if (currentId) {871      setSelectedEntry(872        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null873      );874    }875876    return loadedEntries;877  }878879  async function openVault(preferredEntryId?: string, skipViewSet = false) {880    // Purge expired trash entries on each vault open881    const retDays = trashRetentionDays();882    if (retDays > 0) {883      void sendMessage({884        type: "PURGE_EXPIRED_TRASH",885        payload: { retentionMs: retDays * 86_400_000 },886      });887    }888889    const loadedEntries = await loadEntries();890891    // null means loadEntries() triggered an emergency lock (service worker died).892    // Don't override it by setting view back to "entry" with an empty vault.893    if (loadedEntries === null) return;894895    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry896    let nextSelectedEntry: VaultEntry | null = null;897    if (preferredEntryId) {898      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;899    }900    if (!nextSelectedEntry) {901      const tabDomain = currentTabDomain();902      if (tabDomain) {903        nextSelectedEntry = loadedEntries.find((e) => {904          if (e.type === "login") {905            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;906            for (const extra of e.additionalUrls ?? []) {907              if ((extractDomain(extra) ?? "") === tabDomain) return true;908            }909            return false;910          }911          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;912          return false;913        }) ?? null;914      }915    }916    nextSelectedEntry ??= loadedEntries[0] ?? null;917918    setSelectedEntry(nextSelectedEntry);919    setEditEntry(undefined);920    setContentTransitioning(false);921    setContentPhase("enter");922    queueContentIdle();923    if (!skipViewSet) setView("entry");924  }925926  async function handleUnlock() {927    // If the user previously created a vault but hadn't yet confirmed their928    // recovery words (and the browser was closed before they could), the929    // peach_recovery_pending flag is still set in storage.local. Re-route930    // back to the recovery surface so they finish the confirmation step931    // before reaching the entries view — the words can be re-derived now932    // that the vault is unlocked again.933    let recoveryPending = false;934    try {935      const out = await chrome.storage.local?.get("peach_recovery_pending");936      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";937    } catch { /* best-effort */ }938    if (recoveryPending) {939      setForceRecoveryWords(true);940      setView("lock");941      triggerPipPulse();942      await restoreSettings();943      return;944    }945    setHasVault(true);946    triggerPipPulse();947    await restoreSettings();948    const celebrating = pendingCelebration();949    if (celebrating) {950      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });951      setPendingCelebration(false);952    }953    await openVault(undefined, celebrating);954    if (celebrating) {955      setView("pro-celebration");956      window.setTimeout(() => setView("entry"), 2500);957    }958  }959960  function handleSelectEntry(entry: VaultEntry) {961    setSelectedEntry(entry);962    setContentTransitioning(false);963    setContentPhase("enter");964    queueContentIdle();965    setView("entry");966  }967968  function handleAdd() {969    setEditEntry(undefined);970    setView("add");971  }972973  async function handleDelete() {974    const entry = selectedEntry();975    if (!entry) return;976    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });977    const loadedEntries = await loadEntries() ?? [];978    setSelectedEntry(loadedEntries[0] ?? null);979    setView("entry");980  }981982  async function handleDeleteMany(ids: string[]) {983    for (const id of ids) {984      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });985    }986    const loadedEntries = await loadEntries() ?? [];987    // If the currently selected entry was among the deleted, move to first988    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);989    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);990  }991992  async function handleSave(savedEntry?: VaultEntry) {993    await openVault(savedEntry?.id);994  }995996  function handleBack() {997    setEditEntry(undefined);998    setView("entry");999  }10001001  function handleLock() {1002    clearCanarySuppressions();1003    setEntries([]);1004    setSelectedEntry(null);1005    setEditEntry(undefined);1006    setContentPhase("idle");1007    setView("lock");1008  }10091010  function handleHeaderLock() {1011    // Lock the UI immediately — do not wait for the service worker. If the SW1012    // is dead or slow, the 5s sendMessage timeout would create a dead-click1013    // window. The SW will lock on its next wake regardless.1014    handleLock();1015    void sendMessage({ type: "LOCK" });1016  }10171018  function navigate(dir: number) {1019    const allEntries = entries();1020    if (allEntries.length === 0) return;1021    const currentIndex = selectedIndex();1022    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1023    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1024    setSelectedEntry(allEntries[nextIndex]);1025    setContentPhase("enter");1026    queueContentIdle();1027  }10281029  function openList() {1030    setView("list");1031  }10321033  function openHealth() {1034    setEditEntry(undefined);1035    setView("health");1036  }10371038  function handleOpenFileImport() {1039    setRestoreView("file");1040  }10411042  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10431044  function handleFixEntry(entry: VaultEntry) {1045    // Passkey-only entries have no editable surface — drop into view mode1046    // instead of opening the Add editor.1047    if (isPasskeyOnly(entry)) {1048      setSelectedEntry(entry);1049      setView("entry");1050      return;1051    }1052    setEditEntry(entry);1053    setView("add");1054  }10551056  const isLockedView = () => view() === "lock";10571058  async function handleApprovePendingPasskey() {1059    const pending = pendingPasskey();1060    if (!pending) return;1061    if (pending.browser === "firefox" && pending.type === "create") {1062      // Firefox path: popup itself runs navigator.credentials.create. The1063      // background never approved/rejected anything — it just stashed1064      // intent. After the popup-driven flow resolves (success or cancel),1065      // clear the pending key so the popup doesn't re-show this on next open.1066      const { createFirefoxPasskey } = await import("./firefox-passkey");1067      const result = await createFirefoxPasskey(pending);1068      if (!result.ok) {1069        console.warn("Peach Firefox passkey create failed:", result.error);1070      }1071      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1072      setPendingPasskey(null);1073      void loadEntries();1074      return;1075    }1076    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1077    setPendingPasskey(null);1078  }10791080  async function handleDenyPendingPasskey() {1081    const pending = pendingPasskey();1082    if (!pending) return;1083    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1084    setPendingPasskey(null);1085  }10861087  function queueContentIdle(after?: () => void) {1088    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1089    contentPhaseTimer = window.setTimeout(() => {1090      setContentPhase("idle");1091      after?.();1092    }, ENTRY_TRANSITION_SETTLE_MS);1093  }10941095  return (1096    <div class="popup-root peach-theme">1097      <Show when={bootState() === "ready"}>1098        <Show1099          when={!pendingPasskey()}1100          fallback={1101            <PasskeyApprovalView1102              type={pendingPasskey()!.type}1103              rpName={pendingPasskey()!.rpName}1104              rpId={pendingPasskey()!.rpId}1105              userName={pendingPasskey()!.userName}1106              userDisplayName={pendingPasskey()!.userDisplayName}1107              onApprove={handleApprovePendingPasskey}1108              onDeny={handleDenyPendingPasskey}1109            />1110          }1111        >1112          <Show1113            when={!isLockedView()}1114            fallback={1115              <Show1116                when={onboarded() || hasVault()}1117                fallback={1118                  <Onboarding1119                    onComplete={() => { setOnboarded(true); }}1120                  />1121                }1122              >1123                <LockView1124                  hasVault={hasVault()}1125                  ready={bootState() === "ready"}1126                  isPro={proStatus()}1127                  forceRecoveryWords={forceRecoveryWords()}1128                  onUnlock={() => {1129                    // RecoveryWordDisplay clears the storage flag before1130                    // calling onDone, so handleUnlock will see no pending1131                    // confirmation and proceed through the normal path.1132                    if (forceRecoveryWords()) setForceRecoveryWords(false);1133                    return handleUnlock();1134                  }}1135                  onBackToOnboarding={1136                    !hasVault()1137                      ? () => setOnboarded(false)1138                      : undefined1139                  }1140                />1141              </Show>1142            }1143          >1144            <Show1145              when={view() !== "pro-celebration"}1146              fallback={<ProCelebration />}1147            >1148            <section1149              id="hd-shell"1150              class="peach-shell peach-theme"1151              data-surface="extension"1152            >1153            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1154              <PeachWordmark unlocked />1155              <div class="peach-chrome-actions">1156                <button1157                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1158                  onClick={() => setView("settings")}1159                  aria-label="Settings"1160                >1161                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1162                    <path1163                      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"1164                      stroke="currentColor"1165                      stroke-width="0.9"1166                    />1167                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1168                  </svg>1169                </button>1170                <button1171                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1172                  onClick={handleAdd}1173                  aria-label="New entry"1174                >1175                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1176                    <path d="M5.5 1v9M1 5.5h9" />1177                  </svg>1178                </button>1179                <button1180                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1181                  onClick={() => void handleHeaderLock()}1182                  aria-label="Lock vault"1183                >1184                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1185                    <path1186                      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"1187                      stroke="currentColor"1188                      stroke-width="1"1189                      stroke-linecap="round"1190                    />1191                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1192                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1193                  </svg>1194                </button>1195              </div>1196            </header>11971198            <Show when={recentPairToast()}>1199              <div class="peach-pair-toast" role="status" aria-live="polite">1200                Paired with <strong>{recentPairToast()}</strong>1201              </div>1202            </Show>12031204            <Show when={incomingPair() !== null}>1205              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1206                <div class="peach-pair-request-header">1207                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1208                  <span class="peach-pair-request-title">Pairing request</span>1209                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1210                </div>1211                <p class="peach-pair-request-body">1212                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1213                </p>1214                <div class="peach-pair-request-actions">1215                  <button1216                    class="peach-btn peach-btn--ghost peach-btn--sm"1217                    onClick={() => void respondIncomingPairing(false)}1218                    disabled={incomingPairResponding()}1219                  >1220                    Reject1221                  </button>1222                  <button1223                    class="peach-btn peach-btn--accent peach-btn--sm"1224                    onClick={() => void respondIncomingPairing(true)}1225                    disabled={incomingPairResponding()}1226                  >1227                    Accept1228                  </button>1229                </div>1230              </div>1231            </Show>12321233            <Show when={pendingProNotice() !== null}>1234              <div class="peach-pro-notice-banner">1235                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1236                <button1237                  class="peach-pro-notice-link"1238                  onClick={() => {1239                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1240                    setSettingsInitialSection("license");1241                    setView("settings");1242                    setPendingProNotice(null);1243                  }}1244                >1245                  Learn more →1246                </button>1247                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1248              </div>1249            </Show>12501251            <div class="peach-shell-body">1252              <div class="peach-shell-veil"></div>1253              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1254                <EntryView1255                  entry={selectedEntry()}1256                  currentTabUrl={currentTabUrl()}1257                  onDelete={handleDelete}1258                  onFieldSaved={() => void loadEntries()}1259                  onEscape={() => { setView("list"); }}1260                />1261              </div>12621263              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1264                <div class="peach-search-bar">1265                  <span class="peach-search-icon">1266                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1267                      <circle cx="5.5" cy="5.5" r="3.75" />1268                      <path d="M8.75 8.75L11.5 11.5" />1269                    </svg>1270                  </span>1271                  <input1272                    class="peach-search-input"1273                    placeholder="search vault..."1274                    autocomplete="off"1275                    aria-label="Search vault entries"1276                    onClick={openList}1277                    onFocus={openList}1278                    readOnly1279                  />1280                  <div class="peach-search-meta">1281                    <span class="peach-search-counter">1282                      {entries().length > 01283                        ? `${selectedIndex() + 1} / ${entries().length}`1284                        : "0 entries"}1285                    </span>1286                    <span class="peach-divider"></span>1287                    <button1288                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1289                      onClick={() => navigate(-1)}1290                      aria-label="Previous entry"1291                      disabled={entries().length === 0}1292                    >1293                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1294                        <path d="M5 1L1 5.5L5 10" />1295                      </svg>1296                    </button>1297                    <button1298                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1299                      onClick={() => navigate(1)}1300                      aria-label="Next entry"1301                      disabled={entries().length === 0}1302                    >1303                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1304                        <path d="M1 1L5 5.5L1 10" />1305                      </svg>1306                    </button>1307                  </div>1308                </div>1309              </section>1310            </div>13111312            {/* Desktop: shown on demand via Show. Native sheet is rendered1313                via Portal below at the document root so its position:fixed1314                isn't trapped by .peach-shell's transform-based animations. */}1315            <Show when={!isNativePlatform() && view() === "list"}>1316              <VaultView1317                entries={entries()}1318                selectedEntryId={selectedEntry()?.id}1319                currentTabDomain={currentTabDomain()}1320                sortOrder={sortOrder()}1321                searchSeed={listSearchSeed()}1322                searchSeedNonce={listSearchSeedNonce()}1323                onSelectEntry={handleSelectEntry}1324                onSortOrderChange={setSortOrder}1325                onAdd={handleAdd}1326                onClose={() => setView("entry")}1327                onOpenTrash={() => setView("trash")}1328                onDeleteMany={handleDeleteMany}1329              />1330            </Show>1331            <Show when={isNativePlatform() && hasVault()}>1332              <Portal>1333                <div1334                  class="peach-vault-sheet"1335                  classList={{ "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1336                  style={(() => {1337                    const live = sheetTranslate();1338                    if (live === null) return undefined;1339                    return { transform: `translateY(${live}px)` };1340                  })()}1341                >1342                  <VaultView1343                    entries={entries()}1344                    selectedEntryId={selectedEntry()?.id}1345                    currentTabDomain={currentTabDomain()}1346                    sortOrder={sortOrder()}1347                    searchSeed={listSearchSeed()}1348                    searchSeedNonce={listSearchSeedNonce()}1349                    onSelectEntry={handleSelectEntry}1350                    onSortOrderChange={setSortOrder}1351                    onAdd={handleAdd}1352                    onClose={() => setView("entry")}1353                    onOpenTrash={() => setView("trash")}1354                    onDeleteMany={handleDeleteMany}1355                  />1356                </div>1357              </Portal>1358            </Show>1359            <Show when={view() === "settings"}>1360              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1361                <SettingsView1362                  entriesCount={entries().length}1363                  breachMonitoring={breachMonitoring()}1364                  lockOnClose={lockOnClose()}1365                  autoLockMinutes={autoLockMinutes()}1366                  trashRetentionDays={trashRetentionDays()}1367                  theme={theme()}1368                  accentColor={accentColor()}1369                  displayFont={displayFont()}1370                  textSize={textSize()}1371                  reduceMotion={reduceMotion()}1372                  isPro={proStatus()}1373                  initialSection={settingsInitialSection()}1374                  upgradeHighlight={upgradeHighlight()}1375                  onBreachMonitoringChange={applyBreachMonitoring}1376                  onLockOnCloseChange={applyLockOnClose}1377                  onAutoLockMinutesChange={applyAutoLockMinutes}1378                  onTrashRetentionChange={applyTrashRetention}1379                  onThemeChange={applyTheme}1380                  onAccentChange={applyAccentColor}1381                  onDisplayFontChange={applyDisplayFont}1382                  onTextSizeChange={applyTextSize}1383                  onReduceMotionChange={applyReduceMotion}1384                  shortcuts={shortcutBindings()}1385                  onShortcutsChange={applyShortcuts}1386                  onLicenseChange={async () => {1387                    // After activation/deactivation: refresh Pro status,1388                    // re-load entries (defensive — signal state can drift if1389                    // the SW briefly restarts during the verify+save round-trip),1390                    // and replay the Pro celebration if this is the first time1391                    // a valid Pro license is seen on this device.1392                    await refreshProStatus();1393                    void loadEntries();1394                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1395                    if ((should as { ok: boolean; data?: boolean }).data === true) {1396                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1397                      setView("pro-celebration");1398                      window.setTimeout(() => setView("settings"), 2500);1399                    }1400                  }}1401                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1402                  onImport={() => setView("import")}1403                  onExport={() => setView("export")}1404                  onBreachCheckDone={loadEntries}1405                  onOpenHealth={openHealth}1406                  onOpenSyncPairing={() => setView("sync-pairing")}1407                  onOpenFileImport={handleOpenFileImport}1408                  onOpenPanic={() => setView("panic")}1409                />1410              </Suspense>1411            </Show>1412            <Show when={view() === "sync-pairing"}>1413              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1414                <SyncPairingView1415                  onClose={() => setView("settings")}1416                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1417                />1418              </Suspense>1419            </Show>1420            <Show when={view() === "add"}>1421              <AddView1422                entry={editEntry()}1423                entries={entries()}1424                onBack={handleBack}1425                onSave={handleSave}1426              />1427            </Show>1428            <Show when={view() === "import"}>1429              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1430                <ImportView onBack={handleBack} onImport={handleSave} />1431              </Suspense>1432            </Show>1433            <Show when={view() === "export"}>1434              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1435                <ExportView1436                  onBack={() => {1437                    if (returnToPanic()) {1438                      setReturnToPanic(false);1439                      setView("panic");1440                    } else {1441                      handleBack();1442                    }1443                  }}1444                />1445              </Suspense>1446            </Show>1447            <Show when={view() === "panic"}>1448              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1449                <PanicView1450                  onCancel={() => setView("settings")}1451                  onOpenExport={() => {1452                    setReturnToPanic(true);1453                    setView("export");1454                  }}1455                  onDestroyed={async () => {1456                    clearCanarySuppressions();1457                    setEntries([]);1458                    setSelectedEntry(null);1459                    setEditEntry(undefined);1460                    setHasVault(false);1461                    setOnboarded(false);1462                    setProStatus(false);1463                    setPendingPasskey(null);1464                    setUpgradeHighlight(null);1465                    setSettingsInitialSection(null);1466                    setPendingProNotice(null);1467                    setPendingCelebration(false);1468                    setReturnToPanic(false);1469                    setContentPhase("idle");1470                    setView("lock");1471                  }}1472                />1473              </Suspense>1474            </Show>1475            <Show when={view() === "health"}>1476              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1477                <HealthView1478                  entries={entries()}1479                  isPro={proStatus()}1480                  onFixEntry={handleFixEntry}1481                  onBack={() => setView("settings")}1482                  onRefresh={loadEntries}1483                />1484              </Suspense>1485            </Show>1486            <Show when={view() === "trash"}>1487              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1488                <TrashView1489                  onBack={() => setView("list")}1490                  onRestored={() => void loadEntries()}1491                />1492              </Suspense>1493            </Show>1494            <Show when={restoreView() === "file"}>1495              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1496                <ImportView1497                  mode="onboarding"1498                  replacesExistingVault={true}1499                  onBack={() => setRestoreView(null)}1500                  onImport={async () => {1501                    setRestoreView(null);1502                    await handleUnlock();1503                  }}1504                />1505              </Suspense>1506            </Show>1507            </section>1508            </Show>1509          </Show>1510        </Show>1511      </Show>1512      <Show when={showShortcutsHelp()}>1513        <ShortcutsHelpOverlay1514          bindings={shortcutBindings()}1515          onClose={() => setShowShortcutsHelp(false)}1516        />1517      </Show>1518    </div>1519  );1520}15211522function ShortcutsHelpOverlay(props: {1523  bindings: Record<ShortcutAction, Keybinding>;1524  onClose: () => void;1525}) {1526  return (1527    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1528      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1529        <div class="peach-shortcuts-help-head">1530          <h3>Keyboard shortcuts</h3>1531          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1532        </div>1533        <div class="peach-shortcuts-help-body">1534          <p class="peach-settings-sub-label">ENTRY VIEW</p>1535          <ul>1536            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1537              <li>1538                <span>{d.label}</span>1539                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1540              </li>1541            ))}1542          </ul>1543          <p class="peach-settings-sub-label">ANYWHERE</p>1544          <ul>1545            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1546              <li>1547                <span>{d.label}</span>1548                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1549              </li>1550            ))}1551          </ul>1552        </div>1553      </div>1554    </div>1555  );1556}