From e617c9b591ea556998ab3f7d1c6e7f42cd50e08a Mon Sep 17 00:00:00 2001 From: Aqib Nawab Date: Thu, 3 Dec 2026 13:15:20 +0500 Subject: [PATCH] Add eight general-purpose learning blocks as portable canvas renderers New ```canvas renderers any course can use: architecture, chart, guess-reveal, scale-picker, log-explorer, command-explainer, role-play and self-check-cards. Each has a zod schema, cross-checks, pure model functions, a theme-aware component in BeatFrame, a spec and tests. - architecture: a system diagram written as data (parts, arrows, nested groups) with the design lab's icons; tap for details, drag to move, Copy code writes x and y back; left to right, or top to bottom when the panel is narrow. - chart: pie, bar or line, view only or guess then reveal. - Registered in PORTABLE_CANVAS_RENDERERS, InteractiveCanvas (schema and checks before render) and the publish check's renderer list. - docs/interactive-learning-blocks.md and the /zz-learning-blocks dev page; a test keeps every example valid. Co-Authored-By: Claude Opus 5.5 --- docs/interactive-learning-blocks.md | 195 +++++ frontend/src/app/zz-learning-blocks/page.tsx | 171 +++++ frontend/src/shared/mdx/canvas-tags.ts | 8 + .../tests/unit/canvas/architecture.test.ts | 184 +++++ frontend/tests/unit/canvas/chart.test.ts | 244 ++++++ .../unit/canvas/command-explainer.test.ts | 112 +++ .../tests/unit/canvas/guess-reveal.test.ts | 161 ++++ .../unit/canvas/learning-blocks-docs.test.ts | 73 ++ .../tests/unit/canvas/log-explorer.test.ts | 131 ++++ frontend/tests/unit/canvas/role-play.test.ts | 175 +++++ .../tests/unit/canvas/scale-picker.test.ts | 159 ++++ .../unit/canvas/self-check-cards.test.ts | 111 +++ packages/learning-ui/package.json | 18 +- .../src/canvas/InteractiveCanvas.tsx | 72 ++ .../src/canvas/models/architecture.ts | 479 ++++++++++++ .../learning-ui/src/canvas/models/chart.ts | 334 ++++++++ .../src/canvas/models/command-explainer.ts | 126 ++++ .../src/canvas/models/guess-reveal.ts | 211 ++++++ .../src/canvas/models/log-explorer.ts | 172 +++++ .../learning-ui/src/canvas/models/portable.ts | 19 + .../src/canvas/models/role-play.ts | 244 ++++++ .../src/canvas/models/scale-picker.ts | 230 ++++++ .../src/canvas/models/self-check-cards.ts | 106 +++ .../canvas/primitives/architecture.spec.md | 62 ++ .../src/canvas/primitives/architecture.tsx | 337 +++++++++ .../src/canvas/primitives/chart.spec.md | 45 ++ .../src/canvas/primitives/chart.tsx | 711 ++++++++++++++++++ .../primitives/command-explainer.spec.md | 51 ++ .../canvas/primitives/command-explainer.tsx | 193 +++++ .../canvas/primitives/guess-reveal.spec.md | 57 ++ .../src/canvas/primitives/guess-reveal.tsx | 265 +++++++ .../canvas/primitives/log-explorer.spec.md | 54 ++ .../src/canvas/primitives/log-explorer.tsx | 323 ++++++++ .../src/canvas/primitives/role-play.spec.md | 51 ++ .../src/canvas/primitives/role-play.tsx | 307 ++++++++ .../canvas/primitives/scale-picker.spec.md | 61 ++ .../src/canvas/primitives/scale-picker.tsx | 291 +++++++ .../primitives/self-check-cards.spec.md | 43 ++ .../canvas/primitives/self-check-cards.tsx | 181 +++++ server/src/shared/mdx/canvas-tags.ts | 8 + .../tests/unit/shared/mdx/canvas-tags.test.ts | 13 + 41 files changed, 6787 insertions(+), 1 deletion(-) create mode 100644 docs/interactive-learning-blocks.md create mode 100644 frontend/src/app/zz-learning-blocks/page.tsx create mode 100644 frontend/tests/unit/canvas/architecture.test.ts create mode 100644 frontend/tests/unit/canvas/chart.test.ts create mode 100644 frontend/tests/unit/canvas/command-explainer.test.ts create mode 100644 frontend/tests/unit/canvas/guess-reveal.test.ts create mode 100644 frontend/tests/unit/canvas/learning-blocks-docs.test.ts create mode 100644 frontend/tests/unit/canvas/log-explorer.test.ts create mode 100644 frontend/tests/unit/canvas/role-play.test.ts create mode 100644 frontend/tests/unit/canvas/scale-picker.test.ts create mode 100644 frontend/tests/unit/canvas/self-check-cards.test.ts create mode 100644 packages/learning-ui/src/canvas/models/architecture.ts create mode 100644 packages/learning-ui/src/canvas/models/chart.ts create mode 100644 packages/learning-ui/src/canvas/models/command-explainer.ts create mode 100644 packages/learning-ui/src/canvas/models/guess-reveal.ts create mode 100644 packages/learning-ui/src/canvas/models/log-explorer.ts create mode 100644 packages/learning-ui/src/canvas/models/role-play.ts create mode 100644 packages/learning-ui/src/canvas/models/scale-picker.ts create mode 100644 packages/learning-ui/src/canvas/models/self-check-cards.ts create mode 100644 packages/learning-ui/src/canvas/primitives/architecture.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/architecture.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/chart.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/chart.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/command-explainer.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/command-explainer.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/guess-reveal.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/guess-reveal.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/log-explorer.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/log-explorer.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/role-play.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/role-play.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/scale-picker.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/scale-picker.tsx create mode 100644 packages/learning-ui/src/canvas/primitives/self-check-cards.spec.md create mode 100644 packages/learning-ui/src/canvas/primitives/self-check-cards.tsx diff --git a/docs/interactive-learning-blocks.md b/docs/interactive-learning-blocks.md new file mode 100644 index 000000000..56e548ed2 --- /dev/null +++ b/docs/interactive-learning-blocks.md @@ -0,0 +1,195 @@ +# General-purpose learning blocks + +Eight portable canvas renderers that any course can use, from cloud architecture to fitness, sales or finance. Each one is a ```` ```canvas ```` fence in the chapter: plain YAML (or JSON) data, no JSX, no code. The chapter is stored in the database as text, so every block is stored as code, never as a picture. + +Preview them all at `/zz-learning-blocks` (dev page, no login). + +| Renderer | Use it to | Interaction | +| --- | --- | --- | +| `architecture` | Show a system: parts, arrows, networks inside networks | Tap a part for details, drag to move, moving traffic dots | +| `chart` | Show data as a pie, bar or line chart | View only, or guess the hidden values, then reveal | +| `guess-reveal` | Make the learner commit to a number before the answer | Slider, lock, then see the gap | +| `scale-picker` | Teach "how much": tone, effort, detail, risk | Explore each point, then pick the best one for a situation | +| `log-explorer` | Practise finding the cause in a log | Filter by level, search, tap the line, check | +| `command-explainer` | Explain a command part by part | Tap a part, arrow keys, "Explain all" | +| `role-play` | Practise a conversation (customer, manager, patient) | Branching chat, read aloud, answer by voice | +| `self-check-cards` | Recall practice | Flip, "I knew it" or "Not yet", review the misses | + +The step-by-step diagram is not a new renderer: a ```` ```flow ```` fence with a `packet:` line already steps through with Back and Next (see `diagram-components-plan.md`). + +## Rules that apply to every block + +- `title` and `limits` are required. `limits` says what the picture leaves out, in one or two sentences. +- Publishing (`courses:check`) refuses an unknown `renderer` or a missing `title` or `limits`. +- The reader checks the data against the renderer's schema and its cross-checks (for example, "an arrow points to a part that does not exist"). Bad data shows a quiet note instead of a broken block, and the problems are listed in the browser console in development. +- Every block works at 375 px, in light and dark mode, with the keyboard, and with reduced motion. +- A wrong answer is amber, never red. + +## architecture + +AI or an author writes the system as data. The reader lays it out left to right, or top to bottom when the panel is narrow (a phone). + +```canvas +renderer: architecture +title: Web app with a load balancer +limits: One region only. It leaves out DNS, backups and monitoring. +nodes: + - { id: users, type: client, label: Users } + - { id: lb, type: balancer, label: Load balancer, tech: ALB, desc: Spreads requests across the app servers. } + - { id: app1, type: compute, label: App server 1, tech: Node.js } + - { id: app2, type: compute, label: App server 2, tech: Node.js } + - { id: db, type: database, label: Managed database, tech: PostgreSQL } + - { id: mail, type: external, label: Email service } +edges: + - { from: users, to: lb, label: HTTPS } + - { from: lb, to: app1 } + - { from: lb, to: app2 } + - { from: app1, to: db, label: SQL } + - { from: app2, to: db, label: SQL } + - { from: app2, to: mail } +groups: + - { id: private, label: Private subnet, members: [app1, app2] } + - { id: vpc, label: VPC, members: [lb, private, db] } +``` + +- `type`: `client`, `dns`, `cdn`, `firewall`, `limiter`, `balancer`, `gateway`, `compute`, `function`, `worker`, `cache`, `database`, `nosql`, `search`, `queue`, `stream`, `storage`, or `external`. The icons are the design lab's icons, so diagrams and labs match. +- Limits: 2 to 30 parts, up to 60 arrows, up to 12 groups. Names up to 40 characters, arrow labels up to 24. +- Groups can hold groups. A part can be in only one group. +- `x` and `y` (grid units: column and row) fix a part's place. An author can drag parts in the reader, then press "Copy code" to get the same diagram with `x` and `y` filled in. +- Cards grow to fit their names, so text never leaves a card. + +## chart + +```canvas +renderer: chart +title: Online sales catch up +limits: Made-up shop data. One year only. +chart: line # pie | bar | line +mode: guess # view (default) | guess +prefix: "$" +unit: k +categories: [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug] +series: + - { id: online, label: Online, values: [42, 45, 51, 48, 56, 61, 64, 70] } + - { id: store, label: In store, values: [58, 55, 57, 60, 59, 62, 60, 58] } +guess: { series: online, from: 6 } +answerNote: Online kept growing and passed in-store sales in July. +source: Example data +``` + +- Pie: `slices: [{ id, label, value }]` (2 to 6). In guess mode the learner splits 100%. +- Bar: `categories` (2 to 8) and `series` (1 to 3). Line: `categories` (3 to 24) and `series` (1 to 3). +- Guess mode hides values from `guess.from` and asks the learner to set them with sliders or by dragging. `tolerance` sets what counts as close. +- Colours follow a fixed order, there is a legend for 2 or more series, and a hidden table gives the values to screen readers. + +## guess-reveal + +```canvas +renderer: guess-reveal +title: Guess the number +limits: Rounded numbers. A real line rarely reaches its full speed. +questions: + - question: "You download a 1 GB file on a 100 Mbit/s line. How many seconds, at best?" + min: 0 + max: 300 + step: 5 + unit: " s" + answer: 80 + tolerance: 10 + explanation: "1 GB is 8,000 megabits. 8,000 divided by 100 is 80 seconds." + source: Example +``` + +1 to 6 questions. The slider starts at `min`, so the learner has to move it. A single question shows no counter. + +## scale-picker + +```canvas +renderer: scale-picker +title: Message tone +limits: Two situations only. Real readers vary. +ends: [More blunt, More polite] +frame: Your message +keys: { good: Clear ask, weak: Hedging, bad: Harsh } +points: + - { label: Blunt, text: "[[bad:Release is late. Not my problem.]]", result: They feel blamed., mood: bad } + - { label: Direct, text: "It moves to Thursday. [[good:Can you tell the client?]]", result: Fast and clear., mood: good } + - { label: Over-polite, text: "[[weak:So sorry to bother you,]] maybe a delay?", result: They are not sure what to do., mood: weak } +situations: + - { label: To a teammate, prompt: Your teammate needs to know the release is late. How do you say it?, best: [1], why: A teammate wants the facts and the ask. } +``` + +3 to 7 points, 1 to 6 situations. `[[good:...]]`, `[[weak:...]]` and `[[bad:...]]` mark words in an example. `code: true` shows the example in a monospace panel (for commit messages or config). + +## log-explorer + +```canvas +renderer: log-explorer +title: Find the first failure +limits: A real log has thousands of lines. +lines: + - { id: l1, time: "14:09:41", level: info, source: deploy, text: checkout v2.3 rolled out } + - { id: l2, time: "14:09:58", level: error, source: checkout, text: "db pool exhausted: 20 of 20 in use" } + - { id: l3, time: "14:10:02", level: error, source: web, text: POST /checkout 500 5012ms } +question: { prompt: Which line shows the real cause?, answer: [l2], why: The pool ran out first. The 500s come after it. } +``` + +3 to 80 lines; `level` is `debug`, `info`, `warn` or `error`; 1 to 3 answer lines. + +## command-explainer + +```canvas +renderer: command-explainer +title: Read a copy command +limits: Only the common flags. +prompt: "$" +parts: + - { text: cp, kind: command, explain: Copy files. } + - { text: "-r", kind: flag, explain: Copy folders and everything inside them. } + - { text: notes/, kind: path, explain: The folder to copy. } +``` + +`kind`: `command`, `flag`, `argument`, `pipe`, `path` or `other`. `tight: true` joins a part to the one before it with no space. `examples` adds more commands behind a switcher; `output` shows sample output. + +## role-play + +```canvas +renderer: role-play +title: Calm an upset customer +limits: A real customer does not pick from three lines. +character: { name: Sara Khan, role: Customer } +learnerRole: You, the support agent +goal: Keep Sara as a customer. +start: open +nodes: + open: + says: My order is two weeks late. + choices: + - { text: I am sorry. Let me check it now., next: happy, tone: good, feedback: You own the problem. } + - { text: Delays happen., next: lost, tone: weak, feedback: This brushes her off. } + happy: { says: Thank you., ending: { verdict: Customer kept, tone: good, summary: You said sorry, then acted. } } + lost: { says: I want to cancel., ending: { verdict: Customer lost, tone: warn, summary: She felt ignored. } } +``` + +2 to 30 nodes. A node has 2 to 4 `choices` or an `ending`. The check refuses unknown `next` ids, unreachable nodes and dead ends. "Read aloud" uses the browser's speech; "Answer by voice" uses speech recognition and picks the closest reply by word overlap. Both appear only in browsers that support them. No AI call is made. + +## self-check-cards + +```canvas +renderer: self-check-cards +title: HTTP status codes +limits: Recall on a card is not the same as using it at work. +deckLabel: Status codes +cards: + - { id: "200", front: What does 200 mean?, back: OK. The request worked. } + - { id: "404", front: What does 404 mean?, back: Not found., hint: The page is missing. } +``` + +2 to 20 cards. At the end the learner can review only the "Not yet" cards. + +## Where the code is + +- Model (schema, checks, pure functions): `packages/learning-ui/src/canvas/models/.ts` +- Component: `packages/learning-ui/src/canvas/primitives/.tsx`, with a spec next to it (`.spec.md`) +- Tests: `frontend/tests/unit/canvas/.test.ts` +- Registration: `PORTABLE_CANVAS_RENDERERS` in `models/portable.ts`, the switch in `canvas/InteractiveCanvas.tsx`, and `PORTABLE_CANVAS_RENDERER_NAMES` in `server/src/shared/mdx/canvas-tags.ts` (run `pnpm sync-shared` in `server/`). diff --git a/frontend/src/app/zz-learning-blocks/page.tsx b/frontend/src/app/zz-learning-blocks/page.tsx new file mode 100644 index 000000000..885d3a1d2 --- /dev/null +++ b/frontend/src/app/zz-learning-blocks/page.tsx @@ -0,0 +1,171 @@ +import { ChapterMdx } from "@/mdx/compile"; + +// Dev-only specimen sheet of the general-purpose canvas renderers, like +// /zz-diagram-gallery. Public, no auth, no data. Each example is a ```canvas +// fence that goes through the real chapter pipeline (transformVisualFences, +// then ). See docs/interactive-learning-blocks.md. + +const T = "```"; + +const SOURCE = `## Architecture + +${T}canvas +renderer: architecture +title: Web app with a load balancer +limits: One region only. It leaves out DNS, backups and monitoring. +nodes: + - { id: users, type: client, label: Users } + - { id: cdn, type: cdn, label: CDN, tech: CloudFront, desc: Serves images and scripts from a server near the user. } + - { id: lb, type: balancer, label: Load balancer, tech: ALB, desc: Spreads requests across the app servers and skips one that is down. } + - { id: app1, type: compute, label: App server 1, tech: Node.js } + - { id: app2, type: compute, label: App server 2, tech: Node.js } + - { id: cache, type: cache, label: Cache, tech: Redis } + - { id: db, type: database, label: Managed database, tech: PostgreSQL, desc: Keeps users and orders. One writer, daily backups. } + - { id: mail, type: external, label: Email service } +edges: + - { from: users, to: cdn, label: HTTPS } + - { from: cdn, to: lb, label: cache miss } + - { from: lb, to: app1 } + - { from: lb, to: app2 } + - { from: app1, to: cache } + - { from: app2, to: cache } + - { from: app1, to: db, label: SQL } + - { from: app2, to: db, label: SQL } + - { from: app2, to: mail } +groups: + - { id: private, label: Private subnet, members: [app1, app2] } + - { id: data, label: Data subnet, members: [cache, db] } + - { id: vpc, label: VPC 10.0.0.0/16, members: [lb, private, data] } +${T} + +## Chart + +${T}canvas +renderer: chart +title: Online sales catch up +limits: Made-up shop data. One year only. +chart: line +mode: guess +prefix: "$" +unit: k +categories: [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug] +series: + - { id: online, label: Online, values: [42, 45, 51, 48, 56, 61, 64, 70] } + - { id: store, label: In store, values: [58, 55, 57, 60, 59, 62, 60, 58] } +guess: { series: online, from: 6 } +answerNote: Online kept growing and passed in-store sales in July. +source: Example data +${T} + +${T}canvas +renderer: chart +title: Where the monthly budget goes +limits: One example budget. Your split depends on where you live. +chart: pie +unit: "%" +slices: + - { id: needs, label: Needs, value: 50 } + - { id: wants, label: Wants, value: 30 } + - { id: save, label: Savings, value: 20 } +${T} + +## Guess, then reveal + +${T}canvas +renderer: guess-reveal +title: Guess the number +limits: Rounded numbers. A real line rarely reaches its full speed. +questions: + - { question: "You download a 1 GB file on a 100 Mbit/s line. How many seconds, at best?", min: 0, max: 300, step: 5, unit: " s", answer: 80, tolerance: 10, explanation: "1 GB is 8,000 megabits. 8,000 divided by 100 is 80 seconds." } +${T} + +## Scale picker + +${T}canvas +renderer: scale-picker +title: Message tone +limits: Two situations only. Real readers vary. +ends: [More blunt, More polite] +frame: Your message +keys: { good: Clear ask, weak: Hedging, bad: Harsh } +points: + - { label: Blunt, text: "[[bad:Release is late. Not my problem.]]", result: They feel blamed., mood: bad } + - { label: Direct, text: "It moves to Thursday. [[good:Can you tell the client?]]", result: Fast and clear., mood: good } + - { label: Over-polite, text: "[[weak:So sorry to bother you,]] maybe a delay?", result: They are not sure what to do., mood: weak } +situations: + - { label: To a teammate, prompt: Your teammate needs to know the release is late. How do you say it?, best: [1], why: A teammate wants the facts and the ask. } +${T} + +## Log explorer + +${T}canvas +renderer: log-explorer +title: Find the first failure +limits: A real log has thousands of lines. +lines: + - {id: l1, time: "14:09:41", level: info, source: deploy, text: checkout v2.3 rolled out} + - {id: l2, time: "14:09:50", level: debug, source: checkout, text: pool size 20} + - {id: l3, time: "14:09:58", level: error, source: checkout, text: "db pool exhausted: 20 of 20 in use"} + - {id: l4, time: "14:10:02", level: error, source: web, text: POST /checkout 500 5012ms} + - {id: l5, time: "14:10:03", level: warn, source: web, text: retrying request} +question: {prompt: Which line shows the real cause?, answer: [l3], why: The pool ran out first. The 500 errors come after it.} +${T} + +## Command explainer + +${T}canvas +renderer: command-explainer +title: Read a copy command +limits: Only the common flags. +prompt: "$" +parts: + - {text: cp, kind: command, explain: Copy files.} + - {text: "-r", kind: flag, explain: Copy folders and everything inside them.} + - {text: notes/, kind: path, explain: The folder to copy.} + - {text: backup/, kind: path, explain: Where the copy goes.} +${T} + +## Role-play + +${T}canvas +renderer: role-play +title: Calm an upset customer +limits: A real customer does not pick from three lines. +character: { name: Sara Khan, role: Customer } +learnerRole: You, the support agent +goal: Keep Sara as a customer. +start: open +nodes: + open: + says: My order is two weeks late. + choices: + - { text: I am sorry. Let me check it now., next: happy, tone: good, feedback: You own the problem. } + - { text: Delays happen., next: lost, tone: weak, feedback: This brushes her off. } + happy: { says: Thank you., ending: { verdict: Customer kept, tone: good, summary: You said sorry, then acted. } } + lost: { says: I want to cancel., ending: { verdict: Customer lost, tone: warn, summary: She felt ignored. } } +${T} + +## Self-check cards + +${T}canvas +renderer: self-check-cards +title: HTTP status codes +limits: Recall on a card is not the same as using it at work. +deckLabel: Status codes +cards: + - { id: "200", front: What does 200 mean?, back: OK. The request worked. } + - { id: "404", front: What does 404 mean?, back: Not found., hint: The page is missing. } + - { id: "500", front: What does 500 mean?, back: Server error. The server failed. } +${T} +`; + +export default function LearningBlocksGalleryPage() { + return ( +
+

General learning blocks

+
+ +
+
+ ); +} diff --git a/frontend/src/shared/mdx/canvas-tags.ts b/frontend/src/shared/mdx/canvas-tags.ts index 422e902b9..20012d9c4 100644 --- a/frontend/src/shared/mdx/canvas-tags.ts +++ b/frontend/src/shared/mdx/canvas-tags.ts @@ -29,6 +29,14 @@ export const PORTABLE_CANVAS_RENDERER_NAMES = [ "phrase-fixer", "budget-stack", "slot-card", + "chart", + "scale-picker", + "guess-reveal", + "log-explorer", + "command-explainer", + "role-play", + "self-check-cards", + "architecture", ] as const; export function isPortableCanvasRendererName(value: unknown): boolean { diff --git a/frontend/tests/unit/canvas/architecture.test.ts b/frontend/tests/unit/canvas/architecture.test.ts new file mode 100644 index 000000000..cdc3d80b4 --- /dev/null +++ b/frontend/tests/unit/canvas/architecture.test.ts @@ -0,0 +1,184 @@ +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + architectureDataSchema, + architectureToCode, + checkArchitecture, + connectionsOf, + describeArchitecture, + gridPositions, + layoutArchitecture, + nodeWidth, + toGrid, + withPositions, + type ArchitectureData, +} from "@buildment/learning-ui/canvas/models/architecture"; +import { Architecture } from "@buildment/learning-ui/canvas/primitives/architecture"; + +const raw = { + title: "Web app with a load balancer", + limits: "One region only. It leaves out DNS, backups and monitoring.", + nodes: [ + { id: "users", type: "client", label: "Users" }, + { id: "cdn", type: "cdn", label: "CDN", tech: "CloudFront", desc: "Serves images and scripts from near the user." }, + { id: "lb", type: "balancer", label: "Load balancer", tech: "ALB" }, + { id: "app1", type: "compute", label: "App server 1", tech: "Node.js" }, + { id: "app2", type: "compute", label: "App server 2", tech: "Node.js" }, + { id: "db", type: "database", label: "Managed database", tech: "PostgreSQL" }, + { id: "mail", type: "external", label: "Email service" }, + ], + edges: [ + { from: "users", to: "cdn", label: "HTTPS" }, + { from: "cdn", to: "lb", label: "cache miss" }, + { from: "lb", to: "app1" }, + { from: "lb", to: "app2" }, + { from: "app1", to: "db", label: "SQL" }, + { from: "app2", to: "db", label: "SQL" }, + { from: "app1", to: "mail" }, + ], + groups: [ + { id: "private", label: "Private subnet", members: ["app1", "app2"] }, + { id: "vpc", label: "VPC 10.0.0.0/16", members: ["lb", "private", "db"] }, + ], +}; + +const data: ArchitectureData = architectureDataSchema.parse(raw); + +describe("architecture canvas model", () => { + it("parses good data and fills defaults", () => { + expect(data.flow).toBe(true); + expect(data.purpose).toBe(""); + expect(checkArchitecture(data)).toEqual([]); + }); + + it("rejects unknown part types, bad ids and too few parts", () => { + expect(architectureDataSchema.safeParse({ ...raw, nodes: [{ id: "a", type: "spaceship", label: "A" }, raw.nodes[1]] }).success).toBe(false); + expect(architectureDataSchema.safeParse({ ...raw, nodes: [{ id: "has space", type: "cdn", label: "A" }, raw.nodes[1]] }).success).toBe(false); + expect(architectureDataSchema.safeParse({ ...raw, nodes: [raw.nodes[0]] }).success).toBe(false); + }); + + it("finds arrows and groups that point at parts that do not exist", () => { + const problems = checkArchitecture({ + nodes: data.nodes, + edges: [...data.edges, { from: "app1", to: "pgx" }, { from: "db", to: "db" }], + groups: [...data.groups, { id: "extra", label: "Extra", members: ["ghost", "app1"] }, { id: "db", label: "Clash", members: ["users"] }], + }); + expect(problems.some((p) => p.includes('points to "pgx"'))).toBe(true); + expect(problems.some((p) => p.includes("to itself"))).toBe(true); + expect(problems.some((p) => p.includes('lists "ghost"'))).toBe(true); + expect(problems.some((p) => p.includes('"app1" is in two groups'))).toBe(true); + expect(problems.some((p) => p.includes('The id "db" is used twice'))).toBe(true); + }); + + it("finds duplicate ids, half positions and groups inside themselves", () => { + const problems = checkArchitecture({ + nodes: [...data.nodes, { id: "lb", type: "balancer", label: "Again" }, { id: "half", type: "cdn", label: "Half", x: 1 }], + edges: [], + groups: [ + { id: "a", label: "A", members: ["b"] }, + { id: "b", label: "B", members: ["a"] }, + ], + }); + expect(problems.some((p) => p.includes('"lb" is used by two parts'))).toBe(true); + expect(problems.some((p) => p.includes('"half" has only one of x and y'))).toBe(true); + expect(problems.some((p) => p.includes("inside itself"))).toBe(true); + }); + + it("puts parts in columns that follow the arrows and centres each column", () => { + const pos = gridPositions(data); + expect(pos.users[0]).toBe(0); + expect(pos.cdn[0]).toBe(1); + expect(pos.lb[0]).toBe(2); + expect(pos.app1[0]).toBe(3); + expect(pos.db[0]).toBe(4); + // Two app servers share a column, one above the other. + expect(Math.abs(pos.app1[1] - pos.app2[1])).toBe(1); + }); + + it("lets fixed x and y and dragged positions win over the automatic layout", () => { + const fixed = { ...data, nodes: data.nodes.map((n) => (n.id === "db" ? { ...n, x: 9, y: 2 } : n)) }; + expect(gridPositions(fixed).db).toEqual([9, 2]); + expect(gridPositions(fixed, { db: [1.5, 0.5] }).db).toEqual([1.5, 0.5]); + }); + + it("does not loop forever on a cycle", () => { + const loop = { nodes: data.nodes.slice(0, 3), edges: [{ from: "users", to: "cdn" }, { from: "cdn", to: "lb" }, { from: "lb", to: "users" }], groups: [] }; + const pos = gridPositions(loop); + expect(Object.keys(pos)).toHaveLength(3); + }); + + it("makes cards wide enough for long names", () => { + expect(nodeWidth({ label: "Managed database", tech: "PostgreSQL" })).toBeGreaterThan(nodeWidth({ label: "DB" })); + expect(nodeWidth({ label: "DB" })).toBe(150); + }); + + it("lays out groups around their members, outer groups first, and draws one path per arrow", () => { + const layout = layoutArchitecture(data); + expect(layout.edges).toHaveLength(data.edges.length); + expect(layout.groups.map((g) => g.group.id)).toEqual(["vpc", "private"]); + const vpc = layout.groups[0]; + const lb = layout.nodes.lb; + expect(vpc.x).toBeLessThan(lb.x); + expect(vpc.x + vpc.w).toBeGreaterThan(layout.nodes.db.x + layout.nodes.db.w); + for (const n of Object.values(layout.nodes)) { + expect(n.x).toBeGreaterThanOrEqual(layout.viewBox.x); + expect(n.x + n.w).toBeLessThanOrEqual(layout.viewBox.x + layout.viewBox.w); + } + expect(layout.edges[0].d.startsWith("M")).toBe(true); + }); + + it("turns columns into rows for a phone and stays narrower than the wide layout", () => { + const wide = layoutArchitecture(data); + const tall = layoutArchitecture(data, {}, "down"); + expect(tall.direction).toBe("down"); + expect(tall.nodes.users.y).toBeLessThan(tall.nodes.cdn.y); + expect(tall.nodes.cdn.y).toBeLessThan(tall.nodes.lb.y); + expect(tall.nodes.app1.y).toBe(tall.nodes.app2.y); + expect(tall.viewBox.w).toBeLessThan(wide.viewBox.w); + // Packed cards in one row never overlap. + expect(tall.nodes.app1.x + tall.nodes.app1.w).toBeLessThan(tall.nodes.app2.x); + }); + + it("keeps a part that is outside a group clear of that group's border on a phone", () => { + const tall = layoutArchitecture(data, {}, "down"); + const vpc = tall.groups.find((g) => g.group.id === "vpc")!; + const mail = tall.nodes.mail; + expect(mail.x >= vpc.x + vpc.w || mail.x + mail.w <= vpc.x).toBe(true); + }); + + it("maps pixels back to grid units in both directions", () => { + const wide = layoutArchitecture(data); + const tall = layoutArchitecture(data, {}, "down"); + expect(toGrid(wide, 2 * wide.colStep, 3 * wide.rowStep)).toEqual([2, 3]); + expect(toGrid(tall, 3 * tall.colStep, 2 * tall.rowStep)).toEqual([2, 3]); + }); + + it("describes connections and the whole diagram in words", () => { + expect(connectionsOf(data, "lb")).toEqual({ from: ["CDN (cache miss)"], to: ["App server 1", "App server 2"] }); + const text = describeArchitecture(data); + expect(text).toContain("Users sends to CDN: HTTPS."); + expect(text).toContain("Private subnet contains App server 1, App server 2."); + }); + + it("writes dragged positions back into the code", () => { + const moved = withPositions(data, { db: [5.25, 1] }); + expect(moved.nodes.find((n) => n.id === "db")).toMatchObject({ x: 5.25, y: 1 }); + expect(moved.nodes.every((n) => typeof n.x === "number")).toBe(true); + const code = JSON.parse(architectureToCode(moved)); + expect(code.renderer).toBe("architecture"); + expect(architectureDataSchema.safeParse(code).success).toBe(true); + expect(withPositions(data, {})).toBe(data); + }); +}); + +describe("architecture canvas component", () => { + it("renders every part, label and group on the server", () => { + const html = renderToString(createElement(Architecture, data)); + expect(html).toContain("Managed database"); + expect(html).toContain("VPC 10.0.0.0/16"); + expect(html).toContain("cache miss"); + expect(html).toContain("Show traffic"); + expect(html).toContain('role="img"'); + }); +}); diff --git a/frontend/tests/unit/canvas/chart.test.ts b/frontend/tests/unit/canvas/chart.test.ts new file mode 100644 index 000000000..f29ab1ac6 --- /dev/null +++ b/frontend/tests/unit/canvas/chart.test.ts @@ -0,0 +1,244 @@ +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + canReveal, + chartDataSchema, + checkChart, + formatValue, + guessRange, + guessTargets, + legendLayout, + niceScale, + niceStep, + pieShares, + revealGuess, + roundTo, + scoreGuess, + setGuess, + startGuess, + valueAtY, + verdictText, + xLabelEvery, + type ChartData, +} from "@buildment/learning-ui/canvas/models/chart"; +import { Chart } from "@buildment/learning-ui/canvas/primitives/chart"; + +const base = { title: "A chart", limits: "Made-up numbers." }; + +const pie = (extra: Record = {}): ChartData => + chartDataSchema.parse({ + ...base, + chart: "pie", + slices: [ + { id: "needs", label: "Needs", value: 50 }, + { id: "wants", label: "Wants", value: 30 }, + { id: "save", label: "Savings", value: 20 }, + ], + ...extra, + }); + +const bar = (extra: Record = {}): ChartData => + chartDataSchema.parse({ + ...base, + chart: "bar", + unit: "%", + categories: ["Labs", "Videos", "Reading", "Quizzes"], + series: [{ id: "share", label: "Share", values: [41, 24, 15, 13] }], + ...extra, + }); + +const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug"]; +const line = (extra: Record = {}): ChartData => + chartDataSchema.parse({ + ...base, + chart: "line", + prefix: "$", + unit: "k", + categories: months, + series: [ + { id: "online", label: "Online", values: [42, 45, 51, 48, 56, 61, 64, 70] }, + { id: "store", label: "In store", values: [58, 55, 57, 60, 59, 62, 60, 58] }, + ], + ...extra, + }); + +describe("chart schema", () => { + it("parses good data and fills defaults", () => { + const d = pie(); + expect(d.mode).toBe("view"); + expect(d.purpose).toBe(""); + expect(d.prefix).toBe(""); + expect(bar().chart).toBe("bar"); + expect(line({ mode: "guess", guess: { series: "online", from: 5 } }).guess?.from).toBe(5); + }); + + it("keeps unknown keys (passthrough)", () => { + expect((pie({ layout: "wide" }) as Record).layout).toBe("wide"); + }); + + it("rejects bad shapes and bad cross-field data", () => { + expect(chartDataSchema.safeParse({ ...base, chart: "donut" }).success).toBe(false); + expect(chartDataSchema.safeParse({ ...base, chart: "pie", slices: [{ id: "a", label: "A", value: 1 }] }).success).toBe(false); + expect(chartDataSchema.safeParse({ ...base, limits: "", chart: "pie" }).success).toBe(false); + const mismatch = chartDataSchema.safeParse({ ...base, chart: "bar", categories: ["A", "B"], series: [{ id: "s", label: "S", values: [1] }] }); + expect(mismatch.success).toBe(false); + if (!mismatch.success) expect(mismatch.error.issues.map((i) => i.message).join("\n")).toContain("series s: 1 values, need one per category (2)"); + }); +}); + +describe("checkChart", () => { + it("is empty for good data", () => { + expect(checkChart(pie())).toEqual([]); + expect(checkChart(bar({ mode: "guess", guess: { from: 2 } }))).toEqual([]); + expect(checkChart(line({ mode: "guess", guess: { series: "store", from: 4 } }))).toEqual([]); + }); + + it("flags duplicate ids, unknown series, missing guess and bad ranges", () => { + const d = line(); + const problems = checkChart({ + ...d, + mode: "guess", + series: [d.series![0], { ...d.series![1], id: "online" }], + guess: { series: "nope", from: 0 }, + yMax: 50, + }).join("\n"); + expect(problems).toContain("series online: duplicate id"); + expect(problems).toContain("guess.series nope: unknown series"); + expect(problems).toContain("guess.from 0: need 1 to 7"); + expect(problems).toContain("yMax 50 is below the largest value 70"); + expect(checkChart({ ...d, mode: "guess", guess: undefined })).toContain("guess mode needs guess: { series, from }"); + }); + + it("flags counts and mixed shapes", () => { + const p = pie(); + expect(checkChart({ ...p, slices: [...p.slices!, { id: "needs", label: "Again", value: 1 }] })).toContain("slice needs: duplicate id"); + expect(checkChart({ ...p, categories: ["A", "B"] })).toContain("a pie uses slices, not series or categories"); + const b = bar(); + const nine = Array.from({ length: 9 }, (_, i) => `C${i}`); + expect(checkChart({ ...b, categories: nine, series: [{ id: "s", label: "S", values: nine.map(() => 1) }] })).toContain("9 categories, need 2 to 8 for a bar chart"); + const many = Array.from({ length: 20 }, (_, i) => `M${i}`); + expect(checkChart({ ...line(), categories: many, series: [{ id: "s", label: "S", values: many.map(() => 1) }], mode: "guess", guess: { from: 2 } })).toContain( + "guess.from leaves 18 points to guess, at most 12", + ); + }); +}); + +describe("chart numbers", () => { + it("splits pie values into whole percents that add to 100", () => { + expect(pieShares([50, 30, 20])).toEqual([50, 30, 20]); + expect(pieShares([1, 1, 1])).toEqual([34, 33, 33]); + expect(pieShares([3, 1]).reduce((a, b) => a + b, 0)).toBe(100); + expect(pieShares([0, 0])).toEqual([0, 0]); + }); + + it("picks round steps and scales", () => { + expect(niceStep(17)).toBe(20); + expect(niceStep(0.03)).toBe(0.05); + expect(niceScale(70)).toEqual({ max: 80, step: 20, ticks: [0, 20, 40, 60, 80] }); + expect(niceScale(70, 120).ticks).toEqual([0, 50, 100]); + expect(roundTo(0.1 + 0.2, 0.01)).toBe(0.3); + expect(valueAtY(50, 0, 100, 80, 1)).toBe(40); + expect(valueAtY(-20, 0, 100, 80, 1)).toBe(80); + }); + + it("formats values and lays out legends and labels", () => { + expect(formatValue(1200, "$", "k")).toBe("$1,200k"); + expect(formatValue(3.456, "", " kg")).toBe("3.46 kg"); + const rows = legendLayout( + [ + { label: "A long series name", key: "a" }, + { label: "Another long name here", key: "b" }, + { label: "Third", key: "c" }, + ], + 0, + 260, + ); + expect(rows.map((r) => r.row)).toEqual([0, 1, 1]); + expect(xLabelEvery(months, 360)).toBe(1); + expect(xLabelEvery(Array.from({ length: 24 }, (_, i) => `Week ${i}`), 360)).toBeGreaterThan(1); + }); +}); + +describe("chart guessing", () => { + it("has no targets in view mode", () => { + expect(guessTargets(bar())).toEqual([]); + }); + + it("pie: starts even, reveals only at 100, scores in points", () => { + const d = pie({ mode: "guess" }); + let s = startGuess(d); + expect(s.values).toEqual([34, 33, 33]); + expect(canReveal(d, s)).toBe(true); + s = setGuess(s, d, 0, 40); + expect(canReveal(d, s)).toBe(false); + expect(revealGuess(d, s)).toBe(s); + s = setGuess(setGuess(s, d, 1, 30), d, 2, 30); + s = revealGuess(d, s); + expect(s.revealed).toBe(true); + expect(setGuess(s, d, 0, 10)).toBe(s); + const score = scoreGuess(d, s.values); + expect(score.offs).toEqual([-10, 0, 10]); + expect(score.mean).toBe(6.7); + expect(score.close).toBe(false); + expect(verdictText(d, score)).toBe("Not quite: off by 6.7 points on average"); + expect(verdictText(d, scoreGuess(d, [50, 30, 20]))).toBe("Exact: your guess matches the data"); + }); + + it("bar: hides from the index on, seeds from the last known value, clamps and rounds", () => { + const d = bar({ mode: "guess", guess: { from: 2 }, tolerance: 3 }); + expect(guessTargets(d).map((t) => [t.label, t.real])).toEqual([ + ["Reading", 15], + ["Quizzes", 13], + ]); + expect(guessRange(d)).toEqual({ min: 0, max: 60, step: 1 }); + let s = startGuess(d); + expect(s.values).toEqual([24, 24]); + s = setGuess(s, d, 0, 999); + expect(s.values[0]).toBe(60); + s = setGuess(s, d, 0, 16.4); + expect(s.values[0]).toBe(16); + s = setGuess(s, d, 1, 12); + const score = scoreGuess(d, s.values); + expect(score.close).toBe(true); + expect(verdictText(d, score)).toBe("Close: off by 1% on average"); + }); + + it("line: guesses the chosen series", () => { + const d = line({ mode: "guess", guess: { series: "online", from: 6 } }); + expect(guessTargets(d).map((t) => t.real)).toEqual([64, 70]); + expect(startGuess(d).values).toEqual([61, 61]); + expect(verdictText(d, scoreGuess(d, [60, 60]))).toBe("Close: off by $7k on average"); + }); +}); + +describe("chart canvas", () => { + const html = (d: ChartData) => renderToString(createElement(Chart, d)).replaceAll("", ""); + + it("renders a view pie with its legend and no buttons", () => { + const out = html(pie()); + expect(out).toContain(" { + const out = html(bar({ mode: "guess", guess: { from: 2 }, source: "Survey of 1,000 learners" })); + expect(out).toContain("Guess the hidden values, then reveal"); + expect(out.match(/type="range"/g)?.length).toBe(2); + expect(out).toContain("Reveal"); + expect(out).toContain("Source: Survey of 1,000 learners"); + expect(out).toContain("hidden until you reveal"); + expect(out).toContain('aria-live="polite"'); + }); + + it("renders a line chart with a legend for two series", () => { + const out = html(line({ valueLabel: "Sales per month" })); + expect(out).toContain("Online"); + expect(out).toContain("In store"); + expect(out).toContain("Sales per month"); + expect(out).toContain("$70k"); + }); +}); diff --git a/frontend/tests/unit/canvas/command-explainer.test.ts b/frontend/tests/unit/canvas/command-explainer.test.ts new file mode 100644 index 000000000..5e4fe5f88 --- /dev/null +++ b/frontend/tests/unit/canvas/command-explainer.test.ts @@ -0,0 +1,112 @@ +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + checkCommandExplainer, + commandExplainerDataSchema, + commandLine, + commandViews, + explainLine, + movePart, + type CommandExplainerData, +} from "@buildment/learning-ui/canvas/models/command-explainer"; +import { CommandExplainer } from "@buildment/learning-ui/canvas/primitives/command-explainer"; + +const raw = { + title: "Read a copy command", + limits: "Only the common flags. Run man cp for the rest.", + prompt: "$", + parts: [ + { text: "cp", kind: "command", explain: "Copy files." }, + { text: "-r", kind: "flag", explain: "Copy folders and everything inside them." }, + { text: "notes/", kind: "path", explain: "The folder to copy." }, + { text: "backup/", explain: "Where the copy goes." }, + ], + output: "", + examples: [ + { + label: "tar", + parts: [ + { text: "tar", kind: "command", explain: "The archive tool." }, + { text: "-x", kind: "flag", explain: "Extract files." }, + { text: "zvf", kind: "flag", explain: "Gzip, verbose, file.", tight: true }, + { text: "backup.tar.gz", kind: "argument", explain: "The archive." }, + ], + output: "notes/a.md\nnotes/b.md", + }, + ], +}; +const data: CommandExplainerData = commandExplainerDataSchema.parse(raw); + +describe("command explainer schema", () => { + it("parses good data and keeps extra keys", () => { + const parsed = commandExplainerDataSchema.parse({ ...raw, extra: true }); + expect(parsed.purpose).toBe(""); + expect((parsed as Record).extra).toBe(true); + }); + + it("rejects bad data", () => { + expect(commandExplainerDataSchema.safeParse({ ...raw, parts: [] }).success).toBe(false); + expect(commandExplainerDataSchema.safeParse({ ...raw, parts: Array.from({ length: 17 }, () => raw.parts[0]) }).success).toBe(false); + expect(commandExplainerDataSchema.safeParse({ ...raw, parts: [{ text: "cp", kind: "verb", explain: "x" }] }).success).toBe(false); + expect(commandExplainerDataSchema.safeParse({ ...raw, parts: [{ text: "cp", explain: "" }] }).success).toBe(false); + expect(commandExplainerDataSchema.safeParse({ ...raw, title: "" }).success).toBe(false); + }); +}); + +describe("checkCommandExplainer", () => { + it("accepts good data", () => { + expect(checkCommandExplainer(data)).toEqual([]); + }); + + it("flags padded text, a tight first part and duplicate labels", () => { + const problems = checkCommandExplainer({ + ...data, + parts: [{ text: " cp", explain: "Copy.", tight: true }], + examples: [{ ...data.examples![0], label: "tar" }, { ...data.examples![0], label: "TAR" }], + }).join("\n"); + expect(problems).toContain('command part 1: text " cp" starts or ends with a space'); + expect(problems).toContain("command part 1: the first part cannot be tight"); + expect(problems).toContain('example 2: label "TAR" is used twice'); + }); +}); + +describe("command explainer model", () => { + it("joins parts with spaces, tight parts with none", () => { + expect(commandLine(data.parts)).toBe("cp -r notes/ backup/"); + expect(commandLine(data.examples![0].parts)).toBe("tar -xzvf backup.tar.gz"); + }); + + it("lists the main command first, labelled by its first part", () => { + const views = commandViews(data); + expect(views.map((v) => v.label)).toEqual(["cp", "tar"]); + expect(views[1].prompt).toBe("$"); + expect(commandViews({ ...data, label: "Copy" })[0].label).toBe("Copy"); + }); + + it("writes one explanation line with the kind as a word", () => { + expect(explainLine(data.parts[1])).toBe("-r (flag): Copy folders and everything inside them."); + expect(explainLine(data.parts[3])).toBe("backup/: Where the copy goes."); + }); + + it("moves between parts without wrapping", () => { + expect(movePart(0, -1, 4)).toBe(0); + expect(movePart(0, 1, 4)).toBe(1); + expect(movePart(3, 1, 4)).toBe(3); + }); +}); + +describe("command explainer canvas", () => { + it("server-renders the parts, the first explanation and the switcher", () => { + const html = renderToString(createElement(CommandExplainer, data)).replaceAll("", ""); + expect(html).toContain('role="toolbar"'); + expect(html).toContain("notes/"); + expect(html).toContain("Part 1 of 4"); + expect(html).toContain("Copy files."); + expect(html).toContain("(command)"); + expect(html).toContain('role="radiogroup"'); + expect(html).toContain("Explain all"); + expect(html).toContain('aria-live="polite"'); + expect(html.match(/tabindex="0"/g)?.length).toBe(1); + }); +}); diff --git a/frontend/tests/unit/canvas/guess-reveal.test.ts b/frontend/tests/unit/canvas/guess-reveal.test.ts new file mode 100644 index 000000000..24afcd635 --- /dev/null +++ b/frontend/tests/unit/canvas/guess-reveal.test.ts @@ -0,0 +1,161 @@ +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + checkGuessReveal, + formatValue, + gapSentence, + guessRevealDataSchema, + guessTally, + isClose, + isGuessDone, + linePosition, + lockGuess, + nextQuestion, + setGuess, + snapGuess, + startGuess, + stepGuess, + type GuessRevealData, +} from "@buildment/learning-ui/canvas/models/guess-reveal"; +import { GuessReveal } from "@buildment/learning-ui/canvas/primitives/guess-reveal"; + +const raw = { + title: "Guess the number", + limits: "Rounded numbers from one source each.", + questions: [ + { + context: "A quick check on your sense of scale.", + question: "What share of adults get enough sleep?", + min: 0, + max: 100, + step: 5, + unit: "%", + answer: 70, + tolerance: 10, + explanation: "About 7 in 10 adults sleep 7 hours or more.", + source: "CDC, checked 2026-11", + }, + { question: "How many hours of sleep do adults need, at least?", min: 3, max: 12, step: 0.5, unit: " h", answer: 7, tolerance: 0.5, explanation: "Health agencies say 7 or more hours." }, + ], +}; +const data: GuessRevealData = guessRevealDataSchema.parse(raw); +const [q1, q2] = data.questions; + +describe("guess reveal schema", () => { + it("parses good data and fills defaults", () => { + expect(data.purpose).toBe(""); + expect(q2.unit).toBe(" h"); + expect(guessRevealDataSchema.parse({ ...raw, questions: [{ ...raw.questions[1], unit: undefined }] }).questions[0].unit).toBe(""); + }); + + it("accepts a single question as a one-item list", () => { + expect(guessRevealDataSchema.safeParse({ ...raw, questions: [raw.questions[0]] }).success).toBe(true); + }); + + it("rejects bad data", () => { + expect(guessRevealDataSchema.safeParse({ ...raw, questions: [] }).success).toBe(false); + expect(guessRevealDataSchema.safeParse({ ...raw, questions: [{ ...raw.questions[0], step: 0 }] }).success).toBe(false); + expect(guessRevealDataSchema.safeParse({ ...raw, questions: [{ ...raw.questions[0], tolerance: -1 }] }).success).toBe(false); + expect(guessRevealDataSchema.safeParse({ ...raw, questions: [{ ...raw.questions[0], answer: "70" }] }).success).toBe(false); + expect(guessRevealDataSchema.safeParse({ title: "t", limits: "l", question: "q" }).success).toBe(false); + }); +}); + +describe("numbers", () => { + it("snaps and steps on the grid, inside the range", () => { + expect(snapGuess(42, q1)).toBe(40); + expect(snapGuess(130, q1)).toBe(100); + expect(snapGuess(7.3, q2)).toBe(7.5); + expect(stepGuess(3, q2, 1)).toBe(3.5); + expect(stepGuess(3, q2, -1)).toBe(3); + expect(stepGuess(0.1 + 0.2, { min: 0, max: 1, step: 0.1 }, 1)).toBe(0.4); + }); + + it("formats values with the unit as written", () => { + expect(formatValue(40, "%")).toBe("40%"); + expect(formatValue(7.5, " h", 1)).toBe("7.5 h"); + expect(formatValue(7, " h", 1)).toBe("7 h"); + expect(formatValue(12000, " ms")).toBe("12,000 ms"); + }); + + it("says the gap in words", () => { + expect(gapSentence(40, q1)).toBe("You said 40%. The real number is 70%. You were 30 points low."); + expect(gapSentence(75, q1)).toBe("You said 75%. The real number is 70%. You were 5 points high. That counts as close."); + expect(gapSentence(70, q1)).toBe("You said 70%. The real number is 70%. You got it exactly."); + expect(gapSentence(9, q2)).toBe("You said 9 h. The real number is 7 h. You were 2 h high."); + expect(isClose(80, q1)).toBe(true); + expect(isClose(85, q1)).toBe(false); + expect(linePosition(70, q1)).toBe(0.7); + }); +}); + +describe("guess reveal model", () => { + it("starts at min, and locks only after the slider moved", () => { + const s = startGuess(data.questions); + expect(s).toEqual({ index: 0, guess: 0, moved: false, locked: false, results: [] }); + expect(lockGuess(s, data.questions)).toBe(s); + }); + + it("records results, ignores moves after the lock, and tallies", () => { + let s = lockGuess(setGuess(startGuess(data.questions), data.questions, 40), data.questions); + expect(s.results).toEqual([{ guess: 40, close: false }]); + expect(setGuess(s, data.questions, 70)).toBe(s); + s = nextQuestion(s, data.questions); + expect(s).toMatchObject({ index: 1, guess: 3, moved: false, locked: false }); + s = nextQuestion(lockGuess(setGuess(s, data.questions, 7.4), data.questions), data.questions); + expect(isGuessDone(s, data.questions)).toBe(true); + expect(guessTally(s)).toBe(1); + expect(nextQuestion(s, data.questions)).toBe(s); + }); +}); + +describe("checkGuessReveal", () => { + it("accepts good data", () => { + expect(checkGuessReveal(data)).toEqual([]); + }); + + it("flags ranges, steps, answers and tolerance", () => { + const problems = checkGuessReveal({ + ...data, + questions: [ + { ...q1, min: 10, max: 5 }, + { ...q1, step: 30 }, + { ...q1, answer: 120 }, + { ...q1, tolerance: 60 }, + { ...q1, answer: 0 }, + { ...q1, step: 0.01 }, + { ...q1, explanation: "x".repeat(400) }, + ], + }).join("\n"); + expect(problems).toContain("7 questions, need 1 to 6"); + expect(problems).toContain("question 1: max (5) must be more than min (10)"); + expect(problems).toContain("question 2: the range 0 to 100 is not a whole number of steps of 30"); + expect(problems).toContain("question 3: answer 120 is outside min 0 and max 100"); + expect(problems).toContain("question 4: tolerance 60 covers half the line or more"); + expect(problems).toContain("question 5: answer equals min"); + expect(problems).toContain("question 6: 10000 steps between min and max, at most 1000"); + expect(problems).toContain("question 7 explanation: 400 characters, at most 320"); + }); +}); + +describe("guess reveal canvas", () => { + it("server-renders the question, the number line, the slider and the lock button", () => { + const html = renderToString(createElement(GuessReveal, data)).replaceAll("", ""); + expect(html).toContain("Question 1 of 2"); + expect(html).toContain("What share of adults get enough sleep?"); + expect(html).toContain("A quick check on your sense of scale."); + expect(html).toContain(" { + const one = guessRevealDataSchema.parse({ ...raw, questions: [raw.questions[0]] }); + const html = renderToString(createElement(GuessReveal, one)).replaceAll("", ""); + expect(html).not.toContain("Question 1 of"); + }); +}); diff --git a/frontend/tests/unit/canvas/learning-blocks-docs.test.ts b/frontend/tests/unit/canvas/learning-blocks-docs.test.ts new file mode 100644 index 000000000..0cb76f2ed --- /dev/null +++ b/frontend/tests/unit/canvas/learning-blocks-docs.test.ts @@ -0,0 +1,73 @@ +import fs from "node:fs"; +import path from "node:path"; +import { load as loadYaml } from "js-yaml"; +import { describe, expect, it } from "vitest"; +import type { z } from "zod"; +import { architectureDataSchema, checkArchitecture } from "@buildment/learning-ui/canvas/models/architecture"; +import { chartDataSchema, checkChart } from "@buildment/learning-ui/canvas/models/chart"; +import { checkGuessReveal, guessRevealDataSchema } from "@buildment/learning-ui/canvas/models/guess-reveal"; +import { checkScalePicker, scalePickerDataSchema } from "@buildment/learning-ui/canvas/models/scale-picker"; +import { checkLogExplorer, logExplorerDataSchema } from "@buildment/learning-ui/canvas/models/log-explorer"; +import { checkCommandExplainer, commandExplainerDataSchema } from "@buildment/learning-ui/canvas/models/command-explainer"; +import { checkRolePlay, rolePlayDataSchema } from "@buildment/learning-ui/canvas/models/role-play"; +import { checkSelfCheckCards, selfCheckCardsDataSchema } from "@buildment/learning-ui/canvas/models/self-check-cards"; +import { PORTABLE_CANVAS_RENDERERS } from "@buildment/learning-ui/canvas/models/portable"; +import { PORTABLE_CANVAS_RENDERER_NAMES } from "@/shared/mdx/canvas-tags"; + +// Every example in the author guide and on the /zz-learning-blocks page must +// pass the same schema and cross-checks the reader runs, so an author who +// copies one gets a working block. + +type Entry = { schema: z.ZodType; check: (data: never) => string[] }; +const RENDERERS: Record = { + architecture: { schema: architectureDataSchema, check: checkArchitecture as Entry["check"] }, + chart: { schema: chartDataSchema, check: checkChart as Entry["check"] }, + "guess-reveal": { schema: guessRevealDataSchema, check: checkGuessReveal as Entry["check"] }, + "scale-picker": { schema: scalePickerDataSchema, check: checkScalePicker as Entry["check"] }, + "log-explorer": { schema: logExplorerDataSchema, check: checkLogExplorer as Entry["check"] }, + "command-explainer": { schema: commandExplainerDataSchema, check: checkCommandExplainer as Entry["check"] }, + "role-play": { schema: rolePlayDataSchema, check: checkRolePlay as Entry["check"] }, + "self-check-cards": { schema: selfCheckCardsDataSchema, check: checkSelfCheckCards as Entry["check"] }, +}; + +const root = path.resolve(__dirname, "../../../.."); +const SOURCES = { + guide: fs.readFileSync(path.join(root, "docs/interactive-learning-blocks.md"), "utf8"), + gallery: fs + .readFileSync(path.join(root, "frontend/src/app/zz-learning-blocks/page.tsx"), "utf8") + .split("const SOURCE")[1] + .replace(/\$\{T\}/g, "```"), +}; + +function fences(source: string): Record[] { + return [...source.matchAll(/```canvas\r?\n([\s\S]*?)\r?\n```/g)].map((m) => loadYaml(m[1]) as Record); +} + +describe("general-purpose renderers are registered everywhere", () => { + it("lists each renderer in the reader and in the publish check", () => { + for (const name of Object.keys(RENDERERS)) { + expect(PORTABLE_CANVAS_RENDERERS as readonly string[]).toContain(name); + expect(PORTABLE_CANVAS_RENDERER_NAMES as readonly string[]).toContain(name); + } + }); +}); + +for (const [where, source] of Object.entries(SOURCES)) { + describe(`${where} examples`, () => { + const found = fences(source); + + it("has an example for every renderer", () => { + expect(new Set(found.map((f) => f.renderer))).toEqual(new Set(Object.keys(RENDERERS))); + }); + + found.forEach((fence, i) => { + it(`example ${i + 1} (${String(fence.renderer)}) passes the schema and the checks`, () => { + const entry = RENDERERS[String(fence.renderer)]; + expect(entry, `unknown renderer ${String(fence.renderer)}`).toBeDefined(); + const parsed = entry.schema.safeParse(fence); + expect(parsed.success ? [] : parsed.error.issues.map((x) => `${x.path.join(".")}: ${x.message}`)).toEqual([]); + if (parsed.success) expect(entry.check(parsed.data as never)).toEqual([]); + }); + }); + }); +} diff --git a/frontend/tests/unit/canvas/log-explorer.test.ts b/frontend/tests/unit/canvas/log-explorer.test.ts new file mode 100644 index 000000000..2ef90e143 --- /dev/null +++ b/frontend/tests/unit/canvas/log-explorer.test.ts @@ -0,0 +1,131 @@ +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + checkLogExplorer, + filterLines, + gradePicks, + highlightPieces, + levelCounts, + logExplorerDataSchema, + logSources, + openFilter, + presentLevels, + toggleLevel, + togglePick, + type LogExplorerData, +} from "@buildment/learning-ui/canvas/models/log-explorer"; +import { LogExplorer } from "@buildment/learning-ui/canvas/primitives/log-explorer"; + +const raw = { + title: "Find the first failure", + limits: "A real log has thousands of lines and many services.", + lines: [ + { id: "l1", time: "14:09:30", level: "info", source: "web", text: "GET /products 200 38ms" }, + { id: "l2", time: "14:09:41", level: "info", source: "deploy", text: "checkout v2.3 rolled out" }, + { id: "l3", time: "14:09:50", level: "warn", source: "checkout", text: "db pool: 18 of 20 connections in use" }, + { id: "l4", time: "14:09:58", level: "error", source: "checkout", text: "db pool exhausted: 20 of 20 connections in use" }, + { id: "l5", time: "14:10:02", level: "error", source: "web", text: "POST /checkout 500 5012ms" }, + { id: "l6", time: "14:10:03", level: "debug", source: "web", text: "retry POST /Checkout" }, + ], + question: { prompt: "Which line shows the real cause?", answer: ["l4"], why: "The pool ran out first. Every 500 after it is a symptom." }, +}; +const data: LogExplorerData = logExplorerDataSchema.parse(raw); + +describe("log explorer schema", () => { + it("parses good data, keeps extra keys and fills purpose", () => { + const parsed = logExplorerDataSchema.parse({ ...raw, extra: 1 }); + expect(parsed.purpose).toBe(""); + expect((parsed as Record).extra).toBe(1); + }); + + it("rejects bad data", () => { + expect(logExplorerDataSchema.safeParse({ ...raw, lines: raw.lines.slice(0, 2) }).success).toBe(false); + expect(logExplorerDataSchema.safeParse({ ...raw, lines: [{ ...raw.lines[0], level: "fatal" }, ...raw.lines.slice(1)] }).success).toBe(false); + expect(logExplorerDataSchema.safeParse({ ...raw, question: { ...raw.question, answer: [] } }).success).toBe(false); + expect(logExplorerDataSchema.safeParse({ ...raw, question: { ...raw.question, answer: ["l1", "l2", "l3", "l4"] } }).success).toBe(false); + expect(logExplorerDataSchema.safeParse({ ...raw, limits: "" }).success).toBe(false); + }); +}); + +describe("checkLogExplorer", () => { + it("accepts good data", () => { + expect(checkLogExplorer(data)).toEqual([]); + }); + + it("flags duplicate ids, unknown and repeated answers", () => { + const bad: LogExplorerData = { + ...data, + lines: [...data.lines, { ...data.lines[0] }], + question: { ...data.question, answer: ["l9", "l4", "l4"] }, + }; + const problems = checkLogExplorer(bad).join("\n"); + expect(problems).toContain("line l1: duplicate id"); + expect(problems).toContain("answer l9: no line has this id"); + expect(problems).toContain("answer l4: listed twice"); + }); +}); + +describe("log explorer filters", () => { + it("counts levels and lists sources in order", () => { + expect(levelCounts(data.lines)).toEqual({ error: 2, warn: 1, info: 2, debug: 1 }); + expect(presentLevels(data.lines.filter((l) => l.level !== "debug"))).toEqual(["error", "warn", "info"]); + expect(logSources(data.lines)).toEqual(["web", "deploy", "checkout"]); + }); + + it("shows everything with the open filter", () => { + expect(filterLines(data.lines, openFilter())).toHaveLength(6); + }); + + it("filters by level, source and case-insensitive search", () => { + const errorsOnly = { ...openFilter(), levels: ["error" as const] }; + expect(filterLines(data.lines, errorsOnly).map((l) => l.id)).toEqual(["l4", "l5"]); + expect(filterLines(data.lines, { ...openFilter(), source: "checkout" }).map((l) => l.id)).toEqual(["l3", "l4"]); + expect(filterLines(data.lines, { ...openFilter(), query: " CHECKOUT " }).map((l) => l.id)).toEqual(["l2", "l3", "l4", "l5", "l6"]); + expect(filterLines(data.lines, { ...errorsOnly, source: "web", query: "500" }).map((l) => l.id)).toEqual(["l5"]); + expect(filterLines(data.lines, { ...openFilter(), query: "nothing like this" })).toEqual([]); + }); + + it("toggles a level off and back on, keeping the fixed order", () => { + const off = toggleLevel(openFilter(), "warn"); + expect(off.levels).toEqual(["error", "info", "debug"]); + expect(toggleLevel(off, "warn").levels).toEqual(["error", "warn", "info", "debug"]); + }); + + it("highlights every match without losing text", () => { + const pieces = highlightPieces("POST /checkout then checkout", "Checkout"); + expect(pieces.filter((p) => p.match).map((p) => p.text)).toEqual(["checkout", "checkout"]); + expect(pieces.map((p) => p.text).join("")).toBe("POST /checkout then checkout"); + expect(highlightPieces("abc", " ")).toEqual([{ text: "abc", match: false }]); + }); +}); + +describe("log explorer picks", () => { + it("toggles picks and drops the oldest when full", () => { + expect(togglePick([], "a", 1)).toEqual(["a"]); + expect(togglePick(["a"], "b", 1)).toEqual(["b"]); + expect(togglePick(["a"], "a", 1)).toEqual([]); + expect(togglePick(["a", "b"], "c", 2)).toEqual(["b", "c"]); + }); + + it("grades right, wrong and missed lines", () => { + expect(gradePicks(["l4"], ["l4"])).toEqual({ right: ["l4"], wrong: [], missed: [], allRight: true }); + expect(gradePicks(["l5", "l3"], ["l3", "l4"])).toEqual({ right: ["l3"], wrong: ["l5"], missed: ["l4"], allRight: false }); + }); +}); + +describe("log explorer canvas", () => { + it("server-renders the question, chips with counts, lines and controls", () => { + const html = renderToString(createElement(LogExplorer, data)).replaceAll("", ""); + expect(html).toContain("Which line shows the real cause?"); + expect(html).toContain("db pool exhausted"); + expect(html).toContain("ERROR"); + expect(html).toContain("Showing 6 of 6 lines"); + expect(html).toContain("All sources"); + expect(html).toContain("Check"); + expect(html).toContain("Show answer"); + expect(html).toContain('aria-live="polite"'); + expect(html).toContain("What this picture leaves out"); + expect(html).not.toContain(data.question.why); + }); +}); diff --git a/frontend/tests/unit/canvas/role-play.test.ts b/frontend/tests/unit/canvas/role-play.test.ts new file mode 100644 index 000000000..380959b47 --- /dev/null +++ b/frontend/tests/unit/canvas/role-play.test.ts @@ -0,0 +1,175 @@ +import { createElement } from "react"; +import { renderToString } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + backOneStep, + checkRolePlay, + currentNodeId, + isRolePlayOver, + matchChoice, + pickChoice, + rolePlayDataSchema, + speechWords, + startRolePlay, + tallyReplies, + transcript, + type RolePlayData, +} from "@buildment/learning-ui/canvas/models/role-play"; +import { RolePlay } from "@buildment/learning-ui/canvas/primitives/role-play"; + +const raw = { + title: "Calm an upset customer", + limits: "A real customer does not pick from three lines.", + character: { name: "Sara Khan", role: "Customer" }, + learnerRole: "You, the support agent", + goal: "Keep Sara as a customer.", + start: "open", + nodes: { + open: { + says: "My order is two weeks late and nobody answers my emails.", + choices: [ + { text: "I am sorry. Let me check your order right now.", next: "check", tone: "good", feedback: "You own the problem and act." }, + { text: "Can you send me your order number?", next: "check", tone: "okay", feedback: "Useful, but it skips the apology." }, + { text: "Delays happen with every shop.", next: "angry", tone: "weak", feedback: "This brushes off her problem." }, + ], + }, + check: { + says: "Fine. It is order 4471.", + choices: [ + { text: "It ships today and I will refund the delivery fee.", next: "happy", tone: "good", feedback: "A clear fix and a fair gesture." }, + { text: "It should arrive soon.", next: "angry", tone: "weak", feedback: "Vague. She needs a date." }, + ], + }, + angry: { says: "I want to cancel.", ending: { verdict: "Customer lost", tone: "warn", summary: "She felt ignored." } }, + happy: { says: "Thank you. That helps.", ending: { verdict: "Customer kept", tone: "good", summary: "You said sorry, then fixed it." } }, + }, +}; +const data: RolePlayData = rolePlayDataSchema.parse(raw); + +describe("role-play schema", () => { + it("parses a good script and keeps extra keys", () => { + const parsed = rolePlayDataSchema.parse({ ...raw, extra: 1 }); + expect(parsed.purpose).toBe(""); + expect((parsed as Record).extra).toBe(1); + }); + + it("rejects a bad tone, too few choices, one node and a missing limits", () => { + const badTone = structuredClone(raw); + (badTone.nodes.open.choices[0] as { tone: string }).tone = "great"; + expect(rolePlayDataSchema.safeParse(badTone).success).toBe(false); + const oneChoice = structuredClone(raw); + oneChoice.nodes.check.choices = oneChoice.nodes.check.choices.slice(0, 1); + expect(rolePlayDataSchema.safeParse(oneChoice).success).toBe(false); + expect(rolePlayDataSchema.safeParse({ ...raw, nodes: { open: raw.nodes.angry }, start: "open" }).success).toBe(false); + expect(rolePlayDataSchema.safeParse({ ...raw, limits: "" }).success).toBe(false); + }); +}); + +describe("role-play state", () => { + it("walks a path, builds the transcript and tallies the replies", () => { + let s = startRolePlay(); + expect(currentNodeId(data, s)).toBe("open"); + s = pickChoice(data, s, 1); + expect(currentNodeId(data, s)).toBe("check"); + s = pickChoice(data, s, 0); + expect(currentNodeId(data, s)).toBe("happy"); + expect(isRolePlayOver(data, s)).toBe(true); + expect(tallyReplies(data, s)).toEqual({ good: 1, okay: 1, weak: 0 }); + const t = transcript(data, s); + expect(t.map((m) => m.who)).toEqual(["character", "learner", "character", "learner", "character"]); + expect(t[1]).toMatchObject({ tone: "okay", text: "Can you send me your order number?" }); + expect(t[4].text).toBe("Thank you. That helps."); + }); + + it("ignores picks at an ending or out of range", () => { + const end = pickChoice(data, startRolePlay(), 2); + expect(isRolePlayOver(data, end)).toBe(true); + expect(pickChoice(data, end, 0)).toBe(end); + const s = startRolePlay(); + expect(pickChoice(data, s, 9)).toBe(s); + }); + + it("goes back one step so the last reply can be tried again", () => { + const s = pickChoice(data, pickChoice(data, startRolePlay(), 0), 1); + const back = backOneStep(s); + expect(currentNodeId(data, back)).toBe("check"); + expect(backOneStep(startRolePlay()).steps).toEqual([]); + }); +}); + +describe("matchChoice", () => { + const choices = data.nodes.open.choices ?? []; + it("picks the reply the learner said, even loosely", () => { + expect(matchChoice("I'm so sorry, let me check your order now", choices).index).toBe(0); + expect(matchChoice("could you send your order number please", choices).index).toBe(1); + expect(matchChoice("well, delays happen at every shop", choices).index).toBe(2); + }); + + it("returns null for silence, unrelated words or an even split", () => { + expect(matchChoice("", choices).index).toBeNull(); + expect(matchChoice("what a lovely sunny afternoon", choices).index).toBeNull(); + expect(matchChoice("order", [{ text: "check order" }, { text: "order now" }]).index).toBeNull(); + }); + + it("drops filler words and plural s", () => { + expect(speechWords("Um, the orders, you know!")).toEqual(["order", "know"]); + }); +}); + +describe("checkRolePlay", () => { + it("accepts a good script", () => { + expect(checkRolePlay(data)).toEqual([]); + }); + + it("flags unknown ids, dead ends, unreachable nodes and loops with no ending", () => { + const problems = checkRolePlay({ + start: "a", + nodes: { + a: { + says: "Hi", + choices: [ + { text: "Go on", next: "b", tone: "good", feedback: "ok" }, + { text: "Go on", next: "ghost", tone: "weak", feedback: "no" }, + ], + }, + b: { says: "Stuck" }, + c: { says: "Alone", ending: { verdict: "End", tone: "good", summary: "Done" } }, + d: { + says: "Loop", + choices: [ + { text: "x", next: "d", tone: "okay", feedback: "f" }, + { text: "y", next: "d", tone: "okay", feedback: "f" }, + ], + }, + }, + }).join("\n"); + expect(problems).toContain("node a choice 2: unknown next node ghost"); + expect(problems).toContain("node a choice 2: same text as another choice"); + expect(problems).toContain("node b: dead end"); + expect(problems).toContain("node c: unreachable from start"); + expect(problems).toContain("node d: unreachable from start"); + expect(problems).toContain("node a: no path from here to an ending"); + }); + + it("flags an unknown start and a node with both choices and an ending", () => { + const both = structuredClone(data); + both.nodes.happy.choices = both.nodes.check.choices; + expect(checkRolePlay(both).join("\n")).toContain("node happy: has both choices and an ending"); + expect(checkRolePlay({ ...data, start: "nope" })).toContain("start: unknown node nope"); + }); +}); + +describe("role-play canvas", () => { + it("server-renders the first line, the replies and no voice buttons", () => { + const html = renderToString(createElement(RolePlay, data)).replaceAll("", ""); + expect(html).toContain("My order is two weeks late"); + expect(html).toContain("You, the support agent"); + expect(html).toContain("Your goal: Keep Sara as a customer."); + expect(html).toContain("Delays happen with every shop."); + expect(html).toContain('aria-live="polite"'); + expect(html).toContain("What this picture leaves out"); + expect(html).not.toContain("Answer by voice"); + expect(html).not.toContain("Read aloud"); + expect(html.match(/ + onChange(Number(e.target.value))} + onFocus={onFocus} + onBlur={onBlur} + className={cn("h-11 w-0 min-w-0 flex-1 cursor-pointer", ACCENT_CONTROL, FOCUS_RING)} + /> + + {text} + + ); +} + +// ---------- pie ---------- + +const PIE = { cx: 112, r: 96, legendX: 228 }; +const PIE_TWO = { left: 108, right: 312, r: 76 }; + +function pieLegendRows(labels: string[]) { + return labels.map((l) => wrapWords(l, 18)); +} + +function pieHeight(data: ChartData, state: GuessState, top: number): number { + const labels = (data.slices ?? []).map((s) => s.label); + if (state.revealed) { + const rows = legendLayout(labels.map((l, i) => ({ label: l, key: String(i) })), 16, W - 32); + const n = rows.length ? rows[rows.length - 1].row + 1 : 0; + return top + 22 + PIE_TWO.r * 2 + 18 + n * 20 + 8; + } + const legendH = pieLegendRows(labels).reduce((a, lines) => a + 10 + lines.length * 15, 0); + return top + Math.max(PIE.r * 2 + 16, legendH + 8) + 6; +} + +function pt(cx: number, cy: number, r: number, f: number): [number, number] { + return [cx + r * Math.sin(f * 2 * Math.PI), cy - r * Math.cos(f * 2 * Math.PI)]; +} + +function Pie({ shares, cx, cy, r, focus, setFocus }: { shares: number[]; cx: number; cy: number; r: number; focus: number | null; setFocus?: (i: number | null) => void }) { + let acc = 0; + return ( + + {shares.map((share, i) => { + const a = acc / 100; + acc += share; + const b = acc / 100; + if (share <= 0) return null; + const dim = focus !== null && focus !== i; + const [x1, y1] = pt(cx, cy, r, a); + const [x2, y2] = pt(cx, cy, r, b); + const d = share >= 100 ? undefined : `M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${b - a > 0.5 ? 1 : 0} 1 ${x2},${y2} Z`; + const [lx, ly] = pt(cx, cy, r * 0.64, (a + b) / 2); + return ( + setFocus(i) : undefined} opacity={dim ? 0.45 : 1}> + {d ? ( + + ) : ( + + )} + {share >= 7 ? ( + {`${share}%`} + ) : null} + + ); + })} + + ); +} + +function PiePicture({ data, state, top, focus, setFocus }: { data: ChartData; state: GuessState; top: number; focus: number | null; setFocus: (i: number | null) => void }) { + const slices = data.slices ?? []; + const real = pieShares(slices.map((s) => s.value)); + const guessing = data.mode === "guess"; + if (state.revealed) { + const cy = top + 22 + PIE_TWO.r; + const rows = legendLayout(slices.map((s, i) => ({ label: s.label, key: String(i) })), 16, W - 32); + const ly = cy + PIE_TWO.r + 24; + return ( + + Your guess + Real split + + + {rows.map((item) => { + const i = Number(item.key); + return ( + + + {item.label} + + ); + })} + + ); + } + const shares = guessing ? state.values : real; + const cy = top + 8 + PIE.r; + let y = top + 14; + const legend = pieLegendRows(slices.map((s) => s.label)).map((lines, i) => { + const rowY = y; + y += 10 + lines.length * 15; + const s = slices[i]; + return ( + setFocus(i)} opacity={focus !== null && focus !== i ? 0.55 : 1}> + + {lines.map((line, k) => ( + {line} + ))} + {`${shares[i]}%`} + {!guessing && data.unit !== "%" ? ( + {formatValue(s.value, data.prefix, data.unit)} + ) : null} + + ); + }); + return ( + + + {guessing ? ( + Your guess + ) : null} + {legend} + + ); +} + +// ---------- bar and line ---------- + +function axisGeometry(data: ChartData, top: number) { + const cats = data.categories ?? []; + const series = data.series ?? []; + const guessing = data.mode === "guess"; + const scale = chartScale(data); + const tickLabel = (v: number) => formatValue(v, data.prefix, data.unit); + const L = Math.max(30, Math.max(...scale.ticks.map((t) => tickLabel(t).length)) * 6.2 + 12); + const R = W - 14; + const plotW = R - L; + const legendItems = [ + ...(series.length >= 2 ? series.map((s, i) => ({ label: s.label, key: `s${i}` })) : []), + ...(guessing ? [{ label: "Your guess", key: "guess" }] : []), + ]; + const legend = legendLayout(legendItems, 14, W - 28); + const legendRows = legend.length ? legend[legend.length - 1].row + 1 : 0; + const legendY = top + 8; + const labelY = legendY + legendRows * 20 + (legendRows ? 4 : 0); + const T = labelY + (data.valueLabel ? 20 : 4) + 14; + const B = T + PLOT_H; + const n = cats.length; + const groupW = plotW / Math.max(1, n); + const pad = 12; + const dx = n > 1 ? (plotW - 2 * pad) / (n - 1) : 0; + const every = data.chart === "line" ? xLabelEvery(cats, plotW) : 1; + const barLines = data.chart === "bar" ? cats.map((c) => wrapWords(c, Math.max(4, Math.floor((groupW - 4) / 6)))).map((l) => l.slice(0, 2)) : []; + const xLines = data.chart === "bar" ? Math.max(1, ...barLines.map((l) => l.length)) : 1; + const H = B + 18 + xLines * 13 + 6; + const xAt = (i: number) => (data.chart === "bar" ? L + (i + 0.5) * groupW : L + pad + i * dx); + const y = (v: number) => B - (Math.min(v, scale.max) / scale.max) * PLOT_H; + const indexAt = (px: number): number | null => { + if (px < L - 6 || px > R + 6 || n === 0) return null; + const i = data.chart === "bar" ? Math.floor((px - L) / groupW) : Math.round((px - L - pad) / Math.max(1e-9, dx)); + return Math.min(n - 1, Math.max(0, i)); + }; + return { cats, series, scale, L, R, plotW, legend, legendY, labelY, T, B, H, groupW, xAt, y, indexAt, every, barLines, tickLabel }; +} + +function AxisPicture({ + data, + state, + top, + focus, + active, + fade, + fmt, +}: { + data: ChartData; + state: GuessState; + top: number; + focus: number | null; + active: number | null; + fade: string; + fmt: (v: number) => string; +}) { + const g = axisGeometry(data, top); + const { cats, series, scale, L, R, T, B, y, xAt } = g; + const guessing = data.mode === "guess"; + const gi = guessSeriesIndex(data); + const from = guessing ? (data.guess?.from ?? cats.length) : cats.length; + const hidden = (si: number, i: number) => guessing && !state.revealed && si === gi && i >= from; + const guessAt = (i: number) => state.values[i - from]; + const activeIndex = active !== null ? from + active : null; + + const grid = scale.ticks.map((t) => ( + + + {g.tickLabel(t)} + + )); + + const legend = g.legend.map((item) => { + const ly = g.legendY + item.row * 20 + 8; + const si = item.key === "guess" ? -1 : Number(item.key.slice(1)); + return ( + + {si < 0 ? ( + + ) : data.chart === "line" ? ( + <> + + + + ) : ( + + )} + {item.label} + + ); + }); + + const xLabels = cats.map((c, i) => { + if (data.chart === "line" && i % g.every !== 0) return null; + const lines = data.chart === "bar" ? g.barLines[i] : [c]; + return lines.map((line, k) => ( + {line} + )); + }); + + let marks; + if (data.chart === "bar") { + const inner = g.groupW * 0.74; + const bw = inner / Math.max(1, series.length); + const labelFits = bw >= 26; + marks = cats.map((_, i) => { + const x0 = L + i * g.groupW + (g.groupW - inner) / 2; + return ( + + {focus === i ? : null} + {series.map((s, si) => { + const x = x0 + si * bw + 1; + const w = Math.max(3, bw - 2); + const real = s.values[i]; + const isGuess = guessing && si === gi && i >= from; + const gv = isGuess ? guessAt(i) : 0; + return ( + + {!hidden(si, i) ? ( + + ) : null} + {isGuess ? ( + + ) : null} + {isGuess && !state.revealed ? ( + + ) : null} + {labelFits || focus === i ? ( + + {hidden(si, i) ? fmt(gv) : fmt(real)} + + ) : null} + + ); + })} + + ); + }); + } else { + const path = (pts: [number, number][]) => pts.map(([px, py], k) => `${k ? "L" : "M"}${px},${py}`).join(" "); + const lastKnown = Math.max(0, from - 1); + marks = ( + + {guessing ? ( + <> + + Your guess + + ) : null} + {focus !== null ? : null} + {series.map((s, si) => { + const shownIdx = s.values.map((_, i) => i).filter((i) => !hidden(si, i)); + const isG = guessing && si === gi; + return ( + + [xAt(i), y(s.values[i])]))} + fill="none" + strokeWidth={2} + strokeLinejoin="round" + className={cn(SERIES[si].stroke, isG && state.revealed && fade)} + /> + {shownIdx.map((i) => ( + + ))} + + ); + })} + {guessing ? ( + + {state.revealed + ? state.values.map((v, k) => { + const i = from + k; + const real = series[gi]?.values[i] ?? 0; + return ; + }) + : null} + [xAt(from + k), y(v)])])} + fill="none" + strokeWidth={2} + strokeDasharray="6 4" + className={GUESS_STROKE} + /> + {state.values.map((v, k) => { + const i = from + k; + const big = activeIndex === i || focus === i; + return ( + + + {big ? ( + {fmt(v)} + ) : null} + + ); + })} + + ) : null} + + ); + } + + // A readout for the hovered or focused category, at the top of the plot. + let readout = null; + if (focus !== null && data.chart === "line") { + const parts = series.map((s, si) => `${series.length > 1 ? `${s.label} ` : ""}${hidden(si, focus) ? `guess ${fmt(guessAt(focus))}` : fmt(s.values[focus])}`); + const text = `${cats[focus]}: ${parts.join(", ")}`; + const w = text.length * CHAR_W + 16; + const x = Math.min(R - w, Math.max(L, xAt(focus) - w / 2)); + readout = ( + + + {text} + + ); + } + + return ( + + {legend} + {data.valueLabel ? ( + {data.valueLabel} + ) : null} + {grid} + {marks} + {xLabels} + {readout} + + ); +} diff --git a/packages/learning-ui/src/canvas/primitives/command-explainer.spec.md b/packages/learning-ui/src/canvas/primitives/command-explainer.spec.md new file mode 100644 index 000000000..09567c69c --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/command-explainer.spec.md @@ -0,0 +1,51 @@ +--- +artifact: canvas-spec +course: shared +chapter: shared primitive +slug: command-explainer +version: 1 +owner: interactive-canvas-builder +--- + +# Canvas spec: Command explainer + +## Teaching claim +A long command is a list of small parts, and each part does one thing. + +## Why a canvas +A table of flags is far from the command itself. Here the learner taps the part inside the real command line and reads what it does. + +## Model +- Inputs: optional `prompt` (such as "$"), 1 to 16 `parts` (`text`, `explain`, optional `kind` of command, flag, argument, pipe, path or other, optional `tight`), optional `output`, optional `label`, optional `examples` (up to 5 more commands, each with `label`, `parts`, optional `prompt` and `output`). +- The command shown is the parts joined by single spaces. A part with `tight: true` joins the part before it with no space (for `-xzvf`). +- Pure functions in `models/command-explainer.ts`: `commandViews`, `commandLine`, `kindName`, `explainLine`, `movePart`, `checkCommandExplainer`. + +## Rendering +- HTML in a monospace pane that uses the `--code-*` tokens, like the terminal block. +- Each part is a button. Its underline colour shows its kind. Pipes have a dotted underline; "other" and parts with no kind have a dashed one. +- Optional output shows under the command, in the same pane. +- The command scrolls sideways inside its own pane on a phone. + +## Controls +- Tap a part to explain it. Left and Right arrows move between parts; Home and End jump to the ends. +- "Explain all" (a toggle) lists every part in order. Tapping an item in the list selects that part. +- With examples, a segmented control (a row of radio pills) switches the command. + +## Visualisation +- The selected part has a blue ring and fill. +- The explanation shows the part, its kind as a word in brackets, then what it does: "`-r` (flag): copy folders and everything inside them." + +## Edge cases +- 16 parts or a long path: the pane scrolls sideways. +- No kind: the explanation leaves out the bracket. + +## Accessibility +- The parts are a `role="toolbar"` with a roving tabindex: one Tab stop, arrows inside. +- Each part button has `aria-pressed` and a label with its kind. Targets are 44px on touch. +- An `aria-live="polite"` line reads the selected part and its explanation. +- Colour changes are off under `prefers-reduced-motion`. + +## Acceptance criteria +- [x] Model tested (`frontend/tests/unit/canvas/command-explainer.test.ts`). +- [x] Reads at 375px. +- [x] Light and dark themes through app tokens. diff --git a/packages/learning-ui/src/canvas/primitives/command-explainer.tsx b/packages/learning-ui/src/canvas/primitives/command-explainer.tsx new file mode 100644 index 000000000..a3fa51b9f --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/command-explainer.tsx @@ -0,0 +1,193 @@ +"use client"; + +import { useRef, useState, type KeyboardEvent } from "react"; +import { cn } from "../../lib/utils"; +import { BeatButton, BeatFrame } from "./beat-frame"; +import { BeatSegmented } from "./beat-segmented"; +import { commandLine, commandViews, explainLine, movePart, type CommandExplainerData, type PartKind } from "../models/command-explainer"; + +// A command split into parts in a terminal-style pane. Each part is a button +// with an underline coloured by its kind; the kind is also written as a word +// in the explanation, so colour is never the only signal. Tap a part (or use +// the left and right arrows) to read what it does, or "Explain all" to list +// every part in order. A long command scrolls sideways inside its own pane. + +/** Underline colour and style per kind. Pipes and "other" also change the line style. */ +const KIND_UNDERLINE: Record = { + command: "decoration-blue-600 dark:decoration-blue-400", + flag: "decoration-violet-600 dark:decoration-violet-400", + argument: "decoration-teal-600 dark:decoration-teal-400", + path: "decoration-fuchsia-600 dark:decoration-fuchsia-400", + pipe: "decoration-dotted decoration-slate-500 dark:decoration-slate-400", + other: "decoration-dashed decoration-[var(--code-lang-fg)]", + none: "decoration-dashed decoration-[var(--code-lang-fg)]", +}; + +const KIND_TEXT: Record = { + command: "text-blue-700 dark:text-blue-300", + flag: "text-violet-700 dark:text-violet-300", + argument: "text-teal-700 dark:text-teal-300", + path: "text-fuchsia-700 dark:text-fuchsia-300", + pipe: "text-slate-600 dark:text-slate-300", + other: "text-muted-foreground", + none: "text-muted-foreground", +}; + +export function CommandExplainer(props: CommandExplainerData) { + const { title, limits } = props; + const views = commandViews(props); + const [viewIndex, setViewIndex] = useState(0); + const [selected, setSelected] = useState(0); + const [all, setAll] = useState(false); + const [live, setLive] = useState(""); + const toolbar = useRef(null); + + const view = views[Math.min(viewIndex, views.length - 1)]; + const parts = view.parts; + const index = Math.min(selected, parts.length - 1); + const part = parts[index]; + + const announce = (i: number) => { + const p = parts[i]; + setLive(`Part ${i + 1} of ${parts.length}: ${explainLine(p)}`); + }; + + const select = (i: number, focus = false) => { + setSelected(i); + announce(i); + if (focus) toolbar.current?.querySelectorAll("button[data-part]")[i]?.focus(); + }; + + const onKey = (e: KeyboardEvent) => { + const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0; + if (step) { + e.preventDefault(); + select(movePart(index, step, parts.length), true); + } else if (e.key === "Home" || e.key === "End") { + e.preventDefault(); + select(e.key === "Home" ? 0 : parts.length - 1, true); + } + }; + + const switchView = (id: string) => { + const i = Number(id); + setViewIndex(i); + setSelected(0); + const v = views[i]; + setLive(`Showing ${v.label}: ${commandLine(v.parts)}. Part 1 of ${v.parts.length}: ${explainLine(v.parts[0])}`); + }; + + const toggleAll = () => { + const next = !all; + setAll(next); + setLive(next ? `Explaining all ${parts.length} parts, in order.` : "Explaining one part at a time."); + }; + + const kindKey = (k: PartKind | undefined) => k ?? "none"; + + return ( + + Explain all + + } + > +
+ {views.length > 1 ? ( + ({ id: String(i), label: v.label }))} value={String(viewIndex)} onChange={switchView} /> + ) : null} + +
+
+
+ {view.prompt ? ( + + {view.prompt} + + ) : null} + {parts.map((p, i) => { + const on = i === index; + return ( + + {i > 0 && !p.tight ? : null} + + + ); + })} +
+
+ {view.output ? ( +
+

Output

+
{view.output}
+
+ ) : null} +
+ + {all ? ( +
    + {parts.map((p, i) => ( +
  1. + +
  2. + ))} +
+ ) : ( +
+

+ Part {index + 1} of {parts.length} +

+

+ {part.text}{" "} + {part.kind ? ({part.kind}) : null}: {part.explain} +

+
+ )} +
+

+ {live} +

+
+ ); +} diff --git a/packages/learning-ui/src/canvas/primitives/guess-reveal.spec.md b/packages/learning-ui/src/canvas/primitives/guess-reveal.spec.md new file mode 100644 index 000000000..7389f2cbd --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/guess-reveal.spec.md @@ -0,0 +1,57 @@ +--- +artifact: canvas-spec +course: shared +chapter: shared primitive +slug: guess-reveal +version: 1 +owner: interactive-canvas-builder +--- + +# Canvas spec: Guess, then reveal + +## Teaching claim +Guessing a number before you see it makes the real number stick, and shows how far your own sense of scale is off. + +## Why a canvas +A number read in prose is forgotten. A number you guessed, then saw next to your guess on the same line, is remembered. + +## Data (```canvas fence, `renderer: guess-reveal`) +Always a `questions` list of 1 to 6. A single question is a one-item list; then no "Question 1 of 1" line and no tally. +- `title`, `purpose` (optional), `limits`. +- Each question: `context?` (120), `question` (200), `min`, `max`, `step`, `unit?` (written right after the number: `"%"` gives 40%, `" ms"` gives 40 ms), `answer`, `tolerance` (a guess this close or closer counts as close), `explanation` (320), `source?` (80). + +```canvas +renderer: guess-reveal +title: Guess the number +limits: Rounded numbers from one source each. +questions: + - question: You download a 1 GB file on a 100 Mbit/s line. How many seconds, at best? + min: 0 + max: 300 + step: 5 + unit: " s" + answer: 80 + tolerance: 10 + explanation: 1 GB is 8,000 megabits. 8,000 divided by 100 is 80 seconds. +``` + +## Model (`models/guess-reveal.ts`) +- State: `index`, `guess`, `moved`, `locked`, `results` (guess and close per question). +- The slider starts at `min`. `lockGuess` is ignored until the slider was moved, so the learner must move it. `setGuess` is ignored after the lock. `snapGuess` keeps values on the step grid and avoids float noise. +- `gapSentence`: "You said 40%. The real number is 70%. You were 30 points low." A percent gap is in points; other gaps use the unit. Within the tolerance it adds "That counts as close." +- `checkGuessReveal` reports max not above min, a range that is not a whole number of steps, fewer than 4 or more than 1000 steps, an answer outside the line or equal to `min`, a tolerance of half the line or more, and text over the limits. + +## Rendering +HTML question above an SVG number line (`viewBox` 420 by 196). Before the lock: banner, the big guess value, a blue marker. After the lock: the guess marker above the line, the real answer marker below, a dashed band for the tolerance, and the gap drawn between them. Under the picture: a range slider with - and + buttons (44 px), then the result panel with the gap sentence, explanation and source. Controls: Lock my guess, then Next question or See the tally, or Again. + +## Visualisation +Close is green, far is amber, never red. The banner says "Close" or "Not quite", and the gap is always in words, so colour is never the only signal. + +## Accessibility +Native range input with `aria-valuetext`. - and + buttons with labels. Pressing Lock before moving announces "Move the slider first." An `aria-live="polite"` line reads the guess, then the gap sentence, explanation and source. Focus moves to the next action after each button. The marker slide is off under `prefers-reduced-motion`. + +## Acceptance criteria +- [x] Model tested (`frontend/tests/unit/canvas/guess-reveal.test.ts`). +- [x] Reads at 375 px; labels near the ends are kept inside the picture. +- [x] Light and dark through app tokens. +- [ ] Registration in `portable.ts` and `InteractiveCanvas.tsx` (done by the orchestrator). diff --git a/packages/learning-ui/src/canvas/primitives/guess-reveal.tsx b/packages/learning-ui/src/canvas/primitives/guess-reveal.tsx new file mode 100644 index 000000000..b82514b0d --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/guess-reveal.tsx @@ -0,0 +1,265 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { CircleCheck, Minus, Plus, TriangleAlert } from "lucide-react"; +import { cn } from "../../lib/utils"; +import { BeatButton, BeatFrame } from "./beat-frame"; +import { useReducedMotion } from "./beat-parts"; +import { DotGrid, VerdictBanner } from "./svg-parts"; +import { ACCENT_CONTROL, FOCUS_RING, LABEL_HALO, NEUTRAL, TONES, type Tone } from "./tones"; +import { + formatValue, + gapSentence, + guessTally, + isGuessDone, + linePosition, + lockGuess, + nextQuestion, + setGuess, + startGuess, + stepDecimals, + stepGuess, + type GuessRevealData, + type GuessState, +} from "../models/guess-reveal"; + +// Guess a number, then reveal it. The slider starts at the lowest value, so +// the learner has to move it. After "Lock my guess" the number line shows the +// guess and the real answer side by side, the gap in words, and why. Close +// (within the tolerance) is green; a far guess is amber, never red. With +// several questions, a tally closes the round. + +const W = 420; +const H = 196; +const X0 = 36; +const X1 = W - 36; +const LINE_Y = 122; +const LABEL_MIN_X = 58; +const LABEL_MAX_X = W - 58; + +const xAt = (t: number) => X0 + t * (X1 - X0); +const labelX = (x: number) => Math.max(LABEL_MIN_X, Math.min(LABEL_MAX_X, x)); + +export function GuessReveal({ title, limits, questions }: GuessRevealData) { + const [state, setState] = useState(() => startGuess(questions)); + const [nudge, setNudge] = useState(false); + const reduced = useReducedMotion(); + const controls = useRef(null); + const slider = useRef(null); + const pressed = useRef(false); + + // After Lock, Next or Again the pressed button changes; keep focus on the next useful control. + useEffect(() => { + if (!pressed.current) return; + pressed.current = false; + if (!state.locked && !isGuessDone(state, questions)) slider.current?.focus(); + else controls.current?.querySelector("button")?.focus(); + }, [state, questions]); + + const total = questions.length; + const multi = total > 1; + const done = isGuessDone(state, questions); + const q = done ? null : questions[state.index]; + const d = q ? Math.max(stepDecimals(q.step), stepDecimals(q.min)) : 0; + const fmt = (v: number) => (q ? formatValue(v, q.unit, d) : String(v)); + const close = state.locked && state.results.length > 0 ? state.results[state.results.length - 1].close : false; + const tone: Tone = close ? "good" : "warn"; + + const move = (value: number) => { + setNudge(false); + setState((s) => setGuess(s, questions, value)); + }; + const lock = () => { + if (!state.moved) { + setNudge(true); + return; + } + pressed.current = true; + setState(lockGuess(state, questions)); + }; + const act = (next: GuessState) => { + pressed.current = true; + setNudge(false); + setState(next); + }; + + let live: string; + if (done) live = `All done. ${guessTally(state)} of ${total} guesses were close.`; + else if (q && state.locked) live = `${gapSentence(state.guess, q)} ${q.explanation}${q.source ? ` Source: ${q.source}.` : ""}`; + else if (nudge && q) live = `Move the slider first. It starts at the lowest value, ${fmt(q.min)}.`; + else live = q && state.moved ? `Your guess: ${fmt(state.guess)}` : ""; + + const anim = reduced ? "" : "transition-transform duration-200 ease-out"; + + let picture = null; + if (q) { + const gx = xAt(linePosition(state.guess, q)); + const ax = xAt(linePosition(q.answer, q)); + const lo = xAt(linePosition(q.answer - q.tolerance, q)); + const hi = xAt(linePosition(q.answer + q.tolerance, q)); + const banner = state.locked ? { text: close ? "Close" : "Not quite", tone } : { text: state.moved ? "Lock it when you are ready" : "Move the slider to guess", tone: "accent" as Tone }; + const ticks = [0, 0.25, 0.5, 0.75, 1]; + picture = ( + + + + + {!state.locked ? ( + + {fmt(state.guess)} + + ) : null} + + {/* The tolerance band around the real answer. */} + {state.locked && q.tolerance > 0 ? ( + + ) : null} + + + {ticks.map((t) => ( + + ))} + {fmt(q.min)} + {fmt(q.max)} + + {/* The gap between the guess and the answer. */} + {state.locked ? : null} + + {/* The guess: a marker above the line. */} + + + + + {state.locked ? ( + + {`You: ${fmt(state.guess)}`} + + ) : null} + + {/* The real answer: a marker below the line, after the lock. */} + {state.locked ? ( + <> + + + + {`Real: ${formatValue(q.answer, q.unit, Math.max(d, stepDecimals(q.answer)))}`} + + {q.tolerance > 0 ? ( + + {`Dashed band: within ${formatValue(q.tolerance, q.unit, Math.max(d, stepDecimals(q.tolerance)))} counts as close`} + + ) : null} + + ) : null} + + ); + } + + return ( + + {done ? ( + act(startGuess(questions))}>Again + ) : !state.locked ? ( + Lock my guess + ) : multi && state.index < total - 1 ? ( + act(nextQuestion(state, questions))}>Next question + ) : multi ? ( + act(nextQuestion(state, questions))}>See the tally + ) : ( + act(startGuess(questions))}>Again + )} + + } + > +
+ {done ? ( +
+

All done

+

{`${guessTally(state)} of ${total} guesses were close`}

+
    + {questions.map((item, i) => { + const r = state.results[i]; + if (!r) return null; + const Icon = r.close ? CircleCheck : TriangleAlert; + const dd = Math.max(stepDecimals(item.step), stepDecimals(item.min), stepDecimals(item.answer)); + return ( +
  • + + + {item.question} + {` You said ${formatValue(r.guess, item.unit, dd)}. Real: ${formatValue(item.answer, item.unit, dd)}.`} + +
  • + ); + })} +
+

Now you know the real numbers. That is the point of guessing first.

+
+ ) : q ? ( + <> +
+ {multi ?

{`Question ${state.index + 1} of ${total}`}

: null} + {q.context ?

{q.context}

: null} +

{q.question}

+
+ {picture} +
+ + move(Number(e.target.value))} + className={cn("h-11 w-0 min-w-0 flex-1 cursor-pointer disabled:cursor-default disabled:opacity-60", ACCENT_CONTROL, FOCUS_RING)} + /> + +
+ {state.locked ? ( +
+

+ {close ? : } + {gapSentence(state.guess, q)} +

+

{q.explanation}

+ {q.source ?

{`Source: ${q.source}`}

: null} +
+ ) : null} + + ) : null} +
+

{live}

+
+ ); +} diff --git a/packages/learning-ui/src/canvas/primitives/log-explorer.spec.md b/packages/learning-ui/src/canvas/primitives/log-explorer.spec.md new file mode 100644 index 000000000..47163ad35 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/log-explorer.spec.md @@ -0,0 +1,54 @@ +--- +artifact: canvas-spec +course: shared +chapter: shared primitive +slug: log-explorer +version: 1 +owner: interactive-canvas-builder +--- + +# Canvas spec: Log explorer + +## Teaching claim +The cause of an incident is usually the first unusual line, not the loudest one. Filters and search help you find it. + +## Why a canvas +Reading a pasted log does not train the habit of narrowing it. Here the learner filters, searches and picks the line, then sees if it was right. + +## Model +- Inputs: 3 to 80 log lines (`id`, `time`, `level` of error, warn, info or debug, `source`, `text`), a question with 1 to 3 answer line ids and a `why`, an optional `hint`. +- Pure functions in `models/log-explorer.ts`: `levelCounts`, `presentLevels`, `logSources`, `lineMatches`, `filterLines`, `toggleLevel`, `highlightPieces`, `togglePick`, `gradePicks`, `checkLogExplorer`. +- Search is case-insensitive and matches the line text and the source. +- Picks: at most as many as there are answer lines. When full, a new pick replaces the oldest one. + +## Rendering +- HTML, not SVG: the log is text. The lines sit in a monospace pane that uses the `--code-*` tokens, like the terminal block. +- Long lines scroll sideways inside the pane. The pane also scrolls down after about 26rem. +- Above the pane: the question, level chips with counts, a search box, and a source filter (only when there are 2 or more sources). + +## Controls +- Before Check: "Check" and "Show answer". +- After a wrong check: "Try again" (keeps the right picks) and "Show answer". +- After a right check or Show answer: "Again" (clears picks and filters). +- Show answer clears the filters, so the answer lines can be seen. + +## Visualisation +- Your pick: blue, with the label "Your pick". +- Right line: green, label "Right line". Wrong pick: amber, label "Not this one". Shown answer: green, label "Answer". +- Level names always show as text. Red is used only for the ERROR level name. +- Search matches have a yellow mark. + +## Edge cases +- No lines match: the pane says "No lines match. Clear the search or turn a level back on." +- Check with no picks: nothing is graded. The live line says to pick a line first. + +## Accessibility +- Every line is a real button with `aria-pressed` and a full text label. Up and Down arrows move between lines; Home and End jump to the ends. +- Level chips are toggle buttons. The search box and source filter have visible labels. +- Targets are 44px on touch. An `aria-live="polite"` line says what changed (filter count, pick, result). +- Colour changes are off under `prefers-reduced-motion`. + +## Acceptance criteria +- [x] Model tested (`frontend/tests/unit/canvas/log-explorer.test.ts`). +- [x] Reads at 375px: long lines scroll inside the pane, not the page. +- [x] Light and dark themes through app tokens. diff --git a/packages/learning-ui/src/canvas/primitives/log-explorer.tsx b/packages/learning-ui/src/canvas/primitives/log-explorer.tsx new file mode 100644 index 000000000..8f75a0f64 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/log-explorer.tsx @@ -0,0 +1,323 @@ +"use client"; + +import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent } from "react"; +import { cn } from "../../lib/utils"; +import { BeatButton, BeatFrame } from "./beat-frame"; +import { FOCUS_RING } from "./tones"; +import { + LEVEL_TEXT, + filterLines, + gradePicks, + highlightPieces, + levelCounts, + logSources, + openFilter, + presentLevels, + toggleLevel, + togglePick, + type LogExplorerData, + type LogFilter, + type LogLevel, + type LogLine, +} from "../models/log-explorer"; + +// A log file to investigate. Level chips (with counts), a search box and a +// source filter narrow the lines; the learner taps the line or lines that +// answer the question, then checks. Right picks are green with a label, wrong +// picks amber with a label, never red: red is only the ERROR level name. +// Long lines scroll sideways inside the log pane, never the page. + +/** Level name colour in the log pane. The name is always shown as text too. */ +const LEVEL_CLASS: Record = { + error: "text-red-700 dark:text-red-300", + warn: "text-amber-800 dark:text-amber-300", + info: "text-sky-700 dark:text-sky-300", + debug: "text-[var(--code-lang-fg)]", +}; + +type Mark = { label: string; tone: "accent" | "good" | "warn" }; + +const MARK_CLASS: Record = { + accent: "bg-blue-50 text-blue-800 ring-blue-200/80 dark:bg-blue-500/15 dark:text-blue-200 dark:ring-blue-400/25", + good: "bg-emerald-50 text-emerald-800 ring-emerald-200/80 dark:bg-emerald-500/15 dark:text-emerald-200 dark:ring-emerald-400/25", + warn: "bg-amber-50 text-amber-900 ring-amber-200/80 dark:bg-amber-500/15 dark:text-amber-100 dark:ring-amber-400/25", +}; + +const ROW_TONE: Record = { + accent: "bg-blue-500/10 shadow-[inset_3px_0_0] shadow-blue-600 dark:shadow-blue-400", + good: "bg-emerald-500/10 shadow-[inset_3px_0_0] shadow-emerald-600 dark:shadow-emerald-400", + warn: "bg-amber-500/10 shadow-[inset_3px_0_0] shadow-amber-600 dark:shadow-amber-400", +}; + +type Phase = "pick" | "checked" | "revealed"; + +const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`; + +export function LogExplorer({ title, limits, lines, question, hint }: LogExplorerData) { + const [filter, setFilter] = useState(openFilter); + const [picks, setPicks] = useState([]); + const [phase, setPhase] = useState("pick"); + const [live, setLive] = useState(""); + const controls = useRef(null); + const touched = useRef(false); + const searchId = useId(); + const sourceId = useId(); + + const answer = question.answer; + const max = answer.length; + const counts = useMemo(() => levelCounts(lines), [lines]); + const levels = useMemo(() => presentLevels(lines), [lines]); + const sources = useMemo(() => logSources(lines), [lines]); + const shown = filterLines(lines, filter); + const grade = gradePicks(picks, answer); + const byId = (id: string) => lines.find((l) => l.id === id); + const at = (id: string) => { + const line = byId(id); + return line ? `${line.time} ${LEVEL_TEXT[line.level]} ${line.source}` : id; + }; + + // After a control is pressed the pressed button may go away; keep focus on the next action. + useEffect(() => { + if (touched.current) controls.current?.querySelector("button:not(:disabled)")?.focus(); + touched.current = false; + }, [phase]); + + const changeFilter = (next: LogFilter) => { + setFilter(next); + const n = filterLines(lines, next).length; + setLive(`Showing ${n} of ${lines.length} lines.`); + }; + + const pick = (line: LogLine) => { + if (phase !== "pick") return; + const next = togglePick(picks, line.id, max); + setPicks(next); + setLive(next.includes(line.id) ? `Picked the line at ${line.time}. ${plural(next.length, "line")} picked.` : `Unpicked the line at ${line.time}.`); + }; + + const check = () => { + touched.current = true; + setPhase("checked"); + if (grade.allRight) setLive(`Right. ${question.why}`); + else + setLive( + `Not quite. ${grade.right.length} of ${max} right.${grade.wrong.length ? ` ${plural(grade.wrong.length, "pick")} not part of the answer.` : ""}${grade.missed.length ? ` ${plural(grade.missed.length, "answer line")} still to find.` : ""}` + ); + }; + + const tryAgain = () => { + touched.current = true; + setPicks(grade.right); + setPhase("pick"); + setLive("Wrong picks cleared. Pick again, then check."); + }; + + const reveal = () => { + touched.current = true; + setFilter(openFilter()); + setPhase("revealed"); + setLive(`The answer: ${answer.map(at).join("; ")}. ${question.why}`); + }; + + const again = () => { + touched.current = true; + setFilter(openFilter()); + setPicks([]); + setPhase("pick"); + setLive("Starting again. All lines shown, no picks."); + }; + + const markFor = (id: string): Mark | null => { + const picked = picks.includes(id); + const isAnswer = answer.includes(id); + if (phase === "pick") return picked ? { label: "Your pick", tone: "accent" } : null; + if (picked && isAnswer) return { label: "Right line", tone: "good" }; + if (picked) return { label: "Not this one", tone: "warn" }; + if (phase === "revealed" && isAnswer) return { label: "Answer", tone: "good" }; + return null; + }; + + // Up and down arrows move between log lines, Home and End jump to the ends. + const onListKey = (e: KeyboardEvent) => { + if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(e.key)) return; + const buttons = Array.from(e.currentTarget.querySelectorAll("button[data-line]")); + const i = buttons.indexOf(document.activeElement as HTMLButtonElement); + if (i < 0) return; + e.preventDefault(); + const j = e.key === "Home" ? 0 : e.key === "End" ? buttons.length - 1 : Math.min(buttons.length - 1, Math.max(0, i + (e.key === "ArrowDown" ? 1 : -1))); + buttons[j]?.focus(); + }; + + const done = phase === "revealed" || (phase === "checked" && grade.allRight); + const ask = max === 1 ? "Tap the line that answers the question, then Check." : `Tap the ${max} lines that answer the question, then Check.`; + + let feedback: { tone: "good" | "warn"; head: string; body?: string } | null = null; + if (phase === "checked" && grade.allRight) feedback = { tone: "good", head: "Right.", body: question.why }; + else if (phase === "checked") + feedback = { + tone: "warn", + head: `Not quite. ${grade.right.length} of ${max} right.`, + body: [grade.wrong.length ? `${plural(grade.wrong.length, "pick")} marked "Not this one".` : "", grade.missed.length ? `${plural(grade.missed.length, "answer line")} still to find.` : ""].filter(Boolean).join(" "), + }; + else if (phase === "revealed") feedback = { tone: "good", head: max === 1 ? "The answer line is marked." : "The answer lines are marked.", body: question.why }; + + return ( + + {phase === "pick" ? ( + <> + setLive(max === 1 ? "Pick a line first." : "Pick at least one line first.")}>Check + Show answer + + ) : done ? ( + Again + ) : ( + <> + Try again + Show answer + + )} + + } + > +
+

{question.prompt}

+ +
+ {levels.map((level) => { + const on = filter.levels.includes(level); + return ( + + ); + })} +
+ +
+
+ + changeFilter({ ...filter, query: e.target.value })} + placeholder="Words in the line" + autoComplete="off" + spellCheck={false} + className={cn("h-11 w-full min-w-0 rounded-lg border border-input bg-background px-3 font-mono text-sm text-foreground placeholder:text-muted-foreground sm:h-9", FOCUS_RING)} + /> +
+ {sources.length > 1 ? ( +
+ + +
+ ) : null} +
+ +

+ Showing {shown.length} of {lines.length} lines + {picks.length ? ` · ${plural(picks.length, "line")} picked` : ""} +

+ +
+ {shown.length === 0 ? ( +

No lines match. Clear the search or turn a level back on.

+ ) : ( +
    + {shown.map((line) => { + const mark = markFor(line.id); + return ( +
  • + +
  • + ); + })} +
+ )} +
+ + {feedback ? ( +
+

{feedback.head}

+ {feedback.body ?

{feedback.body}

: null} +
+ ) : null} +
+

+ {live} +

+
+ ); +} diff --git a/packages/learning-ui/src/canvas/primitives/role-play.spec.md b/packages/learning-ui/src/canvas/primitives/role-play.spec.md new file mode 100644 index 000000000..2959ac054 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/role-play.spec.md @@ -0,0 +1,51 @@ +--- +artifact: canvas-spec +course: shared +chapter: shared primitive +slug: role-play +version: 1 +owner: interactive-canvas-builder +--- + +# Canvas spec: Role-play + +## Teaching claim +How you reply changes where a conversation goes. Practise the reply before the real talk. + +## Why a canvas +Reading good and bad replies does not make the learner choose one. A scripted talk with a character makes them commit to a reply, see why it was strong or weak, and hear what the other person says next. + +## Model +- Inputs: `character {name, role}`, `learnerRole`, optional `goal`, `start`, and `nodes` (2 to 30). A node has `says` and either 2 to 4 `choices` (`text`, `next`, `tone` good, okay or weak, `feedback`) or an `ending` (`verdict`, `tone` good or warn, `summary`). +- State: the list of picks (`steps`). The current node, the transcript and the tally are derived from it. +- Rules: `pickChoice` adds a pick (ignored at an ending or for a bad index). `backOneStep` removes the last pick. `tallyReplies` counts strong, okay and weak replies. `matchChoice(said, choices)` scores each reply by word overlap (Dice score on content words, filler and plural s dropped) and returns null below 0.34 or when the top two are within 0.1. +- `checkRolePlay` reports: unknown start, unknown `next`, dead ends, nodes with both choices and an ending, wrong choice counts, repeated choice text, unreachable nodes, nodes with no path to an ending, and a script with no ending. (Node ids are map keys, so YAML itself rejects a repeated id.) +- Limitations: a fixed script. Real people do not answer from three lines. Voice matching is word overlap, not meaning. + +## Rendering +- HTML, not SVG: chat bubbles must wrap long text on a 375 px phone. +- Header: initials, name, role, the learner's role. Optional goal line. +- Transcript (`role="log"`, scrolls, keyboard focusable): character bubbles left, learner bubbles right in the accent colour, each learner bubble followed by a tone chip ("Strong reply", "Okay", "Weak reply") and the feedback. +- Choices: full-width buttons under the transcript. +- Ending: a card with the verdict, summary, and a count of each reply tone. +- Controls row: "Back one step", "Try again" at the end, "Read aloud" toggle. + +## Voice +- "Read aloud" speaks each new character line with `speechSynthesis`. Hidden when not supported. Speech is cancelled when turned off and on unmount. +- "Answer by voice" uses `SpeechRecognition` or `webkitSpeechRecognition`. Hidden when not supported. It shows what it heard, then picks the closest reply or says that nothing matched well enough and asks the learner to tap. +- All speech APIs are detected in an effect after mount, so `renderToString` and the first client render show the plain chat. + +## Visualisation +Strong is green, okay is blue, weak is amber. Never red. Every tone has a text label. A losing ending is amber ("warn"). + +## Accessibility +Real buttons, at least 44 px. One `aria-live="polite"` line reads the tone, the feedback and the character's next line. Focus moves to the first reply after each pick. New bubbles fade in only under `motion-safe`; the log scroll is instant under reduced motion. + +## Acceptance criteria +- [x] Model tested (`frontend/tests/unit/canvas/role-play.test.ts`). +- [x] Reads at 375 px, light and dark (theme tokens only, no hex). +- [x] Server render works with no speech APIs. +- [ ] Voice tested by hand in Chrome and Safari (not done yet). + +## Build plan +Model `models/role-play.ts`, component `primitives/role-play.tsx`. Registration in `InteractiveCanvas` and `PORTABLE_CANVAS_RENDERERS` is done by the orchestrator. diff --git a/packages/learning-ui/src/canvas/primitives/role-play.tsx b/packages/learning-ui/src/canvas/primitives/role-play.tsx new file mode 100644 index 000000000..7aff24043 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/role-play.tsx @@ -0,0 +1,307 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { cn } from "../../lib/utils"; +import { BeatButton, BeatFrame } from "./beat-frame"; +import { useReducedMotion } from "./beat-parts"; +import { FOCUS_RING, TONES, type Tone } from "./tones"; +import { + TONE_LABEL, + backOneStep, + currentNode, + isRolePlayOver, + matchChoice, + pickChoice, + startRolePlay, + tallyReplies, + transcript, + type RolePlayData, + type RolePlayState, + type RolePlayTone, +} from "../models/role-play"; + +// A scripted conversation to practise: the character's lines on the left, the +// learner's picked replies on the right. After each pick a chip says how +// strong the reply was (amber for weak, never red) and why, then the +// character answers. Optional voice: the character's lines can be read +// aloud, and the learner can answer by speaking; the spoken words are matched +// to the closest reply. Every browser speech API is feature-detected after +// mount, so server rendering shows the plain chat. + +const CHOICE_TONE: Record = { good: "good", okay: "accent", weak: "warn" }; + +/** The parts of the Web Speech recognition API this canvas uses. Not in every TypeScript DOM lib, so typed here. */ +type Recognition = { + lang: string; + interimResults: boolean; + continuous: boolean; + maxAlternatives: number; + onresult: ((e: { resultIndex: number; results: ArrayLike & { isFinal: boolean }> }) => void) | null; + onerror: ((e: { error: string }) => void) | null; + onend: (() => void) | null; + start: () => void; + stop: () => void; + abort: () => void; +}; +type RecognitionCtor = new () => Recognition; + +function recognitionCtor(): RecognitionCtor | null { + if (typeof window === "undefined") return null; + const w = window as unknown as { SpeechRecognition?: RecognitionCtor; webkitSpeechRecognition?: RecognitionCtor }; + return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null; +} + +function initials(name: string): string { + return name + .split(/\s+/) + .filter(Boolean) + .slice(0, 2) + .map((p) => p[0]?.toUpperCase() ?? "") + .join(""); +} + +export function RolePlay(props: RolePlayData) { + const { title, limits, character, learnerRole, goal } = props; + const [state, setState] = useState(startRolePlay); + const [canSpeak, setCanSpeak] = useState(false); + const [canListen, setCanListen] = useState(false); + const [readAloud, setReadAloud] = useState(false); + const [listening, setListening] = useState(false); + const [voiceNote, setVoiceNote] = useState(""); + const reduced = useReducedMotion(); + const recRef = useRef(null); + const logRef = useRef(null); + const choicesRef = useRef(null); + const touched = useRef(false); + // Latest state for the recognition callbacks, which outlive a render. + const stateRef = useRef(state); + useEffect(() => { + stateRef.current = state; + }, [state]); + + const node = currentNode(props, state); + const over = isRolePlayOver(props, state); + const messages = transcript(props, state); + const lastLine = [...messages].reverse().find((m) => m.who === "character")?.text ?? ""; + const lastReply = [...messages].reverse().find((m) => m.who === "learner"); + + // Feature-detect speech after mount only, so the server and first client render match. + useEffect(() => { + setCanSpeak(typeof window !== "undefined" && "speechSynthesis" in window && typeof window.SpeechSynthesisUtterance === "function"); + setCanListen(recognitionCtor() !== null); + return () => { + if (typeof window !== "undefined" && "speechSynthesis" in window) window.speechSynthesis.cancel(); + recRef.current?.abort(); + recRef.current = null; + }; + }, []); + + // Read the character's newest line aloud when the toggle is on. + useEffect(() => { + if (!canSpeak || !readAloud || !lastLine) return; + const synth = window.speechSynthesis; + synth.cancel(); + const u = new window.SpeechSynthesisUtterance(lastLine); + const en = synth.getVoices().find((v) => /^en/i.test(v.lang)); + if (en) u.voice = en; + synth.speak(u); + }, [canSpeak, readAloud, lastLine]); + + // Keep the newest message in view, and the keyboard on the next action. + useEffect(() => { + const log = logRef.current; + if (log) log.scrollTo({ top: log.scrollHeight, behavior: reduced ? "auto" : "smooth" }); + if (touched.current) choicesRef.current?.querySelector("button")?.focus(); + }, [state, reduced]); + + const act = (next: RolePlayState) => { + touched.current = true; + setVoiceNote(""); + setState(next); + }; + + const toggleRead = () => { + if (readAloud && canSpeak) window.speechSynthesis.cancel(); + setReadAloud(!readAloud); + }; + + const listen = () => { + if (listening) { + recRef.current?.stop(); + return; + } + const Ctor = recognitionCtor(); + if (!Ctor) return; + if (canSpeak) window.speechSynthesis.cancel(); + const rec = new Ctor(); + rec.lang = "en-US"; + rec.interimResults = false; + rec.continuous = false; + rec.maxAlternatives = 1; + let heard = ""; + rec.onresult = (e) => { + for (let i = e.resultIndex; i < e.results.length; i++) heard += e.results[i][0]?.transcript ?? ""; + }; + rec.onerror = (e) => { + setVoiceNote(e.error === "not-allowed" ? "The microphone is blocked. Allow it in the browser, or tap a reply." : "Could not hear you. Try again, or tap a reply."); + }; + rec.onend = () => { + setListening(false); + recRef.current = null; + const said = heard.trim(); + if (!said) return; + const now = stateRef.current; + const choices = currentNode(props, now)?.choices ?? []; + const match = matchChoice(said, choices); + if (match.index === null) { + setVoiceNote(`You said: "${said}". No reply matched well enough. Tap the reply you meant.`); + return; + } + touched.current = true; + setVoiceNote(`You said: "${said}". Closest reply: "${choices[match.index].text}".`); + setState(pickChoice(props, now, match.index)); + }; + recRef.current = rec; + setVoiceNote("Listening. Say your reply, then stop."); + setListening(true); + try { + rec.start(); + } catch { + setListening(false); + recRef.current = null; + setVoiceNote("Could not start the microphone. Tap a reply instead."); + } + }; + + const tally = tallyReplies(props, state); + const live = over + ? `Conversation over. ${node?.ending?.verdict ?? ""}. ${tally.good} strong, ${tally.okay} okay, ${tally.weak} weak replies.` + : lastReply + ? `${TONE_LABEL[lastReply.tone]}. ${lastReply.feedback} ${character.name} says: ${lastLine}` + : `${character.name} says: ${lastLine}`; + + const fadeIn = "motion-safe:animate-in motion-safe:fade-in motion-safe:slide-in-from-bottom-1 motion-safe:duration-300"; + + return ( + + {state.steps.length > 0 ? act(backOneStep(state))}>Back one step : null} + {over ? act(startRolePlay())}>Try again : null} + {canSpeak ? ( + + {readAloud ? "Read aloud: on" : "Read aloud: off"} + + ) : null} + + } + > +
+
+ + {initials(character.name)} + +
+

{character.name}

+

{character.role}

+
+

{learnerRole}

+
+ {goal ? ( +

+ Your goal: + {goal} +

+ ) : null} + +
+ {messages.map((m, i) => + m.who === "character" ? ( +
0 && fadeIn)}> + {character.name} +

{m.text}

+
+ ) : ( +
+ You +

{m.text}

+

+ {TONE_LABEL[m.tone]}. + {m.feedback} +

+
+ ) + )} +
+ + {over && node?.ending ? ( +
+

Conversation over

+

{node.ending.verdict}

+

{node.ending.summary}

+
    + {(["good", "okay", "weak"] as const).map((t) => ( +
  • + {TONE_LABEL[t]}: {tally[t]} +
  • + ))} +
+
+ ) : null} + + {!over && node?.choices ? ( +
+

Your reply

+ {node.choices.map((c, i) => ( + + ))} + {canListen ? ( + + ) : null} + {voiceNote ?

{voiceNote}

: null} +
+ ) : null} +
+

+ {voiceNote ? `${voiceNote} ` : ""} + {live} +

+
+ ); +} diff --git a/packages/learning-ui/src/canvas/primitives/scale-picker.spec.md b/packages/learning-ui/src/canvas/primitives/scale-picker.spec.md new file mode 100644 index 000000000..626a0c3f5 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/scale-picker.spec.md @@ -0,0 +1,61 @@ +--- +artifact: canvas-spec +course: shared +chapter: shared primitive +slug: scale-picker +version: 1 +owner: interactive-canvas-builder +--- + +# Canvas spec: Scale picker + +## Teaching claim +The right amount of something (effort, detail, politeness) depends on the situation. Seeing each level side by side, with its likely result, makes the choice obvious. + +## Why a canvas +Prose can list the levels, but the learner only feels the difference when they tap from one level to the next and see the example and its result change in place. + +## Data (```canvas fence, `renderer: scale-picker`) +- `title`, `purpose` (optional), `limits`. +- `ends: [left, right]`, at most 24 characters each. +- `frame?`: label over the example panel ("Your message"). `code?`: true shows the example in a monospace panel. +- `keys?: { good?, weak?, bad? }`: legend words for the marks. Without keys, a default legend is shown for the mark kinds used. +- `note?`: one small line under the picture. +- `points` (3 to 7): `label` (18), `text` (320, may hold `[[good:words]]`, `[[weak:words]]`, `[[bad:words]]`), `result` (160), `mood: good | weak | bad`. +- `situations` (1 to 6): `label?` (40), `prompt` (220), `best: [point indexes from 0]`, `why` (260). + +```canvas +renderer: scale-picker +title: Message tone +limits: Two situations only. Real readers vary. +ends: [More blunt, More polite] +frame: Your message +keys: { good: Clear ask, weak: Hedging, bad: Harsh } +points: + - { label: Blunt, text: "[[bad:Release is late. Not my problem.]]", result: They feel blamed., mood: bad } + - { label: Direct, text: "The release moves to Thursday. [[good:Can you tell the client?]]", result: Fast and clear., mood: good } + - { label: Over-polite, text: "[[weak:So sorry to bother you,]] there might be a delay?", result: They are not sure what to do., mood: weak } +situations: + - { label: To a teammate, prompt: Your teammate needs to know the release is late. How do you say it?, best: [1], why: A teammate wants the facts and the ask. } +``` + +## Model (`models/scale-picker.ts`) +- State: `point` (looked at), `situation`, `chosen`, `picks` (first choice per situation). +- `explorePoint` clamps to the scale. `choosePoint` records the looked-at point once per situation. `nextSituation` moves on only after a choice and resets the view to the first point. `scaleTally` counts first picks that fit. +- `towardEnd` names the end to move toward after a pick that does not fit. `parseMarks` splits marked text; unknown marks stay plain. +- `checkScalePicker` reports counts, best indexes out of range or repeated, a best list that covers every point, broken marks, duplicate labels and text over the limits. + +## Rendering +HTML inside `BeatFrame`: situation prompt, the scale (a radiogroup of dots on a line, ends under it), the example panel with marked words, "What happens" with a mood icon and word, the legend, then feedback. After a choice the best zone gets a dashed green outline and "Best" / "Your pick" tags. The end view lists each situation with the pick. + +## Visualisation +Accent blue for the looked-at point. Good fit is green; a pick that does not fit is amber with "Not quite. Move toward ...", never red. Marks have a background and a distinct underline style (solid, dashed, wavy) plus a legend, so colour is never the only signal. The red mark is only for example content marked `bad`, never for the learner's answer. + +## Accessibility +Points are real buttons with `role="radio"`, roving tabindex, arrow keys, Home and End. All targets are at least 44 px. An `aria-live="polite"` line reads the example and result when a point changes, and the feedback after a choice. Focus moves to the next action after Choose, Next and Again. The dot scale transition is off under `prefers-reduced-motion`. + +## Acceptance criteria +- [x] Model tested (`frontend/tests/unit/canvas/scale-picker.test.ts`). +- [x] Reads at 375 px; 7 short labels fit (labels wrap). +- [x] Light and dark through app tokens. +- [ ] Registration in `portable.ts` and `InteractiveCanvas.tsx` (done by the orchestrator). diff --git a/packages/learning-ui/src/canvas/primitives/scale-picker.tsx b/packages/learning-ui/src/canvas/primitives/scale-picker.tsx new file mode 100644 index 000000000..27e488037 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/scale-picker.tsx @@ -0,0 +1,291 @@ +"use client"; + +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { CircleCheck, CircleX, TriangleAlert } from "lucide-react"; +import { cn } from "../../lib/utils"; +import { BeatButton, BeatFrame } from "./beat-frame"; +import { useReducedMotion } from "./beat-parts"; +import { FOCUS_RING } from "./tones"; +import { + bestLabels, + bestZone, + choosePoint, + explorePoint, + fitsSituation, + isScaleDone, + nextSituation, + parseMarks, + plainText, + scaleTally, + startScale, + towardEnd, + type ScaleMood, + type ScalePickerData, + type ScaleState, +} from "../models/scale-picker"; + +// A guided scale: a row of points between two ends. The learner taps a point +// and reads an example at that level and what likely happens. For each +// situation they choose the point that fits; the scale then shades the best +// zone and tags "Your pick" and "Best". A pick that does not fit is amber, +// never red, and says which way to move. A tally closes the round. + +/** Highlight for marked words. Each kind has its own underline style, so colour is not the only signal. */ +const MARK_CLASS: Record = { + good: "bg-emerald-100 decoration-emerald-600 decoration-solid dark:bg-emerald-500/20 dark:decoration-emerald-400", + weak: "bg-amber-100 decoration-amber-600 decoration-dashed dark:bg-amber-500/20 dark:decoration-amber-400", + bad: "bg-red-100 decoration-red-600 decoration-wavy dark:bg-red-500/20 dark:decoration-red-400", +}; +const MARK_BASE = "rounded-sm px-0.5 text-inherit underline decoration-2 underline-offset-4"; + +const MOOD = { + good: { Icon: CircleCheck, word: "Works well", icon: "text-emerald-700 dark:text-emerald-300" }, + weak: { Icon: TriangleAlert, word: "Weak", icon: "text-amber-700 dark:text-amber-300" }, + bad: { Icon: CircleX, word: "Poor", icon: "text-red-700 dark:text-red-300" }, +} as const; + +const DEFAULT_KEYS: Record = { good: "Works", weak: "Weak", bad: "Poor" }; + +function Marked({ text }: { text: string }) { + return ( + <> + {parseMarks(text).map((seg, i) => + seg.mark ? ( + + {seg.text} + + ) : ( + {seg.text} + ) + )} + + ); +} + +export function ScalePicker({ title, limits, ends, frame, code, keys, note, points, situations }: ScalePickerData) { + const [state, setState] = useState(startScale); + const reduced = useReducedMotion(); + const pointRefs = useRef<(HTMLButtonElement | null)[]>([]); + const controls = useRef(null); + const moved = useRef<"point" | "control" | null>(null); + + // After a button press the pressed button may go away; keep focus on the next action. + useEffect(() => { + if (moved.current === "control") controls.current?.querySelector("button")?.focus(); + else if (moved.current === "point") pointRefs.current[state.point]?.focus(); + moved.current = null; + }, [state]); + + const n = points.length; + const total = situations.length; + const done = isScaleDone(state, situations); + const sit = done ? null : situations[state.situation]; + const chosen = state.chosen; + const point = points[state.point]; + const fits = sit !== null && chosen !== null && fitsSituation(sit, chosen); + const legend = keys ? (["good", "weak", "bad"] as const).filter((k) => keys[k]) : []; + const usedMarks = new Set(points.flatMap((p) => parseMarks(p.text).map((s) => s.mark).filter(Boolean))); + + const look = (i: number) => { + moved.current = "point"; + setState((s) => explorePoint(s, i, n)); + }; + const act = (next: ScaleState) => { + moved.current = "control"; + setState(next); + }; + + const onKey = (e: KeyboardEvent) => { + const keyMap: Record = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }; + if (e.key in keyMap) { + e.preventDefault(); + look(state.point + keyMap[e.key]); + } else if (e.key === "Home") { + e.preventDefault(); + look(0); + } else if (e.key === "End") { + e.preventDefault(); + look(n - 1); + } + }; + + const tally = scaleTally(state, situations); + let live: string; + if (done) live = `All situations done. ${tally} of ${total} picks fit on the first try.`; + else if (sit && chosen !== null) { + const toward = towardEnd(sit, chosen, ends); + live = fits + ? `You chose ${points[chosen].label}. Good fit. ${sit.why}` + : `You chose ${points[chosen].label}. Not quite.${toward ? ` Move toward ${toward}.` : ""} Best: ${bestLabels(sit, points)}. ${sit.why}`; + } else live = `${point.label}: ${plainText(point.text)} What happens: ${point.result}`; + + const zone = sit && chosen !== null ? bestZone(sit) : null; + const mood = MOOD[point.mood]; + const moodWord = keys?.[point.mood] ?? mood.word; + + return ( + + {done ? ( + act(startScale())}>Again + ) : chosen === null ? ( + act(choosePoint(state, situations))}>{`Choose "${point.label}"`} + ) : ( + act(nextSituation(state, situations))}>{state.situation === total - 1 ? "See the tally" : "Next situation"} + )} + + } + > +
+ {done ? ( +
+

All situations done

+

{`${tally} of ${total} picks fit on the first try`}

+
    + {situations.map((s, i) => { + const pick = state.picks[i]; + const ok = fitsSituation(s, pick); + const Icon = ok ? CircleCheck : TriangleAlert; + return ( +
  • + + + {s.label ?? `Situation ${i + 1}`}: + {ok ? `you chose ${points[pick]?.label}, a good fit.` : `you chose ${points[pick]?.label}. Best: ${bestLabels(s, points)}.`} + +
  • + ); + })} +
+
+ ) : ( + <> + {sit ? ( +
+

+ {`Situation ${state.situation + 1} of ${total}`} + {sit.label ? {sit.label} : null} +

+

{sit.prompt}

+
+ ) : null} + + {/* The scale: one radio per point, on a line between the two ends. */} +
+
+
+ {zone ? ( +
+ ) : null} +
+ {points.map((p, i) => { + const on = i === state.point; + const tag = chosen === null || !sit ? null : i === chosen ? "Your pick" : sit.best.includes(i) ? "Best" : null; + return ( + + ); + })} +
+
+
+ {`← ${ends[0]}`} + {`${ends[1]} →`} +
+
+ + {/* The example at the point being looked at, and what happens. */} +
+
+ {frame ?? "Example"} + {point.label} +
+
+ +
+
+ +

+ {`What happens (${moodWord}): `} + {point.result} +

+
+
+ + {legend.length > 0 || usedMarks.size > 0 ? ( +
+ {(["good", "weak", "bad"] as const) + .filter((k) => keys?.[k] || (!keys && usedMarks.has(k))) + .map((k) => ( + + {"Aa"} + {keys?.[k] ?? DEFAULT_KEYS[k]} + + ))} +
+ ) : null} + + {sit && chosen !== null ? ( +
+

+ {fits ? : } + {fits + ? "Good fit" + : (() => { + const toward = towardEnd(sit, chosen, ends); + return toward ? `Not quite. Move toward "${toward}"` : "Not quite"; + })()} +

+

{sit.why}

+ {!fits ?

{`The dashed zone shows the best ${sit.best.length > 1 ? "choices" : "choice"}: ${bestLabels(sit, points)}.`}

: null} +
+ ) : null} + + )} + {note ?

{note}

: null} +
+

{live}

+ + ); +} diff --git a/packages/learning-ui/src/canvas/primitives/self-check-cards.spec.md b/packages/learning-ui/src/canvas/primitives/self-check-cards.spec.md new file mode 100644 index 000000000..1c7743257 --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/self-check-cards.spec.md @@ -0,0 +1,43 @@ +--- +artifact: canvas-spec +course: shared +chapter: shared primitive +slug: self-check-cards +version: 1 +owner: interactive-canvas-builder +--- + +# Canvas spec: Self-check cards + +## Teaching claim +Trying to recall an answer before you see it makes it stick. Honest self-grading shows what to review. + +## Why a canvas +A list of questions and answers lets the eye skip to the answer. A card that hides the answer until you flip makes the learner try first, and the "Not yet" pile gives a short review round. + +## Model +- Inputs: `cards` (2 to 20, each `id`, `front`, `back`, optional `hint`), optional `deckLabel`. +- State: `queue` (card ids this round), `index`, `revealed`, `known`, `notYet`, `round`. +- Rules: `revealCard` flips the current card. `gradeCard(state, knew)` works only after the flip, records the card and moves on. `reviewNotYet` starts a new round with only the "not yet" cards, once the round is done. `startSelfCheck` starts over with every card. +- `checkSelfCheckCards` reports the card count, duplicate ids, empty text, and a front that equals its back. +- Limitations: self-grading trusts the learner. No spacing over days. + +## Rendering +- HTML card, so any text length wraps. Header: deck label (or "Review round n") and "Card n of N", with a thin progress bar. +- Front: the question, the hint when opened. Back: the question small, then the answer. +- End: "You knew X of N" and how many are not yet there. +- Controls: "Show answer" (and "Show hint" when there is one), then "I knew it" and "Not yet", then "Review the N not yet cards" and "Start over". + +## Motion +The card squashes to an edge (180 ms), swaps face, and opens. Under `prefers-reduced-motion` the face swaps at once. + +## Accessibility +Real 44 px buttons. Focus moves to the next action after each press. An `aria-live="polite"` line reads the card, the answer, or the round result. The border colour change on the back is backed by the "Answer" label. + +## Acceptance criteria +- [x] Model tested (`frontend/tests/unit/canvas/self-check-cards.test.ts`). +- [x] Reads at 375 px, light and dark. +- [x] Reduced motion handled. + +## Build plan +Model `models/self-check-cards.ts`, component `primitives/self-check-cards.tsx`. Registration is done by the orchestrator. diff --git a/packages/learning-ui/src/canvas/primitives/self-check-cards.tsx b/packages/learning-ui/src/canvas/primitives/self-check-cards.tsx new file mode 100644 index 000000000..22fa0b10e --- /dev/null +++ b/packages/learning-ui/src/canvas/primitives/self-check-cards.tsx @@ -0,0 +1,181 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { cn } from "../../lib/utils"; +import { BeatButton, BeatFrame } from "./beat-frame"; +import { useReducedMotion } from "./beat-parts"; +import { TONES } from "./tones"; +import { + currentCardId, + gradeCard, + isRoundDone, + revealCard, + reviewNotYet, + startSelfCheck, + type SelfCheckCardsData, + type SelfCheckState, +} from "../models/self-check-cards"; + +// Flash cards the learner grades on their own: read the front, recall the +// answer, flip, then say "I knew it" or "Not yet". At the end of a round the +// "not yet" cards can run again by themselves. The flip squashes the card to +// an edge and opens it on the other face; under reduced motion it swaps at once. + +const FLIP_MS = 180; + +export function SelfCheckCards({ title, limits, cards, deckLabel }: SelfCheckCardsData) { + const [state, setState] = useState(() => startSelfCheck(cards)); + // What the card shows. It follows `state` once the card has narrowed to an edge, so the face swaps while it is thin. + const [shown, setShown] = useState(state); + const [thin, setThin] = useState(false); + const [hintOpen, setHintOpen] = useState(false); + const reduced = useReducedMotion(); + const controls = useRef(null); + const touched = useRef(false); + + useEffect(() => { + if (shown === state) return; + if (reduced) { + setShown(state); + return; + } + setThin(true); + const t = setTimeout(() => { + setShown(state); + setThin(false); + }, FLIP_MS); + return () => clearTimeout(t); + }, [state, shown, reduced]); + + // The pressed button goes away; keep keyboard focus on the next action. + useEffect(() => { + if (touched.current) controls.current?.querySelector("button")?.focus(); + }, [state]); + + const act = (next: SelfCheckState) => { + touched.current = true; + setHintOpen(false); + setState(next); + }; + + const byId = (id: string | null) => cards.find((c) => c.id === id); + const done = isRoundDone(state); + const card = byId(currentCardId(state)); + const n = state.queue.length; + + const sDone = isRoundDone(shown); + const sCard = byId(currentCardId(shown)); + const sN = shown.queue.length; + const allKnown = sDone && shown.known.length === sN; + const reviewLabel = shown.round > 1 ? `Review round ${shown.round - 1}` : (deckLabel ?? "Self-check"); + + const live = done + ? `Round finished. You knew ${state.known.length} of ${n}.${state.notYet.length ? ` ${state.notYet.length} not yet.` : ""}` + : state.revealed && card + ? `Answer: ${card.back}. Did you know it?` + : card + ? `Card ${state.index + 1} of ${n}: ${card.front}` + : ""; + + let face; + if (sDone) { + face = ( +
+

Round finished

+

+ You knew {shown.known.length} of {sN} +

+

+ {allKnown ? "Every card in this round. Good recall." : `${shown.notYet.length} ${shown.notYet.length === 1 ? "card is" : "cards are"} not yet there. Review them while they are fresh.`} +

+
+ ); + } else if (sCard && !shown.revealed) { + face = ( + <> +

{sCard.front}

+ {sCard.hint && hintOpen ? ( +

+ Hint: + {sCard.hint} +

+ ) : null} +

Say the answer to yourself, then flip.

+ + ); + } else if (sCard) { + face = ( + <> +

{sCard.front}

+

Answer

+

{sCard.back}

+

Be honest. Not yet is useful.

+ + ); + } + + const notYetCount = state.notYet.length; + return ( + + {done ? ( + <> + {notYetCount > 0 ? ( + act(reviewNotYet(state))}>{`Review the ${notYetCount} not yet ${notYetCount === 1 ? "card" : "cards"}`} + ) : null} + act(startSelfCheck(cards))}>Start over + + ) : state.revealed ? ( + <> + act(gradeCard(state, true))}>I knew it + act(gradeCard(state, false))}>Not yet + + ) : ( + <> + act(revealCard(state))}>Show answer + {card?.hint ? ( + setHintOpen(!hintOpen)}>{hintOpen ? "Hide hint" : "Show hint"} + ) : null} + + )} +
+ } + > +
+
+ {reviewLabel} + {!sDone ? ( + + Card {shown.index + 1} of {sN} + + ) : null} +
+ {!sDone ? ( +
+
+
+ ) : null} +
+
+ {face} +
+
+
+

+ {live} +

+ + ); +} diff --git a/server/src/shared/mdx/canvas-tags.ts b/server/src/shared/mdx/canvas-tags.ts index 111a26714..c1a6d5ab0 100644 --- a/server/src/shared/mdx/canvas-tags.ts +++ b/server/src/shared/mdx/canvas-tags.ts @@ -28,6 +28,14 @@ export const PORTABLE_CANVAS_RENDERER_NAMES = [ "phrase-fixer", "budget-stack", "slot-card", + "chart", + "scale-picker", + "guess-reveal", + "log-explorer", + "command-explainer", + "role-play", + "self-check-cards", + "architecture", ] as const; export function isPortableCanvasRendererName(value: unknown): boolean { diff --git a/server/tests/unit/shared/mdx/canvas-tags.test.ts b/server/tests/unit/shared/mdx/canvas-tags.test.ts index 045149198..2d3dc7858 100644 --- a/server/tests/unit/shared/mdx/canvas-tags.test.ts +++ b/server/tests/unit/shared/mdx/canvas-tags.test.ts @@ -25,6 +25,19 @@ describe("collectCanvasProblems", () => { expect(problems).toEqual([expect.stringMatching(/takes no children/)]); }); + it("accepts the general-purpose renderers in a canvas fence", () => { + const names = ["chart", "scale-picker", "guess-reveal", "log-explorer", "command-explainer", "role-play", "self-check-cards", "architecture"]; + for (const name of names) { + const fence = "```canvas\nrenderer: " + name + "\ntitle: Example\nlimits: A small example.\n```\n"; + expect(collectCanvasProblems(fence), name).toEqual([]); + } + }); + + it("rejects a general-purpose renderer fence with no limits", () => { + const problems = collectCanvasProblems("```canvas\nrenderer: architecture\ntitle: Example\n```\n"); + expect(problems).toEqual([expect.stringMatching(/limits/)]); + }); + it("ignores chapters without canvases", () => { expect(collectCanvasProblems("Hi")).toEqual([]); });