ai-figure.

Documentation

Complete reference for ai-figure — installation, API, markdown syntax, diagram types, and framework integration.

Getting Started

Install

npm install ai-figure

Import

ai-figure ships a single entry-point export. Works in both ES Modules and CommonJS environments.

import { fig } from 'ai-figure';          // ESM
const { fig } = require('ai-figure');     // CJS

Node.js usage

Call fig() and write the SVG string to a file or return it from a server route.

import { fig } from 'ai-figure';
import { writeFileSync } from 'fs';

const svg = fig(`
  figure flow
  direction: LR
  palette: antv
  title: CI Pipeline
  A[Commit] --> B[Test] --> C[Build] --> D[Deploy]
`);

writeFileSync('pipeline.svg', svg);

Browser usage

fig() has zero DOM dependency — it only builds an SVG string. Inject it wherever you need it.

import { fig } from 'ai-figure';

const svg = fig(`
  figure flow
  direction: LR
  A[Start] --> B[End]
`);

document.getElementById('chart').innerHTML = svg;

Streaming-safe

When given a markdown string, fig() never throws. Partial or empty input returns a valid 1×1 empty SVG, so you can pass AI streaming output directly — the diagram fills in progressively as tokens arrive.

// Safe to call with partial AI output
const partialMarkdown = "figure flow\ndirection: LR\nA[Start";
const safeSvg = fig(partialMarkdown);  // returns empty SVG — no throw

API

fig(input) accepts either a markdown string or a typed JSON config object, and always returns a self-contained SVG string.

import { fig } from 'ai-figure';

// ── markdown string (compact, AI-friendly) ──────────────────────
const svg1 = fig(`
  figure flow
  direction: LR
  palette: antv
  A[Start] --> B[End]
`);

// ── JSON config (typed, programmatic) ───────────────────────────
const svg2 = fig({
  figure: 'flow',
  direction: 'LR',
  palette: 'antv',
  nodes: [
    { id: 'a', label: 'Start', type: 'terminal' },
    { id: 'b', label: 'End',   type: 'terminal' },
  ],
  edges: [{ from: 'a', to: 'b' }],
});

Markdown Syntax

The first non-empty line must be figure <type>. Config lines follow, then diagram-specific data. Lines starting with %% are comments.

Line typeSyntaxExample
Headerfigure <type>figure flow
Configkey: valuedirection: LR · palette: antv · title: My Chart
Comment%% text%% this line is ignored
Datadiagram-specificA[Start] --> B[End]

Common config keys

KeyType / ValuesDefault
titlestring
subtitlestring
directionTB · LRTB
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault

Node notation (flow / tree / arch / swimlane)

NotationShape
id[label]process (rectangle)
id{label}decision (diamond)
id((label))terminal (rounded pill)
id[/label/]io (parallelogram)
idprocess, id used as label

Palettes

defaultantvdrawiofigmavegamono-bluemono-greenmono-purplemono-orange

A custom 4-element hex array is also accepted: palette: ['#e64980','#ae3ec9','#7048e8','#1098ad']

Diagram Types

flow — Flowchart

General-purpose directed graph. Supports process, decision, terminal, and IO node shapes; edge labels; and logical groups with dashed borders.

Auth Flow credential validation steps Auth yes no Start Enter Credentials Valid? Dashboard Show Error

Edge syntax: A --> B (unlabeled) or A --> B: label. Groups: group Name: id1, id2.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
directionTB · LRTB
nodesFlowNode[]required
edgesFlowEdge[]required
groupsFlowGroup[][]

Markdown syntax

figure flow
direction: TB
palette: antv
title: Auth Flow
subtitle: credential validation steps
start((Start)) --> login[Enter Credentials]
login --> validate{Valid?}
validate --> dashboard((Dashboard)): yes
validate --> error[Show Error]: no
error --> login
group Auth: login, validate

tree — Tree / Hierarchy

Renders a rooted hierarchy using Dagre layout. Define edges with --> and the tree is computed automatically — no manual positioning needed.

Org Chart engineering & operations CEO CTO COO Frontend Lead Backend Lead Operations

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
directionTB · LRTB

Markdown syntax

figure tree
direction: TB
palette: default
title: Org Chart
subtitle: engineering & operations
ceo[CEO]
ceo --> cto[CTO]
ceo --> coo[COO]
cto --> fe[Frontend Lead]
cto --> be[Backend Lead]
coo --> ops[Operations]

mindmap — Mindmap

Root-centered concept map. First-level branches split left/right automatically; deeper levels inherit branch direction. Supports optional side hints in JSON.

Product Strategy 2026 planning map Product Strategy Market Technology SMB Enterprise AI Features

Syntax is intentionally consistent with tree/flow: node lines plus A --> B links. In JSON mode, root children can provide side: 'left' | 'right' to pin branch direction.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
nodesMindmapNode[]required

Markdown syntax

figure mindmap
title: Product Strategy
subtitle: 2026 planning map
root[Product Strategy]
root --> market[Market]
root --> tech[Technology]
market --> smb[SMB]
market --> ent[Enterprise]
tech --> ai[AI Features]

arch — Architecture Diagram

Color-coded layer cards for tech-stack landscapes. No edges needed — just define layers and the nodes inside each layer.

Web Stack three-tier architecture Frontend React App CDN Assets Backend REST API Auth Service Data PostgreSQL Redis

Layer syntax: layer Name followed by indented node lines id[Label].

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
directionTB (layers stacked) · LR (side-by-side)TB

Markdown syntax

figure arch
direction: TB
palette: figma
title: Web Stack
subtitle: three-tier architecture
layer Frontend
  ui[React App]
  cdn[CDN Assets]
layer Backend
  api[REST API]
  auth[Auth Service]
layer Data
  db[PostgreSQL]
  cache[Redis]

sequence — Sequence Diagram

UML sequence diagram with vertical lifelines and horizontal message arrows. Supports solid (→) and dashed return (-->) arrow styles.

Login Flow token-based authentication Browser API DB POST /login SELECT user user row 200 OK + token

Declare actors with actors: A, B, C. Solid message: A -> B: label. Dashed return: B --> A: label.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
actorsstring (comma-separated)required

Markdown syntax

figure sequence
title: Login Flow
subtitle: token-based authentication
actors: Browser, API, DB
Browser -> API: POST /login
API -> DB: SELECT user
DB --> API: user row
API --> Browser: 200 OK + token

quadrant — Quadrant Chart

2D scatter plot divided into four quadrants. Points are placed with normalized x/y values (0–1) and auto-colored by quadrant.

Feature Priority effort vs value Low High Effort Low High Value Quick Wins Strategic Low Prio Long Shots Search Dashboard Dark Mode Export

Points: Label: x, y where x and y are between 0 and 1.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
x-axisLabel: Low .. Highrequired
y-axisLabel: Low .. Highrequired
quadrant-1..4corner labels (TL, TR, BL, BR)required

Markdown syntax

figure quadrant
title: Feature Priority
subtitle: effort vs value
x-axis Effort: Low .. High
y-axis Value: Low .. High
quadrant-1: Quick Wins
quadrant-2: Strategic
quadrant-3: Low Prio
quadrant-4: Long Shots
Search: 0.15, 0.9
Dashboard: 0.7, 0.85
Dark Mode: 0.25, 0.55
Export: 0.8, 0.35

gantt — Gantt Chart

Project timeline with task bars, optional section grouping, and milestone markers. Time axis ticks auto-adjust to the date range (weekly/monthly/quarterly).

Q1 Roadmap Jan – Mar 2025 Feb 2025 Mar 2025 Design Wireframes Wireframes Mockups Mockups Dev Frontend Frontend Backend Backend Launch

Task format: Label: id, yyyy-mm-dd, yyyy-mm-dd. Milestone: milestone: Label, yyyy-mm-dd.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
sectiongroup header
milestoneLabel, yyyy-mm-dd

Markdown syntax

figure gantt
title: Q1 Roadmap
subtitle: Jan – Mar 2025
section Design
  Wireframes: t1, 2025-01-06, 2025-01-24
  Mockups: t2, 2025-01-25, 2025-02-07
section Dev
  Frontend: t3, 2025-02-03, 2025-02-28
  Backend: t4, 2025-01-27, 2025-03-07
milestone: Launch, 2025-03-14

state — State Machine

UML state machine with start (●) and end (◎) pseudo-states, labeled transitions, accent states, and animated dashed edges.

Order Status e-commerce order lifecycle place order confirmed error retry Idle Processing Shipped Failed

Reserved IDs: start and end. Transition: A --> B: event. Accent: accent: stateId.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
accentstate id to highlight

Markdown syntax

figure state
title: Order Status
subtitle: e-commerce order lifecycle
accent: failed
start --> idle[Idle]
idle --> processing[Processing]: place order
processing --> shipped[Shipped]: confirmed
processing --> failed[Failed]: error
failed --> idle: retry
shipped --> end

er — Entity-Relationship Diagram

Database schema with entity boxes, field lists (pk/fk markers), and relationship lines with cardinality annotations.

Blog Schema users and posts writes ENTITY User # id uuid email text name text ENTITY Post # id uuid → author_id uuid title text

Entity: entity Name followed by indented fieldName [pk|fk]: type lines. Relation: A --> B: label.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault

Markdown syntax

figure er
title: Blog Schema
subtitle: users and posts
entity User
  id pk: uuid
  email: text
  name: text
entity Post
  id pk: uuid
  author_id fk: uuid
  title: text
User --> Post: writes

timeline — Timeline

Horizontal date axis with events spaced proportionally. Labels alternate above and below to reduce collisions. Milestones render with a larger accent dot.

Product History major releases Jan 2020 Jan 2021 Jan 2022 Jan 2023 v1.0 Launch v1.5 Improvements v2.0 Redesign v3.0 AI Features

Event: yyyy-mm-dd: Label. Milestone: append milestone at the end of the line.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault

Markdown syntax

figure timeline
title: Product History
subtitle: major releases
2020-01-15: v1.0 Launch milestone
2021-06-01: v1.5 Improvements
2022-03-10: v2.0 Redesign milestone
2023-11-01: v3.0 AI Features milestone

swimlane — Swimlane Flow

Cross-functional flowchart with horizontal lane bands. Same-lane edges use straight paths; cross-lane edges use S-curve routing. Edges animate with flowing dashes.

Order Processing cross-team workflow Customer Warehouse Shipping Place Order Confirm Payment Receive Order Pack Items Ship Package

Lanes are declared with section Name. Nodes within a section use the same node notation as flow. Cross-lane edges are automatically detected and routed.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault

Markdown syntax

figure swimlane
title: Order Processing
subtitle: cross-team workflow
section Customer
  order[Place Order]
  pay[Confirm Payment]
section Warehouse
  receive[Receive Order]
  pack[Pack Items]
section Shipping
  ship[Ship Package]
order --> pay
pay --> receive
receive --> pack
pack --> ship

bubble — Bubble Chart

Packed-bubble chart where each item's area is proportional to its value. Positions are computed automatically by a greedy circle-packing algorithm — no coordinates needed. Each bubble pulses with a staggered SMIL animation.

Market Analysis Revenue by Product Product C 85 Product A 75 Product E 60 Product B 50 Product D 30 Product F 20

Data lines use the format Label: value (positive numbers only). Bubble area is proportional to value; the largest item always fills the maximum radius. Labels and formatted values are rendered inside each bubble with automatic contrast (white or dark text).

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault

Markdown syntax

figure bubble
title: Market Analysis
subtitle: Revenue by Product
Product A: 75
Product B: 50
Product C: 85
Product D: 30
Product E: 60
Product F: 20

radar — Radar / Spider Chart

Multi-axis polygon chart (spider / web) for comparing multiple series across the same dimensions. Five concentric rings at 20–100%, axis spokes, and a legend below the chart.

Framework Comparison 2025 technical evaluation 20% 40% 60% 80% Performance Scalability DX Ecosystem Tooling React Vue Angular

Declare axes with axes: Axis1, Axis2, Axis3, .... Each series line uses the format Series Name: v1, v2, v3, ... where values are 0–100 (one per axis, clamped). Multiple series overlay with translucent fills; each picks a palette color automatically.

Config

KeyType / ValuesDefault
titlestring
subtitlestring
themelight · darklight
palettedefault · antv · drawio · figma · vega · mono-blue · mono-green · mono-purple · mono-orangedefault
axesstring[]required
seriesRadarSeries[]required

Markdown syntax

figure radar
title: Framework Comparison
subtitle: 2025 technical evaluation
palette: antv
axes: Performance, Scalability, DX, Ecosystem, Tooling
React: 75, 80, 90, 95, 88
Vue: 82, 72, 90, 82, 80
Angular: 65, 92, 72, 90, 86

Framework Integration

ai-figure generates a plain SVG string — there is no special adapter needed. Below are minimal integration examples for common environments.

HTML (via CDN or bundler)

<!DOCTYPE html>
<html>
<head>
  <script type="module">
    import { fig } from 'https://esm.sh/ai-figure';

    const svg = fig(`
      figure flow
      direction: LR
      A[Start] --> B[Process] --> C[End]
    `);

    document.getElementById('chart').innerHTML = svg;
  </script>
</head>
<body>
  <div id="chart"></div>
</body>
</html>

React

import { fig } from 'ai-figure';

// Server Component (Next.js App Router) — runs at build / request time
export default function FlowDiagram() {
  const svg = fig(`
    figure flow
    direction: LR
    palette: antv
    A[Start] --> B[Process] --> C[End]
  `);

  return (
    <div
      dangerouslySetInnerHTML={{ __html: svg }}
      style={{ width: '100%' }}
    />
  );
}
import { fig } from 'ai-figure';
import { useMemo } from 'react';

// Client Component — re-renders when markdown changes
export function DiagramViewer({ markdown }: { markdown: string }) {
  const svg = useMemo(() => fig(markdown), [markdown]);

  return (
    <div
      dangerouslySetInnerHTML={{ __html: svg }}
      style={{ width: '100%' }}
    />
  );
}

Vue 3

<template>
  <div v-html="svg" />
</template>

<script setup lang="ts">
import { fig } from 'ai-figure';
import { computed } from 'vue';

const props = defineProps<{ markdown: string }>();

const svg = computed(() => fig(props.markdown));
</script>

Node.js

import { fig } from 'ai-figure';
import { writeFileSync } from 'fs';

// Write to SVG file
const svg = fig(`
  figure arch
  direction: TB
  title: Microservices
  layer API Gateway
    gw[Gateway]
  layer Services
    users[Users]
    orders[Orders]
    payments[Payments]
  layer Data
    db[PostgreSQL]
    cache[Redis]
`);

writeFileSync('architecture.svg', svg);

// Express route example
import express from 'express';
const app = express();

app.get('/diagram', (req, res) => {
  const svg = fig(req.query.md as string);
  res.setHeader('Content-Type', 'image/svg+xml');
  res.send(svg);
});

AI Agent Skill

ai-figure ships a SKILL.md file that AI agents (GitHub Copilot, Cursor, Claude, etc.) can load as context to generate diagrams autonomously — no additional prompting required.

GitHub Copilot

# .github/copilot-instructions.md
@file node_modules/ai-figure/SKILL.md

Cursor / Claude / other agents

# In your prompt or system message:
Using the ai-figure SKILL.md at node_modules/ai-figure/SKILL.md,
create a sequence diagram showing the OAuth2 authorization code flow.

The Skill file contains the full markdown syntax reference, all config keys, JSON type definitions, and examples for every diagram type. It is designed to be compact and machine-readable while remaining human-friendly.