Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Release 0.3.0: the intelligent-ui skill (Typst references, recipes, check.sh); shorter prompt examples that point to it

razorback1638179b95dd9d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index d115ef5..4c77f69 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "cc-intelligent-ui",
- "version": "0.2.3",
+ "version": "0.3.0",
"description": "Draws Claude's answers as rendered Markdown pictures in the terminal, with live Typst for diagrams, charts and math",
"author": {
"name": "razorback16",
diff --git a/README.md b/README.md
index 42270b4..e19334e 100644
--- a/README.md
+++ b/README.md
@@ -48,7 +48,7 @@ In other terminals, the mod shows the normal text. Refer to [Install](docs/insta
- **Rendered Markdown.** Headings, tables, task lists, block quotes and code with syntax colours, in your terminal's own font.
- **LaTeX math.** Inline `$…$` and display `$$…$$` math, typeset.
-- **Live diagrams, charts and plots.** Claude writes Typst with CeTZ, cetz-plot and fletcher. The drawings use your theme's colours and work offline.
+- **Live diagrams, charts and plots.** Claude writes Typst with CeTZ, cetz-plot and fletcher. The drawings use your theme's colours and work offline. For a complex drawing, Claude loads the bundled `intelligent-ui` skill, with the full API and a compile check.
- **Images and files.** Images in an answer, images that Claude sends, Markdown files that Claude sends, and images that you paste show in the transcript.
- **Copy text from pictures.** In fullscreen mode, select and copy text with the mouse, as you do with normal text. On Linux, this needs a clipboard tool (refer to [Install](docs/install.md#linux)).
- **Links you can click.** The links, file paths and commands of an answer show in rows under its picture. A cmd+click on a link opens it. A click on a command copies it.
@@ -98,7 +98,7 @@ All commands are in [Usage](docs/usage.md).
## Docs
- [Install](docs/install.md): requirements, terminal support and updates
-- [Usage](docs/usage.md): what it draws, commands, copy, plan approval
+- [Usage](docs/usage.md): what it draws, the skill, commands, copy, plan approval
- [Themes](docs/themes.md): built-in themes and your own
- [How it works](docs/how-it-works.md): the render steps and light or dark mode
- [Limitations](docs/limitations.md): copy, search, timing and other limits
diff --git a/docs/development.md b/docs/development.md
index 173cf30..1d71c2f 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -23,6 +23,8 @@ Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines
The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.
+The skill for Claude is in `skills/intelligent-ui/`: `SKILL.md` (the contract, the workflow and an index), `references/` (one file for each topic: Typst, fletcher, CeTZ, plots and charts) and `scripts/check.sh` (the compile check, with the real template). `TYPST_PROMPT` in `hooks/lib/settings.ts` tells Claude when to load it.
+
The Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.
## Marketing images
diff --git a/docs/usage.md b/docs/usage.md
index c8dcc33..0150034 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -34,6 +34,14 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr
These pictures are not larger than the image. They are not wider than the transcript. The height setting (`/iui height`) sets the most rows that they can use (Typst drawings use it too): by default, half the screen and not more than 24 rows. The mod draws PNG, JPEG, WebP and SVG images only. Other image types (for example GIF) stay as the normal row. The size of an SVG image is its width and height in CSS px.
- The plan in plan mode (the ExitPlanMode tool). The mod draws the plan as a picture in the transcript, the same as an answer. Then the mod asks you to approve the plan. Refer to [Plan approval](#plan-approval).
+## The intelligent-ui skill
+
+The mod has a skill for Claude: `intelligent-ui`. It has the full API of Typst, fletcher, CeTZ and cetz-plot, recipes for many diagram and chart types, and a compile check. Claude loads it by itself before it writes a complex drawing, or after a drawing did not compile. For normal answers and simple drawings, Claude does not load it.
+
+The compile check (`scripts/check.sh` in the skill) compiles a drawing with the mod's template and your theme, in dark and light mode. It shows the errors and writes PNG images. Claude looks at the images and corrects the drawing before it answers.
+
+You can also start the skill yourself: type `/cc-intelligent-ui:intelligent-ui` (or `/intelligent-ui` when no other command has that name), and then ask for the drawing.
+
## Commands
| Command | What it does |
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index 28454a0..547b3f5 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -148,28 +148,27 @@ Each typst block compiles alone, with only \`theme\` in scope, so start it with
#import "@preview/cetz:0.5.2"
#import "@preview/cetz-plot:0.1.4": plot, chart
#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
-\`theme\` has: theme.fg, theme.muted, theme.link, theme.border, theme.accent, theme.bg, theme.code-bg, theme.red/green/blue/yellow/orange/purple, theme.palette (6 colours), theme.width (content width, a length), theme.height (the height a drawing should fit in, a length), theme.text-size, theme.sans and theme.mono (font lists), theme.dark (bool).
-Rules (the examples below follow them):
-- Size: fit theme.width × theme.height. A drawing taller than theme.height is not made smaller. The terminal is wide and short, so lay flows out left to right.
-- Colours: text already has theme.fg and the body font. Default strokes are black and invisible on a dark theme, so always pass theme colours as the examples do. Fill shapes with a theme colour \`.transparentize(80%)\`, colour data with theme.palette in order, and use theme.muted for secondary text.
-- fletcher makes no space for edge labels and does not route edges around nodes. Keep labels short, make each gap wider than its label, break a long label with \`\\\`, and go around nodes with corner points, not \`bend\`.
+\`theme\` has: theme.fg, theme.muted, theme.link, theme.border, theme.accent, theme.bg, theme.code-bg, theme.red/green/blue/yellow/orange/purple, theme.palette (6 colours), theme.width (content width) and theme.height (the height a drawing should fit in), both lengths, theme.text-size, theme.sans and theme.mono (font lists), theme.dark (bool).
+Rules (the examples follow them):
+- Size: fit theme.width × theme.height; a taller drawing is not made smaller. The terminal is wide and short, so lay flows out left to right.
+- Colours: text already has theme.fg and the body font. Default strokes are black and invisible on a dark theme, so always pass theme colours as the examples do. Fill shapes with a theme colour \`.transparentize(80%)\`, colour data with theme.palette in order, use theme.muted for secondary text.
+- fletcher makes no space for edge labels and does not route edges around nodes: keep labels short, make each gap wider than its label, break a long label with \`\\\`, and go around nodes with corner points, not \`bend\`.
- #page, #pagebreak and #set page are errors. A block that fails to compile shows as code.
+Only for a complex or unusual drawing (beyond these examples), or after a block failed, load the cc-intelligent-ui:intelligent-ui skill first; normal answers and drawings like these need no skill.
A flow chart (fletcher; \`node-shape: rect\` keeps small nodes from becoming circles, \`stroke: none\` is a text-only node):
\`\`\`typst
#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
#diagram(
node-stroke: theme.fg, edge-stroke: theme.fg, node-shape: rect,
crossing-fill: theme.bg, spacing: (3em, 2em),
- node((0, 0), [Push], fill: theme.blue.transparentize(80%), name: <p>),
- node((1, 0), [Build], fill: theme.purple.transparentize(80%), name: <b>),
- node((2, 0), [Test], fill: theme.orange.transparentize(80%), name: <t>),
- node((3, 0), [Deploy], fill: theme.green.transparentize(80%), name: <d>),
- node((4, 0), [live], stroke: none, name: <l>),
- edge(<p>, <b>, "->"),
+ node((0, 0), [Build], fill: theme.blue.transparentize(80%), name: <b>),
+ node((1, 0), [Test], fill: theme.orange.transparentize(80%), name: <t>),
+ node((2, 0), [Deploy], fill: theme.green.transparentize(80%), name: <d>),
+ node((3, 0), [live], stroke: none, name: <l>),
edge(<b>, <t>, "->"),
edge(<t>, <d>, "->", [pass]),
edge(<d>, <l>, "-->"),
- edge(<t>, (2, 1), (1, 1), <b>, "->", [fail], label-side: right),
+ edge(<t>, (1, 1), (0, 1), <b>, "->", [fail], label-side: right),
)
\`\`\`
A timeline (cetz; lay the drawing out in a W × H unit box, here 10 × 2):
@@ -179,22 +178,22 @@ A timeline (cetz; lay the drawing out in a W × H unit box, here 10 × 2):
import cetz.draw: *
set-style(stroke: theme.fg)
line((0, 0), (10, 0), mark: (end: ">"))
- for (x, name, date, c) in ((1, [v1.0], [Jan], theme.blue), (4, [v1.1], [Apr], theme.green), (8, [v2.0], [Oct], theme.orange)) {
+ for (x, name, date, c) in ((2, [v1.0], [Jan], theme.blue), (7, [v2.0], [Oct], theme.green)) {
circle((x, 0), radius: 0.15, fill: c, stroke: none)
content((x, 0.5), name)
content((x, -0.5), text(fill: theme.muted, date))
}
})
\`\`\`
-A plot (cetz-plot):
+A plot (cetz-plot; the axes, ticks and legend need the set-style line):
\`\`\`typst
#import "@preview/cetz:0.5.2"
#import "@preview/cetz-plot:0.1.4": plot
#cetz.canvas(length: calc.min(theme.width / 14, theme.height / 6), {
cetz.draw.set-style(axes: (stroke: theme.fg, tick: (stroke: theme.fg)), legend: (fill: theme.bg, stroke: theme.border))
plot.plot(size: (12, 4), x-label: [requests], y-label: [ms], legend: "inner-north-west", {
- plot.add(((1, 20), (2, 45), (4, 90), (8, 190)), label: [no cache], style: (stroke: theme.palette.at(0)))
- plot.add(((1, 20), (2, 24), (4, 30), (8, 38)), label: [cache], style: (stroke: theme.palette.at(1)))
+ plot.add(((1, 20), (4, 90), (8, 190)), label: [no cache], style: (stroke: theme.palette.at(0)))
+ plot.add(((1, 20), (4, 30), (8, 38)), label: [cache], style: (stroke: theme.palette.at(1)))
})
})
\`\`\`
diff --git a/skills/intelligent-ui/SKILL.md b/skills/intelligent-ui/SKILL.md
new file mode 100644
index 0000000..8104007
--- /dev/null
+++ b/skills/intelligent-ui/SKILL.md
@@ -0,0 +1,115 @@
+---
+name: intelligent-ui
+description: Full Typst API, recipes and a compile check for the live ```typst blocks that Intelligent UI draws in the terminal. Load it before you write a complex or unusual typst block (a diagram, flow chart, state machine, architecture, chart, plot, timeline, tree, heatmap, gantt or custom layout that goes beyond the short examples in the system prompt), or after a typst block failed to compile and showed as code. Do not load it for normal Markdown answers, tables, math, or a drawing as simple as those examples.
+allowed-tools: Bash(${CLAUDE_SKILL_DIR}/scripts/check.sh *)
+---
+
+# Intelligent UI: complex Typst drawings
+
+Intelligent UI draws each answer as a picture with the template `render/md.typ`. A fenced ```typst (or ```typ) block is compiled live and drawn in the answer. This skill tells you how to write a block that compiles and looks right in dark and light mode, and how to check it before you answer.
+
+## The contract
+
+- Each block compiles alone, as Typst markup (begin code lines with `#`). It must start with its own `#import` lines:
+ ```
+ #import "@preview/cetz:0.5.2"
+ #import "@preview/cetz-plot:0.1.4": plot, chart
+ #import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+ ```
+ These are the only packages. There is no network.
+- Only `theme` is in scope. Its keys:
+ - colours: `fg`, `muted`, `link`, `border`, `accent`, `bg`, `code-bg`, `red`, `green`, `blue`, `yellow`, `orange`, `purple`
+ - `palette`: 6 colours in this order: blue, orange, green, red, purple, yellow
+ - `width`: the content width (a length). `height`: the height a drawing should fit in (a length; 3/4 of the width when the terminal height is unknown). `page-width`: the page width.
+ - `text-size` (11pt), `sans` and `mono` (font lists), `dark` (bool)
+- Size: fit `theme.width` × `theme.height`. The terminal is wide and short, so lay flows out left to right. A drawing wider than its space is made smaller. A drawing taller than `theme.height` is never made smaller: the page grows and the answer gets long.
+- The mod keeps the size of the first draw. When the terminal changes, it scales the whole drawing by one factor. So size from `theme.width` and `theme.height`, never from fixed page numbers.
+- Text already has `theme.fg` and the body font. Strokes do not: the default stroke is black, which is invisible on a dark theme. Pass a theme colour to every stroke, axis, tick, legend and mark.
+- Fill shapes with a theme colour `.transparentize(80%)`. Colour data series with `theme.palette` in order. Use `theme.muted` for secondary text.
+- `#page`, `#pagebreak` and `#set page` are errors. A column break is dropped.
+- One block that fails makes the whole answer compile again in safe mode: then every typst block and all math of that answer show as code. So one bad block spoils the full answer.
+
+## Workflow for a complex drawing
+
+1. Pick the package with the table below.
+2. Read the one matching reference file (see the index). Do not read all of them.
+3. Write the block body (no fences) to a scratch file outside the project, for example `/tmp/iui-draft.typ`.
+4. Run `${CLAUDE_SKILL_DIR}/scripts/check.sh /tmp/iui-draft.typ`.
+5. If a mode prints `error`, read the diagnostics, fix the file and run it again.
+6. Read the dark PNG and the light PNG with the Read tool. Look for: text shown as code (the block did not compile), overlap, labels that cut lines, invisible strokes, a drawing taller than the box, empty space.
+7. Fix and check again until both modes are right. Then paste the exact block from the file into the answer, in a ```typst fence.
+
+For a full answer with Markdown around the drawings, write it to a `.md` file and check that file: it compiles the way the mod does.
+
+### Which package
+
+| You want to draw | Use | Reference |
+|---|---|---|
+| Flow chart, pipeline, state machine, architecture boxes and arrows, commutative diagram | fletcher | `fletcher.md` |
+| Free drawing: timeline, tree, geometry, custom shapes, annotated figures, layouts with exact positions | cetz | `cetz.md` |
+| Line, scatter or function plot, filled area, bar or error bars on numeric axes, contour | cetz-plot `plot` | `plot.md` |
+| Bar, column, pie, radar, pyramid or box chart of categories | cetz-plot `chart` | `charts.md` |
+| Candlestick, ratio bars, heatmap, gantt, waterfall | cetz rects and lines in a scaled box | `charts.md` |
+| Coloured table, cards, side-by-side panels, a legend row | plain Typst `table`, `grid`, `box`, `rect` | `typst.md` |
+
+If Markdown shows it well (a plain table, a list), use Markdown, not typst.
+
+### A cetz start point
+
+A timeline in a 10 × 2 unit box. It shows the canvas size, the stroke style, fills and muted text:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 10, theme.height / 2), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg)
+ line((0, 0), (10, 0), mark: (end: ">"))
+ for (x, name, date, c) in ((1, [v1.0], [Jan], theme.blue), (4, [v1.1], [Apr], theme.green), (8, [v2.0], [Oct], theme.orange)) {
+ circle((x, 0), radius: 0.15, fill: c, stroke: none)
+ content((x, 0.5), name)
+ content((x, -0.5), text(fill: theme.muted, date))
+ }
+})
+```
+
+## check.sh
+
+```
+${CLAUDE_SKILL_DIR}/scripts/check.sh [--theme NAME] [--mode dark|light|both] [--width PT] [--height PT] FILE
+```
+
+- `FILE`: a `.typ` file is one block body without fences. A `.md` file is Markdown with typst blocks. `-` reads the text from stdin.
+- It compiles with the real template, the vendored packages and your active theme (or `--theme NAME`). `--mode` is `both` by default. `--width` and `--height` set the space in pt.
+- Output: a `using …` line, then one line per mode. `ok <mode> <png> …` gives the PNG paths. `error <mode>` is followed by the compiler diagnostics (`FILE:line:col: error: …`).
+- Exit 0 only when all modes compile; 1 on a compile error; 2 on bad use or no Typst 0.15. Font warnings ("unknown font family") are noise.
+- Width, height and row grid are your last values from the mod's design cache, else 900 × 320 pt. The terminal font is not used, so the text width can differ a little.
+- Diagnostics give lines of FILE and 0-based columns, as Typst prints them. Typst stops at the first error of a block, so run the script again after each fix.
+- A `.md` file compiles as one page. The mod can split a long answer into more pages.
+- The PNGs are drawn on the theme's background colour, so you can read them with the Read tool (the mod's own PNGs are transparent).
+- It also accepts `--opt=value`, `-h`, and a folder path for `--theme`.
+- A compile with exit 0 can still be wrong. Always look at the PNGs.
+
+## Top traps
+
+- cetz-plot axes, ticks and legend are black by default. In the canvas, before the plot:
+ `cetz.draw.set-style(axes: (stroke: theme.fg, tick: (stroke: theme.fg)), legend: (fill: theme.bg, stroke: theme.border))`.
+- cetz: begin the canvas body with `set-style(stroke: theme.fg)`. Lay the drawing out in a W × H unit box: `cetz.canvas(length: calc.min(theme.width / W, theme.height / H), { … })`.
+- fletcher: pass `node-stroke: theme.fg, edge-stroke: theme.fg` and `node-shape: rect` (small nodes become circles). Use `crossing-fill: theme.bg`. `stroke: none` makes a text-only node.
+- fletcher makes no space for edge labels and does not route edges around nodes. Keep labels short, make each gap wider than its label, break a long label with `\`, and go around nodes with corner points, not `bend`.
+- cetz-plot 0.1.4 has no candlestick. Draw it with cetz `rect` and `line` in a scaled coordinate box.
+- A variable named `h` shadows the spacing function `h()`. Do not use it in destructuring or loops.
+- In content, `$` starts math and `~` is a non-breaking space. Write `\$` and `\~`. Use `#(expr)` to put an expression into content.
+- Text labels that cross a dashed reference line are hard to read. Put the labels in a fixed column.
+- A drawing taller than `theme.height` is not made smaller. Make it wider and shorter instead.
+
+## References
+
+Read only the file that matches the drawing:
+
+- [`references/typst.md`](references/typst.md): the Typst language for blocks, layout, `table` and `grid`, the theme keys, common compile errors and their fixes.
+- [`references/fletcher.md`](references/fletcher.md): fletcher for flow charts, state machines, architecture diagrams and commutative diagrams.
+- [`references/cetz.md`](references/cetz.md): cetz free drawing: canvas, primitives, anchors, timelines, trees, geometry.
+- [`references/plot.md`](references/plot.md): cetz-plot `plot`: line, scatter, function, bar, error bar, fill and contour plots.
+- [`references/charts.md`](references/charts.md): cetz-plot `chart` (bar, column, pie, radar, pyramid, box) and custom charts (candlestick, ratio bars, heatmap, gantt, waterfall).
+
+The files are in `${CLAUDE_SKILL_DIR}/references/`.
diff --git a/skills/intelligent-ui/references/cetz.md b/skills/intelligent-ui/references/cetz.md
new file mode 100644
index 0000000..0688f44
--- /dev/null
+++ b/skills/intelligent-ui/references/cetz.md
@@ -0,0 +1,472 @@
+# cetz 0.5.2: drawing on a canvas
+
+Use cetz for drawings that are not a chart and not a node-and-edge diagram: timelines, boxes with arrows,
+layer stacks, geometry, trees, braces, gauges, small graphs. For flow charts and state machines, fletcher
+is easier (fletcher.md). For data plots, use cetz-plot (plot.md, charts.md).
+Every ```` ```typst ```` example in this file was compiled with the real template, in dark and light.
+
+Contents
+1. Canvas, sizing and a first drawing (annotated timeline)
+2. Coordinates
+3. Names and anchors
+4. Shapes
+5. Marks (arrow heads)
+6. Styles and `set-style`
+7. Text in the canvas: `content`
+8. Groups, scope, layers, transforms
+9. Libraries: tree, decorations, angle
+10. Recipes: architecture, layer stack, geometry, tree, braces, gauges, network, shape sheet, reusable parts
+11. Traps
+
+## 1. Canvas, sizing and a first drawing
+
+- Import: `#import "@preview/cetz:0.5.2"`. Draw in `#cetz.canvas(length: L, { import cetz.draw: *; ... })`.
+- `length` is the size of one unit. Plan the drawing in a W × H unit box and fit the box to the room:
+ `length: calc.min(theme.width / W, theme.height / H)`. Wide and short: W about 3 × H.
+- The y axis points **up**. (0, 0) is not the corner: the canvas is the bounding box of what you draw.
+- Text does not scale with `length`. At 896pt × 320pt, one unit is about 55–65pt, so a 10-letter label needs about 1 unit.
+- Put `set-style(stroke: theme.fg)` first. The default stroke is black (invisible on dark).
+- The bounding box ignores stroke width. For thick strokes at the edge, add `padding: 0.1` (units) to the canvas.
+- Other canvas parameters: `padding`, `background` (a colour), `baseline`, `debug: true` (shows the bounding boxes).
+
+Annotated timeline (a 14 × 4 box: phases as bands, milestones with name and date, one callout):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 14, theme.height / 4), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg)
+ // Phases as bands under the axis
+ for (x0, x1, name, c) in ((0.5, 4.5, [Design], theme.blue), (4.5, 9.5, [Build], theme.purple), (9.5, 13.5, [Launch], theme.green)) {
+ rect((x0, -0.9), (x1, -0.3), fill: c.transparentize(80%), stroke: none)
+ content(((x0 + x1) / 2, -0.6), text(size: 0.85em, name))
+ }
+ line((0, 0), (14, 0), mark: (end: ">", fill: theme.fg))
+ for (x, name, date, c) in (
+ (1, [Kick-off], [Jan 8], theme.blue),
+ (4, [Spec frozen], [Mar 2], theme.blue),
+ (7, [Beta], [May 20], theme.purple),
+ (10, [RC1], [Aug 1], theme.orange),
+ (13, [v1.0], [Oct 14], theme.green),
+ ) {
+ line((x, 0), (x, 0.8), stroke: (paint: theme.muted, dash: "dotted"))
+ circle((x, 0), radius: 0.14, fill: c, stroke: theme.bg + 1.5pt)
+ content((x, 1.4), name, anchor: "base")
+ content((x, 1.0), text(fill: theme.muted, size: 0.8em, date), anchor: "base")
+ }
+ // A note pointing at one milestone
+ content((7, 2.5), text(fill: theme.orange, size: 0.85em)[slipped 3 weeks], name: "note")
+ line("note.south", (7, 1.85), stroke: theme.orange, mark: (end: ">", fill: theme.orange))
+})
+```
+
+The text on one row has `anchor: "base"`, so labels with and without descenders (p, g) line up.
+
+## 2. Coordinates
+
+| Write | Means |
+|---|---|
+| `(x, y)` / `(x, y, z)` | absolute, in units |
+| `()` | the previous position (the end of the last element) |
+| `(rel: (dx, dy))` | relative to the previous position |
+| `(rel: (dx, dy), to: "a.east")` | relative to another point |
+| `(30deg, 2)` / `(angle: 30deg, radius: 2)` | polar around (0, 0) |
+| `(30deg, (3, 1))` | polar on an ellipse with radii 3 and 1 |
+| `(rel: (30deg, 2), to: (5, 1))` | polar around another point |
+| `(a, 50%, b)` | the point halfway from a to b (any ratio) |
+| `(a, 1.5, b)` | 1.5 units from a toward b |
+| `(a, 50%, 90deg, b)` | as above, with b turned 90° around a |
+| `(a, "\|-", b)` | x of a, y of b |
+| `(a, "-\|", b)` | x of b, y of a |
+| `(p, "_\|_", a, b)` | p projected onto the line a–b |
+| `(bary: (a: 1, b: 1, c: 2))` | weighted mean of named elements |
+| `"name"` / `"name.anchor"` | an anchor of a named element (section 3) |
+| `((a, b) => ..., p, q)` | a function of resolved points; it returns a point |
+
+`a` and `b` can be any coordinate, also anchor strings: `("a.east", 50%, "b.west")`.
+
+## 3. Names and anchors
+
+- Give an element `name: "srv"`. Then use `"srv"` (its default anchor, mostly the centre) or `"srv.<anchor>"`.
+- Border anchors (rect, circle, content, group): `north`, `south`, `east`, `west`, `north-east`, ..., `center`, and any angle: `"srv.30deg"`.
+- Path anchors (line, bezier, arc, catmull, hobby): `start`, `mid`, `end`, a ratio along the path `"l.25%"`, or a distance `"l.2"`.
+- `line("a", "b")` with two names (no anchor) starts and ends on the borders of a and b, on the line between their centres.
+- Content anchors also have `base`, `base-west`, `base-east`, `mid`, `text`.
+- Arc anchors: `arc-start`, `arc-end`, `arc-center`, `origin`, `chord-center`.
+- Inside a named group, a child keeps its name with a prefix: `"g.box.east"`. `anchor("top", (0, 2))` adds a custom anchor to the group.
+- `intersections("i", "a", "b")` makes anchors `"i.0"`, `"i.1"`, ... for the crossing points (example in section 10).
+- An element can be placed by one of its anchors: `rect((0, 0), (2, 1), anchor: "north-west")`, `content(p, [x], anchor: "west")`.
+
+## 4. Shapes
+
+| Shape | Call | Notes |
+|---|---|---|
+| line, polyline | `line(a, b, c, close: false)` | `mark:` for arrows; `close: true` makes a polygon |
+| rectangle | `rect(a, b, radius: 0.1)` | b can be `(rel: (w, ht))`; radius per corner: `(north: 50%)` |
+| circle, ellipse | `circle(c, radius: 1)` / `radius: (rx, ry)` | `circle(a, b)`: centre a, through b; `circle-through(a, b, c)` |
+| arc | `arc(p, start: 0deg, stop: 90deg, radius: 1)` | two of `start`, `stop`, `delta`; `mode: "OPEN" \| "CLOSE" \| "PIE"`; p is the arc start unless `anchor: "origin"` |
+| arc by 3 points | `arc-through(a, b, c)` | |
+| Bézier | `bezier(start, end, c1)` / `bezier(start, end, c1, c2)` | `bezier-through(a, b, c)` passes through b |
+| smooth curve | `catmull(..pts, tension: 0.5)`, `hobby(..pts, omega: 0)` | through all points |
+| regular polygon | `polygon(c, 6, radius: 1)` | star: `n-star(c, 5, inner-radius: 50%)` |
+| grid | `grid(a, b, step: 0.5, stroke: theme.border)` | `step: (x: 1, y: 0.5)` |
+| box around things | `rect-around("a", "b", padding: 0.2)` | |
+| merged path | `merge-path({ line(...); arc(...) }, close: true, fill: ...)` | one fill for many parts |
+| path with holes | `compound-path({ rect(...); circle(...) }, fill-rule: "even-odd")` | |
+| SVG-like path | `svg-path(("m", (0, 0)), ("l", (1, 1)), ("z",))` | |
+
+Thick ring segment: an `arc` with a thick stroke (`stroke: (paint: c, thickness: 7pt, cap: "round")`), example in section 10.
+
+## 5. Marks (arrow heads)
+
+- `line(a, b, mark: (end: ">"))`, `mark: (start: "<", end: ">")`, or `mark: (end: (">", ">"))` for two heads.
+- Symbols: `">"` triangle, `">>"` stealth, `")>"` curved stealth, `"|"` bar, `"o"` circle, `"<>"` diamond,
+ `"[]"` square, `"]"` bracket, `"x"`, `"+"`, `"*"` star. Long names work too: `"triangle"`, `"stealth"`, `"straight"`.
+- Size and look: `mark: (end: ">", scale: 1.5, fill: theme.fg, length: 0.2cm, width: 0.15cm)`.
+- A mark is hollow by default (its outline uses the line stroke). For a solid head, set `mark: (fill: theme.fg)` with `set-style`, or give `fill:` per line in the line's colour.
+- Marks shorten the line so the tip ends at the point. `mark(from, to, symbol: ">")` draws a mark alone.
+
+## 6. Styles and `set-style`
+
+- Per element: `rect(a, b, fill: theme.blue.transparentize(80%), stroke: theme.blue + 0.8pt)`.
+- Strokes: a colour, a length, `c + 1pt`, or `(paint: c, thickness: 1pt, dash: "dashed" | "dotted", cap: "round")`.
+- For everything that follows (inside the current `scope` or `group`): `set-style(stroke: theme.fg, fill: none)`.
+- Per element type: `set-style(rect: (radius: 0.1), circle: (fill: ...), content: (padding: 0.1), mark: (fill: theme.fg))`.
+- Library roots: `brace`, `flat-brace`, `angle`, `zigzag`, `wave`, `coil`; cetz-plot uses `axes` and `legend` (plot.md).
+- `fill(c)` and `stroke(s)` are short forms of `set-style(fill: c)` and `set-style(stroke: s)`.
+
+## 7. Text in the canvas: `content`
+
+- `content(p, [Label])`: centred on p. `anchor: "west"` puts the label's west side on p.
+- `content(a, b, box(width: 100%, height: 100%, ...))`: fills the rect a–b (for wrapped text).
+- `padding: 0.1` (units) gives room around it; `frame: "rect" | "circle"` draws a frame that uses `stroke` and `fill`.
+- `angle: 30deg` turns it; `angle: "l.end"` turns it to point at another coordinate (text along a line).
+- Style the text with Typst: `text(fill: theme.muted, size: 0.8em, font: theme.mono)[...]`, `strong[...]`, math `$theta$`.
+- A named content has border anchors: `content((7, 2.5), [note], name: "n")` then `line("n.south", ...)`.
+
+## 8. Groups, scope, layers, transforms
+
+- `scope({ ... })`: styles and transforms inside stay inside. Use it for every local `translate` or `rotate`.
+- `group(name: "g", { ... })`: like scope, and the group gets anchors from its bounding box.
+- `on-layer(-1, { ... })`: draw behind (lower layers first; default 0). Use it for edges under nodes and backgrounds under text.
+- `translate((dx, dy))`, `rotate(30deg)`, `rotate(30deg, origin: p)`, `scale(2)`, `scale(x: 1, y: 50%)`, `set-origin(p)`.
+- Transforms move shapes; text is moved but not turned or scaled (use `content(..., angle:)`).
+- `hide({ ... })`: elements that only give anchors or intersections, not drawn.
+- `get-ctx(ctx => { ... })`: read the context, for example `cetz.coordinate.resolve(ctx, "a.east")` to get numbers.
+
+## 9. Libraries: tree, decorations, angle
+
+- `cetz.tree.tree(root, direction: "down" | "up" | "left" | "right", grow: 1, spread: 1, draw-node: ..., draw-edge: ...)`.
+ `root` is nested arrays: `([root], ([child], [leaf], [leaf]), [leaf])`.
+ `draw-node: (node, ..) => ...` draws at `()` (the node position); `node.content`, `node.depth`, `node.n` are set.
+ `draw-edge: (from, to, ..) => ...` gets two nodes; their element names are `from.group-name` and `to.group-name`.
+ Node anchors: `"0"` is the root, `"0-1"` its second child (with `name: "t"`: `"t.0-1"`).
+- `cetz.decorations.brace(a, b, amplitude: 0.3, name: "b")`: a curly brace on the left of a → b
+ (left to right points up, right to left points down). Its `fill` is **black** by default: set `brace: (fill: theme.fg, stroke: none)`.
+ Put the text at `"b.content"`.
+- `cetz.decorations.flat-brace(a, b, amplitude: 0.3)`: straight segments, better for long spans; it uses `stroke`.
+- `cetz.decorations.zigzag(line(a, b), amplitude: 0.2, segments: 8)`, also `wave`, `coil`, `square`; `start: 10%, stop: 90%` decorate a part.
+- `cetz.angle.angle(origin, a, b, label: $alpha$, radius: 0.8, label-radius: 1.1)` marks the angle a–origin–b (counter-clockwise; `direction: "cw" | "near" | "far"`).
+ `cetz.angle.right-angle(origin, a, b, radius: 0.3, label: none)` draws the square mark.
+
+## 10. Recipes
+
+Boxes with arrows (architecture). A helper draws a named box; edges go border to border:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 15, theme.height / 5), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg, mark: (fill: theme.fg))
+ // A box: a named rect with its label at the centre
+ let box(pos, name, label, c, w: 2.6, ht: 1) = {
+ rect((pos.at(0) - w / 2, pos.at(1) - ht / 2), (rel: (w, ht)), radius: 0.12,
+ fill: c.transparentize(80%), stroke: c, name: name)
+ content(name + ".center", label)
+ }
+ box((1.5, 2), "web", [Web app], theme.blue)
+ box((1.5, 0), "cli", [CLI], theme.blue)
+ box((5.5, 1), "api", [API gateway], theme.purple, w: 3)
+ box((9.5, 2), "auth", [Auth], theme.orange)
+ box((9.5, 0), "jobs", [Job queue], theme.orange)
+ box((13.3, 1), "db", [Postgres], theme.green, w: 2.2, ht: 2.6)
+ // Edges between borders: "name.east" etc. are border anchors
+ line("web.east", "api.west", mark: (end: ">"))
+ line("cli.east", "api.west", mark: (end: ">"))
+ line("api.east", "auth.west", mark: (end: ">"))
+ line("api.east", "jobs.west", mark: (end: ">"))
+ line("auth.east", ("db.west", "|-", "auth.east"), mark: (end: ">"))
+ line("jobs.east", ("db.west", "|-", "jobs.east"), mark: (end: ">"))
+ // An edge label just above the middle of the edge
+ content(("api.east", 50%, "auth.west"), text(fill: theme.muted, size: 0.8em)[JWT], anchor: "south-east", padding: 0.1)
+ // A dashed group frame around two boxes
+ rect((7.9, -0.75), (11.1, 2.75), stroke: (paint: theme.muted, dash: "dashed"), radius: 0.2)
+ content((9.5, 2.75), text(fill: theme.muted, size: 0.8em)[services], anchor: "south", padding: 0.08)
+})
+```
+
+Layer stack with notes in a fixed column right of the stack:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 14, theme.height / 5), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg)
+ let layers = (
+ ([Application], [your code], theme.blue),
+ ([Framework], [routing, ORM], theme.purple),
+ ([Runtime], [Node 22], theme.orange),
+ ([OS], [Linux 6.8], theme.green),
+ ([Hardware], [x86-64, 32 GB], theme.muted),
+ )
+ // Layer i from the top: y goes down from 4.5
+ for (i, (name, note, c)) in layers.enumerate() {
+ let y = 4 - i * 0.9
+ rect((0, y), (8, y + 0.8), fill: c.transparentize(80%), stroke: c, radius: 0.08, name: "l" + str(i))
+ content((0.3, y + 0.4), strong(name), anchor: "west")
+ content((7.7, y + 0.4), text(fill: theme.muted, note), anchor: "east")
+ }
+ // Notes in a fixed column right of the stack, with a bracket over a span
+ line((8.3, 4.8), (8.5, 4.8), (8.5, 3.1), (8.3, 3.1))
+ content((8.7, 3.95), [user space: you deploy this], anchor: "west")
+ line((8.3, 2.9), (8.5, 2.9), (8.5, 0.4), (8.3, 0.4), stroke: theme.muted)
+ content((8.7, 1.65), text(fill: theme.muted)[platform: managed for you], anchor: "west")
+})
+```
+
+Geometry: vectors (one in polar form), angle, projection, right angle, intersections:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 12, theme.height / 4.6), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg, mark: (fill: theme.fg))
+ // Axes and a light grid
+ grid((-0.5, -0.5), (5.5, 3.5), step: 1, stroke: theme.border + 0.4pt)
+ line((-0.5, 0), (5.6, 0), mark: (end: ">"))
+ line((0, -0.5), (0, 3.6), mark: (end: ">"))
+ content((5.6, 0), $x$, anchor: "west", padding: 0.1)
+ content((0, 3.6), $y$, anchor: "south", padding: 0.1)
+ // Two vectors: one in polar form (angle, length)
+ line((0, 0), (4, 1), stroke: theme.blue + 1.5pt, mark: (end: ">", fill: theme.blue), name: "u")
+ line((0, 0), (35deg, 3.5), stroke: theme.orange + 1.5pt, mark: (end: ">", fill: theme.orange), name: "v")
+ content("u.end", text(fill: theme.blue, $arrow(u)$), anchor: "west", padding: 0.1)
+ content("v.end", text(fill: theme.orange, $arrow(v)$), anchor: "south-west", padding: 0.05)
+ // The angle between them
+ cetz.angle.angle((0, 0), "u.end", "v.end", radius: 1.2, label: text(fill: theme.purple, $theta$),
+ label-radius: 1.5, stroke: theme.purple)
+ // Projection of v onto u, with the right angle mark
+ line("v.end", ("v.end", "_|_", (0, 0), "u.end"), stroke: (paint: theme.muted, dash: "dashed"), name: "p")
+ cetz.angle.right-angle("p.end", "v.end", "u.end", radius: 0.25, stroke: theme.muted, label: none)
+ circle("p.end", radius: 0.06, fill: theme.fg, stroke: none)
+ // Right panel: a circle, a chord and their intersections
+ circle((9, 1.5), radius: 1.5, stroke: theme.green, name: "c")
+ line((7, 0.3), (11, 2.6), stroke: theme.red, name: "l")
+ intersections("i", "c", "l")
+ for p in ("i.0", "i.1") { circle(p, radius: 0.08, fill: theme.red, stroke: none) }
+ content("c.north", text(fill: theme.muted, size: 0.85em)[2 intersections], anchor: "south", padding: 0.1)
+})
+```
+
+Tree with styled nodes and elbow edges:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 16, theme.height / 4.5), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg)
+ cetz.tree.tree(
+ ([src/], ([hooks/], [lib/], [index.ts]), ([render/], [md.typ], [theme.typ], [packages/]), ([tests/], [pure.test.ts])),
+ direction: "down", grow: 1.4, spread: 2.2,
+ draw-node: (node, ..) => {
+ let c = (theme.accent, theme.blue, theme.green).at(calc.min(node.depth, 2))
+ content((), box(inset: (x: 6pt, y: 4pt), radius: 3pt, fill: c.transparentize(82%), stroke: c + 0.6pt,
+ text(font: theme.mono, size: 0.85em, node.content)), name: "box")
+ },
+ draw-edge: (from, to, ..) => {
+ // From the bottom of the parent to the top of the child, with an elbow
+ let (a, b) = (from.group-name + ".south", to.group-name + ".north")
+ line(a, (a, 50%, (a, "|-", b)), ((a, 50%, (a, "|-", b)), "-|", b), b, stroke: theme.muted)
+ },
+ )
+})
+```
+
+Braces over a range (curly brace above, flat brace below):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 14, theme.height / 3.5), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg)
+ // A byte layout: 16 cells
+ let cells = range(16)
+ for i in cells {
+ let c = if i < 2 { theme.blue } else if i < 4 { theme.orange } else if i < 12 { theme.green } else { theme.purple }
+ rect((i * 0.8, 0), (rel: (0.8, 0.8)), fill: c.transparentize(80%), stroke: theme.border)
+ content((i * 0.8 + 0.4, 0.4), text(font: theme.mono, size: 0.8em, str(i)))
+ }
+ // Braces: brace() points left of start -> end, so go right-to-left below, left-to-right above
+ set-style(brace: (fill: theme.fg, stroke: none), flat-brace: (stroke: theme.muted))
+ cetz.decorations.brace((0, 0.9), (1.6, 0.9), name: "magic", amplitude: 0.3)
+ content("magic.content", [magic], anchor: "south")
+ cetz.decorations.brace((1.6, 0.9), (3.2, 0.9), name: "ver", amplitude: 0.3)
+ content("ver.content", [version], anchor: "south")
+ // flat-brace: straight segments, better for long spans
+ cetz.decorations.flat-brace((9.6, -0.1), (3.2, -0.1), name: "body", amplitude: 0.3)
+ content("body.content", text(fill: theme.muted)[payload (8 bytes)], anchor: "north")
+ cetz.decorations.flat-brace((12.8, -0.1), (9.6, -0.1), name: "crc", amplitude: 0.3)
+ content("crc.content", text(fill: theme.muted)[CRC-32], anchor: "north")
+})
+```
+
+Progress rings and a half gauge (arcs with thick strokes, canvas padding):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 13, theme.height / 3), padding: 0.1, {
+ import cetz.draw: *
+ // The bounds ignore stroke width, so thick strokes need canvas padding (in units).
+ // Progress rings: a full track circle, then an arc for the value (clockwise from the top)
+ let ring(pos, frac, label, c) = {
+ circle(pos, radius: 1, stroke: theme.border + 7pt)
+ arc(pos, start: 90deg, delta: -frac * 360deg, radius: 1, anchor: "origin",
+ stroke: (paint: c, thickness: 7pt, cap: "round"))
+ content(pos, text(size: 1.4em, weight: "bold", str(int(frac * 100)) + "%"))
+ content((pos.at(0), pos.at(1) - 1.35), text(fill: theme.muted, label))
+ }
+ ring((1.2, 1.5), 0.72, [CPU], theme.blue)
+ ring((4, 1.5), 0.41, [Memory], theme.green)
+ ring((6.8, 1.5), 0.93, [Disk], theme.red)
+ // A half gauge with a needle
+ let (cx, cy, r) = (10.5, 0.9, 1.8)
+ for (a0, a1, c) in ((180deg, 120deg, theme.green), (120deg, 60deg, theme.yellow), (60deg, 0deg, theme.red)) {
+ arc((cx, cy), start: a0, stop: a1, radius: r, anchor: "origin", stroke: (paint: c, thickness: 6pt))
+ }
+ let v = 0.62 // 0..1
+ let ang = 180deg - v * 180deg
+ line((cx, cy), (rel: (ang, r - 0.35)), stroke: theme.fg + 2pt, mark: (end: ">", fill: theme.fg))
+ circle((cx, cy), radius: 0.1, fill: theme.fg, stroke: none)
+ content((cx, cy - 0.45), text(fill: theme.muted)[latency: 620 ms])
+ for (t, a) in (([0], 180deg), ([500], 90deg), ([1000], 0deg)) {
+ content((rel: (a, r + 0.35), to: (cx, cy)), text(fill: theme.muted, size: 0.8em, t))
+ }
+})
+```
+
+Network graph from a list of names and edges (nodes on an ellipse, edges on a lower layer):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 14, theme.height / 4.4), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg)
+ // Nodes on an ellipse (polar coordinates), edges from a list of pairs
+ let names = ("api", "auth", "db", "cache", "queue", "worker", "mail", "cdn")
+ let edges = (("api", "auth"), ("api", "db"), ("api", "cache"), ("api", "queue"),
+ ("queue", "worker"), ("worker", "db"), ("worker", "mail"), ("cdn", "api"), ("auth", "db"))
+ let n = names.len()
+ for (i, name) in names.enumerate() {
+ let a = 90deg - i * 360deg / n
+ let c = theme.palette.at(calc.rem(i, theme.palette.len()))
+ // (angle, (rx, ry)) is an elliptic polar coordinate around (0, 0)
+ circle((a, (5.5, 1.7)), radius: 0.4, fill: c.transparentize(75%), stroke: c, name: name)
+ content(name, text(size: 0.85em, name))
+ }
+ // Edges go below the nodes (layer -1); line("a", "b") stops at both borders
+ on-layer(-1, {
+ for (a, b) in edges { line(a, b, stroke: theme.muted, mark: (end: ">", fill: theme.muted)) }
+ })
+})
+```
+
+Shape sheet: what each primitive, mark and path decoration looks like:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 16, theme.height / 4), {
+ import cetz.draw: *
+ set-style(stroke: theme.fg, mark: (fill: theme.fg))
+ let cap(x, body) = content((x, -0.35), text(font: theme.mono, fill: theme.muted, size: 0.75em, body), anchor: "north")
+ // Bottom row (y = 0..1; y grows up): shapes
+ rect((0, 0), (rel: (1.4, 1)), radius: 0.15, fill: theme.blue.transparentize(80%)); cap(0.7, "rect")
+ circle((2.4, 0.5), radius: (0.7, 0.45), fill: theme.green.transparentize(80%)); cap(2.4, "circle (ellipse)")
+ arc((4, 0.1), start: 0deg, stop: 120deg, radius: 0.8, mode: "PIE", anchor: "origin", fill: theme.orange.transparentize(70%)); cap(4.0, "arc PIE")
+ polygon((6, 0.5), 6, radius: 0.55, fill: theme.purple.transparentize(80%)); cap(6, "polygon")
+ n-star((7.7, 0.5), 5, radius: 0.55, fill: theme.yellow.transparentize(70%)); cap(7.7, "n-star")
+ bezier((9, 0), (10.6, 0), (9.3, 1.2), (10.3, -0.6), stroke: theme.red); cap(9.8, "bezier")
+ catmull((11.2, 0), (11.7, 1), (12.2, 0.2), (12.8, 0.9), stroke: theme.blue); cap(12, "catmull")
+ hobby((13.4, 0), (13.9, 1), (14.4, 0.2), (15, 0.9), stroke: theme.green); cap(14.2, "hobby")
+ // Middle row: marks and path decorations
+ let y = 2.2
+ for (i, m) in (">", ">>", "|", "o", "<>", "]", "x").enumerate() {
+ line((i * 1.1, y), (i * 1.1 + 0.8, y), mark: (end: m))
+ content((i * 1.1 + 0.4, y - 0.15), text(font: theme.mono, fill: theme.muted, size: 0.75em, m), anchor: "north")
+ }
+ cetz.decorations.zigzag(line((8, y), (10, y)), amplitude: 0.15, segments: 8)
+ cetz.decorations.wave(line((10.5, y), (12.5, y)), amplitude: 0.15, segments: 6, stroke: theme.blue)
+ cetz.decorations.coil(line((13, y), (15, y)), amplitude: 0.25, segments: 8, stroke: theme.orange)
+ for (x, t) in ((9, "zigzag"), (11.5, "wave"), (14, "coil")) {
+ content((x, y - 0.35), text(font: theme.mono, fill: theme.muted, size: 0.75em, t), anchor: "north")
+ }
+ // Top row: grid, content frames, text along a line
+ grid((0, 3), (3, 3.9), step: 0.3, stroke: theme.border + 0.4pt)
+ content((5, 3.45), [frame: "rect"], frame: "rect", padding: 0.12, fill: theme.code-bg, stroke: theme.border)
+ content((8.5, 3.45), [frame: "circle"], frame: "circle", padding: 0.05, stroke: theme.accent)
+ line((10.5, 3.1), (14.5, 3.8), stroke: theme.muted, name: "l")
+ content(("l.start", 50%, "l.end"), angle: "l.end", anchor: "south", padding: 0.08, text(size: 0.8em)[text along a line])
+})
+```
+
+Reusable parts with `group`, `scope` and transforms:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#cetz.canvas(length: calc.min(theme.width / 12.5, theme.height / 3.4), padding: 0.1, {
+ import cetz.draw: *
+ set-style(stroke: theme.fg, mark: (fill: theme.fg))
+ // A reusable part: a function that draws a named group around (0, 0)
+ let server(name, label, c) = group(name: name, {
+ rect((-0.7, -0.9), (0.7, 0.9), radius: 0.1, fill: c.transparentize(85%), stroke: c, name: "box")
+ for y in (0.45, 0, -0.45) {
+ rect((-0.5, y - 0.15), (0.5, y + 0.15), stroke: c + 0.6pt)
+ circle((0.35, y), radius: 0.05, fill: c, stroke: none)
+ }
+ content((0, -1.15), label, anchor: "north")
+ })
+ // translate() inside scope() moves only what is in the scope
+ for (i, (name, c)) in (("eu", theme.blue), ("us", theme.green), ("ap", theme.orange)).enumerate() {
+ scope({ translate((i * 2.4, 0)); server(name, text(font: theme.mono, name), c) })
+ }
+ // Anchors of a named child work outside the group: "eu.box.east"
+ // ("eu.east" is the east of the whole group, label included)
+ line("eu.box.east", "us.box.west", mark: (start: ">", end: ">"))
+ line("us.box.east", "ap.box.west", mark: (start: ">", end: ">"))
+ // rotate() and scale() in a scope: a clock with 12 ticks
+ scope({
+ translate((8.6, 0))
+ circle((0, 0), radius: 1.3, stroke: theme.border + 1.5pt)
+ for i in range(12) {
+ scope({ rotate(i * 30deg); line((0, 1.05), (0, 1.25), stroke: theme.muted + 1.5pt) })
+ }
+ rotate(-60deg) // the hand: 2 o'clock
+ line((0, 0), (0, 0.95), stroke: theme.accent + 2pt, mark: (end: ">", fill: theme.accent))
+ })
+ // set-style per element type: every later circle gets this fill
+ set-style(circle: (fill: theme.purple.transparentize(70%), stroke: theme.purple))
+ scope({ scale(y: 50%); circle((11.4, 0), radius: 0.6) })
+ content((11.4, -0.6), text(fill: theme.muted, size: 0.8em)[scale(y: 50%)])
+})
+```
+
+## 11. Traps
+
+- Default black: strokes, the `brace` fill, `grid` lines. Marks are hollow until you give `fill`. Set them all from `theme`.
+- `"g.east"` of a group is the bounding box of the whole group, label included. Name the inner shape and use `"g.box.east"`.
+- `translate`, `rotate` and `set-style` stay active until the end of the scope. Wrap local changes in `scope({ ... })`.
+- `arc(p, ...)` puts the arc **start** on p. To give the centre, add `anchor: "origin"`.
+- The canvas bounding box ignores stroke width: thick strokes at the edge are cut. Add canvas `padding`.
+- Text has a fixed size. If labels overlap, make the unit box smaller (fewer units = bigger units), not the text.
+- In `content`, `$` and `~` are markup: write `\$` and `\~`. A variable named `h` hides the `h()` function: do not use it.
+- In a tree, `draw-edge` gets node dictionaries, not names: `from + ".south"` fails with "cannot add dictionary and string".
+- A raw compile of the template reports errors at `md.typ:891`. Use `scripts/check.sh` for the line in your block.
diff --git a/skills/intelligent-ui/references/charts.md b/skills/intelligent-ui/references/charts.md
new file mode 100644
index 0000000..2de924c
--- /dev/null
+++ b/skills/intelligent-ui/references/charts.md
@@ -0,0 +1,436 @@
+# cetz-plot 0.1.4: `chart`, and custom charts
+
+`chart` draws category charts: bars, columns, pies and donuts, pyramids, radar, box plots.
+For a chart type that cetz-plot does not have (candlestick, gantt, waterfall, heatmap, bullet bars, sparklines),
+draw it with cetz shapes in a scaled unit box (section 3). For numeric x/y plots see plot.md.
+Every ```` ```typst ```` example in this file was compiled with the real template, in dark and light.
+
+Contents
+1. Which chart for which data
+2. `chart` functions: bar and column, pie and donut, pyramid and radar, box plot
+3. Custom charts: candlestick, ratio bars with a reference line, heatmap, gantt, waterfall, sparklines, bullet bars
+4. Traps
+
+Import: `#import "@preview/cetz:0.5.2"` and `#import "@preview/cetz-plot:0.1.4": chart`. A chart goes in a `cetz.canvas`.
+
+## 1. Which chart for which data
+
+| Data | Use |
+|---|---|
+| a few named values, long names | `chart.barchart` (horizontal) |
+| values per period or category | `chart.columnchart`, `mode: "clustered"` for 2–4 series |
+| parts of one whole, per category | `columnchart` `mode: "stacked"`, or `"stacked100"` for shares |
+| parts of one whole, 2–6 parts | `chart.piechart` (donut with `inner-radius`) |
+| a funnel or a hierarchy of sizes | `chart.pyramid` |
+| a profile on 5–8 axes | `chart.radarchart` |
+| distributions per group | `chart.boxwhisker`, or `plot.add-violin` (plot.md) |
+| a trend over numeric x | `plot.add` (plot.md) |
+| price open/high/low/close | candlestick (3.1) |
+| progress against a target | ratio bars (3.2) or bullet bars (3.7) |
+| a value per (row, column) | heatmap (3.3) |
+| tasks over time | gantt (3.4) |
+| how a total changes step by step | waterfall (3.5) |
+| many small trends in a table | sparklines (3.6) |
+
+## 2. `chart` functions
+
+All chart axes and the legend need the theme style, as in plot.md. The bar, column and box charts also set
+their own dotted gray grid: override it under the chart's style root (`barchart`, `columnchart`, `boxwhisker`).
+`bar-style`, `slice-style`, `level-style` and `data-style` default to a red palette: always pass theme colours.
+
+### Bar and column charts
+
+- `chart.columnchart(data, label-key: 0, value-key: 1, mode: "basic", size: (W, H), bar-style: i => (...), labels: (...), x-label:, y-label:, y-format:, ..plot-args)`.
+- `chart.barchart(...)`: the same with horizontal bars (`x-format`). The first row is at the top.
+- Rows: `([Q1], 12)` for basic; `([Q1], 12, 8, 4)` with `value-key: (1, 2, 3)` for clustered and stacked.
+- `mode`: `"basic"`, `"clustered"`, `"stacked"`, `"stacked100"` (the value axis shows %).
+- `labels: ([EU], [US], [AP])` names the series in the legend (one per value key).
+- Extra arguments go to `plot.plot`: `legend: "inner-north-west"`, `x-tick-step: 20`, `x-min: 0`, `y-max: 100`, ...
+- Style root: `set-style(columnchart: (bar-width: 0.8, cluster-gap: 0, x-inset: 1, axes: (...)))`; `barchart` has `y-inset`.
+- Always give both numbers of `size`.
+
+Clustered and stacked100 columns, side by side (a Typst `grid` of two canvases, each with `length` from `theme.width / 2`):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": chart
+#let style = (
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ // The charts set their own dotted gray grid: override it under the chart's root
+ columnchart: (axes: (grid: (stroke: (paint: theme.border, dash: "dotted")))),
+)
+// One style per bar index (basic) or per series (clustered/stacked)
+#let bars = i => (fill: theme.palette.at(calc.rem(i, 6)).transparentize(25%), stroke: none)
+#let data = (([Q1], 12, 8, 4), ([Q2], 15, 9, 6), ([Q3], 11, 12, 7), ([Q4], 18, 10, 9))
+// Two charts side by side: a grid of two canvases, each half the width
+#grid(columns: (1fr, 1fr), column-gutter: 1em,
+ cetz.canvas(length: calc.min(theme.width / 2 / 8, theme.height / 5.5), {
+ cetz.draw.set-style(..style)
+ chart.columnchart(data, mode: "clustered", value-key: (1, 2, 3), size: (7, 4),
+ labels: ([EU], [US], [AP]), legend: "inner-north-west", bar-style: bars, y-label: [M\$])
+ }),
+ cetz.canvas(length: calc.min(theme.width / 2 / 8, theme.height / 5.5), {
+ cetz.draw.set-style(..style)
+ chart.columnchart(data, mode: "stacked100", value-key: (1, 2, 3), size: (7, 4),
+ labels: ([EU], [US], [AP]), legend: none, bar-style: bars, y-label: [share])
+ }),
+)
+```
+
+Horizontal bars, one bar highlighted:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": chart
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ barchart: (bar-width: 0.7, axes: (grid: (stroke: (paint: theme.border, dash: "dotted")))),
+ )
+ // barchart: horizontal bars; the first row is drawn at the top
+ let langs = (([Rust], 82), ([TypeScript], 74), ([Go], 61), ([Python], 58), ([Java], 40))
+ chart.barchart(langs, size: (15, 4), x-label: [% who would use it again],
+ x-tick-step: 20, x-min: 0, x-max: 100,
+ bar-style: i => (fill: if i == 0 { theme.accent } else { theme.muted.transparentize(40%) }, stroke: none))
+})
+```
+
+### Pie and donut
+
+- `chart.piechart(data, value-key: 1, label-key: 0, slice-style: (...), outset: 0, radius: 1, inner-radius: 0, ...)`.
+- Data: numbers, arrays or dictionaries; `value-key` and `label-key` pick the fields.
+- `slice-style`: an array of styles or colours, a function `i => style`, or a gradient.
+- Style keys: `radius`, `inner-radius` (> 0 makes a donut), `gap: 0.5deg`, `start: 90deg`, `stop: 450deg`, `clockwise: true`,
+ `outset: 0` (or `(0, 2)`) with `outset-offset: 10%` and `outset-mode: "OFFSET" | "RADIUS"`.
+- `outer-label: (content: "LABEL" | "%" | "VALUE" | none | (value, label) => content, radius: 125%, angle: 0deg, anchor: "center")`;
+ `inner-label` has the same keys (default `content: none`, `radius: 150%` of the mid radius).
+- The legend is on when any item has a label: `legend: (label: none)` turns it off. When on, it needs `fill: theme.bg`.
+ Keys: `label`, `position: "south"`, `anchor: "north"`, `orientation: ltr`, `item: (spacing: ...)`.
+- Anchors: `"item-0"` (outer radius of slice 0), `"item-0-inner"`. Text in the donut hole: `cetz.draw.content((0, 0), ...)`.
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": chart
+#let data = (([Chrome], 64), ([Safari], 19), ([Edge], 5), ([Firefox], 3), ([Other], 9))
+#let slices = data.enumerate().map(((i, _)) => (fill: theme.palette.at(i).transparentize(15%), stroke: theme.bg + 1.5pt))
+#grid(columns: (1fr, 1fr), align: center + horizon,
+ // Pie: label-key/value-key pick the fields; outer labels outside, one slice pulled out
+ cetz.canvas(length: theme.height / 3.6, {
+ chart.piechart(data, value-key: 1, label-key: 0, radius: 1, slice-style: slices,
+ outset: 0, outset-offset: 12%,
+ // A function label: skip small slices so labels do not collide
+ inner-label: (content: (v, l) => if v >= 5 { text(fill: theme.bg, weight: "bold", size: 0.85em, str(v) + "%") }, radius: 120%),
+ outer-label: (content: "LABEL", radius: 135%),
+ // The legend is on by default (legend.label: "LABEL", white fill): turn it off here
+ legend: (label: none))
+ }),
+ // Donut: inner-radius > 0; the legend below needs fill: theme.bg (its default is white)
+ cetz.canvas(length: theme.height / 3.6, {
+ chart.piechart(data, value-key: 1, label-key: 0, radius: 1, inner-radius: 0.6, slice-style: slices,
+ gap: 1deg, outer-label: (content: none),
+ legend: (label: "LABEL", fill: theme.bg, item: (spacing: 0.3)))
+ cetz.draw.content((0, 0), text(size: 1.2em, weight: "bold")[100 M])
+ }),
+)
+```
+
+### Pyramid and radar
+
+- `chart.pyramid(data, label-key: 0, value-key: 1, level-style: i => (...), mode: "REGULAR" | "AREA-HEIGHT" | "HEIGHT" | "WIDTH", level-height: 1, gap: 0)`.
+ The first row is the top level. `inner-label: (content: "LABEL" | "%" | "VALUE" | function, force-inside: false)`,
+ `side-label: (content: ..., side: "west" | "east")`. Anchors: `"levels.0"`, `"levels.0.east"`.
+- `chart.radarchart(labels, rows, data-style: i => (...), radius: 2, web-ticks: 4, web-style: (stroke: ...), web-label-offset: 0.4)`.
+ Each value is a fraction **0..1 of the radius** (the source doc says 0..radius; a value of 2 with radius 2 lands far outside).
+ The spokes use the current stroke: `set-style(stroke: theme.border)` first. There is no legend: add `content` lines.
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": chart
+#grid(columns: (1fr, 1fr), align: center + horizon,
+ // Pyramid: the first row is the top level
+ cetz.canvas(length: theme.height / 5, {
+ chart.pyramid(
+ (([Paid], 60), ([Trials], 180), ([Sign-ups], 420), ([Visits], 1000)),
+ label-key: 0, value-key: 1, mode: "REGULAR", level-height: 0.9, gap: 0.08,
+ level-style: i => (fill: theme.palette.at(i).transparentize(30%), stroke: none),
+ inner-label: (content: "LABEL"),
+ side-label: (content: (v, l) => text(fill: theme.muted, str(v)), side: "east"))
+ }),
+ // Radar: values are fractions 0..1 of the radius (not 0..radius);
+ // the spokes use the current stroke, the web uses web-style
+ cetz.canvas(length: theme.height / 5.2, {
+ cetz.draw.set-style(stroke: theme.border)
+ chart.radarchart(
+ ([Speed], [Memory], [Safety], [Tooling], [Docs], [Hiring]),
+ ((0.9, 0.8, 1, 0.7, 0.65, 0.4), (0.6, 0.5, 0.45, 0.95, 0.9, 0.95)),
+ radius: 2, web-ticks: 4,
+ web-style: (stroke: theme.border),
+ data-style: i => (stroke: theme.palette.at(i) + 1.5pt, fill: theme.palette.at(i).transparentize(75%)))
+ cetz.draw.content((2.6, 2), text(fill: theme.palette.at(0))[■ Rust], anchor: "west")
+ cetz.draw.content((2.6, 1.6), text(fill: theme.palette.at(1))[■ Go], anchor: "west")
+ }),
+)
+```
+
+### Box plot chart
+
+- `chart.boxwhisker(boxes, size: (W, H), label-key: "label", mark: "*", ..plot-args)`; each box is
+ `(label: [..], min:, q1:, q2:, q3:, max:, outliers: (...))`.
+- The boxes take `plot-style` and the outliers `mark-style` (both via plot-args); the defaults are blue, red, green, yellow.
+- Style root `boxwhisker: (box-width: 0.75, whisker-width: 0.5, mark-size: 0.15, axes: (...))`.
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": chart
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg)),
+ // Root "boxwhisker": the boxes' style and the chart's dotted gray grid
+ boxwhisker: (box-width: 0.5, axes: (grid: (stroke: (paint: theme.border, dash: "dotted")))),
+ )
+ // Rows: (label, min, q1, q2, q3, max, outliers) as dictionaries; x is the row's position
+ chart.boxwhisker(size: (15, 4), label-key: "label", y-min: 0, y-max: 100, y-tick-step: 25, y-grid: true, y-label: [ms],
+ // The boxes take plot-style (default: blue, red, green, yellow), the outliers mark-style
+ plot-style: i => (stroke: theme.fg, fill: theme.green.transparentize(75%)),
+ mark-style: i => (stroke: theme.red, fill: theme.red.transparentize(50%)),
+ (
+ (label: [eu-west], min: 12, q1: 25, q2: 33, q3: 44, max: 60, outliers: (72, 88)),
+ (label: [us-east], min: 9, q1: 18, q2: 24, q3: 31, max: 45, outliers: (63,)),
+ (label: [ap-south], min: 20, q1: 34, q2: 45, q3: 58, max: 79, outliers: ()),
+ (label: [sa-east], min: 15, q1: 28, q2: 37, q3: 49, max: 66, outliers: (91,)),
+ ))
+})
+```
+
+## 3. Custom charts
+
+The pattern: choose a W × H unit box, write a function that maps a data value to units (`y(p) = (p - lo) / (hi - lo) * H`),
+and draw with `rect`, `line` and `content`. Keep labels in fixed columns (left of the box for names, right for notes),
+so no label crosses a bar or a reference line.
+
+### 3.1 Candlestick (OHLC)
+
+Green body when close ≥ open, red otherwise; the wick spans low to high. cetz-plot 0.1.4 has no candlestick.
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Candlestick (cetz-plot 0.1.4 has none): map prices into a W x H unit box by hand
+#let ohlc = ((101, 106, 99, 104), (104, 108, 103, 107), (107, 107, 101, 102), (102, 104, 97, 98),
+ (98, 103, 96, 102), (102, 109, 101, 108), (108, 112, 106, 110), (110, 111, 104, 105),
+ (105, 107, 100, 101), (101, 106, 100, 105), (105, 113, 104, 112), (112, 115, 109, 114))
+#let (W, H) = (14, 4)
+#let (lo, hi) = (95, 116)
+#let y(p) = (p - lo) / (hi - lo) * H
+#let dx = W / ohlc.len()
+#cetz.canvas(length: calc.min(theme.width / (W + 1.2), theme.height / (H + 0.8)), {
+ import cetz.draw: *
+ // Grid lines and price labels in a fixed column left of the box
+ for p in range(lo + 5, hi + 1, step: 5) {
+ line((0, y(p)), (W, y(p)), stroke: theme.border + 0.5pt)
+ content((-0.15, y(p)), text(fill: theme.muted, size: 0.8em, str(p)), anchor: "east")
+ }
+ line((0, 0), (W, 0), stroke: theme.fg)
+ for (i, (o, h, l, c)) in ohlc.enumerate() {
+ let x = (i + 0.5) * dx
+ let col = if c >= o { theme.green } else { theme.red }
+ line((x, y(l)), (x, y(h)), stroke: col + 1pt) // wick
+ rect((x - dx * 0.3, y(calc.min(o, c))), (x + dx * 0.3, y(calc.max(o, c))),
+ fill: col, stroke: none) // body
+ content((x, -0.15), text(fill: theme.muted, size: 0.75em, "D" + str(i + 1)), anchor: "north")
+ }
+})
+```
+
+### 3.2 Ratio bars with a 100% reference line
+
+Values and notes go in fixed columns right of the longest bar. The reference line is drawn last.
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Horizontal ratio bars against a 100% target. Values and notes sit in fixed columns
+// right of the longest bar, so no label crosses the dashed reference line.
+#let rows = (([Build time], 0.62, [CI cache on]), ([Bundle size], 0.88, [tree-shaken]),
+ ([Cold start], 1.18, [over budget]), ([Memory], 0.95, []), ([Test time], 0.41, [parallel]))
+#let (W, H) = (15, rows.len() * 0.8)
+#let label-w = 2.6 // column for row names
+#let bar-w = 8 // 100% = 8 units
+#let max-r = calc.max(..rows.map(r => r.at(1)))
+#let note-x = label-w + bar-w * calc.max(max-r, 1) + 0.4
+#cetz.canvas(length: calc.min(theme.width / W, theme.height / (H + 1)), {
+ import cetz.draw: *
+ for (i, (name, r, note)) in rows.enumerate() {
+ let yy = H - (i + 0.5) * 0.8
+ let c = if r > 1 { theme.red } else if r > 0.9 { theme.orange } else { theme.green }
+ content((label-w - 0.2, yy), name, anchor: "east")
+ rect((label-w, yy - 0.25), (label-w + bar-w * r, yy + 0.25), fill: c.transparentize(30%), stroke: none)
+ content((note-x + 0.9, yy), text(size: 0.85em, str(int(r * 100)) + "%"), anchor: "east")
+ content((note-x + 1.2, yy), text(fill: theme.muted, size: 0.85em, note), anchor: "west")
+ }
+ // The 100% line, drawn last so it is on top; its label goes above the rows
+ line((label-w + bar-w, 0), (label-w + bar-w, H + 0.1), stroke: (paint: theme.fg, dash: "dashed"))
+ content((label-w + bar-w, H + 0.1), text(fill: theme.muted, size: 0.8em)[budget 100%], anchor: "south")
+})
+```
+
+### 3.3 Heatmap
+
+`color.mix((theme.bg, (1 - t) * 100%), (c, t * 100%))` gives a scale that fades into the background in both modes.
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Heatmap: one rect per cell, colour = theme colour mixed by value
+#let days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
+#let hours = range(0, 24)
+#let v(d, hr) = calc.max(0, calc.sin((hr - 6) / 24 * 2 * calc.pi)) * (if d < 5 { 1 } else { 0.4 }) + calc.rem(d * 7 + hr * 3, 5) / 20
+#let (W, H) = (24 * 0.6, 7 * 0.5)
+#cetz.canvas(length: calc.min(theme.width / (W + 2.2), theme.height / (H + 1.2)), {
+ import cetz.draw: *
+ for (d, day) in days.enumerate() {
+ let yy = H - (d + 1) * 0.5
+ content((-0.15, yy + 0.25), text(fill: theme.muted, size: 0.8em, day), anchor: "east")
+ for hr in hours {
+ let t = calc.min(1, v(d, hr))
+ // color.mix blends two theme colours; t = 0 is the background
+ let c = color.mix((theme.bg, (1 - t) * 100%), (theme.orange, t * 100%))
+ rect((hr * 0.6, yy), (rel: (0.56, 0.46)), fill: c, stroke: none, radius: 0.04)
+ }
+ }
+ for hr in range(0, 24, step: 3) {
+ content((hr * 0.6 + 0.28, -0.1), text(fill: theme.muted, size: 0.75em, str(hr) + "h"), anchor: "north")
+ }
+ // Legend: a gradient bar in its own column
+ rect((W + 0.4, 0), (W + 0.7, H), stroke: theme.border, fill: gradient.linear(theme.orange, theme.bg, angle: 90deg))
+ content((W + 0.8, H), text(fill: theme.muted, size: 0.75em)[high], anchor: "north-west")
+ content((W + 0.8, 0), text(fill: theme.muted, size: 0.75em)[low], anchor: "south-west")
+})
+```
+
+### 3.4 Gantt
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Gantt: tasks (name, start week, length, colour); time axis on top
+#let tasks = (([Research], 0, 3, theme.blue), ([Design], 2, 3, theme.purple), ([Backend], 4, 6, theme.orange),
+ ([Frontend], 5, 5, theme.orange), ([QA], 9, 3, theme.green), ([Launch], 12, 1, theme.red))
+#let weeks = 14
+#let (lw, uw, rh) = (2.4, 0.9, 0.6) // label column, units per week, row height
+#let H = tasks.len() * rh
+#cetz.canvas(length: calc.min(theme.width / (lw + weeks * uw + 0.3), theme.height / (H + 1)), {
+ import cetz.draw: *
+ for w in range(weeks + 1) {
+ line((lw + w * uw, 0), (lw + w * uw, H), stroke: theme.border + 0.4pt)
+ if w < weeks { content((lw + (w + 0.5) * uw, H + 0.1), text(fill: theme.muted, size: 0.75em, "W" + str(w + 1)), anchor: "south") }
+ }
+ for (i, (name, s, n, c)) in tasks.enumerate() {
+ let yy = H - (i + 1) * rh
+ content((lw - 0.2, yy + rh / 2), name, anchor: "east")
+ rect((lw + s * uw, yy + 0.1), (lw + (s + n) * uw, yy + rh - 0.1), fill: c.transparentize(40%), stroke: c, radius: 0.08)
+ }
+ // Today marker
+ let today = lw + 6.4 * uw
+ line((today, -0.05), (today, H), stroke: theme.red + 1.2pt)
+ content((today, -0.05), text(fill: theme.red, size: 0.75em)[today], anchor: "north")
+})
+```
+
+### 3.5 Waterfall
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Waterfall: each step starts where the last one ended; totals are full bars
+#let steps = (([Q3 ARR], 120, "total"), ([New], 34, "step"), ([Expansion], 18, "step"),
+ ([Churn], -22, "step"), ([Downgrade], -9, "step"), ([Q4 ARR], 141, "total"))
+#let (W, H, top) = (14, 4, 180)
+#let y(v) = v / top * H
+#let dx = W / steps.len()
+#cetz.canvas(length: calc.min(theme.width / (W + 1), theme.height / (H + 1)), {
+ import cetz.draw: *
+ for v in range(0, top + 1, step: 40) {
+ line((0, y(v)), (W, y(v)), stroke: theme.border + 0.4pt)
+ content((-0.15, y(v)), text(fill: theme.muted, size: 0.8em, str(v)), anchor: "east")
+ }
+ let run = 0
+ for (i, (name, v, kind)) in steps.enumerate() {
+ let (a, b, c) = if kind == "total" { (0, v, theme.blue) } else if v >= 0 { (run, run + v, theme.green) } else { (run + v, run, theme.red) }
+ run = if kind == "total" { v } else { run + v }
+ let x0 = i * dx + dx * 0.15
+ rect((x0, y(a)), (x0 + dx * 0.7, y(b)), fill: c.transparentize(25%), stroke: none)
+ let sign = if kind == "step" and v > 0 { "+" } else { "" }
+ content((x0 + dx * 0.35, y(calc.max(a, b)) + 0.08), text(size: 0.8em, sign + str(v)), anchor: "south")
+ content((x0 + dx * 0.35, -0.1), text(fill: theme.muted, size: 0.8em, name), anchor: "north")
+ // Connector to the next bar
+ if i < steps.len() - 1 {
+ line((x0 + dx * 0.7, y(run)), (x0 + dx * 1.15, y(run)), stroke: (paint: theme.muted, dash: "dotted"))
+ }
+ }
+})
+```
+
+### 3.6 Sparklines in a table
+
+Small canvases (`length: 1em`) inside a Typst `table`; no axes.
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Sparklines: one tiny canvas per row inside a Typst table
+#let spark(ys, c) = cetz.canvas(length: 1em, {
+ import cetz.draw: *
+ let (lo, hi) = (calc.min(..ys), calc.max(..ys))
+ let pts = ys.enumerate().map(((i, v)) => (i * 6 / (ys.len() - 1), (v - lo) / (hi - lo) * 1.2))
+ line(..pts, stroke: c + 1pt)
+ circle(pts.last(), radius: 0.12, fill: c, stroke: none)
+})
+#let rows = (
+ ([API p95], (210, 190, 230, 250, 240, 280, 300, 290, 320), [320 ms], theme.red),
+ ([Error rate], (2.1, 1.8, 1.5, 1.6, 1.2, 1.1, 0.9, 1.0, 0.8), [0.8 %], theme.green),
+ ([Sign-ups], (40, 42, 39, 51, 55, 53, 60, 64, 71), [71 /day], theme.blue),
+ ([Queue depth], (5, 9, 4, 12, 6, 15, 7, 11, 8), [8], theme.orange),
+)
+#table(columns: (auto, auto, auto), stroke: none, inset: (x: 10pt, y: 5pt), align: (left + horizon, center + horizon, right + horizon),
+ table.header(text(fill: theme.muted)[metric], text(fill: theme.muted)[last 9 days], text(fill: theme.muted)[now]),
+ table.hline(stroke: theme.border),
+ ..rows.map(((n, ys, now, c)) => (n, spark(ys, c), strong(now))).flatten(),
+)
+```
+
+### 3.7 Bullet bars
+
+Bands for poor/ok/good, the value as a thin bar, the target as a tick.
+
+```typst
+#import "@preview/cetz:0.5.2"
+// Bullet bars: bands (poor/ok/good), the value bar and a target tick per row
+#let rows = (([Revenue], 0.72, 0.85, [\$7.2M of \$8.5M]), ([Profit], 0.55, 0.6, [22% margin]),
+ ([New users], 0.93, 0.8, [9.3k, target 8k]), ([NPS], 0.38, 0.5, [38]))
+#let (lw, bw, rh) = (2.4, 9, 0.75)
+#let H = rows.len() * rh
+#cetz.canvas(length: calc.min(theme.width / (lw + bw + 3.6), theme.height / (H + 0.3)), {
+ import cetz.draw: *
+ for (i, (name, v, target, note)) in rows.enumerate() {
+ let y0 = H - (i + 1) * rh + 0.12
+ content((lw - 0.2, y0 + 0.25), strong(name), anchor: "east")
+ // Bands: three muted shades
+ for (a, b, t) in ((0, 0.5, 85%), (0.5, 0.8, 78%), (0.8, 1, 70%)) {
+ rect((lw + a * bw, y0), (lw + b * bw, y0 + 0.5), fill: theme.muted.transparentize(t), stroke: none)
+ }
+ rect((lw, y0 + 0.17), (lw + v * bw, y0 + 0.33), fill: theme.fg, stroke: none)
+ line((lw + target * bw, y0 + 0.05), (lw + target * bw, y0 + 0.45), stroke: theme.orange + 2pt)
+ content((lw + bw + 0.3, y0 + 0.25), text(fill: theme.muted, size: 0.85em, note), anchor: "west")
+ }
+})
+```
+
+## 4. Traps
+
+- `bar-style`, `slice-style`, `level-style`, `data-style` default to `cetz.palette.red`. `cetz.palette.new(colors: theme.palette)`
+ keeps a **black** stroke: write a function `i => (fill: theme.palette.at(calc.rem(i, 6)), stroke: none)` instead.
+- Bar and box charts set `axes: (grid: (stroke: (dash: "dotted", paint: gray)))` inside their group, and this wins over a
+ global `axes` grid style (the column chart sets only the dash). Set the grid under the chart root: `barchart: (axes: (grid: ...))`.
+- `chart.boxwhisker` colours come from `plot-style`, not from `set-style(fill: ...)`.
+- `piechart` shows a white legend whenever items have labels. Turn it off (`legend: (label: none)`) or give it `fill: theme.bg`.
+- Small pie slices: their inner labels collide. Use a label function that returns `none` below a limit.
+- `radarchart` values are fractions of the radius (0..1).
+- In content, `$` starts math: write `[M\$]`, `[\$7.2M]`.
+- The default `size: (auto, 1)` of bar and column charts gives a tiny chart: always give `size: (W, H)`.
diff --git a/skills/intelligent-ui/references/fletcher.md b/skills/intelligent-ui/references/fletcher.md
new file mode 100644
index 0000000..ca58a6b
--- /dev/null
+++ b/skills/intelligent-ui/references/fletcher.md
@@ -0,0 +1,445 @@
+# fletcher 0.5.8: diagrams with nodes and arrows
+
+fletcher draws flow charts, pipelines, state machines, block diagrams, trees and commutative diagrams
+on an elastic grid. Facts here come from the vendored source (`render/packages/preview/fletcher/0.5.8/src/`).
+Every ```` ```typst ```` example was compiled with the real template in dark and light and checked by eye.
+
+Contents
+1. Start here: the safe skeleton
+2. `diagram()` parameters
+3. `node()` parameters and shapes
+4. `edge()` parameters, marks and flags
+5. Coordinates, names, paths
+6. Groups (`enclose`) and layers
+7. Wide and short layouts
+8. Recipes: pipeline + feedback, decision flow, state machine, architecture groups, sequence lanes, tree, commutative diagrams, network, parallel edges, coordinate forms
+9. Traps and fletcher error messages
+
+## 1. Start here: the safe skeleton
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, // defaults: no node outline, black edges
+ node-shape: rect, // auto makes short labels circles
+ crossing-fill: theme.bg, // default is white: white boxes on dark
+ spacing: (3em, 1.5em), // (between columns, between rows)
+ node((0, 0), [A], name: <a>, fill: theme.blue.transparentize(80%)),
+ node((1, 0), [B], name: <b>),
+ edge(<a>, <b>, "->", [label]),
+)
+```
+
+`as fletcher` keeps `fletcher.shapes.*` reachable. `diagram`, `node`, `edge` must be imported in **each** block.
+
+## 2. `diagram()` parameters
+
+| Parameter | Default | Notes |
+|---|---|---|
+| `spacing` | `3em` | gap between bounding boxes of adjacent rows/columns; `(x, y)` pair |
+| `cell-size` | `0pt` | minimum row/column size, centre to centre; `(w, h)` pair; use it to fill `theme.width` |
+| `node-stroke` | `none` | default node outline; pass `theme.fg` |
+| `node-fill` | `none` | default node fill |
+| `node-shape` | `auto` | `auto` = circle when the label is roundish (aspect < 1.5), else rect |
+| `node-inset` | `6pt` | padding inside nodes |
+| `node-outset` | `0pt` | gap between node and edge ends |
+| `node-corner-radius` | `none` | rounded rects |
+| `node-defocus` | `0.2` | how edges aim at wide nodes; `0` = at the centre |
+| `edge-stroke` | `0.048em` (black) | pass `theme.fg`; marks scale with its thickness |
+| `edge-corner-radius` | `2.5pt` | rounding of poly-edge corners |
+| `label-sep` | `0.4em` | gap between edge and label |
+| `label-size` | `1em` | edge label text size |
+| `label-wrapper` | box with `label-fill` | function `edge => content` |
+| `mark-scale` | `100%` | arrowhead size |
+| `crossing-fill` | `white` | fill behind `crossing` edges and `label-side: center` labels: pass `theme.bg` |
+| `crossing-thickness` | `5` | gap width, in stroke widths |
+| `axes` | `(ltr, ttb)` | y grows downwards; `(ltr, btt)` for maths-style |
+| `debug` | `false` | `1` shows the grid, `2`–`3` boxes and anchors |
+| `render` | cetz canvas | `(grid, nodes, edges, options) => …` for custom drawing |
+
+Positional arguments are nodes and edges; arrays and `{ … }` code blocks of them work, so build them with `for` and `.map()` and spread with `..`.
+
+## 3. `node()` parameters and shapes
+
+`node(pos, label, ..)`: up to two positional arguments. One positional argument that is an array, dictionary or label is the position.
+
+| Parameter | Notes |
+|---|---|
+| `pos` | `(x, y)` elastic, `<name>`, `(rel: (dx, dy), to: <name>)` |
+| `label` | content; `align(top + left)[…]` places it in a larger node |
+| `name` | a label `<id>`, or a string (converted). `label("w" + str(i))` makes names in loops |
+| `width`, `height` | fixed size; else label + 2 × inset |
+| `radius` | fixed circle radius (does not grow with the label) |
+| `inset`, `outset`, `fill`, `stroke`, `corner-radius`, `shape`, `defocus` | per-node overrides |
+| `extrude` | extra outlines: `(0, 3)` double, `(0, -3)` inner ring (accept state); numbers = stroke widths |
+| `enclose` | positions/names to surround (a group box); the node's own `pos` is then ignored |
+| `layer` | draw order; `enclose` nodes default to `-1` (behind) |
+| `snap` | edge snapping priority; `false` = edges never snap to it |
+
+`stroke: none` makes a text-only node. A node with `[]` and `stroke: none` is an invisible anchor (an entry arrow start).
+
+Shapes (`fletcher.shapes.*`, pass the function: `shape: fletcher.shapes.diamond`): `rect`, `circle`, `ellipse`, `pill`,
+`diamond`, `hexagon`, `octagon`, `cylinder` (database), `parallelogram`, `trapezium`, `triangle`, `house`, `chevron`,
+`brace`, `bracket`, `paren`. Options with `.with(…)`: `diamond.with(fit: 0.5)`, `cylinder.with(tilt: 8deg, rings: 4pt)`,
+`triangle.with(dir: top)`, `chevron.with(dir: right)`, `parallelogram.with(angle: 20deg)`, `brace.with(dir: bottom, label: […])`.
+The plain functions `rect`, `circle` and the strings `"rect"`, `"circle"` also work; other strings (`"diamond"`) fail.
+
+## 4. `edge()` parameters, marks and flags
+
+`edge(from, to, marks, label, ..)`: vertices first, then a marks string and a content label in any order.
+
+| Parameter | Notes |
+|---|---|
+| vertices | `edge(<a>, <b>)`, `edge(<a>, (2, 1), (4, 1), <b>)` (poly line), `edge(<a>, "r,d")`, `edge("r")` (from the previous node), `edge()` (previous to next node) |
+| `marks` | string shorthand (below) or an array of mark names / dictionaries |
+| `label` | content (a string positional is read as marks, not as a label) |
+| `label-side` | `left`, `right`, `center`, `auto`: left/right of the direction of travel |
+| `label-pos` | `0.5` / `50%` along the edge; `(segment, 50%)` for a poly edge; `100% - 1em` |
+| `label-sep`, `label-angle`, `label-anchor`, `label-size` | fine placement |
+| `label-fill` | `true` = `crossing-fill`; auto is on only for `label-side: center` |
+| `stroke` | `theme.muted`, `1pt + theme.red`, `(paint: theme.fg, dash: "dashed")` |
+| `dash` | `"dashed"`, `"dotted"`, … |
+| `bend` | arc; positive bends to the left of travel (a left-to-right edge bulges up) |
+| `loop-angle` | self loop direction with `edge(<n>, <n>, bend: 130deg)`: `90deg` up, `-90deg` down, `0deg` right, `180deg` left |
+| `corner` | `left` / `right`: one right-angled corner between two points |
+| `corner-radius` | per edge; `none` ≠ `0pt` |
+| `shift` | sideways offset, for parallel edges: `shift: 4pt` |
+| `extrude` | multi-stroke, `(-2, 2)` = double |
+| `decorations` | `"wave"`, `"zigzag"`, `"coil"` |
+| `crossing` | draw a `crossing-fill` gap under this edge where it crosses others |
+| `layer` | `-1` puts guide lines (lifelines) behind |
+| `snap-to` | `(auto, none)` etc.: which nodes the ends attach to |
+| `floating` | do not affect the diagram size |
+
+Marks shorthand = mark, line, mark: `"->"` `"<-"` `"<->"` `"=>"` (double) `"==>"` (triple) `"-->"` (dashed) `"..>"` (dotted)
+`"~>"` (wave) `"-|>"` (solid triangle) `"-}>"` (stealth) `"->>"` (two heads) `">->"` (tail) `"|->"` (maps-to) `"hook->"` `"hook'->"`
+`"-o"` `"-O"` `"*-*"` (dots) `"-@"` `"x-x"` `"<>-"` (diamond) `"-/-"` (slash) `"-||-"` `"-[]"` `"-"` (plain) `"--"` (dashed plain).
+Crow's foot (ER diagrams): `"n-1"`, `"n!-1!"`, `"n?-1?"`. Flags as positional strings: `"dashed"`, `"dotted"`, `"double"`,
+`"triple"`, `"crossing"`, `"wave"`, `"zigzag"`, `"coil"`. Line styles in the middle: `-` `=` `==` `--` `..` `~`.
+A bad string fails with ``Invalid marks shorthand `-->>-x`. Try `-->>--x`.``
+
+## 5. Coordinates, names, paths
+
+- `(x, y)`: column, row. Columns and rows are elastic: each is as wide/tall as its largest node, and `spacing` goes between them.
+- Fractional positions (`(1, 0.5)`, `(3, -0.8)`) are interpolated between rows/columns. They get **no spacing of their own**:
+ two nodes at rows 0 and 0.5 overlap. Use integers for nodes that stack, fractions for nodes between them and for edge corner points.
+- Names: `name: <db>`, then `edge(<api>, <db>)`. Names make edits safe (move a node, edges follow).
+- Relative: `(rel: (1, 0), to: <b>)`. Shorthand vertex strings (not as the first vertex): `"r"`, `"l"`, `"u"`/`"t"`, `"d"`/`"b"`, combined `"d,r,r"`.
+- A poly edge goes through every vertex in order; the first and last snap to the nodes there.
+
+## 6. Groups (`enclose`) and layers
+
+- `node(enclose: (<a>, <b>, (3, 1)), stroke: (paint: c, dash: "dashed"), fill: c.transparentize(94%), inset: 8pt)` draws a box around members, behind them (layer -1).
+- `enclose` makes **no room for the group's own label**: a label in the group node overlaps the members. Put the title in its own
+ `stroke: none` node above the members and enclose that node too (recipe 8.4).
+- Edges to `<a>` still attach to `<a>`, not to the group. To attach to the group, name it and use that name.
+- Groups grow the grid like other nodes; leave a free fractional row for the title.
+
+## 7. Wide and short layouts
+
+- Lay flows left to right; use 1–3 rows. Make the column spacing larger than the row spacing: `spacing: (4em, 1.4em)`.
+- A diagram has its natural size; it does not stretch to `theme.width`. To fill the width with `n` columns:
+ `spacing: (1em, …), cell-size: (theme.width / n - 1em, 0pt)`; or for fixed-width nodes of width `nw`:
+ `spacing: (0pt, …), cell-size: ((theme.width - nw) / (n - 1), …)`.
+- fletcher makes no space for edge labels: a label wider than its gap overlaps nodes. Short labels, `\` breaks, wider gaps.
+- Route long back-edges through a free row above or below (`(x, -0.8)`), never through a row with nodes.
+- A diagram wider than the block is scaled down (smaller text). A tall one is not.
+
+## 8. Recipes
+
+### 8.1 Pipeline with a feedback loop
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, node-shape: rect,
+ node-corner-radius: 3pt, crossing-fill: theme.bg, spacing: (4em, 1.4em),
+ node((0, 0), [Source], fill: theme.blue.transparentize(80%), name: <src>),
+ node((1, 0), [Parse], fill: theme.purple.transparentize(80%), name: <parse>),
+ node((2, 0), [Validate], fill: theme.orange.transparentize(80%), name: <val>),
+ node((3, 0), [Enrich], fill: theme.yellow.transparentize(80%), name: <enr>),
+ node((4, 0), [Store], fill: theme.green.transparentize(80%), name: <db>, shape: fletcher.shapes.cylinder),
+ node((2, 1), text(fill: theme.red)[dead-letter], stroke: (paint: theme.red, dash: "dashed"), name: <dlq>),
+ edge(<src>, <parse>, "->"),
+ edge(<parse>, <val>, "->"),
+ edge(<val>, <enr>, "->", [ok], label-side: right),
+ edge(<enr>, <db>, "->"),
+ edge(<val>, <dlq>, "->", text(fill: theme.red)[bad], label-side: left),
+ // feedback above the row (row 1 is taken): up, left, down
+ edge(<enr>, (3, -0.8), (1, -0.8), <parse>, "->", stroke: theme.accent, text(fill: theme.accent)[retry]),
+)
+```
+
+### 8.2 Decision flow chart (diamonds), filling the width
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#let cols = 5
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, node-shape: rect, crossing-fill: theme.bg,
+ // fill theme.width: cols cells + (cols - 1) gaps
+ spacing: (1em, 1.8em), cell-size: (theme.width / cols - 1em, 0pt),
+ node((0, 0), [Request], shape: fletcher.shapes.pill, fill: theme.blue.transparentize(80%), name: <in>),
+ node((1, 0), [Cached?], shape: fletcher.shapes.diamond, fill: theme.yellow.transparentize(80%), name: <q1>),
+ node((2, 0), [Authorised?], shape: fletcher.shapes.diamond, fill: theme.yellow.transparentize(80%), name: <q2>),
+ node((3, 0), [Query DB], fill: theme.purple.transparentize(80%), name: <db>),
+ node((4, 0), [200 OK], shape: fletcher.shapes.pill, fill: theme.green.transparentize(80%), name: <ok>),
+ node((2, 1), [401], shape: fletcher.shapes.pill, fill: theme.red.transparentize(80%), name: <deny>),
+ edge(<in>, <q1>, "->"),
+ edge(<q1>, <q2>, "->", [no]),
+ edge(<q2>, <db>, "->", [yes]),
+ edge(<db>, <ok>, "->"),
+ edge(<q2>, <deny>, "->", [no], label-side: left),
+ // yes from the cache: around the bottom, past the 401 node
+ edge(<q1>, (1, 1.6), (4, 1.6), <ok>, "->", [yes], label-pos: 0.3, label-side: left),
+)
+```
+
+### 8.3 State machine with self-loops
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#let st(pos, name, body, c) = node(pos, body, name: name, shape: circle, fill: c.transparentize(80%))
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, spacing: (7em, 2em), node-inset: 8pt,
+ node((-0.6, 0), [], name: <start>, stroke: none),
+ st((0, 0), <idle>, [Idle], theme.blue),
+ st((1, 0), <run>, [Running], theme.green),
+ st((2, 0), <paused>, [Paused], theme.yellow),
+ node((3, 0), [Done], name: <done>, shape: circle, extrude: (0, -3), fill: theme.purple.transparentize(80%)),
+ edge(<start>, <idle>, "-|>"),
+ edge(<idle>, <run>, "->", [start], bend: 25deg),
+ edge(<run>, <idle>, "->", [reset], bend: 25deg),
+ edge(<run>, <paused>, "->", [pause], bend: 25deg),
+ edge(<paused>, <run>, "->", [resume], bend: 25deg),
+ edge(<run>, <run>, "->", [tick], bend: 130deg, loop-angle: 90deg, label-sep: 0.2em),
+ edge(<paused>, <paused>, "->", [poll], bend: 130deg, loop-angle: -90deg),
+ edge(<paused>, <done>, "->", [stop]),
+)
+```
+
+### 8.4 Architecture with grouped subsystems
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#let part(pos, body, name, c) = node(pos, body, name: name, fill: c.transparentize(80%), stroke: c)
+// enclose makes no room for a group's own label: give the title its own
+// text node above the members and enclose it too.
+#let group(pos, title, members, c) = (
+ node(pos, text(size: 0.8em, fill: c, weight: "bold", title), stroke: none, name: label(title)),
+ node(enclose: members + (label(title),), inset: 8pt, corner-radius: 6pt,
+ stroke: (paint: c, dash: "dashed"), fill: c.transparentize(94%)),
+)
+#diagram(
+ node-shape: rect, node-corner-radius: 3pt, edge-stroke: theme.fg,
+ spacing: (4em, 1.2em),
+ node((0, 0.5), [Browser], name: <web>, stroke: theme.fg),
+ node((0, 1.5), [Mobile], name: <app>, stroke: theme.fg),
+ part((1, 1), [API gateway], <gw>, theme.purple),
+ part((2, 0), [Users], <users>, theme.blue),
+ part((2, 1), [Orders], <orders>, theme.blue),
+ part((2, 2), [Billing], <billing>, theme.blue),
+ part((3, 0.5), [Postgres], <pg>, theme.green),
+ part((3, 1.5), [Kafka], <kafka>, theme.orange),
+ ..group((2, -0.7), "services", (<users>, <orders>, <billing>), theme.blue),
+ ..group((3, -0.2), "data", (<pg>, <kafka>), theme.green),
+ edge(<web>, <gw>, "->"), edge(<app>, <gw>, "->"),
+ edge(<gw>, <users>, "->"), edge(<gw>, <orders>, "->"), edge(<gw>, <billing>, "->"),
+ edge(<users>, <pg>, "->"), edge(<orders>, <pg>, "->"),
+ edge(<orders>, <kafka>, "->"), edge(<kafka>, <billing>, "->"),
+)
+```
+
+### 8.5 Sequence-style lanes
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#let actors = ([Client], [API], [Auth], [DB])
+#let msgs = (
+ // (from, to, row, label, dashed reply?)
+ (0, 1, 1, [POST /login], false),
+ (1, 2, 2, [verify(pw)], false),
+ (2, 3, 3, [SELECT user], false),
+ (3, 2, 4, [row], true),
+ (2, 1, 5, [token], true),
+ (1, 0, 6, [200 + cookie], true),
+)
+#let last = msgs.len() + 1
+#diagram(
+ edge-stroke: theme.fg, node-stroke: theme.fg, node-shape: rect,
+ spacing: (0pt, 0pt), // column centres are cell-size apart: n - 1 gaps + one node width = theme.width
+ cell-size: ((theme.width - 6em) / (actors.len() - 1), 1.7em),
+ ..actors.enumerate().map(((x, a)) => (
+ node((x, 0), a, fill: theme.palette.at(x).transparentize(80%), width: 6em),
+ edge((x, 0), (x, last), stroke: (paint: theme.muted, dash: "dashed"), layer: -1),
+ )).flatten(),
+ ..msgs.map(((a, b, y, l, reply)) => edge((a, y), (b, y), l,
+ if reply { "--|>" } else { "-|>" },
+ stroke: if reply { theme.muted } else { theme.fg }, label-sep: 0.15em)),
+)
+```
+
+### 8.6 Tree / hierarchy (computed layout)
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+// (label, children). Leaves go left to right; a parent sits over the middle
+// of its children. Returns (next free x, own x, nodes and edges).
+#let tree(t, depth: 0, x: 0) = {
+ let (body, kids) = t
+ let fill = theme.palette.at(depth).transparentize(80%)
+ if kids.len() == 0 { return (x + 1, x, (node((x, depth), body, fill: fill),)) }
+ let (nx, xs, items) = (x, (), ())
+ for k in kids {
+ let (n, kx, its) = tree(k, depth: depth + 1, x: nx)
+ (nx, xs, items) = (n, xs + (kx,), items + its)
+ }
+ let me = (xs.first() + xs.last()) / 2
+ items.push(node((me, depth), body, fill: fill))
+ for kx in xs {
+ // org-chart elbows: down, across, down (straight when right below:
+ // two equal vertices in a row are an error)
+ items.push(if kx == me { edge((me, depth), (kx, depth + 1)) } else {
+ edge((me, depth), (me, depth + 0.5), (kx, depth + 0.5), (kx, depth + 1))
+ })
+ }
+ (nx, me, items)
+}
+// text(font: theme.mono), not raw: raw gets the inline-code box and colour
+#let mono(s) = text(font: theme.mono, s)
+#let leaf(l) = (mono(l), ())
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.muted, node-shape: rect, node-corner-radius: 3pt,
+ spacing: (1.2em, 1.6em),
+ ..tree((mono("src/"), (
+ (mono("app/"), (leaf("main.rs"), leaf("cli.rs"))),
+ (mono("core/"), (leaf("parse.rs"), leaf("eval.rs"), leaf("types.rs"))),
+ (mono("util/"), (leaf("log.rs"),)),
+ ))).at(2),
+)
+```
+
+### 8.7 Commutative diagrams (math)
+
+In math mode `&` separates columns and `\` rows; `edge(..)` inside a cell starts at that cell. Inside `$…$` use `#` for
+non-math values (`label-side: #right`).
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#grid(columns: (1fr, 1fr, 1fr), align: center + horizon,
+ // math mode: & separates columns, \ rows; edge() in a cell starts there
+ diagram(edge-stroke: theme.fg, spacing: 3em, $
+ A edge(f, ->) edge("d", g, ->, label-side: #right) & B edge("d", h, ->) \
+ C edge(k, "->", label-side: #right) & D
+ $),
+ // the same with explicit coordinates, plus a dashed unique arrow
+ diagram(edge-stroke: theme.fg, spacing: (3.5em, 2.5em), crossing-fill: theme.bg,
+ node((0, 0), $X$), node((1, 0), $X times Y$), node((2, 0), $Y$),
+ node((1, 1), $Z$),
+ edge((1, 0), (0, 0), $pi_1$, "->", label-side: right),
+ edge((1, 0), (2, 0), $pi_2$, "->"),
+ edge((1, 1), (0, 0), $f$, "->", label-side: left),
+ edge((1, 1), (2, 0), $g$, "->", label-side: right),
+ edge((1, 1), (1, 0), $exists ! u$, "-->", label-side: center),
+ ),
+ diagram(edge-stroke: theme.fg, spacing: 4em,
+ node((0, 0), $V$), node((1, 0), $W$),
+ edge((0, 0), (1, 0), $T$, "->", bend: 30deg),
+ edge((1, 0), (0, 0), $T^(-1)$, "->", bend: 30deg),
+ edge((0, 0), (0, 0), $id$, "->", bend: 130deg, loop-angle: 180deg),
+ ),
+)
+```
+
+### 8.8 Network / topology
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#let dev(pos, body, name, c, shape: rect) = node(pos, body, name: name, shape: shape,
+ fill: c.transparentize(80%), stroke: c)
+#diagram(
+ edge-stroke: theme.fg, node-corner-radius: 3pt, crossing-fill: theme.bg,
+ // rows 0..5 hold the servers (integer rows get the spacing);
+ // the other nodes sit between them at fractional rows
+ spacing: (3.5em, 0.5em),
+ dev((0, 2.5), [Internet], <net>, theme.muted, shape: fletcher.shapes.ellipse),
+ dev((1, 2.5), [Firewall], <fw>, theme.red, shape: fletcher.shapes.hexagon),
+ dev((2, 1), [Router A], <ra>, theme.purple),
+ dev((2, 4), [Router B], <rb>, theme.purple),
+ dev((3, 1), [Switch 1], <s1>, theme.blue),
+ dev((3, 4), [Switch 2], <s2>, theme.blue),
+ ..range(3).map(i => dev((4, i), [web #(i + 1)], label("w" + str(i)), theme.green)),
+ ..range(3).map(i => dev((4, 3 + i), [db #(i + 1)], label("d" + str(i)), theme.orange)),
+ edge(<net>, <fw>, "<->"),
+ edge(<fw>, <ra>, "-"), edge(<fw>, <rb>, "-"),
+ edge(<ra>, <s1>, "-"), edge(<rb>, <s2>, "-"),
+ // redundant cross links; `crossing` cuts a gap in what lies under
+ edge(<ra>, <s2>, "-", stroke: (paint: theme.muted, dash: "dashed")),
+ edge(<rb>, <s1>, "-", stroke: (paint: theme.muted, dash: "dashed"), crossing: true),
+ ..range(3).map(i => edge(<s1>, label("w" + str(i)), "-")),
+ ..range(3).map(i => edge(<s2>, label("d" + str(i)), "-")),
+)
+```
+
+### 8.9 Parallel edges with labels outside
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, node-shape: rect, spacing: 8em,
+ node((0, 0), [Client], name: <c>),
+ node((1, 0), [Server], name: <s>),
+ // two parallel edges: shift them apart. `left` is left of the direction
+ // of travel, so both labels go to the outer sides.
+ edge(<c>, <s>, "->", [request \ (JSON)], shift: 4pt, label-side: left),
+ edge(<s>, <c>, "->", text(fill: theme.muted)[response], shift: 4pt, label-side: left),
+)
+```
+
+### 8.10 Coordinate forms, corners, shorthands
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, node-shape: rect, crossing-fill: theme.bg,
+ spacing: (3em, 1.5em),
+ node((0, 0), [A], name: <a>),
+ edge("r", "->", [next]), // from the last node, one column right
+ node((1, 0), [B], name: <b>),
+ node((rel: (1, 1), to: <b>), [C], name: <c>), // relative to a named node
+ edge(<b>, <c>, "->", corner: right), // one right-angled corner
+ edge(<a>, "d,r,r", "-->", [via d], label-pos: (1, 50%)), // shorthand path; label on segment 1
+ node((3, 0), [D], name: <d>, extrude: (0, 3)), // double outline
+ edge(<c>, <d>, "=>", bend: -30deg),
+ edge(<b>, <d>, "->", [over], label-side: center, bend: 40deg), // label on the line, crossing-fill behind it
+)
+```
+
+## 9. Traps and fletcher error messages
+
+Traps (each one seen in a render):
+- `crossing-fill` defaults to **white**: `label-side: center` labels and `crossing` edges show white boxes on dark. Set `crossing-fill: theme.bg`.
+- `node-stroke` defaults to none and `edge-stroke` to black: always pass `theme.fg`. Give text-only nodes `stroke: none`.
+- `node-shape: auto` turns short labels (`[A]`, `[Done]`) into circles: set `node-shape: rect`.
+- `diamond`, `triangle`, `chevron` … are drawn **larger** than the box used for layout: neighbours touch. Add spacing around them.
+- Nodes at fractional rows/columns get no spacing and overlap. Stack nodes on integer rows.
+- Edges do not avoid nodes: a corner path through a row with nodes crosses them. Use a free (fractional) row.
+- Two equal vertices in a row (a corner at the start point) fail with `Adjacent vertices must be distinct.` Use a straight edge then.
+- `radius:` fixes a circle size; a longer label spills out. Leave `radius` out to size by the label.
+- `label-side: auto` puts the labels of two parallel edges both above. Use `label-side: left` on both (left of travel).
+- Node names in `edge()` must be labels `<a>`. A string `"a"` is read as marks: `Marks argument passed to edge() twice; found "a" and "->"`.
+- Edge labels must be content `[ok]`. A string `"ok"` is read as marks: ``Couldn't interpret `edge()` arguments `ok`. Try using named arguments.``
+- `raw` inside node labels gets the inline-code box. Use `text(font: theme.mono)[…]`.
+- A helper parameter named `label` shadows the `label()` function inside it. Name it `body`.
+- Marks scale with stroke thickness: `stroke: 2pt + …` gives large heads; lower `mark-scale`.
+
+| Message | Fix |
+|---|---|
+| `Node `zz` not found. Named nodes are: …` | spell the name; define the node in this diagram |
+| `Invalid marks shorthand …. Try ….` | use the suggested string |
+| `` `label-side` must be one of `left`, `center`, `right`, or `auto`; got `top`. `` | `top`/`bottom` are not sides; use `left`/`right` |
+| `expected function, found string` (in `draw.typ`) | `shape: "diamond"`: pass `fletcher.shapes.diamond` |
+| `Adjacent vertices must be distinct.` | remove the duplicate vertex |
+| ``Couldn't interpret `edge()` arguments …`` | a string where content was meant: `[ok]`, not `"ok"` |
+| `Marks argument passed to edge() twice` | a node name given as a string: `<a>`, not `"a"` |
+| `unknown variable: node` | add the `#import` line to this block |
diff --git a/skills/intelligent-ui/references/plot.md b/skills/intelligent-ui/references/plot.md
new file mode 100644
index 0000000..b5413bc
--- /dev/null
+++ b/skills/intelligent-ui/references/plot.md
@@ -0,0 +1,411 @@
+# cetz-plot 0.1.4: `plot`
+
+Use `plot` for data on numeric axes: lines, scatter, functions, bands, log scales, bars on a numeric x,
+error bars, box and violin plots, contours. For category charts (bars by name, pies, radar) see charts.md.
+Every ```` ```typst ```` example in this file was compiled with the real template, in dark and light.
+
+Contents
+1. Set-up: imports, size, theme style
+2. `plot.plot` parameters
+3. Axis options (`x-…`, `y-…`, `x2-…`, `y2-…`)
+4. Series colours: `plot-style`, `mark-style`, `style`
+5. The add functions
+6. Legend
+7. Recipes: lines, scatter, functions, band, log, dual axis, histogram, error bars, box/violin, contour, annotations
+8. Traps
+
+## 1. Set-up
+
+```
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg, minor-stroke: theme.muted),
+ grid: (stroke: theme.border + 0.5pt), minor-grid: (stroke: theme.border + 0.25pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ plot.plot(size: (15, 4), ..., { plot.add(...) })
+})
+```
+
+- `size: (W, H)` is the data area in canvas units, without tick labels and axis labels.
+ Allow about 1.5 units for them: `length: calc.min(theme.width / (W + 1.5), theme.height / (H + 1.5))`.
+ `(15, 4)` with `/ 16.5` and `/ 5.5` fills a wide, short room.
+- The `set-style` lines are required. Axes, ticks and the legend border are black by default, the legend
+ fill is white, the grid is light gray. With school-book axes, also set `axes: (mark: (fill: theme.fg))` for the arrow heads.
+- Normal cetz shapes are not allowed in the plot body. Wrap them in `plot.annotate({ ... })` (section 5).
+
+## 2. `plot.plot` parameters
+
+| Parameter | Values |
+|---|---|
+| `size` | `(width, height)` in canvas units |
+| `axis-style` | `"scientific"` (frame, default), `"scientific-auto"` (only used axes), `"school-book"` (arrows crossing at 0), `"left"` (arrows at the min sides), `none` |
+| `plot-style`, `mark-style` | a style dictionary or a function `i => style` (i = the index of the data call) |
+| `fill-below` | `true` (default): fills are drawn below the axes |
+| `legend` | `auto`, a position string (section 6), a coordinate, or `none` |
+| `legend-anchor` | the legend's anchor at that position (default: the opposite one) |
+| `legend-style` | legend style overrides (section 6) |
+| `name` | element name; the plot's anchors work outside: `"p.north"`, and `add-anchor` points: `"p.peak"` |
+| `x-…`, `y-…`, ... | axis options (section 3) |
+
+## 3. Axis options
+
+Prefix each option with the axis name: `x-min: 0`, `y-tick-step: 10`, `y2-label: [mm]`.
+Axes are `x`, `y`, `x2` (top), `y2` (right). A data call uses `axes: ("x", "y")` by default; use `axes: ("x", "y2")` for the right axis.
+
+| Option | Values |
+|---|---|
+| `label` | content or `none`. The default is the axis name in italics (`x`, `y`): pass `none` to hide it |
+| `min`, `max` | numbers or `auto`; min > max flips the axis |
+| `tick-step` | `auto`, a number, or `none` (no step ticks) |
+| `minor-tick-step` | a number or `none` |
+| `ticks` | extra ticks: `(1, 2, 3)` or `((0, [Jan]), (1, [Feb]))`; with `tick-step: none` they are the only ticks |
+| `format` | `"float"` (default), `"sci"`, or a function `v => content`; also `plot.formats.decimal`, `.sci`, `.fraction`, `.multiple-of` (π steps) |
+| `decimals` | digits for `"float"` (default 2) |
+| `mode` | `"lin"` (default) or `"log"`; with log, `min` must be > 0 |
+| `base` | log base for the tick labels (default 10) |
+| `grid` | `false`, `true` / `"major"`, `"minor"`, `"both"` |
+| `break` | `true`: a zigzag at the axis start when min > 0 |
+| `equal` | `"y"`: lock the x scale to the y scale (circles stay round) |
+| `inset` | `(low, high)` extra space inside the axis ends |
+
+Numeric tick labels are math (the math font). For category names, use `ticks:` with content or strings.
+
+## 4. Series colours
+
+The default series colours are Typst's blue, red, green, yellow and **black**. Always set theme colours, in one of two ways:
+
+- Per call: `plot.add(data, style: (stroke: theme.blue + 1.5pt))`, `mark-style: (stroke: theme.blue, fill: theme.bg)`.
+- For all calls: `plot.plot(plot-style: i => (stroke: theme.palette.at(calc.rem(i, 6)) + 1.5pt, fill: theme.palette.at(calc.rem(i, 6)).transparentize(75%)), mark-style: i => (...))`.
+ `i` counts every data call in the body (also `add-hline`, `add-bar`, ...).
+- Box plots, violins and error bars take their outlier and centre marks from `mark-style`: set it too.
+
+## 5. The add functions
+
+| Function | Main parameters |
+|---|---|
+| `plot.add(data, ...)` | data: array of `(x, y)`, or a function `x => y` (or `t => (x, y)` for parametric) with `domain: (a, b)`, `samples: 50`, `sample-at: (...)`. `line: "raw" \| "linear" \| "spline" \| "hv" \| "vh" \| "hvh"` or `(type: "spline", tension: 0.5)`. `mark: "o" \| "square" \| "triangle" \| "x" \| "+" \| "-" \| "\|" \| "<>" \| 5`, `mark-size: 0.2`, `mark-style`. `fill: true` (to y = 0, `fill-type: "axis"`) or `fill-type: "shape"`. `hypograph`, `epigraph`. `style`, `label`, `axes` |
+| `plot.add-fill-between(a, b, ...)` | two data arrays or functions; `domain`, `samples`, `line`, `style: (fill: ..., stroke: none)`, `label` |
+| `plot.add-hline(..ys, min: auto, max: auto)` | horizontal lines at y values; `style`, `label` |
+| `plot.add-vline(..xs, min: auto, max: auto)` | vertical lines at x values |
+| `plot.add-bar(data, ...)` | rows `(x, y)` or `(x, y1, y2, ...)`; `mode: "basic" \| "clustered" \| "stacked" \| "stacked100"`, `bar-width: 1`, `bar-position: "center" \| "start" \| "end"`, `cluster-gap`, `labels` (one or per series), `error-key`, `style` |
+| `plot.add-errorbar((x, y), x-error: e, y-error: e)` | e is a number or `(down, up)`; `mark: "o"`, `mark-size`, `whisker-size` (in **x data units**), `style`, `mark-style`, `label` |
+| `plot.add-boxwhisker(boxes)` | a dictionary or array of `(x:, min:, q1:, q2:, q3:, max:, outliers: (...))`; `box-width: 0.75`, `whisker-width: 0.5`, `mark: "*"`, `mark-size`, `style` |
+| `plot.add-violin(data, ...)` | items `(x, (samples...))`; `side: "right" \| "left" \| "both"`, `bandwidth: 1`, `extents: 0.25`, `samples`, `style` |
+| `plot.add-contour(f, z: (...), ...)` | `f: (x, y) => z` or a matrix; `x-domain`, `y-domain`, `x-samples: 25`, `y-samples: 25`, `op: auto \| ">" \| "<" \| ...`, `fill: true`, `style` (one style for all levels of one call) |
+| `plot.annotate({ ... }, background: false)` | cetz shapes in data coordinates; `background: true` draws behind the data; `resize: false` keeps the axis range |
+| `plot.add-anchor("name", (x, y))` | a named point in data coordinates, used outside as `"plotname.name"`; x or y can be `"min"`/`"max"` |
+| `plot.add-legend([label], preview: ...)` | an extra legend entry |
+
+`plot.sample-fn(f, domain, samples)` gives the sampled points of a function, if you need them.
+
+## 6. Legend
+
+- Positions: `"north"`, `"south"`, `"east"`, `"west"`, `"north-east"`, ... (outside the data area) and
+ `"inner-north-west"`, `"inner-north"`, `"inner-south-east"`, ... (inside). `auto` = `"north-east"`.
+- `legend-style: (orientation: ltr, item: (spacing: 0.4), padding: 0.1, spacing: 0.1, fill: theme.bg, stroke: theme.border)`.
+ `orientation: ltr` makes one row; give it `item: (spacing: ...)` or the entries touch.
+- Only calls with a `label` get an entry. Give one error bar of a loop a label (`label: if i == 0 [±2σ]`).
+
+## 7. Recipes
+
+Multi-series lines with markers, categories on x, minor grid:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg, minor-stroke: theme.muted),
+ grid: (stroke: theme.border + 0.5pt), minor-grid: (stroke: theme.border + 0.25pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ let months = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug")
+ let series = (([web], (12, 15, 14, 19, 24, 28, 27, 33)), ([iOS], (8, 9, 12, 13, 15, 18, 22, 24)), ([Android], (5, 7, 8, 8, 11, 12, 14, 19)))
+ plot.plot(
+ size: (15, 4), x-label: none, y-label: [k users],
+ x-ticks: months.enumerate(), x-tick-step: none, x-min: -0.3, x-max: 7.3,
+ y-min: 0, y-max: 35, y-tick-step: 10, y-minor-tick-step: 5, y-grid: "both",
+ legend: "inner-north-west",
+ // One style per series index: the theme palette, never the default colours
+ plot-style: i => (stroke: theme.palette.at(calc.rem(i, 6)) + 1.5pt),
+ mark-style: i => (stroke: theme.palette.at(calc.rem(i, 6)), fill: theme.bg),
+ {
+ for (name, ys) in series {
+ plot.add(ys.enumerate(), label: name, mark: "o", mark-size: 0.15)
+ }
+ })
+})
+```
+
+Scatter (no stroke, marks only) with a dashed trend line:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ // Fake data: (size in KB, ms) for two groups
+ let a = range(25).map(i => (i * 4 + calc.rem(i * 7, 5), 20 + i * 1.6 + calc.rem(i * 13, 9)))
+ let b = range(25).map(i => (i * 4 + calc.rem(i * 3, 4), 12 + i * 0.7 + calc.rem(i * 11, 6)))
+ plot.plot(size: (15, 4), x-label: [payload (KB)], y-label: [latency (ms)],
+ x-min: -3, x-max: 103, y-min: 5, y-max: 70, x-grid: true, y-grid: true, legend: "inner-north-west", {
+ // A scatter is plot.add with stroke: none and a mark
+ plot.add(a, label: [gzip], mark: "o", mark-size: 0.18,
+ style: (stroke: none), mark-style: (stroke: theme.orange, fill: theme.orange.transparentize(60%)))
+ plot.add(b, label: [zstd], mark: "triangle", mark-size: 0.2,
+ style: (stroke: none), mark-style: (stroke: theme.blue, fill: theme.blue.transparentize(60%)))
+ // A trend line over the same axes
+ plot.add(domain: (0, 100), x => 12 + 0.175 * x, style: (stroke: (paint: theme.muted, dash: "dashed")))
+ })
+})
+```
+
+Functions with school-book axes, π ticks and a step line:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ // school-book axes are arrows: their mark fill needs the theme colour too
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), mark: (fill: theme.fg)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ plot.plot(size: (15, 4), axis-style: "school-book",
+ x-tick-step: calc.pi / 2, x-format: plot.formats.multiple-of,
+ y-tick-step: 1, y-min: -1.5, y-max: 1.5,
+ legend: "inner-south-east", legend-style: (orientation: ltr, item: (spacing: 0.4)), {
+ plot.add(domain: (-calc.pi, 2 * calc.pi), samples: 120, calc.sin, label: $sin x$,
+ style: (stroke: theme.blue + 1.5pt))
+ plot.add(domain: (-calc.pi, 2 * calc.pi), samples: 120, x => calc.cos(x) / 2, label: $1/2 cos x$,
+ style: (stroke: theme.orange + 1.5pt))
+ // A step function: line: "hv"
+ plot.add(range(-3, 7).map(x => (x, calc.rem(calc.abs(x), 2) - 0.5)), line: "hv", label: [step],
+ style: (stroke: (paint: theme.green, dash: "dashed")))
+ })
+})
+```
+
+Band between two curves, and an area to y = 0:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ let f(x) = 50 + 30 * calc.sin(x / 2) + 2 * x
+ plot.plot(size: (15, 4), x-label: [day], y-label: [req/s], y-min: 0, y-max: 140, y-grid: true, legend: "inner-north-west", {
+ // Band between two functions (p10..p90)
+ plot.add-fill-between(domain: (0, 20), x => f(x) - 8 - x / 2, x => f(x) + 8 + x / 2,
+ label: [p10–p90], style: (fill: theme.blue.transparentize(80%), stroke: none))
+ plot.add(domain: (0, 20), f, label: [median], style: (stroke: theme.blue + 1.5pt))
+ // Area under a curve to y = 0: fill: true
+ plot.add(domain: (0, 20), x => 10 + 5 * calc.cos(x / 3), fill: true, label: [errors],
+ style: (stroke: theme.red, fill: theme.red.transparentize(75%)))
+ })
+})
+```
+
+Log–log axes:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg, minor-stroke: theme.muted),
+ grid: (stroke: theme.border + 0.5pt), minor-grid: (stroke: theme.border + 0.25pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ let n = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024)
+ plot.plot(size: (15, 4), x-label: [n], y-label: [ops],
+ // log axes: mode "log", base for the tick labels; min must be > 0
+ x-mode: "log", x-base: 2, x-tick-step: 1, x-min: 1, x-max: 1024,
+ y-mode: "log", y-base: 10, y-tick-step: 1, y-minor-tick-step: 1, y-min: 1, y-max: 1e6,
+ x-format: v => text(str(int(v))), y-format: v => $10^#calc.round(calc.log(v))$,
+ y-grid: "both", x-grid: true, legend: "inner-north-west", {
+ plot.add(n.map(x => (x, x)), label: $O(n)$, mark: "o", mark-size: 0.12, style: (stroke: theme.green), mark-style: (stroke: theme.green, fill: theme.bg))
+ plot.add(n.map(x => (x, x * calc.log(x, base: 2) + 1)), label: $O(n log n)$, mark: "o", mark-size: 0.12, style: (stroke: theme.blue), mark-style: (stroke: theme.blue, fill: theme.bg))
+ plot.add(n.map(x => (x, x * x)), label: $O(n^2)$, mark: "o", mark-size: 0.12, style: (stroke: theme.red), mark-style: (stroke: theme.red, fill: theme.bg))
+ })
+})
+```
+
+Dual y axes (bars on `y2`, line on `y`):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 17, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ let temp = (3, 4, 8, 12, 16, 19, 22, 21, 17, 12, 7, 4)
+ let rain = (60, 45, 50, 42, 55, 60, 50, 58, 62, 75, 80, 70)
+ plot.plot(size: (15, 4), axis-style: "scientific", x-label: none,
+ x-tick-step: 1, x-min: -0.6, x-max: 11.6,
+ x-format: v => ("J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D").at(int(v)),
+ y-label: text(fill: theme.orange)[°C], y-min: 0, y-max: 25, y-tick-step: 5, y-grid: true,
+ // A secondary axis: name it y2 and plot with axes: ("x", "y2")
+ y2-label: text(fill: theme.blue)[mm rain], y2-min: 0, y2-max: 100, y2-tick-step: 20,
+ legend: "inner-north-west", {
+ plot.add-bar(rain.enumerate(), bar-width: 0.6, axes: ("x", "y2"), labels: [rain],
+ style: (fill: theme.blue.transparentize(70%), stroke: none))
+ plot.add(temp.enumerate(), line: "spline", label: [temp], mark: "o",
+ style: (stroke: theme.orange + 1.5pt), mark-style: (stroke: theme.orange, fill: theme.bg))
+ })
+})
+```
+
+Histogram with `add-bar` (bin the values first) and a mean line:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ // Histogram: count values into bins, then one bar per bin
+ let data = range(400).map(i => calc.rem(i * 7919, 101) / 10 + calc.rem(i * 104729, 53) / 10)
+ let (lo, step, k) = (0, 1, 16)
+ let counts = range(k).map(b => data.filter(v => v >= lo + b * step and v < lo + (b + 1) * step).len())
+ plot.plot(size: (15, 4), x-label: [response time (s)], y-label: [count],
+ x-min: 0, x-max: k, x-tick-step: 2, y-min: 0, y-max: 45, y-grid: true, legend: "inner-north-east", {
+ // bar-position: "start" puts each bar's left edge on its x (a bin start)
+ plot.add-bar(counts.enumerate().map(((b, c)) => (lo + b * step, c)), bar-width: step, bar-position: "start",
+ labels: [requests], style: (fill: theme.purple.transparentize(60%), stroke: theme.purple + 0.5pt))
+ plot.add-vline(8.1, label: [mean], style: (stroke: (paint: theme.red, dash: "dashed")))
+ })
+})
+```
+
+Error bars (categorical x so the whisker width is even):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ // (threads, mean ms, std dev); x is the row index, the tick labels name it
+ let rows = ((1, 120, 8), (2, 64, 6), (4, 35, 5), (8, 21, 4), (16, 15, 5), (32, 14, 7))
+ plot.plot(size: (15, 4), x-label: [threads], y-label: [ms],
+ x-min: -0.5, x-max: 5.5, x-tick-step: none, x-ticks: rows.enumerate().map(((i, r)) => (i, str(r.at(0)))),
+ y-min: 0, y-max: 140, y-grid: true, legend: "inner-north-east", {
+ plot.add(rows.enumerate().map(((i, r)) => (i, r.at(1))), label: [mean], style: (stroke: theme.blue + 1.5pt))
+ for (i, (_, y, e)) in rows.enumerate() {
+ // y-error: a number (symmetric) or (down, up); whisker-size is in x data units
+ plot.add-errorbar((i, y), y-error: 2 * e, mark: "o", mark-size: 0.15, whisker-size: 0.2,
+ label: if i == 0 [±2σ], style: (stroke: theme.fg), mark-style: (fill: theme.blue, stroke: none))
+ }
+ })
+})
+```
+
+Box plots and violins:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ // Outlier marks take the plot mark-style (default: blue, red, ...), so set it
+ plot.plot(size: (15, 4), mark-style: i => (stroke: theme.fg, fill: theme.bg), x-min: 0.3, x-max: 6.7, x-label: none, y-label: [ms],
+ x-ticks: ((1.5, [v1]), (3.5, [v2]), (5.5, [v3])), x-tick-step: none, y-min: 0, y-max: 80, y-grid: true, {
+ // Box plots: one dictionary per box
+ plot.add-boxwhisker((
+ (x: 1, min: 12, q1: 22, q2: 30, q3: 41, max: 58, outliers: (66, 71)),
+ (x: 3, min: 10, q1: 18, q2: 24, q3: 30, max: 44, outliers: (52,)),
+ (x: 5, min: 8, q1: 14, q2: 17, q3: 22, max: 30, outliers: ()),
+ ), box-width: 0.6, mark: "o", mark-size: 0.12,
+ style: (stroke: theme.fg, fill: theme.blue.transparentize(75%)))
+ // Violin plots: (x, (samples...)) items; side "both" draws a full violin
+ let s(m, k) = range(40).map(i => m + calc.rem(i * 37, 23) * k / 10 - k)
+ plot.add-violin(((2, s(32, 9)), (4, s(24, 6)), (6, s(17, 4))), side: "both", bandwidth: 3, extents: 0.4,
+ style: (stroke: theme.purple, fill: theme.purple.transparentize(75%)))
+ })
+})
+```
+
+Contour levels (one call per level, so each level gets its own fill):
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ cetz.draw.set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ let f(x, y) = calc.exp(-((x - 1) * (x - 1) + y * y)) + 0.8 * calc.exp(-((x + 1.5) * (x + 1.5) + (y - 0.5) * (y - 0.5)) * 2)
+ plot.plot(size: (15, 4), x-label: $x$, y-label: $y$, x-tick-step: 1, y-tick-step: 1,
+ x-min: -4, x-max: 4, y-min: -1.6, y-max: 1.6, {
+ // One add-contour per level: each level gets its own colour (one style covers all z of one call)
+ for (i, z) in (0.1, 0.3, 0.5, 0.7, 0.9).enumerate() {
+ plot.add-contour(f, z: z, op: ">=", fill: true, x-domain: (-4, 4), y-domain: (-1.6, 1.6),
+ x-samples: 60, y-samples: 30,
+ style: (fill: theme.orange.transparentize(85% - i * 12%), stroke: theme.orange + 0.6pt))
+ }
+ })
+})
+```
+
+Annotations: a shaded span, a threshold, a vertical marker, and a callout drawn outside the plot:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#cetz.canvas(length: calc.min(theme.width / 16.5, theme.height / 5.5), {
+ import cetz.draw: *
+ set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg), grid: (stroke: theme.border + 0.5pt)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ let cpu = (20, 22, 25, 24, 30, 45, 78, 92, 88, 60, 40, 32, 28, 26, 24, 23)
+ plot.plot(size: (15, 4), name: "p", x-label: [minute], y-label: [CPU %], x-min: 0, x-max: 15, x-tick-step: 3,
+ y-min: 0, y-max: 100, y-tick-step: 25, y-grid: true, legend: "inner-north-east", {
+ // A shaded span behind the data: annotate(background: true) uses plot coordinates
+ plot.annotate(background: true, {
+ rect((5.5, 0), (9.5, 100), fill: theme.red.transparentize(88%), stroke: none)
+ content((5.65, 97), text(fill: theme.red, size: 0.8em)[incident], anchor: "north-west")
+ })
+ plot.add(cpu.enumerate(), label: [cpu], style: (stroke: theme.blue + 1.5pt))
+ plot.add-hline(80, label: [alert], style: (stroke: (paint: theme.orange, dash: "dashed")))
+ plot.add-vline(7, style: (stroke: (paint: theme.muted, dash: "dotted")))
+ // A named point to draw from outside the plot
+ plot.add-anchor("peak", (7, 92))
+ })
+ // Outside the plot: canvas coordinates again, but "p.peak" still works
+ content((rel: (2.2, -0.2), to: "p.peak"), text(fill: theme.fg, size: 0.85em)[peak 92% at 7 min], anchor: "west", name: "lbl")
+ line("lbl.west", "p.peak", stroke: theme.muted, mark: (end: ">", fill: theme.muted))
+})
+```
+
+## 8. Traps
+
+- Black by default: axes, ticks, minor ticks, the legend border and the default series colour list (it ends in black). The legend fill is white: on dark, white text on a white box.
+- The axis labels default to `x` and `y` in italics. Pass `x-label: none` if you do not want them.
+- `size` excludes the tick labels and axis labels: leave about 1.5 units around it in the canvas `length`.
+- `whisker-size` of `add-errorbar` and `bar-width` of `add-bar` are in x data units. On a log x axis they come out uneven: use a categorical x.
+- With `mode: "log"`, values ≤ 0 have no place. Set `min` > 0 and keep the data > 0.
+- Category ticks: `x-ticks: names.enumerate()` with `x-tick-step: none`, and `x-min`/`x-max` half a step outside the first and last index, or the end points sit on the frame.
+- `auto` limits fit the data exactly: a band or a bar touches the frame. Set `y-max` a little higher.
+- Normal cetz calls (`line`, `content`) in the plot body fail with "Expected plot sub-command in plot body". Put them in `plot.annotate`.
+- A `fill: true` area fills to y = 0. Set `y-min: 0` so the area starts at the frame.
diff --git a/skills/intelligent-ui/references/typst.md b/skills/intelligent-ui/references/typst.md
new file mode 100644
index 0000000..7476151
--- /dev/null
+++ b/skills/intelligent-ui/references/typst.md
@@ -0,0 +1,342 @@
+# Typst essentials for live blocks
+
+Typst 0.15 language facts you need to write a ```` ```typst ```` block that compiles the first time and looks right.
+Every ```` ```typst ```` example in this file was compiled with the real template, in dark and light.
+
+Contents
+1. How a block runs
+2. The `theme` dictionary
+3. Markup mode and code mode
+4. Values and types
+5. `let`, functions, closures
+6. Arrays, dictionaries, loops, destructuring
+7. Numbers: `calc` and formatting
+8. Colours
+9. Layout elements
+10. `context`, `measure`, `layout`
+11. Math and `raw`
+12. Recipes: comparison table, heatmap table, stat tiles, legend row, bars, diagram + notes, math
+13. Errors and their fixes
+14. Silent traps (no error, wrong picture)
+
+## 1. How a block runs
+
+- The template evaluates the block source as **markup** (`eval(src, mode: "markup", scope: (theme: …))`).
+ In scope: the Typst standard library and `theme`. Nothing else: no other variables, and no packages until you `#import` them.
+- These set rules are already active: `text(font: theme.sans, size: 11pt, fill: theme.fg)`. You do not set them again.
+- The block is placed in a container. `#page`, `#set page(...)` and `#pagebreak()` are errors.
+- Lay out for `theme.width` × `theme.height` (these are the design size, not always the size on screen).
+ The template scales the whole block by one factor to fit the terminal. A block that is too wide is made smaller to fit.
+ A block taller than `theme.height` is **not** made smaller: the page grows. So make it wide and short.
+- `theme.width` changes with the terminal (for example 896pt or 1404pt). Size things with `fr`, `%` or `theme.width`, not with fixed widths that you guess.
+- To check a block, run `scripts/check.sh` on it (it gives `file:line:col` errors and PNGs). A raw
+ `typst compile` of the template reports every error at `md.typ:891` (the `eval` call), without the line in your block.
+
+## 2. The `theme` dictionary
+
+| Key | Type | Use |
+|---|---|---|
+| `theme.fg` | color | text, strokes, axes |
+| `theme.muted` | color | secondary text, guide lines |
+| `theme.link` | color | links |
+| `theme.border` | color | thin rules, table lines, frames |
+| `theme.accent` | color | one highlight |
+| `theme.bg` | color | page background: `crossing-fill`, label backgrounds, "gaps" |
+| `theme.code-bg` | color (semi-transparent) | tile and track backgrounds |
+| `theme.red` `.green` `.blue` `.yellow` `.orange` `.purple` | color | status and category colours |
+| `theme.palette` | array of 6 colors | data series in order: blue, orange, green, red, purple, yellow |
+| `theme.width` | length | content width of the drawing |
+| `theme.height` | length | height the drawing should fit in |
+| `theme.page-width` | length | page width (content width + margins) |
+| `theme.text-size` | length | body text size (11pt) |
+| `theme.sans`, `theme.mono` | array of strings | font lists for `text(font: …)` |
+| `theme.dark` | bool | true for the dark scheme |
+
+`theme.colour` (a key that is not there) is the error `dictionary does not contain key "colour"`.
+`theme.palette.at(6)` is out of bounds: use `theme.palette.at(calc.rem(i, 6))` for more than 6 series.
+
+## 3. Markup mode and code mode
+
+- The block starts in markup: text is text. `#` switches to code for **one expression**: `#x`, `#f(a)`, `#(x + 1)`, `#for … {}`.
+- `#x+1` shows the value of `x` and then the text `+1`. To compute, write `#(x + 1)`.
+- `#let …` runs to the end of its line. Put one `#let` on each line. A second `#` on the same line after a `#let`
+ is the error ``the character `#` is not valid in code``.
+- Inside `{ … }` (code block) you are in code: no `#`. Inside `[ … ]` (content block) you are in markup again: use `#` to get back to code.
+- A trailing content block is the last argument: `#text(fill: theme.red)[alert]` = `#text(fill: theme.red, [alert])`.
+- Comments: `// line` and `/* block */`, in markup and in code.
+- Markup characters that do something: `*bold*`, `_emph_`, `` `raw` ``, `$math$`, `<label>`, `@ref`, `~` (no-break space),
+ `\` (line break), `//` (comment), `-`/`+`/`=` at the start of a line (list, numbered list, heading).
+ Escape with a backslash: `\$`, `\~`, `\#`, `\@`, `\<`, `\*`, `\_`, `\/\/`.
+
+## 4. Values and types
+
+- `content` is `[…]` (markup). `str` is `"…"`. Many parameters want one and not the other:
+ `raw("x")` needs a string (`raw([x])` is `expected string, found content`); `text(fill: c, "abc")` and `text(fill: c)[abc]` both work.
+- `"a" + "b"` is a string. `"a" + [b]` is content. `"n = " + 3` is an error: write `"n = " + str(3)` or `[n = #n]`.
+- Lengths: `pt`, `em`, `cm`. Ratio: `50%`. Relative: `50% + 1em`. Fraction: `1fr` (only in grid/table columns, `h`, `v`, `stack` spacing).
+ `1pt + 2` is an error. `theme.width / 2pt` is a float (448.0). `theme.width * 0.5` is a length.
+- Colours: `theme.blue`, `rgb("#4a9")`, `luma(50%)`. A string is not a colour: `fill: "blue"` is an error.
+- Strokes: `theme.fg` (colour only), `1pt + theme.fg`, or `(paint: theme.red, thickness: 1pt, dash: "dashed")`.
+ Dash values: `"dashed"`, `"dotted"`, `"densely-dashed"`, `"loosely-dotted"`, …
+- Alignment: `left`, `center`, `right`, `top`, `horizon`, `bottom`, combined with `+`: `top + right`, `center + horizon`.
+- `none` draws nothing. `auto` means "the default".
+
+## 5. `let`, functions, closures
+
+```typc
+let n = 3 // a variable
+let tile(label, value, good: true) = … // a function with a named parameter (default true)
+let double = x => x * 2 // a closure
+let f(..args) = args.pos() // variadic: args.pos(), args.named()
+tile.with(good: false) // pre-fill arguments
+```
+
+- A function body is one expression: `= text(…)`, or `= { … }` (code, the joined result of each line), or `= [ … ]` (markup).
+- A function can **read** outer variables but not change them: `total += 1` inside a function is
+ `variables from outside the function are read-only and cannot be modified`. Return a new value instead,
+ or change the variable in a top-level `for` loop (that is allowed).
+- Do not name a variable after a built-in that you also call: `h`, `v`, `box`, `text`, `line`, `rect`, `table`, `grid`.
+ After `#let (w, h) = (3, 2)`, `#h(1em)` is `expected function, found integer`. Use `wd`, `ht`.
+- Unknown named argument: `unexpected argument: c`.
+
+## 6. Arrays, dictionaries, loops, destructuring
+
+```typc
+let a = (1, 2, 3) // array; a single item needs a comma: (1,)
+a.len() a.at(0) a.at(9, default: 0) a.first() a.last() a.sum() a.rev() a.sorted()
+a.map(x => x * 2) a.filter(x => x > 1) a.enumerate() a.zip(b) a.join(", ") a.flatten()
+range(5) range(1, 6) (1fr,) * 4 // (1fr, 1fr, 1fr, 1fr)
+let d = (name: "api", ms: 182) // dictionary; empty one is (:)
+d.name d.at("ms") d.at("x", default: 0) d.keys() d.values() d.pairs() d.insert("k", 1)
+for x in a { … } for (i, x) in a.enumerate() { … } for (k, v) in d { … }
+let (x, y) = (1, 2) let (first, ..rest) = a let (name, ms) = (d.name, d.ms)
+```
+
+- `..` spreads: `grid(..cells)`, `calc.max(..a)`. `calc.max(a)` (no `..`) returns the array unchanged (no error).
+- `#for` in markup joins the bodies: `#for (i, x) in a.enumerate() [#i: #x ]`.
+- To build cells for `grid`/`table`, map each row to an array and `.flatten()`, then spread with `..`.
+- `let (a, b) = (1, 2, 3)` is `too many elements to destructure`.
+- `if` needs a bool: `if 1 […]` is `expected boolean, found integer`. `if x != none`, `if a.len() > 0`.
+
+## 7. Numbers: `calc` and formatting
+
+- `calc.round(x, digits: 1)`, `calc.floor`, `calc.ceil`, `calc.abs`, `calc.min(a, b)`, `calc.max(..arr)`,
+ `calc.rem(i, n)`, `calc.quo(i, n)` (integer division), `calc.even(i)`, `calc.pow`, `calc.sqrt`, `calc.log`, `calc.sin(30deg)`, `calc.pi`.
+- `str(0.1 + 0.2)` is `0.30000000000000004`: always round before you show a float: `str(calc.round(x, digits: 2))`.
+- `int(7.9)` is 7. `float("3.5")` is 3.5. `str(1234567)` has no separators.
+- For format strings, the vendored oxifmt works offline: `#import "@preview/oxifmt:1.0.0": strfmt`, then
+ `strfmt("{:.2}", 2/3)`, `strfmt("{:.1}%", x)`, `strfmt("{}", 1234567, fmt-thousands-separator: ",")`.
+
+## 8. Colours
+
+- Fills that work in both schemes: `c.transparentize(80%)` (light tint) to `40%` (strong). It takes a **ratio**: `transparentize(80)` is `expected ratio, found integer`.
+- An opaque tint: `color.mix(theme.blue, theme.bg)` (50/50) or weighted `color.mix((theme.green, 70), (theme.red, 30))`.
+- `c.lighten(40%)`, `c.darken(40%)`: the same change in both schemes, so the contrast changes. Prefer `transparentize` and `color.mix` with `theme.bg`.
+- Gradients: `gradient.linear(theme.green, theme.yellow, theme.red)`, with `angle: 90deg` for vertical. `g.sample(30%)` gives one colour (a colour scale for heatmaps).
+- Text on a strong fill: `theme.fg` is fine up to about `transparentize(40%)`. For solid fills use `theme.bg` as the text colour.
+
+```typst
+#let g = gradient.linear(theme.green, theme.yellow, theme.red)
+#stack(dir: ltr, spacing: 4pt,
+ ..range(11).map(i => box(width: 2em, height: 1.2em, radius: 2pt, fill: g.sample(i * 10%))),
+ h(1em),
+ box(width: 3em, height: 1.2em, fill: theme.blue.transparentize(80%)),
+ box(width: 3em, height: 1.2em, fill: color.mix(theme.blue, theme.bg)),
+ box(width: 3em, height: 1.2em, fill: gradient.linear(theme.blue, theme.purple)),
+)
+```
+
+## 9. Layout elements
+
+- `text(fill:, size:, weight: "bold" | 700, style: "italic", font: theme.mono)[…]`. `size` needs a length: `size: 2` is `expected length, found integer`; write `2em` or `22pt`.
+- `box(width:, height:, fill:, stroke:, radius:, inset:, baseline:)` is inline (stays in the line). `block(…)` is a paragraph-level box (starts a new line). Same parameters, plus `breakable`.
+- `rect`, `circle`, `ellipse`, `square`, `line(start:, end:, length:, angle:, stroke:)`, `polygon(…)` are shapes; default stroke is black: pass `stroke:`.
+- `stack(dir: ltr | ttb, spacing: 1em, ..items)` puts items in a row or column.
+- `grid(columns: (1fr, 2fr, auto), rows: auto, gutter: 8pt, column-gutter:, row-gutter:, align:, ..cells)`. `columns: 3` means 3 `auto` columns.
+- `table(…)` is a grid with `stroke` and `inset`; it takes `fill: (x, y) => …`, `align: (x, y) => …` or per-column arrays,
+ `stroke: (x, y) => (bottom: 0.5pt + theme.border)`, `table.header(…)`, `table.cell(colspan: 2, fill: …)[…]`, `table.hline(stroke: …)`, `table.vline(…)`.
+- `align(center + horizon)[…]`, `pad(x: 1em, top: 4pt)[…]` (block level), `place(top + right, dx: -4pt, dy: 4pt)[…]` (out of the flow, relative to the parent container).
+- `h(1em)`, `h(1fr)` (push to the right), `v(0.5em)`. `#h(1fr)` only works inside a line, not next to a block element.
+- `scale(80%, reflow: true)[…]`, `rotate(-90deg, reflow: true)[…]`, `move(dx:, dy:)[…]`, `hide[…]`.
+
+## 10. `context`, `measure`, `layout`
+
+- `measure(c)`, `text.size`, `text.font`, `here()` need context. Without it: `can only be used when context is known`.
+ Wrap the part that uses them: `#context { let w = measure(x).width; … }`.
+- `measure(c).width` of text is its unwrapped width. `measure(c, width: theme.width)` wraps first.
+- **Do not size things from `layout(size => …)` in a live block.** The template measures the block with no width limit, so `size.width` is infinite in that pass,
+ and `box(width: f * size.width)` fails with `cannot expand into infinite width`. Use `theme.width`, `1fr` columns or `%` widths instead.
+- `100%` inside a `box`/`block` is the parent width; inside a `grid` cell it is the cell width.
+
+## 11. Math and `raw`
+
+- Inline `$x^2$`, display `$ x^2 $` (spaces inside the dollars make it a centred block). Math takes the text colour: `text(fill: theme.accent)[$f(x)$]`.
+- In math, multi-letter words are variables unless quoted: `"softmax"(z)`. Functions: `frac(a, b)` or `a / b`, `sqrt(x)`, `sum_(i=1)^n`, `hat(y)`, `cal(L)`, `bb(R)`, `mat(1, 2; 3, 4)`, `cases(…)`.
+- In math, `#` brings code back: `$#theme.width$`, `$x = #str(n)$`.
+- `raw("code", lang: "rust")` gets the template's code look (code font, syntax colours, a background box for inline raw).
+ For plain mono labels inside drawings and nodes use `text(font: theme.mono)[…]` instead.
+
+## 12. Recipes
+
+A coloured comparison table (header tint, zebra rows, status colours, `fr` columns):
+
+```typst
+#let yes = text(fill: theme.green)[✓]
+#let no = text(fill: theme.red)[✗]
+#table(
+ columns: (1.4fr, 1fr, 1fr, 1fr),
+ align: (left, center, center, center),
+ stroke: (x, y) => (bottom: 0.5pt + theme.border),
+ inset: (x: 8pt, y: 6pt),
+ fill: (x, y) => if y == 0 { theme.blue.transparentize(80%) } else if calc.even(y) { theme.code-bg },
+ table.header([*Feature*], [*SQLite*], [*Postgres*], [*Redis*]),
+ [Transactions], yes, yes, text(fill: theme.yellow)[partial],
+ [Runs in-process], yes, no, no,
+ [Full-text search], yes, yes, no,
+ [Latency], [\~µs], [\~ms], [\~µs],
+)
+```
+
+A heatmap table (cell fill from the value):
+
+```typst
+#let rows = ("api", "db", "cache", "auth")
+#let data = (
+ (12, 30, 55, 80, 95, 70, 40, 20),
+ (5, 10, 25, 60, 88, 92, 50, 15),
+ (2, 4, 8, 15, 20, 18, 9, 3),
+ (20, 22, 30, 35, 40, 38, 30, 25),
+)
+#let cell(v) = table.cell(fill: color.mix((theme.green, 100 - v), (theme.red, v)).transparentize(40%))[#v]
+#table(
+ columns: (5em,) + (1fr,) * 8,
+ align: center + horizon, stroke: 0.5pt + theme.bg, inset: 5pt,
+ [], ..range(8).map(i => text(fill: theme.muted)[#(i + 9):00]),
+ ..rows.zip(data).map(((name, vals)) => ([*#name*], ..vals.map(cell))).flatten(),
+)
+```
+
+A stat-tile row (KPI cards in a grid):
+
+```typst
+#let tile(label, value, delta, good) = block(
+ width: 100%, inset: 10pt, radius: 6pt, fill: theme.code-bg, stroke: 0.5pt + theme.border,
+ {
+ text(size: 0.85em, fill: theme.muted, label)
+ v(2pt)
+ text(size: 1.8em, weight: "bold", value)
+ h(6pt)
+ text(fill: if good { theme.green } else { theme.red }, delta)
+ },
+)
+#grid(
+ columns: (1fr,) * 4, gutter: 10pt,
+ tile([Requests / s], [12.4k], [▲ 8%], true),
+ tile([p95 latency], [182 ms], [▲ 12 ms], false),
+ tile([Error rate], [0.21%], [▼ 0.05], true),
+ tile([Cost / day], [\$1,240], [▲ \$90], false),
+)
+```
+
+A legend row:
+
+```typst
+#let swatch(c) = box(width: 0.9em, height: 0.9em, radius: 2pt, fill: c, baseline: 0.1em)
+#let names = ([Ingest], [Transform], [Store], [Serve], [Archive], [Other])
+#stack(dir: ltr, spacing: 1.5em, ..names.zip(theme.palette).map(((n, c)) => [#swatch(c) #n]))
+```
+
+Horizontal bars with a measured label column (no `layout`, see section 10):
+
+```typst
+#let data = (("parse", 0.42), ("type-check", 0.31), ("codegen", 0.18), ("link", 0.09))
+#let mono(s) = text(font: theme.mono, size: 0.9em, s)
+#context {
+ let label-w = calc.max(..data.map(((n, _)) => measure(mono(n)).width))
+ grid(
+ columns: (label-w, 1fr, 4em), column-gutter: 0.6em, row-gutter: 6pt, align: (right, left, right),
+ ..data.enumerate().map(((i, (name, f))) => (
+ mono(name),
+ box(width: 100%, height: 0.9em, radius: 2pt, fill: theme.code-bg,
+ box(width: f * 100%, height: 100%, radius: 2pt, fill: theme.palette.at(i))),
+ text(fill: theme.muted, str(calc.round(f * 100, digits: 1)) + "%"),
+ )).flatten(),
+ )
+}
+```
+
+Two columns: a diagram and its notes:
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#grid(
+ columns: (3fr, 2fr), column-gutter: 2em, align: horizon,
+ diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg, node-shape: rect, spacing: (2.5em, 1.5em),
+ node((0, 0), [Client], fill: theme.blue.transparentize(80%), name: <c>),
+ node((1, 0), [Gateway], fill: theme.purple.transparentize(80%), name: <g>),
+ node((2, 0), [Service], fill: theme.green.transparentize(80%), name: <s>),
+ edge(<c>, <g>, "->"),
+ edge(<g>, <s>, "->"),
+ ),
+ block(inset: (left: 1em), stroke: (left: 2pt + theme.accent))[
+ *Notes*
+ - The gateway checks the token.
+ - The service never sees raw keys.
+ - #text(fill: theme.muted)[Retries: 3, backoff 2×.]
+ ],
+)
+```
+
+Math beside text:
+
+```typst
+#grid(columns: (1fr, 1fr), align: horizon + center,
+ $ "softmax"(z)_i = e^(z_i) / (sum_(j=1)^K e^(z_j)) $,
+ [The loss is #text(fill: theme.accent)[$cal(L) = -sum_i y_i log hat(y)_i$], for $K$ classes.],
+)
+```
+
+## 13. Errors and their fixes
+
+| Error message (Typst 0.15) | Cause | Fix |
+|---|---|---|
+| `unknown variable: node` | package not imported in this block | add the `#import` line at the top of each block |
+| `unknown variable: foo` | typo, or a `#let` in another block | each block is alone: define it here |
+| `expected function, found integer` | a variable `h`/`v`/`box`… shadows the function; or `f(1)(2)` | rename the variable (`ht`, `wd`) |
+| `cannot add string and integer` | `"n = " + n` | `"n = " + str(n)` or `[n = #n]` |
+| `cannot add content and integer` | `[12] + 1`, a function given `[…]` for a number | keep numbers as numbers; `f(3)`, not `f[3]` |
+| `cannot add length and integer` / `and string` | `1pt + 2`, `1pt + "red"` | `1pt + 2pt`, `1pt + theme.red` |
+| `expected string, found content` | `raw([x])`, `str` wanted | `raw("x")` |
+| `expected color, gradient, tiling, or none, found string` | `fill: "blue"` | `fill: theme.blue` |
+| `expected ratio, found integer` | `transparentize(80)` | `transparentize(80%)` |
+| `expected length, found integer` | `text(size: 2)` | `size: 2em` |
+| `expected boolean, found integer` | `if 1 …` | a real comparison |
+| `type integer has no method len` / `element text has no method len` | method on the wrong type (content is not a string) | keep data as strings/arrays; turn into content last |
+| `dictionary does not contain key "x"` | wrong `theme.` key or dict key | see section 2; `d.at("x", default: …)` |
+| `array index out of bounds (index: 6, len: 6)` | `theme.palette.at(6)` | `theme.palette.at(calc.rem(i, 6))` |
+| `too many elements to destructure` | `let (a, b) = (1, 2, 3)` | match the count, or `(a, b, ..rest)` |
+| `unexpected argument: c` | wrong named argument | read the parameter list |
+| `unexpected argument` (cetz) | `line`/`rect` without `import cetz.draw: *` | import the draw functions inside the canvas body |
+| `variables from outside the function are read-only and cannot be modified` | `x += 1` in a function | return values; mutate only in top-level loops |
+| `can only be used when context is known` | `measure`, `text.size` outside `context` | `#context { … }` |
+| `cannot expand into infinite width` | width from `layout(size => …)` | use `theme.width`, `fr`, `%` |
+| ``the character `#` is not valid in code`` | a second `#` on a `#let` line, or `#` inside `{ }` | one statement per line; no `#` in code |
+| `unclosed delimiter` | missing `)` `]` `}`, or an odd `*` / `_` / `$` in text (`2 * 3`) | close it; escape `\*`, `\_`, `\$` |
+| `label <x.com> does not exist in the document` | `[email protected]` (`@` is a reference) | `me\@x.com` |
+| `page configuration is not allowed inside of containers` | `#set page(…)` | remove it; size with `theme.width`/`theme.height` |
+| `pagebreaks are not allowed inside of containers` | `#pagebreak()` | remove it; use one block per drawing |
+| `package found, but version 0.5.9 does not exist (latest is 0.5.8)` | wrong version | use the versions in the prompt |
+
+## 14. Silent traps (no error, wrong picture)
+
+- `$5 and $10` becomes math (`5 ∧ 10`). Write `\$5 and \$10`.
+- `~` becomes a no-break space; `a <b> c` drops `<b>` (it is a label); `x // y` hides the rest of the line. Escape: `\~`, `\<b>`, `\/\/`.
+- A line that starts with `-`, `+`, `=` or `1.` becomes a list item or heading.
+- `#x+1` shows `5+1`. Use `#(x + 1)`.
+- `calc.max(arr)` returns `arr`. Use `calc.max(..arr)`.
+- `str(float)` shows 17 digits. Round first.
+- Any shape or line without `stroke:` is black, invisible on the dark theme. `table` and `grid` strokes too: pass `theme.border`.
+- `pad`, `block`, `align`, `table`, `grid` are block level: text after them starts a new line. Use `box` or `stack(dir: ltr)` to keep a row.
+- `raw` inside a drawing gets the inline-code box and syntax colour. Use `text(font: theme.mono)`.
+- A font name that is not installed is only a warning; the text falls back to another font.
diff --git a/skills/intelligent-ui/scripts/check.sh b/skills/intelligent-ui/scripts/check.sh
new file mode 100755
index 0000000..d3615bb
--- /dev/null
+++ b/skills/intelligent-ui/scripts/check.sh
@@ -0,0 +1,303 @@
+#!/usr/bin/env bash
+# Intelligent UI: compiles a ```typst block (or a Markdown answer) with the
+# mod's own template (render/md.typ), its vendored packages and the active
+# theme, in dark and light, and writes PNGs to look at with the Read tool.
+#
+# check.sh [--theme NAME] [--mode dark|light|both] [--width PT] [--height PT] FILE
+#
+# FILE: a .typ file with one block body (no fences), a .md file with one or
+# more ```typst blocks (compiled as one answer), or `-` (stdin, as .typ).
+# Output, one line each: `using ...`, then per mode `ok <mode> <png>...` or
+# `error <mode>` and its diagnostics (FILE:line:col: error: ...), then a hint.
+# Exit 0: every mode compiled; 1: an error; 2: bad use or no Typst 0.15.
+set -u
+
+usage() {
+ echo "usage: check.sh [--theme NAME] [--mode dark|light|both] [--width PT] [--height PT] FILE|-"
+}
+
+here=$(cd "$(dirname "$0")" && pwd -P)
+root=$(cd "$here/../../.." && pwd -P)
+if [ ! -f "$root/render/md.typ" ]; then
+ echo "error: no render/md.typ in $root (the plugin root)"
+ exit 2
+fi
+
+theme_arg='' mode=both width='' height=''
+while [ $# -gt 0 ]; do
+ case $1 in
+ --theme) theme_arg=${2-}; shift 2 || shift ;;
+ --theme=*) theme_arg=${1#*=}; shift ;;
+ --mode) mode=${2-}; shift 2 || shift ;;
+ --mode=*) mode=${1#*=}; shift ;;
+ --width) width=${2-}; shift 2 || shift ;;
+ --width=*) width=${1#*=}; shift ;;
+ --height) height=${2-}; shift 2 || shift ;;
+ --height=*) height=${1#*=}; shift ;;
+ -h|--help) usage; exit 0 ;;
+ --) shift; break ;;
+ -) break ;;
+ -*) echo "error: unknown option $1"; usage; exit 2 ;;
+ *) break ;;
+ esac
+done
+if [ $# -ne 1 ]; then usage; exit 2; fi
+file=$1
+case $mode in
+ dark|light) modes=$mode ;;
+ both) modes='dark light' ;;
+ *) echo "error: --mode must be dark, light or both"; exit 2 ;;
+esac
+is_pt() { printf '%s' "$1" | grep -Eq '^[0-9]+(\.[0-9]+)?$'; }
+for v in "$width" "$height"; do
+ if [ -n "$v" ] && ! is_pt "$v"; then echo "error: --width and --height are numbers in pt (got $v)"; exit 2; fi
+done
+
+# Typst: the PATH, else the mod's fallbacks (settings.ts TYPST_FALLBACKS).
+typst=$(command -v typst 2>/dev/null || true)
+if [ -z "$typst" ]; then
+ for t in /opt/homebrew/bin/typst /usr/local/bin/typst /usr/bin/typst /snap/bin/typst "$HOME/.cargo/bin/typst" \
+ "$HOME/.local/bin/typst" /home/linuxbrew/.linuxbrew/bin/typst "$HOME/.linuxbrew/bin/typst"; do
+ if [ -x "$t" ]; then typst=$t; break; fi
+ done
+fi
+if [ -z "$typst" ]; then
+ echo "error: typst not found (the mod needs Typst 0.15: brew install typst, or cargo install --locked typst-cli)"
+ exit 2
+fi
+version=$("$typst" --version 2>/dev/null | head -n 1)
+case $version in
+ 'typst 0.15.'*) ;;
+ *) echo "error: typst 0.15.x is needed, found ${version:-nothing} at $typst"; exit 2 ;;
+esac
+
+# The mod's cache root (docs/how-it-works.md step 6); runs older than a day go.
+cache=${TMPDIR:-/tmp}
+cache="${cache%/}/cc-intelligent-ui-$(id -u)"
+mkdir -p "$cache/check" && chmod 700 "$cache" 2>/dev/null
+find "$cache/check" -mindepth 1 -maxdepth 1 -type d -mmin +1440 -exec rm -rf {} + 2>/dev/null
+run=$(mktemp -d "$cache/check/run-XXXXXX") || { echo "error: can not make a folder in $cache/check"; exit 2; }
+
+# The input, kept as src.typ or src.md in the run folder.
+if [ "$file" = - ]; then
+ kind=typ label=stdin base=$PWD
+ cat > "$run/src.typ"
+else
+ if [ ! -f "$file" ]; then echo "error: no file $file"; exit 2; fi
+ case $file in
+ *.md|*.markdown|*.MD) kind=md ;;
+ *) kind=typ ;;
+ esac
+ label=$file
+ base=$(cd "$(dirname "$file")" && pwd -P)
+ cp "$file" "$run/src.$kind"
+fi
+src="$run/src.$kind"
+
+# The mod's store (`/iui theme`, `/iui grid`): the newest of its files.
+config=${CLAUDE_CONFIG_DIR:-$HOME/.claude}
+store=$(ls -t "$config"/plugins/store/cc-intelligent-ui_*.json 2>/dev/null | head -n 1)
+stored() { [ -n "$store" ] && grep -o "\"$1\"[[:space:]]*:[[:space:]]*[^,}]*" "$store" | head -n 1 | sed 's/^[^:]*:[[:space:]]*//; s/^"//; s/"[[:space:]]*$//'; }
+
+# The theme: a user theme wins over a built-in one; else claude-code, else vscode (themes.ts).
+theme_dir_of() {
+ case $1 in
+ */*) if [ -f "$1/theme.json" ]; then (cd "$1" && pwd -P); fi; return ;;
+ esac
+ printf '%s' "$1" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._-]*$' || return
+ for d in "$HOME/.claude/cc-intelligent-ui/themes/$1" "$root/render/themes/$1"; do
+ if [ -f "$d/theme.json" ]; then printf '%s\n' "$d"; return; fi
+ done
+}
+wanted=${theme_arg:-$(stored theme-name)}
+wanted=${wanted:-claude-code}
+theme_name=$wanted theme_note=''
+theme_dir=$(theme_dir_of "$wanted")
+for fallback in claude-code vscode; do
+ [ -n "$theme_dir" ] && break
+ theme_note="note: theme $wanted not found, using $fallback"
+ theme_name=$fallback
+ theme_dir=$(theme_dir_of "$fallback")
+done
+
+# The size: the newest design file (page width and room height in pt at the
+# last first compile, designs.ts), else 900 x 320.
+designs="${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"
+design=$(ls -t "$designs"/*/* 2>/dev/null | head -n 1)
+dw='' dh=''
+if [ -n "$design" ]; then
+ read -r dw dh _ < "$design" 2>/dev/null || true
+ is_pt "${dw:-x}" && is_pt "${dh:-x}" || { dw=''; dh=''; }
+fi
+width=${width:-${dw:-900}}
+height=${height:-${dh:-320}}
+
+# The row grid (on unless `/iui grid off`): one terminal row in pt, from the
+# newest page the mod drew (cell height x pt per pixel at the design width).
+row=''
+if [ "$(stored grid)" != false ] && [ -n "$dw" ]; then
+ pages=$(ls -t "$cache"/*/pages.json 2>/dev/null | head -n 1)
+ if [ -n "$pages" ]; then
+ num() { grep -o "\"$1\":[0-9.]*" "$pages" | head -n 1 | cut -d: -f2; }
+ row=$(awk -v w="$dw" -v pw="$(num width)" -v ph="$(num height)" -v r="$(num rows)" -v c="$(num columns)" 'BEGIN {
+ if (pw > 0 && ph > 0 && r > 0 && c > 0 && w / c > 3 && w / c < 12) { v = w * ph / (r * pw); if (v > 6 && v < 40) printf "%.4f", v }
+ }')
+ fi
+fi
+
+echo "using theme=$theme_name width=$width height=$height row=${row:-off}"
+[ -n "$theme_note" ] && echo "$theme_note"
+
+# The doc JSON (as the mod writes it): a .typ body goes in a fence longer
+# than any backtick run in it; Typst does the JSON escapes.
+"$typst" eval --root / --input "src=$src" --input "kind=$kind" --input "base=$base" '{
+ let body = read(sys.inputs.src)
+ let n = calc.max(3, ..body.matches(regex("`+")).map(m => m.text.len() + 1))
+ let fence = "`" * n
+ let md = if sys.inputs.kind == "typ" { fence + "typst\n" + body.trim("\n", at: end) + "\n" + fence + "\n" } else { body }
+ (base: sys.inputs.base, segments: (md,))
+}' > "$run/doc.json" 2> "$run/doc.log" || {
+ echo "error: can not read $label (it must be UTF-8 text)"
+ grep -v 'unknown font family' "$run/doc.log" | head -n 5
+ exit 2
+}
+printf '{"base":"","segments":[""]}\n' > "$run/empty.json"
+
+# Each live block alone (block-K.typ: the theme import, then its body), for
+# diagnostics with lines in FILE; map.txt: K, the line before the body, indent.
+shim="#import \"$run/shim.typ\": theme"
+printf '#import "%s/render/md.typ": live-theme as theme\n' "$root" > "$run/shim.typ"
+if [ $kind = typ ]; then
+ { printf '%s\n' "$shim"; cat "$src"; } > "$run/block-1.typ"
+ echo "1 0 0" > "$run/map.txt"
+else
+ awk -v dir="$run" -v shim="$shim" '
+ function lead(s, n) { n = 0; while (substr(s, n + 1, 1) == " ") n++; return n }
+ {
+ line = $0; sub(/\r$/, "", line)
+ if (!inb) {
+ if (match(line, /^ *(````*|~~~~*)/)) {
+ ind = lead(line); mark = substr(line, ind + 1, RLENGTH - ind); info = substr(line, RLENGTH + 1)
+ if (substr(mark, 1, 1) == "`" && index(info, "`")) next
+ lang = info; sub(/^[ \t]+/, "", lang); sub(/[ \t{].*$/, "", lang); lang = tolower(lang)
+ inb = 1; live = (lang == "typst" || lang == "typ")
+ if (live) { k++; f = dir "/block-" k ".typ"; print shim > f; print k, NR, ind > (dir "/map.txt") }
+ }
+ next
+ }
+ if (match(line, /^ *(````*|~~~~*)[ \t]*$/)) {
+ m = line; sub(/^ */, "", m); sub(/[ \t]*$/, "", m)
+ if (substr(m, 1, 1) == substr(mark, 1, 1) && length(m) >= length(mark)) { if (live) close(f); inb = 0; next }
+ }
+ if (live) { n = lead(line); if (n > ind) n = ind; print substr(line, n + 1) > f }
+ }
+ END { if (live && inb) close(f) }
+ ' "$src"
+ [ -f "$run/map.txt" ] || { echo "note: $label has no \`\`\`typst block"; : > "$run/map.txt"; }
+fi
+
+# Runs typst in the run folder (short paths) with the mod's env (typst.ts
+# noNetworkEnv) and its 20 s limit; its output goes to file $1.
+run_typst() {
+ local out=$1 pid dog status
+ shift
+ (cd "$run" && exec env HTTPS_PROXY=http://127.0.0.1:9 HTTP_PROXY=http://127.0.0.1:9 ALL_PROXY=http://127.0.0.1:9 \
+ https_proxy=http://127.0.0.1:9 http_proxy=http://127.0.0.1:9 all_proxy=http://127.0.0.1:9 NO_PROXY= no_proxy= \
+ TYPST_PACKAGE_CACHE_PATH="$cache/pkg-cache" "$typst" "$@") > "$out" 2>&1 &
+ pid=$!
+ # The watchdog stops its own sleep when it is stopped, so no process stays.
+ (sleep 20 & s=$!; trap 'kill $s; exit 0' TERM; wait $s && kill "$pid" && echo "error: timed out after 20 s (an endless loop?)" >> "$out") \
+ > /dev/null 2>&1 < /dev/null &
+ dog=$!
+ wait "$pid" 2> /dev/null
+ status=$?
+ kill "$dog" 2> /dev/null
+ wait "$dog" 2> /dev/null
+ return $status
+}
+inputs_of() {
+ set -- --input "theme=$1" --input "theme-dir=$theme_dir" --input "doc=$2" --input "width=$width" --input "height=$height"
+ [ -n "$row" ] && set -- "$@" --input "row=$row" --input grid=1
+ printf '%s\n' "$@"
+}
+
+# Diagnostics without font noise, with short paths.
+clean() {
+ grep -v 'unknown font family' "$1" | grep -v '^[[:space:]]*$' \
+ | sed -e 's#[^ ]*/render/md\.typ:#md.typ:#g' -e "s#$run/##g"
+}
+
+# The diagnostics of each block alone, at lines of FILE; an error inside a
+# package is put at its call site in the block ("in <place>"). Status 0 when
+# a block failed.
+block_errors() {
+ m=$1 failed=1
+ while read -r k start ind; do
+ [ -n "$k" ] || continue
+ old_ifs=$IFS; IFS='
+'
+ set -- $(inputs_of "$m" "$run/empty.json")
+ IFS=$old_ifs
+ log="$run/diag-$m-$k.log"
+ run_typst "$log" compile --root / --package-path "$root/render/packages" --diagnostic-format short \
+ "$@" "block-$k.typ" "diag-$m-$k.pdf" && continue
+ failed=0
+ first=$(clean "$log" | grep -m 1 'error:')
+ at=''
+ case $first in
+ "block-$k.typ:"*|*'timed out'*|'') ;;
+ *)
+ run_typst "$run/trace-$m-$k.log" compile --root / --package-path "$root/render/packages" --diagnostic-format human \
+ "$@" "block-$k.typ" "diag-$m-$k.pdf"
+ at=$(grep -o "block-$k\.typ:[0-9]*:[0-9]*" "$run/trace-$m-$k.log" | head -n 1)
+ ;;
+ esac
+ clean "$log" | awk -v k="$k" -v s="$start" -v i="$ind" -v label="$label" -v at="$at" '
+ function place(p) { split(p, a, ":"); return label ":" (s + a[2] - 1) ":" (a[3] + i) }
+ {
+ p = "block-" k ".typ:"
+ if (index($0, p) == 1 && match($0, /^[^:]*:[0-9]+:[0-9]+/)) print place(substr($0, 1, RLENGTH)) substr($0, RLENGTH + 1)
+ else if (at != "" && !done && index($0, "error:")) { done = 1; c = index($0, ": "); print place(at) substr($0, c) " (in " substr($0, 1, c - 1) ")" }
+ else print " " $0
+ }'
+ done < "$run/map.txt"
+ return $failed
+}
+
+# The PNGs of a mode, in page order, each on the theme's background (the
+# mod's PNGs are clear over the terminal); the clear one when that fails.
+printf '#import "%s/render/theme.typ": C\n#page(width: auto, height: auto, margin: 0pt, fill: C.bg, image(sys.inputs.png))\n' "$root" > "$run/backdrop.typ"
+pngs_of() {
+ n=1 list=''
+ while [ -f "$run/clear-$1-$n.png" ]; do
+ out="$run/$1-$n.png"
+ run_typst "$run/backdrop.log" compile --root / --ppi 72 --input "png=$run/clear-$1-$n.png" --input "theme=$1" \
+ --input "theme-dir=$theme_dir" backdrop.typ "$out" || out="$run/clear-$1-$n.png"
+ list="$list $out"; n=$((n + 1))
+ done
+ printf '%s' "${list# }"
+}
+
+all=0
+for m in $modes; do
+ old_ifs=$IFS; IFS='
+'
+ set -- $(inputs_of "$m" "$run/doc.json")
+ IFS=$old_ifs
+ if run_typst "$run/$m.log" compile --root / --package-path "$root/render/packages" --format png --diagnostic-format short \
+ --ppi 144 "$@" "$root/render/md.typ" "clear-$m-{p}.png"; then
+ echo "ok $m $(pngs_of "$m")"
+ clean "$run/$m.log" | sed 's/^/ /'
+ else
+ all=1
+ echo "error $m"
+ if grep -q 'timed out' "$run/$m.log"; then
+ clean "$run/$m.log" | grep 'timed out'
+ elif ! block_errors "$m"; then
+ clean "$run/$m.log"
+ echo "note: no block fails alone; the error comes from the Markdown or the page (#pagebreak, #set page, bad math)"
+ fi
+ fi
+done
+echo "hint: look at each PNG with the Read tool; a clean compile can still overlap, overflow or draw in invisible colours"
+exit $all
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index 6728762..698282e 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -544,6 +544,8 @@ test('Claude is told about typst blocks', () => {
expect(TYPST_PROMPT.includes('Each typst block compiles alone')).toBe(true)
expect(TYPST_PROMPT.includes('theme.code-bg')).toBe(true)
expect(TYPST_PROMPT.includes('break a long label with `\\`')).toBe(true)
+ expect(TYPST_PROMPT.includes('load the cc-intelligent-ui:intelligent-ui skill first')).toBe(true)
+ expect(TYPST_PROMPT.includes('normal answers and drawings like these need no skill')).toBe(true)
expect(TYPST_PROMPT.endsWith('keep replies readable as plain text too.')).toBe(true)
})