App.tsx

42.8 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { ACCENT_COLORS } from "../shared/types";3import type { AccentColorName, PasskeyEntry, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";4import { LockView } from "./views/Lock";5import { ProCelebration } from "./views/ProCelebration";6import { VaultView, type SortOrder } from "./views/Vault";7import { EntryView } from "./views/Entry";8import { AddView } from "./views/Add";9import { PeachWordmark } from "./components/PeachMark";10import { PasskeyApprovalView } from "./views/PasskeyApproval";11import { PasskeyEntryView } from "./views/PasskeyEntry";12import { extractDomain } from "../shared/domain";13import { popupCopy } from "./copy";14import {15  DEFAULT_BINDINGS,16  formatKeybinding,17  getActiveBindings,18  matchKeybinding,19  SHORTCUT_DESCRIPTORS,20  type Keybinding,21  type ShortcutAction,22} from "../shared/shortcuts";23import { generateTOTP } from "../crypto/totp";2425const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));26const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));27const CJKExport     = lazy(() => import("./views/CJKExport").then(m => ({ default: m.CJKExportView })));28const CJKImport     = lazy(() => import("./views/CJKImport").then(m => ({ default: m.CJKImportView })));29const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));30const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));31const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));3233type View =34  | "lock"35  | "pro-celebration"36  | "entry"37  | "list"38  | "add"39  | "settings"40  | "import"41  | "export"42  | "health"43  | "trash";44type BootState = "loading" | "ready";4546const canarySuppressMap = new Map<string, boolean>();47let shellRingAnimation: Animation | null = null;4849export function isCanarySuppressed(entryId: string): boolean {50  return canarySuppressMap.get(entryId) ?? false;51}5253export function setCanarySuppressed(entryId: string, suppressed: boolean): void {54  canarySuppressMap.set(entryId, suppressed);55}5657export function clearCanarySuppressions(): void {58  canarySuppressMap.clear();59}6061export function triggerRing() {62  const shell = document.getElementById("hd-shell");63  if (!shell) return;6465  shellRingAnimation?.cancel();66  shell.dataset.glowing = "true";67  const animation = shell.animate(68    [69      { offset: 0, boxShadow: "var(--copy-shadow)" },70      {71        offset: 0.3,72        boxShadow:73          "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)",74      },75      { offset: 1, boxShadow: "var(--copy-shadow)" },76    ],77    {78      duration: 720,79      easing: "cubic-bezier(0.4, 0, 0.2, 1)",80      fill: "none",81    }82  );83  shellRingAnimation = animation;84  const clearGlow = () => {85    if (shellRingAnimation !== animation) return;86    shellRingAnimation = null;87    delete shell.dataset.glowing;88  };89  animation.onfinish = clearGlow;90  animation.oncancel = clearGlow;91}929394export function triggerPipPulse() {95  const pip = document.querySelector(".peach-status-pip, .pip");96  if (pip) {97    pip.classList.remove("pulse");98    void (pip as HTMLElement).offsetWidth;99    pip.classList.add("pulse");100  }101}102103function humanizeError(error: string | undefined): string | undefined {104  if (!error) return error;105  if (error === "STORAGE_QUOTA_EXCEEDED") {106    return "Peach has run out of browser storage. Delete some entries or clear browser storage to continue.";107  }108  return error;109}110111async function sendMessage(msg: any): Promise<any> {112  const MESSAGE_TIMEOUT_MS = 5000;113114  return new Promise((resolve) => {115    let settled = false;116    const timeoutId = window.setTimeout(() => {117      if (settled) return;118      settled = true;119      resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });120    }, MESSAGE_TIMEOUT_MS);121122    try {123      chrome.runtime.sendMessage(msg, (response) => {124        if (settled) return;125        settled = true;126        window.clearTimeout(timeoutId);127128        if (chrome.runtime.lastError) {129          resolve({130            ok: false,131            error:132              chrome.runtime.lastError.message ?? "SERVICE_WORKER_UNAVAILABLE",133          });134          return;135        }136137        if (response === undefined) {138          resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });139          return;140        }141142        if (response && response.ok === false) {143          response.error = humanizeError(response.error);144        }145        resolve(response);146      });147    } catch (error) {148      if (settled) return;149      settled = true;150      window.clearTimeout(timeoutId);151      resolve({152        ok: false,153        error:154          error instanceof Error ? error.message : "SERVICE_WORKER_UNAVAILABLE",155      });156    }157  });158}159160export { sendMessage };161162const ENTRY_TRANSITION_EXIT_MS = 95;163const ENTRY_TRANSITION_SETTLE_MS = 135;164165export default function App() {166  const [bootState, setBootState] = createSignal<BootState>("loading");167  const [view, setView] = createSignal<View>("lock");168  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(169    "enter"170  );171  const [contentTransitioning, setContentTransitioning] = createSignal(false);172  const [hasVault, setHasVault] = createSignal(false);173  const [entries, setEntries] = createSignal<VaultEntry[]>([]);174  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);175  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);176  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");177  const [theme, setTheme] = createSignal<"dark" | "light">("dark");178  const [lockOnClose, setLockOnClose] = createSignal(true);179  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);180  const [breachMonitoring, setBreachMonitoring] = createSignal(true);181  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);182  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);183  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);184  const [restoreView, setRestoreView] = createSignal<"cjk" | "file" | null>(null);185  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);186  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");187  // Cached Pro status — synchronous for render paths. Background's188  // GET_LICENSE is async, but render-time reads of isPro() must not block.189  // Refreshed at boot, after activate/deactivate, and whenever the popup190  // re-opens onto a stored license that has changed via another window.191  const [proStatus, setProStatus] = createSignal(false);192  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);193  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);194  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");195  const [listSearchSeed, setListSearchSeed] = createSignal("");196  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);197  const [pendingCelebration, setPendingCelebration] = createSignal(false);198  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);199200  let contentPhaseTimer: number | undefined;201202  function applyAccent(name: AccentColorName) {203    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;204    const hex = color.hex;205    document.documentElement.style.setProperty("--peach-accent", hex);206    // Ambient surface variables — derived from the accent so surfaces shift207    // subtly toward the accent hue rather than staying fixed warm-brown.208    document.documentElement.style.setProperty("--peach-glow", hex + "2A");209    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");210    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");211  }212213  createEffect(() => {214    applyAccent(accentColor());215  });216217  createEffect(() => {218    document.documentElement.classList.toggle("light", theme() === "light");219    document.body.classList.toggle("light", theme() === "light");220  });221222  const selectedIndex = createMemo(() => {223    const currentId = selectedEntry()?.id;224    if (!currentId) return entries().length > 0 ? 0 : -1;225    return entries().findIndex((entry) => entry.id === currentId);226  });227228  async function applyAccentColor(name: AccentColorName) {229    applyAccent(name);230    setAccentColor(name);231    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });232  }233234  async function applyTheme(t: "dark" | "light") {235    setTheme(t);236    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });237  }238239  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload240  // small and lets future default updates land for actions the user hasn't241  // touched. Settings sends us the full active map; we filter and store.242  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {243    setShortcutBindings(active);244    const overrides: Record<string, Keybinding> = {};245    for (const action of Object.keys(active) as ShortcutAction[]) {246      const a = active[action];247      const d = DEFAULT_BINDINGS[action];248      const same = a.key === d.key249        && Boolean(a.ctrl)  === Boolean(d.ctrl)250        && Boolean(a.meta)  === Boolean(d.meta)251        && Boolean(a.shift) === Boolean(d.shift)252        && Boolean(a.alt)   === Boolean(d.alt);253      if (!same) overrides[action] = a;254    }255    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });256  }257258  async function applyLockOnClose(enabled: boolean) {259    setLockOnClose(enabled);260    await sendMessage({261      type: "UPDATE_SETTINGS",262      payload: { lockOnClose: enabled },263    });264  }265266  async function applyAutoLockMinutes(minutes: number) {267    setAutoLockMinutes(minutes);268    await sendMessage({269      type: "UPDATE_SETTINGS",270      payload: { autoLockMinutes: minutes },271    });272  }273274  async function applyBreachMonitoring(enabled: boolean) {275    setBreachMonitoring(enabled);276    await sendMessage({277      type: "UPDATE_SETTINGS",278      payload: { breachMonitoring: enabled },279    });280  }281282  onMount(async () => {283    // Resolve the active tab in parallel with the unlock/has-vault queries —284    // openVault()'s smart selection picks the entry matching currentTabDomain,285    // so it must be populated before openVault runs. Previously refreshCurrentTab286    // ran after openVault, leaving popups that booted already-unlocked falling287    // back to loadedEntries[0] instead of the domain match.288    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([289      sendMessage({ type: "IS_UNLOCKED" }),290      sendMessage({ type: "HAS_VAULT" }),291      refreshCurrentTab(),292      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),293    ]);294    const unlocked = Boolean(295      (unlockResponse as { ok: boolean; data?: boolean }).data296    );297    const vaultExists = Boolean(298      (vaultResponse as { ok: boolean; data?: boolean }).data299    );300    const shouldCelebrate = Boolean(301      (celebrationResponse as { ok: boolean; data?: boolean }).data302    );303    setHasVault(vaultExists);304    await Promise.all([restoreSettings(), refreshProStatus()]);305306    // Mark played before any animation so a crash mid-sequence never replays it307    if (shouldCelebrate) {308      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });309    }310311    if (unlocked && vaultExists) {312      await openVault(undefined, shouldCelebrate);313      if (shouldCelebrate) {314        setView("pro-celebration");315        window.setTimeout(() => setView("entry"), 2500);316      }317    } else if (shouldCelebrate) {318      setPendingCelebration(true);319    }320321    await refreshPendingPasskey();322323    // Track tab changes so smart sort stays current324    const handleTabActivated = () => { void refreshCurrentTab(); };325    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {326      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();327    };328    try {329      chrome.tabs.onActivated.addListener(handleTabActivated);330      chrome.tabs.onUpdated.addListener(handleTabUpdated);331      onCleanup(() => {332        chrome.tabs.onActivated.removeListener(handleTabActivated);333        chrome.tabs.onUpdated.removeListener(handleTabUpdated);334      });335    } catch {336      // tabs permission may not be available in all contexts337    }338339    setBootState("ready");340    document.getElementById("pre-lock")?.setAttribute("hidden", "true");341342    // Check for pending session-storage notices from the background.343    if (chrome.storage.session) {344      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as345        Record<string, { feature?: string } | undefined>;346      if (session.pendingProGate?.feature) {347        await chrome.storage.session.remove("pendingProGate");348        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);349        setSettingsInitialSection("license");350        setView("settings");351      } else if (session.pendingProNotice?.feature) {352        await chrome.storage.session.remove("pendingProNotice");353        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });354      }355    }356357    // Warm the lazy-module cache so the Suspense fallback never shows for358    // locally-bundled extension views. Without this, the first navigation to359    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which360    // covers the shell and absorbs clicks on the header.361    void Promise.all([362      import("./views/Settings").catch(() => {}),363      import("./views/Import").catch(() => {}),364      import("./views/Export").catch(() => {}),365      import("./views/Health").catch(() => {}),366      import("./views/TrashView").catch(() => {}),367      import("./views/CJKExport").catch(() => {}),368      import("./views/CJKImport").catch(() => {}),369    ]);370371    // Lock-on-close via a persistent port. sendMessage in pagehide is372    // unreliable — the popup context tears down before the message lands.373    // The SW's onConnect listener locks when this port disconnects.374    let popupPort: chrome.runtime.Port | null = null;375    try {376      popupPort = chrome.runtime.connect({ name: "popup" });377    } catch { /* extension context invalidated — ignore */ }378    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });379380    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale381    // entries instead of waiting for the next GET_ENTRIES round-trip.382    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {383      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();384      if (msg?.type === "PRO_GATE_TRIGGERED") {385        // Background never navigates UI directly — it asks; the popup decides.386        // Land on Settings → License with the triggering feature highlighted.387        setUpgradeHighlight(msg.payload?.feature ?? null);388        setSettingsInitialSection("license");389        setView("settings");390      }391    };392    chrome.runtime.onMessage.addListener(handleRuntimeMessage);393    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));394395    // Action handlers — keyed by ShortcutAction. The dispatcher below tests396    // each binding against the event and runs the matching handler. New397    // shortcuts only need an entry here; the binding is data, not code.398    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {399      copy_password: () => {400        const entry = selectedEntry();401        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });402      },403      copy_username: () => {404        const entry = selectedEntry();405        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });406      },407      copy_totp: () => {408        const entry = selectedEntry();409        if (!entry?.totp) return;410        try {411          const { code } = generateTOTP(entry.totp);412          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });413        } catch { /* invalid TOTP secret — silent */ }414      },415      new_entry: () => handleAdd(),416      edit_entry: () => {417        const entry = selectedEntry();418        if (!entry || entry.type === "passkey") return;419        setEditEntry(entry);420        setView("add");421      },422      delete_entry: () => {423        if (selectedEntry()) void handleDelete();424      },425      lock_vault: () => { void handleHeaderLock(); },426      search: () => openList(),427      nav_prev: () => navigate(-1),428      nav_next: () => navigate(1),429      jump_vault: () => setView("entry"),430      jump_settings: () => setView("settings"),431      show_help: () => setShowShortcutsHelp(true),432    };433434    // Actions that are MEANINGFUL only on the entry-detail view. Outside435    // that scope the binding is dormant — pressing C while on Settings436    // does nothing rather than awkwardly copying from a now-stale entry.437    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([438      "copy_password", "copy_username", "copy_totp",439      "edit_entry", "delete_entry", "nav_prev", "nav_next",440    ]);441442    const handleGlobalKeydown = (e: KeyboardEvent) => {443      const v = view();444      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"445        || (e.target as HTMLElement)?.tagName === "TEXTAREA"446        || (e.target as HTMLElement)?.isContentEditable;447      const isPrintableSearchKey =448        e.key.length === 1 &&449        !e.ctrlKey &&450        !e.metaKey &&451        !e.altKey;452453      // No input during the pro celebration sequence454      if (v === "pro-celebration") return;455456      // Help dialog: Escape closes it; eat the keypress so it doesn't457      // also navigate away from the underlying view.458      if (showShortcutsHelp()) {459        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }460        return;461      }462463      // ── Escape — fixed binding (not user-customizable) ───────464      if (e.key === "Escape") {465        if (v === "list") { setView("entry"); return; }466        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }467      }468469      // Bindings-driven dispatch. Single-key letter bindings without470      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is471      // inside an input, so users can type into search/forms normally.472      const bindings = shortcutBindings();473      for (const action of Object.keys(bindings) as ShortcutAction[]) {474        const binding = bindings[action];475        if (!matchKeybinding(e, binding)) continue;476        // Single-key letter bindings need the input-focus guard. Bindings477        // with any modifier are safe — Ctrl+L doesn't conflict with typing.478        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;479        if (!hasMod && binding.key.length === 1 && inInput) return;480        if (ENTRY_SCOPED.has(action) && v !== "entry") return;481        e.preventDefault();482        SHORTCUT_HANDLERS[action]?.();483        return;484      }485486      // Type-to-search: in entry view, any printable key not consumed by a487      // shortcut above primes the list search seed and opens the list.488      // Kept outside the bindings table because it's a behavior, not a489      // discrete action — every printable character can trigger it.490      if (v === "entry" && !inInput && isPrintableSearchKey) {491        e.preventDefault();492        primeListSearch(e.key);493        return;494      }495    };496    window.addEventListener("keydown", handleGlobalKeydown);497    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));498499    const handleStorageChanged = (500      changes: Record<string, chrome.storage.StorageChange>,501      areaName: string502    ) => {503      if (areaName !== "session") return;504      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {505        return;506      }507      void refreshPendingPasskey();508    };509510    chrome.storage.onChanged.addListener(handleStorageChanged);511    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));512  });513514  async function refreshCurrentTab() {515    try {516      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });517      const url = tab?.url ?? tab?.pendingUrl ?? "";518      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");519    } catch {520      setCurrentTabDomain("");521    }522  }523524  async function refreshPendingPasskey() {525    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });526    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);527  }528529  async function refreshProStatus() {530    const res = await sendMessage({ type: "GET_LICENSE" });531    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;532    setProStatus(Boolean(data?.valid && data?.plan === "pro"));533  }534535  async function restoreSettings() {536    const res = await sendMessage({ type: "GET_SETTINGS" });537    const s = (res as { ok: boolean; data?: any }).data ?? {};538    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {539      setAccentColor(s.accentColor as AccentColorName);540    }541    setTheme(s.theme === "light" ? "light" : "dark");542    setLockOnClose(s.lockOnClose !== false);543    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);544    setBreachMonitoring(s.breachMonitoring !== false);545    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);546    setShortcutBindings(getActiveBindings(s.shortcuts));547  }548549  async function applyTrashRetention(days: number) {550    setTrashRetentionDays(days);551    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });552  }553554  function primeListSearch(seed: string) {555    setListSearchSeed(seed);556    setListSearchSeedNonce((value) => value + 1);557    openList();558  }559560  // Returns null when it detected a dead service worker and triggered handleLock().561  // Callers that need to abort (e.g. openVault) check for null rather than relying562  // on view() state, which may already be "lock" during normal startup flows.563  async function loadEntries(): Promise<VaultEntry[] | null> {564    const response = await sendMessage({ type: "GET_ENTRIES" });565    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };566567    // If the service worker was killed and restarted (MV3 workers sleep), the568    // vault will be locked again — or the worker may not respond at all.569    // In either case, send the user to the lock screen rather than silently570    // showing an empty vault (which looks like data loss).571    if (!res.ok) {572      if (573        res.error === "vault locked" ||574        res.error === "SERVICE_WORKER_UNAVAILABLE" ||575        (typeof res.error === "string" && res.error.includes("locked"))576      ) {577        handleLock();578        return null; // signal emergency lock to callers579      }580      return [];581    }582583    const loadedEntries = res.data ?? [];584    setEntries(loadedEntries);585586    const currentId = selectedEntry()?.id;587    if (currentId) {588      setSelectedEntry(589        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null590      );591    }592593    return loadedEntries;594  }595596  async function openVault(preferredEntryId?: string, skipViewSet = false) {597    // Purge expired trash entries on each vault open598    const retDays = trashRetentionDays();599    if (retDays > 0) {600      void sendMessage({601        type: "PURGE_EXPIRED_TRASH",602        payload: { retentionMs: retDays * 86_400_000 },603      });604    }605606    const loadedEntries = await loadEntries();607608    // null means loadEntries() triggered an emergency lock (service worker died).609    // Don't override it by setting view back to "entry" with an empty vault.610    if (loadedEntries === null) return;611612    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry613    let nextSelectedEntry: VaultEntry | null = null;614    if (preferredEntryId) {615      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;616    }617    if (!nextSelectedEntry) {618      const tabDomain = currentTabDomain();619      if (tabDomain) {620        nextSelectedEntry = loadedEntries.find((e) => {621          if (e.type === "login") {622            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;623            for (const extra of e.additionalUrls ?? []) {624              if ((extractDomain(extra) ?? "") === tabDomain) return true;625            }626            return false;627          }628          if (e.type === "passkey" && e.rpId) return e.rpId === tabDomain;629          return false;630        }) ?? null;631      }632    }633    nextSelectedEntry ??= loadedEntries[0] ?? null;634635    setSelectedEntry(nextSelectedEntry);636    setEditEntry(undefined);637    setContentTransitioning(false);638    setContentPhase("enter");639    queueContentIdle();640    if (!skipViewSet) setView("entry");641  }642643  async function handleUnlock() {644    setHasVault(true);645    triggerPipPulse();646    await restoreSettings();647    const celebrating = pendingCelebration();648    if (celebrating) {649      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });650      setPendingCelebration(false);651    }652    await openVault(undefined, celebrating);653    if (celebrating) {654      setView("pro-celebration");655      window.setTimeout(() => setView("entry"), 2500);656    }657  }658659  function handleSelectEntry(entry: VaultEntry) {660    setSelectedEntry(entry);661    setContentTransitioning(false);662    setContentPhase("enter");663    queueContentIdle();664    setView("entry");665  }666667  function handleAdd() {668    setEditEntry(undefined);669    setView("add");670  }671672  async function handleDelete() {673    const entry = selectedEntry();674    if (!entry) return;675    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });676    const loadedEntries = await loadEntries() ?? [];677    setSelectedEntry(loadedEntries[0] ?? null);678    setView("entry");679  }680681  async function handleDeleteMany(ids: string[]) {682    for (const id of ids) {683      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });684    }685    const loadedEntries = await loadEntries() ?? [];686    // If the currently selected entry was among the deleted, move to first687    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);688    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);689  }690691  async function handleSave(savedEntry?: VaultEntry) {692    await openVault(savedEntry?.id);693  }694695  function handleBack() {696    setEditEntry(undefined);697    setView("entry");698  }699700  function handleLock() {701    clearCanarySuppressions();702    setEntries([]);703    setSelectedEntry(null);704    setEditEntry(undefined);705    setContentPhase("idle");706    setView("lock");707  }708709  function handleHeaderLock() {710    // Lock the UI immediately — do not wait for the service worker. If the SW711    // is dead or slow, the 5s sendMessage timeout would create a dead-click712    // window. The SW will lock on its next wake regardless.713    handleLock();714    void sendMessage({ type: "LOCK" });715  }716717  function navigate(dir: number) {718    const allEntries = entries();719    if (allEntries.length === 0) return;720    const currentIndex = selectedIndex();721    const baseIndex = currentIndex >= 0 ? currentIndex : 0;722    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;723    setSelectedEntry(allEntries[nextIndex]);724    setContentPhase("enter");725    queueContentIdle();726  }727728  function openList() {729    setView("list");730  }731732  function openHealth() {733    setEditEntry(undefined);734    setView("health");735  }736737  function handleOpenCJKImport() {738    setRestoreView("cjk");739  }740741  function handleOpenFileImport() {742    setRestoreView("file");743  }744745  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;746747  function handleFixEntry(entry: VaultEntry) {748    if (entry.type === "passkey") {749      setSelectedEntry(entry);750      setView("entry");751      return;752    }753    setEditEntry(entry);754    setView("add");755  }756757  const isLockedView = () => view() === "lock";758  const selectedPasskeyEntry = createMemo(() =>759    selectedEntry()?.type === "passkey" ? (selectedEntry() as PasskeyEntry) : null760  );761762  async function handleApprovePendingPasskey() {763    const pending = pendingPasskey();764    if (!pending) return;765    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });766    setPendingPasskey(null);767  }768769  async function handleDenyPendingPasskey() {770    const pending = pendingPasskey();771    if (!pending) return;772    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });773    setPendingPasskey(null);774  }775776  function queueContentIdle(after?: () => void) {777    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);778    contentPhaseTimer = window.setTimeout(() => {779      setContentPhase("idle");780      after?.();781    }, ENTRY_TRANSITION_SETTLE_MS);782  }783784  return (785    <div class="popup-root peach-theme">786      <Show when={bootState() === "ready"}>787        <Show788          when={!pendingPasskey()}789          fallback={790            <PasskeyApprovalView791              type={pendingPasskey()!.type}792              rpName={pendingPasskey()!.rpName}793              rpId={pendingPasskey()!.rpId}794              userName={pendingPasskey()!.userName}795              userDisplayName={pendingPasskey()!.userDisplayName}796              onApprove={handleApprovePendingPasskey}797              onDeny={handleDenyPendingPasskey}798            />799          }800        >801          <Show802            when={!isLockedView()}803            fallback={804              <LockView805                hasVault={hasVault()}806                ready={bootState() === "ready"}807                isPro={proStatus()}808                onUnlock={handleUnlock}809              />810            }811          >812            <Show813              when={view() !== "pro-celebration"}814              fallback={<ProCelebration />}815            >816            <section817              id="hd-shell"818              class="peach-shell peach-theme"819              data-surface="extension"820            >821            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>822              <PeachWordmark unlocked />823              <div class="peach-chrome-actions">824                <button825                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"826                  onClick={() => setView("settings")}827                  aria-label="Settings"828                >829                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">830                    <path831                      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"832                      stroke="currentColor"833                      stroke-width="0.9"834                    />835                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />836                  </svg>837                </button>838                <button839                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"840                  onClick={handleAdd}841                  aria-label="New entry"842                >843                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">844                    <path d="M5.5 1v9M1 5.5h9" />845                  </svg>846                </button>847                <button848                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"849                  onClick={() => void handleHeaderLock()}850                  aria-label="Lock vault"851                >852                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">853                    <path854                      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"855                      stroke="currentColor"856                      stroke-width="1"857                      stroke-linecap="round"858                    />859                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />860                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />861                  </svg>862                </button>863              </div>864            </header>865866            <Show when={pendingProNotice() !== null}>867              <div class="peach-pro-notice-banner">868                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>869                <button870                  class="peach-pro-notice-link"871                  onClick={() => {872                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);873                    setSettingsInitialSection("license");874                    setView("settings");875                    setPendingProNotice(null);876                  }}877                >878                  Learn more →879                </button>880                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>881              </div>882            </Show>883884            <div class="peach-shell-body">885              <div class="peach-shell-veil"></div>886              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>887                <Show888                  when={selectedPasskeyEntry()}889                  fallback={890                    <EntryView891                      entry={selectedEntry()}892                      onDelete={handleDelete}893                      onFieldSaved={() => void loadEntries()}894                      onEscape={() => { setView("list"); }}895                    />896                  }897                >898                  <PasskeyEntryView entry={selectedPasskeyEntry()} onDelete={handleDelete} />899                </Show>900              </div>901902              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>903                <div class="peach-search-bar">904                  <span class="peach-search-icon">905                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">906                      <circle cx="5.5" cy="5.5" r="3.75" />907                      <path d="M8.75 8.75L11.5 11.5" />908                    </svg>909                  </span>910                  <input911                    class="peach-search-input"912                    placeholder="search vault..."913                    autocomplete="off"914                    aria-label="Search vault entries"915                    onClick={openList}916                    onFocus={openList}917                    readOnly918                  />919                  <div class="peach-search-meta">920                    <span class="peach-search-counter">921                      {entries().length > 0922                        ? `${selectedIndex() + 1} / ${entries().length}`923                        : "0 entries"}924                    </span>925                    <span class="peach-divider"></span>926                    <button927                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"928                      onClick={() => navigate(-1)}929                      aria-label="Previous entry"930                      disabled={entries().length === 0}931                    >932                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">933                        <path d="M5 1L1 5.5L5 10" />934                      </svg>935                    </button>936                    <button937                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"938                      onClick={() => navigate(1)}939                      aria-label="Next entry"940                      disabled={entries().length === 0}941                    >942                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">943                        <path d="M1 1L5 5.5L1 10" />944                      </svg>945                    </button>946                  </div>947                </div>948              </section>949            </div>950951            <Show when={view() === "list"}>952              <VaultView953                entries={entries()}954                selectedEntryId={selectedEntry()?.id}955                currentTabDomain={currentTabDomain()}956                sortOrder={sortOrder()}957                searchSeed={listSearchSeed()}958                searchSeedNonce={listSearchSeedNonce()}959                onSelectEntry={handleSelectEntry}960                onSortOrderChange={setSortOrder}961                onAdd={handleAdd}962                onClose={() => setView("entry")}963                onOpenTrash={() => setView("trash")}964                onDeleteMany={handleDeleteMany}965              />966            </Show>967            <Show when={view() === "settings"}>968              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>969                <SettingsView970                  entriesCount={entries().length}971                  breachMonitoring={breachMonitoring()}972                  lockOnClose={lockOnClose()}973                  autoLockMinutes={autoLockMinutes()}974                  trashRetentionDays={trashRetentionDays()}975                  theme={theme()}976                  accentColor={accentColor()}977                  isPro={proStatus()}978                  initialSection={settingsInitialSection()}979                  upgradeHighlight={upgradeHighlight()}980                  onBreachMonitoringChange={applyBreachMonitoring}981                  onLockOnCloseChange={applyLockOnClose}982                  onAutoLockMinutesChange={applyAutoLockMinutes}983                  onTrashRetentionChange={applyTrashRetention}984                  onThemeChange={applyTheme}985                  onAccentChange={applyAccentColor}986                  shortcuts={shortcutBindings()}987                  onShortcutsChange={applyShortcuts}988                  onLicenseChange={refreshProStatus}989                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}990                  onImport={() => setView("import")}991                  onExport={() => setView("export")}992                  onBreachCheckDone={loadEntries}993                  onOpenHealth={openHealth}994                  onOpenCJKImport={handleOpenCJKImport}995                  onOpenFileImport={handleOpenFileImport}996                />997              </Suspense>998            </Show>999            <Show when={view() === "add"}>1000              <AddView1001                entry={editEntry()}1002                entries={entries()}1003                onBack={handleBack}1004                onSave={handleSave}1005              />1006            </Show>1007            <Show when={view() === "import"}>1008              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1009                <ImportView onBack={handleBack} onImport={handleSave} />1010              </Suspense>1011            </Show>1012            <Show when={view() === "export"}>1013              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1014                <ExportView onBack={handleBack} />1015              </Suspense>1016            </Show>1017            <Show when={view() === "health"}>1018              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1019                <HealthView1020                  entries={entries()}1021                  isPro={proStatus()}1022                  onFixEntry={handleFixEntry}1023                  onBack={() => setView("settings")}1024                  onRefresh={loadEntries}1025                />1026              </Suspense>1027            </Show>1028            <Show when={view() === "trash"}>1029              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1030                <TrashView1031                  onBack={() => setView("list")}1032                  onRestored={() => void loadEntries()}1033                />1034              </Suspense>1035            </Show>1036            <Show when={restoreView() === "cjk"}>1037              <CJKImport1038                mode="onboarding"1039                onBack={() => setRestoreView(null)}1040                onDone={async () => {1041                  setRestoreView(null);1042                  await handleUnlock();1043                }}1044              />1045            </Show>1046            <Show when={restoreView() === "file"}>1047              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1048                <ImportView1049                  mode="onboarding"1050                  replacesExistingVault={true}1051                  onBack={() => setRestoreView(null)}1052                  onImport={async () => {1053                    setRestoreView(null);1054                    await handleUnlock();1055                  }}1056                />1057              </Suspense>1058            </Show>1059            </section>1060            </Show>1061          </Show>1062        </Show>1063      </Show>1064      <Show when={showShortcutsHelp()}>1065        <ShortcutsHelpOverlay1066          bindings={shortcutBindings()}1067          onClose={() => setShowShortcutsHelp(false)}1068        />1069      </Show>1070    </div>1071  );1072}10731074function ShortcutsHelpOverlay(props: {1075  bindings: Record<ShortcutAction, Keybinding>;1076  onClose: () => void;1077}) {1078  return (1079    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1080      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1081        <div class="peach-shortcuts-help-head">1082          <h3>Keyboard shortcuts</h3>1083          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1084        </div>1085        <div class="peach-shortcuts-help-body">1086          <p class="peach-settings-sub-label">ENTRY VIEW</p>1087          <ul>1088            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1089              <li>1090                <span>{d.label}</span>1091                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1092              </li>1093            ))}1094          </ul>1095          <p class="peach-settings-sub-label">ANYWHERE</p>1096          <ul>1097            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1098              <li>1099                <span>{d.label}</span>1100                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1101              </li>1102            ))}1103          </ul>1104        </div>1105      </div>1106    </div>1107  );1108}