diff --git a/.github/workflows/e2e-webkit.yml b/.github/workflows/e2e-webkit.yml new file mode 100644 index 0000000..f0dcbb5 --- /dev/null +++ b/.github/workflows/e2e-webkit.yml @@ -0,0 +1,61 @@ +name: iPhone Safari smoke tests + +on: + push: + branches: [main] + pull_request: + branches: [main] + +permissions: + contents: read + +concurrency: + group: e2e-webkit-${{ github.ref }} + cancel-in-progress: true + +jobs: + webkit: + name: Playwright (WebKit, iPhone 15) + runs-on: ubuntu-latest + timeout-minutes: 20 + + steps: + - name: Checkout Codebase + uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + + # Version comes from packageManager in package.json + - name: Setup pnpm + uses: pnpm/action-setup@v6 + + - name: Setup Node.js + uses: actions/setup-node@v7 + with: + node-version: 24 + cache: "pnpm" + + - name: Install Dependencies + run: pnpm install --frozen-lockfile + + - name: Install WebKit + working-directory: artifacts/tc-reference + run: pnpm exec playwright install --with-deps webkit + + - name: Build production app + run: pnpm --filter @workspace/tc-reference build + + - name: Run smoke tests in WebKit + working-directory: artifacts/tc-reference + env: + E2E_SKIP_BUILD: "1" + run: pnpm run test:e2e --project iphone-webkit + + - name: Upload failure report + if: failure() + uses: actions/upload-artifact@v4 + with: + name: playwright-webkit-results + path: artifacts/tc-reference/test-results/ + retention-days: 7 + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index b2a96da..14ff91c 100644 --- a/.gitignore +++ b/.gitignore @@ -57,3 +57,7 @@ Thumbs.db /artifacts/tc-reference/public/cards/TC*/TC*_Phrase_Bank.csv /artifacts/tc-reference/public/cards/TC*/TC*_Anki_Flashcards.csv !/artifacts/tc-reference/public/cards/TC001/** + +# Playwright output +test-results/ +playwright-report/ diff --git a/README.md b/README.md index 0d46acf..18a07df 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,22 @@ A mobile-first reference app for 107 communication techniques. It runs entirely - 107 technique cards (voice/presence, influence/framing, clarity/direction, connection/warmth, resilience/recovery) - Library with category, impact and difficulty filters, sort controls and a live result count -- Phrase Bank (4,000+ phrases, filterable by tone and full-text searchable) +- **Start here**: a guided path through the 15 core cards, with progress kept on the device +- **Help me right now**: pick what is happening (eight common situations) and get one move, three lines to say, what to do next and one thing to avoid, without loading a full card +- Phrase Bank (about 4,500 lines, filterable by tone and length and searchable); a line that several cards share is listed once, under its first card - Daily drill: pick a track (Core 15, one category, a playbook or everything) and a pace, rate each technique Not yet, Getting there or Confident, and review it again when it comes due; streak tracking and undo included -- Playbooks: chain techniques into your own step-by-step guides -- Favourites for cards and phrases via localStorage persistence +- Playbooks: chain techniques into your own step-by-step guides, or start from a template +- Saved: keep cards and phrases (a line saved from any card that lists it shows as saved everywhere) - Quick Lookup overlay for fast in-conversation phrase recall, scoped to the open card with one tap to widen to all cards -- Full-screen search at `/search` (the search button, or `Cmd+K` / `Ctrl+K`) across techniques, phrases and playbooks: it matches as you type, keeps the search in the address so Back returns to your results, forgives typos and word forms, and maps everyday words to card vocabulary through a hand-kept synonym list (`artifacts/tc-reference/src/lib/search-synonyms.ts`), and left/right arrow keys to step between cards -- Light/dark theme persistence -- Back up and restore your data: export favourites, drill progress, playbooks and settings to a JSON file from the Favourites page, and import it on any device +- Full-screen search at `/search` (the search button, or `Cmd+K` / `Ctrl+K`) across techniques, phrases and playbooks: it matches as you type, keeps the search in the address so Back returns to your results, forgives typos and word forms, and maps everyday words to card vocabulary through a hand-kept synonym list (`artifacts/tc-reference/src/lib/search-synonyms.ts`); left/right arrow keys step between cards +- Settings (from the Saved page): light/dark theme, larger phrase text, drill track, offline status and backup +- Back up and restore your data: export saved items, drill progress, playbooks and settings to a JSON file, and import it on any device - Mobile-first navigation with a bottom tab bar, 44px touch targets and safe-area (notch) support -- Installable PWA: the app shell, global search, the Phrase Bank and Quick Lookup work offline after the first visit (a slim card text index is precached); full card pages and downloads work offline once they have been opened while online, and **Save all cards for offline** on the Favourites page saves every card (about 4 MB) in one step; downloads stay on demand +- Installable PWA: the app shell, global search, the Phrase Bank and Quick Lookup work offline after the first visit (a slim card text index is precached); full card pages and downloads work offline once they have been opened while online, and **Save all cards for offline** in Settings saves every card (about 4 MB) in one step; downloads stay on demand + +- On iPhone, add the app to your Home Screen so Safari doesn't clear your saved progress. The app asks the browser to keep its storage, shows a one-time Add to Home Screen hint in Safari, and reminds you to export a backup if you haven't for 30 days +- Daily Drill reviews come back after 1, 3 or 7 days (Not yet, Getting there, Confident) and then grow further apart; the Drill page's **Your progress** section counts techniques by status, overall and per category +- Each card's Use it tab ends with related techniques; missing pages, unknown cards and cards that fail to load offer a way forward (Try again, search, Help me right now) --- @@ -122,6 +128,14 @@ node --test scripts/code-reviewer.test.mjs scripts/local-process-identity.test.m pnpm --filter @workspace/tc-reference test ``` +Browser smoke tests (Playwright, iPhone 15 emulation). CI runs the WebKit project; locally only Chromium may be installed: + +```bash +pnpm --filter @workspace/tc-reference run test:e2e --project iphone-chromium +``` + +The manual iPhone pass (VoiceOver, larger text, offline, install) is in [docs/iphone-test-checklist.md](docs/iphone-test-checklist.md). + Before installing dependencies, run agent instruction and skill packaging checks directly: ```bash @@ -182,14 +196,26 @@ This is what Railway runs. For a quick local check, `serve` still runs ## Routes -| Path | Screen | -| --------------- | ---------------------------------------- | -| `/` | Library | +| Path | Screen | +| --------------- | ----------------------------------------------------- | +| `/` | Library | +| `/start` | Start here: the core cards in order | +| `/help` | Help me right now: pick a situation | +| `/help/:id` | One situation's move and lines | +| `/card/:cardId` | Full technique card (e.g. `/card/TC001`) | +| `/phrases` | Phrase Bank | +| `/drill` | Daily drill | +| `/playbooks` | Your playbooks and templates | +| `/favourites` | Saved cards and phrases (tab label "Saved"), Settings | +| `/search` | Full-screen search (`?q=` keeps the query) | + +--------------- | ---------------------------------------- | +| `/` | Library | | `/card/:cardId` | Full technique card (e.g. `/card/TC001`) | -| `/phrases` | Phrase browser | -| `/drill` | Daily drill screen | -| `/favourites` | Saved cards and phrases | -| `/playbooks` | Your saved technique playbooks | +| `/phrases` | Phrase browser | +| `/drill` | Daily drill screen | +| `/favourites` | Saved cards and phrases | +| `/playbooks` | Your saved technique playbooks | --- @@ -198,5 +224,5 @@ This is what Railway runs. For a quick local check, `serve` still runs TC Reference is a fully client-side SPA with no backend: - Core card, phrase and drill data lives in `artifacts/tc-reference/src/lib` -- User state uses `localStorage` (favourites, drill progress, playbooks under `tc_playbooks`, theme) +- User state uses `localStorage` (saved items under `tc_favourites`, drill progress, playbooks under `tc_playbooks`, preferences under `tc_preferences`, theme) - No backend or credentials are required diff --git a/artifacts/tc-reference/e2e/fixtures.ts b/artifacts/tc-reference/e2e/fixtures.ts new file mode 100644 index 0000000..5c429d1 --- /dev/null +++ b/artifacts/tc-reference/e2e/fixtures.ts @@ -0,0 +1,48 @@ +import { expect, test as base, type Page } from "@playwright/test"; + +/** Main routes every smoke pass visits. */ +export const MAIN_ROUTES = [ + "/", + "/card/TC028", + "/help", + "/help/say-no", + "/search", + "/phrases", + "/drill", + "/playbooks", + "/favourites", + "/start", +] as const; + +/** + * Grant clipboard access where the engine supports the permission names. + * Chromium needs them for navigator.clipboard; WebKit has no such permission + * and allows writes from a user gesture on a secure (localhost) origin. + */ +export const test = base.extend<{ clipboard: boolean }>({ + clipboard: async ({ context, browserName }, use) => { + const granted = browserName === "chromium"; + if (granted) { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + } + await use(granted); + }, +}); + +export { expect }; + +/** + * Wait until the service worker has installed its precache and controls the + * page. The worker is in "prompt" mode (no clients.claim), so the first + * visit is only controlled after one reload, as on a real phone. + */ +export async function waitForServiceWorker(page: Page) { + await page.evaluate(async () => { + await navigator.serviceWorker.ready; + }); + if (await page.evaluate(() => !!navigator.serviceWorker.controller)) return; + await page.reload(); + await expect + .poll(() => page.evaluate(() => !!navigator.serviceWorker.controller)) + .toBe(true); +} diff --git a/artifacts/tc-reference/e2e/layout.spec.ts b/artifacts/tc-reference/e2e/layout.spec.ts new file mode 100644 index 0000000..288148a --- /dev/null +++ b/artifacts/tc-reference/e2e/layout.spec.ts @@ -0,0 +1,168 @@ +import { test, expect, MAIN_ROUTES } from "./fixtures"; + +/** Wait for the route's content (lazy chunks, card loader) to settle. */ +async function settle(page: import("@playwright/test").Page) { + await expect(page.getByRole("heading", { level: 1 }).first()).toBeVisible(); + await expect(page.locator('[aria-busy="true"]')).toHaveCount(0); +} + +for (const route of MAIN_ROUTES) { + test(`${route} has no console errors and no sideways scroll`, async ({ + page, + }) => { + const errors: string[] = []; + page.on("console", (msg) => { + if (msg.type() === "error") errors.push(msg.text()); + }); + page.on("pageerror", (err) => errors.push(err.message)); + + const response = await page.goto(route); + expect(response?.status(), "HTTP status").toBe(200); + await settle(page); + + expect(page.viewportSize()?.width).toBe(393); + const overflow = await page.evaluate(() => { + const root = document.documentElement; + return { + scrollWidth: root.scrollWidth, + clientWidth: root.clientWidth, + bodyScrollWidth: document.body.scrollWidth, + }; + }); + expect(overflow.scrollWidth).toBeLessThanOrEqual(overflow.clientWidth); + expect(overflow.bodyScrollWidth).toBeLessThanOrEqual(overflow.clientWidth); + + expect(errors).toEqual([]); + }); +} + +test("tab bar sits on the bottom edge and pads for the home indicator", async ({ + page, +}) => { + await page.goto("/"); + const viewport = await page.evaluate(() => ({ + fit: document + .querySelector('meta[name="viewport"]') + ?.getAttribute("content"), + height: window.innerHeight, + })); + // viewport-fit=cover is what makes env(safe-area-inset-*) non-zero on iPhone + expect(viewport.fit).toContain("viewport-fit=cover"); + + const bar = page.getByRole("navigation", { name: "Main navigation" }); + await expect(bar).toBeVisible(); + const box = await bar.boundingBox(); + expect(box).not.toBeNull(); + expect(Math.round(box!.y + box!.height)).toBe(viewport.height); + + const padding = await bar.evaluate((el) => { + // Resolve the same expression the bar uses with a known inset, to prove + // the gap follows env(safe-area-inset-bottom) rather than a fixed value. + const probe = document.createElement("div"); + probe.style.paddingBottom = "var(--tabbar-gap)"; + el.appendChild(probe); + const resolved = getComputedStyle(probe).paddingBottom; + probe.remove(); + const rules = [...document.styleSheets].flatMap((sheet) => { + try { + return [...sheet.cssRules].map((rule) => rule.cssText); + } catch { + return []; + } + }); + return { + actual: parseFloat(getComputedStyle(el).paddingBottom), + resolved: parseFloat(resolved), + usesInset: rules.some((text) => + /--tabbar-gap:[^;]*env\(safe-area-inset-bottom/.test(text), + ), + }; + }); + expect(padding.usesInset).toBe(true); + // Emulators report a zero inset, so the 8px floor applies; on a real + // iPhone the home indicator inset (34px) is larger and wins. + expect(padding.actual).toBeGreaterThanOrEqual(8); + expect(padding.actual).toBe(padding.resolved); + + // Every destination is reachable with one tap + for (const name of ["Library", "Phrases", "Drill", "Playbooks", "Saved"]) { + await expect( + bar.getByRole("link", { name: new RegExp(`^${name}`) }), + ).toBeVisible(); + } +}); + +test.describe("landscape iPhone with a notch", () => { + // iPhone 15 turned sideways: 852pt wide, so the sidebar layout. iOS reports + // a 59pt inset on both sides and 21pt for the home indicator. + const INSET = 59; + test.use({ viewport: { width: 852, height: 393 } }); + + for (const route of ["/", "/card/TC028", "/phrases", "/search"]) { + test(`${route} keeps content out of the side safe areas`, async ({ + page, + browserName, + }) => { + // Only Chromium can emulate safe-area insets (via CDP). + test.skip(browserName !== "chromium", "needs CDP safe-area override"); + const cdp = await page.context().newCDPSession(page); + await cdp.send("Emulation.setSafeAreaInsetsOverride", { + insets: { top: 0, left: INSET, right: INSET, bottom: 21 }, + }); + await page.goto(route); + await expect(page.locator("h1").first()).toBeVisible(); + await expect(page.locator('[aria-busy="true"]')).toHaveCount(0); + + const intruders = await page.evaluate((inset) => { + const found: string[] = []; + const selector = "h1, h2, h3, p, a, button, input, [role=tab]"; + for (const el of document.querySelectorAll(selector)) { + const r = el.getBoundingClientRect(); + if (!r.width || !r.height) continue; + // Rows that scroll sideways may run under the edges by design. + if (el.closest("[class*='overflow-x-auto']")) continue; + if (r.left < inset - 0.5 || r.right > innerWidth - inset + 0.5) { + const text = (el.textContent ?? "").trim().slice(0, 30); + found.push( + `${el.tagName} "${text}" ${Math.round(r.left)}-${Math.round(r.right)}`, + ); + } + } + return found; + }, INSET); + expect(intruders).toEqual([]); + }); + } +}); + +test("iOS gets a launch screen for this iPhone, and the manifest allows rotation", async ({ + page, + request, +}) => { + await page.goto("/"); + const links = await page.evaluate(() => + [ + ...document.querySelectorAll( + 'link[rel="apple-touch-startup-image"]', + ), + ].map((link) => ({ href: link.href, media: link.media })), + ); + expect(links.length).toBeGreaterThan(5); + // Exactly one image is for the iPhone 15 screen (393x852pt @3x). The test + // runner's emulated screen is the viewport, so match the query text rather + // than asking matchMedia. + const iphone15 = links.filter( + (l) => + l.media.includes("(device-width: 393px)") && + l.media.includes("(device-height: 852px)") && + l.media.includes("(-webkit-device-pixel-ratio: 3)"), + ); + expect(iphone15).toHaveLength(1); + expect(iphone15[0].href).toMatch(/\/splash\/launch-1179x2556\.png$/); + const image = await request.get(iphone15[0].href); + expect(image.status()).toBe(200); + expect(image.headers()["content-type"]).toContain("image/png"); + + const manifest = await (await request.get("/manifest.webmanifest")).json(); + expect(manifest.orientation ?? "any").toBe("any"); +}); diff --git a/artifacts/tc-reference/e2e/offline.spec.ts b/artifacts/tc-reference/e2e/offline.spec.ts new file mode 100644 index 0000000..dec42d2 --- /dev/null +++ b/artifacts/tc-reference/e2e/offline.spec.ts @@ -0,0 +1,61 @@ +import { test, expect, waitForServiceWorker } from "./fixtures"; + +test("Library and Phrase Bank load offline after the first visit", async ({ + page, + context, + browserName, +}) => { + await page.goto("/"); + await expect( + page.getByRole("heading", { level: 1, name: "Library" }), + ).toBeVisible(); + await waitForServiceWorker(page); + + if (browserName === "webkit") { + // Playwright's WebKit can't reload a service-worker page while emulating + // offline ("WebKit encountered an internal error"), so on WebKit check + // what an offline reload depends on: the worker controls the page and + // the precache holds the app shell, the card text index and the Phrase + // Bank chunk. Chromium below does the real offline reload. + const cached = await page.evaluate(async () => { + const urls: string[] = []; + for (const name of await caches.keys()) { + const cache = await caches.open(name); + for (const req of await cache.keys()) urls.push(req.url); + } + return { controlled: !!navigator.serviceWorker.controller, urls }; + }); + expect(cached.controlled).toBe(true); + const has = (re: RegExp) => cached.urls.some((u) => re.test(u)); + expect(has(/\/index\.html(\?|$)/)).toBe(true); + expect(has(/\/assets\/card-text-data-[^/]+\.js/)).toBe(true); + expect(has(/\/assets\/phrases-[^/]+\.js/)).toBe(true); + return; + } + + await context.setOffline(true); + try { + await page.reload(); + await expect( + page.getByRole("heading", { level: 1, name: "Library" }), + ).toBeVisible(); + await expect( + page.getByRole("link", { name: /^Warm vocal baseline/ }), + ).toBeVisible(); + + await page.goto("/phrases"); + await expect( + page.getByRole("heading", { level: 1, name: "Phrase Bank" }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: /^Copy: / }).first(), + ).toBeVisible(); + + await page.reload(); + await expect( + page.getByRole("heading", { level: 1, name: "Phrase Bank" }), + ).toBeVisible(); + } finally { + await context.setOffline(false); + } +}); diff --git a/artifacts/tc-reference/e2e/smoke.spec.ts b/artifacts/tc-reference/e2e/smoke.spec.ts new file mode 100644 index 0000000..716733e --- /dev/null +++ b/artifacts/tc-reference/e2e/smoke.spec.ts @@ -0,0 +1,170 @@ +import { test, expect } from "./fixtures"; + +test.describe("core flows", () => { + test("Library loads and a card opens", async ({ page }) => { + await page.goto("/"); + await expect( + page.getByRole("heading", { level: 1, name: "Library" }), + ).toBeVisible(); + const row = page.getByRole("link", { name: /^Warm vocal baseline/ }); + // Centre the row first: scrolled only to the viewport edge it can sit + // under the fixed tab bar while the header folds away, and the tap + // lands on the bar instead (seen in WebKit). + await row.evaluate((el) => el.scrollIntoView({ block: "center" })); + await row.click(); + await expect(page).toHaveURL(/\/card\/TC028$/); + await expect( + page.getByRole("heading", { level: 2, name: "Warm vocal baseline" }), + ).toBeVisible(); + }); + + test("card tabs switch between Use it, Learn it and Practise it", async ({ + page, + }) => { + await page.goto("/card/TC028"); + const tabs = page.getByRole("tablist", { name: "Card sections" }); + const useIt = tabs.getByRole("tab", { name: "Use it" }); + const learnIt = tabs.getByRole("tab", { name: "Learn it" }); + const practiseIt = tabs.getByRole("tab", { name: "Practise it" }); + + await expect(useIt).toHaveAttribute("aria-selected", "true"); + await expect(page.getByRole("tabpanel", { name: "Use it" })).toBeVisible(); + + await learnIt.click(); + await expect(learnIt).toHaveAttribute("aria-selected", "true"); + await expect( + page.getByRole("tabpanel", { name: "Learn it" }), + ).toBeVisible(); + + await practiseIt.click(); + await expect(practiseIt).toHaveAttribute("aria-selected", "true"); + await expect( + page.getByRole("tabpanel", { name: "Practise it" }), + ).toBeVisible(); + + await useIt.click(); + await expect(useIt).toHaveAttribute("aria-selected", "true"); + }); + + test("search finds a technique and Back returns to the results", async ({ + page, + }) => { + await page.goto("/"); + await page + .getByRole("link", { name: "Search techniques and phrases…" }) + .click(); + await expect(page).toHaveURL(/\/search/); + await page + .getByRole("searchbox", { + name: "Search techniques, phrases and playbooks", + }) + .fill("mirroring"); + await expect(page.getByRole("status").first()).toContainText( + /results? for mirroring/, + ); + const best = page.getByRole("link", { name: /Best match.*Tactical/ }); + await best.click(); + await expect(page).toHaveURL(/\/card\/TC026$/); + await expect( + page.getByRole("heading", { level: 2, name: "Tactical mirroring" }), + ).toBeVisible(); + + await page.goBack(); + await expect(page).toHaveURL(/\/search\?q=mirroring/); + await expect( + page.getByRole("heading", { level: 1, name: "Search results" }), + ).toBeVisible(); + await expect( + page.getByRole("searchbox", { + name: "Search techniques, phrases and playbooks", + }), + ).toHaveValue("mirroring"); + }); + + test("Help me right now opens a situation and copies a line", async ({ + page, + clipboard, + }) => { + await page.goto("/"); + await page.getByRole("link", { name: /^Help me right now/ }).click(); + await expect( + page.getByRole("heading", { level: 1, name: "What's happening?" }), + ).toBeVisible(); + await page.getByRole("link", { name: /^I need to say no/ }).click(); + await expect(page).toHaveURL(/\/help\/say-no$/); + await expect( + page.getByRole("heading", { level: 1, name: "I need to say no" }), + ).toBeVisible(); + + const line = "I can't take that on right now."; + await page.getByRole("button", { name: `Copy: ${line}` }).click(); + await expect( + page.getByRole("status").filter({ hasText: "Copied" }), + ).toBeVisible(); + if (clipboard) { + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe( + line, + ); + } + }); + + test("Phrase Bank filters by tone", async ({ page }) => { + await page.goto("/phrases"); + await expect( + page.getByRole("heading", { level: 1, name: "Phrase Bank" }), + ).toBeVisible(); + const tones = page.getByRole("group", { name: "Filter by tone" }); + const warm = tones.getByRole("button", { name: /^Warm \d+/ }); + const warmCount = (await warm.textContent())?.match(/\d[\d,]*/)?.[0]; + expect(warmCount).toBeTruthy(); + + await warm.click(); + await expect(warm).toHaveAttribute("aria-pressed", "true"); + await expect(tones.getByRole("button", { name: /^Any/ })).toHaveAttribute( + "aria-pressed", + "false", + ); + await expect( + page.getByText(new RegExp(`^${warmCount} phrases? · Warm$`)), + ).toBeVisible(); + }); + + test("Daily Drill rates today's task", async ({ page }) => { + await page.goto("/drill"); + await expect( + page.getByRole("heading", { level: 1, name: "Daily Drill" }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "Rate it to finish" }), + ).toBeDisabled(); + + const rating = page + .getByRole("group", { name: "How does this technique feel?" }) + .getByRole("button", { name: "Getting there" }); + await rating.click(); + await expect(rating).toHaveAttribute("aria-pressed", "true"); + + const finish = page.getByRole("button", { name: "Finish today's drill" }); + await expect(finish).toBeEnabled(); + await finish.click(); + await expect(finish).toBeHidden(); + }); + + test("Saved keeps a favourited card after reload", async ({ page }) => { + await page.goto("/"); + const heart = page.getByRole("button", { + name: "Favourite Warm vocal baseline", + }); + await heart.click(); + await expect(heart).toHaveAttribute("aria-pressed", "true"); + + await page.goto("/favourites"); + await page.reload(); + await expect( + page.getByRole("heading", { level: 1, name: "Saved" }), + ).toBeVisible(); + await expect( + page.getByRole("main").getByRole("link", { name: /Warm vocal baseline/ }), + ).toBeVisible(); + }); +}); diff --git a/artifacts/tc-reference/e2e/tsconfig.json b/artifacts/tc-reference/e2e/tsconfig.json new file mode 100644 index 0000000..ff828d7 --- /dev/null +++ b/artifacts/tc-reference/e2e/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base.json", + "include": ["./**/*.ts", "../playwright.config.ts"], + "compilerOptions": { + "noEmit": true, + "incremental": false, + "lib": ["esnext", "dom", "dom.iterable"], + "moduleResolution": "bundler", + "types": ["node"] + } +} diff --git a/artifacts/tc-reference/font-preload-plugin.ts b/artifacts/tc-reference/font-preload-plugin.ts new file mode 100644 index 0000000..452bcd6 --- /dev/null +++ b/artifacts/tc-reference/font-preload-plugin.ts @@ -0,0 +1,45 @@ +import type { Plugin } from "vite"; + +/** + * Preloads the self-hosted Inter faces that every first screen paints with. + * + * The @font-face rules live in CSS and the browser only requests a face once + * text using it is laid out, which on a cold load is after the app bundle has + * run. A preload starts those downloads with the HTML instead, so the first + * render does not paint in the fallback face and then lay out again when Inter + * arrives. Only the Latin subsets of the weights used above the fold are + * preloaded; the rest (500, 800 and other scripts) still load on demand. + */ +export function fontPreloadPlugin(weights: readonly number[]): Plugin { + const pattern = new RegExp( + `^assets/inter-latin-(${weights.join("|")})-normal-[^/]+\\.woff2$`, + ); + let base = "/"; + return { + name: "tc-font-preload", + apply: "build", + configResolved(config) { + base = config.base; + }, + transformIndexHtml: { + order: "post", + handler(_html, ctx) { + if (!ctx.bundle) return; + return Object.keys(ctx.bundle) + .filter((fileName) => pattern.test(fileName)) + .sort() + .map((fileName) => ({ + tag: "link", + attrs: { + rel: "preload", + as: "font", + type: "font/woff2", + href: `${base}${fileName}`, + crossorigin: "", + }, + injectTo: "head" as const, + })); + }, + }, + }; +} diff --git a/artifacts/tc-reference/launch-screens.ts b/artifacts/tc-reference/launch-screens.ts new file mode 100644 index 0000000..754dd9f --- /dev/null +++ b/artifacts/tc-reference/launch-screens.ts @@ -0,0 +1,96 @@ +import type { Plugin } from "vite"; + +// iOS launch screens (apple-touch-startup-image). Without one, a Home Screen +// launch shows a blank screen until the first paint. iOS only uses an image +// whose media query matches the device exactly, so there is one per iPhone +// screen size. Portrait only: launches mostly start in portrait, and each +// orientation doubles the files. iPads fall back to the blank screen. +// +// The PNGs live in public/splash/ and are made by +// scripts/generate-launch-screens.ts (rerun it after changing this list or +// the icon). They are deliberately not precached: iOS fetches the matching +// one when the app is added to the Home Screen. + +export const LAUNCH_SCREEN_DIR = "splash"; +export const LAUNCH_SCREEN_BACKGROUND = "#0f1724"; + +export interface LaunchScreen { + /** CSS (portrait) viewport, in points. */ + width: number; + height: number; + /** Device pixel ratio. */ + ratio: 2 | 3; + /** Phones this size covers, for humans. */ + devices: string; +} + +export const LAUNCH_SCREENS: readonly LaunchScreen[] = [ + { width: 440, height: 956, ratio: 3, devices: "16 Pro Max, 17 Pro Max" }, + { + width: 430, + height: 932, + ratio: 3, + devices: "14 Pro Max, 15 Plus/Pro Max, 16 Plus", + }, + { width: 420, height: 912, ratio: 3, devices: "Air" }, + { width: 402, height: 874, ratio: 3, devices: "16 Pro, 17, 17 Pro" }, + { width: 393, height: 852, ratio: 3, devices: "14 Pro, 15, 15 Pro, 16" }, + { width: 428, height: 926, ratio: 3, devices: "12/13 Pro Max, 14 Plus" }, + { + width: 390, + height: 844, + ratio: 3, + devices: "12, 12 Pro, 13, 13 Pro, 14, 16e", + }, + { + width: 375, + height: 812, + ratio: 3, + devices: "X, XS, 11 Pro, 12 mini, 13 mini", + }, + { width: 414, height: 896, ratio: 3, devices: "XS Max, 11 Pro Max" }, + { width: 414, height: 896, ratio: 2, devices: "XR, 11" }, + { width: 375, height: 667, ratio: 2, devices: "SE (2nd/3rd gen), 8" }, +]; + +export function launchScreenFile(screen: LaunchScreen): string { + const w = screen.width * screen.ratio; + const h = screen.height * screen.ratio; + return `${LAUNCH_SCREEN_DIR}/launch-${w}x${h}.png`; +} + +export function launchScreenMedia(screen: LaunchScreen): string { + return ( + `(device-width: ${screen.width}px) and (device-height: ${screen.height}px)` + + ` and (-webkit-device-pixel-ratio: ${screen.ratio})` + + " and (orientation: portrait)" + ); +} + +/** The tags for index.html, with hrefs under the app base. */ +export function launchScreenLinks(base: string): string { + return LAUNCH_SCREENS.map( + (screen) => + ``, + ).join("\n "); +} + +/** Adds the launch screen links to the head of index.html. */ +export function launchScreensPlugin(): Plugin { + let base = "/"; + return { + name: "tc-launch-screens", + configResolved(config) { + base = config.base; + }, + transformIndexHtml: { + order: "post", + handler(html) { + return html.replace( + "", + ` ${launchScreenLinks(base)}\n `, + ); + }, + }, + }; +} diff --git a/artifacts/tc-reference/package.json b/artifacts/tc-reference/package.json index ace0945..6a5c024 100644 --- a/artifacts/tc-reference/package.json +++ b/artifacts/tc-reference/package.json @@ -9,12 +9,14 @@ "build": "pnpm run generate:downloads && vite build --config vite.config.ts && pnpm --filter @workspace/scripts exec tsx ../artifacts/tc-reference/scripts/verify-card-build.ts && node scripts/precompress.mjs", "serve": "vite preview --config vite.config.ts --host 127.0.0.1", "start": "node server.mjs", - "typecheck": "tsc -p tsconfig.json --noEmit", + "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:full": "pnpm run generate:downloads && vitest run --config vitest.config.ts", + "test:e2e": "playwright test --trace off" }, "devDependencies": { "@fontsource/inter": "^5.3.0", + "@playwright/test": "1.63.0", "@tailwindcss/vite": "catalog:", "@testing-library/dom": "^10.4.2", "@testing-library/jest-dom": "^7.0.1", diff --git a/artifacts/tc-reference/playwright.config.ts b/artifacts/tc-reference/playwright.config.ts new file mode 100644 index 0000000..ba7f6e7 --- /dev/null +++ b/artifacts/tc-reference/playwright.config.ts @@ -0,0 +1,47 @@ +import { defineConfig, devices } from "@playwright/test"; + +// Real-browser smoke tests against the production build served by server.mjs. +// "iphone-webkit" is the Safari engine (run in CI); "iphone-chromium" is the +// same phone on Chromium, for machines that only have Chromium installed. +// +// The web server builds first. Set E2E_SKIP_BUILD=1 to serve an existing +// dist/public (CI builds in its own step). +const port = Number(process.env.E2E_PORT ?? 4417); +const baseURL = `http://127.0.0.1:${port}`; +const build = process.env.E2E_SKIP_BUILD ? "" : "pnpm run build && "; + +export default defineConfig({ + testDir: "./e2e", + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + workers: process.env.CI ? 2 : undefined, + reporter: process.env.CI ? [["list"], ["github"]] : "list", + timeout: 30_000, + expect: { timeout: 10_000 }, + use: { + baseURL, + trace: "off", + screenshot: "only-on-failure", + serviceWorkers: "allow", + }, + projects: [ + { + name: "iphone-webkit", + use: { ...devices["iPhone 15"], browserName: "webkit" }, + }, + { + name: "iphone-chromium", + use: { ...devices["iPhone 15"], browserName: "chromium" }, + }, + ], + webServer: { + command: `${build}node server.mjs`, + url: baseURL, + env: { PORT: String(port), HOST: "127.0.0.1" }, + reuseExistingServer: !process.env.CI, + timeout: 300_000, + stdout: "ignore", + stderr: "pipe", + }, +}); diff --git a/artifacts/tc-reference/public/splash/launch-1125x2436.png b/artifacts/tc-reference/public/splash/launch-1125x2436.png new file mode 100644 index 0000000..38b735d Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1125x2436.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1170x2532.png b/artifacts/tc-reference/public/splash/launch-1170x2532.png new file mode 100644 index 0000000..0d6c192 Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1170x2532.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1179x2556.png b/artifacts/tc-reference/public/splash/launch-1179x2556.png new file mode 100644 index 0000000..4708f8d Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1179x2556.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1206x2622.png b/artifacts/tc-reference/public/splash/launch-1206x2622.png new file mode 100644 index 0000000..4e6384a Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1206x2622.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1242x2688.png b/artifacts/tc-reference/public/splash/launch-1242x2688.png new file mode 100644 index 0000000..600b04e Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1242x2688.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1260x2736.png b/artifacts/tc-reference/public/splash/launch-1260x2736.png new file mode 100644 index 0000000..d02a459 Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1260x2736.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1284x2778.png b/artifacts/tc-reference/public/splash/launch-1284x2778.png new file mode 100644 index 0000000..758bfd2 Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1284x2778.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1290x2796.png b/artifacts/tc-reference/public/splash/launch-1290x2796.png new file mode 100644 index 0000000..67f1d0d Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1290x2796.png differ diff --git a/artifacts/tc-reference/public/splash/launch-1320x2868.png b/artifacts/tc-reference/public/splash/launch-1320x2868.png new file mode 100644 index 0000000..bbf3551 Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-1320x2868.png differ diff --git a/artifacts/tc-reference/public/splash/launch-750x1334.png b/artifacts/tc-reference/public/splash/launch-750x1334.png new file mode 100644 index 0000000..41d62ab Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-750x1334.png differ diff --git a/artifacts/tc-reference/public/splash/launch-828x1792.png b/artifacts/tc-reference/public/splash/launch-828x1792.png new file mode 100644 index 0000000..37d5133 Binary files /dev/null and b/artifacts/tc-reference/public/splash/launch-828x1792.png differ diff --git a/artifacts/tc-reference/scripts/generate-launch-screens.ts b/artifacts/tc-reference/scripts/generate-launch-screens.ts new file mode 100644 index 0000000..507ab0e --- /dev/null +++ b/artifacts/tc-reference/scripts/generate-launch-screens.ts @@ -0,0 +1,46 @@ +// Renders the iOS launch screens listed in launch-screens.ts into +// public/splash/: the app icon centred on the app background. +// +// pnpm --filter @workspace/scripts exec tsx ../artifacts/tc-reference/scripts/generate-launch-screens.ts +// +// Uses Playwright's Chromium (already a dev dependency for the e2e tests). +import { mkdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { chromium } from "@playwright/test"; +import { + LAUNCH_SCREENS, + LAUNCH_SCREEN_BACKGROUND, + launchScreenFile, +} from "../launch-screens.ts"; + +const appDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const publicDir = path.join(appDir, "public"); +// The rendered app icon (not favicon.svg, whose text depends on installed +// fonts). Its outer square is the background colour, so only the amber tile +// shows: it reads as the Home Screen icon opening into the app. +const icon = readFileSync(path.join(publicDir, "pwa-icon-512.png")); +const iconUrl = `data:image/png;base64,${icon.toString("base64")}`; +const ICON_POINTS = 160; + +const browser = await chromium.launch(); +try { + for (const screen of LAUNCH_SCREENS) { + const page = await browser.newPage({ + viewport: { width: screen.width, height: screen.height }, + deviceScaleFactor: screen.ratio, + }); + await page.setContent( + `` + + `` + + ``, + ); + const file = path.join(publicDir, launchScreenFile(screen)); + mkdirSync(path.dirname(file), { recursive: true }); + await page.screenshot({ path: file, omitBackground: false }); + await page.close(); + console.log(`wrote ${path.relative(appDir, file)} (${screen.devices})`); + } +} finally { + await browser.close(); +} diff --git a/artifacts/tc-reference/server.mjs b/artifacts/tc-reference/server.mjs index 06fc9b3..092f26e 100644 --- a/artifacts/tc-reference/server.mjs +++ b/artifacts/tc-reference/server.mjs @@ -32,7 +32,8 @@ const NO_CACHE_FILES = new Set([ const APP_ROUTES = [ /^\/$/, /^\/card\/TC\d{3}\/?$/, - /^\/(drill|favourites|phrases|playbooks)\/?$/, + /^\/(drill|favourites|phrases|playbooks|search|start)\/?$/, + /^\/help(\/[a-z0-9-]+)?\/?$/, /^\/index\.html$/, ]; diff --git a/artifacts/tc-reference/src/App.tsx b/artifacts/tc-reference/src/App.tsx index ae3c7bb..4dea4c9 100644 --- a/artifacts/tc-reference/src/App.tsx +++ b/artifacts/tc-reference/src/App.tsx @@ -21,6 +21,7 @@ import { PdfProvider } from "@/lib/pdf-context"; import { AppLayout } from "@/components/app-layout"; import { AppErrorBoundary } from "@/components/app-error-boundary"; import { UpdateToast } from "@/components/update-toast"; +import { DataSafetyNudge } from "@/components/data-safety-nudge"; import { PreferencesSync } from "@/lib/preferences"; function RouteFallback() { @@ -89,6 +90,7 @@ function App() { + diff --git a/artifacts/tc-reference/src/components/app-header.tsx b/artifacts/tc-reference/src/components/app-header.tsx index ed1dfb2..a8cbb9e 100644 --- a/artifacts/tc-reference/src/components/app-header.tsx +++ b/artifacts/tc-reference/src/components/app-header.tsx @@ -42,6 +42,7 @@ const PAGE_TITLES: Record = { "/favourites": "Saved", "/playbooks": "Playbooks", "/start": "Start here", + "/search": "Search", }; // Header actions share one quiet style. "brand" tints the icon amber for the @@ -154,7 +155,7 @@ export function AppHeader() { const isLibraryRoute = location === "/"; const pageTitle = - PAGE_TITLES[location.replace(/^\/help\/.*/, "/help")] ?? "Library"; + PAGE_TITLES[location.replace(/^\/help\/.*/, "/help")] ?? "Page not found"; const searchButton = (testId: string) => ( {/* ── CARD MODE ── */} @@ -243,15 +244,17 @@ export function AppHeader() {
{/* The ID tag gives way to the title on narrow phones */} - - {cardId} - + {cardMeta && ( + + {cardId} + + )}

- {cardMeta?.cardTitle ?? cardId} + {cardMeta?.cardTitle ?? "Card not found"}

diff --git a/artifacts/tc-reference/src/components/app-layout.tsx b/artifacts/tc-reference/src/components/app-layout.tsx index 3529166..2d99d03 100644 --- a/artifacts/tc-reference/src/components/app-layout.tsx +++ b/artifacts/tc-reference/src/components/app-layout.tsx @@ -33,8 +33,11 @@ export function AppLayout({ children }: AppLayoutProps) {
+ + ); +} diff --git a/artifacts/tc-reference/src/components/drill-progress.tsx b/artifacts/tc-reference/src/components/drill-progress.tsx new file mode 100644 index 0000000..6457bd1 --- /dev/null +++ b/artifacts/tc-reference/src/components/drill-progress.tsx @@ -0,0 +1,225 @@ +import type { CSSProperties } from "react"; +import { ChevronRight } from "lucide-react"; +import { categoryStyleFor } from "@/lib/design-tokens"; +import { + STATUS_LABELS, + STATUS_ORDER, + type CategoryProgress, + type ProgressCounts, + type TechniqueStatus, +} from "@/lib/drill-view"; + +const EYEBROW = "text-[12px] font-bold uppercase tracking-[0.06em]"; + +/** Fill for each status in the bars and the key. Shape and text carry the + meaning too, so colour is never the only cue. */ +const STATUS_FILL: Record = { + confident: "var(--brand)", + "getting-there": "color-mix(in srgb, var(--brand) 45%, transparent)", + "not-yet": "var(--fg-35)", + "not-started": "var(--fg-10)", +}; + +const CARD_STYLE: CSSProperties = { + background: "var(--surface-card)", + border: "1px solid var(--fg-07)", + boxShadow: "var(--shadow-card)", +}; + +function plural(n: number, word: string) { + return `${n} ${word}${n === 1 ? "" : "s"}`; +} + +/** "3 confident, 1 getting there, 2 due for review": the non-zero counts. */ +export function progressSummary(counts: ProgressCounts): string { + const parts = STATUS_ORDER.filter( + (s) => s !== "not-started" && counts.byStatus[s] > 0, + ).map((s) => `${counts.byStatus[s]} ${STATUS_LABELS[s].toLowerCase()}`); + if (counts.due > 0) parts.push(`${counts.due} due for review`); + return parts.length > 0 ? parts.join(", ") : "Not started yet"; +} + +/** One bar split by status; decorative, the counts are written out beside it. */ +function StatusBar({ + counts, + height, +}: { + counts: ProgressCounts; + height: number; +}) { + return ( + + ); +} + +interface DrillProgressProps { + overall: ProgressCounts; + categories: readonly CategoryProgress[]; + /** Opens the track picker on that category. */ + onPickCategory?: (category: string) => void; +} + +/** + * How every technique stands: Confident, Getting there, Not yet or not + * started, with reviews due, overall and per library category. + */ +export function DrillProgress({ + overall, + categories, + onPickCategory, +}: DrillProgressProps) { + const started = overall.total - overall.byStatus["not-started"]; + return ( +
+
+

+ Your progress +

+ + {started} of {plural(overall.total, "technique")} started + +
+ +
+ +
+ {STATUS_ORDER.map((s) => ( +
+
+ ))} +
+
+ Due for review +
+
+ {overall.due} +
+
+
+
+ +

By category

+
    + {categories.map((c) => { + const style = categoryStyleFor(c.category); + const confident = c.byStatus.confident; + const body = ( + <> +
+
+ ); +} diff --git a/artifacts/tc-reference/src/components/drill-rating.tsx b/artifacts/tc-reference/src/components/drill-rating.tsx index 903a9e9..b437195 100644 --- a/artifacts/tc-reference/src/components/drill-rating.tsx +++ b/artifacts/tc-reference/src/components/drill-rating.tsx @@ -1,6 +1,6 @@ import { useId } from "react"; import { DRILL_RATINGS, type DrillRating } from "@/lib/drill-state"; -import { gapLabel, RATING_LABELS } from "@/lib/drill-view"; +import { RATING_LABELS, shortGapLabel, spokenGapLabel } from "@/lib/drill-view"; interface DrillRatingProps { value: DrillRating | null; @@ -22,9 +22,6 @@ export function DrillRating({ prompt = "How does this technique feel?", }: DrillRatingProps) { const promptId = useId(); - // A first rating comes back tomorrow whichever is picked; three identical - // hints would only suggest the choice doesn't matter, so say it once. - const sameGap = DRILL_RATINGS.every((r) => gaps[r] === gaps["not-yet"]); return (
onChange(rating)} data-testid={`drill-rating-${rating}`} className="min-h-[52px] px-1 py-2 rounded-[14px] flex flex-col items-center justify-center gap-0.5 text-center transition-transform active:scale-[0.98] motion-reduce:transition-none" @@ -67,29 +60,17 @@ export function DrillRating({ style={{ color: "var(--fg-90)" }} > {RATING_LABELS[rating]} + {" "} + + {shortGapLabel(gaps[rating])} - {!sameGap && ( - - {gapLabel(gaps[rating])} - - )} ); })}
- {sameGap && ( -

- {gapLabel(gaps["not-yet"])} either way. Your rating sets the gaps - after that. -

- )} ); } diff --git a/artifacts/tc-reference/src/components/drill-track-sheet.tsx b/artifacts/tc-reference/src/components/drill-track-sheet.tsx index 47dc3a0..69c767b 100644 --- a/artifacts/tc-reference/src/components/drill-track-sheet.tsx +++ b/artifacts/tc-reference/src/components/drill-track-sheet.tsx @@ -133,6 +133,8 @@ interface DrillTrackSheetProps { dueCount: number; /** Open on Core at three days each: the short way in for a new reader. */ suggestCore?: boolean; + /** Open on this library category (from a progress row). */ + initialCategory?: string; onApply: (track: DrillTrack, pace: DrillPace) => void; onClose: () => void; } @@ -147,6 +149,7 @@ export function DrillTrackSheet({ state, dueCount, suggestCore = false, + initialCategory, onApply, onClose, }: DrillTrackSheetProps) { @@ -187,11 +190,16 @@ export function DrillTrackSheet({ return { options, savedCount }; }, [playbooks, current]); + const startCategory = + initialCategory && CATEGORY_NAMES.includes(initialCategory) + ? initialCategory + : undefined; const [kind, setKind] = useState( - suggestCore ? "core" : current.kind, + startCategory ? "category" : suggestCore ? "core" : current.kind, ); const [category, setCategory] = useState( - current.kind === "category" ? current.category : CATEGORY_NAMES[0], + startCategory ?? + (current.kind === "category" ? current.category : CATEGORY_NAMES[0]), ); const [playbookId, setPlaybookId] = useState( current.kind === "playbook" @@ -389,7 +397,7 @@ export function DrillTrackSheet({ style={ selected ? { - background: "var(--surface-dd)", + background: "var(--surface-segment-active)", color: "var(--fg-90)", boxShadow: "0 1px 4px rgba(0,0,0,0.25)", } diff --git a/artifacts/tc-reference/src/components/library/card-row.tsx b/artifacts/tc-reference/src/components/library/card-row.tsx index e8e7e07..5f6c8a2 100644 --- a/artifacts/tc-reference/src/components/library/card-row.tsx +++ b/artifacts/tc-reference/src/components/library/card-row.tsx @@ -9,7 +9,11 @@ import { Target, } from "lucide-react"; import { CORE_CARD_SET, LIBRARY_CATEGORIES } from "@/lib/data"; -import { IMPACT_STYLES, categoryStyleFor } from "@/lib/design-tokens"; +import { + IMPACT_STYLES, + categoryStyleFor, + difficultyLabel, +} from "@/lib/design-tokens"; export type LibraryCardMeta = (typeof LIBRARY_CATEGORIES)[string][number]; @@ -123,15 +127,15 @@ export function LibraryCardRow({ )} - {card.difficulty} + {difficultyLabel(card.difficulty)} + {/* Named in full, so "Medium · Medium impact" never reads as a + repeated word; matches the tags on the card itself. */} - {badge.label} - {/* The visible text is the accessible name (WCAG 2.5.3 - label-in-name); this just says what the badge means. */} - impact + {badge.label} impact diff --git a/artifacts/tc-reference/src/components/library/category-chips.tsx b/artifacts/tc-reference/src/components/library/category-chips.tsx index 6ccf1d7..9fb888b 100644 --- a/artifacts/tc-reference/src/components/library/category-chips.tsx +++ b/artifacts/tc-reference/src/components/library/category-chips.tsx @@ -43,7 +43,8 @@ export function CategoryChips({ value, onChange }: CategoryChipsProps) { selected={value === c.name} dotColor={c.color} count={c.count} - aria-label={`${c.label}, ${c.count} techniques`} + // Starts with the visible "Voice 4" (WCAG 2.5.3 label in name) + aria-label={`${c.short}, ${c.count} techniques`} onClick={() => onChange(value === c.name ? null : c.name)} data-testid={`category-chip-${c.slug}`} > diff --git a/artifacts/tc-reference/src/components/library/filter-sheet.tsx b/artifacts/tc-reference/src/components/library/filter-sheet.tsx index 427d66e..5d46432 100644 --- a/artifacts/tc-reference/src/components/library/filter-sheet.tsx +++ b/artifacts/tc-reference/src/components/library/filter-sheet.tsx @@ -91,7 +91,7 @@ export function LibraryFilterSheet({ return createPortal(

Start from a template

Load a sequence, then reorder or swap cards before you save it. @@ -67,7 +67,7 @@ export function PlaybookTemplateList({ >

{note && (

{note} @@ -92,26 +92,28 @@ export function PlaybookTemplateList({ type="button" onClick={() => onUse(t)} data-testid={`playbook-template-${t.id}`} - aria-label={`Use template: ${t.name}`} className="w-full h-full text-left flex items-start gap-3 rounded-2xl px-4 py-3.5 transition-all active:scale-[0.98] bg-[var(--surface-card)] hover:bg-[var(--surface-card-hover)]" style={{ border: "1px solid var(--fg-07)", boxShadow: "var(--shadow-card)", }} > + {/* Named by its content (title, summary and steps), so + the name holds the visible text (WCAG 2.5.3) */} + Use template:{" "} {t.name} - + {" "} {t.description} - + {" "} ; + /** + * The first listing of this line across every group. The all-cards view + * shows only these, so a stock line shared by several cards appears once. + */ + primary: boolean; + /** Every card, in any group, that lists the line (shared with duplicates). */ + allTextByCard: Record; } interface QuickGroup { @@ -35,6 +45,8 @@ function buildQuickGroups(cards: CardTextIndex): QuickGroup[] { // Many cards share stock lines ("What was that like?"). Keep one row per // line per group and remember every card it came from. const seen = new Map(); + // Across groups too: the all-cards view lists each line once. + const seenAnywhere = new Map>(); for (const [cardId, card] of Object.entries(cards)) { const cardMeta = Object.values(LIBRARY_CATEGORIES) @@ -54,10 +66,21 @@ function buildQuickGroups(cards: CardTextIndex): QuickGroup[] { const targetGroup = groupsMap.get(group.id)!; for (const phraseText of group.phrases) { if (!isSpeakablePhrase(phraseText)) continue; - const key = `${group.id}\u0000${phraseText.trim().toLowerCase()}`; + const lineKey = phraseDedupeKey(phraseText); + let allTextByCard = seenAnywhere.get(lineKey); + const primary = !allTextByCard; + if (!allTextByCard) { + allTextByCard = {}; + seenAnywhere.set(lineKey, allTextByCard); + } + allTextByCard[cardId] ??= phraseText; + const key = `${group.id}\u0000${lineKey}`; const existing = seen.get(key); if (existing) { - if (!existing.cardIds.includes(cardId)) existing.cardIds.push(cardId); + if (!existing.cardIds.includes(cardId)) { + existing.cardIds.push(cardId); + existing.textByCard[cardId] = phraseText; + } continue; } const entry: QuickPhrase = { @@ -65,6 +88,9 @@ function buildQuickGroups(cards: CardTextIndex): QuickGroup[] { cardId, cardTitle: cardMeta.title, cardIds: [cardId], + textByCard: { [cardId]: phraseText }, + primary, + allTextByCard, }; seen.set(key, entry); targetGroup.phrases.push(entry); @@ -176,15 +202,23 @@ function QuickModeContent() { // Attribute to the open card so favourites file under it .map((p) => ({ ...p, + text: p.textByCard[contextCardId] ?? p.text, cardId: contextCardId, cardTitle: CARD_TITLE_MAP_QM[contextCardId], + allTextByCard: { [contextCardId]: p.textByCard[contextCardId] }, })), })) .filter((g) => g.phrases.length > 0) - : (quickGroups ?? []); + : (quickGroups ?? []).filter((g) => g.phrases.length > 0); + // One situation keeps every line it lists (each is unique within a group). + // Across all situations a shared line shows once, under its first group. const filteredGroups = quickFilter ? allQuickGroups.filter((g) => g.id === quickFilter) - : allQuickGroups; + : scopedToCard + ? allQuickGroups + : allQuickGroups + .map((g) => ({ ...g, phrases: g.phrases.filter((p) => p.primary) })) + .filter((g) => g.phrases.length > 0); const totalPhraseCount = filteredGroups.reduce( (count, group) => count + group.phrases.length, 0, @@ -205,7 +239,7 @@ function QuickModeContent() { role="dialog" aria-modal="true" aria-label="Quick Lookup" - className="fixed inset-0 bg-background flex flex-col animate-in slide-in-from-bottom-full duration-300" + className="safe-x fixed inset-0 bg-background flex flex-col animate-in slide-in-from-bottom-full duration-300" style={{ zIndex: "var(--z-overlay)" as unknown as number }} data-testid="quick-mode-overlay" > @@ -400,7 +434,11 @@ function QuickModeContent() { }} > {group.phrases.map((phrase, i) => { - const isFav = isPhrasesFav(phrase.cardId, phrase.text); + // A shared line counts as saved from any card that lists it. + const savedFrom = Object.entries(phrase.allTextByCard).filter( + ([cardId, text]) => isPhrasesFav(cardId, text), + ); + const isFav = savedFrom.length > 0; return (

+ {/* Most people stay on Use it, so the way on to neighbouring + techniques sits here too, not only on Practise it. */} + {available("related") && ( + + )} {prevNext}
)} @@ -297,6 +307,8 @@ export default function CardDetail() { data: CardData | null; } | null>(null); const [loadFailedCardId, setLoadFailedCardId] = useState(null); + // Bumped by "Try again" to rerun the load; the loader drops failed attempts. + const [loadAttempt, setLoadAttempt] = useState(0); // A new card starts a fresh load: clear any earlier failure during render. const [prevCardId, setPrevCardId] = useState(cardId); if (cardId !== prevCardId) { @@ -334,7 +346,7 @@ export default function CardDetail() { return () => { active = false; }; - }, [cardId, isKnownCard, isLoaded]); + }, [cardId, isKnownCard, isLoaded, loadAttempt]); // Prev/next navigation follows LIBRARY_CATEGORIES order const loadedCardIdx = LOADED_CARDS_NAV.findIndex((c) => c.id === cardId); @@ -408,9 +420,13 @@ export default function CardDetail() { aria-busy={loadFailedCardId !== cardId} > {loadFailedCardId === cardId ? ( -

- Card content is unavailable right now. -

+ { + setLoadFailedCardId(null); + setLoadAttempt((n) => n + 1); + }} + /> ) : ( <> {/* Skeleton in the card's own shape so the page doesn't jump */} diff --git a/artifacts/tc-reference/src/pages/drill.tsx b/artifacts/tc-reference/src/pages/drill.tsx index 239dbd3..b606bd3 100644 --- a/artifacts/tc-reference/src/pages/drill.tsx +++ b/artifacts/tc-reference/src/pages/drill.tsx @@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button"; import { Chip } from "@/components/ui/chip"; import { DockBar } from "@/components/ui/dock-bar"; import { DrillDone } from "@/components/drill-done"; +import { DrillProgress } from "@/components/drill-progress"; import { DrillRating } from "@/components/drill-rating"; import { DrillReviewSheet } from "@/components/drill-review-sheet"; import { DrillReviews } from "@/components/drill-reviews"; @@ -52,10 +53,12 @@ import { CORE_TRACK_NAME, DRILL_CARD_META, drillCardTitle, + drillProgress, durationLabel, gapClause, previewGaps, RATING_LABELS, + returnWords, sameTrack, trackName, weekStrip, @@ -108,6 +111,8 @@ export default function Drill() { const [trackSheet, setTrackSheet] = useState<"closed" | "open" | "suggest">( "closed", ); + // The category a progress row asked the track sheet to open on. + const [trackCategory, setTrackCategory] = useState(); const [reviewId, setReviewId] = useState(null); const [announcement, setAnnouncement] = useState(""); @@ -245,6 +250,7 @@ export default function Drill() { setState(next); } setTrackSheet("closed"); + setTrackCategory(undefined); }; const rateReview = (cardId: string, rating: Rating) => { @@ -256,6 +262,18 @@ export default function Drill() { ); }; + const progress = useMemo(() => drillProgress(srsMap), [srsMap]); + const progressSection = ( + { + setTrackCategory(category); + setTrackSheet("open"); + }} + /> + ); + const retryLoad = () => { setLoadFailed(false); setLoadAttempt((n) => n + 1); @@ -301,8 +319,12 @@ export default function Drill() { state={state} dueCount={due.length} suggestCore={trackSheet === "suggest"} + initialCategory={trackCategory} onApply={applyTrack} - onClose={() => setTrackSheet("closed")} + onClose={() => { + setTrackSheet("closed"); + setTrackCategory(undefined); + }} /> )} {reviewId && ( @@ -337,6 +359,9 @@ export default function Drill() { state.cardIndex === 0 && state.prevCardIndex === cardCount - 1; const prevTitle = prevId ? drillCardTitle(prevId) : ""; + // The finished technique's review: its rating and when it comes back. + const prevReview = prevId ? srsMap[prevId] : undefined; + const prevRating = undo?.rating ?? prevReview?.rating; let milestone: ReactNode; if (finishedTrack) { @@ -355,7 +380,11 @@ export default function Drill() { ); } else if (finishedCard && state.pace > 1) { - milestone = `You have finished ${prevTitle}. It will come back for review. Next up: ${nextTitle}.`; + milestone = `You have finished ${prevTitle}. It ${ + prevReview + ? `comes back for review ${returnWords(prevReview.interval)}` + : "will come back for review" + }. Next up: ${nextTitle}.`; } return ( @@ -370,7 +399,13 @@ export default function Drill() { } detail={ prevId - ? `${prevTitle}${undo ? ` · rated ${RATING_LABELS[undo.rating]}` : ""}` + ? [ + prevTitle, + prevRating && `rated ${RATING_LABELS[prevRating]}`, + prevReview && `back ${returnWords(prevReview.interval)}`, + ] + .filter(Boolean) + .join(" · ") : undefined } onUndo={undo ? handleUndo : undefined} @@ -388,6 +423,7 @@ export default function Drill() { > + {progressSection} - -

-
+ + + + + } + > + Tap the heart on any technique or phrase to keep it here for quick + access. + ) : ( <> diff --git a/artifacts/tc-reference/src/pages/help.tsx b/artifacts/tc-reference/src/pages/help.tsx index f285267..61169f9 100644 --- a/artifacts/tc-reference/src/pages/help.tsx +++ b/artifacts/tc-reference/src/pages/help.tsx @@ -3,6 +3,7 @@ import { ArrowLeft, Check, ChevronRight, + Compass, Copy, Search, X, @@ -15,6 +16,7 @@ import { useNav } from "@/lib/nav-context"; import { useCopyFeedback } from "@/hooks/use-copy-feedback"; import { quoted } from "@/lib/utils"; import { buttonClass } from "@/components/ui/button"; +import { EmptyState } from "@/components/ui/empty-state"; // Help me right now: pick what is happening, then get one move, three lines // to say, what to do next and one thing to avoid. Built only from the light @@ -77,7 +79,7 @@ function HelpPicker() {

-

+ See all situations + + } > - Situation not found -

-

That link may be out of date. Pick what is happening from the list. -

+

); } diff --git a/artifacts/tc-reference/src/pages/library.tsx b/artifacts/tc-reference/src/pages/library.tsx index 38bf502..e018892 100644 --- a/artifacts/tc-reference/src/pages/library.tsx +++ b/artifacts/tc-reference/src/pages/library.tsx @@ -500,7 +500,6 @@ export default function Library() {