@heikeson/md-engine 0.5.3 → 0.6.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.
- package/README.en.md +267 -0
- package/README.md +154 -271
- package/dist/{chunk-YJGGJP2V.js → chunk-BMAGJMFB.js} +1 -2
- package/dist/{chunk-OG47YL3H.js → chunk-JUWL5RG7.js} +1 -2
- package/dist/{chunk-EJGRPSVC.js → chunk-OKP7VFRV.js} +234 -143
- package/dist/{chunk-OJQDOFGL.js → chunk-W463Q7LK.js} +2 -4
- package/dist/{chunk-ONVXIYKH.js → chunk-Y3B7I6LZ.js} +140 -19
- package/dist/components/index.d.ts +72 -6
- package/dist/components/index.js +4 -6
- package/dist/editor/index.d.ts +17 -7
- package/dist/editor/index.js +72 -25
- package/dist/index.d.ts +19 -18
- package/dist/index.js +14 -10
- package/dist/locales/en-US.d.ts +1 -0
- package/dist/locales/en-US.js +1 -3
- package/dist/locales/zh-CN.d.ts +1 -0
- package/dist/locales/zh-CN.js +1 -3
- package/dist/mermaid/index.d.ts +1 -15
- package/dist/mermaid/index.js +3 -5
- package/dist/{mermaid-placeholder-DYfFG3_f.d.ts → mermaid-placeholder-D97goALt.d.ts} +0 -3
- package/dist/{render-BxUxfxMc.d.ts → render-Dv1LAIvk.d.ts} +3 -4
- package/dist/styles.css +1 -1
- package/package.json +6 -1
- package/styles/cards.css +0 -1
- package/styles/columns.css +41 -0
- package/styles/files.css +0 -1
- package/styles/image.css +45 -3
- package/styles/index.css +4 -3
- package/styles/mermaid.css +0 -6
- package/styles/timeline.css +89 -0
- package/styles/video.css +28 -0
- package//345/257/271/346/216/245/345/245/221/347/272/246.en.md +765 -0
- package//345/257/271/346/216/245/345/245/221/347/272/246.md +411 -235
- package/dist/chunk-EJGRPSVC.js.map +0 -1
- package/dist/chunk-OG47YL3H.js.map +0 -1
- package/dist/chunk-OJQDOFGL.js.map +0 -1
- package/dist/chunk-ONVXIYKH.js.map +0 -1
- package/dist/chunk-YJGGJP2V.js.map +0 -1
- package/dist/components/index.js.map +0 -1
- package/dist/editor/index.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/locales/en-US.js.map +0 -1
- package/dist/locales/zh-CN.js.map +0 -1
- package/dist/mermaid/index.js.map +0 -1
|
@@ -0,0 +1,765 @@
|
|
|
1
|
+
# Integration Contract
|
|
2
|
+
|
|
3
|
+
[简体中文](./对接契约.md) | English
|
|
4
|
+
|
|
5
|
+
> @file 对接契约.en.md
|
|
6
|
+
> @description Public interface contract for `@heikeson/md-engine`: entries, type signatures, content syntax, data contracts, degradation matrix, host integration, styling and compatibility rules.
|
|
7
|
+
> @created 2026-11-26 15:20 English mirror of `对接契约.md`, aligned with 0.5.4.
|
|
8
|
+
> @status Implemented · 0.5.4
|
|
9
|
+
> @readonly Maintained by @heikeson; do not edit directly — open an issue instead.
|
|
10
|
+
|
|
11
|
+
This file is the **single source of truth** for the engine/host interface. The implementation may change; signatures and behaviour may not. Anything marked "grow only" is a breaking change if violated once.
|
|
12
|
+
|
|
13
|
+
## 0. Quick reference
|
|
14
|
+
|
|
15
|
+
| Host need | Use | See |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Render an article | `<MarkdownRenderer content />` | §5 |
|
|
18
|
+
| Get structure / TOC / positions | `parse(md)`; diagnostics only: `diagnose(md)` | §4 |
|
|
19
|
+
| Store back as Markdown | `serialize(tree)`, `roundtrip(md)` | §6 |
|
|
20
|
+
| Authoring UI | `<MarkdownEditor value onChange />` | §7 |
|
|
21
|
+
| Change language site-wide | `MdEngineProvider` at the root, or `config.locale` | §8 |
|
|
22
|
+
| Re-theme | Override `--lkes-*` variables | §10 |
|
|
23
|
+
| Interactive diagrams | `mermaidComponents` from `/mermaid` | §11 |
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 1. Three contract constraints
|
|
28
|
+
|
|
29
|
+
| # | Constraint | Meaning | Violation counts as |
|
|
30
|
+
|---|---|---|---|
|
|
31
|
+
| C1 | Content syntax grows only | Components are added only; never renamed, removed, re-typed, or given new child names | Historical posts break |
|
|
32
|
+
| C2 | Config API grows only | New options must ship a default; existing fields are never removed or re-typed | Host fails to compile or changes behaviour on upgrade |
|
|
33
|
+
| C3 | Styles ship with the package | Component styles come from the package; hosts override CSS variables only | Styles vanish if the host misses a rebuild |
|
|
34
|
+
|
|
35
|
+
The host explicitly **does no content migration**, so C1 is non-negotiable: this package must not ship a breaking change. C2 covers render config, editor config, `UIText` message keys and diagnostic codes; C3 covers `--lkes-*` variables and package class names.
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## 2. Entries and artifacts
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"name": "@heikeson/md-engine",
|
|
44
|
+
"exports": {
|
|
45
|
+
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
46
|
+
"./editor": { "types": "./dist/editor/index.d.ts", "import": "./dist/editor/index.js" },
|
|
47
|
+
"./components": { "types": "./dist/components/index.d.ts", "import": "./dist/components/index.js" },
|
|
48
|
+
"./mermaid": { "types": "./dist/mermaid/index.d.ts", "import": "./dist/mermaid/index.js" },
|
|
49
|
+
"./locales/zh-CN": { "types": "./dist/locales/zh-CN.d.ts", "import": "./dist/locales/zh-CN.js" },
|
|
50
|
+
"./locales/en-US": { "types": "./dist/locales/en-US.d.ts", "import": "./dist/locales/en-US.js" },
|
|
51
|
+
"./styles.css": "./dist/styles.css",
|
|
52
|
+
"./styles/*": "./styles/*"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": { "react": ">=19", "react-dom": ">=19", "mermaid": ">=11" },
|
|
55
|
+
"peerDependenciesMeta": { "mermaid": { "optional": true } },
|
|
56
|
+
"engines": { "node": ">=20" }
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
| Entry | Contents | Constraint |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `@heikeson/md-engine` | `parse`, `diagnose`, `serialize`, `roundtrip`, `normalizeMarkdown`, `MarkdownRenderer`, registry constants, component map, locale/message helpers, types | **SSR safe**: no top-level `window`/`document`; no mermaid, no CodeMirror |
|
|
63
|
+
| `@heikeson/md-engine/editor` | `MarkdownEditor`, editor types, reusable text actions, `INSERTABLE_BLOCKS` | File starts with `"use client"`; must **not** be re-exported from the main entry |
|
|
64
|
+
| `@heikeson/md-engine/components` | `mdxComponents` and every container component | Thin shells, no duplicate rendering logic |
|
|
65
|
+
| `@heikeson/md-engine/mermaid` | `mermaidComponents`, `MermaidChart`, theme API, SVG/PNG export helpers | **Client-only**: the bundle carries no `"use client"` (bundlers strip directives), so a host client component must import it; degrades to source when mermaid is absent |
|
|
66
|
+
| `@heikeson/md-engine/styles.css` | Semantic classes and default CSS variables (esbuild bundle, `dist/styles.css`) | `@import` only; never edit package class names |
|
|
67
|
+
| `@heikeson/md-engine/styles/*` | Per-component slices (e.g. `styles/callout.css`) | Opt-in import; tokens live in `styles/tokens.css` and must come first |
|
|
68
|
+
| `@heikeson/md-engine/locales/zh-CN` | Chinese bundle `zhCN` | Plain message table, no runtime side effects |
|
|
69
|
+
| `@heikeson/md-engine/locales/en-US` | English bundle `enUS` | Same |
|
|
70
|
+
|
|
71
|
+
**Artifacts**: the package ships `dist/` (JS + `.d.ts`) and `dist/styles.css`; `styles/` ships as-is; **source is not published**. No `transpilePackages` needed, and **no Tailwind**: styles are plain CSS, colors go through `--lkes-*` tokens. `styles/engine.css` remains a forwarding entry, so old import paths keep working.
|
|
72
|
+
|
|
73
|
+
**Module format**: ESM-only. `exports` declares `import` conditions only, no `require`; CommonJS consumers need their own bundling or interop layer. Adding a CJS entry is a compatibility decision reserved for the repository owner.
|
|
74
|
+
|
|
75
|
+
**Stability tiers**: the names and signatures listed in §3–§8, §10 and §11 are contract. Low-level helpers such as `jsxBlocks`, `jsxFromMarkdown` and `extractBlocks` are usable by hosts, but only "will not be removed" is promised — their exact signatures are not.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 3. registry
|
|
80
|
+
|
|
81
|
+
The single source of truth for syntax. Parsing, serialization and the editor block UI all read it; component and attribute names must not be hardcoded anywhere else.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
export type ComponentMode = "visual" | "source";
|
|
85
|
+
|
|
86
|
+
export interface ComponentSpec {
|
|
87
|
+
/** Component name, capitalised, case-sensitive */
|
|
88
|
+
readonly name: string;
|
|
89
|
+
/** visual: structured editing; source: handled as a source block only */
|
|
90
|
+
readonly mode: ComponentMode;
|
|
91
|
+
/** Child component name; a single string, or an array when kinds are mixed (Files → ["Folder","File"]) */
|
|
92
|
+
readonly items?: string | readonly string[];
|
|
93
|
+
/** Allowed string attributes */
|
|
94
|
+
readonly attrs?: readonly string[];
|
|
95
|
+
/** Allowed boolean attributes (bare, no value) */
|
|
96
|
+
readonly boolAttrs?: readonly string[];
|
|
97
|
+
/** Leaf component, self-closing allowed (e.g. `<Image />`) */
|
|
98
|
+
readonly selfClosing?: boolean;
|
|
99
|
+
/** Attribute defaults */
|
|
100
|
+
readonly defaultAttrs?: Readonly<Record<string, string | boolean>>;
|
|
101
|
+
/** Container body is raw text (not parsed as Markdown); default false */
|
|
102
|
+
readonly rawBody?: boolean;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ItemSpec {
|
|
106
|
+
readonly name: string;
|
|
107
|
+
readonly attrs?: readonly string[];
|
|
108
|
+
readonly boolAttrs?: readonly string[];
|
|
109
|
+
readonly selfClosing?: boolean;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Max container nesting depth (containers only; child items do not count) */
|
|
113
|
+
export const MAX_CONTAINER_DEPTH = 3;
|
|
114
|
+
|
|
115
|
+
export const COMPONENTS: Readonly<Record<string, ComponentSpec>>;
|
|
116
|
+
export const ITEMS: Readonly<Record<string, ItemSpec>>;
|
|
117
|
+
|
|
118
|
+
export function getComponent(name: string): ComponentSpec | undefined;
|
|
119
|
+
export function getItemSpec(name: string): ItemSpec | undefined;
|
|
120
|
+
/** Every container name, for editor menus and validation */
|
|
121
|
+
export function listComponents(): string[];
|
|
122
|
+
export function isContainerWithItems(name: string): boolean;
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### 3.1 Containers
|
|
126
|
+
|
|
127
|
+
| name | mode | items | Attributes | Notes |
|
|
128
|
+
|---|---|---|---|---|
|
|
129
|
+
| `Callout` | visual | — | `type` (default `note`), `title`, `icon` | Body is still Markdown; `icon` as emoji/short text replaces the default icon |
|
|
130
|
+
| `Tabs` | visual | `Tab` | — | ←/→/Home/End keyboard switching, WAI-ARIA |
|
|
131
|
+
| `Steps` | visual | `Step` | — | Ordered steps |
|
|
132
|
+
| `Cards` | visual | `Card` | — | Card links |
|
|
133
|
+
| `Accordion` | visual | `AccItem` | — | Optional default-expanded item |
|
|
134
|
+
| `Files` | visual | `Folder`, `File` | — | Mixed children allowed |
|
|
135
|
+
| `TypeTable` | visual | `TypeItem` | — | Header labels come from `UIText` |
|
|
136
|
+
| `Columns` | visual | `Column` | — | Horizontal columns; stacks into one column below 640px |
|
|
137
|
+
| `Timeline` | visual | `TimelineItem` | — | Vertical timeline, marker colour follows the item `type` |
|
|
138
|
+
| `Video` | visual | — | `src`, `poster`, `caption`, `width` | Self-closing; `src` / `poster` go through the same protocol allow-list as `Image`; `width` uses the same grammar as `Image` (`auto` / percentage / fraction / pixels / length) |
|
|
139
|
+
| `Image` | visual | — | `src`, `alt`, `align` (default `center`), `width`, `caption`, boolean `zoom` | Self-closing; `width` accepts `auto` (default, natural size), `50%` (share of the column), `1/2` (fraction, same as a percentage), `360` (pixels) or `20rem` (length); values above 100% are clamped to 100% and invalid ones fall back to `auto`; `align` only accepts `left`/`center`/`right`, positions the whole figure including the caption (no float), anything else falls back to `center`; images are `loading="lazy"` `decoding="async"`; `zoom` opens with Enter / Space and closes with Esc or a click |
|
|
140
|
+
| `div` | visual | — | `class`, `id` | Attributes pass through to the DOM, no wrapper component; body parsed as Markdown |
|
|
141
|
+
| `Mermaid` | source | — | `title`, `height` | `rawBody` + self-closing; body is **raw text** |
|
|
142
|
+
|
|
143
|
+
### 3.2 Child items
|
|
144
|
+
|
|
145
|
+
| name | Attributes | Boolean attributes | Self-closing | Notes |
|
|
146
|
+
|---|---|---|---|---|
|
|
147
|
+
| `Tab` | `value` | `default` | — | Label comes from the body |
|
|
148
|
+
| `Step` | `title` | — | — | Step title |
|
|
149
|
+
| `Card` | `title`, `href`, `icon`, `description` | — | yes | Description may be an attribute or the body |
|
|
150
|
+
| `AccItem` | `title`, `type` (`open` / `close`) | — | — | `#id` deep-link match wins over `type` |
|
|
151
|
+
| `Folder` | `name` | `defaultOpen` | — | File-tree directory |
|
|
152
|
+
| `File` | `name`, `href`, `icon` | — | yes | Renders as a link when `href` is given |
|
|
153
|
+
| `TypeItem` | `name`, `type`, `default` | `required` | yes | Description column via body or left empty |
|
|
154
|
+
| `Column` | `width` | — | — | Bare number splits by ratio, value with a unit (`px` / `%` / `rem` / `em` / `ch` / `vw`) sets a fixed width; omitted means equal split |
|
|
155
|
+
| `TimelineItem` | `date`, `title`, `type` (`note` / `tip` / `warning` / `danger`) | — | — | Unknown `type` renders as `note` |
|
|
156
|
+
|
|
157
|
+
Rules:
|
|
158
|
+
|
|
159
|
+
1. Names are **case-sensitive**; `Tab` and `tab` are different names.
|
|
160
|
+
2. Attribute values are strings only; boolean attributes must be bare (`default`, `zoom`). `{...}` expressions are unsupported — such an open tag falls back to plain HTML/text, producing no container and no error.
|
|
161
|
+
3. Child items only carry meaning inside their container. A top-level `<Tab>` still parses as a block, but it is not in `listComponents()`, so the editor shows no container UI.
|
|
162
|
+
4. Adding a component means editing `registry` plus shipping the implementation and docs; declarations only grow.
|
|
163
|
+
|
|
164
|
+
---
|
|
165
|
+
|
|
166
|
+
## 4. parse
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
export interface ParseOptions {
|
|
170
|
+
/** Override the nesting limit; defaults to MAX_CONTAINER_DEPTH */
|
|
171
|
+
maxDepth?: number;
|
|
172
|
+
/**
|
|
173
|
+
* Extract the flat block index, default true
|
|
174
|
+
* @description When false, extractBlocks is skipped and `ParseResult.blocks` is an empty array;
|
|
175
|
+
* diagnostics, serialization and rendering are unaffected
|
|
176
|
+
*/
|
|
177
|
+
blocks?: boolean;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export interface ParseResult {
|
|
181
|
+
tree: Root; // mdast with containers as custom nodes
|
|
182
|
+
blocks: Block[]; // flat block index, in document order
|
|
183
|
+
diagnostics: Diagnostic[];
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function parse(md: string, options?: ParseOptions): ParseResult;
|
|
187
|
+
|
|
188
|
+
/** Diagnostics only: equivalent to `parse(md, { blocks: false }).diagnostics` */
|
|
189
|
+
export function diagnose(md: string, options?: ParseOptions): Diagnostic[];
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
`parse` only parses and diagnoses: it never rewrites the source, adds blank lines or touches indentation. `null` / `undefined` are treated as an empty string.
|
|
193
|
+
|
|
194
|
+
### 4.1 Block
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
export type SourceReason =
|
|
198
|
+
| "html" // raw HTML block
|
|
199
|
+
| "definition" // link definition
|
|
200
|
+
| "unknown" // tag outside the whitelist
|
|
201
|
+
| "list-context" // degraded inside a list context
|
|
202
|
+
| "depth-exceeded" // nesting limit hit
|
|
203
|
+
| "mermaid"; // rawBody container: source only, no structure
|
|
204
|
+
|
|
205
|
+
export type Attrs = Readonly<Record<string, string | boolean>>;
|
|
206
|
+
|
|
207
|
+
export interface VisualBlock {
|
|
208
|
+
kind: "visual";
|
|
209
|
+
/** mdast node type, e.g. heading / paragraph / table */
|
|
210
|
+
type: string;
|
|
211
|
+
start: number;
|
|
212
|
+
end: number;
|
|
213
|
+
/** list / listItem / blockquote only: inner blocks (how containers inside lists stay visible) */
|
|
214
|
+
blocks?: Block[];
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export interface SourceBlock {
|
|
218
|
+
kind: "source";
|
|
219
|
+
text: string;
|
|
220
|
+
reason: SourceReason;
|
|
221
|
+
start: number;
|
|
222
|
+
end: number;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface ContainerItem {
|
|
226
|
+
name: string;
|
|
227
|
+
attrs: Attrs;
|
|
228
|
+
blocks: Block[];
|
|
229
|
+
start: number;
|
|
230
|
+
end: number;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export interface ContainerBlock {
|
|
234
|
+
kind: "container";
|
|
235
|
+
name: string;
|
|
236
|
+
attrs: Attrs;
|
|
237
|
+
depth: number; // starts at 1; child items do not count
|
|
238
|
+
blocks: Block[]; // body of containers without items (Callout / Image / div)
|
|
239
|
+
items: ContainerItem[]; // children of containers with items (Tabs / Steps / Cards / Accordion / Files / TypeTable)
|
|
240
|
+
start: number; // opening tag offset
|
|
241
|
+
end: number; // closing tag end offset
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export type Block = VisualBlock | SourceBlock | ContainerBlock;
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
`blocks` is a read-only derivation: use it for TOCs, positioning and scroll sync; do not mutate it or cache it across parses.
|
|
248
|
+
|
|
249
|
+
### 4.2 Diagnostic
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
export type DiagnosticCode =
|
|
253
|
+
| "UNCLOSED_TAG"
|
|
254
|
+
| "DEPTH_EXCEEDED"
|
|
255
|
+
| "UNKNOWN_TAG"
|
|
256
|
+
| "UNSAFE_HREF"
|
|
257
|
+
| "INDENT_AS_CODE"
|
|
258
|
+
| "MERMAID_EMPTY"
|
|
259
|
+
| "MERMAID_TOO_LARGE"
|
|
260
|
+
| "DUPLICATE_ID_ANCHOR"
|
|
261
|
+
| "DUPLICATE_ID_DIV"
|
|
262
|
+
| "DUPLICATE_ID"; // @deprecated, no longer emitted since 0.5.0, still translatable
|
|
263
|
+
|
|
264
|
+
export interface Diagnostic {
|
|
265
|
+
code: DiagnosticCode;
|
|
266
|
+
level: "warn" | "error"; // every current diagnostic is "warn"
|
|
267
|
+
line: number; // 1-based
|
|
268
|
+
message: string; // Chinese fallback text
|
|
269
|
+
params?: Record<string, string | number>; // interpolation values
|
|
270
|
+
range?: [number, number]; // full-text offset range
|
|
271
|
+
}
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
| Code | Trigger | Degradation |
|
|
275
|
+
|---|---|---|
|
|
276
|
+
| `UNCLOSED_TAG` | Container never closed before EOF | Renders as a container without swallowing content; serialization adds no closing tag |
|
|
277
|
+
| `DEPTH_EXCEEDED` | Nesting exceeds `maxDepth` | Node kept and marked `data.degraded`: rendered as a source block, serialized verbatim, indexed as `source` (`depth-exceeded`) |
|
|
278
|
+
| `UNKNOWN_TAG` | Capitalised tag outside the whitelist | Tag and body both shown as text (no HTML execution, nothing dropped) |
|
|
279
|
+
| `UNSAFE_HREF` | `href` / `src` / `poster` / `formaction` / `srcset` failed the scheme whitelist | Link not clickable (`href` → `#`), other attributes removed |
|
|
280
|
+
| `INDENT_AS_CODE` | Indented, unfenced content inside a container became a code block | Warning only; source untouched |
|
|
281
|
+
| `MERMAID_EMPTY` | Diagram source empty or whitespace | Source block plus a notice, never a blank area |
|
|
282
|
+
| `MERMAID_TOO_LARGE` | Diagram source above `MERMAID_MAX_BYTES` (20 KB) | No diagram; source shown verbatim, node marked `data.mermaidTooLarge` |
|
|
283
|
+
| `DUPLICATE_ID_ANCHOR` | `div id` collides with a heading anchor | Warning only; no rewriting |
|
|
284
|
+
| `DUPLICATE_ID_DIV` | Two `div id` values collide | Warning only; no rewriting |
|
|
285
|
+
|
|
286
|
+
`message` is the Chinese fallback for logs and provider-less contexts; UIs should localise by `code` (§8).
|
|
287
|
+
|
|
288
|
+
### 4.3 Position rules (hard requirements)
|
|
289
|
+
|
|
290
|
+
1. Every `start` / `end` is a **full-text offset** (0-based, `end` exclusive), directly usable as `source.slice(start, end)`.
|
|
291
|
+
2. A container's `start` is the first char of the opening tag; `end` is the last char of the closing tag plus one.
|
|
292
|
+
3. Offsets must be produced **natively by the tokenizer**; "rough parse, then re-parse fragments and accumulate offsets" is forbidden.
|
|
293
|
+
4. Regression check: `container nodes === opening tags in source`; any mismatch is an implementation defect (see §13 item 4).
|
|
294
|
+
|
|
295
|
+
### 4.4 Implementation requirement: a micromark extension
|
|
296
|
+
|
|
297
|
+
| Requirement | Detail |
|
|
298
|
+
|---|---|
|
|
299
|
+
| Syntax layer must be a micromark flow extension | `flow: { [60]: jsxBlock }` (`60` is `<`), `concrete: true`, body recurses through the standard Markdown flow |
|
|
300
|
+
| Do not assemble from html nodes | That falls back to CommonMark HTML-block rules: blank lines become hard boundaries again and an opening tag hugging a paragraph is swallowed by it |
|
|
301
|
+
| `nok` immediately when the name is not in registry | Control returns to the built-in html flow; `<section>` and friends behave as before |
|
|
302
|
+
| Closing matches by name, innermost first | Same-name nesting uses a name stack; unclosed at EOF degrades as "unclosed" without swallowing content |
|
|
303
|
+
| Reference implementation | `node_modules/micromark-extension-directive/lib/directive-container.js` |
|
|
304
|
+
|
|
305
|
+
Consequence: **blank lines are not required**. They only affect readability; the parse result is identical either way.
|
|
306
|
+
|
|
307
|
+
### 4.5 Parsing behaviour
|
|
308
|
+
|
|
309
|
+
| Input | Behaviour |
|
|
310
|
+
|---|---|
|
|
311
|
+
| `<Name>` and `</Name>` on their own lines | Normal container node (no blank line needed) |
|
|
312
|
+
| Opening tag hugging the previous paragraph | Normal container node (the flow construct can interrupt a paragraph) |
|
|
313
|
+
| No blank lines between tags | Parses normally (`concrete` body runs the standard Markdown flow) |
|
|
314
|
+
| Container on one line, `<Callout>text</Callout>` | Unsupported; treated as inline text (the opening tag must end its line) |
|
|
315
|
+
| Child item on one line, `<Tab value="a">A</Tab>` | **Supported**: folded into a structured item with props and content preserved (multi-paragraph form also works) |
|
|
316
|
+
| Blank line inside a child item | Supported: folded into one item across paragraphs |
|
|
317
|
+
| `</Name>` at line start | Ends that container; **the same holds inside fenced code (``` / ~~~)** |
|
|
318
|
+
| Unclosed | Renders as a container without swallowing content; serialization adds no closing tag; emits `UNCLOSED_TAG` |
|
|
319
|
+
| Opening tag spanning lines (`<Callout` then attributes) | Unsupported; shown as text |
|
|
320
|
+
| Inside a table cell or inline | Unsupported; shown as text (containers only trigger at line start) |
|
|
321
|
+
| Tag outside the whitelist (`<section>`, `<Foo>`) | Tag and body are **both** shown as text; capitalised names additionally emit `UNKNOWN_TAG`. `<div>` is registered |
|
|
322
|
+
| Nesting beyond the limit | Node kept and marked `data.degraded`; emits `DEPTH_EXCEEDED` |
|
|
323
|
+
| Body indented ≥4 spaces / a tab | Becomes a CommonMark code block (**not rewritten**) and emits `INDENT_AS_CODE`; a line of "indent + known tag" has its indent moved out of the body first and is then judged at column 0, so indented child items still work |
|
|
324
|
+
| Container inside a list item | Parses normally; exposed recursively through `VisualBlock.blocks` (list / blockquote / listItem) |
|
|
325
|
+
| Child item at top level (`<Tab>`, `<File>`, …) | Parses as a block, but without its container it carries no semantics and is absent from `listComponents()` |
|
|
326
|
+
|
|
327
|
+
### 4.6 GFM and math
|
|
328
|
+
|
|
329
|
+
Parsing and rendering share one extension set: GFM (tables, strikethrough, task lists), `$…$`, `$$…$$` and the angle-bracket blocks are registered side by side.
|
|
330
|
+
|
|
331
|
+
- A single-line `$$E=mc^2$$` is promoted to a **block formula** and serializes back as `$$`, never downgraded to `$…$`.
|
|
332
|
+
- Formula content is preserved verbatim; `_` and `\` are not escaped, so saving does not deform it.
|
|
333
|
+
- Hosts building their own toHast pipeline from `parse()` output must keep `data.hName` / `data.hChildren` (present on promoted math nodes) or formulas render empty.
|
|
334
|
+
|
|
335
|
+
---
|
|
336
|
+
|
|
337
|
+
## 5. render
|
|
338
|
+
|
|
339
|
+
```tsx
|
|
340
|
+
export interface RenderConfig {
|
|
341
|
+
/** Per-component escape hatch; anything not overridden keeps the built-in implementation (key = container name, case-sensitive) */
|
|
342
|
+
components?: Partial<Record<string, React.ComponentType<Record<string, unknown>>>>;
|
|
343
|
+
/** Host remark plugins (run before mdast → hast) */
|
|
344
|
+
remarkPlugins?: PluggableList;
|
|
345
|
+
/** Host rehype plugins (must be synchronous to stay SSR safe) */
|
|
346
|
+
rehypePlugins?: PluggableList;
|
|
347
|
+
/** Emit data-src-start on block elements (editor scroll sync), default false */
|
|
348
|
+
sourcePositions?: boolean;
|
|
349
|
+
/** Per-key message overrides (wins over `text` and the built-in bundles) */
|
|
350
|
+
messages?: UITextPatch;
|
|
351
|
+
/** @deprecated Superseded by `messages`; `messages` wins when both are given */
|
|
352
|
+
text?: UITextPatch;
|
|
353
|
+
/** BCP-47 locale; falls back to an outer Provider, then zh-CN */
|
|
354
|
+
locale?: string;
|
|
355
|
+
/** Fallback locale when the target is not bundled, default zh-CN */
|
|
356
|
+
fallbackLocale?: string;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export interface MarkdownRendererProps {
|
|
360
|
+
content: string;
|
|
361
|
+
/** Outer class name: container styles hang off the body class, so hosts normally pass one */
|
|
362
|
+
className?: string;
|
|
363
|
+
config?: RenderConfig;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export function MarkdownRenderer(props: MarkdownRendererProps): React.ReactElement;
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
Rules:
|
|
370
|
+
|
|
371
|
+
1. Attributes map to component props verbatim (attribute name = prop name, no camelCase conversion).
|
|
372
|
+
2. Every URL attribute passes one scheme whitelist: `http(s)`, `mailto`, `tel`, anchors, queries, relative and protocol-relative paths are allowed; any other scheme (including `data:` and `javascript:`) is rejected. A rejected `href` becomes `#`; `src` / `poster` / `formaction` are removed; `srcset` is validated per candidate and dropped entirely if any candidate fails; non-string values are treated as unsafe. Emits `UNSAFE_HREF`.
|
|
373
|
+
3. The gate sits in hast: even a host override of `a` / `img` never sees a dangerous address.
|
|
374
|
+
4. Component styles use package semantic classes only; never host Tailwind classes.
|
|
375
|
+
5. Custom plugins must be synchronous; plugin arrays are cached by reference and must be treated as immutable (in-place mutation will not invalidate the cache).
|
|
376
|
+
6. `sourcePositions` is for the editor only; leave it off on public pages.
|
|
377
|
+
7. Message resolution is described in §8; `MarkdownRenderer` wraps its output in its own `MdEngineProvider`, so `config.locale` applies to that layer.
|
|
378
|
+
8. Multiple instances on one page do not each build a pipeline: without host plugins two processors are shared globally (with / without `sourcePositions`).
|
|
379
|
+
|
|
380
|
+
---
|
|
381
|
+
|
|
382
|
+
## 6. serialize and format
|
|
383
|
+
|
|
384
|
+
```ts
|
|
385
|
+
/** mdast → Markdown; containers are emitted by their handler, shape preserved from the source */
|
|
386
|
+
export function serialize(tree: Root): string;
|
|
387
|
+
|
|
388
|
+
/** Convenience check: md → AST → md */
|
|
389
|
+
export function roundtrip(md: string): string;
|
|
390
|
+
|
|
391
|
+
/** Identity since 0.5.3: returns its input unchanged, kept for compatibility only */
|
|
392
|
+
export function normalizeMarkdown(md: string): string;
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
Guarantees:
|
|
396
|
+
|
|
397
|
+
1. **Lossless round trip**: `roundtrip(md)` equals the source, except for the engine's existing normalisations (`-` bullets, `*` emphasis, fenced code blocks, whitespace around table delimiters).
|
|
398
|
+
2. **Container shape preserved**: inline forms emit `<X a="b">content</X>`; block forms keep the source's line spacing — blank lines stay blank, tight lines stay tight; empty containers keep opening and closing tags on separate lines.
|
|
399
|
+
3. `serialize` never changes the number of blank lines: no adding, no collapsing.
|
|
400
|
+
4. **The engine does not format for you**: since 0.5.3 `normalizeMarkdown` returns its input unchanged (it does not even convert CRLF), and the editor never calls it. Implement formatting on the host side if you need it.
|
|
401
|
+
|
|
402
|
+
### 6.1 Shape and indentation
|
|
403
|
+
|
|
404
|
+
| Item | Owned by | Notes |
|
|
405
|
+
|---|---|---|
|
|
406
|
+
| Inline vs block shape | `serialize` | Decided at parse time; whatever the source wrote is written back |
|
|
407
|
+
| Blank lines | preserved by `serialize` | The engine never adds or removes them |
|
|
408
|
+
| Indentation | tolerated at parse time, never reflowed | "Indent + known tag" is recognised as a tag; indented prose is still a CommonMark code block |
|
|
409
|
+
|
|
410
|
+
---
|
|
411
|
+
|
|
412
|
+
## 7. editor
|
|
413
|
+
|
|
414
|
+
```tsx
|
|
415
|
+
export interface EditorConfig {
|
|
416
|
+
/** Image upload; returns a reachable URL. Paste-upload is unavailable when omitted */
|
|
417
|
+
uploadImage?: (file: File) => Promise<string>;
|
|
418
|
+
/** Empty-document placeholder; takes precedence over `messages.editorPlaceholder` */
|
|
419
|
+
placeholder?: string;
|
|
420
|
+
/** Read-only */
|
|
421
|
+
readOnly?: boolean;
|
|
422
|
+
/** Preview render config (passed straight to MarkdownRenderer) */
|
|
423
|
+
rendererConfig?: RenderConfig;
|
|
424
|
+
/** Per-key message overrides (wins over `text` and the built-in bundles) */
|
|
425
|
+
messages?: UITextPatch;
|
|
426
|
+
/** @deprecated Superseded by `messages` */
|
|
427
|
+
text?: UITextPatch;
|
|
428
|
+
/** Locale; falls back to an outer Provider, then zh-CN */
|
|
429
|
+
locale?: string;
|
|
430
|
+
fallbackLocale?: string;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export type EditorView = "split" | "source" | "preview";
|
|
434
|
+
|
|
435
|
+
export interface MarkdownEditorProps {
|
|
436
|
+
value: string;
|
|
437
|
+
onChange: (value: string) => void;
|
|
438
|
+
/** Initial view; afterwards the toolbar switches it */
|
|
439
|
+
view?: EditorView;
|
|
440
|
+
config?: EditorConfig;
|
|
441
|
+
/** Fullscreen state owned by the host; the button only appears when passed */
|
|
442
|
+
fullscreen?: boolean;
|
|
443
|
+
onToggleFullscreen?: () => void;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
export function MarkdownEditor(props: MarkdownEditorProps): React.ReactElement;
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
Rules:
|
|
450
|
+
|
|
451
|
+
1. `onChange` always hands back **exactly what the user typed**: no `normalizeMarkdown`, no added blank lines.
|
|
452
|
+
2. The editor only edits text; it never produces HTML.
|
|
453
|
+
3. Block property panels are generated from `registry`; forms are not hardcoded.
|
|
454
|
+
4. Diagnostics appear in the status bar: no dialogs, no blocked input.
|
|
455
|
+
5. `rendererConfig` is passed straight to the preview, and `sourcePositions` is forced on by the editor. To get interactive `<Mermaid>` charts in the built-in preview, pass `{ components: mermaidComponents }`; otherwise the source skeleton is shown. The editor entry does **not** depend on `/mermaid`.
|
|
456
|
+
6. Each input batch parses once: diagnostics and preview share a single `parse()`, and the preview goes through the internal `MarkdownTreeRenderer`. `useDeferredValue` keeps keystrokes responsive.
|
|
457
|
+
7. Split-view scroll sync uses **anchor interpolation**: block-level `data-src-start` markers form anchors (innermost only, stale fallbacks filtered out), the source side resolves the exact character position with `posAtCoords`, and adjacent anchors are interpolated linearly. Preview → source sets `scrollTop` via `lineBlockAt`. Nothing snaps to "top of nearest anchor".
|
|
458
|
+
8. Toolbar actions and keyboard shortcuts share plain functions and can be reused:
|
|
459
|
+
|
|
460
|
+
| Shortcut | Action |
|
|
461
|
+
|---|---|
|
|
462
|
+
| `Mod+B` / `Mod+I` / `Mod+E` | Bold / italic / inline code |
|
|
463
|
+
| `Mod+Shift+S` | Strikethrough |
|
|
464
|
+
| `Mod+1` | Heading 2 |
|
|
465
|
+
| `Mod+Shift+Q` | Blockquote |
|
|
466
|
+
| `Mod+Shift+L` | List |
|
|
467
|
+
|
|
468
|
+
`./editor` also exports `wrapSelection`, `toggleLinePrefix`, `insertBlockAt`, `insertAtCursor`, `blockSnippet` and `INSERTABLE_BLOCKS`, so custom toolbars need no copy of the logic.
|
|
469
|
+
|
|
470
|
+
---
|
|
471
|
+
|
|
472
|
+
## 8. Locale and messages
|
|
473
|
+
|
|
474
|
+
Fixed package strings (aria labels, chart toolbar, editor toolbar and status bar, type-table headers, diagnostics) live in `UIText`, Chinese by default.
|
|
475
|
+
|
|
476
|
+
**Resolution order** (per key; never a missing key):
|
|
477
|
+
|
|
478
|
+
```
|
|
479
|
+
config.messages (per-key override)
|
|
480
|
+
→ built-in bundle[locale]
|
|
481
|
+
→ built-in bundle[fallbackLocale]
|
|
482
|
+
→ zh-CN
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
| Option | Where | Notes |
|
|
486
|
+
|---|---|---|
|
|
487
|
+
| `locale` | `RenderConfig` / `EditorConfig` / `MdEngineProvider` | BCP-47; `zh_CN`, `en-us` are normalised |
|
|
488
|
+
| `fallbackLocale` | same | Defaults to `zh-CN` |
|
|
489
|
+
| `messages` | same | Per-key overrides, `UITextPatch` |
|
|
490
|
+
| `text` | same | `@deprecated`, equivalent to `messages`; `messages` wins when both are given |
|
|
491
|
+
|
|
492
|
+
```tsx
|
|
493
|
+
export interface MdEngineProviderProps {
|
|
494
|
+
locale?: string; // when omitted: outer Provider → storage → zh-CN
|
|
495
|
+
fallbackLocale?: string;
|
|
496
|
+
messages?: UITextPatch; // layered over the outer provider, this layer wins
|
|
497
|
+
storage?: LocaleStorage; // defaults to localStorage + `lkes-md-lang`
|
|
498
|
+
children?: ReactNode;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
export function MdEngineProvider(props: MdEngineProviderProps): ReactNode;
|
|
502
|
+
export function useLocale(): { locale: string; direction: "ltr" | "rtl"; fallbackLocale: string };
|
|
503
|
+
export function useUIText(): UIText;
|
|
504
|
+
export function useMessage(): (key: keyof UIText, values?: Record<string, string | number>) => string;
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
Rules:
|
|
508
|
+
|
|
509
|
+
1. The library **never inspects the environment**: no `navigator`, no cookies, no `<html lang>`. `locale` must be a controlled value identical on server and client (route segment or request header), otherwise the first paint mismatches and hydration warns.
|
|
510
|
+
2. If you really need client detection, call `detectLocale(fallback?)` from an effect or event handler only.
|
|
511
|
+
3. `dir` belongs to the host: the engine only exposes `isRTL(locale)` and `useLocale().direction`; it never writes a `dir` attribute.
|
|
512
|
+
4. Messages use ICU MessageFormat, so `{n, plural, …}` works. On Node small-icu builds, check `supportsIntlLocale(locale)` first.
|
|
513
|
+
5. `Diagnostic.message` is a Chinese fallback; render localized text with `formatDiagnostic(t, diagnostic)` (it maps through `diagnosticTextKey`).
|
|
514
|
+
6. **Keys grow only**: `UIText` keys and their meaning fall under C2; removing or renaming one is a breaking change.
|
|
515
|
+
7. Locale helpers (`normalizeLocale`, `languageOf`, `localeCandidates`, `matchLocale`, `resolveLocale`, `toRouteSegment`, `fromRouteSegment`, `createLocaleStorage`, `BUILTIN_LOCALES`, `DEFAULT_LOCALE`) are pure functions and usable in host routing or middleware.
|
|
516
|
+
|
|
517
|
+
---
|
|
518
|
+
|
|
519
|
+
## 9. Host integration steps
|
|
520
|
+
|
|
521
|
+
1. Install: `npm install @heikeson/md-engine` (React 19+ required).
|
|
522
|
+
2. Add `@import "@heikeson/md-engine/styles.css";` to global styles; override §10 variables to re-theme. When importing slices, load `styles/tokens.css` first.
|
|
523
|
+
3. Replace public rendering:
|
|
524
|
+
|
|
525
|
+
```tsx
|
|
526
|
+
import { MarkdownRenderer } from "@heikeson/md-engine";
|
|
527
|
+
|
|
528
|
+
<MarkdownRenderer content={post.content} className="prose-site" config={{ locale }} />;
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
4. Replace admin editing (client component):
|
|
532
|
+
|
|
533
|
+
```tsx
|
|
534
|
+
import { MarkdownEditor } from "@heikeson/md-engine/editor";
|
|
535
|
+
|
|
536
|
+
<MarkdownEditor value={value} onChange={setValue} view="split" config={{ uploadImage }} />;
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
5. Site-wide locale (optional): wrap the root in `MdEngineProvider` and feed `locale` from the route segment or request header.
|
|
540
|
+
6. Persistence: store exactly what `onChange` gives you — **no** `normalizeMarkdown` call needed.
|
|
541
|
+
7. Diagrams (optional): merge `mermaidComponents` inside a client component (§11.4).
|
|
542
|
+
8. No `transpilePackages`, no Tailwind.
|
|
543
|
+
|
|
544
|
+
---
|
|
545
|
+
|
|
546
|
+
## 10. CSS variable contract
|
|
547
|
+
|
|
548
|
+
The namespace is `--lkes-*`: hosts may override, and the package must supply defaults. Nine base tokens:
|
|
549
|
+
|
|
550
|
+
`--lkes-bg` (surface), `--lkes-fg` (body text), `--lkes-muted` (secondary text), `--lkes-fill` (tinted fills: table head, code, row hover), `--lkes-border` (lines), `--lkes-accent` (emphasis: active underline, expander, card hover), `--lkes-ring` (focus ring), `--lkes-radius` (corners), `--lkes-overlay` (image zoom scrim).
|
|
551
|
+
|
|
552
|
+
**Both light and dark literals ship in the package**: light on `:root`, dark on a `.dark` / `[data-theme="dark"]` **ancestor** — add `.dark` to an ancestor and every component (editor shell included) switches at once.
|
|
553
|
+
|
|
554
|
+
Defaults **do not read host variables**: a `var()` inside a custom property is resolved where it is declared, so switching `.dark` later on the host has no effect — that is exactly why "some components stay light" used to happen.
|
|
555
|
+
|
|
556
|
+
Override by redeclaring the variable in normal (unlayered) CSS. `:root`, `.dark` or a body container all work, and import order does not matter (package defaults live in the `lkes.tokens` layer, which loses to unlayered declarations).
|
|
557
|
+
|
|
558
|
+
Class names never change with variables, so existing class-level overrides keep working. Callout's five state colors are semantic constants (plus the fumadocs aliases `warn` / `error` / `success` / `idea`); they do not use those tokens — override the `.callout-*` classes instead. Likewise `--lkes-tone` (the semantic hue used by Callout and Timeline) and `--lkes-col-grow` / `--lkes-col-basis` (Columns widths) are component-scope internals, not part of the nine tokens.
|
|
559
|
+
|
|
560
|
+
Chart colors are **not** here: `<Mermaid>` ships its own `--lkes-chart-*` set in the component's own scope, independent of host variables. See §11.9.
|
|
561
|
+
|
|
562
|
+
---
|
|
563
|
+
|
|
564
|
+
## 11. Mermaid diagram container
|
|
565
|
+
|
|
566
|
+
### 11.1 Syntax
|
|
567
|
+
|
|
568
|
+
```md
|
|
569
|
+
<Mermaid title="Request flow" height="480">
|
|
570
|
+
graph TD
|
|
571
|
+
A[Start] --> B{Check}
|
|
572
|
+
B -->|yes| C[Run]
|
|
573
|
+
</Mermaid>
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
| Attribute | Type | Default | Notes |
|
|
577
|
+
|---|---|---|---|
|
|
578
|
+
| `title` | string | none | Chart title, rendered as a caption |
|
|
579
|
+
| `height` | numeric string / `auto` | `auto` | Upper bound for the chart area (px). Omitted / empty / `auto` all mean automatic height: the area takes the initially fitted height, leaving no blank screen; a positive number becomes the viewport height and overflow is reached by panning |
|
|
580
|
+
|
|
581
|
+
### 11.2 Three hard rules
|
|
582
|
+
|
|
583
|
+
1. **The body is raw text**: no inline Markdown, no nested containers. `#`, `|`, `-->` and leading `-` survive verbatim.
|
|
584
|
+
2. **Only a line-start closing tag counts**: the body closes at a `</Mermaid>` at line start; the same text mid-line never truncates the chart.
|
|
585
|
+
3. **Must be written at column 0**: an opening tag indented ≥4 spaces becomes an indented code block.
|
|
586
|
+
|
|
587
|
+
`<Mermaid />` is allowed: it equals empty source, emits `MERMAID_EMPTY` and renders an empty source block.
|
|
588
|
+
|
|
589
|
+
### 11.3 Diagnostics
|
|
590
|
+
|
|
591
|
+
| Code | Trigger | Degradation |
|
|
592
|
+
|---|---|---|
|
|
593
|
+
| `MERMAID_EMPTY` | Body empty or whitespace | Source block plus a notice, never blank |
|
|
594
|
+
| `MERMAID_TOO_LARGE` | Source above 20 KB (`MERMAID_MAX_BYTES`) | No diagram; source shown verbatim; node marked `data.mermaidTooLarge` |
|
|
595
|
+
|
|
596
|
+
Both cases leave the source untouched: serialization still writes it back verbatim.
|
|
597
|
+
|
|
598
|
+
### 11.4 Host wiring
|
|
599
|
+
|
|
600
|
+
```tsx
|
|
601
|
+
// The host component must be a client component ("use client")
|
|
602
|
+
import { MarkdownRenderer, mdxComponents } from "@heikeson/md-engine";
|
|
603
|
+
import { mermaidComponents } from "@heikeson/md-engine/mermaid";
|
|
604
|
+
import "@heikeson/md-engine/styles.css";
|
|
605
|
+
|
|
606
|
+
const components = { ...mdxComponents, ...mermaidComponents };
|
|
607
|
+
|
|
608
|
+
<MarkdownRenderer content={md} config={{ components }} />;
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
- Without `mermaidComponents`, `<Mermaid>` stays a **source skeleton** (`figure` + `pre`) and mermaid is never loaded.
|
|
612
|
+
- The override key must be `Mermaid` with a capital M: the renderer looks it up by hast tagName, so lowercase fails silently and the skeleton stays.
|
|
613
|
+
- mermaid loads dynamically once a chart **enters the viewport**; one load per page; failures degrade to the source with a console warning.
|
|
614
|
+
|
|
615
|
+
### 11.5 Component props contract
|
|
616
|
+
|
|
617
|
+
| prop | Type | Notes |
|
|
618
|
+
|---|---|---|
|
|
619
|
+
| `raw` | `string?` | Diagram source |
|
|
620
|
+
| `code` | `string?` | Compatibility alias for `raw`; `raw` is used when omitted |
|
|
621
|
+
| `title` | `string?` | Caption |
|
|
622
|
+
| `height` | `string?` | Validated height bound |
|
|
623
|
+
| `tooLarge` | `boolean?` | Source over the limit; source shown only |
|
|
624
|
+
|
|
625
|
+
`mermaidComponents.Mermaid` and the main entry's `MermaidPlaceholder` share one signature (`MermaidProps`), so single-component overrides only need the fields above; remaining hast attributes pass through.
|
|
626
|
+
|
|
627
|
+
### 11.6 Interaction and export
|
|
628
|
+
|
|
629
|
+
**Initial view**: fitted to the container width (never above 1:1; container height also considered when `height` is given) and centred, so large diagrams are not cropped. The chart area has **no padding**: the canvas (the pannable/clipped viewport) shares edges with the card.
|
|
630
|
+
|
|
631
|
+
| Action | Behaviour |
|
|
632
|
+
|---|---|
|
|
633
|
+
| Left-drag | **The whole chart area drags** (the viewport is the gesture surface); it follows the pointer 1:1 regardless of zoom; presses on links, images or form controls are not captured |
|
|
634
|
+
| Dragging out of bounds | Allowed (one viewport of slack), then a 200 ms easeOut snap back to the nearest legal position on release; content smaller than the viewport can sit anywhere without snapping to centre; movement ≤ 5 px counts as a click and does not snap |
|
|
635
|
+
| Two-finger pinch (touch) | Scales around the midpoint of both fingers, which also drags when it moves; lifting one finger ends the pinch, and out-of-bounds cases snap back without flinging the chart |
|
|
636
|
+
| One-finger swipe (touch) | Horizontal gestures pan the chart, **vertical gestures scroll the page** (`touch-action: pan-y`) |
|
|
637
|
+
| Text | Text is selectable when idle; selection is locked only while dragging |
|
|
638
|
+
| Wheel | Not intercepted by default; the page scrolls normally |
|
|
639
|
+
| Left-drag + wheel / Ctrl (⌘) + wheel | Zooms around the cursor (multiplicative, clamped to 0.75–1.33 per step), keeping the point under the pointer fixed |
|
|
640
|
+
| Double click | 200 ms easeOut back to the initial fitted view |
|
|
641
|
+
| Top toolbar | Left: toggle source / chart view. Right: copy source, download SVG, download PNG |
|
|
642
|
+
| Bottom-right zoom pill | Zoom in / out / reset (pill floating in the corner, unaffected by chart zoom), anchored to the viewport centre, 200 ms easing |
|
|
643
|
+
|
|
644
|
+
During gestures the transform layer is written directly by `use-zoom`, bypassing React state, so no re-render happens per frame. Zoom ranges from 0.25× to 8×, with no inertial fling. Scaling uses 2D `translate + scale` (**no compositor promotion**) and the SVG re-renders at the current scale every frame, so magnification stays sharp. If a host ancestor applies `filter` / `backdrop-filter` / `translateZ(0)`, the browser re-rasterises and that part is outside package control.
|
|
645
|
+
|
|
646
|
+
When the SVG exposes no natural size (no `viewBox`/dimensions), interaction degrades to a static display instead of a blank area. Export uses the SVG currently on screen (no re-render); PNG is drawn on a 2× canvas over `--lkes-chart-bg`.
|
|
647
|
+
|
|
648
|
+
`/mermaid` also exports callable helpers — `downloadSvg`, `downloadPng`, `prepareSvg`, `svgToPngBlob` — so custom toolbars need no rewrite.
|
|
649
|
+
|
|
650
|
+
### 11.7 Relation to fenced code
|
|
651
|
+
|
|
652
|
+
A three-backtick fence tagged `mermaid` keeps its **unchanged** meaning (still a code block). Both forms coexist:
|
|
653
|
+
|
|
654
|
+
- The container form is rendered by this package (source skeleton → interactive chart);
|
|
655
|
+
- The fenced form stays the host's decision (it may keep rendering diagrams through its code-block component).
|
|
656
|
+
|
|
657
|
+
Migration is up to the host; the package ships no repo-wide rewriter.
|
|
658
|
+
|
|
659
|
+
### 11.8 Security
|
|
660
|
+
|
|
661
|
+
- `securityLevel: "strict"` is fixed and not configurable: HTML tags and click events inside diagram source are disabled.
|
|
662
|
+
- Rendered output is sanitised by DOMPurify (`svg` profile, `<style>` kept) before injection: no scripts, no event attributes.
|
|
663
|
+
- Diagrams are inline SVG only and never go through the `href` channel; `Image` URL whitelisting is unaffected.
|
|
664
|
+
|
|
665
|
+
### 11.9 Theme (built in, host-independent)
|
|
666
|
+
|
|
667
|
+
`<Mermaid>` ships **both light and dark palettes** and works with zero configuration, reading **no host CSS variables**.
|
|
668
|
+
|
|
669
|
+
| Layer | Where | Priority |
|
|
670
|
+
|---|---|---|
|
|
671
|
+
| JS config | `configureChartTheme({ light, dark })` | Highest (once set, SVG colors come from it, not CSS) |
|
|
672
|
+
| CSS override | Redeclare `--lkes-chart-*` in any scope | Middle |
|
|
673
|
+
| Built-in defaults | Two literal sets in `styles/mermaid.css` component scope | Fallback |
|
|
674
|
+
|
|
675
|
+
Light/dark is decided by the **nearest `.dark` ancestor** (`[data-theme="dark"]` also supported); no theme-variable naming is assumed.
|
|
676
|
+
|
|
677
|
+
| Variable | Light | Dark |
|
|
678
|
+
|---|---|---|
|
|
679
|
+
| `--lkes-chart-bg` (card / chart background) | `#ffffff` | `#161c22` |
|
|
680
|
+
| `--lkes-chart-surface` (toolbar / zoom pill) | `#f6f9f8` | `#1c262c` |
|
|
681
|
+
| `--lkes-chart-fg` (text / buttons) | `#1f2937` | `#e8eef2` |
|
|
682
|
+
| `--lkes-chart-muted` (secondary text) | `#6b7280` | `#9aa8b0` |
|
|
683
|
+
| `--lkes-chart-node` (node fill) | `#e7f0ea` | `#1e3037` |
|
|
684
|
+
| `--lkes-chart-node-border` (node stroke) | `#c9d8cf` | `#2f4a52` |
|
|
685
|
+
| `--lkes-chart-line` (edges) | `#9aa8a0` | `#7a8a92` |
|
|
686
|
+
| `--lkes-chart-accent` (source view, hover) | `#01c4b6` | `#19d3c5` |
|
|
687
|
+
| `--lkes-chart-series-1..6` (slices / branches) | teal/blue/indigo/violet/pink/orange | same, first `#19d3c5` |
|
|
688
|
+
|
|
689
|
+
```ts
|
|
690
|
+
import { configureChartTheme } from "@heikeson/md-engine/mermaid";
|
|
691
|
+
|
|
692
|
+
configureChartTheme({
|
|
693
|
+
// pass only what changes; the rest keeps its default
|
|
694
|
+
light: { node: "#fff3d6", nodeBorder: "#e8d9b0" },
|
|
695
|
+
dark: { node: "#2a2418", nodeBorder: "#4a3f28" },
|
|
696
|
+
});
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
`ChartTokens` fields: `bg`, `fg`, `node`, `nodeBorder`, `line`, `series` (six or more colors), `fontFamily`. Read and reset with `getChartTheme()` / `resetChartTheme()` / `hasCustomChartTheme()`.
|
|
700
|
+
|
|
701
|
+
---
|
|
702
|
+
|
|
703
|
+
## 12. Compatibility and releases
|
|
704
|
+
|
|
705
|
+
| Change | Version | Allowed |
|
|
706
|
+
|---|---|---|
|
|
707
|
+
| New component | minor | yes |
|
|
708
|
+
| New optional attribute / option (with default) | minor | yes |
|
|
709
|
+
| New `UIText` key / diagnostic code | minor | yes |
|
|
710
|
+
| Internal component UI and style tweaks | patch / minor | yes |
|
|
711
|
+
| Renaming or removing a component, child item or attribute | — | **forbidden** |
|
|
712
|
+
| Changing attribute semantics | — | **forbidden** |
|
|
713
|
+
| Removing an option / changing a default that alters behaviour | — | **forbidden** |
|
|
714
|
+
| Removing an exported name | — | **forbidden** (low-level helpers included) |
|
|
715
|
+
|
|
716
|
+
Message contract: fixed strings live in `UIText`, Chinese by default; hosts override per key through `config.messages`. **Keys grow only**, same rule as config options.
|
|
717
|
+
|
|
718
|
+
Version history lives solely in `update.md` at the repository root; this file documents interfaces only, not process.
|
|
719
|
+
|
|
720
|
+
---
|
|
721
|
+
|
|
722
|
+
## 13. Acceptance checklist
|
|
723
|
+
|
|
724
|
+
| # | Item | Criterion |
|
|
725
|
+
|---|---|---|
|
|
726
|
+
| 1 | Main entry under SSR | `parse()` + `serialize()` run in Node with no DOM |
|
|
727
|
+
| 2 | Round trip | Eleven container samples (inline / tight / with blank lines / nested) match per §6 |
|
|
728
|
+
| 3 | Fault tolerance | Unclosed / unknown tag / no blank lines and hugging a paragraph / over the depth limit / container inside a list — none crash or swallow content |
|
|
729
|
+
| 3.1 | Closing rule | A line-start `</Name>` always ends the container (fenced code included) |
|
|
730
|
+
| 3.2 | Inline items | Inline forms with `>` inside attributes and blank lines inside items still yield props |
|
|
731
|
+
| 3.3 | Indentation | Indented child items parse; indented prose still emits `INDENT_AS_CODE` |
|
|
732
|
+
| 4 | Positions | Every container and item `start`/`end` matches the source slice; container count equals opening-tag count |
|
|
733
|
+
| 5 | Security | `javascript:` / `data:` rejected with `UNSAFE_HREF`; one bad `srcset` candidate drops the whole attribute |
|
|
734
|
+
| 6 | Isolation | Main entry output contains no CodeMirror, mermaid or dompurify |
|
|
735
|
+
| 7 | Styling | `--lkes-*` alone re-themes the package with class names unchanged; with no host variables the built-in light/dark defaults apply |
|
|
736
|
+
| 8 | Diagram syntax | `<Mermaid>` round-trips verbatim; `#`, `\|`, `-->` and leading `-` in the body are not parsed as Markdown |
|
|
737
|
+
| 8.1 | Diagram degradation | Empty source emits `MERMAID_EMPTY`, >20 KB emits `MERMAID_TOO_LARGE`; both keep the source and render a code block (no blank area) |
|
|
738
|
+
| 8.2 | Diagram isolation | Without the `/mermaid` entry a source skeleton is rendered; with it, mermaid loads only on viewport entry |
|
|
739
|
+
| 8.3 | Diagram security | `securityLevel` fixed at `strict`; SVG sanitised by DOMPurify before injection |
|
|
740
|
+
| 9 | Duplicate ids | `div id` colliding with a heading anchor or another `div` emits `DUPLICATE_ID_ANCHOR` / `DUPLICATE_ID_DIV` (warn only); Tabs support ←/→/Home/End |
|
|
741
|
+
| 10 | Locale | `locale` identical on server and client with no hydration mismatch; `messages` overrides apply per key |
|
|
742
|
+
| 11 | Module format | `import` only; no `require`, no sourcemaps in the artifacts |
|
|
743
|
+
|
|
744
|
+
---
|
|
745
|
+
|
|
746
|
+
## Appendix A: main entry exports
|
|
747
|
+
|
|
748
|
+
| Group | Names |
|
|
749
|
+
|---|---|
|
|
750
|
+
| Parsing | `parse`, `diagnose`, `ParseOptions`, `ParseResult` |
|
|
751
|
+
| Block index | `extractBlocks`, `Block`, `VisualBlock`, `SourceBlock`, `ContainerBlock`, `ContainerItem`, `Attrs`, `SourceReason` |
|
|
752
|
+
| Serialization | `serialize`, `roundtrip`, `normalizeMarkdown` |
|
|
753
|
+
| Rendering | `MarkdownRenderer`, `MarkdownRendererProps`, `RenderConfig` |
|
|
754
|
+
| Syntax | `COMPONENTS`, `ITEMS`, `MAX_CONTAINER_DEPTH`, `getComponent`, `getItemSpec`, `listComponents`, `isContainerWithItems`, `ComponentSpec`, `ItemSpec`, `ComponentMode` |
|
|
755
|
+
| Components | `mdxComponents`, `MermaidPlaceholder`, `MermaidProps` |
|
|
756
|
+
| Diagnostics | `MERMAID_MAX_BYTES`, `Diagnostic`, `DiagnosticCode`, `diagnosticTextKey`, `formatDiagnostic` |
|
|
757
|
+
| Locale | `MdEngineProvider`, `MdEngineProviderProps`, `useLocale`, `useUIText`, `useMessage`, `defaultUIText`, `mergeUIText`, `UIText`, `UITextPatch`, `TextDirection`, `BUILTIN_LOCALES` |
|
|
758
|
+
| Locale helpers | `DEFAULT_LOCALE`, `normalizeLocale`, `languageOf`, `localeCandidates`, `matchLocale`, `resolveLocale`, `detectLocale`, `isRTL`, `formatMessage`, `supportsIntlLocale`, `toRouteSegment`, `fromRouteSegment` |
|
|
759
|
+
| Locale bundles | `zhCN`, `enUS` |
|
|
760
|
+
| Storage | `createLocaleStorage`, `DEFAULT_LOCALE_STORAGE_KEY`, `LocaleStorage`, `LocaleStorageOptions` |
|
|
761
|
+
| Low-level syntax (usable, signatures not promised) | `jsxBlocks`, `remarkJsxBlocks`, `jsxFromMarkdown`, `jsxToMarkdown`, `parseOpenTag`, `sliceRawBody`, `JsxBlock` |
|
|
762
|
+
|
|
763
|
+
`./editor`: `MarkdownEditor`, `MarkdownEditorProps`, `EditorConfig`, `EditorView`, `wrapSelection`, `toggleLinePrefix`, `insertBlockAt`, `insertAtCursor`, `blockSnippet`, `INSERTABLE_BLOCKS`, `EditResult`, `Selection`.
|
|
764
|
+
`./components`: `mdxComponents` plus the 21 components (`Callout`, `Tabs`, `Tab`, `Steps`, `Step`, `Cards`, `Card`, `Accordion`, `AccItem`, `Files`, `Folder`, `File`, `TypeTable`, `TypeItem`, `Columns`, `Column`, `Timeline`, `TimelineItem`, `Video`, `MdImage`, `MermaidPlaceholder`).
|
|
765
|
+
`./mermaid`: `mermaidComponents`, `MermaidChart`, `MermaidProps`, `configureChartTheme`, `getChartTheme`, `resetChartTheme`, `hasCustomChartTheme`, `DEFAULT_CHART_THEME`, `LIGHT_TOKENS`, `DARK_TOKENS`, `ChartTheme`, `ChartTokens`, `resolveChartTokens`, `useIsDark`, `downloadSvg`, `downloadPng`, `prepareSvg`, `svgToPngBlob`.
|