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 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
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 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
ceo[CEO]
ceo --> cto[CTO]
ceo --> coo[COO]
cto --> fe[Frontend Lead]
cto --> be[Backend Lead]
coo --> ops[Operations]

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 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
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 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
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 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
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 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
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 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
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 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
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 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
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 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
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

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.