App.tsx

39.9 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 { VaultView, type SortOrder } from "./views/Vault";6import { EntryView } from "./views/Entry";7import { AddView } from "./views/Add";8import { PeachWordmark } from "./components/PeachMark";9import { PasskeyApprovalView } from "./views/PasskeyApproval";10import { PasskeyEntryView } from "./views/PasskeyEntry";11import { extractDomain } from "../shared/domain";12import { popupCopy } from "./copy";13import {14  DEFAULT_BINDINGS,15  formatKeybinding,16  getActiveBindings,17  matchKeybinding,18  SHORTCUT_DESCRIPTORS,19  type Keybinding,20  type ShortcutAction,21} from "../shared/shortcuts";22import { generateTOTP } from "../crypto/totp";2324const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));25const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));26const CJKExport     = lazy(() => import("./views/CJKExport").then(m => ({ default: m.CJKExportView })));27const CJKImport     = lazy(() => import("./views/CJKImport").then(m => ({ default: m.CJKImportView })));28const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));29const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));30const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));3132type View =33  | "lock"34  | "entry"35  | "list"36  | "add"37  | "settings"38  | "import"39  | "export"40  | "health"41  | "trash";42type BootState = "loading" | "ready";4344const canarySuppressMap = new Map<string, boolean>();45let shellRingAnimation: Animation | null = null;4647export function isCanarySuppressed(entryId: string): boolean {48  return canarySuppressMap.get(entryId) ?? false;49}5051export function setCanarySuppressed(entryId: string, suppressed: boolean): void {52  canarySuppressMap.set(entryId, suppressed);53}5455export function clearCanarySuppressions(): void {56  canarySuppressMap.clear();57}5859export function triggerRing() {60  const shell = document.getElementById("hd-shell");61  if (!shell) return;6263  shellRingAnimation?.cancel();64  shell.dataset.glowing = "true";65  const animation = shell.animate(66    [67      { offset: 0, boxShadow: "var(--copy-shadow)" },68      {69        offset: 0.3,70        boxShadow:71          "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)",72      },73      { offset: 1, boxShadow: "var(--copy-shadow)" },74    ],75    {76      duration: 720,77      easing: "cubic-bezier(0.4, 0, 0.2, 1)",78      fill: "none",79    }80  );81  shellRingAnimation = animation;82  const clearGlow = () => {83    if (shellRingAnimation !== animation) return;84    shellRingAnimation = null;85    delete shell.dataset.glowing;86  };87  animation.onfinish = clearGlow;88  animation.oncancel = clearGlow;89}909192export function triggerPipPulse() {93  const pip = document.querySelector(".peach-status-pip, .pip");94  if (pip) {95    pip.classList.remove("pulse");96    void (pip as HTMLElement).offsetWidth;97    pip.classList.add("pulse");98  }99}100101function humanizeError(error: string | undefined): string | undefined {102  if (!error) return error;103  if (error === "STORAGE_QUOTA_EXCEEDED") {104    return "Peach has run out of browser storage. Delete some entries or clear browser storage to continue.";105  }106  return error;107}108109async function sendMessage(msg: any): Promise<any> {110  const MESSAGE_TIMEOUT_MS = 5000;111112  return new Promise((resolve) => {113    let settled = false;114    const timeoutId = window.setTimeout(() => {115      if (settled) return;116      settled = true;117      resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });118    }, MESSAGE_TIMEOUT_MS);119120    try {121      chrome.runtime.sendMessage(msg, (response) => {122        if (settled) return;123        settled = true;124        window.clearTimeout(timeoutId);125126        if (chrome.runtime.lastError) {127          resolve({128            ok: false,129            error:130              chrome.runtime.lastError.message ?? "SERVICE_WORKER_UNAVAILABLE",131          });132          return;133        }134135        if (response === undefined) {136          resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });137          return;138        }139140        if (response && response.ok === false) {141          response.error = humanizeError(response.error);142        }143        resolve(response);144      });145    } catch (error) {146      if (settled) return;147      settled = true;148      window.clearTimeout(timeoutId);149      resolve({150        ok: false,151        error:152          error instanceof Error ? error.message : "SERVICE_WORKER_UNAVAILABLE",153      });154    }155  });156}157158export { sendMessage };159160const ENTRY_TRANSITION_EXIT_MS = 95;161const ENTRY_TRANSITION_SETTLE_MS = 135;162163export default function App() {164  const [bootState, setBootState] = createSignal<BootState>("loading");165  const [view, setView] = createSignal<View>("lock");166  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(167    "enter"168  );169  const [contentTransitioning, setContentTransitioning] = createSignal(false);170  const [hasVault, setHasVault] = createSignal(false);171  const [entries, setEntries] = createSignal<VaultEntry[]>([]);172  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);173  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);174  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");175  const [theme, setTheme] = createSignal<"dark" | "light">("dark");176  const [lockOnClose, setLockOnClose] = createSignal(true);177  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);178  const [breachMonitoring, setBreachMonitoring] = createSignal(true);179  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);180  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);181  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);182  const [restoreView, setRestoreView] = createSignal<"cjk" | "file" | null>(null);183  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);184  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");185  // Cached Pro status — synchronous for render paths. Background's186  // GET_LICENSE is async, but render-time reads of isPro() must not block.187  // Refreshed at boot, after activate/deactivate, and whenever the popup188  // re-opens onto a stored license that has changed via another window.189  const [proStatus, setProStatus] = createSignal(false);190  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);191  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);192  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");193  const [listSearchSeed, setListSearchSeed] = createSignal("");194  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);195196  let contentPhaseTimer: number | undefined;197198  function applyAccent(name: AccentColorName) {199    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;200    const hex = color.hex;201    document.documentElement.style.setProperty("--peach-accent", hex);202    // Ambient surface variables — derived from the accent so surfaces shift203    // subtly toward the accent hue rather than staying fixed warm-brown.204    document.documentElement.style.setProperty("--peach-glow", hex + "2A");205    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");206    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");207  }208209  createEffect(() => {210    applyAccent(accentColor());211  });212213  createEffect(() => {214    document.documentElement.classList.toggle("light", theme() === "light");215    document.body.classList.toggle("light", theme() === "light");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  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload236  // small and lets future default updates land for actions the user hasn't237  // touched. Settings sends us the full active map; we filter and store.238  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {239    setShortcutBindings(active);240    const overrides: Record<string, Keybinding> = {};241    for (const action of Object.keys(active) as ShortcutAction[]) {242      const a = active[action];243      const d = DEFAULT_BINDINGS[action];244      const same = a.key === d.key245        && Boolean(a.ctrl)  === Boolean(d.ctrl)246        && Boolean(a.meta)  === Boolean(d.meta)247        && Boolean(a.shift) === Boolean(d.shift)248        && Boolean(a.alt)   === Boolean(d.alt);249      if (!same) overrides[action] = a;250    }251    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });252  }253254  async function applyLockOnClose(enabled: boolean) {255    setLockOnClose(enabled);256    await sendMessage({257      type: "UPDATE_SETTINGS",258      payload: { lockOnClose: enabled },259    });260  }261262  async function applyAutoLockMinutes(minutes: number) {263    setAutoLockMinutes(minutes);264    await sendMessage({265      type: "UPDATE_SETTINGS",266      payload: { autoLockMinutes: minutes },267    });268  }269270  async function applyBreachMonitoring(enabled: boolean) {271    setBreachMonitoring(enabled);272    await sendMessage({273      type: "UPDATE_SETTINGS",274      payload: { breachMonitoring: enabled },275    });276  }277278  onMount(async () => {279    // Resolve the active tab in parallel with the unlock/has-vault queries —280    // openVault()'s smart selection picks the entry matching currentTabDomain,281    // so it must be populated before openVault runs. Previously refreshCurrentTab282    // ran after openVault, leaving popups that booted already-unlocked falling283    // back to loadedEntries[0] instead of the domain match.284    const [unlockResponse, vaultResponse] = await Promise.all([285      sendMessage({ type: "IS_UNLOCKED" }),286      sendMessage({ type: "HAS_VAULT" }),287      refreshCurrentTab(),288    ]);289    const unlocked = Boolean(290      (unlockResponse as { ok: boolean; data?: boolean }).data291    );292    const vaultExists = Boolean(293      (vaultResponse as { ok: boolean; data?: boolean }).data294    );295    setHasVault(vaultExists);296    await Promise.all([restoreSettings(), refreshProStatus()]);297298    if (unlocked && vaultExists) {299      await openVault();300    }301302    await refreshPendingPasskey();303304    // Track tab changes so smart sort stays current305    const handleTabActivated = () => { void refreshCurrentTab(); };306    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {307      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();308    };309    try {310      chrome.tabs.onActivated.addListener(handleTabActivated);311      chrome.tabs.onUpdated.addListener(handleTabUpdated);312      onCleanup(() => {313        chrome.tabs.onActivated.removeListener(handleTabActivated);314        chrome.tabs.onUpdated.removeListener(handleTabUpdated);315      });316    } catch {317      // tabs permission may not be available in all contexts318    }319320    setBootState("ready");321    document.getElementById("pre-lock")?.setAttribute("hidden", "true");322323    // Warm the lazy-module cache so the Suspense fallback never shows for324    // locally-bundled extension views. Without this, the first navigation to325    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which326    // covers the shell and absorbs clicks on the header.327    void Promise.all([328      import("./views/Settings").catch(() => {}),329      import("./views/Import").catch(() => {}),330      import("./views/Export").catch(() => {}),331      import("./views/Health").catch(() => {}),332      import("./views/TrashView").catch(() => {}),333      import("./views/CJKExport").catch(() => {}),334      import("./views/CJKImport").catch(() => {}),335    ]);336337    // Lock-on-close via a persistent port. sendMessage in pagehide is338    // unreliable — the popup context tears down before the message lands.339    // The SW's onConnect listener locks when this port disconnects.340    let popupPort: chrome.runtime.Port | null = null;341    try {342      popupPort = chrome.runtime.connect({ name: "popup" });343    } catch { /* extension context invalidated — ignore */ }344    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });345346    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale347    // entries instead of waiting for the next GET_ENTRIES round-trip.348    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {349      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();350      if (msg?.type === "PRO_GATE_TRIGGERED") {351        // Background never navigates UI directly — it asks; the popup decides.352        // Land on Settings → License with the triggering feature highlighted.353        setUpgradeHighlight(msg.payload?.feature ?? null);354        setSettingsInitialSection("license");355        setView("settings");356      }357    };358    chrome.runtime.onMessage.addListener(handleRuntimeMessage);359    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));360361    // Action handlers — keyed by ShortcutAction. The dispatcher below tests362    // each binding against the event and runs the matching handler. New363    // shortcuts only need an entry here; the binding is data, not code.364    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {365      copy_password: () => {366        const entry = selectedEntry();367        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });368      },369      copy_username: () => {370        const entry = selectedEntry();371        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });372      },373      copy_totp: () => {374        const entry = selectedEntry();375        if (!entry?.totp) return;376        try {377          const { code } = generateTOTP(entry.totp);378          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });379        } catch { /* invalid TOTP secret — silent */ }380      },381      new_entry: () => handleAdd(),382      edit_entry: () => {383        const entry = selectedEntry();384        if (!entry || entry.type === "passkey") return;385        setEditEntry(entry);386        setView("add");387      },388      delete_entry: () => {389        if (selectedEntry()) void handleDelete();390      },391      lock_vault: () => { void handleHeaderLock(); },392      search: () => openList(),393      nav_prev: () => navigate(-1),394      nav_next: () => navigate(1),395      jump_vault: () => setView("entry"),396      jump_settings: () => setView("settings"),397      show_help: () => setShowShortcutsHelp(true),398    };399400    // Actions that are MEANINGFUL only on the entry-detail view. Outside401    // that scope the binding is dormant — pressing C while on Settings402    // does nothing rather than awkwardly copying from a now-stale entry.403    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([404      "copy_password", "copy_username", "copy_totp",405      "edit_entry", "delete_entry", "nav_prev", "nav_next",406    ]);407408    const handleGlobalKeydown = (e: KeyboardEvent) => {409      const v = view();410      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"411        || (e.target as HTMLElement)?.tagName === "TEXTAREA"412        || (e.target as HTMLElement)?.isContentEditable;413      const isPrintableSearchKey =414        e.key.length === 1 &&415        !e.ctrlKey &&416        !e.metaKey &&417        !e.altKey;418419      // Help dialog: Escape closes it; eat the keypress so it doesn't420      // also navigate away from the underlying view.421      if (showShortcutsHelp()) {422        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }423        return;424      }425426      // ── Escape — fixed binding (not user-customizable) ───────427      if (e.key === "Escape") {428        if (v === "list") { setView("entry"); return; }429        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }430      }431432      // Bindings-driven dispatch. Single-key letter bindings without433      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is434      // inside an input, so users can type into search/forms normally.435      const bindings = shortcutBindings();436      for (const action of Object.keys(bindings) as ShortcutAction[]) {437        const binding = bindings[action];438        if (!matchKeybinding(e, binding)) continue;439        // Single-key letter bindings need the input-focus guard. Bindings440        // with any modifier are safe — Ctrl+L doesn't conflict with typing.441        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;442        if (!hasMod && binding.key.length === 1 && inInput) return;443        if (ENTRY_SCOPED.has(action) && v !== "entry") return;444        e.preventDefault();445        SHORTCUT_HANDLERS[action]?.();446        return;447      }448449      // Type-to-search: in entry view, any printable key not consumed by a450      // shortcut above primes the list search seed and opens the list.451      // Kept outside the bindings table because it's a behavior, not a452      // discrete action — every printable character can trigger it.453      if (v === "entry" && !inInput && isPrintableSearchKey) {454        e.preventDefault();455        primeListSearch(e.key);456        return;457      }458    };459    window.addEventListener("keydown", handleGlobalKeydown);460    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));461462    const handleStorageChanged = (463      changes: Record<string, chrome.storage.StorageChange>,464      areaName: string465    ) => {466      if (areaName !== "session") return;467      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {468        return;469      }470      void refreshPendingPasskey();471    };472473    chrome.storage.onChanged.addListener(handleStorageChanged);474    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));475  });476477  async function refreshCurrentTab() {478    try {479      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });480      const url = tab?.url ?? tab?.pendingUrl ?? "";481      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");482    } catch {483      setCurrentTabDomain("");484    }485  }486487  async function refreshPendingPasskey() {488    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });489    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);490  }491492  async function refreshProStatus() {493    const res = await sendMessage({ type: "GET_LICENSE" });494    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;495    setProStatus(Boolean(data?.valid && data?.plan === "pro"));496  }497498  async function restoreSettings() {499    const res = await sendMessage({ type: "GET_SETTINGS" });500    const s = (res as { ok: boolean; data?: any }).data ?? {};501    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {502      setAccentColor(s.accentColor as AccentColorName);503    }504    setTheme(s.theme === "light" ? "light" : "dark");505    setLockOnClose(s.lockOnClose !== false);506    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);507    setBreachMonitoring(s.breachMonitoring !== false);508    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);509    setShortcutBindings(getActiveBindings(s.shortcuts));510  }511512  async function applyTrashRetention(days: number) {513    setTrashRetentionDays(days);514    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });515  }516517  function primeListSearch(seed: string) {518    setListSearchSeed(seed);519    setListSearchSeedNonce((value) => value + 1);520    openList();521  }522523  // Returns null when it detected a dead service worker and triggered handleLock().524  // Callers that need to abort (e.g. openVault) check for null rather than relying525  // on view() state, which may already be "lock" during normal startup flows.526  async function loadEntries(): Promise<VaultEntry[] | null> {527    const response = await sendMessage({ type: "GET_ENTRIES" });528    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };529530    // If the service worker was killed and restarted (MV3 workers sleep), the531    // vault will be locked again — or the worker may not respond at all.532    // In either case, send the user to the lock screen rather than silently533    // showing an empty vault (which looks like data loss).534    if (!res.ok) {535      if (536        res.error === "vault locked" ||537        res.error === "SERVICE_WORKER_UNAVAILABLE" ||538        (typeof res.error === "string" && res.error.includes("locked"))539      ) {540        handleLock();541        return null; // signal emergency lock to callers542      }543      return [];544    }545546    const loadedEntries = res.data ?? [];547    setEntries(loadedEntries);548549    const currentId = selectedEntry()?.id;550    if (currentId) {551      setSelectedEntry(552        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null553      );554    }555556    return loadedEntries;557  }558559  async function openVault(preferredEntryId?: string) {560    // Purge expired trash entries on each vault open561    const retDays = trashRetentionDays();562    if (retDays > 0) {563      void sendMessage({564        type: "PURGE_EXPIRED_TRASH",565        payload: { retentionMs: retDays * 86_400_000 },566      });567    }568569    const loadedEntries = await loadEntries();570571    // null means loadEntries() triggered an emergency lock (service worker died).572    // Don't override it by setting view back to "entry" with an empty vault.573    if (loadedEntries === null) return;574575    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry576    let nextSelectedEntry: VaultEntry | null = null;577    if (preferredEntryId) {578      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;579    }580    if (!nextSelectedEntry) {581      const tabDomain = currentTabDomain();582      if (tabDomain) {583        nextSelectedEntry = loadedEntries.find((e) => {584          if (e.type === "login") {585            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;586            for (const extra of e.additionalUrls ?? []) {587              if ((extractDomain(extra) ?? "") === tabDomain) return true;588            }589            return false;590          }591          if (e.type === "passkey" && e.rpId) return e.rpId === tabDomain;592          return false;593        }) ?? null;594      }595    }596    nextSelectedEntry ??= loadedEntries[0] ?? null;597598    setSelectedEntry(nextSelectedEntry);599    setEditEntry(undefined);600    setContentTransitioning(false);601    setContentPhase("enter");602    queueContentIdle();603    setView("entry");604  }605606  async function handleUnlock() {607    setHasVault(true);608    triggerPipPulse();609    await restoreSettings();610    await openVault();611  }612613  function handleSelectEntry(entry: VaultEntry) {614    setSelectedEntry(entry);615    setContentTransitioning(false);616    setContentPhase("enter");617    queueContentIdle();618    setView("entry");619  }620621  function handleAdd() {622    setEditEntry(undefined);623    setView("add");624  }625626  async function handleDelete() {627    const entry = selectedEntry();628    if (!entry) return;629    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });630    const loadedEntries = await loadEntries() ?? [];631    setSelectedEntry(loadedEntries[0] ?? null);632    setView("entry");633  }634635  async function handleDeleteMany(ids: string[]) {636    for (const id of ids) {637      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });638    }639    const loadedEntries = await loadEntries() ?? [];640    // If the currently selected entry was among the deleted, move to first641    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);642    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);643  }644645  async function handleSave(savedEntry?: VaultEntry) {646    await openVault(savedEntry?.id);647  }648649  function handleBack() {650    setEditEntry(undefined);651    setView("entry");652  }653654  function handleLock() {655    clearCanarySuppressions();656    setEntries([]);657    setSelectedEntry(null);658    setEditEntry(undefined);659    setContentPhase("idle");660    setView("lock");661  }662663  function handleHeaderLock() {664    // Lock the UI immediately — do not wait for the service worker. If the SW665    // is dead or slow, the 5s sendMessage timeout would create a dead-click666    // window. The SW will lock on its next wake regardless.667    handleLock();668    void sendMessage({ type: "LOCK" });669  }670671  function navigate(dir: number) {672    const allEntries = entries();673    if (allEntries.length === 0) return;674    const currentIndex = selectedIndex();675    const baseIndex = currentIndex >= 0 ? currentIndex : 0;676    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;677    setSelectedEntry(allEntries[nextIndex]);678    setContentPhase("enter");679    queueContentIdle();680  }681682  function openList() {683    setView("list");684  }685686  function openHealth() {687    setEditEntry(undefined);688    setView("health");689  }690691  function handleOpenCJKImport() {692    setRestoreView("cjk");693  }694695  function handleOpenFileImport() {696    setRestoreView("file");697  }698699  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;700701  function handleFixEntry(entry: VaultEntry) {702    if (entry.type === "passkey") {703      setSelectedEntry(entry);704      setView("entry");705      return;706    }707    setEditEntry(entry);708    setView("add");709  }710711  const isLockedView = () => view() === "lock";712  const selectedPasskeyEntry = createMemo(() =>713    selectedEntry()?.type === "passkey" ? (selectedEntry() as PasskeyEntry) : null714  );715716  async function handleApprovePendingPasskey() {717    const pending = pendingPasskey();718    if (!pending) return;719    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });720    setPendingPasskey(null);721  }722723  async function handleDenyPendingPasskey() {724    const pending = pendingPasskey();725    if (!pending) return;726    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });727    setPendingPasskey(null);728  }729730  function queueContentIdle(after?: () => void) {731    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);732    contentPhaseTimer = window.setTimeout(() => {733      setContentPhase("idle");734      after?.();735    }, ENTRY_TRANSITION_SETTLE_MS);736  }737738  return (739    <div class="popup-root peach-theme">740      <Show when={bootState() === "ready"}>741        <Show742          when={!pendingPasskey()}743          fallback={744            <PasskeyApprovalView745              type={pendingPasskey()!.type}746              rpName={pendingPasskey()!.rpName}747              rpId={pendingPasskey()!.rpId}748              userName={pendingPasskey()!.userName}749              userDisplayName={pendingPasskey()!.userDisplayName}750              onApprove={handleApprovePendingPasskey}751              onDeny={handleDenyPendingPasskey}752            />753          }754        >755          <Show756            when={!isLockedView()}757            fallback={758              <LockView759                hasVault={hasVault()}760                ready={bootState() === "ready"}761                isPro={proStatus()}762                onUnlock={handleUnlock}763              />764            }765          >766            <section767              id="hd-shell"768              class="peach-shell peach-theme"769              data-surface="extension"770            >771            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>772              <PeachWordmark unlocked />773              <div class="peach-chrome-actions">774                <button775                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"776                  onClick={() => setView("settings")}777                  aria-label="Settings"778                >779                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">780                    <path781                      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"782                      stroke="currentColor"783                      stroke-width="0.9"784                    />785                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />786                  </svg>787                </button>788                <button789                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"790                  onClick={handleAdd}791                  aria-label="New entry"792                >793                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">794                    <path d="M5.5 1v9M1 5.5h9" />795                  </svg>796                </button>797                <button798                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"799                  onClick={() => void handleHeaderLock()}800                  aria-label="Lock vault"801                >802                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">803                    <path804                      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"805                      stroke="currentColor"806                      stroke-width="1"807                      stroke-linecap="round"808                    />809                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />810                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />811                  </svg>812                </button>813              </div>814            </header>815816            <div class="peach-shell-body">817              <div class="peach-shell-veil"></div>818              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>819                <Show820                  when={selectedPasskeyEntry()}821                  fallback={822                    <EntryView823                      entry={selectedEntry()}824                      onDelete={handleDelete}825                      onFieldSaved={() => void loadEntries()}826                      onEscape={() => { setView("list"); }}827                    />828                  }829                >830                  <PasskeyEntryView entry={selectedPasskeyEntry()} onDelete={handleDelete} />831                </Show>832              </div>833834              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>835                <div class="peach-search-bar">836                  <span class="peach-search-icon">837                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">838                      <circle cx="5.5" cy="5.5" r="3.75" />839                      <path d="M8.75 8.75L11.5 11.5" />840                    </svg>841                  </span>842                  <input843                    class="peach-search-input"844                    placeholder="search vault..."845                    autocomplete="off"846                    aria-label="Search vault entries"847                    onClick={openList}848                    onFocus={openList}849                    readOnly850                  />851                  <div class="peach-search-meta">852                    <span class="peach-search-counter">853                      {entries().length > 0854                        ? `${selectedIndex() + 1} / ${entries().length}`855                        : "0 entries"}856                    </span>857                    <span class="peach-divider"></span>858                    <button859                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"860                      onClick={() => navigate(-1)}861                      aria-label="Previous entry"862                      disabled={entries().length === 0}863                    >864                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">865                        <path d="M5 1L1 5.5L5 10" />866                      </svg>867                    </button>868                    <button869                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"870                      onClick={() => navigate(1)}871                      aria-label="Next entry"872                      disabled={entries().length === 0}873                    >874                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">875                        <path d="M1 1L5 5.5L1 10" />876                      </svg>877                    </button>878                  </div>879                </div>880              </section>881            </div>882883            <Show when={view() === "list"}>884              <VaultView885                entries={entries()}886                selectedEntryId={selectedEntry()?.id}887                currentTabDomain={currentTabDomain()}888                sortOrder={sortOrder()}889                searchSeed={listSearchSeed()}890                searchSeedNonce={listSearchSeedNonce()}891                onSelectEntry={handleSelectEntry}892                onSortOrderChange={setSortOrder}893                onAdd={handleAdd}894                onClose={() => setView("entry")}895                onOpenTrash={() => setView("trash")}896                onDeleteMany={handleDeleteMany}897              />898            </Show>899            <Show when={view() === "settings"}>900              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>901                <SettingsView902                  entriesCount={entries().length}903                  breachMonitoring={breachMonitoring()}904                  lockOnClose={lockOnClose()}905                  autoLockMinutes={autoLockMinutes()}906                  trashRetentionDays={trashRetentionDays()}907                  theme={theme()}908                  accentColor={accentColor()}909                  isPro={proStatus()}910                  initialSection={settingsInitialSection()}911                  upgradeHighlight={upgradeHighlight()}912                  onBreachMonitoringChange={applyBreachMonitoring}913                  onLockOnCloseChange={applyLockOnClose}914                  onAutoLockMinutesChange={applyAutoLockMinutes}915                  onTrashRetentionChange={applyTrashRetention}916                  onThemeChange={applyTheme}917                  onAccentChange={applyAccentColor}918                  shortcuts={shortcutBindings()}919                  onShortcutsChange={applyShortcuts}920                  onLicenseChange={refreshProStatus}921                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}922                  onImport={() => setView("import")}923                  onExport={() => setView("export")}924                  onBreachCheckDone={loadEntries}925                  onOpenHealth={openHealth}926                  onOpenCJKImport={handleOpenCJKImport}927                  onOpenFileImport={handleOpenFileImport}928                />929              </Suspense>930            </Show>931            <Show when={view() === "add"}>932              <AddView933                entry={editEntry()}934                entries={entries()}935                onBack={handleBack}936                onSave={handleSave}937              />938            </Show>939            <Show when={view() === "import"}>940              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>941                <ImportView onBack={handleBack} onImport={handleSave} />942              </Suspense>943            </Show>944            <Show when={view() === "export"}>945              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>946                <ExportView onBack={handleBack} onRequiresUnlock={handleLock} />947              </Suspense>948            </Show>949            <Show when={view() === "health"}>950              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>951                <HealthView952                  entries={entries()}953                  isPro={proStatus()}954                  onFixEntry={handleFixEntry}955                  onBack={() => setView("settings")}956                  onRefresh={loadEntries}957                />958              </Suspense>959            </Show>960            <Show when={view() === "trash"}>961              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>962                <TrashView963                  onBack={() => setView("list")}964                  onRestored={() => void loadEntries()}965                />966              </Suspense>967            </Show>968            <Show when={restoreView() === "cjk"}>969              <CJKImport970                mode="onboarding"971                onBack={() => setRestoreView(null)}972                onDone={async () => {973                  setRestoreView(null);974                  await handleUnlock();975                }}976              />977            </Show>978            <Show when={restoreView() === "file"}>979              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>980                <ImportView981                  mode="onboarding"982                  replacesExistingVault={true}983                  onBack={() => setRestoreView(null)}984                  onImport={async () => {985                    setRestoreView(null);986                    await handleUnlock();987                  }}988                />989              </Suspense>990            </Show>991            </section>992          </Show>993        </Show>994      </Show>995      <Show when={showShortcutsHelp()}>996        <ShortcutsHelpOverlay997          bindings={shortcutBindings()}998          onClose={() => setShowShortcutsHelp(false)}999        />1000      </Show>1001    </div>1002  );1003}10041005function ShortcutsHelpOverlay(props: {1006  bindings: Record<ShortcutAction, Keybinding>;1007  onClose: () => void;1008}) {1009  return (1010    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1011      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1012        <div class="peach-shortcuts-help-head">1013          <h3>Keyboard shortcuts</h3>1014          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1015        </div>1016        <div class="peach-shortcuts-help-body">1017          <p class="peach-settings-sub-label">ENTRY VIEW</p>1018          <ul>1019            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1020              <li>1021                <span>{d.label}</span>1022                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1023              </li>1024            ))}1025          </ul>1026          <p class="peach-settings-sub-label">ANYWHERE</p>1027          <ul>1028            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1029              <li>1030                <span>{d.label}</span>1031                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1032              </li>1033            ))}1034          </ul>1035        </div>1036      </div>1037    </div>1038  );1039}