App.tsx

38.4 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, 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  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");186  const [listSearchSeed, setListSearchSeed] = createSignal("");187  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);188189  let contentPhaseTimer: number | undefined;190191  function applyAccent(name: AccentColorName) {192    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;193    const hex = color.hex;194    document.documentElement.style.setProperty("--peach-accent", hex);195    // Ambient surface variables — derived from the accent so surfaces shift196    // subtly toward the accent hue rather than staying fixed warm-brown.197    document.documentElement.style.setProperty("--peach-glow", hex + "2A");198    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");199    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");200  }201202  createEffect(() => {203    applyAccent(accentColor());204  });205206  createEffect(() => {207    document.documentElement.classList.toggle("light", theme() === "light");208    document.body.classList.toggle("light", theme() === "light");209  });210211  const selectedIndex = createMemo(() => {212    const currentId = selectedEntry()?.id;213    if (!currentId) return entries().length > 0 ? 0 : -1;214    return entries().findIndex((entry) => entry.id === currentId);215  });216217  async function applyAccentColor(name: AccentColorName) {218    applyAccent(name);219    setAccentColor(name);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });221  }222223  async function applyTheme(t: "dark" | "light") {224    setTheme(t);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });226  }227228  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload229  // small and lets future default updates land for actions the user hasn't230  // touched. Settings sends us the full active map; we filter and store.231  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {232    setShortcutBindings(active);233    const overrides: Record<string, Keybinding> = {};234    for (const action of Object.keys(active) as ShortcutAction[]) {235      const a = active[action];236      const d = DEFAULT_BINDINGS[action];237      const same = a.key === d.key238        && Boolean(a.ctrl)  === Boolean(d.ctrl)239        && Boolean(a.meta)  === Boolean(d.meta)240        && Boolean(a.shift) === Boolean(d.shift)241        && Boolean(a.alt)   === Boolean(d.alt);242      if (!same) overrides[action] = a;243    }244    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });245  }246247  async function applyLockOnClose(enabled: boolean) {248    setLockOnClose(enabled);249    await sendMessage({250      type: "UPDATE_SETTINGS",251      payload: { lockOnClose: enabled },252    });253  }254255  async function applyAutoLockMinutes(minutes: number) {256    setAutoLockMinutes(minutes);257    await sendMessage({258      type: "UPDATE_SETTINGS",259      payload: { autoLockMinutes: minutes },260    });261  }262263  async function applyBreachMonitoring(enabled: boolean) {264    setBreachMonitoring(enabled);265    await sendMessage({266      type: "UPDATE_SETTINGS",267      payload: { breachMonitoring: enabled },268    });269  }270271  onMount(async () => {272    // Resolve the active tab in parallel with the unlock/has-vault queries —273    // openVault()'s smart selection picks the entry matching currentTabDomain,274    // so it must be populated before openVault runs. Previously refreshCurrentTab275    // ran after openVault, leaving popups that booted already-unlocked falling276    // back to loadedEntries[0] instead of the domain match.277    const [unlockResponse, vaultResponse] = await Promise.all([278      sendMessage({ type: "IS_UNLOCKED" }),279      sendMessage({ type: "HAS_VAULT" }),280      refreshCurrentTab(),281    ]);282    const unlocked = Boolean(283      (unlockResponse as { ok: boolean; data?: boolean }).data284    );285    const vaultExists = Boolean(286      (vaultResponse as { ok: boolean; data?: boolean }).data287    );288    setHasVault(vaultExists);289    await restoreSettings();290291    if (unlocked && vaultExists) {292      await openVault();293    }294295    await refreshPendingPasskey();296297    // Track tab changes so smart sort stays current298    const handleTabActivated = () => { void refreshCurrentTab(); };299    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {300      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();301    };302    try {303      chrome.tabs.onActivated.addListener(handleTabActivated);304      chrome.tabs.onUpdated.addListener(handleTabUpdated);305      onCleanup(() => {306        chrome.tabs.onActivated.removeListener(handleTabActivated);307        chrome.tabs.onUpdated.removeListener(handleTabUpdated);308      });309    } catch {310      // tabs permission may not be available in all contexts311    }312313    setBootState("ready");314    document.getElementById("pre-lock")?.setAttribute("hidden", "true");315316    // Warm the lazy-module cache so the Suspense fallback never shows for317    // locally-bundled extension views. Without this, the first navigation to318    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which319    // covers the shell and absorbs clicks on the header.320    void Promise.all([321      import("./views/Settings").catch(() => {}),322      import("./views/Import").catch(() => {}),323      import("./views/Export").catch(() => {}),324      import("./views/Health").catch(() => {}),325      import("./views/TrashView").catch(() => {}),326      import("./views/CJKExport").catch(() => {}),327      import("./views/CJKImport").catch(() => {}),328    ]);329330    // Lock-on-close via a persistent port. sendMessage in pagehide is331    // unreliable — the popup context tears down before the message lands.332    // The SW's onConnect listener locks when this port disconnects.333    let popupPort: chrome.runtime.Port | null = null;334    try {335      popupPort = chrome.runtime.connect({ name: "popup" });336    } catch { /* extension context invalidated — ignore */ }337    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });338339    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale340    // entries instead of waiting for the next GET_ENTRIES round-trip.341    const handleRuntimeMessage = (msg: { type?: string }) => {342      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();343    };344    chrome.runtime.onMessage.addListener(handleRuntimeMessage);345    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));346347    // Action handlers — keyed by ShortcutAction. The dispatcher below tests348    // each binding against the event and runs the matching handler. New349    // shortcuts only need an entry here; the binding is data, not code.350    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {351      copy_password: () => {352        const entry = selectedEntry();353        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });354      },355      copy_username: () => {356        const entry = selectedEntry();357        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });358      },359      copy_totp: () => {360        const entry = selectedEntry();361        if (!entry?.totp) return;362        try {363          const { code } = generateTOTP(entry.totp);364          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });365        } catch { /* invalid TOTP secret — silent */ }366      },367      new_entry: () => handleAdd(),368      edit_entry: () => {369        const entry = selectedEntry();370        if (!entry || entry.type === "passkey") return;371        setEditEntry(entry);372        setView("add");373      },374      delete_entry: () => {375        if (selectedEntry()) void handleDelete();376      },377      lock_vault: () => { void handleHeaderLock(); },378      search: () => openList(),379      nav_prev: () => navigate(-1),380      nav_next: () => navigate(1),381      jump_vault: () => setView("entry"),382      jump_settings: () => setView("settings"),383      show_help: () => setShowShortcutsHelp(true),384    };385386    // Actions that are MEANINGFUL only on the entry-detail view. Outside387    // that scope the binding is dormant — pressing C while on Settings388    // does nothing rather than awkwardly copying from a now-stale entry.389    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([390      "copy_password", "copy_username", "copy_totp",391      "edit_entry", "delete_entry", "nav_prev", "nav_next",392    ]);393394    const handleGlobalKeydown = (e: KeyboardEvent) => {395      const v = view();396      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"397        || (e.target as HTMLElement)?.tagName === "TEXTAREA"398        || (e.target as HTMLElement)?.isContentEditable;399      const isPrintableSearchKey =400        e.key.length === 1 &&401        !e.ctrlKey &&402        !e.metaKey &&403        !e.altKey;404405      // Help dialog: Escape closes it; eat the keypress so it doesn't406      // also navigate away from the underlying view.407      if (showShortcutsHelp()) {408        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }409        return;410      }411412      // ── Escape — fixed binding (not user-customizable) ───────413      if (e.key === "Escape") {414        if (v === "list") { setView("entry"); return; }415        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }416      }417418      // Bindings-driven dispatch. Single-key letter bindings without419      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is420      // inside an input, so users can type into search/forms normally.421      const bindings = shortcutBindings();422      for (const action of Object.keys(bindings) as ShortcutAction[]) {423        const binding = bindings[action];424        if (!matchKeybinding(e, binding)) continue;425        // Single-key letter bindings need the input-focus guard. Bindings426        // with any modifier are safe — Ctrl+L doesn't conflict with typing.427        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;428        if (!hasMod && binding.key.length === 1 && inInput) return;429        if (ENTRY_SCOPED.has(action) && v !== "entry") return;430        e.preventDefault();431        SHORTCUT_HANDLERS[action]?.();432        return;433      }434435      // Type-to-search: in entry view, any printable key not consumed by a436      // shortcut above primes the list search seed and opens the list.437      // Kept outside the bindings table because it's a behavior, not a438      // discrete action — every printable character can trigger it.439      if (v === "entry" && !inInput && isPrintableSearchKey) {440        e.preventDefault();441        primeListSearch(e.key);442        return;443      }444    };445    window.addEventListener("keydown", handleGlobalKeydown);446    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));447448    const handleStorageChanged = (449      changes: Record<string, chrome.storage.StorageChange>,450      areaName: string451    ) => {452      if (areaName !== "session") return;453      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {454        return;455      }456      void refreshPendingPasskey();457    };458459    chrome.storage.onChanged.addListener(handleStorageChanged);460    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));461  });462463  async function refreshCurrentTab() {464    try {465      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });466      const url = tab?.url ?? tab?.pendingUrl ?? "";467      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");468    } catch {469      setCurrentTabDomain("");470    }471  }472473  async function refreshPendingPasskey() {474    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });475    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);476  }477478  async function restoreSettings() {479    const res = await sendMessage({ type: "GET_SETTINGS" });480    const s = (res as { ok: boolean; data?: any }).data ?? {};481    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {482      setAccentColor(s.accentColor as AccentColorName);483    }484    setTheme(s.theme === "light" ? "light" : "dark");485    setLockOnClose(s.lockOnClose !== false);486    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);487    setBreachMonitoring(s.breachMonitoring !== false);488    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);489    setShortcutBindings(getActiveBindings(s.shortcuts));490  }491492  async function applyTrashRetention(days: number) {493    setTrashRetentionDays(days);494    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });495  }496497  function primeListSearch(seed: string) {498    setListSearchSeed(seed);499    setListSearchSeedNonce((value) => value + 1);500    openList();501  }502503  // Returns null when it detected a dead service worker and triggered handleLock().504  // Callers that need to abort (e.g. openVault) check for null rather than relying505  // on view() state, which may already be "lock" during normal startup flows.506  async function loadEntries(): Promise<VaultEntry[] | null> {507    const response = await sendMessage({ type: "GET_ENTRIES" });508    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };509510    // If the service worker was killed and restarted (MV3 workers sleep), the511    // vault will be locked again — or the worker may not respond at all.512    // In either case, send the user to the lock screen rather than silently513    // showing an empty vault (which looks like data loss).514    if (!res.ok) {515      if (516        res.error === "vault locked" ||517        res.error === "SERVICE_WORKER_UNAVAILABLE" ||518        (typeof res.error === "string" && res.error.includes("locked"))519      ) {520        handleLock();521        return null; // signal emergency lock to callers522      }523      return [];524    }525526    const loadedEntries = res.data ?? [];527    setEntries(loadedEntries);528529    const currentId = selectedEntry()?.id;530    if (currentId) {531      setSelectedEntry(532        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null533      );534    }535536    return loadedEntries;537  }538539  async function openVault(preferredEntryId?: string) {540    // Purge expired trash entries on each vault open541    const retDays = trashRetentionDays();542    if (retDays > 0) {543      void sendMessage({544        type: "PURGE_EXPIRED_TRASH",545        payload: { retentionMs: retDays * 86_400_000 },546      });547    }548549    const loadedEntries = await loadEntries();550551    // null means loadEntries() triggered an emergency lock (service worker died).552    // Don't override it by setting view back to "entry" with an empty vault.553    if (loadedEntries === null) return;554555    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry556    let nextSelectedEntry: VaultEntry | null = null;557    if (preferredEntryId) {558      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;559    }560    if (!nextSelectedEntry) {561      const tabDomain = currentTabDomain();562      if (tabDomain) {563        nextSelectedEntry = loadedEntries.find((e) => {564          if (e.type === "login") {565            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;566            for (const extra of e.additionalUrls ?? []) {567              if ((extractDomain(extra) ?? "") === tabDomain) return true;568            }569            return false;570          }571          if (e.type === "passkey" && e.rpId) return e.rpId === tabDomain;572          return false;573        }) ?? null;574      }575    }576    nextSelectedEntry ??= loadedEntries[0] ?? null;577578    setSelectedEntry(nextSelectedEntry);579    setEditEntry(undefined);580    setContentTransitioning(false);581    setContentPhase("enter");582    queueContentIdle();583    setView("entry");584  }585586  async function handleUnlock() {587    setHasVault(true);588    triggerPipPulse();589    await restoreSettings();590    await openVault();591  }592593  function handleSelectEntry(entry: VaultEntry) {594    setSelectedEntry(entry);595    setContentTransitioning(false);596    setContentPhase("enter");597    queueContentIdle();598    setView("entry");599  }600601  function handleAdd() {602    setEditEntry(undefined);603    setView("add");604  }605606  async function handleDelete() {607    const entry = selectedEntry();608    if (!entry) return;609    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });610    const loadedEntries = await loadEntries() ?? [];611    setSelectedEntry(loadedEntries[0] ?? null);612    setView("entry");613  }614615  async function handleDeleteMany(ids: string[]) {616    for (const id of ids) {617      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });618    }619    const loadedEntries = await loadEntries() ?? [];620    // If the currently selected entry was among the deleted, move to first621    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);622    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);623  }624625  async function handleSave(savedEntry?: VaultEntry) {626    await openVault(savedEntry?.id);627  }628629  function handleBack() {630    setEditEntry(undefined);631    setView("entry");632  }633634  function handleLock() {635    clearCanarySuppressions();636    setEntries([]);637    setSelectedEntry(null);638    setEditEntry(undefined);639    setContentPhase("idle");640    setView("lock");641  }642643  function handleHeaderLock() {644    // Lock the UI immediately — do not wait for the service worker. If the SW645    // is dead or slow, the 5s sendMessage timeout would create a dead-click646    // window. The SW will lock on its next wake regardless.647    handleLock();648    void sendMessage({ type: "LOCK" });649  }650651  function navigate(dir: number) {652    const allEntries = entries();653    if (allEntries.length === 0) return;654    const currentIndex = selectedIndex();655    const baseIndex = currentIndex >= 0 ? currentIndex : 0;656    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;657    setSelectedEntry(allEntries[nextIndex]);658    setContentPhase("enter");659    queueContentIdle();660  }661662  function openList() {663    setView("list");664  }665666  function openHealth() {667    setEditEntry(undefined);668    setView("health");669  }670671  function handleOpenCJKImport() {672    setRestoreView("cjk");673  }674675  function handleOpenFileImport() {676    setRestoreView("file");677  }678679  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;680681  function handleFixEntry(entry: VaultEntry) {682    if (entry.type === "passkey") {683      setSelectedEntry(entry);684      setView("entry");685      return;686    }687    setEditEntry(entry);688    setView("add");689  }690691  const isLockedView = () => view() === "lock";692  const selectedPasskeyEntry = createMemo(() =>693    selectedEntry()?.type === "passkey" ? (selectedEntry() as PasskeyEntry) : null694  );695696  async function handleApprovePendingPasskey() {697    const pending = pendingPasskey();698    if (!pending) return;699    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });700    setPendingPasskey(null);701  }702703  async function handleDenyPendingPasskey() {704    const pending = pendingPasskey();705    if (!pending) return;706    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });707    setPendingPasskey(null);708  }709710  function queueContentIdle(after?: () => void) {711    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);712    contentPhaseTimer = window.setTimeout(() => {713      setContentPhase("idle");714      after?.();715    }, ENTRY_TRANSITION_SETTLE_MS);716  }717718  return (719    <div class="popup-root peach-theme">720      <Show when={bootState() === "ready"}>721        <Show722          when={!pendingPasskey()}723          fallback={724            <PasskeyApprovalView725              type={pendingPasskey()!.type}726              rpName={pendingPasskey()!.rpName}727              rpId={pendingPasskey()!.rpId}728              userName={pendingPasskey()!.userName}729              userDisplayName={pendingPasskey()!.userDisplayName}730              onApprove={handleApprovePendingPasskey}731              onDeny={handleDenyPendingPasskey}732            />733          }734        >735          <Show736            when={!isLockedView()}737            fallback={738              <LockView739                hasVault={hasVault()}740                ready={bootState() === "ready"}741                onUnlock={handleUnlock}742              />743            }744          >745            <section746              id="hd-shell"747              class="peach-shell peach-theme"748              data-surface="extension"749            >750            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>751              <PeachWordmark unlocked />752              <div class="peach-chrome-actions">753                <button754                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"755                  onClick={() => setView("settings")}756                  aria-label="Settings"757                >758                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">759                    <path760                      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"761                      stroke="currentColor"762                      stroke-width="0.9"763                    />764                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />765                  </svg>766                </button>767                <button768                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"769                  onClick={handleAdd}770                  aria-label="New entry"771                >772                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">773                    <path d="M5.5 1v9M1 5.5h9" />774                  </svg>775                </button>776                <button777                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"778                  onClick={() => void handleHeaderLock()}779                  aria-label="Lock vault"780                >781                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">782                    <path783                      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"784                      stroke="currentColor"785                      stroke-width="1"786                      stroke-linecap="round"787                    />788                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />789                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />790                  </svg>791                </button>792              </div>793            </header>794795            <div class="peach-shell-body">796              <div class="peach-shell-veil"></div>797              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>798                <Show799                  when={selectedPasskeyEntry()}800                  fallback={801                    <EntryView802                      entry={selectedEntry()}803                      onDelete={handleDelete}804                      onFieldSaved={() => void loadEntries()}805                      onEscape={() => { setView("list"); }}806                    />807                  }808                >809                  <PasskeyEntryView entry={selectedPasskeyEntry()} onDelete={handleDelete} />810                </Show>811              </div>812813              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>814                <div class="peach-search-bar">815                  <span class="peach-search-icon">816                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">817                      <circle cx="5.5" cy="5.5" r="3.75" />818                      <path d="M8.75 8.75L11.5 11.5" />819                    </svg>820                  </span>821                  <input822                    class="peach-search-input"823                    placeholder="search vault..."824                    autocomplete="off"825                    aria-label="Search vault entries"826                    onClick={openList}827                    onFocus={openList}828                    readOnly829                  />830                  <div class="peach-search-meta">831                    <span class="peach-search-counter">832                      {entries().length > 0833                        ? `${selectedIndex() + 1} / ${entries().length}`834                        : "0 entries"}835                    </span>836                    <span class="peach-divider"></span>837                    <button838                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"839                      onClick={() => navigate(-1)}840                      aria-label="Previous entry"841                      disabled={entries().length === 0}842                    >843                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">844                        <path d="M5 1L1 5.5L5 10" />845                      </svg>846                    </button>847                    <button848                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"849                      onClick={() => navigate(1)}850                      aria-label="Next entry"851                      disabled={entries().length === 0}852                    >853                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">854                        <path d="M1 1L5 5.5L1 10" />855                      </svg>856                    </button>857                  </div>858                </div>859              </section>860            </div>861862            <Show when={view() === "list"}>863              <VaultView864                entries={entries()}865                selectedEntryId={selectedEntry()?.id}866                currentTabDomain={currentTabDomain()}867                sortOrder={sortOrder()}868                searchSeed={listSearchSeed()}869                searchSeedNonce={listSearchSeedNonce()}870                onSelectEntry={handleSelectEntry}871                onSortOrderChange={setSortOrder}872                onAdd={handleAdd}873                onClose={() => setView("entry")}874                onOpenTrash={() => setView("trash")}875                onDeleteMany={handleDeleteMany}876              />877            </Show>878            <Show when={view() === "settings"}>879              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>880                <SettingsView881                  entriesCount={entries().length}882                  breachMonitoring={breachMonitoring()}883                  lockOnClose={lockOnClose()}884                  autoLockMinutes={autoLockMinutes()}885                  trashRetentionDays={trashRetentionDays()}886                  theme={theme()}887                  accentColor={accentColor()}888                  onBreachMonitoringChange={applyBreachMonitoring}889                  onLockOnCloseChange={applyLockOnClose}890                  onAutoLockMinutesChange={applyAutoLockMinutes}891                  onTrashRetentionChange={applyTrashRetention}892                  onThemeChange={applyTheme}893                  onAccentChange={applyAccentColor}894                  shortcuts={shortcutBindings()}895                  onShortcutsChange={applyShortcuts}896                  onBack={handleBack}897                  onImport={() => setView("import")}898                  onExport={() => setView("export")}899                  onBreachCheckDone={loadEntries}900                  onOpenHealth={openHealth}901                  onOpenCJKImport={handleOpenCJKImport}902                  onOpenFileImport={handleOpenFileImport}903                />904              </Suspense>905            </Show>906            <Show when={view() === "add"}>907              <AddView908                entry={editEntry()}909                entries={entries()}910                onBack={handleBack}911                onSave={handleSave}912              />913            </Show>914            <Show when={view() === "import"}>915              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>916                <ImportView onBack={handleBack} onImport={handleSave} />917              </Suspense>918            </Show>919            <Show when={view() === "export"}>920              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>921                <ExportView onBack={handleBack} onRequiresUnlock={handleLock} />922              </Suspense>923            </Show>924            <Show when={view() === "health"}>925              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>926                <HealthView927                  entries={entries()}928                  onFixEntry={handleFixEntry}929                  onBack={() => setView("settings")}930                  onRefresh={loadEntries}931                />932              </Suspense>933            </Show>934            <Show when={view() === "trash"}>935              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>936                <TrashView937                  onBack={() => setView("list")}938                  onRestored={() => void loadEntries()}939                />940              </Suspense>941            </Show>942            <Show when={restoreView() === "cjk"}>943              <CJKImport944                mode="onboarding"945                onBack={() => setRestoreView(null)}946                onDone={async () => {947                  setRestoreView(null);948                  await handleUnlock();949                }}950              />951            </Show>952            <Show when={restoreView() === "file"}>953              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>954                <ImportView955                  mode="onboarding"956                  replacesExistingVault={true}957                  onBack={() => setRestoreView(null)}958                  onImport={async () => {959                    setRestoreView(null);960                    await handleUnlock();961                  }}962                />963              </Suspense>964            </Show>965            </section>966          </Show>967        </Show>968      </Show>969      <Show when={showShortcutsHelp()}>970        <ShortcutsHelpOverlay971          bindings={shortcutBindings()}972          onClose={() => setShowShortcutsHelp(false)}973        />974      </Show>975    </div>976  );977}978979function ShortcutsHelpOverlay(props: {980  bindings: Record<ShortcutAction, Keybinding>;981  onClose: () => void;982}) {983  return (984    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>985      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>986        <div class="peach-shortcuts-help-head">987          <h3>Keyboard shortcuts</h3>988          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>989        </div>990        <div class="peach-shortcuts-help-body">991          <p class="peach-settings-sub-label">ENTRY VIEW</p>992          <ul>993            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (994              <li>995                <span>{d.label}</span>996                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>997              </li>998            ))}999          </ul>1000          <p class="peach-settings-sub-label">ANYWHERE</p>1001          <ul>1002            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1003              <li>1004                <span>{d.label}</span>1005                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1006              </li>1007            ))}1008          </ul>1009        </div>1010      </div>1011    </div>1012  );1013}