App.tsx

66.8 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 { NotesMode } from "./views/NotesMode";12import { ProCelebration } from "./views/ProCelebration";13import { VaultView, type SortOrder } from "./views/Vault";14import { EntryView } from "./views/Entry";15import { AddView } from "./views/Add";16import { PeachMark, PeachWordmark } from "./components/PeachMark";17import { PasskeyApprovalView } from "./views/PasskeyApproval";18import { extractDomain } from "../shared/domain";19import { popupCopy } from "./copy";20import {21  DEFAULT_BINDINGS,22  formatKeybinding,23  getActiveBindings,24  matchKeybinding,25  SHORTCUT_DESCRIPTORS,26  type Keybinding,27  type ShortcutAction,28} from "../shared/shortcuts";29import { generateTOTP } from "../crypto/totp";30import { isNativePlatform, nativePlugin } from "../shared/native";3132export { sendMessage } from "../shared/bridge";3334const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));35const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));36const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));37const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));38const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));39const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));40const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));41const AddDeviceView   = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.AddDeviceView })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "sync-pairing"51  | "sync-add-device"52  | "import"53  | "export"54  | "health"55  | "trash"56  | "panic";57type BootState = "loading" | "ready";5859const canarySuppressMap = new Map<string, boolean>();60let shellRingAnimation: Animation | null = null;6162export function isCanarySuppressed(entryId: string): boolean {63  return canarySuppressMap.get(entryId) ?? false;64}6566export function setCanarySuppressed(entryId: string, suppressed: boolean): void {67  canarySuppressMap.set(entryId, suppressed);68}6970export function clearCanarySuppressions(): void {71  canarySuppressMap.clear();72}7374export function triggerRing() {75  const shell = document.getElementById("hd-shell");76  if (!shell) return;7778  shellRingAnimation?.cancel();79  shell.dataset.glowing = "true";80  const animation = shell.animate(81    [82      { offset: 0, boxShadow: "var(--copy-shadow)" },83      {84        offset: 0.3,85        boxShadow:86          "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)",87      },88      { offset: 1, boxShadow: "var(--copy-shadow)" },89    ],90    {91      duration: 720,92      easing: "cubic-bezier(0.4, 0, 0.2, 1)",93      fill: "none",94    }95  );96  shellRingAnimation = animation;97  const clearGlow = () => {98    if (shellRingAnimation !== animation) return;99    shellRingAnimation = null;100    delete shell.dataset.glowing;101  };102  animation.onfinish = clearGlow;103  animation.oncancel = clearGlow;104}105106107export function triggerPipPulse() {108  const pip = document.querySelector(".peach-status-pip, .pip");109  if (pip) {110    pip.classList.remove("pulse");111    void (pip as HTMLElement).offsetWidth;112    pip.classList.add("pulse");113  }114}115116const ENTRY_TRANSITION_EXIT_MS = 95;117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");137  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");138  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);139  const [lockOnClose, setLockOnClose] = createSignal(true);140  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);141  const [breachMonitoring, setBreachMonitoring] = createSignal(true);142  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);143  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);144  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);145  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);146  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);147  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");148  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");149  // Cached Pro status — synchronous for render paths. Background's150  // GET_LICENSE is async, but render-time reads of isPro() must not block.151  // Refreshed at boot, after activate/deactivate, and whenever the popup152  // re-opens onto a stored license that has changed via another window.153  const [proStatus, setProStatus] = createSignal(false);154  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);155  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);156  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");157  const [listSearchSeed, setListSearchSeed] = createSignal("");158  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);159  const [pendingCelebration, setPendingCelebration] = createSignal(false);160  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);161  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);162  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);163  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);164  const [incomingPairTick, setIncomingPairTick] = createSignal(0);165  const incomingPairSecondsLeft = () => {166    void incomingPairTick();167    const req = incomingPair();168    if (!req) return 0;169    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));170  };171  // True while Panic Step 1 has bounced the user out to Export. When Export's172  // onBack fires we return to Panic instead of Settings so the user keeps the173  // destruction context they came from.174  const [returnToPanic, setReturnToPanic] = createSignal(false);175  const [showNotes, setShowNotes] = createSignal(false);176  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);177  // Set on popup boot when peach_recovery_pending flag is found in session178  // storage — instructs LockView to skip the unlock UI and open the recovery179  // words confirmation surface instead. Cleared via handleUnlock once the180  // user has typed the 3 confirmation words.181  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);182183  let contentPhaseTimer: number | undefined;184185  function applyAccent(name: AccentColorName) {186    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;187    const hex = color.hex;188    document.documentElement.style.setProperty("--peach-accent", hex);189    // Ambient surface variables — derived from the accent so surfaces shift190    // subtly toward the accent hue rather than staying fixed warm-brown.191    document.documentElement.style.setProperty("--peach-glow", hex + "2A");192    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");193    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");194  }195196  createEffect(() => {197    applyAccent(accentColor());198  });199200  createEffect(() => {201    document.documentElement.classList.toggle("light", theme() === "light");202    document.body.classList.toggle("light", theme() === "light");203  });204205  createEffect(() => {206    document.documentElement.setAttribute("data-display-font", displayFont());207  });208209  createEffect(() => {210    document.documentElement.setAttribute("data-text-size", textSize());211  });212213  createEffect(() => {214    if (reduceMotion()) {215      document.documentElement.setAttribute("data-motion", "reduce");216    } else {217      document.documentElement.removeAttribute("data-motion");218    }219  });220221  const selectedIndex = createMemo(() => {222    const currentId = selectedEntry()?.id;223    if (!currentId) return entries().length > 0 ? 0 : -1;224    return entries().findIndex((entry) => entry.id === currentId);225  });226227  async function applyAccentColor(name: AccentColorName) {228    applyAccent(name);229    setAccentColor(name);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });231  }232233  async function applyTheme(t: "dark" | "light") {234    setTheme(t);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });236  }237238  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {239    setDisplayFont(f);240    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });241  }242243  async function applyTextSize(size: "small" | "medium" | "large") {244    setTextSize(size);245    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });246  }247248  async function applyReduceMotion(enabled: boolean) {249    setReduceMotion(enabled);250    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });251  }252253  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload254  // small and lets future default updates land for actions the user hasn't255  // touched. Settings sends us the full active map; we filter and store.256  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {257    setShortcutBindings(active);258    const overrides: Record<string, Keybinding> = {};259    for (const action of Object.keys(active) as ShortcutAction[]) {260      const a = active[action];261      const d = DEFAULT_BINDINGS[action];262      const same = a.key === d.key263        && Boolean(a.ctrl)  === Boolean(d.ctrl)264        && Boolean(a.meta)  === Boolean(d.meta)265        && Boolean(a.shift) === Boolean(d.shift)266        && Boolean(a.alt)   === Boolean(d.alt);267      if (!same) overrides[action] = a;268    }269    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });270  }271272  async function applyLockOnClose(enabled: boolean) {273    setLockOnClose(enabled);274    await sendMessage({275      type: "UPDATE_SETTINGS",276      payload: { lockOnClose: enabled },277    });278  }279280  async function applyAutoLockMinutes(minutes: number) {281    setAutoLockMinutes(minutes);282    await sendMessage({283      type: "UPDATE_SETTINGS",284      payload: { autoLockMinutes: minutes },285    });286  }287288  async function applyBreachMonitoring(enabled: boolean) {289    setBreachMonitoring(enabled);290    await sendMessage({291      type: "UPDATE_SETTINGS",292      payload: { breachMonitoring: enabled },293    });294  }295296  onMount(async () => {297    // Resolve the active tab in parallel with the unlock/has-vault queries —298    // openVault()'s smart selection picks the entry matching currentTabDomain,299    // so it must be populated before openVault runs. Previously refreshCurrentTab300    // ran after openVault, leaving popups that booted already-unlocked falling301    // back to loadedEntries[0] instead of the domain match.302    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([303      sendMessage({ type: "IS_UNLOCKED" }),304      sendMessage({ type: "HAS_VAULT" }),305      refreshCurrentTab(),306      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),307    ]);308    const unlocked = Boolean(309      (unlockResponse as { ok: boolean; data?: boolean }).data310    );311    const vaultExists = Boolean(312      (vaultResponse as { ok: boolean; data?: boolean }).data313    );314    const shouldCelebrate = Boolean(315      (celebrationResponse as { ok: boolean; data?: boolean }).data316    );317    setHasVault(vaultExists);318    // Onboarding gate — show once on first install, never again. Existing319    // users (vaultExists) are auto-marked onboarded so they skip the flow320    // even on the very first popup open after this feature ships.321    try {322      const onboarded = await storageGet("peach_onboarded");323      const seen = onboarded === "true";324      if (vaultExists && !seen) {325        await storageSet("peach_onboarded", "true");326        setOnboarded(true);327      } else {328        setOnboarded(seen);329      }330    } catch {331      // storage unavailable — default to onboarded so we never block boot332      setOnboarded(true);333    }334    await Promise.all([restoreSettings(), refreshProStatus()]);335336    // Mark played before any animation so a crash mid-sequence never replays it337    if (shouldCelebrate) {338      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });339    }340341    // If the user created a vault but hasn't yet confirmed their recovery342    // words, route back to the recovery-words screen instead of opening the343    // entries view. The flag lives in chrome.storage.local so it survives344    // both popup close (SW suppresses lock-on-close) and full browser345    // restart (handleUnlock checks the same flag after a fresh password346    // unlock). Cleared when confirmation succeeds.347    let recoveryPending = false;348    try {349      const out = await chrome.storage.local?.get("peach_recovery_pending");350      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";351    } catch { /* best-effort */ }352353    // Native: closing the app before recovery-words confirmation means the354    // user didn't finish vault creation. Throw the partial vault away and355    // restart onboarding rather than asking them to unlock a vault they356    // never finished creating. Desktop keeps the existing "unlock to357    // resume" flow because closing the popup there is much more casual.358    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {359      try {360        await chrome.storage.local?.remove([361          "peach_vault_a",362          "peach_vault_b",363          "peach_recovery_pending",364          "peach_onboarded",365          "peach_vault_history",366        ]);367      } catch { /* best-effort */ }368      setHasVault(false);369      setOnboarded(false);370      setView("lock");371      setBootState("ready");372      document.getElementById("pre-lock")?.setAttribute("hidden", "true");373      return;374    }375376    if (recoveryPending && unlocked) {377      // forceRecoveryWords overrides LockView's hasVault gate so the378      // recovery surface renders even though the vault now exists.379      setForceRecoveryWords(true);380      setView("lock");381    } else if (unlocked && vaultExists) {382      await openVault(undefined, shouldCelebrate);383      if (shouldCelebrate) {384        setView("pro-celebration");385        window.setTimeout(() => setView("entry"), 2500);386      }387    } else if (shouldCelebrate) {388      setPendingCelebration(true);389    }390391    await refreshPendingPasskey();392    await refreshIncomingPairing();393    await consumeRecentPairing();394395    // Track tab changes so smart sort stays current396    const handleTabActivated = () => { void refreshCurrentTab(); };397    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {398      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();399    };400    try {401      chrome.tabs.onActivated.addListener(handleTabActivated);402      chrome.tabs.onUpdated.addListener(handleTabUpdated);403      onCleanup(() => {404        chrome.tabs.onActivated.removeListener(handleTabActivated);405        chrome.tabs.onUpdated.removeListener(handleTabUpdated);406      });407    } catch {408      // tabs permission may not be available in all contexts409    }410411    setBootState("ready");412    document.getElementById("pre-lock")?.setAttribute("hidden", "true");413414    // Check for pending session-storage notices from the background.415    if (chrome.storage.session) {416      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as417        Record<string, { feature?: string } | undefined>;418      if (session.pendingProGate?.feature) {419        await chrome.storage.session.remove("pendingProGate");420        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);421        setSettingsInitialSection("license");422        setView("settings");423      } else if (session.pendingProNotice?.feature) {424        await chrome.storage.session.remove("pendingProNotice");425        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });426      }427    }428429    // Warm the lazy-module cache so the Suspense fallback never shows for430    // locally-bundled extension views. Without this, the first navigation to431    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which432    // covers the shell and absorbs clicks on the header.433    void Promise.all([434      import("./views/Settings").catch(() => {}),435      import("./views/Import").catch(() => {}),436      import("./views/Export").catch(() => {}),437      import("./views/Health").catch(() => {}),438      import("./views/TrashView").catch(() => {}),439    ]);440441    // Lock-on-close via a persistent port. sendMessage in pagehide is442    // unreliable — the popup context tears down before the message lands.443    // The SW's onConnect listener locks when this port disconnects.444    let popupPort: chrome.runtime.Port | null = null;445    try {446      popupPort = chrome.runtime.connect({ name: "popup" });447    } catch { /* extension context invalidated — ignore */ }448    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });449450    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only451    // reliable signal is appStateChange — setTimeout is killed when the OS452    // backgrounds the app. We measure elapsed background time on resume.453    if (isNativePlatform()) {454      let backgroundedAt: number | null = null;455      let syncPollInterval: ReturnType<typeof setInterval> | null = null;456457      function startSyncPolling() {458        if (syncPollInterval) return;459        syncPollInterval = setInterval(async () => {460          const res = await sendMessage({ type: 'TRIGGER_SYNC' }).catch(() => null);461          const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;462          if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {463            await sendMessage({ type: 'GET_ENTRIES' }).catch(() => null);464          }465        }, 60_000);466      }467468      function stopSyncPolling() {469        if (syncPollInterval) { clearInterval(syncPollInterval); syncPollInterval = null; }470      }471472      const CapApp = nativePlugin<{473        addListener: (474          ev: string,475          cb: (s: { isActive: boolean }) => void,476        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };477      }>("App");478      if (CapApp?.addListener) {479        const sub = CapApp.addListener(480          "appStateChange",481          ({ isActive }: { isActive: boolean }) => {482            if (!isActive) {483              backgroundedAt = Date.now();484              stopSyncPolling();485              return;486            }487            if (backgroundedAt !== null && autoLockMinutes() > 0) {488              const elapsed = Date.now() - backgroundedAt;489              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();490            }491            backgroundedAt = null;492            // Resume polling when app comes to foreground (Pro only).493            if (proStatus()) startSyncPolling();494          }495        );496        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.497        onCleanup(() => {498          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});499          stopSyncPolling();500        });501      }502    }503504    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale505    // entries instead of waiting for the next GET_ENTRIES round-trip.506    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {507      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();508      if (msg?.type === "PRO_GATE_TRIGGERED") {509        setUpgradeHighlight(msg.payload?.feature ?? null);510        setSettingsInitialSection("license");511        setView("settings");512      }513    };514    chrome.runtime.onMessage.addListener(handleRuntimeMessage);515    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));516517    // Android hardware/gesture back. MainActivity fires peach:back; the popup518    // decides what "back" means per surface. Lock+no-vault is the common case519    // — return to onboarding rather than letting the OS dismiss the activity.520    const handlePeachBack = () => {521      // Notes mode captures back first522      if (showNotes()) {523        setShowNotes(false);524        setOpenNoteId(undefined);525        return;526      }527      const v = view();528      if (v === "lock" && !hasVault() && onboarded()) {529        setOnboarded(false);530        return;531      }532      if (v === "list") { setView("entry"); return; }533      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {534        handleBack();535        return;536      }537      if (v === "sync-pairing") { setView("settings"); return; }538    };539    window.addEventListener("peach:back", handlePeachBack);540    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));541542    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that543    // peeks from the bottom (search bar handle visible) and drags up to fill544    // the screen. dragOffset is the LIVE finger offset during a drag, in px,545    // 0 when no drag in progress. The wrapper element computes transform =546    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.547    if (isNativePlatform()) {548      let touchStartY = 0;549      let touchStartX = 0;550      let lastY = 0;551      let lastT = 0;552      let dragging = false;553      let captured = false;554      const HORIZONTAL_TOLERANCE = 16;555      const ACTIVATION_DY = 8;556      const PEEK_PX = 60;557558      const onTouchStart = (e: TouchEvent) => {559        const t = e.touches[0];560        if (!t) return;561        const v = view();562        if (v !== "entry" && v !== "list") return;563        // Entry view: only intercept drags starting in the bottom 40%.564        // List view: intercept drags starting in the top 35% (the search/handle row).565        const inBand = v === "entry"566          ? t.clientY > window.innerHeight * 0.6567          : t.clientY < window.innerHeight * 0.35;568        if (!inBand) return;569        touchStartY = lastY = t.clientY;570        touchStartX = t.clientX;571        lastT = e.timeStamp;572        dragging = true;573        captured = false;574      };575576      const onTouchMove = (e: TouchEvent) => {577        if (!dragging) return;578        const t = e.touches[0];579        if (!t) return;580        const dy = t.clientY - touchStartY;581        const dx = Math.abs(t.clientX - touchStartX);582583        if (!captured) {584          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {585            // Looks like a horizontal swipe — release.586            dragging = false;587            return;588          }589          if (Math.abs(dy) < ACTIVATION_DY) return;590          captured = true;591        }592593        // Translate the sheet by dy from its rest (peek) position. Peek is594        // (viewport height - PEEK_PX). Open is 0.595        const v = view();596        const restClosed = window.innerHeight - PEEK_PX;597        const baseTranslate = v === "list" ? 0 : restClosed;598        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));599        setSheetTranslate(next);600        lastY = t.clientY;601        lastT = e.timeStamp;602      };603604      const onTouchEnd = (e: TouchEvent) => {605        if (!dragging) { return; }606        const t = e.changedTouches[0];607        const elapsed = Math.max(1, e.timeStamp - lastT);608        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms609        const wasCaptured = captured;610        dragging = false;611        captured = false;612        const v = view();613614        if (!wasCaptured) {615          // Tap in the peek strip while in entry view → open the vault list.616          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");617          setSheetTranslate(null);618          return;619        }620621        const restClosed = window.innerHeight - PEEK_PX;622        const current = sheetTranslate() ?? restClosed;623624        // Snap rules:625        //   - Strong upward velocity → open626        //   - Strong downward velocity → close627        //   - Otherwise snap to whichever rest is closer628        let nextOpen: boolean;629        if (velocity < -0.05) nextOpen = true;630        else if (velocity > 0.05) nextOpen = false;631        else nextOpen = current < restClosed * 0.5;632633        if (nextOpen && v !== "list") setView("list");634        if (!nextOpen && v !== "entry") setView("entry");635        // Release the live offset so CSS transition handles the snap.636        setSheetTranslate(null);637      };638639      document.addEventListener("touchstart", onTouchStart, { passive: true });640      document.addEventListener("touchmove",  onTouchMove,  { passive: true });641      document.addEventListener("touchend",   onTouchEnd,   { passive: true });642      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });643      onCleanup(() => {644        document.removeEventListener("touchstart", onTouchStart);645        document.removeEventListener("touchmove",  onTouchMove);646        document.removeEventListener("touchend",   onTouchEnd);647      });648    }649650    // Action handlers — keyed by ShortcutAction. The dispatcher below tests651    // each binding against the event and runs the matching handler. New652    // shortcuts only need an entry here; the binding is data, not code.653    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {654      copy_password: () => {655        const entry = selectedEntry();656        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });657      },658      copy_username: () => {659        const entry = selectedEntry();660        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });661      },662      copy_totp: () => {663        const entry = selectedEntry();664        if (!entry?.totp) return;665        try {666          const { code } = generateTOTP(entry.totp);667          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });668        } catch { /* invalid TOTP secret — silent */ }669      },670      new_entry: () => handleAdd(),671      edit_entry: () => {672        const entry = selectedEntry();673        // Passkey-only entries have nothing user-editable in the Add view; the674        // passkey credential itself is opaque. Skip the edit action for them.675        if (!entry || isPasskeyOnly(entry)) return;676        setEditEntry(entry);677        setView("add");678      },679      delete_entry: () => {680        if (selectedEntry()) void handleDelete();681      },682      lock_vault: () => { void handleHeaderLock(); },683      search: () => openList(),684      nav_prev: () => navigate(-1),685      nav_next: () => navigate(1),686      jump_vault: () => setView("entry"),687      jump_settings: () => setView("settings"),688      show_help: () => setShowShortcutsHelp(true),689    };690691    // Actions that are MEANINGFUL only on the entry-detail view. Outside692    // that scope the binding is dormant — pressing C while on Settings693    // does nothing rather than awkwardly copying from a now-stale entry.694    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([695      "copy_password", "copy_username", "copy_totp",696      "edit_entry", "delete_entry", "nav_prev", "nav_next",697    ]);698699    const handleGlobalKeydown = (e: KeyboardEvent) => {700      const v = view();701      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"702        || (e.target as HTMLElement)?.tagName === "TEXTAREA"703        || (e.target as HTMLElement)?.isContentEditable;704      const isPrintableSearchKey =705        e.key.length === 1 &&706        !e.ctrlKey &&707        !e.metaKey &&708        !e.altKey;709710      // No input during the pro celebration sequence711      if (v === "pro-celebration") return;712713      // Help dialog: Escape closes it; eat the keypress so it doesn't714      // also navigate away from the underlying view.715      if (showShortcutsHelp()) {716        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }717        return;718      }719720      // ── Escape — fixed binding (not user-customizable) ───────721      if (e.key === "Escape") {722        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }723        if (v === "list") { setView("entry"); return; }724        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }725        if (v === "sync-pairing") { setView("settings"); return; }726        if (v === "sync-add-device") { setView("sync-pairing"); return; }727      }728729      // Bindings-driven dispatch. Single-key letter bindings without730      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is731      // inside an input, so users can type into search/forms normally.732      const bindings = shortcutBindings();733      for (const action of Object.keys(bindings) as ShortcutAction[]) {734        const binding = bindings[action];735        if (!matchKeybinding(e, binding)) continue;736        // Single-key letter bindings need the input-focus guard. Bindings737        // with any modifier are safe — Ctrl+L doesn't conflict with typing.738        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;739        if (!hasMod && binding.key.length === 1 && inInput) return;740        if (ENTRY_SCOPED.has(action) && v !== "entry") return;741        e.preventDefault();742        SHORTCUT_HANDLERS[action]?.();743        return;744      }745746      // Type-to-search: in entry view, any printable key not consumed by a747      // shortcut above primes the list search seed and opens the list.748      // Kept outside the bindings table because it's a behavior, not a749      // discrete action — every printable character can trigger it.750      if (v === "entry" && !inInput && isPrintableSearchKey) {751        e.preventDefault();752        primeListSearch(e.key);753        return;754      }755    };756    window.addEventListener("keydown", handleGlobalKeydown);757    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));758759    const handleStorageChanged = (760      changes: Record<string, chrome.storage.StorageChange>,761      areaName: string762    ) => {763      if (areaName !== "session") return;764      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {765        return;766      }767      void refreshPendingPasskey();768    };769    chrome.storage.onChanged.addListener(handleStorageChanged);770    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));771  });772773  async function refreshCurrentTab() {774    try {775      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });776      const url = tab?.url ?? tab?.pendingUrl ?? "";777      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");778      // Skip extension/internal URLs — adding chrome://, about:, or779      // chrome-extension:// to a vault entry is never what the user wants.780      const isWebUrl = /^https?:\/\//i.test(url);781      setCurrentTabUrl(isWebUrl ? url : "");782    } catch {783      setCurrentTabDomain("");784      setCurrentTabUrl("");785    }786  }787788  async function refreshPendingPasskey() {789    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });790    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);791  }792793  async function refreshIncomingPairing() {794    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });795    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;796    setIncomingPair(data);797  }798799  // Drains a single one-shot record left by the background when 6-digit800  // pairing succeeded while the popup was closed (or the SyncPairing view was801  // navigated away from before it could show its own success card).802  async function consumeRecentPairing() {803    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });804    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;805    if (data?.deviceName) {806      setRecentPairToast(data.deviceName);807      window.setTimeout(() => setRecentPairToast(null), 4000);808    }809  }810811  async function respondIncomingPairing(accept: boolean) {812    if (incomingPairResponding()) return;813    setIncomingPairResponding(true);814    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });815    setIncomingPair(null);816    setIncomingPairResponding(false);817  }818819  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a820  // request appears, ticks once per second, and clears the banner if the821  // request expires while the popup is open.822  createEffect(() => {823    const req = incomingPair();824    if (!req) return;825    const handle = window.setInterval(() => {826      setIncomingPairTick((tick) => tick + 1);827      if (Date.now() >= req.expiresAt) {828        setIncomingPair(null);829        window.clearInterval(handle);830      }831    }, 1000);832    onCleanup(() => window.clearInterval(handle));833  });834835  async function refreshProStatus() {836    const res = await sendMessage({ type: "GET_LICENSE" });837    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;838    setProStatus(Boolean(data?.valid && data?.plan === "pro"));839  }840841  async function restoreSettings() {842    const res = await sendMessage({ type: "GET_SETTINGS" });843    const s = (res as { ok: boolean; data?: any }).data ?? {};844    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {845      setAccentColor(s.accentColor as AccentColorName);846    }847    setTheme(s.theme === "light" ? "light" : "dark");848    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {849      setDisplayFont(s.displayFont);850    } else {851      setDisplayFont("cormorant-italic");852    }853    if (s.textSize === "small" || s.textSize === "large") {854      setTextSize(s.textSize);855    } else {856      setTextSize("medium");857    }858    setReduceMotion(s.reduceMotion === true);859    setLockOnClose(s.lockOnClose !== false);860    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);861    setBreachMonitoring(s.breachMonitoring !== false);862    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);863    setShortcutBindings(getActiveBindings(s.shortcuts));864  }865866  async function applyTrashRetention(days: number) {867    setTrashRetentionDays(days);868    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });869  }870871  function primeListSearch(seed: string) {872    setListSearchSeed(seed);873    setListSearchSeedNonce((value) => value + 1);874    openList();875  }876877  // Returns null when it detected a dead service worker and triggered handleLock().878  // Callers that need to abort (e.g. openVault) check for null rather than relying879  // on view() state, which may already be "lock" during normal startup flows.880  async function loadEntries(): Promise<VaultEntry[] | null> {881    const response = await sendMessage({ type: "GET_ENTRIES" });882    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };883884    // If the service worker was killed and restarted (MV3 workers sleep), the885    // vault will be locked again — or the worker may not respond at all.886    // In either case, send the user to the lock screen rather than silently887    // showing an empty vault (which looks like data loss).888    if (!res.ok) {889      if (890        res.error === "vault locked" ||891        res.error === "SERVICE_WORKER_UNAVAILABLE" ||892        (typeof res.error === "string" && res.error.includes("locked"))893      ) {894        handleLock();895        return null; // signal emergency lock to callers896      }897      return [];898    }899900    const loadedEntries = res.data ?? [];901    setEntries(loadedEntries);902903    const currentId = selectedEntry()?.id;904    if (currentId) {905      setSelectedEntry(906        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null907      );908    }909910    return loadedEntries;911  }912913  async function openVault(preferredEntryId?: string, skipViewSet = false) {914    // Desktop: fire-and-forget sync on every vault open (Pro only).915    // Never blocks popup load; refreshes entries if new data arrives.916    if (!isNativePlatform() && proStatus()) {917      void sendMessage({ type: 'TRIGGER_SYNC' }).then((res) => {918        const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;919        if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {920          void loadEntries();921        }922      }).catch(() => {});923    }924925    // Purge expired trash entries on each vault open926    const retDays = trashRetentionDays();927    if (retDays > 0) {928      void sendMessage({929        type: "PURGE_EXPIRED_TRASH",930        payload: { retentionMs: retDays * 86_400_000 },931      });932    }933934    const loadedEntries = await loadEntries();935936    // null means loadEntries() triggered an emergency lock (service worker died).937    // Don't override it by setting view back to "entry" with an empty vault.938    if (loadedEntries === null) return;939940    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry941    let nextSelectedEntry: VaultEntry | null = null;942    if (preferredEntryId) {943      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;944    }945    if (!nextSelectedEntry) {946      const tabDomain = currentTabDomain();947      if (tabDomain) {948        nextSelectedEntry = loadedEntries.find((e) => {949          if (e.type === "login") {950            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;951            for (const extra of e.additionalUrls ?? []) {952              if ((extractDomain(extra) ?? "") === tabDomain) return true;953            }954            return false;955          }956          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;957          return false;958        }) ?? null;959      }960    }961    nextSelectedEntry ??= loadedEntries[0] ?? null;962963    setSelectedEntry(nextSelectedEntry);964    setEditEntry(undefined);965    setContentTransitioning(false);966    setContentPhase("enter");967    queueContentIdle();968    if (!skipViewSet) setView("entry");969  }970971  async function handleUnlock() {972    // If the user previously created a vault but hadn't yet confirmed their973    // recovery words (and the browser was closed before they could), the974    // peach_recovery_pending flag is still set in storage.local. Re-route975    // back to the recovery surface so they finish the confirmation step976    // before reaching the entries view — the words can be re-derived now977    // that the vault is unlocked again.978    let recoveryPending = false;979    try {980      const out = await chrome.storage.local?.get("peach_recovery_pending");981      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";982    } catch { /* best-effort */ }983    if (recoveryPending) {984      setForceRecoveryWords(true);985      setView("lock");986      triggerPipPulse();987      await restoreSettings();988      return;989    }990    setHasVault(true);991    triggerPipPulse();992    await restoreSettings();993    const celebrating = pendingCelebration();994    if (celebrating) {995      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });996      setPendingCelebration(false);997    }998    await openVault(undefined, celebrating);999    if (celebrating) {1000      setView("pro-celebration");1001      window.setTimeout(() => setView("entry"), 2500);1002    }1003  }10041005  function handleSelectEntry(entry: VaultEntry) {1006    if (entry.type === "note") {1007      setOpenNoteId(entry.id);1008      setShowNotes(true);1009      return;1010    }1011    setSelectedEntry(entry);1012    setContentTransitioning(false);1013    setContentPhase("enter");1014    queueContentIdle();1015    setView("entry");1016  }10171018  function handleAdd() {1019    setEditEntry(undefined);1020    setView("add");1021  }10221023  async function handleDelete() {1024    const entry = selectedEntry();1025    if (!entry) return;1026    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1027    const loadedEntries = await loadEntries() ?? [];1028    setSelectedEntry(loadedEntries[0] ?? null);1029    setView("entry");1030  }10311032  async function handleDeleteMany(ids: string[]) {1033    for (const id of ids) {1034      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1035    }1036    const loadedEntries = await loadEntries() ?? [];1037    // If the currently selected entry was among the deleted, move to first1038    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1039    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1040  }10411042  async function handleSave(savedEntry?: VaultEntry) {1043    await openVault(savedEntry?.id);1044  }10451046  function handleBack() {1047    setEditEntry(undefined);1048    setView("entry");1049  }10501051  function handleLock() {1052    clearCanarySuppressions();1053    setEntries([]);1054    setSelectedEntry(null);1055    setEditEntry(undefined);1056    setContentPhase("idle");1057    setView("lock");1058  }10591060  function handleHeaderLock() {1061    // Lock the UI immediately — do not wait for the service worker. If the SW1062    // is dead or slow, the 5s sendMessage timeout would create a dead-click1063    // window. The SW will lock on its next wake regardless.1064    handleLock();1065    void sendMessage({ type: "LOCK" });1066  }10671068  function navigate(dir: number) {1069    const allEntries = entries();1070    if (allEntries.length === 0) return;1071    const currentIndex = selectedIndex();1072    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1073    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1074    setSelectedEntry(allEntries[nextIndex]);1075    setContentPhase("enter");1076    queueContentIdle();1077  }10781079  function openList() {1080    setView("list");1081  }10821083  function openHealth() {1084    setEditEntry(undefined);1085    setView("health");1086  }10871088  function handleOpenFileImport() {1089    setRestoreView("file");1090  }10911092  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10931094  function handleFixEntry(entry: VaultEntry) {1095    // Passkey-only entries have no editable surface — drop into view mode1096    // instead of opening the Add editor.1097    if (isPasskeyOnly(entry)) {1098      setSelectedEntry(entry);1099      setView("entry");1100      return;1101    }1102    setEditEntry(entry);1103    setView("add");1104  }11051106  const isLockedView = () => view() === "lock";11071108  async function handleApprovePendingPasskey() {1109    const pending = pendingPasskey();1110    if (!pending) return;1111    if (pending.browser === "firefox" && pending.type === "create") {1112      // Firefox path: popup itself runs navigator.credentials.create. The1113      // background never approved/rejected anything — it just stashed1114      // intent. After the popup-driven flow resolves (success or cancel),1115      // clear the pending key so the popup doesn't re-show this on next open.1116      const { createFirefoxPasskey } = await import("./firefox-passkey");1117      const result = await createFirefoxPasskey(pending);1118      if (!result.ok) {1119        console.warn("Peach Firefox passkey create failed:", result.error);1120      }1121      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1122      setPendingPasskey(null);1123      void loadEntries();1124      window.close();1125      return;1126    }1127    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1128    window.close();1129  }11301131  async function handleDenyPendingPasskey() {1132    const pending = pendingPasskey();1133    if (!pending) return;1134    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1135    window.close();1136  }11371138  function queueContentIdle(after?: () => void) {1139    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1140    contentPhaseTimer = window.setTimeout(() => {1141      setContentPhase("idle");1142      after?.();1143    }, ENTRY_TRANSITION_SETTLE_MS);1144  }11451146  return (1147    <div class="popup-root peach-theme">1148      <Show when={bootState() === "ready"}>1149        <Show1150          when={!pendingPasskey()}1151          fallback={1152            <PasskeyApprovalView1153              type={pendingPasskey()!.type}1154              rpName={pendingPasskey()!.rpName}1155              rpId={pendingPasskey()!.rpId}1156              userName={pendingPasskey()!.userName}1157              userDisplayName={pendingPasskey()!.userDisplayName}1158              onApprove={handleApprovePendingPasskey}1159              onDeny={handleDenyPendingPasskey}1160            />1161          }1162        >1163          <Show1164            when={!isLockedView()}1165            fallback={1166              <Show1167                when={onboarded() || hasVault()}1168                fallback={1169                  <Onboarding1170                    onComplete={() => { setOnboarded(true); }}1171                  />1172                }1173              >1174                <LockView1175                  hasVault={hasVault()}1176                  ready={bootState() === "ready"}1177                  isPro={proStatus()}1178                  forceRecoveryWords={forceRecoveryWords()}1179                  onUnlock={() => {1180                    // RecoveryWordDisplay clears the storage flag before1181                    // calling onDone, so handleUnlock will see no pending1182                    // confirmation and proceed through the normal path.1183                    if (forceRecoveryWords()) setForceRecoveryWords(false);1184                    return handleUnlock();1185                  }}1186                  onBackToOnboarding={1187                    !hasVault()1188                      ? () => setOnboarded(false)1189                      : undefined1190                  }1191                />1192              </Show>1193            }1194          >1195            <Show1196              when={view() !== "pro-celebration"}1197              fallback={<ProCelebration />}1198            >1199            <section1200              id="hd-shell"1201              class="peach-shell peach-theme"1202              data-surface="extension"1203            >1204            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1205              <PeachWordmark unlocked />1206              <div class="peach-chrome-actions">1207                <button1208                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1209                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1210                  aria-label="Notes"1211                  title="Notes"1212                >1213                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1214                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1215                    <line x1="4" y1="5" x2="10" y2="5" />1216                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1217                    <line x1="4" y1="10" x2="7" y2="10" />1218                  </svg>1219                </button>1220                <button1221                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1222                  onClick={() => setView("settings")}1223                  aria-label="Settings"1224                >1225                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1226                    <path1227                      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"1228                      stroke="currentColor"1229                      stroke-width="0.9"1230                    />1231                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1232                  </svg>1233                </button>1234                <button1235                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1236                  onClick={handleAdd}1237                  aria-label="New entry"1238                >1239                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1240                    <path d="M5.5 1v9M1 5.5h9" />1241                  </svg>1242                </button>1243                <button1244                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1245                  onClick={() => void handleHeaderLock()}1246                  aria-label="Lock vault"1247                >1248                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1249                    <path1250                      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"1251                      stroke="currentColor"1252                      stroke-width="1"1253                      stroke-linecap="round"1254                    />1255                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1256                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1257                  </svg>1258                </button>1259              </div>1260            </header>12611262            <Show when={recentPairToast()}>1263              <div class="peach-pair-toast" role="status" aria-live="polite">1264                Paired with <strong>{recentPairToast()}</strong>1265              </div>1266            </Show>12671268            <Show when={incomingPair() !== null}>1269              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1270                <div class="peach-pair-request-header">1271                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1272                  <span class="peach-pair-request-title">Pairing request</span>1273                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1274                </div>1275                <p class="peach-pair-request-body">1276                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1277                </p>1278                <div class="peach-pair-request-actions">1279                  <button1280                    class="peach-btn peach-btn--ghost peach-btn--sm"1281                    onClick={() => void respondIncomingPairing(false)}1282                    disabled={incomingPairResponding()}1283                  >1284                    Reject1285                  </button>1286                  <button1287                    class="peach-btn peach-btn--accent peach-btn--sm"1288                    onClick={() => void respondIncomingPairing(true)}1289                    disabled={incomingPairResponding()}1290                  >1291                    Accept1292                  </button>1293                </div>1294              </div>1295            </Show>12961297            <Show when={pendingProNotice() !== null}>1298              <div class="peach-pro-notice-banner">1299                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1300                <button1301                  class="peach-pro-notice-link"1302                  onClick={() => {1303                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1304                    setSettingsInitialSection("license");1305                    setView("settings");1306                    setPendingProNotice(null);1307                  }}1308                >1309                  Learn more →1310                </button>1311                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1312              </div>1313            </Show>13141315            <div class="peach-shell-body">1316              <div class="peach-shell-veil"></div>1317              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1318                <EntryView1319                  entry={selectedEntry()}1320                  currentTabUrl={currentTabUrl()}1321                  entries={entries()}1322                  onDelete={handleDelete}1323                  onFieldSaved={() => void loadEntries()}1324                  onEscape={() => { setView("list"); }}1325                />1326              </div>13271328              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1329                <div class="peach-search-bar">1330                  <span class="peach-search-icon">1331                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1332                      <circle cx="5.5" cy="5.5" r="3.75" />1333                      <path d="M8.75 8.75L11.5 11.5" />1334                    </svg>1335                  </span>1336                  <input1337                    class="peach-search-input"1338                    placeholder="search vault..."1339                    autocomplete="off"1340                    aria-label="Search vault entries"1341                    onClick={openList}1342                    onFocus={openList}1343                    readOnly1344                  />1345                  <div class="peach-search-meta">1346                    <span class="peach-search-counter">1347                      {entries().length > 01348                        ? `${selectedIndex() + 1} / ${entries().length}`1349                        : "0 entries"}1350                    </span>1351                    <span class="peach-divider"></span>1352                    <button1353                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1354                      onClick={() => navigate(-1)}1355                      aria-label="Previous entry"1356                      disabled={entries().length === 0}1357                    >1358                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1359                        <path d="M5 1L1 5.5L5 10" />1360                      </svg>1361                    </button>1362                    <button1363                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1364                      onClick={() => navigate(1)}1365                      aria-label="Next entry"1366                      disabled={entries().length === 0}1367                    >1368                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1369                        <path d="M1 1L5 5.5L1 10" />1370                      </svg>1371                    </button>1372                  </div>1373                </div>1374              </section>1375            </div>13761377            {/* Desktop: shown on demand via Show. Native sheet is rendered1378                via Portal below at the document root so its position:fixed1379                isn't trapped by .peach-shell's transform-based animations. */}1380            <Show when={!isNativePlatform() && view() === "list"}>1381              <VaultView1382                entries={entries()}1383                selectedEntryId={selectedEntry()?.id}1384                currentTabDomain={currentTabDomain()}1385                sortOrder={sortOrder()}1386                searchSeed={listSearchSeed()}1387                searchSeedNonce={listSearchSeedNonce()}1388                onSelectEntry={handleSelectEntry}1389                onSortOrderChange={setSortOrder}1390                onAdd={handleAdd}1391                onClose={() => setView("entry")}1392                onOpenTrash={() => setView("trash")}1393                onDeleteMany={handleDeleteMany}1394              />1395            </Show>1396            <Show when={isNativePlatform() && hasVault()}>1397              <Portal>1398                <div1399                  class="peach-vault-sheet"1400                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1401                  style={(() => {1402                    const live = sheetTranslate();1403                    if (live === null) return undefined;1404                    return { transform: `translateY(${live}px)` };1405                  })()}1406                >1407                  <VaultView1408                    entries={entries()}1409                    selectedEntryId={selectedEntry()?.id}1410                    currentTabDomain={currentTabDomain()}1411                    sortOrder={sortOrder()}1412                    searchSeed={listSearchSeed()}1413                    searchSeedNonce={listSearchSeedNonce()}1414                    onSelectEntry={handleSelectEntry}1415                    onSortOrderChange={setSortOrder}1416                    onAdd={handleAdd}1417                    onClose={() => setView("entry")}1418                    onOpenTrash={() => setView("trash")}1419                    onDeleteMany={handleDeleteMany}1420                  />1421                </div>1422              </Portal>1423            </Show>1424            <Show when={view() === "settings"}>1425              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1426                <SettingsView1427                  entriesCount={entries().length}1428                  breachMonitoring={breachMonitoring()}1429                  lockOnClose={lockOnClose()}1430                  autoLockMinutes={autoLockMinutes()}1431                  trashRetentionDays={trashRetentionDays()}1432                  theme={theme()}1433                  accentColor={accentColor()}1434                  displayFont={displayFont()}1435                  textSize={textSize()}1436                  reduceMotion={reduceMotion()}1437                  isPro={proStatus()}1438                  initialSection={settingsInitialSection()}1439                  upgradeHighlight={upgradeHighlight()}1440                  onBreachMonitoringChange={applyBreachMonitoring}1441                  onLockOnCloseChange={applyLockOnClose}1442                  onAutoLockMinutesChange={applyAutoLockMinutes}1443                  onTrashRetentionChange={applyTrashRetention}1444                  onThemeChange={applyTheme}1445                  onAccentChange={applyAccentColor}1446                  onDisplayFontChange={applyDisplayFont}1447                  onTextSizeChange={applyTextSize}1448                  onReduceMotionChange={applyReduceMotion}1449                  shortcuts={shortcutBindings()}1450                  onShortcutsChange={applyShortcuts}1451                  onLicenseChange={async () => {1452                    // After activation/deactivation: refresh Pro status,1453                    // re-load entries (defensive — signal state can drift if1454                    // the SW briefly restarts during the verify+save round-trip),1455                    // and replay the Pro celebration if this is the first time1456                    // a valid Pro license is seen on this device.1457                    await refreshProStatus();1458                    void loadEntries();1459                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1460                    if ((should as { ok: boolean; data?: boolean }).data === true) {1461                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1462                      setView("pro-celebration");1463                      window.setTimeout(() => setView("settings"), 2500);1464                    }1465                  }}1466                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1467                  onImport={() => setView("import")}1468                  onExport={() => setView("export")}1469                  onBreachCheckDone={loadEntries}1470                  onOpenHealth={openHealth}1471                  onOpenSyncPairing={() => setView("sync-pairing")}1472                  onOpenFileImport={handleOpenFileImport}1473                  onOpenPanic={() => setView("panic")}1474                />1475              </Suspense>1476            </Show>1477            <Show when={view() === "sync-pairing"}>1478              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1479                <SyncPairingView1480                  isPro={proStatus()}1481                  onAddDevice={() => setView("sync-add-device")}1482                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1483                  onBack={() => setView("settings")}1484                />1485              </Suspense>1486            </Show>1487            <Show when={view() === "sync-add-device"}>1488              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1489                <AddDeviceView1490                  onClose={() => setView("sync-pairing")}1491                  onPaired={() => setView("sync-pairing")}1492                />1493              </Suspense>1494            </Show>1495            <Show when={view() === "add"}>1496              <AddView1497                entry={editEntry()}1498                entries={entries()}1499                onBack={handleBack}1500                onSave={handleSave}1501              />1502            </Show>1503            <Show when={view() === "import"}>1504              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1505                <ImportView onBack={handleBack} onImport={handleSave} />1506              </Suspense>1507            </Show>1508            <Show when={view() === "export"}>1509              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1510                <ExportView1511                  onBack={() => {1512                    if (returnToPanic()) {1513                      setReturnToPanic(false);1514                      setView("panic");1515                    } else {1516                      handleBack();1517                    }1518                  }}1519                />1520              </Suspense>1521            </Show>1522            <Show when={view() === "panic"}>1523              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1524                <PanicView1525                  onCancel={() => setView("settings")}1526                  onOpenExport={() => {1527                    setReturnToPanic(true);1528                    setView("export");1529                  }}1530                  onDestroyed={async () => {1531                    clearCanarySuppressions();1532                    setEntries([]);1533                    setSelectedEntry(null);1534                    setEditEntry(undefined);1535                    setHasVault(false);1536                    setOnboarded(false);1537                    setProStatus(false);1538                    setPendingPasskey(null);1539                    setUpgradeHighlight(null);1540                    setSettingsInitialSection(null);1541                    setPendingProNotice(null);1542                    setPendingCelebration(false);1543                    setReturnToPanic(false);1544                    setContentPhase("idle");1545                    setView("lock");1546                  }}1547                />1548              </Suspense>1549            </Show>1550            <Show when={view() === "health"}>1551              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1552                <HealthView1553                  entries={entries()}1554                  isPro={proStatus()}1555                  onFixEntry={handleFixEntry}1556                  onBack={() => setView("settings")}1557                  onRefresh={loadEntries}1558                />1559              </Suspense>1560            </Show>1561            <Show when={view() === "trash"}>1562              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1563                <TrashView1564                  onBack={() => setView("list")}1565                  onRestored={() => void loadEntries()}1566                />1567              </Suspense>1568            </Show>1569            <Show when={showNotes()}>1570              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1571                <NotesMode1572                  notes={entries().filter((e) => e.type === "note")}1573                  initialNoteId={openNoteId()}1574                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1575                  onNoteListChanged={() => void loadEntries()}1576                />1577              </div>1578            </Show>1579            <Show when={restoreView() === "file"}>1580              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1581                <ImportView1582                  mode="onboarding"1583                  replacesExistingVault={true}1584                  onBack={() => setRestoreView(null)}1585                  onImport={async () => {1586                    setRestoreView(null);1587                    await handleUnlock();1588                  }}1589                />1590              </Suspense>1591            </Show>1592            </section>1593            </Show>1594          </Show>1595        </Show>1596      </Show>1597      <Show when={showShortcutsHelp()}>1598        <ShortcutsHelpOverlay1599          bindings={shortcutBindings()}1600          onClose={() => setShowShortcutsHelp(false)}1601        />1602      </Show>1603    </div>1604  );1605}16061607function ShortcutsHelpOverlay(props: {1608  bindings: Record<ShortcutAction, Keybinding>;1609  onClose: () => void;1610}) {1611  return (1612    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1613      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1614        <div class="peach-shortcuts-help-head">1615          <h3>Keyboard shortcuts</h3>1616          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1617        </div>1618        <div class="peach-shortcuts-help-body">1619          <p class="peach-settings-sub-label">ENTRY VIEW</p>1620          <ul>1621            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1622              <li>1623                <span>{d.label}</span>1624                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1625              </li>1626            ))}1627          </ul>1628          <p class="peach-settings-sub-label">ANYWHERE</p>1629          <ul>1630            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1631              <li>1632                <span>{d.label}</span>1633                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1634              </li>1635            ))}1636          </ul>1637        </div>1638      </div>1639    </div>1640  );1641}