Plugins
Everything beyond plain boxes and arrows is a plugin: the extra themes, chart and table rows in cards, window frames, the legend and footer strips and the sequence, timeline, chart and git panels. The core stays small, and you can add your own pieces the same way.
yuhwa registers the built-in plugins on import. Nothing to set up.
| plugin | adds |
|---|---|
shapes | every node shape and its aliases: rounded, box, pill, circle, cylinder, … |
markers | the edge ends arrow, open, dot, diamond, bar |
themes | midnight blueprint mono pastel terminal sepia frost contrast ocean ember dusk |
charts | bars, spark, progress and stat card rows |
tables | Markdown tables in cards |
frames | the frame node prop: browser, window, terminal |
legend | the legend setting |
footer | the footer setting |
sequence | sequence { } panels, see Sequence |
timeline | timeline { } panels, see Timeline |
chart | chart { } panels: bar, column, line, pie, donut, see Chart |
git | git { } panels, see Git |
mindmap | mindmap { } panels, see Mindmap |
gantt | gantt { } panels, see Gantt |
quadrant | quadrant { } panels, see Quadrant |
kanban | kanban { } panels, see Kanban |
treeview | treeview { } panels, see Treeview |
Charts
Each row takes an optional colour after its keyword: bars green: ….
theme: midnight
api "API" [meta: 24h] {
stat: 99.9% uptime | 42ms p95 | 1.2k rps
---
spark blue: 3 5 4 6 8 7 9 12 10 14
}
ci "CI" [meta: main] {
progress green: 72% tests
progress amber: 9/12 deploys
---
bars purple: 3 5 4 8 6 9
}
api -> ci| row | values |
|---|---|
bars: 3 5 4 | numbers, drawn as bars |
spark: 3 5 4 | numbers, drawn as a line with a soft area |
progress: 72% label | a percentage, or done/total like 9/12 |
stat: value label | value label | big numbers with a muted label each |
Frames
frame wraps a card in window chrome. The word after the kind is shown in the bar: a URL for browser, a title for window, a path for terminal.
app "Storefront" [frame: browser shop.example.com, blue] {
**Checkout** is live
*since 09:12*
}
cli "Deploy" [frame: terminal ~/shop] {
✓ build || [[green: 42s]]
✓ push || [[green: 8s]]
}
prefs "Flags" [frame: window Settings] {
new-checkout || [[green: on]]
dark-mode || [[off]]
}
app -> cli -> prefsLegend
legend adds a key under the diagram, above the footer. Split items with |. Each item starts with what it explains:
| item | swatch |
|---|---|
.svc Service | a small node styled like the class |
red Deprecated | a colour swatch |
--> async | an arrow; any arrow from the edge table |
legend: .svc Service | .store Datastore | --> async | red Deprecated
.svc [blue]
.store [amber, cylinder]
web "Web" .svc -> api "API" .svc -> db "Orders" .store
api --> queue "Queue" [red]Footer
footer adds a strip under the diagram. Split items with |: the first sits left, the last right, the rest in between. Items take inline markup, style spans included.
title: Shop release **v2.4**
footer: **landfall** v2.4 | `eu-central-1` | updated {green: 2 min ago}
web "Web" -> api "API" -> db "DB" [cylinder]Writing a plugin
A plugin is a plain object passed to use. Registering the same name twice does nothing, so use is safe to call from several modules. unuse(name) removes a plugin again and restores whatever it replaced.
render never throws, and neither do your plugin's functions inside it: an exception becomes an error diagnostic (plugin "dots": render failed: …) and the call falls back to drawing nothing. When a panel's parse throws, the error sits on the panel's first line and the panel is drawn empty: its other functions are not called for it. A plugin that registers a panel, statement, shape, marker, frame, row kind or decoration another plugin already owns replaces it, with a console.warn.
yuhwa/plugin holds everything for writing one: the kind types, definePlugin (types a plugin object without annotations) and the helpers for text, colours, props and geometry. The built-in plugins import nothing else, so a plugin of your own can do whatever a built-in one does.
import { use, render } from 'yuhwa';
import type { YuhwaPlugin, RowKind } from 'yuhwa/plugin';
// `dots: 3/5` in a card body draws five dots, three filled
const dots: RowKind<{ kind: 'dots'; on: number; of: number }> = {
kind: 'dots',
syntax: 'dots: 3/5',
parse(line) {
const m = line.match(/^dots:\s*(\d+)\s*\/\s*(\d+)$/);
return m ? { kind: 'dots', on: +m[1], of: +m[2] } : null;
},
measure: (r, { fs }) => ({ w: r.of * fs, h: fs * 1.2 }),
render(r, box, { fs, col }) {
let out = '';
for (let i = 0; i < r.of; i++)
out += `<circle cx="${box.x + fs * (i + 0.5)}" cy="${box.y + fs * 0.6}" r="${fs * 0.3}"
fill="${i < r.on ? col.text : 'none'}" stroke="${col.stroke}"/>`;
return out;
},
};
const plugin: YuhwaPlugin = { name: 'dots', rows: [dots] };
use(plugin);
render('x "Rating" {\n dots: 3/5\n}');A plugin can provide any of these:
| field | what it is |
|---|---|
themes | Theme objects, selectable with theme:; edge.ink defaults to edge.text |
rows | card body rows: parse claims a line, measure sizes it, render draws it |
frames | chrome for the frame prop: inset reserves space, render draws it |
panels | whole diagram types next to the graph, see below |
decorations | strips around the diagram, switched on by a setting |
settings | extra settings accepted without a warning |
props | extra node, edge and group props accepted without a warning |
enums / bools / numbers | value checks for those props |
statements | new top-level keywords, like service api "API" |
shapes | new node shapes for the shape prop |
markers | new edge ends for head and tail |
transform(d) | change the parsed diagram before layout |
afterLayout(L, d) | move or resize things after automatic layout |
postRender(svg, d, L) | return a changed SVG string |
Row parse gets every trimmed body line in order. Return a row object to claim the line, true when you merged it into the previous row (as tables do), or null to let the next row kind try. Plain text is the fallback.
Panel kinds
A panel kind owns a block kind id "Title" [props] { ... }. The parser hands it the body lines verbatim (dedented); layout places the box; you draw inside it.
import { use } from 'yuhwa';
import { esc, type PanelKind } from 'yuhwa/plugin';
// checklist done "Launch" { [x] docs \n [ ] pricing }
const checklist: PanelKind<{ done: boolean; text: string }[]> = {
name: 'checklist',
syntax: 'checklist id "Title" { [x] item }',
parse(body, props, warn) {
return body.flatMap((line, i) => {
const m = line.trim().match(/^\[( |x)\]\s+(.*)$/);
if (!m) {
if (line.trim()) warn(i, 'checklist: expected "[x] item"');
return [];
}
return [{ done: m[1] === 'x', text: m[2] }];
});
},
measure: (items, { fs }) => ({ w: fs * 14, h: items.length * fs * 1.8 }),
render(items, box, { fs, theme }) {
return items
.map(
(it, i) =>
`<text x="${box.x}" y="${box.y + (i + 0.6) * fs * 1.8}" font-size="${fs}"
fill="${it.done ? theme.node.sub : theme.node.text}">${it.done ? '✓' : '○'} ${esc(it.text)}</text>`,
)
.join('');
},
};
use({ name: 'checklist', panels: [checklist] });warn(i, message) reports a problem on body line i (or the header with -1); the diagnostic points at the right line of the file. measure and render get { theme, measure, fs, props, offsets }, where props are the header props. The frame and title are drawn for you.
render returns raw SVG, so pass every piece of user text through esc before you put it in. It escapes & < > ", which covers element text and quoted attribute values.
guide describes the body lines in one sentence for yuhwa guide (the header props come from options). A kind with handles also sets layoutParts, naming its parts for the layout block.
Letting users adjust the drawing
Automatic placement is never right for every case. A panel kind can name its parts and let the user nudge each one:
ctx.offsetsholds the offsets the user set, by part name. They come frompanel:part D(orpanel:part DX DY) lines in thelayoutblock. Add them where you place that part, inmeasureand inrender.handles(data, box, ctx)returns the draggable points the visual editor shows when the panel is selected:{ part, x, y, axis?, title? }, in diagram units.axis: 'x'or'y'limits a drag to one direction; the editor then writes a single number, which your code reads from.x. Name axes by meaning (along time, across lanes), not by screen direction, and the user's nudges survive a layout switch. When a handle moves a value declared in the panel body, provideeditPosition(body, offset)to rewrite its existing line on drop. Return the updated body with the same line count.optionslists the header props and their type. The editor, the language server andyuhwa guideread it. A list of values is a select.'color'shows a colour picker,'number'a number field,'text'a text field.'flag'is a prop that is off unless written, shown as a checkbox:options: { direction: ['right', 'down'], accent: 'color', gap: 'number', numbered: 'flag' }.helpmaps an option to one line saying what it does. The editor shows it under the field and the language server in its hover:help: { gap: 'space between the steps, px' }.
const steps: PanelKind<string[]> = {
name: 'steps',
parse: (body) => body.map((l) => l.trim()).filter(Boolean),
measure: (items, { fs }) => ({ w: fs * 12, h: items.length * fs * 2 }),
render(items, box, { fs, offsets }) {
return items
.map((t, i) => {
const dx = offsets[`s${i + 1}`]?.x ?? 0; // the user's nudge for this step
return `<text x="${box.x + dx}" y="${box.y + (i + 0.7) * fs * 2}">${esc(t)}</text>`;
})
.join('');
},
handles: (items, box, { fs, offsets }) =>
items.map((_, i) => ({
part: `s${i + 1}`,
axis: 'x',
x: box.x + (offsets[`s${i + 1}`]?.x ?? 0),
y: box.y + (i + 0.5) * fs * 2,
})),
};Keep part names stable when the data changes. Prefer names the user wrote (an id, a tag) over positions.
SVG ids (patterns, gradients, clip paths) must be unique on the page, which may hold several diagrams. Start them with ctx.idPrefix, which is different for every panel of every diagram.
Working out the geometry once
measure, render and handles usually need the same positions. Layout hands all three the same ctx object, so wrap the function that works them out in perPass and it runs (and measures text) once per panel per render:
import { perPass, type PanelCtx } from 'yuhwa/plugin';
const geometry = perPass((items: string[], { fs, measure }: PanelCtx) => {
const w = Math.max(...items.map((t) => measure(t, fs, 400, false)));
return { w, rowH: fs * 2 };
});
// measure: (items, ctx) => { const g = geometry(items, ctx); return { w: g.w, h: items.length * g.rowH }; }The cache is keyed on the ctx and the parsed data, so a new parse or a new layout pass computes it again.
Editable parts
The editor lists a panel's parts and edits them in the source. Two fields drive this:
parts(data)returns{ id, label, kind, tone?, depth?, fields?, values?, actions?, adds? }for each part.fieldsnames what the part can set, by key: a list of values becomes a select, an empty list a text field,['', 'true']a toggle.depthindents the part in the list.valuesholds the current ones.actionslists the moves it takes:up,down,removeandadd(a child, named byadds, such as a card in a column).editPart(body, edit, data)applies one edit to the body lines and returns{ body, id }, whereidis the edited part's id afterwards (it may change when the part moves or is renamed), ornullwhen the edit does not apply. An edit is{ op: 'set', id, key, value },{ op: 'up' | 'down' | 'remove', id }or{ op: 'add', id? };addwithout an id adds a top-level part, named by the kind's ownadds.
color is always a field. For a kind whose parts only take a colour, recolor builds editPart from a function that rewrites the body:
import { recolor, setTrailingProp } from 'yuhwa/plugin';
editPart: recolor((body, id, tone) => {
const i = body.findIndex((l) => l.trim().startsWith(id));
if (i < 0) return null;
const out = [...body];
out[i] = setTrailingProp(body[i], 'color', tone); // tone null removes it
return out;
}),Code outside the editor calls editPart(source, panelId, edit) on the whole source, see Editing source.
Shared drawing helpers
Panels draw lines and props the same way graph edges do with these, all from yuhwa/plugin:
| helper | does |
|---|---|
renderHead(at, angle, kind, color, width, length?) | an edge end (arrow, open, dot, diamond, bar or a plugin marker) with its tip at at |
dashFor(style, width) | the stroke-dasharray for dashed or dotted at a stroke width; null for solid |
lineStyle(props) | the line style a prop list asks for (style: dotted, bare dashed, …) |
splitTrailingProps(text, accept?) | text [props] into the text and its props; accept may refuse the bracket, which then stays text |
setLineProp(line, head, key, value, accept?) | set or remove one prop on a label [props]: value line, keeping the bracket at the end when it was written there; onlyColor accepts only a colour bracket |
setTrailingProp(line, key, value) | set or remove one prop in a line's trailing bracket |
ctx.theme.edge.ink is the line colour for panel lines that should read stronger than graph edges (sequence messages); edge-color on the panel sets it together with edge.stroke.
Statements, shapes and markers
These three extend the language itself. A statement owns a keyword at the start of a line. A line whose keyword is followed by an arrow, : or , is still an edge, a setting or a node list, so a node named like a keyword keeps working.
import { use } from 'yuhwa';
import type { YuhwaPlugin } from 'yuhwa/plugin';
const cloud: YuhwaPlugin = {
name: 'cloud',
// `lambda resize "Resize images"` → a node with the cloud shape
statements: [
{
keyword: 'lambda',
syntax: 'lambda id "Label"',
parse(args, d, { warn }) {
const m = args.match(/^([\w-]+)\s*(?:"([^"]*)")?$/);
if (!m) return warn('lambda: expected lambda id "Label"');
d.nodes.set(m[1], {
id: m[1],
label: m[2] ?? m[1],
props: { shape: 'cloud', color: 'orange' },
classes: [],
implicit: false,
});
},
},
],
// a shape gets the node box and returns SVG path data
shapes: [
{
name: 'cloud',
size: (w, h) => ({ w: w + 48, h: h + 32 }),
path: (b) => {
const r = b.h / 2;
return `M${b.x + r} ${b.y + b.h} a${r} ${r} 0 0 1 0 ${-b.h} h${b.w - 2 * r} a${r} ${r} 0 0 1 0 ${b.h} Z`;
},
},
],
// `head: chevron` on an edge; inset pulls the line back from the node
markers: [
{
name: 'chevron',
inset: 6,
render: (at, angle, { color, width }) =>
`<path d="M-8 -5 L0 0 L-8 5" fill="none" stroke="${color}" stroke-width="${width}"
transform="translate(${at.x} ${at.y}) rotate(${(angle * 180) / Math.PI})"/>`,
},
],
};
use(cloud);parse gets the text after the keyword, the diagram being built, the line number and a warn that reports on that line. Keep what you parsed on d.data[pluginName] when it is not a node, edge or group. Registered shape and marker names are accepted by shape, head and tail without a warning, and show up in the editor, the language server and yuhwa guide.
The built-in shapes and markers are plugins too (shapes and markers), so yours get the same hooks:
aliaseslists other names for the shape (dbforcylinder).textOffsetmoves the label down inside the outline, in px.port(box, side, t)returns where an edge meets the outline onside, withtfrom -1 to 1 along that side. Without it, edges meet the bounding box.portOn(box, side, t, spread, depth)builds one:depth(horiz, rel, u)returns the distance from the centre to the outline.
import { portOn, type ShapeKind } from 'yuhwa/plugin';
const lens: ShapeKind = {
name: 'lens',
aliases: ['eye'],
path: ({ x, y, w, h }) =>
`M${x},${y + h / 2}Q${x + w / 2},${y - h / 2} ${x + w},${y + h / 2}Q${x + w / 2},${y + h * 1.5} ${x},${y + h / 2}Z`,
// the outline bulges to the box edge in the middle and meets the centre line at the ends
port: (b, side, t) => portOn(b, side, t, 0.5, (horiz, rel) => (horiz ? (b.h / 2) * (1 - rel * rel) : b.w / 2)),
};A core without the shapes plugin draws every node as a rounded box. Without markers, edges have no ends.
Hooks
transform, afterLayout and postRender run on every render, in the order plugins were registered. transform runs once per diagram, after its imports are merged in.
use({
name: 'stamp',
// every node without a colour gets one
transform: (d) => {
for (const n of d.nodes.values()) n.props.color ??= 'slate';
},
// nudge a node after the automatic layout
afterLayout: (L) => {
const n = L.nodes.get('db');
if (n) n.y += 20;
},
// add a watermark
postRender: (svg) => svg.replace('</svg>', '<text x="4" y="12" font-size="9" opacity=".4">draft</text></svg>'),
});transform runs after the parser's own checks, so props it adds are not linted. afterLayout runs after edges are routed: edges keep their path when a node moves there, so use it for extra marks, not for moving connected nodes.
The exported helpers parseInline, segsW, renderSegs and tspans give a row the same inline markup as text lines. registry lists what is registered.