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(795 entry.password,796 "Password",797 entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,798 ).then((ok) => { if (ok) triggerRing(); });799 },800 copy_username: () => {801 const entry = selectedEntry();802 if (entry?.username) void popupCopy(803 entry.username,804 "Username",805 entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,806 ).then((ok) => { if (ok) triggerRing(); });807 },808 copy_totp: () => {809 const entry = selectedEntry();810 if (!entry?.totp) return;811 try {812 const { code } = generateTOTP(813 entry.totp,814 entry.totpAlgorithm,815 entry.totpDigits,816 entry.totpPeriod,817 );818 void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });819 } catch { }820 },821 new_entry: () => handleAdd(),822 edit_entry: () => {823 const entry = selectedEntry();824 825 826 if (!entry || isPasskeyOnly(entry)) return;827 setEditEntry(entry);828 setView("add");829 },830 delete_entry: () => {831 if (selectedEntry()) void handleDelete();832 },833 lock_vault: () => { void handleHeaderLock(); },834 search: () => openList(),835 nav_prev: () => navigate(-1),836 nav_next: () => navigate(1),837 jump_vault: () => setView("entry"),838 jump_settings: () => setView("settings"),839 show_help: () => setShowShortcutsHelp(true),840 };841842 843 844 845 const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([846 "copy_password", "copy_username", "copy_totp",847 "edit_entry", "delete_entry", "nav_prev", "nav_next",848 ]);849850 const handleGlobalKeydown = (e: KeyboardEvent) => {851 const v = view();852 const inInput = (e.target as HTMLElement)?.tagName === "INPUT"853 || (e.target as HTMLElement)?.tagName === "TEXTAREA"854 || (e.target as HTMLElement)?.isContentEditable;855 const isPrintableSearchKey =856 e.key.length === 1 &&857 !e.ctrlKey &&858 !e.metaKey &&859 !e.altKey;860861 862 863 864 865 866 if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;867868 869 870 if (showShortcutsHelp()) {871 if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }872 return;873 }874875 876 if (e.key === "Escape") {877 if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }878 if (v === "list") { setView("entry"); return; }879 if (v === "settings" || v === "add") { handleBack(); return; }880 if (v === "import" || v === "health") { setView("settings"); return; }881 if (v === "export") { handleExportBack(); return; }882 if (v === "pair-device") { setView("settings"); return; }883 }884885 886 887 888 const bindings = shortcutBindings();889 for (const action of Object.keys(bindings) as ShortcutAction[]) {890 const binding = bindings[action];891 if (!matchKeybinding(e, binding)) continue;892 893 894 const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;895 if (!hasMod && binding.key.length === 1 && inInput) return;896 if (ENTRY_SCOPED.has(action) && v !== "entry") return;897 e.preventDefault();898 SHORTCUT_HANDLERS[action]?.();899 return;900 }901902 903 904 905 906 if (v === "entry" && !inInput && isPrintableSearchKey) {907 e.preventDefault();908 primeListSearch(e.key);909 return;910 }911 };912 window.addEventListener("keydown", handleGlobalKeydown);913 onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));914915 const handleStorageChanged = (916 changes: Record<string, chrome.storage.StorageChange>,917 areaName: string918 ) => {919 if (areaName !== "session") return;920 if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {921 return;922 }923 void refreshPendingPasskey();924 };925 chrome.storage.onChanged.addListener(handleStorageChanged);926 onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));927 });928929 async function refreshCurrentTab() {930 try {931 const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });932 const url = tab?.url ?? tab?.pendingUrl ?? "";933 setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");934 935 936 const isWebUrl = /^https?:\/\//i.test(url);937 setCurrentTabUrl(isWebUrl ? url : "");938 } catch {939 setCurrentTabDomain("");940 setCurrentTabUrl("");941 }942 }943944 async function refreshPendingPasskey() {945 const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });946 setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);947 }948949 async function refreshProStatus() {950 const res = await sendMessage({ type: "GET_LICENSE" });951 const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;952 setProStatus(Boolean(data?.valid && data?.plan === "pro"));953 }954955 async function restoreSettings() {956 const res = await sendMessage({ type: "GET_SETTINGS" });957 const s = (res as { ok: boolean; data?: any }).data ?? {};958 if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {959 setAccentColor(s.accentColor as AccentColorName);960 }961 setTheme(s.theme === "light" ? "light" : "dark");962 if (s.textSize === "small" || s.textSize === "large") {963 setTextSize(s.textSize);964 } else {965 setTextSize("medium");966 }967 setReduceMotion(s.reduceMotion === true);968 setLockOnClose(s.lockOnClose === true);969 setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);970 setBreachMonitoring(s.breachMonitoring !== false);971 setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);972 setShortcutBindings(getActiveBindings(s.shortcuts));973 }974975 async function applyTrashRetention(days: number) {976 setTrashRetentionDays(days);977 await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });978 }979980 function primeListSearch(seed: string) {981 setListSearchSeed(seed);982 setListSearchSeedNonce((value) => value + 1);983 openList();984 }985986 987 988 989 async function loadEntries(): Promise<VaultEntry[] | null> {990 const response = await sendMessage({ type: "GET_ENTRIES" });991 const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };992993 994 995 996 997 if (!res.ok) {998 if (999 res.error === "vault_locked" ||1000 res.error === "SERVICE_WORKER_UNAVAILABLE" ||1001 (typeof res.error === "string" && res.error.includes("locked"))1002 ) {1003 handleLock();1004 return null; 1005 }1006 return [];1007 }10081009 const loadedEntries = res.data ?? [];1010 setEntries(loadedEntries);10111012 const currentId = selectedEntry()?.id;1013 if (currentId) {1014 setSelectedEntry(1015 loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1016 );1017 }10181019 return loadedEntries;1020 }10211022 async function openVault(preferredEntryId?: string, skipViewSet = false) {1023 1024 const retDays = trashRetentionDays();1025 if (retDays > 0) {1026 void sendMessage({1027 type: "PURGE_EXPIRED_TRASH",1028 payload: { retentionMs: retDays * 86_400_000 },1029 });1030 }10311032 const loadedEntries = await loadEntries();10331034 1035 1036 if (loadedEntries === null) return false;10371038 1039 let nextSelectedEntry: VaultEntry | null = null;1040 if (preferredEntryId) {1041 nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1042 }1043 if (!nextSelectedEntry) {1044 const tabDomain = currentTabDomain();1045 if (tabDomain) {1046 nextSelectedEntry = loadedEntries.find((e) => {1047 if (e.type === "login") {1048 if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1049 for (const extra of e.additionalUrls ?? []) {1050 if ((extractDomain(extra) ?? "") === tabDomain) return true;1051 }1052 return false;1053 }1054 if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1055 return false;1056 }) ?? null;1057 }1058 }1059 nextSelectedEntry ??= pickNavigable(loadedEntries);10601061 setSelectedEntry(nextSelectedEntry);1062 setEditEntry(undefined);1063 setContentPhase("enter");1064 queueContentIdle();1065 if (!skipViewSet) setView("entry");1066 return true;1067 }10681069 async function handleUnlock() {1070 1071 1072 1073 1074 1075 1076 let recoveryPending = false;1077 try {1078 const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1079 recoveryPending = out.ok === true && out.data === true;1080 } catch { }1081 if (recoveryPending) {1082 setForceRecoveryWords(true);1083 setView("lock");1084 triggerPipPulse();1085 await restoreSettings();1086 return;1087 }1088 setHasVault(true);1089 triggerPipPulse();1090 await restoreSettings();1091 const celebrating = pendingCelebration();1092 if (celebrating) {1093 await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1094 setPendingCelebration(false);1095 }1096 await openVault(undefined, celebrating);1097 if (celebrating) {1098 setView("pro-celebration");1099 window.setTimeout(() => setView("entry"), 2500);1100 }1101 1102 1103 if (openedForInlineUnlock) {1104 openedForInlineUnlock = false;1105 window.close();1106 }1107 }11081109 function handleSelectEntry(entry: VaultEntry) {1110 if (entry.type === "note") {1111 setOpenNoteId(entry.id);1112 setShowNotes(true);1113 return;1114 }1115 setSelectedEntry(entry);1116 setContentPhase("enter");1117 queueContentIdle();1118 setView("entry");1119 }11201121 function handleAdd() {1122 setEditEntry(undefined);1123 setView("add");1124 }11251126 async function handleDelete() {1127 const entry = selectedEntry();1128 if (!entry) return;1129 await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1130 const loadedEntries = await loadEntries() ?? [];1131 setSelectedEntry(pickNavigable(loadedEntries));1132 setView("entry");1133 }11341135 async function handleDeleteMany(ids: string[]) {1136 for (const id of ids) {1137 await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1138 }1139 const loadedEntries = await loadEntries() ?? [];1140 1141 const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1142 if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1143 }11441145 async function handleSave(savedEntry?: VaultEntry) {1146 await openVault(savedEntry?.id);1147 }11481149 function handleBack() {1150 const dest = editBackView();1151 setEditBackView("entry");1152 setEditEntry(undefined);1153 setView(dest);1154 }11551156 function handleExportBack() {1157 if (returnToPanic()) {1158 setReturnToPanic(false);1159 setView("panic");1160 return;1161 }1162 setView("settings");1163 }11641165 function handleLock() {1166 setEntries([]);1167 setSelectedEntry(null);1168 setEditEntry(undefined);1169 setContentPhase("idle");1170 setView("lock");1171 }11721173 function handleHeaderLock() {1174 1175 1176 1177 handleLock();1178 void sendMessage({ type: "LOCK" });1179 }11801181 1182 1183 1184 async function handleHeaderSync(): Promise<void> {1185 if (syncBusy()) return;1186 setSyncBusy(true);1187 setSyncFlash(null);1188 try {1189 await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1190 let state: SyncOutcomeSummary = { status: "syncing" };1191 for (let i = 0; i < 40 && state.status === "syncing"; i++) {1192 await new Promise((r) => setTimeout(r, 250));1193 const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1194 ok: boolean;1195 data?: SyncOutcomeSummary;1196 };1197 state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1198 }1199 setSyncSummary(state);1200 setSyncFlash(state.status === "error" ? "error" : "ok");1201 await loadSyncAlerts();1202 await loadEntries();1203 await loadSyncIndicator();1204 } catch {1205 setSyncSummary({ status: "error", outcome: "run_failed" });1206 setSyncFlash("error");1207 } finally {1208 setSyncBusy(false);1209 setTimeout(() => setSyncFlash(null), 2_000);1210 }1211 }12121213 function navigate(dir: number) {1214 const navigable = nonNoteEntries();1215 if (navigable.length === 0) return;1216 const currentIndex = selectedIndex();1217 const baseIndex = currentIndex >= 0 ? currentIndex : 0;1218 const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1219 setSelectedEntry(navigable[nextIndex]);1220 setContentPhase("enter");1221 queueContentIdle();1222 }12231224 122512261227122812291230 function pickNavigable(list: VaultEntry[]): VaultEntry | null {1231 return list.find((e) => e.type !== "note") ?? null;1232 }12331234 function openList() {1235 setView("list");1236 }12371238 function openHealth() {1239 setEditEntry(undefined);1240 setView("health");1241 }12421243 function handleOpenFileImport() {1244 setRestoreView("file");1245 }12461247 const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12481249 function handleFixEntry(entry: VaultEntry) {1250 setSelectedEntry(entry);1251 1252 1253 if (isPasskeyOnly(entry)) {1254 setView("entry");1255 return;1256 }1257 setEditBackView(view()); 1258 setEditEntry(entry);1259 setView("add");1260 }12611262 const isLockedView = () => view() === "lock" || view() === "adopting";12631264 async function handleAdoptionDone() {1265 await storageSet("peach_onboarded", "true").catch(() => {});1266 await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1267 clearOnboardingExit();1268 setOnboarded(true);1269 setHasVault(true);1270 setView("initial-sync");1271 1272 1273 1274 await refreshProStatus();1275 const deviceId = await resolveInitialSyncDeviceId();1276 if (deviceId) {1277 void beginInitialSyncWait(deviceId);1278 } else {1279 1280 1281 1282 setInitialSyncSlow(true);1283 }1284 }12851286 async function handleApprovePendingPasskey() {1287 const pending = pendingPasskey();1288 if (!pending) return;1289 if (pending.browser === "firefox" && pending.type === "create") {1290 1291 1292 1293 1294 const { createFirefoxPasskey } = await import("./firefox-passkey");1295 const result = await createFirefoxPasskey(pending);1296 if (!result.ok) {1297 console.warn("Peach Firefox passkey create failed:", result.error);1298 }1299 await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1300 setPendingPasskey(null);1301 void loadEntries();1302 window.close();1303 return;1304 }1305 await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1306 window.close();1307 }13081309 async function handleDenyPendingPasskey() {1310 const pending = pendingPasskey();1311 if (!pending) return;1312 await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1313 window.close();1314 }13151316 function queueContentIdle(after?: () => void) {1317 if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1318 contentPhaseTimer = window.setTimeout(() => {1319 setContentPhase("idle");1320 after?.();1321 }, ENTRY_TRANSITION_SETTLE_MS);1322 }13231324 return (1325 <div class="popup-root peach-theme">1326 <Show when={bootState() === "ready"}>1327 <Show1328 when={!pendingPasskey()}1329 fallback={1330 <PasskeyApprovalView1331 type={pendingPasskey()!.type}1332 rpName={pendingPasskey()!.rpName}1333 rpId={pendingPasskey()!.rpId}1334 userName={pendingPasskey()!.userName}1335 userDisplayName={pendingPasskey()!.userDisplayName}1336 onApprove={handleApprovePendingPasskey}1337 onDeny={handleDenyPendingPasskey}1338 />1339 }1340 >1341 <Show1342 when={!isLockedView()}1343 fallback={1344 <Show1345 when={view() !== "adopting"}1346 fallback={1347 <Suspense fallback={<div class="peach-loading">loading...</div>}>1348 <AdoptVaultView1349 onCancel={() => {1350 clearOnboardingExit();1351 setOnboarded(false);1352 setView("lock");1353 }}1354 onDone={handleAdoptionDone}1355 />1356 </Suspense>1357 }1358 >1359 <Show1360 when={onboarded() || hasVault()}1361 fallback={1362 <Onboarding1363 initialCard={onboardingCardAtExit()}1364 onComplete={() => {1365 markOnboardingExit("create");1366 setStartOnboardingRestore(false);1367 setOnboarded(true);1368 }}1369 onRestore={() => {1370 markOnboardingExit("restore");1371 setStartOnboardingRestore(true);1372 setOnboarded(true);1373 }}1374 onAdopt={() => {1375 markOnboardingExit("adopt");1376 setStartOnboardingRestore(false);1377 setOnboarded(true);1378 setView("adopting");1379 }}1380 />1381 }1382 >1383 <LockView1384 hasVault={hasVault()}1385 ready={bootState() === "ready"}1386 isPro={proStatus()}1387 forceRecoveryWords={forceRecoveryWords()}1388 initialRestore={startOnboardingRestore()}1389 initialRestoreSource={resumeRestoreSource() ?? undefined}1390 onUnlock={() => {1391 1392 1393 1394 if (forceRecoveryWords()) setForceRecoveryWords(false);1395 1396 1397 1398 setStartOnboardingRestore(false);1399 setResumeRestoreSource(null);1400 void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1401 return handleUnlock();1402 }}1403 onBackToOnboarding={1404 !hasVault()1405 ? () => {1406 1407 1408 clearOnboardingExit();1409 setStartOnboardingRestore(false);1410 setOnboarded(false);1411 }1412 : undefined1413 }1414 onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1415 />1416 </Show>1417 </Show>1418 }1419 >1420 <Show1421 when={1422 view() !== "pro-celebration" &&1423 view() !== "initial-sync"1424 }1425 fallback={1426 <Show1427 when={view() === "initial-sync"}1428 fallback={<ProCelebration />}1429 >1430 <InitialSyncView1431 slow={initialSyncSlow()}1432 onRetry={() => void retryInitialSync()}1433 />1434 </Show>1435 }1436 >1437 <section1438 id="hd-shell"1439 class="peach-shell peach-theme"1440 data-surface="extension"1441 >1442 <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1443 <PeachWordmark unlocked />1444 <div class="peach-chrome-actions">1445 <button1446 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1447 onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1448 aria-label="Notes"1449 title="Notes"1450 >1451 <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1452 <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1453 <line x1="4" y1="5" x2="10" y2="5" />1454 <line x1="4" y1="7.5" x2="10" y2="7.5" />1455 <line x1="4" y1="10" x2="7" y2="10" />1456 </svg>1457 </button>1458 <button1459 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1460 classList={{1461 "is-syncing": syncBusy(),1462 "is-ok": syncFlash() === "ok",1463 "is-error": syncFlash() === "error",1464 }}1465 onClick={() => void handleHeaderSync()}1466 disabled={syncBusy()}1467 aria-label={`Sync now. ${syncLabel()}`}1468 title={syncLabel()}1469 >1470 <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">1471 <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1472 <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1473 <path d="M2.6 1v2.4h2.4" />1474 <path d="M11.4 13v-2.4H9" />1475 </svg>1476 <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1477 </button>1478 <button1479 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1480 onClick={() => setView("settings")}1481 aria-label="Settings"1482 >1483 <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1484 <path1485 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"1486 stroke="currentColor"1487 stroke-width="0.9"1488 />1489 <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1490 </svg>1491 </button>1492 <button1493 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1494 onClick={handleAdd}1495 aria-label="New entry"1496 >1497 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1498 <path d="M5.5 1v9M1 5.5h9" />1499 </svg>1500 </button>1501 <button1502 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1503 onClick={() => void handleHeaderLock()}1504 aria-label="Lock vault"1505 >1506 <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1507 <path1508 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"1509 stroke="currentColor"1510 stroke-width="1"1511 stroke-linecap="round"1512 />1513 <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1514 <circle cx="7" cy="10.25" r="1" fill="currentColor" />1515 </svg>1516 </button>1517 </div>1518 </header>15191520 <Show when={pendingProNotice() !== null}>1521 <div class="peach-pro-notice-banner">1522 <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1523 <button1524 class="peach-pro-notice-link"1525 onClick={() => {1526 setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1527 setSettingsInitialSection("license");1528 setView("settings");1529 setPendingProNotice(null);1530 }}1531 >1532 Learn more →1533 </button>1534 <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1535 </div>1536 </Show>15371538 <Show when={pendingRememberSite()}>1539 {(request) => {1540 let host = request().url;1541 try { host = new URL(request().url).hostname; } catch { }1542 return (1543 <div class="peach-pro-notice-banner">1544 <span>Also use “{request().title}” on {host}?</span>1545 <button1546 class="peach-pro-notice-link"1547 onClick={async () => {1548 await sendMessage({1549 type: "ADD_ADDITIONAL_URL",1550 payload: { id: request().entryId, url: request().url },1551 });1552 await chrome.storage.session.remove("pendingRememberSite");1553 setPendingRememberSite(null);1554 }}1555 >1556 Add1557 </button>1558 <button1559 class="peach-pro-notice-close"1560 onClick={async () => {1561 await chrome.storage.session.remove("pendingRememberSite");1562 setPendingRememberSite(null);1563 }}1564 aria-label="Dismiss"1565 >1566 ✕1567 </button>1568 </div>1569 );1570 }}1571 </Show>15721573 <div class="peach-shell-body">1574 <div class="peach-shell-veil"></div>1575 <div class="peach-content-frame" data-content-phase={contentPhase()}>1576 <EntryView1577 entry={selectedEntry()}1578 currentTabUrl={currentTabUrl()}1579 entries={entries()}1580 isPro={proStatus()}1581 onDelete={handleDelete}1582 onFieldSaved={() => void loadEntries()}1583 onEscape={() => { setView("list"); }}1584 onProGate={(feature) => {1585 setUpgradeHighlight(feature);1586 setSettingsInitialSection("license");1587 setView("settings");1588 }}1589 />1590 </div>15911592 <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1593 <div class="peach-search-bar">1594 <span class="peach-search-icon">1595 <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1596 <circle cx="5.5" cy="5.5" r="3.75" />1597 <path d="M8.75 8.75L11.5 11.5" />1598 </svg>1599 </span>1600 <input1601 class="peach-search-input"1602 placeholder="search vault..."1603 autocomplete="off"1604 aria-label="Search vault entries"1605 onClick={openList}1606 onFocus={openList}1607 readOnly1608 />1609 <div class="peach-search-meta">1610 <span class="peach-search-counter">1611 {nonNoteEntries().length > 01612 ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1613 : "0 entries"}1614 </span>1615 <span class="peach-divider"></span>1616 <button1617 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1618 onClick={() => navigate(-1)}1619 aria-label="Previous entry"1620 disabled={nonNoteEntries().length === 0}1621 >1622 <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1623 <path d="M5 1L1 5.5L5 10" />1624 </svg>1625 </button>1626 <button1627 class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1628 onClick={() => navigate(1)}1629 aria-label="Next entry"1630 disabled={nonNoteEntries().length === 0}1631 >1632 <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1633 <path d="M1 1L5 5.5L1 10" />1634 </svg>1635 </button>1636 </div>1637 </div>1638 </section>1639 </div>16401641 {}1642 <Show when={alertGroups().length > 0}>1643 <div class="peach-sync-alerts">1644 <For each={alertGroups()}>1645 {([type, group]) => {1646 const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1647 return (1648 <div class="peach-sync-alert">1649 <Show when={group.length > 1}>1650 <button1651 class="peach-sync-alert-flip"1652 type="button"1653 aria-label="Previous"1654 onClick={() => flipAlert(type, -1)}1655 >‹</button>1656 </Show>1657 <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1658 <Show when={group.length > 1}>1659 <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1660 <button1661 class="peach-sync-alert-flip"1662 type="button"1663 aria-label="Next"1664 onClick={() => flipAlert(type, 1)}1665 >›</button>1666 </Show>1667 <button1668 class="peach-sync-alert-dismiss"1669 type="button"1670 aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1671 onClick={() => dismissAlertGroup(type)}1672 >×</button>1673 </div>1674 );1675 }}1676 </For>1677 </div>1678 </Show>16791680 <Show when={view() === "list"}>1681 <VaultView1682 entries={entries()}1683 selectedEntryId={selectedEntry()?.id}1684 currentTabDomain={currentTabDomain()}1685 sortOrder={sortOrder()}1686 searchSeed={listSearchSeed()}1687 searchSeedNonce={listSearchSeedNonce()}1688 onSelectEntry={handleSelectEntry}1689 onSortOrderChange={setSortOrder}1690 onAdd={handleAdd}1691 onClose={() => setView("entry")}1692 onOpenTrash={() => setView("trash")}1693 onDeleteMany={handleDeleteMany}1694 />1695 </Show>1696 <Show when={view() === "settings" || settingsExiting()}>1697 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1698 <SettingsView1699 entriesCount={entries().length}1700 breachMonitoring={breachMonitoring()}1701 lockOnClose={lockOnClose()}1702 autoLockMinutes={autoLockMinutes()}1703 trashRetentionDays={trashRetentionDays()}1704 theme={theme()}1705 accentColor={accentColor()}1706 textSize={textSize()}1707 reduceMotion={reduceMotion()}1708 isPro={proStatus()}1709 initialSection={settingsInitialSection()}1710 upgradeHighlight={upgradeHighlight()}1711 isExiting={settingsExiting()}1712 onBreachMonitoringChange={applyBreachMonitoring}1713 onLockOnCloseChange={applyLockOnClose}1714 onAutoLockMinutesChange={applyAutoLockMinutes}1715 onTrashRetentionChange={applyTrashRetention}1716 onThemeChange={applyTheme}1717 onAccentChange={applyAccentColor}1718 onTextSizeChange={applyTextSize}1719 onReduceMotionChange={applyReduceMotion}1720 shortcuts={shortcutBindings()}1721 onShortcutsChange={applyShortcuts}1722 onLicenseChange={async () => {1723 1724 1725 1726 1727 1728 await refreshProStatus();1729 void loadEntries();1730 const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1731 if ((should as { ok: boolean; data?: boolean }).data === true) {1732 await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1733 setView("pro-celebration");1734 window.setTimeout(() => setView("settings"), 2500);1735 }1736 }}1737 onBack={() => {1738 setSettingsExiting(true);1739 window.setTimeout(() => {1740 setSettingsExiting(false);1741 setSettingsInitialSection(null);1742 setUpgradeHighlight(null);1743 handleBack();1744 }, 200);1745 }}1746 onImport={() => setView("import")}1747 onExport={() => setView("export")}1748 onBreachCheckDone={loadEntries}1749 onOpenHealth={openHealth}1750 onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1751 onOpenFileImport={handleOpenFileImport}1752 onOpenPanic={() => setView("panic")}1753 onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1754 onOpenCodexRestore={() => setView("codex-restore")}1755 onCardChange={setSettingsActiveCard}1756 onProGate={(feature) => {1757 setUpgradeHighlight(feature);1758 setSettingsInitialSection("license");1759 }}1760 />1761 </Suspense>1762 </Show>1763 <Show when={view() === "codex-generate"}>1764 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1765 <CodexGenerateView1766 isPro={proStatus()}1767 onBack={() => setView("settings")}1768 onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1769 onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1770 onVaultLocked={() => handleLock()}1771 />1772 </Suspense>1773 </Show>1774 <Show when={view() === "codex-restore"}>1775 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1776 <CodexRestoreView1777 onBack={() => setView("lock")}1778 onRestoreSuccess={async () => {1779 1780 1781 1782 await handleUnlock();1783 }}1784 />1785 </Suspense>1786 </Show>1787 <Show when={view() === "pair-device"}>1788 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1789 <PairDeviceView1790 isPro={proStatus()}1791 onProChanged={() => { void refreshProStatus(); }}1792 onBack={() => setView("settings")}1793 onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1794 />1795 </Suspense>1796 </Show>1797 <Show when={view() === "add"}>1798 <AddView1799 entry={editEntry()}1800 entries={entries()}1801 onBack={handleBack}1802 onSave={handleSave}1803 />1804 </Show>1805 <Show when={view() === "import"}>1806 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1807 <ImportView onBack={() => setView("settings")} onImport={handleSave} />1808 </Suspense>1809 </Show>1810 <Show when={view() === "export"}>1811 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1812 <ExportView onBack={handleExportBack} />1813 </Suspense>1814 </Show>1815 <Show when={view() === "panic"}>1816 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1817 <PanicView1818 onCancel={() => setView("settings")}1819 onOpenExport={() => {1820 setReturnToPanic(true);1821 setView("export");1822 }}1823 onDestroyed={async () => {1824 1825 1826 setOnboardingCardAtExit(0);1827 void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1828 clearOnboardingExit();1829 setEntries([]);1830 setSelectedEntry(null);1831 setEditEntry(undefined);1832 setHasVault(false);1833 setOnboarded(false);1834 setProStatus(false);1835 setPendingPasskey(null);1836 setUpgradeHighlight(null);1837 setSettingsInitialSection(null);1838 setPendingProNotice(null);1839 setPendingCelebration(false);1840 setReturnToPanic(false);1841 setContentPhase("idle");1842 setView("lock");1843 }}1844 />1845 </Suspense>1846 </Show>1847 {1848}1849 <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1850 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1851 <HealthView1852 entries={entries()}1853 isPro={proStatus()}1854 onFixEntry={handleFixEntry}1855 onBack={() => setView("settings")}1856 onRefresh={loadEntries}1857 hidden={view() !== "health"}1858 />1859 </Suspense>1860 </Show>1861 <Show when={view() === "trash"}>1862 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1863 <TrashView1864 onBack={() => setView("list")}1865 onRestored={() => void loadEntries()}1866 />1867 </Suspense>1868 </Show>1869 <Show when={showNotes()}>1870 <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1871 <NotesMode1872 notes={entries().filter((e) => e.type === "note")}1873 initialNoteId={openNoteId()}1874 onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1875 onNoteListChanged={() => void loadEntries()}1876 />1877 </div>1878 </Show>1879 <Show when={restoreView() === "file"}>1880 <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1881 <ImportView1882 mode="onboarding"1883 replacesExistingVault={true}1884 onBack={() => setRestoreView(null)}1885 onImport={async () => {1886 setRestoreView(null);1887 await handleUnlock();1888 }}1889 />1890 </Suspense>1891 </Show>1892 </section>1893 </Show>1894 </Show>1895 </Show>1896 </Show>1897 <Show when={showShortcutsHelp()}>1898 <ShortcutsHelpOverlay1899 bindings={shortcutBindings()}1900 onClose={() => setShowShortcutsHelp(false)}1901 />1902 </Show>1903 </div>1904 );1905}19061907function ShortcutsHelpOverlay(props: {1908 bindings: Record<ShortcutAction, Keybinding>;1909 onClose: () => void;1910}) {1911 return (1912 <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1913 <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1914 <div class="peach-shortcuts-help-head">1915 <h3>Keyboard shortcuts</h3>1916 <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1917 </div>1918 <div class="peach-shortcuts-help-body">1919 <p class="peach-settings-sub-label">ENTRY VIEW</p>1920 <ul>1921 {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1922 <li>1923 <span>{d.label}</span>1924 <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1925 </li>1926 ))}1927 </ul>1928 <p class="peach-settings-sub-label">ANYWHERE</p>1929 <ul>1930 {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1931 <li>1932 <span>{d.label}</span>1933 <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1934 </li>1935 ))}1936 </ul>1937 </div>1938 </div>1939 </div>1940 );1941}