# Architecture

Tritone is built the way Mermaid is: a small core that knows nothing about any diagram, and **diagram types**
that each own a kind of text from start to finish.

```text
text ──► detect ──► diagram type ──► parse ──► lay out ──► draw (SVG string) ──► player (DOM)
```

Everything up to the SVG string is pure and runs anywhere. Only the last stage touches the page. An element
holds one mounted diagram at a time: `host.ts` gives it to the player that
mounts, and takes the listeners, the class and the attributes of the one before away. Both players show their
scene through `canvas.ts` when asked to: zoom and position are the viewBox
of the drawing, so nothing is drawn again to look closer.

This page is about the library, `packages/tritone`. The live editor and the documentation site that sit beside
it are described in [ecosystem](ecosystem.md) and [hosting](hosting.md).

## The core

`index.ts` holds a list of diagram types and asks each in turn whether a text
is its own. The first to say yes draws it. That is the whole dispatch.

| In Tritone | In Mermaid |
| --- | --- |
| `Diagram.detect` | The detector of a diagram |
| `Diagram.render` / `Diagram.mount` | Its parser, db and renderer |
| `registerDiagram` | `registerExternalDiagrams` |
| `registerModel` | `registerLayoutLoaders` |
| The `import()` behind the graph pipeline and behind each model | The `loader` beside each detector, and the layout loaders |
| `registerKind` | Icon packs and shapes |
| `render`, `run`, `initialize` | The functions of the same names |

## What a page fetches

The library is what other people put in their pages, so it is cut by what a page shows.
`index.ts` imports the story diagram, and of the graph diagram only what has
to answer at once: the names of the models, the default one, and `arrange`. The rest of a graph is behind
`import()`: `pipeline.ts`, which is everything between a
Mermaid text and its drawing, and each model on its own. They are fetched side by side the first time a text
needs them, and what can be said of a text without them (it is empty, Mermaid is not loaded, the model is unknown)
is said before anything is fetched.

| Piece | Fetched | Weight |
| --- | --- | --- |
| `tritone`: the API, the story diagram, the names of the models | With the page | 12.6 kB |
| The graph pipeline | At the first Mermaid text | 9.8 kB |
| A model | The first time a text is drawn in it | 0.8 kB (`ring`) to 1.5 kB (`sankey`) |
| `tritone/highlight` | By a page that shows code | 0.5 kB |
| `tritone/markdown-it` | By a Markdown renderer | 0.5 kB |
| `tritone/server` | By a server that answers for images | 7.7 kB |

The weights are minified and compressed with gzip, measured in November 2026 with Bun 1.3.9, each piece built on
its own, as a bundler that splits code builds them. `bun run build:lib` does not split: its one file holds every
piece, 24.3 kB. `size.test.ts` builds every one of them and fails when a
piece is more than 3% over the weight written there, so a model imported with a statement, or the whole library
pulled into the highlighter, does not go unnoticed. Pieces share a little code (a model its helpers, the pipeline
what it has in common with the story player), so a page fetches a little less than the sum: 22.6 kB for a graph in
`planes`, all told.

The highlighter and the image endpoint import the story code they use, not `index.ts`: the first asks only
whether a text is a story, which is `detect.ts`, and the
second parses and draws one.

## The two built-in diagram types

### `story`: `diagrams/story/`

| Stage | File | In | Out |
| --- | --- | --- | --- |
| Detect | `detect.ts` | Text | Whether it is a story: its first line that is not a comment starts with `story` |
| Parse | `parser.ts` | Text | `Story`: actors and steps |
| Lay out | `layout.ts` | `Story` | A floor cell per actor, a route per pair |
| Shapes | `kinds.ts` | A kind, a floor point | SVG of one actor |
| Draw | `renderer.ts` | `Story`, a step or "loop" | SVG markup with its animations |
| Play | `player.ts` | The markup | The player in the page |

One function draws both the interactive step and the looping image. Every element that appears, moves or leaves
is given a start and an end **on the clock of the whole story**; the renderer then cuts that clock to one step
(played once, by the player) or keeps all of it (repeated for ever, for an image). There is one timing model, so
the two outputs cannot drift apart.

### `graph`: `diagrams/graph/`

| Stage | Folder | In | Out |
| --- | --- | --- | --- |
| Read | `sources/` | Mermaid's parsed diagram | `Graph`: nodes, groups, edges |
| Notes | `notes.ts` | Text | A note per node, and how far each moved node went |
| Place | `models/` | `Graph` | `Scene`: primitives in space |
| Move | `shift.ts` | `Scene`, the moved nodes | The scene with those nodes, their links and their floors where the reader took them |
| Draw | `render/` | `Scene`, camera, selection | SVG markup |
| Interact | `mount.ts` | The markup | The widget in the page |

`graph` claims every text no other type claims, so it is always asked last. Its `index.ts` is the part every
page has: it knows the name of each model and how to fetch it, and writes a moved node into the text with
`notes.ts`. The other stages are fetched: see [what a page fetches](#what-a-page-fetches).

## Decisions

| Decision | Why |
| --- | --- |
| **No framework** | The output is an SVG string. A framework would add a runtime to every embed and buy nothing: state is one step number. Integration with frameworks goes through a custom element, which all of them render. This holds for the library: the apps around it have one each, Astro and React, see [a framework for the site or the editor](#a-framework-for-the-site-or-the-editor) |
| **SVG and SMIL, not canvas or WebGL** | Text stays sharp and selectable by assistive technology, themes are CSS, and the renderer has no DOM dependency, so it runs on a server. A SMIL animation plays inside an `<img>`, which is the only way to animate inside a README |
| **An own language for stories** | Steps, narration, notes and metrics have no home in Mermaid's grammar. Hiding them in comments would make the comments the real language |
| **Mermaid's language for graphs** | It exists, people know it, and files stay valid Mermaid |
| **Line-oriented grammar, parsed with regular expressions** | One statement per line means every error has a line number, and the parser is small enough to read in one sitting. A grammar tool can replace it when the language needs nesting |
| **Monospace labels** | The width of a label is its length times a constant, so label boxes can be sized without measuring text, which a server cannot do |
| **A player with no boxes** | The scene is the only drawing. Around it the title, the metrics, the steps and the narration sit on one surface and are told apart by the room between them, so a diagram reads as part of the page it is in, not as a widget dropped on it |
| **A player laid out by its own width** | The same player is in a phone, in a column of an article and in half of the editor's window: the window says nothing about the room it has. Its layout is a container query on its own element, and each row of it means one thing (the story, the step, the controls, the list of steps), so the narration can change length without moving a button. The rules are written in `playerCss` and held by tests that measure the player in a browser: see [how a story fits](embedding.md#how-a-story-fits-its-element) |
| **Layout tested by rule, not by picture** | `player.test.ts` opens the player in a headless Chrome at eight widths, with an everyday story, one where everything is long and a still picture, and checks where each part ended up: nothing sticks out, no part lies over another, the narration is beside the scene from 720px. `apps/live/live.test.ts` does the same for the editor, built as it is deployed, in six windows: side by side it is exactly the window, with nothing under it, and its menus open inside it and keep the keyboard. A comparison of screenshots would say the same on one machine only, since fonts differ between a Mac and the Linux that checks a pull request. The page the tests measure is kept, to be looked at |
| **A place chosen with the pointer is a statement** | Dragging an actor or a node does not add a hidden layout beside the text: the player moves it, and `arrange` writes it into the text, `at col,row` for an actor and a comment for a node. The text stays the only source of a picture, so a link, an image and an embed all show what was dragged |
| **Moved nodes are applied after the model** | A node's move is a distance from where its model put it, added to the scene the model returns. The ten models, and any registered one, need no code for it, and a graph that gains a node keeps the moves of the others. The price is that a link is bent to follow, not laid out again |
| **A band is a link with a width** | A sankey needs a link as wide as an amount. It is not a new primitive: a band is still the link of an edge, with a path and two ends, so lighting it with its nodes, fading it, moving it with them and framing the picture are the code of a link, and only its drawing differs. The width is a vector, not a number: in space a width has a direction, and filling between the path moved half of it each way is exact under any camera, with no tangent to work out |
| **Fixed isometric camera for stories** | The reader follows a narrative; a rotating scene competes with it. Graph views rotate because exploring is their point |
| **Deterministic layouts** | The same text always gives the same picture, so a diagram can live in documentation and in version control |
| **A page pays for what it shows** | Most pages show stories, and a page with a graph shows it in one model. So `tritone` carries the story diagram and fetches the graph pipeline and each model with `import()`, the first time a text needs them: 12.6 kB compressed for a page of stories, where one file with everything was 23.5 kB. The highlighter and the image endpoint imported that whole file and were as heavy; they now import the story code they use, 0.5 and 7.7 kB. What has to answer at once stays where it was: `detect`, `arrange`, `registerModel`. The file `bun run build:lib` writes for a page with no bundler stays one file: cut into pieces by Bun, a page of stories would fetch half the bytes and draw its first story one round trip later. A test weighs every piece: see [what a page fetches](#what-a-page-fetches) |
| **A bridge written by hand in the MCP App** | The page a host draws in a conversation speaks to it in JSON-RPC over `postMessage`, and the specification of MCP Apps writes every message out. The SDK's class for it, with the client and the schemas it brings, is 686 kB in a page, ten times the library that page carries, and the page travels inside an answer. So `apps/mcp/view.ts` says its own few messages, and `mcp.test.ts` opens it in a browser against the SDK's own host, which checks each of them. The server, where weight costs nobody, is made with the SDK |
| **One package, one repository** | The highlighter, the Markdown plugin and the server handler are subpath exports with no dependencies; they can become packages when they grow some. The live editor and the docs site are workspaces beside the library and reach it only through its public exports, so each can move to a repository of its own: see [ecosystem](ecosystem.md) |
| **No editor library in the live editor** | A textarea already has the caret, selection, undo, input methods and screen-reader support. Painting a copy of its text behind it adds highlighting for the cost of one small component, which never sets the textarea's value: that would cost the writer their undo. An editor component such as CodeMirror is the step to take when the language needs search, folding or completion |
| **A site built by Astro, from the Markdown as GitHub shows it** | The pages are the Markdown files of `docs/`, read by an Astro collection and drawn by Astro's Markdown. One remark plugin, `apps/docs/src/markdown.ts`, adds what a site needs: every `tritone` block painted and drawn by Tritone itself during the build, a link between files made a link between pages, and the first paragraph made the description a search result shows. The Markdown files stay plain Markdown, readable on GitHub as they are |
| **One design system, fonts served by the site** | The editor and the site are two apps that must read as one product, so everything a page is made of comes from `packages/ui`: tokens, and components. A component is a stylesheet, which is its look, and a React component, which is its markup and what it does. The editor draws it in the browser; Astro draws the same one into the pages of the site while it builds them, so the site has the markup and no script. A menu is the `Select` of the system, not the browser's `select`, whose list no stylesheet reaches. The rules (a colour, a font and a corner are tokens; a control is a component) are checked by a test on every stylesheet and every page: see `packages/ui/README.md`. Its fonts, Instrument Sans, Instrument Serif italic and Montserrat for the name in the logo, are files of the repository under the SIL Open Font License: a page asks no other host for them. Code and small labels keep the monospace system font, which is what the diagrams already use: a diagram loads no font, wherever it is shown |
| **A theme is a colour scheme, not a second palette** | Every colour is a `light-dark()` pair, in the pages and in the diagrams, so a theme is one property: `color-scheme`. The site's switch sets it, as a keyword the editor's bundler can read, together with `--tritone-scheme`, the property a diagram reads: a diagram in the page changes with the page. Dark is the default of the site, not of the library: a diagram on someone else's page still follows the reader's system |
| **An editor extension made of two scripts, and Mermaid beside them** | The Markdown preview of VS Code and of Cursor takes a plugin for its renderer and a script for its page, and nothing from another host. So `apps/vscode` is the library's own Markdown plugin, writing each block as an element, and one script that mounts those elements: no page, no framework, no look of its own. The script is of the old kind, not a module, because Cursor 3.32 skips a script its manifest declares as one; so it is one file with the whole library inside, 64 kB. Mermaid is a third file, `dist/mermaid.js`: the preview may fetch it from no host, so every copy of the extension carries it, 2.8 MB, and the packed extension is 830 kB where it was some 30 kB. The script imports that file the first time a block is not a story, from the address the script itself was loaded from: the content rules of the preview allow an import to a script that carries their nonce. A file of stories never loads it. Tritone has Mermaid read a text and never draw it, so the build leaves out five packages that only draw, cytoscape with its two layouts, elkjs and katex, each as a module that holds nothing: they were 2.4 MB of the 5.2 MB of Mermaid whole, and elkjs was the one package under a licence that asks for more than a notice. The rest is Mermaid as its package gives it, every type of diagram with it. The build writes the licences of the packages the file is made of beside it |

## A framework for the site or the editor

Weight is a constraint for the library, not for the apps. The library is what other people put in their pages,
and the part of Tritone meant to be published on its own: it has no framework and no runtime dependency, and what
each of its entry points weighs is watched. The landing page, the documentation site and the live editor are the
hosted product, and each has a framework since November 2026: Astro builds the site, and React draws the editor
and the components both are made of.
Each app is built on its own and can be served from a domain of its own ([hosting](hosting.md)).

What the frameworks cost, measured with Bun 1.3.9, Astro 5.18 and React 19.2 (sizes compressed with gzip):

| | Before | With the framework |
| --- | --- | --- |
| Site | Static pages of 6 to 30 kB with their styles inside them, built in 40 ms by one script | Static pages with no script of Astro's: the landing page is 10 kB and two stylesheets of 2 kB. Astro adds about 490 packages, and builds in about 3 seconds |
| Live editor | 27 kB of script, the library included | 90 kB, of which React and React DOM are 59, and a stylesheet of 72 kB, of which its two fonts are 68 |

Whatever an app is built with, these stay:

- **The diagram belongs to the library.** React draws the editor around it, and `mount()` puts the diagram in an
  element React does not touch. Figma is built the same way: React draws its panels, and its canvas is an engine of
  its own, written in C++, compiled to WebAssembly and drawing with the GPU. A faster diagram comes from the
  library, never from the app around it.
- **The apps reach the library only through its public exports**, as any other project would, so the library can
  be published and each app can move to a repository of its own.
- **The look is one design system.** A component of `packages/ui` is a stylesheet and, when it is more than a
  class, a React component. The editor draws it in the browser. Astro draws it while it builds a page, through
  `apps/docs/src/react.ts`, a renderer of a dozen lines that asks React for the markup: the page gets that markup
  and no script, so only a component that needs none is used there. Both apps have the same header from the same
  component.
- **React is held at 19.2.** The server renderer of React 19.3, which the site's build runs, does not load in Bun
  1.3.9, the version the project and its checks run on. The three `package.json` that name React ask for `~19.2.9`
  together. Lift it when Bun reads 19.3: `bun test apps/docs` builds the site and says so.
- **The addresses stay**: `live.html#…`, `embed.html#…` and `svg/….svg` are written into every snippet people have
  pasted elsewhere. On two domains, the links between the apps are whole addresses, written when each is built
  (`SITE_URL`, `EDITOR_URL`), and a diagram the site frames from the editor's domain asks the page around it for its
  theme, since two domains share no storage.

The live editor, part by part:

| Part of the live editor | In React | When it changes |
| --- | --- | --- |
| The source | `CodeEditor` in `editor.tsx`: the textarea, and the painted copy of its text, one `innerHTML` per key. React never sets the textarea, which keeps the writer's undo | At every key |
| Sample and Model | Two `Select` of `packages/ui`, in `live.tsx`: a control and a list the look draws, walked with the keyboard, which stays on the control | When one is opened, walked or chosen |
| Share, export, hide the source | `Button` of `packages/ui`, with their handlers. What they hand out is worked out from the text on screen | When one is pressed |
| The shell | The element React draws in is a grid of two rows, the header and the workspace: side by side it is exactly the window, and `live.test.ts` holds it to that | When the window changes |
| Error and status | State of `Editor` | After each drawing |
| The header | `Header` of `packages/ui`, the one every page of the site has | Never |
| The diagram | An element React does not touch, given to `mount()`: the story player or the 3D widget | A third of a second after the last key, and while it is dragged or zoomed |

Search, when the documentation needs it, needs no more than Astro: [Pagefind](https://pagefind.app) indexes the
built pages as they are.

## Mermaid

Tritone loads Mermaid, unmodified, and uses two of its functions:

- `mermaid.parse(text)`: public. Validates the text, names the diagram type and loads its code. Syntax errors
  shown to the writer are Mermaid's own.
- `mermaid.mermaidAPI.getDiagramFromText(text)`: marked internal by Mermaid. It is the only way to reach an
  already parsed flowchart. It is called in exactly one place, `packages/tritone/src/diagrams/graph/sources/index.ts`.

Because of the second, the Mermaid version is **pinned to 12.3.0**, with its integrity hash, in
`apps/live/mermaid.ts`, and in `apps/vscode/package.json` for the editor extension, which carries Mermaid as a
file. To move it: change the address and the hash in the first and the version in the second, which a test holds
to the first, then load every Mermaid sample in the live editor, and the Mermaid block of `apps/vscode/sample.md`
in the preview of an editor. The tests of the sources use hand-made stand-ins and will not notice a change in
Mermaid.

The Mermaid of the extension is that package built without five of the packages it draws with, which
`apps/vscode/build.ts` names. Mermaid's own code is not changed, but a later version may come to read a text with
one of them: `apps/vscode/preview.test.ts` reads a flowchart, an architecture and a sankey diagram with what is
left, and fails when one is not drawn.

Mermaid is not a dependency of the package: a page loads it, and only when a text is not a story.

## Known limits

- **Stories**: no groups or zones; labels can overlap on short routes; label boxes assume single-width
  characters; the camera is fixed; an image has no narration.
- **Canvas**: no two-finger pinch on touch screens; an actor or a node cannot be moved from the keyboard, only
  written; a moved node's links follow it but are not laid out again, and nothing stops two nodes from being put
  on top of each other.
- **Graph views**: only `flowchart`, `architecture-beta` and `sankey-beta`; one level of grouping; edges to a
  subgraph and junctions are dropped; edge labels show only for the links of what is selected. The amounts of a
  sankey are in the panel only, so a picture of one, with no panel, shows them as widths and says no number; its
  nodes have no group, so they are all one colour; a node whose name has a colon cannot be given a note. The
  `matrix` model sizes its columns by the number of letters in the names of the groups, not by measuring them.
- **MCP App**: stories only. What the reader does stays in the frame: an actor dragged to another cell is not
  written back, and the model is not told which step is on screen. It asks for no larger view than the one the
  host gives it. It was checked with the SDK's own client and host, not in Claude or ChatGPT themselves.
- **Images**: stories only. The endpoint carries the story code alone, so it draws no diagram type added with
  `registerDiagram` either. Whether an animated SVG plays inside a given Markdown host has not been tested host by
  host.
- **Loading**: `bun run build:lib` and the pages of the site do not split: each is one script with every piece
  inside. Built with `--splitting`, the library is cut by Bun, which puts the code the story player shares with
  the graph views, and a helper of its own, in two small files that `tritone.js` asks for once it has arrived: a
  page of stories fetches three files, not one, and waits one more round trip. A piece that cannot be fetched
  makes `mount` fail with the browser's own words, not with a sentence for the writer.
- **Size**: built for tens of actors or nodes, not thousands. The `nodes` model is quadratic, and so are the
  ordering of the nodes that `stages`, `lanes` and `sankey` share and the search `dominators` makes for every node.
- **Mermaid's weight**: 5.5 MB uncompressed, loaded per page that shows Mermaid text.
- **Addresses**: the diagram is in the address uncompressed, so links grow with the text.
- **Live editor**: no history and nothing saved outside the address; no search in the text; highlighting for
  stories only; an error marks its line for stories only; the
  source is hidden or shown, not resized.
- **Theme**: a story shown as an image (the Markdown image, the picture in the README) cannot be told the theme
  of the page around it in Safari, which does not hand an image the page's `color-scheme`; the site puts its
  drawings in the page for that reason. In the editor's pages the theme is applied by a deferred script, so a
  reader who chose light may see the dark page for an instant. On two domains the choice is kept for each: the
  editor opens in the theme last chosen on its own domain, or on a page that framed one of its diagrams.
- **Site**: no search, no versions. It is served from the top of its domain: under a path, Astro's `base` has to
  be set.
- **Browsers**: needs `light-dark()`, `color-mix()`, container queries and `:has()` (2024 and later). The layout
  of the story player is measured in Chrome by the tests; in WebKit it is looked at by hand, and in Firefox not at
  all.
- **Layout tests**: the story player and the live editor. The graph widget and the site have none, and no test
  compares pictures.
- **Live editor**: one script a page. The 3D pipeline and every model are inside it, though the library fetches
  them on demand: with `splitting`, Bun 1.3.9 writes pages that load the wrong file. Its font is inside its
  stylesheet, where the bundler puts it. A menu opens downward from its control, with no check of the room under
  it.
- **Editor extension**: it carries Mermaid, 2.8 MB as a file and 830 kB packed, with every type of diagram Mermaid
  reads for the three Tritone reads. Five packages are left out of it by name, so a Mermaid that needs one of
  them to read a text has to be given it back. A diagram is told from the one before an edit by its place in the file, so a block added above another hands it its step
  and its view. An actor dragged in the preview is not written into the file. A change of theme in VS Code draws
  the whole preview again, and a diagram is back on its first step; in Cursor it stays where it was. Its tests
  open its preview in Chrome, with the content rules of the editors, and not in an editor: that is looked at by
  hand.
- **Distribution**: not published to npm, and the extension to no marketplace; there is no public hosted instance.

## What not to do

- Parse Mermaid syntax in this repository. Mermaid does that.
- Read Mermaid's parsed data outside `packages/tritone/src/diagrams/graph/sources/`.
- Import a file of the library from an app. Apps use `tritone`, `tritone/markdown-it` and `tritone/server`, as
  any other project would.
- Put DOM access, randomness or the current time in a parser, a layout, a kind or a renderer.
- Add a runtime dependency for a few lines.
- Import the graph pipeline or a model with a statement from `index.ts` or `diagrams/graph/index.ts`, or the whole
  library from `highlight.ts` or `server.ts`. `size.test.ts` fails when a piece outgrows its budget.
- Set colours in a shape. Use the classes the theme fills.