From fa7d614fa495608f3e9b7922e30a18db4269d55b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:10:59 +0000 Subject: [PATCH 01/11] feat(tc-reference): safer backups, undoable restore, phrase guard, 6-month drill cap - Export backups through the share sheet (Save to Files) where files can be shared, falling back to a download link. The backup reminder only records a backup when the share finishes or the download starts; closing the share sheet records nothing. The reminder nudge stays up on cancel. - Restore keeps a snapshot of the replaced data (tc_restore_snapshot, device-only, never in backups) and Settings > Backup offers Undo restore for 30 days. - Reject backup files over 5 MB before reading them; a backup from a newer app version asks the reader to update first; versions 1 and 2 restore. - Backup format v2 adds tc_start_opened, tc_recent_cards and tc_welcome_dismissed. - Saved-phrase guard: a committed hashed snapshot of every saveable phrase fails the tests when one disappears without a REPHRASED or retired entry. - Cap drill review intervals at 180 days ("In ~6 months"). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .../src/components/backup-section.tsx | 87 +- .../src/components/data-safety-nudge.tsx | 8 +- artifacts/tc-reference/src/lib/backup.ts | 229 +- artifacts/tc-reference/src/lib/drill-state.ts | 17 +- .../tc-reference/src/lib/favourites-state.ts | 7 +- .../tc-reference/src/lib/recent-cards.ts | 4 +- artifacts/tc-reference/src/lib/share.ts | 22 +- artifacts/tc-reference/src/lib/start-path.ts | 4 +- .../src/test/backup-section.test.tsx | 81 +- .../tc-reference/src/test/backup.test.ts | 184 +- .../src/test/data-safety.test.tsx | 7 +- .../tc-reference/src/test/drill-state.test.ts | 15 + .../test/fixtures/saved-phrase-snapshot.json | 6214 +++++++++++++++++ .../src/test/saved-phrase-guard.test.ts | 156 + 14 files changed, 6977 insertions(+), 58 deletions(-) create mode 100644 artifacts/tc-reference/src/test/fixtures/saved-phrase-snapshot.json create mode 100644 artifacts/tc-reference/src/test/saved-phrase-guard.test.ts diff --git a/artifacts/tc-reference/src/components/backup-section.tsx b/artifacts/tc-reference/src/components/backup-section.tsx index 8fdddbb..d5a757b 100644 --- a/artifacts/tc-reference/src/components/backup-section.tsx +++ b/artifacts/tc-reference/src/components/backup-section.tsx @@ -1,11 +1,14 @@ import { useRef, useState } from "react"; -import { Download, Upload } from "lucide-react"; +import { Download, RotateCcw, Upload } from "lucide-react"; import { Button } from "@/components/ui/button"; import { BackupError, - downloadBackup, + checkBackupFileSize, importBackup, + loadRestoreSnapshot, parseBackup, + saveBackup, + undoRestore, } from "@/lib/backup"; import { hasUserData, @@ -33,18 +36,23 @@ export function BackupSection() { const [pending, setPending] = useState<{ name: string; text: string } | null>( null, ); + const [confirmUndo, setConfirmUndo] = useState(false); const [error, setError] = useState(null); // Read on mount (the sheet unmounts when closed) and after each export. const [safety, setSafety] = useState(() => ({ state: loadDataSafety(), hasData: hasUserData(), })); + const [snapshot] = useState(() => loadRestoreSnapshot()); const lastBackupAt = safety.state.lastBackupAt; const reminderDue = isBackupReminderDue(safety.state, safety.hasData); - const handleExport = () => { + const handleExport = async () => { setError(null); - downloadBackup(); + const outcome = await saveBackup(); + if (outcome === "failed") { + setError("Couldn't save the backup file. Please try again."); + } setSafety({ state: loadDataSafety(), hasData: hasUserData() }); }; @@ -55,7 +63,9 @@ export function BackupSection() { if (!file) return; setError(null); setPending(null); + setConfirmUndo(false); try { + checkBackupFileSize(file); // before reading a huge file into memory const text = await file.text(); parseBackup(text); // validate before asking to confirm setPending({ name: file.name, text }); @@ -77,6 +87,17 @@ export function BackupSection() { window.location.reload(); }; + const handleUndo = () => { + try { + undoRestore(); + } catch (err) { + setConfirmUndo(false); + setError(errorMessage(err)); + return; + } + window.location.reload(); + }; + return (
+ {snapshot && !pending && ( +
+

+ Restored a backup on {formatBackupDate(snapshot.savedAt)}. Your data + from before it is kept for 30 days. +

+ +
+ )} + + {snapshot && confirmUndo && !pending && ( +
+

+ This puts back your saved items, drill progress, playbooks and + settings from before the restore on{" "} + {formatBackupDate(snapshot.savedAt)}. Anything changed since then is + replaced. +

+
+ + +
+
+ )} + {pending && (
Importing {pending.name} replaces your current saved items, drill progress, playbooks and settings on this device. - This can't be undone. + A copy of your current data is kept, so you can undo this here for + 30 days.

    {chain.example.map((line, j) => (
  1. {j + 1} - {line} +
  2. ))} diff --git a/artifacts/tc-reference/src/components/card-detail/method-section.tsx b/artifacts/tc-reference/src/components/card-detail/method-section.tsx index 63738bf..136a015 100644 --- a/artifacts/tc-reference/src/components/card-detail/method-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/method-section.tsx @@ -11,6 +11,7 @@ import { Surface, } from "./card-ui"; import { CoreFormula } from "./overview-section"; +import { CardRefText } from "./card-ref-text"; // Field-tip text often already opens with its own label ("Don't open with...", // "They say: ..."). Only add the label when the text doesn't carry one. @@ -38,7 +39,13 @@ export function DepthDialSection({ cardData }: { cardData: CardData }) { > {row.depth} - {row.useWhen} + + + } /> @@ -109,7 +116,7 @@ function StepBody({ step }: { step: MethodStep }) { className="text-[15px] leading-[1.5] whitespace-pre-line" style={{ color: "var(--fg-80)" }} > - {step.body} +

    {step.examples && step.examples.length > 0 && ( @@ -118,7 +125,9 @@ function StepBody({ step }: { step: MethodStep }) { {step.examples.map((ex, j) => ( - {ex.text} + + + ))} diff --git a/artifacts/tc-reference/src/components/card-detail/overview-section.tsx b/artifacts/tc-reference/src/components/card-detail/overview-section.tsx index cfc81df..4110db2 100644 --- a/artifacts/tc-reference/src/components/card-detail/overview-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/overview-section.tsx @@ -2,6 +2,7 @@ import { X } from "lucide-react"; import type { CardData } from "@/lib/card-types"; import { CardBlock, MarkedList, Surface } from "./card-ui"; import { FORMULA_LABEL } from "./card-sections"; +import { CardRefText } from "./card-ref-text"; /** Chips suit short entries; a card's longer ones read better as a list. */ const CHIP_MAX_CHARS = 44; @@ -53,6 +54,9 @@ export function SkipWhenSection({ cardData }: { cardData: CardData }) { ( + + )} mark={ } diff --git a/artifacts/tc-reference/src/components/card-detail/practice-section.tsx b/artifacts/tc-reference/src/components/card-detail/practice-section.tsx index 43dbd14..c45dff4 100644 --- a/artifacts/tc-reference/src/components/card-detail/practice-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/practice-section.tsx @@ -8,6 +8,7 @@ import { loadDrillState, } from "@/lib/drill-state"; import { CardBlock, EYEBROW, Meta, NumberDisc, Surface } from "./card-ui"; +import { CardRefText } from "./card-ref-text"; /** * Where Daily Drill is with this card, if this is the card it is on. The @@ -90,7 +91,7 @@ export function PracticeSection({ className="text-[15px] leading-[1.45]" style={{ color: "var(--fg-80)" }} > - {today.task} +
{place.inDrill && ( @@ -134,7 +135,7 @@ export function PracticeSection({ className="text-[14px] leading-[1.45]" style={{ color: "var(--fg-70)" }} > - {d.task} + diff --git a/artifacts/tc-reference/src/components/card-detail/related-section.tsx b/artifacts/tc-reference/src/components/card-detail/related-section.tsx index 5f59935..ff2e761 100644 --- a/artifacts/tc-reference/src/components/card-detail/related-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/related-section.tsx @@ -2,6 +2,7 @@ import { ChevronRight } from "lucide-react"; import type { CardData } from "@/lib/card-types"; import { CardBlock, Meta, Surface } from "./card-ui"; import { CARD_TITLE_MAP } from "./card-sections"; +import { CardRefText } from "./card-ref-text"; // ── Pairs well with ── export function RelatedSection({ @@ -39,9 +40,19 @@ export function RelatedSection({ {/* Shortened where it is a quick "where next" */} {limit ? ( - {rt.reason} + + + ) : ( - rt.reason + )} diff --git a/artifacts/tc-reference/src/components/card-detail/tree-section.tsx b/artifacts/tc-reference/src/components/card-detail/tree-section.tsx index f5e5283..be10895 100644 --- a/artifacts/tc-reference/src/components/card-detail/tree-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/tree-section.tsx @@ -1,6 +1,9 @@ import type { CardData } from "@/lib/card-types"; import { splitCondition } from "./best-line"; import { CardBlock, CopyRow, Surface } from "./card-ui"; +import { CardRefText } from "./card-ref-text"; +import { CARD_TITLE_MAP } from "./card-sections"; +import { hasCardRefs } from "@/lib/card-refs"; // ── Decide in the moment ── export function TreeSection({ cardData }: { cardData: CardData }) { @@ -9,6 +12,11 @@ export function TreeSection({ cardData }: { cardData: CardData }) { {cardData.decisionTree.map((item, i) => { const condition = splitCondition(item.condition); + // A row with a phrase is one copy button; when its action names + // another card, the copy button holds only the phrase so the + // reference can be a real link + const linked = + !!item.phrase && hasCardRefs(item.action, CARD_TITLE_MAP); const above = ( <> - {item.action} + ); + if (linked) { + return ( +
+
{above}
+ +
+ ); + } return item.phrase ? ( ) : ( diff --git a/artifacts/tc-reference/src/lib/card-refs.ts b/artifacts/tc-reference/src/lib/card-refs.ts new file mode 100644 index 0000000..7b5f3d0 --- /dev/null +++ b/artifacts/tc-reference/src/lib/card-refs.ts @@ -0,0 +1,114 @@ +// Card text cites other techniques by id, written either after the move's +// name ("Apologise (TC101)", "Switch to broken record (TC107)") or bare in a +// sentence ("TC033 Minimal encouragers uses tiny signals", "TC003, then +// TC001"). parseCardRefs splits such text into plain runs and references so +// the card can show each reference as a link that names the technique. + +export type CardRefSegment = + | { type: "text"; text: string } + | { + type: "ref"; + id: string; + /** What to show: the words already in the sentence, or the title. */ + label: string; + /** + * True when the label is the sentence's own words (the name the + * author wrote next to the id), so it reads as part of the line; false + * when the title stands in for a bare or parenthesised id. + */ + inline: boolean; + }; + +const REF = /\((TC\d{3})\)|\b(TC\d{3})\b/g; +const WORD = /[\p{L}\p{N}]/u; + +function isWordChar(ch: string | undefined): boolean { + return ch !== undefined && WORD.test(ch); +} + +function pushText(out: CardRefSegment[], text: string) { + if (!text) return; + const last = out[out.length - 1]; + if (last?.type === "text") last.text += text; + else out.push({ type: "text", text }); +} + +/** + * Split `text` into plain runs and card references. + * + * - "Name (TC101)": when the words before the id are the card's title, they + * become the link and the id is dropped; otherwise the id becomes a link + * labelled with the title. + * - "TC033 Minimal encouragers": a bare id followed by its own title links + * the title and drops the id; a bare id alone becomes a titled link. + * - Unknown ids stay exactly as written. + * - A reference to `selfId` (the card being read) is not linked: the title + * stays as plain words and a parenthesised id is dropped. + */ +export function parseCardRefs( + text: string, + titles: Readonly>, + selfId?: string, +): CardRefSegment[] { + const out: CardRefSegment[] = []; + let cursor = 0; + for (const m of text.matchAll(REF)) { + const start = m.index; + const id = m[1] ?? m[2]; + const title = titles[id]; + if (!title) continue; // unknown: left in the surrounding text + const before = text.slice(cursor, start); + const self = id === selfId; + let end = start + m[0].length; + + if (m[1]) { + // "(TC101)": look for the title just before it + const trimmed = before.replace(/\s+$/, ""); + const at = trimmed.length - title.length; + const named = + at >= 0 && + trimmed.slice(at).toLowerCase() === title.toLowerCase() && + !isWordChar(trimmed[at - 1]); + if (named) { + pushText(out, trimmed.slice(0, at)); + const label = trimmed.slice(at); + if (self) pushText(out, label); + else out.push({ type: "ref", id, label, inline: true }); + } else if (self) { + // Drop "(TC003)" and the space before it + pushText(out, trimmed); + } else { + pushText(out, before); + out.push({ type: "ref", id, label: title, inline: false }); + } + } else { + // Bare "TC033", maybe followed by its title + pushText(out, before); + const after = text.slice(end); + const lead = after.match(/^\s+/)?.[0] ?? ""; + const candidate = after.slice(lead.length, lead.length + title.length); + const named = + lead.length > 0 && + candidate.toLowerCase() === title.toLowerCase() && + !isWordChar(after[lead.length + title.length]); + const label = named ? candidate : title; + if (named) end += lead.length + title.length; + if (self) pushText(out, label); + else out.push({ type: "ref", id, label, inline: named }); + } + cursor = end; + } + pushText(out, text.slice(cursor)); + return out; +} + +/** True when `text` cites at least one known card. */ +export function hasCardRefs( + text: string, + titles: Readonly>, +): boolean { + for (const m of text.matchAll(REF)) { + if (titles[m[1] ?? m[2]]) return true; + } + return false; +} diff --git a/artifacts/tc-reference/src/test/card-refs.test.ts b/artifacts/tc-reference/src/test/card-refs.test.ts new file mode 100644 index 0000000..ad5b530 --- /dev/null +++ b/artifacts/tc-reference/src/test/card-refs.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vitest"; +import { hasCardRefs, parseCardRefs } from "@/lib/card-refs"; + +const TITLES: Record = { + TC001: "Live thread follow-ups", + TC003: "Comment-before-question", + TC011: "Summary check", + TC033: "Minimal encouragers", + TC101: "Effective apology", + TC107: "Fogging and broken record", +}; + +describe("parseCardRefs", () => { + it("returns plain text untouched", () => { + expect(parseCardRefs("No references here.", TITLES)).toEqual([ + { type: "text", text: "No references here." }, + ]); + }); + + it("links the title written before a parenthesised id", () => { + expect(parseCardRefs("Then use a summary check (TC011).", TITLES)).toEqual([ + { type: "text", text: "Then use a " }, + { type: "ref", id: "TC011", label: "summary check", inline: true }, + { type: "text", text: "." }, + ]); + }); + + it("replaces a parenthesised id with the title when the words differ", () => { + expect( + parseCardRefs( + "They repeat after a no. Switch to broken record (TC107).", + TITLES, + ), + ).toEqual([ + { + type: "text", + text: "They repeat after a no. Switch to broken record ", + }, + { + type: "ref", + id: "TC107", + label: "Fogging and broken record", + inline: false, + }, + { type: "text", text: "." }, + ]); + }); + + it("does not match a title that is only the end of a longer word", () => { + const segments = parseCardRefs("Resummary check (TC011)", TITLES); + expect(segments[1]).toMatchObject({ + label: "Summary check", + inline: false, + }); + }); + + it("links a bare id followed by its title as the title alone", () => { + expect( + parseCardRefs("TC033 Minimal encouragers uses tiny signals.", TITLES), + ).toEqual([ + { type: "ref", id: "TC033", label: "Minimal encouragers", inline: true }, + { type: "text", text: " uses tiny signals." }, + ]); + }); + + it("names a bare id that stands alone", () => { + expect(parseCardRefs("TC003, then TC001", TITLES)).toEqual([ + { + type: "ref", + id: "TC003", + label: "Comment-before-question", + inline: false, + }, + { type: "text", text: ", then " }, + { + type: "ref", + id: "TC001", + label: "Live thread follow-ups", + inline: false, + }, + ]); + }); + + it("leaves unknown ids as written", () => { + expect(parseCardRefs("See TC999 and (TC998).", TITLES)).toEqual([ + { type: "text", text: "See TC999 and (TC998)." }, + ]); + }); + + it("does not link the card being read", () => { + expect( + parseCardRefs( + "Comment first (TC003), then follow the thread (TC001).", + TITLES, + "TC003", + ), + ).toEqual([ + { type: "text", text: "Comment first, then follow the thread " }, + { + type: "ref", + id: "TC001", + label: "Live thread follow-ups", + inline: false, + }, + { type: "text", text: "." }, + ]); + expect( + parseCardRefs("TC003 shapes the question.", TITLES, "TC003"), + ).toEqual([ + { type: "text", text: "Comment-before-question shapes the question." }, + ]); + }); + + it("keeps every character of the source text accounted for", () => { + const text = 'You: "Exhausting how?" (TC001) and Effective apology (TC101)'; + const segments = parseCardRefs(text, TITLES); + expect(segments.filter((s) => s.type === "ref")).toHaveLength(2); + expect(segments.at(-1)).toMatchObject({ + type: "ref", + label: "Effective apology", + inline: true, + }); + }); +}); + +describe("hasCardRefs", () => { + it("is true only for known ids", () => { + expect(hasCardRefs("Apologise (TC101).", TITLES)).toBe(true); + expect(hasCardRefs("See TC999.", TITLES)).toBe(false); + expect(hasCardRefs("Nothing.", TITLES)).toBe(false); + }); +}); From 14a35865f6b4025209198b5180ced46309c5d861 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:19:50 +0000 Subject: [PATCH 05/11] Group the Library's large categories into named runs Connection (54), Clarity (28) and Resilience (16) now show as short groups under their own headings, named by what the reader wants to do ("Draw them out", "Raise a problem or say no", "Repair after a misstep"). Grouping lives in lib/category-groups.ts (ids only, so it stays on the light first-paint path) and a new GroupedCardList component; library.tsx only swaps its list for it. Filters, search and Start-here sort apply within groups; flat sorts stay one list. A test keeps every card in exactly one group. Moves clearly misplaced cards into Connection: TC007 No one-upping and TC009 Anti-boomerasking (from Resilience), TC012 Full-attention signal and TC015 Premature advice restraint (from Clarity). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .../components/library/grouped-card-list.tsx | 58 ++++++ .../tc-reference/src/lib/category-groups.ts | 191 ++++++++++++++++++ artifacts/tc-reference/src/lib/data.ts | 70 +++---- artifacts/tc-reference/src/pages/library.tsx | 11 +- .../src/test/category-groups.test.ts | 65 ++++++ .../src/test/library-home.test.tsx | 11 +- 6 files changed, 366 insertions(+), 40 deletions(-) create mode 100644 artifacts/tc-reference/src/components/library/grouped-card-list.tsx create mode 100644 artifacts/tc-reference/src/lib/category-groups.ts create mode 100644 artifacts/tc-reference/src/test/category-groups.test.ts diff --git a/artifacts/tc-reference/src/components/library/grouped-card-list.tsx b/artifacts/tc-reference/src/components/library/grouped-card-list.tsx new file mode 100644 index 0000000..968a06c --- /dev/null +++ b/artifacts/tc-reference/src/components/library/grouped-card-list.tsx @@ -0,0 +1,58 @@ +import type { ReactNode } from "react"; +import { groupCategoryCards } from "@/lib/category-groups"; + +const LIST_CLASS = "grid gap-2 lg:grid-cols-2"; + +function slug(name: string) { + return name.toLowerCase().replace(/[^a-z0-9]+/g, "-"); +} + +/** + * One category's rows. Large categories split into their named groups + * ("Draw them out", "Repair after a misstep"), each a short run under its + * own heading; small categories and the flat sorted list stay one run. + */ +export function GroupedCardList({ + category, + cards, + renderCard, +}: { + /** null for the flat, cross-category list. */ + category: string | null; + cards: T[]; + renderCard: (card: T) => ReactNode; +}) { + const groups = category + ? groupCategoryCards(category, cards) + : [{ name: null, cards }]; + if (groups.length === 1 && groups[0].name === null) { + return
    {cards.map(renderCard)}
; + } + return ( +
+ {groups.map((group) => ( +
+

+ {group.name} + + {group.cards.length} + + {group.cards.length === 1 ? " technique" : " techniques"} + + +

+
    {group.cards.map(renderCard)}
+
+ ))} +
+ ); +} diff --git a/artifacts/tc-reference/src/lib/category-groups.ts b/artifacts/tc-reference/src/lib/category-groups.ts new file mode 100644 index 0000000..10219e8 --- /dev/null +++ b/artifacts/tc-reference/src/lib/category-groups.ts @@ -0,0 +1,191 @@ +// Subgroups for the Library's large categories, so a 54-card list reads as a +// handful of short runs named by what the reader wants to do. Light metadata +// only (ids), like ./data: the Library imports it on first paint. +// +// Every card in a grouped category sits in exactly one group (checked in +// content-invariants). Categories small enough to scan at a glance are not +// grouped. + +export interface CategoryGroup { + /** Short, verb-first: what the reader is trying to do. */ + name: string; + ids: readonly string[]; +} + +export const CATEGORY_GROUPS: Readonly< + Record +> = { + "Connection / Warmth": [ + { + name: "Open and build rapport", + ids: [ + "TC010", + "TC024", + "TC036", + "TC032", + "TC039", + "TC054", + "TC057", + "TC063", + "TC067", + "TC072", + "TC108", + ], + }, + { + name: "Draw them out", + ids: [ + "TC001", + "TC003", + "TC012", + "TC023", + "TC025", + "TC030", + "TC033", + "TC087", + "TC093", + "TC100", + ], + }, + { + name: "Reflect and check", + ids: [ + "TC004", + "TC006", + "TC037", + "TC040", + "TC058", + "TC060", + "TC061", + "TC064", + "TC084", + "TC109", + ], + }, + { + name: "Support before solving", + ids: [ + "TC002", + "TC005", + "TC007", + "TC009", + "TC015", + "TC070", + "TC090", + "TC098", + "TC104", + ], + }, + { + name: "Appreciate and turn toward", + ids: ["TC016", "TC018", "TC022", "TC075", "TC082", "TC096"], + }, + { + name: "Steer and return to threads", + ids: [ + "TC038", + "TC041", + "TC056", + "TC059", + "TC062", + "TC065", + "TC071", + "TC078", + ], + }, + ], + "Clarity / Direction": [ + { + name: "Make a clear ask", + ids: ["TC013", "TC019", "TC020", "TC068", "TC094"], + }, + { + name: "Structure your point", + ids: [ + "TC042", + "TC044", + "TC047", + "TC048", + "TC049", + "TC050", + "TC066", + "TC088", + ], + }, + { + name: "Guide the conversation", + ids: [ + "TC011", + "TC014", + "TC034", + "TC043", + "TC045", + "TC046", + "TC051", + "TC080", + "TC086", + ], + }, + { + name: "Raise a problem or say no", + ids: ["TC052", "TC053", "TC074", "TC081", "TC095", "TC102"], + }, + ], + "Resilience / Recovery": [ + { + name: "Handle pushback", + ids: [ + "TC069", + "TC073", + "TC077", + "TC079", + "TC083", + "TC089", + "TC092", + "TC107", + ], + }, + { + name: "Repair after a misstep", + ids: ["TC101", "TC103", "TC105"], + }, + { + name: "Avoid common traps", + ids: ["TC008", "TC076", "TC085", "TC091", "TC099"], + }, + ], +}; + +export interface GroupedCards { + /** null for a category without groups: one plain run. */ + name: string | null; + cards: T[]; +} + +/** + * Split a category's (already filtered and sorted) cards into its groups, + * in group order, keeping the incoming order within each group and leaving + * out groups with nothing to show. A card missing from the groups lands in + * a final "More" run rather than disappearing. + */ +export function groupCategoryCards( + category: string, + cards: readonly T[], +): GroupedCards[] { + const groups = CATEGORY_GROUPS[category]; + if (!groups) return [{ name: null, cards: [...cards] }]; + const groupOf = new Map(); + groups.forEach((g, i) => g.ids.forEach((id) => groupOf.set(id, i))); + const runs: T[][] = groups.map(() => []); + const rest: T[] = []; + for (const card of cards) { + const i = groupOf.get(card.id); + if (i === undefined) rest.push(card); + else runs[i].push(card); + } + const out: GroupedCards[] = groups + .map((g, i) => ({ name: g.name, cards: runs[i] })) + .filter((g) => g.cards.length > 0); + if (rest.length) out.push({ name: "More", cards: rest }); + return out; +} diff --git a/artifacts/tc-reference/src/lib/data.ts b/artifacts/tc-reference/src/lib/data.ts index cf2dd6d..2a6e04b 100644 --- a/artifacts/tc-reference/src/lib/data.ts +++ b/artifacts/tc-reference/src/lib/data.ts @@ -116,14 +116,6 @@ export const LIBRARY_CATEGORIES: Record = { impact: "high", difficulty: "Easy-Medium", }, - { - id: "TC012", - title: "Full-attention signal", - summary: 'Phone away, body toward them, and: "Go on, I\'m with you."', - loaded: true, - impact: "high", - difficulty: "Easy", - }, { id: "TC013", title: "Clean request", @@ -141,15 +133,6 @@ export const LIBRARY_CATEGORIES: Record = { impact: "high", difficulty: "Medium", }, - { - id: "TC015", - title: "Premature advice restraint", - summary: - "Reflect once, then ask whether they want ideas or just to be heard.", - loaded: true, - impact: "medium", - difficulty: "Medium", - }, { id: "TC019", title: "Small ask", @@ -430,6 +413,24 @@ export const LIBRARY_CATEGORIES: Record = { impact: "high", difficulty: "Easy-Medium", }, + { + id: "TC007", + title: "No one-upping discipline", + summary: + 'Before saying "me too", ask one more question about their story.', + loaded: true, + impact: "low", + difficulty: "Medium", + }, + { + id: "TC009", + title: "Anti-boomerasking discipline", + summary: + "Ask one real follow-up or reflect before sharing your related story.", + loaded: true, + impact: "low", + difficulty: "Medium", + }, { id: "TC010", title: "Warm presence", @@ -439,6 +440,23 @@ export const LIBRARY_CATEGORIES: Record = { impact: "high", difficulty: "Easy-Medium", }, + { + id: "TC012", + title: "Full-attention signal", + summary: 'Phone away, body toward them, and: "Go on, I\'m with you."', + loaded: true, + impact: "high", + difficulty: "Easy", + }, + { + id: "TC015", + title: "Premature advice restraint", + summary: + "Reflect once, then ask whether they want ideas or just to be heard.", + loaded: true, + impact: "medium", + difficulty: "Medium", + }, { id: "TC016", title: "Active-constructive responding", @@ -817,15 +835,6 @@ export const LIBRARY_CATEGORIES: Record = { }, ], "Resilience / Recovery": [ - { - id: "TC007", - title: "No one-upping discipline", - summary: - 'Before saying "me too", ask one more question about their story.', - loaded: true, - impact: "low", - difficulty: "Medium", - }, { id: "TC008", title: "No-overexplaining discipline", @@ -834,15 +843,6 @@ export const LIBRARY_CATEGORIES: Record = { impact: "low", difficulty: "Medium", }, - { - id: "TC009", - title: "Anti-boomerasking discipline", - summary: - "Ask one real follow-up or reflect before sharing your related story.", - loaded: true, - impact: "low", - difficulty: "Medium", - }, { id: "TC069", title: "Clarify objection", diff --git a/artifacts/tc-reference/src/pages/library.tsx b/artifacts/tc-reference/src/pages/library.tsx index e018892..52171e1 100644 --- a/artifacts/tc-reference/src/pages/library.tsx +++ b/artifacts/tc-reference/src/pages/library.tsx @@ -32,6 +32,7 @@ import { StartHereShelf, } from "@/components/library/start-here-shelf"; import { CategoryChips } from "@/components/library/category-chips"; +import { GroupedCardList } from "@/components/library/grouped-card-list"; import { LibraryCardRow, type LibraryCardMeta, @@ -729,8 +730,10 @@ export default function Library() { {cards.length} -
    - {cards.map((card) => ( + ( - ))} -
+ )} + /> ); }) diff --git a/artifacts/tc-reference/src/test/category-groups.test.ts b/artifacts/tc-reference/src/test/category-groups.test.ts new file mode 100644 index 0000000..947dfb4 --- /dev/null +++ b/artifacts/tc-reference/src/test/category-groups.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import { LIBRARY_CATEGORIES } from "@/lib/data"; +import { CATEGORY_GROUPS, groupCategoryCards } from "@/lib/category-groups"; + +describe("CATEGORY_GROUPS", () => { + it("only groups categories that exist", () => { + for (const category of Object.keys(CATEGORY_GROUPS)) { + expect(LIBRARY_CATEGORIES).toHaveProperty([category]); + } + }); + + it.each(Object.entries(CATEGORY_GROUPS))( + "puts every %s card in exactly one group", + (category, groups) => { + const inCategory = LIBRARY_CATEGORIES[category].map((c) => c.id).sort(); + const grouped = groups.flatMap((g) => g.ids); + expect(new Set(grouped).size).toBe(grouped.length); + expect([...grouped].sort()).toEqual(inCategory); + }, + ); + + it("keeps groups short enough to scan and names unique", () => { + for (const groups of Object.values(CATEGORY_GROUPS)) { + const names = groups.map((g) => g.name); + expect(new Set(names).size).toBe(names.length); + for (const g of groups) { + expect(g.ids.length).toBeGreaterThanOrEqual(3); + expect(g.ids.length).toBeLessThanOrEqual(12); + } + } + }); + + it("groups the categories that are too long to scan", () => { + for (const [category, cards] of Object.entries(LIBRARY_CATEGORIES)) { + if (cards.length > 12) expect(CATEGORY_GROUPS).toHaveProperty([category]); + } + }); +}); + +describe("groupCategoryCards", () => { + const card = (id: string) => ({ id }); + + it("returns one unnamed run for an ungrouped category", () => { + expect(groupCategoryCards("Voice / Presence", [card("TC028")])).toEqual([ + { name: null, cards: [card("TC028")] }, + ]); + }); + + it("keeps the incoming order inside each group and drops empty groups", () => { + const runs = groupCategoryCards("Resilience / Recovery", [ + card("TC105"), + card("TC107"), + card("TC101"), + ]); + expect(runs).toEqual([ + { name: "Handle pushback", cards: [card("TC107")] }, + { name: "Repair after a misstep", cards: [card("TC105"), card("TC101")] }, + ]); + }); + + it("never drops a card that has no group", () => { + const runs = groupCategoryCards("Resilience / Recovery", [card("TC999")]); + expect(runs).toEqual([{ name: "More", cards: [card("TC999")] }]); + }); +}); diff --git a/artifacts/tc-reference/src/test/library-home.test.tsx b/artifacts/tc-reference/src/test/library-home.test.tsx index 31a2382..f757efe 100644 --- a/artifacts/tc-reference/src/test/library-home.test.tsx +++ b/artifacts/tc-reference/src/test/library-home.test.tsx @@ -4,6 +4,7 @@ import { useLocation } from "wouter"; import Library from "../pages/library"; import StartHere from "../pages/start"; import { CORE_CARD_IDS, LIBRARY_CATEGORIES } from "../lib/data"; +import { groupCategoryCards } from "../lib/category-groups"; import { markStartCardOpened, nextStartCard, @@ -145,7 +146,15 @@ describe("Library home", () => { const chip = screen.getByTestId("category-chip-connection-warmth"); fireEvent.click(chip); expect(chip).toHaveAttribute("aria-pressed", "true"); - expect(cardIds()).toEqual(LIBRARY_CATEGORIES[category].map((c) => c.id)); + // Shown in its named groups, each keeping the category's own order + expect(cardIds()).toEqual( + groupCategoryCards(category, LIBRARY_CATEGORIES[category]).flatMap((g) => + g.cards.map((c) => c.id), + ), + ); + expect( + screen.getByRole("heading", { level: 3, name: /Draw them out/ }), + ).toBeInTheDocument(); fireEvent.click(chip); expect(screen.getByTestId("category-chip-all")).toHaveAttribute( "aria-pressed", From a69dbfdc567b670ac9691a6bc3bce6be0bd54fbf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:20:00 +0000 Subject: [PATCH 06/11] Show the header title only after the page title scrolls away iOS large-title pattern. Pages mark their visible title with usePageTitleRef(); the header watches it with an IntersectionObserver and fades its own copy of the name in only once that title is under the bar, so "Saved" over "Saved", the card title twice on phones and "Phrase Bank" twice on desktop are gone. A screen-reader-only h1 (PageIntro and Drill on phones) counts as not drawn, so those pages keep the header title. The header copy is aria-hidden where a page h1 exists; the card's header h1 keeps its role. The "TC Reference" eyebrow is hidden from md up, where the sidebar carries the name, and the sidebar now says "TC Reference" to match. Reduced motion snaps via the existing app-header rule. Also removes the serif from Saved phrases (shared file with this change). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .../src/components/app-header.tsx | 28 ++++- .../src/components/app-layout.tsx | 2 +- .../components/card-detail/card-header.tsx | 7 ++ .../src/components/page-intro.tsx | 3 + artifacts/tc-reference/src/lib/page-title.ts | 105 ++++++++++++++++++ artifacts/tc-reference/src/pages/drill.tsx | 3 + .../tc-reference/src/pages/favourites.tsx | 5 +- artifacts/tc-reference/src/pages/help.tsx | 5 + .../src/test/design-round2.test.tsx | 105 ++++++++++++++++++ 9 files changed, 259 insertions(+), 4 deletions(-) create mode 100644 artifacts/tc-reference/src/lib/page-title.ts create mode 100644 artifacts/tc-reference/src/test/design-round2.test.tsx diff --git a/artifacts/tc-reference/src/components/app-header.tsx b/artifacts/tc-reference/src/components/app-header.tsx index a8cbb9e..922670b 100644 --- a/artifacts/tc-reference/src/components/app-header.tsx +++ b/artifacts/tc-reference/src/components/app-header.tsx @@ -18,6 +18,7 @@ import { useTheme } from "@/lib/theme"; import { usePdf } from "@/lib/pdf-context"; import { LIBRARY_CATEGORIES } from "@/lib/data"; import { useScrollDirection } from "@/hooks/use-scroll-direction"; +import { useHeaderTitleShown } from "@/lib/page-title"; // Lazily loaded — global search builds its cached aggregate index only after a // user enters a query. const SearchModal = lazy(() => @@ -122,6 +123,15 @@ export function AppHeader() { // scroll up or near the top. The shared hook clamps iOS // overscroll so rubber banding can't make the header flicker. const scrollingDown = useScrollDirection(56, 10, location) === "down"; + // iOS large-title pattern: while the page's own big title is on screen the + // header leaves the name out, then fades it in once that title scrolls + // away. Pages without one (the Library) keep the header title throughout. + const { hasPageTitle, shown: titleShown } = useHeaderTitleShown(); + const titleFade: React.CSSProperties = { + opacity: titleShown ? 1 : 0, + transform: titleShown ? "none" : "translateY(4px)", + transition: "opacity 180ms ease, transform 180ms ease", + }; const cardId = location.startsWith("/card/") ? location.replace("/card/", "").split("?")[0] @@ -255,13 +265,17 @@ export function AppHeader() { {cardId} )} + {/* Stays the page h1 for assistive tech; drawn only once the + card's own large title has scrolled away */}

{cardMeta?.cardTitle ?? "Card not found"}

@@ -329,9 +343,15 @@ export function AppHeader() { />
+ {/* The app name. From md up the sidebar already carries it */}

TC Reference @@ -341,8 +361,12 @@ export function AppHeader() { style={{ color: "var(--fg-90)", fontSize: 17, + ...titleFade, }} + // The page's own h1 names it; this copy is visual only + aria-hidden={hasPageTitle || undefined} data-testid="library-title" + data-title-shown={titleShown} > {pageTitle} diff --git a/artifacts/tc-reference/src/components/app-layout.tsx b/artifacts/tc-reference/src/components/app-layout.tsx index 2d99d03..4af79a0 100644 --- a/artifacts/tc-reference/src/components/app-layout.tsx +++ b/artifacts/tc-reference/src/components/app-layout.tsx @@ -69,7 +69,7 @@ export function AppLayout({ children }: AppLayoutProps) { className="block text-[16px] font-bold leading-tight" style={{ color: "var(--fg-90)" }} > - TC Library + TC Reference (); if (compact) { return (

(); return (

diff --git a/artifacts/tc-reference/src/lib/page-title.ts b/artifacts/tc-reference/src/lib/page-title.ts new file mode 100644 index 0000000..0e4a68d --- /dev/null +++ b/artifacts/tc-reference/src/lib/page-title.ts @@ -0,0 +1,105 @@ +import { + useCallback, + useLayoutEffect, + useRef, + useState, + useSyncExternalStore, +} from "react"; + +// The iOS large-title pattern: a page shows its own big title at the top, +// and the app header names the page only once that title has scrolled out +// of view. A page marks its visible title with usePageTitleRef(); the +// header reads useHeaderTitleShown(). + +let current: HTMLElement | null = null; +const listeners = new Set<() => void>(); + +function setCurrent(el: HTMLElement | null) { + if (current === el) return; + current = el; + listeners.forEach((l) => l()); +} + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** Ref for a page's large title (its visible h1, or the card's title). */ +export function usePageTitleRef() { + const own = useRef(null); + return useCallback((el: T | null) => { + if (el) { + own.current = el; + setCurrent(el); + } else { + // Only clear the slot if a newer page has not already taken it + if (current === own.current) setCurrent(null); + own.current = null; + } + }, []); +} + +/** Height of the bar the title has to clear, below any status-bar inset. */ +const HEADER_BAR = 52; + +/** + * A title only counts while it is actually drawn: a screen-reader-only h1 + * (phones, where the header names the page) is a 1px box and leaves the + * header title on. + */ +function isDrawn(rect: DOMRectReadOnly) { + return rect.height > 4 && rect.width > 4; +} + +function titleGone(rect: DOMRectReadOnly) { + return !isDrawn(rect) || rect.bottom <= HEADER_BAR; +} + +/** + * Whether the header should show the page's name: always when the page has + * no large title, otherwise once that title has scrolled up under the + * header. `hasPageTitle` says whether a page title is registered (and so + * whether the header's copy is redundant for assistive tech). + */ +export function useHeaderTitleShown(): { + hasPageTitle: boolean; + shown: boolean; +} { + const el = useSyncExternalStore( + subscribe, + () => current, + () => null, + ); + const [gone, setGone] = useState(true); + + // Layout effect: decide before paint, so a page never flashes the header + // title it is about to hide + useLayoutEffect(() => { + if (!el) return; + const check = () => setGone(titleGone(el.getBoundingClientRect())); + check(); + if (typeof IntersectionObserver === "undefined") { + window.addEventListener("scroll", check, { passive: true }); + window.addEventListener("resize", check); + return () => { + window.removeEventListener("scroll", check); + window.removeEventListener("resize", check); + }; + } + const io = new IntersectionObserver( + ([entry]) => setGone(titleGone(entry.boundingClientRect)), + { rootMargin: `-${HEADER_BAR}px 0px 0px 0px`, threshold: [0, 1] }, + ); + io.observe(el); + // The title can switch between drawn and screen-reader-only at a + // breakpoint without crossing the viewport edge + window.addEventListener("resize", check); + return () => { + io.disconnect(); + window.removeEventListener("resize", check); + }; + }, [el]); + + return { hasPageTitle: !!el, shown: !el || gone }; +} diff --git a/artifacts/tc-reference/src/pages/drill.tsx b/artifacts/tc-reference/src/pages/drill.tsx index b606bd3..9a20fbf 100644 --- a/artifacts/tc-reference/src/pages/drill.tsx +++ b/artifacts/tc-reference/src/pages/drill.tsx @@ -65,6 +65,7 @@ import { } from "@/lib/drill-view"; import { usePlaybooks } from "@/lib/playbook-context"; import { useStorageSync } from "@/lib/storage-sync"; +import { usePageTitleRef } from "@/lib/page-title"; const EYEBROW = "text-[12px] font-bold uppercase tracking-[0.06em]"; @@ -98,6 +99,7 @@ function isUntouched(state: DrillState): boolean { } export default function Drill() { + const pageTitleRef = usePageTitleRef(); const [, navigate] = useLocation(); const [state, setState] = useState(() => loadDrillState()); const [srsMap, setSrsMap] = useState(() => loadSRSMap()); @@ -295,6 +297,7 @@ export default function Drill() { · {shownIndex + 1} of {cardCount}

diff --git a/artifacts/tc-reference/src/pages/favourites.tsx b/artifacts/tc-reference/src/pages/favourites.tsx index 10f920d..db2cdc8 100644 --- a/artifacts/tc-reference/src/pages/favourites.tsx +++ b/artifacts/tc-reference/src/pages/favourites.tsx @@ -22,6 +22,7 @@ import { EmptyState } from "@/components/ui/empty-state"; import { SettingsSheet } from "@/components/settings-sheet"; import { ShareSheet } from "@/components/share-sheet"; import type { ShareItem } from "@/components/share-sheet"; +import { usePageTitleRef } from "@/lib/page-title"; const CARD_META: Record< string, @@ -68,6 +69,7 @@ const iconButton = "w-11 h-11 flex-none flex items-center justify-center rounded-full transition-transform active:scale-90 motion-reduce:transition-none"; export default function Favourites() { + const pageTitleRef = usePageTitleRef(); const { state, toggleCard, togglePhrase } = useFavourites(); const [, setLocation] = useLocation(); const [searchQuery, setSearchQuery] = useState(""); @@ -137,6 +139,7 @@ export default function Favourites() { {totalSaved} {totalSaved === 1 ? "item" : "items"} · on this device

@@ -351,7 +354,7 @@ export default function Favourites() { className="flex-1 min-w-0 flex items-center gap-3 pl-4 pr-1 py-3 min-h-14 text-left" > (); const { openSearch } = useNav(); return (
@@ -82,6 +84,7 @@ function HelpPicker() { In the moment

@@ -148,6 +151,7 @@ function HelpPicker() { } function HelpAnswer({ situation }: { situation: Situation }) { + const pageTitleRef = usePageTitleRef(); const { copied, copy } = useCopyFeedback(1800); const lead = CARD_BY_ID.get(situation.leadCardId); const next = CARD_BY_ID.get(situation.followOn.cardId); @@ -158,6 +162,7 @@ function HelpAnswer({ situation }: { situation: Situation }) {

diff --git a/artifacts/tc-reference/src/test/design-round2.test.tsx b/artifacts/tc-reference/src/test/design-round2.test.tsx new file mode 100644 index 0000000..269db02 --- /dev/null +++ b/artifacts/tc-reference/src/test/design-round2.test.tsx @@ -0,0 +1,105 @@ +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; +import { CardRefText } from "@/components/card-detail/card-ref-text"; +import { useHeaderTitleShown, usePageTitleRef } from "@/lib/page-title"; + +describe("CardRefText", () => { + it("links a cited card by its title", () => { + render( +

+ +

, + ); + const link = screen.getByRole("link", { name: "Receive feedback well" }); + expect(link).toHaveAttribute("href", "/card/TC103"); + expect(screen.queryByText(/TC103/)).not.toBeInTheDocument(); + }); + + it("names but does not link inside a control", () => { + render( + , + ); + expect(screen.queryByRole("link")).not.toBeInTheDocument(); + expect(screen.getByRole("button")).toHaveTextContent( + "Minimal encouragers keeps them talking.", + ); + }); + + it("drops a reference to the card being read", () => { + render( +

+ +

, + ); + expect(screen.getByTestId("line")).toHaveTextContent('You: "How so?"'); + expect(screen.queryByRole("link")).not.toBeInTheDocument(); + }); +}); + +function rect(bottom: number, height = 40): DOMRect { + return { + top: bottom - height, + bottom, + height, + width: 300, + left: 0, + right: 300, + x: 0, + y: bottom - height, + toJSON: () => ({}), + } as DOMRect; +} + +function Harness({ bottom }: { bottom: { current: number } }) { + const ref = usePageTitleRef(); + const { hasPageTitle, shown } = useHeaderTitleShown(); + return ( + <> +

+ {String(hasPageTitle)} {String(shown)} +

+

{ + if (el) el.getBoundingClientRect = () => rect(bottom.current); + ref(el); + }} + > + Saved +

+ + ); +} + +describe("header large title", () => { + it("hides the header title while the page title is on screen", () => { + const bottom = { current: 200 }; + const { unmount } = render(); + expect(screen.getByTestId("state")).toHaveTextContent("true false"); + bottom.current = 20; + act(() => { + fireEvent(window, new Event("resize")); + }); + expect(screen.getByTestId("state")).toHaveTextContent("true true"); + unmount(); + }); + + it("keeps the header title when the page title is not drawn", () => { + function SrOnly() { + const ref = usePageTitleRef(); + const { shown } = useHeaderTitleShown(); + return ( +

+ {String(shown)} +

+ ); + } + // jsdom draws nothing: a zero box counts as screen-reader-only + render(); + expect(screen.getByTestId("h")).toHaveTextContent("true"); + }); +}); From 939b07f140feeb03e11cdc2c76cd0a9975d4845f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:20:00 +0000 Subject: [PATCH 07/11] Use one phrase typeface and tint the best line green Every sayable line now uses Inter through one token (--app-font-phrase, applied by .phrase-text): search results, Saved and drill recall no longer switch to Georgia. Serif stays only on the printed/shared quote card. The best line on Use it (and the ladder's best rung) gets a light green wash via --best-tint; weak stays neutral. Measured contrast: Best label 6.2:1 light / 8.4:1 dark, line text >= 12:1. Also holds the card cross-reference link and chip styles (index.css). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .../card-detail/inpractice-section.tsx | 2 +- .../components/card-detail/ladder-section.tsx | 6 ++- .../src/components/drill-recall.tsx | 2 +- .../src/components/search/result-rows.tsx | 4 +- artifacts/tc-reference/src/index.css | 39 +++++++++++++++++++ .../src/styles/print-and-preferences.css | 7 +++- 6 files changed, 53 insertions(+), 7 deletions(-) diff --git a/artifacts/tc-reference/src/components/card-detail/inpractice-section.tsx b/artifacts/tc-reference/src/components/card-detail/inpractice-section.tsx index d1f920f..c8051ac 100644 --- a/artifacts/tc-reference/src/components/card-detail/inpractice-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/inpractice-section.tsx @@ -23,7 +23,7 @@ function ContrastLine({ const best = kind === "best"; const text = displayLine(line); return ( - +

-
+
Best {row.best} diff --git a/artifacts/tc-reference/src/components/drill-recall.tsx b/artifacts/tc-reference/src/components/drill-recall.tsx index 9eb36a3..ab6d384 100644 --- a/artifacts/tc-reference/src/components/drill-recall.tsx +++ b/artifacts/tc-reference/src/components/drill-recall.tsx @@ -23,7 +23,7 @@ export function DrillRecall({ move, shown, onShow }: DrillRecallProps) { role="status" aria-live="polite" data-testid="drill-recall" - className="font-serif text-[17px] leading-[1.4]" + className="phrase-text text-[17px] leading-[1.4]" style={{ color: "var(--fg-90)" }} > {move} diff --git a/artifacts/tc-reference/src/components/search/result-rows.tsx b/artifacts/tc-reference/src/components/search/result-rows.tsx index 6c7f66d..c77b680 100644 --- a/artifacts/tc-reference/src/components/search/result-rows.tsx +++ b/artifacts/tc-reference/src/components/search/result-rows.tsx @@ -145,7 +145,7 @@ export function PhraseRow({ > @@ -269,7 +269,7 @@ export function BestTechnique({ style={{ background: "var(--fg-06)" }} > {quoted(phrase.text)} diff --git a/artifacts/tc-reference/src/index.css b/artifacts/tc-reference/src/index.css index 9766e9d..b5bb336 100644 --- a/artifacts/tc-reference/src/index.css +++ b/artifacts/tc-reference/src/index.css @@ -60,6 +60,7 @@ --font-sans: var(--app-font-sans); --font-serif: var(--app-font-serif); + --font-phrase: var(--app-font-phrase); --font-mono: var(--app-font-mono); --radius-sm: calc(var(--radius) - 4px); @@ -125,6 +126,10 @@ --app-font-sans: "Inter", system-ui, sans-serif; --app-font-serif: Georgia, serif; + /* Every sayable line, wherever it shows (card, search, Saved, drill): + one face, applied through .phrase-text. Serif is kept only for the + printed and shared quote cards. */ + --app-font-phrase: var(--app-font-sans); --app-font-mono: Menlo, monospace; --radius: 0.5rem; --shadow-2xs: 0px 2px 0px 0px hsl(0 0% 0% / 0.1); @@ -256,6 +261,9 @@ --accent-rose: #fb7185; --accent-red: #f87171; --accent-emerald: #34d399; + /* Light green wash behind a card's best line (weak stays neutral) */ + --best-tint: color-mix(in srgb, #4ade80 11%, transparent); + --best-tint-border: color-mix(in srgb, #4ade80 30%, transparent); --accent-sky: #38bdf8; --accent-blue: #60a5fa; @@ -422,6 +430,8 @@ --accent-rose: #be123c; --accent-red: #b91c1c; --accent-emerald: #047857; + --best-tint: color-mix(in srgb, #16a34a 9%, transparent); + --best-tint-border: color-mix(in srgb, #15803d 30%, transparent); --accent-sky: #0369a1; --accent-blue: #2563eb; @@ -900,3 +910,32 @@ body:has([data-search-screen]) .tab-bar { .no-scrollbar::-webkit-scrollbar { display: none; } + +/* ── Card cross-references (card-ref-text.tsx) ── + A reference reads as part of the sentence: brand text with a quiet + underline that firms up on hover. Where the title stands in for a bare + id it sits in a light chip, so it still reads as a name, not prose. */ +.card-ref { + color: var(--brand-text); + font-weight: 600; + text-decoration-line: underline; + text-decoration-color: color-mix(in srgb, var(--brand-text) 45%, transparent); + text-decoration-thickness: 1px; + text-underline-offset: 3px; + border-radius: 4px; +} +.card-ref:hover { + text-decoration-color: currentColor; +} +.card-ref-chip { + text-decoration-line: none; + padding: 0 0.4em; + background: color-mix(in srgb, var(--brand) 10%, transparent); + border: 1px solid color-mix(in srgb, var(--brand) 26%, transparent); + border-radius: 6px; + -webkit-box-decoration-break: clone; + box-decoration-break: clone; +} +.card-ref-chip:hover { + background: color-mix(in srgb, var(--brand) 18%, transparent); +} diff --git a/artifacts/tc-reference/src/styles/print-and-preferences.css b/artifacts/tc-reference/src/styles/print-and-preferences.css index ee366ba..d65f5c5 100644 --- a/artifacts/tc-reference/src/styles/print-and-preferences.css +++ b/artifacts/tc-reference/src/styles/print-and-preferences.css @@ -1,8 +1,11 @@ /* Display preferences (Settings sheet) and print layouts. Imported from index.css; kept outside @layer so these rules outrank Tailwind utilities. */ -/* Larger phrase text: anything that shows a sayable line carries - .phrase-text, and grows when the setting is on. */ +/* Anything that shows a sayable line carries .phrase-text: it sets the one + phrase face everywhere, and grows when the larger-phrases setting is on. */ +.phrase-text { + font-family: var(--app-font-phrase); +} :root[data-large-phrases] .phrase-text { font-size: 1.1875rem !important; line-height: 1.4 !important; From 72f05c2f1778422e4ab5c3d7e95de3b9ddc5f664 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:21:47 +0000 Subject: [PATCH 08/11] perf(tc-reference): faster Phrase Bank first paint, CI budgets, axe scan, HSTS - Precompute the Phrase Bank count at build time (virtual:phrase-bank-summary, same aggregation as the page via the new phrase-aggregate.ts) so the intro, the page's LCP element, paints before the text index loads. - Cold loads render the first 24 rows, then fill the first page in idle batches; return visits render every row on the first frame. - Add scripts/check-bundle-budget.mjs (gzip budgets ~10% over current for entry JS, vendor JS, main CSS, card-text-data) and run it after the build in code-review.yml. - Add e2e/a11y.spec.ts: axe-core 4.13.0 WCAG 2.x A/AA plus label-content-name-mismatch on every main route; fix the prev/next card button names it flagged. - Send HSTS only for requests that arrived over HTTPS (x-forwarded-proto or TLS socket), with a server test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .github/workflows/code-review.yml | 3 + .../tc-reference/card-text-index-plugin.ts | 30 ++++- artifacts/tc-reference/e2e/a11y.spec.ts | 81 +++++++++++++ artifacts/tc-reference/package.json | 4 +- .../scripts/check-bundle-budget.mjs | 82 +++++++++++++ artifacts/tc-reference/server.mjs | 14 +++ .../card-detail/prev-next-buttons.tsx | 5 +- .../tc-reference/src/lib/phrase-aggregate.ts | 93 +++++++++++++++ .../tc-reference/src/lib/phrases-data.ts | 108 ++++-------------- artifacts/tc-reference/src/pages/phrases.tsx | 59 ++++++++-- .../src/test/phrase-bank-summary-stub.ts | 4 + .../src/test/phrase-bank-summary.test.ts | 18 +++ .../src/test/phrases-progressive.test.tsx | 55 +++++++++ .../tc-reference/src/test/server.test.ts | 22 ++++ .../tc-reference/src/virtual-modules.d.ts | 10 ++ artifacts/tc-reference/vitest.config.ts | 4 + pnpm-lock.yaml | 3 + 17 files changed, 497 insertions(+), 98 deletions(-) create mode 100644 artifacts/tc-reference/e2e/a11y.spec.ts create mode 100644 artifacts/tc-reference/scripts/check-bundle-budget.mjs create mode 100644 artifacts/tc-reference/src/lib/phrase-aggregate.ts create mode 100644 artifacts/tc-reference/src/test/phrase-bank-summary-stub.ts create mode 100644 artifacts/tc-reference/src/test/phrase-bank-summary.test.ts create mode 100644 artifacts/tc-reference/src/test/phrases-progressive.test.tsx diff --git a/.github/workflows/code-review.yml b/.github/workflows/code-review.yml index 0e822d8..5a37628 100644 --- a/.github/workflows/code-review.yml +++ b/.github/workflows/code-review.yml @@ -49,6 +49,9 @@ jobs: - name: Build production app run: pnpm --filter @workspace/tc-reference build + - name: Check bundle size budgets + run: pnpm --filter @workspace/tc-reference run budget + - name: Run Automated Code Reviewer env: CODE_REVIEW_SKIP_CHECKS: "1" diff --git a/artifacts/tc-reference/card-text-index-plugin.ts b/artifacts/tc-reference/card-text-index-plugin.ts index c306802..207c91b 100644 --- a/artifacts/tc-reference/card-text-index-plugin.ts +++ b/artifacts/tc-reference/card-text-index-plugin.ts @@ -3,10 +3,24 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import type { Plugin } from "vite"; import type { CardData } from "./src/lib/card-types"; -import { projectCardText } from "./src/lib/card-text-index-build"; +import { + projectCardText, + type CardTextEntry, +} from "./src/lib/card-text-index-build"; +import { aggregatePhrases } from "./src/lib/phrase-aggregate"; const VIRTUAL_ID = "virtual:card-text-index"; const RESOLVED_ID = "\0" + VIRTUAL_ID; +const SUMMARY_ID = "virtual:phrase-bank-summary"; +const RESOLVED_SUMMARY_ID = "\0" + SUMMARY_ID; + +/** The totals in `virtual:phrase-bank-summary`, from the same aggregation. */ +export function phraseBankSummary(index: Record): { + phraseCount: number; +} { + // Titles do not affect the count. + return { phraseCount: aggregatePhrases(index, (cardId) => cardId).length }; +} /** * Builds `virtual:card-text-index`: the search / phrase text of every card @@ -14,19 +28,24 @@ const RESOLVED_ID = "\0" + VIRTUAL_ID; * chunk that the service worker precaches with the app shell (card chunks * themselves stay runtime-cached). Card sources are loaded with Node's * TypeScript type stripping; they only use type imports. + * + * Also builds `virtual:phrase-bank-summary`, a few bytes of totals the Phrase + * Bank imports statically so its intro paints before the index arrives. */ export function cardTextIndexPlugin(cardsDir: string): Plugin { return { name: "tc-card-text-index", resolveId(id) { - return id === VIRTUAL_ID ? RESOLVED_ID : undefined; + if (id === VIRTUAL_ID) return RESOLVED_ID; + if (id === SUMMARY_ID) return RESOLVED_SUMMARY_ID; + return undefined; }, async load(id) { - if (id !== RESOLVED_ID) return undefined; + if (id !== RESOLVED_ID && id !== RESOLVED_SUMMARY_ID) return undefined; const files = (await readdir(cardsDir)) .filter((file) => /^TC\d{3}\.ts$/.test(file)) .sort(); - const index: Record = {}; + const index: Record = {}; for (const file of files) { const fullPath = path.join(cardsDir, file); this.addWatchFile(fullPath); @@ -38,6 +57,9 @@ export function cardTextIndexPlugin(cardsDir: string): Plugin { if (!card) throw new Error(`${file} does not export ${cardId}`); index[cardId] = projectCardText(card); } + if (id === RESOLVED_SUMMARY_ID) { + return `export default ${JSON.stringify(phraseBankSummary(index))};`; + } // JSON.parse of a string literal parses faster than an object literal. return `export default JSON.parse(${JSON.stringify(JSON.stringify(index))});`; }, diff --git a/artifacts/tc-reference/e2e/a11y.spec.ts b/artifacts/tc-reference/e2e/a11y.spec.ts new file mode 100644 index 0000000..d592c0e --- /dev/null +++ b/artifacts/tc-reference/e2e/a11y.spec.ts @@ -0,0 +1,81 @@ +import { createRequire } from "node:module"; +import type { Page } from "@playwright/test"; +import { test, expect, MAIN_ROUTES } from "./fixtures"; + +// axe-core runs inside the page. The production CSP (rightly) blocks +// injected scripts, so this spec alone bypasses it to add the engine. +test.use({ bypassCSP: true }); + +const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js"); + +interface AxeViolation { + id: string; + impact: string | null; + help: string; + nodes: { target: string[]; html: string }[]; +} + +/** Wait for the route's lazy chunks and data loaders to settle. */ +async function settle(page: Page) { + await expect(page.getByRole("heading", { level: 1 }).first()).toBeVisible(); + await expect(page.locator('[aria-busy="true"]')).toHaveCount(0); + await expect( + page.getByRole("status").filter({ hasText: /^Loading/ }), + ).toHaveCount(0); +} + +async function runAxe( + page: Page, + runOnly: { type: "tag" | "rule"; values: string[] }, +): Promise { + if (!(await page.evaluate(() => "axe" in window))) { + await page.addScriptTag({ path: axePath }); + } + const violations = await page.evaluate(async (only) => { + const axe = ( + window as unknown as { + axe: { + run: ( + ctx: Document, + opts: object, + ) => Promise<{ violations: AxeViolation[] }>; + }; + } + ).axe; + const result = await axe.run(document, { runOnly: only }); + return result.violations; + }, runOnly); + return violations.flatMap((v) => + v.nodes.map( + (n) => + `${v.id} (${v.impact}): ${n.target.join(" ")} ${n.html.slice(0, 120)}`, + ), + ); +} + +for (const route of MAIN_ROUTES) { + test(`${route} passes the basic axe scan and label-in-name`, async ({ + page, + }) => { + await page.goto(route); + await settle(page); + + // WCAG 2.x A/AA rules that axe reports with certainty. + expect( + await runAxe(page, { + type: "tag", + values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"], + }), + ).toEqual([]); + + // Visible label text must be part of the accessible name (WCAG 2.5.3), + // so voice-control users can say what they see. Experimental in axe, so + // it only runs when named. + expect( + await runAxe(page, { + type: "rule", + values: ["label-content-name-mismatch"], + }), + ).toEqual([]); + }); +} diff --git a/artifacts/tc-reference/package.json b/artifacts/tc-reference/package.json index 6a5c024..c44b3ac 100644 --- a/artifacts/tc-reference/package.json +++ b/artifacts/tc-reference/package.json @@ -12,7 +12,8 @@ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p e2e/tsconfig.json", "test": "node scripts/ensure-downloads.mjs && vitest run --config vitest.config.ts", "test:full": "pnpm run generate:downloads && vitest run --config vitest.config.ts", - "test:e2e": "playwright test --trace off" + "test:e2e": "playwright test --trace off", + "budget": "node scripts/check-bundle-budget.mjs" }, "devDependencies": { "@fontsource/inter": "^5.3.0", @@ -25,6 +26,7 @@ "@types/react": "catalog:", "@types/react-dom": "catalog:", "@vitejs/plugin-react": "catalog:", + "axe-core": "4.13.0", "jsdom": "^30.1.3", "lucide-react": "catalog:", "minisearch": "7.2.0", diff --git a/artifacts/tc-reference/scripts/check-bundle-budget.mjs b/artifacts/tc-reference/scripts/check-bundle-budget.mjs new file mode 100644 index 0000000..fcc1994 --- /dev/null +++ b/artifacts/tc-reference/scripts/check-bundle-budget.mjs @@ -0,0 +1,82 @@ +// Fails when a key production chunk grows past its gzip budget. Run after +// `pnpm run build`. Budgets sit about 10% above the sizes when they were set, +// so ordinary edits pass and a regression (a new heavy import in the entry, +// a dependency landing in vendor, the text index doubling) stops CI. +// Raising a budget is fine when the growth is intended: say why in the PR. +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { gzipSync } from "node:zlib"; + +const KB = 1024; +// gzip -9 bytes (KiB). Set from the build of 2026-11-21: entry 31.6, vendor +// 59.4, main CSS 12.4, card text index 173.3. +export const BUDGETS = { + "entry JS": 35 * KB, + "vendor JS": 66 * KB, + "main CSS": 13.75 * KB, + "card-text-data JS": 191 * KB, +}; + +const root = path.join( + path.dirname(fileURLToPath(import.meta.url)), + "..", + "dist", + "public", +); + +/** The budgeted files, found through Vite's build manifest. */ +export function budgetedFiles(manifest) { + const entry = manifest["index.html"]; + if (!entry?.file) throw new Error("manifest has no index.html entry"); + const vendor = Object.values(manifest).find((chunk) => + /^assets\/vendor-[^/]+\.js$/.test(chunk.file), + ); + const textIndex = manifest["virtual:card-text-index"]; + const css = entry.css?.[0]; + const files = { + "entry JS": entry.file, + "vendor JS": vendor?.file, + "main CSS": css, + "card-text-data JS": textIndex?.file, + }; + for (const [label, file] of Object.entries(files)) { + if (!file) throw new Error(`build manifest has no ${label} chunk`); + } + return files; +} + +export function checkBudgets(readFile, manifest) { + const rows = []; + for (const [label, file] of Object.entries(budgetedFiles(manifest))) { + const gzip = gzipSync(readFile(file), { level: 9 }).length; + rows.push({ label, file, gzip, budget: BUDGETS[label] }); + } + return rows; +} + +const invokedPath = process.argv[1] ? path.resolve(process.argv[1]) : ""; +if (invokedPath === fileURLToPath(import.meta.url)) { + const manifest = JSON.parse( + readFileSync(path.join(root, ".vite", "manifest.json"), "utf8"), + ); + const rows = checkBudgets( + (file) => readFileSync(path.join(root, file)), + manifest, + ); + let failed = false; + for (const { label, file, gzip, budget } of rows) { + const over = gzip > budget; + failed ||= over; + const pct = ((gzip / budget) * 100).toFixed(0); + console.log( + `${over ? "OVER" : "ok "} ${label.padEnd(18)} ${(gzip / KB).toFixed(1).padStart(6)} KB gz / ${(budget / KB).toFixed(1)} KB (${pct}%) ${file}`, + ); + } + if (failed) { + console.error( + "\nBundle budget exceeded. Trim the growth, or raise the budget in scripts/check-bundle-budget.mjs and explain why in the PR.", + ); + process.exit(1); + } +} diff --git a/artifacts/tc-reference/server.mjs b/artifacts/tc-reference/server.mjs index 092f26e..27bd547 100644 --- a/artifacts/tc-reference/server.mjs +++ b/artifacts/tc-reference/server.mjs @@ -81,6 +81,19 @@ const securityHeaders = (scriptHashes) => ({ "Permissions-Policy": "camera=(), microphone=(), geolocation=()", }); +// HSTS only means something over HTTPS: browsers ignore it on plain http, and +// sending it from localhost could pin a developer's machine to https. Railway +// terminates TLS at its edge and forwards the original scheme. +const HSTS = "max-age=31536000; includeSubDomains"; + +/** True when the client reached us over HTTPS (directly or via the proxy). */ +export function arrivedOverHttps(req) { + if (req.socket?.encrypted) return true; + const forwarded = req.headers["x-forwarded-proto"]; + const value = Array.isArray(forwarded) ? forwarded[0] : (forwarded ?? ""); + return value.split(",")[0].trim().toLowerCase() === "https"; +} + function setHeaders(res, pathname, headers) { for (const [name, value] of Object.entries(headers)) { res.setHeader(name, value); @@ -124,6 +137,7 @@ export function createRequestHandler(root = defaultRoot) { res.end(req.method === "HEAD" ? undefined : indexHtml); }; return (req, res) => { + if (arrivedOverHttps(req)) res.setHeader("Strict-Transport-Security", HSTS); req.headers["accept-encoding"] = acceptableEncodings( req.headers["accept-encoding"], ); diff --git a/artifacts/tc-reference/src/components/card-detail/prev-next-buttons.tsx b/artifacts/tc-reference/src/components/card-detail/prev-next-buttons.tsx index 614a9cd..22807ea 100644 --- a/artifacts/tc-reference/src/components/card-detail/prev-next-buttons.tsx +++ b/artifacts/tc-reference/src/components/card-detail/prev-next-buttons.tsx @@ -25,8 +25,9 @@ export function PrevNextNav({ setLocation(`/card/${card.id}`); }} data-testid={testId} - // Same words, in the same order, as the visible "Previous · TC102 …" - aria-label={`${dir}: ${card.id} ${CARD_TITLE_MAP[card.id] ?? ""}`} + // Exactly the visible "Previous · TC102 …" text, separator included, + // so the name contains the label (WCAG 2.5.3 label in name) + aria-label={`${dir} · ${card.id} ${CARD_TITLE_MAP[card.id] ?? card.id}`} className={`flex items-center gap-2 rounded-2xl px-3.5 py-3 transition-all active:scale-[0.98] min-w-0 ${dir === "Next" ? "flex-row-reverse text-right" : "text-left"}`} style={{ minHeight: 56, diff --git a/artifacts/tc-reference/src/lib/phrase-aggregate.ts b/artifacts/tc-reference/src/lib/phrase-aggregate.ts new file mode 100644 index 0000000..99e5be6 --- /dev/null +++ b/artifacts/tc-reference/src/lib/phrase-aggregate.ts @@ -0,0 +1,93 @@ +// Pure Phrase Bank aggregation, shared by the app (phrases-data.ts) and the +// build plugin (card-text-index-plugin.ts), which precomputes the phrase count +// so the page can paint its intro before the text index arrives. Keep this +// module free of app-only imports (no "@/" paths, no data.ts). +import { isSpeakablePhrase, inferPhraseTone } from "./card-types"; +import type { CanonicalTone } from "./card-types"; +import type { CardTextIndex } from "./card-text-index-build"; +import { tokenize } from "./search-text"; + +/** Another card that lists the same line, with its own wording of it. */ +export interface PhraseSource { + cardId: string; + cardTitle: string; + text: string; +} + +export interface AggregatedPhrase { + text: string; + groupId: string; + groupLabel: string; + groupTag: string; + tone: CanonicalTone; + cardId: string; + cardTitle: string; + /** + * Other cards that list the same line (ignoring case and punctuation). The + * combined bank shows it once, under the first card; each card's own phrase + * bank still lists it. Absent when the line is on one card only. + */ + alsoOn?: ReadonlyArray; + /** + * Other tones the same line carries on the cards in alsoOn, so a tone + * filter still finds it. Absent when every copy has the same tone. + */ + alsoTones?: ReadonlyArray; +} + +/** + * The key two lines share when they say the same words, ignoring case, + * punctuation and quote marks ("That sounds like it mattered." and "that + * sounds like it mattered" match). + */ +export function phraseDedupeKey(text: string): string { + return tokenize(text).join(" "); +} + +/** Every speakable line across the cards, each shared line listed once. */ +export function aggregatePhrases( + cards: CardTextIndex, + titleOf: (cardId: string) => string, +): AggregatedPhrase[] { + const result: AggregatedPhrase[] = []; + // Shared stock lines are listed once, under the first card. + const byKey = new Map(); + for (const [cardId, card] of Object.entries(cards)) { + const cardTitle = titleOf(cardId); + for (const group of card.phraseBank) { + for (const text of group.phrases) { + if (!isSpeakablePhrase(text)) continue; + const key = phraseDedupeKey(text); + const first = byKey.get(key); + if (first) { + const tone = inferPhraseTone(group); + if (tone !== first.tone && !first.alsoTones?.includes(tone)) { + first.alsoTones = [...(first.alsoTones ?? []), tone]; + } + if ( + first.cardId !== cardId && + !first.alsoOn?.some((s) => s.cardId === cardId) + ) { + first.alsoOn = [ + ...(first.alsoOn ?? []), + { cardId, cardTitle, text }, + ]; + } + continue; + } + const entry: AggregatedPhrase = { + text, + groupId: group.id, + groupLabel: group.label, + groupTag: group.tag, + tone: inferPhraseTone(group), + cardId, + cardTitle, + }; + byKey.set(key, entry); + result.push(entry); + } + } + } + return result; +} diff --git a/artifacts/tc-reference/src/lib/phrases-data.ts b/artifacts/tc-reference/src/lib/phrases-data.ts index 8e36e65..b4fc183 100644 --- a/artifacts/tc-reference/src/lib/phrases-data.ts +++ b/artifacts/tc-reference/src/lib/phrases-data.ts @@ -1,55 +1,24 @@ -import { - CANONICAL_TONES, - isSpeakablePhrase, - inferPhraseTone, -} from "./card-types"; +import { CANONICAL_TONES } from "./card-types"; import type { CanonicalTone } from "./card-types"; import { loadCardTextIndex } from "./card-text-index"; import { LIBRARY_CATEGORIES } from "./data"; -import { tokenize } from "./search-text"; +import { + aggregatePhrases, + type AggregatedPhrase, + type PhraseSource, +} from "./phrase-aggregate"; -/** Another card that lists the same line, with its own wording of it. */ -export interface PhraseSource { - cardId: string; - cardTitle: string; - text: string; -} - -export interface AggregatedPhrase { - text: string; - groupId: string; - groupLabel: string; - groupTag: string; - tone: CanonicalTone; - cardId: string; - cardTitle: string; - /** - * Other cards that list the same line (ignoring case and punctuation). The - * combined bank shows it once, under the first card; each card's own phrase - * bank still lists it. Absent when the line is on one card only. - */ - alsoOn?: ReadonlyArray; - /** - * Other tones the same line carries on the cards in alsoOn, so a tone - * filter still finds it. Absent when every copy has the same tone. - */ - alsoTones?: ReadonlyArray; -} +export { + phraseDedupeKey, + type AggregatedPhrase, + type PhraseSource, +} from "./phrase-aggregate"; /** Every tone a (possibly shared) line carries. */ export function phraseTones(phrase: AggregatedPhrase): CanonicalTone[] { return [phrase.tone, ...(phrase.alsoTones ?? [])]; } -/** - * The key two lines share when they say the same words, ignoring case, - * punctuation and quote marks ("That sounds like it mattered." and "that - * sounds like it mattered" match). - */ -export function phraseDedupeKey(text: string): string { - return tokenize(text).join(" "); -} - /** The phrase and every other card it appears on, for favourite checks. */ export function phraseSources(phrase: AggregatedPhrase): PhraseSource[] { return [ @@ -64,6 +33,16 @@ for (const cards of Object.values(LIBRARY_CATEGORIES)) { } let phrasesPromise: Promise> | null = null; +let loadedPhrases: ReadonlyArray | null = null; + +/** + * The phrases if an earlier load has finished, else null. Lets a return + * visit render its full list on the first frame (so the browser can restore + * the scroll position) instead of waiting a tick for the promise. + */ +export function peekAllAggregatedPhrases(): ReadonlyArray | null { + return loadedPhrases; +} export function loadAllAggregatedPhrases(): Promise< ReadonlyArray @@ -71,47 +50,10 @@ export function loadAllAggregatedPhrases(): Promise< if (!phrasesPromise) { const pending = loadCardTextIndex() .then((cards) => { - const result: AggregatedPhrase[] = []; - // Shared stock lines are listed once, under the first card. - const byKey = new Map(); - for (const [cardId, card] of Object.entries(cards)) { - const cardTitle = CARD_TITLE_MAP[cardId] ?? cardId; - for (const group of card.phraseBank) { - for (const text of group.phrases) { - if (!isSpeakablePhrase(text)) continue; - const key = phraseDedupeKey(text); - const first = byKey.get(key); - if (first) { - const tone = inferPhraseTone(group); - if (tone !== first.tone && !first.alsoTones?.includes(tone)) { - first.alsoTones = [...(first.alsoTones ?? []), tone]; - } - if ( - first.cardId !== cardId && - !first.alsoOn?.some((s) => s.cardId === cardId) - ) { - first.alsoOn = [ - ...(first.alsoOn ?? []), - { cardId, cardTitle, text }, - ]; - } - continue; - } - const entry: AggregatedPhrase = { - text, - groupId: group.id, - groupLabel: group.label, - groupTag: group.tag, - tone: inferPhraseTone(group), - cardId, - cardTitle, - }; - byKey.set(key, entry); - result.push(entry); - } - } - } - return Object.freeze(result); + loadedPhrases = Object.freeze( + aggregatePhrases(cards, (cardId) => CARD_TITLE_MAP[cardId] ?? cardId), + ); + return loadedPhrases; }) .catch((error: unknown) => { if (phrasesPromise === pending) phrasesPromise = null; diff --git a/artifacts/tc-reference/src/pages/phrases.tsx b/artifacts/tc-reference/src/pages/phrases.tsx index 9717358..8fc17be 100644 --- a/artifacts/tc-reference/src/pages/phrases.tsx +++ b/artifacts/tc-reference/src/pages/phrases.tsx @@ -9,10 +9,12 @@ import { X, MessagesSquare, } from "lucide-react"; +import phraseBankSummary from "virtual:phrase-bank-summary"; import { PageIntro } from "@/components/page-intro"; import { Chip } from "@/components/ui/chip"; import { loadAllAggregatedPhrases, + peekAllAggregatedPhrases, getAllTones, phraseSources, type AggregatedPhrase, @@ -34,6 +36,20 @@ import { useCopyFeedback } from "@/hooks/use-copy-feedback"; // The bank runs to thousands of phrases; render a window and grow it on // demand so the page mounts and scrolls smoothly on a phone. const PAGE_SIZE = 120; +// About a phone screen of rows, then the rest of the first page in batches. +const FIRST_BATCH = 24; +const BATCH = 32; + +/** Runs `fn` when the main thread is idle; returns a cancel function. */ +function whenIdle(fn: () => void): () => void { + if (typeof window.requestIdleCallback === "function") { + const id = window.requestIdleCallback(fn, { timeout: 300 }); + return () => window.cancelIdleCallback(id); + } + // Safari has no requestIdleCallback + const id = window.setTimeout(fn, 16); + return () => window.clearTimeout(id); +} const CARD_CATEGORY: Record = Object.fromEntries( Object.entries(LIBRARY_CATEGORIES).flatMap(([category, cards]) => @@ -43,9 +59,18 @@ const CARD_CATEGORY: Record = Object.fromEntries( const formatCount = (n: number) => n.toLocaleString("en-GB"); +const introText = (count: number) => + `${formatCount(count)} lines from every technique. Pick a tone and length, then tap a line to copy it.`; + export default function Phrases() { - const [allPhrases, setAllPhrases] = - useState | null>(null); + // A return visit has the phrases already: render them in the first frame, + // all at once, so the browser can restore the scroll position. + const [allPhrases, setAllPhrases] = useState(peekAllAggregatedPhrases); + // A cold load paints the first screen of rows, then adds the rest a batch + // per idle slot so no single render blocks input for long. + const [renderLimit, setRenderLimit] = useState(() => + allPhrases ? Infinity : FIRST_BATCH, + ); const [loadFailed, setLoadFailed] = useState(false); const [tone, setTone] = useState(null); const [length, setLength] = useState(null); @@ -56,6 +81,15 @@ export default function Phrases() { const savedPhraseCount = favState.phrases.length; useEffect(() => { + if (!allPhrases || renderLimit >= PAGE_SIZE) return; + return whenIdle(() => + setRenderLimit((n) => (n + BATCH >= PAGE_SIZE ? Infinity : n + BATCH)), + ); + }, [allPhrases, renderLimit]); + + useEffect(() => { + // Also runs on a return visit: the cached promise hands back the same + // array, so React skips the re-render. let active = true; loadAllAggregatedPhrases().then( (phrases) => { @@ -95,11 +129,14 @@ export default function Phrases() { setVisibleCount(PAGE_SIZE); } + const renderedCount = Math.min(visibleCount, renderLimit); const groups = useMemo( - () => groupByCard(filtered.slice(0, visibleCount)), - [filtered, visibleCount], + () => groupByCard(filtered.slice(0, renderedCount)), + [filtered, renderedCount], ); - const hasMore = filtered.length > visibleCount; + // Hidden while the first page is still filling in + const hasMore = + filtered.length > visibleCount && renderedCount === visibleCount; const hasActive = !!tone || !!length || !!query; const clearAll = () => { setTone(null); @@ -108,9 +145,15 @@ export default function Phrases() { }; if (!allPhrases) { + // The build precomputes the count, so the intro (the page's largest + // first-screen text) paints now, unchanged when the phrases arrive. + const knownCount = loadFailed ? null : phraseBankSummary?.phraseCount; return ( -
- +
+
{loadFailed ? "Phrase Bank is unavailable right now." @@ -130,7 +173,7 @@ export default function Phrases() {
{savedPhraseCount > 0 && ( diff --git a/artifacts/tc-reference/src/test/phrase-bank-summary-stub.ts b/artifacts/tc-reference/src/test/phrase-bank-summary-stub.ts new file mode 100644 index 0000000..860d887 --- /dev/null +++ b/artifacts/tc-reference/src/test/phrase-bank-summary-stub.ts @@ -0,0 +1,4 @@ +// Unit tests run without the build plugin: no precomputed summary, so the +// Phrase Bank shows its count once the phrases load. +const summary: { phraseCount: number } | null = null; +export default summary; diff --git a/artifacts/tc-reference/src/test/phrase-bank-summary.test.ts b/artifacts/tc-reference/src/test/phrase-bank-summary.test.ts new file mode 100644 index 0000000..caa4ac4 --- /dev/null +++ b/artifacts/tc-reference/src/test/phrase-bank-summary.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { phraseBankSummary } from "../../card-text-index-plugin"; +import { loadAllCards } from "@/lib/card-loader"; +import { projectCardText } from "@/lib/card-text-index-build"; +import { loadAllAggregatedPhrases } from "@/lib/phrases-data"; + +describe("build-time Phrase Bank summary", () => { + it("counts exactly the phrases the page aggregates at runtime", async () => { + const cards = await loadAllCards(); + // The build plugin projects each card the same way before summarising. + const index = Object.fromEntries( + Object.entries(cards).map(([id, card]) => [id, projectCardText(card)]), + ); + const phrases = await loadAllAggregatedPhrases(); + expect(phrases.length).toBeGreaterThan(1000); + expect(phraseBankSummary(index)).toEqual({ phraseCount: phrases.length }); + }); +}); diff --git a/artifacts/tc-reference/src/test/phrases-progressive.test.tsx b/artifacts/tc-reference/src/test/phrases-progressive.test.tsx new file mode 100644 index 0000000..ba8376d --- /dev/null +++ b/artifacts/tc-reference/src/test/phrases-progressive.test.tsx @@ -0,0 +1,55 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { Router } from "wouter"; +import { memoryLocation } from "wouter/memory-location"; + +const rows = () => screen.queryAllByTestId(/^phrase-row-/); + +async function freshPhrasesPage() { + // A fresh module graph is a cold load: nothing cached yet. + vi.resetModules(); + const { default: Phrases } = await import("../pages/phrases"); + const { FavouritesProvider } = await import("../lib/favourites-context"); + const mount = () => + render( + + + + + , + ); + return mount; +} + +beforeEach(() => localStorage.clear()); + +describe("Phrase Bank first paint", () => { + it("shows the first screen of rows first, then fills the first page", async () => { + const mount = await freshPhrasesPage(); + mount(); + await screen.findByTestId("phrases-count"); + const first = rows().length; + expect(first).toBeGreaterThan(0); + expect(first).toBeLessThan(120); + // No "Show more" until the first page has filled in + expect(screen.queryByTestId("phrases-show-more")).not.toBeInTheDocument(); + + await waitFor(() => expect(rows()).toHaveLength(120)); + expect(screen.getByTestId("phrases-show-more")).toHaveTextContent( + "Show more · 120 of", + ); + }); + + it("renders the whole first page at once on a return visit", async () => { + const mount = await freshPhrasesPage(); + const firstVisit = mount(); + await waitFor(() => expect(rows()).toHaveLength(120)); + firstVisit.unmount(); + + // Data is cached now: every row is there on the first frame, so the + // browser can restore the reader's scroll position. + mount(); + expect(screen.queryByRole("status")).not.toBeInTheDocument(); + expect(rows()).toHaveLength(120); + }); +}); diff --git a/artifacts/tc-reference/src/test/server.test.ts b/artifacts/tc-reference/src/test/server.test.ts index 400b82e..150c176 100644 --- a/artifacts/tc-reference/src/test/server.test.ts +++ b/artifacts/tc-reference/src/test/server.test.ts @@ -115,6 +115,28 @@ describe("production server (F-10, F-12)", () => { expect(res.headers.get("content-type")).toContain("wordprocessingml"); }); + it("sends HSTS only when the request arrived over HTTPS", async () => { + const plain = await fetch(`${base}/`); + expect(plain.headers.get("strict-transport-security")).toBeNull(); + const viaProxy = await fetch(`${base}/assets/index-abc123.js`, { + headers: { "x-forwarded-proto": "https" }, + }); + expect(viaProxy.headers.get("strict-transport-security")).toBe( + "max-age=31536000; includeSubDomains", + ); + const unknownRoute = await fetch(`${base}/admin`, { + headers: { "x-forwarded-proto": "https, http" }, + }); + expect(unknownRoute.status).toBe(404); + expect(unknownRoute.headers.get("strict-transport-security")).toBe( + "max-age=31536000; includeSubDomains", + ); + const forwardedHttp = await fetch(`${base}/`, { + headers: { "x-forwarded-proto": "http" }, + }); + expect(forwardedHttp.headers.get("strict-transport-security")).toBeNull(); + }); + it("matches only real app routes", () => { expect(isAppRoute("/")).toBe(true); expect(isAppRoute("/card/TC098")).toBe(true); diff --git a/artifacts/tc-reference/src/virtual-modules.d.ts b/artifacts/tc-reference/src/virtual-modules.d.ts index a41f656..5313eec 100644 --- a/artifacts/tc-reference/src/virtual-modules.d.ts +++ b/artifacts/tc-reference/src/virtual-modules.d.ts @@ -4,3 +4,13 @@ declare module "virtual:card-text-index" { const index: CardTextIndex | null; export default index; } + +declare module "virtual:phrase-bank-summary" { + /** + * Phrase Bank totals computed at build time from the same text index, so + * the page can paint its intro before the index chunk loads. Null where + * the build plugin is absent (unit tests). + */ + const summary: { phraseCount: number } | null; + export default summary; +} diff --git a/artifacts/tc-reference/vitest.config.ts b/artifacts/tc-reference/vitest.config.ts index aaa6317..98bc218 100644 --- a/artifacts/tc-reference/vitest.config.ts +++ b/artifacts/tc-reference/vitest.config.ts @@ -11,6 +11,10 @@ export default defineConfig({ import.meta.dirname, "src/test/card-text-index-stub.ts", ), + "virtual:phrase-bank-summary": path.resolve( + import.meta.dirname, + "src/test/phrase-bank-summary-stub.ts", + ), }, }, test: { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c206b2b..416da49 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -113,6 +113,9 @@ importers: '@vitejs/plugin-react': specifier: 'catalog:' version: 5.2.0(vite@7.3.7(@types/node@24.19.2)(jiti@2.7.0)(lightningcss@1.33.0)(terser@5.51.2)(tsx@4.23.15)) + axe-core: + specifier: 4.13.0 + version: 4.13.0 jsdom: specifier: ^30.1.3 version: 30.1.3 From a2fb4548c3a617978c731cadb1398553f917485c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:27:04 +0000 Subject: [PATCH 09/11] Hold the distress Help situation and safety wording for clinical review The new 'They're very distressed or might not be safe' situation, the TC098 'Checking in on safety' lines, the safety not-for lines on TC105, TC108 and TC109, and the scope notes move to their own pull request so they can be clinically reviewed before release. The dormant safetyNote support stays. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .../components/library/start-here-shelf.tsx | 9 ------- artifacts/tc-reference/src/lib/cards/TC098.ts | 22 ----------------- artifacts/tc-reference/src/lib/cards/TC105.ts | 10 -------- artifacts/tc-reference/src/lib/cards/TC108.ts | 2 -- artifacts/tc-reference/src/lib/cards/TC109.ts | 4 ---- artifacts/tc-reference/src/lib/situations.ts | 21 ---------------- artifacts/tc-reference/src/pages/help.tsx | 9 ------- .../test/fixtures/saved-phrase-snapshot.json | 5 ---- .../tc-reference/src/test/help-page.test.tsx | 24 ------------------- .../tc-reference/src/test/situations.test.ts | 16 ++++--------- 10 files changed, 4 insertions(+), 118 deletions(-) diff --git a/artifacts/tc-reference/src/components/library/start-here-shelf.tsx b/artifacts/tc-reference/src/components/library/start-here-shelf.tsx index 9b97015..2cdc657 100644 --- a/artifacts/tc-reference/src/components/library/start-here-shelf.tsx +++ b/artifacts/tc-reference/src/components/library/start-here-shelf.tsx @@ -54,15 +54,6 @@ export function StartHereShelf() { practise. New here? Begin with the {TOTAL} that cover most conversations.

-

- {/* CLINICAL REVIEW NEEDED */} - This app helps with words, not clinical risk decisions. Follow your - local protocol. -

= new Map( diff --git a/artifacts/tc-reference/src/pages/help.tsx b/artifacts/tc-reference/src/pages/help.tsx index 37c5673..15c2901 100644 --- a/artifacts/tc-reference/src/pages/help.tsx +++ b/artifacts/tc-reference/src/pages/help.tsx @@ -91,15 +91,6 @@ function HelpPicker() { > What's happening?

-

- {/* CLINICAL REVIEW NEEDED */} - This app helps with words, not clinical risk decisions. Follow your - local protocol. -

    { } }); - it("shows the scope note on the picker", () => { - renderAt("/help"); - expect(screen.getByTestId("help-scope-note")).toHaveTextContent( - "This app helps with words, not clinical risk decisions.", - ); - }); - - it("leads the safety situation with the protocol and 000 note", () => { - renderAt("/help/distressed-or-unsafe"); - const note = screen.getByTestId("help-safety"); - expect(note).toHaveTextContent("follow your organisation's safety"); - expect(note).toHaveTextContent("call 000"); - // The note comes before the first move in reading order. - expect( - note.compareDocumentPosition(screen.getByTestId("help-first")) & - Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - }); - - it("shows no safety note on everyday situations", () => { - renderAt("/help/say-no"); - expect(screen.queryByTestId("help-safety")).not.toBeInTheDocument(); - }); - it("reaches a line to say in two taps from the picker", async () => { const location = renderAt("/help"); fireEvent.click(screen.getByTestId("help-situation-say-no")); diff --git a/artifacts/tc-reference/src/test/situations.test.ts b/artifacts/tc-reference/src/test/situations.test.ts index c662dc8..bbefa87 100644 --- a/artifacts/tc-reference/src/test/situations.test.ts +++ b/artifacts/tc-reference/src/test/situations.test.ts @@ -28,10 +28,10 @@ const LIBRARY_IDS = new Set( ); describe("Help me right now situations", () => { - it("has exactly nine situations with unique ids and labels", () => { - expect(SITUATIONS).toHaveLength(9); - expect(new Set(SITUATIONS.map((s) => s.id)).size).toBe(9); - expect(new Set(SITUATIONS.map((s) => s.label)).size).toBe(9); + it("has exactly eight situations with unique ids and labels", () => { + expect(SITUATIONS).toHaveLength(8); + expect(new Set(SITUATIONS.map((s) => s.id)).size).toBe(8); + expect(new Set(SITUATIONS.map((s) => s.label)).size).toBe(8); for (const s of SITUATIONS) { expect(s.id, s.id).toMatch(/^[a-z]+(-[a-z]+)*$/); expect(s.tagline.split(" ").length, s.id).toBeLessThanOrEqual(6); @@ -71,14 +71,6 @@ describe("Help me right now situations", () => { } }); - it("points the distress situation at local protocol and 000", () => { - const s = getSituation("distressed-or-unsafe"); - expect(s?.safetyNote).toMatch(/organisation's safety or risk protocol/); - expect(s?.safetyNote).toMatch(/\b000\b/); - // Only the safety situation carries a safety note. - expect(SITUATIONS.filter((x) => x.safetyNote)).toHaveLength(1); - }); - it("looks situations up by id", () => { expect(getSituation("say-no")?.leadCardId).toBe("TC102"); expect(getSituation("missing")).toBeUndefined(); From d8e462db06ff4ea62438e62ffef51822de0d8291 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:29:07 +0000 Subject: [PATCH 10/11] Wait for fades before axe scans; re-base the bundle budget after the design round Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- artifacts/tc-reference/e2e/a11y.spec.ts | 16 ++++++++++++++++ .../tc-reference/scripts/check-bundle-budget.mjs | 10 +++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/artifacts/tc-reference/e2e/a11y.spec.ts b/artifacts/tc-reference/e2e/a11y.spec.ts index d592c0e..8922811 100644 --- a/artifacts/tc-reference/e2e/a11y.spec.ts +++ b/artifacts/tc-reference/e2e/a11y.spec.ts @@ -22,6 +22,22 @@ async function settle(page: Page) { await expect( page.getByRole("status").filter({ hasText: /^Loading/ }), ).toHaveCount(0); + // Let fades finish (e.g. the header title), so axe never samples colour + // contrast halfway through a transition. + await expect + .poll(() => + page.evaluate( + () => + document + .getAnimations() + .filter( + (a) => + a.playState === "running" && + a.effect?.getTiming().iterations !== Infinity, + ).length, + ), + ) + .toBe(0); } async function runAxe( diff --git a/artifacts/tc-reference/scripts/check-bundle-budget.mjs b/artifacts/tc-reference/scripts/check-bundle-budget.mjs index fcc1994..97bd76c 100644 --- a/artifacts/tc-reference/scripts/check-bundle-budget.mjs +++ b/artifacts/tc-reference/scripts/check-bundle-budget.mjs @@ -9,13 +9,13 @@ import { fileURLToPath } from "node:url"; import { gzipSync } from "node:zlib"; const KB = 1024; -// gzip -9 bytes (KiB). Set from the build of 2026-11-21: entry 31.6, vendor -// 59.4, main CSS 12.4, card text index 173.3. +// gzip -9 bytes (KiB), about 10% above the build of 2026-11-21 after the +// design round: entry 34.3, vendor 59.4, main CSS 12.7, card text index 178.5. export const BUDGETS = { - "entry JS": 35 * KB, + "entry JS": 38 * KB, "vendor JS": 66 * KB, - "main CSS": 13.75 * KB, - "card-text-data JS": 191 * KB, + "main CSS": 14 * KB, + "card-text-data JS": 196 * KB, }; const root = path.join( From 0634bfd90a80a3f4de7edfd525f934e6d3d20fc2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 19:39:22 +0000 Subject: [PATCH 11/11] Fix review findings: stale restore snapshot, Android backup sharing, v1 restores - Remove any older restore snapshot before saving a new one, and retry a restore once without the snapshot if storage runs out, so Undo can never bring back data from before an earlier restore. - Backups use the share sheet only on iPhone and iPad; Android and desktop download as before. A failed share reports failure instead of a download without a user gesture. - Restoring a version 1 backup keeps Start here progress, recent cards and the welcome flag, which v1 files never carried. - Method steps don't link a card to itself. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01GxPPxjtHCQRLDHwTbGHhTp --- .../components/card-detail/method-section.tsx | 8 +-- artifacts/tc-reference/src/lib/backup.ts | 32 ++++++++- artifacts/tc-reference/src/lib/share.ts | 18 ++++- .../src/test/backup-section.test.tsx | 7 ++ .../tc-reference/src/test/backup.test.ts | 69 +++++++++++++++++-- 5 files changed, 120 insertions(+), 14 deletions(-) diff --git a/artifacts/tc-reference/src/components/card-detail/method-section.tsx b/artifacts/tc-reference/src/components/card-detail/method-section.tsx index 136a015..8b84b25 100644 --- a/artifacts/tc-reference/src/components/card-detail/method-section.tsx +++ b/artifacts/tc-reference/src/components/card-detail/method-section.tsx @@ -109,14 +109,14 @@ export function FieldTipSection({ cardData }: { cardData: CardData }) { ); } -function StepBody({ step }: { step: MethodStep }) { +function StepBody({ step, selfId }: { step: MethodStep; selfId: string }) { return ( <>

    - +

    {step.examples && step.examples.length > 0 && ( @@ -126,7 +126,7 @@ function StepBody({ step }: { step: MethodStep }) { - + ))} @@ -165,7 +165,7 @@ export function MethodSection({ cardData }: { cardData: CardData }) { )} - renderBody={(m) => } + renderBody={(m) => } /> {cardData.liveThreadClues && cardData.liveThreadClues.length > 0 && ( diff --git a/artifacts/tc-reference/src/lib/backup.ts b/artifacts/tc-reference/src/lib/backup.ts index de2aea9..b100d72 100644 --- a/artifacts/tc-reference/src/lib/backup.ts +++ b/artifacts/tc-reference/src/lib/backup.ts @@ -68,6 +68,13 @@ export const BACKUP_KEYS = { export type BackupKey = keyof typeof BACKUP_KEYS; +/** Keys that version 1 backups never carried, so restoring one keeps them. */ +const VERSION_2_KEYS: readonly BackupKey[] = [ + "tc_start_opened", + "tc_recent_cards", + "tc_welcome_dismissed", +]; + export const BACKUP_KEY_LIST = Object.keys(BACKUP_KEYS) as BackupKey[]; export interface BackupFile { @@ -171,6 +178,7 @@ export async function saveBackup( backupFileName(now), "application/json", nav, + { shareOnlyOnIos: true }, ); if (outcome === "cancelled") return "cancelled"; if (outcome !== "shared") return "failed"; @@ -221,6 +229,12 @@ function serialiseValue(key: BackupKey, value: unknown): string { * Validate a backup without touching storage. Returns the exact strings that * importBackup would write, keyed by known storage key. */ +/** The version number of an already validated backup file. */ +function backupVersion(json: string): number { + const parsed = JSON.parse(json) as { version: number }; + return parsed.version; +} + export function parseBackup(json: string): Map { checkBackupFileSize({ size: json.length }); let parsed: unknown; @@ -375,6 +389,10 @@ export function loadRestoreSnapshot( } function saveRestoreSnapshot(values: StoredValues, now: number): boolean { + // An older snapshot must never outlive this restore: if the new one can't + // be written, Undo would otherwise bring back data from before an earlier + // restore and silently discard this one. + removeRestoreSnapshot(); try { localStorage.setItem( RESTORE_SNAPSHOT_KEY, @@ -400,13 +418,23 @@ export function importBackup( ): ImportSummary & { undoAvailable: boolean } { const entries = parseBackup(json); const previous = readStoredValues(); + // A version 1 file predates some keys; keep what this device has for them + // rather than clearing Start here progress, recent cards and the welcome. + if (backupVersion(json) < 2) { + for (const key of VERSION_2_KEYS) { + const current = previous.get(key); + if (!entries.has(key) && current != null) entries.set(key, current); + } + } const undoAvailable = saveRestoreSnapshot(previous, now); try { return { ...writeStoredValues(entries, previous), undoAvailable }; } catch (err) { // Nothing changed, so there is nothing to undo; free the space too. - if (undoAvailable) removeRestoreSnapshot(); - throw err; + if (!undoAvailable) throw err; + removeRestoreSnapshot(); + // The snapshot may have been what filled storage: try once without it. + return { ...writeStoredValues(entries, previous), undoAvailable: false }; } } diff --git a/artifacts/tc-reference/src/lib/share.ts b/artifacts/tc-reference/src/lib/share.ts index dcf8427..f178ab6 100644 --- a/artifacts/tc-reference/src/lib/share.ts +++ b/artifacts/tc-reference/src/lib/share.ts @@ -213,15 +213,22 @@ export async function saveFile( nav: Navigator | undefined = typeof navigator !== "undefined" ? navigator : undefined, + options: { shareOnlyOnIos?: boolean } = {}, ): Promise { const file = typeof File === "function" ? new File([blob], fileName, { type }) : null; - if (file && nav?.share && nav.canShare?.({ files: [file] })) { + // Android and desktop share sheets often have no "save to device" target, + // so a file the person needs to keep (a backup) downloads there instead. + const shareAllowed = !options.shareOnlyOnIos || isIosDevice(nav); + if (shareAllowed && file && nav?.share && nav.canShare?.({ files: [file] })) { try { await nav.share({ files: [file] }); return "shared"; } catch (err) { if (isAbort(err)) return "cancelled"; + // The tap's user gesture is spent by now, so a download link would + // likely be blocked: report the failure rather than claim a save. + return "failed"; } } try { @@ -246,3 +253,12 @@ export async function saveFile( export function printTarget(win: Window = window): void { win.print(); } + +/** iPhone, iPod or iPad (iPadOS reports a Mac with touch), any browser. */ +function isIosDevice(nav: Navigator | undefined): boolean { + const ua = nav?.userAgent ?? ""; + return ( + /iPhone|iPad|iPod/.test(ua) || + (/Macintosh/.test(ua) && (nav?.maxTouchPoints ?? 0) > 1) + ); +} diff --git a/artifacts/tc-reference/src/test/backup-section.test.tsx b/artifacts/tc-reference/src/test/backup-section.test.tsx index 57b2e66..0da4673 100644 --- a/artifacts/tc-reference/src/test/backup-section.test.tsx +++ b/artifacts/tc-reference/src/test/backup-section.test.tsx @@ -160,6 +160,12 @@ describe("BackupSection (F-12)", () => { configurable: true, value: () => true, }); + // The share sheet is only used for backups on iPhone and iPad. + Object.defineProperty(navigator, "userAgent", { + configurable: true, + value: + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1", + }); try { render(); await act(async () => { @@ -173,6 +179,7 @@ describe("BackupSection (F-12)", () => { } finally { delete (navigator as { share?: unknown }).share; delete (navigator as { canShare?: unknown }).canShare; + delete (navigator as { userAgent?: unknown }).userAgent; } }); }); diff --git a/artifacts/tc-reference/src/test/backup.test.ts b/artifacts/tc-reference/src/test/backup.test.ts index 9f002a7..7683b00 100644 --- a/artifacts/tc-reference/src/test/backup.test.ts +++ b/artifacts/tc-reference/src/test/backup.test.ts @@ -85,12 +85,49 @@ describe("backup", () => { it("clears known keys that the backup does not include", () => { seed(); - const summary = importBackup(backupWith({ tc_theme: "dark" })); + const summary = importBackup( + backupWith({ tc_theme: "dark" }, { version: 2 }), + ); expect(summary.restored).toEqual(["tc_theme"]); expect(localStorage.getItem("tc_favourites")).toBeNull(); expect(localStorage.getItem("tc_theme")).toBe("dark"); }); + it("keeps keys a version 1 backup never carried", () => { + localStorage.setItem("tc_favourites", SAMPLE.tc_favourites); + localStorage.setItem("tc_start_opened", '["TC001"]'); + localStorage.setItem("tc_recent_cards", '["TC002"]'); + localStorage.setItem("tc_welcome_dismissed", "1"); + importBackup(backupWith({ tc_theme: "dark" }, { version: 1 })); + expect(localStorage.getItem("tc_favourites")).toBeNull(); + expect(localStorage.getItem("tc_start_opened")).toBe('["TC001"]'); + expect(localStorage.getItem("tc_recent_cards")).toBe('["TC002"]'); + expect(localStorage.getItem("tc_welcome_dismissed")).toBe("1"); + }); + + it("drops an older restore snapshot when the new one can't be saved", () => { + localStorage.setItem("tc_theme", "light"); + importBackup(backupWith({ tc_theme: "dark" }, { version: 2 })); + expect(localStorage.getItem("tc_restore_snapshot")).not.toBeNull(); + const setItem = Storage.prototype.setItem; + vi.spyOn(Storage.prototype, "setItem").mockImplementation(function ( + this: Storage, + key: string, + value: string, + ) { + if (key === "tc_restore_snapshot") { + throw new DOMException("full", "QuotaExceededError"); + } + return setItem.call(this, key, value); + }); + const summary = importBackup( + backupWith({ tc_theme: "light" }, { version: 2 }), + ); + expect(summary.undoAvailable).toBe(false); + expect(localStorage.getItem("tc_restore_snapshot")).toBeNull(); + vi.restoreAllMocks(); + }); + it("rejects a file from another app", () => { seed(); expect(() => @@ -195,15 +232,13 @@ describe("backup edge cases", () => { localStorage.setItem("tc_favourites", SAMPLE.tc_favourites); localStorage.setItem("tc_playbooks", SAMPLE.tc_playbooks); const setItem = Storage.prototype.setItem; - let quotaHit = false; vi.spyOn(Storage.prototype, "setItem").mockImplementation(function ( this: Storage, key: string, value: string, ) { - // Fail the first write of the large imported playbooks value only. - if (!quotaHit && key === "tc_playbooks" && value.length > 100) { - quotaHit = true; + // Every write of the large imported playbooks value runs out of space. + if (key === "tc_playbooks" && value.length > 100) { throw new DOMException("full", "QuotaExceededError"); } return setItem.call(this, key, value); @@ -345,8 +380,16 @@ describe("restore snapshot and undo", () => { describe("saveBackup", () => { const NOW = new Date("2026-03-04T05:06:07Z"); - function shareNav(share: (data: ShareData) => Promise) { + const IPHONE_UA = + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"; + + function shareNav( + share: (data: ShareData) => Promise, + userAgent = IPHONE_UA, + ) { return { + userAgent, + maxTouchPoints: 5, canShare: (data: ShareData) => Array.isArray(data.files), share: vi.fn(share), } as unknown as Navigator; @@ -396,12 +439,24 @@ describe("saveBackup", () => { expect(loadDataSafety().lastBackupAt).toBe(NOW.getTime()); }); - it("falls back to a download when sharing fails another way", async () => { + it("reports a failure when sharing fails another way", async () => { const click = stubDownload(); const nav = shareNav(async () => { throw new DOMException("Not allowed", "NotAllowedError"); }); + expect(await saveBackup(NOW, nav)).toBe("failed"); + expect(click).not.toHaveBeenCalled(); + expect(loadDataSafety().lastBackupAt).toBeNull(); + }); + + it("downloads rather than shares on Android and desktop", async () => { + const click = stubDownload(); + const nav = shareNav( + async () => {}, + "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Mobile Safari/537.36", + ); expect(await saveBackup(NOW, nav)).toBe("saved"); + expect(nav.share).not.toHaveBeenCalled(); expect(click).toHaveBeenCalledTimes(1); });