App.tsx

65.0 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 })));40const AddDeviceView   = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.AddDeviceView })));4142type View =43  | "lock"44  | "pro-celebration"45  | "entry"46  | "list"47  | "add"48  | "settings"49  | "sync-pairing"50  | "sync-add-device"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic";56type BootState = "loading" | "ready";5758const canarySuppressMap = new Map<string, boolean>();59let shellRingAnimation: Animation | null = null;6061export function isCanarySuppressed(entryId: string): boolean {62  return canarySuppressMap.get(entryId) ?? false;63}6465export function setCanarySuppressed(entryId: string, suppressed: boolean): void {66  canarySuppressMap.set(entryId, suppressed);67}6869export function clearCanarySuppressions(): void {70  canarySuppressMap.clear();71}7273export function triggerRing() {74  const shell = document.getElementById("hd-shell");75  if (!shell) return;7677  shellRingAnimation?.cancel();78  shell.dataset.glowing = "true";79  const animation = shell.animate(80    [81      { offset: 0, boxShadow: "var(--copy-shadow)" },82      {83        offset: 0.3,84        boxShadow:85          "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)",86      },87      { offset: 1, boxShadow: "var(--copy-shadow)" },88    ],89    {90      duration: 720,91      easing: "cubic-bezier(0.4, 0, 0.2, 1)",92      fill: "none",93    }94  );95  shellRingAnimation = animation;96  const clearGlow = () => {97    if (shellRingAnimation !== animation) return;98    shellRingAnimation = null;99    delete shell.dataset.glowing;100  };101  animation.onfinish = clearGlow;102  animation.oncancel = clearGlow;103}104105106export function triggerPipPulse() {107  const pip = document.querySelector(".peach-status-pip, .pip");108  if (pip) {109    pip.classList.remove("pulse");110    void (pip as HTMLElement).offsetWidth;111    pip.classList.add("pulse");112  }113}114115const ENTRY_TRANSITION_EXIT_MS = 95;116const ENTRY_TRANSITION_SETTLE_MS = 135;117118export default function App() {119  const [bootState, setBootState] = createSignal<BootState>("loading");120  const [view, setView] = createSignal<View>("lock");121  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,122  // CSS transition takes over for snap animation).123  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);124  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(125    "enter"126  );127  const [contentTransitioning, setContentTransitioning] = createSignal(false);128  const [hasVault, setHasVault] = createSignal(false);129  const [onboarded, setOnboarded] = createSignal(true);130  const [entries, setEntries] = createSignal<VaultEntry[]>([]);131  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);132  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);133  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");134  const [theme, setTheme] = createSignal<"dark" | "light">("dark");135  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);155  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");156  const [listSearchSeed, setListSearchSeed] = createSignal("");157  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);158  const [pendingCelebration, setPendingCelebration] = createSignal(false);159  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);160  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);161  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);162  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);163  const [incomingPairTick, setIncomingPairTick] = createSignal(0);164  const incomingPairSecondsLeft = () => {165    void incomingPairTick();166    const req = incomingPair();167    if (!req) return 0;168    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));169  };170  // True while Panic Step 1 has bounced the user out to Export. When Export's171  // onBack fires we return to Panic instead of Settings so the user keeps the172  // destruction context they came from.173  const [returnToPanic, setReturnToPanic] = createSignal(false);174  // Set on popup boot when peach_recovery_pending flag is found in session175  // storage — instructs LockView to skip the unlock UI and open the recovery176  // words confirmation surface instead. Cleared via handleUnlock once the177  // user has typed the 3 confirmation words.178  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);179180  let contentPhaseTimer: number | undefined;181182  function applyAccent(name: AccentColorName) {183    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;184    const hex = color.hex;185    document.documentElement.style.setProperty("--peach-accent", hex);186    // Ambient surface variables — derived from the accent so surfaces shift187    // subtly toward the accent hue rather than staying fixed warm-brown.188    document.documentElement.style.setProperty("--peach-glow", hex + "2A");189    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");190    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");191  }192193  createEffect(() => {194    applyAccent(accentColor());195  });196197  createEffect(() => {198    document.documentElement.classList.toggle("light", theme() === "light");199    document.body.classList.toggle("light", theme() === "light");200  });201202  createEffect(() => {203    document.documentElement.setAttribute("data-display-font", displayFont());204  });205206  createEffect(() => {207    document.documentElement.setAttribute("data-text-size", textSize());208  });209210  createEffect(() => {211    if (reduceMotion()) {212      document.documentElement.setAttribute("data-motion", "reduce");213    } else {214      document.documentElement.removeAttribute("data-motion");215    }216  });217218  const selectedIndex = createMemo(() => {219    const currentId = selectedEntry()?.id;220    if (!currentId) return entries().length > 0 ? 0 : -1;221    return entries().findIndex((entry) => entry.id === currentId);222  });223224  async function applyAccentColor(name: AccentColorName) {225    applyAccent(name);226    setAccentColor(name);227    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });228  }229230  async function applyTheme(t: "dark" | "light") {231    setTheme(t);232    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });233  }234235  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {236    setDisplayFont(f);237    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });238  }239240  async function applyTextSize(size: "small" | "medium" | "large") {241    setTextSize(size);242    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });243  }244245  async function applyReduceMotion(enabled: boolean) {246    setReduceMotion(enabled);247    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });248  }249250  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload251  // small and lets future default updates land for actions the user hasn't252  // touched. Settings sends us the full active map; we filter and store.253  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {254    setShortcutBindings(active);255    const overrides: Record<string, Keybinding> = {};256    for (const action of Object.keys(active) as ShortcutAction[]) {257      const a = active[action];258      const d = DEFAULT_BINDINGS[action];259      const same = a.key === d.key260        && Boolean(a.ctrl)  === Boolean(d.ctrl)261        && Boolean(a.meta)  === Boolean(d.meta)262        && Boolean(a.shift) === Boolean(d.shift)263        && Boolean(a.alt)   === Boolean(d.alt);264      if (!same) overrides[action] = a;265    }266    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });267  }268269  async function applyLockOnClose(enabled: boolean) {270    setLockOnClose(enabled);271    await sendMessage({272      type: "UPDATE_SETTINGS",273      payload: { lockOnClose: enabled },274    });275  }276277  async function applyAutoLockMinutes(minutes: number) {278    setAutoLockMinutes(minutes);279    await sendMessage({280      type: "UPDATE_SETTINGS",281      payload: { autoLockMinutes: minutes },282    });283  }284285  async function applyBreachMonitoring(enabled: boolean) {286    setBreachMonitoring(enabled);287    await sendMessage({288      type: "UPDATE_SETTINGS",289      payload: { breachMonitoring: enabled },290    });291  }292293  onMount(async () => {294    // Resolve the active tab in parallel with the unlock/has-vault queries —295    // openVault()'s smart selection picks the entry matching currentTabDomain,296    // so it must be populated before openVault runs. Previously refreshCurrentTab297    // ran after openVault, leaving popups that booted already-unlocked falling298    // back to loadedEntries[0] instead of the domain match.299    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([300      sendMessage({ type: "IS_UNLOCKED" }),301      sendMessage({ type: "HAS_VAULT" }),302      refreshCurrentTab(),303      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),304    ]);305    const unlocked = Boolean(306      (unlockResponse as { ok: boolean; data?: boolean }).data307    );308    const vaultExists = Boolean(309      (vaultResponse as { ok: boolean; data?: boolean }).data310    );311    const shouldCelebrate = Boolean(312      (celebrationResponse as { ok: boolean; data?: boolean }).data313    );314    setHasVault(vaultExists);315    // Onboarding gate — show once on first install, never again. Existing316    // users (vaultExists) are auto-marked onboarded so they skip the flow317    // even on the very first popup open after this feature ships.318    try {319      const onboarded = await storageGet("peach_onboarded");320      const seen = onboarded === "true";321      if (vaultExists && !seen) {322        await storageSet("peach_onboarded", "true");323        setOnboarded(true);324      } else {325        setOnboarded(seen);326      }327    } catch {328      // storage unavailable — default to onboarded so we never block boot329      setOnboarded(true);330    }331    await Promise.all([restoreSettings(), refreshProStatus()]);332333    // Mark played before any animation so a crash mid-sequence never replays it334    if (shouldCelebrate) {335      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });336    }337338    // If the user created a vault but hasn't yet confirmed their recovery339    // words, route back to the recovery-words screen instead of opening the340    // entries view. The flag lives in chrome.storage.local so it survives341    // both popup close (SW suppresses lock-on-close) and full browser342    // restart (handleUnlock checks the same flag after a fresh password343    // unlock). Cleared when confirmation succeeds.344    let recoveryPending = false;345    try {346      const out = await chrome.storage.local?.get("peach_recovery_pending");347      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";348    } catch { /* best-effort */ }349350    // Native: closing the app before recovery-words confirmation means the351    // user didn't finish vault creation. Throw the partial vault away and352    // restart onboarding rather than asking them to unlock a vault they353    // never finished creating. Desktop keeps the existing "unlock to354    // resume" flow because closing the popup there is much more casual.355    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {356      try {357        await chrome.storage.local?.remove([358          "peach_vault_a",359          "peach_vault_b",360          "peach_recovery_pending",361          "peach_onboarded",362          "peach_vault_history",363        ]);364      } catch { /* best-effort */ }365      setHasVault(false);366      setOnboarded(false);367      setView("lock");368      setBootState("ready");369      document.getElementById("pre-lock")?.setAttribute("hidden", "true");370      return;371    }372373    if (recoveryPending && unlocked) {374      // forceRecoveryWords overrides LockView's hasVault gate so the375      // recovery surface renders even though the vault now exists.376      setForceRecoveryWords(true);377      setView("lock");378    } else if (unlocked && vaultExists) {379      await openVault(undefined, shouldCelebrate);380      if (shouldCelebrate) {381        setView("pro-celebration");382        window.setTimeout(() => setView("entry"), 2500);383      }384    } else if (shouldCelebrate) {385      setPendingCelebration(true);386    }387388    await refreshPendingPasskey();389    await refreshIncomingPairing();390    await consumeRecentPairing();391392    // Track tab changes so smart sort stays current393    const handleTabActivated = () => { void refreshCurrentTab(); };394    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {395      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();396    };397    try {398      chrome.tabs.onActivated.addListener(handleTabActivated);399      chrome.tabs.onUpdated.addListener(handleTabUpdated);400      onCleanup(() => {401        chrome.tabs.onActivated.removeListener(handleTabActivated);402        chrome.tabs.onUpdated.removeListener(handleTabUpdated);403      });404    } catch {405      // tabs permission may not be available in all contexts406    }407408    setBootState("ready");409    document.getElementById("pre-lock")?.setAttribute("hidden", "true");410411    // Check for pending session-storage notices from the background.412    if (chrome.storage.session) {413      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as414        Record<string, { feature?: string } | undefined>;415      if (session.pendingProGate?.feature) {416        await chrome.storage.session.remove("pendingProGate");417        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);418        setSettingsInitialSection("license");419        setView("settings");420      } else if (session.pendingProNotice?.feature) {421        await chrome.storage.session.remove("pendingProNotice");422        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });423      }424    }425426    // Warm the lazy-module cache so the Suspense fallback never shows for427    // locally-bundled extension views. Without this, the first navigation to428    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which429    // covers the shell and absorbs clicks on the header.430    void Promise.all([431      import("./views/Settings").catch(() => {}),432      import("./views/Import").catch(() => {}),433      import("./views/Export").catch(() => {}),434      import("./views/Health").catch(() => {}),435      import("./views/TrashView").catch(() => {}),436    ]);437438    // Lock-on-close via a persistent port. sendMessage in pagehide is439    // unreliable — the popup context tears down before the message lands.440    // The SW's onConnect listener locks when this port disconnects.441    let popupPort: chrome.runtime.Port | null = null;442    try {443      popupPort = chrome.runtime.connect({ name: "popup" });444    } catch { /* extension context invalidated — ignore */ }445    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });446447    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only448    // reliable signal is appStateChange — setTimeout is killed when the OS449    // backgrounds the app. We measure elapsed background time on resume.450    if (isNativePlatform()) {451      let backgroundedAt: number | null = null;452      let syncPollInterval: ReturnType<typeof setInterval> | null = null;453454      function startSyncPolling() {455        if (syncPollInterval) return;456        syncPollInterval = setInterval(async () => {457          const res = await sendMessage({ type: 'TRIGGER_SYNC' }).catch(() => null);458          const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;459          if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {460            await sendMessage({ type: 'GET_ENTRIES' }).catch(() => null);461          }462        }, 60_000);463      }464465      function stopSyncPolling() {466        if (syncPollInterval) { clearInterval(syncPollInterval); syncPollInterval = null; }467      }468469      const CapApp = nativePlugin<{470        addListener: (471          ev: string,472          cb: (s: { isActive: boolean }) => void,473        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };474      }>("App");475      if (CapApp?.addListener) {476        const sub = CapApp.addListener(477          "appStateChange",478          ({ isActive }: { isActive: boolean }) => {479            if (!isActive) {480              backgroundedAt = Date.now();481              stopSyncPolling();482              return;483            }484            if (backgroundedAt !== null && autoLockMinutes() > 0) {485              const elapsed = Date.now() - backgroundedAt;486              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();487            }488            backgroundedAt = null;489            // Resume polling when app comes to foreground (Pro only).490            if (proStatus()) startSyncPolling();491          }492        );493        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.494        onCleanup(() => {495          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});496          stopSyncPolling();497        });498      }499    }500501    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale502    // entries instead of waiting for the next GET_ENTRIES round-trip.503    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {504      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();505      if (msg?.type === "PRO_GATE_TRIGGERED") {506        setUpgradeHighlight(msg.payload?.feature ?? null);507        setSettingsInitialSection("license");508        setView("settings");509      }510    };511    chrome.runtime.onMessage.addListener(handleRuntimeMessage);512    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));513514    // Android hardware/gesture back. MainActivity fires peach:back; the popup515    // decides what "back" means per surface. Lock+no-vault is the common case516    // — return to onboarding rather than letting the OS dismiss the activity.517    const handlePeachBack = () => {518      const v = view();519      if (v === "lock" && !hasVault() && onboarded()) {520        setOnboarded(false);521        return;522      }523      if (v === "list") { setView("entry"); return; }524      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {525        handleBack();526        return;527      }528      if (v === "sync-pairing") { setView("settings"); return; }529    };530    window.addEventListener("peach:back", handlePeachBack);531    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));532533    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that534    // peeks from the bottom (search bar handle visible) and drags up to fill535    // the screen. dragOffset is the LIVE finger offset during a drag, in px,536    // 0 when no drag in progress. The wrapper element computes transform =537    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.538    if (isNativePlatform()) {539      let touchStartY = 0;540      let touchStartX = 0;541      let lastY = 0;542      let lastT = 0;543      let dragging = false;544      let captured = false;545      const HORIZONTAL_TOLERANCE = 16;546      const ACTIVATION_DY = 8;547      const PEEK_PX = 60;548549      const onTouchStart = (e: TouchEvent) => {550        const t = e.touches[0];551        if (!t) return;552        const v = view();553        if (v !== "entry" && v !== "list") return;554        // Entry view: only intercept drags starting in the bottom 40%.555        // List view: intercept drags starting in the top 35% (the search/handle row).556        const inBand = v === "entry"557          ? t.clientY > window.innerHeight * 0.6558          : t.clientY < window.innerHeight * 0.35;559        if (!inBand) return;560        touchStartY = lastY = t.clientY;561        touchStartX = t.clientX;562        lastT = e.timeStamp;563        dragging = true;564        captured = false;565      };566567      const onTouchMove = (e: TouchEvent) => {568        if (!dragging) return;569        const t = e.touches[0];570        if (!t) return;571        const dy = t.clientY - touchStartY;572        const dx = Math.abs(t.clientX - touchStartX);573574        if (!captured) {575          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {576            // Looks like a horizontal swipe — release.577            dragging = false;578            return;579          }580          if (Math.abs(dy) < ACTIVATION_DY) return;581          captured = true;582        }583584        // Translate the sheet by dy from its rest (peek) position. Peek is585        // (viewport height - PEEK_PX). Open is 0.586        const v = view();587        const restClosed = window.innerHeight - PEEK_PX;588        const baseTranslate = v === "list" ? 0 : restClosed;589        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));590        setSheetTranslate(next);591        lastY = t.clientY;592        lastT = e.timeStamp;593      };594595      const onTouchEnd = (e: TouchEvent) => {596        if (!dragging) { return; }597        const t = e.changedTouches[0];598        const elapsed = Math.max(1, e.timeStamp - lastT);599        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms600        const wasCaptured = captured;601        dragging = false;602        captured = false;603        const v = view();604605        if (!wasCaptured) {606          // Tap in the peek strip while in entry view → open the vault list.607          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");608          setSheetTranslate(null);609          return;610        }611612        const restClosed = window.innerHeight - PEEK_PX;613        const current = sheetTranslate() ?? restClosed;614615        // Snap rules:616        //   - Strong upward velocity → open617        //   - Strong downward velocity → close618        //   - Otherwise snap to whichever rest is closer619        let nextOpen: boolean;620        if (velocity < -0.05) nextOpen = true;621        else if (velocity > 0.05) nextOpen = false;622        else nextOpen = current < restClosed * 0.5;623624        if (nextOpen && v !== "list") setView("list");625        if (!nextOpen && v !== "entry") setView("entry");626        // Release the live offset so CSS transition handles the snap.627        setSheetTranslate(null);628      };629630      document.addEventListener("touchstart", onTouchStart, { passive: true });631      document.addEventListener("touchmove",  onTouchMove,  { passive: true });632      document.addEventListener("touchend",   onTouchEnd,   { passive: true });633      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });634      onCleanup(() => {635        document.removeEventListener("touchstart", onTouchStart);636        document.removeEventListener("touchmove",  onTouchMove);637        document.removeEventListener("touchend",   onTouchEnd);638      });639    }640641    // Action handlers — keyed by ShortcutAction. The dispatcher below tests642    // each binding against the event and runs the matching handler. New643    // shortcuts only need an entry here; the binding is data, not code.644    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {645      copy_password: () => {646        const entry = selectedEntry();647        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });648      },649      copy_username: () => {650        const entry = selectedEntry();651        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });652      },653      copy_totp: () => {654        const entry = selectedEntry();655        if (!entry?.totp) return;656        try {657          const { code } = generateTOTP(entry.totp);658          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });659        } catch { /* invalid TOTP secret — silent */ }660      },661      new_entry: () => handleAdd(),662      edit_entry: () => {663        const entry = selectedEntry();664        // Passkey-only entries have nothing user-editable in the Add view; the665        // passkey credential itself is opaque. Skip the edit action for them.666        if (!entry || isPasskeyOnly(entry)) return;667        setEditEntry(entry);668        setView("add");669      },670      delete_entry: () => {671        if (selectedEntry()) void handleDelete();672      },673      lock_vault: () => { void handleHeaderLock(); },674      search: () => openList(),675      nav_prev: () => navigate(-1),676      nav_next: () => navigate(1),677      jump_vault: () => setView("entry"),678      jump_settings: () => setView("settings"),679      show_help: () => setShowShortcutsHelp(true),680    };681682    // Actions that are MEANINGFUL only on the entry-detail view. Outside683    // that scope the binding is dormant — pressing C while on Settings684    // does nothing rather than awkwardly copying from a now-stale entry.685    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([686      "copy_password", "copy_username", "copy_totp",687      "edit_entry", "delete_entry", "nav_prev", "nav_next",688    ]);689690    const handleGlobalKeydown = (e: KeyboardEvent) => {691      const v = view();692      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"693        || (e.target as HTMLElement)?.tagName === "TEXTAREA"694        || (e.target as HTMLElement)?.isContentEditable;695      const isPrintableSearchKey =696        e.key.length === 1 &&697        !e.ctrlKey &&698        !e.metaKey &&699        !e.altKey;700701      // No input during the pro celebration sequence702      if (v === "pro-celebration") return;703704      // Help dialog: Escape closes it; eat the keypress so it doesn't705      // also navigate away from the underlying view.706      if (showShortcutsHelp()) {707        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }708        return;709      }710711      // ── Escape — fixed binding (not user-customizable) ───────712      if (e.key === "Escape") {713        if (v === "list") { setView("entry"); return; }714        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }715        if (v === "sync-pairing") { setView("settings"); return; }716        if (v === "sync-add-device") { setView("sync-pairing"); return; }717      }718719      // Bindings-driven dispatch. Single-key letter bindings without720      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is721      // inside an input, so users can type into search/forms normally.722      const bindings = shortcutBindings();723      for (const action of Object.keys(bindings) as ShortcutAction[]) {724        const binding = bindings[action];725        if (!matchKeybinding(e, binding)) continue;726        // Single-key letter bindings need the input-focus guard. Bindings727        // with any modifier are safe — Ctrl+L doesn't conflict with typing.728        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;729        if (!hasMod && binding.key.length === 1 && inInput) return;730        if (ENTRY_SCOPED.has(action) && v !== "entry") return;731        e.preventDefault();732        SHORTCUT_HANDLERS[action]?.();733        return;734      }735736      // Type-to-search: in entry view, any printable key not consumed by a737      // shortcut above primes the list search seed and opens the list.738      // Kept outside the bindings table because it's a behavior, not a739      // discrete action — every printable character can trigger it.740      if (v === "entry" && !inInput && isPrintableSearchKey) {741        e.preventDefault();742        primeListSearch(e.key);743        return;744      }745    };746    window.addEventListener("keydown", handleGlobalKeydown);747    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));748749    const handleStorageChanged = (750      changes: Record<string, chrome.storage.StorageChange>,751      areaName: string752    ) => {753      if (areaName !== "session") return;754      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {755        return;756      }757      void refreshPendingPasskey();758    };759    chrome.storage.onChanged.addListener(handleStorageChanged);760    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));761  });762763  async function refreshCurrentTab() {764    try {765      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });766      const url = tab?.url ?? tab?.pendingUrl ?? "";767      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");768      // Skip extension/internal URLs — adding chrome://, about:, or769      // chrome-extension:// to a vault entry is never what the user wants.770      const isWebUrl = /^https?:\/\//i.test(url);771      setCurrentTabUrl(isWebUrl ? url : "");772    } catch {773      setCurrentTabDomain("");774      setCurrentTabUrl("");775    }776  }777778  async function refreshPendingPasskey() {779    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });780    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);781  }782783  async function refreshIncomingPairing() {784    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });785    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;786    setIncomingPair(data);787  }788789  // Drains a single one-shot record left by the background when 6-digit790  // pairing succeeded while the popup was closed (or the SyncPairing view was791  // navigated away from before it could show its own success card).792  async function consumeRecentPairing() {793    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });794    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;795    if (data?.deviceName) {796      setRecentPairToast(data.deviceName);797      window.setTimeout(() => setRecentPairToast(null), 4000);798    }799  }800801  async function respondIncomingPairing(accept: boolean) {802    if (incomingPairResponding()) return;803    setIncomingPairResponding(true);804    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });805    setIncomingPair(null);806    setIncomingPairResponding(false);807  }808809  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a810  // request appears, ticks once per second, and clears the banner if the811  // request expires while the popup is open.812  createEffect(() => {813    const req = incomingPair();814    if (!req) return;815    const handle = window.setInterval(() => {816      setIncomingPairTick((tick) => tick + 1);817      if (Date.now() >= req.expiresAt) {818        setIncomingPair(null);819        window.clearInterval(handle);820      }821    }, 1000);822    onCleanup(() => window.clearInterval(handle));823  });824825  async function refreshProStatus() {826    const res = await sendMessage({ type: "GET_LICENSE" });827    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;828    setProStatus(Boolean(data?.valid && data?.plan === "pro"));829  }830831  async function restoreSettings() {832    const res = await sendMessage({ type: "GET_SETTINGS" });833    const s = (res as { ok: boolean; data?: any }).data ?? {};834    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {835      setAccentColor(s.accentColor as AccentColorName);836    }837    setTheme(s.theme === "light" ? "light" : "dark");838    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {839      setDisplayFont(s.displayFont);840    } else {841      setDisplayFont("cormorant-italic");842    }843    if (s.textSize === "small" || s.textSize === "large") {844      setTextSize(s.textSize);845    } else {846      setTextSize("medium");847    }848    setReduceMotion(s.reduceMotion === true);849    setLockOnClose(s.lockOnClose !== false);850    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);851    setBreachMonitoring(s.breachMonitoring !== false);852    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);853    setShortcutBindings(getActiveBindings(s.shortcuts));854  }855856  async function applyTrashRetention(days: number) {857    setTrashRetentionDays(days);858    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });859  }860861  function primeListSearch(seed: string) {862    setListSearchSeed(seed);863    setListSearchSeedNonce((value) => value + 1);864    openList();865  }866867  // Returns null when it detected a dead service worker and triggered handleLock().868  // Callers that need to abort (e.g. openVault) check for null rather than relying869  // on view() state, which may already be "lock" during normal startup flows.870  async function loadEntries(): Promise<VaultEntry[] | null> {871    const response = await sendMessage({ type: "GET_ENTRIES" });872    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };873874    // If the service worker was killed and restarted (MV3 workers sleep), the875    // vault will be locked again — or the worker may not respond at all.876    // In either case, send the user to the lock screen rather than silently877    // showing an empty vault (which looks like data loss).878    if (!res.ok) {879      if (880        res.error === "vault locked" ||881        res.error === "SERVICE_WORKER_UNAVAILABLE" ||882        (typeof res.error === "string" && res.error.includes("locked"))883      ) {884        handleLock();885        return null; // signal emergency lock to callers886      }887      return [];888    }889890    const loadedEntries = res.data ?? [];891    setEntries(loadedEntries);892893    const currentId = selectedEntry()?.id;894    if (currentId) {895      setSelectedEntry(896        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null897      );898    }899900    return loadedEntries;901  }902903  async function openVault(preferredEntryId?: string, skipViewSet = false) {904    // Desktop: fire-and-forget sync on every vault open (Pro only).905    // Never blocks popup load; refreshes entries if new data arrives.906    if (!isNativePlatform() && proStatus()) {907      void sendMessage({ type: 'TRIGGER_SYNC' }).then((res) => {908        const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;909        if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {910          void loadEntries();911        }912      }).catch(() => {});913    }914915    // Purge expired trash entries on each vault open916    const retDays = trashRetentionDays();917    if (retDays > 0) {918      void sendMessage({919        type: "PURGE_EXPIRED_TRASH",920        payload: { retentionMs: retDays * 86_400_000 },921      });922    }923924    const loadedEntries = await loadEntries();925926    // null means loadEntries() triggered an emergency lock (service worker died).927    // Don't override it by setting view back to "entry" with an empty vault.928    if (loadedEntries === null) return;929930    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry931    let nextSelectedEntry: VaultEntry | null = null;932    if (preferredEntryId) {933      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;934    }935    if (!nextSelectedEntry) {936      const tabDomain = currentTabDomain();937      if (tabDomain) {938        nextSelectedEntry = loadedEntries.find((e) => {939          if (e.type === "login") {940            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;941            for (const extra of e.additionalUrls ?? []) {942              if ((extractDomain(extra) ?? "") === tabDomain) return true;943            }944            return false;945          }946          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;947          return false;948        }) ?? null;949      }950    }951    nextSelectedEntry ??= loadedEntries[0] ?? null;952953    setSelectedEntry(nextSelectedEntry);954    setEditEntry(undefined);955    setContentTransitioning(false);956    setContentPhase("enter");957    queueContentIdle();958    if (!skipViewSet) setView("entry");959  }960961  async function handleUnlock() {962    // If the user previously created a vault but hadn't yet confirmed their963    // recovery words (and the browser was closed before they could), the964    // peach_recovery_pending flag is still set in storage.local. Re-route965    // back to the recovery surface so they finish the confirmation step966    // before reaching the entries view — the words can be re-derived now967    // that the vault is unlocked again.968    let recoveryPending = false;969    try {970      const out = await chrome.storage.local?.get("peach_recovery_pending");971      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";972    } catch { /* best-effort */ }973    if (recoveryPending) {974      setForceRecoveryWords(true);975      setView("lock");976      triggerPipPulse();977      await restoreSettings();978      return;979    }980    setHasVault(true);981    triggerPipPulse();982    await restoreSettings();983    const celebrating = pendingCelebration();984    if (celebrating) {985      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });986      setPendingCelebration(false);987    }988    await openVault(undefined, celebrating);989    if (celebrating) {990      setView("pro-celebration");991      window.setTimeout(() => setView("entry"), 2500);992    }993  }994995  function handleSelectEntry(entry: VaultEntry) {996    setSelectedEntry(entry);997    setContentTransitioning(false);998    setContentPhase("enter");999    queueContentIdle();1000    setView("entry");1001  }10021003  function handleAdd() {1004    setEditEntry(undefined);1005    setView("add");1006  }10071008  async function handleDelete() {1009    const entry = selectedEntry();1010    if (!entry) return;1011    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1012    const loadedEntries = await loadEntries() ?? [];1013    setSelectedEntry(loadedEntries[0] ?? null);1014    setView("entry");1015  }10161017  async function handleDeleteMany(ids: string[]) {1018    for (const id of ids) {1019      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1020    }1021    const loadedEntries = await loadEntries() ?? [];1022    // If the currently selected entry was among the deleted, move to first1023    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1024    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1025  }10261027  async function handleSave(savedEntry?: VaultEntry) {1028    await openVault(savedEntry?.id);1029  }10301031  function handleBack() {1032    setEditEntry(undefined);1033    setView("entry");1034  }10351036  function handleLock() {1037    clearCanarySuppressions();1038    setEntries([]);1039    setSelectedEntry(null);1040    setEditEntry(undefined);1041    setContentPhase("idle");1042    setView("lock");1043  }10441045  function handleHeaderLock() {1046    // Lock the UI immediately — do not wait for the service worker. If the SW1047    // is dead or slow, the 5s sendMessage timeout would create a dead-click1048    // window. The SW will lock on its next wake regardless.1049    handleLock();1050    void sendMessage({ type: "LOCK" });1051  }10521053  function navigate(dir: number) {1054    const allEntries = entries();1055    if (allEntries.length === 0) return;1056    const currentIndex = selectedIndex();1057    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1058    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1059    setSelectedEntry(allEntries[nextIndex]);1060    setContentPhase("enter");1061    queueContentIdle();1062  }10631064  function openList() {1065    setView("list");1066  }10671068  function openHealth() {1069    setEditEntry(undefined);1070    setView("health");1071  }10721073  function handleOpenFileImport() {1074    setRestoreView("file");1075  }10761077  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10781079  function handleFixEntry(entry: VaultEntry) {1080    // Passkey-only entries have no editable surface — drop into view mode1081    // instead of opening the Add editor.1082    if (isPasskeyOnly(entry)) {1083      setSelectedEntry(entry);1084      setView("entry");1085      return;1086    }1087    setEditEntry(entry);1088    setView("add");1089  }10901091  const isLockedView = () => view() === "lock";10921093  async function handleApprovePendingPasskey() {1094    const pending = pendingPasskey();1095    if (!pending) return;1096    if (pending.browser === "firefox" && pending.type === "create") {1097      // Firefox path: popup itself runs navigator.credentials.create. The1098      // background never approved/rejected anything — it just stashed1099      // intent. After the popup-driven flow resolves (success or cancel),1100      // clear the pending key so the popup doesn't re-show this on next open.1101      const { createFirefoxPasskey } = await import("./firefox-passkey");1102      const result = await createFirefoxPasskey(pending);1103      if (!result.ok) {1104        console.warn("Peach Firefox passkey create failed:", result.error);1105      }1106      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1107      setPendingPasskey(null);1108      void loadEntries();1109      return;1110    }1111    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1112    setPendingPasskey(null);1113  }11141115  async function handleDenyPendingPasskey() {1116    const pending = pendingPasskey();1117    if (!pending) return;1118    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1119    setPendingPasskey(null);1120  }11211122  function queueContentIdle(after?: () => void) {1123    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1124    contentPhaseTimer = window.setTimeout(() => {1125      setContentPhase("idle");1126      after?.();1127    }, ENTRY_TRANSITION_SETTLE_MS);1128  }11291130  return (1131    <div class="popup-root peach-theme">1132      <Show when={bootState() === "ready"}>1133        <Show1134          when={!pendingPasskey()}1135          fallback={1136            <PasskeyApprovalView1137              type={pendingPasskey()!.type}1138              rpName={pendingPasskey()!.rpName}1139              rpId={pendingPasskey()!.rpId}1140              userName={pendingPasskey()!.userName}1141              userDisplayName={pendingPasskey()!.userDisplayName}1142              onApprove={handleApprovePendingPasskey}1143              onDeny={handleDenyPendingPasskey}1144            />1145          }1146        >1147          <Show1148            when={!isLockedView()}1149            fallback={1150              <Show1151                when={onboarded() || hasVault()}1152                fallback={1153                  <Onboarding1154                    onComplete={() => { setOnboarded(true); }}1155                  />1156                }1157              >1158                <LockView1159                  hasVault={hasVault()}1160                  ready={bootState() === "ready"}1161                  isPro={proStatus()}1162                  forceRecoveryWords={forceRecoveryWords()}1163                  onUnlock={() => {1164                    // RecoveryWordDisplay clears the storage flag before1165                    // calling onDone, so handleUnlock will see no pending1166                    // confirmation and proceed through the normal path.1167                    if (forceRecoveryWords()) setForceRecoveryWords(false);1168                    return handleUnlock();1169                  }}1170                  onBackToOnboarding={1171                    !hasVault()1172                      ? () => setOnboarded(false)1173                      : undefined1174                  }1175                />1176              </Show>1177            }1178          >1179            <Show1180              when={view() !== "pro-celebration"}1181              fallback={<ProCelebration />}1182            >1183            <section1184              id="hd-shell"1185              class="peach-shell peach-theme"1186              data-surface="extension"1187            >1188            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1189              <PeachWordmark unlocked />1190              <div class="peach-chrome-actions">1191                <button1192                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1193                  onClick={() => setView("settings")}1194                  aria-label="Settings"1195                >1196                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1197                    <path1198                      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"1199                      stroke="currentColor"1200                      stroke-width="0.9"1201                    />1202                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1203                  </svg>1204                </button>1205                <button1206                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1207                  onClick={handleAdd}1208                  aria-label="New entry"1209                >1210                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1211                    <path d="M5.5 1v9M1 5.5h9" />1212                  </svg>1213                </button>1214                <button1215                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1216                  onClick={() => void handleHeaderLock()}1217                  aria-label="Lock vault"1218                >1219                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1220                    <path1221                      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"1222                      stroke="currentColor"1223                      stroke-width="1"1224                      stroke-linecap="round"1225                    />1226                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1227                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1228                  </svg>1229                </button>1230              </div>1231            </header>12321233            <Show when={recentPairToast()}>1234              <div class="peach-pair-toast" role="status" aria-live="polite">1235                Paired with <strong>{recentPairToast()}</strong>1236              </div>1237            </Show>12381239            <Show when={incomingPair() !== null}>1240              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1241                <div class="peach-pair-request-header">1242                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1243                  <span class="peach-pair-request-title">Pairing request</span>1244                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1245                </div>1246                <p class="peach-pair-request-body">1247                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1248                </p>1249                <div class="peach-pair-request-actions">1250                  <button1251                    class="peach-btn peach-btn--ghost peach-btn--sm"1252                    onClick={() => void respondIncomingPairing(false)}1253                    disabled={incomingPairResponding()}1254                  >1255                    Reject1256                  </button>1257                  <button1258                    class="peach-btn peach-btn--accent peach-btn--sm"1259                    onClick={() => void respondIncomingPairing(true)}1260                    disabled={incomingPairResponding()}1261                  >1262                    Accept1263                  </button>1264                </div>1265              </div>1266            </Show>12671268            <Show when={pendingProNotice() !== null}>1269              <div class="peach-pro-notice-banner">1270                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1271                <button1272                  class="peach-pro-notice-link"1273                  onClick={() => {1274                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1275                    setSettingsInitialSection("license");1276                    setView("settings");1277                    setPendingProNotice(null);1278                  }}1279                >1280                  Learn more →1281                </button>1282                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1283              </div>1284            </Show>12851286            <div class="peach-shell-body">1287              <div class="peach-shell-veil"></div>1288              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1289                <EntryView1290                  entry={selectedEntry()}1291                  currentTabUrl={currentTabUrl()}1292                  onDelete={handleDelete}1293                  onFieldSaved={() => void loadEntries()}1294                  onEscape={() => { setView("list"); }}1295                />1296              </div>12971298              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1299                <div class="peach-search-bar">1300                  <span class="peach-search-icon">1301                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1302                      <circle cx="5.5" cy="5.5" r="3.75" />1303                      <path d="M8.75 8.75L11.5 11.5" />1304                    </svg>1305                  </span>1306                  <input1307                    class="peach-search-input"1308                    placeholder="search vault..."1309                    autocomplete="off"1310                    aria-label="Search vault entries"1311                    onClick={openList}1312                    onFocus={openList}1313                    readOnly1314                  />1315                  <div class="peach-search-meta">1316                    <span class="peach-search-counter">1317                      {entries().length > 01318                        ? `${selectedIndex() + 1} / ${entries().length}`1319                        : "0 entries"}1320                    </span>1321                    <span class="peach-divider"></span>1322                    <button1323                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1324                      onClick={() => navigate(-1)}1325                      aria-label="Previous entry"1326                      disabled={entries().length === 0}1327                    >1328                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1329                        <path d="M5 1L1 5.5L5 10" />1330                      </svg>1331                    </button>1332                    <button1333                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1334                      onClick={() => navigate(1)}1335                      aria-label="Next entry"1336                      disabled={entries().length === 0}1337                    >1338                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1339                        <path d="M1 1L5 5.5L1 10" />1340                      </svg>1341                    </button>1342                  </div>1343                </div>1344              </section>1345            </div>13461347            {/* Desktop: shown on demand via Show. Native sheet is rendered1348                via Portal below at the document root so its position:fixed1349                isn't trapped by .peach-shell's transform-based animations. */}1350            <Show when={!isNativePlatform() && view() === "list"}>1351              <VaultView1352                entries={entries()}1353                selectedEntryId={selectedEntry()?.id}1354                currentTabDomain={currentTabDomain()}1355                sortOrder={sortOrder()}1356                searchSeed={listSearchSeed()}1357                searchSeedNonce={listSearchSeedNonce()}1358                onSelectEntry={handleSelectEntry}1359                onSortOrderChange={setSortOrder}1360                onAdd={handleAdd}1361                onClose={() => setView("entry")}1362                onOpenTrash={() => setView("trash")}1363                onDeleteMany={handleDeleteMany}1364              />1365            </Show>1366            <Show when={isNativePlatform() && hasVault()}>1367              <Portal>1368                <div1369                  class="peach-vault-sheet"1370                  classList={{ "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1371                  style={(() => {1372                    const live = sheetTranslate();1373                    if (live === null) return undefined;1374                    return { transform: `translateY(${live}px)` };1375                  })()}1376                >1377                  <VaultView1378                    entries={entries()}1379                    selectedEntryId={selectedEntry()?.id}1380                    currentTabDomain={currentTabDomain()}1381                    sortOrder={sortOrder()}1382                    searchSeed={listSearchSeed()}1383                    searchSeedNonce={listSearchSeedNonce()}1384                    onSelectEntry={handleSelectEntry}1385                    onSortOrderChange={setSortOrder}1386                    onAdd={handleAdd}1387                    onClose={() => setView("entry")}1388                    onOpenTrash={() => setView("trash")}1389                    onDeleteMany={handleDeleteMany}1390                  />1391                </div>1392              </Portal>1393            </Show>1394            <Show when={view() === "settings"}>1395              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1396                <SettingsView1397                  entriesCount={entries().length}1398                  breachMonitoring={breachMonitoring()}1399                  lockOnClose={lockOnClose()}1400                  autoLockMinutes={autoLockMinutes()}1401                  trashRetentionDays={trashRetentionDays()}1402                  theme={theme()}1403                  accentColor={accentColor()}1404                  displayFont={displayFont()}1405                  textSize={textSize()}1406                  reduceMotion={reduceMotion()}1407                  isPro={proStatus()}1408                  initialSection={settingsInitialSection()}1409                  upgradeHighlight={upgradeHighlight()}1410                  onBreachMonitoringChange={applyBreachMonitoring}1411                  onLockOnCloseChange={applyLockOnClose}1412                  onAutoLockMinutesChange={applyAutoLockMinutes}1413                  onTrashRetentionChange={applyTrashRetention}1414                  onThemeChange={applyTheme}1415                  onAccentChange={applyAccentColor}1416                  onDisplayFontChange={applyDisplayFont}1417                  onTextSizeChange={applyTextSize}1418                  onReduceMotionChange={applyReduceMotion}1419                  shortcuts={shortcutBindings()}1420                  onShortcutsChange={applyShortcuts}1421                  onLicenseChange={async () => {1422                    // After activation/deactivation: refresh Pro status,1423                    // re-load entries (defensive — signal state can drift if1424                    // the SW briefly restarts during the verify+save round-trip),1425                    // and replay the Pro celebration if this is the first time1426                    // a valid Pro license is seen on this device.1427                    await refreshProStatus();1428                    void loadEntries();1429                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1430                    if ((should as { ok: boolean; data?: boolean }).data === true) {1431                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1432                      setView("pro-celebration");1433                      window.setTimeout(() => setView("settings"), 2500);1434                    }1435                  }}1436                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1437                  onImport={() => setView("import")}1438                  onExport={() => setView("export")}1439                  onBreachCheckDone={loadEntries}1440                  onOpenHealth={openHealth}1441                  onOpenSyncPairing={() => setView("sync-pairing")}1442                  onOpenFileImport={handleOpenFileImport}1443                  onOpenPanic={() => setView("panic")}1444                />1445              </Suspense>1446            </Show>1447            <Show when={view() === "sync-pairing"}>1448              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1449                <SyncPairingView1450                  isPro={proStatus()}1451                  onAddDevice={() => setView("sync-add-device")}1452                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1453                  onBack={() => setView("settings")}1454                />1455              </Suspense>1456            </Show>1457            <Show when={view() === "sync-add-device"}>1458              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1459                <AddDeviceView1460                  onClose={() => setView("sync-pairing")}1461                  onPaired={() => setView("sync-pairing")}1462                />1463              </Suspense>1464            </Show>1465            <Show when={view() === "add"}>1466              <AddView1467                entry={editEntry()}1468                entries={entries()}1469                onBack={handleBack}1470                onSave={handleSave}1471              />1472            </Show>1473            <Show when={view() === "import"}>1474              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1475                <ImportView onBack={handleBack} onImport={handleSave} />1476              </Suspense>1477            </Show>1478            <Show when={view() === "export"}>1479              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1480                <ExportView1481                  onBack={() => {1482                    if (returnToPanic()) {1483                      setReturnToPanic(false);1484                      setView("panic");1485                    } else {1486                      handleBack();1487                    }1488                  }}1489                />1490              </Suspense>1491            </Show>1492            <Show when={view() === "panic"}>1493              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1494                <PanicView1495                  onCancel={() => setView("settings")}1496                  onOpenExport={() => {1497                    setReturnToPanic(true);1498                    setView("export");1499                  }}1500                  onDestroyed={async () => {1501                    clearCanarySuppressions();1502                    setEntries([]);1503                    setSelectedEntry(null);1504                    setEditEntry(undefined);1505                    setHasVault(false);1506                    setOnboarded(false);1507                    setProStatus(false);1508                    setPendingPasskey(null);1509                    setUpgradeHighlight(null);1510                    setSettingsInitialSection(null);1511                    setPendingProNotice(null);1512                    setPendingCelebration(false);1513                    setReturnToPanic(false);1514                    setContentPhase("idle");1515                    setView("lock");1516                  }}1517                />1518              </Suspense>1519            </Show>1520            <Show when={view() === "health"}>1521              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1522                <HealthView1523                  entries={entries()}1524                  isPro={proStatus()}1525                  onFixEntry={handleFixEntry}1526                  onBack={() => setView("settings")}1527                  onRefresh={loadEntries}1528                />1529              </Suspense>1530            </Show>1531            <Show when={view() === "trash"}>1532              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1533                <TrashView1534                  onBack={() => setView("list")}1535                  onRestored={() => void loadEntries()}1536                />1537              </Suspense>1538            </Show>1539            <Show when={restoreView() === "file"}>1540              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1541                <ImportView1542                  mode="onboarding"1543                  replacesExistingVault={true}1544                  onBack={() => setRestoreView(null)}1545                  onImport={async () => {1546                    setRestoreView(null);1547                    await handleUnlock();1548                  }}1549                />1550              </Suspense>1551            </Show>1552            </section>1553            </Show>1554          </Show>1555        </Show>1556      </Show>1557      <Show when={showShortcutsHelp()}>1558        <ShortcutsHelpOverlay1559          bindings={shortcutBindings()}1560          onClose={() => setShowShortcutsHelp(false)}1561        />1562      </Show>1563    </div>1564  );1565}15661567function ShortcutsHelpOverlay(props: {1568  bindings: Record<ShortcutAction, Keybinding>;1569  onClose: () => void;1570}) {1571  return (1572    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1573      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1574        <div class="peach-shortcuts-help-head">1575          <h3>Keyboard shortcuts</h3>1576          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1577        </div>1578        <div class="peach-shortcuts-help-body">1579          <p class="peach-settings-sub-label">ENTRY VIEW</p>1580          <ul>1581            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1582              <li>1583                <span>{d.label}</span>1584                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1585              </li>1586            ))}1587          </ul>1588          <p class="peach-settings-sub-label">ANYWHERE</p>1589          <ul>1590            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1591              <li>1592                <span>{d.label}</span>1593                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1594              </li>1595            ))}1596          </ul>1597        </div>1598      </div>1599    </div>1600  );1601}