----------------------------------------------------------------------
This is the API documentation for the shypermaid library.
----------------------------------------------------------------------
## App
Assemble and launch the full app
create_app() -> 'App'
Create the Shiny app and serve ``www/`` at ``/shypermaid``.
Returns
-------
App
The assembled Shiny app.
run_app(host: 'str' = '127.0.0.1', port: 'int' = 8000) -> 'None'
Launch the app and open it in a browser.
Parameters
----------
host
Address to bind to.
port
Port to listen on.
## Modules
Shiny Core modules for embedding the editor and viewer in another app
wrapper(id: 'Id', *args: 'P.args', **kwargs: 'P.kwargs') -> 'R'
wrapper(id: 'Id', *args: 'P.args', **kwargs: 'P.kwargs') -> 'R'
wrapper(id: 'Id', *args: 'P.args', **kwargs: 'P.kwargs') -> 'R'
wrapper(id: 'Id', *args: 'P.args', **kwargs: 'P.kwargs') -> 'R'
## Diagram helpers
Shiny free functions that prepare Mermaid code and render options
set_direction(code: 'str', direction: 'str') -> 'str'
Rewrite the direction of a flowchart, state, class, or git graph diagram.
Only the diagram type line (after any frontmatter and ``%%`` lines) and,
for state and class diagrams, the top level ``direction`` statement are
changed:
* ``flowchart``, ``flowchart-elk``, and ``graph``: the header direction.
* ``stateDiagram`` and ``classDiagram``: a ``direction`` statement is
replaced or added. ``"TD"`` is written as ``TB``.
* ``gitGraph``: the header (``gitGraph TB:``). ``"TD"`` is written as
``TB``; ``"RL"`` is not supported and leaves the code unchanged.
``"asis"`` and every other diagram type return ``code`` unchanged.
Parameters
----------
code
Mermaid source.
direction
A key of ``DIRECTIONS``: ``"asis"``, ``"TD"``, ``"BT"``, ``"LR"``,
or ``"RL"``.
Returns
-------
str
The code with its direction rewritten.
Raises
------
ValueError
If ``direction`` is not a key of ``DIRECTIONS``.
Examples
--------
>>> set_direction("flowchart TD", "LR")
'flowchart LR'
>>> set_direction("classDiagram", "RL")
'classDiagram\n direction RL\n'
render_config(theme: 'str', look: 'str', layout: 'str' = 'dagre') -> 'dict[str, Any]'
Build the options passed to ``mermaid.initialize()``.
Parameters
----------
theme
A key of ``THEMES``.
look
A key of ``LOOKS``.
layout
A key of ``LAYOUTS``. Mermaid 12 includes the ELK layout, so
``"elk"`` needs no plugin.
Returns
-------
dict[str, Any]
Options with ``startOnLoad`` off and ``securityLevel`` strict.
Raises
------
ValueError
If ``theme``, ``look``, or ``layout`` is unknown.
Examples
--------
>>> render_config("dark", "classic")["theme"]
'dark'
----------------------------------------------------------------------
This is the User Guide documentation for the package.
----------------------------------------------------------------------
## Tutorial
### Getting Started
This tutorial walks through installing `shypermaid`, launching the app, and drawing a first diagram. By the end you'll have edited Mermaid code, changed the theme and direction, and saved the result as an SVG or PNG file.
## Install the package
`shypermaid` uses [`uv`](https://docs.astral.sh/uv/) for package management. Clone the repo, then run `uv sync` to create the environment and install the package with its development tools:
```bash
git clone https://github.com/mjfrigaard/shypermaid.git
cd shypermaid
uv sync
```
`uv sync` installs the package in editable mode, along with the `dev` group from `pyproject.toml`. Changes to files in `src/shypermaid/` show up the next time the app starts.
## Launch the app
The install adds a `shypermaid` command to the environment. Run it with `uv`:
```bash
uv run shypermaid
```
The command starts a server on `127.0.0.1:8000` and opens the app in a browser. The app ships its own copies of Mermaid and svg-pan-zoom, so it works without an internet connection. Mermaid 12 needs a current browser (Safari 17.4 or later, or a recent Chrome, Edge, or Firefox).
We can confirm the app is working by looking at the canvas. The sample flowchart from the editor should be drawn on the right side of the page.

## Edit the diagram
The editor sits in the sidebar on the left. Auto-Update is on by default, so each edit redraws the canvas. Replace the sample code with the flowchart below:
```{verbatim}
flowchart TD
a("Write code") --> b{"Valid?"}
b -->|"yes"| c(["Diagram"])
b -->|"no"| d("Error message")
```
Now break the code on purpose by deleting the closing `)` on the first node. A red error message appears at the bottom of the canvas, and the last good diagram stays in place. Put the `)` back and the error goes away.

::: {.callout-tip}
Turn off Auto-Update when you're writing a long diagram. The canvas only redraws when you click Render, so half finished lines won't flash errors while you type.
:::
## Change how it looks
The menus at the top right of the canvas change the drawing without changing your code. Theme picks the color scheme, and Look switches between the classic style and a hand drawn style. Layout picks the engine that places the nodes: Dagre is the default, and ELK draws right angled edges and often untangles diagrams with many crossing links.
Direction rewrites your code's direction before it is drawn. Pick Left to right and the flowchart turns on its side. Pick As written to go back to the direction in your code.

Direction works on four diagram types, and each one sets it in its own way:
| Diagram | What Direction changes |
|---|---|
| `flowchart`, `graph` | The header, as in `flowchart LR` |
| `stateDiagram`, `classDiagram` | The top level `direction` line (added if missing) |
| `gitGraph` | The header, as in `gitGraph TB:` (no Right to left) |
| Everything else | Nothing; the diagram is drawn as written |
## Move around and save
The tool buttons on the right edge control the view. You can also drag the canvas to pan and use the scroll wheel to zoom.
| Button (tooltip) | Action |
|---|---|
| Zoom in and Zoom out | Zoom in and out |
| Actual size | Show the diagram at its actual size |
| Fit | Fit the whole diagram on the canvas |
| Fullscreen | Enter or leave fullscreen |
| Download SVG | Download the diagram as `diagram.svg` |
| Download PNG | Download the diagram as `diagram.png` at twice its size |
Hover over a button to see its name. Click Download SVG to save the diagram. The file holds the diagram as Mermaid drew it, without the pan and zoom applied. Click Download PNG for an image you can paste into slides or documents; it has a white background (dark gray with the Dark theme).
## Recap
We installed `shypermaid`, launched it with `uv run shypermaid`, and edited a flowchart in the sidebar. The menus change the theme, look, and direction, and the tool buttons control the view and save the SVG or PNG file. The [Embed the Modules](01.01-how-to-embed-modules.qmd) guide shows how to put the editor and viewer in your own app.
## How-To
### Embed the Modules
The editor and viewer are Shiny Core modules, so you can place them in another app. This guide shows the smallest app that uses both, and the assets the page needs for the viewer to draw anything.
## Connect the editor to the viewer
Each module has a UI function and a server function. `editor_server()` returns the committed Mermaid code, and `viewer_server()` takes that value as its `code` argument:
```{mermaid}
%%| eval: true
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"18px", "darkMode":false}}}%%
flowchart TD
subgraph UI["UI"]
eui("editor_ui('editor')")
vui("viewer_ui('viewer')")
end
subgraph Server["Server"]
esrv("editor_server('editor')")
code[/"code
reactive.Value[str]"/]
vsrv("viewer_server('viewer', code=code)")
end
eui -.-> esrv
esrv --> code --> vsrv
vui -.-> vsrv
style UI fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style Server fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style eui fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style vui fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style esrv fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style vsrv fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
```
The dotted lines pair each UI function with its server function through a shared id. The solid line is the only data that crosses between the modules.
## Add the page assets
The viewer draws nothing on its own. The browser needs Mermaid, svg-pan-zoom, and the package's JavaScript binding, and the page needs the package stylesheet. All four ship in the package's `www/` folder (the libraries are in `www/vendor/`), so the app works offline. The app below adds them to the page head and serves `www/` at `/shypermaid`:
```python
from pathlib import Path
import shypermaid
from shiny import App, ui
from shypermaid import editor_server, editor_ui, viewer_server, viewer_ui
WWW = Path(shypermaid.__file__).parent / "www"
MERMAID_JS = "shypermaid/vendor/mermaid.min.js"
PANZOOM_JS = "shypermaid/vendor/svg-pan-zoom.min.js"
app_ui = ui.page_fillable(
ui.head_content(
ui.tags.script(src=MERMAID_JS),
ui.tags.script(src=PANZOOM_JS),
ui.tags.link(rel="stylesheet", href="shypermaid/styles.css"),
ui.tags.script(src="shypermaid/mermaid-binding.js"),
),
ui.layout_sidebar(ui.sidebar(editor_ui("editor")), viewer_ui("viewer")),
)
def server(input, output, session):
code = editor_server("editor")
viewer_server("viewer", code=code)
app = App(app_ui, server, static_assets={"/shypermaid": WWW})
```
The script order matters. Mermaid and svg-pan-zoom must load before `mermaid-binding.js`, because the binding calls both libraries when the first diagram arrives.
::: {.callout-warning}
Without the `static_assets` argument, the libraries, stylesheet, and binding return 404 errors. The page still loads, but the canvas stays empty and no error appears in the app.
:::
## Use your own code source
`viewer_server()` accepts any `reactive.Value[str]`, so the editor is optional. A fixed diagram, a file reader, or another module can supply the code instead:
```python
from shiny import reactive
def server(input, output, session):
code = reactive.Value("flowchart TD\n a --> b")
viewer_server("viewer", code=code)
```
We can confirm it works by running the app and checking that the canvas shows the two node flowchart.
## Recap
Pass the value from `editor_server()` (or any `reactive.Value[str]`) to `viewer_server()`. Add the two libraries, the stylesheet, and the binding to the page head, and serve `www/` at `/shypermaid`. The [Render Cycle](02.02-explanation-render-cycle.qmd) page explains what happens to the code after it leaves Python.
### Build the Desktop App
`shypermaid` also runs as a desktop app: a window of its own, no terminal, and no internet connection. The installers are built with [shinyelectron](https://r-pkg.thecoatlessprofessor.com/shinyelectron/), an R package that wraps a Shiny app in Electron. This guide shows how to install a release, build an installer on your own machine, and publish installers for every operating system.
## Install a release
Each [release on GitHub](https://github.com/mjfrigaard/shypermaid/releases/latest) has one installer per operating system. Download the file for yours:
| System | File |
|---|---|
| macOS (Apple silicon or Intel) | `.dmg` |
| Windows | `.exe` |
| Linux | `.AppImage` or `.deb` (Debian, Ubuntu, Pop!_OS) |
Install the `.deb` with apt, which also adds `shypermaid` to the app menu and a `shypermaid` command:
```bash
sudo apt install ./shypermaid_0.2.3_amd64.deb
```
The installers ship their own copy of Python, so you don't need Python, R, or Node installed. The app opens in its own window with the same editor and canvas as the browser version, with two differences:
* SVG and PNG open a Save dialog, so you choose where the file goes.
* Docs opens the Mermaid syntax reference in a second app window. That page is on the web, so it's the one part of the app that needs an internet connection.
::: {.callout-note}
The installers are not signed yet, so the operating system warns you the first time you open the app. On macOS, double click the app and click Done in the warning, then open System Settings, Privacy & Security, click Open Anyway next to the `shypermaid` message, enter your password, and click Open Anyway once more. On recent macOS versions (checked on macOS 26), right click and Open shows the same warning without an Open button. On Windows, click More info, then Run anyway. On Linux, make the file executable with `chmod +x` and run it.
:::
## Remove the app
The app keeps its settings and cache in a folder of its own, and removing the app leaves that folder in place. Remove both:
| System | Remove the app | Remove the settings |
|---|---|---|
| macOS | Drag `shypermaid` from Applications to the Trash | `rm -rf ~/Library/Application\ Support/shypermaid` |
| Windows | Settings, Apps, Installed apps, `shypermaid`, Uninstall | `Remove-Item -Recurse "$env:APPDATA\shypermaid"` |
| Linux (`.deb`) | `sudo apt remove shypermaid` | `rm -rf ~/.config/shypermaid` |
| Linux (`.AppImage`) | Delete the `.AppImage` file | `rm -rf ~/.config/shypermaid` |
## How the build works
shinyelectron builds from an app folder that holds an `app.py`, not from a Python package. The `electron/` folder bridges the two: a script copies the package into `electron/app/`, next to a one line `app.py` that imports `shypermaid.app.app`. shinyelectron then bundles that folder with Python and Electron into an installer.
```{mermaid}
%%| eval: true
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"18px", "darkMode":false}}}%%
flowchart TD
pkg[("src/shypermaid/")]
scaffold("scaffold_py.py")
subgraph App["electron/app/"]
launcher("app.py")
copy[("shypermaid/")]
yml("_shinyelectron.yml")
end
export("export()")
inst(["Installer"])
pkg --> scaffold --> App
App --> export --> inst
style App fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style scaffold fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style export fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style launcher fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style yml fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style inst fill:#2A6F77,color:#FFFFFF
```
The files in `electron/` have three jobs:
* `electron/app/app.py` and `requirements.txt`: the launcher and the Python packages the app installs.
* `electron/app/_shinyelectron.yml`: the app name, the version (copied from `pyproject.toml`), and the runtime strategy.
* `electron/build.R`: checks the app folder with `app_check()` and builds the installer with `export()`.
The copied package in `electron/app/shypermaid/` and the build output in `electron/dist/` are listed in `.gitignore`. The copy is refreshed before every build, so the package source stays the only place to edit.
The app uses the `bundled` strategy: the installer carries a portable Python, so it works offline on a machine with nothing installed. This is also why the JavaScript libraries ship inside the package (see [Checks and Docs](04.00-dev-checks-and-docs.qmd)).
## Build an installer locally
The build machine needs R 4.4 or later with shinyelectron, and Node 22 or later. Check them from R:
```r
install.packages("shinyelectron")
shinyelectron::sitrep_shinyelectron()
shinyelectron::install_nodejs() # if Node is missing or too old
```
From the package root, refresh `electron/app/`, then build:
```bash
uv run python tools/scaffold_py.py --strategy=bundled --module=shypermaid.app
Rscript electron/build.R
```
The installer for your system lands in `electron/dist/electron-app/dist/`. Run `source("electron/build.R")` from an interactive R session instead to open the app as soon as the build finishes.
::: {.callout-tip}
If the packaged app opens to a blank window, launch it with the `SHINYELECTRON_DEBUG=1` environment variable set. The log shows how it found Python, which packages it installed, and whether the Shiny server started.
:::
A build only makes installers for the system it runs on. macOS installers need a Mac, and the `bundled` strategy can't build for another system.
## Publish installers for every system
`.github/workflows/build-installers.yml` builds all four installers (macOS Apple silicon, macOS Intel, Windows, and Linux) on GitHub's runners. The Linux job also repackages the app as a `.deb`. It runs when you push a version tag, and attaches the installers to a GitHub release for that tag:
```bash
git tag v0.2.0
git push origin v0.2.0
```
Use the version from `pyproject.toml` for the tag. You can also start the workflow by hand from the Actions tab, which builds the installers without making a release.
## Recap
The desktop app is the same package in an Electron window. `tools/scaffold_py.py` copies the package into `electron/app/`, `electron/build.R` turns that folder into an installer, and a version tag builds installers for every system on GitHub.
## Explanation
### Package Layout
This page explains how `shypermaid` is split into files and why. It won't tell you how to do something; the How-To guides cover that.
## Three layers
The package has three layers, and each one only calls the layer below it. The diagram below shows the files in each layer and the calls between them:
```{mermaid}
%%| eval: true
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"18px", "darkMode":false}}}%%
flowchart TD
subgraph App["app.py"]
run(["run_app()"])
create("create_app()")
appui("app_ui()")
srv("server()")
end
subgraph Modules["modules.py"]
editor("editor_ui()editor_server()")
viewer("viewer_ui()viewer_server()")
end
subgraph Diagram["diagram.py"]
dir[["set_direction()"]]
cfg[["render_config()"]]
consts[("THEMES, LOOKS,DIRECTIONS, DEFAULT_CODE")]
end
www[("www/
binding, styles, libraries")]
run --> create --> appui & srv
create -.-> www
appui --> editor & viewer
srv --> editor & viewer
viewer --> dir & cfg
editor & viewer --> consts
style App fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style Modules fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style Diagram fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style run fill:#2A6F77,color:#FFFFFF
style create fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style appui fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style srv fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style editor fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style viewer fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
```
`app.py` assembles the page and launches the server. `modules.py` holds the two Shiny modules. `diagram.py` holds plain Python functions and the menu choices.
## The call tree from the source
The diagram above is drawn by hand, so it can drift from the code. [`callgrove`](https://mjfrigaard.github.io/callgrove/) reads the source files and builds the same tree without running the app. The cell below runs on every docs build, so the tree always matches the package:
```{python}
from pathlib import Path
import shypermaid
from callgrove import call_tree_dir
pkg = Path(shypermaid.__file__).parent
call_tree_dir(pkg, root="create_app")
```
The tree starts at `create_app()`, not `run_app()`. `run_app()` passes the app to Shiny as the string `"shypermaid.app:app"`, so there is no call for `callgrove` to follow, and its tree is a single node.
Each layer shows up one level below the last. `create_app()` calls `app_ui()` and `server()`, those call the modules, and only `viewer_server()` reaches into `diagram.py`. `_tool()` is a private helper that builds the buttons in the viewer's tool rail.
`modules_only=True` keeps only the functions decorated with `@module.ui` or `@module.server`. The wrappers in between are removed, and the modules move up to take their place:
```{python}
call_tree_dir(pkg, root="create_app", modules_only=True)
```
## Why the helpers are Shiny free
`diagram.py` never imports `shiny`. Its two functions take strings and return a string or a dictionary, so the tests call them directly without starting a session. That's why `diagram.py` has full test coverage while the module servers do not.
The same split keeps the menu choices in one place. `THEMES`, `LOOKS`, and `DIRECTIONS` fill the viewer's menus and also validate the arguments to `render_config()` and `set_direction()`. A new theme only needs a new dictionary entry.
## Why the drawing happens in the browser
Mermaid is a JavaScript library, so the diagram is drawn in the browser, not in Python. The files in `www/` handle that side. `mermaid-binding.js` receives the code from the server, draws it, and runs the pan, zoom, fullscreen, and download tools. `styles.css` lays out the editor and canvas. `vendor/` holds pinned copies of Mermaid and svg-pan-zoom, so the app never reaches out to a CDN.
`create_app()` serves `www/` at `/shypermaid` through the `static_assets` argument. The folder ships inside the package, so the paths work after a regular install as well as an editable one.
## A name to watch: `shypermaid.app`
`__init__.py` re-exports the `App` object named `app` from `app.py`:
```python
from .app import app, create_app, run_app
```
The re-exported name matches the submodule name, so after `import shypermaid` the attribute `shypermaid.app` is the `App` object, not the module. `shiny run shypermaid.app:app` still works because it imports the module by its full name. Plain attribute access does not, so code that needs `app_ui()` or `WWW` should use `from shypermaid.app import app_ui, WWW`.
## Recap
The package keeps the app, the modules, and the helpers in separate files, and each layer calls only the one below it. The helpers stay free of Shiny so they're easy to test, and the drawing lives in `www/` because Mermaid runs in the browser. The [Render Cycle](02.02-explanation-render-cycle.qmd) page follows one edit through all three layers.
### Render Cycle
This page follows one edit from the text area to the drawn diagram. The path crosses from Python to the browser once, and knowing where it crosses explains most of the app's behavior.
## Committing the code
The editor does not pass every keystroke to the viewer. `editor_server()` keeps a separate value called `committed`, and only committed code reaches the viewer. The Auto-Update switch decides when an edit is committed:
```{mermaid}
%%| eval: true
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"18px", "darkMode":false}}}%%
flowchart TD
edit(["User edits code"]) --> auto{"Auto-Update on?"}
auto -->|"yes"| commit("committed.set(code)")
auto -->|"no"| wait("Wait")
wait --> btn(["User clicks Render"])
btn --> commit
commit --> out[/"committed changes"/]
style edit fill:#FFFFFF,stroke:#3E2A1E
style btn fill:#FFFFFF,stroke:#3E2A1E
style commit fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style wait fill:#fff
style out fill:#E8A33D,color:#1B2A41
```
Turning Auto-Update back on also commits the current code. The `_auto` effect reads both the code and the switch, so a change to either one runs it again.
## Crossing to the browser
`viewer_server()` has one effect, and it runs when the committed code or any of the three menus changes. It doesn't return an output. Instead it sends a custom message named `shypermaid-render` to the browser:
```{mermaid}
%%| eval: true
%%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "fontSize":"18px", "darkMode":false}}}%%
flowchart TD
subgraph Py["Python"]
inputs[/"code(), theme,look, direction"/]
dir[["set_direction()"]]
cfg[["render_config()"]]
send("send_custom_message()")
end
subgraph JS["Browser"]
parse{"mermaid.parse()
succeeds?"}
draw("mermaid.render()
replace the SVG")
pz("Attach svg-pan-zoom")
err("Show the error
keep the last diagram")
end
inputs -->|"i. rewrite header"| dir
inputs -->|"ii. build options"| cfg
dir & cfg --> send
send -->|"iii. id, code, config"| parse
parse -->|"yes"| draw --> pz
parse -->|"no"| err
style Py fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style JS fill:#FFFFFF,color:#1B2A41,stroke:#1B2A41,stroke-width:1px,rx:10,ry:10
style send fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style draw fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style pz fill:#2A6F77,color:#FFFFFF,rx:5,ry:5
style err fill:#B83A4B,color:#FFFFFF,rx:5,ry:5
```
The Python side of this picture is all of `viewer_server()`. Its call tree from [`callgrove`](https://mjfrigaard.github.io/callgrove/) shows the three helpers it calls in `diagram.py`. The tree stops at the browser, because `callgrove` only reads Python files:
```{python}
from pathlib import Path
import shypermaid
from callgrove import call_tree_dir
call_tree_dir(Path(shypermaid.__file__).parent, root="viewer_server")
```
`code_theme()` reads the theme set in the code's frontmatter for the note in the toolbar. It does not change what is sent to the browser.
The top box runs in `viewer_server()` and the bottom box runs in `mermaid-binding.js`. The message carries three things: the namespaced canvas id, the code after `set_direction()`, and the options from `render_config()`. The id lets two viewers on one page draw into their own canvases.
## Why errors keep the last diagram
The binding calls `mermaid.parse()` before `mermaid.render()`. A parse error jumps to the error handler before the old SVG is removed, so the canvas keeps the last good diagram. The error text is set with `textContent`, which means a message from Mermaid can't inject HTML into the page.
`render_config()` also sets `securityLevel` to `"strict"`. In strict mode Mermaid disables click handlers in diagrams and cleans the HTML in labels.
## What the browser handles alone
Some actions never reach Python. The tool buttons, the Tab key in the editor, and window resizing are all handled in `mermaid-binding.js`:
* Tool buttons: each button carries `data-sm-action` and `data-sm-target` attributes, and one click listener on the page reads them.
* Tab key: inserts four spaces in the editor instead of moving focus. Press Escape, then Tab or Shift+Tab, to leave the editor.
* Highlighting: each edit recolors a `
` that sits behind the text area. The text area's own text is transparent, so Shiny still reads a plain `