@heikeson/md-engine 0.3.1 → 0.5.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 (46) hide show
  1. package/README.md +76 -6
  2. package/dist/{chunk-4TDQECWJ.js → chunk-KC6CBSFU.js} +114 -17
  3. package/dist/chunk-KC6CBSFU.js.map +1 -0
  4. package/dist/chunk-OG47YL3H.js +68 -0
  5. package/dist/chunk-OG47YL3H.js.map +1 -0
  6. package/dist/chunk-OJQDOFGL.js +313 -0
  7. package/dist/chunk-OJQDOFGL.js.map +1 -0
  8. package/dist/{chunk-SUI5PVAV.js → chunk-USP2GQZF.js} +321 -127
  9. package/dist/chunk-USP2GQZF.js.map +1 -0
  10. package/dist/chunk-YJGGJP2V.js +68 -0
  11. package/dist/chunk-YJGGJP2V.js.map +1 -0
  12. package/dist/components/index.d.ts +6 -2
  13. package/dist/components/index.js +4 -1
  14. package/dist/editor/index.d.ts +30 -11
  15. package/dist/editor/index.js +193 -88
  16. package/dist/editor/index.js.map +1 -1
  17. package/dist/index.d.ts +155 -41
  18. package/dist/index.js +6 -3
  19. package/dist/index.js.map +1 -1
  20. package/dist/locales/en-US.d.ts +68 -0
  21. package/dist/locales/en-US.js +3 -0
  22. package/dist/locales/en-US.js.map +1 -0
  23. package/dist/locales/zh-CN.d.ts +68 -0
  24. package/dist/locales/zh-CN.js +3 -0
  25. package/dist/locales/zh-CN.js.map +1 -0
  26. package/dist/mermaid/index.d.ts +209 -0
  27. package/dist/mermaid/index.js +708 -0
  28. package/dist/mermaid/index.js.map +1 -0
  29. package/dist/mermaid-placeholder-DYfFG3_f.d.ts +40 -0
  30. package/dist/render-DbUepYgE.d.ts +247 -0
  31. package/dist/styles.css +1 -1
  32. package/package.json +29 -3
  33. package/styles/accordion.css +1 -1
  34. package/styles/callout.css +2 -2
  35. package/styles/cards.css +9 -1
  36. package/styles/editor.css +1 -1
  37. package/styles/files.css +12 -5
  38. package/styles/image.css +5 -5
  39. package/styles/index.css +3 -0
  40. package/styles/mermaid.css +269 -0
  41. package/styles/steps.css +1 -1
  42. package/styles/tokens.css +32 -14
  43. package/styles/type-table.css +2 -2
  44. package//345/257/271/346/216/245/345/245/221/347/272/246.md +180 -7
  45. package/dist/chunk-4TDQECWJ.js.map +0 -1
  46. package/dist/chunk-SUI5PVAV.js.map +0 -1
@@ -1,11 +1,14 @@
1
- import { COMPONENTS, parse, normalizeMarkdown, MarkdownRenderer } from '../chunk-SUI5PVAV.js';
2
- import '../chunk-4TDQECWJ.js';
3
- import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
4
- import { EditorState } from '@codemirror/state';
5
- import { EditorView, lineNumbers, drawSelection, keymap } from '@codemirror/view';
1
+ import { COMPONENTS, parse, normalizeMarkdown, MarkdownRenderer, formatDiagnostic } from '../chunk-USP2GQZF.js';
2
+ import '../chunk-KC6CBSFU.js';
3
+ import { useShallowStable, MdEngineProvider, useUIText, useMessage } from '../chunk-OJQDOFGL.js';
4
+ import '../chunk-OG47YL3H.js';
5
+ import '../chunk-YJGGJP2V.js';
6
+ import { useMemo, useState, useRef, useDeferredValue, useEffect, useCallback } from 'react';
7
+ import { Compartment, EditorState } from '@codemirror/state';
8
+ import { EditorView, keymap, lineNumbers, drawSelection, placeholder } from '@codemirror/view';
6
9
  import { history, defaultKeymap, historyKeymap } from '@codemirror/commands';
7
10
  import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
8
- import { jsxs, jsx } from 'react/jsx-runtime';
11
+ import { jsx, jsxs } from 'react/jsx-runtime';
9
12
 
10
13
  // src/editor/actions.ts
11
14
  function wrapSelection(value, selection, before, after, placeholder = "\u6587\u672C") {
@@ -43,6 +46,30 @@ function insertBlockAt(value, position, snippet) {
43
46
  const cursor = before.length + lead.length + bodyWithoutBreak.length;
44
47
  return { value: next, selection: { start: cursor, end: cursor } };
45
48
  }
49
+ function buildShortcuts(wrapPlaceholder) {
50
+ return [
51
+ { key: "Mod-b", run: (d, s) => wrapSelection(d, s, "**", "**", wrapPlaceholder) },
52
+ { key: "Mod-i", run: (d, s) => wrapSelection(d, s, "*", "*", wrapPlaceholder) },
53
+ { key: "Mod-e", run: (d, s) => wrapSelection(d, s, "`", "`", wrapPlaceholder) },
54
+ { key: "Mod-Shift-s", run: (d, s) => wrapSelection(d, s, "~~", "~~", wrapPlaceholder) },
55
+ { key: "Mod-1", run: (d, s) => toggleLinePrefix(d, s, "## ") },
56
+ { key: "Mod-Shift-q", run: (d, s) => toggleLinePrefix(d, s, "> ") },
57
+ { key: "Mod-Shift-l", run: (d, s) => toggleLinePrefix(d, s, "- ") }
58
+ ];
59
+ }
60
+ function runTextAction(view, run) {
61
+ if (view.state.readOnly) return false;
62
+ const doc = view.state.doc.toString();
63
+ const { from, to } = view.state.selection.main;
64
+ const result = run(doc, { start: from, end: to });
65
+ const change = diffChange(doc, result.value);
66
+ view.dispatch({
67
+ changes: change ?? void 0,
68
+ selection: { anchor: result.selection.start, head: result.selection.end },
69
+ scrollIntoView: true
70
+ });
71
+ return true;
72
+ }
46
73
  var THEME = EditorView.theme({
47
74
  "&": {
48
75
  height: "100%",
@@ -77,7 +104,15 @@ var THEME = EditorView.theme({
77
104
  }
78
105
  });
79
106
  function createEditor(options) {
80
- const { parent, value, onChange, onSelection, onImage, readOnly } = options;
107
+ const { parent, value, onChange, onSelection, onImage, readOnly, wrapPlaceholder, placeholder: placeholder$1 } = options;
108
+ const placeholderCompartment = new Compartment();
109
+ const shortcutKeymap = keymap.of(
110
+ buildShortcuts(wrapPlaceholder ?? "\u6587\u672C").map((item) => ({
111
+ key: item.key,
112
+ preventDefault: true,
113
+ run: (view2) => runTextAction(view2, item.run)
114
+ }))
115
+ );
81
116
  const view = new EditorView({
82
117
  parent,
83
118
  state: EditorState.create({
@@ -87,6 +122,7 @@ function createEditor(options) {
87
122
  history(),
88
123
  drawSelection(),
89
124
  EditorView.lineWrapping,
125
+ shortcutKeymap,
90
126
  keymap.of([...defaultKeymap, ...historyKeymap]),
91
127
  markdown({ base: markdownLanguage }),
92
128
  THEME,
@@ -111,6 +147,7 @@ function createEditor(options) {
111
147
  return true;
112
148
  }
113
149
  }),
150
+ placeholderCompartment.of(placeholder(placeholder$1 ?? "")),
114
151
  EditorState.readOnly.of(Boolean(readOnly)),
115
152
  EditorView.updateListener.of((update) => {
116
153
  if (update.docChanged) onChange(update.state.doc.toString());
@@ -145,6 +182,11 @@ function createEditor(options) {
145
182
  if (!change) return;
146
183
  view.dispatch({ changes: change });
147
184
  },
185
+ setPlaceholder: (next) => {
186
+ view.dispatch({
187
+ effects: placeholderCompartment.reconfigure(placeholder(next))
188
+ });
189
+ },
148
190
  focus: () => view.focus(),
149
191
  destroy: () => view.destroy()
150
192
  };
@@ -162,73 +204,107 @@ function diffChange(prev, next) {
162
204
  }
163
205
  return { from: start, to: prevEnd, insert: next.slice(start, nextEnd) };
164
206
  }
207
+
208
+ // src/editor/scroll-sync.ts
165
209
  var LOCK_MS = 120;
210
+ function indexByOffset(list, pos) {
211
+ let low = 0;
212
+ let high = list.length - 1;
213
+ let found = -1;
214
+ while (low <= high) {
215
+ const mid = low + high >> 1;
216
+ if (list[mid].offset <= pos) {
217
+ found = mid;
218
+ low = mid + 1;
219
+ } else {
220
+ high = mid - 1;
221
+ }
222
+ }
223
+ return found;
224
+ }
225
+ function indexByTop(list, y) {
226
+ let low = 0;
227
+ let high = list.length - 1;
228
+ let found = -1;
229
+ while (low <= high) {
230
+ const mid = low + high >> 1;
231
+ if (list[mid].top <= y) {
232
+ found = mid;
233
+ low = mid + 1;
234
+ } else {
235
+ high = mid - 1;
236
+ }
237
+ }
238
+ return found;
239
+ }
240
+ function segmentOf(list, index, metric, value) {
241
+ if (list.length === 0) return null;
242
+ if (index < 0) return { a: list[0], b: null, t: 0 };
243
+ const a = list[index];
244
+ const b = list[index + 1] ?? null;
245
+ if (!b) return { a, b: null, t: 1 };
246
+ const span = metric(b) - metric(a);
247
+ const t = span > 0 ? Math.min(1, Math.max(0, (value - metric(a)) / span)) : 0;
248
+ return { a, b, t };
249
+ }
166
250
  function createScrollSync(view, preview) {
167
251
  let owner = null;
168
252
  let releaseTimer = 0;
169
253
  let frame = 0;
170
254
  let cache = null;
171
255
  function rebuild() {
172
- const nodes = preview.querySelectorAll("[data-src-start]");
256
+ const nodes = Array.from(preview.querySelectorAll("[data-src-start]"));
173
257
  const origin = preview.getBoundingClientRect().top - preview.scrollTop;
174
- const list = [];
258
+ const raw = [];
175
259
  for (const el of nodes) {
260
+ if (el.querySelector("[data-src-start]")) continue;
176
261
  const offset = Number(el.dataset.srcStart);
177
262
  if (!Number.isFinite(offset)) continue;
178
- list.push({ el, offset, top: el.getBoundingClientRect().top - origin });
263
+ raw.push({ offset, top: el.getBoundingClientRect().top - origin });
264
+ }
265
+ raw.sort((a, b) => a.offset - b.offset || a.top - b.top);
266
+ const list = [];
267
+ for (const item of raw) {
268
+ const last = list[list.length - 1];
269
+ if (last && item.top < last.top) continue;
270
+ list.push(item);
179
271
  }
180
- list.sort((a, b) => a.top - b.top);
181
272
  cache = list;
182
273
  }
183
274
  function anchors() {
184
275
  if (!cache) rebuild();
185
276
  return cache ?? [];
186
277
  }
187
- function findByTop(y) {
278
+ function yForOffset(pos) {
188
279
  const list = anchors();
189
- if (list.length === 0) return null;
190
- let low = 0;
191
- let high = list.length - 1;
192
- let found = 0;
193
- while (low <= high) {
194
- const mid = low + high >> 1;
195
- if (list[mid].top <= y) {
196
- found = mid;
197
- low = mid + 1;
198
- } else {
199
- high = mid - 1;
200
- }
201
- }
202
- return list[found];
280
+ const seg = segmentOf(list, indexByOffset(list, pos), (anchor) => anchor.offset, pos);
281
+ if (!seg) return null;
282
+ if (!seg.b) return seg.a.top;
283
+ return seg.a.top + seg.t * (seg.b.top - seg.a.top);
203
284
  }
204
- function findByOffset(pos) {
285
+ function posForTop(y) {
205
286
  const list = anchors();
206
- if (list.length === 0) return null;
207
- let low = 0;
208
- let high = list.length - 1;
209
- let found = 0;
210
- while (low <= high) {
211
- const mid = low + high >> 1;
212
- if (list[mid].offset <= pos) {
213
- found = mid;
214
- low = mid + 1;
215
- } else {
216
- high = mid - 1;
217
- }
218
- }
219
- return list[found];
287
+ const seg = segmentOf(list, indexByTop(list, y), (anchor) => anchor.top, y);
288
+ if (!seg) return null;
289
+ if (!seg.b) return seg.a.offset;
290
+ return Math.round(seg.a.offset + seg.t * (seg.b.offset - seg.a.offset));
291
+ }
292
+ function sourceTopPos() {
293
+ const rect = view.scrollDOM.getBoundingClientRect();
294
+ const pos = view.posAtCoords({ x: rect.left + 4, y: rect.top + 1 });
295
+ if (pos !== null) return pos;
296
+ return view.lineBlockAtHeight(view.scrollDOM.scrollTop).from;
220
297
  }
221
298
  function syncPreviewFromSource() {
222
- const viewportTop = view.scrollDOM.scrollTop;
223
- const block = view.lineBlockAtHeight(viewportTop);
224
- const pos = view.state.doc.lineAt(block.from).from;
225
- const hit = findByOffset(pos);
226
- preview.scrollTop = hit ? hit.top : 0;
299
+ const y = yForOffset(sourceTopPos());
300
+ if (y === null) return;
301
+ preview.scrollTop = y;
227
302
  }
228
303
  function syncSourceFromPreview() {
229
- const hit = findByTop(preview.scrollTop + 1);
230
- if (!hit) return;
231
- view.dispatch({ effects: EditorView.scrollIntoView(hit.offset, { y: "start" }) });
304
+ const pos = posForTop(preview.scrollTop + 1);
305
+ if (pos === null) return;
306
+ const block = view.lineBlockAt(pos);
307
+ view.scrollDOM.scrollTop = block.top;
232
308
  }
233
309
  function lock(who) {
234
310
  owner = who;
@@ -295,6 +371,14 @@ var FILES_SNIPPET = `<Files>
295
371
  function blockSnippet(name) {
296
372
  const spec = COMPONENTS[name];
297
373
  if (!spec) return "";
374
+ if (spec.rawBody) {
375
+ return `<${name} title="\u56FE\u8868\u6807\u9898">
376
+ graph TD
377
+ A[\u5F00\u59CB] --> B{\u5224\u65AD}
378
+ B -->|\u662F| C[\u6267\u884C]
379
+ </${name}>
380
+ `;
381
+ }
298
382
  if (spec.selfClosing) {
299
383
  return `<${name} src="" alt="" />
300
384
  `;
@@ -336,32 +420,47 @@ var INSERTABLE_BLOCKS = [
336
420
  "Accordion",
337
421
  "Files",
338
422
  "TypeTable",
339
- "Image"
423
+ "Image",
424
+ "Mermaid"
340
425
  ];
341
426
  var VIEW_OPTIONS = [
342
- { value: "source", label: "\u7F16\u8F91" },
343
- { value: "split", label: "\u5206\u5C4F" },
344
- { value: "preview", label: "\u9884\u89C8" }
427
+ { value: "source", labelKey: "editorViewSource" },
428
+ { value: "split", labelKey: "editorViewSplit" },
429
+ { value: "preview", labelKey: "editorViewPreview" }
345
430
  ];
346
431
  var WRAP_ITEMS = [
347
- { key: "bold", label: "\u7C97\u4F53", before: "**", after: "**" },
348
- { key: "italic", label: "\u659C\u4F53", before: "*", after: "*" },
349
- { key: "strike", label: "\u5220\u9664\u7EBF", before: "~~", after: "~~" },
350
- { key: "code", label: "\u884C\u5185\u7801", before: "`", after: "`" }
432
+ { key: "bold", labelKey: "editorBold", before: "**", after: "**" },
433
+ { key: "italic", labelKey: "editorItalic", before: "*", after: "*" },
434
+ { key: "strike", labelKey: "editorStrike", before: "~~", after: "~~" },
435
+ { key: "code", labelKey: "editorCode", before: "`", after: "`" }
351
436
  ];
352
437
  var LINE_ITEMS = [
353
- { key: "h2", label: "H2", prefix: "## " },
354
- { key: "quote", label: "\u5F15\u7528", prefix: "> " },
355
- { key: "list", label: "\u5217\u8868", prefix: "- " }
438
+ { key: "h2", labelKey: "editorH2", prefix: "## " },
439
+ { key: "quote", labelKey: "editorQuote", prefix: "> " },
440
+ { key: "list", labelKey: "editorList", prefix: "- " }
356
441
  ];
357
- function MarkdownEditor({
358
- value,
359
- onChange,
360
- view = "split",
361
- config,
362
- fullscreen,
363
- onToggleFullscreen
364
- }) {
442
+ function MarkdownEditor(props) {
443
+ const { config } = props;
444
+ const textPatch = useShallowStable(config?.text);
445
+ const messages = useShallowStable(config?.messages);
446
+ const patch = useMemo(() => {
447
+ if (!textPatch) return messages;
448
+ if (!messages) return textPatch;
449
+ return { ...textPatch, ...messages };
450
+ }, [textPatch, messages]);
451
+ return /* @__PURE__ */ jsx(
452
+ MdEngineProvider,
453
+ {
454
+ locale: config?.locale,
455
+ fallbackLocale: config?.fallbackLocale,
456
+ messages: patch,
457
+ children: /* @__PURE__ */ jsx(EditorShell, { ...props })
458
+ }
459
+ );
460
+ }
461
+ function EditorShell({ value, onChange, view = "split", config, fullscreen, onToggleFullscreen }) {
462
+ const text = useUIText();
463
+ const t = useMessage();
365
464
  const [viewMode, setViewMode] = useState(view);
366
465
  const hostRef = useRef(null);
367
466
  const handleRef = useRef(null);
@@ -371,6 +470,8 @@ function MarkdownEditor({
371
470
  const imageHandlerRef = useRef(() => {
372
471
  });
373
472
  const [selection, setSelection] = useState({ start: 0, end: 0 });
473
+ const placeholder = config?.placeholder ?? text.editorPlaceholder;
474
+ const deferredValue = useDeferredValue(value);
374
475
  useEffect(() => {
375
476
  valueRef.current = value;
376
477
  onChangeRef.current = onChange;
@@ -420,14 +521,19 @@ function MarkdownEditor({
420
521
  onChange: (next) => onChangeRef.current(next),
421
522
  onSelection: setSelection,
422
523
  onImage: (file) => imageHandlerRef.current(file),
423
- readOnly: config?.readOnly
524
+ readOnly: config?.readOnly,
525
+ wrapPlaceholder: text.editorWrapPlaceholder,
526
+ placeholder
424
527
  });
425
528
  handleRef.current = handle;
426
529
  return () => {
427
530
  handle.destroy();
428
531
  handleRef.current = null;
429
532
  };
430
- }, [viewMode, config?.readOnly]);
533
+ }, [viewMode, config?.readOnly, text.editorWrapPlaceholder]);
534
+ useEffect(() => {
535
+ handleRef.current?.setPlaceholder(placeholder);
536
+ }, [placeholder]);
431
537
  useEffect(() => {
432
538
  if (viewMode !== "split") return;
433
539
  const handle = handleRef.current;
@@ -439,7 +545,7 @@ function MarkdownEditor({
439
545
  useEffect(() => {
440
546
  handleRef.current?.setDoc(value);
441
547
  }, [value]);
442
- const diagnostics = useMemo(() => parse(value).diagnostics, [value]);
548
+ const diagnostics = useMemo(() => parse(deferredValue).diagnostics, [deferredValue]);
443
549
  const handleBlur = useCallback(() => {
444
550
  const current = valueRef.current;
445
551
  const normalized = normalizeMarkdown(current);
@@ -453,9 +559,11 @@ function MarkdownEditor({
453
559
  "button",
454
560
  {
455
561
  type: "button",
456
- onClick: () => applyLive((doc, sel) => wrapSelection(doc, sel, item.before, item.after)),
562
+ onClick: () => applyLive(
563
+ (doc, sel) => wrapSelection(doc, sel, item.before, item.after, text.editorWrapPlaceholder)
564
+ ),
457
565
  disabled: config?.readOnly,
458
- children: item.label
566
+ children: text[item.labelKey]
459
567
  },
460
568
  item.key
461
569
  )),
@@ -466,7 +574,7 @@ function MarkdownEditor({
466
574
  type: "button",
467
575
  onClick: () => applyLive((doc, sel) => toggleLinePrefix(doc, sel, item.prefix)),
468
576
  disabled: config?.readOnly,
469
- children: item.label
577
+ children: text[item.labelKey]
470
578
  },
471
579
  item.key
472
580
  )),
@@ -475,6 +583,7 @@ function MarkdownEditor({
475
583
  "button",
476
584
  {
477
585
  type: "button",
586
+ title: t("editorInsertBlock", { name }),
478
587
  onClick: () => applyLive((doc, sel) => insertBlockAt(doc, sel.start, blockSnippet(name))),
479
588
  disabled: config?.readOnly,
480
589
  children: name
@@ -482,40 +591,36 @@ function MarkdownEditor({
482
591
  name
483
592
  )),
484
593
  /* @__PURE__ */ jsx("span", { className: "md-editor-grow" }),
485
- /* @__PURE__ */ jsx("div", { className: "md-editor-views", role: "group", "aria-label": "\u89C6\u56FE\u5207\u6362", children: VIEW_OPTIONS.map((option) => /* @__PURE__ */ jsx(
594
+ /* @__PURE__ */ jsx("div", { className: "md-editor-views", role: "group", "aria-label": text.editorViewGroup, children: VIEW_OPTIONS.map((option) => /* @__PURE__ */ jsx(
486
595
  "button",
487
596
  {
488
597
  type: "button",
489
598
  "data-active": viewMode === option.value,
490
599
  "aria-pressed": viewMode === option.value,
491
600
  onClick: () => setViewMode(option.value),
492
- children: option.label
601
+ children: text[option.labelKey]
493
602
  },
494
603
  option.value
495
604
  )) }),
496
- onToggleFullscreen ? /* @__PURE__ */ jsx("button", { type: "button", onClick: onToggleFullscreen, children: fullscreen ? "\u9000\u51FA\u5168\u5C4F" : "\u5168\u5C4F" }) : null
605
+ onToggleFullscreen ? /* @__PURE__ */ jsx("button", { type: "button", onClick: onToggleFullscreen, children: fullscreen ? text.editorExitFullscreen : text.editorFullscreen }) : null
497
606
  ] }),
498
607
  /* @__PURE__ */ jsxs("div", { className: "md-editor-body", onBlur: handleBlur, children: [
499
608
  viewMode !== "preview" && /* @__PURE__ */ jsx("div", { ref: hostRef, className: "md-editor-source" }),
500
609
  viewMode !== "source" && /* @__PURE__ */ jsx("div", { ref: previewRef, className: "md-editor-preview", children: /* @__PURE__ */ jsx(
501
610
  MarkdownRenderer,
502
611
  {
503
- content: value,
612
+ content: deferredValue,
504
613
  className: "prose-site",
505
- config: { sourcePositions: true }
614
+ config: { ...config?.rendererConfig, sourcePositions: true }
506
615
  }
507
616
  ) })
508
617
  ] }),
509
618
  /* @__PURE__ */ jsxs("div", { className: "md-editor-status", children: [
510
- /* @__PURE__ */ jsxs("span", { children: [
511
- value.length,
512
- " \u5B57"
513
- ] }),
514
- diagnostics.length > 0 && /* @__PURE__ */ jsxs("span", { className: "md-editor-status-warn", children: [
515
- diagnostics.length,
516
- " \u6761\u63D0\u793A\uFF1A",
517
- diagnostics[0].message
518
- ] })
619
+ /* @__PURE__ */ jsx("span", { children: t("editorWordCount", { n: value.length }) }),
620
+ diagnostics.length > 0 && /* @__PURE__ */ jsx("span", { className: "md-editor-status-warn", children: t("editorDiagnostic", {
621
+ n: diagnostics.length,
622
+ first: formatDiagnostic(t, diagnostics[0])
623
+ }) })
519
624
  ] })
520
625
  ] });
521
626
  }