@aiquants/markdown 13.0.0 → 13.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +303 -21
  2. package/dist/components/MarkdownRenderer.d.ts +6 -2
  3. package/dist/components/MermaidDiagram.d.ts +20 -0
  4. package/dist/components/blockNotice.d.ts +15 -0
  5. package/dist/components/fileSave.d.ts +1 -0
  6. package/dist/components/mermaidAccessibility.d.ts +11 -0
  7. package/dist/components/mermaidExport.d.ts +24 -0
  8. package/dist/components/mermaidLabels.d.ts +84 -0
  9. package/dist/components/spreadsheetClipboard.d.ts +1 -1
  10. package/dist/components/svgRaster.d.ts +2 -2
  11. package/dist/components/viewerLabels.d.ts +3 -2
  12. package/dist/extractHeadings-BfYlTVvN.js +6773 -0
  13. package/dist/extractHeadings-CZPJi4gM.cjs +12 -0
  14. package/dist/index.cjs +1 -1
  15. package/dist/index.client.cjs +1 -1
  16. package/dist/index.client.d.ts +4 -1
  17. package/dist/index.client.js +50 -48
  18. package/dist/index.js +50 -48
  19. package/dist/index.server.cjs +1 -1
  20. package/dist/index.server.d.ts +1 -1
  21. package/dist/index.server.js +95 -86
  22. package/dist/{markdownServiceClient-C47z3Ynu.cjs → markdownServiceClient-Dle7LnFB.cjs} +1 -1
  23. package/dist/{markdownServiceClient-uDeklhtG.js → markdownServiceClient-OrOuExUG.js} +7 -6
  24. package/dist/markdownServiceClient.d.ts +1 -0
  25. package/dist/mermaidFrame/NOTICES.md +1 -1
  26. package/dist/mermaidFrame/browserPaintView.d.ts +3 -0
  27. package/dist/mermaidFrame/cssCleaner.d.ts +16 -0
  28. package/dist/mermaidFrame/diagramPalette.d.ts +24 -0
  29. package/dist/mermaidFrame/diagramTheme.d.ts +7 -0
  30. package/dist/mermaidFrame/drawableTypes.d.ts +6 -0
  31. package/dist/mermaidFrame/drawer.d.ts +15 -2
  32. package/dist/mermaidFrame/frame.js +379 -378
  33. package/dist/mermaidFrame/insertion.d.ts +11 -0
  34. package/dist/mermaidFrame/namespaces.d.ts +3 -0
  35. package/dist/mermaidFrame/paintCheck.d.ts +2 -0
  36. package/dist/mermaidFrame/paintContract.d.ts +3 -0
  37. package/dist/mermaidFrame/paintDiagram.d.ts +3 -0
  38. package/dist/mermaidFrame/paintMap.d.ts +103 -0
  39. package/dist/mermaidFrame/paintRules.d.ts +18 -0
  40. package/dist/mermaidFrame/protocol.d.ts +5 -0
  41. package/dist/mermaidFrame/serve.d.ts +10 -5
  42. package/dist/remarkProcessor.server.d.ts +2 -0
  43. package/dist/serviceClient.cjs +1 -1
  44. package/dist/serviceClient.js +1 -1
  45. package/dist/styles/markdown.css +1 -1
  46. package/dist/styles/markdown.standalone.css +1 -1
  47. package/package.json +7 -5
  48. package/dist/extractHeadings-BAhmauKo.js +0 -5296
  49. package/dist/extractHeadings-qiJXegCx.cjs +0 -11
package/README.md CHANGED
@@ -58,7 +58,7 @@ export MARKDOWN_API_BINARY=/path/to/markdown-api
58
58
 
59
59
  | 変数 | 既定値 | 用途 |
60
60
  | --- | --- | --- |
61
- | `MARKDOWN_SOCKET_PATH` | (必須) | サービスと通信する UNIX ドメインソケットのパス (サービスも同じ変数を読む)。未設定か空なら `parseMarkdown` は変数を名指して失敗し、`createLinkCardHandler` の処理は 500 で答え、サービスは起動しない (パスを推し量らない)。プロセスの間は変えない (輸送は接続を開く時に読み、開いた接続を使い続ける)。ソケットのディレクトリは持ち主だけが書けること (ソケットの上では何も認証しないので、ほかの利用者が先に道を取ると、呼び出しのトークンと文書を受け取り、答えを返せる) |
61
+ | `MARKDOWN_SOCKET_PATH` | (必須) | サービスと通信する UNIX ドメインソケットのパス (サービスも同じ変数を読む)。未設定か空なら `parseMarkdown` と `nodeMarkdownServiceClient` は変数を名指して失敗し、`createLinkCardHandler` の処理は 500 で答え、サービスは起動しない (パスを推し量らない)。プロセスの間は変えない (輸送は接続を開く時に読み、開いた接続を使い続ける)。ソケットのディレクトリは持ち主だけが書けること (ソケットの上では何も認証しないので、ほかの利用者が先に道を取ると、呼び出しのトークンと文書を受け取り、答えを返せる) |
62
62
  | `MARKDOWN_SOCKET_MODE` | `0600` | サービスのソケットの権限。`0600` (所有者のみ) か `0660` (所有者とグループ) だけで、ほかの値ではサービスが値を名指して起動しない (ソケットの上では何も認証しないため、ほかの利用者へは開かない) |
63
63
  | `MARKDOWN_API_BINARY` | (なし) | 自前ビルドしたバイナリの明示指定 |
64
64
  | `MARKDOWN_API_STARTUP_TIMEOUT_MS` | `10000` | 自動起動したサービスが待ち受け開始するまでの猶予 (ミリ秒。子が先に終われば待たない)。未設定か空なら既定値で、正の整数のほかの値は子を起こす時に `RangeError` で変数を名指す |
@@ -72,7 +72,7 @@ export MARKDOWN_API_BINARY=/path/to/markdown-api
72
72
 
73
73
  後の 4 つはサービス (`markdown-api`) が読む。自動起動したサービスは呼び出し元のプロセスの環境を受け継ぐ。正の数 (時間は正の時間) 以外の値ではサービスが起動しない。
74
74
 
75
- `parseMarkdown` とリンクのカードは `@aiquants/local-service-transport` の輸送でサービスへ届く。呼び出しは HTTP/2 の接続 1 本を分け合い、止めた呼び出しの後は次の呼び出しから新しい接続へ移る。
75
+ `parseMarkdown`・`nodeMarkdownServiceClient`・リンクのカードは `@aiquants/local-service-transport` の輸送でサービスへ届く。呼び出しは HTTP/2 の接続 1 本を分け合い、止めた呼び出しの後は次の呼び出しから新しい接続へ移る。
76
76
 
77
77
  自動起動したサービスは起こしたホストの子で、ホストと一緒に終わる。ソケットを複数のホストで分けると、先に終わるホストの子の上の呼び出しは失敗し、次の呼び出しが子を起こす (サービスは起動のときに道のソケットを生死を問わず消すため、後に起きた子が道を取る)。ソケットを分けるホストでは、サービスをプロセスマネージャで起こす。
78
78
 
@@ -261,11 +261,29 @@ const { htmlContent, headings } = await service.convert(
261
261
  ```
262
262
 
263
263
  - **Options** are `ParseOptions`, checked before anything is sent.
264
- - **Transport**: in Node, use `createLocalServiceTransport` of `@aiquants/local-service-transport`, as `parseMarkdown` does. A fast run of stopped calls loses a plain shared HTTP/2 connection, and every later call fails or hangs until the process restarts; this transport moves the next calls to a new connection.
264
+ - **Transport**: in Node, take [`nodeMarkdownServiceClient`](#node-client), or build the client over `createLocalServiceTransport` of `@aiquants/local-service-transport`, the transport `parseMarkdown` runs on. A fast run of stopped calls loses a plain shared HTTP/2 connection, and every later call fails or hangs until the process restarts; this transport moves the next calls to a new connection.
265
265
  - **Storage**: every call names `X-Storage-Auth-Mode: oauth2`; a token that is no RFC 6750 bearer token is refused with a `TypeError` that does not repeat it; and `userOAuthToken` (`undefined` when the reader holds none) rides as the bearer token: the service reads the cloud only with the reader's own credentials.
266
266
  - **Errors** are the browser converter's classes, with the transport's failure as `cause` when there is one: `MarkdownResourceExhaustedError` past a size limit, an answer longer than `maxHtmlBytes` included; `MarkdownConversionTimeoutError` past a deadline, whose `timeoutMs` is the limit the call set, or `null` when the call set none and the service stopped at its own; and `MarkdownConversionError` with `code`: `unavailable` when the service cannot be reached, goes away during the call or has no provider for the document's scheme, `invalid_argument` for a refused request, `internal`.
267
267
  A call `signal` stopped rejects with a `ConnectError` of code `canceled`, whatever the signal's reason. Any other code (`unauthenticated`, `permission_denied`) stays the `ConnectError` it is.
268
268
 
269
+ #### Node client
270
+
271
+ `nodeMarkdownServiceClient` of `@aiquants/markdown/server` is this client over the process's socket (`MARKDOWN_SOCKET_PATH`), for a Node host that hands a client to code written against `./service-client`:
272
+
273
+ ```ts
274
+ import { nodeMarkdownServiceClient } from "@aiquants/markdown/server"
275
+
276
+ // Code written against ./service-client takes it as a MarkdownServiceClient
277
+ const { htmlContent, headings } = await nodeMarkdownServiceClient.convert(
278
+ { markdownText, filePath: "notes/my-file.md", workspaceRoot: "/workspace", userOAuthToken: undefined },
279
+ { deniedPathSegments: hostDenyRules, maxHtmlBytes: 4 * 1024 * 1024, timeoutMs: 10_000, signal: controller.signal },
280
+ )
281
+ ```
282
+
283
+ - **Conversion**: it converts as `parseMarkdown` does, over the transport `parseMarkdown` and the link cards share: it waits for the service within the call's signal and deadline, starts it when nothing listens, and sends the conversion with what is left of the deadline. The options, the storage headers and the token check are those of the client above.
284
+ - **Errors** are those of the client above. A deadline passed while it waited or converted carries the limit the call set, not what was left of it; a service out of reach, which on Windows is every call, is `unavailable` with its socket named. An unset `MARKDOWN_SOCKET_PATH` (an `Error` naming the variable, before anything), invalid options (a `RangeError` or `TypeError` naming `MarkdownServiceClient.convert` and the option) and an invalid `MARKDOWN_API_STARTUP_TIMEOUT_MS` (a `RangeError` naming the variable, when the service has to be started) are thrown as they are.
285
+ - **Importing** it opens nothing: the value is frozen, and the transport connects on the first call.
286
+
269
287
  ## Viewer, embeds and links
270
288
 
271
289
  `MarkdownRenderer` keys every top-level block by its content, from the keys of the last committed render: a fingerprint of the block's HTML without `data-source-lines` (a ```` ```spreadsheets ```` block's fingerprint also leaves its table's text out), and the content itself. A block takes the earliest unclaimed key of the same fingerprint and content, then the earliest unclaimed key of its fingerprint (a table whose cells changed), else a new key.
@@ -694,8 +712,10 @@ as written.
694
712
  4096 × 4096 pixels of area and 32,767 pixels a side, and hands the clipboard the PNG as an `image/png`
695
713
  `ClipboardItem` within the press, so a browser that only writes during a press (Safari) takes it too. The SVG is
696
714
  drawn from a blob URL of the page's own origin, so the canvas stays readable whatever origin the image comes from,
697
- and, as the image itself, loads nothing outside the file. A file the host cut, a read that fails, or a file the
698
- browser cannot draw copies nothing and says it could not copy, as does a browser without `ClipboardItem`.
715
+ and, as the image itself, loads nothing outside the file; a page whose content security policy limits `img-src`
716
+ (or, without one, `default-src`) must therefore list `blob:` there, or the browser refuses the blob URL. A file the
717
+ host cut, a read that fails, or a file the browser cannot draw copies nothing and says it could not copy, as does a
718
+ browser without `ClipboardItem`.
699
719
  - With the whole source shown (`copy`, its outcomes `copied` and `copyFailed`) it writes the text exactly as read. A
700
720
  source the host cut never offers Copy, so the clipboard never gets part of a file.
701
721
  - Each press of Copy stops the copy before it, and leaving the block stops the one under way, so only the latest press
@@ -729,10 +749,13 @@ as written.
729
749
 
730
750
  Every top-level block renders inside its own error boundary. A block whose rendering throws in the browser — a host's
731
751
  `linkComponent` that fails, a component's bug — shows a short notice in its place (`[data-aqmd-block-failure]`: the
732
- label `blockFailed`, the renderer's `blockFailedLabel`, above the block's text in a `<pre>`; the built-in English notice
752
+ label `blockFailed`, the renderer's `blockFailedLabel`, above the block's text in a `<code>` inside a `<pre>`, which a
753
+ display style colours as its code blocks and which wraps every line; the built-in English notice
733
754
  is marked `lang="en"`, a supplied one carries `labelsLang`, or no language without it), the other blocks render, and React reports the error as a
734
755
  caught one (the root's `onCaughtError`, the console by default). The block renders again as soon as its content
735
- changes. React's server rendering does not stop at error boundaries, so such a block still fails a server render.
756
+ changes. Every text of the notice, the block's text among them, reaches 7:1 or more on the ground under it in the
757
+ None, GitHub and Zenn styles and both schemes, under every colour pair and without one. React's server rendering
758
+ does not stop at error boundaries, so such a block still fails a server render.
736
759
 
737
760
  ### Text that grows
738
761
 
@@ -744,24 +767,27 @@ text with `includeStreamingHints` and passes the result's `blockOffsets` along w
744
767
  <MarkdownRenderer
745
768
  htmlContent={result.htmlContent}
746
769
  blockOffsets={result.blockOffsets}
747
- streaming={!finished} // the stream still writes the text
748
- blockKeyEpoch={attempt} // changes when the text is replaced rather than extended
770
+ streaming={!finished} // the stream still writes the text
771
+ truncated={finished && cutOff} // the text stopped before its end
772
+ blockKeyEpoch={attempt} // changes when the text is replaced rather than extended
749
773
  />
750
774
  ```
751
775
 
752
776
  - **Blocks**: with `blockOffsets`, the renderer cuts the HTML into its top-level blocks and parses and renders only the blocks whose HTML changed since the last committed render. An unchanged block keeps its elements, its formulas' reports and its count of images (KaTeX and Shiki do not run for it again), and a block holding an image renders again when the images before it changed (the document's first image loads eagerly).
753
777
  A block whose HTML changed but stands where the last render had an unmatched block of the same root element takes that block's key, so a growing block keeps its components (focus, scroll, an open `details`). Without `blockOffsets` the whole document is parsed on every render.
754
- - **Stable props**: the kept blocks are dropped whenever another prop that shapes the elements changes (the theme, labels, components, readers), so pass stable values; a labels object or a `linkComponent` made anew on every render drops them every time. `imageSource` and `spreadsheetEditor` may change on any render: the renderer holds a stable stand-in for each.
778
+ - **Stable props**: the kept blocks are dropped whenever another prop that shapes the elements changes (the theme, labels, components, readers, the drawing place of the diagrams), so pass stable values; a labels object or a `linkComponent` made anew on every render drops them every time. `imageSource` and `spreadsheetEditor` may change on any render: the renderer holds a stable stand-in for each.
755
779
  - **Unchanged parts**: inside a block that renders again, a closed code block's highlighting, the frame of a display formula and the copy buttons render again only when their values change.
756
780
  - **Selection**: the reader's selection inside the document stays across these renders. A point inside a text React rewrote returns to its place, cut to the text's new length; a point between elements stays where the DOM moved it. An empty selection, one outside the document, one whose node left the document in the commit and one the commit did not move are left alone.
757
781
  - **Replaced text**: `blockKeyEpoch`, a safe integer, tells the renderer that the text was replaced rather than extended (a stream that restarted, a conversation read again); change it together with the new text's HTML. A render whose epoch differs from the last committed render's hands a block its predecessor's key only when both have the same content, so no component of the replaced text passes to the new one.
758
- - **Open code blocks**: while `streaming` is true, a code block the converter marked open (`data-open-code` on its `pre`) shows its code as plain text and Shiki does not run for it, as a later line can still close it or add code; a code block without the mark is highlighted at once. When the mark goes (the closing fence arrived) or `streaming` turns false, the block is highlighted in the same `pre` (see [Code blocks](#code-blocks)). A change of `streaming` renders again only the blocks that hold a marked code block.
759
- - **Errors**: offsets that do not start at 0, do not increase, are not safe integers or point outside `htmlContent` (or none for HTML that holds a block), an epoch that is not a safe integer and `streaming` true without `blockOffsets` throw a `RangeError`.
782
+ - **Open code blocks**: while `streaming` is true, a code block the converter marked open (`data-open-code` on its `pre`) shows its code as plain text and Shiki does not run for it, as a later line can still close it or add code; a code block without the mark is highlighted at once. When the mark goes (the closing fence arrived) or `streaming` turns false, the block is highlighted in the same `pre` (see [Code blocks](#code-blocks)). A change of `streaming` renders again only the blocks that hold a marked code block or diagram.
783
+ - **Open diagrams**: while `streaming` is true, a Mermaid diagram the converter marked open is not drawn (Mermaid is not loaded for it) and shows its text under the `openStreaming` reason; it is drawn once the mark goes or `streaming` turns false (see **Held diagrams** in [Mermaid diagrams](#mermaid-diagrams)).
784
+ A text that stopped before its end (a stream that broke off, an answer cut at its length limit) takes `truncated`: a diagram marked open then shows its text under `openCut` instead of being drawn from a text whose closing line never came, while a code block so marked is highlighted. With neither, the text counts as complete and a diagram marked open is drawn as it stands. A change of `truncated` too renders again only the blocks that hold a marked code block or diagram.
785
+ - **Errors**: offsets that do not start at 0, do not increase, are not safe integers or point outside `htmlContent` (or none for HTML that holds a block), an epoch that is not a safe integer, `streaming` or `truncated` true without `blockOffsets`, and both true together throw a `RangeError`.
760
786
 
761
787
  ### Mermaid diagrams
762
788
 
763
789
  A fenced code block in the `mermaid` language renders as `MermaidDiagram`, a block that takes its containing block's width (its slot). The first child of the block's dialog (see [Full screen](#full-screen)) is a hidden measuring element, `[data-aqmd-mermaid-measure]` (no height, clipped, `visibility: hidden`, `aria-hidden`), present while the diagram loads, shows or fails; the component measures the slot's width with it (the window's width, less the dialog's padding, while full screen).
764
- Each drawing gets its own drawing host, `[data-aqmd-mermaid-host]`: a hidden element (`visibility: hidden`, `aria-hidden`, absolutely positioned just outside the start edge, `contain: strict`) appended to the main document's `<body>`, with its width set to the measured width in px.
790
+ Unless a host has the diagram drawn in a drawing place (see [Drawing place](#drawing-place)), each drawing gets its own drawing host, `[data-aqmd-mermaid-host]`: a hidden element (`visibility: hidden`, `aria-hidden`, absolutely positioned just outside the start edge, `contain: strict`) appended to the main document's `<body>`, with its width set to the measured width in px.
765
791
  Mermaid draws in that element and the component shows the result in the slot, so a gantt chart, whose width Mermaid takes from where it is drawn, is exactly as wide as the slot. Because Mermaid looks its drawing up through the main document, the host lives in the main document's light DOM, and a diagram in a slot inside a shadow root is drawn the same way.
766
792
 
767
793
  - **Loading Mermaid**: the library is imported, a chunk of its own, when the first diagram with text mounts, and initialized once for the page without its start-on-load scan, so a document without diagrams never loads it, nor does a diagram of white space alone.
@@ -772,6 +798,13 @@ Mermaid draws in that element and the component shows the result in the slot, so
772
798
  - Nothing is drawn while the slot has no width (inside a closed `<details>` the browser does not lay out, or a hidden panel): the loading text stays until the slot gets a width. A drawing already under way when the slot loses its width finishes at the width it was given.
773
799
  - When the width of a slot showing a gantt chart changes (a splitter drag, a window resize), the chart is drawn again at the new width 200 ms after the last change, unless the slot then has no width or the width of the latest drawing. The shown chart stays until the new one replaces it, and the new one starts at the initial zoom and pan. Other diagram types take their size from their text and are never drawn again for a width change.
774
800
  - A drawing that finishes after a newer one was requested, after the diagram's text changed or after the component unmounted is discarded.
801
+ - **Errors**: a diagram that cannot be shown shows in its place (`[data-aqmd-mermaid-error]`) `errorPrefix` and the reason, below them the diagram's text without its leading and trailing white space, as plain text in a `<code>` inside a `<pre>` (`[data-aqmd-mermaid-source]`, as wide as the box), and below that the retry button, which draws the diagram again.
802
+ A display style colours the text as its code blocks (Zenn's grounds every `<pre>` dark in both schemes and colours only the `<code>` in it), and every line wraps to the box's width, so the text never scrolls sideways and the error adds no control to reach.
803
+ - **Held diagrams**: a host holds a diagram back with `held` (`MermaidHeld`): `{ kind: "streaming" }` while a stream still writes its text, `{ kind: "cut" }` when the text stopped before its closing line, or `{ kind: "too-many-diagrams", limit }` past the document's limit of diagrams.
804
+ A held diagram is not drawn, in the page or in a drawing place alike (Mermaid is not loaded for it and the drawing place is not asked), and shows in its place (`[data-aqmd-mermaid-held]`, whose value is the kind) the hold's reason (`openStreaming`, `openCut`, or `tooManyDiagrams` with its `{limit}` filled) above the diagram's text, which shows as in the error, without `errorPrefix` and the retry button; once the hold goes the diagram is drawn.
805
+ The box takes the controls' border, surface and text, whose text reaches 7:1 on the surface in both schemes, as a hold is no error.
806
+ `MarkdownRenderer` holds its diagrams itself from `streaming`, `truncated` and `maxMermaidDiagrams`: the diagrams count in document order, a held one as well as a drawn one, and each past `maxMermaidDiagrams` (a positive safe integer) is held with the limit whatever mark it has, on either path; a block holding a diagram renders again when the diagrams before it changed, and a change of the limit drops the kept blocks. `MarkdownViewer` and `NodesRenderer` hold no diagram.
807
+ A hold that is not an object throws a `TypeError`, and one of another kind or with a limit that is not a positive safe integer a `RangeError`, as does a `maxMermaidDiagrams` that is not a positive safe integer.
775
808
  - **Touch and pen**: the default mode, `both-shift`, is the same for every pointer, and Shift gates only the mouse. A finger or pen pans the drawing only while the drawing overflows its frame (zoomed in, or capped, see below); at fit it scrolls the page over the diagram as anywhere else. The component writes `touch-action` on the diagram's `<svg>` and on its frame to match, rewrites it whenever the zoom or pan changes, the mode changes or the frame resizes, and removes it (with the other styles Panzoom wrote) when it tears its Panzoom instance down:
776
809
 
777
810
  | Mode | Drawing fits its frame | Drawing overflows its frame |
@@ -781,7 +814,8 @@ Mermaid draws in that element and the component shows the result in the slot, so
781
814
  | `pan`, `pan-shift` | `auto` | `pinch-zoom` |
782
815
  | `both`, `both-shift` | `pan-x pan-y` | `none` |
783
816
 
784
- - **Frame and clipping**: the shown drawing sits in a frame, `[data-aqmd-mermaid-frame]` (it also keeps `data-testid="mermaid-diagram"`), that clips it with `overflow: clip` from the components' stylesheet (the component writes no inline `overflow`), and the `<svg>` is a block. A zoomed drawing therefore never widens the frame or scrolls the document sideways. `data-aqmd-mermaid-overflowing` is `"true"` while the drawing overflows the frame and `"false"` otherwise.
817
+ - **Frame and clipping**: the shown drawing sits in a frame, `[data-aqmd-mermaid-frame]` (it also keeps `data-testid="mermaid-diagram"`), that clips it with `overflow: clip` and contains its paint with `contain: paint`, both from the components' stylesheet (the component writes no inline `overflow`), and the `<svg>` is a block (the frame's `<svg>` child, or for a drawing place's copy the part `drawing`, see **Insertion** below).
818
+ A zoomed drawing therefore never widens the frame or scrolls the document sideways, and the paint containment, which makes the frame the containing block of the drawing's positioned elements, clips even one positioned `fixed`, which overflow clipping alone leaves to the viewport (a diagram drawn in the page can position its own root `fixed` through Mermaid's `themeCSS`, and the transform of the zoom holds only the root's descendants). `data-aqmd-mermaid-overflowing` is `"true"` while the drawing overflows the frame and `"false"` otherwise.
785
819
  - **Zoom bounds**: the zoom runs from the drawing as laid out in the frame (1×) to 200 % of the diagram's natural size (WCAG 1.4.4), the width at which one unit of the drawing is one CSS px, read from the drawing itself: the width of its `viewBox`, which the browser scales to the drawing's box; a drawing without a `viewBox` (Mermaid's `info`) is never scaled, so its layout is its natural size and it zooms up to 2×.
786
820
  The fit is the drawing's laid-out width over its natural width, so the bound holds wherever the drawing is laid out (full screen lays a tall drawing out narrower than its frame). Only a drawing whose `viewBox` has no usable size (not four numbers with a positive width and height) shows an error and a retry button in its place.
787
821
  A drawing of 1993.6 px natural width laid out 372 px wide zooms up to 10.72×; a diagram that already fits zooms up to 2×. The view is clamped on each axis like a scroll container: a drawing larger than the frame keeps covering it, a smaller one stays inside.
@@ -789,21 +823,208 @@ Mermaid draws in that element and the component shows the result in the slot, so
789
823
  While a finger or pen pans or pinches the drawing, the frame cancels the default action of its `touchmove` events, so the browser starts no momentum scroll and the next tap on a control is never spent stopping one. That non-passive listener is bound only while the drawing overflows its frame: over a fitting diagram a finger scrolls without the browser waiting for the page's script.
790
824
  - **Keyboard**: the frame takes focus (`tabindex="0"`, `role="group"`) and is named by the `diagram` label, which a hidden element carries with its own `lang`, so the drawing's text is not marked with it. On the frame itself, not on a link inside it and not with Ctrl, Meta or Alt held, the arrow keys pan the view by 25.9 % of the frame (only when the view can move; otherwise the page scrolls), `+` and `=` zoom in, `-` zooms out and `0` resets.
791
825
  When an element inside the drawing takes the focus (a node's link, by Tab), the view pans by the least distance that brings the element's box inside the frame, because the clipping frame is no scroll container the browser could scroll to it.
826
+ - **Screen readers**: a diagram whose text gives it a title (`accTitle`) names the frame, the toolbar and the block's dialog by that title ahead of their own label (`diagram`, or `fullscreenDialog` for the dialog in full screen), so the label's key hints stay in the name, and one with a description (`accDescr`) gives the frame that description (`aria-describedby`).
827
+ Both are read from the shown drawing, in the page and in a drawing place alike: the text of the elements inside the drawing that its root names in `aria-labelledby` and `aria-describedby`, which Mermaid writes from them, with each run of white space collapsed. Hidden elements carry them without a `lang`, so they take the document's language.
828
+ The drawing's root keeps the role Mermaid gives it (`graphics-document document`), and its role description, which Mermaid writes as the type's code (`aria-roledescription="flowchart-v2"`), is the type's name from the `type…` labels instead (see [Labels and languages](#labels-and-languages)), rewritten in place when the labels change. A type without a label (one a later Mermaid adds) has no role description, so its code is never read out.
829
+ The drawing place's real-browser check (`check:mermaid-frame-browser`) checks through the component in Chromium, Firefox and WebKit, on both paths, that the frame, the toolbar and the dialog point at the title and the frame at the description, and that the root of every sample it draws takes its type's name, and reads the frame's computed name and description and the root's role description from Chromium's accessibility tree.
792
830
  - **Pan buttons**: four buttons (`pan-left`, `pan-up`, `pan-down`, `pan-right`) lead the toolbar and are shown only while the drawing overflows its frame, so panning never needs a drag (WCAG 2.5.7); at fit they keep their slots hidden (`visibility: hidden`: not focusable, not exposed), so zooming never adds a toolbar row or moves the frame; each moves the view by the same step as the arrow keys.
793
831
  - **Sizes**: under every pointer (a mouse, a pen or a finger) every control is 44 × 44 px and each menu item and the retry button at least 44 px tall (WCAG 2.2 enhanced target size). The toolbar is a wrapping row above the frame, aligned to the row's end, so the controls never cover the drawing.
794
- The pan buttons come first in it, so the controls always shown (the mode menu, zoom in, zoom out, reset and the full-screen toggle) stay at the row's end while the hidden pan buttons keep their slots.
795
- The pan buttons and the mode menu with the zoom and reset buttons are two groups that each wrap as a whole, followed by the full-screen toggle, so a narrow column puts each group on a row of its own instead of dropping one of a group's controls to the next row.
832
+ The pan buttons come first in it, so the controls always shown (the mode menu, zoom in, zoom out, reset, the Source toggle and the full-screen toggle) stay at the row's end while the hidden pan buttons keep their slots.
833
+ The pan buttons and the mode menu with the zoom and reset buttons are two groups that each wrap as a whole, followed by the Source toggle's group (with the Export menu and Copy diagram before the toggle while they show, see **Export** below, and Copy while the text shows) and the full-screen toggle, so a narrow column puts each group on a row of its own instead of dropping one of a group's controls to the next row.
796
834
  The menu opens below its button within the toolbar's row and the viewport: at the button's start edge, else at its end edge, else moved inside the row as near the button as it allows and narrowed to the row when the row is narrower (`data-aqmd-control-menu`: `start`, `end` or `inside`), so it stays over the diagram.
797
- - **Full screen**: the toolbar's last control shows the diagram over the whole window while it shows a drawing (see [Full screen](#full-screen)). The frame fills the free space below the toolbar without the coarse pointer's cap, and the drawing fits it whole in its natural shape, never past its natural width, at the frame's centre; the view (zoom and pan, kept within the bounds of the new layout) carries across. A diagram that starts loading again or fails leaves full screen with its toolbar.
835
+ - **Full screen**: the toolbar's last control shows the diagram over the whole window while it shows a drawing (see [Full screen](#full-screen)). The frame fills the free space below the toolbar without the coarse pointer's cap, and the drawing fits it whole in its natural shape, never past its natural width, at the frame's centre; the view (zoom and pan, kept within the bounds of the new layout) carries across. A diagram that starts loading again, fails or is held back leaves full screen with its toolbar.
836
+ - **Source**: the Source toggle (`source`, with `aria-pressed`), between the drawing's controls and the full-screen toggle, shows the diagram's text without its leading and trailing white space in place of the drawing, in a `<pre>` (`[data-aqmd-mermaid-source]`, the text in its `<code>`, so a display style colours it as its code blocks) that takes the focus (`role="region"`, named by the `sourceRegion` label after the drawing's title when it has one) and scrolls. It wraps the text as written, is no taller than `--aqmd-viewport-cap` and fills the window below the toolbar in full screen.
837
+ The frame is hidden, not removed (`hidden`), so a second press shows the drawing with the view it had; meanwhile the drawing's controls (pan, mode, zoom and reset) leave the toolbar while their groups keep their slots, the Export menu and Copy diagram (see **Export** below) leave the toggle's group, the pressed toggle keeps the focus, and the arrow keys walk Copy, the toggle and the full-screen toggle. The root's `data-aqmd-mermaid-view` is `"diagram"` or `"source"` while a drawing shows, and absent otherwise.
838
+ While the text shows, a Copy button (`copy-source`) comes before the toggle: it writes the text to the clipboard, and the status line (`[data-aqmd-mermaid-notice]`, `role="status"`, empty until it tells something) tells `copiedSource` or `copySourceFailed` (a window without the asynchronous clipboard fails); only the latest press tells its outcome, and closing the text clears the line.
839
+ The choice is not remembered: each diagram opens with its drawing, keeps the choice while it is drawn again (a gantt chart that follows the slot's width is drawn in the hidden frame), and comes back to it after a failure or a hold once it is drawn.
840
+ - **Export**: a host whose diagrams a drawing place draws (see [Drawing place](#drawing-place)) lets a reader keep a diagram as an image file by passing a way to export it: `exporting` (`MermaidExporting`) on `MermaidDiagram`, or `mermaidExporting` (`MermaidDocumentExporting`) on `MarkdownRenderer`, which gives each diagram it renders its number in the document (`index`, from 1, a held diagram counting as well).
841
+ The way's `fileName` names one diagram's file from a `MermaidDiagramFile`: `index`, `accTitle` (the drawing's title, as it names the frame, or `null`) and `format` (`"svg"` or `"png"`); `pngScale`, a positive finite number, multiplies the export drawing's own size for the PNG, which is then scaled down in proportion to the largest canvas every browser draws (4096 × 4096 pixels, and at most 32,767 on a side).
842
+ While a drawing shows (not while it loads, after a failure, while it is held, for a diagram of white space alone, nor while the text shows), the Source toggle's group holds before the toggle the Export menu (`export`, named by `exportMenu`) and Copy diagram (`copy-diagram`): the menu holds Save as SVG (`save-svg`) and Save as PNG (`save-png`), and Copy as SVG (`copy-svg`) only in a browser whose `ClipboardItem.supports` says yes to `image/svg+xml`.
843
+ Each asks the drawer for the export form of the shown drawing (see **Export form** under [Drawing place](#drawing-place)): the request the drawing was drawn with, in the light scheme whatever `theme` says, so every file keeps the light ground. The SVG file is the finished export drawing's markup (`image/svg+xml`), and the PNG that drawing drawn as above.
844
+ The PNG is drawn from a blob URL of the page, as an SVG image's copy is (see [SVG images](#svg-images)), so a page whose content security policy limits `img-src` (or, without one, `default-src`) must list `blob:` there: without it Save as PNG and Copy diagram fail (`saveFailed`, `copyDiagramFailed`), while Save as SVG and Copy as SVG, which draw no image, still save and copy.
845
+ Copy diagram (a PNG) and Copy as SVG write one clipboard item within the press, before the drawer answers (Safari refuses a write begun after the press), holding the image and the diagram's text without its leading and trailing white space (`text/plain`); a window without the asynchronous clipboard (`navigator.clipboard.write` and `ClipboardItem`) fails the copy without asking the drawer.
846
+ A save calls `fileName` first: a name that is not a non-empty string, or a `fileName` that throws, fails the save without asking the drawer (a file without a name would take one the browser makes from its URL); the file then goes to the browser's download under that name, through a hidden link with `download` whose object URL is released on the next task.
847
+ The status line tells `copiedDiagram`, `saveStarted` (with `{name}`, the file's name) or, when the drawing place refuses to export the drawing, the notice of its reason with nothing on the console: `notExportableHtmlLabel` (a label Mermaid draws only as HTML), `notExportableUnsized` (a root without a usable `viewBox`) or `notExportableUnlikeText` (the export drawing's text differs from the shown drawing's), so a reader always learns that the diagram was not exported, and why.
848
+ A refusal for a reason the package does not know (as a host's own drawer may answer) and any other failure tell `copyDiagramFailed` or `saveFailed` and leave the error, or the name `fileName` answered, on the console. Only the latest press tells its outcome, and a later press or the diagram's removal stops a save whose file is not made yet.
849
+ `exporting` without `drawing`, and `mermaidExporting` without `mermaidDrawing` whatever the document holds, throw a `RangeError` during render, as do a `pngScale` that is not a positive finite number and an `index` that is not a positive safe integer; a way that is not an object, or whose `fileName` is not a function, throws a `TypeError`.
850
+ `MarkdownRenderer` hands its diagrams one stand-in of the way: it calls the `fileName` of the last committed render, and a way the host builds anew with the same `pngScale` on every render (an object and a closure, as while a stream writes the document) keeps the blocks it kept (see [Text that grows](#text-that-grows)), while a new `pngScale` drops them as its other props that shape the elements do.
851
+ The drawing place's real-browser check (`check:mermaid-frame-browser`) checks the export in Chromium, Firefox and WebKit: every sample it compares by pixel, and a flowchart whose labels break their lines with `<br>` alone, draws in the export form, in both schemes, with its labels as SVG text, the shown drawing's characters, its own size and its ground under everything,
852
+ except those the drawing place refuses as Mermaid 11.16.0 draws them, each for its reason (an event model's labels, drawn only as HTML, for `html-label`; the info diagram, whose root has no `viewBox`, for `unsized`; and the flowchart sample, whose bold, table, list and Font Awesome icon the export form writes out as characters, for `unlike-text`);
853
+ the package's PNGs of each take that size, show the ground wherever the drawing leaves the image clear, away from the edges of what it paints, and paint the text colour where the texts lie.
854
+ Through the component it checks that Save as SVG and Save as PNG download their files under the name `fileName` gives, that Copy diagram puts the PNG and the text on Chromium's clipboard, and that on a page whose policy limits `img-src` without `blob:` Save as PNG and Copy diagram fail while Save as SVG and Copy as SVG still save and copy.
798
855
  - **Tall diagrams**: under a coarse pointer the frame is at most `calc(100svh - 2 * 2.75rem)` tall, so two 44 px bands of the page stay outside it wherever it sits and a finger can scroll the page past the diagram; the clipped drawing then overflows and pans by finger.
799
856
  - **Touch menu**: under a coarse pointer the menu button is named by `interactionModeTouch` and the menu lists four items, `none`, `zoom`, `pan` and `both`, worded for touch (see [Labels and languages](#labels-and-languages)); the checked item is the touch counterpart of the mode in force (`pan-shift` shows `pan`, `both-shift` shows `both`), and choosing an item sets that mode. Escape closes a menu and returns the focus to its button.
800
- - **Colours and focus ring**: the controls, the menu items, the checked item, the error message and the retry button reach 7:1 against their surfaces in both schemes (dark when `.dark` or `[data-theme="dark"]` is on an ancestor). The focus ring of the frame, the toolbar controls and the retry button is a 2 px `#003abc` outline with a white 4 px halo, 9:1 apart, so some part of it stands out on any background (WCAG 2.4.13, 1.4.11); the menu items draw it inset. The ring's rules sit outside every cascade layer, so the controls' `shadow` utility cannot replace the halo.
801
- - **Hooks**: `data-aqmd-mermaid` (the root, which carries the palette's CSS variables, and `data-aqmd-fullscreen` while full screen), `data-aqmd-fullscreen-dialog`, `data-aqmd-mermaid-frame`, `data-aqmd-mermaid-toolbar`, `data-aqmd-mermaid-control` (`mode`, `zoom-in`, `zoom-out`, `reset`, `pan-left`, `pan-up`, `pan-down`, `pan-right` or `fullscreen`), `data-aqmd-mermaid-menu`, `data-aqmd-mermaid-error` and `data-aqmd-mermaid-retry`. The component writes the drawing's natural aspect ratio on its `<svg>` as `--aqmd-mermaid-ratio`, which the full-screen layout reads.
857
+ - **Colours and focus ring**: the controls, the menu items, the checked item, the error message (with the diagram's text below it, which a display style colours as its code blocks: the None, GitHub and Zenn styles keep it at 7:1 too, under every colour pair and without one) and the retry button reach 7:1 against their surfaces in both schemes (dark when `.dark` or `[data-theme="dark"]` is on an ancestor).
858
+ The focus ring of the frame, the toolbar controls, the source region and the retry button is a 2 px `#003abc` outline with a white 4 px halo, 9:1 apart, so some part of it stands out on any background (WCAG 2.4.13, 1.4.11); the menu items draw it inset. The ring's rules sit outside every cascade layer, so the controls' `shadow` utility cannot replace the halo.
859
+ - **Hooks**: `data-aqmd-mermaid` (the root, which carries the palette's CSS variables, `data-aqmd-mermaid-view` while a drawing shows, and `data-aqmd-fullscreen` while full screen), `data-aqmd-fullscreen-dialog`, `data-aqmd-mermaid-frame`, `data-aqmd-mermaid-toolbar`, `data-aqmd-mermaid-control` (`mode`, `zoom-in`, `zoom-out`, `reset`, `pan-left`, `pan-up`, `pan-down`, `pan-right`, `export`, `copy-diagram`, `copy-source`, `source` or `fullscreen`), `data-aqmd-mermaid-menu`, `data-aqmd-mermaid-error`, `data-aqmd-mermaid-held`,
860
+ `data-aqmd-mermaid-export-menu` (the Export menu), `data-aqmd-mermaid-export-item` (`save-svg`, `save-png` or `copy-svg`), `data-aqmd-mermaid-source` (the text of an error, a hold or the source view), `data-aqmd-mermaid-notice` and `data-aqmd-mermaid-retry`.
861
+ The component writes the drawing's natural aspect ratio on its `<svg>` as `--aqmd-mermaid-ratio`, which the full-screen layout reads.
862
+
863
+ #### Drawing place
802
864
 
803
865
  `@aiquants/markdown/mermaid-frame` (`dist/mermaidFrame/frame.js`, with the licenses of the code inside it in `NOTICES.md`
804
866
  beside it) is the script of a drawing place: one self-contained file, Mermaid without KaTeX, that a frame document loads
805
867
  as a module script to draw the diagrams sent to it over a message port, with every key of Mermaid's configuration
806
- locked. The components above draw diagrams in the page and do not load it.
868
+ locked: every top-level key of its type and the name of every key at every level of its default configuration, so
869
+ nothing a diagram writes (its `%%{init}%%` and `%%{wrap}%%` directives, its front matter's `config`) changes how it is
870
+ drawn, wherever it writes a key. A text Mermaid draws only as its error picture (the bare word `error`) fails as Mermaid's failure, as no
871
+ diagram, so the page shows it as it shows every text that is no diagram, and a diagram of a type the drawing place does
872
+ not draw fails, unpainted, as a type it does not draw (see **Types** in [Mermaid diagrams](#mermaid-diagrams)). It draws in the package's diagram palette for the request's colour scheme rather than Mermaid's: every colour
873
+ variable of Mermaid's `base` theme takes a role of the palette (the ground, the text, four surfaces, the line, 12 series
874
+ colours and the text on a series), as do the colours of C4's shapes, sankey's links and journey's first 12 actors, and
875
+ xychart and sankey label their values. In the frame, what Mermaid draws is then repainted in that palette, reading the
876
+ frame's browser for what lies under what: a palette colour keeps its place, any other fill or line moves to the palette
877
+ colour nearest it in OKLab of its kind (a grey to a neutral role, a hue to a coloured one) among those its use allows,
878
+ and a translucent fill is not painted and a translucent line is made opaque. Every line narrower than 1 CSS px at the
879
+ size the frame draws it is widened to 1 CSS px (a marker's content at the scale of the lines it sits on): a thinner one
880
+ only shows as pixels it covers less than half of, paler than its paint. A line of the ground's colour stays only as the
881
+ gap outlining an opaque fill, and otherwise moves to the nearest colour of its kind that stands out 3:1 on the ground
882
+ and on every surface. Every line and every marker's content then takes the first of its paint and the text on a series
883
+ that reaches 3:1 on everything under it, passing over what bears its paint (its own shape, a gap). Where neither does
884
+ and the line lies only on fills it does not stand out on, those fills move to the nearest ground or surface of their
885
+ kind and the lines are decided again; a line other than a marker's content that still has neither but stands out on the
886
+ ground gets a casing of the ground 1 px wider on each side, laid just before it. The pie's outer ring is not drawn.
887
+ Every text takes the first text role that reaches 7:1 on everything under it, read down the middle of each character and
888
+ on both sides of every edge that crosses it, on a backing of the ground where none does or where it lies on a picture
889
+ (behind an SVG text, 1 CSS px wider on each side than its box, so the edges of its glyphs stay on the backing), and a
890
+ decoration line is drawn in its element's text colour, or, for an element holding no text of its own, in the colour of
891
+ the first text inside it (an SVG group around the HTML of a `foreignObject` among them). A
892
+ text that a later shape paints over, down the middle of a character or where its glyphs sit (a thin line between two
893
+ characters), is moved above it first, and gradients (as their first stop's colour), filters, patterns, opacity, blend
894
+ modes, shadows and the colours of the diagram's sheets are removed. The repainted drawing holds
895
+ its paints only in `style` attributes (`fill`, `stroke`, `color` and `background-color`, each a palette colour, `none`
896
+ or `transparent`, and `text-decoration` with its line and style only), and no colour, translucency or effect in a sheet
897
+ or a presentation attribute. A drawing that cannot be repainted fails as the drawing place's own failure.
898
+
899
+ A host has the components draw their diagrams in a drawing place by passing one: `drawing` (`MermaidDrawing`) on
900
+ `MermaidDiagram`, or `mermaidDrawing` on `MarkdownRenderer`, which passes it with its own `theme` to every diagram it
901
+ renders. A `MermaidDrawing` holds the drawer, which `createMermaidDrawer` returns (or a host's function that hands each
902
+ request on to one), and the two limits every request carries, each a positive safe integer: `maxChars`, the most UTF-16
903
+ code units of a diagram's text, and `maxEdges`, the most edges of a flowchart. Without a drawing place a diagram is drawn
904
+ in the page as above, and nothing loads the drawing place's script.
905
+
906
+ ```tsx
907
+ import frameScriptUrl from "@aiquants/markdown/mermaid-frame?url" // with Vite: the URL the bundler emits for the script
908
+ import { createMermaidDrawer, MarkdownRenderer, type MermaidDrawing } from "@aiquants/markdown"
909
+
910
+ // One drawer for the page, made in the browser: createMermaidDrawer throws outside a window
911
+ let pageDrawing: MermaidDrawing | undefined
912
+ const drawingOfPage = (): MermaidDrawing => {
913
+ pageDrawing ??= {
914
+ // fontStylesheetUrls: the stylesheets that declare the page's web fonts, if it uses any
915
+ drawer: createMermaidDrawer({ frameScriptUrl, fontStylesheetUrls: [] }),
916
+ maxChars: 50_000,
917
+ maxEdges: 500,
918
+ }
919
+ return pageDrawing
920
+ }
921
+
922
+ // In a component rendered in the browser
923
+ <MarkdownRenderer htmlContent={htmlContent} theme="dark" mermaidDrawing={drawingOfPage()} />
924
+ ```
925
+
926
+ - **The drawer**: `createMermaidDrawer({ frameScriptUrl, fontStylesheetUrls })` makes the function that draws one
927
+ diagram (`MermaidDrawer`); make one per page, in the browser (outside a window it throws a `TypeError`).
928
+ `frameScriptUrl` is the URL of `@aiquants/markdown/mermaid-frame` as the host's bundler emits it, and
929
+ `fontStylesheetUrls` lists the stylesheets that declare the faces of the fonts the page's slots use (empty when the
930
+ page uses no web font), so the frame measures each label in the face the page shows it in. Each must be an `https:`
931
+ or `http:` URL of the page's origin, since the frame's content security policy takes scripts, stylesheets and fonts
932
+ from that origin only: one that is empty or does not parse throws a `TypeError`, and any other a `RangeError`, as
933
+ does a page whose origin has an IPv6 address, which no content security policy takes as a source. The font files the
934
+ sheets name must be of the page's origin too: the drawer does not read the sheets, the frame's policy refuses a font
935
+ file of any other origin, and Mermaid then measures the labels in the next font of the family rather than in the face
936
+ the page shows them in (the frame logs the face that did not load to the console).
937
+ - **The frame**: the drawer makes its frame at the first diagram, a `srcdoc` frame of the page's origin under its own
938
+ content security policy (scripts, stylesheets and fonts of the page's origin, inline styles and `data:` images,
939
+ nothing else), out of sight, focus and the accessibility tree, and draws the diagrams there one at a time in the order
940
+ they were requested. The frame also runs under the page's own policy, so its script must be one the page's
941
+ `script-src` takes: a page whose policy names no `script-src` (only `base-uri`, `object-src`, `frame-src` and
942
+ `frame-ancestors`, say) draws, and neither `frame-src` nor `frame-ancestors` refuses the frame, while on a page whose
943
+ `script-src` takes only a nonce the script never runs and every diagram fails as the drawing place's failure.
944
+ The frame's styles come under the page's policy too, as do those of the copies the page shows (Mermaid writes
945
+ `<style>` elements and `style` attributes, and the cleaning keeps the ones it allows), so the page's `style-src` (or,
946
+ without one, its `default-src`) must take `'unsafe-inline'`: on a page whose policy does not, the frame measures the
947
+ labels in other boxes, the copies lose their styles and show other pixels, and a drawing whose painting falls off the
948
+ diagram palette without them fails as the drawing place's failure.
949
+ A frame that loads without listening (its script did not load or threw) fails the diagrams sent to it and is removed;
950
+ one that loads again (moved in the page) fails the diagrams it held and is connected anew; one that leaves the page
951
+ (removed, or the body replaced) fails them at once, and one that left unseen (the root element replaced) at the next
952
+ diagram. The next diagram makes a new frame, and a diagram already shown stays, as it is a copy in the page.
953
+ - **Requests**: each drawing requests the diagram's text without its leading and trailing white space, `theme`
954
+ (`"light"` by default; unread without a drawing place), the shown form (`form: "shown"`; see **Export form** below),
955
+ the slot's width, the measuring element's computed `font-family`, the `lang` written on the slot or its nearest
956
+ ancestor that has one, as written and also across a shadow root to its host (empty when none has), and the two limits.
957
+ The page's Mermaid is neither imported nor set up for such a diagram, and its drawings take none of the lane, the
958
+ drawing hosts and the retry by itself above. It still waits for its slot's width, and a gantt chart, which the
959
+ `aria-roledescription` of the cleaned drawing's root names (the shown copy's root takes the type's name instead), is
960
+ drawn again when that width changes.
961
+ - **Insertion**: each insertion shows its own copy of the cleaned drawing, imported into the page's document: every id
962
+ of the copy takes the insertion's prefix (`aqmd-mmd-`, 16 random hexadecimal digits and `-`) and every reference
963
+ follows it, so no two insertions share a name, nor an insertion and the page, and a reference to an id the diagram
964
+ does not hold is dropped. The page keeps the ids that start with `aqmd-mmd-` for these copies: a host gives no id and
965
+ no id prefix of its own that start with it. Every class of the drawing starts with `aqmd-mmd-` too, so no class rule
966
+ of the page styles it. The copy sits in the open shadow root of the frame's only child, `[data-aqmd-mermaid-drawing]`
967
+ (a new one for each insertion, which pan and zoom move), so no rule of the page reaches it either, not even one for
968
+ the elements of a label's HTML, such as a display style's margins of a table or a list, which would make the label
969
+ overflow the box the drawing place measured; only inherited properties pass in. The page reaches the copy's `<svg>`
970
+ through its part names: `drawing`, and also `scalable` when it has a `viewBox`
971
+ (`[data-aqmd-mermaid-drawing]::part(drawing)`); nothing inside the copy has a part name. The frame shows the copy on
972
+ the diagram palette's ground of the scheme the drawing was painted for, whatever the page's scheme, so every text and
973
+ line stands on the ground its contrast was reached on (a diagram drawn in the page keeps the frame's white ground,
974
+ light grey under a dark ancestor).
975
+ - **Types**: the drawing place draws the types of diagram in `MERMAID_DRAWABLE_TYPES` (with its type
976
+ `MermaidDrawableType`): each entry holds Mermaid's name of the type (`type`, as Mermaid's detection and the drawn
977
+ root's `aria-roledescription` give it) and the word a writer writes first on the diagram's first line to draw it
978
+ (`header`), in the order Mermaid registers and tries its detectors; the list and its entries are frozen. It holds every
979
+ type Mermaid 11.16.0 registers that the drawing place's configuration reaches but four: `flowchart-elk`, which needs a
980
+ layout loader the drawing place does not register, and three that leave a value or a name nowhere but in a colour,
981
+ `treemap` (it hides the names and values of cells too small to hold them), `radar` (its series differ only in colour)
982
+ and `journey` (its actors on each task differ only in colour). The drawing place refuses a diagram of any other type
983
+ once Mermaid has drawn it, by Mermaid's own detection, as `{ kind: "unlisted-type", type }` with Mermaid's name of the
984
+ type, before painting it; a diagram drawn in the page, without `drawing`, draws every type the page's Mermaid draws.
985
+ A host can tell its writers by the headers which types its diagrams may take.
986
+ - **Failures**: a diagram the drawing place did not draw shows why (see **Errors** above): a text over `maxChars` shows
987
+ `tooLarge` and a flowchart over `maxEdges` shows `tooManyEdges`, each filled with the failure's numbers, and a diagram
988
+ of a type the drawing place does not draw shows `unlistedType` (see
989
+ [Labels and languages](#labels-and-languages)); Mermaid's refusal, the drawing place's own failure and a refusal to
990
+ export (which the drawer gives only to the export form, though a host's drawer may give it to any request) show their
991
+ words (`renderFailed` when they say nothing); a drawer that rejects the request (a `TypeError` or a `RangeError` for
992
+ an invalid one, such as a limit that is not a positive safe integer) or throws shows the error's words; and an answer
993
+ that holds no cleaned drawing shows `renderFailed`. The retry button asks the drawer again. An answer or a refusal
994
+ that arrives after a newer drawing was requested, after the text, `drawing` or `theme` changed or after the component
995
+ unmounted is discarded.
996
+ - **Changes**: the fields of `drawing` and `theme` take effect each on its own, so a `MermaidDrawing` made anew with
997
+ the same fields on every render draws nothing again, and a change of any of them draws the diagram again; a `drawer`
998
+ that is not a function throws a `TypeError` during render. `MarkdownRenderer` takes `mermaidDrawing` as it takes its
999
+ other props that shape the elements (see [Text that grows](#text-that-grows)): a new value drops the blocks it kept,
1000
+ so pass a stable one.
1001
+ - **Export form**: a host that keeps a diagram as an image file asks its drawer for the export form (`form: "export"`),
1002
+ in either scheme and with the other fields as above; the components ask for the shown form to show a diagram, and
1003
+ for the export form in the light scheme when a reader exports it (see **Export** in
1004
+ [Mermaid diagrams](#mermaid-diagrams)), and any other `form` is a `RangeError`.
1005
+ The drawing place then draws every label Mermaid can as SVG text, with `htmlLabels` off at the top
1006
+ level and for flowcharts, which no diagram turns back on, as not every reader of an image file draws the HTML of a
1007
+ `foreignObject`. The answer goes through the cleaning and the palette check of a shown one and is then finished as an
1008
+ image file keeps it: the root's `width` and `height` become the width and the height of its `viewBox` and its style
1009
+ loses `max-width`, so the file has a size of its own rather than the slot's (`width="100%"`), and a rectangle of the
1010
+ diagram palette's ground for the scheme, covering the `viewBox`, is laid under everything the diagram draws, after the
1011
+ root's leading `<title>` and `<desc>`, so the image keeps the ground its contrast was reached on. A drawing that still
1012
+ holds a `foreignObject` (a label Mermaid draws only as HTML) or whose root has no `viewBox` of a positive width and
1013
+ height fails as not exportable (`{ kind: "not-exportable", reason, message }`, a `MermaidDrawFailure` whose `reason`,
1014
+ a `MermaidNotExportableReason`, is `"html-label"` or `"unsized"`), and one whose painting falls off the palette fails
1015
+ first as the drawing place's failure, as in the shown form; either failure is the outcome at once. Otherwise the
1016
+ drawer compares the export drawing with the same request drawn in the shown form, which it asks for right after the
1017
+ export form and before any later request (an export request costs the frame two drawings): the characters of each,
1018
+ their text and CDATA outside `style`, `title` and `desc` (of an SVG `switch`, only those of its first element child,
1019
+ the one it draws, so a label written twice, as HTML and as a `text` to fall back on, counts once) with white
1020
+ space aside, in sorted order, so neither where a label breaks its lines (`<br>` in the shown form, the lines of a
1021
+ `text` in the export form) nor the order the labels are written in counts. An export whose characters differ, as when a label holds formatting or an icon the export form
1022
+ writes out as characters, fails as not exportable for `"unlike-text"` rather than make a file whose text says
1023
+ something else than the diagram shown, and a failure of the shown drawing is the outcome as it is. A host that tells
1024
+ its readers the outcome can thus always say that a diagram was not exported, and why. The finished drawing holds no
1025
+ font face (the cleaning drops every at-rule), so wherever the image is read or drawn its labels take the faces of
1026
+ their family found there: with web fonts in the slots, the image may show other faces than the frame measured the
1027
+ labels in, and a label may then overflow its box. A host that keeps drawings keys them by the form as well.
807
1028
 
808
1029
  ### Spreadsheets
809
1030
 
@@ -1284,7 +1505,9 @@ The display popover's keys of `MarkdownViewerLabels`, all optional and all marke
1284
1505
 
1285
1506
  `missingImage` is the notice of an image that cannot be found (`missingImageLabel` on `MarkdownRenderer`; "Image not found", marked `lang="en"`).
1286
1507
 
1287
- The Mermaid keys of `MermaidDiagramLabels`, all optional (the viewer's key for each is `mermaid` followed by the key with a capital first letter: `panUp` is `mermaidPanUp`; `errorPrefix` alone is the viewer's own `errorPrefix`, one text for the viewer's error and the diagrams'):
1508
+ The Mermaid keys of `MermaidDiagramLabels`, all optional (the viewer's key for each is `mermaid` followed by the key with a capital first letter: `panUp` is `mermaidPanUp`; `errorPrefix` alone is the viewer's own `errorPrefix`, one text for the viewer's error and the diagrams'; `tooLarge`, `tooManyEdges` and `unlistedType`, which only a diagram drawn in a drawing place shows, have no viewer key, as the viewer draws its diagrams in the page, and neither have the twelve labels of the export (`exportMenu` to `notExportableUnlikeText` in the table), for the same reason;
1509
+ nor have `openStreaming`, `openCut` and `tooManyDiagrams`, which only a held diagram shows, as the viewer holds none).
1510
+ A text written as a template fills its `{name}` placeholders with the failure's numbers, the hold's limit, or the saved file's name; a replacement uses the same names, and a placeholder without a value stays as written:
1288
1511
 
1289
1512
  | Key | Names | Built-in text | `lang` |
1290
1513
  | --- | --- | --- | --- |
@@ -1297,11 +1520,70 @@ The Mermaid keys of `MermaidDiagramLabels`, all optional (the viewer's key for e
1297
1520
  | `fullscreen`, `exitFullscreen` | The full-screen toggle, by the way it goes | View full screen / Exit full screen | `en` |
1298
1521
  | `fullscreenDialog` | The block's dialog while full screen | Diagram (full screen) | `en` |
1299
1522
  | `diagram` | The diagram's focusable frame, its toolbar and, outside full screen, the block's dialog | Diagram (arrow keys pan, + and - zoom, 0 resets) | `en` |
1523
+ | `source` | The Source toggle, which shows the diagram's text in place of the drawing and back | Source | `en` |
1524
+ | `sourceRegion` | The focusable region that shows the text, after the drawing's title when it has one | Diagram source | `en` |
1525
+ | `copySource` | The Copy button, shown while the text shows | Copy the source | `en` |
1526
+ | `copiedSource`, `copySourceFailed` | The status line's notice once the text is copied, or when it could not be | Copied the source. / Could not copy the source. | `en` |
1527
+ | `exportMenu` | The Export menu's button, shown while a drawing shows that the host exports (`exporting`) | Export | `en` |
1528
+ | `saveSvg`, `savePng`, `copySvg` | The Export menu's items (`copySvg` only where the clipboard takes SVG) | Save as SVG / Save as PNG / Copy as SVG | `en` |
1529
+ | `copyDiagram` | The Copy diagram button after the Export menu, which copies the drawing as a PNG with the diagram's text | Copy the diagram | `en` |
1530
+ | `copiedDiagram`, `copyDiagramFailed` | The status line's notice once the diagram is copied, or when it could not be | Copied the diagram. / Could not copy the diagram. | `en` |
1531
+ | `saveStarted`, `saveFailed` | The status line's notice once the file's download starts (`{name}`, the file's name), or when the file could not be saved | Started saving {name}. / Could not save the diagram. | `en` |
1532
+ | `notExportableHtmlLabel` | The status line's notice when the drawing place refuses to export the drawing because a label Mermaid draws only as HTML would be missing from the image (`html-label`) | This diagram cannot be copied or saved as an image: some of its labels are drawn as HTML, which not every image viewer shows. | `en` |
1533
+ | `notExportableUnsized` | The status line's notice when the drawing place refuses to export the drawing because its root has no usable `viewBox` to take the image's size from (`unsized`) | This diagram cannot be copied or saved as an image: it has no size of its own to draw the image at. | `en` |
1534
+ | `notExportableUnlikeText` | The status line's notice when the drawing place refuses to export the drawing because its text would differ from the shown diagram's (`unlike-text`) | This diagram cannot be copied or saved as an image: the image's text would differ from the diagram shown, as when a label holds formatting or an icon. | `en` |
1300
1535
  | `retry` | The retry button after a failed drawing | 再試行 | `ja` |
1301
1536
  | `loading` | The notice while a diagram is drawn | Loading diagram... | `en` |
1302
1537
  | `errorPrefix` | The text in front of the reason a diagram could not be drawn | Error: | `en` |
1303
1538
  | `initializationFailed`, `renderFailed` | The reason when Mermaid could not be set up, or a drawing failed, and the error says nothing itself (one that says something shows its own words) | Mermaid failed to initialize globally. / An unknown error occurred while rendering the diagram. | `en` |
1304
1539
  | `emptyDrawing` | The reason when Mermaid answers an empty drawing | Failed to render Mermaid diagram: SVG content is empty or invalid. | `en` |
1540
+ | `tooLarge` | The reason when a diagram's text is longer than the drawing place's `maxChars` (`{length}`, the text's UTF-16 length, and `{limit}`) | The diagram's source is too long ({length} characters; the limit is {limit}). | `en` |
1541
+ | `tooManyEdges` | The reason when a flowchart has more edges than the drawing place's `maxEdges` (`{limit}`) | The diagram has too many edges (the limit is {limit}). | `en` |
1542
+ | `unlistedType` | The reason when the drawing place does not draw the diagram's type (not one of `MERMAID_DRAWABLE_TYPES`; no placeholder) | The diagram is not drawn: its type is not one of the types drawn here. | `en` |
1543
+ | `openStreaming` | The reason of a diagram held while a stream still writes its text (`MarkdownRenderer`'s `streaming`) | The diagram is drawn once its text is complete. | `en` |
1544
+ | `openCut` | The reason of a diagram held because the text stopped before its closing line (`MarkdownRenderer`'s `truncated`) | The diagram is not drawn: the text was cut off before its closing line. | `en` |
1545
+ | `tooManyDiagrams` | The reason of a diagram held past the document's limit (`MarkdownRenderer`'s `maxMermaidDiagrams`; `{limit}`) | The diagram is not drawn: the document draws only its first {limit} diagrams. | `en` |
1546
+ | `typeC4` … `typeRailroad` (the table below) | The role description of a drawn diagram's root, by the diagram's type | C4 diagram … Railroad diagram | `en` |
1547
+
1548
+ The type names (`type…`) name the types Mermaid 11.16 detects, as below (38 types under 31 names); a type
1549
+ without a name has no role description. A drawn diagram's root takes the name as its role description
1550
+ (`aria-roledescription`), an attribute that cannot carry a language of its own: a screen reader reads it in the
1551
+ language the diagram inherits (the document's), whatever the name's built-in `lang`, so a host passes the type names
1552
+ in the document's language.
1553
+
1554
+ | Key | Mermaid's types | Built-in text |
1555
+ | --- | --- | --- |
1556
+ | `typeC4` | `c4` | C4 diagram |
1557
+ | `typeFlowchart` | `flowchart`, `flowchart-v2`, `flowchart-elk` | Flowchart |
1558
+ | `typeSwimlane` | `swimlane` | Swimlane diagram |
1559
+ | `typeEntityRelationship` | `er` | Entity relationship diagram |
1560
+ | `typeGitGraph` | `gitGraph` | Git graph |
1561
+ | `typeGantt` | `gantt` | Gantt chart |
1562
+ | `typeInfo` | `info` | Mermaid information |
1563
+ | `typePie` | `pie` | Pie chart |
1564
+ | `typeQuadrantChart` | `quadrantChart` | Quadrant chart |
1565
+ | `typeXyChart` | `xychart` | XY chart |
1566
+ | `typeRequirement` | `requirement` | Requirement diagram |
1567
+ | `typeSequence` | `sequence` | Sequence diagram |
1568
+ | `typeClass` | `class`, `classDiagram` | Class diagram |
1569
+ | `typeState` | `state`, `stateDiagram` | State diagram |
1570
+ | `typeJourney` | `journey` | User journey |
1571
+ | `typeTimeline` | `timeline` | Timeline |
1572
+ | `typeMindmap` | `mindmap` | Mind map |
1573
+ | `typeKanban` | `kanban` | Kanban board |
1574
+ | `typeSankey` | `sankey` | Sankey diagram |
1575
+ | `typePacket` | `packet` | Packet diagram |
1576
+ | `typeRadar` | `radar` | Radar chart |
1577
+ | `typeBlock` | `block` | Block diagram |
1578
+ | `typeTreeView` | `treeView` | Tree view |
1579
+ | `typeArchitecture` | `architecture` | Architecture diagram |
1580
+ | `typeEventModeling` | `eventmodeling` | Event modeling diagram |
1581
+ | `typeIshikawa` | `ishikawa` | Ishikawa diagram |
1582
+ | `typeVenn` | `venn` | Venn diagram |
1583
+ | `typeTreemap` | `treemap` | Treemap |
1584
+ | `typeWardley` | `wardley` | Wardley map |
1585
+ | `typeCynefin` | `cynefin` | Cynefin diagram |
1586
+ | `typeRailroad` | `railroad`, `railroadEbnf`, `railroadAbnf`, `railroadPeg` | Railroad diagram |
1305
1587
 
1306
1588
  The spreadsheet keys of `SpreadsheetBlockLabels`, all optional (the viewer's key for each is `spreadsheet` followed by the
1307
1589
  key with a capital first letter: `zoomIn` is `spreadsheetZoomIn`). A block takes its built-in texts from the catalog its
@@ -5,7 +5,7 @@ import { CodeBlockLabels } from "./codeBlockLabels.ts";
5
5
  import { DisplayMathLabels } from "./displayMathLabels.ts";
6
6
  import { MarkdownEmbedLabels } from "./embeds/embedLabels.ts";
7
7
  import { MarkdownLinkAttributes } from "./links.ts";
8
- import { MermaidInteractionMode } from "./MermaidDiagram.tsx";
8
+ import { MermaidDocumentExporting, MermaidDrawing, MermaidInteractionMode } from "./MermaidDiagram.tsx";
9
9
  import { MarkdownMathDiagnostic } from "./mathRendering.ts";
10
10
  import { MermaidDiagramLabels } from "./mermaidLabels.ts";
11
11
  import { SpreadsheetEditor } from "./SpreadsheetBlock.tsx";
@@ -38,6 +38,7 @@ type RendererProps = {
38
38
  blockOffsets?: readonly number[];
39
39
  blockKeyEpoch?: number;
40
40
  streaming?: boolean;
41
+ truncated?: boolean;
41
42
  theme?: "light" | "dark";
42
43
  topHeadingLevel?: number;
43
44
  iFrameAllowedDomains?: readonly string[];
@@ -45,6 +46,9 @@ type RendererProps = {
45
46
  embedLabels?: MarkdownEmbedLabels;
46
47
  mermaidInteraction?: MermaidInteractionMode;
47
48
  mermaidLabels?: MermaidDiagramLabels;
49
+ mermaidDrawing?: MermaidDrawing;
50
+ mermaidExporting?: MermaidDocumentExporting;
51
+ maxMermaidDiagrams?: number;
48
52
  codeBlockLabels?: CodeBlockLabels;
49
53
  displayMathLabels?: DisplayMathLabels;
50
54
  spreadsheetEditor?: SpreadsheetEditor;
@@ -74,5 +78,5 @@ type AllowlistProps = {
74
78
  readonly iFrameAllowedDomains?: undefined;
75
79
  };
76
80
  type Props = RendererProps & AllowlistProps;
77
- export declare const MarkdownRenderer: ({ htmlContent, blockOffsets, blockKeyEpoch, streaming, theme, topHeadingLevel, iFrameAllowedDomains, embeds, embedLabels, mermaidInteraction, mermaidLabels, codeBlockLabels, displayMathLabels, spreadsheetEditor, spreadsheetLocale, spreadsheetLabels, spreadsheetTapScrollCircle, spreadsheetScrollBarControls, linkComponent: LinkComponent, missingImageLabel, blockFailedLabel, labelsLang, imageSource, svgImageLabels, onMathDiagnostics, allowlist, imageComponent: ImageComponent, idPrefix, }: Props) => import("react").JSX.Element;
81
+ export declare const MarkdownRenderer: ({ htmlContent, blockOffsets, blockKeyEpoch, streaming, truncated, theme, topHeadingLevel, iFrameAllowedDomains, embeds, embedLabels, mermaidInteraction, mermaidLabels, mermaidDrawing, mermaidExporting, maxMermaidDiagrams, codeBlockLabels, displayMathLabels, spreadsheetEditor, spreadsheetLocale, spreadsheetLabels, spreadsheetTapScrollCircle, spreadsheetScrollBarControls, linkComponent: LinkComponent, missingImageLabel, blockFailedLabel, labelsLang, imageSource, svgImageLabels, onMathDiagnostics, allowlist, imageComponent: ImageComponent, idPrefix, }: Props) => import("react").JSX.Element;
78
82
  export {};
@@ -1,7 +1,23 @@
1
+ import { MermaidDrawer } from "../mermaidFrame/drawer.ts";
2
+ import { MermaidExporting } from "./mermaidExport.ts";
1
3
  import { MermaidInteractionMode } from "./mermaidInteraction.ts";
2
4
  import { MermaidDiagramLabels } from "./mermaidLabels.ts";
5
+ export type { MermaidDiagramFile, MermaidDocumentExporting, MermaidExporting, MermaidSaveFormat } from "./mermaidExport.ts";
3
6
  export { DEFAULT_MERMAID_INTERACTION, type MermaidInteractionMode } from "./mermaidInteraction.ts";
4
7
  export { DEFAULT_MERMAID_DIAGRAM_LABELS, type MermaidDiagramLabels } from "./mermaidLabels.ts";
8
+ export interface MermaidDrawing {
9
+ readonly drawer: MermaidDrawer;
10
+ readonly maxChars: number;
11
+ readonly maxEdges: number;
12
+ }
13
+ export type MermaidHeld = {
14
+ readonly kind: "streaming";
15
+ } | {
16
+ readonly kind: "cut";
17
+ } | {
18
+ readonly kind: "too-many-diagrams";
19
+ readonly limit: number;
20
+ };
5
21
  interface MermaidDiagramProps {
6
22
  chartContent: string;
7
23
  interaction?: MermaidInteractionMode;
@@ -9,6 +25,10 @@ interface MermaidDiagramProps {
9
25
  labels?: MermaidDiagramLabels;
10
26
  labelsLang?: string;
11
27
  sourceLines?: string;
28
+ drawing?: MermaidDrawing;
29
+ theme?: "light" | "dark";
30
+ exporting?: MermaidExporting;
31
+ held?: MermaidHeld;
12
32
  }
13
33
  export declare const MERMAID_REDRAW_DELAY_MS = 200;
14
34
  export declare const MermaidDiagram: import("react").NamedExoticComponent<MermaidDiagramProps>;
@@ -0,0 +1,15 @@
1
+ import { ReactElement } from "react";
2
+ import { ResolvedLabel } from "./labels.ts";
3
+ import { DataHook } from "./toolbar.tsx";
4
+ export type BlockNotice = {
5
+ readonly text: string;
6
+ readonly lang: ResolvedLabel["lang"];
7
+ readonly serial: number;
8
+ };
9
+ export declare const nextBlockNotice: (previous: BlockNotice | null, label: ResolvedLabel) => BlockNotice;
10
+ export type BlockNoticeLineProps = {
11
+ readonly hook: DataHook;
12
+ readonly notice: BlockNotice | null;
13
+ };
14
+ export declare const BlockNoticeLine: ({ hook, notice }: BlockNoticeLineProps) => ReactElement;
15
+ export declare const useLatestCopy: () => (() => AbortSignal);
@@ -0,0 +1 @@
1
+ export declare const saveFile: (contents: Blob, fileName: string, doc: Document) => void;
@@ -0,0 +1,11 @@
1
+ import { MermaidDiagramTypeLabelKey } from "./mermaidLabels.ts";
2
+ export declare const MERMAID_TYPE_LABEL_KEYS: ReadonlyMap<string, MermaidDiagramTypeLabelKey>;
3
+ export interface DrawingTexts {
4
+ readonly title: string | null;
5
+ readonly description: string | null;
6
+ }
7
+ export declare const NO_DRAWING_TEXTS: DrawingTexts;
8
+ export declare const drawingTextsOf: (svg: SVGSVGElement) => DrawingTexts;
9
+ export declare const nameDrawingType: (svg: SVGSVGElement, type: string | null, labels: Readonly<Record<MermaidDiagramTypeLabelKey, {
10
+ readonly text: string;
11
+ }>>) => void;