@tollbooth-dpyc/web 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,7 @@ features. It is the peer of the `tollbooth-dpyc` Python wheel.
10
10
  - **MCP client** — one shared connection to the operator, typed wrappers for
11
11
  the standard tools (balance, top-up, statement, price, profile)
12
12
  - **React components** — `NpubGate`, `NostrProfilePanel`, `SessionKeyClaim`, `WalletCard`,
13
- `AvatarPicker`, `DebugPanel`, `useSession`, `useDebugLog`
13
+ `AvatarPicker`, `DebugPanel`, `QuoteScroller`, `useSession`, `useDebugLog`
14
14
  - **Debug log** — every call, result and error from `callTool`, scrubbed of
15
15
  nsecs, hex keys, tokens and proofs before it is stored
16
16
  - **Pages proxy** — the `/mcp` Cloudflare Pages Function
@@ -61,6 +61,27 @@ configureDebugLog({ persist: true }); // optional: outlive a reload; max defau
61
61
  A site's own `debugPush` lines are scrubbed the same way. Stamps follow the
62
62
  zone the site stores under `<prefix>:timezone`, if any.
63
63
 
64
+ ### Quote scroller
65
+
66
+ Something to read while a page loads. The quotes are the site's own; the
67
+ package only scrolls them. Name a remote corpus to edit the set without a
68
+ redeploy — it is fetched once per page and replaces the inline set when it
69
+ arrives, or never, if it cannot be had:
70
+
71
+ ```tsx
72
+ import { QuoteScroller } from "@tollbooth-dpyc/web/react";
73
+ import type { Quote } from "@tollbooth-dpyc/web";
74
+
75
+ const QUOTES: Quote[] = [{ text: "Observe the seasons.", author: "Hesiod" }];
76
+
77
+ <QuoteScroller
78
+ quotes={QUOTES}
79
+ source="https://raw.githubusercontent.com/lonniev/dpyc-community/main/quotes-agrarian.json"
80
+ heading="Reading the ledger…"
81
+ spinner
82
+ />
83
+ ```
84
+
64
85
  ### Styling
65
86
 
66
87
  Components use Tailwind classes coloured only through CSS variables. Tell
package/dist/index.d.ts CHANGED
@@ -11,4 +11,5 @@ export { canSignFor, isProven, type Claim } from "./signedIn.ts";
11
11
  export { readSignInFailure, type Situation } from "./signInSituation.ts";
12
12
  export { canSignProfile, fetchProfile, publishProfile } from "./nostrProfile.ts";
13
13
  export * from "./avatar.ts";
14
+ export { loadQuotes, peekQuotes, shuffle, validQuotes, type Quote } from "./quotes.ts";
14
15
  export { captureGlobalErrors, clearDebug, configureDebugLog, debugEntries, debugLogText, debugPush, debugSeverity, onDebug, redact, type DebugEntry, type DebugLogOptions, type DebugSeverity, } from "./debugLog.ts";
package/dist/index.js CHANGED
@@ -10,4 +10,5 @@ export { canSignFor, isProven } from "./signedIn.js";
10
10
  export { readSignInFailure } from "./signInSituation.js";
11
11
  export { canSignProfile, fetchProfile, publishProfile } from "./nostrProfile.js";
12
12
  export * from "./avatar.js";
13
+ export { loadQuotes, peekQuotes, shuffle, validQuotes } from "./quotes.js";
13
14
  export { captureGlobalErrors, clearDebug, configureDebugLog, debugEntries, debugLogText, debugPush, debugSeverity, onDebug, redact, } from "./debugLog.js";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Quotations for a wait: something to read while a page loads, instead of a
3
+ * frozen "Loading…".
4
+ *
5
+ * Each site keeps its own set — agrarian for a farm, copywriters for a posting
6
+ * tool — and may name a remote corpus (a `{ quotes: [{ text, author }] }` JSON
7
+ * file) that supersedes it once it loads, so the set can be edited without a
8
+ * redeploy. The remote file is fetched at most once per page per URL; two
9
+ * sites or two corpora never share a cache entry. Anything that goes wrong —
10
+ * offline, a 404, a malformed file, an empty list — leaves the site's own set
11
+ * on screen.
12
+ */
13
+ export interface Quote {
14
+ text: string;
15
+ author: string;
16
+ }
17
+ /** Keep only well-formed rows: both fields present as non-blank strings. */
18
+ export declare function validQuotes(rows: unknown): Quote[];
19
+ /** A shuffled copy (Fisher–Yates); the input is left alone. */
20
+ export declare function shuffle<T>(items: ReadonlyArray<T>, random?: () => number): T[];
21
+ /** The remote list already loaded for `source` this page, if there is one. */
22
+ export declare function peekQuotes(source: string): Quote[] | undefined;
23
+ /**
24
+ * The quotes at `source`, or `fallback` when they cannot be had. Fetched once
25
+ * per page per URL; a failure is remembered too, so a broken corpus costs one
26
+ * request, not one per spinner.
27
+ */
28
+ export declare function loadQuotes(source: string, fallback: ReadonlyArray<Quote>, fetchImpl?: typeof fetch): Promise<Quote[]>;
package/dist/quotes.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Quotations for a wait: something to read while a page loads, instead of a
3
+ * frozen "Loading…".
4
+ *
5
+ * Each site keeps its own set — agrarian for a farm, copywriters for a posting
6
+ * tool — and may name a remote corpus (a `{ quotes: [{ text, author }] }` JSON
7
+ * file) that supersedes it once it loads, so the set can be edited without a
8
+ * redeploy. The remote file is fetched at most once per page per URL; two
9
+ * sites or two corpora never share a cache entry. Anything that goes wrong —
10
+ * offline, a 404, a malformed file, an empty list — leaves the site's own set
11
+ * on screen.
12
+ */
13
+ /** Keep only well-formed rows: both fields present as non-blank strings. */
14
+ export function validQuotes(rows) {
15
+ if (!Array.isArray(rows))
16
+ return [];
17
+ return rows.flatMap((row) => {
18
+ if (typeof row !== "object" || row === null)
19
+ return [];
20
+ const { text, author } = row;
21
+ if (typeof text !== "string" || typeof author !== "string")
22
+ return [];
23
+ if (!text.trim() || !author.trim())
24
+ return [];
25
+ return [{ text, author }];
26
+ });
27
+ }
28
+ /** A shuffled copy (Fisher–Yates); the input is left alone. */
29
+ export function shuffle(items, random = Math.random) {
30
+ const copy = items.slice();
31
+ for (let i = copy.length - 1; i > 0; i--) {
32
+ const j = Math.floor(random() * (i + 1));
33
+ [copy[i], copy[j]] = [copy[j], copy[i]];
34
+ }
35
+ return copy;
36
+ }
37
+ // Per source URL: the validated remote list ([] when the fetch failed), and
38
+ // the one request in flight so concurrent callers share it.
39
+ const loaded = new Map();
40
+ const inflight = new Map();
41
+ /** The remote list already loaded for `source` this page, if there is one. */
42
+ export function peekQuotes(source) {
43
+ const list = loaded.get(source);
44
+ return list && list.length ? list : undefined;
45
+ }
46
+ /**
47
+ * The quotes at `source`, or `fallback` when they cannot be had. Fetched once
48
+ * per page per URL; a failure is remembered too, so a broken corpus costs one
49
+ * request, not one per spinner.
50
+ */
51
+ export async function loadQuotes(source, fallback, fetchImpl = globalThis.fetch) {
52
+ const pick = (list) => (list.length ? list : fallback.slice());
53
+ const done = loaded.get(source);
54
+ if (done)
55
+ return pick(done);
56
+ let pending = inflight.get(source);
57
+ if (!pending) {
58
+ pending = (async () => {
59
+ let list = [];
60
+ try {
61
+ const res = await fetchImpl(source, { cache: "no-cache" });
62
+ if (res.ok) {
63
+ const body = (await res.json());
64
+ list = validQuotes(body?.quotes);
65
+ }
66
+ }
67
+ catch {
68
+ list = [];
69
+ }
70
+ loaded.set(source, list);
71
+ inflight.delete(source);
72
+ return list;
73
+ })();
74
+ inflight.set(source, pending);
75
+ }
76
+ return pick(await pending);
77
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Something worth reading while a page loads — rotating quotations instead of
3
+ * a frozen "Loading…". First written for optionality-mcp as a port of the
4
+ * Pricing Studio app's LoadingQuoteView, then copied across the fleet; this is
5
+ * the one copy.
6
+ *
7
+ * The site brings its own quotes (`quotes`), so the scroller always has
8
+ * something to show without the network. `source` may name a remote corpus
9
+ * that supersedes them once it loads (see `loadQuotes`).
10
+ *
11
+ * The order is shuffled and then walked, so nothing repeats until every quote
12
+ * has shown. It cross-fades (instantly under reduced motion), stops while the
13
+ * tab is hidden, and reserves the height of its longest quote so the page
14
+ * does not jump as quotes change. Coloured only through `--tb-*` tokens.
15
+ */
16
+ import { type Quote } from "../quotes.ts";
17
+ export interface QuoteScrollerProps {
18
+ /** The site's own quotes: shown at once, and kept if `source` fails. Pass a
19
+ * module constant. */
20
+ quotes: ReadonlyArray<Quote>;
21
+ /** URL of a `{ quotes: [{ text, author }] }` JSON file that supersedes
22
+ * `quotes` once it loads. */
23
+ source?: string;
24
+ /** A status line above the quotes ("Reading the ledger…"). */
25
+ heading?: string;
26
+ /** Show a spinner beside the heading. Default false. */
27
+ spinner?: boolean;
28
+ /** How long each quote stays, in ms. Default 3500. */
29
+ intervalMs?: number;
30
+ /** Classes for the outer box (padding, placement). */
31
+ className?: string;
32
+ }
33
+ export default function QuoteScroller({ quotes, source, heading, spinner, intervalMs, className, }: QuoteScrollerProps): import("react").JSX.Element;
@@ -0,0 +1,106 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * Something worth reading while a page loads — rotating quotations instead of
4
+ * a frozen "Loading…". First written for optionality-mcp as a port of the
5
+ * Pricing Studio app's LoadingQuoteView, then copied across the fleet; this is
6
+ * the one copy.
7
+ *
8
+ * The site brings its own quotes (`quotes`), so the scroller always has
9
+ * something to show without the network. `source` may name a remote corpus
10
+ * that supersedes them once it loads (see `loadQuotes`).
11
+ *
12
+ * The order is shuffled and then walked, so nothing repeats until every quote
13
+ * has shown. It cross-fades (instantly under reduced motion), stops while the
14
+ * tab is hidden, and reserves the height of its longest quote so the page
15
+ * does not jump as quotes change. Coloured only through `--tb-*` tokens.
16
+ */
17
+ import { useEffect, useMemo, useRef, useState } from "react";
18
+ import { Loader2 } from "lucide-react";
19
+ import { loadQuotes, peekQuotes, shuffle } from "../quotes.js";
20
+ const FADE_MS = 450;
21
+ function useReducedMotion() {
22
+ const query = "(prefers-reduced-motion: reduce)";
23
+ const [reduced, setReduced] = useState(() => typeof window !== "undefined" && !!window.matchMedia?.(query).matches);
24
+ useEffect(() => {
25
+ const mq = window.matchMedia?.(query);
26
+ if (!mq)
27
+ return;
28
+ const on = () => setReduced(mq.matches);
29
+ mq.addEventListener("change", on);
30
+ return () => mq.removeEventListener("change", on);
31
+ }, []);
32
+ return reduced;
33
+ }
34
+ function usePageVisible() {
35
+ const [shown, setShown] = useState(() => typeof document === "undefined" || document.visibilityState !== "hidden");
36
+ useEffect(() => {
37
+ const on = () => setShown(document.visibilityState !== "hidden");
38
+ document.addEventListener("visibilitychange", on);
39
+ return () => document.removeEventListener("visibilitychange", on);
40
+ }, []);
41
+ return shown;
42
+ }
43
+ export default function QuoteScroller({ quotes, source, heading, spinner = false, intervalMs = 3500, className = "", }) {
44
+ const reduced = useReducedMotion();
45
+ const pageVisible = usePageVisible();
46
+ // Content, not identity: a site that passes an inline array still gets one
47
+ // shuffle, not one per render.
48
+ const signature = quotes.map((q) => `${q.text}\u0000${q.author}`).join("\u0001");
49
+ const [list, setList] = useState(() => shuffle((source && peekQuotes(source)) || quotes));
50
+ const [index, setIndex] = useState(0);
51
+ const [shown, setShown] = useState(false);
52
+ const key = `${source ?? ""}\u0002${signature}`;
53
+ const first = useRef(key);
54
+ useEffect(() => {
55
+ if (first.current !== key) {
56
+ first.current = key;
57
+ setList(shuffle((source && peekQuotes(source)) || quotes));
58
+ setIndex(0);
59
+ }
60
+ if (!source || peekQuotes(source))
61
+ return; // nothing to fetch, or already showing it
62
+ let alive = true;
63
+ void loadQuotes(source, quotes).then((loaded) => {
64
+ if (!alive || !peekQuotes(source))
65
+ return; // the site's own set is already up
66
+ setList(shuffle(loaded));
67
+ setIndex(0);
68
+ });
69
+ return () => {
70
+ alive = false;
71
+ };
72
+ // `key` stands for `quotes` and `source`, by content.
73
+ }, [key]);
74
+ // Fade the first quote in.
75
+ useEffect(() => {
76
+ const id = window.setTimeout(() => setShown(true), 30);
77
+ return () => window.clearTimeout(id);
78
+ }, []);
79
+ useEffect(() => {
80
+ if (list.length <= 1 || !pageVisible)
81
+ return;
82
+ const fade = reduced ? 0 : FADE_MS;
83
+ let swap;
84
+ const tick = window.setInterval(() => {
85
+ setShown(false);
86
+ swap = window.setTimeout(() => {
87
+ setIndex((i) => (i + 1) % list.length);
88
+ setShown(true);
89
+ }, fade);
90
+ }, intervalMs);
91
+ return () => {
92
+ window.clearInterval(tick);
93
+ window.clearTimeout(swap);
94
+ setShown(true);
95
+ };
96
+ }, [list, intervalMs, reduced, pageVisible]);
97
+ const longest = useMemo(() => list.reduce((a, q) => (!a || q.text.length + q.author.length > a.text.length + a.author.length ? q : a), undefined), [list]);
98
+ const q = list[index % Math.max(list.length, 1)];
99
+ return (_jsxs("div", { className: `px-4 py-6 text-center ${className}`, children: [heading && (_jsxs("div", { className: "mb-5 flex items-center justify-center gap-2 font-mono text-[11px] uppercase tracking-[0.3em] text-[var(--tb-accent)]", children: [spinner && _jsx(Loader2, { "aria-hidden": true, className: "h-3.5 w-3.5 motion-safe:animate-spin" }), heading] })), q && longest && (_jsxs("div", { className: "mx-auto grid max-w-xl", children: [_jsx(QuoteText, { quote: longest, className: "invisible [grid-area:1/1]", hidden: true }), _jsx(QuoteText, { quote: q, className: "[grid-area:1/1]", style: {
100
+ opacity: shown ? 1 : 0,
101
+ transition: reduced ? "none" : `opacity ${FADE_MS}ms ease`,
102
+ }, live: true })] }))] }));
103
+ }
104
+ function QuoteText({ quote, className, style, hidden = false, live = false, }) {
105
+ return (_jsxs("figure", { className: `m-0 flex flex-col justify-center gap-3 ${className}`, style: style, "aria-hidden": hidden || undefined, "aria-live": live ? "polite" : undefined, "aria-atomic": live || undefined, children: [_jsxs("blockquote", { className: "m-0 font-serif text-[17px] italic leading-relaxed text-[var(--tb-ink)]", children: [_jsx("span", { className: "not-italic text-[var(--tb-accent)]", children: "\u201C" }), quote.text, _jsx("span", { className: "not-italic text-[var(--tb-accent)]", children: "\u201D" })] }), _jsx("figcaption", { className: "font-mono text-[10.5px] uppercase tracking-[0.22em] text-[var(--tb-muted)]", children: quote.author })] }));
106
+ }
@@ -3,6 +3,7 @@ export { default as AvatarPicker } from "./AvatarPicker.tsx";
3
3
  export { default as DebugPanel, type DebugPanelProps } from "./DebugPanel.tsx";
4
4
  export { default as NpubGate } from "./NpubGate.tsx";
5
5
  export { default as NostrProfilePanel } from "./NostrProfilePanel.tsx";
6
+ export { default as QuoteScroller, type QuoteScrollerProps } from "./QuoteScroller.tsx";
6
7
  export { default as SessionKeyClaim } from "./SessionKeyClaim.tsx";
7
8
  export { default as WalletCard } from "./WalletCard.tsx";
8
9
  export { useSession, type Session } from "./useSession.ts";
@@ -3,6 +3,7 @@ export { default as AvatarPicker } from "./AvatarPicker.js";
3
3
  export { default as DebugPanel } from "./DebugPanel.js";
4
4
  export { default as NpubGate } from "./NpubGate.js";
5
5
  export { default as NostrProfilePanel } from "./NostrProfilePanel.js";
6
+ export { default as QuoteScroller } from "./QuoteScroller.js";
6
7
  export { default as SessionKeyClaim } from "./SessionKeyClaim.js";
7
8
  export { default as WalletCard } from "./WalletCard.js";
8
9
  export { useSession } from "./useSession.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tollbooth-dpyc/web",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Shared browser SDK for Tollbooth DPYC operator front ends: npub sign-in, proofs, MCP client, profile and wallet",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Lonnie VanZandt",