SPB Git

Repository Public

state.ts 11.6 KB 171 lines typescript

1// Engine singleton, UI stores (toasts, confirmations, preferences) and small browser helpers.2// Nothing here writes a secret to localStorage, sessionStorage, the URL, the title or the console.3import { useSyncExternalStore } from "react";4import { ApiError, Engine } from "./core/engine.ts";5import { browserPasskeys, FetchTransport, IdbStore, platformLabel } from "./core/browser.ts";67export const store = new IdbStore();8export const transport = new FetchTransport();9export const engine = new Engine(transport, store, browserPasskeys, platformLabel());1011function createStore<T>(initial: T) {12  let value = initial;13  const subs = new Set<() => void>();14  return {15    get: () => value,16    set(next: T) { value = next; subs.forEach((f) => f()); },17    subscribe(f: () => void) { subs.add(f); return () => { subs.delete(f); }; },18  };19}20function useStore<T>(s: { get: () => T; subscribe: (f: () => void) => () => void }): T { return useSyncExternalStore(s.subscribe, s.get); }2122// ── engine subscription ───────────────────────────────────────────────────────────────────────────────────────23const version = createStore(0);24engine.onChange = () => version.set(version.get() + 1);25/** Re-renders the caller whenever the engine state changes. Returns the engine and a version usable as a memo key. */26export function useEngine(): { engine: Engine; version: number } { return { engine, version: useStore(version) }; }2728// ── toasts ────────────────────────────────────────────────────────────────────────────────────────────────────29export type ToastKind = "info" | "ok" | "danger";30export interface Toast { id: number; text: string; kind: ToastKind; sticky: boolean }31const toasts = createStore<Toast[]>([]);32let toastSeq = 0;33export function toast(text: string, kind: ToastKind = "info", sticky = false) {34  const id = ++toastSeq;35  toasts.set([...toasts.get().filter((t) => t.text !== text), { id, text, kind, sticky }].slice(-4));36  if (!sticky) setTimeout(() => dismissToast(id), kind === "danger" ? 9000 : kind === "ok" ? 3200 : 5200);37}38export const dismissToast = (id: number) => toasts.set(toasts.get().filter((t) => t.id !== id));39export const useToasts = () => useStore(toasts);4041// ── errors ────────────────────────────────────────────────────────────────────────────────────────────────────42const CODES: Record<string, string> = {43  offline: "The server cannot be reached. Check your connection and try again.",44  rate_limited: "Too many attempts. Wait a moment and try again.",45  handle_taken: "This handle is already taken. Choose another one.",46  invalid_invite: "This invitation link is not valid, was already used or has expired.",47  unauthenticated: "Your session ended. Unlock again with your passkey.",48  reauth_required: "A fresh passkey confirmation is required for this action.",49  not_found: "Not found — it may have expired, been revoked or been removed.",50  gone: "This link expired, was revoked or reached its view limit.",51  managed_unavailable: "The managed-secrets service is not enabled on this server.",52  invalid_request: "The server refused this request as invalid.",53  wrong_session_kind: "This action is not available in the current session. Sign in again.",54  internal: "The server failed to process the request. Nothing was changed.",55};56export const isCancel = (e: unknown) => { const n = (e as any)?.name; return n === "NotAllowedError" || n === "AbortError"; };57export const isSecurity = (text: string) => text.startsWith("SECURITY:");58/** Text for a caught exception. Never includes user secrets: engine and server messages are content-free. */59export function errText(e: unknown): string {60  if (isCancel(e)) return "The passkey prompt was cancelled or timed out. Nothing was changed.";61  if (e instanceof ApiError) {62    if (e.message && e.message !== e.code) return e.message;63    return CODES[e.code] ?? `The server refused the request (${e.code}).`;64  }65  const m = (e as any)?.message;66  return typeof m === "string" && m ? m : "Something went wrong.";67}68/** Reports a caught error as a toast (sticky danger for SECURITY: messages). Locks when the session is gone. */69export function reportError(e: unknown) {70  if (sessionEnded(e)) return;71  const text = errText(e);72  toast(text, isCancel(e) ? "info" : "danger", isSecurity(text));73}74/** A 401 that is not a step-up request means the server no longer knows this session (expired or device revoked). */75export function sessionEnded(e: unknown): boolean {76  if (!(e instanceof ApiError) || e.status !== 401 || e.code !== "unauthenticated") return false;77  if (engine.unlocked) { engine.lock(); notice.set("Your session ended on the server. Unlock with your passkey to continue."); }78  return true;79}80/** One-line message shown on the locked / welcome screens (for example after an automatic lock). */81export const notice = createStore<string>("");82export const useNotice = () => useStore(notice);8384export async function safeSync() { if (!engine.unlocked) return; try { await engine.sync(); } catch (e) { if (!sessionEnded(e)) { /* shown in sync health */ } } }8586// ── confirmation dialogs (imperative; rendered by <ConfirmHost/>) ─────────────────────────────────────────────87export interface ConfirmRequest { title: string; body: string | string[]; confirmLabel: string; danger?: boolean; typeToConfirm?: string; resolve: (ok: boolean) => void }88const confirms = createStore<ConfirmRequest | null>(null);89export const useConfirmRequest = () => useStore(confirms);90export function confirmAction(o: Omit<ConfirmRequest, "resolve">): Promise<boolean> {91  return new Promise((resolve) => { confirms.get()?.resolve(false); confirms.set({ ...o, resolve: (ok) => { confirms.set(null); resolve(ok); } }); });92}9394// ── preferences: timings live in the IndexedDB store; only the theme (not sensitive) uses localStorage ─────────95export interface Prefs { autoLockMin: number; clipClearSec: number }96const DEFAULT_PREFS: Prefs = { autoLockMin: 5, clipClearSec: 30 };97const prefs = createStore<Prefs>(DEFAULT_PREFS);98export const usePrefs = () => useStore(prefs);99export const getPrefs = () => prefs.get();100export async function loadPrefs() {101  try { const p = await store.get<Partial<Prefs>>("prefs"); if (p) prefs.set({ ...DEFAULT_PREFS, ...p }); else prefs.set(DEFAULT_PREFS); } catch { /* defaults */ }102}103export async function setPrefs(p: Partial<Prefs>) { prefs.set({ ...prefs.get(), ...p }); try { await store.set("prefs", prefs.get()); } catch { /* kept in memory */ } }104105export type Theme = "system" | "light" | "dark";106const readTheme = (): Theme => { try { const t = localStorage.getItem("spv-theme"); return t === "light" || t === "dark" ? t : "system"; } catch { return "system"; } };107const theme = createStore<Theme>(readTheme());108export const useTheme = () => useStore(theme);109export function applyTheme(t: Theme = theme.get()) {110  theme.set(t);111  try { if (t === "system") localStorage.removeItem("spv-theme"); else localStorage.setItem("spv-theme", t); } catch { /* private mode */ }112  document.documentElement.dataset.theme = t;113  const light = t === "light" || (t === "system" && matchMedia("(prefers-color-scheme: light)").matches);114  document.querySelector('meta[name="theme-color"]')?.setAttribute("content", light ? "#f5f3ee" : "#0c1113");115}116117// ── clipboard ─────────────────────────────────────────────────────────────────────────────────────────────────118let clipTimer: ReturnType<typeof setTimeout> | undefined;119/** Copies a value. The confirmation names the field, never the value. Secrets are overwritten later, best effort. */120export async function copyText(value: string, label: string, secret = true) {121  try { await navigator.clipboard.writeText(value); }122  catch { toast("This browser refused access to the clipboard.", "danger"); return; }123  const sec = prefs.get().clipClearSec;124  toast(secret && sec > 0 ? `${label} copied — clears in ${sec} s (best effort)` : `${label} copied`, "ok");125  if (!secret || sec <= 0) return;126  clearTimeout(clipTimer);127  clipTimer = setTimeout(async () => {128    // The clipboard cannot be read back without a permission prompt, so it is simply overwritten while the page has focus.129    if (!document.hasFocus()) return;130    try { await navigator.clipboard.writeText(""); toast("Cleared from this browser's clipboard (best effort)"); } catch { /* not focused or denied */ }131  }, sec * 1000);132}133134// ── downloads: Blob + object URL + programmatic click; the URL is revoked afterwards ───────────────────────────135export function downloadBlob(data: BlobPart, name: string, mime: string) {136  const url = URL.createObjectURL(new Blob([data], { type: mime }));137  const a = document.createElement("a");138  a.href = url; a.download = name; a.rel = "noopener";139  document.body.appendChild(a); a.click(); a.remove();140  setTimeout(() => URL.revokeObjectURL(url), 1500);141}142143// ── formatting ────────────────────────────────────────────────────────────────────────────────────────────────144export function relTime(iso?: string | null): string {145  if (!iso) return "never";146  const t = Date.parse(iso);147  if (Number.isNaN(t) || t < 86400_000) return "—";148  const s = Math.round((Date.now() - t) / 1000);149  if (s < 0) { const d = Math.ceil(-s / 86400); return -s < 3600 ? `in ${Math.ceil(-s / 60)} min` : -s < 86400 ? `in ${Math.ceil(-s / 3600)} h` : `in ${d} day${d > 1 ? "s" : ""}`; }150  if (s < 45) return "just now";151  if (s < 3600) return `${Math.round(s / 60)} min ago`;152  if (s < 86400) return `${Math.round(s / 3600)} h ago`;153  if (s < 30 * 86400) { const d = Math.round(s / 86400); return `${d} day${d > 1 ? "s" : ""} ago`; }154  return new Date(t).toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });155}156export function dateTime(iso?: string | null): string {157  if (!iso) return "—";158  const t = Date.parse(iso);159  return Number.isNaN(t) ? "—" : new Date(t).toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });160}161export function bytesLabel(n: number): string { return n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} kB` : `${(n / 1048576).toFixed(1)} MB`; }162/** Deterministic hue (0–359) from a string, for item monograms. */163export function hueOf(s: string): number { let h = 7; for (const c of s) h = (h * 31 + c.codePointAt(0)!) % 360; return h; }164165// ── live pokes from the server (content-free): pages subscribe to refresh themselves ───────────────────────────166export const live = new EventTarget();167export function onLive(types: string[], fn: () => void): () => void {168  types.forEach((t) => live.addEventListener(t, fn));169  return () => types.forEach((t) => live.removeEventListener(t, fn));170}171
Files main
Menu

Theme