diff --git a/apps/simplex-badge-service/web/assets/logo-symbol-dark.svg b/apps/simplex-badge-service/web/assets/logo-symbol-dark.svg new file mode 100644 index 0000000000..fa598acf3d --- /dev/null +++ b/apps/simplex-badge-service/web/assets/logo-symbol-dark.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/apps/simplex-badge-service/web/assets/logo-symbol-light.svg b/apps/simplex-badge-service/web/assets/logo-symbol-light.svg new file mode 100644 index 0000000000..d8b5951a0b --- /dev/null +++ b/apps/simplex-badge-service/web/assets/logo-symbol-light.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/apps/simplex-badge-service/web/dist/dev.html b/apps/simplex-badge-service/web/dist/dev.html index 9fa6fbb4eb..c5c2cc8a6f 100644 --- a/apps/simplex-badge-service/web/dist/dev.html +++ b/apps/simplex-badge-service/web/dist/dev.html @@ -23,8 +23,17 @@ -
- +
+ +
+ + +
+
+ +
diff --git a/apps/simplex-badge-service/web/dist/logo-symbol-dark.svg b/apps/simplex-badge-service/web/dist/logo-symbol-dark.svg new file mode 100644 index 0000000000..fa598acf3d --- /dev/null +++ b/apps/simplex-badge-service/web/dist/logo-symbol-dark.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/apps/simplex-badge-service/web/dist/logo-symbol-light.svg b/apps/simplex-badge-service/web/dist/logo-symbol-light.svg new file mode 100644 index 0000000000..d8b5951a0b --- /dev/null +++ b/apps/simplex-badge-service/web/dist/logo-symbol-light.svg @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/apps/simplex-badge-service/web/dist/main.js b/apps/simplex-badge-service/web/dist/main.js index 07da9f6dc5..023e9e136c 100644 --- a/apps/simplex-badge-service/web/dist/main.js +++ b/apps/simplex-badge-service/web/dist/main.js @@ -1,7 +1,21 @@ -// Placeholder entry point; the wizard shell replaces it. -// The relative specifier keeps its ".js" extension into the emitted module: -// tsc does not rewrite specifiers and the browser resolves them itself. -import { renderPlaceholder } from "./ui.js"; +// Entry point. index.html loads this as a module and the browser resolves the +// relative specifiers below itself: tsc does not rewrite them, which is why +// they keep their ".js" extension and why the whole graph is served under one +// prefix (decision 7, D4). +import { startShell } from "./ui.js"; const app = document.getElementById("app"); -if (app) - renderPlaceholder(app); +if (app) { + try { + startShell(app); + } + catch (err) { + // A shell that fails to start must still say so: the alternative is an + // empty page with the reason only in the console (D2). + const banner = document.createElement("p"); + banner.className = "banner"; + banner.setAttribute("role", "alert"); + banner.textContent = "This page failed to load. Please reload, or contact support using the link below."; + app.replaceChildren(banner); + throw err; + } +} diff --git a/apps/simplex-badge-service/web/dist/router.js b/apps/simplex-badge-service/web/dist/router.js new file mode 100644 index 0000000000..122b813466 --- /dev/null +++ b/apps/simplex-badge-service/web/dist/router.js @@ -0,0 +1,40 @@ +// Hash routing for the site wizard: one question per screen, no page reloads. +// +// Everything here is pure — no DOM, no history, no location — so that the +// mapping a browser depends on can be tested with `node --test` (see +// ../test/router.test.mjs). ui.ts owns pushState, popstate and rendering. +/** Every screen the site can show, in wizard order. */ +export const SCREEN_IDS = ["tier", "months", "pay", "checkout", "order", "code"]; +/** Where a visit with no usable hash starts. */ +export const FIRST_SCREEN = "tier"; +const SCREENS = new Set(SCREEN_IDS); +/** + * The screen a location hash names, or null when it names none. + * + * Accepts `#/tier`, `#tier`, and either with a trailing slash, because a hash + * is hand-editable and a URL may be pasted with the slash dropped. Returns + * FIRST_SCREEN for an absent or empty hash. Null is a real answer, not an + * error: the caller decides what an unknown hash does, and ui.ts sends it to + * FIRST_SCREEN rather than leaving a blank page. + */ +export function screenIdForHash(hash) { + const name = hash.replace(/^#/, "").replace(/^\//, "").replace(/\/$/, ""); + if (name === "") + return FIRST_SCREEN; + return SCREENS.has(name) ? name : null; +} +/** The canonical hash for a screen. The inverse of screenIdForHash. */ +export function hashForScreen(id) { + return `#/${id}`; +} +/** + * The screen after this one, or null at the end of the wizard. + * + * `checkout` ends the answered part: `order` and `code` are reached from a + * checkout response (D7, E5, E6), never by advancing. + */ +export function nextScreen(id) { + const wizard = ["tier", "months", "pay", "checkout"]; + const i = wizard.indexOf(id); + return i >= 0 && i + 1 < wizard.length ? wizard[i + 1] : null; +} diff --git a/apps/simplex-badge-service/web/dist/ui.js b/apps/simplex-badge-service/web/dist/ui.js index 3c9a896835..3b5f03b790 100644 --- a/apps/simplex-badge-service/web/dist/ui.js +++ b/apps/simplex-badge-service/web/dist/ui.js @@ -1,6 +1,108 @@ -// Placeholder view layer; the wizard shell replaces it. -export function renderPlaceholder(root) { - const heading = document.createElement("h1"); - heading.textContent = "SimpleX supporter badges"; - root.replaceChildren(heading); +// The wizard shell: the only module that touches the DOM. +// +// One question per screen, hash-routed with no page reload. Forward navigation +// is history.pushState, which does not fire popstate, so the shell renders +// directly; back and forward are history traversals, which do fire it, so the +// listener re-renders from the hash. There is no hashchange listener: every +// hash change originates here. +// +// Everything decidable without a browser lives in router.ts and view.ts. +import { FIRST_SCREEN, hashForScreen, nextScreen, screenIdForHash } from "./router.js"; +import { questionOfScreen, screenView } from "./view.js"; +const CHOOSE_AN_OPTION = "Choose an option to continue."; +// D7 replaces this branch with the POST to /api/checkout. +const PAYMENT_UNAVAILABLE = "Payment is not available yet."; +/** Build elements from a view tree. No innerHTML: text is always a text node. */ +export function toDom(el) { + const node = document.createElement(el.tag); + for (const name of Object.keys(el.attrs)) + node.setAttribute(name, el.attrs[name]); + for (const child of el.children) + node.append(childNode(child)); + return node; +} +function childNode(child) { + return typeof child === "string" ? child : toDom(child); +} +/** Render the screen the current hash names into `root`, and keep it in step with history. */ +export function startShell(root) { + const banner = errorBanner(); + const answers = {}; + let current = FIRST_SCREEN; + const shell = { + showError(message) { + banner.textContent = message; + banner.hidden = false; + }, + go(id) { + history.pushState(null, "", hashForScreen(id)); + render(id, true); + }, + answers() { + return { ...answers }; + }, + }; + function clearError() { + banner.hidden = true; + banner.textContent = ""; + } + function render(id, moveFocus) { + current = id; + clearError(); + const screen = toDom(screenView(id, answers)); + root.replaceChildren(banner, screen); + // The heading is the start of the new screen for a keyboard or screen + // reader user, who would otherwise stay on a button that no longer exists. + const heading = screen.querySelector("h1"); + if (heading) { + heading.setAttribute("tabindex", "-1"); + if (moveFocus) + heading.focus(); + } + } + // An unknown hash renders the first screen rather than nothing, and the + // address bar is corrected in place so that back does not return to it. + function screenFromLocation() { + const id = screenIdForHash(location.hash); + if (id !== null && location.hash === hashForScreen(id)) + return id; + const target = id ?? FIRST_SCREEN; + history.replaceState(null, "", hashForScreen(target)); + return target; + } + function onSubmit(event) { + event.preventDefault(); + const question = questionOfScreen(current); + if (!question) { + // The only other screen with a form is #/checkout, whose Pay button D7 wires. + shell.showError(PAYMENT_UNAVAILABLE); + return; + } + const form = event.target; + if (!(form instanceof HTMLFormElement)) + return; + const chosen = form.querySelector("input[type=radio]:checked"); + if (!chosen) { + shell.showError(CHOOSE_AN_OPTION); + return; + } + answers[question] = chosen.value; + const next = nextScreen(current); + if (next) + shell.go(next); + } + root.addEventListener("submit", onSubmit); + // Choosing an option answers the complaint the banner is showing. + root.addEventListener("change", clearError); + window.addEventListener("popstate", () => render(screenFromLocation(), true)); + render(screenFromLocation(), false); + return shell; +} +function errorBanner() { + const banner = document.createElement("p"); + banner.className = "banner"; + // role=alert so the message is announced when it appears, not only seen. + banner.setAttribute("role", "alert"); + banner.hidden = true; + return banner; } diff --git a/apps/simplex-badge-service/web/dist/view.js b/apps/simplex-badge-service/web/dist/view.js new file mode 100644 index 0000000000..880c36fad7 --- /dev/null +++ b/apps/simplex-badge-service/web/dist/view.js @@ -0,0 +1,132 @@ +// The screens, as pure data. +// +// A screen is described as an element tree and never touches the DOM, so the +// structure a browser will render can be asserted with `node --test` (see +// ../test/static.test.mjs, which counts the

of every screen and checks +// that every radio group is a real fieldset/legend/label). ui.ts turns a tree +// into elements with document.createElement and textContent — there is no +// innerHTML anywhere, so a label that later comes from the catalog (D3) or from +// a query parameter (D5) cannot become markup. +// +// The options here are placeholders. D3 builds the first three screens from the +// catalog payload and replaces them. +/** An element node. An attribute present with an empty value is a boolean attribute. */ +export function h(tag, attrs = {}, children = []) { + return { tag, attrs, children }; +} +const QUESTIONS = { + tier: { + heading: "Choose your level", + legend: "Badge level", + options: [ + { value: "supporter", label: "Supporter", detail: "2 GB files" }, + { value: "legend", label: "Legend", detail: "5 GB files" }, + ], + }, + months: { + heading: "How long?", + legend: "Subscription length", + options: [ + { value: "1", label: "1 month", detail: "Billed once" }, + { value: "3", label: "3 months", detail: "Billed once" }, + { value: "12", label: "12 months", detail: "Billed once" }, + ], + }, + pay: { + heading: "How would you like to pay?", + legend: "Payment method", + options: [ + { value: "card", label: "Card", detail: "Visa, Mastercard and others" }, + { value: "btc", label: "Bitcoin", detail: "On-chain or Lightning" }, + { value: "xmr", label: "Monero", detail: "On-chain" }, + ], + }, +}; +const QUESTION_IDS = new Set(Object.keys(QUESTIONS)); +/** The question a screen asks, or null for a screen that asks none. */ +export function questionOfScreen(id) { + return QUESTION_IDS.has(id) ? id : null; +} +/** The placeholder options of a question screen. D3 replaces this with the catalog. */ +export function optionsOfQuestion(q) { + return QUESTIONS[q].options; +} +/** + * The whole screen, ready to be turned into elements. Exactly one

. + * + * The switch is exhaustive over ScreenId with no default, so adding a screen + * to router.ts fails to compile until this renders it — there is no route the + * shell can reach that renders nothing. + */ +export function screenView(id, answers) { + switch (id) { + case "tier": + case "months": + case "pay": + return questionScreen(id, answers[id]); + case "checkout": + return checkoutScreen(answers); + case "order": + return orderScreen(); + case "code": + return codeScreen(); + } +} +function questionScreen(q, answer) { + const { heading, legend, options } = QUESTIONS[q]; + return section(heading, [ + h("form", { class: "form" }, [ + h("fieldset", { class: "options" }, [h("legend", { class: "options__legend" }, [legend]), ...options.map((o) => optionCard(q, o, answer))]), + submitButton("Continue"), + ]), + ]); +} +function optionCard(group, option, answer) { + const input = { class: "option__input", type: "radio", name: group, value: option.value }; + if (option.value === answer) + input.checked = ""; + if (option.disabled) + input.disabled = ""; + return h("label", { class: "option" }, [ + h("input", input), + h("span", { class: "option__body" }, [ + h("span", { class: "option__label" }, [option.label]), + h("span", { class: "option__detail" }, [option.detail]), + ]), + ]); +} +const NOT_CHOSEN = "Not chosen yet"; +function checkoutScreen(answers) { + return section("Review your order", [ + h("form", { class: "form" }, [ + h("dl", { class: "summary" }, [ + ...summaryRow("Level", labelOf("tier", answers.tier)), + ...summaryRow("Length", labelOf("months", answers.months)), + ...summaryRow("Payment", labelOf("pay", answers.pay)), + ]), + submitButton("Pay"), + ]), + ]); +} +function summaryRow(term, value) { + return [h("dt", { class: "summary__term" }, [term]), h("dd", { class: "summary__value" }, [value])]; +} +function labelOf(q, value) { + if (value === undefined) + return NOT_CHOSEN; + return QUESTIONS[q].options.find((o) => o.value === value)?.label ?? value; +} +// E5 replaces this with the crypto payment screen, E6 with the result screen. +// They exist now so that no path can route to a hash that renders nothing. +function orderScreen() { + return section("Complete your payment", [h("p", { class: "prose" }, ["Payment details will appear here once an order has been created."])]); +} +function codeScreen() { + return section("Your redemption code", [h("p", { class: "prose" }, ["Your code will appear here once a payment has been confirmed."])]); +} +function section(heading, body) { + return h("section", { class: "screen" }, [h("h1", { class: "screen__heading" }, [heading]), ...body]); +} +function submitButton(label) { + return h("button", { class: "button", type: "submit" }, [label]); +} diff --git a/apps/simplex-badge-service/web/index.html b/apps/simplex-badge-service/web/index.html index 34d230cad8..644cdda203 100644 --- a/apps/simplex-badge-service/web/index.html +++ b/apps/simplex-badge-service/web/index.html @@ -22,8 +22,17 @@ -
- +
+ +
+ + +
+
+ +
diff --git a/apps/simplex-badge-service/web/package.json b/apps/simplex-badge-service/web/package.json index 843ad8dcb6..44bb84d45d 100644 --- a/apps/simplex-badge-service/web/package.json +++ b/apps/simplex-badge-service/web/package.json @@ -4,7 +4,8 @@ "private": true, "description": "Checkout site for SimpleX supporter badges, served by simplex-badge-service", "scripts": { - "build": "node build.mjs" + "build": "node build.mjs", + "test": "node --test test/*.test.mjs" }, "devDependencies": { "typescript": "5.9.3" diff --git a/apps/simplex-badge-service/web/src/main.ts b/apps/simplex-badge-service/web/src/main.ts index d1fad003ab..87120841e2 100644 --- a/apps/simplex-badge-service/web/src/main.ts +++ b/apps/simplex-badge-service/web/src/main.ts @@ -1,8 +1,22 @@ -// Placeholder entry point; the wizard shell replaces it. -// The relative specifier keeps its ".js" extension into the emitted module: -// tsc does not rewrite specifiers and the browser resolves them itself. +// Entry point. index.html loads this as a module and the browser resolves the +// relative specifiers below itself: tsc does not rewrite them, which is why +// they keep their ".js" extension and why the whole graph is served under one +// prefix (decision 7, D4). -import {renderPlaceholder} from "./ui.js" +import {startShell} from "./ui.js" const app = document.getElementById("app") -if (app) renderPlaceholder(app) +if (app) { + try { + startShell(app) + } catch (err) { + // A shell that fails to start must still say so: the alternative is an + // empty page with the reason only in the console (D2). + const banner = document.createElement("p") + banner.className = "banner" + banner.setAttribute("role", "alert") + banner.textContent = "This page failed to load. Please reload, or contact support using the link below." + app.replaceChildren(banner) + throw err + } +} diff --git a/apps/simplex-badge-service/web/src/router.ts b/apps/simplex-badge-service/web/src/router.ts new file mode 100644 index 0000000000..d61e5ab408 --- /dev/null +++ b/apps/simplex-badge-service/web/src/router.ts @@ -0,0 +1,47 @@ +// Hash routing for the site wizard: one question per screen, no page reloads. +// +// Everything here is pure — no DOM, no history, no location — so that the +// mapping a browser depends on can be tested with `node --test` (see +// ../test/router.test.mjs). ui.ts owns pushState, popstate and rendering. + +/** Every screen the site can show, in wizard order. */ +export const SCREEN_IDS = ["tier", "months", "pay", "checkout", "order", "code"] as const + +export type ScreenId = (typeof SCREEN_IDS)[number] + +/** Where a visit with no usable hash starts. */ +export const FIRST_SCREEN: ScreenId = "tier" + +const SCREENS: ReadonlySet = new Set(SCREEN_IDS) + +/** + * The screen a location hash names, or null when it names none. + * + * Accepts `#/tier`, `#tier`, and either with a trailing slash, because a hash + * is hand-editable and a URL may be pasted with the slash dropped. Returns + * FIRST_SCREEN for an absent or empty hash. Null is a real answer, not an + * error: the caller decides what an unknown hash does, and ui.ts sends it to + * FIRST_SCREEN rather than leaving a blank page. + */ +export function screenIdForHash(hash: string): ScreenId | null { + const name = hash.replace(/^#/, "").replace(/^\//, "").replace(/\/$/, "") + if (name === "") return FIRST_SCREEN + return SCREENS.has(name) ? (name as ScreenId) : null +} + +/** The canonical hash for a screen. The inverse of screenIdForHash. */ +export function hashForScreen(id: ScreenId): string { + return `#/${id}` +} + +/** + * The screen after this one, or null at the end of the wizard. + * + * `checkout` ends the answered part: `order` and `code` are reached from a + * checkout response (D7, E5, E6), never by advancing. + */ +export function nextScreen(id: ScreenId): ScreenId | null { + const wizard: readonly ScreenId[] = ["tier", "months", "pay", "checkout"] + const i = wizard.indexOf(id) + return i >= 0 && i + 1 < wizard.length ? wizard[i + 1] : null +} diff --git a/apps/simplex-badge-service/web/src/ui.ts b/apps/simplex-badge-service/web/src/ui.ts index 61cd503dec..79b42d8045 100644 --- a/apps/simplex-badge-service/web/src/ui.ts +++ b/apps/simplex-badge-service/web/src/ui.ts @@ -1,7 +1,124 @@ -// Placeholder view layer; the wizard shell replaces it. +// The wizard shell: the only module that touches the DOM. +// +// One question per screen, hash-routed with no page reload. Forward navigation +// is history.pushState, which does not fire popstate, so the shell renders +// directly; back and forward are history traversals, which do fire it, so the +// listener re-renders from the hash. There is no hashchange listener: every +// hash change originates here. +// +// Everything decidable without a browser lives in router.ts and view.ts. -export function renderPlaceholder(root: HTMLElement): void { - const heading = document.createElement("h1") - heading.textContent = "SimpleX supporter badges" - root.replaceChildren(heading) +import {FIRST_SCREEN, hashForScreen, nextScreen, screenIdForHash, type ScreenId} from "./router.js" +import {questionOfScreen, screenView, type Answers, type Child, type El} from "./view.js" + +/** The running shell. D3 fetches the catalog through it; D7 the checkout. */ +export interface Shell { + /** Show the error banner. Nothing on this site fails to a blank screen. */ + showError(message: string): void + /** Navigate to a screen, pushing a history entry. */ + go(id: ScreenId): void + /** The answers gathered so far. */ + answers(): Answers +} + +const CHOOSE_AN_OPTION = "Choose an option to continue." +// D7 replaces this branch with the POST to /api/checkout. +const PAYMENT_UNAVAILABLE = "Payment is not available yet." + +/** Build elements from a view tree. No innerHTML: text is always a text node. */ +export function toDom(el: El): HTMLElement { + const node = document.createElement(el.tag) + for (const name of Object.keys(el.attrs)) node.setAttribute(name, el.attrs[name]) + for (const child of el.children) node.append(childNode(child)) + return node +} + +function childNode(child: Child): HTMLElement | string { + return typeof child === "string" ? child : toDom(child) +} + +/** Render the screen the current hash names into `root`, and keep it in step with history. */ +export function startShell(root: HTMLElement): Shell { + const banner = errorBanner() + const answers: {tier?: string; months?: string; pay?: string} = {} + let current = FIRST_SCREEN + + const shell: Shell = { + showError(message: string): void { + banner.textContent = message + banner.hidden = false + }, + go(id: ScreenId): void { + history.pushState(null, "", hashForScreen(id)) + render(id, true) + }, + answers(): Answers { + return {...answers} + }, + } + + function clearError(): void { + banner.hidden = true + banner.textContent = "" + } + + function render(id: ScreenId, moveFocus: boolean): void { + current = id + clearError() + const screen = toDom(screenView(id, answers)) + root.replaceChildren(banner, screen) + // The heading is the start of the new screen for a keyboard or screen + // reader user, who would otherwise stay on a button that no longer exists. + const heading = screen.querySelector("h1") + if (heading) { + heading.setAttribute("tabindex", "-1") + if (moveFocus) heading.focus() + } + } + + // An unknown hash renders the first screen rather than nothing, and the + // address bar is corrected in place so that back does not return to it. + function screenFromLocation(): ScreenId { + const id = screenIdForHash(location.hash) + if (id !== null && location.hash === hashForScreen(id)) return id + const target = id ?? FIRST_SCREEN + history.replaceState(null, "", hashForScreen(target)) + return target + } + + function onSubmit(event: Event): void { + event.preventDefault() + const question = questionOfScreen(current) + if (!question) { + // The only other screen with a form is #/checkout, whose Pay button D7 wires. + shell.showError(PAYMENT_UNAVAILABLE) + return + } + const form = event.target + if (!(form instanceof HTMLFormElement)) return + const chosen = form.querySelector("input[type=radio]:checked") + if (!chosen) { + shell.showError(CHOOSE_AN_OPTION) + return + } + answers[question] = chosen.value + const next = nextScreen(current) + if (next) shell.go(next) + } + + root.addEventListener("submit", onSubmit) + // Choosing an option answers the complaint the banner is showing. + root.addEventListener("change", clearError) + window.addEventListener("popstate", () => render(screenFromLocation(), true)) + render(screenFromLocation(), false) + return shell +} + +function errorBanner(): HTMLElement { + const banner = document.createElement("p") + banner.className = "banner" + // role=alert so the message is announced when it appears, not only seen. + banner.setAttribute("role", "alert") + banner.hidden = true + return banner } diff --git a/apps/simplex-badge-service/web/src/view.ts b/apps/simplex-badge-service/web/src/view.ts new file mode 100644 index 0000000000..c59bb93921 --- /dev/null +++ b/apps/simplex-badge-service/web/src/view.ts @@ -0,0 +1,179 @@ +// The screens, as pure data. +// +// A screen is described as an element tree and never touches the DOM, so the +// structure a browser will render can be asserted with `node --test` (see +// ../test/static.test.mjs, which counts the

of every screen and checks +// that every radio group is a real fieldset/legend/label). ui.ts turns a tree +// into elements with document.createElement and textContent — there is no +// innerHTML anywhere, so a label that later comes from the catalog (D3) or from +// a query parameter (D5) cannot become markup. +// +// The options here are placeholders. D3 builds the first three screens from the +// catalog payload and replaces them. + +import type {ScreenId} from "./router.js" + +export type Child = El | string + +export interface El { + readonly tag: string + readonly attrs: Readonly> + readonly children: readonly Child[] +} + +/** An element node. An attribute present with an empty value is a boolean attribute. */ +export function h(tag: string, attrs: Record = {}, children: readonly Child[] = []): El { + return {tag, attrs, children} +} + +/** One radio card. `detail` is the secondary line, as on the app's PeriodCard. */ +export interface Option { + readonly value: string + readonly label: string + readonly detail: string + readonly disabled?: boolean +} + +/** The answers gathered so far. D3 replaces the values with catalog identifiers. */ +export interface Answers { + readonly tier?: string + readonly months?: string + readonly pay?: string +} + +/** The radio group name of a question screen, which is also its answer key. */ +export type Question = "tier" | "months" | "pay" + +interface QuestionScreen { + readonly heading: string + readonly legend: string + readonly options: readonly Option[] +} + +const QUESTIONS: Readonly> = { + tier: { + heading: "Choose your level", + legend: "Badge level", + options: [ + {value: "supporter", label: "Supporter", detail: "2 GB files"}, + {value: "legend", label: "Legend", detail: "5 GB files"}, + ], + }, + months: { + heading: "How long?", + legend: "Subscription length", + options: [ + {value: "1", label: "1 month", detail: "Billed once"}, + {value: "3", label: "3 months", detail: "Billed once"}, + {value: "12", label: "12 months", detail: "Billed once"}, + ], + }, + pay: { + heading: "How would you like to pay?", + legend: "Payment method", + options: [ + {value: "card", label: "Card", detail: "Visa, Mastercard and others"}, + {value: "btc", label: "Bitcoin", detail: "On-chain or Lightning"}, + {value: "xmr", label: "Monero", detail: "On-chain"}, + ], + }, +} + +const QUESTION_IDS: ReadonlySet = new Set(Object.keys(QUESTIONS)) + +/** The question a screen asks, or null for a screen that asks none. */ +export function questionOfScreen(id: ScreenId): Question | null { + return QUESTION_IDS.has(id) ? (id as Question) : null +} + +/** The placeholder options of a question screen. D3 replaces this with the catalog. */ +export function optionsOfQuestion(q: Question): readonly Option[] { + return QUESTIONS[q].options +} + +/** + * The whole screen, ready to be turned into elements. Exactly one

. + * + * The switch is exhaustive over ScreenId with no default, so adding a screen + * to router.ts fails to compile until this renders it — there is no route the + * shell can reach that renders nothing. + */ +export function screenView(id: ScreenId, answers: Answers): El { + switch (id) { + case "tier": + case "months": + case "pay": + return questionScreen(id, answers[id]) + case "checkout": + return checkoutScreen(answers) + case "order": + return orderScreen() + case "code": + return codeScreen() + } +} + +function questionScreen(q: Question, answer: string | undefined): El { + const {heading, legend, options} = QUESTIONS[q] + return section(heading, [ + h("form", {class: "form"}, [ + h("fieldset", {class: "options"}, [h("legend", {class: "options__legend"}, [legend]), ...options.map((o) => optionCard(q, o, answer))]), + submitButton("Continue"), + ]), + ]) +} + +function optionCard(group: string, option: Option, answer: string | undefined): El { + const input: Record = {class: "option__input", type: "radio", name: group, value: option.value} + if (option.value === answer) input.checked = "" + if (option.disabled) input.disabled = "" + return h("label", {class: "option"}, [ + h("input", input), + h("span", {class: "option__body"}, [ + h("span", {class: "option__label"}, [option.label]), + h("span", {class: "option__detail"}, [option.detail]), + ]), + ]) +} + +const NOT_CHOSEN = "Not chosen yet" + +function checkoutScreen(answers: Answers): El { + return section("Review your order", [ + h("form", {class: "form"}, [ + h("dl", {class: "summary"}, [ + ...summaryRow("Level", labelOf("tier", answers.tier)), + ...summaryRow("Length", labelOf("months", answers.months)), + ...summaryRow("Payment", labelOf("pay", answers.pay)), + ]), + submitButton("Pay"), + ]), + ]) +} + +function summaryRow(term: string, value: string): readonly El[] { + return [h("dt", {class: "summary__term"}, [term]), h("dd", {class: "summary__value"}, [value])] +} + +function labelOf(q: Question, value: string | undefined): string { + if (value === undefined) return NOT_CHOSEN + return QUESTIONS[q].options.find((o) => o.value === value)?.label ?? value +} + +// E5 replaces this with the crypto payment screen, E6 with the result screen. +// They exist now so that no path can route to a hash that renders nothing. +function orderScreen(): El { + return section("Complete your payment", [h("p", {class: "prose"}, ["Payment details will appear here once an order has been created."])]) +} + +function codeScreen(): El { + return section("Your redemption code", [h("p", {class: "prose"}, ["Your code will appear here once a payment has been confirmed."])]) +} + +function section(heading: string, body: readonly Child[]): El { + return h("section", {class: "screen"}, [h("h1", {class: "screen__heading"}, [heading]), ...body]) +} + +function submitButton(label: string): El { + return h("button", {class: "button", type: "submit"}, [label]) +} diff --git a/apps/simplex-badge-service/web/styles.css b/apps/simplex-badge-service/web/styles.css index 6319261e80..2f6dfa96eb 100644 --- a/apps/simplex-badge-service/web/styles.css +++ b/apps/simplex-badge-service/web/styles.css @@ -1,12 +1,306 @@ -/* Placeholder stylesheet; the design system replaces it. +/* Design system for the supporter-badge checkout site. + Served from web/ rather than from dist/, so that an edit is picked up - without a rebuild when the service runs with [web] web_dir set. */ + without a rebuild when the service runs with [web] web_dir set. + + Two rules bind every edit to this file: + + 1. No double-at token belongs here — the syntax index.html names its assets + with. Only index.html is substituted, so such a token in a CSS rule would + reach the browser as literal text. The two logos are elements in + index.html; this file only chooses which of them is shown. + 2. No cross-origin URL belongs here either. The service sends + Content-Security-Policy: default-src 'self' (D4), so a webfont or a + remote image would be blocked at runtime with nothing to see. The font + stack below is the system one for that reason. + + Every colour is defined on bare :root. The dark block only *redefines* + tokens that already exist: a colour introduced there alone would be + undefined in light mode, which is where most of this site is read, and the + browser would fall back to nothing rather than to an error. */ :root { color-scheme: light dark; + + /* Accent: primary-light and primary-dark from website/tailwind.config.js. */ + --accent: #0053D0; + --accent-hover: #1661D1; + --on-accent: #FFFFFF; + + --bg: #FFFFFF; + --card-bg: #FFFFFF; + --text: #0D0E12; + --text-secondary: #3F484B; + --border: #DFE4EA; + --focus-ring: #0053D0; + + --error-bg: #FDECEC; + --error-text: #8C1C13; + --error-border: #E0A5A0; + + --gutter: 20px; + --radius: 16px; +} + +@media (prefers-color-scheme: dark) { + :root { + --accent: #70F0F9; + --accent-hover: #66D9E2; + --on-accent: #000832; + + --bg: #000832; + /* The app's PeriodCard tints its card in dark mode and leaves it flush + with the page in light mode; these two match that. */ + --card-bg: #071C46; + --text: #FFFFFF; + --text-secondary: #A9BAD4; + --border: #0B2A59; + --focus-ring: #70F0F9; + + --error-bg: #3A1113; + --error-text: #FFB3AD; + --error-border: #7A2B2B; + } + + .logo--light { + display: none; + } + + .logo--dark { + display: block; + } +} + +*, +*::before, +*::after { + box-sizing: border-box; } body { margin: 0; - font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + background: var(--bg); + color: var(--text); + font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 17px; + line-height: 1.5; + /* A long code or address must wrap rather than widen the page: the narrow + layout this site is read on has no horizontal room to give. */ + overflow-wrap: break-word; +} + +img { + max-width: 100%; +} + +/* One centred column, the whole site. */ +.column { + display: flex; + flex-direction: column; + gap: 32px; + width: 100%; + max-width: 560px; + min-height: 100vh; + margin: 0 auto; + padding: 40px var(--gutter) 56px; +} + +.masthead { + display: flex; + justify-content: center; +} + +.logo { + display: block; + width: auto; + height: 34px; +} + +.logo--dark { + display: none; +} + +#app { + display: flex; + flex-direction: column; + gap: 16px; +} + +.screen { + display: flex; + flex-direction: column; + gap: 24px; + animation: screen-fade-in 150ms ease-out; +} + +@keyframes screen-fade-in { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .screen { + animation: none; + } +} + +.screen__heading { + margin: 0; + font-size: 1.625rem; + font-weight: 600; + line-height: 1.25; + text-align: center; +} + +.prose { + margin: 0; + color: var(--text-secondary); +} + +.form { + display: flex; + flex-direction: column; + gap: 24px; + margin: 0; +} + +/* A plain block fieldset: a flex or grid fieldset moves its rendered legend + out of normal flow in some engines, and the legend is a real one here. */ +.options { + margin: 0; + padding: 0; + border: 0; +} + +.options__legend { + margin: 0 0 12px; + padding: 0; + color: var(--text-secondary); + font-size: 0.9375rem; +} + +/* The radio card, following PeriodCard in BadgesPayView.kt: a 2px border that + turns accent when selected. The input stays in the accessibility tree and + in the tab order; only its own rendering is hidden. */ +.option { + display: block; + cursor: pointer; +} + +.option + .option { + margin-top: 12px; +} + +.option__input { + position: absolute; + width: 1px; + height: 1px; + margin: 0; + padding: 0; + border: 0; + overflow: hidden; + white-space: nowrap; + clip-path: inset(50%); +} + +.option__body { + display: flex; + flex-direction: column; + gap: 4px; + padding: 16px 18px; + border: 2px solid var(--border); + border-radius: var(--radius); + background: var(--card-bg); +} + +.option__input:checked + .option__body { + border-color: var(--accent); +} + +.option__input:focus-visible + .option__body { + outline: 2px solid var(--focus-ring); + outline-offset: 2px; +} + +.option__input:disabled + .option__body { + cursor: default; + opacity: 0.5; +} + +.option__label { + font-weight: 600; +} + +.option__detail { + color: var(--text-secondary); + font-size: 0.9375rem; +} + +.option__input:checked + .option__body .option__detail { + color: var(--accent); +} + +.summary { + display: grid; + grid-template-columns: auto 1fr; + gap: 8px 16px; + margin: 0; +} + +.summary__term { + color: var(--text-secondary); +} + +.summary__value { + margin: 0; + text-align: right; +} + +.button { + width: 100%; + padding: 14px 24px; + border: 0; + border-radius: 999px; + background: var(--accent); + color: var(--on-accent); + font: inherit; + font-weight: 600; + cursor: pointer; +} + +.button:hover { + background: var(--accent-hover); +} + +/* Nothing here fails to a blank screen: a failed fetch or an unanswered + question says so in this banner. */ +.banner { + margin: 0; + padding: 12px 16px; + border: 1px solid var(--error-border); + border-radius: 12px; + background: var(--error-bg); + color: var(--error-text); +} + +.footer { + margin-top: auto; + font-size: 0.9375rem; + text-align: center; +} + +.footer a { + color: var(--accent); +} + +/* The only focus styling in this file, and nothing suppresses it: there is no + `outline: none` anywhere here. */ +:focus-visible { + outline: 2px solid var(--focus-ring); + outline-offset: 2px; } diff --git a/apps/simplex-badge-service/web/test/css.mjs b/apps/simplex-badge-service/web/test/css.mjs new file mode 100644 index 0000000000..2978524a12 --- /dev/null +++ b/apps/simplex-badge-service/web/test/css.mjs @@ -0,0 +1,82 @@ +// A very small CSS reader for the assertions in static.test.mjs. +// +// It understands exactly what this stylesheet uses — nested at-rules, rule +// blocks and custom properties — because the alternative is a parser +// dependency and this project is capped at one (decision 7). Anything it +// cannot answer, it answers by throwing rather than by returning nothing: a +// check that silently finds no rules is a check that cannot fail. + +/** The body of the block whose opening brace is at or after `from`. */ +function blockAt(css, from) { + const open = css.indexOf("{", from) + if (open < 0) throw new Error(`no block after offset ${from}`) + let depth = 0 + for (let i = open; i < css.length; i++) { + if (css[i] === "{") depth++ + else if (css[i] === "}" && --depth === 0) return {body: css.slice(open + 1, i), end: i + 1} + } + throw new Error(`unclosed block opened at offset ${open}`) +} + +/** Comments removed, so that prose in them is never mistaken for a declaration. */ +export function stripComments(css) { + return css.replace(/\/\*[\s\S]*?\*\//g, "") +} + +/** + * The body of the at-rule whose prelude contains `prelude`, e.g. + * "prefers-color-scheme: dark". Throws when there is not exactly one. + */ +export function atRule(css, prelude) { + const found = [] + const re = /@media[^{]*/g + for (const m of css.matchAll(re)) { + if (m[0].includes(prelude)) found.push(blockAt(css, m.index).body) + } + if (found.length !== 1) throw new Error(`expected exactly one @media containing "${prelude}", found ${found.length}`) + return found[0] +} + +/** Every at-rule block removed, leaving only top-level rules. */ +export function withoutAtRules(css) { + let out = "" + let i = 0 + while (i < css.length) { + const at = css.indexOf("@", i) + if (at < 0) return out + css.slice(i) + out += css.slice(i, at) + const semi = css.indexOf(";", at) + const brace = css.indexOf("{", at) + // An at-rule with no block (@import, @charset) ends at its semicolon. + if (semi >= 0 && (brace < 0 || semi < brace)) i = semi + 1 + else i = blockAt(css, at).end + } + return out +} + +/** The declarations of every rule whose selector list matches `selector` exactly. */ +export function rules(css, selector) { + const found = [] + let i = 0 + while (i < css.length) { + const open = css.indexOf("{", i) + if (open < 0) break + const sel = css.slice(i, open).trim() + const {body, end} = blockAt(css, open) + if (sel === selector) found.push(body) + i = end + } + return found +} + +/** The custom properties declared by a block, as a Map from name to value. */ +export function customProperties(body) { + const props = new Map() + for (const m of body.matchAll(/(--[\w-]+)\s*:\s*([^;}]+)/g)) props.set(m[1], m[2].trim()) + return props +} + +/** Every custom property referenced through var(), anywhere in the sheet. */ +export function referencedProperties(css) { + return new Set([...css.matchAll(/var\(\s*(--[\w-]+)/g)].map((m) => m[1])) +} diff --git a/apps/simplex-badge-service/web/test/router.test.mjs b/apps/simplex-badge-service/web/test/router.test.mjs new file mode 100644 index 0000000000..25d2648a8d --- /dev/null +++ b/apps/simplex-badge-service/web/test/router.test.mjs @@ -0,0 +1,55 @@ +// Unit tests for the pure routing functions, run against the built modules +// with `npm test` (node's built-in runner — no dependency, decision 7). +// +// These run against dist/, not src/, so they test what a browser is served. +// Run `npm run build` first; `npm test` does not compile. + +import test from "node:test" +import assert from "node:assert/strict" + +import {FIRST_SCREEN, SCREEN_IDS, hashForScreen, nextScreen, screenIdForHash} from "../dist/router.js" + +test("every screen in the plan has a route", () => { + assert.deepEqual([...SCREEN_IDS], ["tier", "months", "pay", "checkout", "order", "code"]) +}) + +test("screenIdForHash resolves the canonical hash of every screen", () => { + for (const id of SCREEN_IDS) { + assert.equal(screenIdForHash(hashForScreen(id)), id, `#/${id} must route to ${id}`) + } +}) + +test("hashForScreen is the inverse of screenIdForHash", () => { + for (const id of SCREEN_IDS) assert.equal(hashForScreen(id), `#/${id}`) +}) + +test("a hand-edited hash is tolerated: no slash, or a trailing one", () => { + assert.equal(screenIdForHash("#tier"), "tier") + assert.equal(screenIdForHash("#/tier/"), "tier") + assert.equal(screenIdForHash("#checkout/"), "checkout") +}) + +test("an absent or empty hash starts the wizard", () => { + assert.equal(screenIdForHash(""), FIRST_SCREEN) + assert.equal(screenIdForHash("#"), FIRST_SCREEN) + assert.equal(screenIdForHash("#/"), FIRST_SCREEN) + assert.equal(FIRST_SCREEN, "tier") +}) + +test("an unknown hash is null, not a screen and not a throw", () => { + for (const hash of ["#/nonsense", "#/TIER", "#/tier/extra", "#//tier", "#/order?id=1"]) { + assert.equal(screenIdForHash(hash), null, `${hash} must not resolve to a screen`) + } +}) + +test("nextScreen walks the wizard and stops at checkout", () => { + assert.equal(nextScreen("tier"), "months") + assert.equal(nextScreen("months"), "pay") + assert.equal(nextScreen("pay"), "checkout") + assert.equal(nextScreen("checkout"), null) +}) + +test("the two screens reached from a checkout response are not advanced into", () => { + assert.equal(nextScreen("order"), null) + assert.equal(nextScreen("code"), null) +}) diff --git a/apps/simplex-badge-service/web/test/static.test.mjs b/apps/simplex-badge-service/web/test/static.test.mjs new file mode 100644 index 0000000000..0b9a600cf0 --- /dev/null +++ b/apps/simplex-badge-service/web/test/static.test.mjs @@ -0,0 +1,306 @@ +// The static half of D2's verification. +// +// There is no browser and no display in this environment, so nothing here +// claims that anything *renders*. What it does assert is every property of the +// built output that a browser would otherwise be the only witness to, and each +// assertion was checked to fail when the thing it names is broken (see the +// D2 report). Run with `npm test` after `npm run build`. +// +// Assertions are against dist/ and against the two files served from web/, +// never against src/: the served bytes are what a browser gets. + +import test from "node:test" +import assert from "node:assert/strict" +import {readFileSync, readdirSync} from "node:fs" +import {fileURLToPath} from "node:url" + +import {SCREEN_IDS} from "../dist/router.js" +import {optionsOfQuestion, questionOfScreen, screenView} from "../dist/view.js" +import {atRule, customProperties, referencedProperties, rules, stripComments, withoutAtRules} from "./css.mjs" + +const read = (rel) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8") + +const cssSource = read("../styles.css") +const css = stripComments(cssSource) +const topLevel = withoutAtRules(css) +const darkBlock = atRule(css, "prefers-color-scheme: dark") +const indexHtml = read("../index.html") +const devHtml = read("../dist/dev.html") +const uiJs = read("../dist/ui.js") + +// Derived, not listed: a screen that view.ts starts calling a question is +// covered by the fieldset and label checks below without editing this file. +const QUESTIONS = SCREEN_IDS.filter((id) => questionOfScreen(id) !== null) +const LOGOS = ["logo-symbol-light.svg", "logo-symbol-dark.svg"] + +// -- colour tokens ---------------------------------------------------------- + +test("every custom property the sheet uses is defined on bare :root", () => { + const rootBlocks = rules(topLevel, ":root") + assert.equal(rootBlocks.length, 1, "expected exactly one top-level :root rule") + const defined = customProperties(rootBlocks[0]) + assert.ok(defined.size > 0, "the :root rule declares no custom properties") + for (const name of referencedProperties(css)) { + assert.ok(defined.has(name), `${name} is used but has no definition on bare :root, so it is undefined in light mode`) + } +}) + +test("the dark block only redefines tokens, and introduces none", () => { + const light = customProperties(rules(topLevel, ":root")[0]) + const darkRoot = rules(darkBlock, ":root") + assert.equal(darkRoot.length, 1, "expected exactly one :root rule inside the dark media query") + const dark = customProperties(darkRoot[0]) + assert.ok(dark.size > 0, "the dark :root rule declares no custom properties") + for (const name of dark.keys()) { + assert.ok(light.has(name), `${name} is defined only in dark mode, so it is undefined in light mode`) + } +}) + +test("no custom property is declared outside a :root rule", () => { + // A token declared on a selector would be scoped to it, and its light and + // dark definitions could then disagree about which elements they reach. + for (const block of [topLevel, darkBlock]) { + let i = 0 + while (i < block.length) { + const open = block.indexOf("{", i) + if (open < 0) break + const selector = block.slice(i, open).trim() + const close = matchingClose(block, open) + if (selector !== ":root") { + const stray = [...customProperties(block.slice(open + 1, close)).keys()] + assert.deepEqual(stray, [], `${selector} declares custom properties: ${stray.join(", ")}`) + } + i = close + 1 + } + } +}) + +function matchingClose(s, open) { + let depth = 0 + for (let i = open; i < s.length; i++) { + if (s[i] === "{") depth++ + else if (s[i] === "}" && --depth === 0) return i + } + throw new Error("unclosed block") +} + +test("the accent is the website's primary colour in both schemes", () => { + const light = customProperties(rules(topLevel, ":root")[0]) + const dark = customProperties(rules(darkBlock, ":root")[0]) + assert.equal(light.get("--accent"), "#0053D0", "light accent must be primary-light from website/tailwind.config.js") + assert.equal(dark.get("--accent"), "#70F0F9", "dark accent must be primary-dark from website/tailwind.config.js") +}) + +// -- what the stylesheet may not contain ------------------------------------ + +test("styles.css carries no @@token@@: it is served verbatim and never substituted", () => { + assert.equal(cssSource.match(/@@[\w.-]+@@/g), null) +}) + +test("styles.css references no external origin: default-src 'self' would block it", () => { + assert.equal(css.match(/[a-z][a-z0-9+.-]*:\/\//gi), null, "an absolute URL in the stylesheet") + assert.equal(css.match(/\burl\(/g), null, "url() would have to resolve to a same-origin asset; none is used") + assert.equal(css.match(/@import/g), null) +}) + +test("the font stack is the system one", () => { + const body = rules(topLevel, "body") + assert.equal(body.length, 1) + assert.match(body[0], /font-family:\s*system-ui/) +}) + +// -- layout, motion, focus -------------------------------------------------- + +test("the column is capped at 560px", () => { + const column = rules(topLevel, ".column") + assert.equal(column.length, 1, "expected exactly one .column rule") + assert.match(column[0], /max-width:\s*560px/) +}) + +test("the screen transition is 150ms and prefers-reduced-motion turns it off", () => { + const screen = rules(topLevel, ".screen") + assert.equal(screen.length, 1, "expected exactly one .screen rule") + assert.match(screen[0], /animation:[^;]*\b150ms\b/, ".screen must carry the 150 ms fade") + const reduced = atRule(css, "prefers-reduced-motion: reduce") + const reducedScreen = rules(reduced, ".screen") + assert.equal(reducedScreen.length, 1, "the reduced-motion block must address .screen") + assert.match(reducedScreen[0], /animation:\s*none/) +}) + +test("a :focus-visible ring exists and nothing suppresses it", () => { + const ring = rules(topLevel, ":focus-visible") + assert.equal(ring.length, 1, "expected a global :focus-visible rule") + assert.match(ring[0], /outline:\s*\d+px\s+solid/) + // Not "no blanket outline:none" but "no outline:none at all" — the weaker + // rule needs a judgement about which selectors count as blanket. + assert.equal(css.match(/outline\s*:\s*none/g), null, "outline: none anywhere would put this ring in doubt") +}) + +test("the selected card gets a 2px accent border, as PeriodCard does", () => { + const body = rules(topLevel, ".option__body") + assert.equal(body.length, 1) + assert.match(body[0], /border:\s*2px\s+solid\s+var\(--border\)/) + const checked = rules(topLevel, ".option__input:checked + .option__body") + assert.equal(checked.length, 1, "expected a rule for the checked card") + assert.match(checked[0], /border-color:\s*var\(--accent\)/) +}) + +test("the focus ring reaches the card, since the radio itself is visually hidden", () => { + const hidden = rules(topLevel, ".option__input") + assert.equal(hidden.length, 1) + assert.doesNotMatch(hidden[0], /display:\s*none/, "display: none would drop the radio out of the tab order") + const focused = rules(topLevel, ".option__input:focus-visible + .option__body") + assert.equal(focused.length, 1, "a hidden radio must show its focus on the card") + assert.match(focused[0], /outline:\s*\d+px\s+solid/) +}) + +// -- the screens ------------------------------------------------------------ + +function walk(node, visit, parents = []) { + visit(node, parents) + const chain = [...parents, node] + for (const child of node.children) if (typeof child !== "string") walk(child, visit, chain) +} + +function findAll(root, tag) { + const found = [] + walk(root, (node, parents) => { + if (node.tag === tag) found.push({node, parents}) + }) + return found +} + +function text(node) { + let out = "" + walk(node, (n) => { + for (const child of n.children) if (typeof child === "string") out += child + }) + return out +} + +test("every screen has exactly one

, and it says something", () => { + for (const id of SCREEN_IDS) { + const headings = findAll(screenView(id, {}), "h1") + assert.equal(headings.length, 1, `screen ${id} must have exactly one

, found ${headings.length}`) + assert.notEqual(text(headings[0].node).trim(), "", `the

of screen ${id} is empty`) + } +}) + +test("every screen renders something under its heading", () => { + for (const id of SCREEN_IDS) { + const view = screenView(id, {}) + assert.ok(view.children.length > 1, `screen ${id} is a bare heading`) + } +}) + +test("the three question screens are the ones the plan names", () => { + // Without this the loops below would pass vacuously if QUESTIONS were empty. + assert.deepEqual(QUESTIONS, ["tier", "months", "pay"]) +}) + +test("each question is a real fieldset with a real legend", () => { + for (const id of QUESTIONS) { + const view = screenView(id, {}) + const fieldsets = findAll(view, "fieldset") + assert.equal(fieldsets.length, 1, `screen ${id} must group its radios in one
`) + const legends = findAll(fieldsets[0].node, "legend") + assert.equal(legends.length, 1, `the
of screen ${id} must have exactly one `) + assert.notEqual(text(legends[0].node).trim(), "", `the of screen ${id} is empty`) + } +}) + +test("every option is a radio inside a label, and every option is offered", () => { + for (const id of QUESTIONS) { + const view = screenView(id, {}) + const radios = findAll(view, "input").filter(({node}) => node.attrs.type === "radio") + const options = optionsOfQuestion(questionOfScreen(id)) + assert.equal(radios.length, options.length, `screen ${id} offers ${options.length} options but renders ${radios.length} radios`) + for (const {node, parents} of radios) { + assert.ok( + parents.some((p) => p.tag === "label"), + `a radio on screen ${id} is not inside a