# Glyphcss — Full Documentation > Glyphcss renders 3D models, Mermaid diagrams and data charts as monospace text for the DOM, chat and terminals. JavaScript libraries, React/Vue bindings and a Node.js CLI. MIT licensed. ## Start here - [Diagrams workbench — Mermaid to text](https://glyphcss.com/diagrams/) - [Charts workbench — ASCII and braille charts](https://glyphcss.com/charts/) - [3D renderer: glyphcss on npm](https://www.npmjs.com/package/glyphcss) - [Diagrams: @glyphcss/diagrams on npm](https://www.npmjs.com/package/@glyphcss/diagrams) - [Charts: @glyphcss/charts on npm](https://www.npmjs.com/package/@glyphcss/charts) - [CLI: @glyphcss/compile on npm](https://www.npmjs.com/package/@glyphcss/compile) — glyphcss diagram graph.mmd; glyphcss chart chart.json - [Agent skill and Claude Code / Codex plugin](https://github.com/apresmoi/glyphcss-diagrams) — npx skills add apresmoi/glyphcss-diagrams - [CLI skill reference](https://glyphcss.com/skill.md) --- # Headless API The `glyphcss` vanilla package exposes a glyph-shaped imperative API plus the raw `@glyphcss/core` math primitives. ## `createGlyphScene` The main entry point. Creates and mounts a scene into a host element and returns a `GlyphSceneHandle` with methods to add meshes, hotspots, and update options. **Always construct a camera first and pass it in.** ```ts import { createGlyphCamera, createGlyphScene } from "glyphcss"; const host = document.querySelector("#scene")!; const camera = createGlyphCamera({ rotX: 25, zoom: 50 }); const scene = createGlyphScene(host, { camera, mode: "solid", // "wireframe" | "solid" | "voxel" | "ink" cols: 100, // grid width in character columns rows: 30, // grid height in character rows cellAspect: 2.0, // cell height ÷ width (typical monospace: ~2.0) glyphPalette: "default", // named glyph palette useColors: true, // emit color s in output directionalLight: { direction: [0.5, 0.7, 0.5], intensity: 1 }, ambientLight: { intensity: 0.4 }, }); ``` ### `.add(polygons, transform?)` Register a `Polygon[]` as a mesh. Returns a `GlyphMeshHandle`. ```ts import { cubePolygons } from "@glyphcss/core"; const meshHandle = scene.add( cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" }), { position: [1, 0, 0], // translate in world space scale: 0.8, // uniform scale (or [sx, sy, sz]) rotation: [0, 45, 0], // XYZ Euler angles in degrees } ); // Later, update the transform and re-render: meshHandle.setTransform({ position: [2, 0, 0] }); scene.rerender(); // Replace the mesh geometry in place: meshHandle.setPolygons(nextPolygons); // Remove the mesh: meshHandle.dispose(); ``` ### `.setOptions(partial)` Update any scene option. Triggers an automatic re-render. ```ts scene.setOptions({ mode: "wireframe", cols: 120, rows: 36, directionalLight: { direction: [1, 0.5, 0.2], intensity: 1.2 }, }); ``` ### `.destroy()` Remove the scene DOM and clear all registered meshes and hotspots. ```ts scene.destroy(); ``` ## End-to-end example The following snippet covers `add`, `setOptions`, `addHotspot`, and `destroy` in one runnable block: ```ts import { createGlyphCamera, createGlyphScene, createGlyphOrbitControls, } from "glyphcss"; import { cubePolygons, octahedronPolygons, axesHelperPolygons } from "@glyphcss/core"; const host = document.querySelector("#scene")!; // 1. Create the camera first. const camera = createGlyphCamera({ rotX: 25, zoom: 50 }); // 2. Create the scene with the camera. const scene = createGlyphScene(host, { camera, mode: "solid", cols: 100, rows: 30 }); // 3. Add meshes. Each call returns a handle. const cubeHandle = scene.add( cubePolygons({ center: [-1, 0, 0], size: 0.8, color: "#4488ff" }) ); const octaHandle = scene.add( octahedronPolygons({ center: [1, 0, 0], size: 0.8, color: "#ffcc44" }) ); scene.add(axesHelperPolygons({ size: 1.5 })); // 4. Add a hotspot. const hotspot = scene.addHotspot( { id: "octa-top", at: [1, 0.8, 0], size: [4, 2] }, () => alert("octahedron top"), ); // 5. Attach orbit controls. const controls = createGlyphOrbitControls(scene, { drag: true, wheel: true }); // 6. Update options at any time. scene.setOptions({ mode: "wireframe" }); // 7. Move a mesh. cubeHandle.setTransform({ position: [-2, 0, 0] }); scene.rerender(); // 8. Cleanup everything. hotspot.remove(); controls.destroy(); octaHandle.dispose(); cubeHandle.dispose(); scene.destroy(); ``` ## Camera factories Two cameras: orthographic (default, `createGlyphCamera`) and perspective. First-person view is `createGlyphPerspectiveCamera` + `createGlyphFirstPersonControls`. ```ts import { createGlyphCamera, createGlyphPerspectiveCamera, createGlyphOrthographicCamera, } from "glyphcss"; // Orthographic — default alias, best for voxel/iso scenes const camera = createGlyphCamera({ rotX: 25, zoom: 50 }); // Orthographic — explicit form const ortho = createGlyphOrthographicCamera({ rotX: 25, zoom: 50 }); // Perspective — foreshortened; required for first-person controls const perspective = createGlyphPerspectiveCamera({ rotX: 25, rotY: 0, distance: 3, zoom: 50, stretch: 0.95, }); // All camera properties are mutable after creation: perspective.rotY = 45; perspective.distance = 4; // Swap the camera on a running scene: scene.setOptions({ camera: ortho }); ``` ## Lower-level pieces `@glyphcss/core` is browser-agnostic (no DOM globals) and can run in Node or a web worker. The rasterizer itself lives in `glyphcss` — it is pure too (geometry + camera → string), it just ships with the renderer rather than with core. ```ts import { icosahedronPolygons } from "@glyphcss/core"; import { buildRasterizeContext, rasterize, projectHotspots, createGlyphPerspectiveCamera, } from "glyphcss"; const polygons = icosahedronPolygons({ center: [0, 0, 0], size: 1, color: "#44ffcc" }); const camera = createGlyphPerspectiveCamera({ rotX: 25, zoom: 50 }); const grid = { cols: 160, rows: 48, cellAspect: 2.0 }; // `RasterizeContextOptions` — `polygons` is required for solid/voxel, and // wireframe edges are derived from it when `wireframe` is omitted. const ctx = buildRasterizeContext({ camera, grid, polygons, mode: "solid" }); // Rasterize one frame to a string: const text = rasterize(ctx); // Project hotspots to grid cells: const cells = projectHotspots( [{ id: "top", at: [0, 1, 0] }], camera, 160, 48, 2.0, ); // cells is { id, col, row, depth, visible }[] ``` `@glyphcss/core` owns the geometry and math — polygon generators (~44 named shapes plus `resolveGeometry`), parsers, mesh ops, and `buildSceneContext({ polygons })` for scene composition. It does not own the rasterizer. ## Static compile `compileScene` renders a scene to its `
` string with **no DOM** — same
defaults as `createGlyphScene`, byte-identical output. The foundation of the
build-time toolchain (see [Compiling to Static](/guides/compile)).

```ts
import { compileScene } from "glyphcss";

const { html, inner, cols, rows } = compileScene({ polygons, cols: 80, rows: 24 });
```

For interactive exports, `buildGlyphInteractiveExport(polygons, { interactions })`
(pure, browser-safe) emits a self-contained snippet shipping only the declared
control + a decimated mesh; `glyphCodepenPrefill` turns it into a CodePen POST.
Mesh simplification is available standalone as `decimatePolygons(polygons, { grid })`
from `@glyphcss/core`.

For a rotation with no runtime, `buildGlyphFramesExport(polygons, options)` bakes
every frame to HTML + CSS and `buildGlyphFramesSvgExport(polygons, options)` to one
SVG that animates as an image. See [Baked rotation](/guides/compile/#baked-rotation).

The Node file pipeline (`loadMeshFromFile`, `compileFile`, the Vite plugin, the
`glyphcss` CLI) lives in `@glyphcss/compile`.


---

# HTML API

`glyphcss/elements` is a side-effect import that registers a set of
`` custom elements with `customElements`. After the import runs,
you can use them in plain HTML — no React, no Vue, no build step required.

## Install

```bash
pnpm add glyphcss
```

```html

```

Or in a bundled app:

```ts
import "glyphcss/elements"; // side-effect — registers customElements
```

Re-imports are idempotent (the module checks `customElements.get` before
defining). In non-DOM environments (SSR, Node) the module silently no-ops.

## Element tree

Camera wraps scene. Attribute names are kebab-case (`rot-x`, `rot-y`,
`hidden-lines`, `auto-size`). Boolean attributes follow standard HTML
convention — present means true.

```html

  
    
    
    
  

```

## Elements

### ``

Root container. Owns the `
` rasterisation output and the lighting state.

| Attribute | Type | Notes |
|---|---|---|
| `mode` | `"wireframe" \| "solid" \| "voxel" \| "ink"` | Default `solid` |
| `cols` | number | Grid width in character columns |
| `rows` | number | Grid height in character rows |
| `cell-aspect` | number | Height ÷ width of the cell (default `2.0`) |
| `glyph-palette` | string | Named palette: `default`, `detail`, `ascii`, `lines`, `blocks`, `dots`, `solid`, `braille`, `runes`, `stars`, `arrows`, `math`, `binary`, `hex` |
| `char-mode` | `"ascii" \| "braille" \| "halfblock" \| "quadrant"` | Character encoding for rasterized output (default `"ascii"`). `"braille"` (wireframe-only) packs a 2×4 subcell dot grid into Unicode Braille Patterns for smoother edges. `"halfblock"` (solid-only) packs two independently colored subcells (top/bottom) into `▀`/`▄`/`█` for 2× vertical color resolution. `"quadrant"` (solid-only) generalizes that to a full 2×2 subcell split (16 possible glyphs) for both shape AND color resolution. Each is a documented no-op outside the mode it applies to |
| `use-colors` | bool | Emit color spans in the output |
| `wireframe-junctions` | flag | Box-drawing junction resolve pass (wireframe + `char-mode="ascii"` only): corners/T-junctions/crossings render from `┌┐└┘├┤┬┴┼─│` instead of a random per-edge glyph |
| `hidden-lines` | `"show" \| "hide"` | Hidden-line removal for wireframe (+ braille) and `ink`. Default `show`. No-op in `solid`, which is already depth-buffered |
| `color-tolerance` | number | Merge adjacent cells into one `` while their colors stay within this redmean distance (range `0`–`765`, not `0`–`255`). Default `0` (off, byte-identical). `NaN`/negative values degrade to `0`; `+Infinity`/`-Infinity` are recognized literally (as strings) and behave the same as the JS surface. No-op under `glyph-output="semantic"` — semantic colors are exact class identifiers, not shaded appearance |
| `glyph-output` | `"visible" \| "semantic"` | Default `visible`. `semantic` needs `sceneManifest` + `dictionary`, which are set as JS **properties** (they are data, not string attributes) |
| `directional-direction` | `"x,y,z"` | Key-light source vector — the direction from the shaded surface *toward* the light. Comma-separated, like ``. Either this or `directional-intensity` configures the light; the other falls back to its default |
| `directional-intensity` | number | Key-light intensity |
| `ambient-intensity` | number | Ambient fill intensity |
| `auto-size` | flag | Auto-fit `cols`/`rows` to the host's box via ResizeObserver |
| `interactive-downscale` | number | Render at `1/n` resolution while dragging, full detail on release (e.g. `2`). Keeps high-density scenes smooth. Default `1` (off) |
| `shadow` | flag | Enable shadow-map pass. Must be present for any shadows to render |
| `shadow-color` | string | Shadow tint hex color (default `"#000000"`) |
| `shadow-opacity` | number | Shadow darkness 0..1 (default `0.25`) |
| `shadow-lift` | number | Depth bias — prevents self-shadow acne (default `0.05`) |
| `shadow-max-extend` | number | Half-extent of the light-space projection volume (default `2000`) |

`solidWeightRamp` (solid-mode-only font-weight density ramp — see the
[render modes guide](/guides/render-modes/#font-weight-density-ramp-solidweightramp))
is a JS property, not an attribute — it is measurement data
(`{ glyph: string; weight: number }[]`), the same "property, not attribute"
rule `sceneManifest`/`dictionary` use: `document.querySelector("glyph-scene").solidWeightRamp = steps`.

### `` / `` / ``

`` is the ergonomic default — an alias for
``. All three accept the same orientation
attributes; perspective additionally accepts `distance`, `perspective`, and `stretch`.

| Attribute | Notes |
|---|---|
| `rot-x` | Pitch in degrees |
| `rot-y` | Yaw in degrees |
| `zoom` | CSS pixels per world unit |
| `distance` | Perspective only — pull-back; CSS pixels with CSS perspective, world units only in legacy `perspective="0"` mode |
| `perspective` | Perspective only — CSS-perspective distance in px (default 32000; `0` = legacy orbit) |
| `stretch` | Perspective only |

### ``

Polygon registration. Picks one source in descending precedence: `geometry`
< `src` < explicit polygons (only available via JS property, not attribute).

| Attribute | Notes |
|---|---|
| `src` | URL of OBJ / GLB / glTF / VOX mesh |
| `geometry` | Built-in name from `@glyphcss/core` registry (`cube`, `dodecahedron`, …) |
| `size` | Uniform size for `geometry` |
| `color` | Fill color for `geometry` |
| `position` | `x,y,z` translation |
| `scale` | `s` or `sx,sy,sz` |
| `rotation` | `rx,ry,rz` XYZ Euler degrees |
| `auto-center` | flag — recenter the mesh's bbox center to the origin so it pivots around its own center (center only) |
| `cast-shadow` | flag — this mesh casts shadows onto `receive-shadow` surfaces |
| `receive-shadow` | flag — this mesh displays shadows from `cast-shadow` meshes. Present on both = self-shadow |
| `density` | number — render this mesh at `density`× the scene resolution, in its own `
` (see the [Density & Detail guide](/guides/density/)) |
| `font-size` | explicit cell size (px or CSS length); overrides `density` |
| `line-height` | explicit cell line-height; overrides `density` |
| `transparent` | flag — see-through: doesn't occlude / isn't occluded |
| `mode` | `"wireframe" \| "solid" \| "voxel" \| "ink"` — render this mesh in its OWN mode, in its own `
`, when it differs from the scene's (see the [Density & Detail guide](/guides/density/)). An unrecognized value is ignored |

### ``

3D-anchored DOM hotspot. Child nodes are positioned at the projected screen
cell every render.

| Attribute | Notes |
|---|---|
| `hotspot-id` | Identifier for handle lookup |
| `at` | `x,y,z` anchor in world space |
| `size` | `w,h` in cells |

### ``

Mounts a retained appearance program inside ``. The executable
definition is a JavaScript value, so use the atomic property API rather than a
JSON attribute:

```ts
import { GlyphEffects } from "@glyphcss/effects";

const effect = document.querySelector("glyph-effect-layer")!;
effect.configure({
  effect: GlyphEffects.matrixRain,
  params: { glyphs: "HOLA", speedMin: 5, speedMax: 12 },
});
const handle = await effect.whenReady();
handle.params.time = performance.now() / 1000;
```

Attributes `target="surfaces|viewport"`, `blend="over|replace"`, `opacity`,
`order`, and `enabled="false"` override the matching configured option. The
element emits `glyphcss:effect-ready` and exposes `getEffectHandle()`. See
[Glyph Effects](/guides/effects) for the catalog, clocks, and current runtime
boundary.

### `` / ``

Camera controls. Orbit rotates around the target; map pans across the
target plane.

| Attribute | Notes |
|---|---|
| `drag` | flag — enable drag |
| `wheel` | flag — enable wheel zoom |
| `invert` | flag or number — invert axis multiplier |
| `pitch-range` | Orbit, turntable mode only: `"min,max"` degrees (default `-90,90`), or `"none"` for unrestricted tumbling past either pole |
| `mode` | Orbit-only: `turntable` (default) \| `trackball` — trackball rotates about the screen axis perpendicular to the drag, reaching any orientation including roll |
| `animate-speed` | Orbit-only: auto-rotation speed |
| `animate-axis` | Orbit-only: `x` \| `y` |

### ``

First-person camera (requires a ``). Pointer-lock
mouselook, WASD/arrow move, Space jump, Ctrl crouch.

| Attribute | Notes |
|---|---|
| `look-enabled` / `move-enabled` / `jump-enabled` / `crouch-enabled` | flags — toggle each axis |
| `look-sensitivity` | degrees per pixel (default `0.15`) |
| `invert-y` | flag — invert vertical look |
| `move-speed` / `jump-velocity` / `gravity` | world-unit motion params |
| `eye-height` / `crouch-height` / `ground-z` | world-unit placement |
| `min-pitch` / `max-pitch` | pitch clamp (degrees) |

## Scene-ready handshake

Custom elements register asynchronously. If you need to call imperative
methods on the scene from JavaScript, listen for `glyphcss:scene-ready` on
the `` element:

```ts
const sceneEl = document.querySelector("glyph-scene")!;
sceneEl.addEventListener("glyphcss:scene-ready", (ev) => {
  const scene = (ev.target as any).getScene();
  scene.addHotspot({ id: "runtime", at: [0, 0, 1] }, () => alert("clicked"));
});
```

## End-to-end example

```html


  
    
    
  
  
    
      
        
        
        
          top
        
      
    
  

```

## See also

- [React API](/api/react) — same elements, JSX form
- [Vue API](/api/vue) — same elements, idiomatic Vue
- [Headless API](/api/headless) — the imperative factory the elements wrap


---

# React API

`@glyphcss/react` is the React binding for the ASCII paint backend. It is a
thin layer over the imperative `glyphcss` factory API — components register
meshes / hotspots / cameras with the surrounding ``; nothing
re-renders per frame.

The React surface mirrors the Vue surface one-to-one. Anything you can do
in React you can do in Vue, with the same option names and defaults.

## Install

```bash
pnpm add @glyphcss/react
```

## Component tree

A scene is always **camera-wraps-scene**. The camera component owns the
projection state; `` rasterises into a `
`; meshes, controls
and hotspots are children of the scene.

```tsx

  
    
    
    
  

```

## Components

| Component | Role |
|---|---|
| [``](/components/glyph-scene) | Root container — owns the `
`, grid, glyph palette, lighting |
| `` | SSR/SSG — renders the compiled `
` with no runtime ([Compiling to Static](/guides/compile)) |
| `` | Default camera (alias for ``) |
| `` | Foreshortened projection — needs a `distance` |
| `` | Parallel projection — best for iso / voxel scenes |
| `` | Polygon registration. Pass `polygons={…}`, `src="…"`, or `geometry="cube"` |
| [``](/guides/effects) | Scene-root retained appearance layer; exposes its stable core handle through a ref |
| `` | Horizontal ground plane. `receiveShadow` defaults to `true`; `castShadow` defaults to `false` |
| `` | 3D-anchored DOM hotspot — projects to a screen cell |
| `` | Drag-rotate + wheel-zoom around the target |
| `` | Drag-pan + wheel-zoom across the target plane |
| `` | WASD + pointer-lock first-person camera |
| `` | Renders world axes as a mesh |
| `` | Visualises the directional light vector |

## Hooks

| Hook | Returns |
|---|---|
| `useGlyphSceneContext()` | The scene + camera handles available to any descendant of `` |
| `useGlyphCamera()` | The camera handle from the surrounding camera component |
| `useGlyphMesh(polygons, options?)` | Imperative handle for a mesh (lower-level than ``) |
| `useGlyphAnimation(opts)` | Drive a `GlyphAnimationClip` from a mesh handle |

## `` shortcuts

`` accepts three mutually-exclusive geometry inputs, in
descending precedence:

```tsx
// 1. Explicit polygons — full control


// 2. File URL — fetched + parsed by the runtime (OBJ / GLB / glTF / VOX)


// 3. Built-in geometry name — resolves via @glyphcss/core registry

```

The transform props (`position`, `scale`, `rotation`) apply to whichever
source you pick. `rotation` is an XYZ Euler triple in degrees.

Shadow props on ``:

| Prop | Type | Default | Description |
|---|---|---|---|
| `castShadow` | `boolean` | `false` | This mesh casts shadows onto `receiveShadow` surfaces |
| `receiveShadow` | `boolean` | `false` | This mesh displays shadows from `castShadow` meshes. A mesh that is both casts and receives self-shadows |

Detail / density props on `` (see the [Density & Detail guide](/guides/density/)):

| Prop | Type | Default | Description |
|---|---|---|---|
| `density` | `number` | `1` | Render this mesh at `density`× the scene resolution, in its own `
` |
| `fontSize` | `number \| string` | — | Explicit cell size (px or CSS length). Overrides `density` |
| `lineHeight` | `number` | — | Explicit cell line-height. Overrides `density` |
| `transparent` | `boolean` | `false` | See-through: doesn't occlude / isn't occluded |

Shadow prop on ``:

| Prop | Type | Default | Description |
|---|---|---|---|
| `shadow` | `GlyphShadowOptions` | `undefined` | Shadow-map config. `undefined` = shadows off. See [`GlyphShadowOptions`](/api/types#shadows) |

## End-to-end example

```tsx
import {
  GlyphPerspectiveCamera,
  GlyphScene,
  GlyphMesh,
  GlyphHotspot,
  GlyphOrbitControls,
  GlyphAxesHelper,
} from "@glyphcss/react";

const directionalLight = { direction: [0.5, 0.7, 0.5], intensity: 1 };
const ambientLight = { intensity: 0.4 };

export function App() {
  return (
    
      
        
        
        
          
            top
          
        
      
    
  );
}
```

## Re-exports from `@glyphcss/core`

`@glyphcss/react` re-exports a curated slice of `@glyphcss/core` — the polygon
factories (`cubePolygons`, `dodecahedronPolygons`, …), the `resolveGeometry`
registry, the math primitives, and the mesh parsers (`loadMesh`, `parseObj`,
`parseGltf`, `parseVox`, `parseStl`). It is not the *whole* surface: mesh ops
such as `decimatePolygons`, `dedupeOverlappingPolygons` and `recenterPolygons`,
plus the quaternion helpers, are only in `@glyphcss/core` — import those from
there directly.

## See also

- [Vue API](/api/vue) — same surface, idiomatic Vue
- [HTML API](/api/html) — `` custom elements
- [Headless API](/api/headless) — the imperative factory the bindings wrap


---

# Three.js Parity API

The `*/three` subpaths expose a Three-like authoring surface on top of glyphcss.
Use them when you are porting a Three.js scene, writing docs for coding agents,
or want familiar `PerspectiveCamera`, `Object3D`, `Vector3`, `lookAt`, and
radian-based mesh transforms.

This is still glyphcss: it rasterises polygons into a character grid. It does
not run Three.js at runtime, and it does not use WebGL. The parity API only
matches Three's parameter surface closely enough that the same scene math frames
the same object with the same projection, orientation, depth ordering, and light
direction/color/intensity.

## Imports

| Package | Import | Use |
|---|---|---|
| Core math | `@glyphcss/core/three` | Three-like classes and coordinate transforms |
| Vanilla / static | `glyphcss/three` | Core parity surface plus `compileScene`, `loadMesh`, and geometry helpers |
| React | `@glyphcss/react/three` | React components and parity classes |
| Vue | `@glyphcss/vue/three` | Vue components and parity classes |

## Conventions

The native glyphcss API uses glyphcss/voxcss conventions: Z-up scene math, camera
rotations in degrees, and `zoom` as CSS pixels per world unit.

The `*/three` subpaths intentionally use Three-style conventions:

| Value | `*/three` convention |
|---|---|
| Coordinates | Y-up authoring space |
| Mesh rotations | Radians, XYZ Euler |
| Cameras | Three-like `PerspectiveCamera(fov, aspect, near, far)` and `OrthographicCamera(left, right, top, bottom, near, far)` |
| Camera targeting | `camera.position.set(...)` + `camera.lookAt(...)` |
| Directional lights | Source vector from `light.target.position` toward `light.position`; color and intensity are preserved |
| Ambient lights | Color and intensity are preserved |

Internally, geometry is converted into glyphcss space with
`transformPolygonsToGlyph`. The axis conversion is right-handed, so polygon
winding and Lambert lighting stay correct.

GlyphCSS native directional lights store the source vector from the shaded
surface toward the distant light. `DirectionalLight.toGlyphDirectionalLight()`
converts the Three.js source/target pair into that native convention and
preserves the light color and intensity unchanged.
`AmbientLight.toGlyphAmbientLight()` also preserves color and intensity
unchanged.

Polygon arrays passed to `transformPolygonsToGlyph` or `` are
interpreted as Three/Y-up coordinates. If you already have native glyphcss
polygons with their own native transform, render them with the native API instead
of converting them again.

## Static / vanilla example

`glyphcss/three` is the smallest path for build-time output, tests, CLIs, and
agent-generated snippets. The scene below is authored with Three-like camera and
transform objects, then rendered by `compileScene`.

```ts
import {
  AmbientLight,
  DirectionalLight,
  Object3D,
  PerspectiveCamera,
  Vector3,
  compileScene,
  cubePolygons,
  transformPolygonsToGlyph,
} from "glyphcss/three";

const camera = new PerspectiveCamera(50, 16 / 9, 0.1, 100);
camera.position.set(3, 2, 5);
camera.lookAt(0, 0, 0);

const object = new Object3D();
object.position.set(0, 0.5, 0);
object.rotation.set(0, Math.PI / 4, 0);
object.scale.set(1, 1, 1);

const light = new DirectionalLight("#ffffff", 1);
light.position.set(3, 5, 4);
light.target.position.set(0, 0, 0);

const polygons = transformPolygonsToGlyph(
  cubePolygons({ center: [0, 0, 0], size: 1, color: "#66aaff" }),
  object,
);

const { html } = compileScene({
  polygons,
  camera,
  cols: 96,
  rows: 36,
  cellAspect: 2,
  mode: "solid",
  useColors: true,
  ambientLight: new AmbientLight("#ffffff", 0.35).toGlyphAmbientLight(),
  directionalLight: light.toGlyphDirectionalLight(),
});
```

## React example

The React parity components wrap the normal ``. Keep the scene and
controls from `@glyphcss/react`, and import the Three-like cameras / meshes from
`@glyphcss/react/three`.

```tsx
import { GlyphOrbitControls, GlyphScene } from "@glyphcss/react";
import {
  DirectionalLight,
  GlyphThreeMesh,
  GlyphThreePerspectiveCamera,
} from "@glyphcss/react/three";

const sun = new DirectionalLight("#ffffff", 1);
sun.position.set(3, 5, 4);
sun.target.position.set(0, 0, 0);

export function App() {
  return (
    
      
        
        
      
    
  );
}
```

`` accepts the same mesh source shortcuts as native
``: `polygons`, `src`, or `geometry`. It also supports
`castShadow`, `receiveShadow`, `density`, `fontSize`, `lineHeight`, and
`transparent`.

## Vue example

Vue mirrors the React parity surface.

```vue



```

## Core exports

All `*/three` subpaths share these core exports:

| Export | Purpose |
|---|---|
| `Vector3` | Minimal Three-like vector class used by cameras, objects, and lights |
| `Euler` | XYZ Euler rotation in radians |
| `Object3D` | `position`, `rotation`, `scale`, `up`, `lookAt`, and `localToWorld` |
| `PerspectiveCamera` | Three-like perspective camera that glyphcss can render with |
| `OrthographicCamera` | Three-like orthographic camera that glyphcss can render with |
| `DirectionalLight` | Three-like positioned light with `target`, convertible to glyphcss light options |
| `AmbientLight` | Ambient light helper, convertible to glyphcss light options |
| `threeToGlyphPoint` / `glyphToThreePoint` | Convert individual points between coordinate spaces |
| `threeToGlyphDirection` / `glyphToThreeDirection` | Convert direction vectors between coordinate spaces |
| `transformPointToGlyph` | Apply an `Object3D` transform to one point and convert it |
| `transformPolygonsToGlyph` | Apply an `Object3D` transform to a `Polygon[]` and convert it |

## When not to use it

Use the native API when you are building glyphcss-first scenes, voxel/diagram
views, or examples where degree-based `rotX` / `rotY` camera controls are more
direct. The parity API is for Three-shaped scene authoring and ports; it is not a
replacement for native glyphcss controls or custom elements.


---

# Core Types

All types below are exported from `@glyphcss/core` unless marked with `glyphcss`
(the vanilla package).

## Geometry primitives

| Type | Description | Used in |
|---|---|---|
| `Vec2` | `[u, v]` tuple — UV coordinates | `TextureTriangle.uvs`, polygon UVs |
| `Vec3` | `[x, y, z]` tuple — world-space point or vector | Vertices, directions, hotspot anchors |
| `Polygon` | N coplanar vertices + optional color/texture | Helper generators, mesh parsers |
| `TextureTriangle` | 3 vertices + 3 UV pairs + optional color | Parser-internal type for UV-mapped meshes |
| `WireframeEdge` | `from`/`to` Vec3 pair + optional weight/color | `buildRasterizeContext` wireframe mode (`glyphcss`) |

```ts
type Vec2 = [number, number];
type Vec3 = [number, number, number];

interface Polygon {
  vertices: Vec3[];
  color?: string;
  texture?: string;
  uvs?: Vec2[];
}

interface TextureTriangle {
  vertices: [Vec3, Vec3, Vec3];
  uvs: [Vec2, Vec2, Vec2];
  color?: string;
}

interface WireframeEdge {
  from: Vec3;
  to: Vec3;
  weight?: EdgeWeight;  // 1 | 2 | 3
  color?: string;
}
```

## Render mode and glyph mapping

| Type | Description | Used in |
|---|---|---|
| `RenderMode` | `"wireframe" \| "solid" \| "voxel" \| "ink"` | `RasterizeContextOptions.mode`, all framework props |
| `CharRamp` | `string[]` — index 0 = darkest, last = brightest | Solid-mode Lambert → glyph mapping |
| `EdgeWeight` | `1 \| 2 \| 3` — thin / normal / core | `WireframeEdge.weight` |

```ts
type RenderMode = "wireframe" | "solid" | "voxel" | "ink";
type CharRamp = string[];          // e.g. [" ", ".", ":", "-", "=", "+", "*", "#", "%", "@"]
type EdgeWeight = 1 | 2 | 3;
```

## Lighting

| Type | Description | Used in |
|---|---|---|
| `GlyphDirectionalLight` | Single distant light source | `GlyphSceneOptions.directionalLight` |
| `GlyphAmbientLight` | Uniform fill light | `GlyphSceneOptions.ambientLight` |

```ts
interface GlyphDirectionalLight {
  direction: Vec3;     // source vector from surface toward the distant light
  intensity?: number;  // default 1
  color?: string;      // hex, default white
}

interface GlyphAmbientLight {
  intensity?: number;  // default 0.4
  color?: string;      // hex, default white
}
```

## Shadows

| Type | Description | Used in |
|---|---|---|
| `GlyphShadowOptions` | Shadow-map configuration. `undefined` on the scene = shadows off | `GlyphSceneOptions.shadow`, `` |

```ts
interface GlyphShadowOptions {
  color?: string;      // shadow tint hex; default "#000000"
  opacity?: number;    // darkness 0..1 toward color; default 0.25
  lift?: number;       // depth bias — prevents self-shadow acne; default 0.05
  maxExtend?: number;  // accepted but NOT READ — the volume is fitted to the casters' own bounds
}
```

Shadow flags on meshes (`GlyphMeshTransform`, ``, ``):

| Field / prop / attribute | Default | Description |
|---|---|---|
| `castShadow` / `cast-shadow` | `false` | This mesh casts shadows onto `receiveShadow` surfaces |
| `receiveShadow` / `receive-shadow` | `false` | This mesh receives shadows. Both flags on the same mesh = self-shadow |

`GlyphGround` sets `receiveShadow=true` and `castShadow=false` by default.

Detail / density on meshes (`GlyphMeshTransform`, ``, ``) — see the [Density & Detail guide](/guides/density/):

| Field / prop / attribute | Type | Default | Description |
|---|---|---|---|
| `density` | `number` | `1` (shared grid) | Render this mesh at `density`× the scene resolution, in its own `
` |
| `fontSize` / `font-size` | `number \| string` | — | Explicit cell size (px or CSS length). Overrides `density` |
| `lineHeight` / `line-height` | `number` | — | Explicit cell line-height. Overrides `density` |
| `transparent` | `boolean` | `false` | See-through: doesn't occlude / isn't occluded (pops into its own `
`) |

Browser-only (detail layers measure the live cell size); works with any camera (orthographic, perspective, FPV).

## Grid and scene

| Type | Description | Used in |
|---|---|---|
| `GridSize` | `{ cols, rows, cellAspect }` | `buildRasterizeContext`, camera `project()` |
| `SceneContext` | Normalized polygons + scene bbox + warnings | The `.context` field of `buildSceneContext({ polygons })`'s `SceneContextBuildResult`. The rasterizer takes `RasterizeContext` from `buildRasterizeContext`, not this |

```ts
interface GridSize {
  cols: number;
  rows: number;
  cellAspect: number;  // cellH / cellW — typically ~2.0
}
```

## Hotspots

| Type | Description | Used in |
|---|---|---|
| `Hotspot` | A 3D anchor that projects to a 2D hitbox | `scene.addHotspot()`, `projectHotspots()` |
| `HotspotCell` | Projected result for one frame | `projectHotspots()` return value |

```ts
interface Hotspot {
  id: string;
  at: Vec3;
  size?: [number, number];  // cols × rows in cells; default [1, 1]
}

interface HotspotCell {
  id: string;
  col: number;
  row: number;
  depth: number;    // camera-space Z; use for z-index
  visible: boolean; // false when behind camera or off-grid
}
```

## Parse results

| Type | Description | Used in |
|---|---|---|
| `ParseResult` | Unified output of all polygon-emitting parsers | `parseObj`, `parseGltf`, `loadMesh` |
| `ParseAnimationClip` | Metadata for one animation in a glTF file | `ParseResult.animation.clips` |

```ts
interface ParseResult {
  polygons: Polygon[];
  animation?: ParseAnimationController;
  objectUrls: string[];
  dispose: () => void;    // revoke blob URLs — always call on unmount
  warnings: string[];
  metadata?: {
    triangleCount?: number;
    meshes?: string[];
    materials?: string[];
    animations?: ParseAnimationClip[];
    sourceBytes?: number;
  };
}

interface ParseAnimationClip {
  index: number;
  name: string;
  duration: number;   // seconds
  channelCount: number;
}
```

## Animation

| Type | Description | Used in |
|---|---|---|
| `GlyphAnimationMixer` | Drives one or more animation actions against a mesh target | `createGlyphAnimationMixer()` |
| `GlyphAnimationAction` | Per-clip playback state | `mixer.clipAction()` |

```ts
// Minimal usage — requires a glTF/GLB file with embedded animation clips.
// Replace "/character.glb" with the path to your own animated mesh.
import { createGlyphAnimationMixer, LoopRepeat, loadMesh } from "@glyphcss/core";

const { polygons, animation } = await loadMesh("/character.glb");
const mixer = createGlyphAnimationMixer(meshHandle, animation!);

const action = mixer.clipAction("walk");
action.setLoop(LoopRepeat, Infinity).play();

// In your animation loop (requestAnimationFrame):
mixer.update(deltaSeconds);
```


---

# Vue API

`@glyphcss/vue` is the Vue 3 binding for the ASCII paint backend. It mirrors
the React surface one-to-one — same component names, same prop shapes, same
defaults — with idiomatic Vue equivalents (composables in place of hooks,
`` for hotspot children, kebab-case attributes in templates).

## Install

```bash
pnpm add @glyphcss/vue
```

## Component tree

Camera wraps scene. Meshes, controls and hotspots are children of the
scene. Template attributes are kebab-case (`:rot-x`, `:rot-y`, `:auto-center`).

```vue

  
    
    
    
  

```

## Components

| Component | Role |
|---|---|
| [``](/components/glyph-scene) | Root container — owns the `
`, grid, glyph palette, lighting |
| `` | SSR/SSG — renders the compiled `
` with no runtime ([Compiling to Static](/guides/compile)) |
| `` | Default camera (alias for ``) |
| `` | Foreshortened projection — needs a `distance` |
| `` | Parallel projection — best for iso / voxel scenes |
| `` | Polygon registration. Pass `:polygons="…"`, `src="…"`, or `geometry="cube"` |
| [``](/guides/effects) | Scene-root retained appearance layer; exposes its stable core handle through a template ref |
| `` | Horizontal ground plane. `receive-shadow` defaults to `true`; `cast-shadow` defaults to `false` |
| `` | 3D-anchored DOM hotspot — projects to a screen cell |
| `` | Drag-rotate + wheel-zoom around the target |
| `` | Drag-pan + wheel-zoom across the target plane |
| `` | WASD + pointer-lock first-person camera |
| `` | Renders world axes as a mesh |
| `` | Visualises the directional light vector |

## Composables

| Composable | Returns |
|---|---|
| `useGlyphSceneContext()` | The scene + camera handles available to any descendant of `` |
| `useGlyphMesh(polygons, options?)` | Register a polygon list with the parent scene; returns `{ meshRef, loading }`. Accepts a plain array or a `ref`, and disposes the mesh on unmount |
| `useGlyphCamera()` | The camera handle from the surrounding camera component |
| `useGlyphAnimation(opts)` | Drive a `GlyphAnimationClip` from a mesh handle |

## `` shortcuts

`` accepts three mutually-exclusive geometry inputs, in descending
precedence: explicit `:polygons`, `src` URL, or `geometry` name.

```vue








```

`rotation` is an XYZ Euler triple in degrees, passed as `:rotation="[x, y, z]"`.

Shadow props on ``:

| Prop | Type | Default | Description |
|---|---|---|---|
| `cast-shadow` | `boolean` | `false` | This mesh casts shadows onto `receive-shadow` surfaces |
| `receive-shadow` | `boolean` | `false` | This mesh displays shadows from `cast-shadow` meshes. A mesh that is both casts and receives self-shadows |

Detail / density props on `` (see the [Density & Detail guide](/guides/density/)):

| Prop | Type | Default | Description |
|---|---|---|---|
| `density` | `number` | `1` | Render this mesh at `density`× the scene resolution, in its own `
` |
| `font-size` | `number \| string` | — | Explicit cell size (px or CSS length). Overrides `density` |
| `line-height` | `number` | — | Explicit cell line-height. Overrides `density` |
| `transparent` | `boolean` | `false` | See-through: doesn't occlude / isn't occluded |

Shadow prop on ``:

| Prop | Type | Default | Description |
|---|---|---|---|
| `:shadow` | `GlyphShadowOptions` | `undefined` | Shadow-map config. `undefined` = shadows off. See [`GlyphShadowOptions`](/api/types#shadows) |

## End-to-end example

```vue



```

## Re-exports from `@glyphcss/core`

`@glyphcss/vue` re-exports a curated slice of `@glyphcss/core` — the polygon
factories (`cubePolygons`, `dodecahedronPolygons`, …), the `resolveGeometry`
registry, the math primitives, and the mesh parsers (`loadMesh`, `parseObj`,
`parseGltf`, `parseVox`, `parseStl`). It is not the *whole* surface: mesh ops
such as `decimatePolygons`, `dedupeOverlappingPolygons` and `recenterPolygons`,
plus the quaternion helpers, are only in `@glyphcss/core` — import those from
there directly.

## See also

- [React API](/api/react) — same surface, idiomatic React
- [HTML API](/api/html) — `` custom elements
- [Headless API](/api/headless) — the imperative factory the bindings wrap


---

# 3D text charts: surfaces, scatter, bars, and lines

`@glyphcss/charts/3d` builds a mark, and `renderGlyphChart3d(mark, options)` turns it into text. Drag any chart to turn it; `[ Code ]` shows the exact call.

```sh
npm install @glyphcss/charts glyphcss
```

## Surface



```ts
import { glyphChartSurface, renderGlyphChart3d } from "@glyphcss/charts/3d";

const mark = glyphChartSurface({
  z: [
    [1, 1.02, 1.11, 1.48, 2.25, 2.94, 3.3, 3.43, 3.1, 2.41, 1.72, 1.28],
    [1, 1.02, 1.11, 1.48, 2.25, 2.94, 3.3, 3.43, 3.1, 2.41, 1.72, 1.28],
    [1, 1.02, 1.11, 1.48, 2.25, 2.94, 3.3, 3.43, 3.1, 2.41, 1.72, 1.28],
    [1, 1.02, 1.11, 1.48, 2.25, 2.94, 3.3, 3.43, 3.1, 2.41, 1.72, 1.28],
    [1, 1.02, 1.11, 1.48, 2.25, 2.94, 3.3, 3.43, 3.1, 2.41, 1.72, 1.28],
    [1, 1.01, 1.05, 1.21, 1.56, 1.93, 2.21, 2.33, 2.16, 1.77, 1.4, 1.16],
    [1, 1.01, 1.05, 1.21, 1.56, 1.93, 2.21, 2.33, 2.16, 1.77, 1.4, 1.16]
  ]
}, {
  x: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22],
  y: [1, 2, 3, 4, 5, 6, 7]
}, {
  axes: {
    x: {
      title: "Hour",
      ticks: 4
    },
    y: {
      title: "Day",
      ticks: 4
    },
    z: {
      title: "k req",
      ticks: 3
    }
  }
});
const { text } = renderGlyphChart3d(mark, {
  target: "web",
  width: 88,
  height: 34,
  charset: "braille"
});
console.log(text);
```

```text
       k req                                                                            
                                                                                        
       ⡄                                                                                
       ⡇                                      ⣀⣤⣤⣀⣀                                     
       ⡇                                 ⣀⣠⣴⣶⣿⠿⠞⠛⠉⠉⢧⡀                                   
3      +                           6⣀⣤⣴⣾⡿⠟⠛⠉⠉⢯⡉⠙⠒⠲⠤⢤⣳⣄                                  
       ⡇                     ⢀⣀⣤⣴⣶⣿⡿⠟⠋⠉⢯⡉⠓⠲⠤⢤⣀⣳⡄⢀⣠⠴⠚⠉⢻⣧⡀⣀⣠⡴⣖⣦⣤⣄                         
       ⡇                4⣀⣤⣴⣾⣿⢿⠟⠛⠻⡗⠒⠦⠤⣄⣀⡳⡄⢀⣀⡤⠴⠚⠻⡿⢤⡀   ⢧⠙⣿⠿⣟⣉⣁⣀⣈⠳⣄                       
       ⡇              ⣠⣴⢿⠋⠉⢻⡓⠒⠦⠤⢤⣀⣙⢦ ⣀⣠⠴⠛⠻⡿⣄⡀   ⢳ ⠉⠓⠦⣄⠈⣇ ⠳⣄ ⣀⣠⠬⠟⠛⢳⡀                     
       ⡇    2       ⢀⡞⠉⡴⠋⡼⣡⣞⡽⣄  ⣀⣠⠼⠛⢿⢧⣀   ⢹⡀⠙⠲⢤⡀⠈⣇   ⠈⢙⣺⣦⡖⠚⢻⡓⠲⠤⣄⣀ ⢳⡀         3.6█       
2      +           ⢠⣾⠴⠋⡄⡾⠛⠉⣡⠞⡟⣶⣏⠁   ⠘⡆⠈⠓⠦⣄ ⢳   ⠉⠳⢼⣄⡤⠖⠚⠉ ⠹⡝⠲⣄⡳⡄  ⠈⣉⡽⠷⡄           █       
       ⡇          ⣠⠿⠛⠉⠗⠿⠁⡴⠚⠁⡞⡞⣽⡎⠙⠦⣄⡀ ⢹   ⠈⠙⠮⣧⣠⠤⠖⠋⠉⢻⡓⢦⣀   ⢳  ⠙⢻⣤⣖⣋⠁  ⠹⣄      2.95▛       
       ⡇       ⢀⣠⣴⠷ ⠞⠁⠼⡵⡋⡤⠶⠛⠉⠉⠋⠹⡄  ⠙⠲⣌⣇⢀⣠⠤⠖⠋⠙⣟⠦⣄   ⢧ ⠈⠓⠦⣄⠈⢧ ⣠⠏⠘⣆⠈⠉⠓⠲⠤⢼⣆         ▛       
       ⡇  ⢀⣠⡴+⣟⡛⣹⣿⣚⣡⡤⠾⠛⠉⠉⠉      ⢳⡀⣀⣠⠴⠒⠻⡿⢤⣀   ⠸⡄⠈⠙⠲⣄⡈⣇   ⠈⣙⣺⣾⠥⢤⣀⣘⣆⣠⠤⠖⠚⠉⠉⠳⡄    2.3▀       
       ⢧⣶⡿⠛⣒⣲⣶⣿⣿⣿⠿⠋⠛⠉            ⢿⢧⣀   ⢹⡀⠈⠙⠦⣄⡀⢹⡀   ⣙⣺⣦⣖⡚⠉⠁ ⠘⣆  ⢠⠏⠻⡍⠉⠙⠒⠒⢲⣽⡦      ▀       
1      +⠈⠙⠻⢿⣒⠚⠋⠉                 ⠘⡆⠈⠓⠦⣄ ⢳    ⠉⣓⣷⣴⡒⠋⠁ ⠘⣆⠉⠙⠒⠦⢤⣈⣧⢠⢏⣀⣀⣹⠦⠴⠒⠋⠉    1.65▘       
            ⠈⠉⠓+⣄⡀                ⢹⡀  ⠈⠙⠮⣧⣠⠴⠒⠋⠁⠈⢧⠉⠙⠲⢤⣀⡘⣆  ⣀⣠⠴⠛⠉⠉                ▘       
                 ⠉⠓⠦⢤⣀             ⢧⣠⠤⠖⠚⠉⠉⢯⠙⠒⠦⣄⣀⠈⢧  ⢀⣀⡭⠿⠒⠋⠁                    1        
                     ⠈+⠲⢤⣀⡀        ⠈⢯⠓⠲⢤⣀⡀⠈⢧   ⢈⣩⠿⠓⠋⠉                                   
      0                   ⠉⠓⠦⣄⡀     ⠈⢧   ⠉⢙⣺⡧⠴⠚⠉                                        
              5              +⠉⠓⠲⢤⣀  ⠈⠧⠴⠒⠋⠉                                             
                                  ⠈⠙+⢤⣀                                                 
                    10                                                                  
                                            Hour                                        
                           15                                                           
                                  20                                                    
```



`glyphChartSurface({ z }, channels?, options?)` takes a row-major grid; `x`/`y` channels place the columns and rows. Here: requests per hour across a week.

## Scatter



```ts
import { glyphChartScatter3d, renderGlyphChart3d } from "@glyphcss/charts/3d";

const mark = glyphChartScatter3d([
  {
    x: -0.9,
    y: 1.1,
    z: 5.6,
    group: "Search"
  },
  {
    x: 3.5,
    y: 2.7,
    z: 4.7,
    group: "Search"
  },
  {
    x: 2.8,
    y: 0.7,
    z: 8,
    group: "Search"
  },
  {
    x: 2.5,
    y: 3.2,
    z: 6.1,
    group: "Search"
  },
  {
    x: 1.2,
    y: 3.2,
    z: 6.9,
    group: "Search"
  },
  {
    x: 1.9,
    y: 2.3,
    z: 7.2,
    group: "Search"
  },
  {
    x: 2,
    y: 2.2,
    z: 6.5,
    group: "Search"
  },
  {
    x: 1.9,
    y: 2,
    z: 5.8,
    group: "Search"
  },
  {
    x: 1.8,
    y: 0.9,
    z: 6.3,
    group: "Search"
  },
  {
    x: 0.2,
    y: 1.7,
    z: 6.2,
    group: "Search"
  },
  {
    x: 1.3,
    y: 2.8,
    z: 5.8,
    group: "Search"
  },
  {
    x: 1.9,
    y: 2.1,
    z: 6.5,
    group: "Search"
  },
  {
    x: 2,
    y: 1.4,
    z: 6.3,
    group: "Search"
  },
  {
    x: 1.5,
    y: 1.3,
    z: 7.6,
    group: "Search"
  },
  {
    x: 6.6,
    y: 3.6,
    z: 3,
    group: "Checkout"
  },
  {
    x: 6.6,
    y: 1.1,
    z: 2.5,
    group: "Checkout"
  },
  {
    x: 4.7,
    y: 3,
    z: 2.4,
    group: "Checkout"
  },
  {
    x: 5.6,
    y: 2.8,
    z: 3.8,
    group: "Checkout"
  },
  {
    x: 5.2,
    y: 3,
    z: 2.7,
    group: "Checkout"
  },
  {
    x: 5.6,
    y: 2.4,
    z: 1.9,
    group: "Checkout"
  },
  {
    x: 6.6,
    y: 3.1,
    z: 4.1,
    group: "Checkout"
  },
  {
    x: 5.9,
    y: 3.8,
    z: 3.6,
    group: "Checkout"
  },
  {
    x: 7,
    y: 3.8,
    z: 2.2,
    group: "Checkout"
  },
  {
    x: 5.4,
    y: 3.4,
    z: 2.4,
    group: "Checkout"
  },
  {
    x: 6,
    y: 2.6,
    z: 2.5,
    group: "Checkout"
  },
  {
    x: 6.8,
    y: 2.1,
    z: 3.2,
    group: "Checkout"
  },
  {
    x: 7.1,
    y: 2.6,
    z: 2.5,
    group: "Checkout"
  },
  {
    x: 4.8,
    y: 2.5,
    z: 2,
    group: "Checkout"
  },
  {
    x: 4.1,
    y: 6.4,
    z: 2.9,
    group: "Profile"
  },
  {
    x: 5.2,
    y: 6.5,
    z: 3.3,
    group: "Profile"
  },
  {
    x: 2.8,
    y: 7.3,
    z: 3.9,
    group: "Profile"
  },
  {
    x: 3.7,
    y: 6.5,
    z: 3.1,
    group: "Profile"
  },
  {
    x: 3.5,
    y: 6,
    z: 4.3,
    group: "Profile"
  },
  {
    x: 2.8,
    y: 8.5,
    z: 4.1,
    group: "Profile"
  },
  {
    x: 4.6,
    y: 6.2,
    z: 4.1,
    group: "Profile"
  },
  {
    x: 3.6,
    y: 7.4,
    z: 4.4,
    group: "Profile"
  },
  {
    x: 4.8,
    y: 8.3,
    z: 3.4,
    group: "Profile"
  },
  {
    x: 4.4,
    y: 5.4,
    z: 6.3,
    group: "Profile"
  },
  {
    x: 4,
    y: 6.6,
    z: 3.4,
    group: "Profile"
  },
  {
    x: 5.1,
    y: 6.6,
    z: 3.8,
    group: "Profile"
  },
  {
    x: 3.7,
    y: 6.1,
    z: 3,
    group: "Profile"
  },
  {
    x: 3.9,
    y: 7.2,
    z: 6.5,
    group: "Profile"
  }
], {
  series: "group"
}, {
  markerSize: 0.07,
  axes: {
    x: {
      ticks: 3
    },
    y: {
      ticks: 3
    },
    z: {
      ticks: 3
    }
  }
});
const { text } = renderGlyphChart3d(mark, {
  target: "web",
  width: 88,
  height: 34,
  charset: "braille"
});
console.log(text);
```

```text
          z                                                                             
                                                                                        
          ⡄                   ⣠⡀                       ⢀⣄                               
   8      +            ⣴⢷⣄⢀ ⢠⣾⣯⢧⣦                     ⣴⡿⠹⣧                              
          ⡇   ⢀     ⣠⣦⣼⣇⣈⣿⣟⣷⣿⢁⢻⣿⠇                 ⢀   ⢿⡒⢒⡿                              
          ⡇  ⣰⣟⢷⣄  ⣰⡟⠘⣿⢿⣼⣯⠤⢼⡇⣿⣿⠃  ⣴⢳⡄    8       ⣰⣟⣷⣄  ⠙⠛⢳⡄                             
   6      +  ⣿⠤⠬⣷  ⠻⣍⠩⣿⣟⣷⣿⠷⠏⣿⡬⣿⡟ 6⣏ ⢳⡆          ⢰⣿⠤⢼⡟⡀⢠⣾⣯⡓⢳⡆                            
          ⡇  ⠈⠇⠞⠁   ⠈⢹⣿⣀⣸⡷⢤⣽⣇⣿⡏⠁ ⠙⣎⠉⡽⠃       ⣀  ⢀⣽⠷⠏⠯⢧⣿⣀⣙⣿⡽⠃                            
          ⡇          ⠈⠳ ⠚⠁⠶⠋⢠⠞⠁   ⠈⠉    ⣀⡤⠴⠒⠋⠁  ⣾⠃⠹⣷⠒⣺⣿⣧⠰⠋    ⢀⣴⣄                       
          ⡇      2                ⢀⣠⡾⣶⡚⠉⠁ +     ⠻⠍⢩⡟⣿⣿⢳⢻⣷⡾⣦⡀ ⢰⡿⠁⢳⣷                      
   4      +                  ⢀⣠⠤⠖⠚+⣿⣀⣘⣶          ⣩⣿⣿⣿⢿⠓⣺⣿⣿⣞⣶ ⠘⠏⠉⠽⠃                      
         0⡇             ⣀⣠⠴⠒⠋⠉    ⠈⠻ ⠰⠋          ⣿⠽⢭⣿⣿⣻⡏⣿⣃⠸⣯   ⠉⠁                       
          ⡇        ⣀⡤⠴⠚⠉⠁ +                ⢀⣴⣄  ⣠⣾⣿⠾⠳ ⠚⠁⠹⠈⢩⠟                            
          ⡇  ⢀⣀⡤⠖⠚+⠁                      ⢀⣾⠁⢳⣷⢰⣿⠈⢿⣷     ⠉⠁                             
   2      +⣖⠋⠉                           ⣴⣻⢯⠉⠽⡃⡘⠏⠉⡽⠃⣄                                   
          +⠈⠙⠲+⣀                       ⢀⣼⣏⣿⣷⣭⣿⣻⣿⡎⢹⣏⣀⣳⣧⡀                                 
               ⠈⠙⠲⠤⣄⡀                 ⢀⣾⠁⢻⣿⣷⣿⣇⣉⣿⣷⢻⣿ ⣾⣋⢿⣄                                
                    ⠉+⠦⣄⡀             ⠘⢏⣿⣿⣿⣿⣿⢾⠐⣻⣏⣀⣻⣿⣧⠤⢼⡆                                
                        ⠉⠓⠲⢤⣀          ⢸⣯⠤⢼⡟⠏⠉ ⠙⢦ ⠞⠁⠙⠦⠏                                 
             0              +⠙⠲⢤⣀       ⠙⠆⠏⠉                                            
                                ⠈⠙⠒+⣄⡀                                                  
                    2                ⠉⠓⠦⣄⡀                                              
                                         ⠉+                                             
                           4                   x                                        
                                  6                                                     
```



`glyphChartScatter3d(records, channels?, options?)` reads x/y/z fields. Use `series` for groups, `color` for a continuous value, `size` for marker size.

## Parametric surfaces



```ts
import { glyphChartParametric3d, renderGlyphChart3d } from "@glyphcss/charts/3d";

const mark = glyphChartParametric3d({
  x: [
    [1.42, 1.38, 1.28, 1.11, 0.89, 0.62, 0.32, 0, -0.32, -0.62, -0.89, -1.11, -1.28, -1.38, -1.42, -1.38, -1.28, -1.11, -0.89, -0.62, -0.32, 0, 0.32, 0.62, 0.89, 1.11, 1.28, 1.38],
    [1.38, 1.34, 1.24, 1.08, 0.86, 0.6, 0.31, 0, -0.31, -0.6, -0.86, -1.08, -1.24, -1.34, -1.38, -1.34, -1.24, -1.08, -0.86, -0.6, -0.31, 0, 0.31, 0.6, 0.86, 1.08, 1.24, 1.34],
    [1.26, 1.23, 1.14, 0.99, 0.79, 0.55, 0.28, 0, -0.28, -0.55, -0.79, -0.99, -1.14, -1.23, -1.26, -1.23, -1.14, -0.99, -0.79, -0.55, -0.28, 0, 0.28, 0.55, 0.79, 0.99, 1.14, 1.23],
    [1.09, 1.07, 0.99, 0.85, 0.68, 0.47, 0.24, 0, -0.24, -0.47, -0.68, -0.85, -0.99, -1.07, -1.09, -1.07, -0.99, -0.85, -0.68, -0.47, -0.24, 0, 0.24, 0.47, 0.68, 0.85, 0.99, 1.07],
    [0.91, 0.88, 0.82, 0.71, 0.57, 0.39, 0.2, 0, -0.2, -0.39, -0.57, -0.71, -0.82, -0.88, -0.91, -0.88, -0.82, -0.71, -0.57, -0.39, -0.2, 0, 0.2, 0.39, 0.57, 0.71, 0.82, 0.88],
    [0.74, 0.72, 0.67, 0.58, 0.46, 0.32, 0.16, 0, -0.16, -0.32, -0.46, -0.58, -0.67, -0.72, -0.74, -0.72, -0.67, -0.58, -0.46, -0.32, -0.16, 0, 0.16, 0.32, 0.46, 0.58, 0.67, 0.72],
    [0.62, 0.61, 0.56, 0.49, 0.39, 0.27, 0.14, 0, -0.14, -0.27, -0.39, -0.49, -0.56, -0.61, -0.62, -0.61, -0.56, -0.49, -0.39, -0.27, -0.14, 0, 0.14, 0.27, 0.39, 0.49, 0.56, 0.61],
    [0.58, 0.57, 0.52, 0.45, 0.36, 0.25, 0.13, 0, -0.13, -0.25, -0.36, -0.45, -0.52, -0.57, -0.58, -0.57, -0.52, -0.45, -0.36, -0.25, -0.13, 0, 0.13, 0.25, 0.36, 0.45, 0.52, 0.57],
    [0.62, 0.61, 0.56, 0.49, 0.39, 0.27, 0.14, 0, -0.14, -0.27, -0.39, -0.49, -0.56, -0.61, -0.62, -0.61, -0.56, -0.49, -0.39, -0.27, -0.14, 0, 0.14, 0.27, 0.39, 0.49, 0.56, 0.61],
    [0.74, 0.72, 0.67, 0.58, 0.46, 0.32, 0.16, 0, -0.16, -0.32, -0.46, -0.58, -0.67, -0.72, -0.74, -0.72, -0.67, -0.58, -0.46, -0.32, -0.16, 0, 0.16, 0.32, 0.46, 0.58, 0.67, 0.72],
    [0.91, 0.88, 0.82, 0.71, 0.57, 0.39, 0.2, 0, -0.2, -0.39, -0.57, -0.71, -0.82, -0.88, -0.91, -0.88, -0.82, -0.71, -0.57, -0.39, -0.2, 0, 0.2, 0.39, 0.57, 0.71, 0.82, 0.88],
    [1.09, 1.07, 0.99, 0.85, 0.68, 0.47, 0.24, 0, -0.24, -0.47, -0.68, -0.85, -0.99, -1.07, -1.09, -1.07, -0.99, -0.85, -0.68, -0.47, -0.24, 0, 0.24, 0.47, 0.68, 0.85, 0.99, 1.07],
    [1.26, 1.23, 1.14, 0.99, 0.79, 0.55, 0.28, 0, -0.28, -0.55, -0.79, -0.99, -1.14, -1.23, -1.26, -1.23, -1.14, -0.99, -0.79, -0.55, -0.28, 0, 0.28, 0.55, 0.79, 0.99, 1.14, 1.23],
    [1.38, 1.34, 1.24, 1.08, 0.86, 0.6, 0.31, 0, -0.31, -0.6, -0.86, -1.08, -1.24, -1.34, -1.38, -1.34, -1.24, -1.08, -0.86, -0.6, -0.31, 0, 0.31, 0.6, 0.86, 1.08, 1.24, 1.34]
  ],
  y: [
    [0, 0.32, 0.62, 0.89, 1.11, 1.28, 1.38, 1.42, 1.38, 1.28, 1.11, 0.89, 0.62, 0.32, 0, -0.32, -0.62, -0.89, -1.11, -1.28, -1.38, -1.42, -1.38, -1.28, -1.11, -0.89, -0.62, -0.32],
    [0, 0.31, 0.6, 0.86, 1.08, 1.24, 1.34, 1.38, 1.34, 1.24, 1.08, 0.86, 0.6, 0.31, 0, -0.31, -0.6, -0.86, -1.08, -1.24, -1.34, -1.38, -1.34, -1.24, -1.08, -0.86, -0.6, -0.31],
    [0, 0.28, 0.55, 0.79, 0.99, 1.14, 1.23, 1.26, 1.23, 1.14, 0.99, 0.79, 0.55, 0.28, 0, -0.28, -0.55, -0.79, -0.99, -1.14, -1.23, -1.26, -1.23, -1.14, -0.99, -0.79, -0.55, -0.28],
    [0, 0.24, 0.47, 0.68, 0.85, 0.99, 1.07, 1.09, 1.07, 0.99, 0.85, 0.68, 0.47, 0.24, 0, -0.24, -0.47, -0.68, -0.85, -0.99, -1.07, -1.09, -1.07, -0.99, -0.85, -0.68, -0.47, -0.24],
    [0, 0.2, 0.39, 0.57, 0.71, 0.82, 0.88, 0.91, 0.88, 0.82, 0.71, 0.57, 0.39, 0.2, 0, -0.2, -0.39, -0.57, -0.71, -0.82, -0.88, -0.91, -0.88, -0.82, -0.71, -0.57, -0.39, -0.2],
    [0, 0.16, 0.32, 0.46, 0.58, 0.67, 0.72, 0.74, 0.72, 0.67, 0.58, 0.46, 0.32, 0.16, 0, -0.16, -0.32, -0.46, -0.58, -0.67, -0.72, -0.74, -0.72, -0.67, -0.58, -0.46, -0.32, -0.16],
    [0, 0.14, 0.27, 0.39, 0.49, 0.56, 0.61, 0.62, 0.61, 0.56, 0.49, 0.39, 0.27, 0.14, 0, -0.14, -0.27, -0.39, -0.49, -0.56, -0.61, -0.62, -0.61, -0.56, -0.49, -0.39, -0.27, -0.14],
    [0, 0.13, 0.25, 0.36, 0.45, 0.52, 0.57, 0.58, 0.57, 0.52, 0.45, 0.36, 0.25, 0.13, 0, -0.13, -0.25, -0.36, -0.45, -0.52, -0.57, -0.58, -0.57, -0.52, -0.45, -0.36, -0.25, -0.13],
    [0, 0.14, 0.27, 0.39, 0.49, 0.56, 0.61, 0.62, 0.61, 0.56, 0.49, 0.39, 0.27, 0.14, 0, -0.14, -0.27, -0.39, -0.49, -0.56, -0.61, -0.62, -0.61, -0.56, -0.49, -0.39, -0.27, -0.14],
    [0, 0.16, 0.32, 0.46, 0.58, 0.67, 0.72, 0.74, 0.72, 0.67, 0.58, 0.46, 0.32, 0.16, 0, -0.16, -0.32, -0.46, -0.58, -0.67, -0.72, -0.74, -0.72, -0.67, -0.58, -0.46, -0.32, -0.16],
    [0, 0.2, 0.39, 0.57, 0.71, 0.82, 0.88, 0.91, 0.88, 0.82, 0.71, 0.57, 0.39, 0.2, 0, -0.2, -0.39, -0.57, -0.71, -0.82, -0.88, -0.91, -0.88, -0.82, -0.71, -0.57, -0.39, -0.2],
    [0, 0.24, 0.47, 0.68, 0.85, 0.99, 1.07, 1.09, 1.07, 0.99, 0.85, 0.68, 0.47, 0.24, 0, -0.24, -0.47, -0.68, -0.85, -0.99, -1.07, -1.09, -1.07, -0.99, -0.85, -0.68, -0.47, -0.24],
    [0, 0.28, 0.55, 0.79, 0.99, 1.14, 1.23, 1.26, 1.23, 1.14, 0.99, 0.79, 0.55, 0.28, 0, -0.28, -0.55, -0.79, -0.99, -1.14, -1.23, -1.26, -1.23, -1.14, -0.99, -0.79, -0.55, -0.28],
    [0, 0.31, 0.6, 0.86, 1.08, 1.24, 1.34, 1.38, 1.34, 1.24, 1.08, 0.86, 0.6, 0.31, 0, -0.31, -0.6, -0.86, -1.08, -1.24, -1.34, -1.38, -1.34, -1.24, -1.08, -0.86, -0.6, -0.31]
  ],
  z: [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18],
    [0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33],
    [0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41],
    [0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41, 0.41],
    [0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33, 0.33],
    [0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18, 0.18],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [-0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18],
    [-0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33],
    [-0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41],
    [-0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41, -0.41],
    [-0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33, -0.33],
    [-0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18, -0.18]
  ]
}, {
  wrapU: true,
  wrapV: true
});
const { text } = renderGlyphChart3d(mark, {
  target: "web",
  width: 88,
  height: 34,
  charset: "braille"
});
console.log(text);
```

```text
       z                                                                                
                                ⢀⣀⣠⣤⣤⣤⣤⢤⣤⣤⣤⣀⣀⡀                                          
      ⢀                     ⣀⣤⣶⣿⣿⠿⣿⣟⢹⣯⢹⢉⣽⣏⣩⡿⣻⣿⢿⣷⣶⣤⣀                                     
      ⢸                  ⢀⣤⣾⣿⡿⣟⣿⡾⣾⣹⡮⢽⡟⣻⠛⣺⡛⢺⠯⣽⣹⣾⢴⡿⣿⣿⣷⣄                                   
      ⢸+                 ⣾⣾⣿⣿⣽⣿⣿⡿⣟⣆⣧⡼⣷⠛⣶⢻⢧⡼⣧⣇⡞⣷⣿⣿⣷⣿⣿⣻⣷⡄                                 
      ⢸                 ⣼⣻⣟⣿⣭⣿⣿⣿⣿⣿⣿⣸⠷⣟⠒⣟⢺⠾⡧⢽⣸⣟⣷⣿⣿⣟⡿⡿⣿⢷⢷                                 
      ⢸+               ⢸⣿⡟⢾⣏⢳⣼⣩⢿⡟⣿⣿⣿⣿⣿⣶⣿⣾⣾⣷⣾⣿⣿⣿⡛⣏⡽⢳⣇⡽⣿⣿⡆                                
      ⢸                0⡿⢳⡟⡎⡽⠛⢦⡾⣞⣩⣯⡖⠯⣿⣧⣾⡿⣿⣇⣿⠓⢮⣧⣩⠿⣗⢫⢷⣠⢿⣯⡇                                
      ⢸                ⣿⣿⢾⣁⢧⣧⠖⢻⢁⡴⣻ ⢉⡽⡏⢉⡽⡿⣍⠉⢹⢯⡉⢸⡳⢤⣸⣸ ⣿⣴⡏⣧    0.41█                       
0     ⢸+     -1        ⣿⢸⡼⣨⢿⡗⠦⡿⣏⣀⣧⣞⠉⢸⣡⠏ ⡇⠈⢧⣸ ⢙⣦⣇⡤⢽⣷⡋⢹⡼⢳⣸        █                       
     -2                ⢻⠻⣷⠃⡞⠹⡄⡇⢀⡞⡇⠈⣩⢿⢯⠉⠉⡿⣍⠉⢹⢯⡉ ⡇⢠⠏⡇⠹⣼⣧⢼⠃   0.205▛                       
      ⢸+           ⢀⣠⠤⠖⢺⣿⢿⡝⡷⠤⣽⣷⡋ ⣇⡼⠁⢸⠈⠳⡄⡇⠈⢧⡘⡆⠹⣄⣧⣏⣠⡷⠚⡿⠇⡞⡇        ▛                       
      ⢸       ⣀⣠⠴⠒⠋⠉    ⣿⢾⡹⣷⢠⠞⡿⣍⠉⡿⡝⠒⢺⠒⠒⣻⡗⠒⠒⣻⡗⠒⡿⡿⣅ ⡇⡞⢸⣨⡟⠁       0▀                       
      ⢸+⢀⣀⡤⠴⠚⠉⠁+        ⠘⣯⡏⣿⣯⣄⣇⡘⢦⡇⠙⢦⢸⢀⡞⠁⡇⣠⠞⢱⢣⠞⠁⡇⣈⣳⣿⠖⡿⣽⠁         ▀                       
      ⠘+⣍⡀               ⠈⠻⣥⣯⣳⣻⢯⡉⣿⣝⠚⢻⠛⠒⣲⡟⠓⢒⣾⠛⢚⣽⡏⡵⢻⠙⡞⠖⠃    -0.205▘                       
         ⠉⠓⠦⣄⡀             ⠈⠛⠻⠻⢷⢿⢾⣬⣝⣮⣧⣞⣁⣧⣞⣉⣸⣴⣫⣼⠾⠿⠋⠋⠁            ▘                       
             ⠉⠙+⢤⣀               ⠉⠉⠙⠓⠛⠛⠓⠑⠋⠛⠛⠛⠉⠉⠁           -0.41                        
                 ⠈⠙⠲⢤⣀                                                                  
     -2              ⠈+⠓⠦⣄⡀                                                             
                          ⠉⠓⠦⣄⣀                                                         
             -1               +⠙⠲⢤⣀                                                     
                                  ⠈⠙⠲⠤                                                  
                     0                +                                                 
                                           x                                            
                             1                                                          
```



`glyphChartParametric3d({ x, y, z, value? }, options?)` takes equal-shaped coordinate grids. `wrapU`/`wrapV` close the seams, as in this torus. `glyphChart3dSphereGrid` and `glyphChart3dTorusGrid` generate grids for you.

## Bars



```ts
import { glyphChartBars3d, renderGlyphChart3d } from "@glyphcss/charts/3d";

const mark = glyphChartBars3d([
  {
    x: 0,
    y: 0,
    z: 4,
    quarter: "Q1",
    region: "EU"
  },
  {
    x: 1,
    y: 0,
    z: 5.3,
    quarter: "Q2",
    region: "EU"
  },
  {
    x: 2,
    y: 0,
    z: 6.1,
    quarter: "Q3",
    region: "EU"
  },
  {
    x: 3,
    y: 0,
    z: 6.5,
    quarter: "Q4",
    region: "EU"
  },
  {
    x: 0,
    y: 1,
    z: 5.7,
    quarter: "Q1",
    region: "US"
  },
  {
    x: 1,
    y: 1,
    z: 6.5,
    quarter: "Q2",
    region: "US"
  },
  {
    x: 2,
    y: 1,
    z: 6.9,
    quarter: "Q3",
    region: "US"
  },
  {
    x: 3,
    y: 1,
    z: 7.1,
    quarter: "Q4",
    region: "US"
  },
  {
    x: 0,
    y: 2,
    z: 3.9,
    quarter: "Q1",
    region: "APAC"
  },
  {
    x: 1,
    y: 2,
    z: 4.3,
    quarter: "Q2",
    region: "APAC"
  },
  {
    x: 2,
    y: 2,
    z: 4.5,
    quarter: "Q3",
    region: "APAC"
  },
  {
    x: 3,
    y: 2,
    z: 5.2,
    quarter: "Q4",
    region: "APAC"
  },
  {
    x: 0,
    y: 3,
    z: 2.9,
    quarter: "Q1",
    region: "LATAM"
  },
  {
    x: 1,
    y: 3,
    z: 3.1,
    quarter: "Q2",
    region: "LATAM"
  },
  {
    x: 2,
    y: 3,
    z: 3.8,
    quarter: "Q3",
    region: "LATAM"
  },
  {
    x: 3,
    y: 3,
    z: 5,
    quarter: "Q4",
    region: "LATAM"
  }
], {
  xLabel: "quarter",
  yLabel: "region"
}, {
  axes: {
    x: {
      title: "Quarter"
    },
    y: {
      title: "Region"
    },
    z: {
      title: "Revenue",
      ticks: 3
    }
  }
});
const { text } = renderGlyphChart3d(mark, {
  target: "web",
  width: 88,
  height: 34,
  charset: "braille"
});
console.log(text);
```

```text
         Revenue                                                                        
                                                                                        
                                                                                        
  8     ⢸+           ⣀⡤⢶⠦⣄⡀              ⣀                                              
        ⢸        ⢠⣴⡚⠉⠁ ⠘  ⠉⢓⣦⣤⣶⢿⢷⠦⣄⡀⣀⡤⠴⠒⠋⢹⠙⠲⢤⣀                                          
        ⢸        ⢸ ⠉⠓⠦⣄⣀⡤⢶⠾⣍⡀     ⢀⣩⣷⣦⣤⣶⣤⣼⡀⢀⣀⡬⠽⣆⣀⣤⣄⡀                                    
  6     ⢸+       ⢸     ⡇ ⢸  ⠉⠓⠦⡤⠖⢫⣽⡚⠉⡇ ⢸ ⠈⠙⣿⣶⣞⡉⡏ ⢸ ⠉⠓⠦⣄⣀⡤⢶⢤⣀    ⣀⣤⣄⡀                    
        ⢸   ⣀⣠⠴⡦⣄⣸   ⣀⣠⣧⣀⢸     ⡇ ⢸ ⠉⠓⠦⣄⣀⡤⠴⢒⣋⡭⡷⡷⣿⣻⢿⣦⣤⣶⠛⠉  ⠸ ⣈⡽⠶⢾⡉⠁⢸ ⠉⠓⠦⣄⡀                
        ⢸⣴⡚⠉⠁  ⠇⢠⣽⠓⠯⣍⠁ ⡇⠈⠙⠲⣤⣠⠤⢶⡧⣄⣸     ⡇ ⢸⠻⢤⣀  ⢸  ⢀⣩⣿⡿⡶⢶⣻⣳⠦⣟⡙⠲⢤⣀ ⢀⣠⠤⠖⠚⠉⡇    7.1█        
  4     ⢸ ⠉⠓⠦⣄⣀⡤⢼⠈⠙⠲⢤⣀ ⣀⣴⢾⣛⠋  ⢸  ⠉⠙⣲⣤⣀⣤⣇⡀⢸  ⠈⠙⠲⡤⠖⠋⠉  ⣇  ⢸  ⢀⣩⠷⡆⠈⢹⠉     ⡇       █        
        ⢸     ⡇ ⢸    ⠈⡏⠁⢸ ⠈⠙⠲⢤⣀⡤⢖⣺⠽⠓⢻⠁⢸ ⠉⢻⠲⢤⣀  ⡇     ⡇⠙⠲⡤⠖⠋⠉  ⡇ ⢸      ⡇  5.325▛        
  2     ⢸     ⡇ ⢸     ⡇ ⢸     ⡇ ⢸⠉⠓⠦⣄⡀ ⣀⡤⠴⠒⠋⢹  ⡇     ⡇  ⡇     ⡇ ⢸      ⡇       ▛        
        ⢸     ⡇ ⢸     ⡇ ⢸     ⡇ ⢸    ⠉⡏⠁    ⢸  ⡇     ⡇  ⡇     ⡇ ⢸      ⡇   3.55▀        
        ⢸     ⡇ ⢸     ⡇ ⢸     ⡇ ⢸     ⡇     ⢸  ⡇     ⡇  ⡇     ⡇ ⢸      ⡇       ▀        
  0     ⠘⠻⢦⣄⡀ ⡇ ⢸     ⡇ ⢸     ⡇ ⢸     ⡇     ⢸  ⡇     ⡇  ⡇     ⡇ ⢸     ⢀⡇  1.775▘        
           ⠈+⠳⠧⣖⣻⢀    ⡇ ⢸     ⡇ ⢸     ⡇     ⢸  ⡇     ⡇  ⡇     ⡇⣀⢸ ⣠⠤⠖⠚⠉        ▘        
                +⠛⠶⣤⣀ ⡇ ⣸     ⡇ ⢸     ⡇     ⢸  ⡇     ⡇  ⡇   ⢀⣠⠇⠈⠉⠉            0         
                    +⠛⠳⢯⣹⣠    ⡇ ⢸     ⡇     ⢸  ⡇     ⡇⠲⢤⣇⡤⠖⠚⠉                           
                        +⠙⠲⢤⣀⡀⡇ ⣸     ⡇     ⢸⡀ ⡇ ⢀⣀⡤⠴⠃                                  
           0                +⠙⠓⠯⣽⣠    ⡇     ⣸⠉⠓⠓⠋⠉                                      
             0.5                +⠉⠓⠦⣄⡀⡇⣀⡤⠴⠒⠋⠁                                           
                   1                 ⠉⠉⠁                                                
                     1.5                   Quarter                                      
                           2                                                            
                             2.5   3                                                    
```



`glyphChartBars3d(records, channels?, options?)` places bars at numeric x/y with z heights; `xLabel`/`yLabel` name them. `barWidth` defaults to 0.7.

## Line



```ts
import { glyphChartLine3d, renderGlyphChart3d } from "@glyphcss/charts/3d";

const mark = glyphChartLine3d([
  {
    name: "Strand A",
    points: [
      [1, 0, 0],
      [0.99, 0.17, 0.06],
      [0.94, 0.33, 0.11],
      [0.88, 0.48, 0.17],
      [0.79, 0.62, 0.22],
      [0.67, 0.74, 0.28],
      [0.54, 0.84, 0.33],
      [0.39, 0.92, 0.39],
      [0.24, 0.97, 0.44],
      [0.07, 1, 0.5],
      [-0.1, 1, 0.56],
      [-0.26, 0.97, 0.61],
      [-0.42, 0.91, 0.67],
      [-0.56, 0.83, 0.72],
      [-0.69, 0.72, 0.78],
      [-0.8, 0.6, 0.83],
      [-0.89, 0.46, 0.89],
      [-0.95, 0.3, 0.94],
      [-0.99, 0.14, 1],
      [-1, -0.03, 1.06],
      [-0.98, -0.19, 1.11],
      [-0.94, -0.35, 1.17],
      [-0.87, -0.5, 1.22],
      [-0.77, -0.64, 1.28],
      [-0.65, -0.76, 1.33],
      [-0.52, -0.85, 1.39],
      [-0.37, -0.93, 1.44],
      [-0.21, -0.98, 1.5],
      [-0.05, -1, 1.56],
      [0.12, -0.99, 1.61],
      [0.28, -0.96, 1.67],
      [0.44, -0.9, 1.72],
      [0.58, -0.81, 1.78],
      [0.71, -0.71, 1.83],
      [0.82, -0.58, 1.89],
      [0.9, -0.43, 1.94],
      [0.96, -0.28, 2],
      [0.99, -0.12, 2.06],
      [1, 0.05, 2.11],
      [0.98, 0.22, 2.17],
      [0.93, 0.37, 2.22],
      [0.85, 0.52, 2.28],
      [0.75, 0.66, 2.33],
      [0.63, 0.77, 2.39],
      [0.5, 0.87, 2.44],
      [0.35, 0.94, 2.5],
      [0.19, 0.98, 2.56],
      [0.02, 1, 2.61],
      [-0.15, 0.99, 2.67],
      [-0.31, 0.95, 2.72],
      [-0.46, 0.89, 2.78],
      [-0.6, 0.8, 2.83],
      [-0.73, 0.69, 2.89],
      [-0.83, 0.56, 2.94],
      [-0.91, 0.41, 3],
      [-0.97, 0.26, 3.06],
      [-1, 0.09, 3.11],
      [-1, -0.08, 3.17],
      [-0.97, -0.24, 3.22],
      [-0.92, -0.4, 3.28]
    ]
  },
  {
    name: "Strand B",
    points: [
      [-1, 0, 0],
      [-0.99, -0.17, 0.06],
      [-0.94, -0.33, 0.11],
      [-0.88, -0.48, 0.17],
      [-0.79, -0.62, 0.22],
      [-0.67, -0.74, 0.28],
      [-0.54, -0.84, 0.33],
      [-0.39, -0.92, 0.39],
      [-0.24, -0.97, 0.44],
      [-0.07, -1, 0.5],
      [0.1, -1, 0.56],
      [0.26, -0.97, 0.61],
      [0.42, -0.91, 0.67],
      [0.56, -0.83, 0.72],
      [0.69, -0.72, 0.78],
      [0.8, -0.6, 0.83],
      [0.89, -0.46, 0.89],
      [0.95, -0.3, 0.94],
      [0.99, -0.14, 1],
      [1, 0.03, 1.06],
      [0.98, 0.19, 1.11],
      [0.94, 0.35, 1.17],
      [0.87, 0.5, 1.22],
      [0.77, 0.64, 1.28],
      [0.65, 0.76, 1.33],
      [0.52, 0.85, 1.39],
      [0.37, 0.93, 1.44],
      [0.21, 0.98, 1.5],
      [0.05, 1, 1.56],
      [-0.12, 0.99, 1.61],
      [-0.28, 0.96, 1.67],
      [-0.44, 0.9, 1.72],
      [-0.58, 0.81, 1.78],
      [-0.71, 0.71, 1.83],
      [-0.82, 0.58, 1.89],
      [-0.9, 0.43, 1.94],
      [-0.96, 0.28, 2],
      [-0.99, 0.12, 2.06],
      [-1, -0.05, 2.11],
      [-0.98, -0.22, 2.17],
      [-0.93, -0.37, 2.22],
      [-0.85, -0.52, 2.28],
      [-0.75, -0.66, 2.33],
      [-0.63, -0.77, 2.39],
      [-0.5, -0.87, 2.44],
      [-0.35, -0.94, 2.5],
      [-0.19, -0.98, 2.56],
      [-0.02, -1, 2.61],
      [0.15, -0.99, 2.67],
      [0.31, -0.95, 2.72],
      [0.46, -0.89, 2.78],
      [0.6, -0.8, 2.83],
      [0.73, -0.69, 2.89],
      [0.83, -0.56, 2.94],
      [0.91, -0.41, 3],
      [0.97, -0.26, 3.06],
      [1, -0.09, 3.11],
      [1, 0.08, 3.17],
      [0.97, 0.24, 3.22],
      [0.92, 0.4, 3.28]
    ]
  }
]);
const { text } = renderGlyphChart3d(mark, {
  target: "web",
  width: 88,
  height: 34,
  charset: "braille"
});
console.log(text);
```

```text
                               ⢀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⣀⡀                                         
          z             ⣀⣠⣤⣶⠾⠟⠛⠛⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠉⠛⠛⠛⠷⠶⣦⣤⣄⣀⡀                                
                      ⣴⡾⠟⠋⠁                         ⠈⠉⠙⠛⠷⣦⣄⡀                            
          ⡄                                               ⠉⠛⠷⣦⣄                         
 3.5      +                 ⣀⣠⣤⣤⣶⣶⣶⣶⠶⠶⠶⠶⠶⠶⢶⣤⣤⣤⣤⣀⣀⣀           ⠈⠛⢿⣦⡀                      
   3      +            ⣀⣤⣶⠿⠛⠋⠉               1⠈⠉⠉⠙⠛⠻⠶⣶⣤⣤⣀       ⠈⠻⣦⡀                    
          ⡇         ⢠⣴⠿⠃⠉                              ⠉⠙⠻⢶⣤⣀    ⣠⠘⣷                    
 2.5      +         ⡿             0.5⣀⣀⡀                   ⠈⠙⠻⣶⣤⡾⠋ ⢹                    
          ⡇         ⣷⡀   ⢀⣠0⣤⣶⠶⠶⠾⠛⠛⠛⠋⠉⠉⠛⠛⠛⠛⠛⠛⣛⠷⠶⣦⣤⣤y⣀⣀⡀    ⣀⣤⣾⠟⠋⠻⣦⡀⣼                    
   2      +         ⠉⠻⣶⣴⣾⡛⠋⠁            ⣀⡤⠴⠒⠋⠁+    ⠉⠉⠙⣻⣷⣶⣾⣟⡛⠉    ⢘⣿⣏                    
 1.5      +    -0.5 ⣰⡟⠁⠈⠙⠛⠿⢶⣤⣤⣄⣀⣀⣀⢀⣀⡤⠖⠚⠉⠁⢀⣀⣀⣀⣠⣤⣤⣤⣴⣶⠶⠟⠛⠋⠉⠁⠉⠛⢿⣷⣦⣀ ⣠⣾⠏⣿⡄                   
          ⡇        ⢸⣟        ⢈⣩⠉⠉⠛⠛⠛⠛+⠛⠛⠛⠛⠛⠛⠛⠛⠉⠉⠉           ⠈⣙⣿⣿⣟⠁ ⣼⡇                   
   1    -1+        ⠈⢿⣦⣀⢀⣠⣤⡶⠿+⠉                           ⣀⣠⣴⠾⠛⠉⠈⠻⣷⣄⣿                    
          ⡇        ⣀⣤⣽⠛⠿⣷⣥⣄⡀                       ⢀⣀⣠⣤⡶⠟⠋⠉      ⢈⣿⠃                    
 0.5      +  ⢀⣀⡤⠖⠚⠉+⣾⠇   ⠈⠉⠛⠛⠿⠶⠶⢶⣦⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⡶⠶⠶⠶⠟⠛⠛⠉⠉         ⣠⣴⠟⠁⢿⡆                   
          ⢧⣖⠋⠉     ⠸⣷⡀                                      ⣠⣴⡾⠟⠁  ⣼⠇                   
   0      +⠈⠙⠲⢤⣀    ⠙⠿⣦⣄                              ⢀⣀⣠⣤⡶⠟⠋⠁    ⣰⡟                    
               ⠈⠙⠲⠤⣄⡀ ⠘⠻⠿⢶⣦⣤⣄⣀⡀                ⢀⣀⣠⣤⡶⠶⠟⠛⠉⠉       ⢀⣾⠟                     
                  + ⠉⠓⠦⣄⡀   ⠉⠙⠛⠛⠛⠛⠛⠛⠷⠶⠶⠶⠾⠛⠛⠛⠛⠛⠛⠛⠉⠉            ⢀⣴⡿⠋                      
                        ⠉⠓+⢤⣀                              ⢠⣴⠾⠛⠉                        
        -1                  ⠈⠙⠲⢤⣀                                                       
                                ⠈⠙+⠦⣄⡀                                                  
              -0.5                   ⠉⠓⠦⣄⡀                                              
                         0               ⠉+                                             
                                               x                                        
                               0.5                                                      
```



`glyphChartLine3d(points, options?)` takes `[x, y, z]` triples or named series `{ name, color, points }`. `glyphChart3dLorenzAttractor()` generates a long trajectory.

## Render options

| Option | Values |
|---|---|
| `charset` | `braille` (draws wireframe), `blocks`, `box`, `ascii` (draw solid) |
| `style` | `solid`, `wireframe`, `ink` |
| `camera` | `{ rotX, rotY }` in degrees, optional `zoom`, or a `mat` matrix; default `{ rotX: 69, rotY: 318 }` |
| `colorscale` (mark option) | `viridis`, `cividis`, `magma`, `greys`, or hex anchors |

The result carries `text`, CSS `html`, `resolved.camera` (pass it back to reproduce a frame) and `report`.

## Interactive scene

```ts
import { createGlyphScene, createGlyphOrthographicCamera } from "glyphcss";
import { glyphChartSurface, glyphChartObject } from "@glyphcss/charts/3d";

const camera = createGlyphOrthographicCamera({ rotX: 69, rotY: 318, zoom: 100 });
const scene = createGlyphScene(host, { camera, cols: 80, rows: 30, mode: "solid" });
scene.addObject(glyphChartObject(glyphChartSurface({ z: [[0, 1], [1, 2]] })));
scene.rerender();
```

`glyphChartObject` mounts any mark in a live scene; add [controls](/components/glyph-controls/) to orbit it. The [chart CLI](/charts/cli/) renders surfaces with `--3d`.


---

# Text labels and rule annotations on terminal charts

Use `glyphChartText(data, { x, y, label })` for labels and `glyphChartRule(values, options?)` for reference lines. Rules default to horizontal (`axis: "y"`); `axis: "x"` makes them vertical.

## Label a release against a target

The example is an illustrative latency series in milliseconds. Paint the rule first, then the data and the label.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "rule",
      data: [50],
      channels: {},
      options: {
        axis: "y",
        name: "Target"
      }
    },
    {
      type: "line",
      data: [
        {
          day: 1,
          ms: 42
        },
        {
          day: 2,
          ms: 44
        },
        {
          day: 3,
          ms: 41
        },
        {
          day: 4,
          ms: 46
        },
        {
          day: 5,
          ms: 43
        },
        {
          day: 6,
          ms: 60
        },
        {
          day: 7,
          ms: 55
        },
        {
          day: 8,
          ms: 47
        },
        {
          day: 9,
          ms: 44
        },
        {
          day: 10,
          ms: 40
        },
        {
          day: 11,
          ms: 38
        },
        {
          day: 12,
          ms: 39
        }
      ],
      channels: {
        x: "day",
        y: "ms"
      },
      options: {
        name: "Latency"
      }
    },
    {
      type: "text",
      data: [
        {
          day: 6,
          ms: 66,
          note: "Release"
        }
      ],
      channels: {
        x: "day",
        y: "ms",
        label: "note"
      }
    }
  ],
  legend: false,
  title: "Checkout latency after release",
  axes: {
    x: {
      title: "Day"
    },
    y: {
      title: "Latency (ms)"
    }
  },
  scales: {
    y: {
      domain: [30, 70],
      nice: false
    }
  }
}, {
  target: "web",
  width: 64,
  height: 20
});
console.log(text);
```

```text
                 Checkout latency after release                 
                                                                
Latency (ms)                                                    
                                                                
70 ┤                        Release                             
   │                                                            
   │                                                            
60 ┤                           ⢠⡀                               
   │                          ⢠⠃⠈⠑⢄                             
   │                         ⢠⠃    ⠉⠢⣀                          
50 ┤── ── ── ── ── ── ── ── ⢠⠃ ── ── ─⠑⠢⣀─ ── ── ── ── ── ── ── 
   │                       ⢠⠃            ⠑⠢⢄⡀                   
   │    ⣀⠤⢄⣀       ⣀⠤⢄⡀   ⢠⠃                ⠈⠉⠒⠤⡀               
   │⠠⠔⠊⠉    ⠉⠑⠒⠤⠔⠊⠉   ⠈⠉⠒⠤⠃                     ⠈⠑⢄             
40 ┤                                               ⠉⠢⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤
   │                                                            
   │                                                            
30 └─────┬──────────┬──────────┬──────────┬─────────┬──────────┬
         2          4          6          8        10         12
                                Day                             
```



```ts
import { glyphChartLine, glyphChartText, glyphChartRule, glyphChartPlot } from "@glyphcss/charts";
const spec = glyphChartPlot({
  title: "Checkout latency after release",
  scales: { y: { domain: [30, 70], nice: false } },
  axes: { x: { title: "Day" }, y: { title: "Latency (ms)" } },
  marks: [
    glyphChartRule([50], { name: "Target", strokeWidth: 2 }),
    glyphChartLine([42, 44, 41, 46, 43, 60, 55, 47, 44, 40, 38, 39], {
      x: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    }),
    glyphChartText([{ day: 6, ms: 66, note: "Release" }], { x: "day", y: "ms", label: "note" }),
  ],
  legend: false,
});
```

Numeric-array line x coordinates start at zero unless an explicit x channel overrides them. Record coordinates use the values you supply. Keep annotations within an explicit domain if they must stay visible; leave enough cells around labels and inspect render notes for fitting changes. Use `axes.x.grid` or `axes.y.grid` for repeated tick-aligned guides rather than adding many rule marks.


---

# Text pie charts and donut charts with arc marks

`glyphChartArc(data, channels?, options?)` uses y as the slice magnitude and label as its name. Numeric arrays also work. The example shows an illustrative allocation of engineering hours.

## Pie with callouts



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "arc",
  data: [
    {
      part: "API",
      hours: 30
    },
    {
      part: "Web",
      hours: 22
    },
    {
      part: "Tests",
      hours: 16
    },
    {
      part: "Ops",
      hours: 12
    },
    {
      part: "Docs",
      hours: 10
    },
    {
      part: "Design",
      hours: 10
    }
  ],
  channels: {
    y: "hours",
    label: "part"
  }
}, {
  target: "chat",
  width: 72,
  height: 18,
  legend: false
});
console.log(text);
```

```text
             Design · 10%─────══════██████                              
                           ▌════════█████████                           
          Docs · 10%─────▌▌▌▌═══════███████████─────API · 30%           
                       ▌▌▌▌▌▌▌▌═════█████████████                       
                      ▌▌▌▌▌▌▌▌▌▌════██████████████                      
                      ╱╱╱╱╱▌▌▌▌▌▌▌══██████████████                      
                      ╱╱╱╱╱╱╱╱╱╱╱▌▌═██████████████                      
        Ops · 12%─────╱╱╱╱╱╱╱╱╱╱╱╱▚▚░░░███████████                      
                      ╱╱╱╱╱╱╱╱▚▚▚▚▚▚░░░░░░░░░█████                      
                      ╱╱╱▚▚▚▚▚▚▚▚▚▚░░░░░░░░░░░░░░░                      
                       ▚▚▚▚▚▚▚▚▚▚▚▚░░░░░░░░░░░░░░                       
                         ▚▚▚▚▚▚▚▚▚▚░░░░░░░░░░░░                         
           Tests · 16%─────▚▚▚▚▚▚▚▚░░░░░░░░░░                           
                              ▚▚▚▚░░░░░░░░─────Web · 22%                
```



## Donut with a hole



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "arc",
  data: [
    {
      part: "API",
      hours: 30
    },
    {
      part: "Web",
      hours: 22
    },
    {
      part: "Tests",
      hours: 16
    },
    {
      part: "Ops",
      hours: 12
    },
    {
      part: "Docs",
      hours: 10
    },
    {
      part: "Design",
      hours: 10
    }
  ],
  channels: {
    y: "hours",
    label: "part"
  },
  options: {
    innerRadius: 0.5
  }
}, {
  target: "chat",
  width: 72,
  height: 18,
  legend: false
});
console.log(text);
```

```text
             Design · 10%─────══════██████                              
                           ▌════════█████████                           
          Docs · 10%─────▌▌▌▌═══════███████████─────API · 30%           
                       ▌▌▌▌▌▌▌▌═══    ███████████                       
                      ▌▌▌▌▌▌▌▌▌          █████████                      
                      ╱╱╱╱╱▌▌              ███████                      
                      ╱╱╱╱╱╱╱              ███████                      
        Ops · 12%─────╱╱╱╱╱╱╱              ███████                      
                      ╱╱╱╱╱╱╱              ░░█████                      
                      ╱╱╱▚▚▚▚▚▚          ░░░░░░░░░                      
                       ▚▚▚▚▚▚▚▚▚▚▚    ░░░░░░░░░░░                       
                         ▚▚▚▚▚▚▚▚▚▚░░░░░░░░░░░░                         
           Tests · 16%─────▚▚▚▚▚▚▚▚░░░░░░░░░░                           
                              ▚▚▚▚░░░░░░░░─────Web · 22%                
```



```ts
import { glyphChartArc, renderGlyphChart } from "@glyphcss/charts";
const result = renderGlyphChart(
  glyphChartArc(
    [
      { part: "API", hours: 30 },
      { part: "Web", hours: 22 },
      { part: "Tests", hours: 16 },
      { part: "Ops", hours: 12 },
      { part: "Docs", hours: 10 },
      { part: "Design", hours: 10 },
    ],
    { y: "hours", label: "part" },
    { innerRadius: 0.5 },
  ),
  {
    target: "chat",
    width: 72,
    height: 20,
  },
);
```

- `innerRadius` is a fraction in `[0, 1)`, not a pixel radius.
- `labels: "callout"` is the default; `"legend-only"` suppresses the leader labels. Callouts already name every slice, so these examples render with `legend: false`.
- Negative values do not contribute and report `slice-dropped`; all-zero input reports `empty-total`.
- `cellAspect` adjusts the width/height ratio used to shape the disc. Measure your display font when a circle appears stretched.
- Narrow layouts may omit or abbreviate labels; inspect the report and increase width.

For source-text input, see [Mermaid pie charts](/charts/mermaid/#pie).


---

# ASCII bar charts: categories, groups, and intervals

`glyphChartBar(data, channels?, options?)` defaults to vertical bars. The following sales-channel counts are illustrative.

## Vertical categories



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "bar",
      data: [
        {
          channel: "Search",
          orders: 42,
          month: "April"
        },
        {
          channel: "Direct",
          orders: 34,
          month: "April"
        },
        {
          channel: "Email",
          orders: 24,
          month: "April"
        },
        {
          channel: "Social",
          orders: 18,
          month: "April"
        },
        {
          channel: "Partner",
          orders: 30,
          month: "April"
        },
        {
          channel: "Ads",
          orders: 22,
          month: "April"
        },
        {
          channel: "Search",
          orders: 55,
          month: "May"
        },
        {
          channel: "Direct",
          orders: 38,
          month: "May"
        },
        {
          channel: "Email",
          orders: 32,
          month: "May"
        },
        {
          channel: "Social",
          orders: 26,
          month: "May"
        },
        {
          channel: "Partner",
          orders: 36,
          month: "May"
        },
        {
          channel: "Ads",
          orders: 28,
          month: "May"
        }
      ],
      channels: {
        x: "channel",
        y: "orders",
        fill: "month"
      }
    }
  ],
  scales: {
    x: {
      type: "band"
    }
  },
  title: "Orders by sales channel"
}, {
  target: "chat",
  width: 72,
  height: 18
});
console.log(text);
```

```text
                         Orders by sales channel                        
                                                                        
orders                                                                  
                                                                        
   │      ░░░                                                           
50 ┤      ░░░                                                           
   │   ▃▃▃░░░                                                           
40 ┤   ███░░░        ░░░                                                
   │   ███░░░     ▆▆▆░░░                               ░░░              
30 ┤   ███░░░     ███░░░        ░░░                 ███░░░        ░░░   
   │   ███░░░     ███░░░     ▆▆▆░░░         ░░░     ███░░░     ▃▃▃░░░   
20 ┤   ███░░░     ███░░░     ███░░░      ▅▅▅░░░     ███░░░     ███░░░   
   │   ███░░░     ███░░░     ███░░░      ███░░░     ███░░░     ███░░░   
10 ┤   ███░░░     ███░░░     ███░░░      ███░░░     ███░░░     ███░░░   
   │   ███░░░     ███░░░     ███░░░      ███░░░     ███░░░     ███░░░   
 0 └─────┬──────────┬──────────┬───────────┬──────────┬──────────┬──────
      Search     Direct      Email      Social     Partner      Ads     
             █  April                             ░  May                
```



## Horizontal categories

Horizontal bars swap the channel roles: x is the numeric value and y is the category. Use a band y scale.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "bar",
      data: [
        {
          channel: "Search",
          orders: 42
        },
        {
          channel: "Direct",
          orders: 28
        },
        {
          channel: "Email",
          orders: 18
        }
      ],
      channels: {
        x: "orders",
        y: "channel"
      },
      options: {
        orientation: "horizontal"
      }
    }
  ],
  scales: {
    y: {
      type: "band"
    }
  },
  legend: false
}, {
  target: "chat",
  width: 60,
  height: 9
});
console.log(text);
```

```text
channel                                                     
                                                            
 Email ┤ ██████████████████████                             
       │                                                    
Direct ┤ ██████████████████████████████████                 
       │                                                    
Search ┤ ███████████████████████████████████████████████████
       └┬───────────┬───────────┬───────────┬────────────┬──
        0          10          20          30           40  
```



```ts
import { glyphChartBar, renderGlyphChart } from "@glyphcss/charts";
const mark = glyphChartBar([
  { channel: "Search", orders: 42 },
  { channel: "Direct", orders: 28 },
  { channel: "Email", orders: 18 },
], { x: "orders", y: "channel" }, { orientation: "horizontal" });
const result = renderGlyphChart({ marks: [mark], scales: { y: { type: "band" } } }, { target: "chat" });
```

Bind `fill` to a category for grouped series. For stacked vertical bars set `transform: { kind: "stack" }` on the mark. Narrow grouped bands can overlap; check `series-dodge-degraded` in render notes.

## Floating intervals

Use `x0` for the start and `x` for the end of a horizontal interval. These bars do not require a zero baseline. Horizontal bars take materialized rows and reject transforms.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "bar",
      data: [
        {
          task: "Build",
          start: 1,
          end: 4
        },
        {
          task: "Test",
          start: 4,
          end: 6
        },
        {
          task: "Ship",
          start: 6,
          end: 7
        }
      ],
      channels: {
        x0: "start",
        x: "end",
        y: "task"
      },
      options: {
        orientation: "horizontal"
      }
    }
  ],
  scales: {
    y: {
      type: "band"
    }
  },
  legend: false
}, {
  target: "chat",
  width: 60,
  height: 9
});
console.log(text);
```

```text
task                                                        
                                                            
 Ship ┤                                            █████████
      │                                                     
 Test ┤                           █████████████████         
      │                                                     
Build ┤ ██████████████████████████                          
      └┬────────┬───────┬────────┬────────┬───────┬────────┬
       1        2       3        4        5       6        7
```



Intervals narrower than one cell become event dots and report `bar-interval-collapsed`. Use [Mermaid Gantt](/charts/mermaid-schedules/#gantt-schedules) for calendar dates and dependencies.


---

# ASCII heatmaps with cell marks and color ramps

`glyphChartCell(data, { x, y, fill })` maps a numeric fill value to a ramp. Set both scales to band for a flush heatmap grid.

## Seasonal city temperatures

This grid uses all twelve months and eight cities from the workbench's 1991–2020 monthly city-temperature dataset, in °C. Positive and negative values produce a diverging ramp with a blank at zero.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "cell",
      data: [
        {
          city: "New York",
          month: "Jan",
          temperature: 0.9
        },
        {
          city: "New York",
          month: "Feb",
          temperature: 2.2
        },
        {
          city: "New York",
          month: "Mar",
          temperature: 6
        },
        {
          city: "New York",
          month: "Apr",
          temperature: 12.1
        },
        {
          city: "New York",
          month: "May",
          temperature: 17.3
        },
        {
          city: "New York",
          month: "Jun",
          temperature: 22.2
        },
        {
          city: "New York",
          month: "Jul",
          temperature: 25.3
        },
        {
          city: "New York",
          month: "Aug",
          temperature: 24.5
        },
        {
          city: "New York",
          month: "Sep",
          temperature: 20.7
        },
        {
          city: "New York",
          month: "Oct",
          temperature: 14.4
        },
        {
          city: "New York",
          month: "Nov",
          temperature: 8.9
        },
        {
          city: "New York",
          month: "Dec",
          temperature: 3.9
        },
        {
          city: "Chicago",
          month: "Jan",
          temperature: -3.8
        },
        {
          city: "Chicago",
          month: "Feb",
          temperature: -1.8
        },
        {
          city: "Chicago",
          month: "Mar",
          temperature: 3.9
        },
        {
          city: "Chicago",
          month: "Apr",
          temperature: 9.8
        },
        {
          city: "Chicago",
          month: "May",
          temperature: 15.9
        },
        {
          city: "Chicago",
          month: "Jun",
          temperature: 21.4
        },
        {
          city: "Chicago",
          month: "Jul",
          temperature: 24.1
        },
        {
          city: "Chicago",
          month: "Aug",
          temperature: 23.2
        },
        {
          city: "Chicago",
          month: "Sep",
          temperature: 19.1
        },
        {
          city: "Chicago",
          month: "Oct",
          temperature: 12.2
        },
        {
          city: "Chicago",
          month: "Nov",
          temperature: 5.2
        },
        {
          city: "Chicago",
          month: "Dec",
          temperature: -0.8
        },
        {
          city: "Los Angeles",
          month: "Jan",
          temperature: 14.7
        },
        {
          city: "Los Angeles",
          month: "Feb",
          temperature: 15
        },
        {
          city: "Los Angeles",
          month: "Mar",
          temperature: 16.2
        },
        {
          city: "Los Angeles",
          month: "Apr",
          temperature: 17.6
        },
        {
          city: "Los Angeles",
          month: "May",
          temperature: 18.8
        },
        {
          city: "Los Angeles",
          month: "Jun",
          temperature: 20.7
        },
        {
          city: "Los Angeles",
          month: "Jul",
          temperature: 22.9
        },
        {
          city: "Los Angeles",
          month: "Aug",
          temperature: 23.7
        },
        {
          city: "Los Angeles",
          month: "Sep",
          temperature: 23.1
        },
        {
          city: "Los Angeles",
          month: "Oct",
          temperature: 20.7
        },
        {
          city: "Los Angeles",
          month: "Nov",
          temperature: 17.2
        },
        {
          city: "Los Angeles",
          month: "Dec",
          temperature: 14.3
        },
        {
          city: "Miami",
          month: "Jan",
          temperature: 20.3
        },
        {
          city: "Miami",
          month: "Feb",
          temperature: 21.5
        },
        {
          city: "Miami",
          month: "Mar",
          temperature: 22.8
        },
        {
          city: "Miami",
          month: "Apr",
          temperature: 24.8
        },
        {
          city: "Miami",
          month: "May",
          temperature: 26.7
        },
        {
          city: "Miami",
          month: "Jun",
          temperature: 28.2
        },
        {
          city: "Miami",
          month: "Jul",
          temperature: 28.9
        },
        {
          city: "Miami",
          month: "Aug",
          temperature: 29
        },
        {
          city: "Miami",
          month: "Sep",
          temperature: 28.3
        },
        {
          city: "Miami",
          month: "Oct",
          temperature: 26.7
        },
        {
          city: "Miami",
          month: "Nov",
          temperature: 23.8
        },
        {
          city: "Miami",
          month: "Dec",
          temperature: 21.8
        },
        {
          city: "Seattle",
          month: "Jan",
          temperature: 6
        },
        {
          city: "Seattle",
          month: "Feb",
          temperature: 6.7
        },
        {
          city: "Seattle",
          month: "Mar",
          temperature: 8.4
        },
        {
          city: "Seattle",
          month: "Apr",
          temperature: 10.7
        },
        {
          city: "Seattle",
          month: "May",
          temperature: 14.2
        },
        {
          city: "Seattle",
          month: "Jun",
          temperature: 16.7
        },
        {
          city: "Seattle",
          month: "Jul",
          temperature: 19.5
        },
        {
          city: "Seattle",
          month: "Aug",
          temperature: 19.7
        },
        {
          city: "Seattle",
          month: "Sep",
          temperature: 17
        },
        {
          city: "Seattle",
          month: "Oct",
          temperature: 12.1
        },
        {
          city: "Seattle",
          month: "Nov",
          temperature: 8.1
        },
        {
          city: "Seattle",
          month: "Dec",
          temperature: 5.6
        },
        {
          city: "Denver",
          month: "Jan",
          temperature: -0.2
        },
        {
          city: "Denver",
          month: "Feb",
          temperature: 0.4
        },
        {
          city: "Denver",
          month: "Mar",
          temperature: 5.3
        },
        {
          city: "Denver",
          month: "Apr",
          temperature: 8.8
        },
        {
          city: "Denver",
          month: "May",
          temperature: 14.1
        },
        {
          city: "Denver",
          month: "Jun",
          temperature: 20.1
        },
        {
          city: "Denver",
          month: "Jul",
          temperature: 23.9
        },
        {
          city: "Denver",
          month: "Aug",
          temperature: 22.7
        },
        {
          city: "Denver",
          month: "Sep",
          temperature: 18.2
        },
        {
          city: "Denver",
          month: "Oct",
          temperature: 10.6
        },
        {
          city: "Denver",
          month: "Nov",
          temperature: 4.1
        },
        {
          city: "Denver",
          month: "Dec",
          temperature: -0.4
        },
        {
          city: "Phoenix",
          month: "Jan",
          temperature: 13.8
        },
        {
          city: "Phoenix",
          month: "Feb",
          temperature: 15.5
        },
        {
          city: "Phoenix",
          month: "Mar",
          temperature: 19.1
        },
        {
          city: "Phoenix",
          month: "Apr",
          temperature: 22.9
        },
        {
          city: "Phoenix",
          month: "May",
          temperature: 27.8
        },
        {
          city: "Phoenix",
          month: "Jun",
          temperature: 33
        },
        {
          city: "Phoenix",
          month: "Jul",
          temperature: 35.3
        },
        {
          city: "Phoenix",
          month: "Aug",
          temperature: 34.7
        },
        {
          city: "Phoenix",
          month: "Sep",
          temperature: 31.8
        },
        {
          city: "Phoenix",
          month: "Oct",
          temperature: 25.2
        },
        {
          city: "Phoenix",
          month: "Nov",
          temperature: 18.4
        },
        {
          city: "Phoenix",
          month: "Dec",
          temperature: 13.2
        },
        {
          city: "Minneapolis",
          month: "Jan",
          temperature: -8.8
        },
        {
          city: "Minneapolis",
          month: "Feb",
          temperature: -6.3
        },
        {
          city: "Minneapolis",
          month: "Mar",
          temperature: 0.7
        },
        {
          city: "Minneapolis",
          month: "Apr",
          temperature: 8.4
        },
        {
          city: "Minneapolis",
          month: "May",
          temperature: 15.3
        },
        {
          city: "Minneapolis",
          month: "Jun",
          temperature: 20.9
        },
        {
          city: "Minneapolis",
          month: "Jul",
          temperature: 23.5
        },
        {
          city: "Minneapolis",
          month: "Aug",
          temperature: 22.1
        },
        {
          city: "Minneapolis",
          month: "Sep",
          temperature: 17.5
        },
        {
          city: "Minneapolis",
          month: "Oct",
          temperature: 9.7
        },
        {
          city: "Minneapolis",
          month: "Nov",
          temperature: 1.6
        },
        {
          city: "Minneapolis",
          month: "Dec",
          temperature: -5.6
        }
      ],
      channels: {
        x: "month",
        y: "city",
        fill: "temperature"
      }
    }
  ],
  scales: {
    x: {
      type: "band"
    },
    y: {
      type: "band"
    }
  },
  title: "Monthly temperatures (C)"
}, {
  target: "chat",
  width: 84,
  height: 28
});
console.log(text);
```

```text
                  Monthly temperatures (C)                   
                                                             
city                                                         
                                                             
            │▙▙▙▙▚▚▚▚░░░░░░░░▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░▚▚▚▚
Minneapolis ┤▙▙▙▙▚▚▚▚░░░░░░░░▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░▚▚▚▚
            │▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓████████████████▓▓▓▓▒▒▒▒▒▒▒▒
    Phoenix ┤▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓████████████████▓▓▓▓▒▒▒▒▒▒▒▒
            │▖▖▖▖░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░▖▖▖▖
     Denver ┤▖▖▖▖░░░░░░░░░░░░▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░▖▖▖▖
            │░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░
    Seattle ┤░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░
            │▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
      Miami ┤▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
            │▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒
Los Angeles ┤▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒
            │▞▞▞▞▖▖▖▖░░░░▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░▖▖▖▖
    Chicago ┤▞▞▞▞▖▖▖▖░░░░▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒░░░░▖▖▖▖
            │░░░░░░░░░░░░▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒░░░░░░░░
   New York ┤░░░░░░░░░░░░▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒▒▒░░░░░░░░
            └──┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬─
              Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
                                  month                      
```



```ts
import { glyphChartCell, renderGlyphChart } from "@glyphcss/charts";
const result = renderGlyphChart({
  marks: [glyphChartCell([
    { month: "Jan", city: "Seattle", temperature: 6.0 },
    { month: "Jul", city: "Seattle", temperature: 19.5 },
    { month: "Jan", city: "Phoenix", temperature: 13.8 },
    { month: "Jul", city: "Phoenix", temperature: 35.3 },
  ], { x: "month", y: "city", fill: "temperature" })],
  scales: { x: { type: "band" }, y: { type: "band" } },
}, { target: "web", width: 60, height: 14 });
```

Cell-only plots with two band scales fit an integer grid of `2k × k` cells and can shrink the requested canvas to that grid. Unsigned heatmaps use a nonblank ramp and a range key. A signed heatmap reserves blank only for zero.

Use render option `cellRamp: [".", ":", "+", "#"]` to replace an unsigned ramp, lightest first. Signed ramps stay gain/loss ramps. Mark `options.color` sets one ink color or `[lossColor, gainColor]`; it does not replace the numeric fill channel. See [targets and colors](/charts/targets/).


---

# Render chart JSON from the command line

The `glyphcss` executable comes from `@glyphcss/compile`. Its `chart` subcommand reads JSON, not Mermaid.

## Install and render from a clean directory

```sh
npm init -y
npm install @glyphcss/compile
cat > chart.json <<'JSON'
{"marks":[{"type":"line","data":[18,24,21,35,42,39,48,44,38,52,61,57],"channels":{},"options":{"name":"Orders"}},{"type":"line","data":[30,32,34,38,44,46,50,52,54,58,64,66],"channels":{},"options":{"name":"Plan"}}],"title":"Daily orders vs plan","axes":{"x":{"title":"Day (index)"},"y":{"title":"Orders"}}}
JSON
npx glyphcss chart chart.json --target chat --charset blocks --width 64 --height 18
npx glyphcss chart chart.json --target terminal --color ansi256 --width 64 --height 18 --out chart.ansi
cat > surface.json <<'JSON'
{"data":{"z":[[0,1,0],[1,3,1],[0,1,0]]}}
JSON
npx glyphcss chart surface.json --3d --charset braille --camera 30,-35 --style wireframe --width 60 --height 24
```



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  charset: "blocks",
  width: 64,
  height: 18
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   │                                                     ▗▄▄▄▄▄▄
60 ┤                                                  ▗▄▀▚▄▄▖   
   │                                          ▄▄▄▄▄▄▄▀▚▄▀▘  ▝▀▀▄
50 ┤                               ▄▄▄▄▄▄▄▄▞▀▀      ▄▀▘         
   │                         ▗▄▄▞▀▀ ▄▄▄           ▗▞            
40 ┤                    ▄▄▟█▀▘   ▗▞▀   ▀▀▀▄▄▖    ▞▘             
   │               ▄▄▞▀▀    ▀▀▀▄▀▘          ▝▀▀▄▀               
30 ┤▗▄▄▄▄▄▄▄▄▄▄▄▞▀▜▞                                            
   │             ▞▘                                             
   │    ▄▄▄▄▄▄▄▄▀                                               
20 └▗▞▀▀───────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
                            Day (index)                         
         ▗▄▄ Orders                       ▗▖▄ Plan              
```



## Flags

| Flag | Accepted values / behavior |
| --- | --- |
| `--target` | `chat`, `terminal`, `web`; CLI default is terminal. |
| `--charset` | `ascii`, `box`, `blocks`, `braille`. |
| `--color` | `none`, `ansi16`, `ansi256`, `truecolor`, `css`. |
| `--width`, `--height` | Positive integer columns and rows. |
| `-o`, `--out` | Write the emitted text to a file. |
| `--3d` | Read a surface spec `{ data, channels?, options? }`. |
| `--camera` | `rotX,rotY[,zoom]`, degrees and optional zoom; requires `--3d`. Omit for auto-fit. |
| `--style` | `solid`, `wireframe`, `ink`; requires `--3d`. Default follows charset. |
| `-h`, `--help` | Print usage. |

Output defaults to ANSI on a TTY and plain text when piped; `--color` overrides this choice. The CLI forwards `NO_COLOR` and `FORCE_COLOR`. It writes text even for `--color css`; use the JavaScript API's `result.html` when you need colored HTML.

Adaptation notes go to stderr as `glyphcss: : `. Failures retain tagged rule codes and exit 1. Keep stderr when diagnosing missing labels or invalid data.

## Mermaid chart files

Use the separate `diagram` dispatcher for Mermaid charts. It preserves source adaptation notes and accepts supported chart headers alongside diagram headers.

```sh
npm init -y
npm install @glyphcss/compile
cat > orders.mmd <<'MERMAID'
xychart
  x-axis [Mon, Tue, Wed]
  bar [18, 24, 21]
MERMAID
npx glyphcss diagram orders.mmd --target chat --width 60 --height 12
```

See [diagram CLI flags](/diagrams/cli/). Only the `chart` subcommand supports `--3d`.


---

# Text charts in vanilla JavaScript, React, and Vue

2D charts use `@glyphcss/charts` directly. They do not need React/Vue scene bindings. Install the package, render synchronously, and replace the `
` text when your data changes.

```sh
npm install @glyphcss/charts
```

## Vanilla JavaScript

```html

```

```ts
import { renderGlyphChart } from "@glyphcss/charts";
const host = document.querySelector("#chart")!;
try {
  host.textContent = renderGlyphChart([18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57], {
    target: "web", color: "none", width: 60, height: 12,
  }).text;
} catch (error) {
  host.textContent = error instanceof Error ? error.message : String(error);
}
```

## React

```tsx
import { useMemo } from "react";
import { renderGlyphChart } from "@glyphcss/charts";
const defaultValues = [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57];

export function GlyphOrderChart({ values = defaultValues }) {
  const text = useMemo(() => {
    try {
      return renderGlyphChart(values, { target: "web", color: "none", width: 60, height: 12 }).text;
    } catch (error) {
      return error instanceof Error ? error.message : String(error);
    }
  }, [values]);
  return 
{text}
; } ``` Replace the values array when data changes so memoization can observe it. ## Vue ```vue ``` ## Shared font rules Apply this stylesheet in each application. Load Glyph Mono separately, or use another font with complete charset coverage. Keep `line-height: 1` so adjacent glyph rows align. ```css .order-chart { font-family: "Glyph Mono", ui-monospace, monospace; font-size: 13px; line-height: 1; white-space: pre; overflow: auto; } ``` ```ts import { renderGlyphChart } from "@glyphcss/charts"; const { text } = renderGlyphChart([18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57], { target: "web", color: "none", width: 60, height: 12 }); console.log(text); ``` ```text 60 ┤ ⡠⢄⡀ │ ⢀⠔⠉ ⠈⠉⠒⠤ │ ⡠⠊⠁ 50 ┤ ⡠⢄⡀ ⢀⠜ │ ⡠⢄⡀ ⢀⠔⠉ ⠈⠉⠒⠤⢄⡀ ⡔⠁ 40 ┤ ⢀⠔⠉ ⠈⠉⠒⠤⠊⠁ ⠈⠉⠒⠤⠊ │ ⡠⠊⠁ 30 ┤ ⢀⠜ │ ⡔⠁ │ ⣀⠤⠤⠤⠤⠤⠤⠊ 20 └⠠⠔⠊⠉──────┬─────────┬─────────┬─────────┬─────────┬───── 0 2 4 6 8 10 ``` ## CSS color and static output Use `color: "css"` for `result.html`. It is an escaped span fragment; assign it inside a `
`, not as a whole HTML document.

```ts
import { renderGlyphChart } from "@glyphcss/charts";
const host = document.querySelector("#chart")!;
const result = renderGlyphChart([18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57], {
  target: "web", color: "css", width: 60, height: 12,
});
host.innerHTML = result.html!;
```

React uses `
`; Vue uses `
`. Obtain `html` from the renderer, and never concatenate unescaped data into its fragment.

For responsive charts, measure available columns and rows, then re-render with those cell budgets. Own and disconnect any `ResizeObserver` in the component lifecycle. At build time, emit text or HTML without hydration, as these docs do. Use the [3D guide](/charts/3d/) for chart scene objects and [diagram framework examples](/diagrams/frameworks/) for asynchronous diagram rendering.


---

# Text funnel charts for conversion stages

Use `glyphChartFunnel(data, { stage?, value?, name?, color? })`. The workbench's illustrative conversion funnel below uses benchmark-shaped counts, not observations from a particular store.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "funnel",
  data: [
    {
      stage: "Visits",
      count: 10000
    },
    {
      stage: "Product Views",
      count: 6500
    },
    {
      stage: "Add to Cart",
      count: 3200
    },
    {
      stage: "Shipping",
      count: 2100
    },
    {
      stage: "Payment",
      count: 1600
    },
    {
      stage: "Review",
      count: 1400
    },
    {
      stage: "Purchase",
      count: 1250
    }
  ],
  channels: {
    stage: "stage",
    value: "count"
  }
}, {
  target: "chat",
  width: 72,
  height: 23
});
console.log(text);
```

```text
███████████████████████████████████  Visits         10,000  100%        
                                                                        
 ▜███████████████████████████████▛                                      
  ▝▜███████████████████████████▛▘                                       
   ▐███████████████████████████▌     Product Views   6,500   65%        
                                                                        
    ▝▜███████████████████████▛▘                                         
      ▝▜███████████████████▛▘                                           
       ▐███████████████████▌         Add to Cart     3,200   32%   ↓ 49%
                                                                        
        ▝▜███████████████▛▘                                             
         ▐███████████████▌           Shipping        2,100   21%   ↓ 66%
                                                                        
          ▜█████████████▛                                               
          ▐█████████████▌            Payment         1,600   16%   ↓ 76%
                                                                        
          ▝█████████████▘                                               
           █████████████             Review          1,400   14%   ↓ 88%
                                                                        
           ▜███████████▛                                                
           ▐███████████▌             Purchase        1,250   13%   ↓ 89%
```



```ts
import { glyphChartFunnel, renderGlyphChart } from "@glyphcss/charts";
const result = renderGlyphChart(
  glyphChartFunnel(
    [
      { stage: "Visits", count: 10000 },
      { stage: "Product Views", count: 6500 },
      { stage: "Add to Cart", count: 3200 },
      { stage: "Shipping", count: 2100 },
      { stage: "Payment", count: 1600 },
      { stage: "Review", count: 1400 },
      { stage: "Purchase", count: 1250 },
    ],
    { stage: "stage", value: "count" },
  ),
  { target: "chat", width: 72, height: 23 },
);
```

Stages keep their declared order. Values must be finite and nonnegative; a bare number array uses its indices as stage names. Labels show values and percentages relative to the first stage when it is positive.

Widths follow square roots of stage values to keep late stages readable. They are not a linear width scale. Growing stages report `funnel-not-monotone`; very small stages can become one-cell stubs (`funnel-thin-stage`). More height keeps stages from folding together. An all-zero funnel reports `empty-total`.

Funnels reject Cartesian scales and transforms. Use [bar charts](/charts/bar/) when readers need direct comparisons of lengths on a numeric axis.


---

# Braille line charts and filled area charts

Use `glyphChartLine(data, channels?, options?)` for trends and `glyphChartArea` for filled values from a zero baseline. The example is an illustrative twelve days of orders, not measured production data.

## Line over an area

Compose marks in paint order. Give matching marks the same series name and color. Here the shaded area is capacity and the line is actual demand.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "area",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Capacity"
      }
    },
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders",
        strokeWidth: 2
      }
    }
  ],
  title: "Daily order volume"
}, {
  target: "terminal",
  width: 64,
  height: 18
});
console.log(text);
```

```text
                       Daily order volume                       
                                                                
   │                                                    ▗▄██████
60 ┤                                               ▗▄████⢀⣠⣄⡀███
   │                                      ▗▄▄▄████████⢀⣠⠶⠋⠁⠈⠙⠛⠶█
50 ┤                            ▗▄██████████████████⣠⠶⠋⠁████████
   │                   ▗▄██████████⣀⣤⣤⣤⣤⣤⣤⣤⡀██████⢀⡼⠃███████████
40 ┤               ▄▄███⣀⣤⣤⣤⣤⣤⣤⣤⡴⠞⠛⠉███████⠙⠳⣄███⣴⠋█████████████
   │     ▄▄▄▄███████⣠⡴⠞⠛⠉████████████████████⠈⠛⢦⠞⠁██████████████
30 ┤██████████████⢀⡼⠃███████████████████████████████████████████
   │███⢀⣀⣤⣄⣀█████⣴⠋█████████████████████████████████████████████
20 ┤█⠰⠞⠋⠉█⠈⠉⠛⠳⠶⣤⠞⠁██████████████████████████████████████████████
   │████████████████████████████████████████████████████████████
10 ┤████████████████████████████████████████████████████████████
   │████████████████████████████████████████████████████████████
 0 └┬──────────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
         █  Capacity                     ⢠⡄⣤ Orders             
```



```ts
import { glyphChartArea, glyphChartLine, glyphChartPlot, renderGlyphChart } from "@glyphcss/charts";

const spec = glyphChartPlot({
  marks: [
    glyphChartArea([30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66], {}, { name: "Capacity" }),
    glyphChartLine(
      [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      {},
      { name: "Orders", strokeWidth: 2 },
    ),
  ],
});
const result = renderGlyphChart(spec, { target: "terminal", width: 60, height: 18 });
```

## Record-based series

For records, bind `x` and `y` explicitly. Bind `stroke` or `fill` to a category to split a mark into series. Keep rows in the intended traversal order; pre-sort dates yourself.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [
        {
          day: 1,
          orders: 18,
          store: "North"
        },
        {
          day: 2,
          orders: 24,
          store: "North"
        },
        {
          day: 3,
          orders: 21,
          store: "North"
        },
        {
          day: 4,
          orders: 35,
          store: "North"
        },
        {
          day: 5,
          orders: 42,
          store: "North"
        },
        {
          day: 6,
          orders: 39,
          store: "North"
        },
        {
          day: 7,
          orders: 48,
          store: "North"
        },
        {
          day: 1,
          orders: 12,
          store: "South"
        },
        {
          day: 2,
          orders: 20,
          store: "South"
        },
        {
          day: 3,
          orders: 28,
          store: "South"
        },
        {
          day: 4,
          orders: 25,
          store: "South"
        },
        {
          day: 5,
          orders: 32,
          store: "South"
        },
        {
          day: 6,
          orders: 36,
          store: "South"
        },
        {
          day: 7,
          orders: 41,
          store: "South"
        }
      ],
      channels: {
        x: "day",
        y: "orders",
        stroke: "store"
      }
    }
  ]
}, {
  target: "web",
  width: 64,
  height: 16
});
console.log(text);
```

```text
orders                                                          
                                                                
   │                                                          ⢀⡠
   │                                                       ⣀⠤⠊⠁ 
40 ┤                                      ⣀⠤⠤⣀⣀⡀        ⡠⠔⠊   ⣀⠤
   │                                 ⢀⡠⠤⠒⠉     ⠈⠉⠉⠒⠒⠢⠤⠒⠉ ⣀⠤⠔⠊⠉  
   │                              ⡠⠔⠊⠁            ⣀⣀⡠⠤⠔⠊⠉       
30 ┤                           ⢀⠔⠉        ⣀⠤⠤⠒⠒⠊⠉⠉              
   │                   ⢀⡠⠤⣀⣀⡀⡠⠊⠁     ⢀⡠⠤⠒⠉                      
   │         ⣀⠤⠤⣀⣀⡀ ⣀⠤⠊⠁  ⢀⠔⠉⠉⠉⠒⠒⠢⠤⠔⠊⠁                          
   │    ⣀⠤⠔⠊⠉    ⡠⠜⠋⠉⠒⠒⠢⠤⠊⠁                                     
20 ┤⠠⠔⠊⠉     ⣀⠤⠒⠉                                               
   │    ⣀⠤⠔⠊⠉                                                   
   └⠠⠔⠊⠉──────┬─────────┬─────────┬────────┬─────────┬─────────┬
    1         2         3         4        5         6         7
          ⠠⠤⠤ North                       ⠠⠄⠤ South             
```



Use `scales.x.type: "time"` for ISO dates or `Date` values. Areas require a domain containing zero. A rolling mean uses a mark-level `window` transform; see the [spec reference](/charts/spec/#transforms). Choose box drawing for chat when its font lacks braille.


---

# Mermaid charts as ASCII and braille text

`renderGlyphChartMermaid(source, options?)` supports `pie`, `xychart`/`xychart-beta`, `sankey`/`sankey-beta`, `quadrantChart`, `gantt`, `radar`/`radar-beta`, `treemap`/`treemap-beta`, `journey`, `timeline`, `packet`/`packet-beta`, and `kanban`.

Every example below is rendered at build time from the source in its collapsed disclosure. Use the [schedule and journey guide](/charts/mermaid-schedules/) and [packet and kanban guide](/charts/mermaid-structures/) for the remaining families.

```ts
import { renderGlyphChartMermaid, glyphChartFromMermaid } from "@glyphcss/charts";
const source = `pie
 "Docs": 25
 "Code": 75`;
const result = renderGlyphChartMermaid(source, { target: "chat", width: 60, height: 14 });
const spec = glyphChartFromMermaid(source);
console.log(result.text, result.report.ledger, spec);
```

## Pie



```mermaid
pie title Engineering hours
 "API": 30
 "Web": 22
 "Tests": 16
 "Ops": 12
 "Docs": 10
 "Design": 10
```

```text
                            Engineering hours                           
                                                                        
                                                                        
                   Design · 10%─────                                    
                             ═══════███████                             
                           ▌▌═══════█████████                           
          Docs · 10%─────▌▌▌▌▌▌═════███████████─────API · 30%           
                        ▌▌▌▌▌▌▌▌════████████████                        
                        ╱╱╱▌▌▌▌▌▌▌══████████████                        
                       ╱╱╱╱╱╱╱╱╱╱▌▌═█████████████                       
         Ops · 12%─────╱╱╱╱╱╱╱╱╱╱╱▚▚░░░██████████                       
                        ╱╱╱╱╱╱▚▚▚▚▚▚░░░░░░░░░███                        
                        ╱▚▚▚▚▚▚▚▚▚▚░░░░░░░░░░░░░                        
                         ▚▚▚▚▚▚▚▚▚▚░░░░░░░░░░░░                         
                           ▚▚▚▚▚▚▚▚░░░░░░░░░░                           
             Tests · 16%─────▚▚▚▚▚▚░░░░░░░░─────Web · 22%               
```



## XY charts

Categories or numeric ranges drive bar and line marks. `horizontal` swaps their axes. `xychart-beta` is also accepted.



```mermaid
xychart
 title Daily orders
 x-axis [Mon, Tue, Wed, Thu, Fri, Sat, Sun]
 y-axis Orders 0 --> 60
 bar [18, 24, 21, 35, 42, 39, 48]
 line [30, 32, 34, 38, 44, 46, 50]
```

```text
                            Daily orders                            
                                                                    
Orders                                                              
                                                                    
60 ┤                                                                
   │                                                                
   │                                                       __---    
   │                                     __--─────────---‾‾  ███    
40 ┤                            __-----‾‾  ███      ███      ███    
   │     ──────────────────---‾‾  ███      ███      ███      ███    
   │            ▃▃▃               ███      ███      ███      ███    
20 ┤   ▂▂▂      ███      ▇▇▇      ███      ███      ███      ███    
   │   ███      ███      ███      ███      ███      ███      ███    
   │   ███      ███      ███      ███      ███      ███      ███    
   │   ███      ███      ███      ███      ███      ███      ███    
 0 └────┬────────┬────────┬────────┬────────┬────────┬────────┬─────
       Mon      Tue      Wed      Thu      Fri      Sat      Sun    
             █  Bar                          ──  Line               
```



## Sankey

Rows are CSV source, target, value. Quoted fields can contain commas. Cycles adapt to a flow list with notes; native Sankey rejects cycles.



```mermaid
sankey-beta
Solar,Grid,30
Wind,Grid,25
Gas,Grid,45
Grid,Homes,40
Grid,Shops,20
Grid,Rail,15
Grid,Industry,25
```

```text
         █──╮                  ╭──█──╮                  ╭──█            
         █──┴─╮              ╭─┴──█──┴─╮                ├──█            
Solar 30 █────┼━━━━━ 30 ━━━━━┼────█────┼━━━━ 40 ━━━━┓ ╭─┴──█            
         █──┬─╯              ╰─┬──█──┬─╯            ┗━┼────█ Homes 40   
         █──╯                  ╰──█──┤                ╰─┬──█            
                                  █──╯                  ├──█            
                             ╭────█                     ╰──█            
         █──╮              ┏━┼────█──╮                                  
         █──┴─╮            ┃ ╰─┬──█──┼───── 20 ─────╮                   
 Wind 25 █────┼━━━━ 25 ━━━━┛   ╰──█──╯              │ ╭────█            
         █──┬─╯                   █                 ╰─┼────█ Shops 20   
         █──╯                  ╭──█──┬───── 15 ──────╮╰─┬──█            
                               ├──█──╯               │  ╰──█            
                             ╭─┴──█                  │                  
         █──╮              ┏━┼────█────╮             │                  
         █──┴─╮            ┃ ╰─┬──█────┼━━━━ 25 ━━━━┓│  ╭──█            
         █────┤            ┃   ├──█──┬─╯            ┃╰──┼──█ Rail 15    
  Gas 45 █────┼━━━━ 45 ━━━━┛   ╰──█──╯              ┃   ╰──█            
         █────┤               Grid 100              ┃                   
         █──┬─╯                                     ┃                   
         █──┤                                       ┃ ╭────█            
         █──╯                                       ┗━┼────█ Industry 25
                                                      ╰─┬──█            
                                                        ╰──█            
```



## Quadrant priorities

Coordinates run from 0 to 1. Endpoint captions replace the corresponding numeric endpoint ticks.



```mermaid
quadrantChart
 title Campaign priorities
 x-axis Low Reach --> High Reach
 y-axis Low Engagement --> High Engagement
 quadrant-1 Expand
 quadrant-2 Promote
 quadrant-3 Reassess
 quadrant-4 Improve
 Search: [0.72, 0.80]
 Email: [0.25, 0.70]
 Social: [0.72, 0.25]
 Events: [0.25, 0.18]
 Partners: [0.72, 0.60]
 Referral: [0.25, 0.90]
```

```text
                              Campaign priorities                             
                                                                              
High Engagement │            Promote           │           Expand             
                │           Referral           │                              
                │               ●                                             
                │                              │         Search               
                │                              │            ●                 
                │                                                             
                │             Email            │                              
                │               ●              │                              
                │                                       Partners              
                │                              │            ●                 
                │                              │                              
                │── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ── ─
                │                              │                              
                │           Reassess           │           Improve            
                │                                                             
                │                              │         Social               
                │                              │            ●                 
                │            Events                                           
                │               ●              │                              
                │                              │                              
                │                                                             
                │                              │                              
 Low Engagement ──────────────────────────────────────────────────────────────
                Low Reach                                           High Reach
```



## Radar comparisons

Braille and blocks use polygon lines; box and ASCII adapt radar curves to grouped bars. `radarGrid: "outer"` keeps only the outer contour and spokes. `radarSeries: "cells"` uses whole-cell symbol edges instead of native lines.



```mermaid
radar-beta
 title Delivery options
 axis speed["Speed"], cost["Cost"], scale["Scale"], quality["Quality"], safety["Safety"], control["Control"]
 curve hosted["Hosted"] {9, 6, 9, 7, 8, 4}
 curve custom["Custom"] {4, 8, 6, 9, 7, 10}
 min 0
 max 10
 graticule polygon
 ticks 2
 showLegend true
```

```text
                          Delivery options                          
                                                                    
                                                                    
                                 Speed                              
                                                                    
                                 ⣀⠔⢺⠒⢄                              
                              ⢀⠤⠊  ⣼⢆ ⠉⠢⣀                           
                           ⢀⠤⠊⠁   ⡜⢸ ⠱⡀  ⠑⠢⡀                        
             Control    ⢀⡠⠒⠁     ⡜ ⢸  ⠈⢆   ⠈⠑⢄⡀    Cost             
                        ⣟⠫⣒⠒⠒⠒⠤⠤⡼⣤⣔⣺⣒⣄⣀⣀⣣⣀⣀⣀⣀⠔⢺                     
                        ⡿⡀ ⠑⠤⡀⣀⡜⠊  ⢸  ⠉⠢⣀⢘⡤⠊⡝ ⢸                     
                        ⡇⢇   ⢸⡹⠤⡀  ⢸   ⡠⠒⡇⢸⢠⠃ ⢸                     
                        ⡇⢸   ⣸⠁ ⠈⠒⢄⣸⣀⠔⠉  ⡇ ⣟  ⢸                     
                        ⡇ ⡇ ⡰⢹   ⣀⠔⢺⠒⢄⡀  ⡇⢀⠟⡄ ⢸                     
                        ⡇ ⢸⡰⠁⢸⣀⠔⠊  ⢸  ⠈⠒⢄⡇⡸ ⢣ ⢸                     
                        ⡇ ⡰⣧⠔⠉⠉⠢⢄  ⢸  ⣀⠔⠉⢩⠣⢄⠈⡆⢸                     
                        ⡧⠔⠉⠒⠵⣄   ⠉⠢⢼⠤⠊  ⡰⠁ ⢀⣉⠷⢼                     
              Safety    ⠈⠑⠤⡀  ⠙⡖⠤⣀ ⢸  ⣀⡼⠤⠒⠉⢁⡠⠊⠁    Scale            
                           ⠈⠒⢄⡀⠈⠢⡀⠉⢺⠊⡩⠃  ⡠⠔⠁                        
                              ⠈⠒⢄⠈⠢⣸⡔⠁⣀⠔⠉                           
                                 ⠉⠢⢼⠤⠊                              
                                                                    
                                Quality                             
                                                                    
                                                                    
         ⠠⠤⠤ A: Hosted                     ⠠⠤⠤ B: Custom            
```



## Treemap

Indentation defines hierarchy; leaf values follow colons. Preserve the nesting when copying source.



```mermaid
treemap-beta
 title Engineering budget
 "Product"
  "Portal": 22
  "Mobile": 18
 "Platform"
  "Cloud": 20
  "Security": 15
 "Delivery"
  "CI": 13
  "QA": 12
```

```text
                       Engineering budget                       
                                                                
┌──────────────────────────────────────────────┬───────────────┐
│ Product                                      │ Delivery      │
├─────────────────────────┬────────────────────┼───────────────┤
│ Portal                  │ Mobile             │ CI            │
│ 22                      │ 18                 │ 13            │
│                         │                    │               │
│                         │                    │               │
├─────────────────────────┴────────────────────┤               │
│ Platform                                     ├───────────────┤
├──────────────────────────┬───────────────────┤ QA            │
│ Cloud                    │ Security          │ 12            │
│ 20                       │ 15                │               │
│                          │                   │               │
└──────────────────────────┴───────────────────┴───────────────┘
```



## Adaptation and errors

Mermaid themes, browser actions, and configuration can remain inert; read `mermaid-degraded` entries for the actual replacement. `label-folded` identifies unsupported characters changed before wrapping. These are text layouts, so pixel-based Mermaid styling does not transfer directly.

Invalid source throws `GLYPH_MERMAID_SYNTAX`; a header belonging to another diagram family throws `GLYPH_MERMAID_NOT_CHART_TYPE`. Use [Diagrams](/diagrams/overview/) for flowcharts, sequences, and other node/edge syntax. The [CLI](/charts/cli/) accepts Mermaid through `glyphcss diagram`, not `glyphcss chart`.


---

# Mermaid Gantt, journey, and timeline charts in text

Use `renderGlyphChartMermaid` for all three families. Omit render `height` to let these structured layouts choose their content height; fixed heights can omit content and report it.

## Gantt schedules

Dates and `after` dependencies produce calendar intervals. Forward references are supported. Status tags such as `done`, `active`, and `crit` remain identifiable; milestones become dots when needed.



```mermaid
gantt
 title Portal release
 dateFormat YYYY-MM-DD
 axisFormat %b %d
 section Discovery
 Interviews :done, research, 2026-04-06, 3d
 Prototype :done, design, after research, 4d
 section Delivery
 API :active, api, after design, 5d
 Portal :portal, after design, 6d
 QA :crit, qa, after api portal, 3d
 section Rollout
 Preview :preview, after qa, 2d
 Training :training, after qa, 3d
 Launch :milestone, after preview training, 0d
```

```text
                                Portal release                                
                                                                              
Discovery                                                                     
    Interviews  done   █████████                                              
     Prototype  done            ███████████                                   
                                                                              
Delivery                                                                      
           API  active                     ███████████████                    
        Portal                             ██████████████████                 
            QA  crit                                         ████████         
                                                                              
Rollout                                                                       
       Preview                                                       ██████   
      Training                                                       █████████
        Launch                                                               ●
                     └───┬──────────┬───────────┬───────────┬──────────┬──────
                      Apr 07     Apr 11      Apr 15      Apr 19     Apr 23    
```



Calendar ticks use local dates and can coarsen to fit. Excluded days are not shaded; today/layout settings may remain inert with notes. Supply complete dates and task starts when their meaning matters; partial or missing dates can use logged epoch defaults.

## Journey scores and actors

Scores render as compact 0–5 bars with task and actor text, grouped by section. Out-of-range scores are clamped with notes.



```mermaid
journey
 title First order
 section Discover
 Find store: 4: Buyer
 Compare plans: 3: Buyer, Sales
 section Purchase
 Create account: 3: Buyer
 Add to cart: 4: Buyer
 Pay: 2: Buyer, Payments
 section Follow up
 Receipt: 5: Buyer
 Track delivery: 4: Buyer, Support
```

```text
                            First order                             
                                                                    
  Discover                                                          
    Find store      █████████████████████      4  Buyer             
    Compare plans   ████████████████           3  Buyer, Sales      
                                                                    
  Purchase                                                          
    Create account  ████████████████           3  Buyer             
    Add to cart     █████████████████████      4  Buyer             
    Pay             ██████████                 2  Buyer, Payments   
                                                                    
  Follow up                                                         
    Receipt         ██████████████████████████ 5  Buyer             
    Track delivery  █████████████████████      4  Buyer, Support    
```



## Timeline events

Periods and events form a table in source order, rather than a quantitative time axis. Whitespace-followed colons split events; embedded times and URLs retain their colons.



```mermaid
timeline
 title Portal roadmap
 section Foundation
 April : Interviews : Prototype
 May : API beta : Team login
 section Delivery
 June : Private preview : Usage charts
 July : Public launch : Support training
 section Growth
 August : Billing export
 September : Regional rollout
```

```text
                           Portal roadmap                           
                                                                    
                  Foundation                                        
                    April     │ - Interviews                        
                              │ - Prototype                         
                    May       │ - API beta                          
                              │ - Team login                        
                                                                    
                  Delivery                                          
                    June      │ - Private preview                   
                              │ - Usage charts                      
                    July      │ - Public launch                     
                              │ - Support training                  
                                                                    
                  Growth                                            
                    August    │ - Billing export                    
                    September │ - Regional rollout                  
```



Long event text wraps on words. Narrow layouts can stack the event column. Increase width or inspect omission notes when a fixed size cannot retain all entries. For ownership lanes and dependencies without dates, see [Git history and lane diagrams](/diagrams/gitgraph/).


---

# Mermaid packet headers and kanban boards as text

Both families use `renderGlyphChartMermaid(source, options)`. They share the chart target and color options but use structured layouts rather than numeric axes.

## Packet bit fields

Use absolute bit ranges; fields wrap across 32-bit rows with shared sharp borders. Vertical row keys show ascending decimal offsets.



```mermaid
packet-beta
 title Order event header
 0-7: "Version"
 8-15: "Flags"
 16-31: "Length"
 32-63: "Request ID"
 64-95: "Order ID"
 96-111: "Region"
 112-127: "Event type"
 128-159: "Checksum"
```

```text
                         Order event header                         
                                                                    
                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3   
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1   
 ┌───────────────┬───────────────┬───────────────────────────────┐  
 │    Version    │     Flags     │            Length             │  
 └───────────────┴───────────────┴───────────────────────────────┘  
  3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 6 6 6   
  2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3   
 ┌───────────────────────────────────────────────────────────────┐  
 │                          Request ID                           │  
 └───────────────────────────────────────────────────────────────┘  
  6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9   
  4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5   
 ┌───────────────────────────────────────────────────────────────┐  
 │                           Order ID                            │  
 └───────────────────────────────────────────────────────────────┘  
          1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   
  9 9 9 9 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2   
  6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7   
 ┌───────────────────────────────┬───────────────────────────────┐  
 │            Region             │          Event type           │  
 └───────────────────────────────┴───────────────────────────────┘  
  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1   
  2 2 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5   
  8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9   
 ┌───────────────────────────────────────────────────────────────┐  
 │                           Checksum                            │  
 └───────────────────────────────────────────────────────────────┘  
```



Narrow rows, overlapping/invalid ranges, inert config, and the 256-row limit produce render notes. Choose enough width for field names rather than relying on truncated labels.

## Kanban lanes and cards

Indent cards under lanes. Metadata can include assigned person, ticket, and priority; it wraps between complete items. Card URLs remain inert.



```mermaid
kanban
title Portal sprint
 ready[Ready]
  search[Search filters]@{ assigned: 'Mia', ticket: '241', priority: 'High' }
  export[Billing export]@{ assigned: 'Noah', ticket: '246' }
 doing[In progress]
  login[Team login]@{ assigned: 'Liam', ticket: '238' }
  alerts[Usage alerts]@{ assigned: 'Ava', ticket: '243' }
 done[Done]
  charts[Usage charts]@{ assigned: 'Mia', ticket: '235' }
  audit[Audit log]@{ assigned: 'Liam', ticket: '231' }
```

```text
                                Portal sprint                                 
                                                                              
┌───────────────────────┐  ┌──────────────────────┐  ┌───────────────────────┐
│ Ready                 │  │ In progress          │  │ Done                  │
├───────────────────────┤  ├──────────────────────┤  ├───────────────────────┤
│ ┌───────────────────┐ │  │ ┌──────────────────┐ │  │ ┌───────────────────┐ │
│ │ Search filters    │ │  │ │ Team login       │ │  │ │ Usage charts      │ │
│ │ #241 · Mia · High │ │  │ │ #238 · Liam      │ │  │ │ #235 · Mia        │ │
│ └───────────────────┘ │  │ └──────────────────┘ │  │ └───────────────────┘ │
│ ┌───────────────────┐ │  │ ┌──────────────────┐ │  │ ┌───────────────────┐ │
│ │ Billing export    │ │  │ │ Usage alerts     │ │  │ │ Audit log         │ │
│ │ #246 · Noah       │ │  │ │ #243 · Ava       │ │  │ │ #231 · Liam       │ │
│ └───────────────────┘ │  │ └──────────────────┘ │  │ └───────────────────┘ │
└───────────────────────┘  └──────────────────────┘  └───────────────────────┘
```



Preserve indentation and place the title outside lane data. Narrow boards can wrap lanes onto additional rows; read `report.ledger` for changes. Omit `height` for content-driven fitting. For graph-shaped workflows, use [flowcharts](/diagrams/flowcharts/) instead.


---

# ASCII and braille charts for chat, terminals, and the web

`@glyphcss/charts` draws charts into a cell canvas and returns text or escaped HTML spans. Display the result in a monospace `
`; no browser is needed to generate a static chart.

## Install and render a chart

```sh
npm install @glyphcss/charts
```

```ts
import { glyphChartLine, glyphChartPlot, renderGlyphChart } from "@glyphcss/charts";

const spec = glyphChartPlot({
  title: "Daily orders vs plan",
  marks: [
    glyphChartLine([18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57], {}, { name: "Orders" }),
    glyphChartLine([30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66], {}, { name: "Plan" }),
  ],
  axes: { x: { title: "Day (index)" }, y: { title: "Orders" } },
});
const result = renderGlyphChart(spec, {
  target: "chat",
  width: 64,
  height: 18,
});
console.log(result.text);
```



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  charset: "blocks",
  width: 64,
  height: 18
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   │                                                     ▗▄▄▄▄▄▄
60 ┤                                                  ▗▄▀▚▄▄▖   
   │                                          ▄▄▄▄▄▄▄▀▚▄▀▘  ▝▀▀▄
50 ┤                               ▄▄▄▄▄▄▄▄▞▀▀      ▄▀▘         
   │                         ▗▄▄▞▀▀ ▄▄▄           ▗▞            
40 ┤                    ▄▄▟█▀▘   ▗▞▀   ▀▀▀▄▄▖    ▞▘             
   │               ▄▄▞▀▀    ▀▀▀▄▀▘          ▝▀▀▄▀               
30 ┤▗▄▄▄▄▄▄▄▄▄▄▄▞▀▜▞                                            
   │             ▞▘                                             
   │    ▄▄▄▄▄▄▄▄▀                                               
20 └▗▞▀▀───────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
                            Day (index)                         
         ▗▄▄ Orders                       ▗▖▄ Plan              
```



A bare number array also works: `renderGlyphChart([18, 24, 21])` creates one line mark. Use a spec when marks share axes, scales, or a title.

## Compare the three targets

These previews use the same data at 60 × 12 cells. Terminal color is shown with CSS here; the terminal API default is ANSI truecolor. Chat defaults to plain box drawing because chat fonts misalign braille; this preview passes `charset: "blocks"`, which most chat fonts also draw cleanly. Terminal and web use braille.

### Chat · blocks



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "line",
  data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
  channels: {},
  options: {
    name: "Orders"
  }
}, {
  target: "chat",
  color: "none",
  charset: "blocks",
  width: 60,
  height: 12
});
console.log(text);
```

```text
60 ┤                                                  ▄▄▖   
   │                                               ▗▞▀  ▝▀▀▄
50 ┤                                             ▄▀▘        
   │                              ▄▄▖          ▗▞           
40 ┤                   ▄▄▄▖    ▗▞▀  ▝▀▀▄▄▖    ▞▘            
   │               ▄▞▀▀   ▝▀▀▄▀▘         ▝▀▀▄▀              
30 ┤             ▗▞                                         
   │            ▞▘                                          
   │    ▄▄▄▄▄▄▄▀                                            
20 └▗▞▀▀──────┬─────────┬─────────┬─────────┬─────────┬─────
    0         2         4         6         8        10     
                       ▗▄▄ Orders                           
```



### Terminal · braille



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "line",
  data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
  channels: {},
  options: {
    name: "Orders"
  }
}, {
  target: "terminal",
  width: 60,
  height: 12
});
console.log(text);
```

```text
60 ┤                                                  ⡠⢄⡀   
   │                                               ⢀⠔⠉  ⠈⠉⠒⠤
50 ┤                                             ⡠⠊⠁        
   │                              ⡠⢄⡀          ⢀⠜           
40 ┤                   ⣀⠤⢄⡀    ⢀⠔⠉  ⠈⠉⠒⠤⢄⡀    ⡔⠁            
   │               ⡠⠔⠊⠉   ⠈⠉⠒⠤⠊⠁         ⠈⠉⠒⠤⠊              
30 ┤             ⢀⠜                                         
   │            ⡔⠁                                          
   │    ⣀⠤⠤⠤⠤⠤⠤⠊                                            
20 └⠠⠔⠊⠉──────┬─────────┬─────────┬─────────┬─────────┬─────
    0         2         4         6         8        10     
                       ⠠⠤⠤ Orders                           
```



### Web · braille



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "line",
  data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
  channels: {},
  options: {
    name: "Orders"
  }
}, {
  target: "web",
  width: 60,
  height: 12
});
console.log(text);
```

```text
60 ┤                                                  ⡠⢄⡀   
   │                                               ⢀⠔⠉  ⠈⠉⠒⠤
50 ┤                                             ⡠⠊⠁        
   │                              ⡠⢄⡀          ⢀⠜           
40 ┤                   ⣀⠤⢄⡀    ⢀⠔⠉  ⠈⠉⠒⠤⢄⡀    ⡔⠁            
   │               ⡠⠔⠊⠉   ⠈⠉⠒⠤⠊⠁         ⠈⠉⠒⠤⠊              
30 ┤             ⢀⠜                                         
   │            ⡔⠁                                          
   │    ⣀⠤⠤⠤⠤⠤⠤⠊                                            
20 └⠠⠔⠊⠉──────┬─────────┬─────────┬─────────┬─────────┬─────
    0         2         4         6         8        10     
                       ⠠⠤⠤ Orders                           
```



## Choose your next step

- Learn the [spec, channels, scales, and axes](/charts/spec/).
- Try [line and area](/charts/line-area/), [bars](/charts/bar/), or [scatter plots](/charts/scatter/).
- Render [Mermaid charts](/charts/mermaid/) or explore [3D charts](/charts/3d/).
- Edit data in the [charts workbench](/charts/), render files with the [CLI](/charts/cli/), or embed charts in [vanilla JavaScript, React, and Vue](/charts/frameworks/).
- Install [glyphcss-diagrams](/coding-agents/install/) for charts in coding-agent conversations.
- For nodes, edges, and message exchanges, use the [Diagrams section](/diagrams/overview/).


---

# Text Sankey charts for flows between categories

Use `glyphChartSankey(data, { source, target, value, name?, color? })` for directed, positive-valued flows. The example is an illustrative energy balance; values use the same unit throughout.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "sankey",
  data: [
    {
      from: "Solar",
      to: "Grid",
      amount: 30
    },
    {
      from: "Wind",
      to: "Grid",
      amount: 25
    },
    {
      from: "Gas",
      to: "Grid",
      amount: 45
    },
    {
      from: "Grid",
      to: "Homes",
      amount: 40
    },
    {
      from: "Grid",
      to: "Shops",
      amount: 20
    },
    {
      from: "Grid",
      to: "Rail",
      amount: 15
    },
    {
      from: "Grid",
      to: "Industry",
      amount: 25
    }
  ],
  channels: {
    source: "from",
    target: "to",
    value: "amount"
  }
}, {
  target: "chat",
  width: 72,
  height: 24
});
console.log(text);
```

```text
         █──╮                  ╭──█──╮                  ╭──█            
         █──┴─╮              ╭─┴──█──┴─╮                ├──█            
Solar 30 █────┼━━━━━ 30 ━━━━━┼────█────┼━━━━ 40 ━━━━┓ ╭─┴──█            
         █──┬─╯              ╰─┬──█──┬─╯            ┗━┼────█ Homes 40   
         █──╯                  ╰──█──┤                ╰─┬──█            
                                  █──╯                  ├──█            
                             ╭────█                     ╰──█            
         █──╮              ┏━┼────█──╮                                  
         █──┴─╮            ┃ ╰─┬──█──┼───── 20 ─────╮                   
 Wind 25 █────┼━━━━ 25 ━━━━┛   ╰──█──╯              │ ╭────█            
         █──┬─╯                   █                 ╰─┼────█ Shops 20   
         █──╯                  ╭──█──┬───── 15 ──────╮╰─┬──█            
                               ├──█──╯               │  ╰──█            
                             ╭─┴──█                  │                  
         █──╮              ┏━┼────█────╮             │                  
         █──┴─╮            ┃ ╰─┬──█────┼━━━━ 25 ━━━━┓│  ╭──█            
         █────┤            ┃   ├──█──┬─╯            ┃╰──┼──█ Rail 15    
  Gas 45 █────┼━━━━ 45 ━━━━┛   ╰──█──╯              ┃   ╰──█            
         █────┤               Grid 100              ┃                   
         █──┬─╯                                     ┃                   
         █──┤                                       ┃ ╭────█            
         █──╯                                       ┗━┼────█ Industry 25
                                                      ╰─┬──█            
                                                        ╰──█            
```



```ts
import { glyphChartSankey, renderGlyphChart } from "@glyphcss/charts";
const mark = glyphChartSankey(
  [
    { from: "Solar", to: "Grid", amount: 30 },
    { from: "Wind", to: "Grid", amount: 25 },
    { from: "Gas", to: "Grid", amount: 45 },
    { from: "Grid", to: "Homes", amount: 40 },
    { from: "Grid", to: "Shops", amount: 20 },
    { from: "Grid", to: "Rail", amount: 15 },
    { from: "Grid", to: "Industry", amount: 25 },
  ],
  { source: "from", target: "to", value: "amount" },
);
const result = renderGlyphChart(mark, { target: "chat", width: 72, height: 24 });
```

- Values must be finite and greater than zero. Native cyclic input rejects with `sankey-cycle`.
- `sankey-imbalance` reports differing inflow/outflow totals at intermediate nodes.
- Increase width for more columns and height for more nodes/flows. Narrow layouts may fold thin flows into an identified “other” band or omit nodes; read every relevant render note.
- Sankey uses its graph structure, not Cartesian scales or transforms.
- This text renderer draws node stubs, brackets, and one line per flow rather than filled ribbons.

[Mermaid Sankey](/charts/mermaid/#sankey) accepts CSV source and can adapt cycles to a flow list. For dependencies without quantitative flow, use a [flowchart](/diagrams/flowcharts/).


---

# Scatter plots and dot charts in terminal text

Use `glyphChartDot(data, { x, y, fill? }, options?)` for scatter plots. Braille gives sub-cell point resolution; box and ASCII use whole-cell glyphs.

## Iris measurements

This thirty-flower excerpt follows the Iris dataset in the charts workbench: sepal length against petal length in centimetres. It samples ten observations from each species, rather than the complete 150-flower distribution.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "dot",
      data: [
        {
          sepal: 5.1,
          petal: 1.4,
          species: "setosa"
        },
        {
          sepal: 5.4,
          petal: 1.7,
          species: "setosa"
        },
        {
          sepal: 5.4,
          petal: 1.5,
          species: "setosa"
        },
        {
          sepal: 5.7,
          petal: 1.5,
          species: "setosa"
        },
        {
          sepal: 5.4,
          petal: 1.7,
          species: "setosa"
        },
        {
          sepal: 5,
          petal: 1.6,
          species: "setosa"
        },
        {
          sepal: 4.8,
          petal: 1.6,
          species: "setosa"
        },
        {
          sepal: 5,
          petal: 1.2,
          species: "setosa"
        },
        {
          sepal: 5,
          petal: 1.3,
          species: "setosa"
        },
        {
          sepal: 4.8,
          petal: 1.4,
          species: "setosa"
        },
        {
          sepal: 7,
          petal: 4.7,
          species: "versicolor"
        },
        {
          sepal: 5.7,
          petal: 4.5,
          species: "versicolor"
        },
        {
          sepal: 5,
          petal: 3.5,
          species: "versicolor"
        },
        {
          sepal: 6.7,
          petal: 4.4,
          species: "versicolor"
        },
        {
          sepal: 5.9,
          petal: 4.8,
          species: "versicolor"
        },
        {
          sepal: 6.6,
          petal: 4.4,
          species: "versicolor"
        },
        {
          sepal: 5.5,
          petal: 3.8,
          species: "versicolor"
        },
        {
          sepal: 6,
          petal: 4.5,
          species: "versicolor"
        },
        {
          sepal: 5.5,
          petal: 4.4,
          species: "versicolor"
        },
        {
          sepal: 5.7,
          petal: 4.2,
          species: "versicolor"
        },
        {
          sepal: 6.3,
          petal: 6,
          species: "virginica"
        },
        {
          sepal: 7.6,
          petal: 6.6,
          species: "virginica"
        },
        {
          sepal: 6.5,
          petal: 5.1,
          species: "virginica"
        },
        {
          sepal: 6.4,
          petal: 5.3,
          species: "virginica"
        },
        {
          sepal: 6.9,
          petal: 5.7,
          species: "virginica"
        },
        {
          sepal: 7.2,
          petal: 6,
          species: "virginica"
        },
        {
          sepal: 7.4,
          petal: 6.1,
          species: "virginica"
        },
        {
          sepal: 7.7,
          petal: 6.1,
          species: "virginica"
        },
        {
          sepal: 6.7,
          petal: 5.6,
          species: "virginica"
        },
        {
          sepal: 6.7,
          petal: 5.2,
          species: "virginica"
        }
      ],
      channels: {
        x: "sepal",
        y: "petal",
        fill: "species"
      }
    }
  ],
  axes: {
    x: {
      title: "Sepal (cm)"
    },
    y: {
      title: "Petal (cm)"
    }
  },
  title: "Iris: three species",
  scales: {
    x: {
      domain: [4, 8],
      nice: false
    },
    y: {
      domain: [0, 8],
      nice: false
    }
  }
}, {
  target: "web",
  width: 68,
  height: 22
});
console.log(text);
```

```text
                         Iris: three species                        
                                                                    
Petal (cm)                                                          
                                                                    
8 ┤                                                                 
  │                                                                 
  │                                                          ⣤      
6 ┤                                                      ⣤    ⣤     
  │                                     ⠛     ⣤  ⣤    ⠛             
  │                                      ⠛ ⣤  ⠛                     
  │                        ⣤  ⣤  ⠛ ⣤         ⣤⣤    ⠛                
4 ┤                        ⣤  ⠛                                     
  │                ⠛                                                
  │                                                                 
2 ┤                                                                 
  │             ⣤  ⣤     ⣤    ⣤                                     
  │             ⠛  ⠛ ⠛                                              
  │                                                                 
0 └┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬───────┬
   4      4.5      5      5.5      6      6.5      7      7.5      8
                              Sepal (cm)                            
     ⣤  setosa           ⣤  versicolor          ⣤  virginica        
```



```ts
import { glyphChartDot, renderGlyphChart } from "@glyphcss/charts";
const result = renderGlyphChart(glyphChartDot([
  { sepal: 5.1, petal: 1.4, species: "setosa" },
  { sepal: 7.0, petal: 4.7, species: "versicolor" },
], { x: "sepal", y: "petal", fill: "species" }), { target: "terminal" });
```

Dots in the same cell may overlap. Increase width/height or aggregate dense data before rendering. There is no 2D point-size or shape option. Add [text annotations](/charts/annotations/) for selected observations, or use [3D scatter](/charts/3d/#scatter) for a third numeric coordinate.


---

# Chart spec reference: marks, channels, scales, and axes

`glyphChartPlot({ marks, scales?, axes?, title?, description?, legend? })` returns a plain `GlyphChartSpec`. `renderGlyphChart(input, options?)` accepts that spec, one mark, an array of marks, or a number array.

## Spec and mark shape

```ts
import { glyphChartBar, glyphChartPlot, renderGlyphChart } from "@glyphcss/charts";

const spec = glyphChartPlot({
  marks: [
    glyphChartBar(
      [
        { quarter: "25Q1", revenue: 12000 },
        { quarter: "25Q2", revenue: 18000 },
        { quarter: "25Q3", revenue: 16000 },
        { quarter: "25Q4", revenue: 19500 },
        { quarter: "26Q1", revenue: 17500 },
        { quarter: "26Q2", revenue: 20000 },
      ],
      { x: "quarter", y: "revenue" },
      { name: "Revenue", color: "#38bdf8" },
    ),
  ],
  scales: { x: { type: "band" }, y: { type: "linear", domain: [0, 20000], nice: false } },
  axes: {
    x: { title: "Quarter", ticks: 6, titleAt: "center" },
    y: { title: "USD", ticks: 4, grid: true, format: { preset: "currency", decimals: 0 } },
  },
  title: { text: "Quarterly revenue", align: "left", position: "top" },
  description: "Illustrative revenue in US dollars.",
  legend: false,
});
const result = renderGlyphChart(spec, { target: "web", width: 72, height: 20 });
```



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "bar",
      data: [
        {
          quarter: "25Q1",
          revenue: 12000
        },
        {
          quarter: "25Q2",
          revenue: 18000
        },
        {
          quarter: "25Q3",
          revenue: 16000
        },
        {
          quarter: "25Q4",
          revenue: 19500
        },
        {
          quarter: "26Q1",
          revenue: 17500
        },
        {
          quarter: "26Q2",
          revenue: 20000
        }
      ],
      channels: {
        x: "quarter",
        y: "revenue"
      },
      options: {
        name: "Revenue",
        color: "#38bdf8"
      }
    }
  ],
  scales: {
    x: {
      type: "band"
    },
    y: {
      type: "linear",
      domain: [0, 20000],
      nice: false
    }
  },
  axes: {
    x: {
      title: "Quarter",
      ticks: 6,
      titleAt: "center"
    },
    y: {
      title: "USD",
      ticks: 4,
      grid: true,
      format: {
        preset: "currency",
        decimals: 0
      }
    }
  },
  title: {
    text: "Quarterly revenue",
    align: "left",
    position: "top"
  },
  description: "Illustrative revenue in US dollars.",
  legend: false
}, {
  target: "web",
  width: 72,
  height: 20
});
console.log(text);
```

```text
Quarterly revenue                                                       
                                                                        
USD                                                                     
                                                                        
$20,000 ┤┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈▅▅▅┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈███┈┈┈┈
        │              ▆▆▆                  ███       ▃▃▃        ███    
        │              ███        ▃▃▃       ███       ███        ███    
        │              ███        ███       ███       ███        ███    
        │              ███        ███       ███       ███        ███    
        │    ▆▆▆       ███        ███       ███       ███        ███    
$10,000 ┤┈┈┈┈███┈┈┈┈┈┈┈███┈┈┈┈┈┈┈┈███┈┈┈┈┈┈┈███┈┈┈┈┈┈┈███┈┈┈┈┈┈┈┈███┈┈┈┈
        │    ███       ███        ███       ███       ███        ███    
        │    ███       ███        ███       ███       ███        ███    
        │    ███       ███        ███       ███       ███        ███    
        │    ███       ███        ███       ███       ███        ███    
        │    ███       ███        ███       ███       ███        ███    
        │    ███       ███        ███       ███       ███        ███    
     $0 └─────┬─────────┬──────────┬─────────┬─────────┬──────────┬─────
            25Q1      25Q2       25Q3      25Q4      26Q1       26Q2    
                                     Quarter                            
```



Each mark has `type`, nonempty `data`, `channels`, and optional `transform` and `options`. Constructors return this same shape. Put transforms beside `channels`, not inside `options`.

| Spec field | Meaning |
| --- | --- |
| `marks` | Array of composed marks. Supported types: line, area, bar, dot, arc, cell, text, rule, sankey, funnel, treemap. |
| `scales.x`, `scales.y` | Shared `type`, `domain`, and `nice` settings. |
| `axes.x`, `axes.y` | Axis titles, ticks, lines, grid, and formatting. `axes.color` sets a shared color. |
| `title` | String, or `{ text, align?, position? }`. Align: left/center/right; position: top/bottom. |
| `description` | Text exposed through `result.meta.description`. Supply accessible prose separately in your UI. |
| `legend` | Boolean or `{ placement }`. See placements below. |

## Channels and mark options

A channel is a field-name string, `(datum, index) => value`, or a parallel array of values. Function channels are JavaScript-only. For numeric arrays, Cartesian marks infer index/value coordinates; horizontal bars infer value/index.

| Channel | Use |
| --- | --- |
| `x`, `y` | Coordinates; record-based Cartesian marks need both. Arc values use `y`. |
| `fill`, `stroke` | Series identity; `cell.fill` carries the numeric heatmap value. Use `options.color` for literal colors. |
| `label` | Text labels and slice names. |
| `x0` | Start of a horizontal bar interval, with `x` as its end. |
| `source`, `target`, `value` | Sankey endpoints and flow magnitude. |
| `stage`, `value` | Funnel stage name and magnitude. |
| `id`, `parent`, `value`, `label` | Treemap hierarchy, leaf magnitude, and displayed name. |

Mark `options` supports `name`, `color`, `strokeWidth` (1, 2, or 3), `orientation` (vertical/horizontal bars), `innerRadius` (arc hole fraction, 0 inclusive to 1 exclusive), `labels` (arc callout/legend-only), and `axis` (rule x/y). Arbitrary size, shape, or curve options are unsupported.

Most constructors take `(data, channels?, options?)`. Exceptions: `glyphChartRule(values, options?)`; `glyphChartSankey(data, { source, target, value, name?, color? })`; `glyphChartFunnel(data, { stage?, value?, name?, color? })`.

## Scales

- `type`: `linear`, `log`, `sqrt`, `time`, `band`, or `ordinal`.
- `domain`: numeric endpoints, time endpoints (`Date` or ISO strings), or ordered categorical values.
- `nice`: boolean controlling domain rounding.
- Bar and area domains include zero, except floating intervals. An explicit domain that excludes their zero baseline rejects with `bar-domain-excludes-zero`.
- A log domain must stay on one side of zero. Mixed numeric and categorical x coordinates reject with `mixed-x-scale`.
- Sankey, funnel, and treemap marks have no x/y scales; explicit scale settings and transforms are rejected.

## Axes and tick formats

Both axes accept `title`, `ticks` (requested count), `tickMarks`, `line`, `grid`, `color`, and `format`. `line: false` hides the axis line and tick marks while retaining labels and title. `ticks: 0` hides tick labels. Layout can thin requested ticks to avoid collisions.

Field-name channels supply automatic axis titles when space allows. Use `title: ""` to suppress them. `axes.x.titleAt` is `start`, `center`, or `end`; `axes.y.titleAt` is `top` or `bottom`. Tight layouts can omit or stack title rows, with render notes.

`format` accepts a preset name, a parameter object, or `(value, index, ticks) => string` in JavaScript. It changes axis ticks, not pie percentages or funnel labels.

| Presets | Parameters |
| --- | --- |
| `auto`, `number`, `si`, `compact`, `integer`, `scientific` | None. `auto` is the default. |
| `percent` | Optional `of` (default 1; use 100 for values already in 0–100). |
| `currency` | Optional `symbol` (default `$`) and `decimals` (default 2). |
| `decimals` | Required `places`. |
| `date`, `year`, `month`, `day`, `time` | None. |
| `template` | Required `pattern`, for example `"{value} ms"`. |

## Transforms

A mark takes one `transform: { kind, n?, by?, reduce? }`. It runs after channel resolution and before scales. These are small built-in transforms, not the full Observable Plot API.

| Kind | Behavior |
| --- | --- |
| `bin` | Equal-width bins over numeric x; y becomes count. `n` defaults to 10. |
| `stack` | Rows stack in input order at each x; `by` does not change stack order. |
| `group` | Aggregate y for each distinct x; `reduce` defaults to sum. |
| `normalize` | Divide y by the largest absolute y in each `by` group; default grouping uses fill, or all rows without fill. |
| `window` | Reduce a window around each row, using input order; `n` defaults to 3 and `reduce` to mean. Sort data first. |

`reduce` accepts `mean`, `sum`, `min`, or `max`. `by` uses resolved rows (for example `"fill"`), not arbitrary original record fields. `n` must be a positive integer. Horizontal bars and structural marks do not support transforms.

```ts
import { glyphChartLine } from "@glyphcss/charts";
const smoothed = {
  ...glyphChartLine([18, 24, 21, 35, 42, 39, 48]),
  transform: { kind: "window" as const, n: 3, reduce: "mean" as const },
};
```



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "line",
  data: [18, 24, 21, 35, 42, 39, 48],
  channels: {},
  transform: {
    kind: "window",
    n: 3,
    reduce: "mean"
  }
}, {
  target: "chat",
  charset: "blocks",
  width: 60,
  height: 16
});
console.log(text);
```

```text
   │                                             ▗▄▄▄▄▄▄▄▄▄▄
   │                                          ▗▄▀▘          
40 ┤                                       ▗▄▀▘             
   │                                     ▄▀▘                
   │                                  ▗▄▀                   
35 ┤                                ▗▞▘                     
   │                              ▄▞▘                       
   │                           ▗▄▀                          
30 ┤                        ▄▄▀▘                            
   │                     ▄▞▀                                
   │                  ▄▀▀                                   
   │               ▗▄▀                                      
25 ┤             ▗▞▘                                        
   │           ▄▞▘                                          
   └▗▄▄▄▄▄▄▄▄▄▀───────┬─────────┬────────┬────────┬────────┬
    0        1        2         3        4        5        6
```



## Legends, color, and size

`legend: true` uses bottom placement; `false` suppresses it. Object placements are `bottom`, `top-left`, `top-right`, `bottom-left`, `bottom-right`, or `title`. Corner legends occupy plot cells. Title placement can fall back to bottom when it cannot fit. Render-option `legend` overrides the spec.

`options.name` names a mark's series. `options.color` takes a canonical lowercase `#rrggbb` or an array cycling through its series (arc: slices; sankey: source nodes; funnel: stages; cell: ramp ink or loss/gain colors). Axis colors use the same hex format.

Render `width` and `height` are positive integer cell budgets, not pixels. `target`, `charset`, `color`, `detail`, `cellAspect`, `textScale`, `regionFill`, `shades`, `cellRamp`, `env`, `radarGrid`, and `radarSeries` are render options, not spec fields. See [targets and color](/charts/targets/) for their values and defaults.

## JSON Schema and validation

```ts
import { glyphChartJsonSchema, validateGlyphChartSpec, renderGlyphChart } from "@glyphcss/charts";

const spec = { marks: [{ type: "line" as const, data: [3, 5, 4], channels: {} }] };
validateGlyphChartSpec(spec); // Returns the spec, or throws an error with a code.
const schema = glyphChartJsonSchema(); // Feed to your JSON Schema validator/editor.
const result = renderGlyphChart(spec); // Also checks resolved data and layout constraints.
console.log(schema, result.report.ledger);
```

Schema validation covers JSON structure; resolved channel values and graph/hierarchy constraints also need the renderer. Accessors, callback formats, and `Date` objects need JavaScript equivalents in JSON (field names/arrays, named formats, ISO strings).

`buildGlyphChart(spec, options)` creates the canvas model; `encodeGlyphChart(build, "text" | "html")` encodes it. `renderGlyphChart` composes both and returns `text`, optional `html`, `build`, `meta`, and `report`. `renderGlyphChartJson(json, options)` returns a JSON string containing output or a tagged error.


---

# Chart charsets, ANSI color, and output targets

Targets select defaults; explicit render options override them. The library default target is `web`. The command-line chart target defaults to `terminal`.

| Target | Width × height in cells | Charset | Color |
| --- | --- | --- | --- |
| `chat` | 72 × 24 | `box` | `none` |
| `terminal` | 80 × 24 | `braille` | `truecolor` |
| `web` | 96 × 32 | `braille` | `css` |

## Choose a charset

| Charset | Use |
| --- | --- |
| `ascii` | Strict 7-bit output where Unicode support is uncertain. |
| `box` | Readable whole-cell lines and junctions, the default for chat. |
| `blocks` | Filled regions and sub-cell boundaries using block glyphs. |
| `braille` | Fine sub-cell lines and dots for terminal or web charts. Requires matching font coverage. |

The same illustrative twelve-day order series and plan rendered with each charset:

### ASCII



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  width: 64,
  height: 18,
  charset: "ascii"
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   |                                                     _------
60 +                                                  _-'_--_   
   |                                         _-------'_-'    `--
50 +                              _---------'       -'          
   |                         _---' _--_           /'            
40 +                   _---''    --    ``---_   ,/              
   |              _---'     ``--'            `-/                
30 +-------------'/'                                            
   |            ,/                                              
   |   _-------/                                                
20 +--'--------+---------+----------+----------+----------+-----
    0          2         4          6          8         10     
                            Day (index)                         
         --- Orders                       --  Plan              
```



### Box



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  width: 64,
  height: 18,
  charset: "box"
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   │                                                     _──────
60 ┤                                                  _-‾_--_   
   │                                         _-─────-‾_-‾    ‾--
50 ┤                              _-──────--‾       -‾          
   │                         _---‾ _--_           /‾            
40 ┤                   _---‾‾    --    ‾‾---_   _/              
   │              _---‾     ‾‾--‾            ‾-/                
30 ┤───────────--‾/‾                                            
   │            _/                                              
   │   _-──────/                                                
20 └--‾────────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
                            Day (index)                         
         ─── Orders                       ──  Plan              
```



### Blocks



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  width: 64,
  height: 18,
  charset: "blocks"
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   │                                                     ▗▄▄▄▄▄▄
60 ┤                                                  ▗▄▀▚▄▄▖   
   │                                          ▄▄▄▄▄▄▄▀▚▄▀▘  ▝▀▀▄
50 ┤                               ▄▄▄▄▄▄▄▄▞▀▀      ▄▀▘         
   │                         ▗▄▄▞▀▀ ▄▄▄           ▗▞            
40 ┤                    ▄▄▟█▀▘   ▗▞▀   ▀▀▀▄▄▖    ▞▘             
   │               ▄▄▞▀▀    ▀▀▀▄▀▘          ▝▀▀▄▀               
30 ┤▗▄▄▄▄▄▄▄▄▄▄▄▞▀▜▞                                            
   │             ▞▘                                             
   │    ▄▄▄▄▄▄▄▄▀                                               
20 └▗▞▀▀───────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
                            Day (index)                         
         ▗▄▄ Orders                       ▗▖▄ Plan              
```



### Braille



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  width: 64,
  height: 18,
  charset: "braille"
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   │                                                     ⢀⡠⠤⠤⠤⠤⠤
60 ┤                                                  ⢀⡠⠒⢁⡠⢄⡀   
   │                                          ⣀⠤⠤⠤⠤⠤⠤⠒⢁⡠⠒⠁  ⠈⠉⠒⠤
50 ┤                               ⣀⠤⠤⠤⠤⠤⠤⠤⠔⠊⠉      ⡠⠒⠁         
   │                         ⢀⣀⠤⠔⠊⠉ ⡠⢄⣀           ⢀⠜            
40 ┤                    ⣀⠤⢔⣒⠉⠁   ⢀⠔⠉   ⠉⠑⠒⠤⢄⡀    ⡔⠁             
   │               ⣀⡤⠔⠊⠉    ⠉⠑⠒⠤⠊⠁          ⠈⠉⠒⠤⠊               
30 ┤⠠⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠤⠔⠊⢉⠜                                            
   │             ⡔⠁                                             
   │    ⣀⠤⠤⠤⠤⠤⠤⠤⠊                                               
20 └⠠⠔⠊⠉───────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
                            Day (index)                         
         ⠠⠤⠤ Orders                       ⠠⠄⠤ Plan              
```



Chat clients control their fonts and commonly lose braille alignment or ANSI escapes. Prefer box or ASCII when pasting into a conversation.

## Choose a color encoding

| `color` | Result |
| --- | --- |
| `none` | Plain `result.text`. |
| `ansi16` | Text with 16-color ANSI escapes. |
| `ansi256` | Text with 256-color ANSI escapes. |
| `truecolor` | Text with 24-bit ANSI escapes. |
| `css` | Plain text plus `result.html`, an escaped span fragment for a `
`. |

There is no `color: "ansi"` value. Pass `env: process.env` explicitly in Node when `NO_COLOR`/`FORCE_COLOR` should affect ANSI output; the library does not read the process environment implicitly. The CLI does this for you.

```ts
import { renderGlyphChart } from "@glyphcss/charts";
const result = renderGlyphChart([18, 24, 21, 35, 42], {
  target: "terminal", color: "ansi256", env: process.env,
  width: 60, height: 12,
});
console.log(result.text);
```

These documentation previews display terminal examples with CSS color, since ANSI escape sequences do not color HTML pages.

## Size and detail

- `width` and `height` are positive integer cell budgets. Increasing them changes layout and data resolution; changing CSS font size changes physical size.
- `detail` accepts `auto`, `faithful`, `balanced`, or `simplified`; always inspect fitting notes rather than assuming every label survives a small budget.
- `cellAspect` is column width divided by row height. It adjusts arc shaping; use measured monospace metrics when overriding it.
- `textScale` is an integer at least 1 for web HTML text sizing. Plain text/ANSI and compiled outputs ignore it. It reserves more cells for titles, ticks, and labels.
- `regionFill` accepts `auto`, `solid`, or `texture`. Colored outputs may use solid regions; plain text keeps textures. Indistinguishable solid series fall back to textures with a note.
- `shades` replaces series texture glyphs. `cellRamp` replaces unsigned heatmap ramp glyphs. Each must be a nonempty array of single visible characters; ASCII requires 7-bit characters.
- Mermaid radar alone reads `radarGrid: "all" | "outer"` and `radarSeries: "line" | "cells"`.

Use a font covering braille U+2800–U+28FF, box drawing, and blocks with consistent advances. On web output use `font-family: "Glyph Mono", ui-monospace, monospace` and `line-height: 1`, and load the font in your application. See [framework snippets](/charts/frameworks/) and [troubleshooting](/charts/troubleshooting/).


---

# Text treemaps for hierarchical budgets and totals

Use `glyphChartTreemap(data, channels?, options?)`. Its default channels are `{ id: "id", parent: "parent", value: "value", label: "label" }`.

## Engineering allocation

These illustrative budget units form one root with three teams and six leaves. Branch totals come from children; assign magnitudes to leaves.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  type: "treemap",
  data: [
    {
      id: "root",
      parent: null,
      label: "Engineering"
    },
    {
      id: "Product",
      parent: "root",
      label: "Product"
    },
    {
      id: "Portal",
      parent: "Product",
      label: "Portal",
      value: 22
    },
    {
      id: "Mobile",
      parent: "Product",
      label: "Mobile",
      value: 18
    },
    {
      id: "Platform",
      parent: "root",
      label: "Platform"
    },
    {
      id: "Cloud",
      parent: "Platform",
      label: "Cloud",
      value: 20
    },
    {
      id: "Security",
      parent: "Platform",
      label: "Security",
      value: 15
    },
    {
      id: "Delivery",
      parent: "root",
      label: "Delivery"
    },
    {
      id: "CI",
      parent: "Delivery",
      label: "CI",
      value: 13
    },
    {
      id: "QA",
      parent: "Delivery",
      label: "QA",
      value: 12
    }
  ],
  channels: {
    id: "id",
    parent: "parent",
    value: "value",
    label: "label"
  }
}, {
  target: "chat",
  width: 64,
  height: 16
});
console.log(text);
```

```text
┌──────────────────────────────────────────────────────────────┐
│ Engineering                                                  │
├──────────────────────────────────────────────┬───────────────┤
│ Product                                      │ Delivery      │
├─────────────────────────┬────────────────────┼───────────────┤
│ Portal                  │ Mobile             │ CI            │
│ 22                      │ 18                 │ 13            │
│                         │                    │               │
│                         │                    │               │
├─────────────────────────┴────────────────────┤               │
│ Platform                                     ├───────────────┤
├──────────────────────────┬───────────────────┤ QA            │
│ Cloud                    │ Security          │ 12            │
│ 20                       │ 15                │               │
│                          │                   │               │
└──────────────────────────┴───────────────────┴───────────────┘
```



```ts
import { glyphChartTreemap, renderGlyphChart } from "@glyphcss/charts";
const result = renderGlyphChart(
  glyphChartTreemap([
    { id: "root", parent: null, label: "Engineering" },
    { id: "Product", parent: "root", label: "Product" },
    { id: "Portal", parent: "Product", label: "Portal", value: 22 },
    { id: "Mobile", parent: "Product", label: "Mobile", value: 18 },
    { id: "Platform", parent: "root", label: "Platform" },
    { id: "Cloud", parent: "Platform", label: "Cloud", value: 20 },
    { id: "Security", parent: "Platform", label: "Security", value: 15 },
    { id: "Delivery", parent: "root", label: "Delivery" },
    { id: "CI", parent: "Delivery", label: "CI", value: 13 },
    { id: "QA", parent: "Delivery", label: "QA", value: 12 },
  ]),
  { target: "chat", width: 64, height: 16 },
);
```

Ids must be unique, parents must exist, and the hierarchy must be acyclic. Use null or an empty parent for roots. Leaves require finite, nonnegative values. Invalid hierarchy rejects with `treemap-hierarchy`.

Tiles share borders. Labels and leaf values need interior space; small tiles or whole labels that do not fit are omitted with `treemap-omitted`. Increase dimensions or aggregate tiny categories before rendering. Treemap rejects x/y scales and transforms.

For indented source syntax, see [Mermaid treemaps](/charts/mermaid/#treemap). For entity relationships rather than weighted areas, use [ER diagrams](/diagrams/er/).


---

# Fix chart validation errors, missing labels, and braille fonts

Validation failures throw tagged errors. Layout adaptations succeed but add `result.report.ledger` entries. Treat them separately: fix invalid data before increasing the chart size.

## Validate and read the report

```ts
import { renderGlyphChart, validateGlyphChartSpec, glyphChartRepairHint } from "@glyphcss/charts";
const spec = {
  marks: [
    {
      type: "line" as const,
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: { name: "Orders" },
    },
    {
      type: "line" as const,
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: { name: "Plan" },
    },
  ],
  title: "Daily orders vs plan",
  axes: { x: { title: "Day (index)" }, y: { title: "Orders" } },
};
try {
  validateGlyphChartSpec(spec);
  const result = renderGlyphChart(spec, { target: "chat", width: 64, height: 18 });
  console.log(result.text);
  for (const entry of result.report.ledger) console.warn(entry.code, entry.message, entry.detail);
} catch (error) {
  if (error instanceof Error) {
    console.error(error.message);
    if ("code" in error) console.error(glyphChartRepairHint(String(error.code)));
  }
}
```

This illustrative order series fits both its data and legend at 64 × 18 cells. Inspect the report before reducing the budget.



```ts
import { renderGlyphChart } from "@glyphcss/charts";

const { text } = renderGlyphChart({
  marks: [
    {
      type: "line",
      data: [18, 24, 21, 35, 42, 39, 48, 44, 38, 52, 61, 57],
      channels: {},
      options: {
        name: "Orders"
      }
    },
    {
      type: "line",
      data: [30, 32, 34, 38, 44, 46, 50, 52, 54, 58, 64, 66],
      channels: {},
      options: {
        name: "Plan"
      }
    }
  ],
  title: "Daily orders vs plan",
  axes: {
    x: {
      title: "Day (index)"
    },
    y: {
      title: "Orders"
    }
  }
}, {
  target: "chat",
  charset: "blocks",
  width: 64,
  height: 18
});
console.log(text);
```

```text
                      Daily orders vs plan                      
                                                                
Orders                                                          
                                                                
   │                                                     ▗▄▄▄▄▄▄
60 ┤                                                  ▗▄▀▚▄▄▖   
   │                                          ▄▄▄▄▄▄▄▀▚▄▀▘  ▝▀▀▄
50 ┤                               ▄▄▄▄▄▄▄▄▞▀▀      ▄▀▘         
   │                         ▗▄▄▞▀▀ ▄▄▄           ▗▞            
40 ┤                    ▄▄▟█▀▘   ▗▞▀   ▀▀▀▄▄▖    ▞▘             
   │               ▄▄▞▀▀    ▀▀▀▄▀▘          ▝▀▀▄▀               
30 ┤▗▄▄▄▄▄▄▄▄▄▄▄▞▀▜▞                                            
   │             ▞▘                                             
   │    ▄▄▄▄▄▄▄▄▀                                               
20 └▗▞▀▀───────┬─────────┬──────────┬──────────┬──────────┬─────
    0          2         4          6          8         10     
                            Day (index)                         
         ▗▄▄ Orders                       ▗▖▄ Plan              
```



Structural validation cannot resolve every accessor or hierarchy. Rendering performs the additional checks. Use [JSON Schema](/charts/spec/#json-schema-and-validation) in an editor, then render the actual data.

## Common error codes

| Code | Repair |
| --- | --- |
| `bad-chart-input`, `empty-marks`, `empty-data` | Supply a supported input shape and nonempty marks/data. |
| `missing-xy-channels`, `bad-channels` | Map both x/y for Cartesian record data; channels are fields, arrays, or functions. |
| `non-finite-data` | Remove NaN/Infinity and return finite numeric values from accessors. |
| `arc-missing-value`, `funnel-missing-value`, `sankey-bad-value` | Supply required value channels; Sankey values must be positive. |
| `funnel-bad-value` | Use nonnegative finite stage values. |
| `bad-scale`, `log-domain`, `bad-time-domain` | Use valid types/domains; log domains cannot cross zero and time domains need valid dates. |
| `mixed-x-scale` | Keep numeric and categorical x values out of the same shared scale. |
| `bar-domain-excludes-zero` | Include zero for baseline bars/areas, or use horizontal floating intervals. |
| `sankey-cycle`, `treemap-hierarchy` | Repair cyclic flows or invalid parent/id trees. |
| `bad-size`, `bad-text-scale` | Use positive integer cell dimensions and integral textScale ≥1. |
| `bad-options`, `bad-stroke-width`, `invalid-inner-radius` | Remove unsupported options; strokeWidth is 1–3, arc hole is in `[0, 1)`. |
| `bad-axis-color`, `bad-mark-color`, `bad-axis-title-at`, `bad-tick-format` | Use lowercase six-digit hex, the correct axis placement vocabulary, and supported formats. |
| `GLYPH_MERMAID_SYNTAX`, `GLYPH_MERMAID_NOT_CHART_TYPE` | Fix Mermaid source, or route diagram headers to the [diagram renderer](/diagrams/overview/). |

`glyphChartRepairHint(code)` covers native validation and several runtime errors, and returns undefined for unknown codes. Use the error message and dedicated guide for other codes. 3D exports `GLYPH_CHART_3D_VALIDATION_RULES` and `glyphChart3dRepairHint` separately.

## Output fits, but information is missing

- `ticks-thinned`, `label-dropped`, `label-abbreviated`, `title-dropped`, or `legend-dropped`: increase the cell budget, simplify labels, or move/suppress optional chrome.
- `legend-placement-degraded`: title placement did not fit; the legend moved to bottom.
- `treemap-omitted`, `sankey-folded-flows`, or `funnel-folded-stages`: aggregate tiny categories or provide more space.
- `label-folded`: source characters were replaced to fit the output vocabulary.
- `mermaid-degraded`: a source feature was adapted or kept inert. Read the message rather than assuming browser Mermaid styling survived.

## Braille is broken or rows do not join

Use Glyph Mono or another font covering braille, box drawing, and block elements at consistent monospace advances. Disable proportional font substitution. In HTML, keep `white-space: pre` and `line-height: 1`; color spans must inherit the same metrics.

Chat applications choose their own fonts. If you cannot control them, use `target: "chat"` with box drawing, or `charset: "ascii"`. ANSI escapes are for terminals, not chat or HTML; use CSS output on web pages.

## The chart is blank or different after copy

An all-zero pie/funnel reports `empty-total`; negative pie slices are omitted. Heatmap zero can be intentionally blank. Inspect the actual data and the report before changing CSS. Colored HTML and plain text can use different region fills while preserving series readability. Copy `result.text` for text consumers and `result.html` for web color; never copy ANSI into an HTML element.


---

# Install the coding-agent skills

```sh
npx skills add apresmoi/glyphcss-diagrams
```

Requires **Node.js 22+**. Select hosts; start a new session. Use one install route per host.

> Use glyphcss-diagrams to draw Request → Agent → Answer.



```mermaid
flowchart LR; request[Request] --> agent[Agent] --> answer[Answer]
```

```text
       ┌─────────┐  ┌───────┐  ┌────────┐       
       │ Request │──▶ Agent │──▶ Answer │       
       └─────────┘  └───────┘  └────────┘       
```



## Diagrams and charts

```sh
claude plugin marketplace add apresmoi/glyphcss-diagrams
claude plugin install glyphcss-diagrams@glyphcss-diagrams
claude plugin details glyphcss-diagrams@glyphcss-diagrams
```

Invoke `/glyphcss-diagrams:glyphcss-diagrams`.

  

```sh
codex plugin marketplace add apresmoi/glyphcss-diagrams
codex plugin add glyphcss-diagrams@glyphcss-diagrams
codex plugin list --marketplace glyphcss-diagrams
```

Requires `codex plugin`; otherwise use the installer above.

  

```sh
copilot plugin marketplace add apresmoi/glyphcss-diagrams
copilot plugin install glyphcss-diagrams@glyphcss-diagrams
copilot skill list
```

  

```sh
droid plugin marketplace add https://github.com/apresmoi/glyphcss-diagrams
droid plugin install glyphcss-diagrams@glyphcss-diagrams --scope user
droid plugin list --scope user
```

  

```sh
pi install https://github.com/apresmoi/glyphcss-diagrams
pi list
```

Existing sessions: run `/reload`. Invoke `/skill:glyphcss-diagrams`.

  

Import the [skill folder URL](https://github.com/apresmoi/glyphcss-diagrams/tree/main/skills/glyphcss-diagrams).

### Cursor, OpenCode, and other hosts

```sh
test -d glyphcss-diagrams/.git || git clone https://github.com/apresmoi/glyphcss-diagrams.git
cd glyphcss-diagrams
node install.mjs --provider grok
```

- Other providers: `cursor`, `opencode`, `agents`, `codex`, `claude`; Antigravity: `agy` (CLI), `antigravity` (IDE).
- For custom destinations, replace `--provider grok` with `--dest /absolute/path/to/skills`.
- Append `--copy` to avoid symlinks; symlink installs require the checkout to stay put.

[Directories, updates, and removal](https://github.com/apresmoi/glyphcss-diagrams/blob/main/docs/installation.md).

## 3D CLI skill

```sh
npm i -g @glyphcss/compile
mkdir -p .claude/skills/glyphcss
curl -sS https://glyphcss.com/skill.md -o .claude/skills/glyphcss/SKILL.md
glyphcss cube --auto-center
```

Claude Code: run in your project. Other hosts: place [SKILL.md](/skill.md) at `glyphcss/SKILL.md` in their skill directory. Bundled copy: `node_modules/@glyphcss/compile/SKILL.md`.

Without a global installation:

```sh
npx @glyphcss/compile cube --auto-center
```

## Troubleshooting

- **No trigger:** start a new session; check the host lists `glyphcss-diagrams`; name it explicitly.
- **Wrapping:** request fewer columns; split without losing values or connections. See [sizing](/diagrams/options/).
- **Misalignment:** request `--charset ascii` or `box`. Use monospace; web embeds need `white-space: pre` and `line-height: 1`; chat must omit ANSI escapes.


---

# GlyphCamera

```ts
import { createGlyphPerspectiveCamera, createGlyphScene, createGlyphOrbitControls } from "glyphcss";
import { resolveGeometry } from "@glyphcss/core";

const host = document.getElementById("scene");
const camera = createGlyphPerspectiveCamera({ rotX: 35, rotY: 0, zoom: 0.3, distance: 0, perspective: 8000, stretch: 1 });
const scene = createGlyphScene(host, { camera, autoSize: true, mode: "solid" });
scene.output.style.fontSize = "10px";
scene.output.style.lineHeight = "1";
scene.fit();
const polygons = resolveGeometry("cube", { size: 100 });
scene.add(polygons);
createGlyphOrbitControls(scene, { drag: true, wheel: true });
```



Drag to orbit; change tilt, zoom, or distance. This perspective demo uses `perspective: 8000` to make foreshortening easier to see.

## Choose a camera

```tsx
import { GlyphCamera, GlyphPerspectiveCamera, GlyphScene, GlyphMesh, GlyphOrbitControls } from "@glyphcss/react";

export function Example() {
  return (
    
      
        
        
      
    
  );
}
// Replace GlyphPerspectiveCamera with GlyphCamera for orthographic projection.
```

  

```vue



```

  

```ts
import { createGlyphPerspectiveCamera, createGlyphOrthographicCamera, createGlyphScene, createGlyphOrbitControls } from "glyphcss";
import { cubePolygons } from "@glyphcss/core";

const host = document.querySelector("#scene")!;
const camera = createGlyphPerspectiveCamera({ rotX: 35, rotY: 45, zoom: 50 });
const scene = createGlyphScene(host, { camera, mode: "solid" });
scene.add(cubePolygons({ center: [0, 0, 0], size: 1 }));
const controls = createGlyphOrbitControls(scene, { drag: true, wheel: true });

camera.rotY = 60;
scene.rerender();
scene.setOptions({ camera: createGlyphOrthographicCamera({ rotX: 35, zoom: 50 }) });

// On unmount:
// controls.destroy();
// scene.destroy();
```

`GlyphCamera` aliases `GlyphOrthographicCamera`: parallel lines stay parallel. `GlyphPerspectiveCamera` adds foreshortening. Wrap `GlyphScene` inside the camera in React/Vue; pass a camera handle to `createGlyphScene` in vanilla JS.

## Options and defaults

| Option | Default | Meaning |
|---|---|---|
| `rotX` | `65` | X rotation, degrees; `0` looks down Z |
| `rotY` | `45` | Y rotation, degrees |
| `zoom` | `0.65` | CSS pixels per world unit |
| `distance` | `0` | Perspective pull-back: CSS pixels; world units when `perspective: 0` |
| `perspective` | `32000` | Virtual-pixel perspective distance; larger looks flatter; `0` selects legacy orbit projection |
| `stretch` | `1` | Perspective-only extra horizontal scale |

Orthographic cameras use `rotX`, `rotY`, and `zoom`; `distance` has no effect. The renderer and hit layer share camera state. After mutating a vanilla camera, call `scene.rerender()`.


---

# GlyphOrbitControls

glyphcss ships three pointer-based control modes. All must be placed inside a
`` (React / Vue) or receive a scene handle (vanilla). The camera
component wraps the scene.

| Control | Interaction | When to use |
|---|---|---|
| `GlyphOrbitControls` | Left-drag orbits; wheel zooms | General-purpose — object inspection |
| `GlyphMapControls` | Left-drag pans; right-drag / Shift+left orbits; wheel zooms | Top-down maps, floor plans |
| `GlyphFirstPersonControls` | Pointer-lock look; WASD move, jump, crouch | Walk-through scenes |

## Orbit controls

`GlyphOrbitControls` mutates the camera-state object on drag; the rasterizer
reads it and writes one string per pointermove. With `interactiveDownscale` set,
the scene renders at reduced resolution for the duration of the gesture and
restores full detail on release.

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| `drag` | `boolean` | `true` | Enable click-and-drag rotation |
| `wheel` | `boolean` | `true` | Enable scroll-to-zoom |
| `invert` | `boolean \| number` | `false` | Invert drag direction |
| `pitchRange` | `[number, number] \| null` | `[-90, 90]` | Turntable-mode pitch clamp in degrees. `null` for globe-style unrestricted tumbling (views past either pole; the up-vector never rolls) |
| `mode` | `"turntable" \| "trackball"` | `"turntable"` | `"trackball"` rotates about the screen axis perpendicular to the drag, reaching any orientation including roll (two-finger twist rolls) |
| `animate` | `false \| { speed?, axis?, pauseOnInteraction? }` | `false` | Auto-rotation config. `axis` is `"x"` or `"y"` |

```tsx
import { GlyphCamera, GlyphScene, GlyphMesh, GlyphOrbitControls } from "@glyphcss/react";
import { icosahedronPolygons } from "@glyphcss/core";

const icosa = icosahedronPolygons({ center: [0, 0, 0], size: 1, color: "#44ffcc" });

export function App() {
  return (
    
      
        
        
      
    
  );
}
```

  

```vue



```

  

```ts
import { createGlyphCamera, createGlyphScene, createGlyphOrbitControls } from "glyphcss";
import { icosahedronPolygons } from "@glyphcss/core";

const host = document.querySelector("#scene")!;
const camera = createGlyphCamera({ rotX: 25 });
const scene = createGlyphScene(host, { camera, mode: "solid" });
scene.add(icosahedronPolygons({ center: [0, 0, 0], size: 1, color: "#44ffcc" }));

const controls = createGlyphOrbitControls(scene, {
  drag: true,
  wheel: true,
  animate: { axis: "y", speed: 0.5 },
});

// Cleanup:
// controls.destroy();
```

## Map controls

Left-drag pans the camera target. Right-drag (or Shift + left-drag) orbits. Wheel
zooms. Best for top-down maps or floor-plan scenes.

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| `drag` | `boolean` | `true` | Enable pointer-drag pan |
| `wheel` | `boolean` | `true` | Enable scroll-to-zoom |
| `invert` | `boolean \| number` | `false` | Invert drag direction |
| `animate` | `false \| { speed?, axis?, pauseOnInteraction? }` | `false` | Auto-rotation. `axis` is `"x"` or `"y"` |

```tsx
import { GlyphCamera, GlyphScene, GlyphMesh, GlyphMapControls } from "@glyphcss/react";
import { cubePolygons } from "@glyphcss/core";

const cube = cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" });

export function MapDemo() {
  return (
    
      
        
        
      
    
  );
}
```

  

```vue



```

  

```ts
import { createGlyphCamera, createGlyphScene, createGlyphMapControls } from "glyphcss";
import { cubePolygons } from "@glyphcss/core";

const host = document.querySelector("#scene")!;
const camera = createGlyphCamera({ rotX: 35 });
const scene = createGlyphScene(host, { camera, mode: "solid", cols: 120, rows: 36 });
scene.add(cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" }));

const controls = createGlyphMapControls(scene, { drag: true, wheel: true });
```

## First-person controls

Pointer-lock mouselook, WASD / arrow planar move, Space jump, Ctrl crouch — each
axis independently toggleable. Good for walk-through environments and large scenes.
Click the scene to capture the pointer; Esc releases it.

**Requires a perspective camera.** `GlyphFirstPersonControls` throws if attached
to a scene with an orthographic camera. Use `` explicitly
(not ``, which aliases orthographic).

Distances are in world units — size `moveSpeed` / `eyeHeight` to your mesh's scale
(the gallery derives them from the model bbox).

### Props

| Prop | Type | Default | Description |
|---|---|---|---|
| `lookEnabled` | `boolean` | `true` | Pointer-lock mouselook |
| `moveEnabled` | `boolean` | `true` | WASD / arrow planar movement |
| `jumpEnabled` | `boolean` | `true` | Space-bar jump arc |
| `crouchEnabled` | `boolean` | `true` | Ctrl crouch |
| `lookSensitivity` | `number` | `0.15` | Degrees per pixel of mouse |
| `invertY` | `boolean` | `false` | Invert vertical look |
| `moveSpeed` | `number` | `5` | World units per second |
| `jumpVelocity` | `number` | `7` | Initial jump velocity (units/s) |
| `gravity` | `number` | `18` | Gravity (units/s²) |
| `eyeHeight` | `number` | `1.7` | Standing eye height above ground |
| `crouchHeight` | `number` | `1` | Eye height while crouching |
| `groundZ` | `number` | `0` | World Z of the ground plane |
| `minPitch` / `maxPitch` | `number` | `5` / `175` | Pitch clamp (degrees) |

```tsx
import { GlyphPerspectiveCamera, GlyphScene, GlyphMesh, GlyphFirstPersonControls } from "@glyphcss/react";
import { cubePolygons } from "@glyphcss/core";

const floor = cubePolygons({ center: [0, -0.6, 0], size: 4, color: "#334455" });

export function FPVDemo() {
  return (
    
      
        
        
      
    
  );
}
```

  

```vue



```

  

```ts
import { createGlyphPerspectiveCamera, createGlyphScene, createGlyphFirstPersonControls } from "glyphcss";
import { cubePolygons } from "@glyphcss/core";

const host = document.querySelector("#scene")!;
const camera = createGlyphPerspectiveCamera();
const scene = createGlyphScene(host, { camera, mode: "solid", cols: 140, rows: 42 });
scene.add(cubePolygons({ center: [0, -0.6, 0], size: 4, color: "#334455" }));

const controls = createGlyphFirstPersonControls(scene, {
  moveSpeed: 3,
  eyeHeight: 1.2,
});
```


---

# GlyphHotspot

`` renders a real, absolutely-positioned `
` over the ASCII render, tracking a 3D anchor through the live camera. The `
` is `pointer-events: auto` inside an otherwise transparent hit layer — events fire on it like any normal DOM element. ## Props | Prop | Type | Default | Description | |---|---|---|---| | `id` | `string` | required | Stable identifier for this hotspot | | `at` | `Vec3` | required | World-space anchor `[x, y, z]` | | `size` | `[number, number]` | `[1, 1]` | Hitbox size in character cells | | `onClick` | `MouseEventHandler` | — | Click handler | | `aria-label` | `string` | — | Accessibility label | | `className` | `string` | — | CSS class | | `children` | `ReactNode` | — | Rendered inside the `
` (use for tooltips/badges) | ## Tracking math On every render pass the anchor is projected through the current camera and the resulting cell is written straight to the element's inline `transform` — one assignment per hotspot, no DOM rebuild and no second projection. While the user drags, the same projection runs per pointermove, so the hotspot stays glued to its anchor through the whole gesture. ## Full examples ```tsx import { GlyphCamera, GlyphScene, GlyphMesh, GlyphOrbitControls, GlyphHotspot, } from "@glyphcss/react"; import { cubePolygons } from "@glyphcss/core"; const cube = cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" }); export function HotspotDemo() { return ( {/* Hotspot on the top face */} alert("top face clicked")} > Top {/* Hotspot on the right face */} alert("right face clicked")} > Right ); } ``` ```vue ``` ```ts import { createGlyphScene } from "glyphcss"; import { cubePolygons } from "@glyphcss/core"; const host = document.querySelector("#scene")!; const scene = createGlyphScene(host, { mode: "solid", cols: 100, rows: 30 }); scene.add(cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" })); const topHotspot = scene.addHotspot( { id: "top", at: [0, 0.5, 0], size: [5, 3] }, () => alert("top face clicked"), ); const rightHotspot = scene.addHotspot( { id: "right", at: [0.5, 0, 0], size: [5, 3] }, () => alert("right face clicked"), ); // Remove a hotspot when no longer needed: // topHotspot.remove(); ``` ## Visibility A hotspot whose projected cell is not visible (behind the camera, or occluded) is hidden with `display: "none"` rather than faded — the renderer stages the style and applies it in the same single write as the rest of the frame. There is no opacity keyframe to hook a CSS transition onto; animate the element yourself if you want a fade. ## Anchors `at` is a world-space `Vec3`. String anchors (`"vertex:42"`, `"face:roof"`, `"centroid"`) are **not** implemented — resolve the coordinate yourself from the polygon data and pass the result: ```ts const centroid = polygons .flatMap((p) => p.vertices) .reduce((a, v, _i, all) => [a[0] + v[0] / all.length, a[1] + v[1] / all.length, a[2] + v[2] / all.length], [0, 0, 0]); ``` --- # GlyphScene `` is the visual host. It owns the `
` output element, the sibling
hit layer, and the measured cell metrics the projection uses.

`` must be a child of a camera component (``,
``, or ``).



```ts
import { createGlyphPerspectiveCamera, createGlyphScene, createGlyphOrbitControls } from "glyphcss";
import { resolveGeometry } from "@glyphcss/core";

const host = document.getElementById("scene");
const camera = createGlyphPerspectiveCamera({ rotX: 65, rotY: 0, zoom: 0.3, distance: 0, perspective: 32000, stretch: 1 });
const scene = createGlyphScene(host, { camera, autoSize: true, mode: "wireframe", charMode: "braille" });
scene.output.style.fontSize = "10px";
scene.output.style.lineHeight = "1";
scene.fit();
const polygons = resolveGeometry("cuboctahedron", { size: 100 });
scene.add(polygons);
createGlyphOrbitControls(scene, { drag: true, wheel: true });
```



## Props

| Prop | Type | Default | Description |
|---|---|---|---|
| `mode` | `"wireframe" \| "solid" \| "voxel" \| "ink"` | `"solid"` | Render mode |
| `cols` | `number` | `80` | Grid width in character columns |
| `rows` | `number` | `24` | Grid height in character rows |
| `cellAspect` | `number` | `2.0` | Character cell height ÷ width |
| `glyphPalette` | `string` | `"default"` | Named glyph palette |
| `autoSize` | `boolean` | `false` | Measure the host element and derive `cols`/`rows` from it instead of using the fixed grid |
| `charMode` | `"ascii" \| "braille" \| "halfblock" \| "quadrant"` | `"ascii"` | Sub-cell character encoding. `"braille"` is wireframe-only; `"halfblock"` and `"quadrant"` are solid-only. No-op outside its mode. See [character encoding](/guides/render-modes/#character-encoding-charmode) |
| `wireframeJunctions` | `boolean` | `false` | Resolve wireframe corners and crossings to box-drawing glyphs (`┌┐└┘├┤┬┴┼─│`). ASCII wireframe only. See [junctions](/guides/render-modes/#box-drawing-junctions-wireframejunctions) |
| `hiddenLines` | `"show" \| "hide"` | `"show"` | Hidden-line removal for `wireframe` and `ink`: `"hide"` drops strokes a nearer surface covers. No-op in `solid`. See [hidden-line removal](/guides/render-modes/#hidden-line-removal-hiddenlines) |
| `solidWeightRamp` | `{ glyph: string; weight: number }[]` | `undefined` | Solid-only shading ramp that varies `font-weight` as well as glyph, ordered darkest → densest. Replaces the palette's solid ramp when set. See [font-weight ramp](/guides/render-modes/#font-weight-density-ramp-solidweightramp) |
| `colorTolerance` | `number` | `0` | Merge adjacent cells into one `` while their colors stay within this redmean distance (range `0`–`765`, not `0`–`255`) — fewer spans, faster paint, at the cost of color fidelity. `0` is off and byte-identical. `NaN`/negative values degrade to `0`; `+Infinity` merges every same-glyph run in a row. No-op under `glyphOutput: "semantic"` — semantic colors are exact class identifiers, not shaded appearance. See [spans, not just cells](/guides/performance/#spans-not-just-cells-colortolerance) |
| `colorEncoding` | `"spans" \| "atlas"` | `"spans"` | `"atlas"` encodes each `(glyph, color)` pair as a Private Use Area code point against a checked-in COLR/CPAL color font, so the render is one text node with zero ``s. `"spans"` is byte-identical to before the option existed. Falls back to spans, whole-scene, whenever the atlas cannot carry the frame. See [color encoding](/guides/color-encoding) |
| `atlasPalette` | `readonly string[]` | `undefined` | Pin the ordered `#rrggbb` palette that `colorEncoding: "atlas"` slots encode against — a brand ramp or a reproducible bake. Omitted, the scene derives and pools one itself, so this does **not** gate the atlas. Bounded by the atlas's slot count. See [the palette](/guides/color-encoding/#the-palette-atlaspalette) |
| `fontAtlas` | `GlyphFontAtlas` | `GLYPH_FONT_ATLAS` | Which color-font atlas to encode against — the universal one (212 glyphs / 30 palette slots) or `GLYPH_FONT_ATLAS_ASCII` (94 / 68), trading glyph coverage for color resolution. **Fixed at scene creation**; a later change is not forwarded. See [choosing an atlas](/guides/color-encoding/#choosing-an-atlas-fontatlas) |
| `smoothShading` | `boolean` | `false` | Gouraud shading from averaged vertex normals. Off by default — the faceted look is part of glyph's identity |
| `creaseAngle` | `number` | `60` | Max angle (degrees) between adjacent faces still smoothed together when `smoothShading` is on |
| `interactiveDownscale` | `number` | `1` | Render at `1/n` resolution while a control is dragging, full detail on release. Same on-screen size — this keeps high-density scenes inside the frame budget mid-gesture |
| `trackOpaqueCoverage` | `boolean` | `false` | Force a base-layer depth raster each render so `scene.getOpaqueCoverage()` can publish it. A scene only builds an occlusion id-map when it has an opaque detail mesh or a foreign mask, so a scene of plain base meshes needs this to feed another scene's `setForeignOcclusion`. Changes no output; costs one raster |
| `glyphOutput` | `"visible" \| "semantic"` | `"visible"` | `"semantic"` renders authored class labels instead of shaded glyphs and enables `scene.getGlyphSemanticCellFrame()`. Requires the `sceneManifest` + `dictionary` JS properties |
| `useColors` | `boolean` | `true` | Emit color spans in the output |
| `directionalLight` | `GlyphDirectionalLight` | — | Directional light for solid mode |
| `ambientLight` | `GlyphAmbientLight` | — | Ambient fill for solid mode |
| `shadow` | `GlyphShadowOptions` | `undefined` | Shadow-map config. `undefined` = off. Set alongside `castShadow`/`receiveShadow` on meshes |
| `transformCells` | `TransformCells` | `undefined` | Transform the completed cell grid before its single `
` write |
| `className` | `string` | — | CSS class on the outer host |
| `style` | `CSSProperties` | — | Inline styles on the outer host |
| `children` | `ReactNode` | — | ``, controls, hotspots |

### Vanilla-only scene options

`createGlyphScene` accepts a few options the React and Vue components do not
expose as props. `compileScene` accepts the first two (`doubleSided` and
`supersample`) as well:

| Option | Default | What it does |
|---|---|---|
| `doubleSided` | `false` | Shade back faces instead of culling them — needed for open meshes and flat planes viewed from behind |
| `supersample` | `1` | Rasterize at `n×` the cell grid and box-filter down, for coverage antialiasing. `charMode: "halfblock"`/`"quadrant"` force an even supersample of at least 2 internally |
| `depthEpsilon` | `0` | Depth-test tolerance for coplanar surfaces |
| `temporalBlend` | `0` | Reprojection TAA: blends the ramp index and RGB against the previous frame. `solidWeightRamp` and `charMode: "halfblock"`/`"quadrant"` are no-ops while it is active |

## Cell transforms and surface UVs

`transformCells` runs after rasterization, shading, and depth testing, immediately
before glyphcss stringifies the grid. The hook may mutate `grid.char` and
`grid.color`; glyphcss still performs one write to the scene's `
` for the
completed frame.

In solid mode, polygons with authored `uvs` also expose `grid.surfaceUv`. This is
an optional interleaved `Float32Array` containing the perspective-correct UV from
the depth-winning surface for each cell:

```ts
import { createGlyphScene } from "glyphcss";
import type { TransformCells } from "glyphcss";

const word = Array.from("HOLA");

const mapWordToSurface: TransformCells = (grid) => {
  const uv = grid.surfaceUv;
  if (!uv) return;

  for (let i = 0; i < grid.char.length; i++) {
    const u = uv[i * 2];
    const v = uv[i * 2 + 1];
    if (!Number.isFinite(u) || !Number.isFinite(v)) continue;

    grid.char[i] = word[((Math.floor(u * 12) % word.length) + word.length) % word.length];
  }
};

const scene = createGlyphScene(host, {
  camera,
  mode: "solid",
  transformCells: mapWordToSurface,
});
```

`surfaceUv` uses `[u0, v0, u1, v1, ...]`. Empty cells and cells whose winning
polygon has no UVs contain `NaN`/non-finite coordinates, so effects must check
both components. Values remain in the polygon's authored coordinate space;
they are not clamped to `0..1`, and may tile beyond that range. Because the
mapping follows the polygon UVs rather than screen rows and columns, patterns
rotate and foreshorten with the surface. Treat the grid buffers as
callback-scoped; use `rasterizeToCells` when they must outlive the synchronous
`transformCells` call.

For reusable or animated appearance, prefer a mounted
[`GlyphEffectLayer`](/guides/effects). Generic layers retain the geometry raster
and avoid re-projecting the mesh on parameter-only ticks; `transformCells`
remains the final application-specific escape hatch and runs after those layers.

## Full examples

```tsx
import {
  GlyphPerspectiveCamera,
  GlyphScene,
  GlyphMesh,
  GlyphOrbitControls,
  GlyphHotspot,
} from "@glyphcss/react";
import { cubePolygons } from "@glyphcss/core";

const cube = cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" });

export function App() {
  return (
    
      
        
        
           alert("top face")}
          />
        
      
    
  );
}
```

  

```vue



```

  

```ts
import {
  createGlyphPerspectiveCamera,
  createGlyphScene,
  createGlyphOrbitControls,
} from "glyphcss";
import { cubePolygons } from "@glyphcss/core";

const host = document.querySelector("#scene")!;

const camera = createGlyphPerspectiveCamera({ rotX: 25, zoom: 50, distance: 3 });
const scene = createGlyphScene(host, {
  camera,
  mode: "solid",
  cols: 100,
  rows: 30,
});

scene.add(cubePolygons({ center: [0, 0, 0], size: 1, color: "#4488ff" }));

scene.addHotspot(
  { id: "top", at: [0, 0.5, 0], size: [3, 2] },
  () => alert("top face"),
);

const controls = createGlyphOrbitControls(scene, { drag: true, wheel: true });

// Later, when done:
// controls.destroy();
// scene.destroy();
```

  

```html



  
    
    
  

```

## Shadows

Shadows are opt-in. Set `shadow` on `` to enable the shadow-map pass,
then flag individual meshes with `castShadow` and/or `receiveShadow`.
A mesh with both flags self-shadows. `` defaults to `receiveShadow=true`.

```tsx
import {
  GlyphPerspectiveCamera,
  GlyphScene,
  GlyphMesh,
  GlyphGround,
} from "@glyphcss/react";

const shadow = { color: "#000000", opacity: 0.25, lift: 0.05 };
const directionalLight = { direction: [0.5, 0.7, 0.5], intensity: 1 };

export function ShadowDemo() {
  return (
    
      
        
        
      
    
  );
}
```

  

```vue



```

  

```html

  
    
    
    
  

```

### `GlyphShadowOptions` fields

| Field | Type | Default | Description |
|---|---|---|---|
| `color` | `string` | `"#000000"` | Shadow tint hex color |
| `opacity` | `number` | `0.25` | Darkness 0..1 toward `color` |
| `lift` | `number` | `0.05` | Depth bias — prevents self-shadow acne on flat lit surfaces. A WORLD-UNIT length, so the default assumes a room-scale scene; a scene whose unit is (say) an Earth radius must set its own, or every shadow is biased away |
| `maxExtend` | `number` | `2000` | **Accepted but not read.** The light-space volume is fitted to the casters' own bounds; this value has no effect on any render |

## Lifecycle methods (vanilla)

| Method | Description |
|---|---|
| `scene.add(polygons, transform?)` | Register a mesh, returns a `GlyphMeshHandle` |
| `mesh.setPolygons(polygons)` | Replace a mesh's geometry in place |
| `mesh.setTransform(transform)` | Replace a mesh's transform |
| `mesh.dispose()` | Remove a mesh |
| `scene.addHotspot(opts, onClick?)` | Register a hotspot overlay, returns a `GlyphHotspotHandle` |
| `hotspot.setAt(at)` | Move a hotspot's 3D anchor without touching its element — the element, its listeners and anything you wrote on it survive, and only the projected position changes |
| `hotspot.remove()` | Remove a hotspot overlay |
| `scene.setOptions(partial)` | Update any scene option and trigger a re-render |
| `scene.getOptions()` | Return a snapshot of current options |
| `scene.rerender()` | Force an immediate re-rasterize |
| `scene.addEffectLayer(opts)` | Mount an ordered appearance program over the retained grid, returns a `GlyphEffectLayerHandle` (see [Glyph Effects](/guides/effects)). Changing the handle's `params` / `opacity` / `blend` / `order` / `enabled` recomposes without re-projecting the mesh |
| `scene.setInteracting(active)` | Tell the scene a gesture is in progress, so `interactiveDownscale` applies. The bundled controls call this for you — use it for custom interaction sources |
| `scene.getOpaqueCoverage()` | The last committed render's opaque per-cell coverage at the output grid — cells owned by the base grid or an opaque detail layer, foreign stamps excluded. `null` when that render built no occlusion id-map (see `trackOpaqueCoverage`). `solid` mode only |
| `scene.setForeignOcclusion(coverage)` | Consume another scene's `getOpaqueCoverage()` result: every layer of this scene blanks under the covered cells, so two scenes stacked over one host share a single occlusion domain. `null` clears. Re-publishing identical bytes costs a comparison, not a render. `solid` mode only |
| `scene.getGlyphSemanticCellFrame()` | Immutable snapshot of the last committed base grid's polygon → surface → instance → class lineage. `null` unless `glyphOutput: "semantic"` |
| `scene.destroy()` | Remove the scene DOM and clear all meshes |


---

# Core Concepts

## One render pass, one write

glyphcss does not build a DOM node per polygon, and it does not pre-bake frames.
Every camera or scene change runs a single render pass:

1. Walk all mounted meshes in scene order.
2. Transform polygon vertices through the camera to 2D projected positions.
3. Fill a `cols × rows` character grid — depth-testing overlapping polygons and
   picking a glyph per cell according to the render mode.
4. Join the grid into one string and assign it to `
.textContent`, **once**.

That last point is the invariant the whole renderer is built around: each render
cycle writes each `
` exactly once. No cell-by-cell DOM patching, no
`matrix3d`, no per-polygon elements. A scene with per-mesh detail layers writes
the base `
` plus one write per detail layer, and nothing else.

Interaction follows the same path rather than a special one: a control mutates a
single camera-state object, the rasterizer reads it, and one string is written.
Dragging can optionally render at reduced resolution via `interactiveDownscale`
and restore full detail on release — same on-screen size, fewer cells mid-gesture.

Because `rasterize` is pure — geometry + camera in, string out — the same pass
runs at build time or on a server. That is what `compileScene` and
`GlyphSceneStatic` use, and their output is byte-identical to the runtime render
for the same inputs.

## The hit layer

polycss-style "every polygon is a DOM node" doesn't fit ASCII rendering: the visible
output is a single character grid, not a set of clickable polygons. Instead, glyphcss
exposes a **sparse** hit layer: you opt-in to interactivity by registering hotspots
at specific 3D anchors.

```tsx
import { GlyphMesh, GlyphHotspot } from "@glyphcss/react";
import { dodecahedronPolygons } from "@glyphcss/core";

const shape = dodecahedronPolygons({ center: [0, 0, 0], size: 1, color: "#cc44ff" });


  
    Top
  

```

Each hotspot becomes a real `
` absolutely positioned at its projected cell. The rasterizer projects `Hotspot.at` through the same camera the grid was drawn with and returns a `HotspotCell` (col, row, depth, visible); the consumer moves the element with a single inline-style assignment per hotspot — no DOM rebuild, and no second projection that could disagree with the glyphs. Hotspots: - Render real DOM children (use them for tooltips, badges, hover affordances). - Fire normal DOM events (`onClick`, `onMouseEnter`, `onFocus`). - Get free CSS `:hover` and `:focus-visible` styling. - Inspect in DevTools like any other element. ## The camera contract The renderer and the hit layer **must** use the same `camera.project(v, ...)` call. This is enforced by both reading from a shared `GlyphCamera` handle: ```ts const camera = createGlyphPerspectiveCamera({ rotX: 25, rotY: 0, distance: 3, zoom: 50, stretch: 1.0, }); const ctx = buildRasterizeContext({ camera, grid, polygons, mode: "solid" }); // Renderer — one pass, one string const text = rasterize(ctx); // Hit layer — the SAME camera object, so it cannot disagree const cells = projectHotspots(hotspots, camera, grid.cols, grid.rows, grid.cellAspect); ``` Mutating `camera.rotY` and re-running both calls is all "animation" is here: there is no baked sequence to keep in sync, and nothing caches a projection that could go stale. If you ever find yourself threading a separate "current angle" through projection, stop: one camera-state object feeds both the grid and the hotspots, and that is exactly what keeps them from drifting apart. ## Cell measurement (the recurring footgun) `
` is `display: block`, so `getBoundingClientRect().width` returns the
**container width**, not the character width. Always measure on a hidden
`` instead. The probe should have the same
font properties as the `
` (same `font-family`, same `font-size`,
`line-height: normal`).

The measured cell matters because the projection uses its aspect ratio: with
`autoSize`, the scene re-measures the host cell and overwrites `cellAspect` from
it, so geometry stays correctly proportioned when the font or size changes. A
fixed-size scene (explicit `cols`/`rows`, no `autoSize`) has no such correction —
it keeps whatever `cellAspect` you gave it, which is why `compileScene` takes the
value explicitly.


---

# Mermaid architecture diagrams as text

Pass `architecture` or `architecture-beta` source to `renderGlyphDiagram`. Services become labelled nodes and icon names become text tags.

## Connect an API to storage



```mermaid
architecture-beta
 service api(server)[Order API]
 service db(database)[Orders]
 service queue(server)[Job queue]
 service worker(server)[Receipt worker]
 service files(disk)[Receipts]
 service mail(cloud)[Email gateway]
 api:R --> L:db
 api:R --> L:queue
 queue:R --> L:worker
 worker:R --> L:files
 worker:R --> L:mail
```

```text
                      ◜─────────────◝                                         
                   ┌──▶ [db] Orders │                                         
┌────────────────┐ │  ◟─────────────◞                       ┌───────────────┐ 
│ [server] Order ├─┤                                      ┌─▶ [cloud] Email │ 
│       API      │ │ ┌──────────────┐  ┌────────────────┐ │ │    gateway    │ 
└────────────────┘ └─▶ [server] Job │──▶    [server]    ├─┤ └───────────────┘ 
                     │     queue    │  │ Receipt worker │ │                   
                     └──────────────┘  └────────────────┘ │ ┌──────────┐      
                                                          └─▶  [disk]  │      
                                                            │ Receipts │      
                                                            └──────────┘      
```



## Group services



```mermaid
architecture-beta
 group cloud(cloud)[Production]
 service api(server)[API] in cloud
 service jobs(server)[Jobs] in cloud
 service files(disk)[Receipts] in cloud
 api:R --> L:jobs
 jobs:B --> T:files
```

```text
······················[cloud] Production························
·                                                              ·
· ┌──────────────┐    ┌───────────────┐    ┌─────────────────┐ ·
· │ [server] API │────▶ [server] Jobs │────▶ [disk] Receipts │ ·
· └──────────────┘    └───────────────┘    └─────────────────┘ ·
·                                                              ·
································································
```



## Syntax and limits

- Declare `service id(icon)[Label]`, `group id(icon)[Label]`, and membership with `in groupId`.
- Connections use side prefixes such as `api:R --> L:db`. The first source side guides the initial layout direction.
- Junctions become `+` nodes. Database icons become tags such as `[db]`; external icon assets do not load.
- Port sides, alignment, group-edge attachment, and self-loops are approximated where needed and recorded in the report.
- The result is a text graph, so icon artwork and exact Mermaid positioning are not preserved. Use explicit [direction and cell budgets](/diagrams/options/) to tune it.


---

# Mermaid block diagrams as monospace text

Pass `block` or `block-beta` source to `renderGlyphDiagram`. Column hints guide the layout while the fitter keeps labels readable.

## Place services in columns



```mermaid
block-beta
 columns 3
 web["Storefront"] api["Order API"] db[("Orders")]
 queue["Job queue"] worker["Receipt worker"] mail["Email gateway"]
 web --> api
 api --> db
 api --> queue
 queue --> worker
 worker --> mail
```

```text
     ┌────────────────┐    ┌────────────────┐    ◜────────────────◝     
     │                │    │                │    │                │     
     │   Storefront   │────▶    Order API   │────▶     Orders     │     
     │                │    │                │    │                │     
     └────────────────┘    └────────────────┘    ◟────────────────◞     
                                   │                                    
                                   │                                    
             ┌─────────────────────┘                                    
             │                                                          
     ┌───────▼────────┐    ┌────────────────┐    ┌────────────────┐     
     │    Job queue   │────▶ Receipt worker │────▶  Email gateway │     
     └────────────────┘    └────────────────┘    └────────────────┘     
```



## Nest a spanning block



```mermaid
block-beta
 columns 2
 block:Gateway:2
 columns 2
 auth["Auth"] quota["Rate limit"]
 end
 queue["Jobs"] worker["Worker"]
 queue --> worker
```

```text
              ··············Gateway···············              
              ·                                  ·              
              · ┌────────────┐    ┌────────────┐ ·              
              · │    Auth    │    │ Rate limit │ ·              
              · └────────────┘    └────────────┘ ·              
              ·                                  ·              
              ····································              
                                                                
                                                                
                                                                
                                                                
              ┌──────────────┐    ┌──────────────┐              
              │     Jobs     │────▶    Worker    │              
              └──────────────┘    └──────────────┘              
```



## Syntax and limits

- `columns N` sets a grid. `:N` spans that many columns, including the gaps between them.
- `block:Name ... end` nests a grid. `space` reserves blank cells; spaces and empty block input are supported.
- Labels, shapes, and arrows become graph elements. Styling and external assets are inert.
- Crowded grids may wrap to fewer columns (`block-row-wrap`) or use the general fitter (`block-layout`). Column positions are hints rather than fixed pixel coordinates.
- Large or tall blocks can paginate. Expansion and explicit direction are available through [render options](/diagrams/options/).


---

# Mermaid C4 diagrams as text

All five Mermaid C4 headers use `renderGlyphDiagram`. Nodes carry stereotypes,
technology, and descriptions as text; boundaries become groups. These are graph layouts,
not pixel-identical Mermaid C4 drawings.

## System context



```mermaid
C4Context
 Person(buyer, "Buyer")
 System(portal, "Order portal", "Online checkout")
 System_Ext(pay, "Payments", "Card processor")
 System_Ext(ship, "Shipping", "Parcel tracking")
 System_Ext(mail, "Email", "Order updates")
 Rel(buyer, portal, "Orders")
 Rel(portal, pay, "Charges")
 Rel(portal, ship, "Dispatches")
 Rel(portal, mail, "Notifies")
```

```text
                                                            ┌────────────────────┐      
                                                Charges     │      Payments      │      
                                              ┌─────────────▶ [system, external] │      
                                              │             │   Card processor   │      
                                              │             └────────────────────┘      
                                              │                                         
                          ┌─────────────────┐ │             ┌────────────────────┐      
      ╭──────────╮ Orders │  Order portal   │ │  Dispatches │      Shipping      │      
      │   Buyer  │────────▶    [system]     ├─┼─────────────▶ [system, external] │      
      │ [person] │        │ Online checkout │ │             │   Parcel tracking  │      
      ╰──────────╯        └─────────────────┘ │             └────────────────────┘      
                                              │                                         
                                              │             ┌────────────────────┐      
                                              │             │        Email       │      
                                              └─────────────▶ [system, external] │      
                                               Notifies     │    Order updates   │      
                                                            └────────────────────┘      
```



## Containers



```mermaid
C4Container
 System_Boundary(shop, "Shop") {
 Container(api, "API", "Node")
 ContainerDb(db, "Orders", "Postgres")
 }
 Rel(api, db, "Stores")
```

```text
           ······················Shop·······················            
           ·                                               ·            
           · ┌─────────────┐            ◜────────────────◝ ·            
           · │     API     │   Stores   │     Orders     │ ·            
           · │ [container] │────────────▶ [container db] │ ·            
           · │    Node     │            │    Postgres    │ ·            
           · └─────────────┘            ◟────────────────◞ ·            
           ·                                               ·            
           ·················································            
```



## Components



```mermaid
C4Component
 Container_Boundary(api, "API") {
 Component(handler, "Checkout", "HTTP")
 Component(repo, "Repository", "SQL")
 }
 Rel(handler, repo, "Saves")
```

```text
             ·····················API·····················              
             ·                                           ·              
             · ┌─────────────┐           ┌─────────────┐ ·              
             · │  Checkout   │   Saves   │ Repository  │ ·              
             · │ [component] │───────────▶ [component] │ ·              
             · │    HTTP     │           │     SQL     │ ·              
             · └─────────────┘           └─────────────┘ ·              
             ·                                           ·              
             ·············································              
```



## Dynamic interactions



```mermaid
C4Dynamic
 Container(web, "Web", "React")
 Container(api, "API", "Node")
 Rel(web, api, "Submit cart")
 Rel(api, web, "Confirm")
```

```text
             ┌─────────────┐                ┌─────────────┐             
             │     Web     │ 1: Submit cart │     API     │             
             │ [container] │────────────────▶ [container] │             
             │    React    │                │    Node     │             
             └──────▲──────┘                └─────────────┘             
                    │         2: Confirm           │                    
                    └──────────────────────────────┘                    
```



## Deployment



```mermaid
C4Deployment
 Deployment_Node(prod, "Production", "Linux") {
 Container(api, "API", "Node")
 ContainerDb(db, "Orders", "Postgres")
 }
 Rel(api, db, "Writes")
```

```text
           ···············Production [Linux]················            
           ·                                               ·            
           · ┌─────────────┐            ◜────────────────◝ ·            
           · │     API     │   Writes   │     Orders     │ ·            
           · │ [container] │────────────▶ [container db] │ ·            
           · │    Node     │            │    Postgres    │ ·            
           · └─────────────┘            ◟────────────────◞ ·            
           ·                                               ·            
           ·················································            
```



## Syntax and limits

- Use `Person`, `System`, `Container`, and `Component` declarations with the appropriate header. External variants add an external marker.
- Database variants draw cylinders; queue variants draw rectangles. Person nodes use rounded outlines.
- `Enterprise_Boundary`, `System_Boundary`, `Container_Boundary`, and `Deployment_Node` enclose related nodes where supported.
- `Rel` and its directional variants create edges; dynamic relationships retain order in their labels.
- Index, style, layout, title, and asset directives are inert and reported. Set a rendered title through the API's `title` option.
- C4 captions often need a wider or taller budget. The fitter protects words and captions before gutters; an explicit direction takes precedence over automatic C4 orientation.


---

# Mermaid class diagrams as ASCII text

Use `classDiagram` with `renderGlyphDiagram`. Class names, members, and relationship captions become text; the renderer does not execute methods.

## Classes and inheritance



```mermaid
classDiagram
 class Account {
 +String email
 +signIn() bool
 }
 class Buyer {
 +checkout() Order
 }
 class Staff {
 +refund() bool
 }
 class Order {
 +String status
 +submit()
 }
 class Line {
 +int quantity
 }
 Account <|-- Buyer
 Account <|-- Staff
 Buyer --> Order : places
 Order "1" *-- "*" Line : contains
```

```text
                             ┌────────────────┐                               
                             │     Account    │                               
                             ├────────────────┤                               
                             │ +String email  │                               
                             ├────────────────┤                               
                             │ +signIn() bool │                               
                             └──────△─△───────┘                               
                                    │ │                                       
                         ┌──────────┘ └──────────┐                            
                         │                       │                            
                 ┌────────────────┐    ┌───────────────────┐                  
                 │      Staff     │    │       Buyer       │                  
                 ├────────────────┤    ├───────────────────┤                  
                 │ +refund() bool │    │ +checkout() Order │                  
                 └────────────────┘    └───────────────────┘                  
                                                 │                            
                                          places │                            
                                                 │                            
                                         ┌───────▼────────┐                   
                                         │      Order     │                   
                                         ├────────────────┤                   
                                         │ +String status │                   
                                         ├────────────────┤                   
                                         │ +submit()      │                   
                                         └───────◆────────┘                   
                                                 │                            
                                [1] contains [*] │                            
                                                 │                            
                                         ┌───────────────┐                    
                                         │     Line      │                    
                                         ├───────────────┤                    
                                         │ +int quantity │                    
                                         └───────────────┘                    
```



## Composition and multiplicity



```mermaid
classDiagram
 class Order {
 +submit()
 }
 class Line {
 +int quantity
 }
 Order "1" *-- "*" Line : contains
```

```text
                              ┌───────────┐                     
                              │   Order   │                     
                              ├───────────┤                     
                              │ +submit() │                     
                              └─────◆─────┘                     
                                    │                           
                   [1] contains [*] │                           
                                    │                           
                            ┌───────────────┐                   
                            │     Line      │                   
                            ├───────────────┤                   
                            │ +int quantity │                   
                            └───────────────┘                   
```



## Syntax and limits

- Braced member rows form compartments below the class header. Visibility markers and generic type text remain literal.
- Inheritance and realization use triangle heads; aggregation and composition use open and filled diamonds.
- Associations, dependencies, relationship labels, quoted multiplicities, namespaces, and notes are adapted into graph nodes, groups, and captions.
- Class identifiers may contain hyphens. Spaced generic types are accepted.
- Configuration, styles, and URLs are inert and reported. Cell budgets can wrap or omit captions: inspect the fidelity report and [increase the budget](/diagrams/options/).


---

# Render Mermaid files with the glyphcss diagram CLI

The `diagram` subcommand ships in `@glyphcss/compile`. It accepts a `.mmd` Mermaid
file or `.json` graph file. It dispatches sequences and gitGraph automatically;
Mermaid chart headers also use their native chart renderer.

## Install and render

```sh
npm i -D @glyphcss/compile
cat > example.mmd <<'EOF'
flowchart LR
 Push[Push commit] --> Build[Build app]
 Build --> Test{Tests pass?}
 Test -->|yes| Stage[Deploy staging]
 Stage --> Smoke[Smoke tests]
 Smoke --> Prod[Deploy prod]
 Test -->|no| Fix[Fix build]
EOF
npx glyphcss diagram example.mmd --target chat --width 72 --height 19
npx glyphcss diagram example.mmd --charset ascii --color none -o example.txt
```



```mermaid
flowchart LR
 Push[Push commit] --> Build[Build app]
 Build --> Test{Tests pass?}
 Test -->|yes| Stage[Deploy staging]
 Stage --> Smoke[Smoke tests]
 Smoke --> Prod[Deploy prod]
 Test -->|no| Fix[Fix build]
```

```text
        ┌─────────────┐    ┌───────────┐    ╭───────────────╮           
        │ Push commit │────▶ Build app │────▶ ◆ Tests pass? │           
        └─────────────┘    └───────────┘    ╰───────────────╯           
                                                   │ │                  
                ┌──────────────────────────────────┘ │ no               
                │             yes                    │                  
                │                             ┌──────▼────┐             
                │                             │ Fix build │             
                │                             └───────────┘             
                │                                                       
        ┌───────▼────────┐    ┌─────────────┐    ┌─────────────┐        
        │ Deploy staging │────▶ Smoke tests │────▶ Deploy prod │        
        └────────────────┘    └─────────────┘    └─────────────┘        
```



Graph JSON uses the [graph format](/diagrams/json/#graph-json); direction defaults to `TB`
when omitted. Sequence JSON and lane JSON use their Node APIs, not this subcommand.
`diagram` is 2D-only. Mesh flags and `--3d` are unknown options.

## Every flag

| Flag | Values and behavior |
| --- | --- |
| `--target` | `chat`, `terminal` (CLI default), `web` |
| `--charset` | `ascii`, `box`, `blocks`, `braille`; otherwise target default |
| `--color` | `none`, `ansi16`, `ansi256`, `truecolor`, `css`; explicit encoding override |
| `--width N` | Positive integer columns; otherwise target default |
| `--height N` | Positive integer rows; otherwise target default |
| `--direction` | `TB`, `LR`, `BT`, `RL`; graph direction override |
| `--engine` | `dagre` only |
| `--nodesep N` | Graph node separation in cells; integer ≥ 3, default 4 |
| `--ranksep N` | Graph rank separation in cells; integer ≥ 3, default 4 |
| `--title TEXT` | Diagram title; quote spaces |
| `--detail` | `auto`, `faithful`, `balanced`, `simplified` |
| `-o FILE`, `--out FILE` | Write output to a UTF-8 file |
| `-h`, `--help` | Print help to stderr and exit successfully |

The CLI does not expose API options such as `overflow`, `autoDirection`, `labelWidth`,
`loopLabelWidth`, color callbacks, lane ordering, or ID visibility.

## Piping and color

```sh
npm i -D @glyphcss/compile
printf 'flowchart LR; Build --> Test --> Ship\n' > pipeline.mmd
npx glyphcss diagram pipeline.mmd --target terminal | cat
npx glyphcss diagram pipeline.mmd --target chat > pipeline.txt
npx glyphcss diagram pipeline.mmd --target web --color css -o pipeline.html
npx glyphcss diagram pipeline.mmd --direction TB --engine dagre --nodesep 3 --ranksep 3 --title 'Release pipeline' --detail faithful
```

A TTY uses the target's default color; redirected or piped stdout uses plain text
unless `--color` overrides it. `NO_COLOR` and `FORCE_COLOR` follow the renderer's environment rules.
`--color css` emits escaped span markup for the inside of a `
`. `--out` alone does not select CSS.
There is no stdin input or `-` input convention: save source to a `.mmd` or `.json` file first.

## Diagnostics and exit codes

- Output goes to stdout, with a final newline, or to `--out` without that added newline.
- Each adaptation is printed to stderr as `glyphcss: : `.
- A file write also prints `glyphcss: wrote ` to stderr.
- Success exits 0, including renders with adaptation notes. Help exits 0. No arguments exits 1.
- Invalid arguments, file errors, validation failures, and parse errors exit 1 and print the error to stderr.

## Dispatch and ignored flags

Graph direction, spacing, and engine flags do not apply to charts, sequences, or gitGraph.
`--detail` applies to graphs and charts. `--title` applies to diagrams, including sequences
and gitGraph; chart titles come from source. Ignored flags produce `mermaid-option-ignored`.

Sequence frontmatter and initialization are inert and reported; use `--title` for its title.
Unknown headers and malformed bodies retain their tagged errors. See [troubleshooting](/diagrams/troubleshooting/).


---

# glyphcss vs beautiful-mermaid vs mermaid-ascii

This compares `@glyphcss/diagrams` and `@glyphcss/charts` with
[beautiful-mermaid](https://github.com/lukilabs/beautiful-mermaid#readme) and
[mermaid-ascii](https://github.com/AlexanderGrooff/mermaid-ascii#readme).
Competitor entries describe their public READMEs, checked on 23 October 2026.
An empty cell means the README does not establish that feature, not that it is
unsupported. Family support does not imply every Mermaid feature is reproduced.



```mermaid
flowchart LR
 Cart[Submit cart] --> Stock{In stock?}
 Stock -->|yes| Pay[Take payment]
 Pay --> Pack[Pack order]
 Pack --> Ship[Ship parcel]
 Ship --> Receipt[Send receipt]
 Stock -->|no| Notify[Notify buyer]
 Notify --> Wait[Join waitlist]
```

```text
       ┌─────────────┐   ╭─────────────╮  yes  ┌──────────────┐         
       │ Submit cart │───▶ ◆ In stock? │───────▶ Take payment │         
       └─────────────┘   ╰─────────────╯       └──────────────┘         
                                │                     │                 
                             no │                     └────────┐        
                                │                              │        
                         ┌──────▼───────┐    ┌───────────────┐ │        
                         │ Notify buyer │────▶ Join waitlist │ │        
                         └──────────────┘    └───────────────┘ │        
                                                               │        
             ┌─────────────────────────────────────────────────┘        
             │                                                          
       ┌─────▼──────┐   ┌─────────────┐    ┌──────────────┐             
       │ Pack order │───▶ Ship parcel │────▶ Send receipt │             
       └────────────┘   └─────────────┘    └──────────────┘             
```



## Documented features

| Feature | glyphcss | beautiful-mermaid | mermaid-ascii |
| --- | --- | --- | --- |
| Diagram families | Flowchart, sequence, state, class, ER, mindmap, gitGraph, block, architecture, requirement, C4; JSON graphs, sequences, and lanes | Flowchart, state, sequence, class, ER | Graph/flowchart, sequence, ER |
| Charts | Line, area, bar, scatter, pie/donut, heatmap, Sankey, funnel, treemap; Mermaid charts and schedules | XY bars, lines, combinations; ASCII and SVG | |
| Text charsets | `ascii`, `box`, `blocks`, `braille`; diagram borders remain whole-cell | ASCII or Unicode box drawing; XY bars also use blocks | ASCII or Unicode box drawing |
| Width fitting | Cell budgets, label wrapping, orientation fitting, diagram pagination; skill checks output fit | | Graph-only `--max-width N` or `auto`; retries compact spacing and warns if still too wide |
| Agent skill | One [glyphcss-diagrams skill](/coding-agents/install/) for charts and diagrams | | |
| Runtime | JavaScript/TypeScript; Node.js for CLI, browser for embeds | TypeScript, no DOM dependency | Go; prebuilt CLI binaries |
| Output | Plain/ANSI text or escaped HTML spans for a `
` | SVG plus ASCII/Unicode, ANSI/HTML color modes | Terminal text; HTTP rendering server |
| License | MIT | MIT | |

Glyphcss entries follow the [diagrams README](https://github.com/apresmoi/glyphcss/tree/main/packages/diagrams#readme),
[charts README](https://github.com/apresmoi/glyphcss/tree/main/packages/charts#readme),
and [skill README](https://github.com/apresmoi/glyphcss-diagrams#readme).
For beautiful-mermaid, see its [features](https://github.com/lukilabs/beautiful-mermaid#features),
[ASCII chart support](https://github.com/lukilabs/beautiful-mermaid#ascii-xy-charts),
and [API reference](https://github.com/lukilabs/beautiful-mermaid#api-reference).
For mermaid-ascii, see [usage and width fitting](https://github.com/AlexanderGrooff/mermaid-ascii#usage)
and [supported types](https://github.com/AlexanderGrooff/mermaid-ascii#supported-diagram-types).

## Choose for your destination

- Use Glyphcss when you need chat-sized text, diagram panels, chart types beyond XY plots, or the bundled agent skill. Check render notes for adaptations; [Mermaid styling and interactions are inert](/diagrams/troubleshooting/).
- Use beautiful-mermaid when SVG, theme switching, or Shiki theme integration matters. Its README also documents synchronous rendering and interactive SVG chart tooltips. Charts are available there too.
- Use mermaid-ascii when a prebuilt Go CLI or its HTTP server fits your workflow. Its README documents sequence frames and ER attribute tables as well as flowcharts.

Try the [diagrams workbench](/diagrams/), explore [charts](/charts/overview/),
or [install the agent skill](/coding-agents/install/).


---

# Mermaid entity relationship diagrams as text

Use `erDiagram` with `renderGlyphDiagram`. Entity attributes occupy compartments; relationship endpoints carry cardinality symbols.

## Customer orders



```mermaid
erDiagram
 CUSTOMER ||--o{ ORDER : places
 ORDER ||--|{ LINE : contains
 LINE }o--|| PRODUCT : references
 ORDER ||--o{ PAYMENT : receives
 PAYMENT ||--o| REFUND : reverses
```

```text
                                   ┌──────────┐                               
                                   │ CUSTOMER │                               
                                   └────┼─────┘                               
                                        ┼                                     
                                 places │                                     
                                        ○                                     
                                    ┌───v───┐                                 
                                    │ ORDER │                                 
                                    └──┼─┼──┘                                 
                                       ┼ ┼                                    
                              receives │ │ contains                           
                                 ┌─────┘ └─────┐                              
                                 ○             ┼                              
                            ┌────v────┐     ┌──v───┐                          
                            │ PAYMENT │     │ LINE │                          
                            └────┼────┘     └──^───┘                          
                                 ┼             ○                              
                        reverses │  references │                              
                                 ○             ┼                              
                             ┌───┼────┐   ┌────┼────┐                         
                             │ REFUND │   │ PRODUCT │                         
                             └────────┘   └─────────┘                         
```



## Attributes and keys



```mermaid
erDiagram
 ORDER {
 int id PK
 int buyer_id FK
 }
 LINE {
 int order_id PK, FK
 int quantity
 }
 ORDER ||--|{ LINE : contains
```

```text
                      ┌─────────────────┐                       
                      │      ORDER      │                       
                      ├─────────────────┤                       
                      │ int id PK       │                       
                      │ int buyer_id FK │                       
                      └────────┼────────┘                       
                               ┼                                
                      contains │                                
                               ┼                                
                     ┌─────────v──────────┐                     
                     │        LINE        │                     
                     ├────────────────────┤                     
                     │ int order_id PK,FK │                     
                     │ int quantity       │                     
                     └────────────────────┘                     
```



## Syntax and limits

- Entity declarations can include typed attribute rows and `PK`, `FK`, or `UK` markers. Backtick identifiers and comments in attribute syntax remain text.
- `||`, `o|`, `|{`, and `o{` encode one, zero-or-one, one-or-more, and zero-or-more endpoints. Crow-foot heads carry the distinction without color.
- Solid/dotted relationships and captions are adapted to graph edges. Attributes are displayed, not validated as database types.
- Styles and URLs are inert. Wide attribute lists need more columns or rows; use [faithful detail](/diagrams/options/#detail-levels) to retain identities before splitting.


---

# Mermaid flowcharts as ASCII text diagrams

Use `renderGlyphDiagram` from `@glyphcss/diagrams`. Both `flowchart` and `graph` accept `TB`, `BT`, `LR`, and `RL`; an omitted direction starts at `TB`.

## Route an order



```mermaid
flowchart LR
 Cart[Submit cart] --> Stock{In stock?}
 Stock -->|yes| Pay[Take payment]
 Pay --> Pack[Pack order]
 Pack --> Ship[Ship parcel]
 Ship --> Receipt[Send receipt]
 Stock -->|no| Notify[Notify buyer]
 Notify --> Wait[Join waitlist]
```

```text
       ┌─────────────┐   ╭─────────────╮  yes  ┌──────────────┐         
       │ Submit cart │───▶ ◆ In stock? │───────▶ Take payment │         
       └─────────────┘   ╰─────────────╯       └──────────────┘         
                                │                     │                 
                             no │                     └────────┐        
                                │                              │        
                         ┌──────▼───────┐    ┌───────────────┐ │        
                         │ Notify buyer │────▶ Join waitlist │ │        
                         └──────────────┘    └───────────────┘ │        
                                                               │        
             ┌─────────────────────────────────────────────────┘        
             │                                                          
       ┌─────▼──────┐   ┌─────────────┐    ┌──────────────┐             
       │ Pack order │───▶ Ship parcel │────▶ Send receipt │             
       └────────────┘   └─────────────┘    └──────────────┘             
```



## Group a processing pipeline



```mermaid
graph LR
 subgraph ingest[Order ingestion]
 Upload[Upload batch] --> Validate[Validate rows]
 end
 Validate -->|valid| Store[(Orders)]
 Validate -->|invalid| Reject[Reject batch]
 Store -.-> Audit[Audit log]
```

```text
                                                ◜────────◝       ┌───────────┐  
·············Order ingestion·············     ┌─▶ Orders │╌╌╌╌╌╌╌▶ Audit log │  
·                                       ·     │ ◟────────◞       └───────────┘  
·                     ┌───────────────┐ ·     │                                 
· ┌──────────────┐    │               │───────┘ valid                           
· │ Upload batch │────▶ Validate rows │ ·invalid                                
· └──────────────┘    │               │────┐                                    
·                     └───────────────┘ ·  │ ┌──────────────┐                   
·                                       ·  └─▶ Reject batch │                   
·········································    └──────────────┘                   
```



## Syntax and limits

- Declare labels with `A[Label]`, decisions with `A{Question}`, and storage with `A[(Records)]`. See the [shape catalogue](/diagrams/shapes/) for JSON and `@{shape: ...}` forms.
- Use `-->` for a directed edge, `---` for a line, `-.->` for dotted, and `==>` for thick. Pipe labels such as `-->|yes|` travel with their edge.
- `subgraph ... end` creates a group; nested groups reserve enclosing frames.
- Bidirectional edges retain both heads. Invisible connections influence layout without painting an edge.
- Styling, click actions, images, and external assets do not execute. Read `mermaid-degraded` notes for adaptations.
- Long labels wrap. A fixed grid may simplify or split a graph; choose [faithful detail or expansion](/diagrams/options/) when identity matters.


---

# Text diagrams in vanilla JavaScript, React, and Vue

Diagrams use the cell renderer directly. They do not need the 3D scene bindings.
Install `@glyphcss/diagrams` in your application, then pass Mermaid source or graph data.
The examples use `color: "none"` and assign the result as text.

## Vanilla JavaScript

```html


```

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const host = document.querySelector("#diagram")!;
try {
  const result = await renderGlyphDiagram(`flowchart LR
  Push[Push commit] --> Build[Build app]
  Build --> Test{Tests pass?}
  Test -->|yes| Stage[Deploy staging]
  Stage --> Smoke[Smoke tests]
  Smoke --> Prod[Deploy prod]
  Test -->|no| Fix[Fix build]`, {
    target: "web", color: "none", width: 72, height: 19, overflow: "expand",
  });
  host.textContent = result.text;
} catch (error) {
  host.textContent = error instanceof Error ? error.message : String(error);
}
```

## React

```tsx
import { useEffect, useState } from "react";
import { renderGlyphDiagram } from "@glyphcss/diagrams";

export function GlyphOrderDiagram({ source = `flowchart LR
  Push[Push commit] --> Build[Build app]
  Build --> Test{Tests pass?}
  Test -->|yes| Stage[Deploy staging]
  Stage --> Smoke[Smoke tests]
  Smoke --> Prod[Deploy prod]
  Test -->|no| Fix[Fix build]` }) {
  const [text, setText] = useState("");
  useEffect(() => {
    let active = true;
    renderGlyphDiagram(source, {
      target: "web", color: "none", width: 72, height: 19, overflow: "expand",
    }).then(
      result => { if (active) setText(result.text); },
      error => { if (active) setText(error instanceof Error ? error.message : String(error)); },
    );
    return () => { active = false; };
  }, [source]);
  return 
{text}
; } ``` ```css .order-diagram { font-family: "Glyph Mono", ui-monospace, monospace; line-height: 1; overflow: auto; } ``` The cleanup prevents a completed older request from replacing a newer diagram or updating an unmounted component. It also tolerates React StrictMode replay. ## Vue ```vue ``` ## Rendered result ```mermaid flowchart LR Push[Push commit] --> Build[Build app] Build --> Test{Tests pass?} Test -->|yes| Stage[Deploy staging] Stage --> Smoke[Smoke tests] Smoke --> Prod[Deploy prod] Test -->|no| Fix[Fix build] ``` ```text ┌─────────────┐ ┌───────────┐ ╭───────────────╮ │ Push commit │────▶ Build app │────▶ ◆ Tests pass? │ └─────────────┘ └───────────┘ ╰───────────────╯ │ │ ┌──────────────────────────────────┘ │ no │ yes │ │ ┌──────▼────┐ │ │ Fix build │ │ └───────────┘ │ ┌───────▼────────┐ ┌─────────────┐ ┌─────────────┐ │ Deploy staging │────▶ Smoke tests │────▶ Deploy prod │ └────────────────┘ └─────────────┘ └─────────────┘ ``` ## Colored HTML Use `color: "css"` to obtain `result.html`, escaped span markup for the contents of a `
`.
Insert that fragment inside the `
`; the library does not supply the outer element.
The library escapes label text; do not concatenate unescaped source into the fragment.

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const result = await renderGlyphDiagram("flowchart LR; Build --> Ship", {
  target: "web", color: "css", width: 64, height: 16,
});
const wrapper = document.createElement("pre");
wrapper.className = "diagram-html";
wrapper.innerHTML = result.html!;
document.body.append(wrapper);
```

```css
.diagram-html {
  font-family: "Glyph Mono", ui-monospace, monospace;
  line-height: 1;
  overflow: auto;
}
```

React can use `
`; Vue can use
`
`. Populate `html` from `result.html` and retain the same stale-result
cleanup as in the text examples. The `pre` needs the font and line-height rules above.

## Resize and static rendering

Measure available columns and rows at a stable font size, then call the renderer again.
Use a `ResizeObserver` owned and disconnected by the component lifecycle. Read actual
expanded dimensions from `result.canvas.grid`; see [sizing](/diagrams/options/#width-and-height).

For a static site, call the renderer at build time and emit text or CSS HTML without
hydration. These documentation examples do that through a shared Astro adapter; no diagram
runtime is required to display their output. The same renderer works in Node for server output.


---

# Mermaid gitGraph and JSON lane diagrams

Mermaid `gitGraph` goes through `renderGlyphDiagram`. Direct lane JSON and git-log text use `renderGlyphLaneDag` from `@glyphcss/diagrams/lanes`.

## Branch and merge



```mermaid
gitGraph TB:
 commit id: "Baseline" tag: "v1.0"
 branch checkout
 commit id: "Cart totals"
 commit id: "Card payment"
 checkout main
 commit id: "Update docs"
 branch receipts
 commit id: "Email template"
 commit id: "Receipt tests"
 checkout main
 merge checkout id: "Ship checkout"
 merge receipts id: "Ship receipts"
 commit id: "Release" tag: "v1.1"
```

```text
                 *     Baseline  (tag: v1.0)                      
                 ├─╮                                              
                 │ *   Cart totals                                
                 │ *   Card payment  (checkout)                   
                 * │   Update docs                                
                 ├─┼─╮                                            
                 │ │ * Email template                             
                 │ │ * Receipt tests  (receipts)                  
                 ├─╯ │                                            
                 *   │ Ship checkout  (merge)                     
                 ├───╯                                            
                 *     Ship receipts  (merge)                     
                 *     Release  (main, tag: v1.1)                 
```



## Tags and commit annotations



```mermaid
gitGraph BT:
 commit id: "Baseline" tag: "v1.0"
 commit id: "Fix" type: REVERSE
 commit id: "Release" tag: "v1.1" type: HIGHLIGHT
```

```text
            * Release  (main, HIGHLIGHT, tag: v1.1)             
            * Fix  (REVERSE)                                    
            * Baseline  (tag: v1.0)                             
```



## Syntax and limits

- `commit`, `branch`, `checkout`, `merge`, and `cherry-pick` build the history. Tags, types, and authored IDs become text annotations.
- `TB` and `LR` read oldest-first; `BT` reads newest-first. `LR` uses the vertical lane layout and reports the adaptation.
- Mermaid commit IDs become stable internal hexadecimal IDs; duplicate authored IDs still create distinct nodes and retain their authored text.
- Lane ordering configuration is adapted where supported; unused configuration and visual settings are reported.
- Direct lane options include `order: "newest-first" | "oldest-first"` and `ids`. IDs default on for git-log strings and off for lane objects.
- Lane objects must list newest nodes first, with parents later. Set `truncated: true` for a window with missing older parents; continuation strokes mark the boundary.
- A narrow canvas can collapse lanes while retaining rows and labels. Pagination keeps each node with its connectors; expansion grows height at the same width.

## Read a repository log

```sh
npm i -D @glyphcss/diagrams
git log --pretty=format:'%h|%p|%d|%s' > history.txt
```

```ts
import { readFile } from "node:fs/promises";
import { renderGlyphLaneDag } from "@glyphcss/diagrams/lanes";
const source = await readFile("history.txt", "utf8");
const result = await renderGlyphLaneDag(source, { target: "chat" });
console.log(result.text);
```

The [JSON reference](/diagrams/json/#lanes-json) shows the equivalent lane structure.


---

# JSON diagram formats and validation schemas

Choose the data model that matches your diagram. Graphs describe spatial connections;
sequences describe messages in time; lane DAGs describe ancestry. Unknown fields are rejected.
Pass objects directly to renderers, or use the JSON-string wrappers below.

## Graph JSON



```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "api",
      label: "Order API",
      shape: "rounded"
    },
    {
      id: "cache",
      label: "Cache",
      shape: "cylinder"
    },
    {
      id: "db",
      label: "Orders",
      shape: "cylinder"
    },
    {
      id: "queue",
      label: "Job queue"
    },
    {
      id: "worker",
      label: "Receipt worker"
    },
    {
      id: "files",
      label: "Receipts",
      shape: "cylinder"
    }
  ],
  edges: [
    {
      id: "read",
      from: "api",
      to: "cache",
      label: "reads"
    },
    {
      id: "save",
      from: "api",
      to: "db",
      label: "stores"
    },
    {
      id: "enqueue",
      from: "api",
      to: "queue",
      label: "enqueues"
    },
    {
      from: "queue",
      to: "worker"
    },
    {
      from: "worker",
      to: "files",
      label: "writes"
    }
  ]
}, {
  target: "chat",
  width: 74,
  height: 23,
  overflow: "expand"
});
console.log(text);
```

```text
               enqueues   ┌───────────┐  ┌────────────────┐ writes ◜──────────◝
              ┌───────────▶ Job queue │──▶ Receipt worker │────────▶ Receipts │
              │           └───────────┘  └────────────────┘        ◟──────────◞
              │                                                                
╭───────────╮ │     reads   ◜───────◝                                          
│ Order API ├─┼─────────────▶ Cache │                                          
╰───────────╯ │             ◟───────◞                                          
              │                                                                
              │  stores     ◜────────◝                                         
              └─────────────▶ Orders │                                         
                            ◟────────◞                                         
```



`renderGlyphDiagram(graph, options)` uses these fields:

| Object | Fields |
| --- | --- |
| Graph | `nodes`, `edges`, `direction`; optional `groups` |
| Node | Required `id`, `label`; optional `shape`, `kind`, `group`, `compartments` |
| Edge | Required `from`, `to`; optional `id`, `label`, `style`, `priority`, `startHead`, `endHead`, `invisible` |
| Group | Required `id`, `members`; optional `label`, `parent` |

IDs must be unique in their collection. Edges and group members must reference known nodes.
A node's named group must contain it. A group's parent must contain its members and cannot form a cycle.
`compartments` is an array of string arrays for `shape: "compartment"`.
`kind` is informational; it does not select an outline.

Directions are `TB`, `LR`, `BT`, `RL`. `glyphGraphFromJson` and the renderer default an
omitted direction to `TB`; `validateGlyphGraph` and the schema require it explicitly.
Edge styles are `solid`, `dotted`, `thick`, `undirected`. Heads are `arrow`, `circle`,
`cross`, `none`, `triangle`, `filled-diamond`, `open-diamond`, `er-one`, `er-zero-one`,
`er-many`, `er-zero-many`. Invisible edges affect layout without painting.

## Sequence JSON



```ts
import { renderGlyphSequence } from "@glyphcss/diagrams/sequence";

const { text } = await renderGlyphSequence({
  participants: [
    {
      id: "client",
      label: "Client"
    },
    {
      id: "api",
      label: "API"
    }
  ],
  messages: [
    {
      from: "client",
      to: "api",
      label: "GET /orders"
    },
    {
      from: "api",
      to: "client",
      label: "200 OK",
      style: "dashed"
    }
  ],
  frames: [
    {
      kind: "loop",
      label: "Poll",
      from: 0,
      to: 1
    }
  ],
  notes: [
    {
      text: "Read only",
      over: ["client", "api"],
      at: 0
    }
  ]
}, {
  target: "chat",
  width: 56,
  height: 20,
  overflow: "expand"
});
console.log(text);
```

```text
          Client                         API            
             │                            │             
           ┌─ loop Poll ──────────────────┼─┐           
           │ ┌────────────────────────────┐ │           
           │ │       note  Read only      │ │           
           │ └────────────────────────────┘ │           
           │ │ GET /orders                │ │           
           │ ├───────────────────────────▶│ │           
           │ │                            │ │           
           │ │ 200 OK                     │ │           
           │ │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┤ │           
           └─┼────────────────────────────┼─┘           
             │                            │             
```



`renderGlyphSequence(sequence, options)` takes required `participants` and `messages`,
plus optional `title`, `frames`, and `notes`.

- Participants have `id`, `label`, optional informational `kind`, and `shape: "lane" | "actor"`.
- Messages have `from`, `to`, optional `id`, `label`, and `style: "solid" | "dashed"`.
- Frames have `kind`, optional `label`, inclusive zero-based message indices `from` and `to`, and optional `branches`.
- Branches have `kind`, optional `label`, and `at`, in ascending order within the frame's range through `to + 1`.
- Notes have `text`, participant IDs in `over`, and `at` before a message. `at: messages.length` places a final note. Optional `placement: "left" | "right"` positions it beside one participant.

Frame kinds render verbatim. All participant references and index ranges are validated.

## Lanes JSON



```ts
import { renderGlyphLaneDag } from "@glyphcss/diagrams/lanes";

const { text } = await renderGlyphLaneDag({
  nodes: [
    {
      id: "ship",
      label: "Release",
      parents: ["fix", "docs"],
      marks: ["v1.1"]
    },
    {
      id: "fix",
      label: "Payment fix",
      parents: ["start"]
    },
    {
      id: "docs",
      label: "Documentation",
      parents: ["start"]
    },
    {
      id: "start",
      label: "Baseline",
      parents: []
    }
  ]
}, {
  target: "chat",
  width: 56,
  height: 14
});
console.log(text);
```

```text
                  *   (v1.1)  Release                   
                  ├─╮                                   
                  * │ Payment fix                       
                  │ * Documentation                     
                  ├─╯                                   
                  *   Baseline                          
```



`renderGlyphLaneDag(dag, options)` takes `nodes` and optional `truncated`.
Each node has `id`, `label`, `parents` (older IDs), and optional `marks` (strings).

Nodes must be newest-first and every present parent must occur later in the array.
Self-parents and duplicate IDs fail validation. Missing parents are allowed only with
`truncated: true`; this represents older history outside the supplied window.
Use `order` to change display order without changing input order.

## Validate and generate schemas

```ts
import {
  glyphGraphFromJson,
  validateGlyphGraph,
  glyphDiagramJsonSchema,
  GLYPH_DIAGRAM_JSON_SCHEMA_KEYWORDS,
} from "@glyphcss/diagrams";

const graph = glyphGraphFromJson({
  nodes: [{ id: "input", label: "Input" }],
  edges: [],
});
validateGlyphGraph(graph); // Returns the validated graph; throws a tagged error.
const schema = glyphDiagramJsonSchema();
```

For sequences use `validateGlyphSequence`, `glyphSequenceJsonSchema`, and
`GLYPH_SEQUENCE_JSON_SCHEMA_KEYWORDS` from `@glyphcss/diagrams/sequence`.
For lanes use `validateGlyphLaneDag`, `glyphLaneDagJsonSchema`, and
`GLYPH_LANE_JSON_SCHEMA_KEYWORDS` from `@glyphcss/diagrams/lanes`.

Standard JSON Schema checks structure. Register the exported custom keywords with Ajv
for relational checks such as unique IDs, valid endpoints, group membership, or parent order:

```ts
import Ajv from "ajv";
import { glyphDiagramJsonSchema, GLYPH_DIAGRAM_JSON_SCHEMA_KEYWORDS } from "@glyphcss/diagrams";

const ajv = new Ajv({ strict: false });
for (const keyword of GLYPH_DIAGRAM_JSON_SCHEMA_KEYWORDS) ajv.addKeyword(keyword);
const validate = ajv.compile(glyphDiagramJsonSchema());
```

## JSON-string wrappers

| Import | Wrapper |
| --- | --- |
| `@glyphcss/diagrams` | `renderGlyphDiagramJson(json, options)` |
| `@glyphcss/diagrams/sequence` | `renderGlyphSequenceJson(json, options)` |
| `@glyphcss/diagrams/lanes` | `renderGlyphLaneDagJson(json, options)` |

These return promises of serialized JSON output, not the normal result object.
Use the object renderer when you need `canvas`, `pages`, or `report` as JavaScript values.
Failures resolve to serialized `{ error, code, hint }` rather than rejecting.
Malformed JSON has model-specific error codes listed in [troubleshooting](/diagrams/troubleshooting/).


---

# Mermaid mindmaps as text trees

Pass `mindmap` source to `renderGlyphDiagram`. Indentation defines parentage; the adapter creates a left-to-right tree.

## Plan a release



```mermaid
mindmap
 root(Release v2)
  Checkout
   Card payments
   Order receipts
  Operations
   Backups
   Error alerts
  Rollout
   Staff preview
   Public launch
```

```text
                                         ╭───────────────╮        
                                      ┌──│ Card payments │        
                         ╭──────────╮ │  ╰───────────────╯        
                      ┌──│ Checkout ├─┤                           
                      │  ╰──────────╯ │  ╭────────────────╮       
                      │               └──│ Order receipts │       
                      │                  ╰────────────────╯       
                      │                                           
                      │                   ╭─────────╮             
                      │                ┌──│ Backups │             
       ╭────────────╮ │ ╭────────────╮ │  ╰─────────╯             
       │ Release v2 ├─┼─│ Operations ├─┤                          
       ╰────────────╯ │ ╰────────────╯ │  ╭──────────────╮        
                      │                └──│ Error alerts │        
                      │                   ╰──────────────╯        
                      │                                           
                      │                   ╭───────────────╮       
                      │               ┌───│ Staff preview │       
                      │   ╭─────────╮ │   ╰───────────────╯       
                      └───│ Rollout ├─┤                           
                          ╰─────────╯ │   ╭───────────────╮       
                                      └───│ Public launch │       
                                          ╰───────────────╯       
```



## Choose node outlines



```mermaid
mindmap
 root(Portal)
  )Cloud services(
  ))Alerts((
  {{Security}}
```

```text
                             ╭◠◠◠◠◠◠◠◠◠◠◠◠◠◠◠◠╮                 
                           ┌─│ Cloud services │                 
                           │ ╰◡◡◡◡◡◡◡◡◡◡◡◡◡◡◡◡╯                 
                           │                                    
                ╭────────╮ │ *╱╲╱╲╱╲╱╲*                         
                │ Portal ├─┼─│ Alerts │                         
                ╰────────╯ │ *╲╱╲╱╲╱╲╱*                         
                           │                                    
                           │ ╱──────────╲                       
                           └─❬ Security ❭                       
                             ╲──────────╱                       
```



## Syntax and limits

- Rounded nodes are the default. Circle, cloud, bang, and hexagon delimiters select outlines.
- Repeated labels are separate tree nodes. Uneven dedents and apostrophes are accepted.
- Icons, classes, and configuration are inert. Markdown labels become plain text and the adaptation is reported.
- Deep trees may become wide. Use `autoDirection`, more columns, or [pagination](/diagrams/options/) rather than shrinking the font.


---

# ASCII diagram options, sizing, and overflow

All three diagram renderers accept `target`, `charset`, `color`, `width`, `height`,
`overflow`, and `title`. Graph-only layout options do not apply to sequences or lanes.

## Targets and character sets

`target` chooses defaults; explicit options override them. See the [target table](/diagrams/overview/#choose-a-target).
`charset` accepts `ascii`, `box`, `blocks`, or `braille`. Borders remain whole-cell;
ASCII replaces special outlines and folds unsupported label characters.



```mermaid
flowchart LR
 Read[Read order] --> Auth[Check access]
 Auth --> Cache{Cached?}
 Cache -->|yes| Reply[Return order]
 Cache -->|no| Load[(Orders)]
 Load --> Refresh[Refresh cache]
```

```text
                                          yes +--------+                
                                            +-> Return |                
                                            | |  order |                
  +------------+  +--------+  /-----------\ | +--------+                
  | Read order |-->  Check |--> * Cached? +-+                           
  +------------+  | access |  \-----------/ | +--------+  +---------+   
                  +--------+                +-> Orders |--> Refresh |   
                                           no +--------+  |  cache  |   
                                                          +---------+   
```





```mermaid
flowchart LR
 Read[Read order] --> Auth[Check access]
 Auth --> Cache{Cached?}
 Cache -->|yes| Reply[Return order]
 Cache -->|no| Load[(Orders)]
 Load --> Refresh[Refresh cache]
```

```text
                                          yes ┌────────┐                
                                            ┌─▶ Return │                
                                            │ │  order │                
  ┌────────────┐  ┌────────┐  ╭───────────╮ │ └────────┘                
  │ Read order │──▶  Check │──▶ ◆ Cached? ├─┤                           
  └────────────┘  │ access │  ╰───────────╯ │ ◜────────◝  ┌─────────┐   
                  └────────┘                └─▶ Orders │──▶ Refresh │   
                                           no ◟────────◞  │  cache  │   
                                                          └─────────┘   
```



## Color encodings

| `color` | Result |
| --- | --- |
| `none` | Plain `text`, no color escapes |
| `ansi16` | ANSI text using 16 colors |
| `ansi256` | ANSI text using 256 colors |
| `truecolor` | ANSI text using RGB colors |
| `css` | Escaped HTML in `html`, with colored spans |

Use `text` for text-only hosts and `html` for browser color. Do not put ANSI text into HTML.
`nodeColor` and `edgeColor` override graph colors; `participantColor` overrides sequence colors;
`laneColor` overrides lane colors. Each accepts a color string or item callback, and has no effect with `color: "none"`.



```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                                 yes ┌────────────┐  ┌──────────────┐   
                                  ┌──▶ Load order │──▶ Return order │   
   ┌───────────────┐  ╭─────────╮ │  └────────────┘  └──────────────┘   
   │ Order request │──▶ ◆ Token ├─┤                                     
   └───────────────┘  │ valid?  │ │  ┌────────────┐                     
                      ╰─────────╯ └──▶ Return 401 │                     
                                  no └────────────┘                     
```



## Width and height

`width` and `height` are positive integer cell budgets, not pixels. A fixed font size
makes available columns approximately host width divided by character advance, and rows
approximately host height divided by line height. Re-render when those counts change.
Resize changes layout; it does not shrink the font or alter density.

### Paginate for fixed output

`overflow: "paginate"` is the default. Graph pages keep the requested dimensions.
When fitting fails, the renderer can simplify or split the graph. A budget too small
for even one node can yield an empty panel and a report entry; inspect the output.
Sequences paginate by time and repeat headers. Lane pages keep nodes with their connectors.
This 32-column example keeps the labels whole and repeats boundary nodes across panels.



```mermaid
flowchart TB; Receive[Receive order] --> Validate[Validate payment] --> Dispatch[Dispatch parcel]
```

```text
       ┌───────────────┐        
       │ Receive order │        
       └───────────────┘        
               │                
               │                
      ┌────────▼─────────┐      
      │ Validate payment │      
      └──────────────────┘      
                                

      ┌──────────────────┐      
      │ Validate payment │      
      └──────────────────┘      
               │                
               │                
      ┌────────▼────────┐       
      │ Dispatch parcel │       
      └─────────────────┘       
```



### Expand for a pannable host

`overflow: "expand"` lets graphs grow to a connected canvas. Read actual dimensions
from `result.canvas.grid.cols` and `.rows`, then let the host pan or scroll.
Sequences and lanes expand their height at the requested width; they can still be too wide.
The same 32-column example below grows vertically to keep the path connected.
The workbench uses expansion for web diagrams. Expansion can still fall back to splitting
when the bounded fitting search cannot find a usable layout.



```mermaid
flowchart TB; Receive[Receive order] --> Validate[Validate payment] --> Dispatch[Dispatch parcel]
```

```text
       ┌───────────────┐        
       │ Receive order │        
       └───────────────┘        
               │                
               │                
      ┌────────▼─────────┐      
      │ Validate payment │      
      └──────────────────┘      
               │                
               │                
      ┌────────▼────────┐       
      │ Dispatch parcel │       
      └─────────────────┘       
```



## Direction and automatic direction

Graphs accept `direction: "TB" | "LR" | "BT" | "RL"` to override their source direction.
`autoDirection: true` permits a perpendicular orientation during fitting. Omit it to keep
the source orientation in ordinary flowcharts. Structured Mermaid readers may enable
adaptive orientation by default; C4 respects an explicit direction.



```mermaid
flowchart LR; Build[Build app] --> Test{Tests pass?}; Test -->|yes| Ship[Deploy]; Test -->|no| Fix[Fix build]
```

```text
            ┌───────────┐               
            │ Build app │               
            └───────────┘               
                  │                     
                  │                     
          ╭───────▼───────╮             
          │ ◆ Tests pass? │             
          ╰───────┬───────╯             
                  │                     
          ┌───────┴───────┐             
          │ yes        no │             
          │               │             
      ┌───▼────┐    ┌─────▼─────┐       
      │ Deploy │    │ Fix build │       
      └────────┘    └───────────┘       
```



## Detail levels

| `detail` | Graph behavior |
| --- | --- |
| `auto` (also the omitted behavior) | Fit first, then reduce decoration, merge duplicates, collapse leaves, and split as needed |
| `balanced` | Currently follows the same graph path as `auto` |
| `faithful` | Skip decoration/duplicate/leaf reductions; fitting and splitting remain possible |
| `simplified` | Start decoration reduction even when the initial layout fits |

Faithful output can still wrap labels, lose optional diamond markers, or split.
It is not a promise that arbitrary input fits an arbitrary grid.



```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                                 yes ┌────────────┐  ┌──────────────┐   
                                  ┌──▶ Load order │──▶ Return order │   
   ┌───────────────┐  ╭─────────╮ │  └────────────┘  └──────────────┘   
   │ Order request │──▶ ◆ Token ├─┤                                     
   └───────────────┘  │ valid?  │ │  ┌────────────┐                     
                      ╰─────────╯ └──▶ Return 401 │                     
                                  no └────────────┘                     
```





```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                                       ┌────────────┐  ┌──────────────┐ 
                                     ┌─▶ Load order │──▶ Return order │ 
 ┌───────────────┐  ┌──────────────┐ │ └────────────┘  └──────────────┘ 
 │ Order request │──▶ Token valid? ├─┤                                  
 └───────────────┘  └──────────────┘ │ ┌────────────┐                   
                                     └─▶ Return 401 │                   
                                       └────────────┘                   
```



## Titles and spacing

`title` adds a rendered title and overrides sequence/lane source titles. Graph spacing options are
`nodesep`, `ranksep`, `margin`, `labelWidth` (default 18), `loopLabelWidth` (default 24),
and `frameInset` (default true). `nodesep` and `ranksep` default to 4 and require integers
of at least 3. `margin` defaults to 1 and accepts nonnegative integers; label-width options
require positive integers. Width limits wrap labels; frame inset pads nested group boundaries.
The default layout engine is `dagre`. The `elk` option names a reserved adapter that is
currently unavailable; use `dagre`. The CLI exposes only `dagre`.



```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                              Order lookup                              
                                                                        
                                   yes ┌────────────┐  ┌──────────────┐ 
                                     ┌─▶ Load order │──▶ Return order │ 
 ┌───────────────┐  ╭──────────────╮ │ └────────────┘  └──────────────┘ 
 │ Order request │──▶ Token valid? ├─┤                                  
 └───────────────┘  ╰──────────────╯ │ ┌────────────┐                   
                                     └─▶ Return 401 │                   
                                    no └────────────┘                   
```



## Read the fidelity report

A fidelity report explains how the result differs from the input. `report.ledger` holds
entries with a stable `code`, readable `message`, and optional structured `detail`.

```ts
for (const { code, message } of result.report.ledger) {
  console.warn(`${code}: ${message}`);
}
console.log(result.pages.length);
```

`meta` retains source identities. `report.unsupportedGlyphs` lists unsupported characters;
graph results also expose `report.unroutable`. Common adaptation codes and remedies are in
[troubleshooting](/diagrams/troubleshooting/).


---

# Mermaid and JSON diagrams as ASCII text

`@glyphcss/diagrams` turns Mermaid source and JSON data into monospace text.
It measures labels, lays out nodes, routes connections, and paints character cells.
It needs no scene, canvas element, or WebGL context.

## Install and render a flowchart

```sh
npm i @glyphcss/diagrams
```

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const result = await renderGlyphDiagram(
  `flowchart LR
 Push[Push commit] --> Build[Build app]
 Build --> Test{Tests pass?}
 Test -->|yes| Stage[Deploy staging]
 Stage --> Smoke[Smoke tests]
 Smoke --> Prod[Deploy prod]
 Test -->|no| Fix[Fix build]`,
  { target: "chat", width: 72, height: 19, overflow: "expand" },
);
console.log(result.text);
```



```mermaid
flowchart LR
 Push[Push commit] --> Build[Build app]
 Build --> Test{Tests pass?}
 Test -->|yes| Stage[Deploy staging]
 Stage --> Smoke[Smoke tests]
 Smoke --> Prod[Deploy prod]
 Test -->|no| Fix[Fix build]
```

```text
        ┌─────────────┐    ┌───────────┐    ╭───────────────╮           
        │ Push commit │────▶ Build app │────▶ ◆ Tests pass? │           
        └─────────────┘    └───────────┘    ╰───────────────╯           
                                                   │ │                  
                ┌──────────────────────────────────┘ │ no               
                │             yes                    │                  
                │                             ┌──────▼────┐             
                │                             │ Fix build │             
                │                             └───────────┘             
                │                                                       
        ┌───────▼────────┐    ┌─────────────┐    ┌─────────────┐        
        │ Deploy staging │────▶ Smoke tests │────▶ Deploy prod │        
        └────────────────┘    └─────────────┘    └─────────────┘        
```



## Choose a target

Targets set default cell budgets, character sets, and color encodings.
A cell is one monospace character position; width counts columns and height counts rows.
These previews use explicit compact sizes and `color: "none"` so terminal escape codes do not appear in HTML.

| Target | Default columns × rows | Charset | Color |
| --- | --- | --- | --- |
| `chat` | 72 × 24 | `box` | `none` |
| `terminal` | 80 × 24 | `braille` | `truecolor` |
| `web` (API default) | 96 × 32 | `braille` | `css` |

### Chat



```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                                 yes ┌────────────┐  ┌──────────────┐   
                                  ┌──▶ Load order │──▶ Return order │   
   ┌───────────────┐  ╭─────────╮ │  └────────────┘  └──────────────┘   
   │ Order request │──▶ ◆ Token ├─┤                                     
   └───────────────┘  │ valid?  │ │  ┌────────────┐                     
                      ╰─────────╯ └──▶ Return 401 │                     
                                  no └────────────┘                     
```



### Terminal



```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                                 yes ┌────────────┐  ┌──────────────┐   
                                  ┌──▶ Load order │──▶ Return order │   
   ┌───────────────┐  ╭─────────╮ │  └────────────┘  └──────────────┘   
   │ Order request │──▶ ◆ Token ├─┤                                     
   └───────────────┘  │ valid?  │ │  ┌────────────┐                     
                      ╰─────────╯ └──▶ Return 401 │                     
                                  no └────────────┘                     
```



### Web



```mermaid
flowchart LR; Request[Order request] --> Auth{Token valid?}; Auth -->|yes| Load[Load order]; Load --> Reply[Return order]; Auth -->|no| Deny[Return 401]
```

```text
                                 yes ┌────────────┐  ┌──────────────┐   
                                  ┌──▶ Load order │──▶ Return order │   
   ┌───────────────┐  ╭─────────╮ │  └────────────┘  └──────────────┘   
   │ Order request │──▶ ◆ Token ├─┤                                     
   └───────────────┘  │ valid?  │ │  ┌────────────┐                     
                      ╰─────────╯ └──▶ Return 401 │                     
                                  no └────────────┘                     
```



Diagram borders use whole cells in every charset. Targets do not change a diagram into a raster image.

## Choose the entry point

| Input | Import and function |
| --- | --- |
| Mermaid graph families, including gitGraph; JSON graph | `@glyphcss/diagrams`: `renderGlyphDiagram` |
| Mermaid sequence; JSON sequence | `@glyphcss/diagrams/sequence`: `renderGlyphSequence` |
| JSON lane DAG; git-log text | `@glyphcss/diagrams/lanes`: `renderGlyphLaneDag` |

Every renderer returns `text`, optional `html`, `pages`, `meta`, and `report`.
The **fidelity report** describes adaptations made while reading and fitting the source.
Its `ledger` is a list of `{ code, message, detail? }` entries. Read it when labels,
shapes, or panel boundaries differ from your source.

## Where to go next

- Explore [flowcharts](/diagrams/flowcharts/), [sequences](/diagrams/sequence/), or [JSON input](/diagrams/json/).
- Tune [options and sizing](/diagrams/options/) and compare [node shapes](/diagrams/shapes/).
- Edit a live example in the [diagrams workbench](/diagrams/).
- Render files with the [CLI](/diagrams/cli/).
- Embed output in [vanilla JavaScript, React, or Vue](/diagrams/frameworks/).
- Install [glyphcss-diagrams](/coding-agents/install/) for diagrams in coding-agent conversations.
- Compare [glyphcss, beautiful-mermaid, and mermaid-ascii](/diagrams/comparison/).


---

# Mermaid requirement diagrams as text

Pass `requirementDiagram` source to `renderGlyphDiagram`. Fields become compartment rows and relations become labelled edges.

## Connect an implementation to a requirement



```mermaid
requirementDiagram
 requirement safe {
 id: R1
 text: "No duplicate charge"
 risk: high
 verifymethod: test
 }
 requirement audit {
 id: R2
 text: "Record every refund"
 risk: medium
 verifymethod: test
 }
 element api {
 type: service
 docref: "Payment API"
 }
 element suite {
 type: test
 docref: "Retry tests"
 }
 element ledger {
 type: service
 docref: "Refund log"
 }
 api - satisfies -> safe
 suite - verifies -> safe
 ledger - satisfies -> audit
 safe - traces -> audit
```

```text
                           ┌─────────────────────┐    ┌─────────────────────┐           
                           │        suite        │    │         api         │           
                           │     <>     │    │     <>     │           
                           ├─────────────────────┤    ├─────────────────────┤           
                           │ type: test          │    │ type: service       │           
                           │ docref: Retry tests │    │ docref: Payment API │           
                           └─────────────────────┘    └─────────────────────┘           
                                      ╎                          ╎                      
                                      ╎ verifies       satisfies ╎                      
                                      └╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌┘                      
                                                   │                                    
                                     ┌─────────────▼─────────────┐                      
           ┌────────────────────┐    │           safe            │                      
           │       ledger       │    │      <>      │                      
           │     <>    │    ├───────────────────────────┤                      
           ├────────────────────┤    │ id: R1                    │                      
           │ type: service      │    │ text: No duplicate charge │                      
           │ docref: Refund log │    │ risk: high                │                      
           └────────────────────┘    │ verifymethod: test        │                      
                     ╎               └───────────────────────────┘                      
                     ╎                             ╎                                    
                     ╎ satisfies          traces   ╎                                    
                     └╌╌╌╌╌╌╌╌╌╌╌╌╌╌┬╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘                                    
                                    │                                                   
                      ┌─────────────▼─────────────┐                                     
                      │           audit           │                                     
                      │      <>      │                                     
                      ├───────────────────────────┤                                     
                      │ id: R2                    │                                     
                      │ text: Record every refund │                                     
                      │ risk: medium              │                                     
                      │ verifymethod: test        │                                     
                      └───────────────────────────┘                                     
```



## Record verification



```mermaid
requirementDiagram
 performanceRequirement fast {
 id: R2
 text: "Checkout under 2s"
 risk: medium
 verifymethod: analysis
 }
 element suite {
 type: test
 docref: "Load tests"
 }
 suite - verifies -> fast
```

```text
                     ┌────────────────────┐                     
                     │        suite       │                     
                     │     <>    │                     
                     ├────────────────────┤                     
                     │ type: test         │                     
                     │ docref: Load tests │                     
                     └────────────────────┘                     
                               ╎                                
                      verifies ╎                                
                               ╎                                
                 ┌─────────────▼──────────────┐                 
                 │            fast            │                 
                 │ <> │                 
                 ├────────────────────────────┤                 
                 │ id: R2                     │                 
                 │ text: Checkout under 2s    │                 
                 │ risk: medium               │                 
                 │ verifymethod: analysis     │                 
                 └────────────────────────────┘                 
```



## Syntax and limits

- Requirement declarations include `requirement`, `functionalRequirement`, `interfaceRequirement`, `performanceRequirement`, `physicalRequirement`, and `designConstraint`.
- Fields include `id`, `text`, `risk`, and `verifymethod`. Elements include `type` and `docref`.
- Relations are `contains`, `copies`, `derives`, `satisfies`, `verifies`, `refines`, and `traces`.
- Markdown is reduced to plain text; styles and external assets are inert and reported.
- Long field text wraps inside compartments. Give detailed requirements more rows and inspect [render notes](/diagrams/options/#read-the-fidelity-report) before sharing.


---

# Mermaid sequence diagrams as text

Import `renderGlyphSequence` from `@glyphcss/diagrams/sequence`, then pass source and [shared render options](/diagrams/options/). The root graph renderer is not the sequence entry point.

## Request and response



```mermaid
sequenceDiagram
 participant Buyer
 participant API
 participant Stock
 participant Pay
 participant Mail
 Buyer->>API: Place order
 API->>Stock: Reserve items
 Stock-->>API: Items held
 API->>Pay: Charge card
 Pay-->>API: Approved
 API->>Mail: Send receipt
 Mail-->>API: Queued
 API-->>Buyer: Order confirmed
```

```text
   Buyer                       API                     Stock           Pay          Mail    
     │                          │                        │              │             │     
     │ Place order              │                        │              │             │     
     ├─────────────────────────▶│                        │              │             │     
     │                          │                        │              │             │     
     │                          │ Reserve items          │              │             │     
     │                          ├───────────────────────▶│              │             │     
     │                          │                        │              │             │     
     │                          │ Items held             │              │             │     
     │                          │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┤              │             │     
     │                          │                        │              │             │     
     │                          │ Charge card            │              │             │     
     │                          ├────────────────────────┼─────────────▶│             │     
     │                          │                        │              │             │     
     │                          │ Approved               │              │             │     
     │                          │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┼╌ ╌ ╌ ╌ ╌ ╌ ╌ ┤             │     
     │                          │                        │              │             │     
     │                          │ Send receipt           │              │             │     
     │                          ├────────────────────────┼──────────────┼────────────▶│     
     │                          │                        │              │             │     
     │                          │ Queued                 │              │             │     
     │                          │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┼╌ ╌ ╌ ╌ ╌ ╌ ╌ ┼ ╌ ╌ ╌ ╌ ╌ ╌ ┤     
     │                          │                        │              │             │     
     │ Order confirmed          │                        │              │             │     
     │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┤                        │              │             │     
     │                          │                        │              │             │     
```



## Alternative responses and notes



```mermaid
sequenceDiagram
 actor Buyer
 participant API
 Note right of API: Keep receipt
 Buyer->>API: Place order
 alt In stock
 API-->>Buyer: Confirmed
 else Sold out
 API-->>Buyer: Try later
 end
```

```text
      o                                                         
    Buyer                         API                           
      │                            │                            
      │                            │ ┌────────────────────┐     
      │                            │ │ note  Keep receipt │     
      │                            │ └────────────────────┘     
      │ Place order                │                            
      ├───────────────────────────▶│                            
      │                            │                            
    ┌─ alt In stock ───────────────┼─┐                          
    │ │ Confirmed                  │ │                          
    │ │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┤ │                          
    │ │                            │ │                          
    ├╌ else Sold out ╌╌╌╌╌╌╌╌╌╌╌╌╌╌│╌┤                          
    │ │ Try later                  │ │                          
    │ │◀╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌ ╌┤ │                          
    └─┼────────────────────────────┼─┘                          
      │                            │                            
```



## Syntax and limits

- Participant aliases use `participant API as Order service`; `actor` draws a stick figure.
- Message endpoints control direction; solid and dashed message styles remain distinct. Self-messages draw a loop.
- `loop`, `alt`/`else`, `opt`, `par`/`and`, `critical`/`option`, and `break` create frames with matched `end` statements.
- Notes can sit over participants or left/right of one participant. `autonumber` supports start and step.
- Activations, `rect`, and participant `box` styling are inert. Create/destroy syntax becomes full lifelines; half and central arrows become solid or dashed directed messages with notes in the report.
- Pagination follows time and repeats participant headers and continuing frames. `overflow: "expand"` grows the height; too many participants can still produce `sequence-layout-overflow`.
- See [sequence JSON](/diagrams/json/#sequence-json) for direct control over frames and note positions.


---

# ASCII diagram node shape catalogue

Use a JSON node's `shape` field, or Mermaid's `N@{shape: doc, label: "Read item"}`.
These examples use JSON so the exact public shape name appears beside its output.
Shapes carry meaning through outlines, independent of color.

## Basic and semantic shapes



**rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "rect",
      shape: "rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           ┌──────┐           
           │ rect │           
           └──────┘           
```




**rounded**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "rounded",
      shape: "rounded"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ╭─────────╮          
         │ rounded │          
         ╰─────────╯          
```




**diamond**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "diamond",
      shape: "diamond"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ╭───────────╮         
        │ ◆ diamond │         
        ╰───────────╯         
```




**circle**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "circle",
      shape: "circle"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ◜◠◠◠◠◠◠◠◠◝          
          │ circle │          
          ◟◡◡◡◡◡◡◡◡◞          
```




**subroutine**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "subroutine",
      shape: "subroutine"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
       ┌──────────────┐       
       ││ subroutine ││       
       └──────────────┘       
```




**asymmetric**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "asymmetric",
      shape: "asymmetric"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌────────────╲        
        │ asymmetric │        
        └────────────╱        
```




**stadium**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "stadium",
      shape: "stadium"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ◜─────────◝          
         │ stadium │          
         ◟─────────◞          
```




**cylinder**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "cylinder",
      shape: "cylinder"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ◜──────────◝         
         │ cylinder │         
         ◟──────────◞         
```




**point**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "*",
      shape: "point"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
              *               
```




**compartment**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "compartment",
      shape: "compartment",
      compartments: [
        ["+id: string"],
        ["+save()"]
      ]
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
       ┌─────────────┐        
       │ compartment │        
       ├─────────────┤        
       │ +id: string │        
       ├─────────────┤        
       │ +save()     │        
       └─────────────┘        
```




**cloud**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "cloud",
      shape: "cloud"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ╭◠◠◠◠◠◠◠╮           
          │ cloud │           
          ╰◡◡◡◡◡◡◡╯           
```




**bang**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "bang",
      shape: "bang"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           *╱╲╱╲╱╲*           
           │ bang │           
           *╲╱╲╱╲╱*           
```




**hexagon**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "hexagon",
      shape: "hexagon"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ╱─────────╲          
         ❬ hexagon ❭          
         ╲─────────╱          
```



## Mermaid catalogue shapes

Catalogue names below work in JSON and in Mermaid shape metadata.



**doc**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "doc",
      shape: "doc"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ┌───────┐           
          │  doc  │           
          ╰◡◡◡◡◡◡◡╯           
```




**docs**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "docs",
      shape: "docs"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           ┌──────┐           
          ┌──────┐│           
          │ docs │┘           
          ╰◡◡◡◡◡◡╯            
```




**st-rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "st-rect",
      shape: "st-rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ┌─────────┐         
         ┌─────────┐│         
         │ st-rect │┘         
         └─────────┘          
```




**tag-doc**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "tag-doc",
      shape: "tag-doc"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌───────────┐         
        │ tag-doc ◇ │         
        ╰◡◡◡◡◡◡◡◡◡◡◡╯         
```




**notch-rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "notch-rect",
      shape: "notch-rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ╱───────────┐        
        ╱ notch-rect │        
        └────────────┘        
```




**div-rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "div-rect",
      shape: "div-rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ┌──────────┐         
         ├ div-rect ┤         
         └──────────┘         
```




**lin-rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "lin-rect",
      shape: "lin-rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌─┬──────────┐        
        │ │ lin-rect │        
        └─┴──────────┘        
```




**tag-rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "tag-rect",
      shape: "tag-rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌────────────┐        
        │ tag-rect ◇ │        
        └────────────┘        
```




**lean-r**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "lean-r",
      shape: "lean-r"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           ╱────────╱         
          ╱ lean-r ╱          
         ╱────────╱           
```




**lean-l**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "lean-l",
      shape: "lean-l"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ╲────────╲           
          ╲ lean-l ╲          
           ╲────────╲         
```




**trap-t**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "trap-t",
      shape: "trap-t"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ────────────         
         ╲  trap-t  ╱         
          ╲────────╱          
```




**trap-b**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "trap-b",
      shape: "trap-b"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ╱────────╲          
         ╱  trap-b  ╲         
         ────────────         
```




**notch-pent**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "notch-pent",
      shape: "notch-pent"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ╱────────────╲        
       │  notch-pent  │       
       └──────────────┘       
```




**delay**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "delay",
      shape: "delay"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ┌───────╮           
          │ delay │           
          └───────╯           
```




**bow-rect**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "bow-rect",
      shape: "bow-rect"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ╲──────────╱         
          )bow-rect(          
         ╱──────────╲         
```




**curv-trap**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "curv-trap",
      shape: "curv-trap"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ╱──────────╮         
        ( curv-trap │         
         ╲──────────╯         
```




**tri**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "tri",
      shape: "tri"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
              ╱╲              
             ╱  ╲             
            ╱    ╲            
           ╱ tri  ╲           
           ────────           
```




**flip-tri**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "flip-tri",
      shape: "flip-tri"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ────────────         
         ╲          ╱         
          ╲        ╱          
           flip-tri           
            ╲    ╱            
             ╲  ╱             
              ╲╱              
```




**hourglass**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "hourglass",
      shape: "hourglass"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ╲───────────╱         
         )hourglass(          
        ╱───────────╲         
```




**bolt**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "bolt",
      shape: "bolt"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ┌─────────┐          
         │ ╲╱ bolt │          
         └─────────┘          
```




**flag**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "flag",
      shape: "flag"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           ╭◠◠◠◠◠◠╮           
           │ flag │           
           ╰◡◡◡◡◡◡╯           
```




**dbl-circ**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "dbl-circ",
      shape: "dbl-circ"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ╔════════════╗        
        ║( dbl-circ )║        
        ╚════════════╝        
```




**cross-circ**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "cross-circ",
      shape: "cross-circ"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        (╳) cross-circ        
```




**fr-circ**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "fr-circ",
      shape: "fr-circ"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌───┐                 
        │ ○ │ fr-circ         
        └───┘                 
```




**f-circ**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "f-circ",
      shape: "f-circ"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           ● f-circ           
```




**sm-circ**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "sm-circ",
      shape: "sm-circ"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ○ sm-circ           
```




**h-cyl**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "h-cyl",
      shape: "h-cyl"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ╭───────┬╮          
          │ h-cyl ││          
          ╰───────┴╯          
```




**lin-cyl**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "lin-cyl",
      shape: "lin-cyl"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌───────────┐         
        ├───────────┤         
        │ lin-cyl   │         
        ├───────────┤         
        └───────────┘         
```




**datastore**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "datastore",
      shape: "datastore"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ─────────────         
          datastore           
        ─────────────         
```




**bucket**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "bucket",
      shape: "bucket"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
         ◜◠◠◠◠◠◠◠◠◠◠◝         
         ╲  bucket  ╱         
          ╰────────╯          
```




**text**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "text",
      shape: "text"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
             text             
```




**fork**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "",
      shape: "fork"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ━━━━━━━━━           
             │                
```




**brace**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "brace",
      shape: "brace"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
           ╭                  
           ┤ brace            
           ╰                  
```




**brace-r**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "brace-r",
      shape: "brace-r"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
                   ╮          
           brace-r ├          
                   ╯          
```




**braces**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "braces",
      shape: "braces"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
          ╭        ╮          
          ┤ braces ├          
          ╰        ╯          
```




**browser**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "browser",
      shape: "browser"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌───────────┐         
        │ ○ browser │         
        └───────────┘         
```




**console**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "console",
      shape: "console"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
        ┌───────────┐         
        ├───────────┤         
        │ $ console │         
        └───────────┘         
```




**person**

```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "person",
      shape: "person"
    }
  ],
  edges: []
}, {
  target: "web",
  color: "none",
  width: 30,
  height: 9,
  overflow: "expand"
});
console.log(text);
```

```text
              ○               
          ╭────────╮          
          │ person │          
          ╰────────╯          
```



## ASCII and font compatibility

`ascii` uses simpler outlines. Box, blocks, and braille hexagons use ❬ and ❭ sides;
ASCII uses angle brackets. Clouds and bangs also have ASCII outlines.



```ts
import { renderGlyphDiagram } from "@glyphcss/diagrams";

const { text } = await renderGlyphDiagram({
  direction: "LR",
  nodes: [
    {
      id: "n",
      label: "Decision",
      shape: "hexagon"
    }
  ],
  edges: []
}, {
  target: "chat",
  charset: "ascii",
  width: 30,
  height: 9
});
console.log(text);
```

```text
         /----------\         
         < Decision >         
         \----------/         
```



Use Glyph Mono for special glyphs in web output; chat uses the receiving application's font.
See [fonts and fallbacks](/diagrams/troubleshooting/#fonts-and-alignment).

## Adaptations and connection limits

Catalogue shapes reserve their full footprint and attach edges away from seams.
`point` draws the first character of its required nonempty label and cannot have a direct JSON self-edge. `fork` draws an
unlabelled bar/stub; a supplied label goes below it. `compartment` accepts member rows.

Mermaid names `lin-doc`, `win-pane`, `sl-rect`, and `folder` have logged adaptations;
they are not additional JSON shape values. External icons and images are inert.
Inspect render notes when [fitting](/diagrams/options/) changes an outline or label.


---

# Mermaid state diagrams as text

Pass `stateDiagram` or `stateDiagram-v2` source to `renderGlyphDiagram`.

## Order lifecycle



```mermaid
stateDiagram-v2
 direction LR
 [*] --> Draft
 Draft --> Pending: submit
 Pending --> Paid: pay
 Pending --> Cancelled: cancel
 Paid --> Shipped: dispatch
 Paid --> Refunded: refund
 Shipped --> [*]
```

```text
                                                            dispatch  ╭─────────╮           
                                                           ┌──────────▶ Shipped │──▶◉       
                                          pay    ╭──────╮  │          ╰─────────╯           
                                      ┌──────────▶ Paid ├──┤                                
         ╭───────╮ submit ╭─────────╮ │          ╰──────╯  │ refund  ╭──────────╮           
      ●──▶ Draft │────────▶ Pending ├─┤                    └─────────▶ Refunded │           
         ╰───────╯        ╰─────────╯ │       ╭───────────╮          ╰──────────╯           
                                      └───────▶ Cancelled │                                 
                                       cancel ╰───────────╯                                 
```



## Composite state



```mermaid
stateDiagram-v2
 direction LR
 [*] --> Checkout
 state Checkout {
 [*] --> Review
 Review --> Payment
 Payment --> [*]
 }
 Checkout --> Complete
 Complete --> [*]
```

```text
       ················Checkout·················                        
       ·                                       ·                        
       ·       ╭────────╮    ╭─────────╮       ·    ╭──────────╮        
  ●──────▶●────▶ Review │────▶ Payment │────▶◉──────▶ Complete │────▶◉  
       ·       ╰────────╯    ╰─────────╯       ·    ╰──────────╯        
       ·                                       ·                        
       ·········································                        
```



## Syntax and limits

- `[*]` becomes a point marker scoped to its region; transitions use `-->` with an optional `: caption`.
- `state Choice <>` draws a diamond. Fork/join declarations use rounded nodes and report the adaptation.
- `state Name { ... }` encloses a composite. `--` separates concurrent regions; empty regions are omitted and reported.
- Notes become text rows. Invalid notes and concurrency separators have named errors in [troubleshooting](/diagrams/troubleshooting/).
- Composite transitions attach to the group's start/first or end/last child. Self-transitions on composites are adapted and reported.
- Reused state identities across scopes may need copies; inspect `state-shared`. Styling and nested directives do not execute.


---

# Fix Mermaid text diagram errors and layout problems

Start with the error's `code` or `result.report.ledger`. Parse and validation failures
are different from successful renders that needed layout adaptations.



```mermaid
flowchart LR
 Error[Read error code] --> Parse{Parse failed?}
 Parse -->|yes| Syntax[Check syntax]
 Parse -->|no| Ledger[Read render notes]
 Ledger --> Size[Increase budget]
 Size --> Inspect[Inspect all pages]
 Syntax --> Retry[Render again]
```

```text
                              yes ┌────────┐   ┌────────┐                   
                               ┌──▶  Check │───▶ Render │                   
                               │  │ syntax │   │  again │                   
   ┌────────────┐  ╭─────────╮ │  └────────┘   └────────┘                   
   │ Read error │──▶ ◆ Parse ├─┤                                            
   │    code    │  │ failed? │ │  ┌────────┐                                
   └────────────┘  ╰─────────╯ │  │  Read  │  ┌──────────┐  ┌───────────┐   
                               └──▶ render │──▶ Increase │──▶  Inspect  │   
                              no  │  notes │  │  budget  │  │ all pages │   
                                  └────────┘  └──────────┘  └───────────┘   
```



## Parser and JSON errors

| Error code | What to check |
| --- | --- |
| `GLYPH_MERMAID_SYNTAX` | Flowchart statements, delimiters, labels, and edge syntax |
| `GLYPH_MERMAID_UNSUPPORTED_
` | The header is unsupported by this reader; choose the correct [entry point](/diagrams/overview/#choose-the-entry-point) | | `GLYPH_SEQUENCE_MERMAID_SYNTAX` | Sequence participant declarations, messages, and matched frame endings | | `GLYPH_MERMAID_CLASS_SYNTAX` | Class declarations, member braces, and relationships | | `GLYPH_MERMAID_ER_SYNTAX` | Entity attributes and cardinality syntax | | `GLYPH_MERMAID_MINDMAP_SYNTAX` | Mindmap indentation and node delimiters | | `GLYPH_MERMAID_GIT_SYNTAX` | Branch names, checkout, merge, and commit statements | | `GLYPH_MERMAID_BLOCK_SYNTAX` | Block grids, spans, and closing `end` statements | | `GLYPH_MERMAID_ARCHITECTURE_SYNTAX` | Service/group declarations and side-prefixed links | | `GLYPH_MERMAID_REQUIREMENT_SYNTAX` | Requirement braces, fields, and relations | | `GLYPH_MERMAID_C4_SYNTAX` | C4 declaration arguments, boundaries, and relationships | | `GLYPH_MERMAID_STATE_NOTE` | State note syntax and target state | | `GLYPH_MERMAID_STATE_CONCURRENCY` | State region separators and concurrent structure | | `GLYPH_DIAGRAM_BAD_JSON` | Malformed graph JSON text | | `GLYPH_SEQUENCE_BAD_JSON` | Malformed sequence JSON text | | `GLYPH_LANE_BAD_JSON` | Malformed lane JSON text | | `GLYPH_LANE_GIT_SYNTAX` | Expected `id|parents|decoration|subject`, one commit per line | | `GLYPH_DIAGRAM_ELK_NOT_INSTALLED` | The ELK adapter is reserved and unavailable; use `engine: "dagre"` | The CLI also dispatches Mermaid charts; chart parse errors retain their own tagged codes. Configuration, styles, clicks, and external assets are inert. `mermaid-degraded` entries explain a supported input whose appearance needed adaptation. ## Validation failures - `bad-size`: supply positive integer columns and rows. - `bad-options` or `bad-color`: check option values and color strings against the API. - `duplicate-node-id`, `duplicate-edge-id`, or `unknown-node`: use unique IDs and valid endpoints. - `unknown-group` or `group-membership`: check group references, membership, and parent containment. - `point-loop`: a JSON point node cannot connect to itself. - `unknown-participant`, `bad-frame-range`, or `bad-note-range`: check sequence IDs and zero-based message indices. - `bad-parent-order`, `unknown-parent`, or `self-parent`: list lane nodes newest-first with older parents later; use `truncated: true` only for a real history window. The object renderers throw errors with a `code` property. JSON-string wrappers instead resolve to serialized `{ error, code, hint }` on failure; parse their result before checking it. The CLI exits 1 for failures and prints diagnostics to stderr. ## When a diagram does not fit 1. Read the report and inspect every page. A successful call can still have omitted or abbreviated content. 2. Increase `width` or `height` in character cells. Long names need enough room for whole words. 3. For graph families, try `autoDirection: true` or an explicit perpendicular `direction`. 4. Use `overflow: "expand"` for a scrollable web host, or `"paginate"` for fixed chat/terminal panels. 5. Choose `detail: "faithful"` when preserving identities matters more than compactness, or split the source into smaller diagrams. | Report code | Meaning and response | | --- | --- | | `layout-expanded` | The graph grew beyond the requested budget; use its actual dimensions | | `layout-overflow` | A graph did not fit during adaptation; inspect the final pages | | `unroutable` | A final edge could not be drawn; increase space or simplify connections | | `word-cut`, `label-abbreviated`, `label-folded` | Label text was split, shortened, or converted to the charset | | `render-work-limited` | The bounded fitting search stopped; reduce complexity or provide more room | | `sequence-layout-overflow` | Participants/messages exceeded the available sequence space | | `lane-cap-collapsed` | Lanes were collapsed to fit; provide more columns | | `lane-history-continues` | Older lane history lies outside the supplied window | | `mermaid-option-ignored` | A CLI flag does not apply to the dispatched renderer | ## Fonts and alignment Web output needs a true monospace font and `line-height: 1`. Use the bundled Glyph Mono font for special outlines and junctions; declaring its name in CSS requires loading the font. The website loads it centrally. Your application must serve a font file or use a fallback. ```css .diagram pre { font-family: "Glyph Mono", ui-monospace, monospace; line-height: 1; white-space: pre; overflow: auto; } ``` Chat and terminal output use the receiving application's fonts. Some chat fonts misalign braille, junctions, or the ❬/❭ hexagon sides. Put the text in a fenced code block and use `target: "chat"`; if needed, choose `charset: "ascii"`. Keep labels short when fallback fonts change character widths. Do not scale the font to hide a layout overflow. ## Missing colors or unexpected HTML Use `color: "none"` for plain text. ANSI encodings belong in a compatible terminal; CSS encoding belongs in HTML. `html` contains escaped span markup for the inside of a `
`; provide that outer element.
Piping CLI output disables color unless overridden; choosing `--out` does not select HTML.


---

# Fluid

Move the pointer over it to stir the fluid; tune the field and the reader in the [fluid workbench](/fluid).

`@glyphcss/fluid` is a living braille fluid as a glyphcss surface. A shallow-water simulation runs on a cell grid; DOM text, images and meshes become *targets* the ink flows toward and condenses into, then melts back out of. Each frame is one `textContent` write to one `
`, drawn as 8-dot braille with per-cell colour through glyphcss's colour-font atlas. The simulation runs in a Web Worker.

## A first fluid

```ts
import { createGlyphFluid, GlyphFluidTargets } from "@glyphcss/fluid";

const host = document.querySelector("#fluid")!;
const fluid = createGlyphFluid(host);
await fluid.ready;

const h1 = document.querySelector("h1")!;
h1.style.color = "transparent"; // the fluid draws it; the element keeps layout and accessibility
const title = fluid.addTarget(GlyphFluidTargets.text(h1, { color: "#3ccf96" }));

title.melt();      // flows out; title.condense() flows back in
// On unmount: fluid.destroy();
```

Install with `npm install @glyphcss/fluid glyphcss`. There are no React/Vue bindings: create the fluid in your framework's mount hook and `destroy()` it on unmount.

## Layers

Each layer works alone; only the last touches the DOM.

```
GlyphFluidSim  →  computeGlyphFluidCells  →  GlyphFluidEncoder  →  createGlyphFluid
(the fluid sim,   (braille mask + colour     (glyphcss atlas text   (targets, worker,
 bit-identical)    per cell)                  + pooled palette)      one 
)
```

- `GlyphFluidSim` steps bit-identically to a reference implementation of the step.
- `computeGlyphFluidCells` is the renderer's per-cell decision as data: which of the 8 dots light and in what colour.
- `GlyphFluidEncoder` turns cells into atlas text against a pooled palette, so the palette CSS changes only when it repools.
- `createGlyphFluid` composes targets and zones, runs the pipeline in a worker and writes the frame.
- [`@glyphcss/fluid/reader`](/fluid/reader) adds a speed reader on top.

## Handle reference

| Task | Methods |
|---|---|
| Content | `addTarget(spec)` → `{ enabled, condense, melt, remove }`; `addZone({ el, kind })` → `{ remove }` |
| Motion | `impulse(clientX, clientY, { strength, radius })`, `push(clientX, clientY, dx, dy)` |
| Clock | `step(dt)` with `clock: "manual"`; `relayout()` after layout changes the observers miss |
| Lifecycle | `ready`, `stats()`, `destroy()` |

`stats()` reports `fps`, `pipeline` (`"worker"` or `"main"`), `encoding`, `cols`, `rows`, `frames`, `stalls`, `stepMs` and `lit` cells.

## Where next

- [Targets & zones](/fluid/targets): text, image and mesh targets and the zones that shape the field.
- [Runtime & performance](/fluid/runtime): worker, frame rate, reduced motion and measured costs.
- [Reader](/fluid/reader): one word at a time out of the fluid.
- [Troubleshooting](/fluid/troubleshooting).


---

# Reader

`@glyphcss/fluid/reader` is a speed reader in two layers:

- **Rules**: tokenizer, optimal recognition point (ORP), word delay and a word clock. Pure functions with no fluid or DOM dependency.
- **Rendering**: `createGlyphFluidReader` draws the clock's words with a fluid of its own.

## Read a sentence

```ts
import { createGlyphFluidReader } from "@glyphcss/fluid/reader";

const reader = createGlyphFluidReader(host, {
  text: "Words appear one at a time, out of the fluid.",
  wpm: 250,
  shape: "circle",   // a circular surface
  loop: 2600,        // ms of rest after the last word, then read again
});

reader.clock.setWpm(400);            // takes effect from the next word
reader.clock.pause();
reader.clock.play();
reader.clock.seek(3);                // show word 3 now
reader.clock.setText("Something new to say.");
reader.destroy();
```

## Looks

Both looks pivot the ORP letter on the centre column in the accent orange. Every word change sends a soft ring out from the centre; after the last word the letters melt back into the field.

- **`plain`** (default): the fluid pools into a band under the word, and real letters condense out of it. A letter appears once enough ink has arrived under it, as a scramble of ramp glyphs (`.:-=+*#%@`), and decodes into the real letter as the ink fills in; it rides the wave height and brightens with the ink. The fluid stays blank under shown letters. Letters are bold monospace (`font`), sized once per sentence so they don't jump between words.
- **`glyph`**: the fluid itself takes the letter shapes, in a heavy face stretched ×1.9 in height (cells are taller than wide). Each word is sized to fill the screen on its own, so short words are large.

The plain letters are real DOM text: one positioned `` per letter in an overlay above the fluid's `
`, each updated with at most one inline-style assignment per frame (position, colour, opacity) and its text written only when the shown character changes. Whether a letter shows, and the ink and wave under it, come from the same simulation step as the fluid frame, on the worker or the main thread.

During the lead-in the first word is already the target, so its ink gathers (and its plain letters scramble in) before the clock shows it.

Reader options are the fluid's options (except `glue`) plus:

| Option | Default | |
|---|---|---|
| `text` | `""` | the sentence; `clock.setText` replaces it |
| `wpm` | `250` | words per minute |
| `leadIn` | `550` | ms before the first word, while the ink gathers |
| `loop` | `false` | ms of rest after the last word before reading again |
| `autoplay` | `true` | start once the fluid is ready |
| `look` | `"plain"` | `"plain"`: real letters condense out of a pooled band; `"glyph"`: the fluid takes the letter shapes |
| `font` | `"ui-monospace, Menlo, Consolas, monospace"` | plain letters' font-family, drawn bold |
| `ariaLive` | `"off"` | the hidden word element's `aria-live`; `"polite"` announces every word |
| `color` | `"#f2f5ff"` | letter colour; the ORP accent is the fluid's accent orange |
| `ripple` | `0.63` | strength of the ring each later word sends out; 0 for none (the first word condensing and the last melting still stir the fluid, like any target) |
| `scheduler` | timers | the clock's `now` / `setTimeout` / `clearTimeout` |
| `grid` | 52 columns | the default grid width |

The fluid's `
` and the letter overlay are `aria-hidden`; the showing word is kept as text in a visually hidden element, with `aria-live="off"` by default (a word every quarter second would flood a screen reader), so it is readable on demand. For a sentence read aloud, keep the whole text in the page. Under reduced motion each word is drawn as one settled still, and plain letters show settled: no scramble, no wave.

## The rules

```ts
import { tokenizeGlyphReaderText, glyphReaderOrp, glyphReaderWordDelay } from "@glyphcss/fluid/reader";

const tokens = tokenizeGlyphReaderText("Stop.\n\nGo on, slowly.");
// [{ word: "Stop.", orp: 1, core: 4, para: true }, { word: "Go", ... }, ...]
glyphReaderWordDelay(tokens[0], 250);   // 600 ms
```

- **ORP**: strip leading and trailing non-alphanumerics to get the core; the focal letter is the core start plus a bucket of the core length: ≤ 1 → 0, 2–5 → 1, 6–9 → 2, 10–13 → 3, ≥ 14 → 4.
- **Delay**: `max(40, round(60000 / wpm × long × punctuation))` ms, where `long = min(2, 1 + 0.05 × (core − 6))` for cores longer than 6, and punctuation is 2.5 at a paragraph end, 2.0 after `.` `!` `?`, 1.5 after `,` `;` `:` (closing quotes and brackets are skipped).
- **Tokens**: words are runs of non-whitespace; a blank line marks the word before it as a paragraph end. Indices count UTF-16 code units, exactly as JavaScript string indices do.

The rules are held to a reference implementation on a corpus of punctuation, Unicode, emoji and paragraph cases, with planted-bug tests that prove the comparison catches a one-character slip.

## The word clock

```ts
import { createGlyphReaderClock } from "@glyphcss/fluid/reader";

const clock = createGlyphReaderClock({ text, wpm: 300, loop: 2000 });
const off = clock.subscribe((e) => {
  if (e.type === "text") prepare(e.tokens);          // a reading (re)starts: lead-in
  if (e.type === "word") show(e.token, e.index, e.ms);
  if (e.type === "end") clear();
});
```

| Member | |
|---|---|
| `tokens`, `index`, `playing`, `wpm` | state; `index` is −1 during the lead-in, `tokens.length` once ended |
| `play()`, `pause()` | pause keeps the remaining time of the current word |
| `seek(i)` | show word `i` now (clamped); while playing it stays for its full delay |
| `setWpm(wpm)` | from the next word |
| `setText(text)` | new tokens, back to the lead-in; playing state is kept |
| `subscribe(fn)` | `text`, `word` and `end` events; returns an unsubscribe |
| `destroy()` | cancels the pending step |

The clock knows nothing about the fluid: drive a terminal, a canvas or another renderer with it. If a second consumer appears, the rules layer moves to its own package unchanged.


---

# Runtime & performance

## One frame

```
DOM targets ──measure()──► target frame (packed Float32Array)
                                 │  + queued ops (impulse, push, kick, scroll)
                                 ▼
                 worker: ops → adopt targets → step → cells → encode
                                 │
                                 ▼
             main: one 
.textContent write (+ palette