markloom 0.5.1 → 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 +42 -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-VXM7Q6P5.cjs → chunk-ACFYBYZJ.cjs} +2604 -966
  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-YIFOGP2D.cjs → chunk-I5VK4U7J.cjs} +103 -60
  14. package/dist/{chunk-ZMTLSFLO.js → chunk-KYZJIOOL.js} +2138 -500
  15. package/dist/chunk-QEVME6ZU.cjs +759 -0
  16. package/dist/{chunk-MFYF2A6U.js → chunk-SNFF6X45.js} +51 -1
  17. package/dist/{chunk-FCH7LZFI.js → chunk-TB2OY3D4.js} +50 -7
  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-ZRZj2nkq.d.cts → client-CLYq17SW.d.ts} +63 -7
  24. package/dist/{client-6KiH4kGK.d.ts → client-DAth8pPq.d.cts} +63 -7
  25. package/dist/collab/index.cjs +16 -4
  26. package/dist/collab/index.d.cts +19 -6
  27. package/dist/collab/index.d.ts +19 -6
  28. package/dist/collab/index.js +18 -6
  29. package/dist/{controller-BNuuUM3E.d.ts → controller-6AJ36G52.d.ts} +99 -7
  30. package/dist/{controller-DQITsFhy.d.cts → controller-BIOO_XKJ.d.cts} +99 -7
  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 +1829 -1587
  56. package/io.md +38 -0
  57. package/package.json +21 -5
  58. package/dist/chunk-4JSJAHTB.js +0 -255
  59. package/dist/chunk-ALZ3A5CS.cjs +0 -255
  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-FCH7LZFI.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,17 +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,
58
77
  collabColor,
78
+ collabFg,
59
79
  collabInitial,
60
80
  connectCollab
61
- } from "./chunk-4JSJAHTB.js";
81
+ } from "./chunk-YBAT343I.js";
82
+ import {
83
+ mapSelectionThrough,
84
+ resolveTxAfter
85
+ } from "./chunk-VSBIMMI7.js";
62
86
  import {
63
87
  isElement,
64
88
  isInlineAtom,
65
89
  isText
66
- } from "./chunk-LA5SBCGQ.js";
90
+ } from "./chunk-EJSFZHGT.js";
67
91
 
68
92
  // src/view/render.ts
69
93
  import { h as h2 } from "preact";
@@ -213,6 +237,13 @@ var ICONS = {
213
237
  "pen-line": [
214
238
  ["path", { d: "M12 20h9" }],
215
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 }]
216
247
  ]
217
248
  };
218
249
  function icon(name, size2 = 16, className = "markloom-icon") {
@@ -308,6 +339,9 @@ function renderImage(spec, key, atomSelect) {
308
339
  const align = a.align === "center" || a.align === "right" ? a.align : void 0;
309
340
  const caption = typeof a.caption === "string" ? a.caption : "";
310
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;
311
345
  const alignStyle = align === "center" ? "display:block;margin-left:auto;margin-right:auto" : align === "right" ? "display:block;margin-left:auto" : void 0;
312
346
  const imgProps = {
313
347
  "data-atom": "image",
@@ -316,14 +350,14 @@ function renderImage(spec, key, atomSelect) {
316
350
  "title": a.title,
317
351
  "data-load": "loading",
318
352
  "loading": "lazy",
319
- "width": a.w != null ? Number(a.w) : void 0,
320
- "height": a.h != null ? Number(a.h) : void 0,
353
+ "width": iw,
354
+ "height": ih,
321
355
  "onLoad": (e) => e.currentTarget.removeAttribute("data-load"),
322
356
  "onError": (e) => e.currentTarget.setAttribute("data-load", "error")
323
357
  };
324
358
  if (caption) {
325
359
  const { "data-atom": _a, ...innerImg } = imgProps;
326
- 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";
327
361
  return h2("figure", {
328
362
  "key": spec.id ?? key,
329
363
  "data-block-id": spec.id ?? "",
@@ -332,14 +366,15 @@ function renderImage(spec, key, atomSelect) {
332
366
  "contentEditable": "false",
333
367
  "class": "markloom-figure",
334
368
  "style": figAlign
335
- }, [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)]);
336
370
  }
371
+ const boxStyle = [alignStyle, sizeStyle].filter(Boolean).join(";") || void 0;
337
372
  return h2("img", {
338
373
  "key": spec.id ?? key,
339
374
  "data-block-id": spec.id ?? "",
340
375
  "contentEditable": "false",
341
- "style": alignStyle,
342
376
  "data-selected": selected ? "" : void 0,
377
+ "style": boxStyle,
343
378
  ...imgProps
344
379
  });
345
380
  }
@@ -371,6 +406,7 @@ function markProps(mark, commentState) {
371
406
  const url = String(mark.attrs.url);
372
407
  return {
373
408
  "href": url,
409
+ "target": "_blank",
374
410
  "data-mark": "link",
375
411
  "class": "markloom-link",
376
412
  "rel": "noopener noreferrer",
@@ -390,6 +426,17 @@ function markProps(mark, commentState) {
390
426
  ].filter(Boolean).join(" ");
391
427
  return { "data-mark": "comment", "data-comment-id": id, class: cls };
392
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
+ }
393
440
  return { "data-mark": mark.name };
394
441
  }
395
442
  function renderInlineAtom(spec, key, opts) {
@@ -661,7 +708,8 @@ function blockCtx(opts) {
661
708
  renderChild: (c, k) => renderNode(c, k, opts),
662
709
  slug: opts.slug,
663
710
  codeView: opts.codeView,
664
- atomSelect: opts.atomSelect
711
+ atomSelect: opts.atomSelect,
712
+ editable: opts.editable
665
713
  };
666
714
  }
667
715
  function renderNode(node, key, opts) {
@@ -744,7 +792,12 @@ function renderNode(node, key, opts) {
744
792
  }
745
793
  function renderCode(spec, key, ctx) {
746
794
  if (ctx.codeView)
747
- 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
+ });
748
801
  const children = spec.children.length ? spec.children.map((c, i) => ctx.renderChild(c, i)) : [h2("span", { "key": 0, "data-leaf": 0 }, "\u200B")];
749
802
  return h2("pre", { "key": spec.id ?? key, "data-block-id": spec.id ?? "" }, children);
750
803
  }
@@ -753,6 +806,7 @@ function renderTable(spec, key, ctx) {
753
806
  const grid = buildGrid(spec);
754
807
  const freezeRows = Number(spec.attrs?.freezeRows ?? 0);
755
808
  const freezeCols = Number(spec.attrs?.freezeCols ?? 0);
809
+ const cellEdit = ctx.editable !== false;
756
810
  const cell = (cellNode, idx, tag) => {
757
811
  const m = grid.cellOf(idx);
758
812
  const a = align?.[m.c];
@@ -762,7 +816,8 @@ function renderTable(spec, key, ctx) {
762
816
  return h2(tag, {
763
817
  "key": idx,
764
818
  "data-block-id": cellNode.id ?? "",
765
- "contentEditable": true,
819
+ // 字符串:Preact 对布尔 false 会删属性,只读态就关不干净
820
+ "contentEditable": cellEdit ? "true" : "false",
766
821
  "class": "markloom-cell",
767
822
  "scope": tag === "th" ? "col" : void 0,
768
823
  "colSpan": m.colspan > 1 ? m.colspan : void 0,
@@ -799,7 +854,7 @@ function renderTable(spec, key, ctx) {
799
854
  "contentEditable": "false",
800
855
  // 字符串 'false':Preact 对布尔 false 会删属性,正文选区就跨得进来了
801
856
  "class": "markloom-table",
802
- "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%"
803
858
  }, children);
804
859
  return h2("div", { "key": `w${spec.id ?? key}`, "data-pass": "", "class": "markloom-table-scroll" }, [table]);
805
860
  }
@@ -816,7 +871,7 @@ var defaultBlockRenderers = {
816
871
  embed: (spec, key, ctx) => renderEmbed(spec, key, ctx.atomSelect),
817
872
  raw: renderHr
818
873
  };
819
- function renderDoc(doc, opts = {}) {
874
+ function projectDoc(doc, opts = {}) {
820
875
  const pass = {
821
876
  slug: opts.slug?.(),
822
877
  codeView: opts.nodeViews?.code,
@@ -826,7 +881,8 @@ function renderDoc(doc, opts = {}) {
826
881
  renderMath: opts.renderMath,
827
882
  invisibleCharacters: opts.invisibleCharacters,
828
883
  commentState: opts.commentState,
829
- atomSelect: opts.atomSelect
884
+ atomSelect: opts.atomSelect,
885
+ editable: opts.editable !== false
830
886
  };
831
887
  const first = doc.children[0];
832
888
  const emptyLeaf = (n) => leafText(n) === "" && n.children.every((c) => isText(c));
@@ -838,7 +894,7 @@ function renderDoc(doc, opts = {}) {
838
894
  emptyDocPh = `H${Math.min(Math.max(Number(first.attrs?.depth ?? 1), 1), 6)}`;
839
895
  }
840
896
  let foldDepth = null;
841
- const kids = doc.children.map((c, i) => {
897
+ const children = doc.children.map((c, i) => {
842
898
  let foldHidden = false;
843
899
  if (!isText(c) && c.type === "heading") {
844
900
  const depth = Math.min(Math.max(Number(c.attrs?.depth ?? 2), 1), 6);
@@ -861,11 +917,15 @@ function renderDoc(doc, opts = {}) {
861
917
  }
862
918
  return vnode;
863
919
  });
864
- const cls = opts.invisibleCharacters ? "markloom-doc markloom-invisible" : "markloom-doc";
865
- 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);
866
926
  }
867
927
  function renderToHtml(doc, opts = {}) {
868
- return renderToString(renderDoc(doc, opts));
928
+ return renderToString(renderDoc(doc, { ...opts, editable: opts.editable ?? false }));
869
929
  }
870
930
 
871
931
  // src/view/input.ts
@@ -1012,6 +1072,10 @@ function deleteRange(doc, p1, p2) {
1012
1072
  insert.push(prunedTail);
1013
1073
  caret3 = headLives ? lo : insert.length ? [loTop, ...firstLeafPath(insert[0]), 0] : [loTop, 0, 0];
1014
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
+ }
1015
1079
  return {
1016
1080
  steps: [{ kind: "spliceChildren", path: [], at: loTop, remove: hiTop - loTop + 1, insert }],
1017
1081
  caret: caret3
@@ -1035,9 +1099,13 @@ function pruneBlock(node) {
1035
1099
  }
1036
1100
  function keepBefore(node, rel) {
1037
1101
  const idx = rel[0];
1102
+ if (idx == null || idx < 0 || idx >= node.children.length)
1103
+ return { ...node, children: [] };
1038
1104
  if (rel.length === 2)
1039
1105
  return { ...node, children: [...node.children.slice(0, idx), trimTail(node.children[idx], rel[1])] };
1040
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)] };
1041
1109
  return { ...node, children: [...node.children.slice(0, idx), keepBefore(child, rel.slice(1))] };
1042
1110
  }
1043
1111
  function peelAfter(kept, depth) {
@@ -1765,9 +1833,13 @@ function sliceDoc(doc, p1, p2) {
1765
1833
  }
1766
1834
  function keepAfter(node, rel) {
1767
1835
  const idx = rel[0];
1836
+ if (idx == null || idx < 0 || idx >= node.children.length)
1837
+ return { ...node, children: node.children.slice() };
1768
1838
  if (rel.length === 2)
1769
1839
  return { ...node, children: coalesceLeaves([trimHead(node.children[idx], rel[1]), ...node.children.slice(idx + 1)]) };
1770
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)]) };
1771
1843
  return { ...node, children: [keepAfter(child, rel.slice(1)), ...node.children.slice(idx + 1)] };
1772
1844
  }
1773
1845
  function serializeSelection(doc, sel) {
@@ -1775,6 +1847,16 @@ function serializeSelection(doc, sel) {
1775
1847
  return "";
1776
1848
  return docToMd(sliceDoc(doc, sel.anchor.path, sel.head.path), "");
1777
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
+ }
1778
1860
  function mapPaste(doc, sel, md, newId4) {
1779
1861
  const frag = mdToDoc(md).children.filter((c) => !isText(c));
1780
1862
  return mapPasteBlocks(doc, sel, frag, newId4);
@@ -1857,14 +1939,17 @@ function splitDeep(block, path, newId4) {
1857
1939
  function emptyInline(b) {
1858
1940
  return isInline(b) && b.children.every((c) => isText(c) && c.text === "");
1859
1941
  }
1942
+ function isTextLeafBlock(b) {
1943
+ return b.children.length > 0 && b.children.every(isText);
1944
+ }
1860
1945
  function lastInlinePath(b) {
1861
- if (isInline(b))
1946
+ if (isInline(b) || isTextLeafBlock(b))
1862
1947
  return [];
1863
1948
  const i = b.children.length - 1;
1864
1949
  return [i, ...lastInlinePath(b.children[i])];
1865
1950
  }
1866
1951
  function firstInlinePath(b) {
1867
- if (isInline(b))
1952
+ if (isInline(b) || isTextLeafBlock(b))
1868
1953
  return [];
1869
1954
  return [0, ...firstInlinePath(b.children[0])];
1870
1955
  }
@@ -1967,7 +2052,7 @@ function caretInDescendant(blocks, idx, block, inlinePath, off) {
1967
2052
  function caretAtEnd(blocks, topIdx) {
1968
2053
  const globalIdx = topIdx + blocks.length - 1;
1969
2054
  const last = blocks[blocks.length - 1];
1970
- if (isAtom(last))
2055
+ if (isOpaque(last))
1971
2056
  return caret([globalIdx, 0, 0]);
1972
2057
  const lp = lastInlinePath(last);
1973
2058
  const inline2 = descend(last, lp);
@@ -1980,6 +2065,131 @@ function descend(block, path) {
1980
2065
  return n;
1981
2066
  }
1982
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
+
1983
2193
  // src/view/extension.ts
1984
2194
  function resolve(extensions) {
1985
2195
  const out = { markTags: {}, markProps: {}, blockRenderers: {}, keymap: {}, inputRules: [], pasteRules: [], decorationFactories: [] };
@@ -3371,25 +3581,37 @@ function normalizeLinkUrl(raw) {
3371
3581
  function readAnchor(a) {
3372
3582
  return typeof a === "function" ? a() : a;
3373
3583
  }
3374
- function askLinkPopover(opts) {
3584
+ function askPopover(opts) {
3375
3585
  if (active)
3376
3586
  dismissActive(null);
3377
3587
  return new Promise((resolve2) => {
3378
3588
  const root = document.createElement("div");
3379
- root.className = "markloom-link-pop-host";
3589
+ root.className = "markloom-ask-pop-host";
3380
3590
  document.body.appendChild(root);
3381
3591
  let value = opts.defaultValue ?? "";
3592
+ let error = null;
3382
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);
3383
3597
  const finish = (v) => {
3384
3598
  if (active?.root !== root)
3385
3599
  return;
3386
3600
  dismissActive(v);
3387
3601
  };
3388
3602
  const confirm = () => {
3389
- const trimmed = value.trim();
3390
- if (!trimmed)
3603
+ const raw = multi ? value : value.trim();
3604
+ if (!opts.allowEmpty && !raw.trim())
3391
3605
  return;
3392
- 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);
3393
3615
  };
3394
3616
  const onKey = (e) => {
3395
3617
  if (e.key === "Escape") {
@@ -3409,52 +3631,68 @@ function askLinkPopover(opts) {
3409
3631
  document.addEventListener("pointerdown", onDocDown, true);
3410
3632
  });
3411
3633
  const paint = (focus = false) => {
3412
- 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
+ };
3413
3662
  render(
3414
3663
  h3("div", {
3415
- class: "markloom-link-pop",
3416
- "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 : "",
3417
3668
  role: "dialog",
3418
- "aria-label": "\u6DFB\u52A0\u94FE\u63A5",
3669
+ "aria-label": opts.ariaLabel ?? "\u8F93\u5165",
3419
3670
  onMouseDown: (e) => {
3420
- e.preventDefault();
3421
3671
  const t = e.target;
3422
- if (t instanceof HTMLInputElement)
3423
- t.focus();
3672
+ if (t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement)
3673
+ return;
3674
+ e.preventDefault();
3424
3675
  }
3425
3676
  }, [
3426
- h3("input", {
3427
- key: "i",
3428
- class: "markloom-link-pop-input",
3429
- type: "text",
3430
- value,
3431
- placeholder: opts.placeholder ?? "\u7C98\u8D34\u6216\u8F93\u5165\u94FE\u63A5",
3432
- onInput: (e) => {
3433
- value = e.target.value;
3434
- paint(false);
3435
- },
3436
- onKeyDown: (e) => {
3437
- 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) => {
3438
3687
  e.preventDefault();
3439
3688
  confirm();
3440
3689
  }
3441
- }
3442
- }),
3443
- h3("button", {
3444
- key: "ok",
3445
- type: "button",
3446
- class: "markloom-link-pop-ok" + (can ? " is-ready" : ""),
3447
- "data-act": "confirm",
3448
- disabled: !can,
3449
- onMouseDown: (e) => {
3450
- e.preventDefault();
3451
- confirm();
3452
- }
3453
- }, opts.confirmLabel ?? "\u786E\u8BA4")
3690
+ }, opts.confirmLabel ?? "\u786E\u8BA4")
3691
+ ])
3454
3692
  ]),
3455
3693
  root
3456
3694
  );
3457
- const el = root.querySelector(".markloom-link-pop");
3695
+ const el = root.querySelector(".markloom-ask-pop");
3458
3696
  if (el && !placed) {
3459
3697
  placed = true;
3460
3698
  const rect = readAnchor(opts.anchor);
@@ -3462,17 +3700,33 @@ function askLinkPopover(opts) {
3462
3700
  }
3463
3701
  if (focus) {
3464
3702
  queueMicrotask(() => {
3465
- const input = root.querySelector("input");
3703
+ const input = root.querySelector("input, textarea");
3466
3704
  input?.focus();
3467
3705
  if (opts.defaultValue)
3468
3706
  input?.select();
3469
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
+ }
3470
3716
  }
3471
3717
  };
3472
3718
  active = { resolve: resolve2, root, onKey, onDocDown };
3473
3719
  paint(true);
3474
3720
  });
3475
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
+ }
3476
3730
  function closeAskInput() {
3477
3731
  dismissActive(null);
3478
3732
  }
@@ -3691,8 +3945,18 @@ var MARK_ITEMS = [
3691
3945
  { name: "italic", label: "I", tip: `\u659C\u4F53 (${mod} + I)`, md: "*\u6587\u672C* \u7A7A\u683C", cls: "markloom-bb-italic" },
3692
3946
  { name: "underline", label: "U", tip: `\u4E0B\u5212\u7EBF (${mod} + U)`, md: "", cls: "markloom-bb-under" }
3693
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
+ }
3694
3958
  var FONT_COLORS = [
3695
- { value: null, title: "\u9ED8\u8BA4", swatch: "#1f2329" },
3959
+ { value: null, title: "\u9ED8\u8BA4", swatch: defaultFg },
3696
3960
  { value: "#8f959e", title: "\u7070", swatch: "#8f959e" },
3697
3961
  { value: "#f54a45", title: "\u7EA2", swatch: "#f54a45" },
3698
3962
  { value: "#ff8800", title: "\u6A59", swatch: "#ff8800" },
@@ -3701,7 +3965,19 @@ var FONT_COLORS = [
3701
3965
  { value: "#3370ff", title: "\u84DD", swatch: "#3370ff" },
3702
3966
  { value: "#7b67ee", title: "\u7D2B", swatch: "#7b67ee" }
3703
3967
  ];
3704
- 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 = [
3705
3981
  { value: null, title: "\u65E0", swatch: "transparent", none: true },
3706
3982
  { value: "#f2f3f5", title: "\u6D45\u7070", swatch: "#f2f3f5", edge: true },
3707
3983
  { value: "#fde2e2", title: "\u6D45\u7EA2", swatch: "#fde2e2" },
@@ -3710,15 +3986,22 @@ var BG_COLORS = [
3710
3986
  { value: "#d9f5d6", title: "\u6D45\u7EFF", swatch: "#d9f5d6" },
3711
3987
  { value: "#e1eaff", title: "\u6D45\u84DD", swatch: "#e1eaff" },
3712
3988
  { value: "#ece2fe", title: "\u6D45\u7D2B", swatch: "#ece2fe" },
3713
- { value: "#dee0e3", title: "\u7070", swatch: "#dee0e3" },
3714
- { value: "#8f959e", title: "\u6DF1\u7070", swatch: "#8f959e" },
3715
- { value: "#f54a45", title: "\u7EA2", swatch: "#f54a45" },
3716
- { value: "#ff8800", title: "\u6A59", swatch: "#ff8800" },
3717
- { value: "#ffc60a", title: "\u9EC4", swatch: "#ffc60a" },
3718
- { value: "#34c724", title: "\u7EFF", swatch: "#34c724" },
3719
- { value: "#3370ff", title: "\u84DD", swatch: "#3370ff" },
3720
- { value: "#7b67ee", title: "\u7D2B", swatch: "#7b67ee" }
3989
+ { value: "#dee0e3", title: "\u7070", swatch: "#dee0e3" }
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)" }
3721
4001
  ];
4002
+ function bgColors() {
4003
+ return [...uiDark() ? BG_SOFT_DARK : BG_SOFT_LIGHT, ...BG_SOLIDS];
4004
+ }
3722
4005
  function tipNode(title, md) {
3723
4006
  return h5("div", { class: "markloom-bubble-tip", key: "tip" }, [
3724
4007
  h5("div", { class: "markloom-bubble-tip-t", key: "t" }, title),
@@ -4011,7 +4294,7 @@ var BubbleMenu = class {
4011
4294
  const curBlock = currentBlockKind(this.host.doc(), sel);
4012
4295
  const curColor = this.activeColor(sel);
4013
4296
  const curBg = this.activeBg(sel);
4014
- const colorSwatch = curColor ?? "#1f2329";
4297
+ const colorSwatch = curColor ?? defaultFg();
4015
4298
  const hasStyle = !!(curColor || curBg || active2.has("highlight"));
4016
4299
  const sep = (k) => h5("span", { key: k, class: "markloom-bubble-sep" });
4017
4300
  const blockBtn = h5("button", {
@@ -4229,7 +4512,7 @@ var BubbleMenu = class {
4229
4512
  class: "markloom-bb-a",
4230
4513
  style: {
4231
4514
  color: colorSwatch,
4232
- background: curBg ?? (active2.has("highlight") ? "#faf1d1" : "transparent")
4515
+ background: curBg ?? (active2.has("highlight") ? uiDark() ? "rgba(255,198,10,0.28)" : "#faf1d1" : "transparent")
4233
4516
  }
4234
4517
  }, "A"),
4235
4518
  icon("chevron-down", 12, "markloom-bb-chev"),
@@ -4248,7 +4531,7 @@ var BubbleMenu = class {
4248
4531
  type: "button",
4249
4532
  class: "markloom-bb-font-a" + (on ? " is-on" : ""),
4250
4533
  title: c.title,
4251
- style: { color: c.swatch },
4534
+ style: { color: fontSwatch(c) },
4252
4535
  onMouseDown: (e) => {
4253
4536
  e.preventDefault();
4254
4537
  const cur = this.host.markSel();
@@ -4261,7 +4544,7 @@ var BubbleMenu = class {
4261
4544
  }, "A");
4262
4545
  })),
4263
4546
  h5("div", { class: "markloom-bb-color-sec", key: "ht" }, "\u80CC\u666F\u989C\u8272"),
4264
- 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) => {
4265
4548
  const on = c.value === null ? !curBg && !active2.has("highlight") : curBg === c.value;
4266
4549
  return h5("button", {
4267
4550
  key: c.title,
@@ -5335,8 +5618,8 @@ var markCmd = (name) => (ctx) => {
5335
5618
  if (r)
5336
5619
  return r;
5337
5620
  const a = ctx.markSel.anchor.path;
5338
- const h13 = ctx.markSel.head.path;
5339
- 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]))
5340
5623
  return { pendingToggle: name };
5341
5624
  return null;
5342
5625
  };
@@ -5355,10 +5638,11 @@ var linkMark = {
5355
5638
  tag: "a",
5356
5639
  props: (mark) => {
5357
5640
  if (!mark.attrs?.url)
5358
- return { "data-mark": "link", class: "markloom-link" };
5641
+ return { "data-mark": "link", class: "markloom-link", target: "_blank", rel: "noopener noreferrer" };
5359
5642
  const url = String(mark.attrs.url);
5360
5643
  return {
5361
5644
  href: url,
5645
+ target: "_blank",
5362
5646
  "data-mark": "link",
5363
5647
  class: "markloom-link",
5364
5648
  rel: "noopener noreferrer",
@@ -5617,8 +5901,8 @@ var CommentPanel = class {
5617
5901
  const want = parseFloat(c.style.top) || 0;
5618
5902
  const top = Math.max(want, floor2);
5619
5903
  c.style.top = `${top}px`;
5620
- const h13 = c.offsetHeight || 120;
5621
- floor2 = top + h13 + CARD_GAP;
5904
+ const h17 = c.offsetHeight || 120;
5905
+ floor2 = top + h17 + CARD_GAP;
5622
5906
  maxBottom = floor2;
5623
5907
  }
5624
5908
  body.style.minHeight = `${Math.max(maxBottom + RAIL_PAD, 0)}px`;
@@ -5887,70 +6171,141 @@ function cssEscape(s) {
5887
6171
  import { h as h9, render as render7 } from "preact";
5888
6172
  var TocPanel = class {
5889
6173
  host;
6174
+ shell;
5890
6175
  rail;
5891
6176
  open = true;
5892
6177
  activeId = null;
5893
6178
  entries = [];
5894
6179
  scrollRoot = window;
6180
+ parentEl;
6181
+ fill = false;
6182
+ padEl = null;
6183
+ /** 判定线:滚动容器顶 + 偏移;jump / sync 共用 */
6184
+ markOffset = 12;
5895
6185
  constructor(host) {
5896
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);
5897
6197
  this.rail = document.createElement("div");
5898
6198
  this.rail.className = "markloom-toc-host";
5899
- 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
+ }
5900
6209
  host.root.addEventListener("markloom-redraw", this.onRedraw);
5901
- this.scrollRoot = findScrollParent2(host.root) ?? window;
5902
6210
  this.scrollRoot.addEventListener("scroll", this.onScroll, { passive: true, capture: true });
5903
- window.addEventListener("resize", this.onScroll);
5904
- this.setPadOpen(true);
6211
+ window.addEventListener("resize", this.onResize);
5905
6212
  this.refresh();
5906
6213
  }
5907
6214
  destroy() {
5908
6215
  this.host.root.removeEventListener("markloom-redraw", this.onRedraw);
5909
6216
  this.scrollRoot.removeEventListener("scroll", this.onScroll, { capture: true });
5910
- window.removeEventListener("resize", this.onScroll);
5911
- this.setPadOpen(false);
6217
+ window.removeEventListener("resize", this.onResize);
6218
+ this.clearEndScrollRoom();
5912
6219
  render7(null, this.rail);
5913
- 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");
5914
6225
  }
5915
6226
  setOpen(open) {
5916
6227
  this.open = open;
5917
- this.setPadOpen(open);
5918
6228
  this.paint();
5919
6229
  }
5920
- // 有滚动父 → 给滚动父加 padding(正文区);否则退回 html(lab 全页)
5921
- setPadOpen(open) {
5922
- const pad2 = this.scrollRoot instanceof HTMLElement ? this.scrollRoot : document.documentElement;
5923
- pad2.classList.toggle("markloom-toc-open", open);
5924
- if (pad2 !== document.documentElement)
5925
- document.documentElement.classList.remove("markloom-toc-open");
5926
- }
5927
6230
  onRedraw = () => this.refresh();
5928
- refresh() {
5929
- this.entries = outline(this.host.doc()).filter((e) => e.text.trim());
6231
+ onScroll = () => {
6232
+ const prev = this.activeId;
5930
6233
  this.syncActive();
6234
+ if (this.activeId === prev)
6235
+ return;
5931
6236
  this.paint();
5932
- }
5933
- onScroll = () => {
6237
+ this.revealActiveInRail();
6238
+ };
6239
+ onResize = () => {
6240
+ this.ensureEndScrollRoom();
5934
6241
  this.syncActive();
5935
6242
  this.paint();
6243
+ this.revealActiveInRail();
5936
6244
  };
5937
- /** 视口上 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
+ }
5938
6294
  syncActive() {
5939
6295
  if (!this.entries.length) {
5940
6296
  this.activeId = null;
5941
6297
  return;
5942
6298
  }
5943
- const mark = window.innerHeight * 0.22;
6299
+ const mark = (this.scrollRoot instanceof HTMLElement ? this.scrollRoot.getBoundingClientRect().top : 0) + this.markOffset;
5944
6300
  let best = null;
5945
6301
  for (const e of this.entries) {
5946
6302
  const el = this.headingEl(e);
5947
6303
  if (!el)
5948
6304
  continue;
5949
6305
  const top = el.getBoundingClientRect().top;
5950
- const dist = top - mark;
5951
- if (dist <= 8) {
5952
- if (!best || dist > best.dist)
5953
- 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 };
5954
6309
  }
5955
6310
  }
5956
6311
  if (!best) {
@@ -5968,39 +6323,85 @@ var TocPanel = class {
5968
6323
  }
5969
6324
  const docEl = this.host.root.querySelector(".markloom-doc") ?? this.host.root;
5970
6325
  const kids = [...docEl.children].filter((c) => c instanceof HTMLElement && c.dataset.blockId !== void 0);
5971
- const idx = e.path[0];
5972
- return kids[idx] ?? null;
6326
+ return kids[e.path[0]] ?? null;
5973
6327
  }
5974
6328
  jump(e) {
5975
- this.activeId = e.id ?? pathKey(e.path);
6329
+ const id = e.id ?? pathKey(e.path);
6330
+ this.activeId = id;
5976
6331
  this.paint();
5977
6332
  const el = this.headingEl(e);
5978
- if (el && typeof el.scrollIntoView === "function")
5979
- 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
+ });
5980
6368
  }
5981
6369
  paint() {
5982
6370
  if (!this.open) {
6371
+ this.shell.classList.remove("markloom-shell-has-toc");
5983
6372
  render7(null, this.rail);
5984
6373
  return;
5985
6374
  }
6375
+ this.shell.classList.add("markloom-shell-has-toc");
5986
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
+ }
5987
6390
  let minLv = 6;
5988
- for (const e of items)
6391
+ for (const e of items) {
5989
6392
  if (e.level < minLv)
5990
6393
  minLv = e.level;
5991
- if (!items.length)
5992
- minLv = 1;
6394
+ }
5993
6395
  render7(
5994
6396
  h9("aside", {
5995
6397
  class: "markloom-toc-rail",
5996
6398
  "data-toc-rail": "",
5997
6399
  "aria-label": "\u76EE\u5F55"
5998
6400
  }, [
5999
- h9("div", { class: "markloom-toc-hd", key: "hd" }, "\u76EE\u5F55"),
6000
6401
  h9(
6001
6402
  "nav",
6002
6403
  { class: "markloom-toc-nav", key: "nav" },
6003
- items.length ? items.map((e, i) => {
6404
+ items.map((e, i) => {
6004
6405
  const key = e.id ?? pathKey(e.path);
6005
6406
  const active2 = this.activeId === key;
6006
6407
  const depth = Math.max(0, e.level - minLv);
@@ -6011,20 +6412,30 @@ var TocPanel = class {
6011
6412
  "data-level": String(e.level),
6012
6413
  "data-active": active2 ? "" : void 0,
6013
6414
  "data-toc-id": e.id ?? void 0,
6014
- style: { paddingLeft: `${12 + depth * 14}px` },
6415
+ style: { paddingLeft: `${6 + depth * 10}px` },
6015
6416
  title: e.text,
6016
6417
  onMouseDown: (ev) => {
6017
6418
  ev.preventDefault();
6018
6419
  this.jump(e);
6019
6420
  }
6020
6421
  }, e.text || "\u672A\u547D\u540D\u6807\u9898");
6021
- }) : h9("div", { class: "markloom-toc-empty", key: "empty" }, "\u6DFB\u52A0\u6807\u9898\u540E\u663E\u793A\u76EE\u5F55")
6422
+ })
6022
6423
  )
6023
6424
  ]),
6024
6425
  this.rail
6025
6426
  );
6026
6427
  }
6027
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
+ }
6028
6439
  function pathKey(path) {
6029
6440
  return `p:${path.join(".")}`;
6030
6441
  }
@@ -6044,78 +6455,531 @@ function findScrollParent2(el) {
6044
6455
  return null;
6045
6456
  }
6046
6457
 
6047
- // src/view/mention-popovers.ts
6458
+ // src/view/search-bar.ts
6048
6459
  import { h as h10, render as render8 } from "preact";
6049
- var MentionPopovers = class {
6460
+ var SearchBar = class {
6050
6461
  host;
6051
- overlay;
6052
- mode = { kind: "closed" };
6462
+ el;
6463
+ open_ = false;
6464
+ q = "";
6465
+ r = "";
6466
+ caseSensitive = false;
6467
+ hits = [];
6468
+ idx = -1;
6053
6469
  constructor(host) {
6054
6470
  this.host = host;
6055
- this.overlay = document.createElement("div");
6056
- this.overlay.className = "markloom-mention-pop-host";
6057
- document.body.appendChild(this.overlay);
6058
- document.addEventListener("pointerdown", this.onDocDown, true);
6059
- document.addEventListener("keydown", this.onKey, true);
6060
- window.addEventListener("scroll", this.close, true);
6061
- 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_;
6062
6498
  }
6063
6499
  destroy() {
6064
- document.removeEventListener("pointerdown", this.onDocDown, true);
6065
- document.removeEventListener("keydown", this.onKey, true);
6066
- window.removeEventListener("scroll", this.close, true);
6067
- window.removeEventListener("resize", this.close);
6068
- render8(null, this.overlay);
6069
- this.overlay.remove();
6500
+ render8(null, this.el);
6501
+ this.el.remove();
6070
6502
  }
6071
- close = () => {
6072
- if (this.mode.kind === "closed")
6503
+ rescan() {
6504
+ if (!this.open_)
6073
6505
  return;
6074
- this.mode = { kind: "closed" };
6075
- render8(null, this.overlay);
6076
- };
6077
- openPerson(profile, anchor) {
6078
- this.mode = { kind: "person", profile, rect: anchor };
6506
+ this.refresh();
6079
6507
  this.paint();
6080
6508
  }
6081
- openDate(iso, path, anchor) {
6082
- const d = parseDateTime(iso) ?? /* @__PURE__ */ new Date();
6083
- this.mode = {
6084
- kind: "date",
6085
- path,
6086
- rect: anchor,
6087
- draft: {
6088
- y: d.getFullYear(),
6089
- m: d.getMonth(),
6090
- d: d.getDate(),
6091
- h: d.getHours(),
6092
- min: d.getMinutes(),
6093
- s: d.getSeconds(),
6094
- viewY: d.getFullYear(),
6095
- viewM: d.getMonth()
6096
- }
6097
- };
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]);
6098
6523
  this.paint();
6099
6524
  }
6100
- onDocDown = (e) => {
6101
- if (this.mode.kind === "closed")
6525
+ doReplaceOne() {
6526
+ if (this.idx < 0 || !this.hits[this.idx] || this.host.readonly())
6102
6527
  return;
6103
- const t = e.target;
6104
- 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())
6105
6544
  return;
6106
- 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)
6107
6549
  return;
6108
- this.close();
6109
- };
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
+ }
6679
+ onKey = (e) => {
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
+ }
6110
6809
  onKey = (e) => {
6111
- if (e.key === "Escape" && this.mode.kind !== "closed") {
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") {
6112
6962
  e.preventDefault();
6113
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();
6114
6972
  }
6115
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
+ }
6116
6980
  paint() {
6117
6981
  if (this.mode.kind === "closed") {
6118
- render8(null, this.overlay);
6982
+ render11(null, this.overlay);
6119
6983
  return;
6120
6984
  }
6121
6985
  if (this.mode.kind === "person")
@@ -6131,29 +6995,29 @@ var MentionPopovers = class {
6131
6995
  paintPerson(mode) {
6132
6996
  const p = mode.profile;
6133
6997
  const initial = (p.name || "?").slice(0, 1);
6134
- render8(
6135
- h10("div", {
6998
+ render11(
6999
+ h13("div", {
6136
7000
  class: "markloom-profile-card",
6137
- style: { position: "fixed", width: "280px", zIndex: "100" },
7001
+ style: { position: "fixed", width: "272px", zIndex: "100" },
6138
7002
  "data-mention-pop": "person",
6139
7003
  onMouseDown: (e) => e.stopPropagation()
6140
7004
  }, [
6141
- h10("div", { class: "markloom-profile-head", key: "h" }, [
6142
- p.avatar ? h10("img", { class: "markloom-profile-avatar", src: p.avatar, alt: "" }) : h10("div", { class: "markloom-profile-avatar markloom-profile-avatar-fallback" }, initial),
6143
- h10("div", { class: "markloom-profile-id" }, [
6144
- h10("div", { class: "markloom-profile-name" }, p.name),
6145
- p.title && h10("div", { class: "markloom-profile-title" }, p.title),
6146
- 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)
6147
7011
  ])
6148
7012
  ]),
6149
- (p.email || p.status) && h10("div", { class: "markloom-profile-meta", key: "m" }, [
6150
- p.status && h10("div", { class: "markloom-profile-row" }, [
6151
- h10("span", { class: "markloom-profile-k" }, "\u72B6\u6001"),
6152
- 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)
6153
7017
  ]),
6154
- p.email && h10("div", { class: "markloom-profile-row" }, [
6155
- h10("span", { class: "markloom-profile-k" }, "\u90AE\u7BB1"),
6156
- 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)
6157
7021
  ])
6158
7022
  ])
6159
7023
  ]),
@@ -6181,37 +7045,44 @@ var MentionPopovers = class {
6181
7045
  this.mode = { ...mode, draft: { ...draft, ...patch } };
6182
7046
  this.paint();
6183
7047
  };
6184
- const apply = () => {
6185
- this.host.onDateChange?.(mode.path, toIso(draft));
6186
- this.close();
6187
- };
6188
- const spin = (key, max2, label) => h10("label", { class: "markloom-time-field", key }, [
6189
- h10("span", { class: "markloom-time-field-lab" }, label),
6190
- h10("input", {
6191
- type: "number",
6192
- class: "markloom-time-input",
6193
- min: 0,
6194
- max: max2,
6195
- value: draft[key],
6196
- "data-time": key,
6197
- onInput: (e) => {
6198
- let n = Math.floor(Number(e.target.value));
6199
- if (!Number.isFinite(n))
6200
- n = 0;
6201
- n = Math.max(0, Math.min(max2, n));
6202
- 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();
6203
7070
  }
6204
- })
6205
- ]);
6206
- render8(
6207
- h10("div", {
7071
+ }
7072
+ });
7073
+ render11(
7074
+ h13("div", {
6208
7075
  class: "markloom-date-picker markloom-datetime-picker",
6209
- style: { position: "fixed", width: "300px", zIndex: "100" },
7076
+ style: { position: "fixed", width: "292px", zIndex: "100" },
6210
7077
  "data-mention-pop": "date",
6211
- onMouseDown: (e) => e.stopPropagation()
7078
+ onMouseDown: (e) => {
7079
+ const t = e.target;
7080
+ if (!(t instanceof HTMLInputElement))
7081
+ e.preventDefault();
7082
+ }
6212
7083
  }, [
6213
- h10("div", { class: "markloom-date-hd", key: "hd" }, [
6214
- h10("button", {
7084
+ h13("div", { class: "markloom-date-hd", key: "hd" }, [
7085
+ h13("button", {
6215
7086
  type: "button",
6216
7087
  class: "markloom-date-nav",
6217
7088
  "data-act": "prev",
@@ -6225,8 +7096,8 @@ var MentionPopovers = class {
6225
7096
  setDraft({ viewY: ny, viewM: nm });
6226
7097
  }
6227
7098
  }, "\u2039"),
6228
- h10("span", { class: "markloom-date-label" }, monthLabel),
6229
- h10("button", {
7099
+ h13("span", { class: "markloom-date-label" }, monthLabel),
7100
+ h13("button", {
6230
7101
  type: "button",
6231
7102
  class: "markloom-date-nav",
6232
7103
  "data-act": "next",
@@ -6241,15 +7112,15 @@ var MentionPopovers = class {
6241
7112
  }
6242
7113
  }, "\u203A")
6243
7114
  ]),
6244
- h10(
7115
+ h13(
6245
7116
  "div",
6246
7117
  { class: "markloom-date-week", key: "w" },
6247
- week.map((d) => h10("span", { key: d }, d))
7118
+ week.map((d) => h13("span", { key: d }, d))
6248
7119
  ),
6249
- h10(
7120
+ h13(
6250
7121
  "div",
6251
7122
  { class: "markloom-date-grid", key: "g" },
6252
- 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", {
6253
7124
  key: `d${c.day}`,
6254
7125
  type: "button",
6255
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" : ""),
@@ -6257,20 +7128,26 @@ var MentionPopovers = class {
6257
7128
  onMouseDown: (e) => {
6258
7129
  e.preventDefault();
6259
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();
6260
7137
  }
6261
7138
  }, String(c.day)))
6262
7139
  ),
6263
- // 时:分:秒 一体
6264
- h10("div", { class: "markloom-time-row", key: "time" }, [
6265
- spin("h", 23, "\u65F6"),
6266
- h10("span", { class: "markloom-time-colon", key: "c1" }, ":"),
6267
- spin("min", 59, "\u5206"),
6268
- h10("span", { class: "markloom-time-colon", key: "c2" }, ":"),
6269
- 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)
6270
7147
  ]),
6271
- h10("div", { class: "markloom-date-preview", key: "pv" }, preview),
6272
- h10("div", { class: "markloom-date-ft", key: "ft" }, [
6273
- h10("button", {
7148
+ h13("div", { class: "markloom-date-preview", key: "pv" }, preview),
7149
+ h13("div", { class: "markloom-date-ft", key: "ft" }, [
7150
+ h13("button", {
6274
7151
  type: "button",
6275
7152
  class: "markloom-date-today-btn",
6276
7153
  "data-act": "now",
@@ -6289,13 +7166,13 @@ var MentionPopovers = class {
6289
7166
  });
6290
7167
  }
6291
7168
  }, "\u73B0\u5728"),
6292
- h10("button", {
7169
+ h13("button", {
6293
7170
  type: "button",
6294
7171
  class: "markloom-date-ok",
6295
7172
  "data-act": "ok",
6296
7173
  onMouseDown: (e) => {
6297
7174
  e.preventDefault();
6298
- apply();
7175
+ this.applyDate();
6299
7176
  }
6300
7177
  }, "\u786E\u5B9A")
6301
7178
  ])
@@ -6325,14 +7202,14 @@ function parseDateTime(s) {
6325
7202
  const y = Number(dp[0]), mo = Number(dp[1]), d = Number(dp[2]);
6326
7203
  if (!y || !mo || !d)
6327
7204
  return null;
6328
- let h13 = 0, mi = 0, se = 0;
7205
+ let h17 = 0, mi = 0, se = 0;
6329
7206
  if (timePart) {
6330
7207
  const tp = timePart.split(":");
6331
- h13 = Number(tp[0]) || 0;
7208
+ h17 = Number(tp[0]) || 0;
6332
7209
  mi = Number(tp[1]) || 0;
6333
7210
  se = Math.floor(Number(tp[2]) || 0);
6334
7211
  }
6335
- const dt = new Date(y, mo - 1, d, h13, mi, se);
7212
+ const dt = new Date(y, mo - 1, d, h17, mi, se);
6336
7213
  if (dt.getFullYear() !== y || dt.getMonth() !== mo - 1 || dt.getDate() !== d)
6337
7214
  return null;
6338
7215
  return dt;
@@ -6343,7 +7220,7 @@ function isToday(y, m, day) {
6343
7220
  }
6344
7221
 
6345
7222
  // src/view/editor.ts
6346
- import { render as render11 } from "preact";
7223
+ import { Fragment, h as h16, render as render14 } from "preact";
6347
7224
 
6348
7225
  // src/view/collab-presence.ts
6349
7226
  function wireOf(sel) {
@@ -6362,10 +7239,13 @@ var CollabPresence = class {
6362
7239
  host;
6363
7240
  rail;
6364
7241
  avatars;
7242
+ statusEl;
6365
7243
  carets;
6366
7244
  peers = [];
6367
7245
  self = null;
6368
- presenceTimer = null;
7246
+ status = "connecting";
7247
+ /** rAF 合并;输入路径走 flushPresence 同步发,无 80ms 延迟 */
7248
+ presenceRaf = 0;
6369
7249
  lastWire = "";
6370
7250
  onSel = () => this.schedulePresence();
6371
7251
  onScroll = () => this.paintCarets();
@@ -6379,13 +7259,23 @@ var CollabPresence = class {
6379
7259
  this.rail = document.createElement("div");
6380
7260
  this.rail.className = "markloom-collab-rail";
6381
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";
6382
7265
  this.avatars = document.createElement("div");
6383
7266
  this.avatars.className = "markloom-collab-avatars";
7267
+ this.rail.appendChild(this.statusEl);
6384
7268
  this.rail.appendChild(this.avatars);
6385
7269
  this.carets = document.createElement("div");
6386
7270
  this.carets.className = "markloom-collab-carets";
6387
7271
  this.carets.setAttribute("contenteditable", "false");
6388
- root.appendChild(this.rail);
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
+ }
6389
7279
  root.appendChild(this.carets);
6390
7280
  document.addEventListener("selectionchange", this.onSel);
6391
7281
  window.addEventListener("scroll", this.onScroll, true);
@@ -6396,6 +7286,19 @@ var CollabPresence = class {
6396
7286
  this.self = { siteId, name, color: collabColor(siteId, color) };
6397
7287
  this.paintAvatars();
6398
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
+ }
6399
7302
  setPeers(peers) {
6400
7303
  this.peers = peers.map((p) => ({
6401
7304
  ...p,
@@ -6408,36 +7311,51 @@ var CollabPresence = class {
6408
7311
  onRedraw() {
6409
7312
  this.paintCarets();
6410
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
+ }
6411
7325
  destroy() {
6412
7326
  this.destroyed = true;
6413
7327
  document.removeEventListener("selectionchange", this.onSel);
6414
7328
  window.removeEventListener("scroll", this.onScroll, true);
6415
7329
  window.removeEventListener("resize", this.onResize);
6416
- if (this.presenceTimer)
6417
- clearTimeout(this.presenceTimer);
7330
+ if (this.presenceRaf)
7331
+ cancelAnimationFrame(this.presenceRaf);
6418
7332
  this.rail.remove();
6419
7333
  this.carets.remove();
6420
7334
  }
7335
+ /** 纯移光标:并到下一帧,避免 selectionchange 风暴 */
6421
7336
  schedulePresence() {
6422
- if (this.presenceTimer)
6423
- clearTimeout(this.presenceTimer);
6424
- this.presenceTimer = setTimeout(() => {
6425
- this.presenceTimer = null;
6426
- this.sendPresence();
6427
- }, 80);
6428
- }
6429
- sendPresence() {
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) {
6430
7345
  const c = this.host.collab();
6431
7346
  if (!c || this.destroyed)
6432
7347
  return;
6433
7348
  const sel = readSelection(this.host.root, this.host.doc());
6434
7349
  if (!sel) {
6435
- c.presence(null);
7350
+ if (force || this.lastWire !== "null") {
7351
+ this.lastWire = "null";
7352
+ c.presence(null);
7353
+ }
6436
7354
  return;
6437
7355
  }
6438
7356
  const w = wireOf(sel);
6439
7357
  const key = JSON.stringify(w);
6440
- if (key === this.lastWire)
7358
+ if (!force && key === this.lastWire)
6441
7359
  return;
6442
7360
  this.lastWire = key;
6443
7361
  c.presence(w);
@@ -6466,17 +7384,15 @@ var CollabPresence = class {
6466
7384
  return a.siteId - b.siteId;
6467
7385
  });
6468
7386
  this.avatars.replaceChildren();
6469
- if (list.length === 0) {
6470
- this.rail.hidden = true;
6471
- return;
6472
- }
6473
7387
  this.rail.hidden = false;
6474
7388
  for (const p of list) {
6475
7389
  const el = document.createElement("div");
6476
7390
  el.className = "markloom-collab-avatar";
6477
7391
  if (this.self && p.siteId === this.self.siteId)
6478
7392
  el.classList.add("is-self");
6479
- el.style.setProperty("--collab-c", p.color || collabColor(p.siteId));
7393
+ const bg = p.color || collabColor(p.siteId);
7394
+ el.style.setProperty("--collab-c", bg);
7395
+ el.style.color = collabFg(bg);
6480
7396
  el.textContent = collabInitial(p.name, p.siteId);
6481
7397
  el.title = p.name || `\u7528\u6237 ${p.siteId}`;
6482
7398
  this.avatars.appendChild(el);
@@ -6522,18 +7438,22 @@ var CollabPresence = class {
6522
7438
  }
6523
7439
  }
6524
7440
  addCaret(p, rect, rootRect, scrollX, scrollY) {
6525
- const color = p.color || collabColor(p.siteId);
7441
+ const soft = p.color || collabColor(p.siteId);
7442
+ const hard = collabCaretColor(p.siteId, p.color);
6526
7443
  const el = document.createElement("div");
6527
7444
  el.className = "markloom-collab-caret";
6528
- el.style.setProperty("--collab-c", color);
7445
+ el.style.setProperty("--collab-c", hard);
7446
+ el.style.setProperty("--collab-lab", soft);
6529
7447
  const left = rect.left - rootRect.left + scrollX;
6530
7448
  const top = rect.top - rootRect.top + scrollY;
6531
- const h13 = Math.max(rect.height || 16, 14);
7449
+ const h17 = Math.max(rect.height || 16, 14);
6532
7450
  el.style.left = `${left}px`;
6533
7451
  el.style.top = `${top}px`;
6534
- el.style.height = `${h13}px`;
7452
+ el.style.height = `${h17}px`;
6535
7453
  const lab = document.createElement("div");
6536
7454
  lab.className = "markloom-collab-caret-lab";
7455
+ lab.style.background = soft;
7456
+ lab.style.color = collabFg(soft);
6537
7457
  lab.textContent = p.name || `\u7528\u6237${p.siteId}`;
6538
7458
  el.appendChild(lab);
6539
7459
  this.carets.appendChild(el);
@@ -6541,7 +7461,9 @@ var CollabPresence = class {
6541
7461
  };
6542
7462
 
6543
7463
  // src/view/image-controls.ts
6544
- 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";
6545
7467
  var DRAG_THRESHOLD = 4;
6546
7468
  var MIN = 24;
6547
7469
  function atomIdsInSelection(doc, sel) {
@@ -6573,8 +7495,13 @@ var ImageControls = class {
6573
7495
  /** 点选 exclusive 块 id(全套柄);与 range 互斥 */
6574
7496
  exclusiveId = null;
6575
7497
  rangeIds = /* @__PURE__ */ new Set();
6576
- lightbox = null;
7498
+ /** PhotoSwipe 实例;非 null 表示预览打开 */
7499
+ pswp = null;
7500
+ /** 测试钩:最近一次打开的预览 src */
7501
+ previewSrc = null;
6577
7502
  editingCaption = false;
7503
+ /** 图注草稿:paint 时写回 value;避免 selectionchange→paint 用空 attrs 冲掉正在输入的字 */
7504
+ captionDraft = "";
6578
7505
  ctxKey = "";
6579
7506
  constructor(root, host) {
6580
7507
  this.root = root;
@@ -6594,10 +7521,12 @@ var ImageControls = class {
6594
7521
  document.removeEventListener("selectionchange", this.onSelChange);
6595
7522
  window.removeEventListener("scroll", this.onReflow, true);
6596
7523
  window.removeEventListener("resize", this.onReflow);
7524
+ this.closePreview();
6597
7525
  this.exclusiveId = null;
6598
7526
  this.rangeIds = /* @__PURE__ */ new Set();
6599
- this.lightbox = null;
6600
- render9(null, this.overlay);
7527
+ this.editingCaption = false;
7528
+ this.captionDraft = "";
7529
+ render12(null, this.overlay);
6601
7530
  this.overlay.remove();
6602
7531
  }
6603
7532
  /** 供 renderDoc 注入的选中上下文 */
@@ -6618,7 +7547,7 @@ var ImageControls = class {
6618
7547
  this.paint();
6619
7548
  }
6620
7549
  onSelChange = () => {
6621
- if (this.lightbox)
7550
+ if (this.pswp || this.editingCaption)
6622
7551
  return;
6623
7552
  const sel = this.host.sel();
6624
7553
  const nextRange = atomIdsInSelection(this.host.doc(), sel);
@@ -6630,33 +7559,135 @@ var ImageControls = class {
6630
7559
  };
6631
7560
  onDocDown = (e) => {
6632
7561
  const el = e.target instanceof HTMLElement ? e.target : null;
6633
- if (el?.closest(".markloom-image-overlay") || el?.closest(".markloom-lightbox"))
7562
+ if (el?.closest(".markloom-image-overlay") || el?.closest(".pswp"))
6634
7563
  return;
6635
7564
  const atom = el?.closest('[data-atom="image"], [data-atom="embed"]');
6636
7565
  if (atom && this.root.contains(atom)) {
6637
7566
  const host = atom.dataset.blockId ? atom : atom.closest("[data-block-id]");
6638
7567
  const id = host?.dataset.blockId ?? atom.dataset.blockId ?? null;
6639
7568
  if (id && id === this.exclusiveId) {
6640
- if ((host ?? atom).getAttribute("data-atom") === "image" || atom.closest('[data-atom="image"]'))
6641
- this.lightbox = imgSrc(host ?? atom);
6642
- this.paint();
6643
7569
  return;
6644
7570
  }
6645
7571
  if (id)
6646
7572
  this.selectByBlockId(id);
6647
7573
  return;
6648
7574
  }
6649
- if (this.exclusiveId || this.lightbox || this.rangeIds.size)
7575
+ if (this.exclusiveId || this.pswp || this.rangeIds.size)
6650
7576
  this.clearSelected();
6651
7577
  };
6652
7578
  onKeyDown = (e) => {
6653
- 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)
6654
7584
  this.clearSelected();
6655
7585
  };
6656
7586
  onReflow = () => {
6657
- if (this.exclusiveId || this.rangeIds.size || this.lightbox)
7587
+ if (this.editingCaption)
7588
+ return;
7589
+ if (this.exclusiveId || this.rangeIds.size)
6658
7590
  this.paint();
6659
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
+ }
6660
7691
  hasSelected() {
6661
7692
  return !!this.exclusiveId && !!this.atomEl(this.exclusiveId);
6662
7693
  }
@@ -6670,7 +7701,8 @@ var ImageControls = class {
6670
7701
  this.exclusiveId = id;
6671
7702
  this.rangeIds = /* @__PURE__ */ new Set();
6672
7703
  this.editingCaption = false;
6673
- this.lightbox = null;
7704
+ this.captionDraft = "";
7705
+ this.closePreview();
6674
7706
  const sel = atom.ownerDocument.getSelection();
6675
7707
  if (sel) {
6676
7708
  const range = atom.ownerDocument.createRange();
@@ -6683,10 +7715,11 @@ var ImageControls = class {
6683
7715
  return true;
6684
7716
  }
6685
7717
  clearSelected() {
7718
+ this.closePreview();
6686
7719
  this.exclusiveId = null;
6687
7720
  this.rangeIds = /* @__PURE__ */ new Set();
6688
- this.lightbox = null;
6689
7721
  this.editingCaption = false;
7722
+ this.captionDraft = "";
6690
7723
  this.publishCtx();
6691
7724
  }
6692
7725
  atomEl(id) {
@@ -6712,23 +7745,50 @@ var ImageControls = class {
6712
7745
  if (attrs[k] === "" || attrs[k] === "left" || attrs[k] == null)
6713
7746
  delete attrs[k];
6714
7747
  this.host.dispatch([{ kind: "replaceNode", path: b.path, node: { ...b.node, attrs } }]);
6715
- 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() {
6716
7771
  this.editingCaption = false;
6717
- this.publishCtx();
7772
+ this.captionDraft = "";
7773
+ this.paint();
6718
7774
  }
6719
7775
  paint() {
7776
+ if (this.pswp) {
7777
+ render12(null, this.overlay);
7778
+ return;
7779
+ }
6720
7780
  if (this.exclusiveId && !this.atomEl(this.exclusiveId))
6721
7781
  this.exclusiveId = null;
6722
7782
  const kids = [];
6723
7783
  const ex = this.exclusiveId ? this.atomEl(this.exclusiveId) : null;
6724
7784
  if (ex) {
6725
7785
  const r = ex.getBoundingClientRect();
6726
- 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` }));
6727
7787
  if (ex.getAttribute("data-atom") === "image") {
6728
7788
  for (const corner of ["nw", "ne", "sw", "se"]) {
6729
7789
  const x = corner === "nw" || corner === "sw" ? r.left : r.right;
6730
7790
  const y = corner === "nw" || corner === "ne" ? r.top : r.bottom;
6731
- kids.push(h11("div", {
7791
+ kids.push(h14("div", {
6732
7792
  key: corner,
6733
7793
  class: `markloom-ic-handle markloom-ic-${corner}`,
6734
7794
  style: `left:${x}px;top:${y}px`,
@@ -6736,6 +7796,23 @@ var ImageControls = class {
6736
7796
  }));
6737
7797
  }
6738
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)));
6739
7816
  }
6740
7817
  }
6741
7818
  for (const id of this.rangeIds) {
@@ -6745,17 +7822,13 @@ var ImageControls = class {
6745
7822
  if (!atom)
6746
7823
  continue;
6747
7824
  const r = atom.getBoundingClientRect();
6748
- kids.push(h11("div", {
7825
+ kids.push(h14("div", {
6749
7826
  key: `r-${id}`,
6750
7827
  class: "markloom-ic-box",
6751
7828
  style: `left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px`
6752
7829
  }));
6753
7830
  }
6754
- if (this.lightbox)
6755
- kids.push(h11("div", { key: "lb", class: "markloom-lightbox", onPointerDown: () => this.clearSelected() }, [
6756
- h11("img", { key: "lbimg", src: this.lightbox })
6757
- ]));
6758
- 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);
6759
7832
  }
6760
7833
  toolbar(r) {
6761
7834
  const cur = this.blockNode()?.node.attrs?.align ?? "left";
@@ -6766,7 +7839,7 @@ var ImageControls = class {
6766
7839
  { value: "right", ico: "align-right", title: "\u53F3\u5BF9\u9F50" },
6767
7840
  { value: "caption", ico: "type", title: "\u56FE\u6CE8" }
6768
7841
  ];
6769
- const btns = aligns.map((a) => h11("button", {
7842
+ const btns = aligns.map((a) => h14("button", {
6770
7843
  "key": a.value,
6771
7844
  "type": "button",
6772
7845
  "title": a.title,
@@ -6774,47 +7847,79 @@ var ImageControls = class {
6774
7847
  "onMouseDown": (e) => {
6775
7848
  e.preventDefault();
6776
7849
  if (a.value === "caption") {
6777
- this.editingCaption = !this.editingCaption;
6778
- this.paint();
6779
- } 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
+ }
6780
7857
  }
6781
7858
  }, icon(a.ico, 14)));
6782
- 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)];
6783
7860
  if (this.editingCaption)
6784
- row.push(h11("input", {
7861
+ row.push(h14("input", {
6785
7862
  "key": "capin",
6786
7863
  "class": "markloom-ic-tb-caption",
6787
7864
  "type": "text",
6788
- "value": cap,
7865
+ // 草稿驱动;attrs.caption 只在 Enter 提交后变
7866
+ "value": this.captionDraft,
6789
7867
  "placeholder": "\u56FE\u6CE8\u2026",
6790
- "autoFocus": true,
7868
+ "onInput": (e) => {
7869
+ this.captionDraft = e.currentTarget.value;
7870
+ },
6791
7871
  "onKeyDown": (e) => {
6792
7872
  if (e.key === "Enter") {
6793
7873
  e.preventDefault();
6794
- this.patchAttrs({ caption: e.currentTarget.value });
7874
+ e.stopPropagation();
7875
+ this.commitCaption();
6795
7876
  } else if (e.key === "Escape") {
6796
7877
  e.preventDefault();
6797
- this.editingCaption = false;
6798
- this.paint();
7878
+ e.stopPropagation();
7879
+ this.cancelCaptionEdit();
6799
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
+ });
6800
7893
  }
6801
7894
  }));
6802
- 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);
6803
7896
  }
6804
7897
  startResize(down, corner) {
6805
7898
  down.preventDefault();
6806
7899
  down.stopPropagation();
6807
7900
  const el = this.exclusiveId ? this.atomEl(this.exclusiveId) : null;
6808
- const img = el?.matches("img") ? el : el?.querySelector("img");
7901
+ const img = el?.matches("img") ? el : el?.querySelector("img") ?? null;
6809
7902
  if (!img)
6810
7903
  return;
6811
7904
  const r = img.getBoundingClientRect();
6812
7905
  const startW = r.width;
6813
7906
  const startH = r.height;
6814
- 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;
6815
7910
  const signX = corner === "ne" || corner === "se" ? 1 : -1;
7911
+ const signY = corner === "se" || corner === "sw" ? 1 : -1;
6816
7912
  let active2 = false;
6817
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
+ };
6818
7923
  const move = (ev) => {
6819
7924
  const dx = ev.clientX - down.clientX;
6820
7925
  const dy = ev.clientY - down.clientY;
@@ -6822,17 +7927,22 @@ var ImageControls = class {
6822
7927
  active2 = true;
6823
7928
  if (!active2)
6824
7929
  return;
6825
- w = Math.max(MIN, startW + signX * dx);
6826
- const hgt = Math.max(MIN, Math.round(w * ratio));
6827
- img.style.width = `${Math.round(w)}px`;
6828
- img.style.height = `${hgt}px`;
6829
- 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);
6830
7940
  };
6831
7941
  const up = () => {
6832
7942
  document.removeEventListener("pointermove", move);
6833
7943
  document.removeEventListener("pointerup", up);
6834
7944
  if (active2)
6835
- this.commitSize(Math.round(w), Math.round(Math.max(MIN, w * ratio)));
7945
+ this.commitSize(Math.round(w), Math.round(h17));
6836
7946
  };
6837
7947
  document.addEventListener("pointermove", move);
6838
7948
  document.addEventListener("pointerup", up);
@@ -6841,9 +7951,11 @@ var ImageControls = class {
6841
7951
  const b = this.blockNode();
6842
7952
  if (!b)
6843
7953
  return;
6844
- this.host.dispatch([{ kind: "replaceNode", path: b.path, node: { ...b.node, attrs: { ...b.node.attrs, w, h: hgt } } }]);
6845
- this.exclusiveId = null;
6846
- 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();
6847
7959
  }
6848
7960
  };
6849
7961
  function imgSrc(atom) {
@@ -6857,7 +7969,7 @@ function cssEscape3(s) {
6857
7969
  }
6858
7970
 
6859
7971
  // src/view/table-controls.ts
6860
- import { h as h12, render as render10 } from "preact";
7972
+ import { h as h15, render as render13 } from "preact";
6861
7973
  var BAR = 10;
6862
7974
  var DOT_OUT = 15;
6863
7975
  var HIT = 24;
@@ -6899,7 +8011,7 @@ var TableControls = class {
6899
8011
  document.removeEventListener("keydown", this.onKeyDown);
6900
8012
  window.removeEventListener("scroll", this.onReflow, true);
6901
8013
  window.removeEventListener("resize", this.onReflow);
6902
- render10(null, this.overlay);
8014
+ render13(null, this.overlay);
6903
8015
  this.overlay.remove();
6904
8016
  }
6905
8017
  // ── 整表选中态(与图片同构:两段删第一段=选中整表,再删=删整表)。─────────────
@@ -7150,7 +8262,7 @@ var TableControls = class {
7150
8262
  grip(tableEl) {
7151
8263
  const r = tableEl.getBoundingClientRect();
7152
8264
  const selected = tableEl === this.selectedBlock;
7153
- return h12("div", {
8265
+ return h15("div", {
7154
8266
  key: "grip",
7155
8267
  class: `markloom-tc-grip${selected ? " is-selected" : ""}`,
7156
8268
  style: `left:${r.left - 22}px;top:${r.top - 22}px`,
@@ -7217,7 +8329,7 @@ var TableControls = class {
7217
8329
  const gap = this.blockDrag.gap;
7218
8330
  const y = gap === 0 ? blocks[0]?.getBoundingClientRect().top ?? 0 : blocks[gap - 1]?.getBoundingClientRect().bottom ?? 0;
7219
8331
  const box = docEl.getBoundingClientRect();
7220
- 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` });
7221
8333
  }
7222
8334
  // 选中态写到 cell 的 data-selected(纯视图,主题给强高亮)。span 稳健:每格取其锚点足迹,
7223
8335
  // 与 sel(行/列/全选/矩形)相交则选中。矩形按归一化区间判交(足迹与 rect 有重叠即选)。
@@ -7253,12 +8365,12 @@ var TableControls = class {
7253
8365
  if (this.selectedBlock) {
7254
8366
  if (!this.root.contains(this.selectedBlock)) {
7255
8367
  this.selectedBlock = null;
7256
- render10(null, this.overlay);
8368
+ render13(null, this.overlay);
7257
8369
  return;
7258
8370
  }
7259
8371
  const r = this.selectedBlock.getBoundingClientRect();
7260
- render10(h12("div", { class: "markloom-tc" }, [
7261
- 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` }),
7262
8374
  this.grip(this.selectedBlock),
7263
8375
  this.blockDropLine()
7264
8376
  ]), this.overlay);
@@ -7266,19 +8378,19 @@ var TableControls = class {
7266
8378
  }
7267
8379
  if (!this.active || !this.root.contains(this.active)) {
7268
8380
  this.active = null;
7269
- render10(null, this.overlay);
8381
+ render13(null, this.overlay);
7270
8382
  return;
7271
8383
  }
7272
8384
  const g = this.geom(this.active);
7273
8385
  if (!g) {
7274
- render10(null, this.overlay);
8386
+ render13(null, this.overlay);
7275
8387
  return;
7276
8388
  }
7277
8389
  const wrap = this.active.closest(".markloom-table-scroll");
7278
8390
  const clip = wrap ? wrap.getBoundingClientRect() : null;
7279
8391
  const pad2 = Math.max(BAR, DOT_OUT + 12);
7280
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;
7281
- render10(h12("div", { class: "markloom-tc", style: clipStyle }, [
8393
+ render13(h15("div", { class: "markloom-tc", style: clipStyle }, [
7282
8394
  ...this.colHandles(g),
7283
8395
  ...this.rowHandles(g),
7284
8396
  ...this.insertDots(g),
@@ -7296,7 +8408,7 @@ var TableControls = class {
7296
8408
  const w = g.colX[c + 1] - g.colX[c];
7297
8409
  const selected = this.sel?.kind === "col" && this.sel.index === c;
7298
8410
  const edge = c === 0 ? " is-first" : c === g.cols - 1 ? " is-last" : "";
7299
- out.push(h12("div", {
8411
+ out.push(h15("div", {
7300
8412
  key: `ch${c}`,
7301
8413
  class: `markloom-tc-handle markloom-tc-col${selected ? " is-selected" : ""}${edge}`,
7302
8414
  style: `left:${left}px;top:${g.rect.top - BAR}px;width:${w}px;height:${BAR}px`,
@@ -7312,14 +8424,14 @@ var TableControls = class {
7312
8424
  const ht = g.rowY[r + 1] - g.rowY[r];
7313
8425
  const selected = this.sel?.kind === "row" && this.sel.index === r;
7314
8426
  const edge = r === 0 ? " is-first" : r === g.rows - 1 ? " is-last" : "";
7315
- out.push(h12("div", {
8427
+ out.push(h15("div", {
7316
8428
  key: `rh${r}`,
7317
8429
  class: `markloom-tc-handle markloom-tc-row${selected ? " is-selected" : ""}${edge}`,
7318
8430
  style: `top:${top}px;left:${g.rect.left - BAR}px;height:${ht}px;width:${BAR}px`,
7319
8431
  onPointerDown: (e) => this.startHandle(e, "row", r)
7320
8432
  }));
7321
8433
  }
7322
- out.push(h12("div", {
8434
+ out.push(h15("div", {
7323
8435
  key: "all",
7324
8436
  class: `markloom-tc-handle markloom-tc-all${this.sel?.kind === "all" ? " is-selected" : ""}`,
7325
8437
  style: `top:${g.rect.top - BAR}px;left:${g.rect.left - BAR}px;width:${BAR}px;height:${BAR}px`,
@@ -7347,33 +8459,33 @@ var TableControls = class {
7347
8459
  const insY = g.rect.top - DOT_OUT - HIT / 2;
7348
8460
  const insX = g.rect.left - DOT_OUT - HIT / 2;
7349
8461
  for (let c = 0; c <= g.cols; c++) {
7350
- out.push(h12("div", {
8462
+ out.push(h15("div", {
7351
8463
  key: `ci${c}`,
7352
8464
  class: "markloom-tc-ins markloom-tc-ins-col",
7353
8465
  style: `left:${g.colX[c] - HIT / 2}px;top:${insY}px;width:${HIT}px;height:${HIT}px`,
7354
8466
  title: "\u63D2\u5165\u5217",
7355
8467
  onPointerDown: (e) => this.insertAt(e, g.tableEl, "col", c)
7356
8468
  }, [
7357
- h12("div", {
8469
+ h15("div", {
7358
8470
  class: "markloom-tc-guide markloom-tc-guide-col",
7359
8471
  style: `left:${g.colX[c]}px;top:${g.rect.top}px;height:${g.rect.height}px`
7360
8472
  }),
7361
- h12("div", { class: "markloom-tc-dot markloom-tc-dot-col" })
8473
+ h15("div", { class: "markloom-tc-dot markloom-tc-dot-col" })
7362
8474
  ]));
7363
8475
  }
7364
8476
  for (let r = 0; r <= g.rows; r++) {
7365
- out.push(h12("div", {
8477
+ out.push(h15("div", {
7366
8478
  key: `ri${r}`,
7367
8479
  class: "markloom-tc-ins markloom-tc-ins-row",
7368
8480
  style: `top:${g.rowY[r] - HIT / 2}px;left:${insX}px;width:${HIT}px;height:${HIT}px`,
7369
8481
  title: "\u63D2\u5165\u884C",
7370
8482
  onPointerDown: (e) => this.insertAt(e, g.tableEl, "row", r)
7371
8483
  }, [
7372
- h12("div", {
8484
+ h15("div", {
7373
8485
  class: "markloom-tc-guide markloom-tc-guide-row",
7374
8486
  style: `top:${g.rowY[r]}px;left:${g.rect.left}px;width:${g.rect.width}px`
7375
8487
  }),
7376
- h12("div", { class: "markloom-tc-dot markloom-tc-dot-row" })
8488
+ h15("div", { class: "markloom-tc-dot markloom-tc-dot-row" })
7377
8489
  ]));
7378
8490
  }
7379
8491
  return out;
@@ -7388,7 +8500,7 @@ var TableControls = class {
7388
8500
  resizeHandles(g) {
7389
8501
  const out = [];
7390
8502
  for (let c = 0; c < g.cols; c++) {
7391
- out.push(h12("div", {
8503
+ out.push(h15("div", {
7392
8504
  key: `rz${c}`,
7393
8505
  class: "markloom-tc-resize",
7394
8506
  style: `left:${g.colX[c + 1] - 3}px;top:${g.rect.top}px;height:${g.rect.height}px`,
@@ -7402,10 +8514,10 @@ var TableControls = class {
7402
8514
  return null;
7403
8515
  if (this.drag.kind === "col") {
7404
8516
  const x = g.colX[Math.min(this.drag.to, g.cols)];
7405
- 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` });
7406
8518
  }
7407
8519
  const y = g.rowY[Math.min(this.drag.to, g.rows)];
7408
- 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` });
7409
8521
  }
7410
8522
  // 柄菜单:增删行列/清空/合并拆分/样式/冻结。锚到选中柄或矩形左上附近。
7411
8523
  menuEl(g) {
@@ -7416,7 +8528,7 @@ var TableControls = class {
7416
8528
  const x = m.kind === "col" ? g.colX[m.index] : m.kind === "rect" ? g.colX[rect ? rect.c1 : 0] : g.rect.left - BAR;
7417
8529
  const y = m.kind === "col" ? g.rect.top - BAR : m.kind === "rect" ? g.rowY[rect ? rect.r2 + 1 : 0] : g.rowY[m.index];
7418
8530
  const labels = this.menuLabels(m);
7419
- 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", {
7420
8532
  key: i,
7421
8533
  type: "button",
7422
8534
  onPointerDown: (e) => this.clickMenu(e, g, m, i)
@@ -7469,7 +8581,7 @@ var TableControls = class {
7469
8581
  }
7470
8582
  this.menu = null;
7471
8583
  }
7472
- // 矩形菜单:合并 / 拆分左上格 / 设背景·边框 / 清除。背景色·边框色用 prompt 取值(装饰,非命脉,不做取色器)。
8584
+ // 矩形菜单:合并 / 拆分左上格 / 设背景·边框 / 清除。色值走轻量浮层(与链接同形态)。
7473
8585
  runRectMenu(g, i) {
7474
8586
  if (this.sel?.kind !== "rect")
7475
8587
  return;
@@ -7479,11 +8591,13 @@ var TableControls = class {
7479
8591
  else if (i === 1)
7480
8592
  this.op(g.tableEl, (t, p) => splitCell(t, p, rr.r1, rr.c1));
7481
8593
  else if (i === 2) {
7482
- void askInput({
7483
- title: "\u5355\u5143\u683C\u80CC\u666F\u8272",
7484
- description: "\u5982 #fee\u3001red\u3001rgba(\u2026)",
7485
- placeholder: "#fff7e6",
7486
- 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
7487
8601
  }).then((bg) => {
7488
8602
  if (bg)
7489
8603
  this.op(g.tableEl, (t, p) => setCellStyle(t, p, rr.r1, rr.c1, { bg }));
@@ -7491,11 +8605,13 @@ var TableControls = class {
7491
8605
  } else if (i === 3) {
7492
8606
  this.op(g.tableEl, (t, p) => setCellStyle(t, p, rr.r1, rr.c1, { bg: null }));
7493
8607
  } else if (i === 4) {
7494
- void askInput({
7495
- title: "\u5355\u5143\u683C\u8FB9\u6846\u8272",
7496
- description: "\u5982 #333\u3001black",
7497
- placeholder: "#333333",
7498
- 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
7499
8615
  }).then((border) => {
7500
8616
  if (border)
7501
8617
  this.op(g.tableEl, (t, p) => setCellStyle(t, p, rr.r1, rr.c1, { border }));
@@ -7598,6 +8714,8 @@ var TableControls = class {
7598
8714
  // src/view/editor.ts
7599
8715
  var Editor = class {
7600
8716
  root;
8717
+ /** Preact 独占且 ≡ .markloom-doc;chrome 只挂 root,与投影不交 */
8718
+ surface;
7601
8719
  history;
7602
8720
  composing = false;
7603
8721
  composeBase = null;
@@ -7615,6 +8733,18 @@ var Editor = class {
7615
8733
  commentPanel = null;
7616
8734
  // 左侧目录(飞书式 H1–H6 索引)
7617
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;
7618
8748
  // mention 点击浮层:person 名片 / date 选择器
7619
8749
  mentionPops;
7620
8750
  decorations;
@@ -7626,10 +8756,17 @@ var Editor = class {
7626
8756
  applyingRemote = false;
7627
8757
  constructor(root, doc, opts = {}) {
7628
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);
7629
8764
  const dev = typeof process !== "undefined" && process.env?.NODE_ENV !== "production";
7630
8765
  this.history = init(ensureGaps(doc), dev ? (d) => firstViolation(invariants(basicSchema, d)) : void 0);
7631
8766
  this.opts = opts;
7632
- 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];
7633
8770
  this.resolved = resolve(exts);
7634
8771
  this.invisible = opts.invisibleCharacters ?? exts.some((e) => e.name === "invisibleCharacters");
7635
8772
  root.contentEditable = opts.editable === false ? "false" : "true";
@@ -7637,6 +8774,7 @@ var Editor = class {
7637
8774
  root.addEventListener("compositionstart", this.onCompositionStart);
7638
8775
  root.addEventListener("compositionend", this.onCompositionEnd);
7639
8776
  root.addEventListener("keydown", this.onKeyDown);
8777
+ root.addEventListener("mousedown", this.onRootMouseDown);
7640
8778
  root.addEventListener("click", this.onClick);
7641
8779
  root.addEventListener("click", this.onTaskCheck, true);
7642
8780
  root.addEventListener("copy", this.onCopy);
@@ -7677,6 +8815,50 @@ var Editor = class {
7677
8815
  if (typeof opts.toc === "object" && opts.toc.open === false)
7678
8816
  this.tocPanel.setOpen(false);
7679
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" })),
8850
+ newId: newId3,
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();
8861
+ }
7680
8862
  if (opts.ai) {
7681
8863
  const cfg = typeof opts.ai === "object" ? opts.ai : {};
7682
8864
  this.aiCtl = new MarkloomAi(() => this, {
@@ -7688,26 +8870,6 @@ var Editor = class {
7688
8870
  onBusy: cfg.onBusy
7689
8871
  });
7690
8872
  }
7691
- if (opts.collab) {
7692
- this.collabUi = new CollabPresence({
7693
- root,
7694
- doc: () => this.history.doc,
7695
- collab: () => this.collabCtl
7696
- });
7697
- this.collabCtl = connectCollab(
7698
- { ...opts.collab, seed: opts.collab.seed ?? doc },
7699
- {
7700
- onDoc: (d) => this.replaceDoc(d),
7701
- onRemote: (steps) => this.applyRemote(steps),
7702
- onWelcome: (info) => this.collabUi?.setSelf(info.siteId, info.name, info.color),
7703
- onPeers: (peers) => this.collabUi?.setPeers(peers),
7704
- onError: (msg) => {
7705
- if (typeof console !== "undefined")
7706
- console.warn("[markloom collab]", msg);
7707
- }
7708
- }
7709
- );
7710
- }
7711
8873
  const host = {
7712
8874
  root,
7713
8875
  doc: () => this.history.doc,
@@ -7720,7 +8882,7 @@ var Editor = class {
7720
8882
  insertBelow: (idx) => this.insertBelow(idx),
7721
8883
  langs: () => this.opts.nodeViews?.code?.langs?.() ?? [],
7722
8884
  mentionSource: () => this.opts.mentionSource,
7723
- // 气泡/Cmd+K:host 注入同步取 URL;未注入时气泡与下方 onKeyDown 走 askInput。
8885
+ // 气泡/Cmd+K:host 注入同步取 URL;未注入时气泡与下方 onKeyDown 走 askLinkPopover。
7724
8886
  promptLink: this.opts.promptLink ? () => this.opts.promptLink() : void 0,
7725
8887
  beginComment: this.commentPanel ? () => this.commentPanel.beginCompose() : void 0,
7726
8888
  // AI 已进内置 ITEMS(openAiSlash);此处只合并产品层额外 slash,避免「AI 续写」重复
@@ -7752,6 +8914,48 @@ var Editor = class {
7752
8914
  }
7753
8915
  });
7754
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
+ }
7755
8959
  this.draw();
7756
8960
  }
7757
8961
  destroy() {
@@ -7759,6 +8963,7 @@ var Editor = class {
7759
8963
  this.root.removeEventListener("compositionstart", this.onCompositionStart);
7760
8964
  this.root.removeEventListener("compositionend", this.onCompositionEnd);
7761
8965
  this.root.removeEventListener("keydown", this.onKeyDown);
8966
+ this.root.removeEventListener("mousedown", this.onRootMouseDown);
7762
8967
  this.root.removeEventListener("click", this.onClick);
7763
8968
  this.root.removeEventListener("click", this.onTaskCheck, true);
7764
8969
  this.root.removeEventListener("copy", this.onCopy);
@@ -7772,6 +8977,9 @@ var Editor = class {
7772
8977
  this.mentionPops.destroy();
7773
8978
  this.commentPanel?.destroy();
7774
8979
  this.tocPanel?.destroy();
8980
+ this.searchBar?.destroy();
8981
+ this.versionsPanel?.destroy();
8982
+ this.suggestBar?.destroy();
7775
8983
  this.aiCtl?.destroy();
7776
8984
  this.collabUi?.destroy();
7777
8985
  this.collabUi = null;
@@ -7780,7 +8988,11 @@ var Editor = class {
7780
8988
  this.aiCtl = null;
7781
8989
  for (const d of this.decorations)
7782
8990
  d.destroy();
7783
- 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;
7784
8996
  }
7785
8997
  /** AI 控制器(opts.ai 启用时);应用工具栏可 ed.ai?.openAtFocus / stop */
7786
8998
  get ai() {
@@ -7790,6 +9002,100 @@ var Editor = class {
7790
9002
  get collab() {
7791
9003
  return this.collabCtl;
7792
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
+ }
7793
9099
  openAi(mode) {
7794
9100
  this.aiCtl?.openAtFocus(mode);
7795
9101
  }
@@ -7800,9 +9106,11 @@ var Editor = class {
7800
9106
  return this.history.doc;
7801
9107
  }
7802
9108
  // 运行时切只读/可编辑(tiptap setEditable 对位)。只读:关 contentEditable,输入/快捷键早返,装饰层各自门控 isContentEditable。
9109
+ // 必须重绘:table cell 是嵌套 contentEditable 岛,只改根节点透传不过去。
7803
9110
  setEditable(editable) {
7804
9111
  this.opts.editable = editable;
7805
9112
  this.root.contentEditable = editable ? "true" : "false";
9113
+ this.draw(readSelection(this.root, this.history.doc) ?? void 0);
7806
9114
  }
7807
9115
  // 运行时切显隐符(tiptap show/hide/toggleInvisibleCharacters 对位)。纯重绘,model 不动。
7808
9116
  setInvisibleCharacters(visible) {
@@ -7823,10 +9131,11 @@ var Editor = class {
7823
9131
  return this.opts.editable === false;
7824
9132
  }
7825
9133
  // model → DOM。composing 期间绝不重绘,否则打断 IME。
7826
- draw(restore) {
9134
+ // scroll:仅 undo/redo 把光标滚进视口;常态输入不 scroll(防每键 jump)。
9135
+ draw(restore, opts) {
7827
9136
  if (this.composing)
7828
9137
  return;
7829
- render11(renderDoc(this.history.doc, {
9138
+ const view = projectDoc(this.history.doc, {
7830
9139
  slug: this.opts.slug,
7831
9140
  nodeViews: this.opts.nodeViews,
7832
9141
  placeholder: this.opts.placeholder,
@@ -7836,11 +9145,14 @@ var Editor = class {
7836
9145
  renderMath: this.opts.renderMath,
7837
9146
  invisibleCharacters: this.invisible,
7838
9147
  commentState: this.commentPanel?.renderState(),
7839
- atomSelect: this.imageControls.selectCtx()
7840
- }), this.root);
7841
- 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);
7842
9154
  if (restore)
7843
- writeSelection(this.root, this.history.doc, restore);
9155
+ writeSelection(this.root, this.history.doc, restore, opts);
7844
9156
  this.root.dispatchEvent(new Event("markloom-redraw", { bubbles: true }));
7845
9157
  this.syncPlaceholder();
7846
9158
  this.collabUi?.onRedraw();
@@ -7877,8 +9189,8 @@ var Editor = class {
7877
9189
  const sel = readSelection(this.root, this.history.doc);
7878
9190
  if (sel) {
7879
9191
  const a = sel.anchor.path;
7880
- const h13 = sel.head.path;
7881
- 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]);
7882
9194
  if (collapsed) {
7883
9195
  const i = a[0];
7884
9196
  const b = kids[i];
@@ -7898,39 +9210,60 @@ var Editor = class {
7898
9210
  if (el)
7899
9211
  el.setAttribute("data-placeholder", text);
7900
9212
  };
9213
+ // 唯一本地写入口。事务选区律 → resolveTxAfter(见 map.ts):
9214
+ // before 必读;after = 显式 | before↦batch。undo/redo 只 restore Commit 对,无旁路。
7901
9215
  dispatch(steps, selectionAfter) {
7902
9216
  if (steps.length === 0)
7903
9217
  return;
7904
- const after = applyAll(this.history.doc, steps);
7905
- const batch = steps.concat(gapSteps(after));
7906
- this.history = commit(this.history, batch);
7907
- 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();
7908
9227
  this.opts.onChange?.(this.history.doc);
7909
- if (!this.applyingRemote)
9228
+ if (!this.applyingRemote) {
7910
9229
  this.collabCtl?.push(batch);
9230
+ this.collabUi?.flushPresence();
9231
+ }
7911
9232
  }
7912
- // AI 流式 / 事务内续写:并入 past 最后一条,一次 undo 回退整笔事务。
9233
+ // AI 流式:并入 past 末条,一次 undo 回整笔(before 起笔 / after 末 chunk)。
7913
9234
  dispatchStream(steps, selectionAfter) {
7914
9235
  if (steps.length === 0)
7915
9236
  return;
7916
- const after = applyAll(this.history.doc, steps);
7917
- const batch = steps.concat(gapSteps(after));
7918
- this.history = amend(this.history, batch);
7919
- 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);
7920
9245
  this.opts.onChange?.(this.history.doc);
7921
- if (!this.applyingRemote)
9246
+ if (!this.applyingRemote) {
7922
9247
  this.collabCtl?.push(batch);
9248
+ this.collabUi?.flushPresence();
9249
+ }
7923
9250
  }
7924
- /** 远端协作 op:写入 model 但不上行 */
7925
- 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) {
7926
9259
  if (steps.length === 0)
7927
9260
  return;
7928
9261
  this.applyingRemote = true;
7929
9262
  try {
7930
- const after = applyAll(this.history.doc, steps);
7931
- const batch = steps.concat(gapSteps(after));
7932
- this.history = commit(this.history, batch);
7933
- 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));
7934
9267
  this.opts.onChange?.(this.history.doc);
7935
9268
  } finally {
7936
9269
  this.applyingRemote = false;
@@ -7943,29 +9276,54 @@ var Editor = class {
7943
9276
  this.draw();
7944
9277
  this.opts.onChange?.(this.history.doc);
7945
9278
  }
7946
- /** 回退一笔 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
+ */
7947
9297
  undo() {
7948
9298
  const last = this.history.past[this.history.past.length - 1];
9299
+ if (!last)
9300
+ return false;
7949
9301
  const next = undo(this.history);
7950
9302
  if (next === this.history)
7951
9303
  return false;
7952
9304
  this.history = next;
7953
- this.draw();
9305
+ this.draw(last.before, { scroll: true });
7954
9306
  this.opts.onChange?.(this.history.doc);
7955
- if (!this.applyingRemote && last)
9307
+ if (!this.applyingRemote && last.inverse.length)
7956
9308
  this.collabCtl?.push(last.inverse);
9309
+ if (!this.applyingRemote)
9310
+ this.collabUi?.flushPresence();
7957
9311
  return true;
7958
9312
  }
7959
9313
  redo() {
7960
9314
  const fut = this.history.future[0];
9315
+ if (!fut)
9316
+ return false;
7961
9317
  const next = redo(this.history);
7962
9318
  if (next === this.history)
7963
9319
  return false;
7964
9320
  this.history = next;
7965
- this.draw();
9321
+ this.draw(fut.after, { scroll: true });
7966
9322
  this.opts.onChange?.(this.history.doc);
7967
- if (!this.applyingRemote && fut)
9323
+ if (!this.applyingRemote && fut.steps.length)
7968
9324
  this.collabCtl?.push(fut.steps);
9325
+ if (!this.applyingRemote)
9326
+ this.collabUi?.flushPresence();
7969
9327
  return true;
7970
9328
  }
7971
9329
  /** 续写:当前块后插空段并流式灌入 */
@@ -7989,6 +9347,31 @@ var Editor = class {
7989
9347
  const leaf = nodeAt(this.history.doc, leafPath);
7990
9348
  this.composeBase = { leafPath, text: isText(leaf) ? leaf.text : "" };
7991
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
+ };
7992
9375
  // task 勾选:独立 capture 处理器(见 onTaskCheck)。此处:链接打开 + callout/math/mention。
7993
9376
  onClick = (e) => {
7994
9377
  const target = e.target;
@@ -8165,11 +9548,72 @@ var Editor = class {
8165
9548
  if (this.atomSelectGuard(intent, sel, e))
8166
9549
  return;
8167
9550
  e.preventDefault();
8168
- 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
+ }
8169
9610
  const result = mapInput(this.history.doc, intent, e.data ?? "", sel, newId3, this.resolved.inputRules, pending);
8170
9611
  if (result) {
8171
- if (intent === "insertParagraph" || intent === "insertLineBreak")
9612
+ if (intent === "insertParagraph" || intent === "insertLineBreak") {
8172
9613
  this.pendingMarks = null;
9614
+ this.suggestInsertId = null;
9615
+ this.suggestDeleteId = null;
9616
+ }
8173
9617
  this.dispatch(result.steps, result.selection);
8174
9618
  }
8175
9619
  };
@@ -8653,6 +10097,11 @@ var Editor = class {
8653
10097
  }
8654
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"))
8655
10099
  this.pendingMarks = null;
10100
+ if (mod2 && chord(e) === "Mod-f" && this.searchBar) {
10101
+ e.preventDefault();
10102
+ this.searchBar.open();
10103
+ return;
10104
+ }
8656
10105
  if (mod2 && chord(e) === "Mod-k" && !this.opts.promptLink) {
8657
10106
  const markSel = this.markSel();
8658
10107
  if (!markSel)
@@ -8682,9 +10131,10 @@ var Editor = class {
8682
10131
  e.preventDefault();
8683
10132
  if ("history" in r) {
8684
10133
  this.pendingMarks = null;
8685
- this.history = r.history === "undo" ? undo(this.history) : redo(this.history);
8686
- this.draw();
8687
- this.opts.onChange?.(this.history.doc);
10134
+ if (r.history === "undo")
10135
+ this.undo();
10136
+ else
10137
+ this.redo();
8688
10138
  return;
8689
10139
  }
8690
10140
  if ("pendingToggle" in r) {
@@ -8701,18 +10151,23 @@ var Editor = class {
8701
10151
  }
8702
10152
  if (mod2 && !e.shiftKey && (e.key === "a" || e.key === "A")) {
8703
10153
  const sel = readSelection(this.root, this.history.doc);
8704
- if (!sel)
8705
- return;
8706
- const blockPath = sel.head.path.slice(0, -2);
8707
- 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)
8708
10168
  return;
8709
10169
  e.preventDefault();
8710
- const len = leafText2(this.history.doc, [...blockPath, 0]).length;
8711
- writeSelection(
8712
- this.root,
8713
- this.history.doc,
8714
- { anchor: { path: [...blockPath, 0, 0] }, head: { path: [...blockPath, 0, len] } }
8715
- );
10170
+ writeSelection(this.root, this.history.doc, next);
8716
10171
  }
8717
10172
  };
8718
10173
  // 取 mark 操作的选区:任一端在代码块内则返 null(抑制 Cmd+B/I/E/Shift+X/K)。
@@ -8726,8 +10181,43 @@ var Editor = class {
8726
10181
  return null;
8727
10182
  return sel;
8728
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
+ }
8729
10214
  // 复制/剪切/粘贴:选区 ⟷ markdown。md 是 markloom 的唯一真值,剪贴板也走 md,跨编辑器/外部可读。
8730
10215
  onCopy = (e) => {
10216
+ const atom = this.exclusiveAtomMd();
10217
+ if (atom) {
10218
+ this.writeExclusiveClipboard(e, atom);
10219
+ return;
10220
+ }
8731
10221
  const sel = readSelection(this.root, this.history.doc);
8732
10222
  if (!sel)
8733
10223
  return;
@@ -8743,6 +10233,25 @@ var Editor = class {
8743
10233
  return;
8744
10234
  }
8745
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
+ }
8746
10255
  const sel = readSelection(this.root, this.history.doc);
8747
10256
  if (!sel)
8748
10257
  return;
@@ -8760,68 +10269,61 @@ var Editor = class {
8760
10269
  const sel = readSelection(this.root, this.history.doc);
8761
10270
  if (!sel)
8762
10271
  return;
8763
- const inCode = this.isCodeBlock(sel.head.path.slice(0, -2));
8764
- if (!inCode) {
8765
- const file = imageFileFrom(e.clipboardData);
8766
- if (file) {
8767
- e.preventDefault();
8768
- 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);
8769
10288
  return;
8770
10289
  }
8771
- const htmlUrl = imgSrcFromHtml(e.clipboardData?.getData("text/html"));
8772
- if (htmlUrl && !e.clipboardData?.getData("text/plain")) {
8773
- e.preventDefault();
8774
- this.insertImageUrl(htmlUrl, sel);
10290
+ case "image-file":
10291
+ this.insertImageFile(plan.file, sel);
8775
10292
  return;
8776
- }
8777
- }
8778
- const raw = e.clipboardData?.getData("text/plain") ?? "";
8779
- const html = e.clipboardData?.getData("text/html") ?? "";
8780
- if (inCode) {
8781
- if (!raw && !html)
10293
+ case "image-url":
10294
+ this.insertImageUrl(plan.url, sel);
8782
10295
  return;
8783
- e.preventDefault();
8784
- const text = raw || html;
8785
- const result2 = mapInput(this.history.doc, "insertText", text, sel, newId3);
8786
- if (result2)
8787
- this.dispatch(result2.steps, result2.selection);
8788
- return;
8789
- }
8790
- if (raw && !selCollapsed(sel) && isBareUrl(raw)) {
8791
- e.preventDefault();
8792
- const r = toggleMark(this.history.doc, sel, "link", { url: raw.trim() });
8793
- if (r)
8794
- this.dispatch(r.steps, r.selection);
8795
- return;
8796
- }
8797
- if (raw && isBareUrl(raw.trim()) && this.isEmptyTopPara(sel)) {
8798
- const url = raw.trim();
8799
- const kind = youtubeId(url) ? "youtube" : twitchChannel(url) ? "twitch" : null;
8800
- if (kind) {
8801
- 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": {
8802
10303
  const top = sel.head.path[0];
8803
- 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
+ };
8804
10310
  this.dispatch([{ kind: "replaceNode", path: [top], node }]);
8805
10311
  return;
8806
10312
  }
8807
- }
8808
- if (html) {
8809
- const blocks = htmlToBlocks(html);
8810
- if (blocks && isRichHtmlBlocks(blocks)) {
8811
- e.preventDefault();
8812
- const result2 = mapPasteBlocks(this.history.doc, sel, blocks, newId3);
8813
- if (result2)
8814
- 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);
8815
10324
  return;
8816
10325
  }
8817
10326
  }
8818
- if (!raw)
8819
- return;
8820
- e.preventDefault();
8821
- const md = this.resolved.pasteRules.reduce((s, rule) => rule(s), raw);
8822
- const result = mapPaste(this.history.doc, sel, md, newId3);
8823
- if (result)
8824
- this.dispatch(result.steps, result.selection);
8825
10327
  };
8826
10328
  // 图片 blob → url(onImage 上传钩子,或退回自包含 data: URL)→ 插入。异步:读完 blob 再重取选区更稳,
8827
10329
  // 但选区在异步间隙一般不动,直接用捕获的 sel(与 promptLink 同步路径语义对齐,够用)。
@@ -8836,10 +10338,20 @@ var Editor = class {
8836
10338
  });
8837
10339
  }
8838
10340
  // url → ![alt](<url>) → mapPaste。尖括号形式让 url 对 mdast 不透明(含括号/data: 冒号都安全)。
10341
+ // 插入后点选 image atom:mapPaste 的 selection 会落 atom 内假路径(无叶),且用户期望回车在图下插空段
10342
+ // (atom 选中态 Enter → 下方插段,见 onKeyDown)。
8839
10343
  insertImageUrl(url, sel) {
8840
10344
  const result = mapPaste(this.history.doc, sel, `![](<${url}>)`, newId3);
8841
- if (result)
8842
- 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);
8843
10355
  }
8844
10356
  // 斜杠 /image:开原生文件选择,选中后把触发段(blockIdx,含 `/image`)整块替换成 image atom。
8845
10357
  // 复用 onImage 上传钩子(未注入退回 data: URL)。取消选择 → 不动 model。
@@ -8858,22 +10370,26 @@ var Editor = class {
8858
10370
  fr.readAsDataURL(file);
8859
10371
  });
8860
10372
  to.then((url) => {
8861
- const node = { type: "image", id: newId3(), attrs: { url, alt: "" }, children: [] };
10373
+ const id = newId3();
10374
+ const node = { type: "image", id, attrs: { url, alt: "" }, children: [] };
8862
10375
  this.dispatch([{ kind: "replaceNode", path: [blockIdx], node }]);
10376
+ this.imageControls.selectByBlockId(id);
8863
10377
  }).catch(() => {
8864
10378
  });
8865
10379
  };
8866
10380
  input.click();
8867
10381
  };
8868
- // 斜杠 /math → 当前段换成含 math atom 的段(display block)。
10382
+ // 斜杠 /math → 当前段换成含 math atom 的段(display block)。轻量浮层,贴块锚点。
8869
10383
  slashInsertMath = (blockIdx) => {
8870
- void askInput({
8871
- title: "\u63D2\u5165\u516C\u5F0F",
8872
- description: "\u8F93\u5165 LaTeX\uFF0C\u4F8B\u5982 E=mc^2 \u6216 \\frac{a}{b}",
8873
- placeholder: "E=mc^2",
10384
+ void askPopover({
10385
+ anchor: this.blockRect(blockIdx),
10386
+ placeholder: "E=mc^2 \u6216 \\frac{a}{b}",
8874
10387
  defaultValue: "E=mc^2",
8875
10388
  confirmLabel: "\u63D2\u5165",
10389
+ ariaLabel: "\u63D2\u5165\u516C\u5F0F",
8876
10390
  multiline: true,
10391
+ mono: true,
10392
+ width: 340,
8877
10393
  validate: (v) => !v.trim() ? "\u516C\u5F0F\u4E0D\u80FD\u4E3A\u7A7A" : null
8878
10394
  }).then((latex) => {
8879
10395
  if (latex == null)
@@ -8883,6 +10399,18 @@ var Editor = class {
8883
10399
  this.dispatch([{ kind: "replaceNode", path: [blockIdx], node }], { anchor: { path: [blockIdx, 1, 0] }, head: { path: [blockIdx, 1, 0] } });
8884
10400
  });
8885
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
+ }
8886
10414
  // 斜杠 /youtube|/twitch|/audio|/file → embed 块。file/audio 走文件选择;yt/twitch 弹 URL。
8887
10415
  slashInsertEmbed = (blockIdx, kind) => {
8888
10416
  if (kind === "file" || kind === "audio") {
@@ -8914,11 +10442,12 @@ var Editor = class {
8914
10442
  return;
8915
10443
  }
8916
10444
  const isYt = kind === "youtube";
8917
- void askInput({
8918
- title: isYt ? "\u5D4C\u5165 YouTube" : "\u5D4C\u5165 Twitch",
8919
- 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),
8920
10447
  placeholder: isYt ? "https://www.youtube.com/watch?v=\u2026" : "https://www.twitch.tv/\u2026",
8921
10448
  confirmLabel: "\u5D4C\u5165",
10449
+ ariaLabel: isYt ? "\u5D4C\u5165 YouTube" : "\u5D4C\u5165 Twitch",
10450
+ width: 340,
8922
10451
  validate: (v) => {
8923
10452
  if (!v.trim())
8924
10453
  return "\u8BF7\u8F93\u5165\u94FE\u63A5";
@@ -8935,7 +10464,7 @@ var Editor = class {
8935
10464
  this.dispatch([{ kind: "replaceNode", path: [blockIdx], node }]);
8936
10465
  });
8937
10466
  };
8938
- // 点 math atom → 弹层改 latex。叶路径:块 data-block-id + data-leaf 下标。
10467
+ // 点 math atom → 锚点旁轻量浮层改 latex(与链接同一形态,无遮罩)。
8939
10468
  editMathAtom(mathEl) {
8940
10469
  const blockEl = mathEl.closest("[data-block-id]");
8941
10470
  const id = blockEl?.getAttribute("data-block-id");
@@ -8955,12 +10484,16 @@ var Editor = class {
8955
10484
  if (isText(atom) || atom.type !== "math")
8956
10485
  return;
8957
10486
  const cur = String(atom.attrs?.latex ?? "");
8958
- void askInput({
8959
- title: "\u7F16\u8F91\u516C\u5F0F",
8960
- description: "\u4FEE\u6539 LaTeX \u6E90\u7801",
10487
+ const anchor = mathEl.getBoundingClientRect();
10488
+ void askPopover({
10489
+ anchor,
10490
+ placeholder: "LaTeX",
8961
10491
  defaultValue: cur,
8962
10492
  confirmLabel: "\u4FDD\u5B58",
10493
+ ariaLabel: "\u7F16\u8F91\u516C\u5F0F",
8963
10494
  multiline: true,
10495
+ mono: true,
10496
+ width: 340,
8964
10497
  validate: (v) => !v.trim() ? "\u516C\u5F0F\u4E0D\u80FD\u4E3A\u7A7A" : null
8965
10498
  }).then((next) => {
8966
10499
  if (next == null || next.trim() === cur)
@@ -9212,36 +10745,24 @@ function gapSteps(after) {
9212
10745
  }
9213
10746
  function selCollapsed(sel) {
9214
10747
  const a = sel.anchor.path;
9215
- const h13 = sel.head.path;
9216
- return a.length === h13.length && a.every((v, i) => v === h13[i]);
9217
- }
9218
- function isBareUrl(s) {
9219
- const t = s.trim();
9220
- if (!t.startsWith("http://") && !t.startsWith("https://"))
9221
- return false;
9222
- for (let i = 0; i < t.length; i++) {
9223
- const c = t.charCodeAt(i);
9224
- if (c === 32 || c === 9 || c === 10 || c === 13)
9225
- 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
+ }
9226
10764
  }
9227
- return true;
9228
- }
9229
- function imageFileFrom(dt) {
9230
- if (!dt)
9231
- return null;
9232
- for (const f of Array.from(dt.files))
9233
- if (f.type.startsWith("image/"))
9234
- return f;
9235
- return null;
9236
- }
9237
- function imgSrcFromHtml(html) {
9238
- if (!html || typeof DOMParser === "undefined")
9239
- return null;
9240
- const body = new DOMParser().parseFromString(html, "text/html").body;
9241
- const imgs = body.querySelectorAll("img");
9242
- if (imgs.length !== 1 || body.textContent?.trim())
9243
- return null;
9244
- return imgs[0].getAttribute("src");
10765
+ return id;
9245
10766
  }
9246
10767
  function deleteDir(inputType) {
9247
10768
  if (!inputType.startsWith("delete"))
@@ -9280,6 +10801,103 @@ function diffSpan(a, b) {
9280
10801
  suf++;
9281
10802
  return { at: pre, remove: a.length - pre - suf, insert: b.slice(pre, b.length - suf) };
9282
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
+ }
9283
10901
 
9284
10902
  export {
9285
10903
  atomIsSelected,
@@ -9295,6 +10913,7 @@ export {
9295
10913
  renderTable,
9296
10914
  renderHr,
9297
10915
  defaultBlockRenderers,
10916
+ projectDoc,
9298
10917
  renderDoc,
9299
10918
  renderToHtml,
9300
10919
  caret,
@@ -9319,10 +10938,24 @@ export {
9319
10938
  mergeTextStyleAttrs,
9320
10939
  setTextStyle,
9321
10940
  serializeSelection,
10941
+ serializeBlock,
9322
10942
  mapPaste,
9323
10943
  mapPasteBlocks,
9324
10944
  indentItem,
9325
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,
9326
10959
  resolve,
9327
10960
  textAlign,
9328
10961
  tableBlock,
@@ -9333,6 +10966,7 @@ export {
9333
10966
  blockExtensions,
9334
10967
  askInput,
9335
10968
  normalizeLinkUrl,
10969
+ askPopover,
9336
10970
  askLinkPopover,
9337
10971
  closeAskInput,
9338
10972
  MentionMenu,
@@ -9358,6 +10992,10 @@ export {
9358
10992
  markloomKit,
9359
10993
  CommentPanel,
9360
10994
  TocPanel,
10995
+ SearchBar,
10996
+ VersionsPanel,
10997
+ SuggestBar,
10998
+ suggest,
9361
10999
  MentionPopovers,
9362
11000
  Editor,
9363
11001
  chord,