Interactive blocks
Reference for data-only fences that render as interactive lesson widgets
Interactive blocks
Lessons can include interactive widgets through fenced code blocks and callout blockquotes. All blocks are data-only: you write JSON or markdown, and LearnOS owns the markup and behavior. This keeps lesson content portable and secure — no raw HTML, no script injection.
| Block | Syntax | What it renders |
|---|---|---|
| Generative UI | ```ui | Checkpoint questions, worked examples, choice reveals, re-explain cards, citation chips |
| Quiz | ```quiz | A graded knowledge check; misses go to the learner's review deck |
| Chart | ```chart | Bar, stacked-bar, line, area, or donut chart with a data table |
| Callouts | > [!TYPE] | Note, tip, definition, important, takeaway, warning, caution, commands, and data callouts; aside types can fold |
| Mermaid | ```mermaid | Flowcharts, sequence diagrams, and other Mermaid diagrams |
| Runnable code | ```js-run ```ts-run ```py-run | An editable snippet with a Run button and output pane |
Where a block renders depends on the surface:
| Surface | ui, quiz, chart | Callouts | Mermaid, runnable code |
|---|---|---|---|
| Lessons, review guide sections, presentation slides, citation-rail previews | ✓ | ✓ | ✓ |
| Chat answers (including review chat and review model answers) | plain code block | plain blockquote | ✓ |
| Blog posts | plain code block | plain blockquote | ✓ |
The Preview panes on this page are the one docs exception. They run the lesson renderer so you can see each block as learners do. Other docs pages show fences as code.
The examples below share one running scenario, a lesson on web sessions and HTTP, so you can see how the blocks work together. Each one opens on Preview, which is the real lesson renderer, so you can click through quizzes, tabs, and runnable code. Switch to Code for the markdown to paste into a lesson.
Security model
Authors emit JSON; LearnOS owns markup. Every spec passes through a strict Zod schema before rendering. Invalid or unknown specs render nothing (with a dev-only console error).
ui,quiz, andchartblocks reject any text field that contains an HTML tag at parse time (the same rule as generative UI).- Quiz prompts and options also allow inline
`code`. The check treats any<followed by a letter,/, or!as a tag, even inside inline code, so`<p>`,`Promise<void>`, anda<bare rejected. Comparisons with a space or a digit after the<, likea < bor2<3, are fine. To quiz on HTML or generics, name the element in words ("the paragraph element") or writePromise of void.
Generative UI components
Generative UI blocks use the ```ui fence. Each one names a component and
carries 1–8 citations that ground it in course content (see
Common fields). Citation chips that point back to the lesson
the learner is already reading are hidden.
checkpoint-question
An inline comprehension check with confidence calibration. Renders radio options and a confidence slider. After Check, it marks the learner's pick, reveals the correct answer, and shows the explanation alongside the confidence they reported.
```ui
{
"spec_version": 1,
"component": "checkpoint-question",
"citations": [
{
"id": "cookie-sessions",
"lesson_id": "550e8400-e29b-41d4-a716-446655440000",
"anchor": "cookie-sessions",
"label": "L3#cookie-sessions",
"title": "Cookie-based sessions",
"excerpt": "Store the session in an HttpOnly, Secure, SameSite=Lax cookie. The browser attaches it to every request, and no script on the page can read it."
},
{
"id": "xss-basics",
"lesson_id": "550e8400-e29b-41d4-a716-446655440001",
"anchor": "xss-basics",
"label": "L2#xss-basics",
"title": "XSS basics",
"excerpt": "Cross-site scripting runs an attacker's script in your page, with access to everything your own scripts can read."
}
],
"props": {
"id": "check-session-storage",
"title": "Quick check",
"prompt": "Where should a web app keep its session token?",
"options": [
{ "text": "localStorage" },
{ "text": "sessionStorage" },
{ "text": "An HttpOnly, Secure cookie" },
{ "text": "A query-string parameter" }
],
"correct_index": 2,
"explanation": "Any script on the page can read localStorage, so one XSS bug leaks the session. An HttpOnly cookie is sent with each request but is invisible to JavaScript.",
"initial_confidence": 50
}
}
```| Prop | Type | Required | Description |
|---|---|---|---|
id | slug | yes | Stable identifier for this question |
title | string | yes | Card header (max 120 chars) |
prompt | string | yes | The question (max 600 chars) |
options | array | yes | 2-6 answer choices, each with text |
correct_index | int | yes | 0-based index of the correct option |
explanation | string | yes | Shown after checking (max 1200 chars) |
initial_confidence | int | no | Default confidence % (0-100, default 50) |
worked-example
A step-by-step walkthrough with prev/next navigation. Shows one step at a time,
with dots that jump to any step. On the last step, Next is disabled and the
optional why_it_matters panel appears.
```ui
{
"spec_version": 1,
"component": "worked-example",
"citations": [
{
"id": "session-refresh",
"lesson_id": "550e8400-e29b-41d4-a716-446655440002",
"anchor": "session-refresh",
"label": "L4#session-refresh",
"title": "Refreshing the session",
"excerpt": "Refresh the session on every request so server components never read an expired token."
}
],
"props": {
"title": "Setting up cookie auth",
"steps": [
{
"title": "Install the SDK",
"body": "Run: npm install @supabase/ssr @supabase/supabase-js"
},
{
"title": "Create the client",
"body": "Add a createClient() helper that reads the project URL and publishable key from environment variables and stores the session in cookies."
},
{
"title": "Refresh the session in the proxy",
"body": "Call updateSession() from proxy.ts on every request. It reads the cookie, refreshes the token if it is close to expiry, and writes the new cookie on the response."
}
],
"why_it_matters": "Cookie sessions keep the token out of JavaScript, and refreshing in the proxy means server components never see an expired session."
}
}
```| Prop | Type | Required | Description |
|---|---|---|---|
title | string | yes | Card header (max 120 chars) |
steps | array | yes | 2-12 steps, each with title and body |
steps[].title | string | yes | Step title (max 120 chars) |
steps[].body | string | yes | Step content (max 2000 chars) |
why_it_matters | string | no | Summary shown on the last step (max 600 chars) |
choice-reveal
A tabbed interface where tapping an option reveals its panel, and tapping it again collapses it. Arrow keys, Home, and End move between tabs. Good for comparisons or "choose your path" scenarios.
```ui
{
"spec_version": 1,
"component": "choice-reveal",
"citations": [
{
"id": "api-styles",
"lesson_id": "550e8400-e29b-41d4-a716-446655440003",
"anchor": "api-styles",
"label": "L5#api-styles",
"title": "Choosing an API style",
"excerpt": "The choice depends on your data shape, your clients, and how much you lean on HTTP caching."
}
],
"props": {
"options": [
{
"label": "REST",
"title": "REST API",
"body": "Resource-oriented endpoints over plain HTTP verbs. Easy to cache at the CDN, but clients often over-fetch or need several round-trips."
},
{
"label": "GraphQL",
"title": "GraphQL",
"body": "One endpoint and a typed query language. Clients ask for exactly the fields they need, at the cost of harder HTTP caching."
},
{
"label": "tRPC",
"title": "tRPC",
"body": "Type-safe procedure calls shared between a TypeScript server and client. No schema step, but both sides must be TypeScript."
}
],
"default_index": 0
}
}
```| Prop | Type | Required | Description |
|---|---|---|---|
options | array | yes | 2-6 options, each with label, title, body |
options[].label | string | yes | Tab button text (max 80 chars) |
options[].title | string | yes | Panel heading (max 120 chars) |
options[].body | string | yes | Panel content (max 2000 chars) |
default_index | int | no | 0-based index of initially revealed option |
re-explain-card
Shows an alternative explanation when a learner struggles with a concept. The header names the persona and format it is tuned for, and the card quotes the learner's answer next to the misconception it addresses. Still unclear and Got it, retry let the learner respond.
```ui
{
"spec_version": 1,
"component": "re-explain-card",
"citations": [
{
"id": "idempotency",
"lesson_id": "550e8400-e29b-41d4-a716-446655440004",
"anchor": "idempotency",
"label": "L6#idempotency",
"title": "Idempotent methods",
"excerpt": "PUT replaces the target resource with the request body, so repeating it leaves the server in the same state. POST does not make that promise."
}
],
"props": {
"title": "Let's try another angle",
"persona": "visual learner",
"format": "analogy",
"explanation": "Think of PUT as replacing a whole page in a binder: you hand over the complete page, and the old one goes in the bin. POST is dropping a new page into the binder's inbox tray. Someone else decides where it goes, and dropping it twice gives you two pages.",
"previous_answer": "POST and PUT both update a record, so they're interchangeable.",
"misconception": "post-vs-put"
}
}
```| Prop | Type | Required | Description |
|---|---|---|---|
title | string | yes | Card header (max 120 chars) |
persona | string | yes | Target learner type (max 80 chars) |
format | enum | yes | analogy, plain-language, or worked-example |
explanation | string | yes | The alternative explanation (max 4000 chars) |
previous_answer | string | yes | What the learner said (max 600 chars) |
misconception | string | yes | Short label for the misconception (max 160 chars) |
citation-chip
A standalone inline citation. Clicking the chip opens a popover with the section title, the cited excerpt, the anchor, and an Open section link. Every component above renders the same chip for each of its citations; use this component to place one on its own.
```ui
{
"spec_version": 1,
"component": "citation-chip",
"citations": [
{
"id": "cookie-sessions",
"lesson_id": "550e8400-e29b-41d4-a716-446655440000",
"anchor": "cookie-sessions",
"label": "L3#cookie-sessions",
"title": "Cookie-based sessions",
"excerpt": "Store the session in an HttpOnly, Secure, SameSite=Lax cookie. The browser attaches it to every request, and no script on the page can read it."
}
],
"props": {
"citation_id": "cookie-sessions"
}
}
```| Prop | Type | Required | Description |
|---|---|---|---|
citation_id | slug | yes | The id of one of this spec's citations |
Common fields
All generative UI components share these top-level fields:
| Field | Type | Required | Description |
|---|---|---|---|
spec_version | literal 1 | yes | Schema version (always 1 for now) |
component | string | yes | Component name from the registry |
citations | array | yes | 1-8 source citations for grounding |
Each citation object:
| Field | Type | Required | Description |
|---|---|---|---|
id | slug | yes | Unique within this spec (used by citation_id) |
lesson_id | uuid | yes | The lesson containing the source |
anchor | slug | yes | Heading anchor within the lesson |
label | string | yes | Display label like L3#tools-call |
title | string | yes | Heading text (max 200 chars) |
excerpt | string | yes | Quoted source text (max 2000 chars) |
Citation title and excerpt are author-attested: the schema checks length and
rejects HTML, but does not verify that the excerpt matches the live lesson section.
Grounding is enforced by author review (and by adaptive flows that resolve chunks
server-side when they exist).
Core blocks
Quiz
A graded knowledge check. A question with one correct option renders as single
choice; a question with more than one correct option becomes multi-select ("select
all that apply"). After Check answer, each picked option shows its why, and
the question's explanation appears below. When a signed-in learner misses a
question, it is saved to their review deck as a flashcard. The card is rebuilt
from the stored lesson, never from what the browser sends.
```quiz
{
"id": "http-methods-check",
"title": "Check your understanding",
"questions": [
{
"prompt": "Which HTTP method is idempotent?",
"options": [
{ "text": "POST", "correct": false, "why": "Sending the same POST twice can create two records." },
{ "text": "PUT", "correct": true, "why": "Repeating a PUT leaves the resource in the same state." },
{ "text": "PATCH", "correct": false }
],
"explanation": "PUT replaces the resource with the body you send, so repeating it leaves the server in the same state."
},
{
"prompt": "Which of these responses can a CDN cache by default?",
"options": [
{ "text": "GET 200 with `Cache-Control: public`", "correct": true },
{ "text": "POST 201 Created", "correct": false },
{ "text": "GET 404 Not Found", "correct": true, "why": "404 is cacheable by default, so CDNs may hold it briefly." }
]
}
]
}
```| Field | Type | Required | Description |
|---|---|---|---|
id | slug | yes | Stable per-lesson id: lowercase letters, digits, and hyphens, starting with a letter or digit (2-61 chars). Keep it unchanged after publishing; review-deck cards point at it |
title | string | no | Card header (max 80 chars). Hidden when it repeats the heading just above the quiz |
questions | array | yes | 1-5 questions |
questions[].prompt | string | yes | The question (max 400 chars). Inline `code` is allowed |
questions[].options | array | yes | 2-6 options; at least one must be correct |
options[].text | string | yes | Option text (max 200 chars) |
options[].correct | boolean | no | Defaults to false |
options[].why | string | no | Shown under the option after checking (max 300 chars) |
questions[].explanation | string | no | Shown after checking (max 600 chars) |
Chart
A data chart with a View data toggle that shows the numbers as a table. Colors come from a fixed five-slot palette that is safe for color-vision deficiencies. You cannot set colors, and series keys never reach the page's CSS.
```chart
{
"type": "bar",
"title": "Study minutes per week",
"x": "week",
"series": [
{ "key": "reading", "label": "Reading" },
{ "key": "practice", "label": "Practice" }
],
"data": [
{ "week": "Wk 1", "reading": 90, "practice": 20 },
{ "week": "Wk 2", "reading": 85, "practice": 35 },
{ "week": "Wk 3", "reading": 70, "practice": 55 },
{ "week": "Wk 4", "reading": 60, "practice": 80 },
{ "week": "Wk 5", "reading": 50, "practice": 95 },
{ "week": "Wk 6", "reading": 45, "practice": 110 }
],
"format": "number",
"yLabel": "Minutes",
"caption": "Practice time overtakes reading once the runnable exercises start in week 4."
}
```
| Week | Reading (min) | Practice (min) |
|------|--------------:|---------------:|
| Wk 1 | 90 | 20 |
| Wk 2 | 85 | 35 |
| Wk 3 | 70 | 55 |
| Wk 4 | 60 | 80 |
| Wk 5 | 50 | 95 |
| Wk 6 | 45 | 110 || Field | Type | Required | Description |
|---|---|---|---|
type | enum | yes | bar, stacked-bar, line, area, or donut |
title | string | yes | Figure caption (max 80 chars) |
x | string | yes | Key of the category field in each data row (1-40 chars; slice name for donut) |
series | array | yes | 1-5 series, each with key (1-40 chars) and label. A donut takes exactly one |
data | array | yes | 1-60 rows. Each value is a number or null; a donut has at most 5 slices |
format | enum | no | number (default), usd, usd-compact, or percent (values already 0-100) |
yLabel | string | no | Y-axis label for cartesian charts (max 60 chars) |
caption | string | no | Note under the chart (max 300 chars) |
Put a markdown table with the same numbers next to the chart, as in the example
above. Chat and search read
lesson text, not chart JSON, so without the table the tutor can't quote the figures.
pnpm validate-blocks warns when a chart has no table nearby.
Callouts
Callouts are blockquotes with a GitHub-style marker. The text after the marker on
the first line becomes an optional title. NOTE through CAUTION also render as
alerts on GitHub; DEFINITION, TAKEAWAY and COMMANDS are LearnOS additions.
> [!NOTE]
> Browsers cap cookies at roughly 4 KB each, so keep session payloads small.
> [!TIP]
> Open DevTools › Application › Cookies to watch the session refresh live.
> [!DEFINITION] Idempotent
> An operation that gives the same result whether you run it once or many times.
> [!IMPORTANT]
> Never send the service-role key to the browser. It bypasses every RLS policy.
> [!TAKEAWAY]
> Keep the session in an HttpOnly cookie, and refresh it on every request.
> [!WARNING]
> SameSite=None cookies need the Secure flag, or the browser drops them silently.
> [!CAUTION]
> Running this migration drops the legacy table. Back it up first.The eight types share three visual styles:
| Style | Types | Label | Use it for |
|---|---|---|---|
| Aside | NOTE, TIP, DEFINITION, COMMANDS | Note, Tip, Definition, Show the commands | Supporting detail the reader can skip |
| Emphasis | IMPORTANT, TAKEAWAY | Important, Key takeaway | The points the lesson is about |
| Alert | WARNING, CAUTION | Watch out, Caution | Mistakes with real consequences |
Two data callouts use an emoji lead-in instead of a marker. Start the blockquote with 📌 for a snapshot of real figures, or 📊 for a slot telling the learner what to look up:
> 📌 **Snapshot:** RFC 6265 asks browsers to support at least 4,096 bytes per cookie and 50 cookies per domain.
> 📊 **Look it up:** what share of your own app's cookies are missing the Secure flag?Only put verified figures with a source in a 📌 snapshot.
Foldable callouts
Put - right after the marker to render a callout closed, with its label as the
toggle, or + to render it open but collapsible. Only the aside types fold:
NOTE, TIP, DEFINITION and COMMANDS. A fold marker on IMPORTANT,
TAKEAWAY, WARNING or CAUTION is ignored, so those always render open, and
validate-blocks warns about it. The
COMMANDS type exists for this: lead with the plain-language instruction or
agent prompt, and tuck the exact commands underneath for readers who want them.
Tell your agent: "Show me what would be committed, and confirm `.env.local` isn't in the list."
> [!COMMANDS]- Show the commands
> ```bash
> git status
> git add .
> git commit -m "First save point"
> ```Without a title, a COMMANDS callout is labelled "Show the commands". Every line
of the callout, including code fences, starts with > . Folded text is still part
of the lesson, so search, chat and quizzes can use it; don't fold anything the
reader must see to follow the lesson.
Mermaid
Any Mermaid diagram: flowcharts, sequence, class, and state diagrams. It renders client-side in Mermaid's default theme (its dark theme in dark mode). Clicking the diagram opens it full screen.
```mermaid
graph TD
A[Request] --> B["proxy.ts · updateSession()"]
B --> C{Token near expiry?}
C -->|Yes| D[Refresh + set cookie]
C -->|No| E[Render page]
```Quote labels that contain parentheses or other Mermaid syntax, as with node B
above. A diagram that fails to parse shows "Mermaid diagram failed to render" and
its source in place of the diagram.
Runnable code
A ```js-run, ```ts-run, or ```py-run fence becomes an editable snippet
with Run, Stop, and Reset controls. Output appears in a pane below the
editor. Each run is stopped after 5 seconds, so an infinite loop can't freeze the
lesson.
In js-run and ts-run, the snippet runs inside an async function: top-level
await works, and a top-level return value is shown after a ⟶.
[!WARNING]
ts-runis not transpiled. It runs as plain JavaScript, so TypeScript-only syntax such as type annotations (const n: number = 1) orinterfacedeclarations fails with a syntax error. Keepts-runsnippets to JavaScript-compatible code, or usejs-run. Objects and arrays are logged as indented JSON. Inpy-run, output comes fromprint(), and Python loads its runtime the first time a learner runs a snippet.
```js-run
const cookie = "session=abc123; HttpOnly; Secure";
const flags = cookie.split("; ").slice(1);
console.log("flags:", flags);
return flags.includes("HttpOnly");
```Running this logs the flags array, then shows ⟶ true.
Validation rules
ui,quiz, andcharttext fields reject HTML tags (<script>,<img>, etc.) at parse time- Citation IDs must be unique within a spec
citation_idincitation-chipmust reference an existing citationcorrect_index/default_indexmust be valid array indices- Every quiz question needs at least one correct option
- Every chart row needs the
xfield (a string or number); series values must be numbers ornull - Quiz
idmust be lowercase letters, digits, and hyphens, starting with a letter or digit - Steps/options arrays have min and max bounds (see individual components)
Invalid specs render nothing in production; in development, an error is logged to the console with the failing paths.
Check every block in a folder of lessons before importing it. The checker uses the renderer's own schemas:
pnpm validate-blocks <dir>