Skip to content

JavaScript API ​

sh
npm install yuhwa
sh
pnpm add yuhwa
ts
import { render } from 'yuhwa';

The package is ESM with TypeScript types. The core has no DOM access and no dependencies.

importcontents
yuhwathe core API below
yuhwa/browserthe core API, plus a browser render, run and the <yuhwa-diagram> element
yuhwa/yuhwa.iife.jsthe browser build for a <script> tag; global Yuhwa
yuhwa/markdown-itmarkdown-it plugin (VitePress, Eleventy, Slidev)
yuhwa/remarkremark plugin (Docusaurus, Vocs, Nextra, Fumadocs, Rspress, MDX)
yuhwa/astroAstro and Starlight integration
yuhwa/satteriSätteri plugin (the Astro 7 Markdown processor), for a hand-built pipeline
yuhwa/vuepressVuePress 2 plugin
yuhwa/ironmarkironmark plugin: renders fences in .md and .mdx at build time or run time
yuhwa/viteVite plugin: import svg from './x.yu'
yuhwa/pluginhelpers and types for writing a plugin, see Writing a plugin
yuhwa/lspthe language service; /server, /browser (Web Worker) and /client, see Language server
yuhwa/style.csslight/dark switching for the docs plugins
yuhwa/zoompan and zoom for the docs plugins; exports zoomable, zoomHeight, zoomScript and installZoom, see Zoom and pan
yuhwa/canvasoutput: 'canvas' for the docs plugins: draws each diagram into a canvas; exports installCanvas, see Output
yuhwa/llms.txtthe 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');
optiondefaultmeaning
scaledevicePixelRatiopixels per SVG unit
canvasa new canvascanvas to draw into
backgroundnonefill 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:

fieldcontents
settings, classestop-level settings and class props
nodes, edges, groups, panelsthe declarations, each with a ref to its source line
layoutthe layout { } overrides
importsresolved paths of imported files, in order
vars$name values, by name without the $
defscomponents: { name, params: { name, default? }[], body }
exportsnames after export, when the file has any
sharedSettingssettings the file exports (export theme: midnight)
datawhat plugin statements parsed, keyed by plugin
diagnosticserrors 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.

functiondoes
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
exportcontents
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
registryplugins, rows, frames and panels (both Maps) and decorations
builtins, shapes, markers, themes, charts, tables, frames, legend, footer, sequence, timeline, chart, git, mindmap, gantt, quadrant, kanban, treeviewthe built-in plugins
YuhwaPlugin, RowKind, RowCtx, RowPaint, FrameKind, Decoration, PanelKind, PanelCtxplugin 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), PanelOptionthe field type of a PanelKind option: select, color, number, flag or text
renderHead, dashFor, lineStyleedge ends and dash patterns, shared with graph edges
joinPath(from, rel)how import paths are resolved, for custom resolvers
parseInline, segsW, renderSegs, tspansinline 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, ThemeInputtheme 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 ​

exportcontents
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_KEYSthe keys a theme block takes, with descriptions
TONEStone names
SHAPESnode shape names
portOn(box, side, t, spread?, depth?)where an edge meets a shape's outline, for ShapeKind.port
KNOWN_SETTINGSsetting keys
NODE_PROPS, EDGE_PROPS, GROUP_PROPSknown prop names per element
GUIDEthe language reference (same as yuhwa guide)

Released under the MIT License.