App.tsx

63.7 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      const CapApp = nativePlugin<{453        addListener: (454          ev: string,455          cb: (s: { isActive: boolean }) => void,456        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };457      }>("App");458      if (CapApp?.addListener) {459        const sub = CapApp.addListener(460          "appStateChange",461          ({ isActive }: { isActive: boolean }) => {462            if (!isActive) {463              backgroundedAt = Date.now();464              return;465            }466            if (backgroundedAt !== null && autoLockMinutes() > 0) {467              const elapsed = Date.now() - backgroundedAt;468              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();469            }470            backgroundedAt = null;471          }472        );473        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.474        onCleanup(() => {475          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});476        });477      }478    }479480    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale481    // entries instead of waiting for the next GET_ENTRIES round-trip.482    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {483      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();484      if (msg?.type === "PRO_GATE_TRIGGERED") {485        setUpgradeHighlight(msg.payload?.feature ?? null);486        setSettingsInitialSection("license");487        setView("settings");488      }489    };490    chrome.runtime.onMessage.addListener(handleRuntimeMessage);491    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));492493    // Android hardware/gesture back. MainActivity fires peach:back; the popup494    // decides what "back" means per surface. Lock+no-vault is the common case495    // — return to onboarding rather than letting the OS dismiss the activity.496    const handlePeachBack = () => {497      const v = view();498      if (v === "lock" && !hasVault() && onboarded()) {499        setOnboarded(false);500        return;501      }502      if (v === "list") { setView("entry"); return; }503      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {504        handleBack();505        return;506      }507      if (v === "sync-pairing") { setView("settings"); return; }508    };509    window.addEventListener("peach:back", handlePeachBack);510    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));511512    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that513    // peeks from the bottom (search bar handle visible) and drags up to fill514    // the screen. dragOffset is the LIVE finger offset during a drag, in px,515    // 0 when no drag in progress. The wrapper element computes transform =516    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.517    if (isNativePlatform()) {518      let touchStartY = 0;519      let touchStartX = 0;520      let lastY = 0;521      let lastT = 0;522      let dragging = false;523      let captured = false;524      const HORIZONTAL_TOLERANCE = 16;525      const ACTIVATION_DY = 8;526      const PEEK_PX = 60;527528      const onTouchStart = (e: TouchEvent) => {529        const t = e.touches[0];530        if (!t) return;531        const v = view();532        if (v !== "entry" && v !== "list") return;533        // Entry view: only intercept drags starting in the bottom 40%.534        // List view: intercept drags starting in the top 35% (the search/handle row).535        const inBand = v === "entry"536          ? t.clientY > window.innerHeight * 0.6537          : t.clientY < window.innerHeight * 0.35;538        if (!inBand) return;539        touchStartY = lastY = t.clientY;540        touchStartX = t.clientX;541        lastT = e.timeStamp;542        dragging = true;543        captured = false;544      };545546      const onTouchMove = (e: TouchEvent) => {547        if (!dragging) return;548        const t = e.touches[0];549        if (!t) return;550        const dy = t.clientY - touchStartY;551        const dx = Math.abs(t.clientX - touchStartX);552553        if (!captured) {554          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {555            // Looks like a horizontal swipe — release.556            dragging = false;557            return;558          }559          if (Math.abs(dy) < ACTIVATION_DY) return;560          captured = true;561        }562563        // Translate the sheet by dy from its rest (peek) position. Peek is564        // (viewport height - PEEK_PX). Open is 0.565        const v = view();566        const restClosed = window.innerHeight - PEEK_PX;567        const baseTranslate = v === "list" ? 0 : restClosed;568        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));569        setSheetTranslate(next);570        lastY = t.clientY;571        lastT = e.timeStamp;572      };573574      const onTouchEnd = (e: TouchEvent) => {575        if (!dragging) { return; }576        const t = e.changedTouches[0];577        const elapsed = Math.max(1, e.timeStamp - lastT);578        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms579        const wasCaptured = captured;580        dragging = false;581        captured = false;582        const v = view();583584        if (!wasCaptured) {585          // Tap in the peek strip while in entry view → open the vault list.586          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");587          setSheetTranslate(null);588          return;589        }590591        const restClosed = window.innerHeight - PEEK_PX;592        const current = sheetTranslate() ?? restClosed;593594        // Snap rules:595        //   - Strong upward velocity → open596        //   - Strong downward velocity → close597        //   - Otherwise snap to whichever rest is closer598        let nextOpen: boolean;599        if (velocity < -0.05) nextOpen = true;600        else if (velocity > 0.05) nextOpen = false;601        else nextOpen = current < restClosed * 0.5;602603        if (nextOpen && v !== "list") setView("list");604        if (!nextOpen && v !== "entry") setView("entry");605        // Release the live offset so CSS transition handles the snap.606        setSheetTranslate(null);607      };608609      document.addEventListener("touchstart", onTouchStart, { passive: true });610      document.addEventListener("touchmove",  onTouchMove,  { passive: true });611      document.addEventListener("touchend",   onTouchEnd,   { passive: true });612      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });613      onCleanup(() => {614        document.removeEventListener("touchstart", onTouchStart);615        document.removeEventListener("touchmove",  onTouchMove);616        document.removeEventListener("touchend",   onTouchEnd);617      });618    }619620    // Action handlers — keyed by ShortcutAction. The dispatcher below tests621    // each binding against the event and runs the matching handler. New622    // shortcuts only need an entry here; the binding is data, not code.623    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {624      copy_password: () => {625        const entry = selectedEntry();626        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });627      },628      copy_username: () => {629        const entry = selectedEntry();630        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });631      },632      copy_totp: () => {633        const entry = selectedEntry();634        if (!entry?.totp) return;635        try {636          const { code } = generateTOTP(entry.totp);637          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });638        } catch { /* invalid TOTP secret — silent */ }639      },640      new_entry: () => handleAdd(),641      edit_entry: () => {642        const entry = selectedEntry();643        // Passkey-only entries have nothing user-editable in the Add view; the644        // passkey credential itself is opaque. Skip the edit action for them.645        if (!entry || isPasskeyOnly(entry)) return;646        setEditEntry(entry);647        setView("add");648      },649      delete_entry: () => {650        if (selectedEntry()) void handleDelete();651      },652      lock_vault: () => { void handleHeaderLock(); },653      search: () => openList(),654      nav_prev: () => navigate(-1),655      nav_next: () => navigate(1),656      jump_vault: () => setView("entry"),657      jump_settings: () => setView("settings"),658      show_help: () => setShowShortcutsHelp(true),659    };660661    // Actions that are MEANINGFUL only on the entry-detail view. Outside662    // that scope the binding is dormant — pressing C while on Settings663    // does nothing rather than awkwardly copying from a now-stale entry.664    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([665      "copy_password", "copy_username", "copy_totp",666      "edit_entry", "delete_entry", "nav_prev", "nav_next",667    ]);668669    const handleGlobalKeydown = (e: KeyboardEvent) => {670      const v = view();671      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"672        || (e.target as HTMLElement)?.tagName === "TEXTAREA"673        || (e.target as HTMLElement)?.isContentEditable;674      const isPrintableSearchKey =675        e.key.length === 1 &&676        !e.ctrlKey &&677        !e.metaKey &&678        !e.altKey;679680      // No input during the pro celebration sequence681      if (v === "pro-celebration") return;682683      // Help dialog: Escape closes it; eat the keypress so it doesn't684      // also navigate away from the underlying view.685      if (showShortcutsHelp()) {686        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }687        return;688      }689690      // ── Escape — fixed binding (not user-customizable) ───────691      if (e.key === "Escape") {692        if (v === "list") { setView("entry"); return; }693        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }694        if (v === "sync-pairing") { setView("settings"); return; }695        if (v === "sync-add-device") { setView("sync-pairing"); return; }696      }697698      // Bindings-driven dispatch. Single-key letter bindings without699      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is700      // inside an input, so users can type into search/forms normally.701      const bindings = shortcutBindings();702      for (const action of Object.keys(bindings) as ShortcutAction[]) {703        const binding = bindings[action];704        if (!matchKeybinding(e, binding)) continue;705        // Single-key letter bindings need the input-focus guard. Bindings706        // with any modifier are safe — Ctrl+L doesn't conflict with typing.707        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;708        if (!hasMod && binding.key.length === 1 && inInput) return;709        if (ENTRY_SCOPED.has(action) && v !== "entry") return;710        e.preventDefault();711        SHORTCUT_HANDLERS[action]?.();712        return;713      }714715      // Type-to-search: in entry view, any printable key not consumed by a716      // shortcut above primes the list search seed and opens the list.717      // Kept outside the bindings table because it's a behavior, not a718      // discrete action — every printable character can trigger it.719      if (v === "entry" && !inInput && isPrintableSearchKey) {720        e.preventDefault();721        primeListSearch(e.key);722        return;723      }724    };725    window.addEventListener("keydown", handleGlobalKeydown);726    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));727728    const handleStorageChanged = (729      changes: Record<string, chrome.storage.StorageChange>,730      areaName: string731    ) => {732      if (areaName !== "session") return;733      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {734        return;735      }736      void refreshPendingPasskey();737    };738    chrome.storage.onChanged.addListener(handleStorageChanged);739    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));740  });741742  async function refreshCurrentTab() {743    try {744      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });745      const url = tab?.url ?? tab?.pendingUrl ?? "";746      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");747      // Skip extension/internal URLs — adding chrome://, about:, or748      // chrome-extension:// to a vault entry is never what the user wants.749      const isWebUrl = /^https?:\/\//i.test(url);750      setCurrentTabUrl(isWebUrl ? url : "");751    } catch {752      setCurrentTabDomain("");753      setCurrentTabUrl("");754    }755  }756757  async function refreshPendingPasskey() {758    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });759    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);760  }761762  async function refreshIncomingPairing() {763    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });764    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;765    setIncomingPair(data);766  }767768  // Drains a single one-shot record left by the background when 6-digit769  // pairing succeeded while the popup was closed (or the SyncPairing view was770  // navigated away from before it could show its own success card).771  async function consumeRecentPairing() {772    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });773    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;774    if (data?.deviceName) {775      setRecentPairToast(data.deviceName);776      window.setTimeout(() => setRecentPairToast(null), 4000);777    }778  }779780  async function respondIncomingPairing(accept: boolean) {781    if (incomingPairResponding()) return;782    setIncomingPairResponding(true);783    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });784    setIncomingPair(null);785    setIncomingPairResponding(false);786  }787788  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a789  // request appears, ticks once per second, and clears the banner if the790  // request expires while the popup is open.791  createEffect(() => {792    const req = incomingPair();793    if (!req) return;794    const handle = window.setInterval(() => {795      setIncomingPairTick((tick) => tick + 1);796      if (Date.now() >= req.expiresAt) {797        setIncomingPair(null);798        window.clearInterval(handle);799      }800    }, 1000);801    onCleanup(() => window.clearInterval(handle));802  });803804  async function refreshProStatus() {805    const res = await sendMessage({ type: "GET_LICENSE" });806    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;807    setProStatus(Boolean(data?.valid && data?.plan === "pro"));808  }809810  async function restoreSettings() {811    const res = await sendMessage({ type: "GET_SETTINGS" });812    const s = (res as { ok: boolean; data?: any }).data ?? {};813    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {814      setAccentColor(s.accentColor as AccentColorName);815    }816    setTheme(s.theme === "light" ? "light" : "dark");817    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {818      setDisplayFont(s.displayFont);819    } else {820      setDisplayFont("cormorant-italic");821    }822    if (s.textSize === "small" || s.textSize === "large") {823      setTextSize(s.textSize);824    } else {825      setTextSize("medium");826    }827    setReduceMotion(s.reduceMotion === true);828    setLockOnClose(s.lockOnClose !== false);829    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);830    setBreachMonitoring(s.breachMonitoring !== false);831    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);832    setShortcutBindings(getActiveBindings(s.shortcuts));833  }834835  async function applyTrashRetention(days: number) {836    setTrashRetentionDays(days);837    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });838  }839840  function primeListSearch(seed: string) {841    setListSearchSeed(seed);842    setListSearchSeedNonce((value) => value + 1);843    openList();844  }845846  // Returns null when it detected a dead service worker and triggered handleLock().847  // Callers that need to abort (e.g. openVault) check for null rather than relying848  // on view() state, which may already be "lock" during normal startup flows.849  async function loadEntries(): Promise<VaultEntry[] | null> {850    const response = await sendMessage({ type: "GET_ENTRIES" });851    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };852853    // If the service worker was killed and restarted (MV3 workers sleep), the854    // vault will be locked again — or the worker may not respond at all.855    // In either case, send the user to the lock screen rather than silently856    // showing an empty vault (which looks like data loss).857    if (!res.ok) {858      if (859        res.error === "vault locked" ||860        res.error === "SERVICE_WORKER_UNAVAILABLE" ||861        (typeof res.error === "string" && res.error.includes("locked"))862      ) {863        handleLock();864        return null; // signal emergency lock to callers865      }866      return [];867    }868869    const loadedEntries = res.data ?? [];870    setEntries(loadedEntries);871872    const currentId = selectedEntry()?.id;873    if (currentId) {874      setSelectedEntry(875        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null876      );877    }878879    return loadedEntries;880  }881882  async function openVault(preferredEntryId?: string, skipViewSet = false) {883    // Purge expired trash entries on each vault open884    const retDays = trashRetentionDays();885    if (retDays > 0) {886      void sendMessage({887        type: "PURGE_EXPIRED_TRASH",888        payload: { retentionMs: retDays * 86_400_000 },889      });890    }891892    const loadedEntries = await loadEntries();893894    // null means loadEntries() triggered an emergency lock (service worker died).895    // Don't override it by setting view back to "entry" with an empty vault.896    if (loadedEntries === null) return;897898    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry899    let nextSelectedEntry: VaultEntry | null = null;900    if (preferredEntryId) {901      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;902    }903    if (!nextSelectedEntry) {904      const tabDomain = currentTabDomain();905      if (tabDomain) {906        nextSelectedEntry = loadedEntries.find((e) => {907          if (e.type === "login") {908            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;909            for (const extra of e.additionalUrls ?? []) {910              if ((extractDomain(extra) ?? "") === tabDomain) return true;911            }912            return false;913          }914          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;915          return false;916        }) ?? null;917      }918    }919    nextSelectedEntry ??= loadedEntries[0] ?? null;920921    setSelectedEntry(nextSelectedEntry);922    setEditEntry(undefined);923    setContentTransitioning(false);924    setContentPhase("enter");925    queueContentIdle();926    if (!skipViewSet) setView("entry");927  }928929  async function handleUnlock() {930    // If the user previously created a vault but hadn't yet confirmed their931    // recovery words (and the browser was closed before they could), the932    // peach_recovery_pending flag is still set in storage.local. Re-route933    // back to the recovery surface so they finish the confirmation step934    // before reaching the entries view — the words can be re-derived now935    // that the vault is unlocked again.936    let recoveryPending = false;937    try {938      const out = await chrome.storage.local?.get("peach_recovery_pending");939      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";940    } catch { /* best-effort */ }941    if (recoveryPending) {942      setForceRecoveryWords(true);943      setView("lock");944      triggerPipPulse();945      await restoreSettings();946      return;947    }948    setHasVault(true);949    triggerPipPulse();950    await restoreSettings();951    const celebrating = pendingCelebration();952    if (celebrating) {953      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });954      setPendingCelebration(false);955    }956    await openVault(undefined, celebrating);957    if (celebrating) {958      setView("pro-celebration");959      window.setTimeout(() => setView("entry"), 2500);960    }961  }962963  function handleSelectEntry(entry: VaultEntry) {964    setSelectedEntry(entry);965    setContentTransitioning(false);966    setContentPhase("enter");967    queueContentIdle();968    setView("entry");969  }970971  function handleAdd() {972    setEditEntry(undefined);973    setView("add");974  }975976  async function handleDelete() {977    const entry = selectedEntry();978    if (!entry) return;979    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });980    const loadedEntries = await loadEntries() ?? [];981    setSelectedEntry(loadedEntries[0] ?? null);982    setView("entry");983  }984985  async function handleDeleteMany(ids: string[]) {986    for (const id of ids) {987      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });988    }989    const loadedEntries = await loadEntries() ?? [];990    // If the currently selected entry was among the deleted, move to first991    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);992    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);993  }994995  async function handleSave(savedEntry?: VaultEntry) {996    await openVault(savedEntry?.id);997  }998999  function handleBack() {1000    setEditEntry(undefined);1001    setView("entry");1002  }10031004  function handleLock() {1005    clearCanarySuppressions();1006    setEntries([]);1007    setSelectedEntry(null);1008    setEditEntry(undefined);1009    setContentPhase("idle");1010    setView("lock");1011  }10121013  function handleHeaderLock() {1014    // Lock the UI immediately — do not wait for the service worker. If the SW1015    // is dead or slow, the 5s sendMessage timeout would create a dead-click1016    // window. The SW will lock on its next wake regardless.1017    handleLock();1018    void sendMessage({ type: "LOCK" });1019  }10201021  function navigate(dir: number) {1022    const allEntries = entries();1023    if (allEntries.length === 0) return;1024    const currentIndex = selectedIndex();1025    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1026    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1027    setSelectedEntry(allEntries[nextIndex]);1028    setContentPhase("enter");1029    queueContentIdle();1030  }10311032  function openList() {1033    setView("list");1034  }10351036  function openHealth() {1037    setEditEntry(undefined);1038    setView("health");1039  }10401041  function handleOpenFileImport() {1042    setRestoreView("file");1043  }10441045  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10461047  function handleFixEntry(entry: VaultEntry) {1048    // Passkey-only entries have no editable surface — drop into view mode1049    // instead of opening the Add editor.1050    if (isPasskeyOnly(entry)) {1051      setSelectedEntry(entry);1052      setView("entry");1053      return;1054    }1055    setEditEntry(entry);1056    setView("add");1057  }10581059  const isLockedView = () => view() === "lock";10601061  async function handleApprovePendingPasskey() {1062    const pending = pendingPasskey();1063    if (!pending) return;1064    if (pending.browser === "firefox" && pending.type === "create") {1065      // Firefox path: popup itself runs navigator.credentials.create. The1066      // background never approved/rejected anything — it just stashed1067      // intent. After the popup-driven flow resolves (success or cancel),1068      // clear the pending key so the popup doesn't re-show this on next open.1069      const { createFirefoxPasskey } = await import("./firefox-passkey");1070      const result = await createFirefoxPasskey(pending);1071      if (!result.ok) {1072        console.warn("Peach Firefox passkey create failed:", result.error);1073      }1074      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1075      setPendingPasskey(null);1076      void loadEntries();1077      return;1078    }1079    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1080    setPendingPasskey(null);1081  }10821083  async function handleDenyPendingPasskey() {1084    const pending = pendingPasskey();1085    if (!pending) return;1086    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1087    setPendingPasskey(null);1088  }10891090  function queueContentIdle(after?: () => void) {1091    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1092    contentPhaseTimer = window.setTimeout(() => {1093      setContentPhase("idle");1094      after?.();1095    }, ENTRY_TRANSITION_SETTLE_MS);1096  }10971098  return (1099    <div class="popup-root peach-theme">1100      <Show when={bootState() === "ready"}>1101        <Show1102          when={!pendingPasskey()}1103          fallback={1104            <PasskeyApprovalView1105              type={pendingPasskey()!.type}1106              rpName={pendingPasskey()!.rpName}1107              rpId={pendingPasskey()!.rpId}1108              userName={pendingPasskey()!.userName}1109              userDisplayName={pendingPasskey()!.userDisplayName}1110              onApprove={handleApprovePendingPasskey}1111              onDeny={handleDenyPendingPasskey}1112            />1113          }1114        >1115          <Show1116            when={!isLockedView()}1117            fallback={1118              <Show1119                when={onboarded() || hasVault()}1120                fallback={1121                  <Onboarding1122                    onComplete={() => { setOnboarded(true); }}1123                  />1124                }1125              >1126                <LockView1127                  hasVault={hasVault()}1128                  ready={bootState() === "ready"}1129                  isPro={proStatus()}1130                  forceRecoveryWords={forceRecoveryWords()}1131                  onUnlock={() => {1132                    // RecoveryWordDisplay clears the storage flag before1133                    // calling onDone, so handleUnlock will see no pending1134                    // confirmation and proceed through the normal path.1135                    if (forceRecoveryWords()) setForceRecoveryWords(false);1136                    return handleUnlock();1137                  }}1138                  onBackToOnboarding={1139                    !hasVault()1140                      ? () => setOnboarded(false)1141                      : undefined1142                  }1143                />1144              </Show>1145            }1146          >1147            <Show1148              when={view() !== "pro-celebration"}1149              fallback={<ProCelebration />}1150            >1151            <section1152              id="hd-shell"1153              class="peach-shell peach-theme"1154              data-surface="extension"1155            >1156            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1157              <PeachWordmark unlocked />1158              <div class="peach-chrome-actions">1159                <button1160                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1161                  onClick={() => setView("settings")}1162                  aria-label="Settings"1163                >1164                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1165                    <path1166                      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"1167                      stroke="currentColor"1168                      stroke-width="0.9"1169                    />1170                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1171                  </svg>1172                </button>1173                <button1174                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1175                  onClick={handleAdd}1176                  aria-label="New entry"1177                >1178                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1179                    <path d="M5.5 1v9M1 5.5h9" />1180                  </svg>1181                </button>1182                <button1183                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1184                  onClick={() => void handleHeaderLock()}1185                  aria-label="Lock vault"1186                >1187                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1188                    <path1189                      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"1190                      stroke="currentColor"1191                      stroke-width="1"1192                      stroke-linecap="round"1193                    />1194                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1195                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1196                  </svg>1197                </button>1198              </div>1199            </header>12001201            <Show when={recentPairToast()}>1202              <div class="peach-pair-toast" role="status" aria-live="polite">1203                Paired with <strong>{recentPairToast()}</strong>1204              </div>1205            </Show>12061207            <Show when={incomingPair() !== null}>1208              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1209                <div class="peach-pair-request-header">1210                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1211                  <span class="peach-pair-request-title">Pairing request</span>1212                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1213                </div>1214                <p class="peach-pair-request-body">1215                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1216                </p>1217                <div class="peach-pair-request-actions">1218                  <button1219                    class="peach-btn peach-btn--ghost peach-btn--sm"1220                    onClick={() => void respondIncomingPairing(false)}1221                    disabled={incomingPairResponding()}1222                  >1223                    Reject1224                  </button>1225                  <button1226                    class="peach-btn peach-btn--accent peach-btn--sm"1227                    onClick={() => void respondIncomingPairing(true)}1228                    disabled={incomingPairResponding()}1229                  >1230                    Accept1231                  </button>1232                </div>1233              </div>1234            </Show>12351236            <Show when={pendingProNotice() !== null}>1237              <div class="peach-pro-notice-banner">1238                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1239                <button1240                  class="peach-pro-notice-link"1241                  onClick={() => {1242                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1243                    setSettingsInitialSection("license");1244                    setView("settings");1245                    setPendingProNotice(null);1246                  }}1247                >1248                  Learn more →1249                </button>1250                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1251              </div>1252            </Show>12531254            <div class="peach-shell-body">1255              <div class="peach-shell-veil"></div>1256              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1257                <EntryView1258                  entry={selectedEntry()}1259                  currentTabUrl={currentTabUrl()}1260                  onDelete={handleDelete}1261                  onFieldSaved={() => void loadEntries()}1262                  onEscape={() => { setView("list"); }}1263                />1264              </div>12651266              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1267                <div class="peach-search-bar">1268                  <span class="peach-search-icon">1269                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1270                      <circle cx="5.5" cy="5.5" r="3.75" />1271                      <path d="M8.75 8.75L11.5 11.5" />1272                    </svg>1273                  </span>1274                  <input1275                    class="peach-search-input"1276                    placeholder="search vault..."1277                    autocomplete="off"1278                    aria-label="Search vault entries"1279                    onClick={openList}1280                    onFocus={openList}1281                    readOnly1282                  />1283                  <div class="peach-search-meta">1284                    <span class="peach-search-counter">1285                      {entries().length > 01286                        ? `${selectedIndex() + 1} / ${entries().length}`1287                        : "0 entries"}1288                    </span>1289                    <span class="peach-divider"></span>1290                    <button1291                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1292                      onClick={() => navigate(-1)}1293                      aria-label="Previous entry"1294                      disabled={entries().length === 0}1295                    >1296                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1297                        <path d="M5 1L1 5.5L5 10" />1298                      </svg>1299                    </button>1300                    <button1301                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1302                      onClick={() => navigate(1)}1303                      aria-label="Next entry"1304                      disabled={entries().length === 0}1305                    >1306                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1307                        <path d="M1 1L5 5.5L1 10" />1308                      </svg>1309                    </button>1310                  </div>1311                </div>1312              </section>1313            </div>13141315            {/* Desktop: shown on demand via Show. Native sheet is rendered1316                via Portal below at the document root so its position:fixed1317                isn't trapped by .peach-shell's transform-based animations. */}1318            <Show when={!isNativePlatform() && view() === "list"}>1319              <VaultView1320                entries={entries()}1321                selectedEntryId={selectedEntry()?.id}1322                currentTabDomain={currentTabDomain()}1323                sortOrder={sortOrder()}1324                searchSeed={listSearchSeed()}1325                searchSeedNonce={listSearchSeedNonce()}1326                onSelectEntry={handleSelectEntry}1327                onSortOrderChange={setSortOrder}1328                onAdd={handleAdd}1329                onClose={() => setView("entry")}1330                onOpenTrash={() => setView("trash")}1331                onDeleteMany={handleDeleteMany}1332              />1333            </Show>1334            <Show when={isNativePlatform() && hasVault()}>1335              <Portal>1336                <div1337                  class="peach-vault-sheet"1338                  classList={{ "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1339                  style={(() => {1340                    const live = sheetTranslate();1341                    if (live === null) return undefined;1342                    return { transform: `translateY(${live}px)` };1343                  })()}1344                >1345                  <VaultView1346                    entries={entries()}1347                    selectedEntryId={selectedEntry()?.id}1348                    currentTabDomain={currentTabDomain()}1349                    sortOrder={sortOrder()}1350                    searchSeed={listSearchSeed()}1351                    searchSeedNonce={listSearchSeedNonce()}1352                    onSelectEntry={handleSelectEntry}1353                    onSortOrderChange={setSortOrder}1354                    onAdd={handleAdd}1355                    onClose={() => setView("entry")}1356                    onOpenTrash={() => setView("trash")}1357                    onDeleteMany={handleDeleteMany}1358                  />1359                </div>1360              </Portal>1361            </Show>1362            <Show when={view() === "settings"}>1363              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1364                <SettingsView1365                  entriesCount={entries().length}1366                  breachMonitoring={breachMonitoring()}1367                  lockOnClose={lockOnClose()}1368                  autoLockMinutes={autoLockMinutes()}1369                  trashRetentionDays={trashRetentionDays()}1370                  theme={theme()}1371                  accentColor={accentColor()}1372                  displayFont={displayFont()}1373                  textSize={textSize()}1374                  reduceMotion={reduceMotion()}1375                  isPro={proStatus()}1376                  initialSection={settingsInitialSection()}1377                  upgradeHighlight={upgradeHighlight()}1378                  onBreachMonitoringChange={applyBreachMonitoring}1379                  onLockOnCloseChange={applyLockOnClose}1380                  onAutoLockMinutesChange={applyAutoLockMinutes}1381                  onTrashRetentionChange={applyTrashRetention}1382                  onThemeChange={applyTheme}1383                  onAccentChange={applyAccentColor}1384                  onDisplayFontChange={applyDisplayFont}1385                  onTextSizeChange={applyTextSize}1386                  onReduceMotionChange={applyReduceMotion}1387                  shortcuts={shortcutBindings()}1388                  onShortcutsChange={applyShortcuts}1389                  onLicenseChange={async () => {1390                    // After activation/deactivation: refresh Pro status,1391                    // re-load entries (defensive — signal state can drift if1392                    // the SW briefly restarts during the verify+save round-trip),1393                    // and replay the Pro celebration if this is the first time1394                    // a valid Pro license is seen on this device.1395                    await refreshProStatus();1396                    void loadEntries();1397                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1398                    if ((should as { ok: boolean; data?: boolean }).data === true) {1399                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1400                      setView("pro-celebration");1401                      window.setTimeout(() => setView("settings"), 2500);1402                    }1403                  }}1404                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1405                  onImport={() => setView("import")}1406                  onExport={() => setView("export")}1407                  onBreachCheckDone={loadEntries}1408                  onOpenHealth={openHealth}1409                  onOpenSyncPairing={() => setView("sync-pairing")}1410                  onOpenFileImport={handleOpenFileImport}1411                  onOpenPanic={() => setView("panic")}1412                />1413              </Suspense>1414            </Show>1415            <Show when={view() === "sync-pairing"}>1416              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1417                <SyncPairingView1418                  isPro={proStatus()}1419                  onAddDevice={() => setView("sync-add-device")}1420                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1421                  onBack={() => setView("settings")}1422                />1423              </Suspense>1424            </Show>1425            <Show when={view() === "sync-add-device"}>1426              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1427                <AddDeviceView1428                  onClose={() => setView("sync-pairing")}1429                  onPaired={() => setView("sync-pairing")}1430                />1431              </Suspense>1432            </Show>1433            <Show when={view() === "add"}>1434              <AddView1435                entry={editEntry()}1436                entries={entries()}1437                onBack={handleBack}1438                onSave={handleSave}1439              />1440            </Show>1441            <Show when={view() === "import"}>1442              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1443                <ImportView onBack={handleBack} onImport={handleSave} />1444              </Suspense>1445            </Show>1446            <Show when={view() === "export"}>1447              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1448                <ExportView1449                  onBack={() => {1450                    if (returnToPanic()) {1451                      setReturnToPanic(false);1452                      setView("panic");1453                    } else {1454                      handleBack();1455                    }1456                  }}1457                />1458              </Suspense>1459            </Show>1460            <Show when={view() === "panic"}>1461              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1462                <PanicView1463                  onCancel={() => setView("settings")}1464                  onOpenExport={() => {1465                    setReturnToPanic(true);1466                    setView("export");1467                  }}1468                  onDestroyed={async () => {1469                    clearCanarySuppressions();1470                    setEntries([]);1471                    setSelectedEntry(null);1472                    setEditEntry(undefined);1473                    setHasVault(false);1474                    setOnboarded(false);1475                    setProStatus(false);1476                    setPendingPasskey(null);1477                    setUpgradeHighlight(null);1478                    setSettingsInitialSection(null);1479                    setPendingProNotice(null);1480                    setPendingCelebration(false);1481                    setReturnToPanic(false);1482                    setContentPhase("idle");1483                    setView("lock");1484                  }}1485                />1486              </Suspense>1487            </Show>1488            <Show when={view() === "health"}>1489              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1490                <HealthView1491                  entries={entries()}1492                  isPro={proStatus()}1493                  onFixEntry={handleFixEntry}1494                  onBack={() => setView("settings")}1495                  onRefresh={loadEntries}1496                />1497              </Suspense>1498            </Show>1499            <Show when={view() === "trash"}>1500              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1501                <TrashView1502                  onBack={() => setView("list")}1503                  onRestored={() => void loadEntries()}1504                />1505              </Suspense>1506            </Show>1507            <Show when={restoreView() === "file"}>1508              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1509                <ImportView1510                  mode="onboarding"1511                  replacesExistingVault={true}1512                  onBack={() => setRestoreView(null)}1513                  onImport={async () => {1514                    setRestoreView(null);1515                    await handleUnlock();1516                  }}1517                />1518              </Suspense>1519            </Show>1520            </section>1521            </Show>1522          </Show>1523        </Show>1524      </Show>1525      <Show when={showShortcutsHelp()}>1526        <ShortcutsHelpOverlay1527          bindings={shortcutBindings()}1528          onClose={() => setShowShortcutsHelp(false)}1529        />1530      </Show>1531    </div>1532  );1533}15341535function ShortcutsHelpOverlay(props: {1536  bindings: Record<ShortcutAction, Keybinding>;1537  onClose: () => void;1538}) {1539  return (1540    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1541      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1542        <div class="peach-shortcuts-help-head">1543          <h3>Keyboard shortcuts</h3>1544          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1545        </div>1546        <div class="peach-shortcuts-help-body">1547          <p class="peach-settings-sub-label">ENTRY VIEW</p>1548          <ul>1549            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1550              <li>1551                <span>{d.label}</span>1552                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1553              </li>1554            ))}1555          </ul>1556          <p class="peach-settings-sub-label">ANYWHERE</p>1557          <ul>1558            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1559              <li>1560                <span>{d.label}</span>1561                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1562              </li>1563            ))}1564          </ul>1565        </div>1566      </div>1567    </div>1568  );1569}