@heikeson/md-engine 0.5.4 → 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 ADDED
@@ -0,0 +1,267 @@
1
+ # @heikeson/md-engine
2
+
3
+ [简体中文](./README.md) | English
4
+
5
+ A Markdown renderer for React, plus an editor built on CodeMirror 6. GFM and math are supported.
6
+ The interesting part is this:
7
+
8
+ ```md
9
+ <Callout type="tip" title="Heads up">
10
+ The body is still Markdown — `inline code` and [links](https://example.com) work as usual.
11
+ </Callout>
12
+ ```
13
+
14
+ These angle-bracket containers are not scraped out of the rendered HTML with a regex; they land in
15
+ the mdast just like headings and lists. They therefore carry position info, can be serialized back
16
+ to the source, and can be swapped for your own component as a whole block. Run `md → AST → md` and
17
+ the text comes back byte for byte.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @heikeson/md-engine
23
+ ```
24
+
25
+ Requires React 19 or later. The package ships ESM only; older Jest or webpack 4 setups need their
26
+ own interop layer. Styles are plain CSS and have nothing to do with Tailwind — they render fine even
27
+ if the host defines no theme variables.
28
+
29
+ ## Rendering
30
+
31
+ ```tsx
32
+ import { MarkdownRenderer } from "@heikeson/md-engine";
33
+ import "@heikeson/md-engine/styles.css";
34
+
35
+ export default function Article({ content }: { content: string }) {
36
+ return <MarkdownRenderer content={content} className="prose-site" />;
37
+ }
38
+ ```
39
+
40
+ Do not drop `prose-site` — the styles for all eleven containers hang off it. Mermaid uses
41
+ `.lkes-mermaid` and the editor uses `.md-editor`, neither of which you need here.
42
+
43
+ Parsing and rendering never touch `window` or `document`, so the server can call them directly.
44
+
45
+ ## Containers
46
+
47
+ | Container | Props | Children |
48
+ | --- | --- | --- |
49
+ | `Callout` | `type` (`note` `info` `tip` `important` `warning` `caution` `danger`, default `note`), `title`, `icon` | body |
50
+ | `Tabs` | none | `Tab`: `value`, `default` |
51
+ | `Steps` | none | `Step`: `title` |
52
+ | `Cards` | none | `Card`: `title`, `href`, `icon`, `description` |
53
+ | `Accordion` | none | `AccItem`: `title`, `type` (`open` / `close`) |
54
+ | `Files` | none | `Folder`: `name`, `defaultOpen`; `File`: `name`, `href`, `icon` |
55
+ | `TypeTable` | none | `TypeItem`: `name`, `type`, `default`, `required` |
56
+ | `Columns` | none | `Column`: `width` |
57
+ | `Timeline` | none | `TimelineItem`: `date`, `title`, `type` |
58
+ | `Video` | `src`, `poster`, `caption`, `width` | self-closing |
59
+ | `Image` | `src`, `alt`, `align`, `width`, `caption`, `zoom` | self-closing |
60
+ | `Mermaid` | `title`, `height` | raw text, not parsed as Markdown |
61
+ | `div` | `class`, `id` | body; attributes pass through to the DOM |
62
+
63
+ ```md
64
+ <Tabs>
65
+ <Tab value="npm">npm install @heikeson/md-engine</Tab>
66
+ <Tab value="pnpm">pnpm add @heikeson/md-engine</Tab>
67
+ </Tabs>
68
+
69
+ <Cards>
70
+ <Card title="Quick start" description="Smallest example that renders a section" href="/docs/start" />
71
+ </Cards>
72
+
73
+ <Columns>
74
+ <Column width="2">Wide column</Column>
75
+ <Column width="1">Narrow column</Column>
76
+ </Columns>
77
+
78
+ <Timeline>
79
+ <TimelineItem date="2026-11" title="Point">Body</TimelineItem>
80
+ </Timeline>
81
+
82
+ <Video src="/demo.mp4" poster="/demo.png" caption="Demo" width="60%" />
83
+ ```
84
+
85
+ `Image` and `Video` share one `width` grammar: `auto` (natural size), `60%` (share of the column),
86
+ `1/3` (fraction), `360` (pixels), `20rem` (length); anything above 100% is clamped to full width.
87
+ `Image` also takes `align` (`left` / `center` / `right`), which positions the whole figure including
88
+ its caption — block alignment, not text wrapping. `Column`'s `width` means something else: a bare
89
+ number splits by ratio, a value with a unit sets a fixed width.
90
+
91
+ A few hard rules — break them and you get no error, just mangled output:
92
+
93
+ - Containers must start at column 0. Children may be indented, but body lines indented to 4 spaces
94
+ are treated as a code block by CommonMark.
95
+ - Only `a="b"` attributes and bare booleans are understood; `{...}` expressions are not supported.
96
+ - Tags outside the whitelist are shown as literal text, contents included. If you want a plain block
97
+ you can hang a `class` on, use `div`.
98
+ - `Image`, `Video`, `Card` and `File` may self-close; every other container needs a closing tag.
99
+ - Nesting stops at 3 levels; anything deeper is emitted as raw text.
100
+
101
+ ## Parsing and serialization
102
+
103
+ ```ts
104
+ import { parse, serialize, roundtrip, normalizeMarkdown, diagnose } from "@heikeson/md-engine";
105
+
106
+ const { tree, blocks, diagnostics } = parse(md);
107
+ serialize(tree); // back to Markdown, preserving shape and blank lines
108
+ roundtrip(md); // shorthand for the two lines above
109
+ normalizeMarkdown(md); // when you want unified formatting; serialize does not reformat for you
110
+ diagnose(md); // diagnostics only, same as parse(md, { blocks: false }).diagnostics
111
+ ```
112
+
113
+ `blocks` is a flat block index carrying document-wide offsets — handy for tables of contents,
114
+ jumping to a location, and scroll sync. When the editor only needs diagnostics, call `diagnose()` and
115
+ skip the full tree conversion.
116
+
117
+ ## Editor
118
+
119
+ ```tsx
120
+ "use client";
121
+
122
+ import { useState } from "react";
123
+ import { MarkdownEditor } from "@heikeson/md-engine/editor";
124
+ import "@heikeson/md-engine/styles.css";
125
+
126
+ export default function EditorPage() {
127
+ const [value, setValue] = useState("");
128
+ return (
129
+ <MarkdownEditor
130
+ value={value}
131
+ onChange={setValue}
132
+ view="split"
133
+ config={{ placeholder: "Start writing…" }}
134
+ />
135
+ );
136
+ }
137
+ ```
138
+
139
+ It is a controlled component: `value` is the Markdown text, editing on the left and previewing on the
140
+ right. The snippets the toolbar inserts are generated by `registry.ts`, sharing names and props with
141
+ the parsing rules, so they cannot drift apart. Shortcuts go through the same implementation as the
142
+ buttons: `Mod+B`, `Mod+I` and `Mod+E` for bold, italic and inline code, `Mod+Shift+S` for strikethrough,
143
+ `Mod+1` for a level-2 heading, `Mod+Shift+Q` for a quote, `Mod+Shift+L` for a list.
144
+
145
+ ## Diagrams
146
+
147
+ `<Mermaid>` renders source code only by default. To draw actual diagrams on the page, merge the
148
+ overrides inside a client component:
149
+
150
+ ```tsx
151
+ "use client";
152
+ import { MarkdownRenderer, mdxComponents } from "@heikeson/md-engine";
153
+ import { mermaidComponents } from "@heikeson/md-engine/mermaid";
154
+
155
+ const components = { ...mdxComponents, ...mermaidComponents };
156
+
157
+ <MarkdownRenderer content={md} config={{ components }} />;
158
+ ```
159
+
160
+ The key is `Mermaid`, capitalized. Lowercase raises no error — the diagram just stays as source.
161
+ `mermaid` is an optional peer; without it, rendering degrades to source code and parsing/serialization
162
+ are unaffected.
163
+
164
+ ## Locales
165
+
166
+ Built-in `zh-CN` and `en-US`. Pick a locale bundle with `config.locale`, or override individual strings
167
+ with `config.messages`. To set it once at the root, wrap the app in a Provider:
168
+
169
+ ```tsx
170
+ import { MdEngineProvider } from "@heikeson/md-engine";
171
+
172
+ <MdEngineProvider locale={locale}>
173
+ <App />
174
+ </MdEngineProvider>
175
+ ```
176
+
177
+ `locale` must be a controlled value that matches on server and client — usually taken from a URL
178
+ segment or a request header. The library does not read `navigator`, cookies or `<html lang>`, because
179
+ those make the first paint disagree with the server under SSR. If you really need client-side
180
+ detection, call `detectLocale()` inside an effect.
181
+
182
+ ## Swapping components
183
+
184
+ ```tsx
185
+ <MarkdownRenderer
186
+ content={md}
187
+ config={{
188
+ components: { Callout: MyCallout }, // replace just this one, everything else uses the built-in
189
+ remarkPlugins: [],
190
+ rehypePlugins: [], // must be synchronous, otherwise SSR is unsafe
191
+ sourcePositions: false, // only needed for editor scroll sync
192
+ }}
193
+ />
194
+ ```
195
+
196
+ Inside your own components, read strings with `useUIText()` and format with `useMessage()` using ICU
197
+ syntax.
198
+
199
+ ## Styles
200
+
201
+ Import `@heikeson/md-engine/styles.css` once. Colors come from standalone `--lkes-*` variables: nine
202
+ tokens with light and dark literals. Add `.dark` or `[data-theme="dark"]` on an ancestor to switch the
203
+ whole thing to dark. The token list and override recipes are in section 10 of
204
+ [the integration contract](./对接契约.en.md).
205
+
206
+ Importing per component also works — `styles/*.css` is published as-is in the npm package. But the
207
+ tokens live in `tokens.css` alone: import only a slice and you get no `--lkes-*`, so dark mode stops
208
+ working and colors fall back to hardcoded values. Order matters too — `tokens` first, so the
209
+ `components` layer can win over the token layer:
210
+
211
+ ```ts
212
+ import "@heikeson/md-engine/styles/tokens.css";
213
+ import "@heikeson/md-engine/styles/callout.css";
214
+ ```
215
+
216
+ ## Development
217
+
218
+ ```bash
219
+ npm run dev # playground for renderer + editor work
220
+ npm run snapshot # static snapshot with roundtrip and diagnostics self-checks
221
+ npm run selfcheck # parse, render and serialize assertions against the build
222
+ npm run typecheck # tsc --noEmit
223
+ npm run build # dist and dist/styles.css
224
+ ```
225
+
226
+ `dev/`, `docs/` and `site/` are not published; `files` ships only `dist`, `styles`, the READMEs,
227
+ `对接契约.md`, `对接契约.en.md` and `LICENSE`.
228
+
229
+ ```
230
+ src/
231
+ ├─ registry.ts syntax declarations, the single source of truth
232
+ ├─ policy.ts depth trimming, unclosed detection, diagnostics
233
+ ├─ parse.ts / blocks.ts
234
+ ├─ render.tsx / serialize.ts / format.ts
235
+ ├─ syntax/ micromark angle-bracket extension
236
+ ├─ components/ container components and mapping
237
+ ├─ mermaid/ the /mermaid entry
238
+ ├─ editor/ CodeMirror wrapper, toolbar, scroll sync
239
+ └─ locales/ locale bundles
240
+ styles/ plain CSS slices
241
+ ```
242
+
243
+ ## Entries
244
+
245
+ ```
246
+ @heikeson/md-engine parse, serialize, MarkdownRenderer, Provider
247
+ @heikeson/md-engine/editor MarkdownEditor
248
+ @heikeson/md-engine/mermaid interactive diagrams
249
+ @heikeson/md-engine/components individual container components
250
+ @heikeson/md-engine/locales/zh-CN locale bundle
251
+ @heikeson/md-engine/locales/en-US
252
+ @heikeson/md-engine/styles.css all styles in one file
253
+ ```
254
+
255
+ The main entry exports no editor code at all. Full signatures, diagnostic codes and CSS variables live
256
+ in [the integration contract](./对接契约.en.md) (Chinese original: [对接契约.md](./对接契约.md)); version
257
+ history is in [update.md](./update.md) (Chinese).
258
+
259
+ ## Compatibility
260
+
261
+ Shipped API stays put: component names, prop names and semantics only grow, new config options must
262
+ carry a default, and style class names and variables are supplied by the package. Anything else is a
263
+ breaking change and needs a major version.
264
+
265
+ ## License
266
+
267
+ MIT
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # @heikeson/md-engine
2
2
 
3
+ 简体中文 | [English](./README.en.md)
4
+
3
5
  React 的 Markdown 渲染器,外加一个基于 CodeMirror 6 的编辑器。GFM 和数学公式都支持,
4
6
  重点在下面这种写法:
5
7
 
@@ -32,7 +34,7 @@ export default function Article({ content }: { content: string }) {
32
34
  }
33
35
  ```
34
36
 
35
- `prose-site` 别省,八个容器的样式都挂在它下面。Mermaid 用 `.lkes-mermaid`,编辑器用
37
+ `prose-site` 别省,十一个容器的样式都挂在它下面。Mermaid 用 `.lkes-mermaid`,编辑器用
36
38
  `.md-editor`,这两个不需要。
37
39
 
38
40
  解析和渲染都不碰 `window`、`document`,服务端可以直接调。
@@ -48,6 +50,9 @@ export default function Article({ content }: { content: string }) {
48
50
  | `Accordion` | 无 | `AccItem`:`title`、`type`(`open` / `close`) |
49
51
  | `Files` | 无 | `Folder`:`name`、`defaultOpen`;`File`:`name`、`href`、`icon` |
50
52
  | `TypeTable` | 无 | `TypeItem`:`name`、`type`、`default`、`required` |
53
+ | `Columns` | 无 | `Column`:`width` |
54
+ | `Timeline` | 无 | `TimelineItem`:`date`、`title`、`type` |
55
+ | `Video` | `src`、`poster`、`caption`、`width` | 自闭合 |
51
56
  | `Image` | `src`、`alt`、`align`、`width`、`caption`、`zoom` | 自闭合 |
52
57
  | `Mermaid` | `title`、`height` | 原始文本,内部不按 Markdown 解析 |
53
58
  | `div` | `class`、`id` | 正文,属性透传到 DOM |
@@ -61,14 +66,30 @@ export default function Article({ content }: { content: string }) {
61
66
  <Cards>
62
67
  <Card title="快速开始" description="渲染一节的最小示例" href="/docs/start" />
63
68
  </Cards>
69
+
70
+ <Columns>
71
+ <Column width="2">宽列</Column>
72
+ <Column width="1">窄列</Column>
73
+ </Columns>
74
+
75
+ <Timeline>
76
+ <TimelineItem date="2026-11" title="要点">正文</TimelineItem>
77
+ </Timeline>
78
+
79
+ <Video src="/demo.mp4" poster="/demo.png" caption="演示" width="60%" />
64
80
  ```
65
81
 
82
+ `Image` 与 `Video` 的 `width` 是同一套写法:`auto`(原始尺寸)、`60%`(占比)、`1/3`(分数)、
83
+ `360`(像素)、`20rem`(长度),超过 100% 按满宽处理。`Image` 另有 `align`(`left` / `center` /
84
+ `right`),控制整块连同题注的位置,是块级对齐而非图文环绕。`Column` 的 `width` 语义不同:纯数字
85
+ 按比例分份,带单位按固定宽度。
86
+
66
87
  有几条是硬规则,写错了不报错但会变形:
67
88
 
68
89
  - 容器顶格。子项可以缩进,正文行缩进到 4 格会被 CommonMark 判成代码块。
69
90
  - 属性只认 `a="b"` 和裸布尔,`{...}` 表达式不支持。
70
91
  - 白名单外的标签,连同里面的内容按文本原样显示。想要一个能挂 `class` 的分块,用 `div`。
71
- - `Image`、`Card`、`File` 能自闭合,其他容器必须写结束标签。
92
+ - `Image`、`Video`、`Card`、`File` 能自闭合,其他容器必须写结束标签。
72
93
  - 嵌套最多 3 层,超出的那层按原文输出。
73
94
 
74
95
  ## 解析与序列化
@@ -167,7 +188,7 @@ cookie、`<html lang>`,那些在 SSR 下会让首屏语言对不上。确实
167
188
 
168
189
  引一次 `@heikeson/md-engine/styles.css`。配色走独立的 `--lkes-*` 变量,九个令牌,亮暗各一套
169
190
  字面量,祖先加 `.dark` 或者 `[data-theme="dark"]` 就整体切暗色。变量清单和覆盖写法在
170
- [对接契约.md](./对接契约.md) 第 9 节。
191
+ [对接契约.md](./对接契约.md) 第 10 节(英文版 [对接契约.en.md](./对接契约.en.md))。
171
192
 
172
193
  按组件拆分也行,`styles/*.css` 在 npm 包里是原样发布的。但令牌单独放在 `tokens.css`,
173
194
  只引分片就拿不到 `--lkes-*`,暗色失效、颜色退回兜底值。顺序也有讲究,`tokens` 得在前,
@@ -189,7 +210,7 @@ npm run build # dist 和 dist/styles.css
189
210
  ```
190
211
 
191
212
  `dev/`、`docs/`、`site/` 都不进发布包,`files` 里只有 `dist`、`styles`、`README.md`、
192
- `对接契约.md`、`LICENSE`。
213
+ `README.en.md`、`对接契约.md`、`对接契约.en.md`、`LICENSE`。
193
214
 
194
215
  ```
195
216
  src/
@@ -1,6 +1,7 @@
1
1
  // src/locales/en-US.ts
2
2
  var enUS = {
3
3
  // —— 组件 ——
4
+ imageZoomOpen: "Open larger image",
4
5
  imageZoomClose: "Close zoomed image",
5
6
  // —— Mermaid ——
6
7
  mermaidSourceView: "Source view",
@@ -1,6 +1,7 @@
1
1
  // src/locales/zh-CN.ts
2
2
  var zhCN = {
3
3
  // —— 组件 ——
4
+ imageZoomOpen: "\u653E\u5927\u67E5\u770B\u56FE\u7247",
4
5
  imageZoomClose: "\u5173\u95ED\u653E\u5927\u56FE\u7247",
5
6
  // —— Mermaid ——
6
7
  mermaidSourceView: "\u6E90\u7801\u89C6\u56FE",
@@ -1,5 +1,5 @@
1
- import { mdxComponents, isSafeHref } from './chunk-2A72VTCO.js';
2
- import { useShallowStable, MdEngineProvider } from './chunk-SGORBOHN.js';
1
+ import { mdxComponents, isSafeHref } from './chunk-Y3B7I6LZ.js';
2
+ import { useShallowStable, MdEngineProvider } from './chunk-W463Q7LK.js';
3
3
  import { asciiAlpha, asciiAlphanumeric, markdownLineEnding, markdownSpace } from 'micromark-util-character';
4
4
  import { fromMarkdown } from 'mdast-util-from-markdown';
5
5
  import remarkGfm from 'remark-gfm';
@@ -40,7 +40,11 @@ var ITEMS = {
40
40
  attrs: ["name", "type", "default"],
41
41
  boolAttrs: ["required"],
42
42
  selfClosing: true
43
- }
43
+ },
44
+ // 列布局子项:width 为比例("2" 占 2 份)或带单位宽度("320px");不写则等分
45
+ Column: { name: "Column", attrs: ["width"] },
46
+ // 时间线子项:date 时间标识、title 标题、type 语气(note / tip / warning / danger)
47
+ TimelineItem: { name: "TimelineItem", attrs: ["date", "title", "type"] }
44
48
  };
45
49
  var COMPONENTS = {
46
50
  Callout: {
@@ -58,6 +62,17 @@ var COMPONENTS = {
58
62
  Files: { name: "Files", mode: "visual", items: ["Folder", "File"] },
59
63
  // 类型表:fumadocs 的 TypeTable,但属性只支持字符串,故用子项而非对象表达式
60
64
  TypeTable: { name: "TypeTable", mode: "visual", items: "TypeItem" },
65
+ // 多列布局:子项 Column 的 width 决定比例或固定宽度,窄屏自动堆叠
66
+ Columns: { name: "Columns", mode: "visual", items: "Column" },
67
+ // 时间线:子项 TimelineItem 带 date / title / type,竖线与节点由包内样式绘制
68
+ Timeline: { name: "Timeline", mode: "visual", items: "TimelineItem" },
69
+ // 视频:自闭合叶子,src / poster 与 Image 同口径走协议白名单
70
+ Video: {
71
+ name: "Video",
72
+ mode: "visual",
73
+ selfClosing: true,
74
+ attrs: ["src", "poster", "caption", "width"]
75
+ },
61
76
  Image: {
62
77
  name: "Image",
63
78
  mode: "visual",
@@ -1,5 +1,5 @@
1
- import { zhCN } from './chunk-RWT2RMCY.js';
2
- import { enUS } from './chunk-P4SAIRGF.js';
1
+ import { zhCN } from './chunk-JUWL5RG7.js';
2
+ import { enUS } from './chunk-BMAGJMFB.js';
3
3
  import { IntlMessageFormat } from 'intl-messageformat';
4
4
  import { createContext, useRef, useContext, useState, useEffect, useMemo } from 'react';
5
5
  import { jsx } from 'react/jsx-runtime';
@@ -1,4 +1,4 @@
1
- import { useUIText } from './chunk-SGORBOHN.js';
1
+ import { useUIText } from './chunk-W463Q7LK.js';
2
2
  import { useState, Children, isValidElement, useEffect, useRef, useId } from 'react';
3
3
  import { ChevronDown, Lightbulb, XCircle, AlertTriangle, AlertCircle, Info, FileType, FileKey, FileLock, FileTerminal, FileSpreadsheet, FileArchive, FileMusic, FilePlay, FileImage, FileBraces, FileText, FileCode } from 'lucide-react';
4
4
  import { clsx } from 'clsx';
@@ -131,6 +131,28 @@ function Cards({ children }) {
131
131
  return safeHref ? /* @__PURE__ */ jsx("a", { href: safeHref, className: cls, children: inner }, i) : /* @__PURE__ */ jsx("div", { className: cls, children: inner }, i);
132
132
  }) });
133
133
  }
134
+ function Column(props) {
135
+ return /* @__PURE__ */ jsx(Fragment, { children: props.children });
136
+ }
137
+ var WIDTH_RE = /^\d+(?:\.\d+)?(?:px|%|rem|em|ch|vw)?$/;
138
+ var RATIO_RE = /^\d+(?:\.\d+)?$/;
139
+ function columnVars(width) {
140
+ if (!width) return void 0;
141
+ const value = width.trim();
142
+ if (!WIDTH_RE.test(value)) return void 0;
143
+ if (RATIO_RE.test(value)) {
144
+ const ratio = Number(value);
145
+ return ratio > 0 ? { "--lkes-col-grow": ratio } : void 0;
146
+ }
147
+ return { "--lkes-col-basis": value };
148
+ }
149
+ function Columns({ children }) {
150
+ const items = Children.toArray(children).filter(isValidElement);
151
+ return /* @__PURE__ */ jsx("div", { className: "columns", children: items.map((el, i) => {
152
+ const { width, children: body } = el.props;
153
+ return /* @__PURE__ */ jsx("div", { className: "column", style: columnVars(width), children: body }, i);
154
+ }) });
155
+ }
134
156
  var OPEN_LID_PATH = "M1 12.3L2.5 9.95A1.4 1.4 0 013.7 9.3h10.05a1.25 1.25 0 011.2 1.6l-1.13 3.3a1.4 1.4 0 01-1.32.93H2.4A1.4 1.4 0 011 13.73V12.3z";
135
157
  function FileIcon() {
136
158
  return /* @__PURE__ */ jsxs("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", className: "files-icon", children: [
@@ -355,10 +377,40 @@ function Folder({ name, defaultOpen, children }) {
355
377
  /* @__PURE__ */ jsx("div", { className: "files-children", children })
356
378
  ] });
357
379
  }
380
+
381
+ // src/internal/width.ts
382
+ var LENGTH_RE = /^\d+(?:\.\d+)?(?:px|%|rem|em|ch|vw)?$/;
383
+ var BARE_NUMBER_RE = /^\d+(?:\.\d+)?$/;
384
+ var FRACTION_RE = /^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/;
385
+ var MAX_PERCENT = 100;
386
+ function parseWidth(value) {
387
+ if (value === void 0 || value === null) return void 0;
388
+ const text = typeof value === "number" ? String(value) : value.trim();
389
+ if (text === "" || text === "auto") return void 0;
390
+ const fraction = FRACTION_RE.exec(text);
391
+ if (fraction) {
392
+ const numerator = Number(fraction[1]);
393
+ const denominator = Number(fraction[2]);
394
+ if (!(numerator > 0) || !(denominator > 0)) return void 0;
395
+ const percent = Math.min(MAX_PERCENT, numerator / denominator * MAX_PERCENT);
396
+ return `${Number(percent.toFixed(2))}%`;
397
+ }
398
+ if (!LENGTH_RE.test(text)) return void 0;
399
+ if (text.endsWith("%")) {
400
+ const percent = Number(text.slice(0, -1));
401
+ if (!Number.isFinite(percent)) return void 0;
402
+ return `${Number(Math.min(MAX_PERCENT, percent).toFixed(2))}%`;
403
+ }
404
+ return BARE_NUMBER_RE.test(text) ? `${text}px` : text;
405
+ }
406
+ var ALIGNS = ["left", "center", "right"];
407
+ function alignOf(value) {
408
+ return value && ALIGNS.includes(value) ? value : "center";
409
+ }
358
410
  function Image({
359
411
  src,
360
412
  alt,
361
- align = "center",
413
+ align: alignProp,
362
414
  width,
363
415
  caption,
364
416
  zoom,
@@ -366,33 +418,58 @@ function Image({
366
418
  }) {
367
419
  const [open, setOpen] = useState(false);
368
420
  const maskRef = useRef(null);
421
+ const triggerRef = useRef(null);
422
+ const wasOpen = useRef(false);
369
423
  const text = useUIText();
370
424
  const safeSrc = src && isSafeHref(src) ? src : void 0;
371
- const w = width ? typeof width === "number" ? `${width}px` : width : void 0;
372
- const figStyle = { width: w };
373
- if (align === "center" && !width) figStyle.marginInline = "auto";
425
+ const align = alignOf(alignProp);
426
+ const w = parseWidth(width);
374
427
  useEffect(() => {
375
- if (!open) return;
428
+ if (!open) {
429
+ if (wasOpen.current) {
430
+ wasOpen.current = false;
431
+ triggerRef.current?.focus();
432
+ }
433
+ return;
434
+ }
435
+ wasOpen.current = true;
436
+ maskRef.current?.focus();
376
437
  const onKey = (event) => {
377
438
  if (event.key === "Escape") setOpen(false);
378
439
  };
440
+ const previousOverflow = document.body.style.overflow;
441
+ document.body.style.overflow = "hidden";
379
442
  window.addEventListener("keydown", onKey);
380
- return () => window.removeEventListener("keydown", onKey);
381
- }, [open]);
382
- useEffect(() => {
383
- if (open) maskRef.current?.focus();
443
+ return () => {
444
+ document.body.style.overflow = previousOverflow;
445
+ window.removeEventListener("keydown", onKey);
446
+ };
384
447
  }, [open]);
385
- return /* @__PURE__ */ jsxs("figure", { className: cn("image", `align-${align}`), style: figStyle, children: [
448
+ if (!safeSrc && !caption && !children) return null;
449
+ return /* @__PURE__ */ jsxs("figure", { className: cn("image", `align-${align}`), style: w ? { width: w } : void 0, children: [
386
450
  safeSrc ? (
387
451
  // eslint-disable-next-line @next/next/no-img-element
388
452
  /* @__PURE__ */ jsx(
389
453
  "img",
390
454
  {
455
+ ref: triggerRef,
391
456
  src: safeSrc,
392
457
  alt: alt ?? "",
393
- style: { width: w },
458
+ loading: "lazy",
459
+ decoding: "async",
460
+ style: w ? { width: "100%" } : void 0,
394
461
  className: cn("image-img", zoom && "image-img-zoomable"),
395
- onClick: zoom ? () => setOpen(true) : void 0
462
+ role: zoom ? "button" : void 0,
463
+ tabIndex: zoom ? 0 : void 0,
464
+ "aria-label": zoom ? text.imageZoomOpen : void 0,
465
+ "aria-haspopup": zoom ? "dialog" : void 0,
466
+ onClick: zoom ? () => setOpen(true) : void 0,
467
+ onKeyDown: zoom ? (event) => {
468
+ if (event.key === "Enter" || event.key === " ") {
469
+ event.preventDefault();
470
+ setOpen(true);
471
+ }
472
+ } : void 0
396
473
  }
397
474
  )
398
475
  ) : null,
@@ -402,9 +479,10 @@ function Image({
402
479
  {
403
480
  ref: maskRef,
404
481
  className: "image-zoom-mask",
405
- role: "button",
406
- tabIndex: 0,
482
+ role: "dialog",
483
+ "aria-modal": "true",
407
484
  "aria-label": text.imageZoomClose,
485
+ tabIndex: -1,
408
486
  onClick: () => setOpen(false),
409
487
  onKeyDown: (event) => {
410
488
  if (event.key === "Enter" || event.key === " ") {
@@ -412,7 +490,7 @@ function Image({
412
490
  setOpen(false);
413
491
  }
414
492
  },
415
- children: /* @__PURE__ */ jsx("img", { src, alt: alt ?? "", className: "image-zoom-img" })
493
+ children: /* @__PURE__ */ jsx("img", { src: safeSrc, alt: alt ?? "", className: "image-zoom-img" })
416
494
  }
417
495
  ) : null
418
496
  ] });
@@ -546,6 +624,27 @@ function Tabs({ children }) {
546
624
  }) })
547
625
  ] });
548
626
  }
627
+ var TONES = /* @__PURE__ */ new Set(["note", "tip", "warning", "danger"]);
628
+ function Timeline({ children }) {
629
+ const items = Children.toArray(children).filter(isValidElement);
630
+ return /* @__PURE__ */ jsx("div", { className: "timeline", children: items.map((el, i) => {
631
+ const { date, title, type, children: body } = el.props;
632
+ const tone = type && TONES.has(type) ? type : "note";
633
+ return /* @__PURE__ */ jsxs("div", { className: cn("timeline-item", `is-${tone}`), children: [
634
+ /* @__PURE__ */ jsx("span", { className: "timeline-marker", "aria-hidden": "true" }),
635
+ /* @__PURE__ */ jsxs("div", { className: "timeline-body", children: [
636
+ date || title ? /* @__PURE__ */ jsxs("div", { className: "timeline-head", children: [
637
+ date ? /* @__PURE__ */ jsx("span", { className: "timeline-date", children: date }) : null,
638
+ title ? /* @__PURE__ */ jsx("span", { className: "timeline-title", children: title }) : null
639
+ ] }) : null,
640
+ /* @__PURE__ */ jsx("div", { className: "timeline-content", children: body })
641
+ ] })
642
+ ] }, i);
643
+ }) });
644
+ }
645
+ function TimelineItem(props) {
646
+ return /* @__PURE__ */ jsx(Fragment, { children: props.children });
647
+ }
549
648
  function TypeItem({ name, type, default: defaultValue, required, children }) {
550
649
  const text = useUIText();
551
650
  const empty = text.typeItemEmpty;
@@ -572,6 +671,25 @@ function TypeTable({ children }) {
572
671
  /* @__PURE__ */ jsx("tbody", { children: items })
573
672
  ] }) });
574
673
  }
674
+ function Video({ src, poster, caption, width, children }) {
675
+ const safeSrc = src && isSafeHref(src) ? src : void 0;
676
+ const safePoster = poster && isSafeHref(poster) ? poster : void 0;
677
+ const w = parseWidth(width);
678
+ return /* @__PURE__ */ jsxs("figure", { className: "video", style: w ? { width: w } : void 0, children: [
679
+ safeSrc ? /* @__PURE__ */ jsx(
680
+ "video",
681
+ {
682
+ className: "video-el",
683
+ src: safeSrc,
684
+ poster: safePoster,
685
+ controls: true,
686
+ preload: "metadata",
687
+ playsInline: true
688
+ }
689
+ ) : null,
690
+ caption ? /* @__PURE__ */ jsx("figcaption", { children: caption }) : children ? /* @__PURE__ */ jsx("figcaption", { children }) : null
691
+ ] });
692
+ }
575
693
 
576
694
  // src/components/index.ts
577
695
  var mdxComponents = {
@@ -589,9 +707,14 @@ var mdxComponents = {
589
707
  File,
590
708
  TypeTable,
591
709
  TypeItem,
710
+ Columns,
711
+ Column,
712
+ Timeline,
713
+ TimelineItem,
714
+ Video,
592
715
  Image,
593
716
  // 图表:主入口只出源码骨架;交互由 `/mermaid` 入口通过 components 覆写替换
594
717
  Mermaid: MermaidPlaceholder
595
718
  };
596
719
 
597
- export { AccItem, Accordion, Callout, Card, Cards, File, Files, Folder, Image, MermaidPlaceholder, Step, Steps, Tab, Tabs, TypeItem, TypeTable, isSafeHref, mdxComponents };
720
+ export { AccItem, Accordion, Callout, Card, Cards, Column, Columns, File, Files, Folder, Image, MermaidPlaceholder, Step, Steps, Tab, Tabs, Timeline, TimelineItem, TypeItem, TypeTable, Video, isSafeHref, mdxComponents };