App.tsx

63.0 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import type { IncomingPairingRequest } from "../shared/sync-types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { ProCelebration } from "./views/ProCelebration";11import { VaultView, type SortOrder } from "./views/Vault";12import { EntryView } from "./views/Entry";13import { AddView } from "./views/Add";14import { PeachMark, PeachWordmark } from "./components/PeachMark";15import { PasskeyApprovalView } from "./views/PasskeyApproval";16import { extractDomain } from "../shared/domain";17import { popupCopy } from "./copy";18import {19  DEFAULT_BINDINGS,20  formatKeybinding,21  getActiveBindings,22  matchKeybinding,23  SHORTCUT_DESCRIPTORS,24  type Keybinding,25  type ShortcutAction,26} from "../shared/shortcuts";27import { generateTOTP } from "../crypto/totp";28import { isNativePlatform, nativePlugin } from "../shared/native";2930export { sendMessage } from "../shared/bridge";3132const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));33const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));34const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));35const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));36const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));37const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));38const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));3940type View =41  | "lock"42  | "pro-celebration"43  | "entry"44  | "list"45  | "add"46  | "settings"47  | "sync-pairing"48  | "import"49  | "export"50  | "health"51  | "trash"52  | "panic";53type BootState = "loading" | "ready";5455const canarySuppressMap = new Map<string, boolean>();56let shellRingAnimation: Animation | null = null;5758export function isCanarySuppressed(entryId: string): boolean {59  return canarySuppressMap.get(entryId) ?? false;60}6162export function setCanarySuppressed(entryId: string, suppressed: boolean): void {63  canarySuppressMap.set(entryId, suppressed);64}6566export function clearCanarySuppressions(): void {67  canarySuppressMap.clear();68}6970export function triggerRing() {71  const shell = document.getElementById("hd-shell");72  if (!shell) return;7374  shellRingAnimation?.cancel();75  shell.dataset.glowing = "true";76  const animation = shell.animate(77    [78      { offset: 0, boxShadow: "var(--copy-shadow)" },79      {80        offset: 0.3,81        boxShadow:82          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",83      },84      { offset: 1, boxShadow: "var(--copy-shadow)" },85    ],86    {87      duration: 720,88      easing: "cubic-bezier(0.4, 0, 0.2, 1)",89      fill: "none",90    }91  );92  shellRingAnimation = animation;93  const clearGlow = () => {94    if (shellRingAnimation !== animation) return;95    shellRingAnimation = null;96    delete shell.dataset.glowing;97  };98  animation.onfinish = clearGlow;99  animation.oncancel = clearGlow;100}101102103export function triggerPipPulse() {104  const pip = document.querySelector(".peach-status-pip, .pip");105  if (pip) {106    pip.classList.remove("pulse");107    void (pip as HTMLElement).offsetWidth;108    pip.classList.add("pulse");109  }110}111112const ENTRY_TRANSITION_EXIT_MS = 95;113const ENTRY_TRANSITION_SETTLE_MS = 135;114115export default function App() {116  const [bootState, setBootState] = createSignal<BootState>("loading");117  const [view, setView] = createSignal<View>("lock");118  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,119  // CSS transition takes over for snap animation).120  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);121  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(122    "enter"123  );124  const [contentTransitioning, setContentTransitioning] = createSignal(false);125  const [hasVault, setHasVault] = createSignal(false);126  const [onboarded, setOnboarded] = createSignal(true);127  const [entries, setEntries] = createSignal<VaultEntry[]>([]);128  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);129  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);130  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");131  const [theme, setTheme] = createSignal<"dark" | "light">("dark");132  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");133  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");134  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);135  const [lockOnClose, setLockOnClose] = createSignal(true);136  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);137  const [breachMonitoring, setBreachMonitoring] = createSignal(true);138  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);139  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);140  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);141  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);142  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);143  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");144  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");145  // Cached Pro status — synchronous for render paths. Background's146  // GET_LICENSE is async, but render-time reads of isPro() must not block.147  // Refreshed at boot, after activate/deactivate, and whenever the popup148  // re-opens onto a stored license that has changed via another window.149  const [proStatus, setProStatus] = createSignal(false);150  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);151  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);152  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");153  const [listSearchSeed, setListSearchSeed] = createSignal("");154  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);155  const [pendingCelebration, setPendingCelebration] = createSignal(false);156  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);157  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);158  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);159  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);160  const [incomingPairTick, setIncomingPairTick] = createSignal(0);161  const incomingPairSecondsLeft = () => {162    void incomingPairTick();163    const req = incomingPair();164    if (!req) return 0;165    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));166  };167  // True while Panic Step 1 has bounced the user out to Export. When Export's168  // onBack fires we return to Panic instead of Settings so the user keeps the169  // destruction context they came from.170  const [returnToPanic, setReturnToPanic] = createSignal(false);171  // Set on popup boot when peach_recovery_pending flag is found in session172  // storage — instructs LockView to skip the unlock UI and open the recovery173  // words confirmation surface instead. Cleared via handleUnlock once the174  // user has typed the 3 confirmation words.175  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);176177  let contentPhaseTimer: number | undefined;178179  function applyAccent(name: AccentColorName) {180    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;181    const hex = color.hex;182    document.documentElement.style.setProperty("--peach-accent", hex);183    // Ambient surface variables — derived from the accent so surfaces shift184    // subtly toward the accent hue rather than staying fixed warm-brown.185    document.documentElement.style.setProperty("--peach-glow", hex + "2A");186    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");187    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");188  }189190  createEffect(() => {191    applyAccent(accentColor());192  });193194  createEffect(() => {195    document.documentElement.classList.toggle("light", theme() === "light");196    document.body.classList.toggle("light", theme() === "light");197  });198199  createEffect(() => {200    document.documentElement.setAttribute("data-display-font", displayFont());201  });202203  createEffect(() => {204    document.documentElement.setAttribute("data-text-size", textSize());205  });206207  createEffect(() => {208    if (reduceMotion()) {209      document.documentElement.setAttribute("data-motion", "reduce");210    } else {211      document.documentElement.removeAttribute("data-motion");212    }213  });214215  const selectedIndex = createMemo(() => {216    const currentId = selectedEntry()?.id;217    if (!currentId) return entries().length > 0 ? 0 : -1;218    return entries().findIndex((entry) => entry.id === currentId);219  });220221  async function applyAccentColor(name: AccentColorName) {222    applyAccent(name);223    setAccentColor(name);224    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });225  }226227  async function applyTheme(t: "dark" | "light") {228    setTheme(t);229    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });230  }231232  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {233    setDisplayFont(f);234    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });235  }236237  async function applyTextSize(size: "small" | "medium" | "large") {238    setTextSize(size);239    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });240  }241242  async function applyReduceMotion(enabled: boolean) {243    setReduceMotion(enabled);244    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });245  }246247  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload248  // small and lets future default updates land for actions the user hasn't249  // touched. Settings sends us the full active map; we filter and store.250  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {251    setShortcutBindings(active);252    const overrides: Record<string, Keybinding> = {};253    for (const action of Object.keys(active) as ShortcutAction[]) {254      const a = active[action];255      const d = DEFAULT_BINDINGS[action];256      const same = a.key === d.key257        && Boolean(a.ctrl)  === Boolean(d.ctrl)258        && Boolean(a.meta)  === Boolean(d.meta)259        && Boolean(a.shift) === Boolean(d.shift)260        && Boolean(a.alt)   === Boolean(d.alt);261      if (!same) overrides[action] = a;262    }263    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });264  }265266  async function applyLockOnClose(enabled: boolean) {267    setLockOnClose(enabled);268    await sendMessage({269      type: "UPDATE_SETTINGS",270      payload: { lockOnClose: enabled },271    });272  }273274  async function applyAutoLockMinutes(minutes: number) {275    setAutoLockMinutes(minutes);276    await sendMessage({277      type: "UPDATE_SETTINGS",278      payload: { autoLockMinutes: minutes },279    });280  }281282  async function applyBreachMonitoring(enabled: boolean) {283    setBreachMonitoring(enabled);284    await sendMessage({285      type: "UPDATE_SETTINGS",286      payload: { breachMonitoring: enabled },287    });288  }289290  onMount(async () => {291    // Resolve the active tab in parallel with the unlock/has-vault queries —292    // openVault()'s smart selection picks the entry matching currentTabDomain,293    // so it must be populated before openVault runs. Previously refreshCurrentTab294    // ran after openVault, leaving popups that booted already-unlocked falling295    // back to loadedEntries[0] instead of the domain match.296    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([297      sendMessage({ type: "IS_UNLOCKED" }),298      sendMessage({ type: "HAS_VAULT" }),299      refreshCurrentTab(),300      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),301    ]);302    const unlocked = Boolean(303      (unlockResponse as { ok: boolean; data?: boolean }).data304    );305    const vaultExists = Boolean(306      (vaultResponse as { ok: boolean; data?: boolean }).data307    );308    const shouldCelebrate = Boolean(309      (celebrationResponse as { ok: boolean; data?: boolean }).data310    );311    setHasVault(vaultExists);312    // Onboarding gate — show once on first install, never again. Existing313    // users (vaultExists) are auto-marked onboarded so they skip the flow314    // even on the very first popup open after this feature ships.315    try {316      const onboarded = await storageGet("peach_onboarded");317      const seen = onboarded === "true";318      if (vaultExists && !seen) {319        await storageSet("peach_onboarded", "true");320        setOnboarded(true);321      } else {322        setOnboarded(seen);323      }324    } catch {325      // storage unavailable — default to onboarded so we never block boot326      setOnboarded(true);327    }328    await Promise.all([restoreSettings(), refreshProStatus()]);329330    // Mark played before any animation so a crash mid-sequence never replays it331    if (shouldCelebrate) {332      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });333    }334335    // If the user created a vault but hasn't yet confirmed their recovery336    // words, route back to the recovery-words screen instead of opening the337    // entries view. The flag lives in chrome.storage.local so it survives338    // both popup close (SW suppresses lock-on-close) and full browser339    // restart (handleUnlock checks the same flag after a fresh password340    // unlock). Cleared when confirmation succeeds.341    let recoveryPending = false;342    try {343      const out = await chrome.storage.local?.get("peach_recovery_pending");344      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";345    } catch { /* best-effort */ }346347    // Native: closing the app before recovery-words confirmation means the348    // user didn't finish vault creation. Throw the partial vault away and349    // restart onboarding rather than asking them to unlock a vault they350    // never finished creating. Desktop keeps the existing "unlock to351    // resume" flow because closing the popup there is much more casual.352    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {353      try {354        await chrome.storage.local?.remove([355          "peach_vault_a",356          "peach_vault_b",357          "peach_recovery_pending",358          "peach_onboarded",359          "peach_vault_history",360        ]);361      } catch { /* best-effort */ }362      setHasVault(false);363      setOnboarded(false);364      setView("lock");365      setBootState("ready");366      document.getElementById("pre-lock")?.setAttribute("hidden", "true");367      return;368    }369370    if (recoveryPending && unlocked) {371      // forceRecoveryWords overrides LockView's hasVault gate so the372      // recovery surface renders even though the vault now exists.373      setForceRecoveryWords(true);374      setView("lock");375    } else if (unlocked && vaultExists) {376      await openVault(undefined, shouldCelebrate);377      if (shouldCelebrate) {378        setView("pro-celebration");379        window.setTimeout(() => setView("entry"), 2500);380      }381    } else if (shouldCelebrate) {382      setPendingCelebration(true);383    }384385    await refreshPendingPasskey();386    await refreshIncomingPairing();387    await consumeRecentPairing();388389    // Track tab changes so smart sort stays current390    const handleTabActivated = () => { void refreshCurrentTab(); };391    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {392      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();393    };394    try {395      chrome.tabs.onActivated.addListener(handleTabActivated);396      chrome.tabs.onUpdated.addListener(handleTabUpdated);397      onCleanup(() => {398        chrome.tabs.onActivated.removeListener(handleTabActivated);399        chrome.tabs.onUpdated.removeListener(handleTabUpdated);400      });401    } catch {402      // tabs permission may not be available in all contexts403    }404405    setBootState("ready");406    document.getElementById("pre-lock")?.setAttribute("hidden", "true");407408    // Check for pending session-storage notices from the background.409    if (chrome.storage.session) {410      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as411        Record<string, { feature?: string } | undefined>;412      if (session.pendingProGate?.feature) {413        await chrome.storage.session.remove("pendingProGate");414        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);415        setSettingsInitialSection("license");416        setView("settings");417      } else if (session.pendingProNotice?.feature) {418        await chrome.storage.session.remove("pendingProNotice");419        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });420      }421    }422423    // Warm the lazy-module cache so the Suspense fallback never shows for424    // locally-bundled extension views. Without this, the first navigation to425    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which426    // covers the shell and absorbs clicks on the header.427    void Promise.all([428      import("./views/Settings").catch(() => {}),429      import("./views/Import").catch(() => {}),430      import("./views/Export").catch(() => {}),431      import("./views/Health").catch(() => {}),432      import("./views/TrashView").catch(() => {}),433    ]);434435    // Lock-on-close via a persistent port. sendMessage in pagehide is436    // unreliable — the popup context tears down before the message lands.437    // The SW's onConnect listener locks when this port disconnects.438    let popupPort: chrome.runtime.Port | null = null;439    try {440      popupPort = chrome.runtime.connect({ name: "popup" });441    } catch { /* extension context invalidated — ignore */ }442    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });443444    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only445    // reliable signal is appStateChange — setTimeout is killed when the OS446    // backgrounds the app. We measure elapsed background time on resume.447    if (isNativePlatform()) {448      let backgroundedAt: number | null = null;449      const CapApp = nativePlugin<{450        addListener: (451          ev: string,452          cb: (s: { isActive: boolean }) => void,453        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };454      }>("App");455      if (CapApp?.addListener) {456        const sub = CapApp.addListener(457          "appStateChange",458          ({ isActive }: { isActive: boolean }) => {459            if (!isActive) {460              backgroundedAt = Date.now();461              return;462            }463            if (backgroundedAt !== null && autoLockMinutes() > 0) {464              const elapsed = Date.now() - backgroundedAt;465              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();466            }467            backgroundedAt = null;468          }469        );470        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.471        onCleanup(() => {472          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});473        });474      }475    }476477    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale478    // entries instead of waiting for the next GET_ENTRIES round-trip.479    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {480      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();481      if (msg?.type === "PRO_GATE_TRIGGERED") {482        setUpgradeHighlight(msg.payload?.feature ?? null);483        setSettingsInitialSection("license");484        setView("settings");485      }486      if (msg?.type === "INCOMING_PAIRING_REQUEST") {487        void refreshIncomingPairing();488      }489    };490    chrome.runtime.onMessage.addListener(handleRuntimeMessage);491    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));492493    // Android hardware/gesture back. MainActivity fires peach:back; the popup494    // decides what "back" means per surface. Lock+no-vault is the common case495    // — return to onboarding rather than letting the OS dismiss the activity.496    const handlePeachBack = () => {497      const v = view();498      if (v === "lock" && !hasVault() && onboarded()) {499        setOnboarded(false);500        return;501      }502      if (v === "list") { setView("entry"); return; }503      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {504        handleBack();505        return;506      }507      if (v === "sync-pairing") { setView("settings"); return; }508    };509    window.addEventListener("peach:back", handlePeachBack);510    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));511512    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that513    // peeks from the bottom (search bar handle visible) and drags up to fill514    // the screen. dragOffset is the LIVE finger offset during a drag, in px,515    // 0 when no drag in progress. The wrapper element computes transform =516    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.517    if (isNativePlatform()) {518      let touchStartY = 0;519      let touchStartX = 0;520      let lastY = 0;521      let lastT = 0;522      let dragging = false;523      let captured = false;524      const HORIZONTAL_TOLERANCE = 16;525      const ACTIVATION_DY = 8;526527      const onTouchStart = (e: TouchEvent) => {528        const t = e.touches[0];529        if (!t) return;530        const v = view();531        if (v !== "entry" && v !== "list") return;532        // Entry view: only intercept drags starting in the bottom 40%.533        // List view: intercept drags starting in the top 35% (the search/handle row).534        const inBand = v === "entry"535          ? t.clientY > window.innerHeight * 0.6536          : t.clientY < window.innerHeight * 0.35;537        if (!inBand) return;538        touchStartY = lastY = t.clientY;539        touchStartX = t.clientX;540        lastT = e.timeStamp;541        dragging = true;542        captured = false;543      };544545      const onTouchMove = (e: TouchEvent) => {546        if (!dragging) return;547        const t = e.touches[0];548        if (!t) return;549        const dy = t.clientY - touchStartY;550        const dx = Math.abs(t.clientX - touchStartX);551552        if (!captured) {553          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {554            // Looks like a horizontal swipe — release.555            dragging = false;556            return;557          }558          if (Math.abs(dy) < ACTIVATION_DY) return;559          captured = true;560        }561562        // Translate the sheet by dy from its rest position. Clamp so the563        // sheet can't be dragged above its open position or below its peek.564        const v = view();565        const restClosed = window.innerHeight - 60; // peek height566        const baseTranslate = v === "list" ? 0 : restClosed;567        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));568        setSheetTranslate(next);569        lastY = t.clientY;570        lastT = e.timeStamp;571      };572573      const onTouchEnd = (e: TouchEvent) => {574        if (!dragging) { return; }575        const t = e.changedTouches[0];576        const elapsed = Math.max(1, e.timeStamp - lastT);577        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms578        const wasCaptured = captured;579        dragging = false;580        captured = false;581582        if (!wasCaptured) {583          // It was a tap, not a drag. Let the underlying click handler run.584          setSheetTranslate(null);585          return;586        }587588        const restClosed = window.innerHeight - 60;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.4) nextOpen = true;598        else if (velocity > 0.4) 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={() => { console.log("[peach] settings tap"); 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            {/* Native: vault list lives in an always-mounted bottom sheet1313                that peeks at the bottom (search-bar handle) and drags up to1314                fill the screen. Desktop: shown on demand via Show. */}1315            <Show when={isNativePlatform()}>1316              <div1317                class="peach-vault-sheet"1318                classList={{ "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1319                style={(() => {1320                  const live = sheetTranslate();1321                  if (live === null) return undefined;1322                  return { transform: `translateY(${live}px)` };1323                })()}1324              >1325                <VaultView1326                  entries={entries()}1327                  selectedEntryId={selectedEntry()?.id}1328                  currentTabDomain={currentTabDomain()}1329                  sortOrder={sortOrder()}1330                  searchSeed={listSearchSeed()}1331                  searchSeedNonce={listSearchSeedNonce()}1332                  onSelectEntry={handleSelectEntry}1333                  onSortOrderChange={setSortOrder}1334                  onAdd={handleAdd}1335                  onClose={() => setView("entry")}1336                  onOpenTrash={() => setView("trash")}1337                  onDeleteMany={handleDeleteMany}1338                />1339              </div>1340            </Show>1341            <Show when={!isNativePlatform() && view() === "list"}>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            </Show>1357            <Show when={view() === "settings"}>1358              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1359                <SettingsView1360                  entriesCount={entries().length}1361                  breachMonitoring={breachMonitoring()}1362                  lockOnClose={lockOnClose()}1363                  autoLockMinutes={autoLockMinutes()}1364                  trashRetentionDays={trashRetentionDays()}1365                  theme={theme()}1366                  accentColor={accentColor()}1367                  displayFont={displayFont()}1368                  textSize={textSize()}1369                  reduceMotion={reduceMotion()}1370                  isPro={proStatus()}1371                  initialSection={settingsInitialSection()}1372                  upgradeHighlight={upgradeHighlight()}1373                  onBreachMonitoringChange={applyBreachMonitoring}1374                  onLockOnCloseChange={applyLockOnClose}1375                  onAutoLockMinutesChange={applyAutoLockMinutes}1376                  onTrashRetentionChange={applyTrashRetention}1377                  onThemeChange={applyTheme}1378                  onAccentChange={applyAccentColor}1379                  onDisplayFontChange={applyDisplayFont}1380                  onTextSizeChange={applyTextSize}1381                  onReduceMotionChange={applyReduceMotion}1382                  shortcuts={shortcutBindings()}1383                  onShortcutsChange={applyShortcuts}1384                  onLicenseChange={async () => {1385                    // After activation/deactivation: refresh Pro status,1386                    // re-load entries (defensive — signal state can drift if1387                    // the SW briefly restarts during the verify+save round-trip),1388                    // and replay the Pro celebration if this is the first time1389                    // a valid Pro license is seen on this device.1390                    await refreshProStatus();1391                    void loadEntries();1392                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1393                    if ((should as { ok: boolean; data?: boolean }).data === true) {1394                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1395                      setView("pro-celebration");1396                      window.setTimeout(() => setView("settings"), 2500);1397                    }1398                  }}1399                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1400                  onImport={() => setView("import")}1401                  onExport={() => setView("export")}1402                  onBreachCheckDone={loadEntries}1403                  onOpenHealth={openHealth}1404                  onOpenSyncPairing={() => setView("sync-pairing")}1405                  onOpenFileImport={handleOpenFileImport}1406                  onOpenPanic={() => setView("panic")}1407                />1408              </Suspense>1409            </Show>1410            <Show when={view() === "sync-pairing"}>1411              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1412                <SyncPairingView1413                  onClose={() => setView("settings")}1414                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1415                />1416              </Suspense>1417            </Show>1418            <Show when={view() === "add"}>1419              <AddView1420                entry={editEntry()}1421                entries={entries()}1422                onBack={handleBack}1423                onSave={handleSave}1424              />1425            </Show>1426            <Show when={view() === "import"}>1427              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1428                <ImportView onBack={handleBack} onImport={handleSave} />1429              </Suspense>1430            </Show>1431            <Show when={view() === "export"}>1432              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1433                <ExportView1434                  onBack={() => {1435                    if (returnToPanic()) {1436                      setReturnToPanic(false);1437                      setView("panic");1438                    } else {1439                      handleBack();1440                    }1441                  }}1442                />1443              </Suspense>1444            </Show>1445            <Show when={view() === "panic"}>1446              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1447                <PanicView1448                  onCancel={() => setView("settings")}1449                  onOpenExport={() => {1450                    setReturnToPanic(true);1451                    setView("export");1452                  }}1453                  onDestroyed={async () => {1454                    clearCanarySuppressions();1455                    setEntries([]);1456                    setSelectedEntry(null);1457                    setEditEntry(undefined);1458                    setHasVault(false);1459                    setOnboarded(false);1460                    setProStatus(false);1461                    setPendingPasskey(null);1462                    setUpgradeHighlight(null);1463                    setSettingsInitialSection(null);1464                    setPendingProNotice(null);1465                    setPendingCelebration(false);1466                    setReturnToPanic(false);1467                    setContentPhase("idle");1468                    setView("lock");1469                  }}1470                />1471              </Suspense>1472            </Show>1473            <Show when={view() === "health"}>1474              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1475                <HealthView1476                  entries={entries()}1477                  isPro={proStatus()}1478                  onFixEntry={handleFixEntry}1479                  onBack={() => setView("settings")}1480                  onRefresh={loadEntries}1481                />1482              </Suspense>1483            </Show>1484            <Show when={view() === "trash"}>1485              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1486                <TrashView1487                  onBack={() => setView("list")}1488                  onRestored={() => void loadEntries()}1489                />1490              </Suspense>1491            </Show>1492            <Show when={restoreView() === "file"}>1493              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1494                <ImportView1495                  mode="onboarding"1496                  replacesExistingVault={true}1497                  onBack={() => setRestoreView(null)}1498                  onImport={async () => {1499                    setRestoreView(null);1500                    await handleUnlock();1501                  }}1502                />1503              </Suspense>1504            </Show>1505            </section>1506            </Show>1507          </Show>1508        </Show>1509      </Show>1510      <Show when={showShortcutsHelp()}>1511        <ShortcutsHelpOverlay1512          bindings={shortcutBindings()}1513          onClose={() => setShowShortcutsHelp(false)}1514        />1515      </Show>1516    </div>1517  );1518}15191520function ShortcutsHelpOverlay(props: {1521  bindings: Record<ShortcutAction, Keybinding>;1522  onClose: () => void;1523}) {1524  return (1525    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1526      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1527        <div class="peach-shortcuts-help-head">1528          <h3>Keyboard shortcuts</h3>1529          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1530        </div>1531        <div class="peach-shortcuts-help-body">1532          <p class="peach-settings-sub-label">ENTRY VIEW</p>1533          <ul>1534            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1535              <li>1536                <span>{d.label}</span>1537                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1538              </li>1539            ))}1540          </ul>1541          <p class="peach-settings-sub-label">ANYWHERE</p>1542          <ul>1543            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1544              <li>1545                <span>{d.label}</span>1546                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1547              </li>1548            ))}1549          </ul>1550        </div>1551      </div>1552    </div>1553  );1554}