# Syntax A yuhwa file reads like notes: one thing per line, written the way you would say it. Start with arrows and add detail only where it helps. ```yuhwa web -> api -> db ``` Name things, label the edges and add a little colour: ```yuhwa web "Storefront" -> api "Orders API": place order api -> db "Postgres" [cylinder, amber]: SQL ``` When a line gets long, put the props on their own lines below it: ```yuhwa title: Order pipeline api "Orders API" color: blue sub: Kotlin · 3 pods link: https://example.com/orders db "Postgres" [cylinder, amber] api -> db: SQL style: dashed ``` For a large diagram, name the look once with classes and variables, stamp out repeated parts with components, and split the file with imports. `//` starts a comment at the start of a line or after a space, so the `//` in `https://example.com` stays text. There is no other comment syntax: a line starting with `#` is an error. The statements: 1. Settings 2. Nodes 3. Edges 4. Classes, variables and components 5. Groups 6. Props 7. The `layout` block ## Settings A setting is `key: value` on its own line, usually at the top of the file. | setting | values | default | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- | | `title` | text, with inline markup | none | | `subtitle` | muted line under the title | none | | `footer` | `a \| b \| c`: a strip under the diagram, items spread edge to edge (plugin) | none | | `theme` | `paper` `midnight` `blueprint` `mono` `pastel` `terminal` `sepia` `frost` `contrast` `ocean` `ember` `dusk`, or your own (`auto` in the browser) | `paper` | | `direction` | `right` `down` `left` `up`; Mermaid's `LR` `RL` `TB` `TD` `BT` work too | `right` | | `curve` | `smooth` `orthogonal` `straight` | `smooth` | | `gap` | space between nodes in a rank, px | `36` | | `rank-gap` | space between ranks, px | `72` (`96` with groups) | | `max-width` | fit the diagram into this width, px: ranks wrap into rows (more) | none | | `padding` | space around the diagram, px | `24` | | `shape` | default node shape | `rounded` | | `font` | font family or fallback list, e.g. `Inter`, `Lora, Georgia, serif` (fonts) | theme font | | `font-size` | px | theme size | | `background` | colour, or `none` for transparent | theme background | | `grid` | `true`, `false` or a colour | theme default | | `shadow` | `true` / `false` | theme default | | `radius` | node corner radius, px | theme default | | `stroke-width` | node border width, px | theme default | | `edge-color` | default colour of every edge, sequence message and Gantt arrow | theme edge colour | | `edge-width` | their default width, px | theme default | | `accent` | colour of `` `code` ``, chips and bars in cards | theme accent | | `panels` | `row` `column` `grid`: how panels line up next to the graph | `row` | | `panel-gap` | space between the graph and panels, px | `48` | | `wrap` | wrap node labels wider than this, px | none | | `legend` | `.class Label \| color Label \| --> Label`: a key under the diagram (plugin) | none | An unknown setting gives a warning that suggests the closest known one (`titel` → `title`). The setting is kept, so typos stay visible. ## Nodes ``` id ["Label"] [.class ...] [[props]] ``` ```yuhwa web api "API Gateway" .store [amber] db "Orders DB" .store [cylinder] ``` - `id` is letters, digits, `_` and `-`. It is what edges refer to. - The label defaults to the id. Labels use `"double"` or `'single'` quotes. `\n` inside a label makes a line break. - Declaring the same id twice merges the props. The later value wins. Several nodes can go on one line, separated by commas: ```yuhwa a "Alpha", b "Beta", c "Gamma" [green] ``` A node does not have to be declared. Using an id in an edge creates it. ## Edges ``` a -> b [-> c ...] [: label] [.class ...] [[props]] ``` ```yuhwa user -> web -> api api -> db: SQL api -> cache: read-through [dashed] api -> audit: [flow] ``` ### Arrows | arrow | line | heads | | ---------- | ------ | ------------ | | `->` | solid | at the end | | `-->` | dashed | at the end | | `..>` | dotted | at the end | | `=>` `==>` | thick | at the end | | `<->` | solid | at both ends | | `--` `-` | solid | none | Props can override all of these: `style`, `width`, `head` and `tail`. ### Labels and props after a colon Edge labels, classes and props always go after a colon. The colon keeps them apart from inline node declarations (see the next section). ```yuhwa a -> b: add item .warn [red] a -> b: "label: with a colon" a -> b: retry .warn [width: 2] a -> b: [dotted] ``` A label without quotes runs to the first class or `[`. Use quotes when the label contains `:`, `[`, `.` at the start of a word, or leading spaces. ### Inline nodes A label, classes or props written directly after an id in an edge declare that node, exactly like a node statement: ```yuhwa web "Web" [blue] -> api "API" -> db "DB" [cylinder]: SQL ``` Here `[cylinder]` belongs to `db` and `SQL` labels every edge on the line. A quoted string after the last node without a colon is an error. The message shows the fix: `(edge labels go after a colon: a -> b: "label")`. In the same way, `a -> b [dashed]` dashes the border of `b`, not the edge. Write `a -> b: [dashed]`, or put `style: dashed` on the next line. An edge-only prop on a node, like `[thick]`, gives a warning that says so. ### Chains and fan-out `a -> b -> c` creates two edges. Commas fan out: ```yuhwa web, mobile -> api // two edges api -> users, orders, cart // three edges ``` The label, classes and props after the colon apply to every edge created by the statement. ### Repeated edges Two edges between the same nodes are both drawn. In the `layout` block the second one is addressed as `a->b#2`. ## Classes A class is a named set of props. ```yuhwa .svc [blue, rounded] .store [amber, cylinder] .async [dashed, flow] orders "Orders" .svc db .store orders -> queue: publish .async ``` - A class can apply to nodes, edges and groups. Props that do not fit the target are ignored. - Several classes apply left to right. Props written on the element override all classes. - An unknown class gives a warning. A class can build on other classes. The new class gets their props, then its own: ```yuhwa .svc [blue, rounded] .primary .svc [bold, stroke-width: 2] .legacy .svc [gray, dashed] api "API" .primary old "Old API" .legacy api -> old ``` ## Variables A variable holds a value you use in many places. Define it with `$name: value`, then write `$name` in labels, props, settings and panel bodies. ```yuhwa $brand: violet $db: "Postgres 16" title: Shop accent: $brand .svc [$brand] api "API" .svc -> orders-db "$db" [cylinder] ``` - Define a variable before you use it. A later definition replaces the value for the lines after it. - Write `${name}` when letters follow directly: `${id}_db`. - `$$` is a literal `$`. A `$` before a digit stays as it is: `"costs $5"`. - An unknown variable gives a warning and the text stays unchanged. ## Components A component stamps out the same lines many times. Define it with `def`, then call it like a function: ```yuhwa $db: Postgres .svc [blue, rounded] .store [amber, cylinder] def service(id, label, lang = Go) { $id "$label" .svc [sub: $lang] ${id}_db "$db" .store $id -> ${id}_db } service(orders, "Orders") service(payments, "Payments", Rust) service(search, "Search", lang: Kotlin) gateway "Gateway" -> orders, payments, search ``` - Parameters are variables inside the body. `name = value` gives a default. - Arguments go by position or by name (`lang: Rust`). Quote an argument that holds a comma. - A body can hold nodes, edges, groups, cards and calls to other components. - File variables are fixed when the component is defined, so a component works the same after it is imported. - `def` is top-level only. Errors inside a call point at the call line. - The visual editor cannot edit a generated line in place. A prop you change there is added as a new line for that node. ## Groups ``` group id ["Label"] [.class ...] [[props]] { members } ``` ```yuhwa group backend "Backend" [blue] { api "API" worker "Worker" group data "Data" { db [cylinder] } } group edge "Edge" { cdn, waf } ``` - The id is optional: `group "Order service" {` gets the id `order-service`. - Nodes declared or referenced inside the braces become members. - Groups nest. - Edges can be written inside or outside a group. Where an edge is written does not change membership of nodes that are already in a group. - Edges can not point at a group. ## Props Props are a comma-separated list in square brackets: ``` [key: value, key: "quoted value", flag] ``` A key without a value means `true`. Values can be bare words, numbers, colours or quoted strings. A bare value that only fits one key stands for that key: | written | means | | ---------------------- | --------------------------------- | | `[blue]` | `[blue]` | | `[cylinder]` | `[shape: cylinder]` | | `[orthogonal]` | `[curve: orthogonal]` | | `[dashed]`, `[dotted]` | a dashed or dotted line or border | | `[thick]` | a line twice as wide (edges) | So `db "Postgres" [cylinder, amber, bold]` needs no keys at all. ### One prop per line Props can also go on their own lines, indented below the statement. This reads better than a long `[...]` list: ```yuhwa .svc color: blue shape: rounded group payments "Payments" { color: green pay "Payment API" .svc sub: Rust tooltip: "charges, refunds, payouts" ledger [cylinder] } pay -> ledger: write style: dashed caption: append only ``` - A `key: value` line indented deeper than a node, edge, class or group line belongs to that statement. - Inside a group, a `key: value` line at the members' indent belongs to the group. - The value runs to the end of the line, so commas need no quotes. - Both styles can be mixed. A line below wins over the same key in `[...]`. - The visual editor keeps the style: it edits the prop line, and adds new props as lines too. ### Colours Any colour prop accepts: - a CSS colour: `#2563eb`, `rgb(…)`, `tomato` - a palette name: `blue`, `amber`, … The theme picks a fitting shade. - a palette name with a shade: `blue-600`, `slate-100` (50, 100 … 900, 950) ### `color` `color` sets fill, border and text colour together. It is the quickest way to colour something. Write it bare, `[blue]`, or as `[color: blue]`. Palette names: `slate` `gray` `red` `orange` `amber` `lime` `green` `teal` `cyan` `blue` `indigo` `purple` `pink`. The theme picks shades that fit, so they look right in light and dark themes. Any CSS colour works too, bare or with the key: `[#e11d48]`, `[#e11d4880]`, `[rgb(225, 29, 72)]`, `[hsl(350 80% 50%)]`, `[tomato]`. Yuhwa derives the fill, border and text from it. `tone` is the old name of `color` and still works. ### Node props | prop | values | | --------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `shape` | `rounded` `box` `pill` `circle` `ellipse` `diamond` `hexagon` `cylinder` `parallelogram` `document` `note` `text` | | `color` | palette name or any CSS colour: fill, border and label in one | | `fill` | colour | | `stroke` | border colour | | `text` | label colour | | `sub` | second, smaller line of text | | `sub-color` | colour of the `sub` line | | `icon` | emoji or short text shown before the label | | `border` / `stroke-width` | border width, px | | `border-style` | `solid` `dashed` `dotted` | | `dashed` | shorthand for `border-style: dashed` | | `radius` | corner radius, px | | `bold` / `italic` | flags | | `font` | label font: `sans` `serif` `mono` or font names (quote a list: `font: "Lora, serif"`) | | `font-size` / `font-weight` | numbers | | `shadow` | `true` / `false` | | `opacity` | 0 to 1 | | `width` / `height` | box size, px | | `max-width` | wrap the label at this width, px (overrides the `wrap` setting) | | `link` | URL; the node becomes a link in the SVG. Only http(s), mailto, `#anchor` and relative links render | | `tooltip` | text shown on hover | | `meta` | muted text at the top right of a card | | `caps` | small-caps header label | | `mono` | `false` sets a card body in the diagram font | | `body-size` / `body-weight` | card body font size, px, and weight (cards) | | `body-color` | card body text colour; defaults to `text` | | `line-height` | card body row height as a multiple of `body-size`, default `1.75` | | `frame` | `browser `, `window ` or `terminal <path>`: window chrome around a card (plugin) | | `below` / `above` | node id: place this node under or over that one (placement) | | `right-of` / `left-of` | node id: place this node to the right or left of that one | | `rank` | node id: put this node in the same rank as that one | `shape: text` draws only the label, with no box. Use it for annotations. ### Edge props | prop | values | | -------------------- | ------------------------------------------------------------------------- | | `style` | `solid` `dashed` `dotted` | | `width` | line width, px | | `color` | line and label colour: palette name or any CSS colour | | `stroke` | line colour only | | `curve` | `smooth` `orthogonal` `straight` | | `head` | `arrow` `open` `dot` `diamond` `bar` `none` | | `tail` | same values as `head`, for the start | | `flow` / `animate` | animated dashes along the edge | | `opacity` | 0 to 1 | | `text` | label text colour (`label-color` works too) | | `font` | label font: `sans` `serif` `mono` or font names | | `font-size` | label font size, px | | `font-weight` | label weight: `400`, `600`, `700` ... | | `italic` | italic label | | `label-bg` | label background colour | | `exit` / `from-side` | `top` `right` `bottom` `left` | | `enter` / `to-side` | `top` `right` `bottom` `left` | | `constraint` | `false` keeps the edge from affecting the layout | | `length` | ranks the edge spans, 1 to 12 (default 1): pushes the target further away | | `caption` | small muted text under the label | | `rotate` | `true` turns the label to run vertically | The `curve:` setting picks the default for the whole diagram. An edge's own `curve` overrides it, so one diagram can mix all three. A class works too: ```yuhwa direction: right curve: smooth .wire [orthogonal, dashed] api "API" -> db "DB" [shape: cylinder]: [orthogonal] api -> cache "Cache": [straight] api -> queue "Queue": .wire queue -> worker "Worker" ``` Use `constraint: false` for feedback edges that would pull the layout apart. ### Group props | prop | values | | -------------- | ------------------------------------ | | `color` | palette name or any CSS colour | | `fill` | background colour | | `stroke` | border colour | | `text` | title colour | | `font` | title font: `sans` `serif` `mono` | | `font-size` | title font size, px | | `font-weight` | title weight, default `600` | | `italic` | italic title | | `border-style` | `solid` `dashed` `dotted` | | `dashed` | shorthand for `border-style: dashed` | | `meta` | muted text at the top right | | `caps` | small-caps title | A group is as wide as its label and `meta` need. When other nodes leave too little room beside the group, the label wraps onto more lines instead. ### Text Every element takes the same five text props: `text` (colour), `font`, `font-size`, `font-weight` and `italic`. They style a node's label, an edge's label, a group's title and a panel's title. On a panel, `font-size` also scales the text inside it. `font` takes the same values as the `font` setting: `sans`, `serif`, `mono` or font names. Quote a list, since commas separate props: `[font: "Lora, serif"]`. To style only part of a text, wrap it in a span: `{keys | text}`. The keys are `color`, `size`, `weight`, `font` and `italic`, separated by commas. A span's `font` takes one name: `{font: mono | code}`. A bare colour sets the colour, and a bare `bold` or `italic` sets that flag. Spans work in every text: labels, `sub`, edge labels and captions, group and panel titles, card bodies and panel items. | span | result | | ------------------------------- | ------------------------ | | `{color: red \| text}` | coloured text | | `{size: 18 \| text}` | bigger text, px | | `{weight: 700 \| text}` | heavier text | | `{italic \| text}` | italic text | | `{font: mono \| text}` | monospace text | | `{red, bold, size: 18 \| text}` | all at once, short form | | `{red: text}` | coloured text, as before | The other inline markup (`**bold**`, `*muted*`, `[[chip]]` ...) works in these texts too. ```yuhwa direction: right api "{size: 18, weight: 800 | API} {font: mono | v2}" [sub: "{green | ●} healthy", italic] db "Orders" [shape: cylinder, font: serif, font-size: 16, font-weight: 700, text: indigo] group back "Backend" [font-size: 14, font-weight: 800, text: teal] { api db } api -> db: "{bold | writes}, {italic | async}" [font-size: 13, text: orange] ``` ## Cards A node with a `{ }` body becomes a card: a header with the label, a divider, and monospace lines below. A body opens with `{` at the end of the node line and closes with a line that is only `}`. ```yuhwa theme: terminal checks "checks" [meta: 42s, caps] { ✓ typecheck || [[green: pass]] ✓ tests || [[green: 128]] *skipped: e2e* --- bars: 3 5 4 6 8 7 9 } release "release" [meta: v0.1.0, caps] { | type | bump | |-------|-------| | feat | minor | | fix | patch | --- ~~manual tagging~~ } checks -> release: green caption: on main ``` Body lines: | line | result | | -------------------------------- | --------------------------------------------------------- | | text | a line of text | | `left \|\| right` | `right` is aligned to the right edge | | `---` | a divider | | empty line | a small gap | | `bars: 3 5 8` | a bar chart; `bars green: …` picks a colour | | `spark: 3 5 4 8` | a sparkline with a soft area | | `progress: 72% tests` | a labelled progress bar; `9/12 deploys` works too | | `stat: 99.9% uptime \| 42ms p95` | big numbers with labels, side by side | | `\| a \| b \|` | a table row; a `\|---\|` row makes the row above a header | `bars`, `spark`, `progress`, `stat` and tables come from the built-in plugins. Each takes an optional colour after its keyword. Inline markup inside a line: | markup | result | | --------------------------------- | --------------------------- | | `**bold**` | bold | | `*muted*` | muted colour | | `~~text~~` | struck through | | `` `code` `` | accent colour | | `[[chip]]` / `[[green: chip]]` | a small outlined chip | | `{red: text}` / `{#f97316: text}` | coloured text | | `{size: 18, weight: 700 \| text}` | styled text (text) | `meta` puts muted text at the top right, `caps` turns the header into small caps. With `shape: text` the card has no frame. The header and the body are styled apart. `font-size`, `font-weight` and `text` set the header label. `body-size`, `body-weight`, `body-color` and `line-height` set the body lines; inline colours still win over `body-color`. ```yuhwa theme: midnight laptop "~/shop" [frame: window your laptop, font-size: 18, body-size: 15, body-weight: 500, body-color: #e2e8f0, line-height: 1.6] { $ lf setup vps --host <server-ip> {green: ✓} docker · ufw · fail2ban · traefik $ lf deploy {green: ✓} live → https://shop.example.com } ``` ## Placement A placement prop puts one node next to another. The value is the other node's id. ```yuhwa firewall -> traefik -> app journal [below: traefik] cron [right-of: app] ``` | prop | where the node goes | | ---------- | --------------------------------------------- | | `below` | under the other node | | `above` | over the other node | | `right-of` | to the right of the other node | | `left-of` | to the left of the other node | | `rank` | in the same rank (column or row) as the other | The directions are on screen. They do not turn with `direction`. A placement draws no edge. It replaces the old trick of an invisible edge (`a -> b: [opacity: 0]`). Placement works inside groups, and across them. A node takes one placement prop. An unknown id, a group id, the node's own id and a loop of placements each give a warning with the line. Edges win over placement. When an edge runs the other way, the placement is dropped with a warning. ## Fitting a narrow column The `max-width` setting keeps a wide diagram inside a column. When the diagram is wider than the limit, its ranks wrap into rows, like words in a paragraph. Each row starts at the left. Edges to the next row run through the gap between the rows. ```yuhwa max-width: 640 commit -> lint -> test -> build -> scan -> stage -> e2e -> prod ``` A diagram that already fits does not change. A group is never split: all its ranks stay in one row. Only `direction: right` and `direction: left` wrap. A `down` or `up` diagram grows in height, so it is left as it is. A single rank or group wider than the limit stays wider. Pinned nodes (the `layout` block) turn wrapping off. ## The `layout` block The visual editor writes manual positions into a `layout` block at the end of the file. It can also be written by hand. ```yuhwa a -> b: HTTPS b -> c layout { a at 40 40 b at 260 40 size 160 64 c at 40 200 a->b label 0 -14 b->c via 340 224 ports bottom right } ``` | line | meaning | | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | | `id at X Y` | pin a node or group at this top-left position | | `id ... size W H` | fixed size | | `a->b via X Y [X Y ...]` | waypoints the edge passes through | | `a->b ... ports S S` | start and end sides: `top` `right` `bottom` `left` (`auto` to let the router pick) | | `a->b ... label DX DY` | move the label from its default place | | `a->b#2 ...` | the second edge from `a` to `b`, when there are several | | `rank a b c` | keep these nodes in the same rank (row or column) | | `panel at X Y` | pin a panel at this top-left position (panels take no `size`) | | `panel:part D` | nudge one part of a panel along the axis it moves on; the panel kind names its parts (see git) | | `panel:part DX DY` | nudge a part that moves freely in both directions | Nodes without a position are still laid out automatically around the pinned ones. Delete the block to return to full auto-layout. `rank` lines are layout hints, not positions: the nodes still get placed automatically, but share one rank. Nothing in a rank set is pinned. ## Panels, imports and exports Sequence diagrams, timelines, charts and git histories can sit next to the graph in the same file. A diagram can be split over files: ``` import "./styles.yu" // everything the file exports import { api, .svc as .service } from "./x" // only some things, renamed import { service, $brand } from "./kit" // components and variables export api, data, .svc // what importers may take export db "Orders DB" .store // export in front of a declaration export $brand: violet // ... or a variable export def service(id) { ... } // ... or a component ``` See Combining diagrams. ## Other input formats Every API and CLI command also accepts JSON and Mermaid flowcharts. See From Mermaid or JSON. For the look of each theme, see Themes and styling. # Combining diagrams One file can hold more than a flowchart. Sequence diagrams, timelines, charts, git histories and the other diagram types are **panels**: blocks that sit next to the graph and share its title, theme and footer. And a diagram can be split over files with `import`. ## Panels A panel is a block with a kind, an id, an optional title and props: ```yuhwa title: Sign in subtitle: the flow and the conversation behind it web "Web" [blue] -> api "API" [blue] -> db "Postgres" [cylinder, amber] sequence login "Sign in" [numbered] { actor user "Customer" [purple] participant web, api, db user -> web: open /login web -> api: POST /login api -> db: find user db --> api: row note api: compares the **bcrypt** hash --- session --- api --> web: 200 + cookie web -> web: store token } ``` The body belongs to the panel plugin: graph syntax does not apply inside it. The block ends at a line that is only `}`. ### Arranging `panels` sets how the graph and the panels line up. The graph comes first. `panel-gap` sets the space between them (default 48). | setting | result | | ---------------- | ------------------------------------------------- | | `panels: row` | side by side (default) | | `panels: column` | stacked | | `panels: grid` | a near-square grid | | `panels: wrap` | graph on top, panels in rows as wide as the graph | A file without nodes is fine. It is then just its panels: ```yuhwa panels: grid chart traffic "Traffic by region" [type: donut, unit: %] { EU: 46 US: 31 APAC: 23 } chart latency "Latency p95" [unit: ms] { checkout: 120 search [green]: 48 login: 80 } chart deploys "Deploys" [type: column] { Mon: 4 Tue: 7 Wed: 3 Thu: 9 Fri: 2 } chart users "Users" [type: line] { Jan: 120 Feb: 180 Mar: 160 Apr: 260 } ``` ### Connecting panels An edge may name a panel id instead of a node. It runs from or to the panel's border, like an edge between nodes: ```yuhwa api "API" [blue] api -> plan: schedules timeline plan "Plan" { 2024: beta 2025: launch } chart sales "Sales" [type: column] { Q1: 4 Q2: 7 } plan -> sales: drives sales --> api: reports ``` Panels are placed after the graph, so these edges do not move them. Set `exit` and `enter` on an edge to pick the sides it leaves and enters by. ### Panel style Every panel takes these props for its box, next to its own: | prop | result | | ---------------------- | ------------------------------------------------------------ | | `color: teal` | tints the box, the border and the title | | `theme: midnight` | draws this panel in another theme | | `background: #0f172a` | box fill (`none` for no fill) | | `border: orange` | border colour, a width (`border: 2`) or `none` | | `border-width: 2` | border width | | `border-style: dashed` | `solid`, `dashed` or `dotted` | | `radius: 4` | corner radius | | `shadow` | a drop shadow | | `frame: false` | no box at all | | `width: 480` | the smallest frame width; wider frames stretch their content | | `height: 300` | the smallest frame height | | `edge-color: slate` | colour of the panel's lines: sequence messages, Gantt arrows | | `edge-width: 2` | width of those lines | | `text: indigo` | title colour | | `font-size: 16` | base font size: the title and all text inside scale with it | | `font-weight: 800` | title weight | | `italic` | italic title | ```yuhwa panels: row chart night "Night shift" [theme: midnight, shadow] { api: 42 jobs: 18 } chart draft "Draft numbers" [background: lightyellow, border: orange, border-style: dashed, radius: 4] { api: 30 jobs: 12 } ``` Every panel takes `color` to colour its box and `frame: false` to drop it. Parts take a colour too: a timeline event (`Q2 [green]: Launch`), a chart item (`"Search" [teal]: 48`), a sequence participant, message or note, and a git branch or commit (`[pink]`). Any colour may be a palette name, `#hex`, `rgb()`, `hsl()` or a CSS name. On timeline, chart, gantt and quadrant lines the bracket may also end the line: `Q2: Launch [green]`, `"Search": 48 [teal]`. A bracket at the end of free text counts only when it is a colour, so `Q2: Launch [beta]` keeps its text. The editor keeps a colour where you wrote it. The visual editor lists every part of a selected panel with a colour picker. ### Panel kinds Each kind has its own page with its syntax, props and examples: | kind | page | | ---------- | --------------------------------- | | `sequence` | Sequence | | `timeline` | Timeline | | `chart` | Chart | | `git` | Git | | `mindmap` | Mind map | | `treeview` | Tree view | | `gantt` | Gantt | | `quadrant` | Quadrant | | `kanban` | Kanban | ## Imports `import` pulls another file into this one: its classes, nodes, groups, edges, and panels. Settings such as `theme:` stay in their own file unless the file exports them, see settings across files. ```yuhwa // shared/services.yu .svc [blue] .store [amber, cylinder] web "Web" .svc sub: Next.js api "API" .svc db "Postgres" .store ``` ```yuhwa import "./shared/services.yu" title: Checkout direction: right api [purple] // restyle an imported node web -> api api -> db: SQL ``` - The importing file wins: its settings, class props and node props override the imported ones. - Paths are relative to the importing file. Imports may import other files. A file imported twice is merged once; a cycle is an error. - An imported file's `layout { }` block is ignored; its `rank` lines are kept. - Errors inside an imported file are reported on the `import` line, with the file and line. Where the files come from depends on where you render: | where | how | | ---------------------------- | ---------------------------------------------------------------------------------- | | CLI, `yuhwa md` | from disk, relative to the input file | | VitePress fence (these docs) | from disk at build time | | `<yuhwa-diagram src="...">` | fetched next to the `src` file before rendering (embedding) | | visual editor | from the editor's other file tabs (editor) | | JavaScript | pass `resolve` and `file`, see the API | ### Exports and selective imports A file can say what it offers with `export`. Without any `export` line, everything is importable. ```yuhwa // shared/styles.yu .svc [blue] .store [amber, cylinder] .internal [red] // private: not in the export list export .svc, .store ``` ```yuhwa // services.yu export orders, payments // a list, anywhere in the file export search "Search" .svc // or in front of a declaration group orders "Orders" { orders-api "Orders API" .svc orders-db .store } payments "Payments" .svc ``` For a large deck, keep one kit file with the shared look and building blocks: ```yuhwa // kit.yu export $brand: violet export .svc [color: $brand, rounded] export .store [amber, cylinder] export def service(id, label) { $id "$label" .svc ${id}_db .store $id -> ${id}_db } ``` ```yuhwa // checkout.yu import "./kit.yu" title: Checkout service(cart, "Cart") service(orders, "Orders") cart -> orders ``` An importer takes everything that is exported, or names what it wants: ```yuhwa import "./shared/styles.yu" // .svc and .store import { orders, payments as billing } from "./services.yu" import { .svc as .service } from "./shared/styles.yu" ``` - Classes carry their leading dot: `.svc`. Variables carry their `$`: `$brand`. Panels are picked by id, components by name. - A component brings the classes its body names and can still call the components of its own file. - Picking a group brings its members. An edge comes along when both of its ends are picked. Classes come along when something picked uses them. - `as` renames a node, group, panel, class, variable or component. Edges follow the new name. - Naming something that is not exported is an error that lists the exports. `export` of a name the file does not declare gives a warning. - `import` and `export` are top-level only. ### Settings across files Settings (`theme`, `direction`, `title`, `curve`, ...) belong to the file that writes them. Importing a file takes its nodes and classes, never its `title:` or `theme:`. So every file can have its own theme, and it shows when that file is rendered on its own. To share a setting, export it: ```yuhwa // kit.yu export theme: midnight export curve: orthogonal export .svc [blue, rounded] ``` ```yuhwa // checkout.yu import "./kit.yu" // takes theme: midnight and curve: orthogonal title: Checkout api "API" .svc -> db ``` ```yuhwa // admin.yu import "./kit.yu" theme: paper // its own setting wins over the import ``` - A plain `import` takes every exported setting. A selective import takes the ones it names: `import { theme, .svc } from "./kit.yu"`. A setting keeps its name, so `as` is an error. - The importing file's own setting always wins. - An exported setting does not close the file: without other `export` lines, its nodes and classes stay importable. - Exported settings do not pass through. If `admin.yu` imports the kit, a file importing `admin.yu` does not get the kit's theme. Import the kit there too. - One global theme for a project: put `export theme: ...` in a kit file and import it everywhere. A host theme (`--theme`, the `theme` option) still overrides all of them. ### Mixing kinds Imports and panels combine. Keep the architecture in one file, then build a release page from it: the graph, the branch history and the numbers. ```yuhwa // release.yu import "./shared/services.yu" title: Release 2.0 panels: grid web -> api api -> db: SQL git branches "Branches" { commit "v1" [tag: v1.0] branch checkout-v2 commit "new cart" checkout main merge checkout-v2 [tag: v2.0] } chart errors "Errors after deploy" [type: line] { Mon: 12 Tue: 4 Wed: 2 } ``` # Flowchart The graph is the heart of yuhwa: nodes, edges between them and groups around them. The layout is automatic, so you write what is connected and yuhwa decides where it goes. ```yuhwa direction: down start "Start" [pill, green] -> form "Fill in form" -> valid "Valid?" [diamond, amber] valid -> save "Save order": yes valid -> form: no [dashed, constraint: false] save -> mail "Send receipt" [document] -> done "Done" [pill, green] ``` This page is a tour with examples. Syntax is the full reference for nodes, edges, groups, classes and every prop. ## Nodes and edges A node is an id with an optional label and props. An edge is two ids and an arrow. Using an id in an edge creates the node, so the shortest diagram is one line: ```yuhwa web -> api -> db ``` Labels go in quotes, edge labels after a colon, props in brackets: ```yuhwa web "Storefront" [blue] -> api "Orders API" [blue]: place order api -> db "Postgres" [cylinder, amber]: SQL api -> cache "Redis" [cylinder]: read-through [dashed] ``` ## Direction `direction` sets where the graph grows: `right` (default), `down`, `left` or `up`. Mermaid's `LR`, `TB`, `TD`, `RL` and `BT` work too. ```yuhwa direction: down idea "Idea" -> spec "Spec" -> build "Build" -> ship "Ship" [green] ``` ## Shapes A shape name works as a flag: `[diamond]` is short for `[shape: diamond]`. `shape:` as a setting changes the default for every node. ```yuhwa rounded "rounded" -- box "box" [box] -- pill "pill" [pill] -- circle "circle" [circle] ellipse "ellipse" [ellipse] -- diamond "diamond" [diamond] -- hexagon "hexagon" [hexagon] -- cylinder "cylinder" [cylinder] para "parallelogram" [parallelogram] -- document "document" [document] -- note "note" [note] -- text "text" [text] ``` Aliases cover the names other tools use: `rect`, `stadium`, `decision`, `database`, `io`, `sticky` and more. ## Arrows | arrow | line | heads | | ---------- | ------ | ------------ | | `->` | solid | at the end | | `-->` | dashed | at the end | | `..>` | dotted | at the end | | `=>` `==>` | thick | at the end | | `<->` | solid | at both ends | | `--` `-` | solid | none | ```yuhwa a "A" -> b "B": calls a --> c "C": replies a ..> d "D": async a => e "E": hot path a <-> f "F": sync a -- g "G": linked b -> h "H": events [flow] c -> h: [head: diamond, tail: dot] ``` `flow` animates the dashes. `head` and `tail` take `arrow`, `open`, `dot`, `diamond`, `bar` or `none`. ## Groups A group draws a box around its nodes. Groups nest. ```yuhwa title: Shop direction: right user "Customer" [circle, purple] group edge "Edge" [dashed] { cdn "CDN" } group app "App" [blue] { web "Web" api "API" worker "Worker" } group data "Data" [amber] { db "Postgres" [cylinder] queue "Queue" [pill] } user -> cdn -> web -> api api -> db: SQL api -> queue: publish queue -> worker: consume [flow] worker -> db ``` ## Cards and frames A node with a `{ }` body is a card: a header and monospace lines with dividers, aligned columns, tables, bars and sparklines. `frame` draws browser, window or terminal chrome around it. See cards for every body line. ```yuhwa theme: dusk shop "Shop" [frame: browser shop.example.com] { **Cart** || 3 items --- progress: 2/3 checkout spark: 3 5 4 8 7 9 } cli "Deploy" [frame: terminal ~/shop] { yuhwa render shop.yu `✓ shop.svg` } shop -> cli: [dashed] ``` ## Examples ### State machine States as pills, transitions as labelled edges. `constraint: false` keeps a backwards edge from pulling the layout apart. ```yuhwa title: Order states new "New" [pill] -> paid "Paid" [pill]: pay paid -> shipped "Shipped" [pill]: ship shipped -> done "Delivered" [pill, green]: deliver new, paid -> cancelled "Cancelled" [pill, red]: cancel [dashed] shipped -> paid: return [dotted, constraint: false] ``` ### Decision tree ```yuhwa direction: down theme: pastel q1 "Is it broken?" [diamond] -> q2 "Did you touch it?" [diamond]: yes q1 -> ok "Leave it" [pill, green]: no q2 -> fix "Fix it" [pill, amber]: yes q2 -> log "Read the logs" [pill, blue]: no ``` ### Data model Cards with tables work as entity boxes; edge heads mark the cardinality. ```yuhwa direction: right user "users" [caps] { | id | uuid | | email | text | } order "orders" [caps] { | id | uuid | | user_id | uuid | | total | numeric | } user -> order: 1..n [head: open, tail: bar] ``` ### Annotated pipeline A note joins the pipeline with a dotted, unconstrained edge, so it sits next to the step it explains. ```yuhwa theme: mono curve: straight a "Input" -> b "Parse" -> c "Layout" -> d "Render" -> e "SVG" [document] note "same input,\nsame SVG" [note] d -- note: [dotted, constraint: false] ``` More in the examples: web apps, deploys, team ownership and status boards. # Sequence A sequence diagram shows who talks to whom, in what order: one lifeline per participant, one arrow per message, top to bottom. ```yuhwa sequence login "Sign in" [numbered] { actor user "Customer" [purple] participant web, api, db user -> web: open /login web -> api: POST /login api -> db: find user db --> api: row note api: compares the **bcrypt** hash --- session --- api --> web: 200 + cookie web -> web: store token } ``` ## Syntax ```yuhwa sequence id "Title" [numbered] { participant api "API" [blue] // declare to set label, colour or order actor user "Customer" // rounded, for people participant web, db // order only user -> web: message // solid web --> user: reply // dashed web ..> db: async // dotted web => api: important // thick api -> db: write [amber] // a colour tints one message db --> api: rows [width: 2, head: open] // edge props style one message api -> api: self call note api: text over one participant note web, db: text across several --- section --- } ``` Participants appear in order of first use unless declared. `numbered` puts a number in front of every message. A colour in brackets at the end of a message or note colours it: `a -> b: retry [red]`, `note api: slow [amber]`, or `a -> b: [red]` without text. Messages take the edge props `width`, `style: solid | dashed | dotted` (or `dashed`, `dotted`), `thick` and `head: arrow | open | none` next to the colour: `a -> b: audit [red, dotted, head: open]`. Message text takes the inline markup: `**bold**`, `*muted*`, `` `code` `` and style spans like `{red, bold | text}` (text). The header styles the lifelines: `lifeline: <colour>` and `lifeline-style: dashed | dotted | solid` (`dashed` by default). `edge-color` and `edge-width` set the ink of every message. To make room, nudge a part in the `layout` block or drag its handle in the visual editor. A participant name widens the gap to its left; `m3`, `note1` and `d1` (the third message, first note, first `---` divider) add space above that row: ```yuhwa layout { login:api 40 login:m3 24 } ``` ## Examples ### OAuth sign-in ```yuhwa theme: pastel sequence oauth "Sign in with GitHub" [numbered] { actor user "User" [purple] participant app "App" participant gh "GitHub" [slate] user -> app: click sign in app --> user: redirect to GitHub user -> gh: authorize the app gh --> app: callback with a code app -> gh: exchange the code gh --> app: access token note app: stores the token **encrypted** --- later --- app -> gh: GET /user [blue] gh --> app: profile } ``` ### Background job Dotted lifelines, async messages and a self call. ```yuhwa theme: midnight sequence job "Resize an upload" [lifeline-style: dotted] { participant api "API" [blue] participant q "Queue" [amber] participant w "Worker" [green] api ..> q: enqueue resize q ..> w: deliver w -> w: resize to 3 sizes w -> api: done [dotted, head: open] w => q: ack note q, w: retried 3 times on failure [amber] } ``` ### Next to the architecture The graph shows the parts, the panel the conversation between them: ```yuhwa title: Checkout web "Web" [blue] -> api "API" [blue] -> psp "Payments" [green] sequence pay "Pay" { participant web, api, psp web -> api: POST /checkout api -> psp: charge 49 € psp --> api: ok api --> web: receipt } ``` # Timeline A timeline puts events on a line: quarters on a roadmap, versions in a release history, the hours of an incident. ```yuhwa theme: midnight panels: column timeline roadmap "Roadmap" { 2025 Q1: Private beta - 40 design partners 2025 Q2 [green]: **Launch** - public docs - pricing 2025 Q4 [amber]: EU region } timeline day "Release day" [direction: down] { 09:00: freeze 12:30 [red]: deploy - canary 5% 15:00 [green]: done } ``` Each event is `when [color]: title`, with `- detail` lines below. The colon needs a space after it, so times like `12:30` work. `direction: down` runs top to bottom (`vertical` is the old spelling). Nudge an event to add space before it: `roadmap:Q2 40` names the event by its `when` when that is one unique word, else by position (`e3` is the third). ## Examples ### Release history ```yuhwa timeline history "Releases" { 0.1: First render - nodes, edges, themes 0.5 [blue]: Panels - sequence, timeline, chart 0.9 [teal]: Visual editor 1.0 [green]: **Stable** - language server - VS Code extension } ``` ### Incident A vertical timeline reads like a log. ```yuhwa theme: terminal timeline outage "Checkout outage" [direction: down] { 14:02 [red]: alerts fire - error rate 12% 14:09: on-call joins 14:21 [amber]: bad deploy found - rollback started 14:30 [green]: recovered 16:00: postmortem scheduled } ``` ### Two timelines `panels: column` stacks them. ```yuhwa title: Search launch panels: column timeline q "2026" { Q1: Discovery Q2 [blue]: Beta Q3 [green]: **GA** Q4 [amber]: Personalisation } timeline day "Launch day" { 08:00: freeze 10:00 [blue]: deploy - canary 5% 12:00 [green]: 100% 16:00: retro } ``` # Chart Bar, column, line, pie and donut charts from a list of numbers. ```yuhwa chart latency "Latency p95" [unit: ms] { checkout: 120 search [green]: 48 login: 80 } ``` ## Syntax Each line is `label [color]: number`. | prop | values | | ------ | ------------------------------------------------- | | `type` | `bar` (default), `column`, `line`, `pie`, `donut` | | `unit` | appended to every value, e.g. `ms` or `%` | Bars, columns and lines use the theme accent unless a line sets a colour. Pie and donut slices cycle through the palette. For small charts inside a node, use the card rows `bars`, `spark` and `progress` instead. A chart has one handle, `size`, at its bottom-right corner. `stats:size 80 40` makes the plot 80 wider and 40 taller. ## Every type ```yuhwa panels: grid chart bar "bar" [type: bar] { EU: 46 US: 31 APAC: 23 } chart column "column" [type: column] { Mon: 4 Tue: 7 Wed: 3 Thu: 9 Fri: 2 } chart line "line" [type: line] { Jan: 120 Feb: 180 Mar: 160 Apr: 260 } chart pie "pie" [type: pie, unit: %] { Chrome: 64 Safari: 19 Firefox: 9 Other: 8 } chart donut "donut" [type: donut, unit: %] { TypeScript: 64 Rust: 21 CSS: 15 } ``` ## Examples ### Colours per item ```yuhwa chart budget "Cloud spend" [type: column, unit: k€] { compute: 42 storage [teal]: 18 network: 9 "data transfer" [red]: 27 } ``` ### Numbers next to the system ```yuhwa title: Search direction: right web "Web" [blue] -> search "Search API" [blue] -> idx "Index" [cylinder, amber] chart qps "Queries per second" [type: line] { Mon: 820 Tue: 940 Wed: 1100 Thu: 1040 Fri: 1310 } ``` ### A dark dashboard ```yuhwa theme: midnight panels: row chart uptime "Uptime" [type: donut, unit: %] { up [green]: 99.9 down [red]: 0.1 } chart errors "Errors by service" { api [red]: 14 jobs [amber]: 6 web: 2 } ``` # Git A branch history, drawn the way people sketch it on a whiteboard: one lane per branch, tags above the commits, merges as filled dots. ```yuhwa git flow "Release flow" { commit "init" [tag: v0.1.0] branch feature/login commit "login form" commit "oauth" checkout main commit "fix typo" branch fix/cache [amber] commit "cache headers" checkout main merge fix/cache [tag: v0.1.1] merge feature/login [tag: v0.2.0] } ``` | line | meaning | | ------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `commit ["message"] [props]` | a commit on the current branch | | `branch name [from X] [props]` | create a branch and switch to it; `X` is a branch, a commit id or a tag (default: the current commit) | | `checkout -b name` / `switch -c name` | the same as `branch name` | | `checkout name` / `switch name` | switch to an existing branch | | `merge name ["message"] [props]` | a merge commit with two parents; the message defaults to `Merge name` | | `cherry-pick X ["message"] [props]` | copy commit `X` (id, tag or branch head) onto the current branch | | `tag v1` | tag the current commit | Commit and merge props: | prop | result | | --------------------------------- | --------------------------------------------------------------------------- | | `tag: v1` | a tag pill above the commit | | `id: a1b2c3` | names the commit for `from` and `cherry-pick`; shown with `direction: down` | | `type: highlight` / `[highlight]` | a filled square, for the commit that matters | | `type: reverse` / `[reverse]` | a crossed circle, for a revert | | a colour, like `[red]` | colour of this commit | Branch props: a colour, `label: "1.x"` (shown instead of the name) and `order: 2` (moves the lane; lanes otherwise follow creation order). A cherry-picked commit is drawn as a dashed circle, with a dashed line back to the original. Picking a commit onto the branch it is already on gives a warning, as does a commit id used twice. History starts on `main`. ```yuhwa git hotfix "Hotfix on a release branch" { commit "v1.0" [tag: v1.0] commit "new api" checkout -b feature/search commit "search ui" checkout main commit "fix auth" [id: fix, highlight, tag: v1.1] merge feature/search [tag: v1.2] branch release/1.0 from v1.0 [label: "1.0.x", amber] cherry-pick fix [tag: v1.0.1] } ``` | header prop | result | | ------------------ | ------------------------------------------------------------------------------------------------------- | | `main: trunk` | name of the first branch | | `direction: down` | top to bottom like `git log --graph`, with branch names at their heads (`vertical` is the old spelling) | | `direction: right` | left to right (default) | ```yuhwa theme: midnight git log "git log --graph" [direction: down, main: trunk] { commit "initial import" [id: 1a2b3c] branch api commit "add /orders" [id: 4d5e6f] checkout trunk commit "ci: cache deps" [id: 7a8b9c] checkout api commit "validate body" [id: 0d1e2f] checkout trunk merge api [id: 3a4b5c, tag: v2.0] } ``` ## Adjusting the layout When a line lands in the wrong place, move it. Select the panel in the visual editor and drag its handles, or write the offsets into the `layout` block by hand. Each line nudges one part of the history by a distance along the axis that part moves on, so a nudge keeps its meaning when you switch `direction`. Positive moves right on the time axis (down with `direction: down`) and away from `main` across it: | part | what moves | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `feat` | the lane of branch `feat`, and every lane after it | | `v1.0`, `fix`, `c3` | one commit, and every commit after it, along the time axis; named by `id`, else its first tag, else its position (`c1` is the first). A branch name wins: a commit with the same id or tag falls back to its position | | `c5^1` | the bend into commit `c5` from its parent on another lane (where a branch starts), along the time axis | | `c5^2` | the bend into merge `c5` from the merged branch | | `c5^pick` | the dashed cherry-pick line to `c5`, in both directions: two numbers, `DX DY` | ```yuhwa git flow "Release flow" { commit "init" [tag: v0.1.0] branch feature/login commit "login form" checkout main commit "fix typo" merge feature/login [tag: v0.2.0] } layout { flow at 0 0 flow:feature/login 24 flow:c3 36 flow:v0.2.0^2 -24 } ``` `flow at X Y` pins the whole panel, like a node. A panel takes no `size`: its content decides that. Older files may write `flow:c3 offset 36`; the word `offset` is optional. Delete the lines to go back to the automatic drawing. ## Examples ### Git flow A `develop` branch, a feature branch and a release branch merged both ways. ```yuhwa git gitflow "Git flow" { commit "1.0" [tag: v1.0] branch develop [blue] commit "start 1.1" branch feature/cart [green] commit "cart" commit "tests" checkout develop merge feature/cart branch release/1.1 [amber] commit "bump version" checkout main merge release/1.1 [tag: v1.1] checkout develop merge release/1.1 } ``` ### Trunk-based Short branches, merged the same day. ```yuhwa theme: pastel git trunk "Trunk-based" [main: trunk] { commit branch a [purple] commit "flag off" checkout trunk merge a branch b [teal] commit "small fix" checkout trunk merge b commit [tag: deploy-42] } ``` ### git log ```yuhwa theme: terminal git log "git log --graph --oneline" [direction: down] { commit "initial import" [id: 9fceb02] branch release/2.0 commit "bump version" [id: 3a1e5d7] checkout main commit "add payments" [id: b7c41f0] commit "fix flaky test" [id: 0e8d2a9] checkout release/2.0 commit "changelog" [id: 6d2f3b1, tag: v2.0.0] checkout main merge release/2.0 [id: c4a9e12] } ``` # Mind map A mind map grows an outline into branches: ideas, notes from a meeting, a team's structure. ```yuhwa mindmap ideas "Launch plan" [layout: both] { **Launch** Marketing [pink] Blog posts Newsletter Product Beta [#16a34a] - Pricing page Sales [shape: pill] } ``` Indentation is the tree: the first line is the root, each deeper line a child of the last shallower one. `- ` and `* ` bullets are optional, so a Markdown outline pastes as is. A trailing colour tints a node and its subtree; branches without one take the next palette colour. `[shape: box | pill | plain | circle]` changes one node's look. | node prop | result | | ------------- | ------------------------------------ | | `text` | text colour of this node | | `font-size` | font size of this node, px | | `font-weight` | font weight of this node, e.g. `300` | Props combine in one bracket: `Beta [green, text: white, font-size: 18]`. A bracket with any other key, or a value that does not fit, stays part of the text. | header prop | result | | ------------------------ | ----------------------------------------------------------------------------------------- | | `layout: both` | branches left and right of the root (default) | | `layout: vertical` | branches above and below the root | | `layout: right` / `left` | all branches on one side | | `layout: down` / `up` | an org-chart style tree, growing down or up | | `colors: mono` | no automatic branch colours | | `font-size: 16` | first-level size; root 1.2×, deeper 0.92× (panel style) | ## Examples ### Org chart `layout: down` draws a tree from the top. ```yuhwa mindmap org "Engineering" [layout: down] { CTO Platform [blue] Infra Tooling Product [green] Web Mobile Data [amber] Analytics } ``` ### Above and below `layout: vertical` is `both` turned upright: the first branches go above the root, the rest below, so a wide map fits a narrow page. ```yuhwa mindmap trip "Trip" [layout: vertical] { **Japan trip** Before Visa Rail pass Tokyo Shibuya Asakusa Kyoto Temples After Photos } ``` ### A pasted outline Markdown bullets paste as they are. `colors: mono` keeps it quiet. ```yuhwa mindmap retro "Retro" [layout: right, colors: mono] { - Sprint 12 - Went well - faster deploys - pairing on the API - To improve - flaky tests - on-call handover - Actions - quarantine flaky tests [red] } ``` ### Text ```yuhwa mindmap talk "Talk" [layout: right, font-size: 16] { **Keynote** [font-size: 26] Opening [text: #7c3aed, font-weight: 700] a story Demo *live coding* [font-size: 12] Q&A [font-weight: 300] } ``` ### Shapes ```yuhwa theme: dusk mindmap stack "Stack" { **App** [shape: circle] Frontend [shape: pill] Vue Vite Backend [shape: pill] Node Postgres Ops [shape: plain] Docker Fly.io } ``` # Tree view A tree view draws a file tree: folders and files with icons, notes, badges and git status. Paste the output of `tree` or write the indentation yourself. ```yuhwa treeview files "my-app" [sort: folders, chevrons] { src/ index.ts: entry point components/ [collapsed] Button.tsx routes/ [id]/ page.tsx [added] util.ts [modified] legacy.js [deleted] package.json README.md [highlight] diagram.yu # the source } ``` Indentation is the tree, and there may be several top-level entries. `- ` bullets are optional, and so are the `├──`, `│` and `|--` prefixes the `tree` command prints, so its output pastes as is (the `N directories, M files` line is skipped). An entry is a folder when it has children, ends in `/` or says `[folder]`, and a `...` entry stands for "more files". Files get an icon and a colour from their name: code, tests, scripts, documents, images, fonts, media, config, lockfiles, packages, git files and databases. Folders such as `node_modules/`, `dist/` and `.git/` get a grey one. `name: note` or `name # note` adds a note. The props go at the end of the line, after a space, so a folder named `[id]` stays a name: | entry prop | result | | ---------------------------------------------------- | ----------------------------------------------------------- | | a colour | tints the icon and the name | | `icon: folder \| code \| doc \| image \| …` | another icon; any other text, like an emoji, is drawn as is | | `badge: text` | a pill after the name | | `note: text` | a note, like `: text` | | `size: text` | a right-aligned column, like `4 KB` or `12 lines` | | `collapsed` | a closed folder: its children are hidden | | `highlight` | a band behind the row | | `dim` | a faded row | | `folder` / `file` | forces the entry's type | | `added`, `modified`, `deleted`, `renamed`, `ignored` | git status: colours the name and adds a letter on the right | The icon names are `folder`, `folder-open`, `file`, `code`, `doc`, `image`, `config`, `lock`, `package`, `git`, `database`, `test`, `font`, `media`, `terminal` and `yuhwa`. ### Rules `match <glob> [props]` gives every entry the glob matches the same props, so a tree can say once that tests are faded or that a folder starts closed. A rule may go anywhere in the body; the entry's own props win over a rule's. | glob | matches | | ------------- | ------------------------------------------------ | | `*.test.ts` | names; `*` and `?` never cross a `/` | | `src/**/*.ts` | paths, when the glob has a `/`; `**` crosses `/` | | `*.{ts,tsx}` | either ending | | `docs/` | folders only, when the glob ends in `/` | A rule that matches nothing gets a warning. | header prop | result | | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `icons: color \| mono \| emoji \| none` | coloured icons (default), grey ones, emoji, none | | `lines: solid \| rounded \| dashed \| dotted \| none` | the guide lines; `rounded` curves the corner to the last child | | `sort: none \| name \| folders` | as written (default), by name, folders first | | `notes: column \| inline` | notes in one aligned column (default) or after each name | | `chevrons` | a `›` before every folder | | `rows: striped` | every other row shaded | | `spacing: compact \| normal \| relaxed` | row height (not the same as `compact`) | | `slashes: true \| false` | add or remove the `/` after folder names | | `compact` | a folder whose only child is a folder shares its row: `a/b/c/`; a folder with a note, badge, status or other prop stays on its own | | `counts: collapsed \| all \| none` | how many entries a folder holds: closed ones (default) | | `marks: letter \| dot \| none` | the git status column on the right, set by `added`, `modified`, … : letters `M`, `A`, `D`, `R` (default), dots, or none | | `rollup: false` | no dot on folders that hold changed files | | `depth: 2` | show only the first levels; deeper folders show closed | | `indent: 24` | the width of one level | | `folder-color: teal` | the folder icons (default amber) | | `line-color`, `note-color` | the guide lines, the notes | | `highlight-color`, `badge-color` | the default `highlight` band and badge pill | | `strike-width: 2`, `strike-color: red` | the line through `deleted` entries | The panel props work as on every panel: `radius`, `shadow`, `border`, `background` and `frame: false` style the frame. `edge-color` and `edge-width` draw the guide lines (`line-color` wins over `edge-color`), and `radius` also rounds the `highlight` band. `width` makes the frame at least that wide; the notes, sizes and marks then line up at its right edge. ## Examples ### Rules, counts and sizes ```yuhwa treeview web "acme-web" [sort: folders, chevrons, compact, folder-color: teal] { match *.test.ts [dim] match docs/ [collapsed] src/ main/ java/ App.java: entry point components/ Button.tsx [added, size: 2.1 KB] Button.test.ts [size: 1.4 KB] Card.tsx [modified, size: 3.8 KB] ... docs/ intro.md guide.md scripts/ deploy.sh package.json } ``` Folders that hold changed files get a dot in the status column; closed folders show how many entries they hide. ### Rounded lines and a styled frame ```yuhwa treeview src "src" [lines: rounded, compact, edge-color: teal, edge-width: 2, radius: 16, shadow] { main/ java/ com/ acme/ App.java [highlight] Router.java test/ java/ AppTest.java } ``` `compact` puts `main/java/com/acme/` and `test/java/` on one row each. ### Pasted `tree` output The drawing characters and the summary line are skipped. ```yuhwa treeview out "tree" { . ├── src │ ├── main.go │ └── handler.go ├── go.mod └── README.md 1 directory, 4 files } ``` ### A pull request Statuses colour the names and add a letter on the right. ```yuhwa treeview pr "feat: dark mode" [sort: folders] { src/ theme/ dark.ts [added] tokens.ts [modified] old-colors.ts [deleted] App.tsx [modified] .env [ignored] CHANGELOG.md [modified] } ``` ### A monorepo, explained Notes line up in one column; badges mark what matters. ```yuhwa treeview repo "acme" [chevrons, rows: striped] { apps/ web/: the Next.js site admin/: internal tools [badge: beta] packages/ ui/: shared components config/: lint and tsconfig presets docs/ [collapsed] intro.md pnpm-workspace.yaml turbo.json: build pipeline } ``` ### Plain No icons, dashed lines, compact rows. ```yuhwa theme: mono treeview plain "layout" [icons: none, lines: dashed, spacing: compact] { content/ posts/ hello.md about.md layouts/ base.html config.toml } ``` ### Emoji and your own icons ```yuhwa treeview fun "assets" [icons: emoji] { images/ logo.svg hero.png fonts/ [icon: 🔤] Inter.woff2 notes.txt [icon: 📝] } ``` # Gantt A Gantt chart lays a plan out over time: tasks with dates or dependencies, sections, milestones and a line for today. ```yuhwa gantt plan "Q1 plan" [today: 2025-01-20] { --- Design --- research "User research": 2025-01-06, 5d wireframes [blue, done]: after research, 4d review [milestone]: after wireframes --- Build --- api "Build API" [green, active]: 2025-01-15, 2w ui [crit]: after wireframes api, 10d launch [milestone]: 2025-02-14 } ``` A task is `id "Label" [props]: start, length`, or with the props at the end, `id "Label": start, length [props]`. The start is a date (`2025-01-06`, `2025-01-06 14:00`) or `after a b`, the latest end of those tasks. Leave it out and the task starts where the one above ends. The length is `3h`, `5d`, `2w` or an end date. Dependency arrows are drawn for you, and a cycle or an unknown task gets a warning instead of a wrong chart. | task prop | result | | ------------------------ | --------------------------- | | a colour, like `[green]` | bar colour | | `done` | muted bar and a ✓ | | `active` | the open work is striped | | `crit` | red outline | | `milestone` | a diamond, no length | | `progress: 60%` | fills that share of the bar | | `owner: ana` | a note after the bar | `--- Section ---` (or `section Name`) starts a group of rows, with a summary bar over its tasks. `--- Build [teal] ---` colours the section and every task in it that has no colour of its own. | header prop | values | | ----------- | ------------------------------------------------------------- | | `today` | a date or `now`: a marker line with a tag | | `scale` | `day`, `week` or `month` (default: fits the range) | | `bars` | `soft` (default), `solid`, `outline` or `thin` | | `labels` | `left` (a label column, default) or `bar` (names on the bars) | | `notes` | `length` (default), `dates` or `none`: what a bar says | | `density` | `compact`, `normal` or `loose` row height | | `arrows` | `elbow` (default), `curved` or `hide` | | `rows` | `striped` (default) or `plain` | | `grid` | `show` (default) or `none`: the tick lines | | `summary` | `show` (default) or `hide`: the section bars | | `weekends` | `show` shades Saturdays and Sundays | Elbow arrows run along the gap between rows, so they never cross a label. A label that does not fit on its bar goes after it. ```yuhwa gantt release "Release 2.0" [today: 2025-01-20, bars: solid, labels: bar, notes: dates, density: compact] { --- Design [violet] --- research "User research" [progress: 100%]: 2025-01-06, 5d wireframes [done]: after research, 4d --- Build [teal] --- api "Build API" [active, progress: 60%, owner: ana]: 2025-01-15, 2w ui "UI" [crit]: after wireframes api, 10d launch [milestone]: after ui } ``` ## Examples ### A sprint by day ```yuhwa gantt sprint "Sprint 12" [scale: day, weekends: show, today: 2025-03-12] { --- Backend [blue] --- schema "Schema": 2025-03-10, 2d api "Endpoints": after schema, 3d --- Frontend [pink] --- ui "Screens": 2025-03-11, 4d e2e "E2E tests" [crit]: after api ui, 2d demo [milestone]: after e2e } ``` ### A quarter by month ```yuhwa theme: midnight gantt q2 "Q2" [scale: month, bars: outline, arrows: curved] { research "Research" [done]: 2025-04-01, 3w design "Design": after research, 4w build "Build" [active, progress: 30%]: after design, 6w launch [milestone]: after build } ``` # Quadrant A quadrant chart places items on two axes and splits the plane into four named fields: effort against value, risk against impact. ```yuhwa quadrant prio "Priorities" { x-axis Low effort -> High effort y-axis Low value -> High value q1 [green]: Quick wins q2: Big bets q3: Fill-ins q4 [red]: Money pit Search [teal]: 0.25, 0.8 Billing: 0.7, 0.65 Exports: 0.3, 0.3 } ``` `q1` is top right, `q2` top left, `q3` bottom left and `q4` bottom right, as in Mermaid. A point is `Name [color]: x, y` with values from 0 to 1, or 0 to 100 when any value is above 1. Labels move aside so they never overlap the points or each other. ## Examples ### Tech radar Values from 0 to 100 work too. ```yuhwa theme: dusk quadrant radar "Tech radar" { x-axis Less mature -> More mature y-axis Low impact -> High impact q1 [green]: Adopt q2 [blue]: Trial q3: Hold q4 [amber]: Assess Postgres: 90, 85 Bun: 45, 60 Kubernetes: 80, 35 HTMX: 30, 25 } ``` ### Risks ```yuhwa quadrant risks "Risks" { x-axis Unlikely -> Likely y-axis Minor -> Severe q1 [red]: Act now q2 [amber]: Plan for it q3: Accept q4: Watch "Data loss" [red]: 0.2, 0.9 "Vendor outage": 0.6, 0.7 "Slow builds": 0.85, 0.2 } ``` # Kanban A kanban board: columns, cards with owners and tickets, and WIP limits. ```yuhwa kanban sprint "Sprint 12" { Todo [gray] - Write docs [owner: ana, priority: high] - **Fix** login [red] Doing [blue, limit: 2] - API v2 [ticket: MER-12] needs the new auth flow Done [green] - Ship 1.0 } ``` A line at the outer indent starts a column, `- text` adds a card and deeper lines are the card's details. Card props: a colour, `owner`, `ticket`, `priority: low | medium | high`; any other `key: value` shows as a chip. `limit: n` on a column is its WIP limit: the count turns red above it. In the visual editor, select the board to edit it: open a column or a card in the Parts list to set its colour, text, WIP limit, owner, ticket or priority, move a card to another column, reorder with ↑ ↓, remove it with ✕, or add cards and columns. ## Examples ### Bug triage ```yuhwa theme: pastel kanban bugs "Bug triage" { New [gray] - Login loops on Safari [priority: high] - Typo in footer [priority: low] Investigating [amber, limit: 2] - Slow search [owner: kai, ticket: BUG-88] p95 up 40% since Monday Fixed [green] - CSV export encoding [owner: ana] } ``` ### Next to the plan ```yuhwa title: Launch panels: row kanban board "This week" { Doing [blue] - Pricing page [owner: ana] Done [green] - Docs } timeline plan "Plan" { Mon: Freeze Wed [blue]: Launch Fri [green]: Retro } ``` # Themes and styling ## Themes Pick a theme with the `theme:` setting or `--theme` on the command line. The command line wins. In the browser, `theme: auto` (or no theme) follows the reader's colour scheme: `paper` in light mode, `midnight` in dark mode. yuhwa ships twelve themes, shown below. You can also define your own. A theme belongs to the file that sets it: importing a file does not take its theme. For one theme across many files, put `export theme: midnight` in a shared kit file and import that. See settings across files. ### paper The default. Warm off-white with soft tones. ```yuhwa theme: paper .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### midnight Dark, close to GitHub's dark mode. ```yuhwa theme: midnight .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### blueprint White lines on blueprint blue, monospace text, a grid. ```yuhwa theme: blueprint .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### mono Black and white. Good for print and for slides with their own colours. ```yuhwa theme: mono .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### pastel Soft fills, borderless boxes, round corners. ```yuhwa theme: pastel .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### sepia Warm paper and a serif face, like a printed book. ```yuhwa theme: sepia .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### frost Cool blue-grey and flat boxes with no shadow. ```yuhwa theme: frost .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### contrast Black on white with heavier lines. Easy to read on a projector or in print. ```yuhwa theme: contrast .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### ocean Dark navy with cyan lines. ```yuhwa theme: ocean .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### ember Warm charcoal with orange lines. ```yuhwa theme: ember .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### dusk Deep violet with pink lines. ```yuhwa theme: dusk .svc [blue] user "User" [circle, purple] -> api "API" .svc -> db "Postgres" [cylinder, amber] api -> queue "Events" [hexagon, pink]: [flow] ``` ### terminal Monospace on near-black with violet edges. Made for cards and infographics. ```yuhwa title: >landfall subtitle: bare server to HTTPS in two commands theme: terminal direction: right rank-gap: 120 laptop "~/shop" [meta: your laptop] { $ `lf setup vps --host <server-ip>` {green: ✓} docker · ufw · fail2ban · traefik $ `lf server domain vps example.com` {green: ✓} new sites get *<site>.example.com* $ `lf deploy` *→ compose.yaml: web, db* {green: ✓} built web · health check passed {green: ✓} live → **https://shop.example.com** } group vps "vps" [caps] { meta: Ubuntu 24.04 · no agent installed traefik "Traefik" [meta: $ lf certs] { Let's Encrypt · HTTP/3 · :443 } shop "shop.example.com" [meta: compose] { [[web :3000]] [[db postgres]] || `$ lf volume backup` backup **daily** → nas } blog "blog.example.com" [meta: static] { [[nginx:alpine]] login in front || `$ lf auth` } api "api.example.com" [meta: Dockerfile] { [[app :8080]] releases {green: ●●●●} || `$ lf rollback` } journal "journal" [meta: every change recorded, caps] { *#5 14:41* env shop STRIPE_KEY=… || {green: ↺} *#4 14:38* domains shop +www || {green: ↺} *#3 14:30* deploy shop || {green: ↺} --- `$ lf history · lf undo` } } group net "the internet" [caps] { d1 "🔒 shop.example.com" sub: your shop, live d2 "🔒 blog.example.com" sub: static files, nginx d3 "🔒 api.example.com/health" sub: {ok: true} } dns "dns at your registrar" [caps, dashed] { A example.com → <server-ip> A *.example.com → <server-ip> --- `$ lf domains · lf check` } traffic "last 24h" [meta: $ lf traffic, caps] { | site | requests | 5xx | p95 | |------|----------|-----|-------| | shop | 12.4k | 0 | 84 ms | | blog | 3.1k | 0 | 12 ms | | api | 48.0k | 2 | 41 ms | bars: 2 3 2 4 6 8 9 8 7 9 10 9 8 7 6 5 cpu **12%** · mem **41%** · disk **38%** } stop "what you stop doing" [shape: text, caps] { ~~hand-writing nginx configs and certbot cron jobs~~ ~~paying a PaaS for a side project~~ ~~running a daemon you can't read~~ } laptop -> traefik: ssh caption: one bash script per command laptop -> journal: [dotted, head: dot] traefik -> shop, blog, api shop -> d1: HTTPS blog -> d2 api -> d3 d3 -> dns: [dotted, head: none] d1 -> traffic: [dotted, head: none] ``` ## Your own theme Define a theme in the file with a `theme` block, then pick it like any other: ```yuhwa theme brand { base: paper background: #fffaf0 node-fill: amber node-stroke: orange edge-color: orange title-color: #7c2d12 radius: 4 } theme: brand title: Checkout cart "Cart" -> pay "Payment" -> done "Done" [green] ``` Short themes fit on one line: ```yuhwa theme brand [base: midnight, accent: orange, edge-color: orange] theme: brand a "Build" -> b "Ship" ``` A theme starts from its `base`, `paper` unless set, and changes only the keys you give. The base can be a built-in theme or another theme of your own. A theme named like a built-in one (`theme midnight [radius: 0]`) adjusts that theme in place. Colours take a palette name (`orange`), which picks a shade that suits the role, or any CSS colour. `yuhwa check` warns on unknown keys and colours. | key | sets | | ------------------------------------------------ | -------------------------------------------------------------------------------------------- | | `base` | the theme to start from (default `paper`) | | `dark` | `true` for a dark theme: palette colours pick dark shades | | `background` | page colour, or `none` | | `font` | font family; `mono` and `sans` are shortcuts, a name with "mono" in it switches to monospace | | `font-size` | base text size in px | | `node-fill` `node-stroke` `node-text` `node-sub` | box fill, border, label and second line | | `group-fill` `group-stroke` `group-text` | group background (or `none`), border and label | | `group-border` | group border style: `solid`, `dashed` or `dotted` | | `edge-color` `edge-text` `label-bg` | lines, edge labels, the background behind edge labels | | `title-color` | title and panel headings | | `accent` | code spans, chips and highlights | | `radius` `stroke-width` `edge-width` | corner radius, box border and line width in px | | `shadow` | box shadow colour, or `none` | | `grid` | background grid colour, or `none` | ### Sharing a theme Themes travel with imports, like classes. Keep your themes in a kit file and import it wherever you need them: ```yuhwa // brand.yu theme brand [base: paper, accent: orange, edge-color: orange] export theme: brand ``` ```yuhwa import "./brand.yu" a -> b ``` `export theme: brand` also makes it the theme of every file that imports the kit. Leave it out to only make `brand` available. Pick one theme with `import { brand } from "./brand.yu"`. A panel can use a custom theme too: `chart sales [theme: brand] { … }`. ### From JavaScript To use a theme in every diagram without defining it in each file, register it as a plugin. `createTheme` builds a theme from the same keys: ```ts import { use, createTheme } from 'yuhwa'; use({ name: 'brand-theme', themes: [createTheme('brand', { base: 'midnight', accent: 'orange', 'edge-color': 'orange' })], }); ``` `theme: brand` then works in every diagram that script renders. `--theme` on the command line also accepts a theme defined in the file: `yuhwa render diagram.yu --theme brand`. ## Tones `color` sets fill, border and text colour in one prop. Each theme picks the shades, so a palette colour looks right in light and dark themes. ```yuhwa direction: right gap: 16 slate [slate], red [red], orange [orange], amber [amber] lime [lime], green [green], teal [teal], cyan [cyan] blue [blue], indigo [indigo], purple [purple], pink [pink] slate -> red -> orange -> amber lime -> green -> teal -> cyan blue -> indigo -> purple -> pink ``` ## Shapes ```yuhwa direction: down gap: 20 rounded [rounded], box [box], pill [pill], circle [circle] ellipse [ellipse], diamond [diamond], hexagon [hexagon], cylinder [cylinder] parallelogram [parallelogram], document [document], note [note], text [shape: text] rounded -> ellipse -> parallelogram box -> diamond -> document pill -> hexagon -> note circle -> cylinder -> text ``` ## Edges ```yuhwa a -> b: solid c --> d: dashed e ..> f: dotted g => h: thick i <-> j: both ends k -> l: animated [flow, blue] m -> n: heads head: diamond tail: dot ``` ## Classes Define a look once and apply it by name. Props on the element override the class. ```yuhwa .svc [blue] sub: service .store [amber, cylinder] .async [dashed, flow] api "API" .svc billing "Billing" .svc [green] db "Postgres" .store api -> db api -> billing: invoice .async ``` ## Diagram settings Settings at the top of the file change the whole diagram: `curve`, `gap`, `rank-gap`, `padding`, `font`, `font-size`, `background`, `grid`, `shadow`, `radius`, `stroke-width`, `shape`, `subtitle` and `accent`. The settings table has the details. ```yuhwa curve: orthogonal radius: 2 shadow: false grid: true font: JetBrains Mono a "build" -> b "test" -> c "deploy" b -> d "report": [dotted] ``` # Fonts A yuhwa SVG names its fonts. It does not carry the font files. Whoever shows the SVG supplies the fonts: the page, the browser, the operating system, or the PNG renderer. This page covers which fonts you can name and where each one works. ## Picking a font Set the font for one diagram with the `font` setting, or for every diagram that uses a theme with the theme's `font` key: ```yuhwa font: Georgia font-size: 15 client "Browser" -> api "API" -> db "Orders" [shape: cylinder] ``` ```yuhwa theme { base: paper font: Inter font-size: 14 } ``` | value | font stack in the SVG | | ----------------- | -------------------------------------------------------------------------------------------------- | | none | the theme's font. Every built-in theme uses `sans` | | `sans` | `Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif` | | `mono` | `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace` | | `serif` | `ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif` | | any other name | that name, then `ui-sans-serif, system-ui, sans-serif` | | a monospaced name | a name containing `mono`, `code` or `courier` is set as monospace, then `ui-monospace, monospace` | Any font family name works: a system font such as `Georgia` or `Menlo`, or a web font the page loads, such as `Inter` or `IBM Plex Sans`. The diagram falls back to the rest of the stack when the font is missing, so it never shows without text. ### Fallback fonts Name more fonts, separated by commas, to pick what shows when the first one is missing. Each viewer sees the first font in the list that they have: ```yuhwa font: Lora, Georgia, serif a "Lora, or Georgia" -> b "or any serif font" ``` `sans`, `serif` and `mono` in a list stand for their whole stack, so `font: Lora, serif` falls back to Georgia, Cambria and the other serif fonts. A list that does not end in `sans`, `serif`, `mono` or a CSS generic family (`sans-serif`, `serif`, `monospace`, `system-ui` …) gets the sans or mono ending from the table. Whether the diagram counts as monospace depends on the first font only. The visual editor suggests fonts for the `font` setting and says which font of the list it really shows. When the first font is missing on your computer, it names the fallback. A node, edge, group or panel takes its own `font` the same way: `a "Title" [font: serif]`, or `[font: "Lora, serif"]` for a list. A span sets the font of part of a text: `"{font: mono | v2} release"`. See text. Text weight comes from `font-weight` on a node, edge, group or panel, and from the theme (titles are `600`). A weight only shows when the font has it. A font with only a regular face shows bold text as regular, or as a faked bold. ### Card bodies The body lines of a card are always monospace, so code and columns line up. They use the `mono` stack unless the diagram font is itself monospaced. `mono: false` on the node sets the body in the diagram font instead. ## Where fonts come from | how the SVG is shown | fonts it can use | | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | inline in a page: `<yuhwa-diagram>`, the script tag, docs `output: 'svg'`, `innerHTML` | the page's web fonts and system fonts | | as an image: `<img src="x.svg">`, docs plugins (default), `yuhwa md` output, GitHub, image URLs | system fonts only | | a browser canvas or PNG: `renderCanvas`, `svgToCanvas`, the editor's PNG, `render="canvas"`, docs `output: 'canvas'` | system fonts, plus the page's web fonts, which yuhwa embeds | | a CLI PNG: `yuhwa render -o x.png`, docs plugins with `output: 'png'` | system fonts, plus the files you pass with `--font` or `png.fonts` | | an SVG file opened in an app (Figma, Inkscape, a browser tab) | fonts installed on the computer that opens it | ### Inline SVG An inline SVG is part of the page, so it uses the page's fonts like any other text. Load the font as you normally would, then name it: ```html <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" /> <script src="https://cdn.jsdelivr.net/npm/yuhwa/dist/yuhwa.iife.js"></script> <pre><code class="language-yuhwa"> font: Inter a -> b -> c </code></pre> ``` In the browser, yuhwa measures text with a canvas in the diagram's font, so boxes fit the text exactly. A web font that has not loaded yet is measured with its fallback. The script tag, `<yuhwa-diagram>` and `renderCanvas` therefore load the diagram's web fonts, in the weights it uses, and draw the diagram again once they arrive. When you call `render` yourself, `loadFonts(svg)` does the same step. It resolves `true` when a font arrived, and the diagram should be rendered again: ```ts import { render, loadFonts } from 'yuhwa/browser'; let { svg } = render(source); if (await loadFonts(svg)) ({ svg } = render(source)); ``` ### SVG as an image A browser shows an SVG image in isolation. It cannot reach the page's fonts or load fonts from the network, so only fonts installed on the reader's computer apply. This covers `<img>` tags, CSS backgrounds, the image links that `yuhwa md` writes, SVGs on GitHub, and the `yuhwa serve` image URLs. For an SVG that will be shown as an image, pick a font that readers have: the default `sans`, or a system font such as `Georgia`, `Verdana` or `Courier New`. If the diagram must use a web font, export a PNG instead. ## Canvas and PNG in the browser `renderCanvas` and `svgToCanvas` draw the SVG as an image, which normally means system fonts only. To keep web fonts, they first embed every `@font-face` font of the page that the diagram names, as `data:` URLs inside the SVG. A canvas drawn on a page that loads Inter therefore shows Inter. ```ts import { renderCanvas } from 'yuhwa/browser'; const { canvas } = await renderCanvas(source, { scale: 2 }); canvas.toBlob((png) => save(png), 'image/png'); ``` The `fonts` option controls what is embedded: | value | embeds | | --------------- | --------------------------------------------------------- | | `'page'` | the page's `@font-face` fonts the diagram names (default) | | a list of fonts | those files, e.g. a font the page does not load | | `false` | nothing: system fonts only | ```ts await svgToCanvas(svg, { fonts: [ { family: 'Inter', url: '/fonts/Inter.woff2', weight: '100 900' }, { family: 'Inter', url: '/fonts/Inter-Italic.woff2', weight: '100 900', style: 'italic' }, ], }); ``` Embedding works with: - `@font-face` rules in the page's stylesheets, including `<style>` tags, `@import`, and Google Fonts or other font CDNs; - `woff2`, `woff`, `ttf` and `otf` files. Only the faces the diagram needs are embedded: - rules for a `unicode-range` the diagram never uses are skipped, so a Google Fonts family pulls only the subsets it needs; - of a family offered in many weights, only the weights the diagram uses are embedded. A weight with no face of its own gets the face a browser would pick, e.g. `700` for a `650` title. Italic faces come along only when the diagram has italic text. It does not work with: - fonts added from JavaScript with `new FontFace(...)`: they have no stylesheet rule to read. Pass them in `fonts` instead; - font files on another origin that send no CORS header. yuhwa must fetch the file to embed it. Google Fonts and most font CDNs allow this. A font that cannot be fetched is skipped, and the text falls back to system fonts; - fonts that are only installed on the computer. They need no embedding: the canvas uses them directly. ## PNG from the command line `yuhwa render -o x.png` draws with [resvg](https://github.com/linebender/resvg), through the optional [`@resvg/resvg-js`](https://www.npmjs.com/package/@resvg/resvg-js) package. Install it next to yuhwa first: **-group** ```sh [npm] npm install -D @resvg/resvg-js ``` ```sh [pnpm] pnpm add -D @resvg/resvg-js ``` `render` shows how to run it once without installing anything. resvg reads the fonts installed on the system. Pass font files, or folders of them, with `--font`. It can be repeated: ```sh yuhwa render diagram.yu -o diagram.png --font fonts/Inter.ttf yuhwa render diagram.yu -o diagram.png --font ./fonts --font ~/Library/Fonts ``` The family name in the diagram must match the font's internal family name, as a font viewer shows it. resvg reads `ttf`, `otf` and `ttc` files. A `woff` or `woff2` file is an error; in a folder, such files are ignored. In CI and containers, few fonts are installed. Install the ones your diagrams name, or commit them and pass `--font`, so the PNG looks the same on every machine. `--no-system-fonts` ignores installed fonts entirely, so a machine with extra fonts cannot change the result. Text in a family that none of the `--font` files provide is then left out, so pass a font for every family the diagram uses, including the monospace one for card bodies: ```sh yuhwa render diagram.yu -o diagram.png --font ./fonts --no-system-fonts ``` ## Measuring text yuhwa sizes boxes to fit their labels, so it must know how wide text is. | where | how text is measured | | ----------------- | ---------------------------------------------------------------- | | browser | a canvas in the diagram's font: exact for that font | | Node, the CLI | a table of character widths tuned for Inter: close for most sans | | your own function | `measure` or `measureFor`, see the API | In Node, a much wider or narrower font than Inter can leave labels tight or loose in their boxes. Pass a `measure` that knows the font, for example one built on [`@napi-rs/canvas`](https://www.npmjs.com/package/@napi-rs/canvas) with the font registered. # Examples Copy any of these into the editor and change them from there. ## Everything at once One file with every kind of diagram: a graph with groups, classes, variables, a component, cards and every arrow, plus a sequence, timeline, charts, git graph, mind map, three Gantt charts in different styles, quadrant and Kanban board. Some panels use their own theme, background and border, and `panels: wrap` lays them out in rows under the graph. Colours mix palette names, `#hex`, `rgb()`, `hsl()` and CSS names. The file is `examples/showcase.yu` in the repository. ```yuhwa title: **Shopfront** platform subtitle: everything yuhwa can draw, in one file direction: right theme: paper panels: wrap panel-gap: 40 legend: .svc Service | .store Datastore | .ext External | --> async | ..> optional | red Deprecated footer: yuhwa showcase | {teal: v1.0} | 2026 // variables: replaced in labels, props, settings and panel bodies $brand: indigo $db: "Postgres 16" $warn: rgb(234, 88, 12) // classes, one built on another .svc [color: $brand, shape: rounded] .store [amber, cylinder] .ext [color: hsl(330 70% 50%), dashed] .primary .svc [bold, shadow] .async [dashed, flow: true] // a component: one service, its database and the edge between them def service(id, label, lang = Go) { $id "$label" .svc [sub: $lang] ${id}_db "$label DB" .store $id -> ${id}_db: SQL } // nodes: every shape, sub lines, icons, links and tooltips user "Customer" [shape: circle, purple, icon: 🙂] admin "Admin" [ellipse, #0ea5e9] web "Storefront" [frame: browser shop.example.com] { **Cart** || 3 items --- progress: 72% checkout funnel spark: 3 5 4 6 8 7 9 } group edge "Edge" [color: slate, dashed] { cdn "CDN" [hexagon, teal, link: https://example.com, tooltip: cached at 40 PoPs] waf "WAF" [parallelogram, color: tomato] } group core "Core services" [color: #4f46e5] { gateway "API Gateway" .svc .primary [sub: "auth, rate limit"] service(orders, Orders, Kotlin) service(payments, Payments, lang: Rust) group search "Search" [teal] { indexer "Indexer" .svc es "Elasticsearch" .store [color: $warn] } } queue "Event bus" [diamond, lime] stripe "Stripe" .ext [document] legacy "Legacy ERP" [box, red, opacity: 0.7] note "nightly sync,\nbest effort" [note, yellow-100] metrics "metrics" [meta: live, caps: true] { stat: 99.98% uptime | 41ms p50 bars: 3 5 4 6 8 9 7 | service | p95 | |----------|--------| | orders | 120 ms | | payments | 88 ms | ✓ health || [[green: ok]] } // edges: every arrow, labels, captions and edge props user -> web: browse web -> cdn: assets [label-bg: lightyellow, curve: straight] admin => cdn: purge [color: $brand, width: 3] cdn -> waf -> gateway gateway -> orders, payments gateway <-> indexer: query [curve: orthogonal] orders --> queue: OrderPlaced .async queue ..> indexer: reindex [caption: within 2 s] payments -> stripe: charge [head: dot, color: #db2777] indexer -- es queue -> legacy: export [dotted, red] legacy .. note stripe == metrics // panels, in reading order: how it works, how it runs, what comes next sequence login "Sign in" [numbered, lifeline-style: dotted] { actor user "Customer" [purple] participant web, db participant api "API" [indigo] user -> web: open /login web -> api: POST /login api -> db: find user db --> api: row [width: 2] api -> db: audit [red, dotted, head: open] note api: checks the hash [amber] --- session --- api --> web: 200 + cookie [green] web -> web: render } chart p95 "Latency p95" [type: column, unit: ms] { checkout: 120 search [green]: 48 payments [hsl(330 70% 50%)]: 88 } chart traffic "Traffic by region" [type: donut, unit: %, theme: midnight, shadow] { EU: 46 US [indigo]: 31 APAC: 23 } quadrant prio "Priorities" [background: lightyellow, border: orange, border-style: dashed, radius: 6] { x-axis Low effort -> High effort y-axis Low value -> High value q1 [green]: Quick wins q2: Big bets q3: Fill-ins q4 [red]: Money pit Search [teal]: 0.25, 0.8 Billing: 0.7, 0.65 Exports [color: tomato]: 0.3, 0.3 } // three looks for a gantt: a label column, names on solid bars, thin lines gantt plan "Q1 plan" [today: 2026-01-20, weekends: show] { --- Design [violet] --- research "User research" [progress: 100%]: 2026-01-05, 5d wireframes [done]: after research, 4d review [milestone]: after wireframes --- Build [teal] --- api "Build API" [active, progress: 40%, owner: ana]: 2026-01-14, 2w ui [crit, owner: kim]: after wireframes api, 10d launch [milestone, red]: after ui } gantt release "Release 2.0" [theme: midnight, today: 2026-02-18, bars: solid, labels: bar, notes: dates, density: compact, arrows: curved, summary: hide] { --- Beta [sky] --- beta "Private beta" [progress: 80%]: 2026-02-02, 2w feedback "Feedback round" [active]: after beta, 1w --- GA [green] --- docs "Docs" [progress: 30%]: 2026-02-16, 10d ga "General availability" [milestone]: after feedback docs } gantt hiring "Hiring" [bars: thin, labels: bar, rows: plain, grid: none, scale: week, density: loose] { sourcing "Sourcing" [blue, progress: 70%]: 2026-01-05, 3w interviews "Interviews" [indigo]: after sourcing, 4w offers "Offers" [green]: after interviews, 2w start "First day" [milestone]: after offers } timeline roadmap "Roadmap" [border: 2] { 2026 Q1: Private beta - 40 design partners 2026 Q2 [green]: **Launch** 2026 Q3 [#0ea5e9]: Mobile app 2026 Q4 [color: rgb(234, 88, 12)]: EU region } kanban sprint "Sprint 12" { Todo [gray] - Write docs [owner: ana, priority: high] - **Fix** login [red] Doing [blue, limit: 2] - API v2 [ticket: MER-12] needs the new auth flow - Search tuning [owner: kim] - Billing export Done [green] - Ship 1.0 } git release_flow "Release flow" { commit "init" [tag: v1.0] branch feature/login [pink] commit "login form" commit "oauth" checkout main commit "hotfix" [id: fix, highlight, red] merge feature/login [tag: v1.1] branch release/1.0 from v1.0 [label: "1.0.x", #0ea5e9] cherry-pick fix } mindmap ideas "Launch plan" [layout: both] { **Launch** Marketing [pink] Blog posts Newsletter Product Beta [#16a34a] - Pricing page Sales [shape: pill] Partners } ``` ## Web app ```yuhwa title: Web app direction: right .svc [blue] .store [cylinder, amber] user "Customer" [circle, purple] cdn "CDN" [slate] group app "App" [blue] { web "Web" .svc sub: Next.js api "API" .svc sub: REST + auth } group async "Background" [pink, dashed] { queue "Jobs" [hexagon, pink] worker "Worker" .svc } user <-> cdn: visits [flow] cdn -> web web -> api: fetch api -> db "Postgres" .store api --> queue: enqueue queue --> worker worker -> db: [constraint: false] ``` ## Request lifecycle ```yuhwa title: Request lifecycle direction: down curve: orthogonal req "Request" [pill, slate] auth "Authenticated?" [diamond, amber] cache "In cache?" [diamond, amber] hit "Serve cached" [green] handler "Run handler" [blue] deny "401" [pill, red] req -> auth auth -> deny: no auth -> cache: yes cache -> hit: yes cache -> handler: no handler -> store "Write cache" [blue] ``` ## Event-driven services ```yuhwa title: Order events theme: midnight .svc [blue] .topic [hexagon, pink] orders "Orders" .svc placed "order.placed" .topic paid "order.paid" .topic group consumers "Consumers" [dashed] { billing "Billing" .svc mail "Mail" .svc [icon: ✉️] stock "Inventory" .svc } orders => placed: publish [flow] placed --> billing, stock billing => paid: publish [flow] paid --> mail, orders ``` ## Service status board Cards hold short facts: status chips, numbers, a small chart. ```yuhwa title: Platform status subtitle: last 24 hours theme: terminal api "api" [meta: eu-west-1, caps] { uptime || [[green: 99.98%]] p95 || **182 ms** errors || {amber: 0.4%} --- bars: 4 6 5 7 9 8 6 7 10 9 } db "postgres" [meta: primary, caps] { connections || 84 / 200 replicas || [[green: 2 healthy]] --- bars amber: 3 3 4 6 9 7 5 4 } jobs "jobs" [meta: queue, caps] { waiting || 12 failed || [[red: 3]] *retry in 5 min* } api <-> db: sql caption: pooled api -> jobs: enqueue ``` ## Server deploy A product infographic in the `terminal` theme: terminal output, nested cards, chips, a table with bars and a struck-through list. ```yuhwa title: >landfall subtitle: bare server to HTTPS in two commands theme: terminal direction: right rank-gap: 120 laptop "~/shop" [meta: your laptop] { $ `lf setup vps --host <server-ip>` {green: ✓} docker · ufw · fail2ban · traefik $ `lf server domain vps example.com` {green: ✓} new sites get *<site>.example.com* $ `lf deploy` *→ compose.yaml: web, db* {green: ✓} built web · health check passed {green: ✓} live → **https://shop.example.com** } group vps "vps" [caps] { meta: Ubuntu 24.04 · no agent installed traefik "Traefik" [meta: $ lf certs] { Let's Encrypt · HTTP/3 · :443 } shop "shop.example.com" [meta: compose] { [[web :3000]] [[db postgres]] || `$ lf volume backup` backup **daily** → nas } blog "blog.example.com" [meta: static] { [[nginx:alpine]] login in front || `$ lf auth` } api "api.example.com" [meta: Dockerfile] { [[app :8080]] releases {green: ●●●●} || `$ lf rollback` } journal "journal" [meta: every change recorded, caps] { *#5 14:41* env shop STRIPE_KEY=… || {green: ↺} *#4 14:38* domains shop +www || {green: ↺} *#3 14:30* deploy shop || {green: ↺} --- `$ lf history · lf undo` } } group net "the internet" [caps] { d1 "🔒 shop.example.com" sub: your shop, live d2 "🔒 blog.example.com" sub: static files, nginx d3 "🔒 api.example.com/health" sub: {ok: true} } dns "dns at your registrar" [caps, dashed] { A example.com → <server-ip> A *.example.com → <server-ip> --- `$ lf domains · lf check` } traffic "last 24h" [meta: $ lf traffic, caps] { | site | requests | 5xx | p95 | |------|----------|-----|-------| | shop | 12.4k | 0 | 84 ms | | blog | 3.1k | 0 | 12 ms | | api | 48.0k | 2 | 41 ms | bars: 2 3 2 4 6 8 9 8 7 9 10 9 8 7 6 5 cpu **12%** · mem **41%** · disk **38%** } stop "what you stop doing" [shape: text, caps] { ~~hand-writing nginx configs and certbot cron jobs~~ ~~paying a PaaS for a side project~~ ~~running a daemon you can't read~~ } laptop -> traefik: ssh caption: one bash script per command laptop -> journal: [dotted, head: dot] traefik -> shop, blog, api shop -> d1: HTTPS blog -> d2 api -> d3 d3 -> dns: [dotted, head: none] d1 -> traffic: [dotted, head: none] ``` ## Release pipeline ```yuhwa title: release pipeline subtitle: from commit to release, without a release manager theme: terminal commit "conventional commit" [meta: main, caps] { ✓ `feat(api): add search` ✓ `fix: trim header` *chore: bump deps* } group ci "CI pipeline" [caps] { meta: 3 jobs checks "checks" [meta: 42s, caps] { ✓ typecheck || [[green: pass]] ✓ tests || [[green: 128]] ✓ build || [[green: ok]] } } release "release" [meta: v0.1.0, caps] { | commit | bump | |--------|-------| | feat | minor | | fix | patch | | feat! | major | --- ~~manual tagging~~ } npm "npm" [shape: text] { **yuhwa** *trusted publishing* } commit -> checks: push caption: every commit checks -> release: green release -> npm: publish [rotate] ``` ## Data model Cards with tables work as entity boxes. ```yuhwa title: Shop schema direction: right user "users" [caps] { | id | uuid | | email | text | | name | text | } order "orders" [caps] { | id | uuid | | user_id | uuid | | total | numeric | | status | text | } item "order_items" [caps] { | order_id | uuid | | sku | text | | qty | int | } user -> order: 1..n head: open tail: bar order -> item: 1..n head: open tail: bar ``` ## Team ownership One class per team carries its colour to the group and to every node in it, so ownership reads at a glance. ```yuhwa title: Who owns what subtitle: three teams, one request path direction: right theme: pastel .web [blue] .platform [purple] .data [green] group web "Web team" .web { meta: 5 people site "Marketing site" .web shop "Shop frontend" .web } group platform "Platform team" .platform { meta: 4 people gw "API gateway" .platform auth "Auth" .platform } group data "Data team" .data { meta: 3 people wh "Warehouse" .data [cylinder] bi "Dashboards" .data } site, shop -> gw gw -> auth gw ..> wh: events [flow] wh -> bi ``` ## Annotated sketch A note joins the pipeline with a `constraint: false` edge, so it sits right next to the step it explains. ```yuhwa theme: mono curve: straight a "Input" -> b "Parse" -> c "Layout" -> d "Render" -> e "SVG" [document] note "deterministic:\nsame input, same SVG" [note] d -- note: [dotted, constraint: false] ``` ## Product dashboard Plugins add presentation pieces: window frames, stat tiles, sparklines, progress bars and a footer strip. ```yuhwa title: Shop release **v2.4** subtitle: what ships on {green: Friday} footer: **landfall** v2.4 | `eu-central-1` | updated {green: 2 min ago} theme: midnight app "Storefront" [frame: browser shop.example.com, blue] { stat: 99.9% uptime | 42ms p95 | 1.2k rps --- spark blue: 3 5 4 6 8 7 9 12 10 14 } ci "Pipeline" [frame: terminal ~/shop, meta: 42s] { progress green: 72% tests progress amber: 9/12 deploys bars purple: 3 5 4 8 6 9 } flags "Flags" [frame: window Settings] { new-checkout || [[green: on]] dark-mode || [[off]] } app -> ci: build [flow] ci -> flags ``` ## Git branching Feature and hotfix branches with release tags. `merge` draws a merge commit; a colour after `branch` colours the lane. ```yuhwa title: Release branches subtitle: features merge into main, hotfixes get a patch tag git flow "main" { commit "init" [tag: v1.0.0] branch feature/search commit "index products" commit "search UI" checkout main branch hotfix/cart [red] commit "fix rounding" checkout main merge hotfix/cart [tag: v1.0.1] checkout feature/search commit "rank by sales" checkout main merge feature/search [tag: v1.1.0] } ``` ## Git log `direction: down` reads like `git log --graph`: commit ids, branch names at their heads and tags on one line. ```yuhwa theme: terminal git log "git log --graph --oneline" [direction: down] { commit "initial import" [id: 9fceb02] branch release/2.0 commit "bump version" [id: 3a1e5d7] checkout main commit "add payments" [id: b7c41f0] commit "fix flaky test" [id: 0e8d2a9] checkout release/2.0 commit "changelog" [id: 6d2f3b1, tag: v2.0.0] checkout main merge release/2.0 [id: c4a9e12] } ``` ## Checkout sequence A sequence panel without a graph: actors, numbered messages, dashed replies, notes and a divider. ```yuhwa theme: pastel sequence pay "Card payment" [numbered] { actor user "Customer" [purple] participant shop "Shop" participant psp "Payment provider" participant bank "Bank" user -> shop: pay 49.00 € shop -> psp: create intent psp -> bank: authorize bank --> psp: approved note psp, bank: 3-D Secure may add a step here --- capture --- psp --> shop: webhook: succeeded shop --> user: order confirmed } ``` ## Roadmap Two timelines stacked with `panels: column`: the quarters and the launch day. ```yuhwa title: Search launch panels: column timeline q "2026" { Q1: Discovery - 12 customer interviews Q2 [blue]: Beta - 3 design partners Q3 [green]: **GA** Q4 [amber]: Personalisation } timeline day "Launch day" { 08:00: freeze 10:00 [blue]: deploy - canary 5% 12:00 [green]: 100% 16:00: retro } ``` ## Release overview Graph, roadmap, branches and numbers in one file. `panels: grid` arranges them in two columns. ```yuhwa title: Checkout v2 subtitle: architecture, plan, branches and numbers in one file panels: grid .svc [blue] web "Web" .svc -> api "API" .svc -> db "Orders" [cylinder, amber] api -> queue "Events" [pill, teal]: publish [dashed] timeline plan "Roadmap" { Jan: Design Feb [blue]: Build Mar [green]: **Launch** } git branches "Branches" { commit "v1" [tag: v1.0] branch checkout-v2 commit "new cart" commit "payments" checkout main merge checkout-v2 [tag: v2.0] } chart conv "Conversion" [type: line, unit: %] { Jan: 2.1 Feb: 2.4 Mar: 3.2 } ``` ## Shared services The services live in `shared/services.yu`. This file imports them, restyles one node and adds its own edges and a chart. ```yuhwa import "./shared/services.yu" title: Checkout traffic api [purple] web -> api api -> db: SQL chart rps "Requests / s" [type: column] { web: 820 api: 640 db: 310 } ``` # From Mermaid or JSON Every API and CLI command accepts three input formats and detects the format from the content. ## Mermaid Mermaid diagrams render as they are. Flowcharts become a yuhwa graph. Most other diagram types become a panel or nodes and groups: ```yuhwa flowchart LR A[Start] --> B{Valid?} B -->|yes| C((Done)) B -.->|no| D[(Error log)] subgraph svc [Service] C end ``` Convert one to yuhwa source to restyle it: ```sh yuhwa convert flow.mmd -o flow.yu ``` ### What converts | Mermaid | yuhwa | | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `graph`, `flowchart` | nodes, edges and groups | | `stateDiagram`, `stateDiagram-v2` | nodes and groups. `[*]`, fork, join and choice states get small classes such as `.state-start`. Composite states become groups | | `classDiagram` | card nodes (attributes, `---`, methods). Inheritance, composition and dependency become edges with `head`/`tail` markers. Cardinalities become the edge caption. Namespaces become groups | | `erDiagram` | an entity block becomes a node with a `type \| name \| keys \| comment` table. A relationship becomes an edge with the cardinality as caption | | `sequenceDiagram` | `sequence` panel | | `timeline` | `timeline` panel | | `gitGraph` | `git` panel | | `pie` | `chart` panel, `type: pie` | | `xychart-beta` | `chart` panel, bar or line | | `journey` | `chart` panel, one column per task score, coloured by score | | `mindmap` | `mindmap` panel | | `gantt` | `gantt` panel | | `quadrantChart` | `quadrant` panel | | `kanban` | `kanban` panel | The `gantt`, `quadrant` and `kanban` panels come from plugins. Register a plugin with `use()` before you render its panel. Flowchart details: | Mermaid | yuhwa | | --------------------------------------------------- | ------------------------------------------------------- | | `TD` `TB` `LR` `RL` `BT` | `direction` | | `A[x]` `A(x)` | default shape | | `A{x}` `A{{x}}` `A[(x)]` `A((x))` `A([x])` `A[/x/]` | diamond, hexagon, cylinder, circle, pill, parallelogram | | `-->` `---` `-.->` `==>` `<-->` | `->` `--` `..>` `=>` `<->` | | `-->\|label\|` and `-- label -->` | edge label | | `subgraph id [Title] … end` | `group` | | `classDef`, `class`, `:::name`, `style` | classes and props | Mermaid `style` and `classDef` colours pass through: `fill` and `stroke` keep their hex or `rgb()` value. Mermaid's `color` is the text colour, so it becomes `text`. yuhwa's own `color` prop sets the palette colour of a node. ### What gives a warning The converter keeps going and lists what it skipped or changed: - `click`, `linkStyle`, `accTitle` and `accDescr` are skipped. - A `direction` inside a subgraph or composite state is skipped. - Sequence `loop`, `alt`, `opt` and `par` blocks become `--- … ---` dividers. `rect` boxes and activations are skipped. Cross ends (`-x`) are drawn as normal arrows. - State concurrency regions (`--`) are drawn as one region. Edges to a composite state attach to its start or end state inside. - Class aggregation (`o--`) is drawn as a diamond, like composition. - Journey actors are skipped. The scores become a column chart. - `xychart-beta` y-axis titles and ranges are skipped; the chart scales to the data. - Mindmap icons and classes are skipped. Cloud, bang and hexagon shapes use the default look. - Gantt `excludes`, a `dateFormat` other than `YYYY-MM-DD`, and lengths in seconds or minutes are approximated. - Kanban priority `Very High` becomes `high`, `Very Low` becomes `low`. ### What gives an error These types have no yuhwa equivalent yet: `sankey-beta`, `C4Context` and the other C4 types, `requirementDiagram`, `packet-beta`, `block-beta`, `architecture-beta`, `radar-beta`, `treemap-beta` and `zenuml`. ### What yuhwa does better | Mermaid | yuhwa | | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | | styles repeat on every node, or need `classDef` plus `class` lines | `.svc [blue]` once, `.primary .svc [bold]` to extend | | colours are CSS strings per diagram type | one palette everywhere: `[red]`, `[color: teal]`, or a hex, `rgb()` or `hsl()` value | | no variables | `$brand: violet`, then `color: $brand` anywhere | | no reuse of node patterns | `def service(id, label) { … }`, then `service(cart, "Cart")` | | one file per diagram | `import`, with `export` lists and `import { a as b }` | | one diagram type per block | a graph and any number of panels (sequence, chart, git, gantt, …) in one file | | positions cannot be fixed | drag in the editor; positions land in a `layout { }` block | | a gantt task needs an id and a date format | `design "Design": 2024-01-01, 10d`, and the next task follows on its own | | kanban metadata is a YAML-like `@{ }` block | chips: `- Fix login [owner: ana, priority: high]` | | a class or ER diagram is its own syntax | they are ordinary nodes, so classes, groups and themes apply | | errors stop the render | warnings with line numbers and _did you mean_ hints; the rest still renders | ## JSON Programs and tool-calling models can send structured data instead of text. The object has optional `title`, `direction`, `theme`, `settings`, `classes`, `groups`, `nodes` and `edges` keys. Any other key on a node, edge or group is a prop. ```json { "title": "Checkout", "direction": "down", "classes": { "svc": { "color": "blue" } }, "groups": [{ "id": "core", "label": "Core", "color": "slate" }], "nodes": [ { "id": "api", "label": "API", "group": "core", "class": "svc", "sub": "Node 22" }, { "id": "db", "label": "Postgres", "shape": "cylinder" } ], "edges": [{ "from": "api", "to": ["db", "cache"], "label": "read", "arrow": "-->" }] } ``` - `groups[].parent` nests a group in another one. - `edges[].from` and `edges[].to` take an id or a list of ids (fan-out). - `edges[].arrow` is one of the arrows. The default is `->`. - `class` takes a name or a list of names. `render()` also accepts the object directly. `yuhwa convert diagram.json` prints the equivalent yuhwa source. ## In the editor **Import** in the visual editor takes Mermaid, JSON or yuhwa: paste it, pick a file, or drop one on the window. The editor converts it and opens the result as a new file tab, or replaces the current one. A Markdown file works too: the first `yuhwa`, `mermaid` or `json` fence is imported. # CLI **-group** ```sh [npm] npm install -g yuhwa # or run: npx yuhwa <command> ``` ```sh [pnpm] pnpm add -g yuhwa # or run: pnpm dlx yuhwa <command> ``` A global install adds two commands, `yu` and `yuhwa`, which are the same program. In a project that has `yuhwa` installed, `npx yuhwa` runs that installed version. `pnpm dlx yuhwa` always fetches the latest release. Use `pnpm exec yuhwa` for the project's version. | command | does | | ---------------------------------------------------- | -------------------------------- | | `yuhwa <file>` | same as `yuhwa render <file>` | | `yuhwa render <file\|-> [-o out.svg] [--theme name]` | render to SVG, HTML or PNG | | `yuhwa check <file...> [--json] [--lang a,b]` | validate without rendering | | `yuhwa lint <file...> [--fix] [--json]` | check plus hygiene and format | | `yuhwa convert <file\|-> [-o out.yu]` | Mermaid or JSON to yuhwa | | `yuhwa md <file.md...>` | render blocks in Markdown | | `yuhwa edit <file> [--block n]` | open the visual editor | | `yuhwa serve`, `yuhwa url <file>` | HTTP render service and its URLs | | `yuhwa guide` (alias `llms`) | language reference for AI agents | | `yuhwa themes` | list themes | | `yuhwa -v`, `yuhwa -h` | version, help | Every command that reads a diagram accepts yuhwa, a Mermaid flowchart or JSON. The format is detected from the content. Pass `-` to read from stdin. Imports only read `.yu` files. `import "./other.yu"` lines are read from disk, relative to the file that imports them. From stdin, they resolve against the current directory. See Imports. ## render ```sh yuhwa render diagram.yu -o diagram.svg [--theme midnight] yuhwa render - < diagram.yu > diagram.svg ``` Writes the SVG to stdout unless `-o` is given. `--theme` overrides the `theme:` setting. `--html`, or an `-o` path ending in `.html`, writes a page instead: the diagram in a full-window pan and zoom viewer, with no files to load. ```sh yuhwa render big.yu -o big.html ``` `--png`, or an `-o` path ending in `.png`, writes a PNG. `--scale n` sets the pixels per SVG unit (default 2). PNG output needs the optional `@resvg/resvg-js` package, since Node has no canvas: **-group** ```sh [npm] npm install -D @resvg/resvg-js yuhwa render diagram.yu -o diagram.png --scale 3 ``` ```sh [pnpm] pnpm add -D @resvg/resvg-js yuhwa render diagram.yu -o diagram.png --scale 3 ``` The PNG uses fonts installed on the system. `--font` adds a font file or a folder of them, and can be repeated. `--no-system-fonts` uses only those fonts. See Fonts. Without installing anything, `npx` or `pnpm dlx` can fetch both packages for one run: **-group** ```sh [npm] npx -p yuhwa -p @resvg/resvg-js yuhwa render diagram.yu -o diagram.png ``` ```sh [pnpm] pnpm --package=yuhwa --package=@resvg/resvg-js dlx yuhwa render diagram.yu -o diagram.png ``` From a Markdown file, `render` draws one block. `--block n` picks it, counting from 0. The default is the first block. ```sh yuhwa render README.md --block 1 -o second.svg ``` ## check ```sh yuhwa check diagram.yu yuhwa check docs/*.yu yuhwa check diagram.yu --json ``` Validates without rendering and takes several files. Each file gets a `file: ok (yuhwa, N diagnostic(s))` summary line. Warnings and errors go to stderr as `file:line: severity: message`. `--json` prints a machine-readable report to stdout: ```json { "file": "diagram.yu", "ok": true, "format": "yuhwa", "nodes": 2, "edges": 1, "groups": 0, "diagnostics": [{ "line": 1, "severity": "warning", "message": "Unknown color \"bleu\" (did you mean \"blue\"?)" }] } ``` With several files, `--json` prints an array of these reports. ### Markdown files ```sh yuhwa check README.md docs/*.md yuhwa check docs/*.mdx --lang yuhwa,yu,mermaid ``` A `.md`, `.mdx` or `.markdown` file is checked block by block. These blocks count: - fences in the languages `yuhwa` and `yu`; - `<!--yuhwa name … -->` comments, as written by `yuhwa md`. `--lang` replaces the fence languages, comma-separated. Fences with `no-render` are skipped, like the docs integrations skip them. A fence in another language is skipped with everything inside it, so a ` ```markdown ` fence that shows a yuhwa block is not checked. Line numbers point into the Markdown file. The summary line reads `file.md: ok (markdown, N block(s), N diagnostic(s))`. A page without blocks is ok and says `no yuhwa blocks found`. `--json` prints one report per Markdown file. It has the same keys, with `format: "markdown"` and the counts summed over all blocks. Each diagnostic also has `block`, the block's index. `blocks` lists every block: ```json { "file": "README.md", "ok": false, "format": "markdown", "nodes": 5, "edges": 2, "groups": 0, "diagnostics": [{ "line": 15, "message": "…", "severity": "error", "block": 1 }], "blocks": [ { "index": 0, "lang": "yuhwa", "name": "checkout", "line": 3, "ok": true, "format": "yuhwa", "nodes": 2, "edges": 1, "groups": 0 }, { "index": 1, "lang": "yu", "line": 13, "ok": false, "format": "yuhwa", "nodes": 3, "edges": 1, "groups": 0 } ] } ``` `line` is the line of the opening fence. `lang` is `comment` for a `<!--yuhwa -->` block. A page without blocks has `blocks: []` and `note: "no yuhwa blocks found"`. `render` and `check` exit with status 1 when the source has errors. Warnings do not change the exit status, but they point at real mistakes: a node renamed by an edge, a node moved between groups, a `layout` line for a node that no longer exists, an edge to a misspelled node id. Fix them too. ## lint ```sh yuhwa lint docs/*.yu README.md yuhwa lint diagram.yu --fix ``` `lint` reports everything `check` does, plus things that render fine but should not stay in the file: - a class, `$variable` or `def` component that is never used; - the same edge drawn twice; - a `.yu` file, or a diagram block in Markdown, that is not formatted. A file that draws nothing is a library for imports, so its definitions count as used. So does anything it exports. `lint` exits with status 1 on any finding, warnings included, which makes it fit for CI and pre-commit hooks. `--fix` formats `.yu` files in place; the other findings name their fix. Markdown files are linted block by block, like `check`, and `--fix` formats their ` ```yuhwa ` blocks and `<!--yuhwa` comments, leaving the rest of the page as it is. `no-render` blocks and JSON blocks are not touched. `--json` prints `{ file, ok, diagnostics }`, with `fixed: true` when the file was formatted. The language server shows the same findings as hints in the editor. Unused definitions are greyed out. ## convert ```sh yuhwa convert flow.mmd -o flow.yu yuhwa convert diagram.json ``` Turns a Mermaid flowchart or a JSON diagram into yuhwa source. ## md ```sh yuhwa md README.md docs/*.md [--out-dir diagrams] [--dark] [--keep-fences] [--view[=base]] ``` `--view` links each image to a pan and zoom viewer of the diagram. See Zoom and pan on GitHub. Renders every yuhwa block in Markdown files. See Markdown and GitHub. ## edit ```sh yuhwa edit diagram.yu [--port 4747] [--no-open] yuhwa edit README.md --block 1 ``` Opens the visual editor on a local file. Saving writes back into the file and into imported `.yu` files you changed. `--block n` picks the n-th diagram (from 0) in a Markdown file. ## serve and url ```sh yuhwa serve [--port 4749] [--host 127.0.0.1] yuhwa url diagram.yu [--base http://localhost:4749] [--view] ``` The HTTP render service and its image URLs. See Image URLs. `url --view` prints a link to a pan and zoom viewer instead: the hosted one, or `/yuhwa/view/…` on your server with `--base`. ## guide and themes ```sh yuhwa guide # the language reference, written for AI agents (alias: llms) yuhwa themes # list the themes ``` # 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: …`. ```yuhwa 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`. ```yuhwa 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 -> prefs ``` ## Legend `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 | ```yuhwa 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. ```yuhwa 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. ```ts 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. ```ts 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.offsets` holds the offsets the user set, by part name. They come from `panel:part D` (or `panel:part DX DY`) lines in the `layout` block. Add them where you place that part, in `measure` and in `render`. - `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, provide `editPosition(body, offset)` to rewrite its existing line on drop. Return the updated body with the same line count. - `options` lists the header props and their type. The editor, the language server and `yuhwa guide` read 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' }`. - `help` maps 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' }`. ```ts 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: ```ts 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. `fields` names what the part can set, by key: a list of values becomes a select, an empty list a text field, `['', 'true']` a toggle. `depth` indents the part in the list. `values` holds the current ones. `actions` lists the moves it takes: `up`, `down`, `remove` and `add` (a child, named by `adds`, such as a card in a column). - `editPart(body, edit, data)` applies one edit to the body lines and returns `{ body, id }`, where `id` is the edited part's id afterwards (it may change when the part moves or is renamed), or `null` when the edit does not apply. An edit is `{ op: 'set', id, key, value }`, `{ op: 'up' | 'down' | 'remove', id }` or `{ op: 'add', id? }`; `add` without an id adds a top-level part, named by the kind's own `adds`. `color` is always a field. For a kind whose parts only take a colour, `recolor` builds `editPart` from a function that rewrites the body: ```ts 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. ```ts 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: - `aliases` lists other names for the shape (`db` for `cylinder`). - `textOffset` moves the label down inside the outline, in px. - `port(box, side, t)` returns where an edge meets the outline on `side`, with `t` from -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. ```ts 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. ```ts 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. # JavaScript API **-group** ```sh [npm] npm install yuhwa ``` ```sh [pnpm] pnpm add yuhwa ``` ```ts import { render } from 'yuhwa'; ``` The package is ESM with TypeScript types. The core has no DOM access and no dependencies. | import | contents | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `yuhwa` | the core API below | | `yuhwa/browser` | the core API, plus a browser `render`, `run` and the `<yuhwa-diagram>` element | | `yuhwa/yuhwa.iife.js` | the browser build for a `<script>` tag; global `Yuhwa` | | `yuhwa/markdown-it` | markdown-it plugin (VitePress, Eleventy, Slidev) | | `yuhwa/remark` | remark plugin (Docusaurus, Vocs, Nextra, Fumadocs, Rspress, MDX) | | `yuhwa/astro` | Astro and Starlight integration | | `yuhwa/satteri` | Sätteri plugin (the Astro 7 Markdown processor), for a hand-built pipeline | | `yuhwa/vuepress` | VuePress 2 plugin | | `yuhwa/ironmark` | ironmark plugin: renders fences in `.md` and `.mdx` at build time or run time | | `yuhwa/vite` | Vite plugin: `import svg from './x.yu'` | | `yuhwa/plugin` | helpers and types for writing a plugin, see Writing a plugin | | `yuhwa/lsp` | the language service; `/server`, `/browser` (Web Worker) and `/client`, see Language server | | `yuhwa/style.css` | light/dark switching for the docs plugins | | `yuhwa/zoom` | pan and zoom for the docs plugins; exports `zoomable`, `zoomHeight`, `zoomScript` and `installZoom`, see Zoom and pan | | `yuhwa/canvas` | `output: 'canvas'` for the docs plugins: draws each diagram into a canvas; exports `installCanvas`, see Output | | `yuhwa/llms.txt` | the language reference as text | The docs plugins are described in Docs sites and frameworks. **`yuhwa/browser` runs on import** Importing the browser entry renders every yuhwa block on the page once the DOM is ready, like the script tag. To render only on demand, import from `yuhwa` and call `render` yourself. ## render ```ts function render(input: string | DiagramJSON, opts?: Options): Result; ``` Parses, lays out and renders a diagram. `input` can be yuhwa source, a Mermaid flowchart, a JSON string or a JSON object. `render` never throws on bad input. ```ts interface Options { theme?: string; // overrides the theme: setting measure?: Measure; // text width function, see below idPrefix?: string; // prefix for ids inside the SVG interactive?: boolean; // wide hit areas and data attributes for editors width?: number | string; // fixed width attribute transparent?: boolean; // no background rect resolve?: (path: string) => string | undefined; // reads import "..." targets file?: string; // path of this source; imports resolve against it } interface Result { svg: string; // self-contained SVG markup source: string; // yuhwa source (converted for Mermaid and JSON) format: 'yuhwa' | 'mermaid' | 'json'; diagram: Diagram; // parsed model layout: Layout; // positions of every node, group and edge diagnostics: Diagnostic[]; // { line, severity: 'error' | 'warning', message } } ``` `import "./shared.yu"` needs `resolve`. It gets the path joined to `file` and returns the source, or `undefined` when it does not exist. In Node: ```ts const resolve = (p: string) => (existsSync(p) ? readFileSync(p, 'utf8') : undefined); render(readFileSync('docs/checkout.yu', 'utf8'), { file: 'docs/checkout.yu', resolve }); ``` In the browser, look the path up in a map you filled earlier. `fetchImports` from `yuhwa/browser` fills one: it fetches every import, and their imports, before the synchronous `render`. ```ts import { fetchImports, render } from 'yuhwa/browser'; const file = '/docs/checkout.yu'; const source = await (await fetch(file)).text(); const files = await fetchImports(source, file); render(source, { file, resolve: (p) => files[p] }); ``` `resolve` is synchronous. URLs are passed through unchanged, so a resolver can also serve prefetched remote files. Ids inside the SVG get a prefix derived from the source. Several diagrams can therefore share a page. ### Browser render `render` from `yuhwa/browser` (and `Yuhwa.render` in the script build) measures text with a canvas for exact box sizes. When no theme is set, it picks `paper` or `midnight` to match the reader's colour scheme. `run(root?, opts?)` renders every yuhwa block under `root` (default `document`). ### Canvas and image `renderCanvas` from `yuhwa/browser` renders a diagram and draws it into a canvas. It returns the usual `Result` plus `canvas`. To save an image, use the canvas's own `toBlob` or `toDataURL`: ```ts import { renderCanvas } from 'yuhwa/browser'; const { canvas } = await renderCanvas(source, { scale: 2 }); document.body.append(canvas); canvas.toBlob((png) => upload(png), 'image/png'); ``` | option | default | meaning | | ------------ | ------------------ | -------------------------------------------------------------- | | `scale` | `devicePixelRatio` | pixels per SVG unit | | `canvas` | a new canvas | canvas to draw into | | `background` | none | fill behind the diagram, e.g. for JPEG | | `fonts` | `'page'` | fonts to embed: `'page'`, a list of `{ family, url }`, `false` | `svgToCanvas(svg, opts)` does the same for an SVG string you already have. It is exported from `yuhwa` too, which has no side effects on import, so an app can use it without the script-tag runtime: ```ts import { render, svgToCanvas } from 'yuhwa'; const canvas = await svgToCanvas(render(source).svg, { scale: 2 }); ``` The SVG is drawn as an image, which cannot reach the page's web fonts. By default yuhwa embeds the page's `@font-face` fonts that the diagram names. `embedFonts(svg, fonts?)` does only that step and returns the SVG. `loadFonts(svg)` loads the page's web fonts the SVG names and resolves `true` when one arrived, so a diagram measured with a fallback can be rendered again. See Fonts. ## Lower-level steps ```ts import { parse, layout, renderSvg } from 'yuhwa'; const diagram = parse(source); // Diagram, with diagnostics const positions = layout(diagram, opts); // Layout const svg = renderSvg(diagram, positions, opts); ``` The `Diagram` holds everything the source declared, after imports, variables and components are applied: | field | contents | | ------------------------------------ | ---------------------------------------------------------- | | `settings`, `classes` | top-level settings and class props | | `nodes`, `edges`, `groups`, `panels` | the declarations, each with a `ref` to its source line | | `layout` | the `layout { }` overrides | | `imports` | resolved paths of imported files, in order | | `vars` | `$name` values, by name without the `$` | | `defs` | components: `{ name, params: { name, default? }[], body }` | | `exports` | names after `export`, when the file has any | | `sharedSettings` | settings the file exports (`export theme: midnight`) | | `data` | what plugin statements parsed, keyed by plugin | | `diagnostics` | errors and warnings with line numbers | A `ref` with `generated: true` points at a line that a component call or a variable expanded. `setProp` does not edit such a line; it appends an `id [props]` line instead. `toSource(input)` converts Mermaid or JSON into yuhwa source without rendering. It returns `{ source, format, diagnostics }`. `fromMermaid` and `fromJSON` expose the converters directly. ## Editing source These helpers change source text in place and keep the user's formatting. The visual editor uses them. | function | does | | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `setProp(source, { kind, id }, key, value)` | set or remove (`null`) a prop on a node, edge or group | | `setSetting(source, key, value)` | set or remove a top-level setting | | `writeLayout(source, overrides)` | replace the `layout { }` block | | `formatLayout(overrides)` | the `layout { }` block as text | | `setLabel(source, target, text)` | change the label of a node, edge or group | | `setPartTone(source, panelId, partId, tone)` | colour one panel part; `null` removes the colour | | `editPart(source, panelId, edit)` | set a field on a panel part, move, add or remove it; returns `{ source, id }` with the part's id afterwards | | `addNode(source, { id, label?, from?, group? })` | add a node, inside a group and with an edge from `from` when given | | `removeElement(source, { kind, id })` | delete a node (with its edges), an edge or a panel, or unwrap a group; returns the source unchanged when the element shares a line | | `parseProps(text)` / `serializeProps(props)` | read and write `[key: value]` lists | | `splitTrailingProps(text)` / `setTrailingProp(line, key, value)` | read and change the `[props]` that end a line | | `setLineProp(line, head, key, value, accept?)` | change one prop on a panel line whose `[props]` sit before the colon or at the end; `onlyColor` is the `accept` for lines that end in free text | ## Markdown `processMarkdown(markdown, opts)` is what `yuhwa md` runs. It renders every yuhwa block in a Markdown string and returns the new Markdown plus the SVG files to write: ```ts const { markdown, files, diagnostics } = processMarkdown(text, { dark: true, file: mdPath, resolve }); // f.path is relative to the Markdown file for (const f of files) writeFileSync(join(dirname(mdPath), f.path), f.svg); ``` `findBlocks(markdown)` lists the blocks with their line ranges, and `replaceBlockSource(markdown, index, source)` swaps the source of the block at `index`. `MD_LANGUAGES` holds the fence languages read as diagrams (`['yuhwa', 'yu']`). ## Plugins Themes, chart and table rows, frames and the footer are plugins. All built-in ones are registered on import. Add your own with `use`; see the plugin guide. ```ts import { use, registry, type YuhwaPlugin } from 'yuhwa'; use(myPlugin); registry.rows.map((r) => r.kind); // every registered row kind ``` | export | contents | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `use(...plugins)` | registers plugins; a name already registered is skipped | | `unuse(name)` | removes a plugin and restores what it replaced; `false` when no plugin has that name | | `registry` | `plugins`, `rows`, `frames` and `panels` (both `Map`s) and `decorations` | | `builtins`, `shapes`, `markers`, `themes`, `charts`, `tables`, `frames`, `legend`, `footer`, `sequence`, `timeline`, `chart`, `git`, `mindmap`, `gantt`, `quadrant`, `kanban`, `treeview` | the built-in plugins | | `YuhwaPlugin`, `RowKind`, `RowCtx`, `RowPaint`, `FrameKind`, `Decoration`, `PanelKind`, `PanelCtx` | plugin types | | `perPass(fn)` | caches a panel's geometry for one layout pass, see Panel kinds | | `recolor(fn)` | an `editPart` for panels whose parts only take a colour | | `optionKind(o)`, `PanelOption` | the field type of a `PanelKind` option: `select`, `color`, `number`, `flag` or `text` | | `renderHead`, `dashFor`, `lineStyle` | edge ends and dash patterns, shared with graph edges | | `joinPath(from, rel)` | how import paths are resolved, for custom resolvers | | `parseInline`, `segsW`, `renderSegs`, `tspans` | inline markup helpers for rows | | `esc(text)` | escapes `& < > "` so user text is safe inside a row's or panel's SVG | | `createTheme(name, keys, base?)` | builds a `Theme` from the theme keys, for `use({ themes: [...] })` | | `registerTheme`, `ramp`, `RAMPS`, `ThemeInput` | theme building blocks; `ThemeInput` is a `Theme` whose `edge.ink` may be left out | | `isSafeCss(value)`, `isSafeLink(url)` | guards for plugin output: a CSS value that cannot leave its attribute, a link that is http(s), mailto, `#` or relative | ## Text measuring Box sizes depend on text width. Node has no fonts, so the core uses `approxMeasure`, a per-character width table. In browsers, `canvasMeasure(font)` measures exactly. Pass your own `measure` to match a specific font: ```ts type Measure = (text: string, fontSize: number, weight: number, mono: boolean) => number; ``` The font usually comes from the theme, which is only known after parsing. `measureFor` builds the measure from the resolved theme, with custom themes and the `font:` setting applied: ```ts render(source, { measureFor: (theme) => canvasMeasure(theme.font) }); ``` ## Constants | export | contents | | -------------------------------------------------- | ------------------------------------------------------------------------------------ | | `THEMES`, `THEME_NAMES`, `getTheme(name, custom?)` | theme objects and names; pass `diagram.themes` to resolve themes defined in the file | | `themeNames(custom?)` | built-in names plus the given custom ones | | `THEME_KEYS` | the keys a `theme` block takes, with descriptions | | `TONES` | tone names | | `SHAPES` | node shape names | | `portOn(box, side, t, spread?, depth?)` | where an edge meets a shape's outline, for `ShapeKind.port` | | `KNOWN_SETTINGS` | setting keys | | `NODE_PROPS`, `EDGE_PROPS`, `GROUP_PROPS` | known prop names per element | | `GUIDE` | the language reference (same as `yuhwa guide`) |