1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageRemove, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import { isPasskeyOnly } from "../shared/types";7import {8 hasCompletedInitialSync,9 INITIAL_SYNC_PENDING_DEVICE_KEY,10 type InitialSyncDevice,11} from "../shared/initial-sync";12import { LockView, RESTORE_SOURCE_STORAGE_KEY, type RestoreSource } from "./views/Lock";13import {14 ONBOARDING_CARD_STORAGE_KEY,15 ONBOARDING_LAST_CARD,16 Onboarding,17} from "./views/Onboarding";1819const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";20import { NotesMode } from "./views/NotesMode";21import { ProCelebration } from "./views/ProCelebration";22import { InitialSyncView } from "./views/InitialSyncView";23import { VaultView, type SortOrder } from "./views/Vault";24import { EntryView } from "./views/Entry";25import { AddView } from "./views/Add";26import { PeachWordmark } from "./components/PeachMark";27import { PasskeyApprovalView } from "./views/PasskeyApproval";28import { extractDomain } from "../shared/domain";29import {30 syncIndicator,31 syncIndicatorLabel,32 type SyncOutcomeSummary,33} from "../shared/sync-outcome";34import { popupCopy } from "./copy";35import {36 DEFAULT_BINDINGS,37 formatKeybinding,38 getActiveBindings,39 matchKeybinding,40 SHORTCUT_DESCRIPTORS,41 type Keybinding,42 type ShortcutAction,43} from "../shared/shortcuts";44import { generateTOTP } from "../crypto/totp";4546export { sendMessage } from "../shared/bridge";4748const ImportView = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));49const ExportView = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));50const SettingsView = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));51const HealthView = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));52const TrashView = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));53const PanicView = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));54const PairDeviceView = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));55const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));56const CodexRestoreView = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));57const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));5859type View =60 | "lock"61 | "pro-celebration"62 | "entry"63 | "list"64 | "add"65 | "settings"66 | "pair-device"67 | "import"68 | "export"69 | "health"70 | "trash"71 | "panic"72 | "adopting"73 | "initial-sync"74 | "codex-generate"75 | "codex-restore";76type BootState = "loading" | "ready";7778const INITIAL_SYNC_POLL_MS = 500;79const INITIAL_SYNC_SLOW_MS = 15_000;8081let shellRingAnimation: Animation | null = null;8283export function triggerRing() {84 const shell = document.getElementById("hd-shell");85 if (!shell) return;8687 shellRingAnimation?.cancel();88 shell.dataset.glowing = "true";89 const animation = shell.animate(90 [91 { offset: 0, boxShadow: "var(--copy-shadow)" },92 {93 offset: 0.3,94 boxShadow:95 "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)",96 },97 { offset: 1, boxShadow: "var(--copy-shadow)" },98 ],99 {100 duration: 720,101 easing: "cubic-bezier(0.4, 0, 0.2, 1)",102 fill: "none",103 }104 );105 shellRingAnimation = animation;106 const clearGlow = () => {107 if (shellRingAnimation !== animation) return;108 shellRingAnimation = null;109 delete shell.dataset.glowing;110 };111 animation.onfinish = clearGlow;112 animation.oncancel = clearGlow;113}114115export function triggerPipPulse() {116 const pip = document.querySelector(".peach-status-pip, .pip");117 if (pip) {118 pip.classList.remove("pulse");119 void (pip as HTMLElement).offsetWidth;120 pip.classList.add("pulse");121 }122}123124const ENTRY_TRANSITION_SETTLE_MS = 135;125126export default function App() {127 const [bootState, setBootState] = createSignal<BootState>("loading");128 const [view, setView] = createSignal<View>("lock");129 const [contentPhase, setContentPhase] = createSignal<"enter" | "idle">("enter");130 const [hasVault, setHasVault] = createSignal(false);131 const [onboarded, setOnboarded] = createSignal(true);132 const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);133 134 135 136 const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);137 138 139 140 const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);141 const [entries, setEntries] = createSignal<VaultEntry[]>([]);142 const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);143 const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);144145 146 interface SyncAlert {147 type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";148 entryId: string;149 entryTitle: string;150 deviceName: string;151 timestamp: number;152 }153 const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);154 155 const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});156 async function loadSyncAlerts() {157 const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {158 ok: boolean;159 data?: SyncAlert[];160 };161 if (r.ok && (r.data?.length ?? 0) > 0) {162 setSyncAlerts(r.data ?? []);163 164 165 void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });166 }167 }168 function dismissAlertGroup(type: string) {169 setSyncAlerts((arr) => arr.filter((a) => a.type !== type));170 setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });171 }172 function flipAlert(type: string, dir: 1 | -1) {173 const group = syncAlerts().filter((a) => a.type === type);174 if (group.length <= 1) return;175 setAlertFlipIdx((m) => {176 const cur = m[type] ?? 0;177 return { ...m, [type]: (cur + dir + group.length) % group.length };178 });179 }180 181 const alertGroups = createMemo(() => {182 const map = new Map<string, SyncAlert[]>();183 for (const a of syncAlerts()) {184 const g = map.get(a.type);185 if (g) g.push(a); else map.set(a.type, [a]);186 }187 return [...map.entries()];188 });189 function syncAlertText(a: SyncAlert): string {190 if (a.type === "DEVICE_REVOKED") {191 return `${a.deviceName} revoked a paired device — review your devices in Settings`;192 }193 return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;194 }195 const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");196 const [theme, setTheme] = createSignal<"dark" | "light">("dark");197 const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");198 const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);199 const [lockOnClose, setLockOnClose] = createSignal(false);200 const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);201 const [breachMonitoring, setBreachMonitoring] = createSignal(true);202 const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);203 const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);204 const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);205 const [restoreView, setRestoreView] = createSignal<"file" | null>(null);206 const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);207 const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");208 const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");209 210 211 212 213 const [proStatus, setProStatus] = createSignal(false);214 const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);215 216 217 const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");218 const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);219 const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");220 const [listSearchSeed, setListSearchSeed] = createSignal("");221 const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);222 const [pendingCelebration, setPendingCelebration] = createSignal(false);223 const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);224 225 226 227 const [pendingRememberSite, setPendingRememberSite] = createSignal<{228 entryId: string;229 url: string;230 title: string;231 } | null>(null);232 233 234 235 const [returnToPanic, setReturnToPanic] = createSignal(false);236 237 238 const [editBackView, setEditBackView] = createSignal<View>("entry");239 const [settingsExiting, setSettingsExiting] = createSignal(false);240 const [showNotes, setShowNotes] = createSignal(false);241 242 243 244 const [syncBusy, setSyncBusy] = createSignal(false);245 const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);246 247 248 const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});249 const [pairedCount, setPairedCount] = createSignal(0);250 const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);251 const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);252 let initialSyncWaitGeneration = 0;253 const syncLight = () =>254 syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());255 const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());256 async function loadSyncIndicator() {257 const [stateRes, devicesRes] = await Promise.all([258 sendMessage({ type: "GET_SYNC_STATE" }),259 sendMessage({ type: "LIST_PAIRED_DEVICES" }),260 ]);261 const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };262 if (s.ok && s.data) setSyncSummary(s.data);263 const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };264 if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);265 }266267 interface InitialSyncPairedDevice extends InitialSyncDevice {268 pairedAt?: number;269 }270271 async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {272 const response = (await sendMessage({273 type: "LIST_PAIRED_DEVICES",274 })) as {275 ok: boolean;276 data?: { devices?: InitialSyncPairedDevice[] };277 };278 return response.ok ? response.data?.devices ?? [] : [];279 }280281 async function resolveInitialSyncDeviceId(): Promise<string | null> {282 const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(283 () => null,284 );285 const devices = await listInitialSyncDevices().catch(() => []);286 if (stored && devices.some((device) => device.deviceId === stored)) {287 return stored;288 }289290 291 292 const newest = [...devices].sort(293 (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),294 )[0];295 if (!newest) return stored;296 await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(297 () => undefined,298 );299 return newest.deviceId;300 }301302 async function finishInitialSync(generation: number): Promise<void> {303 if (generation !== initialSyncWaitGeneration) return;304 await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);305 setInitialSyncDeviceId(null);306 setInitialSyncSlow(false);307 await refreshProStatus();308309 310 311 312 const celebration = (await sendMessage({313 type: "SHOULD_PLAY_CELEBRATION",314 })) as { ok: boolean; data?: boolean };315 const shouldCelebrate = celebration.ok && celebration.data === true;316 if (shouldCelebrate) {317 await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });318 }319320 const opened = await openVault(undefined, shouldCelebrate);321 if (!opened || generation !== initialSyncWaitGeneration) return;322 if (shouldCelebrate) {323 setView("pro-celebration");324 window.setTimeout(() => {325 if (generation === initialSyncWaitGeneration) setView("entry");326 }, 2500);327 }328 }329330 async function beginInitialSyncWait(deviceId: string): Promise<void> {331 const generation = ++initialSyncWaitGeneration;332 setInitialSyncDeviceId(deviceId);333 setInitialSyncSlow(false);334 setView("initial-sync");335 const startedAt = Date.now();336337 338 339 void sendMessage({340 type: "TRIGGER_SYNC",341 payload: { reason: "foreground" },342 }).catch(() => undefined);343344 while (345 generation === initialSyncWaitGeneration &&346 view() === "initial-sync"347 ) {348 try {349 const devices = await listInitialSyncDevices();350 if (hasCompletedInitialSync(devices, deviceId)) {351 await finishInitialSync(generation);352 return;353 }354 } catch {355 356 }357 if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {358 setInitialSyncSlow(true);359 }360 await new Promise((resolve) =>361 window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),362 );363 }364 }365366 async function retryInitialSync(): Promise<void> {367 const deviceId =368 initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());369 if (deviceId) {370 await beginInitialSyncWait(deviceId);371 } else {372 setInitialSyncSlow(true);373 }374 }375376 const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);377 378 379 380 381 const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);382383 let contentPhaseTimer: number | undefined;384 385 386 let openedForInlineUnlock = false;387388 onCleanup(() => {389 initialSyncWaitGeneration += 1;390 });391392 function applyAccent(name: AccentColorName) {393 const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;394 const hex = color.hex;395 document.documentElement.style.setProperty("--peach-accent", hex);396 397 document.documentElement.style.setProperty("--peach-glow", hex + "2A");398 document.documentElement.style.setProperty("--peach-border-accent", hex + "24");399 }400401 createEffect(() => {402 applyAccent(accentColor());403 });404405 createEffect(() => {406 document.documentElement.classList.toggle("light", theme() === "light");407 document.body.classList.toggle("light", theme() === "light");408 });409410 createEffect(() => {411 document.documentElement.setAttribute("data-text-size", textSize());412 });413414 createEffect(() => {415 if (reduceMotion()) {416 document.documentElement.setAttribute("data-motion", "reduce");417 } else {418 document.documentElement.removeAttribute("data-motion");419 }420 });421422 423 424 425 426 427 const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));428429 const selectedIndex = createMemo(() => {430 const currentId = selectedEntry()?.id;431 if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;432 return nonNoteEntries().findIndex((entry) => entry.id === currentId);433 });434435 async function applyAccentColor(name: AccentColorName) {436 applyAccent(name);437 setAccentColor(name);438 await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });439 }440441 async function applyTheme(t: "dark" | "light") {442 setTheme(t);443 await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });444 }445446 async function applyTextSize(size: "small" | "medium" | "large") {447 setTextSize(size);448 await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });449 }450451 async function applyReduceMotion(enabled: boolean) {452 setReduceMotion(enabled);453 await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });454 }455456 457 458 459 async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {460 setShortcutBindings(active);461 const overrides: Record<string, Keybinding> = {};462 for (const action of Object.keys(active) as ShortcutAction[]) {463 const a = active[action];464 const d = DEFAULT_BINDINGS[action];465 const same = a.key === d.key466 && Boolean(a.ctrl) === Boolean(d.ctrl)467 && Boolean(a.meta) === Boolean(d.meta)468 && Boolean(a.shift) === Boolean(d.shift)469 && Boolean(a.alt) === Boolean(d.alt);470 if (!same) overrides[action] = a;471 }472 await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });473 }474475 async function applyLockOnClose(enabled: boolean) {476 setLockOnClose(enabled);477 await sendMessage({478 type: "UPDATE_SETTINGS",479 payload: { lockOnClose: enabled },480 });481 }482483 async function applyAutoLockMinutes(minutes: number) {484 setAutoLockMinutes(minutes);485 await sendMessage({486 type: "UPDATE_SETTINGS",487 payload: { autoLockMinutes: minutes },488 });489 }490491 async function applyBreachMonitoring(enabled: boolean) {492 setBreachMonitoring(enabled);493 await sendMessage({494 type: "UPDATE_SETTINGS",495 payload: { breachMonitoring: enabled },496 });497 }498499 500 501 502 function markOnboardingExit(flow: "create" | "restore" | "adopt") {503 setOnboardingCardAtExit(ONBOARDING_LAST_CARD);504 void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});505 506 507 void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});508 }509 function clearOnboardingExit() {510 void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});511 void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});512 setResumeRestoreSource(null);513 }514515 onMount(async () => {516 517 518 519 520 521 const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([522 sendMessage({ type: "IS_UNLOCKED" }),523 sendMessage({ type: "HAS_VAULT" }),524 refreshCurrentTab(),525 sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),526 ]);527 const unlocked = Boolean(528 (unlockResponse as { ok: boolean; data?: boolean }).data529 );530 const vaultExists = Boolean(531 (vaultResponse as { ok: boolean; data?: boolean }).data532 );533 const shouldCelebrate = Boolean(534 (celebrationResponse as { ok: boolean; data?: boolean }).data535 );536 setHasVault(vaultExists);537 538 539 540 try {541 const onboarded = await storageGet("peach_onboarded");542 const seen = onboarded === "true";543 if (vaultExists && !seen) {544 await storageSet("peach_onboarded", "true");545 await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});546 await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});547 await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});548 setOnboarded(true);549 } else {550 setOnboarded(seen);551 if (!seen) {552 553 554 555 const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);556 if (exit === "create" || exit === "restore" || exit === "adopt") {557 setOnboardingCardAtExit(ONBOARDING_LAST_CARD);558 setOnboarded(true);559 setStartOnboardingRestore(exit === "restore");560 if (exit === "restore") {561 562 563 const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);564 if (source === "symbols" || source === "codex" || source === "csv") {565 setResumeRestoreSource(source);566 }567 }568 if (exit === "adopt") setView("adopting");569 } else {570 571 572 const stored = Number(573 await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),574 );575 if (576 Number.isInteger(stored) &&577 stored > 0 &&578 stored <= ONBOARDING_LAST_CARD579 ) {580 setOnboardingCardAtExit(stored);581 }582 }583 }584 }585 } catch {586 587 setOnboarded(true);588 }589590 591 592 593 594 595 try {596 const restoreRoute = new URLSearchParams(window.location.search).get("restore");597 if (restoreRoute === "peachscript" || restoreRoute === "csv") {598 setOnboarded(true);599 setStartOnboardingRestore(true);600 setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");601 }602 } catch {603 604 }605606 await Promise.all([restoreSettings(), refreshProStatus()]);607608 const pendingInitialSyncMarker =609 unlocked && vaultExists610 ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)611 : null;612 const pendingInitialSyncDeviceId = pendingInitialSyncMarker613 ? await resolveInitialSyncDeviceId()614 : null;615616 617 618 619 if (shouldCelebrate && !pendingInitialSyncDeviceId) {620 await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });621 }622623 624 625 if (unlocked && vaultExists) {626 void sendMessage({627 type: "TRIGGER_SYNC",628 payload: { reason: "foreground" },629 });630 void loadSyncIndicator();631 632 void loadSyncAlerts();633 }634635 636 637 638 639 640 let recoveryPending = false;641 try {642 const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });643 recoveryPending = out.ok === true && out.data === true;644 } catch { }645646 647 648 let pendingOpenEntryId: string | undefined;649 if (chrome.storage.session) {650 try {651 const s = await chrome.storage.session.get(["peach_inline_unlock", "peach_open_entry"]);652 const pending = s as { peach_inline_unlock?: boolean; peach_open_entry?: string };653 if (pending.peach_inline_unlock) {654 openedForInlineUnlock = true;655 }656 if (typeof pending.peach_open_entry === "string") pendingOpenEntryId = pending.peach_open_entry;657 await chrome.storage.session.remove(["peach_inline_unlock", "peach_open_entry"]);658 } catch { }659 }660661 if (recoveryPending && unlocked) {662 663 664 setForceRecoveryWords(true);665 setView("lock");666 } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {667 void beginInitialSyncWait(pendingInitialSyncDeviceId);668 } else if (unlocked && vaultExists) {669 await openVault(pendingOpenEntryId, shouldCelebrate);670 if (shouldCelebrate) {671 setView("pro-celebration");672 window.setTimeout(() => setView("entry"), 2500);673 }674 } else if (shouldCelebrate) {675 setPendingCelebration(true);676 }677678 await refreshPendingPasskey();679680 681 const handleTabActivated = () => { void refreshCurrentTab(); };682 const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {683 if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();684 };685 try {686 chrome.tabs.onActivated.addListener(handleTabActivated);687 chrome.tabs.onUpdated.addListener(handleTabUpdated);688 onCleanup(() => {689 chrome.tabs.onActivated.removeListener(handleTabActivated);690 chrome.tabs.onUpdated.removeListener(handleTabUpdated);691 });692 } catch {693 694 }695696 setBootState("ready");697698 699 700 701 702 try {703 const route = new URLSearchParams(window.location.search).get("codex");704 if (route === "pdf" || route === "restore") {705 setView("codex-restore");706 }707 } catch {708 709 }710711 712 if (chrome.storage.session) {713 const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as714 Record<string, { feature?: string } | undefined>;715 if (session.pendingProGate?.feature) {716 await chrome.storage.session.remove("pendingProGate");717 setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);718 setSettingsInitialSection("license");719 setView("settings");720 } else if (session.pendingProNotice?.feature) {721 await chrome.storage.session.remove("pendingProNotice");722 setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });723 }724 const remembered = (await chrome.storage.session.get("pendingRememberSite")) as {725 pendingRememberSite?: { entryId?: unknown; url?: unknown };726 };727 const request = remembered.pendingRememberSite;728 if (729 typeof request?.entryId === "string" &&730 typeof request.url === "string"731 ) {732 const entry = await sendMessage({ type: "GET_ENTRIES" });733 const match = entry.ok734 ? (entry.data as Array<{ id: string; title?: string }> | undefined)?.find(735 (candidate) => candidate.id === request.entryId,736 )737 : undefined;738 if (match) {739 let host = request.url;740 try { host = new URL(request.url).hostname; } catch { }741 setPendingRememberSite({ entryId: request.entryId, url: request.url, title: match.title ?? host });742 } else {743 await chrome.storage.session.remove("pendingRememberSite");744 }745 }746 }747748 749 750 751 752 void Promise.all([753 import("./views/Settings").catch(() => {}),754 import("./views/Import").catch(() => {}),755 import("./views/Export").catch(() => {}),756 import("./views/Health").catch(() => {}),757 import("./views/TrashView").catch(() => {}),758 ]);759760 761 762 763 let popupPort: chrome.runtime.Port | null = null;764 try {765 766 767 768 popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });769 } catch { }770 onCleanup(() => { try { popupPort?.disconnect(); } catch {} });771772 773 774 const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {775 if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();776 if (msg?.type === "SYNC_STATE_CHANGED") {777 setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);778 }779 if (msg?.type === "PRO_GATE_TRIGGERED") {780 setUpgradeHighlight(msg.payload?.feature ?? null);781 setSettingsInitialSection("license");782 setView("settings");783 }784 };785 chrome.runtime.onMessage.addListener(handleRuntimeMessage);786 onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));787788 789 790 791 const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {792 copy_password: () => {793 const entry = selectedEntry();794 if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });795 },796 copy_username: () => {797 const entry = selectedEntry();798 if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });799 },800 copy_totp: () => {801 const entry = selectedEntry();802 if (!entry?.totp) return;803 try {804 const { code } = generateTOTP(805 entry.totp,806 entry.totpAlgorithm,807 entry.totpDigits,808 entry.totpPeriod,809 );810 void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });811 } catch { }812 },813 new_entry: () => handleAdd(),814 edit_entry: () => {815 const entry = selectedEntry();816 817 818 if (!entry || isPasskeyOnly(entry)) return;819 setEditEntry(entry);820 setView("add");821 },822 delete_entry: () => {823 if (selectedEntry()) void handleDelete();824 },825 lock_vault: () => { void handleHeaderLock(); },826 search: () => openList(),827 nav_prev: () => navigate(-1),828 nav_next: () => navigate(1),829 jump_vault: () => setView("entry"),830 jump_settings: () => setView("settings"),831 show_help: () => setShowShortcutsHelp(true),832 };833834 835 836 837 const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([838 "copy_password", "copy_username", "copy_totp",839 "edit_entry", "delete_entry", "nav_prev", "nav_next",840 ]);841842 const handleGlobalKeydown = (e: KeyboardEvent) => {843 const v = view();844 const inInput = (e.target as HTMLElement)?.tagName === "INPUT"845 || (e.target as HTMLElement)?.tagName === "TEXTAREA"846 || (e.target as HTMLElement)?.isContentEditable;847 const isPrintableSearchKey =848 e.key.length === 1 &&849 !e.ctrlKey &&850 !e.metaKey &&851 !e.altKey;852853 854 855 856 857 858 if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;859860 861 862 if (showShortcutsHelp()) {863 if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }864 return;865 }866867 868 if (e.key === "Escape") {869 if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }870 if (v === "list") { setView("entry"); return; }871 if (v === "settings" || v === "add") { handleBack(); return; }872 if (v === "import" || v === "health") { setView("settings"); return; }873 if (v === "export") { handleExportBack(); return; }874 if (v === "pair-device") { setView("settings"); return; }875 }876877 878 879 880 const bindings = shortcutBindings();881 for (const action of Object.keys(bindings) as ShortcutAction[]) {882 const binding = bindings[action];883 if (!matchKeybinding(e, binding)) continue;884 885 886 const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;887 if (!hasMod && binding.key.length === 1 && inInput) return;888 if (ENTRY_SCOPED.has(action) && v !== "entry") return;889 e.preventDefault();890 SHORTCUT_HANDLERS[action]?.();891 return;892 }893894 895 896 897 898 if (v === "entry" && !inInput && isPrintableSearchKey) {899 e.preventDefault();900 primeListSearch(e.key);901 return;902 }903 };904 window.addEventListener("keydown", handleGlobalKeydown);905 onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));906907 const handleStorageChanged = (908 changes: Record<string, chrome.storage.StorageChange>,909 areaName: string910 ) => {911 if (areaName !== "session") return;912 if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {913 return;914 }915 void refreshPendingPasskey();916 };917 chrome.storage.onChanged.addListener(handleStorageChanged);918 onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));919 });920921 async function refreshCurrentTab() {922 try {923 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });924 const url = tab?.url ?? tab?.pendingUrl ?? "";925 setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");926 927 928 const isWebUrl = /^https?:\/\//i.test(url);929 setCurrentTabUrl(isWebUrl ? url : "");930 } catch {931 setCurrentTabDomain("");932 setCurrentTabUrl("");933 }934 }935936 async function refreshPendingPasskey() {937 const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });938 setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);939 }940941 async function refreshProStatus() {942 const res = await sendMessage({ type: "GET_LICENSE" });943 const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;944 setProStatus(Boolean(data?.valid && data?.plan === "pro"));945 }946947 async function restoreSettings() {948 const res = await sendMessage({ type: "GET_SETTINGS" });949 const s = (res as { ok: boolean; data?: any }).data ?? {};950 if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {951 setAccentColor(s.accentColor as AccentColorName);952 }953 setTheme(s.theme === "light" ? "light" : "dark");954 if (s.textSize === "small" || s.textSize === "large") {955 setTextSize(s.textSize);956 } else {957 setTextSize("medium");958 }959 setReduceMotion(s.reduceMotion === true);960 setLockOnClose(s.lockOnClose === true);961 setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);962 setBreachMonitoring(s.breachMonitoring !== false);963 setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);964 setShortcutBindings(getActiveBindings(s.shortcuts));965 }966967 async function applyTrashRetention(days: number) {968 setTrashRetentionDays(days);969 await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });970 }971972 function primeListSearch(seed: string) {973 setListSearchSeed(seed);974 setListSearchSeedNonce((value) => value + 1);975 openList();976 }977978 979 980 981 async function loadEntries(): Promise<VaultEntry[] | null> {982 const response = await sendMessage({ type: "GET_ENTRIES" });983 const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };984985 986 987 988 989 if (!res.ok) {990 if (991 res.error === "vault_locked" ||992 res.error === "SERVICE_WORKER_UNAVAILABLE" ||993 (typeof res.error === "string" && res.error.includes("locked"))994 ) {995 handleLock();996 return null; 997 }998 return [];999 }10001001 const loadedEntries = res.data ?? [];1002 setEntries(loadedEntries);10031004 const currentId = selectedEntry()?.id;1005 if (currentId) {1006 setSelectedEntry(1007 loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1008 );1009 }10101011 return loadedEntries;1012 }10131014 async function openVault(preferredEntryId?: string, skipViewSet = false) {1015 1016 const retDays = trashRetentionDays();1017 if (retDays > 0) {1018 void sendMessage({1019 type: "PURGE_EXPIRED_TRASH",1020 payload: { retentionMs: retDays * 86_400_000 },1021 });1022 }10231024 const loadedEntries = await loadEntries();10251026 1027 1028 if (loadedEntries === null) return false;10291030 1031 let nextSelectedEntry: VaultEntry | null = null;1032 if (preferredEntryId) {1033 nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1034 }1035 if (!nextSelectedEntry) {1036 const tabDomain = currentTabDomain();1037 if (tabDomain) {1038 nextSelectedEntry = loadedEntries.find((e) => {1039 if (e.type === "login") {1040 if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1041 for (const extra of e.additionalUrls ?? []) {1042 if ((extractDomain(extra) ?? "") === tabDomain) return true;1043 }1044 return false;1045 }1046 if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1047 return false;1048 }) ?? null;1049 }1050 }1051 nextSelectedEntry ??= pickNavigable(loadedEntries);10521053 setSelectedEntry(nextSelectedEntry);1054 setEditEntry(undefined);1055 setContentPhase("enter");1056 queueContentIdle();1057 if (!skipViewSet) setView("entry");1058 return true;1059 }10601061 async function handleUnlock() {1062 1063 1064 1065 1066 1067 1068 let recoveryPending = false;1069 try {1070 const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1071 recoveryPending = out.ok === true && out.data === true;1072 } catch { }1073 if (recoveryPending) {1074 setForceRecoveryWords(true);1075 setView("lock");1076 triggerPipPulse();1077 await restoreSettings();1078 return;1079 }1080 setHasVault(true);1081 triggerPipPulse();1082 await restoreSettings();1083 const celebrating = pendingCelebration();1084 if (celebrating) {1085 await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1086 setPendingCelebration(false);1087 }1088 await openVault(undefined, celebrating);1089 if (celebrating) {1090 setView("pro-celebration");1091 window.setTimeout(() => setView("entry"), 2500);1092 }1093 1094 1095 if (openedForInlineUnlock) {1096 openedForInlineUnlock = false;1097 window.close();1098 }1099 }11001101 function handleSelectEntry(entry: VaultEntry) {1102 if (entry.type === "note") {1103 setOpenNoteId(entry.id);1104 setShowNotes(true);1105 return;1106 }1107 setSelectedEntry(entry);1108 setContentPhase("enter");1109 queueContentIdle();1110 setView("entry");1111 }11121113 function handleAdd() {1114 setEditEntry(undefined);1115 setView("add");1116 }11171118 async function handleDelete() {1119 const entry = selectedEntry();1120 if (!entry) return;1121 await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1122 const loadedEntries = await loadEntries() ?? [];1123 setSelectedEntry(pickNavigable(loadedEntries));1124 setView("entry");1125 }11261127 async function handleDeleteMany(ids: string[]) {1128 for (const id of ids) {1129 await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1130 }1131 const loadedEntries = await loadEntries() ?? [];1132 1133 const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1134 if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1135 }11361137 async function handleSave(savedEntry?: VaultEntry) {1138 await openVault(savedEntry?.id);1139 }11401141 function handleBack() {1142 const dest = editBackView();1143 setEditBackView("entry");1144 setEditEntry(undefined);1145 setView(dest);1146 }11471148 function handleExportBack() {1149 if (returnToPanic()) {1150 setReturnToPanic(false);1151 setView("panic");1152 return;1153 }1154 setView("settings");1155 }11561157 function handleLock() {1158 setEntries([]);1159 setSelectedEntry(null);1160 setEditEntry(undefined);1161 setContentPhase("idle");1162 setView("lock");1163 }11641165 function handleHeaderLock() {1166 1167 1168 1169 handleLock();1170 void sendMessage({ type: "LOCK" });1171 }11721173 1174 1175 1176 async function handleHeaderSync(): Promise<void> {1177 if (syncBusy()) return;1178 setSyncBusy(true);1179 setSyncFlash(null);1180 try {1181 await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1182 let state: SyncOutcomeSummary = { status: "syncing" };1183 for (let i = 0; i < 40 && state.status === "syncing"; i++) {1184 await new Promise((r) => setTimeout(r, 250));1185 const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1186 ok: boolean;1187 data?: SyncOutcomeSummary;1188 };1189 state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1190 }1191 setSyncSummary(state);1192 setSyncFlash(state.status === "error" ? "error" : "ok");1193 await loadSyncAlerts();1194 await loadEntries();1195 await loadSyncIndicator();1196 } catch {1197 setSyncSummary({ status: "error", outcome: "run_failed" });1198 setSyncFlash("error");1199 } finally {1200 setSyncBusy(false);1201 setTimeout(() => setSyncFlash(null), 2_000);1202 }1203 }12041205 function navigate(dir: number) {1206 const navigable = nonNoteEntries();1207 if (navigable.length === 0) return;1208 const currentIndex = selectedIndex();1209 const baseIndex = currentIndex >= 0 ? currentIndex : 0;1210 const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1211 setSelectedEntry(navigable[nextIndex]);1212 setContentPhase("enter");1213 queueContentIdle();1214 }12151216 121712181219122012211222 function pickNavigable(list: VaultEntry[]): VaultEntry | null {1223 return list.find((e) => e.type !== "note") ?? null;1224 }12251226 function openList() {1227 setView("list");1228 }12291230 function openHealth() {1231 setEditEntry(undefined);1232 setView("health");1233 }12341235 function handleOpenFileImport() {1236 setRestoreView("file");1237 }12381239 const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12401241 function handleFixEntry(entry: VaultEntry) {1242 setSelectedEntry(entry);1243 1244 1245 if (isPasskeyOnly(entry)) {1246 setView("entry");1247 return;1248 }1249 setEditBackView(view()); 1250 setEditEntry(entry);1251 setView("add");1252 }12531254 const isLockedView = () => view() === "lock" || view() === "adopting";12551256 async function handleAdoptionDone() {1257 await storageSet("peach_onboarded", "true").catch(() => {});1258 await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1259 clearOnboardingExit();1260 setOnboarded(true);1261 setHasVault(true);1262 setView("initial-sync");1263 1264 1265 1266 await refreshProStatus();1267 const deviceId = await resolveInitialSyncDeviceId();1268 if (deviceId) {1269 void beginInitialSyncWait(deviceId);1270 } else {1271 1272 1273 1274 setInitialSyncSlow(true);1275 }1276 }12771278 async function handleApprovePendingPasskey() {1279 const pending = pendingPasskey();1280 if (!pending) return;1281 if (pending.browser === "firefox" && pending.type === "create") {1282 1283 1284 1285 1286 const { createFirefoxPasskey } = await import("./firefox-passkey");1287 const result = await createFirefoxPasskey(pending);1288 if (!result.ok) {1289 console.warn("Peach Firefox passkey create failed:", result.error);1290 }1291 await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1292 setPendingPasskey(null);1293 void loadEntries();1294 window.close();1295 return;1296 }1297 await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1298 window.close();1299 }13001301 async function handleDenyPendingPasskey() {1302 const pending = pendingPasskey();1303 if (!pending) return;1304 await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1305 window.close();1306 }13071308 function queueContentIdle(after?: () => void) {1309 if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1310 contentPhaseTimer = window.setTimeout(() => {1311 setContentPhase("idle");1312 after?.();1313 }, ENTRY_TRANSITION_SETTLE_MS);1314 }13151316 return (1317 <div class="popup-root peach-theme">1318 <Show when={bootState() === "ready"}>1319 <Show1320 when={!pendingPasskey()}1321 fallback={1322 <PasskeyApprovalView1323 type={pendingPasskey()!.type}1324 rpName={pendingPasskey()!.rpName}1325 rpId={pendingPasskey()!.rpId}1326 userName={pendingPasskey()!.userName}1327 userDisplayName={pendingPasskey()!.userDisplayName}1328 onApprove={handleApprovePendingPasskey}1329 onDeny={handleDenyPendingPasskey}1330 />1331 }1332 >1333 <Show1334 when={!isLockedView()}1335 fallback={1336 <Show1337 when={view() !== "adopting"}1338 fallback={1339 <Suspense fallback={<div class="peach-loading">loading...</div>}>1340 <AdoptVaultView1341 onCancel={() => {1342 clearOnboardingExit();1343 setOnboarded(false);1344 setView("lock");1345 }}1346 onDone={handleAdoptionDone}1347 />1348 </Suspense>1349 }1350 >1351 <Show1352 when={onboarded() || hasVault()}1353 fallback={1354 <Onboarding1355 initialCard={onboardingCardAtExit()}1356 onComplete={() => {1357 markOnboardingExit("create");1358 setStartOnboardingRestore(false);1359 setOnboarded(true);1360 }}1361 onRestore={() => {1362 markOnboardingExit("restore");1363 setStartOnboardingRestore(true);1364 setOnboarded(true);1365 }}1366 onAdopt={() => {1367 markOnboardingExit("adopt");1368 setStartOnboardingRestore(false);1369 setOnboarded(true);1370 setView("adopting");1371 }}1372 />1373 }1374 >1375 <LockView1376 hasVault={hasVault()}1377 ready={bootState() === "ready"}1378 isPro={proStatus()}1379 forceRecoveryWords={forceRecoveryWords()}1380 initialRestore={startOnboardingRestore()}1381 initialRestoreSource={resumeRestoreSource() ?? undefined}1382 onUnlock={() => {1383 1384 1385 1386 if (forceRecoveryWords()) setForceRecoveryWords(false);1387 1388 1389 1390 setStartOnboardingRestore(false);1391 setResumeRestoreSource(null);1392 void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1393 return handleUnlock();1394 }}1395 onBackToOnboarding={1396 !hasVault()1397 ? () => {1398 1399 1400 clearOnboardingExit();1401 setStartOnboardingRestore(false);1402 setOnboarded(false);1403 }1404 : undefined1405 }1406 onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1407 />1408 </Show>1409 </Show>1410 }1411 >1412 <Show1413 when={1414 view() !== "pro-celebration" &&1415 view() !== "initial-sync"1416 }1417 fallback={1418 <Show1419 when={view() === "initial-sync"}1420 fallback={<ProCelebration />}1421 >1422 <InitialSyncView1423 slow={initialSyncSlow()}1424 onRetry={() => void retryInitialSync()}1425 />1426 </Show>1427 }1428 >1429 <section1430 id="hd-shell"1431 class="peach-shell peach-theme"1432 data-surface="extension"1433 >1434 <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1435 <PeachWordmark unlocked />1436 <div class="peach-chrome-actions">1437 <button1438 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1439 onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1440 aria-label="Notes"1441 title="Notes"1442 >1443 <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1444 <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1445 <line x1="4" y1="5" x2="10" y2="5" />1446 <line x1="4" y1="7.5" x2="10" y2="7.5" />1447 <line x1="4" y1="10" x2="7" y2="10" />1448 </svg>1449 </button>1450 <button1451 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1452 classList={{1453 "is-syncing": syncBusy(),1454 "is-ok": syncFlash() === "ok",1455 "is-error": syncFlash() === "error",1456 }}1457 onClick={() => void handleHeaderSync()}1458 disabled={syncBusy()}1459 aria-label={`Sync now. ${syncLabel()}`}1460 title={syncLabel()}1461 >1462 <svg class="peach-sync-icon" width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1463 <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1464 <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1465 <path d="M2.6 1v2.4h2.4" />1466 <path d="M11.4 13v-2.4H9" />1467 </svg>1468 <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1469 </button>1470 <button1471 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1472 onClick={() => setView("settings")}1473 aria-label="Settings"1474 >1475 <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1476 <path1477 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"1478 stroke="currentColor"1479 stroke-width="0.9"1480 />1481 <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1482 </svg>1483 </button>1484 <button1485 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1486 onClick={handleAdd}1487 aria-label="New entry"1488 >1489 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1490 <path d="M5.5 1v9M1 5.5h9" />1491 </svg>1492 </button>1493 <button1494 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1495 onClick={() => void handleHeaderLock()}1496 aria-label="Lock vault"1497 >1498 <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1499 <path1500 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"1501 stroke="currentColor"1502 stroke-width="1"1503 stroke-linecap="round"1504 />1505 <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1506 <circle cx="7" cy="10.25" r="1" fill="currentColor" />1507 </svg>1508 </button>1509 </div>1510 </header>15111512 <Show when={pendingProNotice() !== null}>1513 <div class="peach-pro-notice-banner">1514 <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1515 <button1516 class="peach-pro-notice-link"1517 onClick={() => {1518 setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1519 setSettingsInitialSection("license");1520 setView("settings");1521 setPendingProNotice(null);1522 }}1523 >1524 Learn more →1525 </button>1526 <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1527 </div>1528 </Show>15291530 <Show when={pendingRememberSite()}>1531 {(request) => {1532 let host = request().url;1533 try { host = new URL(request().url).hostname; } catch { }1534 return (1535 <div class="peach-pro-notice-banner">1536 <span>Also use “{request().title}” on {host}?</span>1537 <button1538 class="peach-pro-notice-link"1539 onClick={async () => {1540 await sendMessage({1541 type: "ADD_ADDITIONAL_URL",1542 payload: { id: request().entryId, url: request().url },1543 });1544 await chrome.storage.session.remove("pendingRememberSite");1545 setPendingRememberSite(null);1546 }}1547 >1548 Add1549 </button>1550 <button1551 class="peach-pro-notice-close"1552 onClick={async () => {1553 await chrome.storage.session.remove("pendingRememberSite");1554 setPendingRememberSite(null);1555 }}1556 aria-label="Dismiss"1557 >1558 ✕1559 </button>1560 </div>1561 );1562 }}1563 </Show>15641565 <div class="peach-shell-body">1566 <div class="peach-shell-veil"></div>1567 <div class="peach-content-frame" data-content-phase={contentPhase()}>1568 <EntryView1569 entry={selectedEntry()}1570 currentTabUrl={currentTabUrl()}1571 entries={entries()}1572 isPro={proStatus()}1573 onDelete={handleDelete}1574 onFieldSaved={() => void loadEntries()}1575 onEscape={() => { setView("list"); }}1576 onProGate={(feature) => {1577 setUpgradeHighlight(feature);1578 setSettingsInitialSection("license");1579 setView("settings");1580 }}1581 />1582 </div>15831584 <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1585 <div class="peach-search-bar">1586 <span class="peach-search-icon">1587 <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1588 <circle cx="5.5" cy="5.5" r="3.75" />1589 <path d="M8.75 8.75L11.5 11.5" />1590 </svg>1591 </span>1592 <input1593 class="peach-search-input"1594 placeholder="search vault..."1595 autocomplete="off"1596 aria-label="Search vault entries"1597 onClick={openList}1598 onFocus={openList}1599 readOnly1600 />1601 <div class="peach-search-meta">1602 <span class="peach-search-counter">1603 {nonNoteEntries().length > 01604 ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1605 : "0 entries"}1606 </span>1607 <span class="peach-divider"></span>1608 <button1609 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1610 onClick={() => navigate(-1)}1611 aria-label="Previous entry"1612 disabled={nonNoteEntries().length === 0}1613 >1614 <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1615 <path d="M5 1L1 5.5L5 10" />1616 </svg>1617 </button>1618 <button1619 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1620 onClick={() => navigate(1)}1621 aria-label="Next entry"1622 disabled={nonNoteEntries().length === 0}1623 >1624 <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1625 <path d="M1 1L5 5.5L1 10" />1626 </svg>1627 </button>1628 </div>1629 </div>1630 </section>1631 </div>16321633 {}1634 <Show when={alertGroups().length > 0}>1635 <div class="peach-sync-alerts">1636 <For each={alertGroups()}>1637 {([type, group]) => {1638 const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1639 return (1640 <div class="peach-sync-alert">1641 <Show when={group.length > 1}>1642 <button1643 class="peach-sync-alert-flip"1644 type="button"1645 aria-label="Previous"1646 onClick={() => flipAlert(type, -1)}1647 >‹</button>1648 </Show>1649 <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1650 <Show when={group.length > 1}>1651 <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1652 <button1653 class="peach-sync-alert-flip"1654 type="button"1655 aria-label="Next"1656 onClick={() => flipAlert(type, 1)}1657 >›</button>1658 </Show>1659 <button1660 class="peach-sync-alert-dismiss"1661 type="button"1662 aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1663 onClick={() => dismissAlertGroup(type)}1664 >×</button>1665 </div>1666 );1667 }}1668 </For>1669 </div>1670 </Show>16711672 <Show when={view() === "list"}>1673 <VaultView1674 entries={entries()}1675 selectedEntryId={selectedEntry()?.id}1676 currentTabDomain={currentTabDomain()}1677 sortOrder={sortOrder()}1678 searchSeed={listSearchSeed()}1679 searchSeedNonce={listSearchSeedNonce()}1680 onSelectEntry={handleSelectEntry}1681 onSortOrderChange={setSortOrder}1682 onAdd={handleAdd}1683 onClose={() => setView("entry")}1684 onOpenTrash={() => setView("trash")}1685 onDeleteMany={handleDeleteMany}1686 />1687 </Show>1688 <Show when={view() === "settings" || settingsExiting()}>1689 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1690 <SettingsView1691 entriesCount={entries().length}1692 breachMonitoring={breachMonitoring()}1693 lockOnClose={lockOnClose()}1694 autoLockMinutes={autoLockMinutes()}1695 trashRetentionDays={trashRetentionDays()}1696 theme={theme()}1697 accentColor={accentColor()}1698 textSize={textSize()}1699 reduceMotion={reduceMotion()}1700 isPro={proStatus()}1701 initialSection={settingsInitialSection()}1702 upgradeHighlight={upgradeHighlight()}1703 isExiting={settingsExiting()}1704 onBreachMonitoringChange={applyBreachMonitoring}1705 onLockOnCloseChange={applyLockOnClose}1706 onAutoLockMinutesChange={applyAutoLockMinutes}1707 onTrashRetentionChange={applyTrashRetention}1708 onThemeChange={applyTheme}1709 onAccentChange={applyAccentColor}1710 onTextSizeChange={applyTextSize}1711 onReduceMotionChange={applyReduceMotion}1712 shortcuts={shortcutBindings()}1713 onShortcutsChange={applyShortcuts}1714 onLicenseChange={async () => {1715 1716 1717 1718 1719 1720 await refreshProStatus();1721 void loadEntries();1722 const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1723 if ((should as { ok: boolean; data?: boolean }).data === true) {1724 await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1725 setView("pro-celebration");1726 window.setTimeout(() => setView("settings"), 2500);1727 }1728 }}1729 onBack={() => {1730 setSettingsExiting(true);1731 window.setTimeout(() => {1732 setSettingsExiting(false);1733 setSettingsInitialSection(null);1734 setUpgradeHighlight(null);1735 handleBack();1736 }, 200);1737 }}1738 onImport={() => setView("import")}1739 onExport={() => setView("export")}1740 onBreachCheckDone={loadEntries}1741 onOpenHealth={openHealth}1742 onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1743 onOpenFileImport={handleOpenFileImport}1744 onOpenPanic={() => setView("panic")}1745 onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1746 onOpenCodexRestore={() => setView("codex-restore")}1747 onCardChange={setSettingsActiveCard}1748 onProGate={(feature) => {1749 setUpgradeHighlight(feature);1750 setSettingsInitialSection("license");1751 }}1752 />1753 </Suspense>1754 </Show>1755 <Show when={view() === "codex-generate"}>1756 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1757 <CodexGenerateView1758 isPro={proStatus()}1759 onBack={() => setView("settings")}1760 onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1761 onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1762 onVaultLocked={() => handleLock()}1763 />1764 </Suspense>1765 </Show>1766 <Show when={view() === "codex-restore"}>1767 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1768 <CodexRestoreView1769 onBack={() => setView("lock")}1770 onRestoreSuccess={async () => {1771 1772 1773 1774 await handleUnlock();1775 }}1776 />1777 </Suspense>1778 </Show>1779 <Show when={view() === "pair-device"}>1780 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1781 <PairDeviceView1782 isPro={proStatus()}1783 onProChanged={() => { void refreshProStatus(); }}1784 onBack={() => setView("settings")}1785 onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1786 />1787 </Suspense>1788 </Show>1789 <Show when={view() === "add"}>1790 <AddView1791 entry={editEntry()}1792 entries={entries()}1793 onBack={handleBack}1794 onSave={handleSave}1795 />1796 </Show>1797 <Show when={view() === "import"}>1798 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1799 <ImportView onBack={() => setView("settings")} onImport={handleSave} />1800 </Suspense>1801 </Show>1802 <Show when={view() === "export"}>1803 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1804 <ExportView onBack={handleExportBack} />1805 </Suspense>1806 </Show>1807 <Show when={view() === "panic"}>1808 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1809 <PanicView1810 onCancel={() => setView("settings")}1811 onOpenExport={() => {1812 setReturnToPanic(true);1813 setView("export");1814 }}1815 onDestroyed={async () => {1816 1817 1818 setOnboardingCardAtExit(0);1819 void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1820 clearOnboardingExit();1821 setEntries([]);1822 setSelectedEntry(null);1823 setEditEntry(undefined);1824 setHasVault(false);1825 setOnboarded(false);1826 setProStatus(false);1827 setPendingPasskey(null);1828 setUpgradeHighlight(null);1829 setSettingsInitialSection(null);1830 setPendingProNotice(null);1831 setPendingCelebration(false);1832 setReturnToPanic(false);1833 setContentPhase("idle");1834 setView("lock");1835 }}1836 />1837 </Suspense>1838 </Show>1839 {1840}1841 <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1842 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1843 <HealthView1844 entries={entries()}1845 isPro={proStatus()}1846 onFixEntry={handleFixEntry}1847 onBack={() => setView("settings")}1848 onRefresh={loadEntries}1849 hidden={view() !== "health"}1850 />1851 </Suspense>1852 </Show>1853 <Show when={view() === "trash"}>1854 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1855 <TrashView1856 onBack={() => setView("list")}1857 onRestored={() => void loadEntries()}1858 />1859 </Suspense>1860 </Show>1861 <Show when={showNotes()}>1862 <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1863 <NotesMode1864 notes={entries().filter((e) => e.type === "note")}1865 initialNoteId={openNoteId()}1866 onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1867 onNoteListChanged={() => void loadEntries()}1868 />1869 </div>1870 </Show>1871 <Show when={restoreView() === "file"}>1872 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1873 <ImportView1874 mode="onboarding"1875 replacesExistingVault={true}1876 onBack={() => setRestoreView(null)}1877 onImport={async () => {1878 setRestoreView(null);1879 await handleUnlock();1880 }}1881 />1882 </Suspense>1883 </Show>1884 </section>1885 </Show>1886 </Show>1887 </Show>1888 </Show>1889 <Show when={showShortcutsHelp()}>1890 <ShortcutsHelpOverlay1891 bindings={shortcutBindings()}1892 onClose={() => setShowShortcutsHelp(false)}1893 />1894 </Show>1895 </div>1896 );1897}18981899function ShortcutsHelpOverlay(props: {1900 bindings: Record<ShortcutAction, Keybinding>;1901 onClose: () => void;1902}) {1903 return (1904 <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1905 <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1906 <div class="peach-shortcuts-help-head">1907 <h3>Keyboard shortcuts</h3>1908 <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1909 </div>1910 <div class="peach-shortcuts-help-body">1911 <p class="peach-settings-sub-label">ENTRY VIEW</p>1912 <ul>1913 {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1914 <li>1915 <span>{d.label}</span>1916 <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1917 </li>1918 ))}1919 </ul>1920 <p class="peach-settings-sub-label">ANYWHERE</p>1921 <ul>1922 {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1923 <li>1924 <span>{d.label}</span>1925 <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1926 </li>1927 ))}1928 </ul>1929 </div>1930 </div>1931 </div>1932 );1933}