markloom 0.5.0 → 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.
Files changed (67) hide show
  1. package/PACKAGES.md +26 -0
  2. package/README.md +20 -2
  3. package/collab.md +44 -7
  4. package/dist/ai/index.cjs +4 -4
  5. package/dist/ai/index.d.cts +5 -4
  6. package/dist/ai/index.d.ts +5 -4
  7. package/dist/ai/index.js +3 -3
  8. package/dist/ai/theme.css +66 -102
  9. package/dist/{chunk-YJAWPRJW.cjs → chunk-ACFYBYZJ.cjs} +2817 -903
  10. package/dist/chunk-CGYCJORO.js +759 -0
  11. package/dist/chunk-EADZKEU4.cjs +498 -0
  12. package/dist/chunk-EJSFZHGT.js +24 -0
  13. package/dist/{chunk-SLRD6FMP.cjs → chunk-I5VK4U7J.cjs} +122 -73
  14. package/dist/{chunk-WUHTCCAE.js → chunk-KYZJIOOL.js} +2403 -489
  15. package/dist/chunk-QEVME6ZU.cjs +759 -0
  16. package/dist/{chunk-MFYF2A6U.js → chunk-SNFF6X45.js} +51 -1
  17. package/dist/{chunk-JMOJU5EU.js → chunk-TB2OY3D4.js} +69 -20
  18. package/dist/{chunk-4TMHVNL6.cjs → chunk-TWD5T4YC.cjs} +155 -105
  19. package/dist/{chunk-JS527FDV.cjs → chunk-U3JZDFL4.cjs} +49 -9
  20. package/dist/{chunk-RLTHVQNQ.js → chunk-VSBIMMI7.js} +45 -5
  21. package/dist/chunk-YBAT343I.js +498 -0
  22. package/dist/chunk-ZKQSQSSM.cjs +24 -0
  23. package/dist/{client-BNams4wv.d.cts → client-CLYq17SW.d.ts} +70 -7
  24. package/dist/{client-A0ZQJnyR.d.ts → client-DAth8pPq.d.cts} +70 -7
  25. package/dist/collab/index.cjs +22 -4
  26. package/dist/collab/index.d.cts +24 -3
  27. package/dist/collab/index.d.ts +24 -3
  28. package/dist/collab/index.js +24 -6
  29. package/dist/{controller-BkY1VPzc.d.ts → controller-6AJ36G52.d.ts} +108 -8
  30. package/dist/{controller-CVIZI--A.d.cts → controller-BIOO_XKJ.d.cts} +108 -8
  31. package/dist/index.cjs +57 -7
  32. package/dist/index.d.cts +18 -5
  33. package/dist/index.d.ts +18 -5
  34. package/dist/index.js +54 -4
  35. package/dist/io/index.cjs +1413 -0
  36. package/dist/io/index.d.cts +33 -0
  37. package/dist/io/index.d.ts +33 -0
  38. package/dist/io/index.js +1413 -0
  39. package/dist/react/index.cjs +8 -8
  40. package/dist/react/index.d.cts +5 -4
  41. package/dist/react/index.d.ts +5 -4
  42. package/dist/react/index.js +7 -7
  43. package/dist/{rebase-batch-8rL_aXEE.d.ts → rebase-batch-DlerAcFN.d.ts} +11 -9
  44. package/dist/{rebase-batch-bYnBJpRO.d.cts → rebase-batch-PjENQ742.d.cts} +11 -9
  45. package/dist/suggest-Bk4zLzuv.d.ts +120 -0
  46. package/dist/suggest-BkGGiPKA.d.cts +120 -0
  47. package/dist/types-COUweEav.d.cts +30 -0
  48. package/dist/types-COUweEav.d.ts +30 -0
  49. package/dist/versions-9mG1epfB.d.cts +51 -0
  50. package/dist/versions-Bubyo4pt.d.ts +51 -0
  51. package/dist/view/index.cjs +56 -12
  52. package/dist/view/index.d.cts +203 -11
  53. package/dist/view/index.d.ts +203 -11
  54. package/dist/view/index.js +52 -8
  55. package/dist/view/theme.css +1840 -1526
  56. package/io.md +38 -0
  57. package/package.json +21 -5
  58. package/dist/chunk-6DCI7AL3.js +0 -208
  59. package/dist/chunk-AC5E42NH.cjs +0 -208
  60. package/dist/chunk-GQ2HHRGI.cjs +0 -16
  61. package/dist/chunk-LA5SBCGQ.js +0 -16
  62. package/dist/chunk-LEYAQNJA.js +0 -220
  63. package/dist/chunk-YXQDCW4Y.cjs +0 -220
  64. package/dist/comments-DlExS6f-.d.cts +0 -43
  65. package/dist/comments-PhnR7Gkn.d.ts +0 -43
  66. package/dist/step-BrvHIK7O.d.cts +0 -65
  67. package/dist/step-BrvHIK7O.d.ts +0 -65
@@ -1,24 +1,41 @@
1
1
  import {
2
+ acceptSuggestion,
2
3
  amend,
4
+ applyForeign,
3
5
  commit,
6
+ findText,
4
7
  firstViolation,
8
+ getVersion,
5
9
  init,
6
10
  invariants,
11
+ listSuggestions,
12
+ markSuggestRange,
7
13
  outline,
14
+ pushVersion,
15
+ rangeForDelete,
16
+ rangeIsSuggestInsert,
8
17
  redo,
18
+ rejectSuggestion,
19
+ removeVersion,
20
+ replaceAll,
21
+ replaceMatch,
22
+ snapshotDoc,
9
23
  stripCommentMarks,
24
+ suggestMark,
10
25
  undo
11
- } from "./chunk-LEYAQNJA.js";
26
+ } from "./chunk-CGYCJORO.js";
12
27
  import {
13
28
  MarkloomAi,
14
29
  createAiStream,
30
+ docExtent,
15
31
  elementChildren,
16
32
  pointToDom,
17
33
  readSelection,
18
34
  rootEl,
35
+ selectionCovers,
19
36
  startAiWrite,
20
37
  writeSelection
21
- } from "./chunk-JMOJU5EU.js";
38
+ } from "./chunk-TB2OY3D4.js";
22
39
  import {
23
40
  applyAll,
24
41
  arrowCell,
@@ -46,6 +63,7 @@ import {
46
63
  nextCell,
47
64
  nodeAt,
48
65
  pathOfId,
66
+ preferMarkdownPaste,
49
67
  rewriteNode,
50
68
  setAlign,
51
69
  setCellStyle,
@@ -53,15 +71,23 @@ import {
53
71
  setFreeze,
54
72
  splitCell,
55
73
  tableColWidths
56
- } from "./chunk-MFYF2A6U.js";
74
+ } from "./chunk-SNFF6X45.js";
57
75
  import {
76
+ collabCaretColor,
77
+ collabColor,
78
+ collabFg,
79
+ collabInitial,
58
80
  connectCollab
59
- } from "./chunk-6DCI7AL3.js";
81
+ } from "./chunk-YBAT343I.js";
82
+ import {
83
+ mapSelectionThrough,
84
+ resolveTxAfter
85
+ } from "./chunk-VSBIMMI7.js";
60
86
  import {
61
87
  isElement,
62
88
  isInlineAtom,
63
89
  isText
64
- } from "./chunk-LA5SBCGQ.js";
90
+ } from "./chunk-EJSFZHGT.js";
65
91
 
66
92
  // src/view/render.ts
67
93
  import { h as h2 } from "preact";
@@ -211,6 +237,13 @@ var ICONS = {
211
237
  "pen-line": [
212
238
  ["path", { d: "M12 20h9" }],
213
239
  ["path", { d: "M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z" }]
240
+ ],
241
+ // lucide zoom-in
242
+ "zoom-in": [
243
+ ["circle", { cx: 11, cy: 11, r: 8 }],
244
+ ["line", { x1: 21, x2: 16.65, y1: 21, y2: 16.65 }],
245
+ ["line", { x1: 11, x2: 11, y1: 8, y2: 14 }],
246
+ ["line", { x1: 8, x2: 14, y1: 11, y2: 11 }]
214
247
  ]
215
248
  };
216
249
  function icon(name, size2 = 16, className = "markloom-icon") {
@@ -306,6 +339,9 @@ function renderImage(spec, key, atomSelect) {
306
339
  const align = a.align === "center" || a.align === "right" ? a.align : void 0;
307
340
  const caption = typeof a.caption === "string" ? a.caption : "";
308
341
  const selected = atomIsSelected(spec.id, atomSelect);
342
+ const iw = a.w != null ? Number(a.w) : void 0;
343
+ const ih = a.h != null ? Number(a.h) : void 0;
344
+ const sizeStyle = iw != null && Number.isFinite(iw) ? `width:${iw}px;height:auto;max-width:100%` : void 0;
309
345
  const alignStyle = align === "center" ? "display:block;margin-left:auto;margin-right:auto" : align === "right" ? "display:block;margin-left:auto" : void 0;
310
346
  const imgProps = {
311
347
  "data-atom": "image",
@@ -314,14 +350,14 @@ function renderImage(spec, key, atomSelect) {
314
350
  "title": a.title,
315
351
  "data-load": "loading",
316
352
  "loading": "lazy",
317
- "width": a.w != null ? Number(a.w) : void 0,
318
- "height": a.h != null ? Number(a.h) : void 0,
353
+ "width": iw,
354
+ "height": ih,
319
355
  "onLoad": (e) => e.currentTarget.removeAttribute("data-load"),
320
356
  "onError": (e) => e.currentTarget.setAttribute("data-load", "error")
321
357
  };
322
358
  if (caption) {
323
359
  const { "data-atom": _a, ...innerImg } = imgProps;
324
- const figAlign = align === "center" ? "width:fit-content;max-width:100%;margin-left:auto;margin-right:auto;text-align:center" : align === "right" ? "width:fit-content;max-width:100%;margin-left:auto;text-align:right" : "width:fit-content;max-width:100%";
360
+ const figAlign = align === "center" ? "width:fit-content;max-width:100%;margin-left:auto;margin-right:auto;text-align:center" : align === "right" ? "width:fit-content;max-width:100%;margin-left:auto;text-align:center" : "width:fit-content;max-width:100%;text-align:center";
325
361
  return h2("figure", {
326
362
  "key": spec.id ?? key,
327
363
  "data-block-id": spec.id ?? "",
@@ -330,14 +366,15 @@ function renderImage(spec, key, atomSelect) {
330
366
  "contentEditable": "false",
331
367
  "class": "markloom-figure",
332
368
  "style": figAlign
333
- }, [h2("img", { key: "img", ...innerImg }), h2("figcaption", { key: "cap", "data-caption": "" }, caption)]);
369
+ }, [h2("img", { key: "img", style: sizeStyle, ...innerImg }), h2("figcaption", { key: "cap", "data-caption": "" }, caption)]);
334
370
  }
371
+ const boxStyle = [alignStyle, sizeStyle].filter(Boolean).join(";") || void 0;
335
372
  return h2("img", {
336
373
  "key": spec.id ?? key,
337
374
  "data-block-id": spec.id ?? "",
338
375
  "contentEditable": "false",
339
- "style": alignStyle,
340
376
  "data-selected": selected ? "" : void 0,
377
+ "style": boxStyle,
341
378
  ...imgProps
342
379
  });
343
380
  }
@@ -369,6 +406,7 @@ function markProps(mark, commentState) {
369
406
  const url = String(mark.attrs.url);
370
407
  return {
371
408
  "href": url,
409
+ "target": "_blank",
372
410
  "data-mark": "link",
373
411
  "class": "markloom-link",
374
412
  "rel": "noopener noreferrer",
@@ -388,6 +426,17 @@ function markProps(mark, commentState) {
388
426
  ].filter(Boolean).join(" ");
389
427
  return { "data-mark": "comment", "data-comment-id": id, class: cls };
390
428
  }
429
+ if (mark.name === "suggest") {
430
+ const id = String(mark.attrs?.id ?? "");
431
+ const kind = mark.attrs?.kind === "delete" ? "delete" : "insert";
432
+ return {
433
+ "data-mark": "suggest",
434
+ "data-suggest-id": id,
435
+ "data-suggest-kind": kind,
436
+ "class": `markloom-suggest-mark is-${kind}`,
437
+ "title": kind === "insert" ? "\u5EFA\u8BAE\u63D2\u5165" : "\u5EFA\u8BAE\u5220\u9664"
438
+ };
439
+ }
391
440
  return { "data-mark": mark.name };
392
441
  }
393
442
  function renderInlineAtom(spec, key, opts) {
@@ -659,7 +708,8 @@ function blockCtx(opts) {
659
708
  renderChild: (c, k) => renderNode(c, k, opts),
660
709
  slug: opts.slug,
661
710
  codeView: opts.codeView,
662
- atomSelect: opts.atomSelect
711
+ atomSelect: opts.atomSelect,
712
+ editable: opts.editable
663
713
  };
664
714
  }
665
715
  function renderNode(node, key, opts) {
@@ -742,7 +792,12 @@ function renderNode(node, key, opts) {
742
792
  }
743
793
  function renderCode(spec, key, ctx) {
744
794
  if (ctx.codeView)
745
- return ctx.codeView.render({ node: spec, text: leafText(spec), key: spec.id ?? key });
795
+ return ctx.codeView.render({
796
+ node: spec,
797
+ text: leafText(spec),
798
+ key: spec.id ?? key,
799
+ editable: ctx.editable
800
+ });
746
801
  const children = spec.children.length ? spec.children.map((c, i) => ctx.renderChild(c, i)) : [h2("span", { "key": 0, "data-leaf": 0 }, "\u200B")];
747
802
  return h2("pre", { "key": spec.id ?? key, "data-block-id": spec.id ?? "" }, children);
748
803
  }
@@ -751,6 +806,7 @@ function renderTable(spec, key, ctx) {
751
806
  const grid = buildGrid(spec);
752
807
  const freezeRows = Number(spec.attrs?.freezeRows ?? 0);
753
808
  const freezeCols = Number(spec.attrs?.freezeCols ?? 0);
809
+ const cellEdit = ctx.editable !== false;
754
810
  const cell = (cellNode, idx, tag) => {
755
811
  const m = grid.cellOf(idx);
756
812
  const a = align?.[m.c];
@@ -760,7 +816,8 @@ function renderTable(spec, key, ctx) {
760
816
  return h2(tag, {
761
817
  "key": idx,
762
818
  "data-block-id": cellNode.id ?? "",
763
- "contentEditable": true,
819
+ // 字符串:Preact 对布尔 false 会删属性,只读态就关不干净
820
+ "contentEditable": cellEdit ? "true" : "false",
764
821
  "class": "markloom-cell",
765
822
  "scope": tag === "th" ? "col" : void 0,
766
823
  "colSpan": m.colspan > 1 ? m.colspan : void 0,
@@ -797,7 +854,7 @@ function renderTable(spec, key, ctx) {
797
854
  "contentEditable": "false",
798
855
  // 字符串 'false':Preact 对布尔 false 会删属性,正文选区就跨得进来了
799
856
  "class": "markloom-table",
800
- "style": widths ? `width:${widths.reduce((a, b) => a + b, 0)}px` : "width:100%"
857
+ "style": widths ? `width:${widths.reduce((a, b) => a + b, 0)}px` : "width:max-content;min-width:100%"
801
858
  }, children);
802
859
  return h2("div", { "key": `w${spec.id ?? key}`, "data-pass": "", "class": "markloom-table-scroll" }, [table]);
803
860
  }
@@ -814,7 +871,7 @@ var defaultBlockRenderers = {
814
871
  embed: (spec, key, ctx) => renderEmbed(spec, key, ctx.atomSelect),
815
872
  raw: renderHr
816
873
  };
817
- function renderDoc(doc, opts = {}) {
874
+ function projectDoc(doc, opts = {}) {
818
875
  const pass = {
819
876
  slug: opts.slug?.(),
820
877
  codeView: opts.nodeViews?.code,
@@ -824,7 +881,8 @@ function renderDoc(doc, opts = {}) {
824
881
  renderMath: opts.renderMath,
825
882
  invisibleCharacters: opts.invisibleCharacters,
826
883
  commentState: opts.commentState,
827
- atomSelect: opts.atomSelect
884
+ atomSelect: opts.atomSelect,
885
+ editable: opts.editable !== false
828
886
  };
829
887
  const first = doc.children[0];
830
888
  const emptyLeaf = (n) => leafText(n) === "" && n.children.every((c) => isText(c));
@@ -836,7 +894,7 @@ function renderDoc(doc, opts = {}) {
836
894
  emptyDocPh = `H${Math.min(Math.max(Number(first.attrs?.depth ?? 1), 1), 6)}`;
837
895
  }
838
896
  let foldDepth = null;
839
- const kids = doc.children.map((c, i) => {
897
+ const children = doc.children.map((c, i) => {
840
898
  let foldHidden = false;
841
899
  if (!isText(c) && c.type === "heading") {
842
900
  const depth = Math.min(Math.max(Number(c.attrs?.depth ?? 2), 1), 6);
@@ -859,11 +917,15 @@ function renderDoc(doc, opts = {}) {
859
917
  }
860
918
  return vnode;
861
919
  });
862
- const cls = opts.invisibleCharacters ? "markloom-doc markloom-invisible" : "markloom-doc";
863
- return h2("div", { "class": cls, "data-markloom": true }, kids);
920
+ const className = opts.invisibleCharacters ? "markloom-doc markloom-invisible" : "markloom-doc";
921
+ return { className, children };
922
+ }
923
+ function renderDoc(doc, opts = {}) {
924
+ const { className, children } = projectDoc(doc, opts);
925
+ return h2("div", { "class": className, "data-markloom": true }, children);
864
926
  }
865
927
  function renderToHtml(doc, opts = {}) {
866
- return renderToString(renderDoc(doc, opts));
928
+ return renderToString(renderDoc(doc, { ...opts, editable: opts.editable ?? false }));
867
929
  }
868
930
 
869
931
  // src/view/input.ts
@@ -1010,6 +1072,10 @@ function deleteRange(doc, p1, p2) {
1010
1072
  insert.push(prunedTail);
1011
1073
  caret3 = headLives ? lo : insert.length ? [loTop, ...firstLeafPath(insert[0]), 0] : [loTop, 0, 0];
1012
1074
  }
1075
+ if (insert.length === 0 && loTop === 0 && hiTop >= doc.children.length - 1) {
1076
+ insert.push({ type: "paragraph", children: [{ text: "" }] });
1077
+ caret3 = [0, 0, 0];
1078
+ }
1013
1079
  return {
1014
1080
  steps: [{ kind: "spliceChildren", path: [], at: loTop, remove: hiTop - loTop + 1, insert }],
1015
1081
  caret: caret3
@@ -1033,9 +1099,13 @@ function pruneBlock(node) {
1033
1099
  }
1034
1100
  function keepBefore(node, rel) {
1035
1101
  const idx = rel[0];
1102
+ if (idx == null || idx < 0 || idx >= node.children.length)
1103
+ return { ...node, children: [] };
1036
1104
  if (rel.length === 2)
1037
1105
  return { ...node, children: [...node.children.slice(0, idx), trimTail(node.children[idx], rel[1])] };
1038
1106
  const child = node.children[idx];
1107
+ if (!isElement(child))
1108
+ return { ...node, children: [...node.children.slice(0, idx), trimTail(child, rel[rel.length - 1] ?? 0)] };
1039
1109
  return { ...node, children: [...node.children.slice(0, idx), keepBefore(child, rel.slice(1))] };
1040
1110
  }
1041
1111
  function peelAfter(kept, depth) {
@@ -1228,11 +1298,32 @@ function mapInput(doc, intent, data, sel, newId4, rules = [], pendingMarks) {
1228
1298
  return { steps: [{ kind: "deleteText", path: leafPath, offset: from - 1, length: 1 }], selection: caret(leafPath.concat(from - 1)) };
1229
1299
  {
1230
1300
  const aiParent = parentPath.length ? nodeAt(doc, parentPath) : null;
1231
- if (aiParent && aiParent.type === "ai" && isEmptyBlock(block) && leafIdx === 0) {
1232
- const node = { type: "paragraph", id: aiParent.id, children: [{ text: "" }] };
1301
+ if (aiParent && aiParent.type === "ai" && aiParent.id && isEmptyBlock(block) && leafIdx === 0) {
1302
+ const aiId = aiParent.id;
1303
+ const steps = [];
1304
+ const draftAt = [];
1305
+ for (let i = 0; i < doc.children.length; i++) {
1306
+ const c = doc.children[i];
1307
+ if (!isText(c) && c.attrs?.aiFrom === aiId)
1308
+ draftAt.push(i);
1309
+ }
1310
+ for (let i = draftAt.length - 1; i >= 0; i--)
1311
+ steps.push({ kind: "spliceChildren", path: [], at: draftAt[i], remove: 1, insert: [] });
1312
+ let aiIdx = parentPath[0] ?? 0;
1313
+ let shift3 = 0;
1314
+ for (const i of draftAt) {
1315
+ if (i < aiIdx)
1316
+ shift3++;
1317
+ }
1318
+ aiIdx -= shift3;
1319
+ steps.push({
1320
+ kind: "replaceNode",
1321
+ path: [aiIdx],
1322
+ node: { type: "paragraph", id: aiId, children: [{ text: "" }] }
1323
+ });
1233
1324
  return {
1234
- steps: [{ kind: "replaceNode", path: parentPath, node }],
1235
- selection: caret([...parentPath, 0, 0])
1325
+ steps,
1326
+ selection: caret([Math.max(0, aiIdx), 0, 0])
1236
1327
  };
1237
1328
  }
1238
1329
  }
@@ -1742,9 +1833,13 @@ function sliceDoc(doc, p1, p2) {
1742
1833
  }
1743
1834
  function keepAfter(node, rel) {
1744
1835
  const idx = rel[0];
1836
+ if (idx == null || idx < 0 || idx >= node.children.length)
1837
+ return { ...node, children: node.children.slice() };
1745
1838
  if (rel.length === 2)
1746
1839
  return { ...node, children: coalesceLeaves([trimHead(node.children[idx], rel[1]), ...node.children.slice(idx + 1)]) };
1747
1840
  const child = node.children[idx];
1841
+ if (!isElement(child))
1842
+ return { ...node, children: coalesceLeaves([trimHead(child, rel[rel.length - 1] ?? 0), ...node.children.slice(idx + 1)]) };
1748
1843
  return { ...node, children: [keepAfter(child, rel.slice(1)), ...node.children.slice(idx + 1)] };
1749
1844
  }
1750
1845
  function serializeSelection(doc, sel) {
@@ -1752,6 +1847,16 @@ function serializeSelection(doc, sel) {
1752
1847
  return "";
1753
1848
  return docToMd(sliceDoc(doc, sel.anchor.path, sel.head.path), "");
1754
1849
  }
1850
+ function serializeBlock(doc, path) {
1851
+ if (path.length !== 1)
1852
+ return null;
1853
+ const n = doc.children[path[0]];
1854
+ if (!n || isText(n))
1855
+ return null;
1856
+ if (n.type !== "image" && n.type !== "embed" && n.type !== "table")
1857
+ return null;
1858
+ return docToMd({ type: "doc", children: [stripSpan(n)] }, "");
1859
+ }
1755
1860
  function mapPaste(doc, sel, md, newId4) {
1756
1861
  const frag = mdToDoc(md).children.filter((c) => !isText(c));
1757
1862
  return mapPasteBlocks(doc, sel, frag, newId4);
@@ -1834,14 +1939,17 @@ function splitDeep(block, path, newId4) {
1834
1939
  function emptyInline(b) {
1835
1940
  return isInline(b) && b.children.every((c) => isText(c) && c.text === "");
1836
1941
  }
1942
+ function isTextLeafBlock(b) {
1943
+ return b.children.length > 0 && b.children.every(isText);
1944
+ }
1837
1945
  function lastInlinePath(b) {
1838
- if (isInline(b))
1946
+ if (isInline(b) || isTextLeafBlock(b))
1839
1947
  return [];
1840
1948
  const i = b.children.length - 1;
1841
1949
  return [i, ...lastInlinePath(b.children[i])];
1842
1950
  }
1843
1951
  function firstInlinePath(b) {
1844
- if (isInline(b))
1952
+ if (isInline(b) || isTextLeafBlock(b))
1845
1953
  return [];
1846
1954
  return [0, ...firstInlinePath(b.children[0])];
1847
1955
  }
@@ -1944,7 +2052,7 @@ function caretInDescendant(blocks, idx, block, inlinePath, off) {
1944
2052
  function caretAtEnd(blocks, topIdx) {
1945
2053
  const globalIdx = topIdx + blocks.length - 1;
1946
2054
  const last = blocks[blocks.length - 1];
1947
- if (isAtom(last))
2055
+ if (isOpaque(last))
1948
2056
  return caret([globalIdx, 0, 0]);
1949
2057
  const lp = lastInlinePath(last);
1950
2058
  const inline2 = descend(last, lp);
@@ -1957,6 +2065,131 @@ function descend(block, path) {
1957
2065
  return n;
1958
2066
  }
1959
2067
 
2068
+ // src/view/paste/link.ts
2069
+ var tryLinkMark = (ctx, clip) => {
2070
+ if (!clip.plain || ctx.selCollapsed || !isBareUrl(clip.plain))
2071
+ return null;
2072
+ return { kind: "link-mark", url: clip.plain.trim() };
2073
+ };
2074
+ function isBareUrl(s) {
2075
+ const t = s.trim();
2076
+ if (!t.startsWith("http://") && !t.startsWith("https://"))
2077
+ return false;
2078
+ for (let i = 0; i < t.length; i++) {
2079
+ const c = t.charCodeAt(i);
2080
+ if (c === 32 || c === 9 || c === 10 || c === 13)
2081
+ return false;
2082
+ }
2083
+ return true;
2084
+ }
2085
+
2086
+ // src/view/paste/embed.ts
2087
+ var tryEmbed = (ctx, clip) => {
2088
+ if (!clip.plain || !ctx.emptyTopPara || !isBareUrl(clip.plain))
2089
+ return null;
2090
+ const url = clip.plain.trim();
2091
+ if (youtubeId(url))
2092
+ return { kind: "embed", embedKind: "youtube", url };
2093
+ if (twitchChannel(url))
2094
+ return { kind: "embed", embedKind: "twitch", url };
2095
+ return null;
2096
+ };
2097
+
2098
+ // src/view/paste/html.ts
2099
+ var tryHtmlBlocks = (_ctx, clip) => {
2100
+ if (!clip.html)
2101
+ return null;
2102
+ const blocks = htmlToBlocks(clip.html);
2103
+ if (!blocks || !isRichHtmlBlocks(blocks) || preferMarkdownPaste(clip.plain, blocks))
2104
+ return null;
2105
+ return { kind: "blocks", blocks };
2106
+ };
2107
+
2108
+ // src/view/paste/image.ts
2109
+ var tryImageFile = (_ctx, clip) => {
2110
+ if (!clip.imageFile)
2111
+ return null;
2112
+ return { kind: "image-file", file: clip.imageFile };
2113
+ };
2114
+ var tryImageUrl = (_ctx, clip) => {
2115
+ if (clip.plain)
2116
+ return null;
2117
+ const url = soloImgSrcFromHtml(clip.html);
2118
+ return url ? { kind: "image-url", url } : null;
2119
+ };
2120
+ function soloImgSrcFromHtml(html) {
2121
+ if (!html || typeof DOMParser === "undefined")
2122
+ return null;
2123
+ const body = new DOMParser().parseFromString(html, "text/html").body;
2124
+ const imgs = body.querySelectorAll("img");
2125
+ if (imgs.length !== 1 || body.textContent?.trim())
2126
+ return null;
2127
+ return imgs[0].getAttribute("src");
2128
+ }
2129
+
2130
+ // src/view/paste/literal.ts
2131
+ var tryLiteral = (ctx, clip) => {
2132
+ if (!ctx.inCode)
2133
+ return null;
2134
+ const text = clip.plain || htmlToPlainText(clip.html);
2135
+ return text ? { kind: "literal", text } : { kind: "noop" };
2136
+ };
2137
+ function htmlToPlainText(html) {
2138
+ if (!html)
2139
+ return "";
2140
+ if (typeof DOMParser === "undefined")
2141
+ return html;
2142
+ return new DOMParser().parseFromString(html, "text/html").body.textContent ?? "";
2143
+ }
2144
+
2145
+ // src/view/paste/markdown.ts
2146
+ var tryMarkdown = (_ctx, clip) => {
2147
+ if (!clip.plain)
2148
+ return null;
2149
+ return { kind: "markdown", text: clip.plain };
2150
+ };
2151
+
2152
+ // src/view/paste/clipboard.ts
2153
+ function clipboardFromDataTransfer(dt) {
2154
+ return {
2155
+ plain: dt?.getData("text/plain") ?? "",
2156
+ html: dt?.getData("text/html") ?? "",
2157
+ imageFile: imageFileFrom(dt)
2158
+ };
2159
+ }
2160
+ function imageFileFrom(dt) {
2161
+ if (!dt)
2162
+ return null;
2163
+ for (const f of Array.from(dt.files))
2164
+ if (f.type.startsWith("image/"))
2165
+ return f;
2166
+ return null;
2167
+ }
2168
+
2169
+ // src/view/paste/index.ts
2170
+ var PIPELINE = [
2171
+ tryLiteral,
2172
+ tryImageFile,
2173
+ tryImageUrl,
2174
+ tryLinkMark,
2175
+ tryEmbed,
2176
+ tryHtmlBlocks,
2177
+ tryMarkdown
2178
+ ];
2179
+ function resolvePaste(ctx, clip) {
2180
+ const normalized = {
2181
+ plain: clip.plain ?? "",
2182
+ html: clip.html ?? "",
2183
+ imageFile: clip.imageFile ?? null
2184
+ };
2185
+ for (const tryFormat of PIPELINE) {
2186
+ const plan = tryFormat(ctx, normalized);
2187
+ if (plan)
2188
+ return plan;
2189
+ }
2190
+ return { kind: "noop" };
2191
+ }
2192
+
1960
2193
  // src/view/extension.ts
1961
2194
  function resolve(extensions) {
1962
2195
  const out = { markTags: {}, markProps: {}, blockRenderers: {}, keymap: {}, inputRules: [], pasteRules: [], decorationFactories: [] };
@@ -3348,25 +3581,37 @@ function normalizeLinkUrl(raw) {
3348
3581
  function readAnchor(a) {
3349
3582
  return typeof a === "function" ? a() : a;
3350
3583
  }
3351
- function askLinkPopover(opts) {
3584
+ function askPopover(opts) {
3352
3585
  if (active)
3353
3586
  dismissActive(null);
3354
3587
  return new Promise((resolve2) => {
3355
3588
  const root = document.createElement("div");
3356
- root.className = "markloom-link-pop-host";
3589
+ root.className = "markloom-ask-pop-host";
3357
3590
  document.body.appendChild(root);
3358
3591
  let value = opts.defaultValue ?? "";
3592
+ let error = null;
3359
3593
  let placed = false;
3594
+ const multi = !!opts.multiline;
3595
+ const w = opts.width ?? (multi ? 320 : 280);
3596
+ const rows = opts.rows ?? (multi ? 3 : 1);
3360
3597
  const finish = (v) => {
3361
3598
  if (active?.root !== root)
3362
3599
  return;
3363
3600
  dismissActive(v);
3364
3601
  };
3365
3602
  const confirm = () => {
3366
- const trimmed = value.trim();
3367
- if (!trimmed)
3603
+ const raw = multi ? value : value.trim();
3604
+ if (!opts.allowEmpty && !raw.trim())
3368
3605
  return;
3369
- finish(normalizeLinkUrl(trimmed));
3606
+ if (opts.validate) {
3607
+ const err = opts.validate(raw);
3608
+ if (err) {
3609
+ error = err;
3610
+ paint(false);
3611
+ return;
3612
+ }
3613
+ }
3614
+ finish(opts.normalize ? opts.normalize(raw) : raw);
3370
3615
  };
3371
3616
  const onKey = (e) => {
3372
3617
  if (e.key === "Escape") {
@@ -3386,52 +3631,68 @@ function askLinkPopover(opts) {
3386
3631
  document.addEventListener("pointerdown", onDocDown, true);
3387
3632
  });
3388
3633
  const paint = (focus = false) => {
3389
- const can = value.trim().length > 0;
3634
+ const can = opts.allowEmpty || value.trim().length > 0;
3635
+ const prev = root.querySelector("input, textarea");
3636
+ const selStart = !focus && prev ? prev.selectionStart : null;
3637
+ const selEnd = !focus && prev ? prev.selectionEnd : null;
3638
+ const fieldClass = "markloom-ask-pop-input" + (opts.mono ? " is-mono" : "") + (error ? " is-err" : "");
3639
+ const fieldProps = {
3640
+ key: "i",
3641
+ class: fieldClass,
3642
+ value,
3643
+ placeholder: opts.placeholder ?? "",
3644
+ style: { width: `${w}px` },
3645
+ onInput: (e) => {
3646
+ value = e.target.value;
3647
+ if (error)
3648
+ error = null;
3649
+ paint(false);
3650
+ },
3651
+ onKeyDown: (e) => {
3652
+ if (e.key === "Enter" && !multi) {
3653
+ e.preventDefault();
3654
+ confirm();
3655
+ }
3656
+ if (e.key === "Enter" && multi && (e.metaKey || e.ctrlKey)) {
3657
+ e.preventDefault();
3658
+ confirm();
3659
+ }
3660
+ }
3661
+ };
3390
3662
  render(
3391
3663
  h3("div", {
3392
- class: "markloom-link-pop",
3393
- "data-markloom-link-pop": "",
3664
+ class: "markloom-ask-pop" + (multi ? " is-multi" : ""),
3665
+ "data-markloom-ask-pop": "",
3666
+ // 兼容旧选择器(链接测)
3667
+ "data-markloom-link-pop": multi ? void 0 : "",
3394
3668
  role: "dialog",
3395
- "aria-label": "\u6DFB\u52A0\u94FE\u63A5",
3669
+ "aria-label": opts.ariaLabel ?? "\u8F93\u5165",
3396
3670
  onMouseDown: (e) => {
3397
- e.preventDefault();
3398
3671
  const t = e.target;
3399
- if (t instanceof HTMLInputElement)
3400
- t.focus();
3672
+ if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement)
3673
+ return;
3674
+ e.preventDefault();
3401
3675
  }
3402
3676
  }, [
3403
- h3("input", {
3404
- key: "i",
3405
- class: "markloom-link-pop-input",
3406
- type: "text",
3407
- value,
3408
- placeholder: opts.placeholder ?? "\u7C98\u8D34\u6216\u8F93\u5165\u94FE\u63A5",
3409
- onInput: (e) => {
3410
- value = e.target.value;
3411
- paint(false);
3412
- },
3413
- onKeyDown: (e) => {
3414
- if (e.key === "Enter") {
3677
+ multi ? h3("textarea", { ...fieldProps, rows }) : h3("input", { ...fieldProps, type: "text" }),
3678
+ error ? h3("div", { key: "e", class: "markloom-ask-pop-err" }, error) : null,
3679
+ h3("div", { key: "ft", class: "markloom-ask-pop-ft" }, [
3680
+ multi ? h3("span", { class: "markloom-ask-pop-hint" }, "\u2318\u21B5 \u786E\u8BA4") : null,
3681
+ h3("button", {
3682
+ type: "button",
3683
+ class: "markloom-ask-pop-ok" + (can ? " is-ready" : ""),
3684
+ "data-act": "confirm",
3685
+ disabled: !can,
3686
+ onMouseDown: (e) => {
3415
3687
  e.preventDefault();
3416
3688
  confirm();
3417
3689
  }
3418
- }
3419
- }),
3420
- h3("button", {
3421
- key: "ok",
3422
- type: "button",
3423
- class: "markloom-link-pop-ok" + (can ? " is-ready" : ""),
3424
- "data-act": "confirm",
3425
- disabled: !can,
3426
- onMouseDown: (e) => {
3427
- e.preventDefault();
3428
- confirm();
3429
- }
3430
- }, opts.confirmLabel ?? "\u786E\u8BA4")
3690
+ }, opts.confirmLabel ?? "\u786E\u8BA4")
3691
+ ])
3431
3692
  ]),
3432
3693
  root
3433
3694
  );
3434
- const el = root.querySelector(".markloom-link-pop");
3695
+ const el = root.querySelector(".markloom-ask-pop");
3435
3696
  if (el && !placed) {
3436
3697
  placed = true;
3437
3698
  const rect = readAnchor(opts.anchor);
@@ -3439,17 +3700,33 @@ function askLinkPopover(opts) {
3439
3700
  }
3440
3701
  if (focus) {
3441
3702
  queueMicrotask(() => {
3442
- const input = root.querySelector("input");
3703
+ const input = root.querySelector("input, textarea");
3443
3704
  input?.focus();
3444
3705
  if (opts.defaultValue)
3445
3706
  input?.select();
3446
3707
  });
3708
+ } else if (selStart != null && selEnd != null) {
3709
+ const input = root.querySelector("input, textarea");
3710
+ if (input) {
3711
+ try {
3712
+ input.setSelectionRange(selStart, selEnd);
3713
+ } catch {
3714
+ }
3715
+ }
3447
3716
  }
3448
3717
  };
3449
3718
  active = { resolve: resolve2, root, onKey, onDocDown };
3450
3719
  paint(true);
3451
3720
  });
3452
3721
  }
3722
+ function askLinkPopover(opts) {
3723
+ return askPopover({
3724
+ ...opts,
3725
+ placeholder: opts.placeholder ?? "\u7C98\u8D34\u6216\u8F93\u5165\u94FE\u63A5",
3726
+ ariaLabel: "\u6DFB\u52A0\u94FE\u63A5",
3727
+ normalize: normalizeLinkUrl
3728
+ });
3729
+ }
3453
3730
  function closeAskInput() {
3454
3731
  dismissActive(null);
3455
3732
  }
@@ -3668,8 +3945,18 @@ var MARK_ITEMS = [
3668
3945
  { name: "italic", label: "I", tip: `\u659C\u4F53 (${mod} + I)`, md: "*\u6587\u672C* \u7A7A\u683C", cls: "markloom-bb-italic" },
3669
3946
  { name: "underline", label: "U", tip: `\u4E0B\u5212\u7EBF (${mod} + U)`, md: "", cls: "markloom-bb-under" }
3670
3947
  ];
3948
+ function uiDark() {
3949
+ if (typeof document === "undefined")
3950
+ return false;
3951
+ if (document.documentElement.classList.contains("dark"))
3952
+ return true;
3953
+ return typeof matchMedia !== "undefined" && matchMedia("(prefers-color-scheme: dark)").matches;
3954
+ }
3955
+ function defaultFg() {
3956
+ return uiDark() ? "rgba(255,255,255,0.88)" : "#1f2329";
3957
+ }
3671
3958
  var FONT_COLORS = [
3672
- { value: null, title: "\u9ED8\u8BA4", swatch: "#1f2329" },
3959
+ { value: null, title: "\u9ED8\u8BA4", swatch: defaultFg },
3673
3960
  { value: "#8f959e", title: "\u7070", swatch: "#8f959e" },
3674
3961
  { value: "#f54a45", title: "\u7EA2", swatch: "#f54a45" },
3675
3962
  { value: "#ff8800", title: "\u6A59", swatch: "#ff8800" },
@@ -3678,7 +3965,19 @@ var FONT_COLORS = [
3678
3965
  { value: "#3370ff", title: "\u84DD", swatch: "#3370ff" },
3679
3966
  { value: "#7b67ee", title: "\u7D2B", swatch: "#7b67ee" }
3680
3967
  ];
3681
- var BG_COLORS = [
3968
+ function fontSwatch(c) {
3969
+ return typeof c.swatch === "function" ? c.swatch() : c.swatch;
3970
+ }
3971
+ var BG_SOLIDS = [
3972
+ { value: "#8f959e", title: "\u6DF1\u7070", swatch: "#8f959e" },
3973
+ { value: "#f54a45", title: "\u7EA2", swatch: "#f54a45" },
3974
+ { value: "#ff8800", title: "\u6A59", swatch: "#ff8800" },
3975
+ { value: "#ffc60a", title: "\u9EC4", swatch: "#ffc60a" },
3976
+ { value: "#34c724", title: "\u7EFF", swatch: "#34c724" },
3977
+ { value: "#3370ff", title: "\u84DD", swatch: "#3370ff" },
3978
+ { value: "#7b67ee", title: "\u7D2B", swatch: "#7b67ee" }
3979
+ ];
3980
+ var BG_SOFT_LIGHT = [
3682
3981
  { value: null, title: "\u65E0", swatch: "transparent", none: true },
3683
3982
  { value: "#f2f3f5", title: "\u6D45\u7070", swatch: "#f2f3f5", edge: true },
3684
3983
  { value: "#fde2e2", title: "\u6D45\u7EA2", swatch: "#fde2e2" },
@@ -3687,15 +3986,22 @@ var BG_COLORS = [
3687
3986
  { value: "#d9f5d6", title: "\u6D45\u7EFF", swatch: "#d9f5d6" },
3688
3987
  { value: "#e1eaff", title: "\u6D45\u84DD", swatch: "#e1eaff" },
3689
3988
  { value: "#ece2fe", title: "\u6D45\u7D2B", swatch: "#ece2fe" },
3690
- { value: "#dee0e3", title: "\u7070", swatch: "#dee0e3" },
3691
- { value: "#8f959e", title: "\u6DF1\u7070", swatch: "#8f959e" },
3692
- { value: "#f54a45", title: "\u7EA2", swatch: "#f54a45" },
3693
- { value: "#ff8800", title: "\u6A59", swatch: "#ff8800" },
3694
- { value: "#ffc60a", title: "\u9EC4", swatch: "#ffc60a" },
3695
- { value: "#34c724", title: "\u7EFF", swatch: "#34c724" },
3696
- { value: "#3370ff", title: "\u84DD", swatch: "#3370ff" },
3697
- { value: "#7b67ee", title: "\u7D2B", swatch: "#7b67ee" }
3989
+ { value: "#dee0e3", title: "\u7070", swatch: "#dee0e3" }
3698
3990
  ];
3991
+ var BG_SOFT_DARK = [
3992
+ { value: null, title: "\u65E0", swatch: "transparent", none: true },
3993
+ { value: "rgba(255,255,255,0.08)", title: "\u6D45\u7070", swatch: "rgba(255,255,255,0.12)", edge: true },
3994
+ { value: "rgba(245,74,69,0.28)", title: "\u6D45\u7EA2", swatch: "rgba(245,74,69,0.35)" },
3995
+ { value: "rgba(255,136,0,0.28)", title: "\u6D45\u6A59", swatch: "rgba(255,136,0,0.35)" },
3996
+ { value: "rgba(255,198,10,0.28)", title: "\u6D45\u9EC4", swatch: "rgba(255,198,10,0.35)" },
3997
+ { value: "rgba(52,199,36,0.28)", title: "\u6D45\u7EFF", swatch: "rgba(52,199,36,0.35)" },
3998
+ { value: "rgba(76,139,245,0.28)", title: "\u6D45\u84DD", swatch: "rgba(76,139,245,0.35)" },
3999
+ { value: "rgba(123,103,238,0.28)", title: "\u6D45\u7D2B", swatch: "rgba(123,103,238,0.35)" },
4000
+ { value: "rgba(255,255,255,0.16)", title: "\u7070", swatch: "rgba(255,255,255,0.2)" }
4001
+ ];
4002
+ function bgColors() {
4003
+ return [...uiDark() ? BG_SOFT_DARK : BG_SOFT_LIGHT, ...BG_SOLIDS];
4004
+ }
3699
4005
  function tipNode(title, md) {
3700
4006
  return h5("div", { class: "markloom-bubble-tip", key: "tip" }, [
3701
4007
  h5("div", { class: "markloom-bubble-tip-t", key: "t" }, title),
@@ -3988,7 +4294,7 @@ var BubbleMenu = class {
3988
4294
  const curBlock = currentBlockKind(this.host.doc(), sel);
3989
4295
  const curColor = this.activeColor(sel);
3990
4296
  const curBg = this.activeBg(sel);
3991
- const colorSwatch = curColor ?? "#1f2329";
4297
+ const colorSwatch = curColor ?? defaultFg();
3992
4298
  const hasStyle = !!(curColor || curBg || active2.has("highlight"));
3993
4299
  const sep = (k) => h5("span", { key: k, class: "markloom-bubble-sep" });
3994
4300
  const blockBtn = h5("button", {
@@ -4206,7 +4512,7 @@ var BubbleMenu = class {
4206
4512
  class: "markloom-bb-a",
4207
4513
  style: {
4208
4514
  color: colorSwatch,
4209
- background: curBg ?? (active2.has("highlight") ? "#faf1d1" : "transparent")
4515
+ background: curBg ?? (active2.has("highlight") ? uiDark() ? "rgba(255,198,10,0.28)" : "#faf1d1" : "transparent")
4210
4516
  }
4211
4517
  }, "A"),
4212
4518
  icon("chevron-down", 12, "markloom-bb-chev"),
@@ -4225,7 +4531,7 @@ var BubbleMenu = class {
4225
4531
  type: "button",
4226
4532
  class: "markloom-bb-font-a" + (on ? " is-on" : ""),
4227
4533
  title: c.title,
4228
- style: { color: c.swatch },
4534
+ style: { color: fontSwatch(c) },
4229
4535
  onMouseDown: (e) => {
4230
4536
  e.preventDefault();
4231
4537
  const cur = this.host.markSel();
@@ -4238,7 +4544,7 @@ var BubbleMenu = class {
4238
4544
  }, "A");
4239
4545
  })),
4240
4546
  h5("div", { class: "markloom-bb-color-sec", key: "ht" }, "\u80CC\u666F\u989C\u8272"),
4241
- h5("div", { class: "markloom-bb-swatches markloom-bb-bg-row", key: "hs" }, BG_COLORS.map((c) => {
4547
+ h5("div", { class: "markloom-bb-swatches markloom-bb-bg-row", key: "hs" }, bgColors().map((c) => {
4242
4548
  const on = c.value === null ? !curBg && !active2.has("highlight") : curBg === c.value;
4243
4549
  return h5("button", {
4244
4550
  key: c.title,
@@ -5312,8 +5618,8 @@ var markCmd = (name) => (ctx) => {
5312
5618
  if (r)
5313
5619
  return r;
5314
5620
  const a = ctx.markSel.anchor.path;
5315
- const h13 = ctx.markSel.head.path;
5316
- if (a.length === h13.length && a.every((v, i) => v === h13[i]))
5621
+ const h17 = ctx.markSel.head.path;
5622
+ if (a.length === h17.length && a.every((v, i) => v === h17[i]))
5317
5623
  return { pendingToggle: name };
5318
5624
  return null;
5319
5625
  };
@@ -5332,10 +5638,11 @@ var linkMark = {
5332
5638
  tag: "a",
5333
5639
  props: (mark) => {
5334
5640
  if (!mark.attrs?.url)
5335
- return { "data-mark": "link", class: "markloom-link" };
5641
+ return { "data-mark": "link", class: "markloom-link", target: "_blank", rel: "noopener noreferrer" };
5336
5642
  const url = String(mark.attrs.url);
5337
5643
  return {
5338
5644
  href: url,
5645
+ target: "_blank",
5339
5646
  "data-mark": "link",
5340
5647
  class: "markloom-link",
5341
5648
  rel: "noopener noreferrer",
@@ -5594,8 +5901,8 @@ var CommentPanel = class {
5594
5901
  const want = parseFloat(c.style.top) || 0;
5595
5902
  const top = Math.max(want, floor2);
5596
5903
  c.style.top = `${top}px`;
5597
- const h13 = c.offsetHeight || 120;
5598
- floor2 = top + h13 + CARD_GAP;
5904
+ const h17 = c.offsetHeight || 120;
5905
+ floor2 = top + h17 + CARD_GAP;
5599
5906
  maxBottom = floor2;
5600
5907
  }
5601
5908
  body.style.minHeight = `${Math.max(maxBottom + RAIL_PAD, 0)}px`;
@@ -5864,70 +6171,141 @@ function cssEscape(s) {
5864
6171
  import { h as h9, render as render7 } from "preact";
5865
6172
  var TocPanel = class {
5866
6173
  host;
6174
+ shell;
5867
6175
  rail;
5868
6176
  open = true;
5869
6177
  activeId = null;
5870
6178
  entries = [];
5871
6179
  scrollRoot = window;
6180
+ parentEl;
6181
+ fill = false;
6182
+ padEl = null;
6183
+ /** 判定线:滚动容器顶 + 偏移;jump / sync 共用 */
6184
+ markOffset = 12;
5872
6185
  constructor(host) {
5873
6186
  this.host = host;
6187
+ const root = host.root;
6188
+ const parent = root.parentElement;
6189
+ if (!parent)
6190
+ throw new Error("TocPanel: root must be in the document");
6191
+ this.parentEl = parent;
6192
+ this.shell = document.createElement("div");
6193
+ this.shell.className = "markloom-shell";
6194
+ parent.insertBefore(this.shell, root);
6195
+ root.classList.add("markloom-editor-pane");
6196
+ this.shell.appendChild(root);
5874
6197
  this.rail = document.createElement("div");
5875
6198
  this.rail.className = "markloom-toc-host";
5876
- document.body.appendChild(this.rail);
6199
+ this.shell.appendChild(this.rail);
6200
+ const oy = getComputedStyle(parent).overflowY;
6201
+ if (oy === "auto" || oy === "scroll" || oy === "overlay") {
6202
+ this.fill = true;
6203
+ this.shell.classList.add("markloom-shell-fill");
6204
+ parent.classList.add("markloom-toc-scroll-host");
6205
+ this.scrollRoot = root;
6206
+ } else {
6207
+ this.scrollRoot = findScrollParent2(this.shell) ?? window;
6208
+ }
5877
6209
  host.root.addEventListener("markloom-redraw", this.onRedraw);
5878
- this.scrollRoot = findScrollParent2(host.root) ?? window;
5879
6210
  this.scrollRoot.addEventListener("scroll", this.onScroll, { passive: true, capture: true });
5880
- window.addEventListener("resize", this.onScroll);
5881
- this.setPadOpen(true);
6211
+ window.addEventListener("resize", this.onResize);
5882
6212
  this.refresh();
5883
6213
  }
5884
6214
  destroy() {
5885
6215
  this.host.root.removeEventListener("markloom-redraw", this.onRedraw);
5886
6216
  this.scrollRoot.removeEventListener("scroll", this.onScroll, { capture: true });
5887
- window.removeEventListener("resize", this.onScroll);
5888
- this.setPadOpen(false);
6217
+ window.removeEventListener("resize", this.onResize);
6218
+ this.clearEndScrollRoom();
5889
6219
  render7(null, this.rail);
5890
- this.rail.remove();
6220
+ this.host.root.classList.remove("markloom-editor-pane");
6221
+ this.parentEl.insertBefore(this.host.root, this.shell);
6222
+ this.shell.remove();
6223
+ if (this.fill)
6224
+ this.parentEl.classList.remove("markloom-toc-scroll-host");
5891
6225
  }
5892
6226
  setOpen(open) {
5893
6227
  this.open = open;
5894
- this.setPadOpen(open);
5895
6228
  this.paint();
5896
6229
  }
5897
- // 有滚动父 → 给滚动父加 padding(正文区);否则退回 html(lab 全页)
5898
- setPadOpen(open) {
5899
- const pad2 = this.scrollRoot instanceof HTMLElement ? this.scrollRoot : document.documentElement;
5900
- pad2.classList.toggle("markloom-toc-open", open);
5901
- if (pad2 !== document.documentElement)
5902
- document.documentElement.classList.remove("markloom-toc-open");
5903
- }
5904
6230
  onRedraw = () => this.refresh();
5905
- refresh() {
5906
- this.entries = outline(this.host.doc()).filter((e) => e.text.trim());
6231
+ onScroll = () => {
6232
+ const prev = this.activeId;
5907
6233
  this.syncActive();
6234
+ if (this.activeId === prev)
6235
+ return;
5908
6236
  this.paint();
5909
- }
5910
- onScroll = () => {
6237
+ this.revealActiveInRail();
6238
+ };
6239
+ onResize = () => {
6240
+ this.ensureEndScrollRoom();
5911
6241
  this.syncActive();
5912
6242
  this.paint();
6243
+ this.revealActiveInRail();
5913
6244
  };
5914
- /** 视口上 1/4 处最近的标题 = 当前节(飞书感) */
6245
+ refresh() {
6246
+ this.entries = outline(this.host.doc()).filter((e) => e.text.trim());
6247
+ this.ensureEndScrollRoom();
6248
+ this.syncActive();
6249
+ this.paint();
6250
+ this.revealActiveInRail();
6251
+ }
6252
+ /** 留白挂在滚动容器上(在全部子节点之后),避免夹在正文与页脚/prev-next 之间 */
6253
+ padTarget() {
6254
+ if (this.scrollRoot instanceof HTMLElement)
6255
+ return this.scrollRoot;
6256
+ return this.host.root.querySelector(".markloom-doc") ?? this.host.root;
6257
+ }
6258
+ /**
6259
+ * 文末可滚空间:让最后一个标题也能对齐顶线。
6260
+ * 有了它,慢滚 / 点末项都走同一套「越过顶线」规则,无需触底特判。
6261
+ */
6262
+ ensureEndScrollRoom() {
6263
+ if (!this.entries.length) {
6264
+ this.clearEndScrollRoom();
6265
+ return;
6266
+ }
6267
+ const last = this.headingEl(this.entries[this.entries.length - 1]);
6268
+ if (!last) {
6269
+ this.clearEndScrollRoom();
6270
+ return;
6271
+ }
6272
+ const el = this.padTarget();
6273
+ this.padEl = el;
6274
+ el.style.paddingBottom = "0px";
6275
+ if (this.scrollRoot instanceof HTMLElement) {
6276
+ const c = this.scrollRoot;
6277
+ const cRect = c.getBoundingClientRect();
6278
+ const lastTop2 = last.getBoundingClientRect().top - cRect.top + c.scrollTop;
6279
+ const need2 = Math.max(0, Math.ceil(lastTop2 - this.markOffset - (c.scrollHeight - c.clientHeight)));
6280
+ el.style.paddingBottom = need2 > 0 ? `${need2}px` : "";
6281
+ return;
6282
+ }
6283
+ const se = document.scrollingElement ?? document.documentElement;
6284
+ const lastTop = last.getBoundingClientRect().top + se.scrollTop;
6285
+ const need = Math.max(0, Math.ceil(lastTop - this.markOffset - (se.scrollHeight - window.innerHeight)));
6286
+ el.style.paddingBottom = need > 0 ? `${need}px` : "";
6287
+ }
6288
+ clearEndScrollRoom() {
6289
+ if (this.padEl) {
6290
+ this.padEl.style.paddingBottom = "";
6291
+ this.padEl = null;
6292
+ }
6293
+ }
5915
6294
  syncActive() {
5916
6295
  if (!this.entries.length) {
5917
6296
  this.activeId = null;
5918
6297
  return;
5919
6298
  }
5920
- const mark = window.innerHeight * 0.22;
6299
+ const mark = (this.scrollRoot instanceof HTMLElement ? this.scrollRoot.getBoundingClientRect().top : 0) + this.markOffset;
5921
6300
  let best = null;
5922
6301
  for (const e of this.entries) {
5923
6302
  const el = this.headingEl(e);
5924
6303
  if (!el)
5925
6304
  continue;
5926
6305
  const top = el.getBoundingClientRect().top;
5927
- const dist = top - mark;
5928
- if (dist <= 8) {
5929
- if (!best || dist > best.dist)
5930
- best = { id: e.id ?? pathKey(e.path), dist };
6306
+ if (top <= mark + 1) {
6307
+ if (!best || top >= best.top)
6308
+ best = { id: e.id ?? pathKey(e.path), top };
5931
6309
  }
5932
6310
  }
5933
6311
  if (!best) {
@@ -5945,39 +6323,85 @@ var TocPanel = class {
5945
6323
  }
5946
6324
  const docEl = this.host.root.querySelector(".markloom-doc") ?? this.host.root;
5947
6325
  const kids = [...docEl.children].filter((c) => c instanceof HTMLElement && c.dataset.blockId !== void 0);
5948
- const idx = e.path[0];
5949
- return kids[idx] ?? null;
6326
+ return kids[e.path[0]] ?? null;
5950
6327
  }
5951
6328
  jump(e) {
5952
- this.activeId = e.id ?? pathKey(e.path);
6329
+ const id = e.id ?? pathKey(e.path);
6330
+ this.activeId = id;
5953
6331
  this.paint();
5954
6332
  const el = this.headingEl(e);
5955
- if (el && typeof el.scrollIntoView === "function")
5956
- el.scrollIntoView({ behavior: "smooth", block: "start" });
6333
+ if (!el)
6334
+ return;
6335
+ if (this.scrollRoot instanceof HTMLElement) {
6336
+ const c = this.scrollRoot;
6337
+ const delta = el.getBoundingClientRect().top - c.getBoundingClientRect().top - this.markOffset;
6338
+ c.scrollTop = Math.max(0, c.scrollTop + delta);
6339
+ } else if (typeof el.scrollIntoView === "function") {
6340
+ el.scrollIntoView({ behavior: "auto", block: "start" });
6341
+ }
6342
+ this.activeId = id;
6343
+ this.paint();
6344
+ this.revealActiveInRail();
6345
+ }
6346
+ /**
6347
+ * 长目录时 TOC 自身是滚轴:正文 scroll-spy 换了 active,
6348
+ * 若该项在目录视口外则只滚 TOC 容器,不带动正文。
6349
+ */
6350
+ revealActiveInRail() {
6351
+ if (!this.activeId)
6352
+ return;
6353
+ requestAnimationFrame(() => {
6354
+ const btn = this.rail.querySelector(".markloom-toc-item-active");
6355
+ if (!btn)
6356
+ return;
6357
+ const scroller = tocScrollerOf(btn, this.shell);
6358
+ if (!scroller)
6359
+ return;
6360
+ const s = scroller.getBoundingClientRect();
6361
+ const b = btn.getBoundingClientRect();
6362
+ const pad2 = 12;
6363
+ if (b.top < s.top + pad2)
6364
+ scroller.scrollTop += b.top - s.top - pad2;
6365
+ else if (b.bottom > s.bottom - pad2)
6366
+ scroller.scrollTop += b.bottom - s.bottom + pad2;
6367
+ });
5957
6368
  }
5958
6369
  paint() {
5959
6370
  if (!this.open) {
6371
+ this.shell.classList.remove("markloom-shell-has-toc");
5960
6372
  render7(null, this.rail);
5961
6373
  return;
5962
6374
  }
6375
+ this.shell.classList.add("markloom-shell-has-toc");
5963
6376
  const items = this.entries;
6377
+ if (!items.length) {
6378
+ render7(
6379
+ h9("aside", {
6380
+ class: "markloom-toc-rail is-empty",
6381
+ "data-toc-rail": "",
6382
+ "aria-label": "\u76EE\u5F55"
6383
+ }, [
6384
+ h9("div", { class: "markloom-toc-empty", key: "empty" }, "\u6682\u65E0\u6807\u9898")
6385
+ ]),
6386
+ this.rail
6387
+ );
6388
+ return;
6389
+ }
5964
6390
  let minLv = 6;
5965
- for (const e of items)
6391
+ for (const e of items) {
5966
6392
  if (e.level < minLv)
5967
6393
  minLv = e.level;
5968
- if (!items.length)
5969
- minLv = 1;
6394
+ }
5970
6395
  render7(
5971
6396
  h9("aside", {
5972
6397
  class: "markloom-toc-rail",
5973
6398
  "data-toc-rail": "",
5974
6399
  "aria-label": "\u76EE\u5F55"
5975
6400
  }, [
5976
- h9("div", { class: "markloom-toc-hd", key: "hd" }, "\u76EE\u5F55"),
5977
6401
  h9(
5978
6402
  "nav",
5979
6403
  { class: "markloom-toc-nav", key: "nav" },
5980
- items.length ? items.map((e, i) => {
6404
+ items.map((e, i) => {
5981
6405
  const key = e.id ?? pathKey(e.path);
5982
6406
  const active2 = this.activeId === key;
5983
6407
  const depth = Math.max(0, e.level - minLv);
@@ -5988,20 +6412,30 @@ var TocPanel = class {
5988
6412
  "data-level": String(e.level),
5989
6413
  "data-active": active2 ? "" : void 0,
5990
6414
  "data-toc-id": e.id ?? void 0,
5991
- style: { paddingLeft: `${12 + depth * 14}px` },
6415
+ style: { paddingLeft: `${6 + depth * 10}px` },
5992
6416
  title: e.text,
5993
6417
  onMouseDown: (ev) => {
5994
6418
  ev.preventDefault();
5995
6419
  this.jump(e);
5996
6420
  }
5997
6421
  }, e.text || "\u672A\u547D\u540D\u6807\u9898");
5998
- }) : h9("div", { class: "markloom-toc-empty", key: "empty" }, "\u6DFB\u52A0\u6807\u9898\u540E\u663E\u793A\u76EE\u5F55")
6422
+ })
5999
6423
  )
6000
6424
  ]),
6001
6425
  this.rail
6002
6426
  );
6003
6427
  }
6004
6428
  };
6429
+ function tocScrollerOf(from, shell) {
6430
+ let cur = from.parentElement;
6431
+ while (cur && cur !== shell) {
6432
+ const oy = getComputedStyle(cur).overflowY;
6433
+ if ((oy === "auto" || oy === "scroll" || oy === "overlay") && cur.scrollHeight > cur.clientHeight + 1)
6434
+ return cur;
6435
+ cur = cur.parentElement;
6436
+ }
6437
+ return null;
6438
+ }
6005
6439
  function pathKey(path) {
6006
6440
  return `p:${path.join(".")}`;
6007
6441
  }
@@ -6021,78 +6455,531 @@ function findScrollParent2(el) {
6021
6455
  return null;
6022
6456
  }
6023
6457
 
6024
- // src/view/mention-popovers.ts
6458
+ // src/view/search-bar.ts
6025
6459
  import { h as h10, render as render8 } from "preact";
6026
- var MentionPopovers = class {
6460
+ var SearchBar = class {
6027
6461
  host;
6028
- overlay;
6029
- mode = { kind: "closed" };
6462
+ el;
6463
+ open_ = false;
6464
+ q = "";
6465
+ r = "";
6466
+ caseSensitive = false;
6467
+ hits = [];
6468
+ idx = -1;
6030
6469
  constructor(host) {
6031
6470
  this.host = host;
6032
- this.overlay = document.createElement("div");
6033
- this.overlay.className = "markloom-mention-pop-host";
6034
- document.body.appendChild(this.overlay);
6035
- document.addEventListener("pointerdown", this.onDocDown, true);
6036
- document.addEventListener("keydown", this.onKey, true);
6037
- window.addEventListener("scroll", this.close, true);
6038
- window.addEventListener("resize", this.close);
6471
+ this.el = document.createElement("div");
6472
+ this.el.className = "markloom-search";
6473
+ this.el.hidden = true;
6474
+ host.root.appendChild(this.el);
6475
+ }
6476
+ open() {
6477
+ if (this.host.readonly())
6478
+ return;
6479
+ this.open_ = true;
6480
+ this.el.hidden = false;
6481
+ this.refresh();
6482
+ this.paint();
6483
+ requestAnimationFrame(() => {
6484
+ const inp = this.el.querySelector("input[data-search-q]");
6485
+ inp?.focus();
6486
+ inp?.select();
6487
+ });
6488
+ }
6489
+ close() {
6490
+ this.open_ = false;
6491
+ this.el.hidden = true;
6492
+ this.hits = [];
6493
+ this.idx = -1;
6494
+ this.paint();
6495
+ }
6496
+ get isOpen() {
6497
+ return this.open_;
6039
6498
  }
6040
6499
  destroy() {
6041
- document.removeEventListener("pointerdown", this.onDocDown, true);
6042
- document.removeEventListener("keydown", this.onKey, true);
6043
- window.removeEventListener("scroll", this.close, true);
6044
- window.removeEventListener("resize", this.close);
6045
- render8(null, this.overlay);
6046
- this.overlay.remove();
6500
+ render8(null, this.el);
6501
+ this.el.remove();
6047
6502
  }
6048
- close = () => {
6049
- if (this.mode.kind === "closed")
6503
+ rescan() {
6504
+ if (!this.open_)
6050
6505
  return;
6051
- this.mode = { kind: "closed" };
6052
- render8(null, this.overlay);
6053
- };
6054
- openPerson(profile, anchor) {
6055
- this.mode = { kind: "person", profile, rect: anchor };
6506
+ this.refresh();
6056
6507
  this.paint();
6057
6508
  }
6058
- openDate(iso, path, anchor) {
6059
- const d = parseDateTime(iso) ?? /* @__PURE__ */ new Date();
6060
- this.mode = {
6061
- kind: "date",
6062
- path,
6063
- rect: anchor,
6064
- draft: {
6065
- y: d.getFullYear(),
6066
- m: d.getMonth(),
6067
- d: d.getDate(),
6068
- h: d.getHours(),
6069
- min: d.getMinutes(),
6070
- s: d.getSeconds(),
6071
- viewY: d.getFullYear(),
6072
- viewM: d.getMonth()
6073
- }
6074
- };
6509
+ refresh() {
6510
+ this.hits = this.q ? findText(this.host.doc(), this.q, { caseSensitive: this.caseSensitive }) : [];
6511
+ if (this.hits.length === 0)
6512
+ this.idx = -1;
6513
+ else if (this.idx >= this.hits.length)
6514
+ this.idx = this.hits.length - 1;
6515
+ else if (this.idx < 0)
6516
+ this.idx = 0;
6517
+ }
6518
+ go(delta) {
6519
+ if (!this.hits.length)
6520
+ return;
6521
+ this.idx = (this.idx + delta + this.hits.length) % this.hits.length;
6522
+ this.host.focusMatch(this.hits[this.idx]);
6075
6523
  this.paint();
6076
6524
  }
6077
- onDocDown = (e) => {
6078
- if (this.mode.kind === "closed")
6525
+ doReplaceOne() {
6526
+ if (this.idx < 0 || !this.hits[this.idx] || this.host.readonly())
6079
6527
  return;
6080
- const t = e.target;
6081
- if (this.overlay.contains(t))
6528
+ const m = this.hits[this.idx];
6529
+ const steps = replaceMatch(m, this.r);
6530
+ const caret3 = m.offset + this.r.length;
6531
+ this.host.dispatch(steps, {
6532
+ anchor: { path: m.path.concat(caret3), assoc: 1 },
6533
+ head: { path: m.path.concat(caret3), assoc: 1 }
6534
+ });
6535
+ this.refresh();
6536
+ if (this.hits.length)
6537
+ this.idx = Math.min(this.idx, this.hits.length - 1);
6538
+ this.paint();
6539
+ if (this.hits[this.idx])
6540
+ this.host.focusMatch(this.hits[this.idx]);
6541
+ }
6542
+ doReplaceAll() {
6543
+ if (!this.q || this.host.readonly())
6082
6544
  return;
6083
- if (t.closest?.('[data-atom="mention"]'))
6545
+ const { steps, count } = replaceAll(this.host.doc(), this.q, this.r, {
6546
+ caseSensitive: this.caseSensitive
6547
+ });
6548
+ if (!count)
6084
6549
  return;
6085
- this.close();
6086
- };
6550
+ this.host.dispatch(steps);
6551
+ this.refresh();
6552
+ this.paint();
6553
+ }
6554
+ paint() {
6555
+ if (!this.open_) {
6556
+ render8(null, this.el);
6557
+ return;
6558
+ }
6559
+ const n = this.hits.length;
6560
+ const label = !this.q ? "" : n === 0 ? "0" : `${this.idx + 1}/${n}`;
6561
+ render8(
6562
+ h10(
6563
+ "div",
6564
+ {
6565
+ class: "markloom-search-bar",
6566
+ onKeyDown: (e) => this.onBarKey(e)
6567
+ },
6568
+ h10("input", {
6569
+ "data-search-q": "",
6570
+ type: "text",
6571
+ placeholder: "\u67E5\u627E",
6572
+ value: this.q,
6573
+ onInput: (e) => {
6574
+ this.q = e.target.value;
6575
+ this.idx = 0;
6576
+ this.refresh();
6577
+ this.paint();
6578
+ if (this.hits[0])
6579
+ this.host.focusMatch(this.hits[0]);
6580
+ }
6581
+ }),
6582
+ h10("input", {
6583
+ "data-search-r": "",
6584
+ type: "text",
6585
+ placeholder: "\u66FF\u6362\u4E3A",
6586
+ value: this.r,
6587
+ onInput: (e) => {
6588
+ this.r = e.target.value;
6589
+ }
6590
+ }),
6591
+ h10(
6592
+ "label",
6593
+ { class: "markloom-search-case" },
6594
+ h10("input", {
6595
+ type: "checkbox",
6596
+ checked: this.caseSensitive,
6597
+ onChange: (e) => {
6598
+ this.caseSensitive = e.target.checked;
6599
+ this.refresh();
6600
+ this.paint();
6601
+ }
6602
+ }),
6603
+ "Aa"
6604
+ ),
6605
+ h10("span", { class: "markloom-search-count" }, label),
6606
+ h10("button", { type: "button", onClick: () => this.go(-1), title: "\u4E0A\u4E00\u4E2A" }, "\u2191"),
6607
+ h10("button", { type: "button", onClick: () => this.go(1), title: "\u4E0B\u4E00\u4E2A" }, "\u2193"),
6608
+ h10("button", { type: "button", onClick: () => this.doReplaceOne() }, "\u66FF\u6362"),
6609
+ h10("button", { type: "button", onClick: () => this.doReplaceAll() }, "\u5168\u90E8"),
6610
+ h10("button", {
6611
+ type: "button",
6612
+ class: "markloom-search-x",
6613
+ onClick: () => this.close(),
6614
+ title: "\u5173\u95ED"
6615
+ }, "\xD7")
6616
+ ),
6617
+ this.el
6618
+ );
6619
+ }
6620
+ onBarKey(e) {
6621
+ if (e.key === "Escape") {
6622
+ e.preventDefault();
6623
+ e.stopPropagation();
6624
+ this.close();
6625
+ return;
6626
+ }
6627
+ if (e.key === "Enter") {
6628
+ e.preventDefault();
6629
+ e.stopPropagation();
6630
+ if (e.shiftKey)
6631
+ this.go(-1);
6632
+ else
6633
+ this.go(1);
6634
+ }
6635
+ }
6636
+ };
6637
+
6638
+ // src/view/versions-panel.ts
6639
+ import { h as h11, render as render9 } from "preact";
6640
+ var VersionsPanel = class {
6641
+ host;
6642
+ el;
6643
+ open = false;
6644
+ onRedraw = () => {
6645
+ if (this.open)
6646
+ this.paint();
6647
+ };
6648
+ constructor(host) {
6649
+ this.host = host;
6650
+ this.el = document.createElement("div");
6651
+ this.el.className = "markloom-versions";
6652
+ this.el.setAttribute("contenteditable", "false");
6653
+ this.el.hidden = true;
6654
+ host.root.insertBefore(this.el, host.root.firstChild);
6655
+ host.root.addEventListener("markloom-redraw", this.onRedraw);
6656
+ host.root.addEventListener("keydown", this.onKey, true);
6657
+ }
6658
+ destroy() {
6659
+ this.host.root.removeEventListener("markloom-redraw", this.onRedraw);
6660
+ this.host.root.removeEventListener("keydown", this.onKey, true);
6661
+ render9(null, this.el);
6662
+ this.el.remove();
6663
+ }
6664
+ show() {
6665
+ this.open = true;
6666
+ this.el.hidden = false;
6667
+ this.paint();
6668
+ }
6669
+ hide() {
6670
+ this.open = false;
6671
+ this.el.hidden = true;
6672
+ }
6673
+ toggle() {
6674
+ if (this.open)
6675
+ this.hide();
6676
+ else
6677
+ this.show();
6678
+ }
6087
6679
  onKey = (e) => {
6088
- if (e.key === "Escape" && this.mode.kind !== "closed") {
6680
+ if (!(e.metaKey || e.ctrlKey) || !e.shiftKey || e.key.toLowerCase() !== "s")
6681
+ return;
6682
+ if (this.host.readonly())
6683
+ return;
6684
+ e.preventDefault();
6685
+ e.stopPropagation();
6686
+ this.host.save();
6687
+ this.show();
6688
+ };
6689
+ paint() {
6690
+ const list = [...this.host.list()].reverse();
6691
+ render9(
6692
+ h11("div", { class: "markloom-versions-bar" }, [
6693
+ h11("span", { class: "markloom-versions-title" }, "\u7248\u672C"),
6694
+ h11("button", {
6695
+ type: "button",
6696
+ class: "markloom-versions-save",
6697
+ disabled: this.host.readonly(),
6698
+ onClick: () => {
6699
+ this.host.save();
6700
+ this.paint();
6701
+ }
6702
+ }, "\u4FDD\u5B58"),
6703
+ h11(
6704
+ "div",
6705
+ { class: "markloom-versions-list" },
6706
+ list.length === 0 ? h11("span", { class: "markloom-versions-empty" }, "\u5C1A\u65E0\u5FEB\u7167 \xB7 \u2318\u21E7S") : list.map((v) => h11("div", { key: v.id, class: "markloom-versions-row" }, [
6707
+ h11("button", {
6708
+ type: "button",
6709
+ class: "markloom-versions-name",
6710
+ title: new Date(v.createdAt).toLocaleString(),
6711
+ onClick: () => {
6712
+ this.host.restore(v.id);
6713
+ }
6714
+ }, v.name),
6715
+ h11("button", {
6716
+ type: "button",
6717
+ class: "markloom-versions-x",
6718
+ title: "\u5220\u9664",
6719
+ onClick: () => {
6720
+ this.host.remove(v.id);
6721
+ this.paint();
6722
+ }
6723
+ }, "\xD7")
6724
+ ]))
6725
+ ),
6726
+ h11("button", {
6727
+ type: "button",
6728
+ class: "markloom-versions-close",
6729
+ onClick: () => this.hide()
6730
+ }, "\xD7")
6731
+ ]),
6732
+ this.el
6733
+ );
6734
+ }
6735
+ };
6736
+
6737
+ // src/view/suggest-bar.ts
6738
+ import { h as h12, render as render10 } from "preact";
6739
+ var SuggestBar = class {
6740
+ host;
6741
+ el;
6742
+ open = false;
6743
+ onRedraw = () => {
6744
+ if (this.open)
6745
+ this.paint();
6746
+ };
6747
+ constructor(host) {
6748
+ this.host = host;
6749
+ this.el = document.createElement("div");
6750
+ this.el.className = "markloom-suggest";
6751
+ this.el.setAttribute("contenteditable", "false");
6752
+ this.el.hidden = true;
6753
+ host.root.insertBefore(this.el, host.root.firstChild);
6754
+ host.root.addEventListener("markloom-redraw", this.onRedraw);
6755
+ host.root.addEventListener("keydown", this.onKey, true);
6756
+ }
6757
+ destroy() {
6758
+ this.host.root.removeEventListener("markloom-redraw", this.onRedraw);
6759
+ this.host.root.removeEventListener("keydown", this.onKey, true);
6760
+ render10(null, this.el);
6761
+ this.el.remove();
6762
+ }
6763
+ show() {
6764
+ this.open = true;
6765
+ this.el.hidden = false;
6766
+ this.paint();
6767
+ }
6768
+ hide() {
6769
+ this.open = false;
6770
+ this.el.hidden = true;
6771
+ }
6772
+ toggle() {
6773
+ if (this.open)
6774
+ this.hide();
6775
+ else
6776
+ this.show();
6777
+ }
6778
+ rescan() {
6779
+ if (this.open)
6780
+ this.paint();
6781
+ }
6782
+ /** 选区标建议(insert|delete) */
6783
+ markSelection(kind) {
6784
+ if (this.host.readonly())
6785
+ return false;
6786
+ const sel = this.host.markSel();
6787
+ if (!sel)
6788
+ return false;
6789
+ const id = this.host.newId();
6790
+ const steps = markSuggestRange(this.host.doc(), sel, kind, id, this.host.author());
6791
+ if (!steps.length)
6792
+ return false;
6793
+ this.host.dispatch(steps);
6794
+ this.show();
6795
+ return true;
6796
+ }
6797
+ accept(id) {
6798
+ const steps = acceptSuggestion(this.host.doc(), id);
6799
+ if (steps.length)
6800
+ this.host.dispatch(steps);
6801
+ this.rescan();
6802
+ }
6803
+ reject(id) {
6804
+ const steps = rejectSuggestion(this.host.doc(), id);
6805
+ if (steps.length)
6806
+ this.host.dispatch(steps);
6807
+ this.rescan();
6808
+ }
6809
+ onKey = (e) => {
6810
+ if (!(e.metaKey || e.ctrlKey) || !e.shiftKey || e.key.toLowerCase() !== "g")
6811
+ return;
6812
+ e.preventDefault();
6813
+ e.stopPropagation();
6814
+ if (!this.open) {
6815
+ this.host.setTracking(true);
6816
+ this.show();
6817
+ } else {
6818
+ this.host.setTracking(!this.host.tracking());
6819
+ this.paint();
6820
+ }
6821
+ };
6822
+ paint() {
6823
+ const hits = listSuggestions(this.host.doc());
6824
+ const tracking = this.host.tracking();
6825
+ render10(
6826
+ h12("div", { class: "markloom-suggest-bar" }, [
6827
+ h12("label", { class: "markloom-suggest-track" }, [
6828
+ h12("input", {
6829
+ type: "checkbox",
6830
+ checked: tracking,
6831
+ onChange: (e) => {
6832
+ this.host.setTracking(e.target.checked);
6833
+ this.paint();
6834
+ }
6835
+ }),
6836
+ "\u8DDF\u8E2A\u4FEE\u8BA2"
6837
+ ]),
6838
+ h12("button", {
6839
+ type: "button",
6840
+ disabled: this.host.readonly(),
6841
+ onClick: () => this.markSelection("insert")
6842
+ }, "\u6807\u63D2\u5165"),
6843
+ h12("button", {
6844
+ type: "button",
6845
+ disabled: this.host.readonly(),
6846
+ onClick: () => this.markSelection("delete")
6847
+ }, "\u6807\u5220\u9664"),
6848
+ h12("span", { class: "markloom-suggest-count" }, `${hits.length} \u6761`),
6849
+ h12(
6850
+ "div",
6851
+ { class: "markloom-suggest-list" },
6852
+ hits.map((hit) => h12("div", {
6853
+ key: hit.id,
6854
+ class: `markloom-suggest-row is-${hit.kind}`
6855
+ }, [
6856
+ h12("span", { class: "markloom-suggest-kind" }, hit.kind === "insert" ? "+" : "\u2212"),
6857
+ h12(
6858
+ "span",
6859
+ { class: "markloom-suggest-quote", title: hit.quote },
6860
+ hit.quote.length > 24 ? `${hit.quote.slice(0, 24)}\u2026` : hit.quote
6861
+ ),
6862
+ h12("button", {
6863
+ type: "button",
6864
+ class: "markloom-suggest-ok",
6865
+ title: "\u63A5\u53D7",
6866
+ disabled: this.host.readonly(),
6867
+ onClick: () => this.accept(hit.id)
6868
+ }, "\u2713"),
6869
+ h12("button", {
6870
+ type: "button",
6871
+ class: "markloom-suggest-no",
6872
+ title: "\u62D2\u7EDD",
6873
+ disabled: this.host.readonly(),
6874
+ onClick: () => this.reject(hit.id)
6875
+ }, "\u2717")
6876
+ ]))
6877
+ ),
6878
+ h12("button", {
6879
+ type: "button",
6880
+ class: "markloom-suggest-close",
6881
+ onClick: () => this.hide()
6882
+ }, "\xD7")
6883
+ ]),
6884
+ this.el
6885
+ );
6886
+ }
6887
+ };
6888
+
6889
+ // src/view/extensions/suggest.ts
6890
+ var suggest = {
6891
+ name: "suggest",
6892
+ marks: [{ name: "suggest", tag: "span" }]
6893
+ };
6894
+
6895
+ // src/view/mention-popovers.ts
6896
+ import { h as h13, render as render11 } from "preact";
6897
+ var MentionPopovers = class {
6898
+ host;
6899
+ overlay;
6900
+ mode = { kind: "closed" };
6901
+ constructor(host) {
6902
+ this.host = host;
6903
+ this.overlay = document.createElement("div");
6904
+ this.overlay.className = "markloom-mention-pop-host";
6905
+ document.body.appendChild(this.overlay);
6906
+ document.addEventListener("pointerdown", this.onDocDown, true);
6907
+ document.addEventListener("keydown", this.onKey, true);
6908
+ window.addEventListener("scroll", this.close, true);
6909
+ window.addEventListener("resize", this.close);
6910
+ }
6911
+ destroy() {
6912
+ document.removeEventListener("pointerdown", this.onDocDown, true);
6913
+ document.removeEventListener("keydown", this.onKey, true);
6914
+ window.removeEventListener("scroll", this.close, true);
6915
+ window.removeEventListener("resize", this.close);
6916
+ render11(null, this.overlay);
6917
+ this.overlay.remove();
6918
+ }
6919
+ close = () => {
6920
+ if (this.mode.kind === "closed")
6921
+ return;
6922
+ this.mode = { kind: "closed" };
6923
+ render11(null, this.overlay);
6924
+ };
6925
+ openPerson(profile, anchor) {
6926
+ this.mode = { kind: "person", profile, rect: anchor };
6927
+ this.paint();
6928
+ }
6929
+ openDate(iso, path, anchor) {
6930
+ const d = parseDateTime(iso) ?? /* @__PURE__ */ new Date();
6931
+ this.mode = {
6932
+ kind: "date",
6933
+ path,
6934
+ rect: anchor,
6935
+ draft: {
6936
+ y: d.getFullYear(),
6937
+ m: d.getMonth(),
6938
+ d: d.getDate(),
6939
+ h: d.getHours(),
6940
+ min: d.getMinutes(),
6941
+ s: d.getSeconds(),
6942
+ viewY: d.getFullYear(),
6943
+ viewM: d.getMonth()
6944
+ }
6945
+ };
6946
+ this.paint();
6947
+ }
6948
+ onDocDown = (e) => {
6949
+ if (this.mode.kind === "closed")
6950
+ return;
6951
+ const t = e.target;
6952
+ if (this.overlay.contains(t))
6953
+ return;
6954
+ if (t.closest?.('[data-atom="mention"]'))
6955
+ return;
6956
+ this.close();
6957
+ };
6958
+ onKey = (e) => {
6959
+ if (this.mode.kind === "closed")
6960
+ return;
6961
+ if (e.key === "Escape") {
6089
6962
  e.preventDefault();
6090
6963
  this.close();
6964
+ return;
6965
+ }
6966
+ if (e.key === "Enter" && this.mode.kind === "date") {
6967
+ const t = e.target;
6968
+ if (t?.tagName === "INPUT")
6969
+ return;
6970
+ e.preventDefault();
6971
+ this.applyDate();
6091
6972
  }
6092
6973
  };
6974
+ applyDate() {
6975
+ if (this.mode.kind !== "date")
6976
+ return;
6977
+ this.host.onDateChange?.(this.mode.path, toIso(this.mode.draft));
6978
+ this.close();
6979
+ }
6093
6980
  paint() {
6094
6981
  if (this.mode.kind === "closed") {
6095
- render8(null, this.overlay);
6982
+ render11(null, this.overlay);
6096
6983
  return;
6097
6984
  }
6098
6985
  if (this.mode.kind === "person")
@@ -6108,29 +6995,29 @@ var MentionPopovers = class {
6108
6995
  paintPerson(mode) {
6109
6996
  const p = mode.profile;
6110
6997
  const initial = (p.name || "?").slice(0, 1);
6111
- render8(
6112
- h10("div", {
6998
+ render11(
6999
+ h13("div", {
6113
7000
  class: "markloom-profile-card",
6114
- style: { position: "fixed", width: "280px", zIndex: "100" },
7001
+ style: { position: "fixed", width: "272px", zIndex: "100" },
6115
7002
  "data-mention-pop": "person",
6116
7003
  onMouseDown: (e) => e.stopPropagation()
6117
7004
  }, [
6118
- h10("div", { class: "markloom-profile-head", key: "h" }, [
6119
- p.avatar ? h10("img", { class: "markloom-profile-avatar", src: p.avatar, alt: "" }) : h10("div", { class: "markloom-profile-avatar markloom-profile-avatar-fallback" }, initial),
6120
- h10("div", { class: "markloom-profile-id" }, [
6121
- h10("div", { class: "markloom-profile-name" }, p.name),
6122
- p.title && h10("div", { class: "markloom-profile-title" }, p.title),
6123
- p.department && h10("div", { class: "markloom-profile-dept" }, p.department)
7005
+ h13("div", { class: "markloom-profile-head", key: "h" }, [
7006
+ p.avatar ? h13("img", { class: "markloom-profile-avatar", src: p.avatar, alt: "" }) : h13("div", { class: "markloom-profile-avatar markloom-profile-avatar-fallback" }, initial),
7007
+ h13("div", { class: "markloom-profile-id" }, [
7008
+ h13("div", { class: "markloom-profile-name" }, p.name),
7009
+ p.title && h13("div", { class: "markloom-profile-title" }, p.title),
7010
+ p.department && h13("div", { class: "markloom-profile-dept" }, p.department)
6124
7011
  ])
6125
7012
  ]),
6126
- (p.email || p.status) && h10("div", { class: "markloom-profile-meta", key: "m" }, [
6127
- p.status && h10("div", { class: "markloom-profile-row" }, [
6128
- h10("span", { class: "markloom-profile-k" }, "\u72B6\u6001"),
6129
- h10("span", { class: "markloom-profile-v" }, p.status)
7013
+ (p.email || p.status) && h13("div", { class: "markloom-profile-meta", key: "m" }, [
7014
+ p.status && h13("div", { class: "markloom-profile-row" }, [
7015
+ h13("span", { class: "markloom-profile-k" }, "\u72B6\u6001"),
7016
+ h13("span", { class: "markloom-profile-v" }, p.status)
6130
7017
  ]),
6131
- p.email && h10("div", { class: "markloom-profile-row" }, [
6132
- h10("span", { class: "markloom-profile-k" }, "\u90AE\u7BB1"),
6133
- h10("a", { class: "markloom-profile-v markloom-profile-link", href: `mailto:${p.email}` }, p.email)
7018
+ p.email && h13("div", { class: "markloom-profile-row" }, [
7019
+ h13("span", { class: "markloom-profile-k" }, "\u90AE\u7BB1"),
7020
+ h13("a", { class: "markloom-profile-v markloom-profile-link", href: `mailto:${p.email}` }, p.email)
6134
7021
  ])
6135
7022
  ])
6136
7023
  ]),
@@ -6158,37 +7045,44 @@ var MentionPopovers = class {
6158
7045
  this.mode = { ...mode, draft: { ...draft, ...patch } };
6159
7046
  this.paint();
6160
7047
  };
6161
- const apply = () => {
6162
- this.host.onDateChange?.(mode.path, toIso(draft));
6163
- this.close();
6164
- };
6165
- const spin = (key, max2, label) => h10("label", { class: "markloom-time-field", key }, [
6166
- h10("span", { class: "markloom-time-field-lab" }, label),
6167
- h10("input", {
6168
- type: "number",
6169
- class: "markloom-time-input",
6170
- min: 0,
6171
- max: max2,
6172
- value: draft[key],
6173
- "data-time": key,
6174
- onInput: (e) => {
6175
- let n = Math.floor(Number(e.target.value));
6176
- if (!Number.isFinite(n))
6177
- n = 0;
6178
- n = Math.max(0, Math.min(max2, n));
6179
- setDraft({ [key]: n });
7048
+ const spin = (key, max2) => h13("input", {
7049
+ type: "number",
7050
+ key,
7051
+ class: "markloom-time-input",
7052
+ min: 0,
7053
+ max: max2,
7054
+ value: draft[key],
7055
+ "data-time": key,
7056
+ onFocus: (e) => {
7057
+ e.target.select();
7058
+ },
7059
+ onInput: (e) => {
7060
+ let n = Math.floor(Number(e.target.value));
7061
+ if (!Number.isFinite(n))
7062
+ n = 0;
7063
+ n = Math.max(0, Math.min(max2, n));
7064
+ setDraft({ [key]: n });
7065
+ },
7066
+ onKeyDown: (e) => {
7067
+ if (e.key === "Enter") {
7068
+ e.preventDefault();
7069
+ this.applyDate();
6180
7070
  }
6181
- })
6182
- ]);
6183
- render8(
6184
- h10("div", {
7071
+ }
7072
+ });
7073
+ render11(
7074
+ h13("div", {
6185
7075
  class: "markloom-date-picker markloom-datetime-picker",
6186
- style: { position: "fixed", width: "300px", zIndex: "100" },
7076
+ style: { position: "fixed", width: "292px", zIndex: "100" },
6187
7077
  "data-mention-pop": "date",
6188
- onMouseDown: (e) => e.stopPropagation()
7078
+ onMouseDown: (e) => {
7079
+ const t = e.target;
7080
+ if (!(t instanceof HTMLInputElement))
7081
+ e.preventDefault();
7082
+ }
6189
7083
  }, [
6190
- h10("div", { class: "markloom-date-hd", key: "hd" }, [
6191
- h10("button", {
7084
+ h13("div", { class: "markloom-date-hd", key: "hd" }, [
7085
+ h13("button", {
6192
7086
  type: "button",
6193
7087
  class: "markloom-date-nav",
6194
7088
  "data-act": "prev",
@@ -6202,8 +7096,8 @@ var MentionPopovers = class {
6202
7096
  setDraft({ viewY: ny, viewM: nm });
6203
7097
  }
6204
7098
  }, "\u2039"),
6205
- h10("span", { class: "markloom-date-label" }, monthLabel),
6206
- h10("button", {
7099
+ h13("span", { class: "markloom-date-label" }, monthLabel),
7100
+ h13("button", {
6207
7101
  type: "button",
6208
7102
  class: "markloom-date-nav",
6209
7103
  "data-act": "next",
@@ -6218,15 +7112,15 @@ var MentionPopovers = class {
6218
7112
  }
6219
7113
  }, "\u203A")
6220
7114
  ]),
6221
- h10(
7115
+ h13(
6222
7116
  "div",
6223
7117
  { class: "markloom-date-week", key: "w" },
6224
- week.map((d) => h10("span", { key: d }, d))
7118
+ week.map((d) => h13("span", { key: d }, d))
6225
7119
  ),
6226
- h10(
7120
+ h13(
6227
7121
  "div",
6228
7122
  { class: "markloom-date-grid", key: "g" },
6229
- cells.map((c, i) => c.day == null ? h10("span", { key: `e${i}`, class: "markloom-date-cell markloom-date-empty" }) : h10("button", {
7123
+ cells.map((c, i) => c.day == null ? h13("span", { key: `e${i}`, class: "markloom-date-cell markloom-date-empty" }) : h13("button", {
6230
7124
  key: `d${c.day}`,
6231
7125
  type: "button",
6232
7126
  class: "markloom-date-cell" + (draft.y === viewY && draft.m === viewM && draft.d === c.day ? " markloom-date-selected" : "") + (isToday(viewY, viewM, c.day) ? " markloom-date-today" : ""),
@@ -6234,20 +7128,26 @@ var MentionPopovers = class {
6234
7128
  onMouseDown: (e) => {
6235
7129
  e.preventDefault();
6236
7130
  setDraft({ y: viewY, m: viewM, d: c.day });
7131
+ },
7132
+ // 双击日 → 立即确认(时分秒保留)
7133
+ onDblClick: (e) => {
7134
+ e.preventDefault();
7135
+ this.mode = { ...mode, draft: { ...draft, y: viewY, m: viewM, d: c.day } };
7136
+ this.applyDate();
6237
7137
  }
6238
7138
  }, String(c.day)))
6239
7139
  ),
6240
- // 时:分:秒 一体
6241
- h10("div", { class: "markloom-time-row", key: "time" }, [
6242
- spin("h", 23, "\u65F6"),
6243
- h10("span", { class: "markloom-time-colon", key: "c1" }, ":"),
6244
- spin("min", 59, "\u5206"),
6245
- h10("span", { class: "markloom-time-colon", key: "c2" }, ":"),
6246
- spin("s", 59, "\u79D2")
7140
+ // 时:分:秒 紧凑一行 + 预览
7141
+ h13("div", { class: "markloom-time-row", key: "time" }, [
7142
+ spin("h", 23),
7143
+ h13("span", { class: "markloom-time-colon", key: "c1" }, ":"),
7144
+ spin("min", 59),
7145
+ h13("span", { class: "markloom-time-colon", key: "c2" }, ":"),
7146
+ spin("s", 59)
6247
7147
  ]),
6248
- h10("div", { class: "markloom-date-preview", key: "pv" }, preview),
6249
- h10("div", { class: "markloom-date-ft", key: "ft" }, [
6250
- h10("button", {
7148
+ h13("div", { class: "markloom-date-preview", key: "pv" }, preview),
7149
+ h13("div", { class: "markloom-date-ft", key: "ft" }, [
7150
+ h13("button", {
6251
7151
  type: "button",
6252
7152
  class: "markloom-date-today-btn",
6253
7153
  "data-act": "now",
@@ -6266,13 +7166,13 @@ var MentionPopovers = class {
6266
7166
  });
6267
7167
  }
6268
7168
  }, "\u73B0\u5728"),
6269
- h10("button", {
7169
+ h13("button", {
6270
7170
  type: "button",
6271
7171
  class: "markloom-date-ok",
6272
7172
  "data-act": "ok",
6273
7173
  onMouseDown: (e) => {
6274
7174
  e.preventDefault();
6275
- apply();
7175
+ this.applyDate();
6276
7176
  }
6277
7177
  }, "\u786E\u5B9A")
6278
7178
  ])
@@ -6302,14 +7202,14 @@ function parseDateTime(s) {
6302
7202
  const y = Number(dp[0]), mo = Number(dp[1]), d = Number(dp[2]);
6303
7203
  if (!y || !mo || !d)
6304
7204
  return null;
6305
- let h13 = 0, mi = 0, se = 0;
7205
+ let h17 = 0, mi = 0, se = 0;
6306
7206
  if (timePart) {
6307
7207
  const tp = timePart.split(":");
6308
- h13 = Number(tp[0]) || 0;
7208
+ h17 = Number(tp[0]) || 0;
6309
7209
  mi = Number(tp[1]) || 0;
6310
7210
  se = Math.floor(Number(tp[2]) || 0);
6311
7211
  }
6312
- const dt = new Date(y, mo - 1, d, h13, mi, se);
7212
+ const dt = new Date(y, mo - 1, d, h17, mi, se);
6313
7213
  if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d)
6314
7214
  return null;
6315
7215
  return dt;
@@ -6320,10 +7220,250 @@ function isToday(y, m, day) {
6320
7220
  }
6321
7221
 
6322
7222
  // src/view/editor.ts
6323
- import { render as render11 } from "preact";
7223
+ import { Fragment, h as h16, render as render14 } from "preact";
7224
+
7225
+ // src/view/collab-presence.ts
7226
+ function wireOf(sel) {
7227
+ const split2 = (p) => {
7228
+ const path = p.path;
7229
+ if (path.length < 1)
7230
+ return { path: [], offset: 0 };
7231
+ return { path: path.slice(0, -1), offset: path[path.length - 1] };
7232
+ };
7233
+ return { anchor: split2(sel.anchor), head: split2(sel.head) };
7234
+ }
7235
+ function posOf(w) {
7236
+ return { path: w.path.concat(w.offset) };
7237
+ }
7238
+ var CollabPresence = class {
7239
+ host;
7240
+ rail;
7241
+ avatars;
7242
+ statusEl;
7243
+ carets;
7244
+ peers = [];
7245
+ self = null;
7246
+ status = "connecting";
7247
+ /** rAF 合并;输入路径走 flushPresence 同步发,无 80ms 延迟 */
7248
+ presenceRaf = 0;
7249
+ lastWire = "";
7250
+ onSel = () => this.schedulePresence();
7251
+ onScroll = () => this.paintCarets();
7252
+ onResize = () => this.paintCarets();
7253
+ destroyed = false;
7254
+ constructor(host) {
7255
+ this.host = host;
7256
+ const root = host.root;
7257
+ if (getComputedStyle(root).position === "static")
7258
+ root.style.position = "relative";
7259
+ this.rail = document.createElement("div");
7260
+ this.rail.className = "markloom-collab-rail";
7261
+ this.rail.setAttribute("contenteditable", "false");
7262
+ this.statusEl = document.createElement("span");
7263
+ this.statusEl.className = "markloom-collab-status is-connecting";
7264
+ this.statusEl.title = "\u8FDE\u63A5\u4E2D";
7265
+ this.avatars = document.createElement("div");
7266
+ this.avatars.className = "markloom-collab-avatars";
7267
+ this.rail.appendChild(this.statusEl);
7268
+ this.rail.appendChild(this.avatars);
7269
+ this.carets = document.createElement("div");
7270
+ this.carets.className = "markloom-collab-carets";
7271
+ this.carets.setAttribute("contenteditable", "false");
7272
+ const railParent = host.railParent?.() ?? null;
7273
+ if (railParent) {
7274
+ this.rail.classList.add("is-chrome");
7275
+ railParent.appendChild(this.rail);
7276
+ } else {
7277
+ root.insertBefore(this.rail, root.firstChild);
7278
+ }
7279
+ root.appendChild(this.carets);
7280
+ document.addEventListener("selectionchange", this.onSel);
7281
+ window.addEventListener("scroll", this.onScroll, true);
7282
+ window.addEventListener("resize", this.onResize);
7283
+ }
7284
+ /** welcome 后设本人;peers 更新时刷新 */
7285
+ setSelf(siteId, name, color) {
7286
+ this.self = { siteId, name, color: collabColor(siteId, color) };
7287
+ this.paintAvatars();
7288
+ }
7289
+ setStatus(s) {
7290
+ this.status = s;
7291
+ this.statusEl.className = `markloom-collab-status is-${s}`;
7292
+ const tip = {
7293
+ connecting: "\u8FDE\u63A5\u4E2D\u2026",
7294
+ open: "\u5DF2\u8FDE\u63A5",
7295
+ closed: "\u5DF2\u65AD\u5F00 \xB7 \u91CD\u8FDE\u4E2D",
7296
+ resyncing: "\u540C\u6B65\u4E2D\u2026",
7297
+ "auth-error": "\u9274\u6743\u5931\u8D25"
7298
+ };
7299
+ this.statusEl.title = tip[s] ?? s;
7300
+ this.rail.hidden = false;
7301
+ }
7302
+ setPeers(peers) {
7303
+ this.peers = peers.map((p) => ({
7304
+ ...p,
7305
+ color: collabColor(p.siteId, p.color)
7306
+ }));
7307
+ this.paintAvatars();
7308
+ this.paintCarets();
7309
+ }
7310
+ /** model 重绘后光标 DOM 位可能变 */
7311
+ onRedraw() {
7312
+ this.paintCarets();
7313
+ }
7314
+ /**
7315
+ * 本地刚打完字/改完 doc 后立刻上报光标(与 op 同帧)。
7316
+ * 不走 debounce,避免对方看到彩色光标落后输入几百 ms。
7317
+ */
7318
+ flushPresence() {
7319
+ if (this.presenceRaf) {
7320
+ cancelAnimationFrame(this.presenceRaf);
7321
+ this.presenceRaf = 0;
7322
+ }
7323
+ this.sendPresence(true);
7324
+ }
7325
+ destroy() {
7326
+ this.destroyed = true;
7327
+ document.removeEventListener("selectionchange", this.onSel);
7328
+ window.removeEventListener("scroll", this.onScroll, true);
7329
+ window.removeEventListener("resize", this.onResize);
7330
+ if (this.presenceRaf)
7331
+ cancelAnimationFrame(this.presenceRaf);
7332
+ this.rail.remove();
7333
+ this.carets.remove();
7334
+ }
7335
+ /** 纯移光标:并到下一帧,避免 selectionchange 风暴 */
7336
+ schedulePresence() {
7337
+ if (this.presenceRaf || this.destroyed)
7338
+ return;
7339
+ this.presenceRaf = requestAnimationFrame(() => {
7340
+ this.presenceRaf = 0;
7341
+ this.sendPresence(false);
7342
+ });
7343
+ }
7344
+ sendPresence(force) {
7345
+ const c = this.host.collab();
7346
+ if (!c || this.destroyed)
7347
+ return;
7348
+ const sel = readSelection(this.host.root, this.host.doc());
7349
+ if (!sel) {
7350
+ if (force || this.lastWire !== "null") {
7351
+ this.lastWire = "null";
7352
+ c.presence(null);
7353
+ }
7354
+ return;
7355
+ }
7356
+ const w = wireOf(sel);
7357
+ const key = JSON.stringify(w);
7358
+ if (!force && key === this.lastWire)
7359
+ return;
7360
+ this.lastWire = key;
7361
+ c.presence(w);
7362
+ }
7363
+ paintAvatars() {
7364
+ const list = [];
7365
+ if (this.self) {
7366
+ list.push({
7367
+ siteId: this.self.siteId,
7368
+ name: this.self.name,
7369
+ color: this.self.color
7370
+ });
7371
+ }
7372
+ for (const p of this.peers) {
7373
+ if (this.self && p.siteId === this.self.siteId)
7374
+ continue;
7375
+ list.push(p);
7376
+ }
7377
+ list.sort((a, b) => {
7378
+ if (this.self) {
7379
+ if (a.siteId === this.self.siteId)
7380
+ return 1;
7381
+ if (b.siteId === this.self.siteId)
7382
+ return -1;
7383
+ }
7384
+ return a.siteId - b.siteId;
7385
+ });
7386
+ this.avatars.replaceChildren();
7387
+ this.rail.hidden = false;
7388
+ for (const p of list) {
7389
+ const el = document.createElement("div");
7390
+ el.className = "markloom-collab-avatar";
7391
+ if (this.self && p.siteId === this.self.siteId)
7392
+ el.classList.add("is-self");
7393
+ const bg = p.color || collabColor(p.siteId);
7394
+ el.style.setProperty("--collab-c", bg);
7395
+ el.style.color = collabFg(bg);
7396
+ el.textContent = collabInitial(p.name, p.siteId);
7397
+ el.title = p.name || `\u7528\u6237 ${p.siteId}`;
7398
+ this.avatars.appendChild(el);
7399
+ }
7400
+ }
7401
+ paintCarets() {
7402
+ this.carets.replaceChildren();
7403
+ const root = this.host.root;
7404
+ const doc = this.host.doc();
7405
+ const rootRect = root.getBoundingClientRect();
7406
+ const scrollX = root.scrollLeft;
7407
+ const scrollY = root.scrollTop;
7408
+ for (const p of this.peers) {
7409
+ if (this.self && p.siteId === this.self.siteId)
7410
+ continue;
7411
+ if (!p.sel?.head)
7412
+ continue;
7413
+ const pos = posOf(p.sel.head);
7414
+ const dom = pointToDom(root, doc, pos);
7415
+ if (!dom)
7416
+ continue;
7417
+ const range = document.createRange();
7418
+ try {
7419
+ const n = dom.node;
7420
+ const max2 = n.nodeType === 3 ? n.textContent?.length ?? 0 : 0;
7421
+ const off = Math.max(0, Math.min(dom.offset, max2));
7422
+ range.setStart(n, off);
7423
+ range.setEnd(n, off);
7424
+ } catch {
7425
+ continue;
7426
+ }
7427
+ const rects = range.getClientRects();
7428
+ const rect = rects[0] ?? range.getBoundingClientRect();
7429
+ if (!rect || rect.width === 0 && rect.height === 0 && rect.top === 0) {
7430
+ const leaf = dom.node.parentElement;
7431
+ if (!leaf)
7432
+ continue;
7433
+ const r = leaf.getBoundingClientRect();
7434
+ this.addCaret(p, r, rootRect, scrollX, scrollY);
7435
+ continue;
7436
+ }
7437
+ this.addCaret(p, rect, rootRect, scrollX, scrollY);
7438
+ }
7439
+ }
7440
+ addCaret(p, rect, rootRect, scrollX, scrollY) {
7441
+ const soft = p.color || collabColor(p.siteId);
7442
+ const hard = collabCaretColor(p.siteId, p.color);
7443
+ const el = document.createElement("div");
7444
+ el.className = "markloom-collab-caret";
7445
+ el.style.setProperty("--collab-c", hard);
7446
+ el.style.setProperty("--collab-lab", soft);
7447
+ const left = rect.left - rootRect.left + scrollX;
7448
+ const top = rect.top - rootRect.top + scrollY;
7449
+ const h17 = Math.max(rect.height || 16, 14);
7450
+ el.style.left = `${left}px`;
7451
+ el.style.top = `${top}px`;
7452
+ el.style.height = `${h17}px`;
7453
+ const lab = document.createElement("div");
7454
+ lab.className = "markloom-collab-caret-lab";
7455
+ lab.style.background = soft;
7456
+ lab.style.color = collabFg(soft);
7457
+ lab.textContent = p.name || `\u7528\u6237${p.siteId}`;
7458
+ el.appendChild(lab);
7459
+ this.carets.appendChild(el);
7460
+ }
7461
+ };
6324
7462
 
6325
7463
  // src/view/image-controls.ts
6326
- import { h as h11, render as render9 } from "preact";
7464
+ import { h as h14, render as render12 } from "preact";
7465
+ import PhotoSwipe from "photoswipe";
7466
+ import "photoswipe/style.css";
6327
7467
  var DRAG_THRESHOLD = 4;
6328
7468
  var MIN = 24;
6329
7469
  function atomIdsInSelection(doc, sel) {
@@ -6355,8 +7495,13 @@ var ImageControls = class {
6355
7495
  /** 点选 exclusive 块 id(全套柄);与 range 互斥 */
6356
7496
  exclusiveId = null;
6357
7497
  rangeIds = /* @__PURE__ */ new Set();
6358
- lightbox = null;
7498
+ /** PhotoSwipe 实例;非 null 表示预览打开 */
7499
+ pswp = null;
7500
+ /** 测试钩:最近一次打开的预览 src */
7501
+ previewSrc = null;
6359
7502
  editingCaption = false;
7503
+ /** 图注草稿:paint 时写回 value;避免 selectionchange→paint 用空 attrs 冲掉正在输入的字 */
7504
+ captionDraft = "";
6360
7505
  ctxKey = "";
6361
7506
  constructor(root, host) {
6362
7507
  this.root = root;
@@ -6376,10 +7521,12 @@ var ImageControls = class {
6376
7521
  document.removeEventListener("selectionchange", this.onSelChange);
6377
7522
  window.removeEventListener("scroll", this.onReflow, true);
6378
7523
  window.removeEventListener("resize", this.onReflow);
7524
+ this.closePreview();
6379
7525
  this.exclusiveId = null;
6380
7526
  this.rangeIds = /* @__PURE__ */ new Set();
6381
- this.lightbox = null;
6382
- render9(null, this.overlay);
7527
+ this.editingCaption = false;
7528
+ this.captionDraft = "";
7529
+ render12(null, this.overlay);
6383
7530
  this.overlay.remove();
6384
7531
  }
6385
7532
  /** 供 renderDoc 注入的选中上下文 */
@@ -6400,7 +7547,7 @@ var ImageControls = class {
6400
7547
  this.paint();
6401
7548
  }
6402
7549
  onSelChange = () => {
6403
- if (this.lightbox)
7550
+ if (this.pswp || this.editingCaption)
6404
7551
  return;
6405
7552
  const sel = this.host.sel();
6406
7553
  const nextRange = atomIdsInSelection(this.host.doc(), sel);
@@ -6412,33 +7559,135 @@ var ImageControls = class {
6412
7559
  };
6413
7560
  onDocDown = (e) => {
6414
7561
  const el = e.target instanceof HTMLElement ? e.target : null;
6415
- if (el?.closest(".markloom-image-overlay") || el?.closest(".markloom-lightbox"))
7562
+ if (el?.closest(".markloom-image-overlay") || el?.closest(".pswp"))
6416
7563
  return;
6417
7564
  const atom = el?.closest('[data-atom="image"], [data-atom="embed"]');
6418
7565
  if (atom && this.root.contains(atom)) {
6419
7566
  const host = atom.dataset.blockId ? atom : atom.closest("[data-block-id]");
6420
7567
  const id = host?.dataset.blockId ?? atom.dataset.blockId ?? null;
6421
7568
  if (id && id === this.exclusiveId) {
6422
- if ((host ?? atom).getAttribute("data-atom") === "image" || atom.closest('[data-atom="image"]'))
6423
- this.lightbox = imgSrc(host ?? atom);
6424
- this.paint();
6425
7569
  return;
6426
7570
  }
6427
7571
  if (id)
6428
7572
  this.selectByBlockId(id);
6429
7573
  return;
6430
7574
  }
6431
- if (this.exclusiveId || this.lightbox || this.rangeIds.size)
7575
+ if (this.exclusiveId || this.pswp || this.rangeIds.size)
6432
7576
  this.clearSelected();
6433
7577
  };
6434
7578
  onKeyDown = (e) => {
6435
- if (e.key === "Escape" && (this.lightbox || this.exclusiveId))
7579
+ if (this.editingCaption)
7580
+ return;
7581
+ if (this.pswp)
7582
+ return;
7583
+ if (e.key === "Escape" && this.exclusiveId)
6436
7584
  this.clearSelected();
6437
7585
  };
6438
7586
  onReflow = () => {
6439
- if (this.exclusiveId || this.rangeIds.size || this.lightbox)
7587
+ if (this.editingCaption)
7588
+ return;
7589
+ if (this.exclusiveId || this.rangeIds.size)
6440
7590
  this.paint();
6441
7591
  };
7592
+ /** 用 PhotoSwipe 打开大图(缩放/拖拽/键盘) */
7593
+ openPreview(atom) {
7594
+ const src = imgSrc(atom);
7595
+ if (!src)
7596
+ return;
7597
+ const imgEl = atom.matches("img") ? atom : atom.querySelector("img");
7598
+ const displaySrc = imgEl && (imgEl.currentSrc || imgEl.src) || src;
7599
+ this.closePreview();
7600
+ this.previewSrc = displaySrc;
7601
+ render12(null, this.overlay);
7602
+ const start = (w, h17) => {
7603
+ let pswp;
7604
+ try {
7605
+ pswp = new PhotoSwipe({
7606
+ dataSource: [{
7607
+ src: displaySrc,
7608
+ // 占位用同一张已显示的图 → 首帧就有像素,不闪白
7609
+ msrc: displaySrc,
7610
+ width: Math.max(1, w),
7611
+ height: Math.max(1, h17),
7612
+ alt: imgEl?.getAttribute("alt") || "",
7613
+ element: imgEl ?? void 0
7614
+ }],
7615
+ // 不用 zoom 开场:缺可靠 thumbBounds 时会卡在半开/畸变
7616
+ showHideAnimationType: "fade",
7617
+ // 默认 .4,0,.22,1 收尾拖沓;用急起急收的 ease-out
7618
+ easing: "cubic-bezier(0.32, 0.72, 0, 1)",
7619
+ showAnimationDuration: 200,
7620
+ hideAnimationDuration: 140,
7621
+ bgOpacity: 0.92,
7622
+ wheelToZoom: true,
7623
+ initialZoomLevel: "fit",
7624
+ secondaryZoomLevel: 2.5,
7625
+ maxZoomLevel: 6,
7626
+ padding: { top: 32, bottom: 32, left: 32, right: 32 },
7627
+ clickToCloseNonZoomable: true,
7628
+ tapAction: "toggle-controls",
7629
+ imageClickAction: "zoom-or-close"
7630
+ });
7631
+ } catch {
7632
+ this.paint();
7633
+ return;
7634
+ }
7635
+ if (imgEl && imgEl.complete && imgEl.naturalWidth > 0) {
7636
+ pswp.on("contentLoad", (e) => {
7637
+ const content = e.content;
7638
+ if (!content.isImageContent())
7639
+ return;
7640
+ e.preventDefault();
7641
+ const clone = document.createElement("img");
7642
+ clone.className = "pswp__img";
7643
+ clone.alt = imgEl.getAttribute("alt") || "";
7644
+ clone.src = displaySrc;
7645
+ content.element = clone;
7646
+ content.state = "loaded";
7647
+ });
7648
+ }
7649
+ pswp.on("destroy", () => {
7650
+ if (this.pswp === pswp)
7651
+ this.pswp = null;
7652
+ this.previewSrc = null;
7653
+ this.paint();
7654
+ });
7655
+ this.pswp = pswp;
7656
+ pswp.init();
7657
+ };
7658
+ if (imgEl && imgEl.naturalWidth > 0 && imgEl.naturalHeight > 0) {
7659
+ start(imgEl.naturalWidth, imgEl.naturalHeight);
7660
+ return;
7661
+ }
7662
+ const fallback = () => {
7663
+ const r = imgEl?.getBoundingClientRect();
7664
+ start(Math.max(1, Math.round(r?.width || 1200)), Math.max(1, Math.round(r?.height || 800)));
7665
+ };
7666
+ if (imgEl && typeof imgEl.decode === "function") {
7667
+ imgEl.decode().then(() => {
7668
+ if (imgEl.naturalWidth > 0)
7669
+ start(imgEl.naturalWidth, imgEl.naturalHeight);
7670
+ else
7671
+ fallback();
7672
+ }).catch(fallback);
7673
+ return;
7674
+ }
7675
+ fallback();
7676
+ }
7677
+ closePreview() {
7678
+ if (!this.pswp)
7679
+ return;
7680
+ try {
7681
+ this.pswp.close();
7682
+ } catch (_) {
7683
+ try {
7684
+ this.pswp.destroy();
7685
+ } catch (_2) {
7686
+ }
7687
+ }
7688
+ this.pswp = null;
7689
+ this.previewSrc = null;
7690
+ }
6442
7691
  hasSelected() {
6443
7692
  return !!this.exclusiveId && !!this.atomEl(this.exclusiveId);
6444
7693
  }
@@ -6452,7 +7701,8 @@ var ImageControls = class {
6452
7701
  this.exclusiveId = id;
6453
7702
  this.rangeIds = /* @__PURE__ */ new Set();
6454
7703
  this.editingCaption = false;
6455
- this.lightbox = null;
7704
+ this.captionDraft = "";
7705
+ this.closePreview();
6456
7706
  const sel = atom.ownerDocument.getSelection();
6457
7707
  if (sel) {
6458
7708
  const range = atom.ownerDocument.createRange();
@@ -6465,10 +7715,11 @@ var ImageControls = class {
6465
7715
  return true;
6466
7716
  }
6467
7717
  clearSelected() {
7718
+ this.closePreview();
6468
7719
  this.exclusiveId = null;
6469
7720
  this.rangeIds = /* @__PURE__ */ new Set();
6470
- this.lightbox = null;
6471
7721
  this.editingCaption = false;
7722
+ this.captionDraft = "";
6472
7723
  this.publishCtx();
6473
7724
  }
6474
7725
  atomEl(id) {
@@ -6494,23 +7745,50 @@ var ImageControls = class {
6494
7745
  if (attrs[k] === "" || attrs[k] === "left" || attrs[k] == null)
6495
7746
  delete attrs[k];
6496
7747
  this.host.dispatch([{ kind: "replaceNode", path: b.path, node: { ...b.node, attrs } }]);
6497
- this.exclusiveId = null;
7748
+ if ("caption" in patch) {
7749
+ this.editingCaption = false;
7750
+ this.captionDraft = "";
7751
+ }
7752
+ this.paint();
7753
+ }
7754
+ openCaptionEditor() {
7755
+ this.editingCaption = true;
7756
+ this.captionDraft = String(this.blockNode()?.node.attrs?.caption ?? "");
7757
+ this.paint();
7758
+ queueMicrotask(() => {
7759
+ const inp = this.overlay.querySelector(".markloom-ic-tb-caption");
7760
+ if (!inp)
7761
+ return;
7762
+ inp.focus();
7763
+ inp.select();
7764
+ });
7765
+ }
7766
+ commitCaption() {
7767
+ const v = this.captionDraft;
7768
+ this.patchAttrs({ caption: v });
7769
+ }
7770
+ cancelCaptionEdit() {
6498
7771
  this.editingCaption = false;
6499
- this.publishCtx();
7772
+ this.captionDraft = "";
7773
+ this.paint();
6500
7774
  }
6501
7775
  paint() {
7776
+ if (this.pswp) {
7777
+ render12(null, this.overlay);
7778
+ return;
7779
+ }
6502
7780
  if (this.exclusiveId && !this.atomEl(this.exclusiveId))
6503
7781
  this.exclusiveId = null;
6504
7782
  const kids = [];
6505
7783
  const ex = this.exclusiveId ? this.atomEl(this.exclusiveId) : null;
6506
7784
  if (ex) {
6507
7785
  const r = ex.getBoundingClientRect();
6508
- kids.push(h11("div", { key: "box", class: "markloom-ic-box", style: `left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px` }));
7786
+ kids.push(h14("div", { key: "box", class: "markloom-ic-box", style: `left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px` }));
6509
7787
  if (ex.getAttribute("data-atom") === "image") {
6510
7788
  for (const corner of ["nw", "ne", "sw", "se"]) {
6511
7789
  const x = corner === "nw" || corner === "sw" ? r.left : r.right;
6512
7790
  const y = corner === "nw" || corner === "ne" ? r.top : r.bottom;
6513
- kids.push(h11("div", {
7791
+ kids.push(h14("div", {
6514
7792
  key: corner,
6515
7793
  class: `markloom-ic-handle markloom-ic-${corner}`,
6516
7794
  style: `left:${x}px;top:${y}px`,
@@ -6518,6 +7796,23 @@ var ImageControls = class {
6518
7796
  }));
6519
7797
  }
6520
7798
  kids.push(this.toolbar(r));
7799
+ kids.push(h14("button", {
7800
+ "key": "preview",
7801
+ "type": "button",
7802
+ "class": "markloom-ic-preview",
7803
+ "title": "\u9884\u89C8",
7804
+ "aria-label": "\u9884\u89C8\u56FE\u7247",
7805
+ "style": `left:${r.right - 32}px;top:${r.top + 4}px`,
7806
+ "onMouseDown": (ev) => {
7807
+ ev.preventDefault();
7808
+ ev.stopPropagation();
7809
+ },
7810
+ "onClick": (ev) => {
7811
+ ev.preventDefault();
7812
+ ev.stopPropagation();
7813
+ this.openPreview(ex);
7814
+ }
7815
+ }, icon("zoom-in", 16)));
6521
7816
  }
6522
7817
  }
6523
7818
  for (const id of this.rangeIds) {
@@ -6527,17 +7822,13 @@ var ImageControls = class {
6527
7822
  if (!atom)
6528
7823
  continue;
6529
7824
  const r = atom.getBoundingClientRect();
6530
- kids.push(h11("div", {
7825
+ kids.push(h14("div", {
6531
7826
  key: `r-${id}`,
6532
7827
  class: "markloom-ic-box",
6533
7828
  style: `left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px`
6534
7829
  }));
6535
7830
  }
6536
- if (this.lightbox)
6537
- kids.push(h11("div", { key: "lb", class: "markloom-lightbox", onPointerDown: () => this.clearSelected() }, [
6538
- h11("img", { key: "lbimg", src: this.lightbox })
6539
- ]));
6540
- render9(kids.length ? h11("div", { class: "markloom-ic" }, kids) : null, this.overlay);
7831
+ render12(kids.length ? h14("div", { class: "markloom-ic" }, kids) : null, this.overlay);
6541
7832
  }
6542
7833
  toolbar(r) {
6543
7834
  const cur = this.blockNode()?.node.attrs?.align ?? "left";
@@ -6548,7 +7839,7 @@ var ImageControls = class {
6548
7839
  { value: "right", ico: "align-right", title: "\u53F3\u5BF9\u9F50" },
6549
7840
  { value: "caption", ico: "type", title: "\u56FE\u6CE8" }
6550
7841
  ];
6551
- const btns = aligns.map((a) => h11("button", {
7842
+ const btns = aligns.map((a) => h14("button", {
6552
7843
  "key": a.value,
6553
7844
  "type": "button",
6554
7845
  "title": a.title,
@@ -6556,47 +7847,79 @@ var ImageControls = class {
6556
7847
  "onMouseDown": (e) => {
6557
7848
  e.preventDefault();
6558
7849
  if (a.value === "caption") {
6559
- this.editingCaption = !this.editingCaption;
6560
- this.paint();
6561
- } else this.patchAttrs({ align: a.value });
7850
+ if (this.editingCaption)
7851
+ this.cancelCaptionEdit();
7852
+ else
7853
+ this.openCaptionEditor();
7854
+ } else {
7855
+ this.patchAttrs({ align: a.value });
7856
+ }
6562
7857
  }
6563
7858
  }, icon(a.ico, 14)));
6564
- const row = [h11("div", { key: "row", class: "markloom-ic-tb-row" }, btns)];
7859
+ const row = [h14("div", { key: "row", class: "markloom-ic-tb-row" }, btns)];
6565
7860
  if (this.editingCaption)
6566
- row.push(h11("input", {
7861
+ row.push(h14("input", {
6567
7862
  "key": "capin",
6568
7863
  "class": "markloom-ic-tb-caption",
6569
7864
  "type": "text",
6570
- "value": cap,
7865
+ // 草稿驱动;attrs.caption 只在 Enter 提交后变
7866
+ "value": this.captionDraft,
6571
7867
  "placeholder": "\u56FE\u6CE8\u2026",
6572
- "autoFocus": true,
7868
+ "onInput": (e) => {
7869
+ this.captionDraft = e.currentTarget.value;
7870
+ },
6573
7871
  "onKeyDown": (e) => {
6574
7872
  if (e.key === "Enter") {
6575
7873
  e.preventDefault();
6576
- this.patchAttrs({ caption: e.currentTarget.value });
7874
+ e.stopPropagation();
7875
+ this.commitCaption();
6577
7876
  } else if (e.key === "Escape") {
6578
7877
  e.preventDefault();
6579
- this.editingCaption = false;
6580
- this.paint();
7878
+ e.stopPropagation();
7879
+ this.cancelCaptionEdit();
6581
7880
  }
7881
+ },
7882
+ // 失焦提交(点别处前 onDocDown 会 clear;此处点工具条外且仍 focus 的路径)
7883
+ "onBlur": () => {
7884
+ if (!this.editingCaption)
7885
+ return;
7886
+ queueMicrotask(() => {
7887
+ if (!this.editingCaption)
7888
+ return;
7889
+ if (this.overlay.contains(this.overlay.ownerDocument.activeElement))
7890
+ return;
7891
+ this.commitCaption();
7892
+ });
6582
7893
  }
6583
7894
  }));
6584
- return h11("div", { key: "tb", class: "markloom-ic-tb", style: `left:${r.left}px;top:${r.top - 40}px` }, row);
7895
+ return h14("div", { key: "tb", class: "markloom-ic-tb", style: `left:${r.left}px;top:${r.top - 40}px` }, row);
6585
7896
  }
6586
7897
  startResize(down, corner) {
6587
7898
  down.preventDefault();
6588
7899
  down.stopPropagation();
6589
7900
  const el = this.exclusiveId ? this.atomEl(this.exclusiveId) : null;
6590
- const img = el?.matches("img") ? el : el?.querySelector("img");
7901
+ const img = el?.matches("img") ? el : el?.querySelector("img") ?? null;
6591
7902
  if (!img)
6592
7903
  return;
6593
7904
  const r = img.getBoundingClientRect();
6594
7905
  const startW = r.width;
6595
7906
  const startH = r.height;
6596
- const ratio = startH / startW || 1;
7907
+ const natW = img.naturalWidth > 0 ? img.naturalWidth : startW;
7908
+ const natH = img.naturalHeight > 0 ? img.naturalHeight : startH;
7909
+ const ratio = natH / natW || startH / startW || 1;
6597
7910
  const signX = corner === "ne" || corner === "se" ? 1 : -1;
7911
+ const signY = corner === "se" || corner === "sw" ? 1 : -1;
6598
7912
  let active2 = false;
6599
7913
  let w = startW;
7914
+ let h17 = startH;
7915
+ const applySize = (nw, nh) => {
7916
+ w = nw;
7917
+ h17 = nh;
7918
+ img.style.width = `${nw}px`;
7919
+ img.style.height = "auto";
7920
+ img.removeAttribute("height");
7921
+ this.paint();
7922
+ };
6600
7923
  const move = (ev) => {
6601
7924
  const dx = ev.clientX - down.clientX;
6602
7925
  const dy = ev.clientY - down.clientY;
@@ -6604,17 +7927,22 @@ var ImageControls = class {
6604
7927
  active2 = true;
6605
7928
  if (!active2)
6606
7929
  return;
6607
- w = Math.max(MIN, startW + signX * dx);
6608
- const hgt = Math.max(MIN, Math.round(w * ratio));
6609
- img.style.width = `${Math.round(w)}px`;
6610
- img.style.height = `${hgt}px`;
6611
- this.paint();
7930
+ const fromX = startW + signX * dx;
7931
+ const fromY = ratio > 0 ? (startH + signY * dy) / ratio : fromX;
7932
+ const rawW = Math.abs(dx) >= Math.abs(dy) ? fromX : fromY;
7933
+ let nw = Math.max(MIN, Math.round(rawW));
7934
+ let nh = Math.round(nw * ratio);
7935
+ if (nh < MIN) {
7936
+ nh = MIN;
7937
+ nw = Math.max(MIN, Math.round(nh / ratio));
7938
+ }
7939
+ applySize(nw, nh);
6612
7940
  };
6613
7941
  const up = () => {
6614
7942
  document.removeEventListener("pointermove", move);
6615
7943
  document.removeEventListener("pointerup", up);
6616
7944
  if (active2)
6617
- this.commitSize(Math.round(w), Math.round(Math.max(MIN, w * ratio)));
7945
+ this.commitSize(Math.round(w), Math.round(h17));
6618
7946
  };
6619
7947
  document.addEventListener("pointermove", move);
6620
7948
  document.addEventListener("pointerup", up);
@@ -6623,9 +7951,11 @@ var ImageControls = class {
6623
7951
  const b = this.blockNode();
6624
7952
  if (!b)
6625
7953
  return;
6626
- this.host.dispatch([{ kind: "replaceNode", path: b.path, node: { ...b.node, attrs: { ...b.node.attrs, w, h: hgt } } }]);
6627
- this.exclusiveId = null;
6628
- this.publishCtx();
7954
+ const ratio = hgt / w || 1;
7955
+ const nw = Math.max(MIN, Math.round(w));
7956
+ const nh = Math.max(MIN, Math.round(nw * ratio));
7957
+ this.host.dispatch([{ kind: "replaceNode", path: b.path, node: { ...b.node, attrs: { ...b.node.attrs, w: nw, h: nh } } }]);
7958
+ this.paint();
6629
7959
  }
6630
7960
  };
6631
7961
  function imgSrc(atom) {
@@ -6639,7 +7969,7 @@ function cssEscape3(s) {
6639
7969
  }
6640
7970
 
6641
7971
  // src/view/table-controls.ts
6642
- import { h as h12, render as render10 } from "preact";
7972
+ import { h as h15, render as render13 } from "preact";
6643
7973
  var BAR = 10;
6644
7974
  var DOT_OUT = 15;
6645
7975
  var HIT = 24;
@@ -6681,7 +8011,7 @@ var TableControls = class {
6681
8011
  document.removeEventListener("keydown", this.onKeyDown);
6682
8012
  window.removeEventListener("scroll", this.onReflow, true);
6683
8013
  window.removeEventListener("resize", this.onReflow);
6684
- render10(null, this.overlay);
8014
+ render13(null, this.overlay);
6685
8015
  this.overlay.remove();
6686
8016
  }
6687
8017
  // ── 整表选中态(与图片同构:两段删第一段=选中整表,再删=删整表)。─────────────
@@ -6932,7 +8262,7 @@ var TableControls = class {
6932
8262
  grip(tableEl) {
6933
8263
  const r = tableEl.getBoundingClientRect();
6934
8264
  const selected = tableEl === this.selectedBlock;
6935
- return h12("div", {
8265
+ return h15("div", {
6936
8266
  key: "grip",
6937
8267
  class: `markloom-tc-grip${selected ? " is-selected" : ""}`,
6938
8268
  style: `left:${r.left - 22}px;top:${r.top - 22}px`,
@@ -6999,7 +8329,7 @@ var TableControls = class {
6999
8329
  const gap = this.blockDrag.gap;
7000
8330
  const y = gap === 0 ? blocks[0]?.getBoundingClientRect().top ?? 0 : blocks[gap - 1]?.getBoundingClientRect().bottom ?? 0;
7001
8331
  const box = docEl.getBoundingClientRect();
7002
- return h12("div", { key: "drop", class: "markloom-tc-drop markloom-tc-drop-row", style: `top:${y}px;left:${box.left}px;width:${box.width}px` });
8332
+ return h15("div", { key: "drop", class: "markloom-tc-drop markloom-tc-drop-row", style: `top:${y}px;left:${box.left}px;width:${box.width}px` });
7003
8333
  }
7004
8334
  // 选中态写到 cell 的 data-selected(纯视图,主题给强高亮)。span 稳健:每格取其锚点足迹,
7005
8335
  // 与 sel(行/列/全选/矩形)相交则选中。矩形按归一化区间判交(足迹与 rect 有重叠即选)。
@@ -7035,12 +8365,12 @@ var TableControls = class {
7035
8365
  if (this.selectedBlock) {
7036
8366
  if (!this.root.contains(this.selectedBlock)) {
7037
8367
  this.selectedBlock = null;
7038
- render10(null, this.overlay);
8368
+ render13(null, this.overlay);
7039
8369
  return;
7040
8370
  }
7041
8371
  const r = this.selectedBlock.getBoundingClientRect();
7042
- render10(h12("div", { class: "markloom-tc" }, [
7043
- h12("div", { key: "box", class: "markloom-ic-box", style: `left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px` }),
8372
+ render13(h15("div", { class: "markloom-tc" }, [
8373
+ h15("div", { key: "box", class: "markloom-ic-box", style: `left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px` }),
7044
8374
  this.grip(this.selectedBlock),
7045
8375
  this.blockDropLine()
7046
8376
  ]), this.overlay);
@@ -7048,19 +8378,19 @@ var TableControls = class {
7048
8378
  }
7049
8379
  if (!this.active || !this.root.contains(this.active)) {
7050
8380
  this.active = null;
7051
- render10(null, this.overlay);
8381
+ render13(null, this.overlay);
7052
8382
  return;
7053
8383
  }
7054
8384
  const g = this.geom(this.active);
7055
8385
  if (!g) {
7056
- render10(null, this.overlay);
8386
+ render13(null, this.overlay);
7057
8387
  return;
7058
8388
  }
7059
8389
  const wrap = this.active.closest(".markloom-table-scroll");
7060
8390
  const clip = wrap ? wrap.getBoundingClientRect() : null;
7061
8391
  const pad2 = Math.max(BAR, DOT_OUT + 12);
7062
8392
  const clipStyle = clip ? `position:fixed;inset:0;clip-path:inset(${Math.max(0, clip.top - pad2)}px ${Math.max(0, window.innerWidth - clip.right)}px ${Math.max(0, window.innerHeight - clip.bottom)}px ${Math.max(0, clip.left - pad2)}px)` : void 0;
7063
- render10(h12("div", { class: "markloom-tc", style: clipStyle }, [
8393
+ render13(h15("div", { class: "markloom-tc", style: clipStyle }, [
7064
8394
  ...this.colHandles(g),
7065
8395
  ...this.rowHandles(g),
7066
8396
  ...this.insertDots(g),
@@ -7078,7 +8408,7 @@ var TableControls = class {
7078
8408
  const w = g.colX[c + 1] - g.colX[c];
7079
8409
  const selected = this.sel?.kind === "col" && this.sel.index === c;
7080
8410
  const edge = c === 0 ? " is-first" : c === g.cols - 1 ? " is-last" : "";
7081
- out.push(h12("div", {
8411
+ out.push(h15("div", {
7082
8412
  key: `ch${c}`,
7083
8413
  class: `markloom-tc-handle markloom-tc-col${selected ? " is-selected" : ""}${edge}`,
7084
8414
  style: `left:${left}px;top:${g.rect.top - BAR}px;width:${w}px;height:${BAR}px`,
@@ -7094,14 +8424,14 @@ var TableControls = class {
7094
8424
  const ht = g.rowY[r + 1] - g.rowY[r];
7095
8425
  const selected = this.sel?.kind === "row" && this.sel.index === r;
7096
8426
  const edge = r === 0 ? " is-first" : r === g.rows - 1 ? " is-last" : "";
7097
- out.push(h12("div", {
8427
+ out.push(h15("div", {
7098
8428
  key: `rh${r}`,
7099
8429
  class: `markloom-tc-handle markloom-tc-row${selected ? " is-selected" : ""}${edge}`,
7100
8430
  style: `top:${top}px;left:${g.rect.left - BAR}px;height:${ht}px;width:${BAR}px`,
7101
8431
  onPointerDown: (e) => this.startHandle(e, "row", r)
7102
8432
  }));
7103
8433
  }
7104
- out.push(h12("div", {
8434
+ out.push(h15("div", {
7105
8435
  key: "all",
7106
8436
  class: `markloom-tc-handle markloom-tc-all${this.sel?.kind === "all" ? " is-selected" : ""}`,
7107
8437
  style: `top:${g.rect.top - BAR}px;left:${g.rect.left - BAR}px;width:${BAR}px;height:${BAR}px`,
@@ -7129,33 +8459,33 @@ var TableControls = class {
7129
8459
  const insY = g.rect.top - DOT_OUT - HIT / 2;
7130
8460
  const insX = g.rect.left - DOT_OUT - HIT / 2;
7131
8461
  for (let c = 0; c <= g.cols; c++) {
7132
- out.push(h12("div", {
8462
+ out.push(h15("div", {
7133
8463
  key: `ci${c}`,
7134
8464
  class: "markloom-tc-ins markloom-tc-ins-col",
7135
8465
  style: `left:${g.colX[c] - HIT / 2}px;top:${insY}px;width:${HIT}px;height:${HIT}px`,
7136
8466
  title: "\u63D2\u5165\u5217",
7137
8467
  onPointerDown: (e) => this.insertAt(e, g.tableEl, "col", c)
7138
8468
  }, [
7139
- h12("div", {
8469
+ h15("div", {
7140
8470
  class: "markloom-tc-guide markloom-tc-guide-col",
7141
8471
  style: `left:${g.colX[c]}px;top:${g.rect.top}px;height:${g.rect.height}px`
7142
8472
  }),
7143
- h12("div", { class: "markloom-tc-dot markloom-tc-dot-col" })
8473
+ h15("div", { class: "markloom-tc-dot markloom-tc-dot-col" })
7144
8474
  ]));
7145
8475
  }
7146
8476
  for (let r = 0; r <= g.rows; r++) {
7147
- out.push(h12("div", {
8477
+ out.push(h15("div", {
7148
8478
  key: `ri${r}`,
7149
8479
  class: "markloom-tc-ins markloom-tc-ins-row",
7150
8480
  style: `top:${g.rowY[r] - HIT / 2}px;left:${insX}px;width:${HIT}px;height:${HIT}px`,
7151
8481
  title: "\u63D2\u5165\u884C",
7152
8482
  onPointerDown: (e) => this.insertAt(e, g.tableEl, "row", r)
7153
8483
  }, [
7154
- h12("div", {
8484
+ h15("div", {
7155
8485
  class: "markloom-tc-guide markloom-tc-guide-row",
7156
8486
  style: `top:${g.rowY[r]}px;left:${g.rect.left}px;width:${g.rect.width}px`
7157
8487
  }),
7158
- h12("div", { class: "markloom-tc-dot markloom-tc-dot-row" })
8488
+ h15("div", { class: "markloom-tc-dot markloom-tc-dot-row" })
7159
8489
  ]));
7160
8490
  }
7161
8491
  return out;
@@ -7170,7 +8500,7 @@ var TableControls = class {
7170
8500
  resizeHandles(g) {
7171
8501
  const out = [];
7172
8502
  for (let c = 0; c < g.cols; c++) {
7173
- out.push(h12("div", {
8503
+ out.push(h15("div", {
7174
8504
  key: `rz${c}`,
7175
8505
  class: "markloom-tc-resize",
7176
8506
  style: `left:${g.colX[c + 1] - 3}px;top:${g.rect.top}px;height:${g.rect.height}px`,
@@ -7184,10 +8514,10 @@ var TableControls = class {
7184
8514
  return null;
7185
8515
  if (this.drag.kind === "col") {
7186
8516
  const x = g.colX[Math.min(this.drag.to, g.cols)];
7187
- return h12("div", { key: "di", class: "markloom-tc-drop markloom-tc-drop-col", style: `left:${x}px;top:${g.rect.top - BAR}px;height:${g.rect.height + BAR}px` });
8517
+ return h15("div", { key: "di", class: "markloom-tc-drop markloom-tc-drop-col", style: `left:${x}px;top:${g.rect.top - BAR}px;height:${g.rect.height + BAR}px` });
7188
8518
  }
7189
8519
  const y = g.rowY[Math.min(this.drag.to, g.rows)];
7190
- return h12("div", { key: "di", class: "markloom-tc-drop markloom-tc-drop-row", style: `top:${y}px;left:${g.rect.left - BAR}px;width:${g.rect.width + BAR}px` });
8520
+ return h15("div", { key: "di", class: "markloom-tc-drop markloom-tc-drop-row", style: `top:${y}px;left:${g.rect.left - BAR}px;width:${g.rect.width + BAR}px` });
7191
8521
  }
7192
8522
  // 柄菜单:增删行列/清空/合并拆分/样式/冻结。锚到选中柄或矩形左上附近。
7193
8523
  menuEl(g) {
@@ -7198,7 +8528,7 @@ var TableControls = class {
7198
8528
  const x = m.kind === "col" ? g.colX[m.index] : m.kind === "rect" ? g.colX[rect ? rect.c1 : 0] : g.rect.left - BAR;
7199
8529
  const y = m.kind === "col" ? g.rect.top - BAR : m.kind === "rect" ? g.rowY[rect ? rect.r2 + 1 : 0] : g.rowY[m.index];
7200
8530
  const labels = this.menuLabels(m);
7201
- return h12("div", { key: "menu", class: "markloom-tc-menu", style: `left:${x}px;top:${y}px` }, labels.map((label, i) => h12("button", {
8531
+ return h15("div", { key: "menu", class: "markloom-tc-menu", style: `left:${x}px;top:${y}px` }, labels.map((label, i) => h15("button", {
7202
8532
  key: i,
7203
8533
  type: "button",
7204
8534
  onPointerDown: (e) => this.clickMenu(e, g, m, i)
@@ -7251,7 +8581,7 @@ var TableControls = class {
7251
8581
  }
7252
8582
  this.menu = null;
7253
8583
  }
7254
- // 矩形菜单:合并 / 拆分左上格 / 设背景·边框 / 清除。背景色·边框色用 prompt 取值(装饰,非命脉,不做取色器)。
8584
+ // 矩形菜单:合并 / 拆分左上格 / 设背景·边框 / 清除。色值走轻量浮层(与链接同形态)。
7255
8585
  runRectMenu(g, i) {
7256
8586
  if (this.sel?.kind !== "rect")
7257
8587
  return;
@@ -7261,11 +8591,13 @@ var TableControls = class {
7261
8591
  else if (i === 1)
7262
8592
  this.op(g.tableEl, (t, p) => splitCell(t, p, rr.r1, rr.c1));
7263
8593
  else if (i === 2) {
7264
- void askInput({
7265
- title: "\u5355\u5143\u683C\u80CC\u666F\u8272",
7266
- description: "\u5982 #fee\u3001red\u3001rgba(\u2026)",
7267
- placeholder: "#fff7e6",
7268
- confirmLabel: "\u5E94\u7528"
8594
+ const anchor = g.tableEl.getBoundingClientRect();
8595
+ void askPopover({
8596
+ anchor,
8597
+ placeholder: "#fff7e6 / red / rgba(\u2026)",
8598
+ confirmLabel: "\u5E94\u7528",
8599
+ ariaLabel: "\u5355\u5143\u683C\u80CC\u666F\u8272",
8600
+ width: 220
7269
8601
  }).then((bg) => {
7270
8602
  if (bg)
7271
8603
  this.op(g.tableEl, (t, p) => setCellStyle(t, p, rr.r1, rr.c1, { bg }));
@@ -7273,11 +8605,13 @@ var TableControls = class {
7273
8605
  } else if (i === 3) {
7274
8606
  this.op(g.tableEl, (t, p) => setCellStyle(t, p, rr.r1, rr.c1, { bg: null }));
7275
8607
  } else if (i === 4) {
7276
- void askInput({
7277
- title: "\u5355\u5143\u683C\u8FB9\u6846\u8272",
7278
- description: "\u5982 #333\u3001black",
7279
- placeholder: "#333333",
7280
- confirmLabel: "\u5E94\u7528"
8608
+ const anchor = g.tableEl.getBoundingClientRect();
8609
+ void askPopover({
8610
+ anchor,
8611
+ placeholder: "#333333 / black",
8612
+ confirmLabel: "\u5E94\u7528",
8613
+ ariaLabel: "\u5355\u5143\u683C\u8FB9\u6846\u8272",
8614
+ width: 220
7281
8615
  }).then((border) => {
7282
8616
  if (border)
7283
8617
  this.op(g.tableEl, (t, p) => setCellStyle(t, p, rr.r1, rr.c1, { border }));
@@ -7380,6 +8714,8 @@ var TableControls = class {
7380
8714
  // src/view/editor.ts
7381
8715
  var Editor = class {
7382
8716
  root;
8717
+ /** Preact 独占且 ≡ .markloom-doc;chrome 只挂 root,与投影不交 */
8718
+ surface;
7383
8719
  history;
7384
8720
  composing = false;
7385
8721
  composeBase = null;
@@ -7397,6 +8733,18 @@ var Editor = class {
7397
8733
  commentPanel = null;
7398
8734
  // 左侧目录(飞书式 H1–H6 索引)
7399
8735
  tocPanel = null;
8736
+ // 查找替换栏
8737
+ searchBar = null;
8738
+ // 命名版本
8739
+ versionsPanel = null;
8740
+ versionList = [];
8741
+ versionMax = 50;
8742
+ // 修订/建议
8743
+ suggestBar = null;
8744
+ suggestTracking = false;
8745
+ /** 连续 insert / delete 各自 stream id,避免每键一条且插删串 id */
8746
+ suggestInsertId = null;
8747
+ suggestDeleteId = null;
7400
8748
  // mention 点击浮层:person 名片 / date 选择器
7401
8749
  mentionPops;
7402
8750
  decorations;
@@ -7404,13 +8752,21 @@ var Editor = class {
7404
8752
  aiCtl = null;
7405
8753
  /** 协作会话;applyingRemote 期间本地 steps 不上行 */
7406
8754
  collabCtl = null;
8755
+ collabUi = null;
7407
8756
  applyingRemote = false;
7408
8757
  constructor(root, doc, opts = {}) {
7409
8758
  this.root = root;
8759
+ root.__markloom = this;
8760
+ this.surface = document.createElement("div");
8761
+ this.surface.className = "markloom-doc";
8762
+ this.surface.setAttribute("data-markloom", "true");
8763
+ root.appendChild(this.surface);
7410
8764
  const dev = typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
7411
8765
  this.history = init(ensureGaps(doc), dev ? (d) => firstViolation(invariants(basicSchema, d)) : void 0);
7412
8766
  this.opts = opts;
7413
- const exts = opts.extensions ?? markloomKit();
8767
+ let exts = opts.extensions ?? markloomKit();
8768
+ if (opts.suggest && !exts.some((e) => e.name === "suggest"))
8769
+ exts = [...exts, suggest];
7414
8770
  this.resolved = resolve(exts);
7415
8771
  this.invisible = opts.invisibleCharacters ?? exts.some((e) => e.name === "invisibleCharacters");
7416
8772
  root.contentEditable = opts.editable === false ? "false" : "true";
@@ -7418,6 +8774,7 @@ var Editor = class {
7418
8774
  root.addEventListener("compositionstart", this.onCompositionStart);
7419
8775
  root.addEventListener("compositionend", this.onCompositionEnd);
7420
8776
  root.addEventListener("keydown", this.onKeyDown);
8777
+ root.addEventListener("mousedown", this.onRootMouseDown);
7421
8778
  root.addEventListener("click", this.onClick);
7422
8779
  root.addEventListener("click", this.onTaskCheck, true);
7423
8780
  root.addEventListener("copy", this.onCopy);
@@ -7446,17 +8803,61 @@ var Editor = class {
7446
8803
  doc: () => this.history.doc,
7447
8804
  dispatch: (steps, sel) => this.dispatch(steps, sel),
7448
8805
  markSel: () => this.markSel(),
7449
- author: opts.comments?.author ?? (() => ({ id: "me", name: "\u6211" })),
8806
+ author: opts.comments?.author ?? (() => ({ id: "me", name: "\u6211" })),
8807
+ newId: newId3,
8808
+ redraw: () => this.draw(readSelection(this.root, this.history.doc) ?? void 0),
8809
+ onChange: opts.comments?.onChange,
8810
+ readonly: () => this.readonly
8811
+ }, opts.comments?.threads ?? []);
8812
+ }
8813
+ if (opts.toc) {
8814
+ this.tocPanel = new TocPanel({ root, doc: () => this.history.doc });
8815
+ if (typeof opts.toc === "object" && opts.toc.open === false)
8816
+ this.tocPanel.setOpen(false);
8817
+ }
8818
+ if (opts.search) {
8819
+ this.searchBar = new SearchBar({
8820
+ root,
8821
+ doc: () => this.history.doc,
8822
+ dispatch: (steps, sel) => this.dispatch(steps, sel),
8823
+ readonly: () => this.readonly,
8824
+ focusMatch: (m) => this.focusSearchMatch(m)
8825
+ });
8826
+ }
8827
+ if (opts.versions) {
8828
+ const vc = typeof opts.versions === "object" ? opts.versions : {};
8829
+ this.versionList = vc.seed ? [...vc.seed] : [];
8830
+ this.versionMax = vc.max ?? 50;
8831
+ this.versionsPanel = new VersionsPanel({
8832
+ root,
8833
+ doc: () => this.history.doc,
8834
+ list: () => this.versionList,
8835
+ save: (name) => this.saveVersion(name),
8836
+ restore: (id) => this.restoreVersion(id),
8837
+ remove: (id) => this.removeVersion(id),
8838
+ readonly: () => this.readonly
8839
+ });
8840
+ }
8841
+ if (opts.suggest) {
8842
+ const sc = typeof opts.suggest === "object" ? opts.suggest : {};
8843
+ this.suggestTracking = sc.tracking ?? false;
8844
+ this.suggestBar = new SuggestBar({
8845
+ root,
8846
+ doc: () => this.history.doc,
8847
+ dispatch: (steps, sel) => this.dispatch(steps, sel),
8848
+ markSel: () => this.markSel(),
8849
+ author: sc.author ?? (() => ({ id: "me", name: "\u6211" })),
7450
8850
  newId: newId3,
7451
- redraw: () => this.draw(readSelection(this.root, this.history.doc) ?? void 0),
7452
- onChange: opts.comments?.onChange,
7453
- readonly: () => this.readonly
7454
- }, opts.comments?.threads ?? []);
7455
- }
7456
- if (opts.toc) {
7457
- this.tocPanel = new TocPanel({ root, doc: () => this.history.doc });
7458
- if (typeof opts.toc === "object" && opts.toc.open === false)
7459
- this.tocPanel.setOpen(false);
8851
+ readonly: () => this.readonly,
8852
+ tracking: () => this.suggestTracking,
8853
+ setTracking: (on) => {
8854
+ this.suggestTracking = on;
8855
+ if (typeof this.opts.suggest === "object")
8856
+ this.opts.suggest.onChange?.(on);
8857
+ }
8858
+ });
8859
+ if (this.suggestTracking)
8860
+ this.suggestBar.show();
7460
8861
  }
7461
8862
  if (opts.ai) {
7462
8863
  const cfg = typeof opts.ai === "object" ? opts.ai : {};
@@ -7469,19 +8870,6 @@ var Editor = class {
7469
8870
  onBusy: cfg.onBusy
7470
8871
  });
7471
8872
  }
7472
- if (opts.collab) {
7473
- this.collabCtl = connectCollab(
7474
- { ...opts.collab, seed: opts.collab.seed ?? doc },
7475
- {
7476
- onDoc: (d) => this.replaceDoc(d),
7477
- onRemote: (steps) => this.applyRemote(steps),
7478
- onError: (msg) => {
7479
- if (typeof console !== "undefined")
7480
- console.warn("[markloom collab]", msg);
7481
- }
7482
- }
7483
- );
7484
- }
7485
8873
  const host = {
7486
8874
  root,
7487
8875
  doc: () => this.history.doc,
@@ -7494,7 +8882,7 @@ var Editor = class {
7494
8882
  insertBelow: (idx) => this.insertBelow(idx),
7495
8883
  langs: () => this.opts.nodeViews?.code?.langs?.() ?? [],
7496
8884
  mentionSource: () => this.opts.mentionSource,
7497
- // 气泡/Cmd+K:host 注入同步取 URL;未注入时气泡与下方 onKeyDown 走 askInput。
8885
+ // 气泡/Cmd+K:host 注入同步取 URL;未注入时气泡与下方 onKeyDown 走 askLinkPopover。
7498
8886
  promptLink: this.opts.promptLink ? () => this.opts.promptLink() : void 0,
7499
8887
  beginComment: this.commentPanel ? () => this.commentPanel.beginCompose() : void 0,
7500
8888
  // AI 已进内置 ITEMS(openAiSlash);此处只合并产品层额外 slash,避免「AI 续写」重复
@@ -7526,6 +8914,48 @@ var Editor = class {
7526
8914
  }
7527
8915
  });
7528
8916
  this.decorations = this.resolved.decorationFactories.map((f) => f(host));
8917
+ if (opts.collab) {
8918
+ this.collabUi = new CollabPresence({
8919
+ root,
8920
+ doc: () => this.history.doc,
8921
+ collab: () => this.collabCtl,
8922
+ railParent: opts.collab.railParent
8923
+ });
8924
+ this.collabCtl = connectCollab(
8925
+ { ...opts.collab, seed: opts.collab.seed ?? doc },
8926
+ {
8927
+ onDoc: (d) => {
8928
+ if (this.isSparseCollabDoc(d) && !this.isSparseCollabDoc(this.history.doc))
8929
+ return;
8930
+ this.replaceDoc(d);
8931
+ },
8932
+ onRemote: (steps, siteId) => this.applyRemote(steps, siteId),
8933
+ onWelcome: (info) => this.collabUi?.setSelf(info.siteId, info.name, info.color),
8934
+ onPeers: (peers) => this.collabUi?.setPeers(peers),
8935
+ onStatus: (s) => {
8936
+ this.collabUi?.setStatus(s);
8937
+ opts.collab?.onStatus?.(s);
8938
+ },
8939
+ onResync: (version) => {
8940
+ this.collabUi?.setStatus("resyncing");
8941
+ opts.collab?.onResync?.(version);
8942
+ },
8943
+ onVersions: (list) => {
8944
+ if (!this.versionsPanel)
8945
+ return;
8946
+ this.versionList = list.slice();
8947
+ if (typeof this.opts.versions === "object")
8948
+ this.opts.versions.onChange?.(this.versionList);
8949
+ this.versionsPanel.show();
8950
+ },
8951
+ onError: (msg) => {
8952
+ if (typeof console !== "undefined")
8953
+ console.warn("[markloom collab]", msg);
8954
+ opts.collab?.onError?.(msg);
8955
+ }
8956
+ }
8957
+ );
8958
+ }
7529
8959
  this.draw();
7530
8960
  }
7531
8961
  destroy() {
@@ -7533,6 +8963,7 @@ var Editor = class {
7533
8963
  this.root.removeEventListener("compositionstart", this.onCompositionStart);
7534
8964
  this.root.removeEventListener("compositionend", this.onCompositionEnd);
7535
8965
  this.root.removeEventListener("keydown", this.onKeyDown);
8966
+ this.root.removeEventListener("mousedown", this.onRootMouseDown);
7536
8967
  this.root.removeEventListener("click", this.onClick);
7537
8968
  this.root.removeEventListener("click", this.onTaskCheck, true);
7538
8969
  this.root.removeEventListener("copy", this.onCopy);
@@ -7546,13 +8977,22 @@ var Editor = class {
7546
8977
  this.mentionPops.destroy();
7547
8978
  this.commentPanel?.destroy();
7548
8979
  this.tocPanel?.destroy();
8980
+ this.searchBar?.destroy();
8981
+ this.versionsPanel?.destroy();
8982
+ this.suggestBar?.destroy();
7549
8983
  this.aiCtl?.destroy();
8984
+ this.collabUi?.destroy();
8985
+ this.collabUi = null;
7550
8986
  this.collabCtl?.close();
7551
8987
  this.collabCtl = null;
7552
8988
  this.aiCtl = null;
7553
8989
  for (const d of this.decorations)
7554
8990
  d.destroy();
7555
- render11(null, this.root);
8991
+ render14(null, this.surface);
8992
+ this.surface.remove();
8993
+ const host = this.root;
8994
+ if (host.__markloom === this)
8995
+ host.__markloom = void 0;
7556
8996
  }
7557
8997
  /** AI 控制器(opts.ai 启用时);应用工具栏可 ed.ai?.openAtFocus / stop */
7558
8998
  get ai() {
@@ -7562,6 +9002,100 @@ var Editor = class {
7562
9002
  get collab() {
7563
9003
  return this.collabCtl;
7564
9004
  }
9005
+ /** 查找替换栏(opts.search 时) */
9006
+ openSearch() {
9007
+ this.searchBar?.open();
9008
+ }
9009
+ closeSearch() {
9010
+ this.searchBar?.close();
9011
+ }
9012
+ /** 纯读:当前文档内命中(不依赖 UI) */
9013
+ find(query, opts) {
9014
+ return findText(this.history.doc, query, opts);
9015
+ }
9016
+ /** 全部替换并 commit;返回命中数 */
9017
+ replaceAllText(query, replacement, opts) {
9018
+ const { steps, count } = replaceAll(this.history.doc, query, replacement, opts);
9019
+ if (count)
9020
+ this.dispatch(steps);
9021
+ return count;
9022
+ }
9023
+ /** 命名版本 API(opts.versions) */
9024
+ get versions() {
9025
+ if (!this.versionsPanel)
9026
+ return null;
9027
+ return {
9028
+ list: () => this.versionList.slice(),
9029
+ save: (name) => this.saveVersion(name),
9030
+ restore: (id) => this.restoreVersion(id),
9031
+ remove: (id) => this.removeVersion(id),
9032
+ open: () => this.versionsPanel?.show(),
9033
+ close: () => this.versionsPanel?.hide()
9034
+ };
9035
+ }
9036
+ /** 修订/建议 API(opts.suggest) */
9037
+ get suggest() {
9038
+ if (!this.suggestBar)
9039
+ return null;
9040
+ return {
9041
+ tracking: () => this.suggestTracking,
9042
+ setTracking: (on) => {
9043
+ this.suggestTracking = on;
9044
+ this.suggestInsertId = null;
9045
+ this.suggestDeleteId = null;
9046
+ if (typeof this.opts.suggest === "object")
9047
+ this.opts.suggest.onChange?.(on);
9048
+ if (on)
9049
+ this.suggestBar?.show();
9050
+ },
9051
+ open: () => this.suggestBar?.show(),
9052
+ close: () => this.suggestBar?.hide(),
9053
+ markInsert: () => this.suggestBar?.markSelection("insert") ?? false,
9054
+ markDelete: () => this.suggestBar?.markSelection("delete") ?? false,
9055
+ accept: (id) => this.suggestBar?.accept(id),
9056
+ reject: (id) => this.suggestBar?.reject(id)
9057
+ };
9058
+ }
9059
+ saveVersion(name) {
9060
+ const v = snapshotDoc(this.history.doc, name ?? "");
9061
+ this.versionList = pushVersion(this.versionList, v, this.versionMax);
9062
+ if (typeof this.opts.versions === "object")
9063
+ this.opts.versions.onChange?.(this.versionList);
9064
+ this.collabCtl?.pushVersion(v);
9065
+ this.versionsPanel?.show();
9066
+ return v;
9067
+ }
9068
+ restoreVersion(id) {
9069
+ const v = getVersion(this.versionList, id);
9070
+ if (!v)
9071
+ return false;
9072
+ this.replaceDoc(v.doc);
9073
+ return true;
9074
+ }
9075
+ removeVersion(id) {
9076
+ const next = removeVersion(this.versionList, id);
9077
+ if (next.length === this.versionList.length)
9078
+ return false;
9079
+ this.versionList = next;
9080
+ if (typeof this.opts.versions === "object")
9081
+ this.opts.versions.onChange?.(this.versionList);
9082
+ this.collabCtl?.removeVersion(id);
9083
+ return true;
9084
+ }
9085
+ focusSearchMatch(m) {
9086
+ const sel = {
9087
+ anchor: { path: m.path.concat(m.offset), assoc: 1 },
9088
+ head: { path: m.path.concat(m.offset + m.length), assoc: 1 }
9089
+ };
9090
+ writeSelection(this.root, this.history.doc, sel);
9091
+ try {
9092
+ const r = document.getSelection()?.getRangeAt(0);
9093
+ const n = r?.startContainer;
9094
+ const el = n?.nodeType === 3 ? n.parentElement : n;
9095
+ el?.scrollIntoView({ block: "nearest" });
9096
+ } catch {
9097
+ }
9098
+ }
7565
9099
  openAi(mode) {
7566
9100
  this.aiCtl?.openAtFocus(mode);
7567
9101
  }
@@ -7572,9 +9106,11 @@ var Editor = class {
7572
9106
  return this.history.doc;
7573
9107
  }
7574
9108
  // 运行时切只读/可编辑(tiptap setEditable 对位)。只读:关 contentEditable,输入/快捷键早返,装饰层各自门控 isContentEditable。
9109
+ // 必须重绘:table cell 是嵌套 contentEditable 岛,只改根节点透传不过去。
7575
9110
  setEditable(editable) {
7576
9111
  this.opts.editable = editable;
7577
9112
  this.root.contentEditable = editable ? "true" : "false";
9113
+ this.draw(readSelection(this.root, this.history.doc) ?? void 0);
7578
9114
  }
7579
9115
  // 运行时切显隐符(tiptap show/hide/toggleInvisibleCharacters 对位)。纯重绘,model 不动。
7580
9116
  setInvisibleCharacters(visible) {
@@ -7595,10 +9131,11 @@ var Editor = class {
7595
9131
  return this.opts.editable === false;
7596
9132
  }
7597
9133
  // model → DOM。composing 期间绝不重绘,否则打断 IME。
7598
- draw(restore) {
9134
+ // scroll:仅 undo/redo 把光标滚进视口;常态输入不 scroll(防每键 jump)。
9135
+ draw(restore, opts) {
7599
9136
  if (this.composing)
7600
9137
  return;
7601
- render11(renderDoc(this.history.doc, {
9138
+ const view = projectDoc(this.history.doc, {
7602
9139
  slug: this.opts.slug,
7603
9140
  nodeViews: this.opts.nodeViews,
7604
9141
  placeholder: this.opts.placeholder,
@@ -7608,13 +9145,17 @@ var Editor = class {
7608
9145
  renderMath: this.opts.renderMath,
7609
9146
  invisibleCharacters: this.invisible,
7610
9147
  commentState: this.commentPanel?.renderState(),
7611
- atomSelect: this.imageControls.selectCtx()
7612
- }), this.root);
7613
- stripStrayNodes(this.root.querySelector(".markloom-doc"));
9148
+ atomSelect: this.imageControls.selectCtx(),
9149
+ editable: this.opts.editable !== false
9150
+ });
9151
+ this.surface.className = view.className;
9152
+ render14(h16(Fragment, null, ...view.children), this.surface);
9153
+ stripStrayNodes(this.surface);
7614
9154
  if (restore)
7615
- writeSelection(this.root, this.history.doc, restore);
9155
+ writeSelection(this.root, this.history.doc, restore, opts);
7616
9156
  this.root.dispatchEvent(new Event("markloom-redraw", { bubbles: true }));
7617
9157
  this.syncPlaceholder();
9158
+ this.collabUi?.onRedraw();
7618
9159
  }
7619
9160
  // 空块提示(不进 model):空 paragraph → opts.placeholder(slash 引导);
7620
9161
  // 空 heading → 类型名 H1…H6(飞书/Notion 式)。空文档常显;光标落空块时也显。
@@ -7648,8 +9189,8 @@ var Editor = class {
7648
9189
  const sel = readSelection(this.root, this.history.doc);
7649
9190
  if (sel) {
7650
9191
  const a = sel.anchor.path;
7651
- const h13 = sel.head.path;
7652
- const collapsed = a.length === h13.length && a.every((v, i) => v === h13[i]);
9192
+ const h17 = sel.head.path;
9193
+ const collapsed = a.length === h17.length && a.every((v, i) => v === h17[i]);
7653
9194
  if (collapsed) {
7654
9195
  const i = a[0];
7655
9196
  const b = kids[i];
@@ -7669,39 +9210,60 @@ var Editor = class {
7669
9210
  if (el)
7670
9211
  el.setAttribute("data-placeholder", text);
7671
9212
  };
9213
+ // 唯一本地写入口。事务选区律 → resolveTxAfter(见 map.ts):
9214
+ // before 必读;after = 显式 | before↦batch。undo/redo 只 restore Commit 对,无旁路。
7672
9215
  dispatch(steps, selectionAfter) {
7673
9216
  if (steps.length === 0)
7674
9217
  return;
7675
- const after = applyAll(this.history.doc, steps);
7676
- const batch = steps.concat(gapSteps(after));
7677
- this.history = commit(this.history, batch);
7678
- this.draw(selectionAfter);
9218
+ const before = readSelection(this.root, this.history.doc) ?? void 0;
9219
+ const nextDoc = applyAll(this.history.doc, steps);
9220
+ const gaps = gapSteps(nextDoc);
9221
+ const batch = steps.concat(gaps);
9222
+ const selAfter = resolveTxAfter(before, selectionAfter, steps, gaps);
9223
+ this.history = commit(this.history, batch, before, selAfter);
9224
+ this.draw(selAfter);
9225
+ this.searchBar?.rescan();
9226
+ this.suggestBar?.rescan();
7679
9227
  this.opts.onChange?.(this.history.doc);
7680
- if (!this.applyingRemote)
9228
+ if (!this.applyingRemote) {
7681
9229
  this.collabCtl?.push(batch);
9230
+ this.collabUi?.flushPresence();
9231
+ }
7682
9232
  }
7683
- // AI 流式 / 事务内续写:并入 past 最后一条,一次 undo 回退整笔事务。
9233
+ // AI 流式:并入 past 末条,一次 undo 回整笔(before 起笔 / after 末 chunk)。
7684
9234
  dispatchStream(steps, selectionAfter) {
7685
9235
  if (steps.length === 0)
7686
9236
  return;
7687
- const after = applyAll(this.history.doc, steps);
7688
- const batch = steps.concat(gapSteps(after));
7689
- this.history = amend(this.history, batch);
7690
- this.draw(selectionAfter);
9237
+ const live = readSelection(this.root, this.history.doc) ?? void 0;
9238
+ const seedBefore = this.history.past.length === 0 ? live : void 0;
9239
+ const nextDoc = applyAll(this.history.doc, steps);
9240
+ const gaps = gapSteps(nextDoc);
9241
+ const batch = steps.concat(gaps);
9242
+ const selAfter = resolveTxAfter(live, selectionAfter, steps, gaps);
9243
+ this.history = amend(this.history, batch, selAfter, seedBefore);
9244
+ this.draw(selAfter);
7691
9245
  this.opts.onChange?.(this.history.doc);
7692
- if (!this.applyingRemote)
9246
+ if (!this.applyingRemote) {
7693
9247
  this.collabCtl?.push(batch);
9248
+ this.collabUi?.flushPresence();
9249
+ }
7694
9250
  }
7695
- /** 远端协作 op:写入 model 但不上行 */
7696
- applyRemote(steps, selectionAfter) {
9251
+ /**
9252
+ * 远端协作 op — 写路径唯一 foreign 入口:
9253
+ * · 改 doc,不入 past/future(人员粒度)
9254
+ * · OT 搬本端 undo/redo 栈
9255
+ * · 不再 gapSteps(发送方 batch 已含 gap;本地再补会分叉)
9256
+ * · 本端选区随 steps map(光标不被远端编辑挤飞)
9257
+ */
9258
+ applyRemote(steps, foreignSite = 1, selectionAfter) {
7697
9259
  if (steps.length === 0)
7698
9260
  return;
7699
9261
  this.applyingRemote = true;
7700
9262
  try {
7701
- const after = applyAll(this.history.doc, steps);
7702
- const batch = steps.concat(gapSteps(after));
7703
- this.history = commit(this.history, batch);
7704
- this.draw(selectionAfter);
9263
+ const me = this.collabCtl?.siteId ?? 0;
9264
+ const sel0 = selectionAfter ?? readSelection(this.root, this.history.doc) ?? void 0;
9265
+ this.history = applyForeign(this.history, steps, me, foreignSite);
9266
+ this.draw(selectionAfter ?? mapSelectionThrough(sel0, steps));
7705
9267
  this.opts.onChange?.(this.history.doc);
7706
9268
  } finally {
7707
9269
  this.applyingRemote = false;
@@ -7714,29 +9276,54 @@ var Editor = class {
7714
9276
  this.draw();
7715
9277
  this.opts.onChange?.(this.history.doc);
7716
9278
  }
7717
- /** 回退一笔 history(AI 事务 discard = undo 整笔) */
9279
+ /** 协作快照是否实质为空(仅空段) */
9280
+ isSparseCollabDoc(doc) {
9281
+ const walk = (n) => {
9282
+ if (n == null)
9283
+ return "";
9284
+ if (typeof n.text === "string")
9285
+ return n.text;
9286
+ if (Array.isArray(n.children))
9287
+ return n.children.map(walk).join("");
9288
+ return "";
9289
+ };
9290
+ return walk(doc).trim().length === 0;
9291
+ }
9292
+ /**
9293
+ * 回退一笔**本端** history(AI discard / 协作人员粒度 undo)。
9294
+ * 协作时 past 仅含本地提交;inverse 经 applyForeign 保持与远端交错后的坐标,再上行。
9295
+ * restore before + scroll(与 redo 对称,无旁路选区通道)。
9296
+ */
7718
9297
  undo() {
7719
9298
  const last = this.history.past[this.history.past.length - 1];
9299
+ if (!last)
9300
+ return false;
7720
9301
  const next = undo(this.history);
7721
9302
  if (next === this.history)
7722
9303
  return false;
7723
9304
  this.history = next;
7724
- this.draw();
9305
+ this.draw(last.before, { scroll: true });
7725
9306
  this.opts.onChange?.(this.history.doc);
7726
- if (!this.applyingRemote && last)
9307
+ if (!this.applyingRemote && last.inverse.length)
7727
9308
  this.collabCtl?.push(last.inverse);
9309
+ if (!this.applyingRemote)
9310
+ this.collabUi?.flushPresence();
7728
9311
  return true;
7729
9312
  }
7730
9313
  redo() {
7731
9314
  const fut = this.history.future[0];
9315
+ if (!fut)
9316
+ return false;
7732
9317
  const next = redo(this.history);
7733
9318
  if (next === this.history)
7734
9319
  return false;
7735
9320
  this.history = next;
7736
- this.draw();
9321
+ this.draw(fut.after, { scroll: true });
7737
9322
  this.opts.onChange?.(this.history.doc);
7738
- if (!this.applyingRemote && fut)
9323
+ if (!this.applyingRemote && fut.steps.length)
7739
9324
  this.collabCtl?.push(fut.steps);
9325
+ if (!this.applyingRemote)
9326
+ this.collabUi?.flushPresence();
7740
9327
  return true;
7741
9328
  }
7742
9329
  /** 续写:当前块后插空段并流式灌入 */
@@ -7760,6 +9347,31 @@ var Editor = class {
7760
9347
  const leaf = nodeAt(this.history.doc, leafPath);
7761
9348
  this.composeBase = { leafPath, text: isText(leaf) ? leaf.text : "" };
7762
9349
  };
9350
+ // 点 CE 内、.markloom-doc 外的空白(版心两侧/文下留白):落最近块末。版心内交给浏览器。
9351
+ onRootMouseDown = (e) => {
9352
+ if (this.readonly || e.button !== 0)
9353
+ return;
9354
+ const t = e.target;
9355
+ if (!(t instanceof Node) || this.surface.contains(t))
9356
+ return;
9357
+ if (t instanceof Element && t.closest("button, a, input, textarea, select, [data-task-check], .markloom-collab-rail"))
9358
+ return;
9359
+ e.preventDefault();
9360
+ const doc = this.history.doc;
9361
+ const kids = elementChildren(this.surface);
9362
+ let idx = kids.length - 1;
9363
+ for (let i = 0; i < kids.length; i++) {
9364
+ if (e.clientY < kids[i].getBoundingClientRect().bottom) {
9365
+ idx = i;
9366
+ break;
9367
+ }
9368
+ }
9369
+ const block = doc.children[idx];
9370
+ if (!isElement(block))
9371
+ return;
9372
+ const path = [idx, ...lastLeafEnd(block)];
9373
+ writeSelection(this.root, doc, { anchor: { path }, head: { path } });
9374
+ };
7763
9375
  // task 勾选:独立 capture 处理器(见 onTaskCheck)。此处:链接打开 + callout/math/mention。
7764
9376
  onClick = (e) => {
7765
9377
  const target = e.target;
@@ -7936,11 +9548,72 @@ var Editor = class {
7936
9548
  if (this.atomSelectGuard(intent, sel, e))
7937
9549
  return;
7938
9550
  e.preventDefault();
7939
- const pending = intent === "insertText" ? this.pendingMarks : null;
9551
+ if (this.suggestTracking && this.suggestBar && (intent === "deleteBackward" || intent === "deleteForward")) {
9552
+ const dir = intent === "deleteBackward" ? "backward" : "forward";
9553
+ const range = rangeForDelete(this.history.doc, sel, dir);
9554
+ if (range) {
9555
+ if (rangeIsSuggestInsert(this.history.doc, range)) {
9556
+ const r = mapInput(this.history.doc, intent, "", range, newId3, this.resolved.inputRules, null);
9557
+ if (r) {
9558
+ this.suggestInsertId = null;
9559
+ this.dispatch(r.steps, r.selection);
9560
+ }
9561
+ return;
9562
+ }
9563
+ const author = typeof this.opts.suggest === "object" && this.opts.suggest.author ? this.opts.suggest.author() : { id: "me", name: "\u6211" };
9564
+ this.suggestInsertId = null;
9565
+ if (!this.suggestDeleteId)
9566
+ this.suggestDeleteId = newId3();
9567
+ const steps = markSuggestRange(
9568
+ this.history.doc,
9569
+ range,
9570
+ "delete",
9571
+ this.suggestDeleteId,
9572
+ author
9573
+ );
9574
+ if (steps.length) {
9575
+ const [lo, hi] = (() => {
9576
+ const a = range.anchor.path;
9577
+ const b = range.head.path;
9578
+ let lt = true;
9579
+ const n = Math.min(a.length, b.length);
9580
+ for (let i = 0; i < n; i++) {
9581
+ if (a[i] !== b[i]) {
9582
+ lt = a[i] < b[i];
9583
+ break;
9584
+ }
9585
+ }
9586
+ return lt ? [a, b] : [b, a];
9587
+ })();
9588
+ const caretPath = dir === "backward" ? lo : hi;
9589
+ this.dispatch(steps, { anchor: { path: caretPath }, head: { path: caretPath } });
9590
+ this.suggestBar.rescan();
9591
+ this.suggestBar.show();
9592
+ return;
9593
+ }
9594
+ }
9595
+ this.suggestDeleteId = null;
9596
+ }
9597
+ let pending = intent === "insertText" ? this.pendingMarks : null;
9598
+ if (intent === "insertText" && this.suggestTracking && this.suggestBar) {
9599
+ const author = typeof this.opts.suggest === "object" && this.opts.suggest.author ? this.opts.suggest.author() : { id: "me", name: "\u6211" };
9600
+ this.suggestDeleteId = null;
9601
+ if (!this.suggestInsertId)
9602
+ this.suggestInsertId = newId3();
9603
+ const sm = suggestMark(this.suggestInsertId, "insert", author);
9604
+ const base = pending ?? marksAtCaret(this.history.doc, sel.head.path);
9605
+ pending = [...base.filter((m) => m.name !== "suggest"), sm];
9606
+ } else if (intent !== "insertText" && intent !== "deleteBackward" && intent !== "deleteForward") {
9607
+ this.suggestInsertId = null;
9608
+ this.suggestDeleteId = null;
9609
+ }
7940
9610
  const result = mapInput(this.history.doc, intent, e.data ?? "", sel, newId3, this.resolved.inputRules, pending);
7941
9611
  if (result) {
7942
- if (intent === "insertParagraph" || intent === "insertLineBreak")
9612
+ if (intent === "insertParagraph" || intent === "insertLineBreak") {
7943
9613
  this.pendingMarks = null;
9614
+ this.suggestInsertId = null;
9615
+ this.suggestDeleteId = null;
9616
+ }
7944
9617
  this.dispatch(result.steps, result.selection);
7945
9618
  }
7946
9619
  };
@@ -7952,15 +9625,23 @@ var Editor = class {
7952
9625
  return top;
7953
9626
  }
7954
9627
  // AI 输入守卫:
7955
- // · 顶层 draft 段(attrs.aiDraft)只读
7956
- // · ai 块内:Enter 生成/确认;loading 锁输入
9628
+ // · 顶层 draft(attrs.aiDraft)且对应 ai 壳仍在 → 只读(确认前淡化)
9629
+ // · 孤儿 draft(壳已丢)→ 当场解锁可编辑,避免「虚区域无法输入」
9630
+ // · ai 块内:Enter 生成/确认;loading 锁输入;空指令块首退格 → discard
7957
9631
  aiBlockGuard(intent, sel, e) {
7958
9632
  if (!this.aiCtl)
7959
9633
  return false;
7960
9634
  const top = this.history.doc.children[sel.head.path[0]];
7961
- if (top && !isText(top) && top.type === "paragraph" && top.attrs?.aiDraft) {
7962
- e.preventDefault();
7963
- return true;
9635
+ if (top && !isText(top) && top.attrs?.aiDraft) {
9636
+ const from = typeof top.attrs.aiFrom === "string" ? top.attrs.aiFrom : "";
9637
+ const live = !!from && this.history.doc.children.some(
9638
+ (c) => !isText(c) && c.type === "ai" && c.id === from
9639
+ );
9640
+ if (live) {
9641
+ e.preventDefault();
9642
+ return true;
9643
+ }
9644
+ this.promoteOrphanAiDrafts();
7964
9645
  }
7965
9646
  const ai = this.aiBlockAt(sel);
7966
9647
  if (!ai || !ai.id)
@@ -7970,6 +9651,16 @@ var Editor = class {
7970
9651
  e.preventDefault();
7971
9652
  return true;
7972
9653
  }
9654
+ if (intent === "deleteBackward") {
9655
+ const prompt = ai.children[0];
9656
+ const empty = !prompt || isText(prompt) || !isText(prompt) && prompt.type === "paragraph" && prompt.children.every((c) => isText(c) && c.text === "");
9657
+ const atPromptStart = sel.head.path.length >= 4 && sel.head.path[1] === 0 && sel.head.path[sel.head.path.length - 1] === 0;
9658
+ if (empty && atPromptStart) {
9659
+ e.preventDefault();
9660
+ this.aiCtl.discard(ai.id);
9661
+ return true;
9662
+ }
9663
+ }
7973
9664
  if (intent === "insertParagraph") {
7974
9665
  e.preventDefault();
7975
9666
  if (status === "preview")
@@ -7980,6 +9671,35 @@ var Editor = class {
7980
9671
  }
7981
9672
  return false;
7982
9673
  }
9674
+ /** 壳已不在的 aiDraft 顶层块 → 剥事务标记,恢复可编辑 */
9675
+ promoteOrphanAiDrafts() {
9676
+ const doc = this.history.doc;
9677
+ const liveAi = /* @__PURE__ */ new Set();
9678
+ for (const c of doc.children) {
9679
+ if (!isText(c) && c.type === "ai" && c.id)
9680
+ liveAi.add(c.id);
9681
+ }
9682
+ const steps = [];
9683
+ for (let i = 0; i < doc.children.length; i++) {
9684
+ const c = doc.children[i];
9685
+ if (isText(c) || !c.attrs?.aiDraft)
9686
+ continue;
9687
+ const from = typeof c.attrs.aiFrom === "string" ? c.attrs.aiFrom : "";
9688
+ if (from && liveAi.has(from))
9689
+ continue;
9690
+ const attrs = { ...c.attrs };
9691
+ delete attrs.aiDraft;
9692
+ delete attrs.aiFrom;
9693
+ delete attrs.aiStream;
9694
+ const clean = Object.keys(attrs).length ? attrs : void 0;
9695
+ const next = { type: c.type, id: c.id, children: c.children };
9696
+ if (clean)
9697
+ next.attrs = clean;
9698
+ steps.push({ kind: "replaceNode", path: [i], node: next });
9699
+ }
9700
+ if (steps.length)
9701
+ this.dispatch(steps);
9702
+ }
7983
9703
  // 塌缩 caret 落在**非空** code 块的边界时,给出它在首/尾。否则返 null(不在 code / 非塌缩 / 空块 → 放行给 mapInput)。
7984
9704
  // 「code 内首尾删会与相邻块并块、破坏『单文本叶』不变量」是 codeBlockGuard 与 codeBoundaryDelete 共守的同一判定,
7985
9705
  // 抽成单一真相:collapsed/off/len/边界只算一处,两处消费,口径不漂。空块(len===0)无内容可护,放行删空块。
@@ -8377,6 +10097,11 @@ var Editor = class {
8377
10097
  }
8378
10098
  if (!mod2 && (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown" || e.key === "Home" || e.key === "End" || e.key === "PageUp" || e.key === "PageDown"))
8379
10099
  this.pendingMarks = null;
10100
+ if (mod2 && chord(e) === "Mod-f" && this.searchBar) {
10101
+ e.preventDefault();
10102
+ this.searchBar.open();
10103
+ return;
10104
+ }
8380
10105
  if (mod2 && chord(e) === "Mod-k" && !this.opts.promptLink) {
8381
10106
  const markSel = this.markSel();
8382
10107
  if (!markSel)
@@ -8406,9 +10131,10 @@ var Editor = class {
8406
10131
  e.preventDefault();
8407
10132
  if ("history" in r) {
8408
10133
  this.pendingMarks = null;
8409
- this.history = r.history === "undo" ? undo(this.history) : redo(this.history);
8410
- this.draw();
8411
- this.opts.onChange?.(this.history.doc);
10134
+ if (r.history === "undo")
10135
+ this.undo();
10136
+ else
10137
+ this.redo();
8412
10138
  return;
8413
10139
  }
8414
10140
  if ("pendingToggle" in r) {
@@ -8425,18 +10151,23 @@ var Editor = class {
8425
10151
  }
8426
10152
  if (mod2 && !e.shiftKey && (e.key === "a" || e.key === "A")) {
8427
10153
  const sel = readSelection(this.root, this.history.doc);
8428
- if (!sel)
8429
- return;
8430
- const blockPath = sel.head.path.slice(0, -2);
8431
- if (!this.isCodeBlock(blockPath))
10154
+ let next = docExtent(this.history.doc);
10155
+ if (sel) {
10156
+ const blockPath = sel.head.path.slice(0, -2);
10157
+ if (this.isCodeBlock(blockPath)) {
10158
+ const len = leafText2(this.history.doc, [...blockPath, 0]).length;
10159
+ const leaf = {
10160
+ anchor: { path: [...blockPath, 0, 0] },
10161
+ head: { path: [...blockPath, 0, len] }
10162
+ };
10163
+ if (!selectionCovers(sel, leaf))
10164
+ next = leaf;
10165
+ }
10166
+ }
10167
+ if (!next)
8432
10168
  return;
8433
10169
  e.preventDefault();
8434
- const len = leafText2(this.history.doc, [...blockPath, 0]).length;
8435
- writeSelection(
8436
- this.root,
8437
- this.history.doc,
8438
- { anchor: { path: [...blockPath, 0, 0] }, head: { path: [...blockPath, 0, len] } }
8439
- );
10170
+ writeSelection(this.root, this.history.doc, next);
8440
10171
  }
8441
10172
  };
8442
10173
  // 取 mark 操作的选区:任一端在代码块内则返 null(抑制 Cmd+B/I/E/Shift+X/K)。
@@ -8450,8 +10181,43 @@ var Editor = class {
8450
10181
  return null;
8451
10182
  return sel;
8452
10183
  }
10184
+ // 图/表 exclusive 选中态:DOM 选区塌缩在 atom 后 → serializeSelection 会当空选。
10185
+ // 复制/剪切要读控制器上的 block path,整块出 md。
10186
+ exclusiveAtomMd() {
10187
+ const ctrl = this.imageControls.hasSelected() ? this.imageControls : this.tableControls.hasSelected() ? this.tableControls : null;
10188
+ if (!ctrl)
10189
+ return null;
10190
+ const path = ctrl.selectedBlockPath();
10191
+ if (!path || path.length !== 1)
10192
+ return null;
10193
+ const md = serializeBlock(this.history.doc, path);
10194
+ return md ? { md, path } : null;
10195
+ }
10196
+ /**
10197
+ * exclusive 图复制到系统剪贴板:text/plain=md(本编辑器粘贴)、text/html=<img>(富文本应用)、
10198
+ * image/png=像素(预览/Finder/微信等)。表只写 md。
10199
+ */
10200
+ writeExclusiveClipboard(e, atom) {
10201
+ e.preventDefault();
10202
+ const node = this.history.doc.children[atom.path[0]];
10203
+ e.clipboardData?.setData("text/plain", atom.md);
10204
+ if (!node || isText(node) || node.type !== "image")
10205
+ return;
10206
+ const url = String(node.attrs?.url ?? "");
10207
+ const alt = String(node.attrs?.alt ?? "");
10208
+ const html = `<img src="${escapeAttr(url)}" alt="${escapeAttr(alt)}">`;
10209
+ e.clipboardData?.setData("text/html", html);
10210
+ const host = node.id ? this.root.querySelector(`[data-block-id="${cssEsc(node.id)}"][data-atom="image"]`) : null;
10211
+ const imgEl = host?.matches("img") ? host : host?.querySelector("img") ?? null;
10212
+ writeImageToSystemClipboard(atom.md, html, imgEl, url);
10213
+ }
8453
10214
  // 复制/剪切/粘贴:选区 ⟷ markdown。md 是 markloom 的唯一真值,剪贴板也走 md,跨编辑器/外部可读。
8454
10215
  onCopy = (e) => {
10216
+ const atom = this.exclusiveAtomMd();
10217
+ if (atom) {
10218
+ this.writeExclusiveClipboard(e, atom);
10219
+ return;
10220
+ }
8455
10221
  const sel = readSelection(this.root, this.history.doc);
8456
10222
  if (!sel)
8457
10223
  return;
@@ -8467,6 +10233,25 @@ var Editor = class {
8467
10233
  return;
8468
10234
  }
8469
10235
  e.preventDefault();
10236
+ const atom = this.exclusiveAtomMd();
10237
+ if (atom) {
10238
+ this.writeExclusiveClipboard(e, atom);
10239
+ const ctrl = this.imageControls.hasSelected() ? this.imageControls : this.tableControls;
10240
+ const idx = atom.path[0];
10241
+ const doc = this.history.doc;
10242
+ ctrl.clearSelected();
10243
+ if (ctrl === this.tableControls) {
10244
+ const only2 = doc.children.length === 1;
10245
+ const caret4 = this.neighborCaret(idx, only2 ? [idx] : null);
10246
+ this.dispatch([deleteTableBlock([idx], doc)], caret4);
10247
+ return;
10248
+ }
10249
+ const only = doc.children.length === 1;
10250
+ const insert = only ? [{ type: "paragraph", id: newId3(), children: [{ text: "" }] }] : [];
10251
+ const caret3 = this.neighborCaret(idx, insert.length ? [idx] : null);
10252
+ this.dispatch([{ kind: "spliceChildren", path: [], at: idx, remove: 1, insert }], caret3);
10253
+ return;
10254
+ }
8470
10255
  const sel = readSelection(this.root, this.history.doc);
8471
10256
  if (!sel)
8472
10257
  return;
@@ -8484,68 +10269,61 @@ var Editor = class {
8484
10269
  const sel = readSelection(this.root, this.history.doc);
8485
10270
  if (!sel)
8486
10271
  return;
8487
- const inCode = this.isCodeBlock(sel.head.path.slice(0, -2));
8488
- if (!inCode) {
8489
- const file = imageFileFrom(e.clipboardData);
8490
- if (file) {
8491
- e.preventDefault();
8492
- this.insertImageFile(file, sel);
10272
+ const plan = resolvePaste(
10273
+ {
10274
+ inCode: this.isCodeBlock(sel.head.path.slice(0, -2)),
10275
+ selCollapsed: selCollapsed(sel),
10276
+ emptyTopPara: this.isEmptyTopPara(sel)
10277
+ },
10278
+ clipboardFromDataTransfer(e.clipboardData)
10279
+ );
10280
+ if (plan.kind === "noop")
10281
+ return;
10282
+ e.preventDefault();
10283
+ switch (plan.kind) {
10284
+ case "literal": {
10285
+ const result = mapInput(this.history.doc, "insertText", plan.text, sel, newId3);
10286
+ if (result)
10287
+ this.dispatch(result.steps, result.selection);
8493
10288
  return;
8494
10289
  }
8495
- const htmlUrl = imgSrcFromHtml(e.clipboardData?.getData("text/html"));
8496
- if (htmlUrl && !e.clipboardData?.getData("text/plain")) {
8497
- e.preventDefault();
8498
- this.insertImageUrl(htmlUrl, sel);
10290
+ case "image-file":
10291
+ this.insertImageFile(plan.file, sel);
8499
10292
  return;
8500
- }
8501
- }
8502
- const raw = e.clipboardData?.getData("text/plain") ?? "";
8503
- const html = e.clipboardData?.getData("text/html") ?? "";
8504
- if (inCode) {
8505
- if (!raw && !html)
10293
+ case "image-url":
10294
+ this.insertImageUrl(plan.url, sel);
8506
10295
  return;
8507
- e.preventDefault();
8508
- const text = raw || html;
8509
- const result2 = mapInput(this.history.doc, "insertText", text, sel, newId3);
8510
- if (result2)
8511
- this.dispatch(result2.steps, result2.selection);
8512
- return;
8513
- }
8514
- if (raw && !selCollapsed(sel) && isBareUrl(raw)) {
8515
- e.preventDefault();
8516
- const r = toggleMark(this.history.doc, sel, "link", { url: raw.trim() });
8517
- if (r)
8518
- this.dispatch(r.steps, r.selection);
8519
- return;
8520
- }
8521
- if (raw && isBareUrl(raw.trim()) && this.isEmptyTopPara(sel)) {
8522
- const url = raw.trim();
8523
- const kind = youtubeId(url) ? "youtube" : twitchChannel(url) ? "twitch" : null;
8524
- if (kind) {
8525
- e.preventDefault();
10296
+ case "link-mark": {
10297
+ const r = toggleMark(this.history.doc, sel, "link", { url: plan.url });
10298
+ if (r)
10299
+ this.dispatch(r.steps, r.selection);
10300
+ return;
10301
+ }
10302
+ case "embed": {
8526
10303
  const top = sel.head.path[0];
8527
- const node = { type: "embed", id: newId3(), attrs: { kind, src: url }, children: [] };
10304
+ const node = {
10305
+ type: "embed",
10306
+ id: newId3(),
10307
+ attrs: { kind: plan.embedKind, src: plan.url },
10308
+ children: []
10309
+ };
8528
10310
  this.dispatch([{ kind: "replaceNode", path: [top], node }]);
8529
10311
  return;
8530
10312
  }
8531
- }
8532
- if (html) {
8533
- const blocks = htmlToBlocks(html);
8534
- if (blocks && isRichHtmlBlocks(blocks)) {
8535
- e.preventDefault();
8536
- const result2 = mapPasteBlocks(this.history.doc, sel, blocks, newId3);
8537
- if (result2)
8538
- this.dispatch(result2.steps, result2.selection);
10313
+ case "blocks": {
10314
+ const result = mapPasteBlocks(this.history.doc, sel, plan.blocks, newId3);
10315
+ if (result)
10316
+ this.dispatch(result.steps, result.selection);
10317
+ return;
10318
+ }
10319
+ case "markdown": {
10320
+ const md = this.resolved.pasteRules.reduce((s, rule) => rule(s), plan.text);
10321
+ const result = mapPaste(this.history.doc, sel, md, newId3);
10322
+ if (result)
10323
+ this.dispatch(result.steps, result.selection);
8539
10324
  return;
8540
10325
  }
8541
10326
  }
8542
- if (!raw)
8543
- return;
8544
- e.preventDefault();
8545
- const md = this.resolved.pasteRules.reduce((s, rule) => rule(s), raw);
8546
- const result = mapPaste(this.history.doc, sel, md, newId3);
8547
- if (result)
8548
- this.dispatch(result.steps, result.selection);
8549
10327
  };
8550
10328
  // 图片 blob → url(onImage 上传钩子,或退回自包含 data: URL)→ 插入。异步:读完 blob 再重取选区更稳,
8551
10329
  // 但选区在异步间隙一般不动,直接用捕获的 sel(与 promptLink 同步路径语义对齐,够用)。
@@ -8560,10 +10338,20 @@ var Editor = class {
8560
10338
  });
8561
10339
  }
8562
10340
  // url → ![alt](<url>) → mapPaste。尖括号形式让 url 对 mdast 不透明(含括号/data: 冒号都安全)。
10341
+ // 插入后点选 image atom:mapPaste 的 selection 会落 atom 内假路径(无叶),且用户期望回车在图下插空段
10342
+ // (atom 选中态 Enter → 下方插段,见 onKeyDown)。
8563
10343
  insertImageUrl(url, sel) {
8564
10344
  const result = mapPaste(this.history.doc, sel, `![](<${url}>)`, newId3);
8565
- if (result)
8566
- this.dispatch(result.steps, result.selection);
10345
+ if (!result)
10346
+ return;
10347
+ this.dispatch(result.steps);
10348
+ this.selectInsertedImage(result.steps);
10349
+ }
10350
+ // 本批 step 里最后插入的 image id → exclusive 选中(与点击图同态)。
10351
+ selectInsertedImage(steps) {
10352
+ const id = lastInsertedImageId(steps);
10353
+ if (id)
10354
+ this.imageControls.selectByBlockId(id);
8567
10355
  }
8568
10356
  // 斜杠 /image:开原生文件选择,选中后把触发段(blockIdx,含 `/image`)整块替换成 image atom。
8569
10357
  // 复用 onImage 上传钩子(未注入退回 data: URL)。取消选择 → 不动 model。
@@ -8582,22 +10370,26 @@ var Editor = class {
8582
10370
  fr.readAsDataURL(file);
8583
10371
  });
8584
10372
  to.then((url) => {
8585
- const node = { type: "image", id: newId3(), attrs: { url, alt: "" }, children: [] };
10373
+ const id = newId3();
10374
+ const node = { type: "image", id, attrs: { url, alt: "" }, children: [] };
8586
10375
  this.dispatch([{ kind: "replaceNode", path: [blockIdx], node }]);
10376
+ this.imageControls.selectByBlockId(id);
8587
10377
  }).catch(() => {
8588
10378
  });
8589
10379
  };
8590
10380
  input.click();
8591
10381
  };
8592
- // 斜杠 /math → 当前段换成含 math atom 的段(display block)。
10382
+ // 斜杠 /math → 当前段换成含 math atom 的段(display block)。轻量浮层,贴块锚点。
8593
10383
  slashInsertMath = (blockIdx) => {
8594
- void askInput({
8595
- title: "\u63D2\u5165\u516C\u5F0F",
8596
- description: "\u8F93\u5165 LaTeX\uFF0C\u4F8B\u5982 E=mc^2 \u6216 \\frac{a}{b}",
8597
- placeholder: "E=mc^2",
10384
+ void askPopover({
10385
+ anchor: this.blockRect(blockIdx),
10386
+ placeholder: "E=mc^2 \u6216 \\frac{a}{b}",
8598
10387
  defaultValue: "E=mc^2",
8599
10388
  confirmLabel: "\u63D2\u5165",
10389
+ ariaLabel: "\u63D2\u5165\u516C\u5F0F",
8600
10390
  multiline: true,
10391
+ mono: true,
10392
+ width: 340,
8601
10393
  validate: (v) => !v.trim() ? "\u516C\u5F0F\u4E0D\u80FD\u4E3A\u7A7A" : null
8602
10394
  }).then((latex) => {
8603
10395
  if (latex == null)
@@ -8607,6 +10399,18 @@ var Editor = class {
8607
10399
  this.dispatch([{ kind: "replaceNode", path: [blockIdx], node }], { anchor: { path: [blockIdx, 1, 0] }, head: { path: [blockIdx, 1, 0] } });
8608
10400
  });
8609
10401
  };
10402
+ /** 顶层块在视口中的 rect;找不到则回退视口中上 */
10403
+ blockRect(blockIdx) {
10404
+ for (const el of this.root.querySelectorAll("[data-block-id]")) {
10405
+ const id = el.getAttribute("data-block-id");
10406
+ if (!id)
10407
+ continue;
10408
+ const p = pathOfId(this.history.doc, id);
10409
+ if (p && p[0] === blockIdx)
10410
+ return el.getBoundingClientRect();
10411
+ }
10412
+ return new DOMRect(window.innerWidth / 2 - 160, 120, 0, 0);
10413
+ }
8610
10414
  // 斜杠 /youtube|/twitch|/audio|/file → embed 块。file/audio 走文件选择;yt/twitch 弹 URL。
8611
10415
  slashInsertEmbed = (blockIdx, kind) => {
8612
10416
  if (kind === "file" || kind === "audio") {
@@ -8638,11 +10442,12 @@ var Editor = class {
8638
10442
  return;
8639
10443
  }
8640
10444
  const isYt = kind === "youtube";
8641
- void askInput({
8642
- title: isYt ? "\u5D4C\u5165 YouTube" : "\u5D4C\u5165 Twitch",
8643
- description: isYt ? "\u7C98\u8D34\u89C6\u9891\u94FE\u63A5\u6216\u5206\u4EAB\u5730\u5740" : "\u7C98\u8D34\u9891\u9053\u4E3B\u9875\u6216\u76F4\u64AD\u95F4\u94FE\u63A5",
10445
+ void askPopover({
10446
+ anchor: this.blockRect(blockIdx),
8644
10447
  placeholder: isYt ? "https://www.youtube.com/watch?v=\u2026" : "https://www.twitch.tv/\u2026",
8645
10448
  confirmLabel: "\u5D4C\u5165",
10449
+ ariaLabel: isYt ? "\u5D4C\u5165 YouTube" : "\u5D4C\u5165 Twitch",
10450
+ width: 340,
8646
10451
  validate: (v) => {
8647
10452
  if (!v.trim())
8648
10453
  return "\u8BF7\u8F93\u5165\u94FE\u63A5";
@@ -8659,7 +10464,7 @@ var Editor = class {
8659
10464
  this.dispatch([{ kind: "replaceNode", path: [blockIdx], node }]);
8660
10465
  });
8661
10466
  };
8662
- // 点 math atom → 弹层改 latex。叶路径:块 data-block-id + data-leaf 下标。
10467
+ // 点 math atom → 锚点旁轻量浮层改 latex(与链接同一形态,无遮罩)。
8663
10468
  editMathAtom(mathEl) {
8664
10469
  const blockEl = mathEl.closest("[data-block-id]");
8665
10470
  const id = blockEl?.getAttribute("data-block-id");
@@ -8679,12 +10484,16 @@ var Editor = class {
8679
10484
  if (isText(atom) || atom.type !== "math")
8680
10485
  return;
8681
10486
  const cur = String(atom.attrs?.latex ?? "");
8682
- void askInput({
8683
- title: "\u7F16\u8F91\u516C\u5F0F",
8684
- description: "\u4FEE\u6539 LaTeX \u6E90\u7801",
10487
+ const anchor = mathEl.getBoundingClientRect();
10488
+ void askPopover({
10489
+ anchor,
10490
+ placeholder: "LaTeX",
8685
10491
  defaultValue: cur,
8686
10492
  confirmLabel: "\u4FDD\u5B58",
10493
+ ariaLabel: "\u7F16\u8F91\u516C\u5F0F",
8687
10494
  multiline: true,
10495
+ mono: true,
10496
+ width: 340,
8688
10497
  validate: (v) => !v.trim() ? "\u516C\u5F0F\u4E0D\u80FD\u4E3A\u7A7A" : null
8689
10498
  }).then((next) => {
8690
10499
  if (next == null || next.trim() === cur)
@@ -8936,36 +10745,24 @@ function gapSteps(after) {
8936
10745
  }
8937
10746
  function selCollapsed(sel) {
8938
10747
  const a = sel.anchor.path;
8939
- const h13 = sel.head.path;
8940
- return a.length === h13.length && a.every((v, i) => v === h13[i]);
8941
- }
8942
- function isBareUrl(s) {
8943
- const t = s.trim();
8944
- if (!t.startsWith("http://") && !t.startsWith("https://"))
8945
- return false;
8946
- for (let i = 0; i < t.length; i++) {
8947
- const c = t.charCodeAt(i);
8948
- if (c === 32 || c === 9 || c === 10 || c === 13)
8949
- return false;
10748
+ const h17 = sel.head.path;
10749
+ return a.length === h17.length && a.every((v, i) => v === h17[i]);
10750
+ }
10751
+ function lastInsertedImageId(steps) {
10752
+ let id = null;
10753
+ for (const s of steps) {
10754
+ if (s.kind === "replaceNode") {
10755
+ const n = s.node;
10756
+ if (!isText(n) && n.type === "image" && n.id)
10757
+ id = n.id;
10758
+ } else if (s.kind === "spliceChildren") {
10759
+ for (const n of s.insert) {
10760
+ if (!isText(n) && n.type === "image" && n.id)
10761
+ id = n.id;
10762
+ }
10763
+ }
8950
10764
  }
8951
- return true;
8952
- }
8953
- function imageFileFrom(dt) {
8954
- if (!dt)
8955
- return null;
8956
- for (const f of Array.from(dt.files))
8957
- if (f.type.startsWith("image/"))
8958
- return f;
8959
- return null;
8960
- }
8961
- function imgSrcFromHtml(html) {
8962
- if (!html || typeof DOMParser === "undefined")
8963
- return null;
8964
- const body = new DOMParser().parseFromString(html, "text/html").body;
8965
- const imgs = body.querySelectorAll("img");
8966
- if (imgs.length !== 1 || body.textContent?.trim())
8967
- return null;
8968
- return imgs[0].getAttribute("src");
10765
+ return id;
8969
10766
  }
8970
10767
  function deleteDir(inputType) {
8971
10768
  if (!inputType.startsWith("delete"))
@@ -9004,6 +10801,103 @@ function diffSpan(a, b) {
9004
10801
  suf++;
9005
10802
  return { at: pre, remove: a.length - pre - suf, insert: b.slice(pre, b.length - suf) };
9006
10803
  }
10804
+ function escapeAttr(s) {
10805
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
10806
+ }
10807
+ function cssEsc(s) {
10808
+ if (typeof CSS !== "undefined" && typeof CSS.escape === "function")
10809
+ return CSS.escape(s);
10810
+ return s.replace(/["\\]/g, "\\$&");
10811
+ }
10812
+ function writeImageToSystemClipboard(md, html, imgEl, url) {
10813
+ if (typeof ClipboardItem === "undefined" || !navigator.clipboard?.write)
10814
+ return;
10815
+ const png = rasterizeToPng(imgEl, url);
10816
+ const plain = new Blob([md], { type: "text/plain" });
10817
+ const rich = new Blob([html], { type: "text/html" });
10818
+ try {
10819
+ void navigator.clipboard.write([new ClipboardItem({
10820
+ "image/png": png,
10821
+ "text/html": rich,
10822
+ "text/plain": plain
10823
+ })]).catch(() => {
10824
+ void png.then((blob) => navigator.clipboard.write([new ClipboardItem({ "image/png": blob })])).catch(() => {
10825
+ });
10826
+ });
10827
+ } catch {
10828
+ void png.then((blob) => navigator.clipboard.write([new ClipboardItem({ "image/png": blob })])).catch(() => {
10829
+ });
10830
+ }
10831
+ }
10832
+ function rasterizeToPng(imgEl, url) {
10833
+ if (imgEl && imgEl.complete && imgEl.naturalWidth > 0) {
10834
+ return new Promise((resolve2, reject) => {
10835
+ const canvas = document.createElement("canvas");
10836
+ canvas.width = imgEl.naturalWidth;
10837
+ canvas.height = imgEl.naturalHeight;
10838
+ const ctx = canvas.getContext("2d");
10839
+ if (!ctx) {
10840
+ reject(new Error("no 2d"));
10841
+ return;
10842
+ }
10843
+ try {
10844
+ ctx.drawImage(imgEl, 0, 0);
10845
+ canvas.toBlob((b) => {
10846
+ if (b)
10847
+ resolve2(b);
10848
+ else
10849
+ fetchAsBlob(url).then(resolve2, reject);
10850
+ }, "image/png");
10851
+ } catch {
10852
+ fetchAsBlob(url).then(resolve2, reject);
10853
+ }
10854
+ });
10855
+ }
10856
+ return fetchAsBlob(url);
10857
+ }
10858
+ function fetchAsBlob(url) {
10859
+ if (!url)
10860
+ return Promise.reject(new Error("no url"));
10861
+ return fetch(url).then((r) => {
10862
+ if (!r.ok)
10863
+ throw new Error(`fetch ${r.status}`);
10864
+ return r.blob();
10865
+ }).then((blob) => {
10866
+ if (blob.type === "image/png" || blob.type === "")
10867
+ return blob;
10868
+ return blobToPng(blob);
10869
+ });
10870
+ }
10871
+ function blobToPng(blob) {
10872
+ return new Promise((resolve2, reject) => {
10873
+ const src = URL.createObjectURL(blob);
10874
+ const img = new Image();
10875
+ img.onload = () => {
10876
+ const canvas = document.createElement("canvas");
10877
+ canvas.width = img.naturalWidth;
10878
+ canvas.height = img.naturalHeight;
10879
+ const ctx = canvas.getContext("2d");
10880
+ if (!ctx) {
10881
+ URL.revokeObjectURL(src);
10882
+ reject(new Error("no 2d"));
10883
+ return;
10884
+ }
10885
+ ctx.drawImage(img, 0, 0);
10886
+ canvas.toBlob((b) => {
10887
+ URL.revokeObjectURL(src);
10888
+ if (b)
10889
+ resolve2(b);
10890
+ else
10891
+ reject(new Error("toBlob"));
10892
+ }, "image/png");
10893
+ };
10894
+ img.onerror = () => {
10895
+ URL.revokeObjectURL(src);
10896
+ reject(new Error("img load"));
10897
+ };
10898
+ img.src = src;
10899
+ });
10900
+ }
9007
10901
 
9008
10902
  export {
9009
10903
  atomIsSelected,
@@ -9019,6 +10913,7 @@ export {
9019
10913
  renderTable,
9020
10914
  renderHr,
9021
10915
  defaultBlockRenderers,
10916
+ projectDoc,
9022
10917
  renderDoc,
9023
10918
  renderToHtml,
9024
10919
  caret,
@@ -9043,10 +10938,24 @@ export {
9043
10938
  mergeTextStyleAttrs,
9044
10939
  setTextStyle,
9045
10940
  serializeSelection,
10941
+ serializeBlock,
9046
10942
  mapPaste,
9047
10943
  mapPasteBlocks,
9048
10944
  indentItem,
9049
10945
  outdentItem,
10946
+ tryLinkMark,
10947
+ isBareUrl,
10948
+ tryEmbed,
10949
+ tryHtmlBlocks,
10950
+ tryImageFile,
10951
+ tryImageUrl,
10952
+ soloImgSrcFromHtml,
10953
+ tryLiteral,
10954
+ htmlToPlainText,
10955
+ tryMarkdown,
10956
+ clipboardFromDataTransfer,
10957
+ imageFileFrom,
10958
+ resolvePaste,
9050
10959
  resolve,
9051
10960
  textAlign,
9052
10961
  tableBlock,
@@ -9057,6 +10966,7 @@ export {
9057
10966
  blockExtensions,
9058
10967
  askInput,
9059
10968
  normalizeLinkUrl,
10969
+ askPopover,
9060
10970
  askLinkPopover,
9061
10971
  closeAskInput,
9062
10972
  MentionMenu,
@@ -9082,6 +10992,10 @@ export {
9082
10992
  markloomKit,
9083
10993
  CommentPanel,
9084
10994
  TocPanel,
10995
+ SearchBar,
10996
+ VersionsPanel,
10997
+ SuggestBar,
10998
+ suggest,
9085
10999
  MentionPopovers,
9086
11000
  Editor,
9087
11001
  chord,