App.tsx

44.0 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 SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));28const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));29const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));3031type View =32  | "lock"33  | "pro-celebration"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 [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");177  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");178  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);179  const [lockOnClose, setLockOnClose] = createSignal(true);180  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);181  const [breachMonitoring, setBreachMonitoring] = createSignal(true);182  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);183  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);184  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);185  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);186  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);187  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");188  // Cached Pro status — synchronous for render paths. Background's189  // GET_LICENSE is async, but render-time reads of isPro() must not block.190  // Refreshed at boot, after activate/deactivate, and whenever the popup191  // re-opens onto a stored license that has changed via another window.192  const [proStatus, setProStatus] = createSignal(false);193  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);194  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);195  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");196  const [listSearchSeed, setListSearchSeed] = createSignal("");197  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);198  const [pendingCelebration, setPendingCelebration] = createSignal(false);199  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);200201  let contentPhaseTimer: number | undefined;202203  function applyAccent(name: AccentColorName) {204    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;205    const hex = color.hex;206    document.documentElement.style.setProperty("--peach-accent", hex);207    // Ambient surface variables — derived from the accent so surfaces shift208    // subtly toward the accent hue rather than staying fixed warm-brown.209    document.documentElement.style.setProperty("--peach-glow", hex + "2A");210    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");211    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");212  }213214  createEffect(() => {215    applyAccent(accentColor());216  });217218  createEffect(() => {219    document.documentElement.classList.toggle("light", theme() === "light");220    document.body.classList.toggle("light", theme() === "light");221  });222223  createEffect(() => {224    document.documentElement.setAttribute("data-display-font", displayFont());225  });226227  createEffect(() => {228    document.documentElement.setAttribute("data-text-size", textSize());229  });230231  createEffect(() => {232    if (reduceMotion()) {233      document.documentElement.setAttribute("data-motion", "reduce");234    } else {235      document.documentElement.removeAttribute("data-motion");236    }237  });238239  const selectedIndex = createMemo(() => {240    const currentId = selectedEntry()?.id;241    if (!currentId) return entries().length > 0 ? 0 : -1;242    return entries().findIndex((entry) => entry.id === currentId);243  });244245  async function applyAccentColor(name: AccentColorName) {246    applyAccent(name);247    setAccentColor(name);248    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });249  }250251  async function applyTheme(t: "dark" | "light") {252    setTheme(t);253    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });254  }255256  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {257    setDisplayFont(f);258    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });259  }260261  async function applyTextSize(size: "small" | "medium" | "large") {262    setTextSize(size);263    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });264  }265266  async function applyReduceMotion(enabled: boolean) {267    setReduceMotion(enabled);268    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });269  }270271  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload272  // small and lets future default updates land for actions the user hasn't273  // touched. Settings sends us the full active map; we filter and store.274  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {275    setShortcutBindings(active);276    const overrides: Record<string, Keybinding> = {};277    for (const action of Object.keys(active) as ShortcutAction[]) {278      const a = active[action];279      const d = DEFAULT_BINDINGS[action];280      const same = a.key === d.key281        && Boolean(a.ctrl)  === Boolean(d.ctrl)282        && Boolean(a.meta)  === Boolean(d.meta)283        && Boolean(a.shift) === Boolean(d.shift)284        && Boolean(a.alt)   === Boolean(d.alt);285      if (!same) overrides[action] = a;286    }287    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });288  }289290  async function applyLockOnClose(enabled: boolean) {291    setLockOnClose(enabled);292    await sendMessage({293      type: "UPDATE_SETTINGS",294      payload: { lockOnClose: enabled },295    });296  }297298  async function applyAutoLockMinutes(minutes: number) {299    setAutoLockMinutes(minutes);300    await sendMessage({301      type: "UPDATE_SETTINGS",302      payload: { autoLockMinutes: minutes },303    });304  }305306  async function applyBreachMonitoring(enabled: boolean) {307    setBreachMonitoring(enabled);308    await sendMessage({309      type: "UPDATE_SETTINGS",310      payload: { breachMonitoring: enabled },311    });312  }313314  onMount(async () => {315    // Resolve the active tab in parallel with the unlock/has-vault queries —316    // openVault()'s smart selection picks the entry matching currentTabDomain,317    // so it must be populated before openVault runs. Previously refreshCurrentTab318    // ran after openVault, leaving popups that booted already-unlocked falling319    // back to loadedEntries[0] instead of the domain match.320    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([321      sendMessage({ type: "IS_UNLOCKED" }),322      sendMessage({ type: "HAS_VAULT" }),323      refreshCurrentTab(),324      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),325    ]);326    const unlocked = Boolean(327      (unlockResponse as { ok: boolean; data?: boolean }).data328    );329    const vaultExists = Boolean(330      (vaultResponse as { ok: boolean; data?: boolean }).data331    );332    const shouldCelebrate = Boolean(333      (celebrationResponse as { ok: boolean; data?: boolean }).data334    );335    setHasVault(vaultExists);336    await Promise.all([restoreSettings(), refreshProStatus()]);337338    // Mark played before any animation so a crash mid-sequence never replays it339    if (shouldCelebrate) {340      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });341    }342343    if (unlocked && vaultExists) {344      await openVault(undefined, shouldCelebrate);345      if (shouldCelebrate) {346        setView("pro-celebration");347        window.setTimeout(() => setView("entry"), 2500);348      }349    } else if (shouldCelebrate) {350      setPendingCelebration(true);351    }352353    await refreshPendingPasskey();354355    // Track tab changes so smart sort stays current356    const handleTabActivated = () => { void refreshCurrentTab(); };357    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {358      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();359    };360    try {361      chrome.tabs.onActivated.addListener(handleTabActivated);362      chrome.tabs.onUpdated.addListener(handleTabUpdated);363      onCleanup(() => {364        chrome.tabs.onActivated.removeListener(handleTabActivated);365        chrome.tabs.onUpdated.removeListener(handleTabUpdated);366      });367    } catch {368      // tabs permission may not be available in all contexts369    }370371    setBootState("ready");372    document.getElementById("pre-lock")?.setAttribute("hidden", "true");373374    // Check for pending session-storage notices from the background.375    if (chrome.storage.session) {376      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as377        Record<string, { feature?: string } | undefined>;378      if (session.pendingProGate?.feature) {379        await chrome.storage.session.remove("pendingProGate");380        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);381        setSettingsInitialSection("license");382        setView("settings");383      } else if (session.pendingProNotice?.feature) {384        await chrome.storage.session.remove("pendingProNotice");385        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });386      }387    }388389    // Warm the lazy-module cache so the Suspense fallback never shows for390    // locally-bundled extension views. Without this, the first navigation to391    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which392    // covers the shell and absorbs clicks on the header.393    void Promise.all([394      import("./views/Settings").catch(() => {}),395      import("./views/Import").catch(() => {}),396      import("./views/Export").catch(() => {}),397      import("./views/Health").catch(() => {}),398      import("./views/TrashView").catch(() => {}),399    ]);400401    // Lock-on-close via a persistent port. sendMessage in pagehide is402    // unreliable — the popup context tears down before the message lands.403    // The SW's onConnect listener locks when this port disconnects.404    let popupPort: chrome.runtime.Port | null = null;405    try {406      popupPort = chrome.runtime.connect({ name: "popup" });407    } catch { /* extension context invalidated — ignore */ }408    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });409410    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale411    // entries instead of waiting for the next GET_ENTRIES round-trip.412    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {413      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();414      if (msg?.type === "PRO_GATE_TRIGGERED") {415        // Background never navigates UI directly — it asks; the popup decides.416        // Land on Settings → License with the triggering feature highlighted.417        setUpgradeHighlight(msg.payload?.feature ?? null);418        setSettingsInitialSection("license");419        setView("settings");420      }421    };422    chrome.runtime.onMessage.addListener(handleRuntimeMessage);423    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));424425    // Action handlers — keyed by ShortcutAction. The dispatcher below tests426    // each binding against the event and runs the matching handler. New427    // shortcuts only need an entry here; the binding is data, not code.428    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {429      copy_password: () => {430        const entry = selectedEntry();431        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });432      },433      copy_username: () => {434        const entry = selectedEntry();435        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });436      },437      copy_totp: () => {438        const entry = selectedEntry();439        if (!entry?.totp) return;440        try {441          const { code } = generateTOTP(entry.totp);442          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });443        } catch { /* invalid TOTP secret — silent */ }444      },445      new_entry: () => handleAdd(),446      edit_entry: () => {447        const entry = selectedEntry();448        if (!entry || entry.type === "passkey") return;449        setEditEntry(entry);450        setView("add");451      },452      delete_entry: () => {453        if (selectedEntry()) void handleDelete();454      },455      lock_vault: () => { void handleHeaderLock(); },456      search: () => openList(),457      nav_prev: () => navigate(-1),458      nav_next: () => navigate(1),459      jump_vault: () => setView("entry"),460      jump_settings: () => setView("settings"),461      show_help: () => setShowShortcutsHelp(true),462    };463464    // Actions that are MEANINGFUL only on the entry-detail view. Outside465    // that scope the binding is dormant — pressing C while on Settings466    // does nothing rather than awkwardly copying from a now-stale entry.467    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([468      "copy_password", "copy_username", "copy_totp",469      "edit_entry", "delete_entry", "nav_prev", "nav_next",470    ]);471472    const handleGlobalKeydown = (e: KeyboardEvent) => {473      const v = view();474      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"475        || (e.target as HTMLElement)?.tagName === "TEXTAREA"476        || (e.target as HTMLElement)?.isContentEditable;477      const isPrintableSearchKey =478        e.key.length === 1 &&479        !e.ctrlKey &&480        !e.metaKey &&481        !e.altKey;482483      // No input during the pro celebration sequence484      if (v === "pro-celebration") return;485486      // Help dialog: Escape closes it; eat the keypress so it doesn't487      // also navigate away from the underlying view.488      if (showShortcutsHelp()) {489        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }490        return;491      }492493      // ── Escape — fixed binding (not user-customizable) ───────494      if (e.key === "Escape") {495        if (v === "list") { setView("entry"); return; }496        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }497      }498499      // Bindings-driven dispatch. Single-key letter bindings without500      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is501      // inside an input, so users can type into search/forms normally.502      const bindings = shortcutBindings();503      for (const action of Object.keys(bindings) as ShortcutAction[]) {504        const binding = bindings[action];505        if (!matchKeybinding(e, binding)) continue;506        // Single-key letter bindings need the input-focus guard. Bindings507        // with any modifier are safe — Ctrl+L doesn't conflict with typing.508        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;509        if (!hasMod && binding.key.length === 1 && inInput) return;510        if (ENTRY_SCOPED.has(action) && v !== "entry") return;511        e.preventDefault();512        SHORTCUT_HANDLERS[action]?.();513        return;514      }515516      // Type-to-search: in entry view, any printable key not consumed by a517      // shortcut above primes the list search seed and opens the list.518      // Kept outside the bindings table because it's a behavior, not a519      // discrete action — every printable character can trigger it.520      if (v === "entry" && !inInput && isPrintableSearchKey) {521        e.preventDefault();522        primeListSearch(e.key);523        return;524      }525    };526    window.addEventListener("keydown", handleGlobalKeydown);527    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));528529    const handleStorageChanged = (530      changes: Record<string, chrome.storage.StorageChange>,531      areaName: string532    ) => {533      if (areaName !== "session") return;534      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {535        return;536      }537      void refreshPendingPasskey();538    };539540    chrome.storage.onChanged.addListener(handleStorageChanged);541    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));542  });543544  async function refreshCurrentTab() {545    try {546      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });547      const url = tab?.url ?? tab?.pendingUrl ?? "";548      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");549    } catch {550      setCurrentTabDomain("");551    }552  }553554  async function refreshPendingPasskey() {555    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });556    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);557  }558559  async function refreshProStatus() {560    const res = await sendMessage({ type: "GET_LICENSE" });561    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;562    setProStatus(Boolean(data?.valid && data?.plan === "pro"));563  }564565  async function restoreSettings() {566    const res = await sendMessage({ type: "GET_SETTINGS" });567    const s = (res as { ok: boolean; data?: any }).data ?? {};568    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {569      setAccentColor(s.accentColor as AccentColorName);570    }571    setTheme(s.theme === "light" ? "light" : "dark");572    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {573      setDisplayFont(s.displayFont);574    } else {575      setDisplayFont("cormorant-italic");576    }577    if (s.textSize === "small" || s.textSize === "large") {578      setTextSize(s.textSize);579    } else {580      setTextSize("medium");581    }582    setReduceMotion(s.reduceMotion === true);583    setLockOnClose(s.lockOnClose !== false);584    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);585    setBreachMonitoring(s.breachMonitoring !== false);586    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);587    setShortcutBindings(getActiveBindings(s.shortcuts));588  }589590  async function applyTrashRetention(days: number) {591    setTrashRetentionDays(days);592    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });593  }594595  function primeListSearch(seed: string) {596    setListSearchSeed(seed);597    setListSearchSeedNonce((value) => value + 1);598    openList();599  }600601  // Returns null when it detected a dead service worker and triggered handleLock().602  // Callers that need to abort (e.g. openVault) check for null rather than relying603  // on view() state, which may already be "lock" during normal startup flows.604  async function loadEntries(): Promise<VaultEntry[] | null> {605    const response = await sendMessage({ type: "GET_ENTRIES" });606    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };607608    // If the service worker was killed and restarted (MV3 workers sleep), the609    // vault will be locked again — or the worker may not respond at all.610    // In either case, send the user to the lock screen rather than silently611    // showing an empty vault (which looks like data loss).612    if (!res.ok) {613      if (614        res.error === "vault locked" ||615        res.error === "SERVICE_WORKER_UNAVAILABLE" ||616        (typeof res.error === "string" && res.error.includes("locked"))617      ) {618        handleLock();619        return null; // signal emergency lock to callers620      }621      return [];622    }623624    const loadedEntries = res.data ?? [];625    setEntries(loadedEntries);626627    const currentId = selectedEntry()?.id;628    if (currentId) {629      setSelectedEntry(630        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null631      );632    }633634    return loadedEntries;635  }636637  async function openVault(preferredEntryId?: string, skipViewSet = false) {638    // Purge expired trash entries on each vault open639    const retDays = trashRetentionDays();640    if (retDays > 0) {641      void sendMessage({642        type: "PURGE_EXPIRED_TRASH",643        payload: { retentionMs: retDays * 86_400_000 },644      });645    }646647    const loadedEntries = await loadEntries();648649    // null means loadEntries() triggered an emergency lock (service worker died).650    // Don't override it by setting view back to "entry" with an empty vault.651    if (loadedEntries === null) return;652653    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry654    let nextSelectedEntry: VaultEntry | null = null;655    if (preferredEntryId) {656      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;657    }658    if (!nextSelectedEntry) {659      const tabDomain = currentTabDomain();660      if (tabDomain) {661        nextSelectedEntry = loadedEntries.find((e) => {662          if (e.type === "login") {663            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;664            for (const extra of e.additionalUrls ?? []) {665              if ((extractDomain(extra) ?? "") === tabDomain) return true;666            }667            return false;668          }669          if (e.type === "passkey" && e.rpId) return e.rpId === tabDomain;670          return false;671        }) ?? null;672      }673    }674    nextSelectedEntry ??= loadedEntries[0] ?? null;675676    setSelectedEntry(nextSelectedEntry);677    setEditEntry(undefined);678    setContentTransitioning(false);679    setContentPhase("enter");680    queueContentIdle();681    if (!skipViewSet) setView("entry");682  }683684  async function handleUnlock() {685    setHasVault(true);686    triggerPipPulse();687    await restoreSettings();688    const celebrating = pendingCelebration();689    if (celebrating) {690      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });691      setPendingCelebration(false);692    }693    await openVault(undefined, celebrating);694    if (celebrating) {695      setView("pro-celebration");696      window.setTimeout(() => setView("entry"), 2500);697    }698  }699700  function handleSelectEntry(entry: VaultEntry) {701    setSelectedEntry(entry);702    setContentTransitioning(false);703    setContentPhase("enter");704    queueContentIdle();705    setView("entry");706  }707708  function handleAdd() {709    setEditEntry(undefined);710    setView("add");711  }712713  async function handleDelete() {714    const entry = selectedEntry();715    if (!entry) return;716    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });717    const loadedEntries = await loadEntries() ?? [];718    setSelectedEntry(loadedEntries[0] ?? null);719    setView("entry");720  }721722  async function handleDeleteMany(ids: string[]) {723    for (const id of ids) {724      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });725    }726    const loadedEntries = await loadEntries() ?? [];727    // If the currently selected entry was among the deleted, move to first728    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);729    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);730  }731732  async function handleSave(savedEntry?: VaultEntry) {733    await openVault(savedEntry?.id);734  }735736  function handleBack() {737    setEditEntry(undefined);738    setView("entry");739  }740741  function handleLock() {742    clearCanarySuppressions();743    setEntries([]);744    setSelectedEntry(null);745    setEditEntry(undefined);746    setContentPhase("idle");747    setView("lock");748  }749750  function handleHeaderLock() {751    // Lock the UI immediately — do not wait for the service worker. If the SW752    // is dead or slow, the 5s sendMessage timeout would create a dead-click753    // window. The SW will lock on its next wake regardless.754    handleLock();755    void sendMessage({ type: "LOCK" });756  }757758  function navigate(dir: number) {759    const allEntries = entries();760    if (allEntries.length === 0) return;761    const currentIndex = selectedIndex();762    const baseIndex = currentIndex >= 0 ? currentIndex : 0;763    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;764    setSelectedEntry(allEntries[nextIndex]);765    setContentPhase("enter");766    queueContentIdle();767  }768769  function openList() {770    setView("list");771  }772773  function openHealth() {774    setEditEntry(undefined);775    setView("health");776  }777778  function handleOpenFileImport() {779    setRestoreView("file");780  }781782  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;783784  function handleFixEntry(entry: VaultEntry) {785    if (entry.type === "passkey") {786      setSelectedEntry(entry);787      setView("entry");788      return;789    }790    setEditEntry(entry);791    setView("add");792  }793794  const isLockedView = () => view() === "lock";795  const selectedPasskeyEntry = createMemo(() =>796    selectedEntry()?.type === "passkey" ? (selectedEntry() as PasskeyEntry) : null797  );798799  async function handleApprovePendingPasskey() {800    const pending = pendingPasskey();801    if (!pending) return;802    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });803    setPendingPasskey(null);804  }805806  async function handleDenyPendingPasskey() {807    const pending = pendingPasskey();808    if (!pending) return;809    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });810    setPendingPasskey(null);811  }812813  function queueContentIdle(after?: () => void) {814    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);815    contentPhaseTimer = window.setTimeout(() => {816      setContentPhase("idle");817      after?.();818    }, ENTRY_TRANSITION_SETTLE_MS);819  }820821  return (822    <div class="popup-root peach-theme">823      <Show when={bootState() === "ready"}>824        <Show825          when={!pendingPasskey()}826          fallback={827            <PasskeyApprovalView828              type={pendingPasskey()!.type}829              rpName={pendingPasskey()!.rpName}830              rpId={pendingPasskey()!.rpId}831              userName={pendingPasskey()!.userName}832              userDisplayName={pendingPasskey()!.userDisplayName}833              onApprove={handleApprovePendingPasskey}834              onDeny={handleDenyPendingPasskey}835            />836          }837        >838          <Show839            when={!isLockedView()}840            fallback={841              <LockView842                hasVault={hasVault()}843                ready={bootState() === "ready"}844                isPro={proStatus()}845                onUnlock={handleUnlock}846              />847            }848          >849            <Show850              when={view() !== "pro-celebration"}851              fallback={<ProCelebration />}852            >853            <section854              id="hd-shell"855              class="peach-shell peach-theme"856              data-surface="extension"857            >858            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>859              <PeachWordmark unlocked />860              <div class="peach-chrome-actions">861                <button862                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"863                  onClick={() => setView("settings")}864                  aria-label="Settings"865                >866                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">867                    <path868                      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"869                      stroke="currentColor"870                      stroke-width="0.9"871                    />872                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />873                  </svg>874                </button>875                <button876                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"877                  onClick={handleAdd}878                  aria-label="New entry"879                >880                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">881                    <path d="M5.5 1v9M1 5.5h9" />882                  </svg>883                </button>884                <button885                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"886                  onClick={() => void handleHeaderLock()}887                  aria-label="Lock vault"888                >889                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">890                    <path891                      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"892                      stroke="currentColor"893                      stroke-width="1"894                      stroke-linecap="round"895                    />896                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />897                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />898                  </svg>899                </button>900              </div>901            </header>902903            <Show when={pendingProNotice() !== null}>904              <div class="peach-pro-notice-banner">905                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>906                <button907                  class="peach-pro-notice-link"908                  onClick={() => {909                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);910                    setSettingsInitialSection("license");911                    setView("settings");912                    setPendingProNotice(null);913                  }}914                >915                  Learn more →916                </button>917                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>918              </div>919            </Show>920921            <div class="peach-shell-body">922              <div class="peach-shell-veil"></div>923              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>924                <Show925                  when={selectedPasskeyEntry()}926                  fallback={927                    <EntryView928                      entry={selectedEntry()}929                      onDelete={handleDelete}930                      onFieldSaved={() => void loadEntries()}931                      onEscape={() => { setView("list"); }}932                    />933                  }934                >935                  <PasskeyEntryView entry={selectedPasskeyEntry()} onDelete={handleDelete} />936                </Show>937              </div>938939              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>940                <div class="peach-search-bar">941                  <span class="peach-search-icon">942                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">943                      <circle cx="5.5" cy="5.5" r="3.75" />944                      <path d="M8.75 8.75L11.5 11.5" />945                    </svg>946                  </span>947                  <input948                    class="peach-search-input"949                    placeholder="search vault..."950                    autocomplete="off"951                    aria-label="Search vault entries"952                    onClick={openList}953                    onFocus={openList}954                    readOnly955                  />956                  <div class="peach-search-meta">957                    <span class="peach-search-counter">958                      {entries().length > 0959                        ? `${selectedIndex() + 1} / ${entries().length}`960                        : "0 entries"}961                    </span>962                    <span class="peach-divider"></span>963                    <button964                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"965                      onClick={() => navigate(-1)}966                      aria-label="Previous entry"967                      disabled={entries().length === 0}968                    >969                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">970                        <path d="M5 1L1 5.5L5 10" />971                      </svg>972                    </button>973                    <button974                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"975                      onClick={() => navigate(1)}976                      aria-label="Next entry"977                      disabled={entries().length === 0}978                    >979                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">980                        <path d="M1 1L5 5.5L1 10" />981                      </svg>982                    </button>983                  </div>984                </div>985              </section>986            </div>987988            <Show when={view() === "list"}>989              <VaultView990                entries={entries()}991                selectedEntryId={selectedEntry()?.id}992                currentTabDomain={currentTabDomain()}993                sortOrder={sortOrder()}994                searchSeed={listSearchSeed()}995                searchSeedNonce={listSearchSeedNonce()}996                onSelectEntry={handleSelectEntry}997                onSortOrderChange={setSortOrder}998                onAdd={handleAdd}999                onClose={() => setView("entry")}1000                onOpenTrash={() => setView("trash")}1001                onDeleteMany={handleDeleteMany}1002              />1003            </Show>1004            <Show when={view() === "settings"}>1005              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1006                <SettingsView1007                  entriesCount={entries().length}1008                  breachMonitoring={breachMonitoring()}1009                  lockOnClose={lockOnClose()}1010                  autoLockMinutes={autoLockMinutes()}1011                  trashRetentionDays={trashRetentionDays()}1012                  theme={theme()}1013                  accentColor={accentColor()}1014                  displayFont={displayFont()}1015                  textSize={textSize()}1016                  reduceMotion={reduceMotion()}1017                  isPro={proStatus()}1018                  initialSection={settingsInitialSection()}1019                  upgradeHighlight={upgradeHighlight()}1020                  onBreachMonitoringChange={applyBreachMonitoring}1021                  onLockOnCloseChange={applyLockOnClose}1022                  onAutoLockMinutesChange={applyAutoLockMinutes}1023                  onTrashRetentionChange={applyTrashRetention}1024                  onThemeChange={applyTheme}1025                  onAccentChange={applyAccentColor}1026                  onDisplayFontChange={applyDisplayFont}1027                  onTextSizeChange={applyTextSize}1028                  onReduceMotionChange={applyReduceMotion}1029                  shortcuts={shortcutBindings()}1030                  onShortcutsChange={applyShortcuts}1031                  onLicenseChange={refreshProStatus}1032                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1033                  onImport={() => setView("import")}1034                  onExport={() => setView("export")}1035                  onBreachCheckDone={loadEntries}1036                  onOpenHealth={openHealth}1037                  onOpenFileImport={handleOpenFileImport}1038                />1039              </Suspense>1040            </Show>1041            <Show when={view() === "add"}>1042              <AddView1043                entry={editEntry()}1044                entries={entries()}1045                onBack={handleBack}1046                onSave={handleSave}1047              />1048            </Show>1049            <Show when={view() === "import"}>1050              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1051                <ImportView onBack={handleBack} onImport={handleSave} />1052              </Suspense>1053            </Show>1054            <Show when={view() === "export"}>1055              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1056                <ExportView onBack={handleBack} />1057              </Suspense>1058            </Show>1059            <Show when={view() === "health"}>1060              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1061                <HealthView1062                  entries={entries()}1063                  isPro={proStatus()}1064                  onFixEntry={handleFixEntry}1065                  onBack={() => setView("settings")}1066                  onRefresh={loadEntries}1067                />1068              </Suspense>1069            </Show>1070            <Show when={view() === "trash"}>1071              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1072                <TrashView1073                  onBack={() => setView("list")}1074                  onRestored={() => void loadEntries()}1075                />1076              </Suspense>1077            </Show>1078            <Show when={restoreView() === "file"}>1079              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1080                <ImportView1081                  mode="onboarding"1082                  replacesExistingVault={true}1083                  onBack={() => setRestoreView(null)}1084                  onImport={async () => {1085                    setRestoreView(null);1086                    await handleUnlock();1087                  }}1088                />1089              </Suspense>1090            </Show>1091            </section>1092            </Show>1093          </Show>1094        </Show>1095      </Show>1096      <Show when={showShortcutsHelp()}>1097        <ShortcutsHelpOverlay1098          bindings={shortcutBindings()}1099          onClose={() => setShowShortcutsHelp(false)}1100        />1101      </Show>1102    </div>1103  );1104}11051106function ShortcutsHelpOverlay(props: {1107  bindings: Record<ShortcutAction, Keybinding>;1108  onClose: () => void;1109}) {1110  return (1111    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1112      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1113        <div class="peach-shortcuts-help-head">1114          <h3>Keyboard shortcuts</h3>1115          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1116        </div>1117        <div class="peach-shortcuts-help-body">1118          <p class="peach-settings-sub-label">ENTRY VIEW</p>1119          <ul>1120            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1121              <li>1122                <span>{d.label}</span>1123                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1124              </li>1125            ))}1126          </ul>1127          <p class="peach-settings-sub-label">ANYWHERE</p>1128          <ul>1129            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1130              <li>1131                <span>{d.label}</span>1132                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1133              </li>1134            ))}1135          </ul>1136        </div>1137      </div>1138    </div>1139  );1140}