markloom 0.3.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.
@@ -0,0 +1,2305 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/tree/types.ts
2
+ function isText(n) {
3
+ return "text" in n;
4
+ }
5
+ function isElement(n) {
6
+ return "children" in n;
7
+ }
8
+ function isInlineAtom(n) {
9
+ return isElement(n) && (n.type === "mention" || n.type === "hard_break" || n.type === "math");
10
+ }
11
+
12
+ // src/tree/addr.ts
13
+ function resolve(doc, path) {
14
+ if (path.length === 0)
15
+ return { node: doc, offset: 0, parents: [], indexInParent: [] };
16
+ const parents = [];
17
+ const indexInParent = [];
18
+ let cur = doc;
19
+ for (let i = 0; i < path.length - 1; i++) {
20
+ if (!isElement(cur))
21
+ throw new Error(`path \u8D8A\u8FC7\u6587\u672C\u53F6: ${path.join(",")} \u5728\u7B2C ${i} \u6BB5`);
22
+ parents.push(cur);
23
+ indexInParent.push(path[i]);
24
+ const child = cur.children[path[i]];
25
+ if (!child)
26
+ throw new Error(`path \u8D8A\u754C: ${path.join(",")} \u5728\u7B2C ${i} \u6BB5\u65E0 child ${path[i]}`);
27
+ cur = child;
28
+ }
29
+ const last = path[path.length - 1];
30
+ return { node: cur, offset: last, parents, indexInParent };
31
+ }
32
+ function firstLeafPath(block) {
33
+ for (let i = 0; i < block.children.length; i++) {
34
+ const c = block.children[i];
35
+ if (isInlineAtom(c))
36
+ continue;
37
+ if (isText(c))
38
+ return [i];
39
+ return [i, ...firstLeafPath(c)];
40
+ }
41
+ return [0];
42
+ }
43
+ function normalizeToLeaf(doc, path) {
44
+ const prefix = [];
45
+ let cur = doc;
46
+ for (let i = 0; i < path.length; i++) {
47
+ if (isText(cur)) {
48
+ return prefix.concat(Math.max(0, path[i]));
49
+ }
50
+ if (i === path.length - 1)
51
+ break;
52
+ const child = cur.children[path[i]];
53
+ if (!child)
54
+ break;
55
+ prefix.push(path[i]);
56
+ cur = child;
57
+ }
58
+ if (isText(cur))
59
+ return prefix.concat(0);
60
+ if (isInlineAtom(cur) && prefix.length >= 1) {
61
+ const parent = nodeAt(doc, prefix.slice(0, -1));
62
+ const idx = prefix[prefix.length - 1];
63
+ const base = prefix.slice(0, -1);
64
+ const preferNext = cur.type === "hard_break";
65
+ const prev = parent.children[idx - 1];
66
+ const next = parent.children[idx + 1];
67
+ if (preferNext) {
68
+ if (next && isText(next))
69
+ return base.concat(idx + 1, 0);
70
+ if (prev && isText(prev))
71
+ return base.concat(idx - 1, prev.text.length);
72
+ } else {
73
+ if (prev && isText(prev))
74
+ return base.concat(idx - 1, prev.text.length);
75
+ if (next && isText(next))
76
+ return base.concat(idx + 1, 0);
77
+ }
78
+ }
79
+ if (cur.children.length === 0 && prefix.length >= 1) {
80
+ const parent = nodeAt(doc, prefix.slice(0, -1));
81
+ const idx = prefix[prefix.length - 1];
82
+ const base = prefix.slice(0, -1);
83
+ const next = parent.children[idx + 1];
84
+ if (next && !isText(next))
85
+ return base.concat(idx + 1, firstLeafPath(next), 0);
86
+ const prev = parent.children[idx - 1];
87
+ if (prev && !isText(prev))
88
+ return base.concat(idx - 1, lastLeafEnd(prev));
89
+ }
90
+ return prefix.concat(firstLeafPath(cur), 0);
91
+ }
92
+ function lastLeafEnd(block) {
93
+ for (let i = block.children.length - 1; i >= 0; i--) {
94
+ const last = block.children[i];
95
+ if (isInlineAtom(last))
96
+ continue;
97
+ if (isText(last))
98
+ return [i, last.text.length];
99
+ return [i, ...lastLeafEnd(last)];
100
+ }
101
+ return [0, 0];
102
+ }
103
+ function nodeAt(doc, path) {
104
+ let cur = doc;
105
+ for (const seg of path) {
106
+ if (!isElement(cur))
107
+ throw new Error(`nodeAt \u8D8A\u8FC7\u6587\u672C\u53F6: ${path.join(",")}`);
108
+ const child = cur.children[seg];
109
+ if (!child)
110
+ throw new Error(`nodeAt \u8D8A\u754C: ${path.join(",")} \u65E0 child ${seg}`);
111
+ cur = child;
112
+ }
113
+ return cur;
114
+ }
115
+ function replaceAt(doc, path, next) {
116
+ if (path.length === 0) {
117
+ if (isText(next))
118
+ throw new Error("\u6839\u4E0D\u80FD\u662F\u6587\u672C\u53F6");
119
+ return next;
120
+ }
121
+ return update(doc, path, 0, () => next);
122
+ }
123
+ function spliceAt(doc, path, at, remove, insert) {
124
+ return update(doc, path, 0, (node) => {
125
+ if (!isElement(node))
126
+ throw new Error("spliceAt \u76EE\u6807\u4E0D\u662F\u5143\u7D20");
127
+ const children = node.children.slice();
128
+ children.splice(at, remove, ...insert);
129
+ return { ...node, children };
130
+ });
131
+ }
132
+ function update(node, path, depth, fn) {
133
+ if (depth === path.length) {
134
+ const r = fn(node);
135
+ if (isText(r))
136
+ throw new Error("update \u4E0D\u80FD\u628A\u5143\u7D20\u6362\u6210\u6587\u672C\u53F6");
137
+ return r;
138
+ }
139
+ if (!isElement(node))
140
+ throw new Error(`update \u8D8A\u8FC7\u6587\u672C\u53F6: ${path.join(",")}`);
141
+ const idx = path[depth];
142
+ const children = node.children.slice();
143
+ children[idx] = updateChild(children[idx], path, depth + 1, fn);
144
+ return { ...node, children };
145
+ }
146
+ function updateChild(node, path, depth, fn) {
147
+ if (depth === path.length)
148
+ return fn(node);
149
+ if (!isElement(node))
150
+ throw new Error(`update \u8D8A\u8FC7\u6587\u672C\u53F6: ${path.join(",")}`);
151
+ const idx = path[depth];
152
+ const children = node.children.slice();
153
+ children[idx] = updateChild(children[idx], path, depth + 1, fn);
154
+ return { ...node, children };
155
+ }
156
+
157
+ // src/atom/table.ts
158
+ function tableShape(table) {
159
+ return { rows: Number(_nullishCoalesce(_optionalChain([table, 'access', _2 => _2.attrs, 'optionalAccess', _3 => _3.rows]), () => ( 0))), cols: Number(_nullishCoalesce(_optionalChain([table, 'access', _4 => _4.attrs, 'optionalAccess', _5 => _5.cols]), () => ( 0))) };
160
+ }
161
+ function colspanOf(cell) {
162
+ return isText(cell) ? 1 : Math.max(1, Number(_nullishCoalesce(_optionalChain([cell, 'access', _6 => _6.attrs, 'optionalAccess', _7 => _7.colspan]), () => ( 1))));
163
+ }
164
+ function rowspanOf(cell) {
165
+ return isText(cell) ? 1 : Math.max(1, Number(_nullishCoalesce(_optionalChain([cell, 'access', _8 => _8.attrs, 'optionalAccess', _9 => _9.rowspan]), () => ( 1))));
166
+ }
167
+ function buildGrid(table) {
168
+ const { rows, cols } = tableShape(table);
169
+ const owner = new Array(rows * cols).fill(-1);
170
+ const meta = /* @__PURE__ */ new Map();
171
+ const anchors = [];
172
+ let ci = 0;
173
+ for (let r = 0; r < rows; r++) {
174
+ for (let c = 0; c < cols; c++) {
175
+ if (owner[r * cols + c] !== -1)
176
+ continue;
177
+ const cell = table.children[ci];
178
+ if (cell === void 0)
179
+ continue;
180
+ const cs = Math.min(colspanOf(cell), cols - c);
181
+ const rs = Math.min(rowspanOf(cell), rows - r);
182
+ for (let dr = 0; dr < rs; dr++)
183
+ for (let dc = 0; dc < cs; dc++)
184
+ owner[(r + dr) * cols + (c + dc)] = ci;
185
+ meta.set(ci, { r, c, colspan: cs, rowspan: rs });
186
+ anchors.push(ci);
187
+ ci++;
188
+ }
189
+ }
190
+ return {
191
+ rows,
192
+ cols,
193
+ at: (r, c) => r >= 0 && r < rows && c >= 0 && c < cols ? owner[r * cols + c] : -1,
194
+ cellOf: (idx) => _nullishCoalesce(meta.get(idx), () => ( { r: 0, c: 0, colspan: 1, rowspan: 1 })),
195
+ anchors
196
+ };
197
+ }
198
+ function cellCaret(tablePath, table, r, c, off = 0) {
199
+ const idx = buildGrid(table).at(r, c);
200
+ return [...tablePath, idx < 0 ? 0 : idx, 0, 0, off];
201
+ }
202
+ function caretCell(tablePath, table, caret) {
203
+ if (caret.length <= tablePath.length)
204
+ return null;
205
+ const i = caret[tablePath.length];
206
+ if (i < 0 || i >= table.children.length)
207
+ return null;
208
+ const { r, c } = buildGrid(table).cellOf(i);
209
+ return { r, c };
210
+ }
211
+ function emptyCell() {
212
+ return { type: "table_cell", children: [{ type: "paragraph", children: [{ text: "" }] }] };
213
+ }
214
+ function makeTable(id, rows, cols) {
215
+ const children = [];
216
+ for (let i = 0; i < rows * cols; i++)
217
+ children.push(emptyCell());
218
+ return { type: "table", id, attrs: { rows, cols }, children };
219
+ }
220
+ function cellText(table, r, c) {
221
+ const idx = buildGrid(table).at(r, c);
222
+ const cell = idx < 0 ? void 0 : table.children[idx];
223
+ if (!cell || isText(cell) || isText(cell.children[0]))
224
+ return "";
225
+ const leaf = cell.children[0].children[0];
226
+ return leaf && isText(leaf) ? leaf.text : "";
227
+ }
228
+ function nextCell(table, r, c, dir) {
229
+ const grid = buildGrid(table);
230
+ const n = table.children.length;
231
+ if (n === 0)
232
+ return { r, c };
233
+ const cur = grid.at(r, c);
234
+ const i = ((cur < 0 ? 0 : cur) + dir + n) % n;
235
+ const m = grid.cellOf(i);
236
+ return { r: m.r, c: m.c };
237
+ }
238
+ function arrowCell(table, r, c, dir) {
239
+ const grid = buildGrid(table);
240
+ const idx = grid.at(r, c);
241
+ const cur = idx < 0 ? { r, c, colspan: 1, rowspan: 1 } : grid.cellOf(idx);
242
+ let tr = cur.r;
243
+ let tc = cur.c;
244
+ if (dir === "up")
245
+ tr = cur.r - 1;
246
+ else if (dir === "down")
247
+ tr = cur.r + cur.rowspan;
248
+ else if (dir === "left")
249
+ tc = cur.c - 1;
250
+ else tc = cur.c + cur.colspan;
251
+ const target = grid.at(tr, tc);
252
+ if (target < 0)
253
+ return null;
254
+ const a = grid.cellOf(target);
255
+ return { r: a.r, c: a.c };
256
+ }
257
+ function withSpan(cell, cs, rs) {
258
+ if (isText(cell))
259
+ return cell;
260
+ const attrs = { ...cell.attrs };
261
+ if (cs > 1)
262
+ attrs.colspan = cs;
263
+ else delete attrs.colspan;
264
+ if (rs > 1)
265
+ attrs.rowspan = rs;
266
+ else delete attrs.rowspan;
267
+ return { ...cell, attrs };
268
+ }
269
+ function insertRow(table, tablePath, at) {
270
+ const { rows, cols } = tableShape(table);
271
+ const grid = buildGrid(table);
272
+ const children = table.children.map((c) => c);
273
+ const fresh = [];
274
+ for (let c = 0; c < cols; ) {
275
+ const idxAbove = at > 0 ? grid.at(at - 1, c) : -1;
276
+ const idxAt = at < rows ? grid.at(at, c) : -1;
277
+ if (idxAbove >= 0 && idxAbove === idxAt) {
278
+ const m = grid.cellOf(idxAbove);
279
+ children[idxAbove] = withSpan(children[idxAbove], m.colspan, m.rowspan + 1);
280
+ c += m.colspan;
281
+ } else {
282
+ const ref = idxAt >= 0 ? grid.cellOf(idxAt) : at > 0 && idxAbove >= 0 ? grid.cellOf(idxAbove) : null;
283
+ const w = ref ? ref.colspan : 1;
284
+ fresh.push(withSpan(emptyCell(), w, 1));
285
+ c += w;
286
+ }
287
+ }
288
+ const insAt = at < rows ? firstFlatAtRow(grid, table.children.length, at) : table.children.length;
289
+ children.splice(insAt, 0, ...fresh);
290
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs: { ...table.attrs, rows: rows + 1, cols }, children } };
291
+ }
292
+ function firstFlatAtRow(grid, n, r) {
293
+ for (let i = 0; i < n; i++) {
294
+ if (grid.cellOf(i).r === r)
295
+ return i;
296
+ }
297
+ return n;
298
+ }
299
+ function deleteRow(table, tablePath, r, doc) {
300
+ const { rows, cols } = tableShape(table);
301
+ if (rows <= 1)
302
+ return deleteTableBlock(tablePath, doc);
303
+ const grid = buildGrid(table);
304
+ const remove = /* @__PURE__ */ new Set();
305
+ const children = table.children.map((c) => c);
306
+ for (let c = 0; c < cols; ) {
307
+ const idx = grid.at(r, c);
308
+ if (idx < 0) {
309
+ c++;
310
+ continue;
311
+ }
312
+ const m = grid.cellOf(idx);
313
+ if (m.rowspan === 1) {
314
+ remove.add(idx);
315
+ } else if (m.r === r) {
316
+ children[idx] = withSpan(children[idx], m.colspan, m.rowspan - 1);
317
+ } else {
318
+ children[idx] = withSpan(children[idx], m.colspan, m.rowspan - 1);
319
+ }
320
+ c += m.colspan;
321
+ }
322
+ const kept = children.filter((_, i) => !remove.has(i));
323
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs: { ...table.attrs, rows: rows - 1, cols }, children: kept } };
324
+ }
325
+ function insertCol(table, tablePath, at) {
326
+ const { rows, cols } = tableShape(table);
327
+ const grid = buildGrid(table);
328
+ const children = table.children.map((c) => c);
329
+ const inserts = [];
330
+ for (let r = 0; r < rows; ) {
331
+ const idxLeft = at > 0 ? grid.at(r, at - 1) : -1;
332
+ const idxAt = at < cols ? grid.at(r, at) : -1;
333
+ if (idxLeft >= 0 && idxLeft === idxAt) {
334
+ const m = grid.cellOf(idxLeft);
335
+ children[idxLeft] = withSpan(children[idxLeft], m.colspan + 1, m.rowspan);
336
+ r += m.rowspan;
337
+ } else {
338
+ const ref = idxAt >= 0 ? grid.cellOf(idxAt) : idxLeft >= 0 ? grid.cellOf(idxLeft) : null;
339
+ const h = ref ? ref.rowspan : 1;
340
+ const anchorAt = idxAt >= 0 ? idxAt : nextFlatAfterRow(grid, table.children.length, r);
341
+ inserts.push({ flatIdx: anchorAt, cell: withSpan(emptyCell(), 1, h) });
342
+ r += h;
343
+ }
344
+ }
345
+ inserts.sort((a, b) => b.flatIdx - a.flatIdx);
346
+ for (const ins of inserts)
347
+ children.splice(ins.flatIdx, 0, ins.cell);
348
+ const attrs = withColOp(table, cols + 1, { kind: "insert", at });
349
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs, children } };
350
+ }
351
+ function nextFlatAfterRow(grid, n, r) {
352
+ for (let i = 0; i < n; i++) {
353
+ if (grid.cellOf(i).r > r)
354
+ return i;
355
+ }
356
+ return n;
357
+ }
358
+ function deleteCol(table, tablePath, c, doc) {
359
+ const { rows, cols } = tableShape(table);
360
+ if (cols <= 1)
361
+ return deleteTableBlock(tablePath, doc);
362
+ const grid = buildGrid(table);
363
+ const remove = /* @__PURE__ */ new Set();
364
+ const children = table.children.map((cc) => cc);
365
+ for (let r = 0; r < rows; ) {
366
+ const idx = grid.at(r, c);
367
+ if (idx < 0) {
368
+ r++;
369
+ continue;
370
+ }
371
+ const m = grid.cellOf(idx);
372
+ if (m.colspan === 1)
373
+ remove.add(idx);
374
+ else children[idx] = withSpan(children[idx], m.colspan - 1, m.rowspan);
375
+ r += m.rowspan;
376
+ }
377
+ const kept = children.filter((_, i) => !remove.has(i));
378
+ const attrs = withColOp(table, cols - 1, { kind: "delete", at: c });
379
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs, children: kept } };
380
+ }
381
+ function hasSpan(table) {
382
+ const grid = buildGrid(table);
383
+ return grid.anchors.some((i) => {
384
+ const m = grid.cellOf(i);
385
+ return m.colspan > 1 || m.rowspan > 1;
386
+ });
387
+ }
388
+ function moveRow(table, tablePath, from, to) {
389
+ const { rows, cols } = tableShape(table);
390
+ if (hasSpan(table))
391
+ return { kind: "replaceNode", path: tablePath, node: table };
392
+ const grid = Array.from({ length: rows }, (_, r) => table.children.slice(r * cols, (r + 1) * cols));
393
+ const [row] = grid.splice(from, 1);
394
+ grid.splice(to, 0, row);
395
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs: { ...table.attrs, rows, cols }, children: grid.flat() } };
396
+ }
397
+ function moveCol(table, tablePath, from, to) {
398
+ const { rows, cols } = tableShape(table);
399
+ if (hasSpan(table))
400
+ return { kind: "replaceNode", path: tablePath, node: table };
401
+ const children = [];
402
+ for (let r = 0; r < rows; r++) {
403
+ const row = table.children.slice(r * cols, (r + 1) * cols);
404
+ const [c] = row.splice(from, 1);
405
+ row.splice(to, 0, c);
406
+ children.push(...row);
407
+ }
408
+ const attrs = withColOp(table, cols, { kind: "move", from, to });
409
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs, children } };
410
+ }
411
+ function tableColWidths(table) {
412
+ const w = _optionalChain([table, 'access', _10 => _10.attrs, 'optionalAccess', _11 => _11.colWidths]);
413
+ return Array.isArray(w) ? w.map(Number) : null;
414
+ }
415
+ function setColWidths(table, tablePath, widths) {
416
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs: { ...table.attrs, colWidths: widths } } };
417
+ }
418
+ function setAlign(table, tablePath, col, value) {
419
+ const { cols } = tableShape(table);
420
+ const cur = Array.isArray(_optionalChain([table, 'access', _12 => _12.attrs, 'optionalAccess', _13 => _13.align])) ? table.attrs.align : [];
421
+ const align = Array.from({ length: cols }, (_, i) => _nullishCoalesce(cur[i], () => ( null)));
422
+ align[col] = value;
423
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs: { ...table.attrs, align } } };
424
+ }
425
+ function mergeCells(table, tablePath, r1, c1, r2, c2) {
426
+ const grid = buildGrid(table);
427
+ let top = Math.min(r1, r2);
428
+ let bot = Math.max(r1, r2);
429
+ let left = Math.min(c1, c2);
430
+ let right = Math.max(c1, c2);
431
+ let grew = true;
432
+ while (grew) {
433
+ grew = false;
434
+ for (const idx of grid.anchors) {
435
+ const m = grid.cellOf(idx);
436
+ const ir = m.r <= bot && m.r + m.rowspan - 1 >= top;
437
+ const ic = m.c <= right && m.c + m.colspan - 1 >= left;
438
+ if (!ir || !ic)
439
+ continue;
440
+ const nt = Math.min(top, m.r);
441
+ const nb = Math.max(bot, m.r + m.rowspan - 1);
442
+ const nl = Math.min(left, m.c);
443
+ const nr = Math.max(right, m.c + m.colspan - 1);
444
+ if (nt !== top || nb !== bot || nl !== left || nr !== right) {
445
+ top = nt;
446
+ bot = nb;
447
+ left = nl;
448
+ right = nr;
449
+ grew = true;
450
+ }
451
+ }
452
+ }
453
+ const covered = grid.anchors.filter((idx) => {
454
+ const m = grid.cellOf(idx);
455
+ return m.r >= top && m.r + m.rowspan - 1 <= bot && m.c >= left && m.c + m.colspan - 1 <= right;
456
+ });
457
+ if (covered.length <= 1)
458
+ return { kind: "replaceNode", path: tablePath, node: table };
459
+ const survivor = covered[0];
460
+ const survCell = table.children[survivor];
461
+ const paras = survCell.children.slice();
462
+ for (const idx of covered.slice(1)) {
463
+ const cell = table.children[idx];
464
+ for (const p of cell.children) {
465
+ if (!isText(p) && p.type === "paragraph" && isNonEmptyPara(p))
466
+ paras.push(p);
467
+ }
468
+ }
469
+ const merged = withSpan({ ...survCell, children: paras }, right - left + 1, bot - top + 1);
470
+ const removeSet = new Set(covered.slice(1));
471
+ const children = table.children.map((c, i) => i === survivor ? merged : c).filter((_, i) => !removeSet.has(i));
472
+ return { kind: "replaceNode", path: tablePath, node: { ...table, children } };
473
+ }
474
+ function isNonEmptyPara(p) {
475
+ return p.children.some((c) => isText(c) && c.text !== "");
476
+ }
477
+ function splitCell(table, tablePath, r, c) {
478
+ const grid = buildGrid(table);
479
+ const idx = grid.at(r, c);
480
+ if (idx < 0)
481
+ return { kind: "replaceNode", path: tablePath, node: table };
482
+ const m = grid.cellOf(idx);
483
+ if (m.colspan === 1 && m.rowspan === 1)
484
+ return { kind: "replaceNode", path: tablePath, node: table };
485
+ const fill = m.colspan * m.rowspan - 1;
486
+ const children = table.children.map((cc) => cc);
487
+ children[idx] = withSpan(children[idx], 1, 1);
488
+ children.splice(idx + 1, 0, ...Array.from({ length: fill }, emptyCell));
489
+ return { kind: "replaceNode", path: tablePath, node: { ...table, children } };
490
+ }
491
+ function setCellStyle(table, tablePath, r, c, style) {
492
+ const idx = buildGrid(table).at(r, c);
493
+ if (idx < 0)
494
+ return { kind: "replaceNode", path: tablePath, node: table };
495
+ const cell = table.children[idx];
496
+ const attrs = { ...cell.attrs };
497
+ if ("bg" in style) {
498
+ if (style.bg)
499
+ attrs.bg = style.bg;
500
+ else delete attrs.bg;
501
+ }
502
+ if ("border" in style) {
503
+ if (style.border)
504
+ attrs.border = style.border;
505
+ else delete attrs.border;
506
+ }
507
+ const children = table.children.map((cc, i) => i === idx ? { ...cell, attrs } : cc);
508
+ return { kind: "replaceNode", path: tablePath, node: { ...table, children } };
509
+ }
510
+ function clearCells(table, tablePath, rect) {
511
+ const grid = buildGrid(table);
512
+ const children = table.children.map((cell, i) => {
513
+ if (isText(cell) || cell.type !== "table_cell")
514
+ return cell;
515
+ const m = grid.cellOf(i);
516
+ const hit = m.r <= rect.r2 && m.r + m.rowspan - 1 >= rect.r1 && m.c <= rect.c2 && m.c + m.colspan - 1 >= rect.c1;
517
+ return hit ? { ...cell, children: [{ type: "paragraph", children: [{ text: "" }] }] } : cell;
518
+ });
519
+ return { kind: "replaceNode", path: tablePath, node: { ...table, children } };
520
+ }
521
+ function setFreeze(table, tablePath, freeze) {
522
+ const attrs = { ...table.attrs };
523
+ if ("rows" in freeze) {
524
+ if (freeze.rows)
525
+ attrs.freezeRows = freeze.rows;
526
+ else delete attrs.freezeRows;
527
+ }
528
+ if ("cols" in freeze) {
529
+ if (freeze.cols)
530
+ attrs.freezeCols = freeze.cols;
531
+ else delete attrs.freezeCols;
532
+ }
533
+ return { kind: "replaceNode", path: tablePath, node: { ...table, attrs } };
534
+ }
535
+ function mapCol(arr, op, fill) {
536
+ if (op.kind === "insert")
537
+ return arr.slice(0, op.at).concat(fill, arr.slice(op.at));
538
+ if (op.kind === "delete")
539
+ return arr.slice(0, op.at).concat(arr.slice(op.at + 1));
540
+ const a = arr.slice();
541
+ const [x] = a.splice(op.from, 1);
542
+ a.splice(op.to, 0, x);
543
+ return a;
544
+ }
545
+ function withColOp(table, cols, op) {
546
+ const attrs = { ...table.attrs, cols };
547
+ const widths = tableColWidths(table);
548
+ if (widths)
549
+ attrs.colWidths = mapCol(widths, op, 120);
550
+ const align = Array.isArray(_optionalChain([table, 'access', _14 => _14.attrs, 'optionalAccess', _15 => _15.align])) ? table.attrs.align : null;
551
+ if (align)
552
+ attrs.align = mapCol(align, op, null);
553
+ return attrs;
554
+ }
555
+ function deleteTableBlock(tablePath, doc) {
556
+ const parent = tablePath.slice(0, -1);
557
+ const at = tablePath[tablePath.length - 1];
558
+ if (doc && parent.length === 0 && doc.children.length <= 1) {
559
+ const para = { type: "paragraph", children: [{ text: "" }] };
560
+ return { kind: "spliceChildren", path: [], at, remove: 1, insert: [para] };
561
+ }
562
+ return { kind: "spliceChildren", path: parent, at, remove: 1, insert: [] };
563
+ }
564
+ function tableAt(doc, tablePath) {
565
+ const n = nodeAt(doc, tablePath);
566
+ return !isText(n) && n.type === "table" ? n : null;
567
+ }
568
+ function checkTable(table) {
569
+ const out = [];
570
+ const { rows, cols } = tableShape(table);
571
+ if (rows * cols > 0) {
572
+ const grid = buildGrid(table);
573
+ let covered = 0;
574
+ let holes = 0;
575
+ for (let r = 0; r < rows; r++)
576
+ for (let c = 0; c < cols; c++)
577
+ grid.at(r, c) < 0 ? holes++ : covered++;
578
+ if (holes > 0)
579
+ out.push(`\u7F51\u683C\u6709 ${holes} \u4E2A\u672A\u8986\u76D6\u70B9(span \u4E4B\u548C < rows*cols \u6216 children \u4E0D\u8DB3)`);
580
+ if (grid.anchors.length !== table.children.length)
581
+ out.push(`\u951A\u70B9\u6570 ${grid.anchors.length} \u2260 children \u6570 ${table.children.length}(span \u4E4B\u548C > rows*cols)`);
582
+ void covered;
583
+ }
584
+ table.children.forEach((cell, i) => {
585
+ if (isText(cell) || cell.type !== "table_cell") {
586
+ out.push(`children[${i}] \u4E0D\u662F table_cell`);
587
+ return;
588
+ }
589
+ for (const child of cell.children) {
590
+ if (!isText(child) && child.type !== "paragraph")
591
+ out.push(`children[${i}] cell \u5185\u975E paragraph: ${child.type}`);
592
+ }
593
+ });
594
+ const widths = tableColWidths(table);
595
+ if (widths && widths.length !== cols)
596
+ out.push(`colWidths \u957F\u5EA6 ${widths.length} \u2260 cols ${cols}`);
597
+ const align = _optionalChain([table, 'access', _16 => _16.attrs, 'optionalAccess', _17 => _17.align]);
598
+ if (Array.isArray(align) && align.length !== cols)
599
+ out.push(`align \u957F\u5EA6 ${align.length} \u2260 cols ${cols}`);
600
+ return out;
601
+ }
602
+ var tableSchema = {
603
+ marks: ["bold", "italic", "code"],
604
+ nodes: {
605
+ table: { content: ["table_cell"], atom: true },
606
+ table_cell: { content: ["paragraph"] },
607
+ paragraph: { content: ["text"], inline: true }
608
+ }
609
+ };
610
+
611
+ // src/md.ts
612
+ var _mdastutilfrommarkdown = require('mdast-util-from-markdown');
613
+ var _mdastutilgfm = require('mdast-util-gfm');
614
+ var _mdastutiltomarkdown = require('mdast-util-to-markdown');
615
+ var _micromarkextensiongfm = require('micromark-extension-gfm');
616
+ var mdExt = { extensions: [_micromarkextensiongfm.gfm.call(void 0, )], mdastExtensions: [_mdastutilgfm.gfmFromMarkdown.call(void 0, )] };
617
+ function imgHtmlToMark(html) {
618
+ if (typeof DOMParser === "undefined")
619
+ return null;
620
+ const body = new DOMParser().parseFromString(html, "text/html").body;
621
+ const img = body.querySelector("img");
622
+ if (!img || body.querySelectorAll("*").length !== 1)
623
+ return null;
624
+ const attrs = { url: _nullishCoalesce(img.getAttribute("src"), () => ( "")) };
625
+ const title = img.getAttribute("title");
626
+ if (title != null)
627
+ attrs.title = title;
628
+ const w = img.getAttribute("width");
629
+ const h = img.getAttribute("height");
630
+ if (w != null && w !== "")
631
+ attrs.w = Number(w);
632
+ if (h != null && h !== "")
633
+ attrs.h = Number(h);
634
+ const align = imgStyleAlign(img.getAttribute("style"));
635
+ if (align)
636
+ attrs.align = align;
637
+ return { alt: _nullishCoalesce(img.getAttribute("alt"), () => ( "")), attrs };
638
+ }
639
+ function mentionFromHtml(openTag) {
640
+ if (typeof DOMParser === "undefined")
641
+ return null;
642
+ const el = new DOMParser().parseFromString(`${openTag}</span>`, "text/html").body.querySelector("span");
643
+ if (!el || !el.hasAttribute("data-mention"))
644
+ return null;
645
+ const id = _nullishCoalesce(el.getAttribute("data-id"), () => ( ""));
646
+ const label = _nullishCoalesce(el.getAttribute("data-label"), () => ( id));
647
+ const kind = el.getAttribute("data-kind");
648
+ const date = el.getAttribute("data-date");
649
+ const attrs = { id, label };
650
+ if (kind)
651
+ attrs.kind = kind;
652
+ if (date)
653
+ attrs.date = date;
654
+ return { type: "mention", attrs, children: [] };
655
+ }
656
+ function mathFromHtml(html) {
657
+ if (typeof DOMParser === "undefined")
658
+ return null;
659
+ const src = html.includes("</span>") ? html : `${html}</span>`;
660
+ const el = new DOMParser().parseFromString(src, "text/html").body.querySelector("span");
661
+ if (!el || !el.hasAttribute("data-math"))
662
+ return null;
663
+ const latex = _nullishCoalesce(el.getAttribute("data-latex"), () => ( ""));
664
+ const display = el.getAttribute("data-display") === "block" ? "block" : "inline";
665
+ return { type: "math", attrs: { latex, display }, children: [] };
666
+ }
667
+ function embedFromHtml(html) {
668
+ if (typeof DOMParser === "undefined")
669
+ return null;
670
+ const el = new DOMParser().parseFromString(html, "text/html").body.querySelector("div[data-embed]");
671
+ if (!el)
672
+ return null;
673
+ const kind = _nullishCoalesce(el.getAttribute("data-kind"), () => ( ""));
674
+ const src = _nullishCoalesce(el.getAttribute("data-src"), () => ( ""));
675
+ if (!kind || !src)
676
+ return null;
677
+ const attrs = { kind, src };
678
+ const title = el.getAttribute("data-title");
679
+ const name = el.getAttribute("data-name");
680
+ if (title)
681
+ attrs.title = title;
682
+ if (name)
683
+ attrs.name = name;
684
+ return { type: "embed", attrs, children: [] };
685
+ }
686
+ function imgStyleAlign(style) {
687
+ if (!style)
688
+ return "";
689
+ const decls = style.split(";").map((s) => s.trim());
690
+ const left = decls.includes("margin-left:auto");
691
+ const right = decls.includes("margin-right:auto");
692
+ return left && right ? "center" : left ? "right" : "";
693
+ }
694
+ function figureFromHtml(html) {
695
+ if (typeof DOMParser === "undefined")
696
+ return null;
697
+ const body = new DOMParser().parseFromString(html, "text/html").body;
698
+ const fig = body.querySelector("figure");
699
+ const img = _optionalChain([fig, 'optionalAccess', _18 => _18.querySelector, 'call', _19 => _19("img")]);
700
+ if (!fig || !img)
701
+ return null;
702
+ const mark = imgHtmlToMark(img.outerHTML);
703
+ if (!mark)
704
+ return null;
705
+ const attrs = { ...mark.attrs, alt: mark.alt };
706
+ const cap = _nullishCoalesce(_optionalChain([fig, 'access', _20 => _20.querySelector, 'call', _21 => _21("figcaption"), 'optionalAccess', _22 => _22.textContent]), () => ( ""));
707
+ if (cap)
708
+ attrs.caption = cap;
709
+ const falign = _optionalChain([fig, 'access', _23 => _23.getAttribute, 'call', _24 => _24("style"), 'optionalAccess', _25 => _25.split, 'call', _26 => _26(";"), 'access', _27 => _27.map, 'call', _28 => _28((s) => s.trim()), 'access', _29 => _29.find, 'call', _30 => _30((s) => s.startsWith("text-align:")), 'optionalAccess', _31 => _31.slice, 'call', _32 => _32("text-align:".length), 'access', _33 => _33.trim, 'call', _34 => _34()]);
710
+ if (falign === "center" || falign === "right")
711
+ attrs.align = falign;
712
+ return { type: "image", attrs, children: [] };
713
+ }
714
+ var htmlTagName = (v) => {
715
+ const s = v.trim();
716
+ if (s[0] !== "<" || s[s.length - 1] !== ">")
717
+ return null;
718
+ let i = 1;
719
+ const close = s[i] === "/";
720
+ if (close)
721
+ i++;
722
+ let name = "";
723
+ for (; i < s.length; i++) {
724
+ const c2 = s[i].toLowerCase();
725
+ if (c2 >= "a" && c2 <= "z")
726
+ name += c2;
727
+ else
728
+ break;
729
+ }
730
+ if (!name)
731
+ return null;
732
+ if (close)
733
+ return s.slice(i) === ">" ? { name, close } : null;
734
+ const c = s[i];
735
+ if (c === ">" || c === " " || c === " " || c === "\n" || c === "\r")
736
+ return { name, close: false };
737
+ return null;
738
+ };
739
+ function isHtmlMarkOpen(open, raw) {
740
+ if (open.close)
741
+ return false;
742
+ if (simpleTagMark(open.name))
743
+ return true;
744
+ if (open.name === "font")
745
+ return true;
746
+ if (open.name === "span") {
747
+ if (raw.includes("data-mention") || raw.includes("data-math"))
748
+ return false;
749
+ return raw.includes("style=") || raw.includes("data-mark") || raw.includes("data-comment");
750
+ }
751
+ return false;
752
+ }
753
+ function stitchInlineHtml(nodes, carry, md) {
754
+ for (let i = 0; i < nodes.length; i++) {
755
+ const n = nodes[i];
756
+ if (n.type !== "html")
757
+ continue;
758
+ const open = htmlTagName(n.value);
759
+ if (!open || !isHtmlMarkOpen(open, n.value))
760
+ continue;
761
+ let depth = 1, j = i + 1;
762
+ for (; j < nodes.length; j++) {
763
+ const t = nodes[j].type === "html" ? htmlTagName(nodes[j].value) : null;
764
+ if (t && t.name === open.name)
765
+ depth += t.close ? -1 : 1;
766
+ if (depth === 0)
767
+ break;
768
+ }
769
+ if (j >= nodes.length)
770
+ continue;
771
+ const start = _optionalChain([nodes, 'access', _35 => _35[i], 'access', _36 => _36.position, 'optionalAccess', _37 => _37.start, 'access', _38 => _38.offset]);
772
+ const end = _optionalChain([nodes, 'access', _39 => _39[j], 'access', _40 => _40.position, 'optionalAccess', _41 => _41.end, 'access', _42 => _42.offset]);
773
+ if (start === void 0 || end === void 0)
774
+ continue;
775
+ const leaves2 = inlineHtmlToLeaves(md.slice(start, end), carry);
776
+ if (!leaves2)
777
+ continue;
778
+ const dropEmpty = (ns) => ns.filter((n2) => !(n2.text === "" && !_optionalChain([n2, 'access', _43 => _43.marks, 'optionalAccess', _44 => _44.length])));
779
+ const out = [
780
+ ...dropEmpty(i > 0 ? phrasingToText(nodes.slice(0, i), carry, md) : []),
781
+ ...leaves2,
782
+ ...dropEmpty(j + 1 < nodes.length ? phrasingToText(nodes.slice(j + 1), carry, md) : [])
783
+ ];
784
+ return out.length ? out : [{ text: "" }];
785
+ }
786
+ return null;
787
+ }
788
+ function phrasingToText(nodes, carry, md) {
789
+ const stitched = stitchInlineHtml(nodes, carry, md);
790
+ if (stitched)
791
+ return stitched;
792
+ const out = [];
793
+ for (const n of nodes) {
794
+ switch (n.type) {
795
+ case "text":
796
+ out.push(carry.length ? { text: n.value, marks: carry } : { text: n.value });
797
+ break;
798
+ case "inlineCode":
799
+ out.push({ text: n.value, marks: carry.concat({ name: "code" }) });
800
+ break;
801
+ case "strong":
802
+ out.push(...phrasingToText(n.children, carry.concat({ name: "bold" }), md));
803
+ break;
804
+ case "emphasis":
805
+ out.push(...phrasingToText(n.children, carry.concat({ name: "italic" }), md));
806
+ break;
807
+ case "delete":
808
+ out.push(...phrasingToText(n.children, carry.concat({ name: "strike" }), md));
809
+ break;
810
+ case "link":
811
+ out.push(...phrasingToText(n.children, carry.concat({ name: "link", attrs: { url: n.url, title: _nullishCoalesce(n.title, () => ( void 0)) } }), md));
812
+ break;
813
+ case "break":
814
+ out.push({ text: "\n", marks: carry });
815
+ break;
816
+ case "html": {
817
+ const img = imgHtmlToMark(n.value);
818
+ if (img) {
819
+ out.push({ text: img.alt, marks: carry.concat({ name: "image", attrs: img.attrs }) });
820
+ break;
821
+ }
822
+ const parsed = inlineHtmlToLeaves(n.value, carry);
823
+ if (parsed && parsed.length) {
824
+ out.push(...parsed);
825
+ break;
826
+ }
827
+ out.push({ text: n.value, marks: carry.concat({ name: "html" }) });
828
+ break;
829
+ }
830
+ case "image":
831
+ out.push({ text: _nullishCoalesce(n.alt, () => ( "")), marks: carry.concat({ name: "image", attrs: { url: n.url, title: _nullishCoalesce(n.title, () => ( void 0)) } }) });
832
+ break;
833
+ default: {
834
+ const s = n.value;
835
+ if (typeof s === "string") {
836
+ out.push({ text: s, marks: carry });
837
+ break;
838
+ }
839
+ const off = n.position;
840
+ if (_optionalChain([off, 'optionalAccess', _45 => _45.start, 'access', _46 => _46.offset]) !== void 0 && off.end.offset !== void 0)
841
+ out.push({ text: md.slice(off.start.offset, off.end.offset), marks: carry.concat({ name: "html" }) });
842
+ }
843
+ }
844
+ }
845
+ return out.length ? out : [{ text: "" }];
846
+ }
847
+ function phrasingToNodes(nodes, md) {
848
+ const isSpanOpen = (n) => n.type === "html" && n.value.trimStart().toLowerCase().startsWith("<span") && (n.value.includes("data-mention") || n.value.includes("data-math"));
849
+ const isSpanClose = (n) => n.type === "html" && n.value.trim().toLowerCase() === "</span>";
850
+ for (let i = 0; i < nodes.length; i++) {
851
+ if (!isSpanOpen(nodes[i]))
852
+ continue;
853
+ let j = i + 1;
854
+ for (; j < nodes.length; j++)
855
+ if (isSpanClose(nodes[j]))
856
+ break;
857
+ if (j >= nodes.length)
858
+ continue;
859
+ const open = nodes[i].value;
860
+ const atom = open.includes("data-math") ? mathFromHtml(open) : mentionFromHtml(open);
861
+ if (!atom)
862
+ continue;
863
+ const dropEmpty = (ns) => ns.filter((n) => !(isText(n) && n.text === "" && !_optionalChain([n, 'access', _47 => _47.marks, 'optionalAccess', _48 => _48.length])));
864
+ return [
865
+ ...i > 0 ? dropEmpty(phrasingToNodes(nodes.slice(0, i), md)) : [],
866
+ atom,
867
+ ...j + 1 < nodes.length ? dropEmpty(phrasingToNodes(nodes.slice(j + 1), md)) : []
868
+ ];
869
+ }
870
+ return phrasingWithBreaks(nodes, md);
871
+ }
872
+ function phrasingWithBreaks(nodes, md) {
873
+ const out = [];
874
+ let run = [];
875
+ const flush = () => {
876
+ if (!run.length)
877
+ return;
878
+ const leaves2 = phrasingToText(run, [], md);
879
+ for (const l of leaves2) {
880
+ if (isText(l) && l.text === "" && !_optionalChain([l, 'access', _49 => _49.marks, 'optionalAccess', _50 => _50.length]) && out.length)
881
+ continue;
882
+ out.push(l);
883
+ }
884
+ run = [];
885
+ };
886
+ for (const n of nodes) {
887
+ if (n.type === "break") {
888
+ flush();
889
+ out.push({ type: "hard_break", children: [] });
890
+ } else {
891
+ run.push(n);
892
+ }
893
+ }
894
+ flush();
895
+ return out.length ? out : [{ text: "" }];
896
+ }
897
+ function span(n) {
898
+ return _optionalChain([n, 'access', _51 => _51.position, 'optionalAccess', _52 => _52.start, 'access', _53 => _53.offset]) !== void 0 && n.position.end.offset !== void 0 ? [n.position.start.offset, n.position.end.offset] : void 0;
899
+ }
900
+ function tableToAtom(t, md) {
901
+ const rows = t.children;
902
+ const cols = rows.reduce((m, r) => Math.max(m, r.children.length), 0);
903
+ const children = [];
904
+ for (const row of rows) {
905
+ for (let c = 0; c < cols; c++) {
906
+ const cell = row.children[c];
907
+ const text = cell ? phrasingToText(cell.children, [], md) : [{ text: "" }];
908
+ children.push({ type: "table_cell", children: leavesToParas(text) });
909
+ }
910
+ }
911
+ return { type: "table", attrs: { rows: rows.length, cols, span: span(t), align: _nullishCoalesce(t.align, () => ( void 0)) }, children };
912
+ }
913
+ function leavesToParas(leaves2) {
914
+ const isBreak = (l) => l.text === "\n" || l.text === "<br>" && !!_optionalChain([l, 'access', _54 => _54.marks, 'optionalAccess', _55 => _55.some, 'call', _56 => _56((m) => m.name === "html")]);
915
+ const paras = [[]];
916
+ for (const l of leaves2) {
917
+ if (isBreak(l))
918
+ paras.push([]);
919
+ else
920
+ paras[paras.length - 1].push(l);
921
+ }
922
+ return paras.map((text) => ({ type: "paragraph", children: text.length ? text : [{ text: "" }] }));
923
+ }
924
+ function simpleTagMark(tag) {
925
+ switch (tag) {
926
+ case "strong":
927
+ case "b":
928
+ return "bold";
929
+ case "em":
930
+ case "i":
931
+ return "italic";
932
+ case "del":
933
+ case "s":
934
+ return "strike";
935
+ case "u":
936
+ return "underline";
937
+ case "mark":
938
+ return "highlight";
939
+ case "sup":
940
+ return "superscript";
941
+ case "sub":
942
+ return "subscript";
943
+ default:
944
+ return null;
945
+ }
946
+ }
947
+ function inlineHtmlToLeaves(html, carry) {
948
+ if (typeof DOMParser === "undefined")
949
+ return null;
950
+ const body = new DOMParser().parseFromString(html, "text/html").body;
951
+ const out = [];
952
+ let known = true;
953
+ const walk = (node, marks) => {
954
+ if (node.nodeType === 3) {
955
+ const t = _nullishCoalesce(node.textContent, () => ( ""));
956
+ if (t)
957
+ out.push(marks.length ? { text: t, marks } : { text: t });
958
+ return;
959
+ }
960
+ if (node.nodeType !== 1)
961
+ return;
962
+ const el = node;
963
+ const tag = el.tagName.toLowerCase();
964
+ const simple = simpleTagMark(tag);
965
+ if (simple) {
966
+ el.childNodes.forEach((ch) => walk(ch, marks.concat({ name: simple })));
967
+ return;
968
+ }
969
+ if (tag === "code") {
970
+ out.push({ text: _nullishCoalesce(el.textContent, () => ( "")), marks: marks.concat({ name: "code" }) });
971
+ return;
972
+ }
973
+ if (tag === "a") {
974
+ el.childNodes.forEach((ch) => walk(ch, marks.concat({ name: "link", attrs: { url: _nullishCoalesce(el.getAttribute("href"), () => ( "")) } })));
975
+ return;
976
+ }
977
+ if (tag === "span") {
978
+ const cid = el.getAttribute("data-comment");
979
+ if (cid) {
980
+ el.childNodes.forEach((ch) => walk(ch, marks.concat({ name: "comment", attrs: { id: cid } })));
981
+ return;
982
+ }
983
+ const ts = styleToTextStyleAttrs(el.getAttribute("style"));
984
+ if (ts || el.getAttribute("data-mark") === "textStyle") {
985
+ const mark = { name: "textStyle", attrs: _nullishCoalesce(ts, () => ( {})) };
986
+ el.childNodes.forEach((ch) => walk(ch, marks.concat(mark)));
987
+ return;
988
+ }
989
+ el.childNodes.forEach((ch) => walk(ch, marks));
990
+ return;
991
+ }
992
+ if (tag === "font") {
993
+ const attrs = {};
994
+ const color = el.getAttribute("color");
995
+ const face = el.getAttribute("face");
996
+ const size = el.getAttribute("size");
997
+ if (color)
998
+ attrs.color = color;
999
+ if (face)
1000
+ attrs.fontFamily = face;
1001
+ if (size)
1002
+ attrs.fontSize = size;
1003
+ if (Object.keys(attrs).length) {
1004
+ el.childNodes.forEach((ch) => walk(ch, marks.concat({ name: "textStyle", attrs })));
1005
+ return;
1006
+ }
1007
+ el.childNodes.forEach((ch) => walk(ch, marks));
1008
+ return;
1009
+ }
1010
+ known = false;
1011
+ };
1012
+ body.childNodes.forEach((ch) => walk(ch, carry));
1013
+ return known ? out : null;
1014
+ }
1015
+ function domInlineToNodes(root) {
1016
+ const out = [];
1017
+ const walk = (node, marks) => {
1018
+ if (node.nodeType === 3) {
1019
+ const t = _nullishCoalesce(node.textContent, () => ( ""));
1020
+ if (t)
1021
+ out.push(marks.length ? { text: t, marks } : { text: t });
1022
+ return;
1023
+ }
1024
+ if (node.nodeType !== 1)
1025
+ return;
1026
+ const el = node;
1027
+ const tag = el.tagName.toLowerCase();
1028
+ if (tag === "br") {
1029
+ out.push({ type: "hard_break", children: [] });
1030
+ return;
1031
+ }
1032
+ const add = (m) => marks.concat(m);
1033
+ let next = marks;
1034
+ const simple = simpleTagMark(tag);
1035
+ if (simple)
1036
+ next = add({ name: simple });
1037
+ else if (tag === "code") {
1038
+ out.push({ text: _nullishCoalesce(el.textContent, () => ( "")), marks: add({ name: "code" }) });
1039
+ return;
1040
+ } else if (tag === "a")
1041
+ next = add({ name: "link", attrs: { url: _nullishCoalesce(el.getAttribute("href"), () => ( "")) } });
1042
+ else if (tag === "img") {
1043
+ const attrs = { url: _nullishCoalesce(el.getAttribute("src"), () => ( "")) };
1044
+ const w = el.getAttribute("width");
1045
+ const h = el.getAttribute("height");
1046
+ if (w != null && w !== "") attrs.w = Number(w);
1047
+ if (h != null && h !== "") attrs.h = Number(h);
1048
+ out.push({ text: _nullishCoalesce(el.getAttribute("alt"), () => ( "")), marks: add({ name: "image", attrs }) });
1049
+ return;
1050
+ } else if (tag === "span" && el.hasAttribute("data-math")) {
1051
+ const latex = _nullishCoalesce(_nullishCoalesce(el.getAttribute("data-latex"), () => ( el.textContent)), () => ( ""));
1052
+ const display = el.getAttribute("data-display") === "block" ? "block" : "inline";
1053
+ out.push({ type: "math", attrs: { latex, display }, children: [] });
1054
+ return;
1055
+ } else if (tag === "span" && el.hasAttribute("data-mention")) {
1056
+ const id = _nullishCoalesce(el.getAttribute("data-id"), () => ( ""));
1057
+ const label = _nullishCoalesce(el.getAttribute("data-label"), () => ( id));
1058
+ const attrs = { id, label };
1059
+ const kind = el.getAttribute("data-kind");
1060
+ const date = el.getAttribute("data-date");
1061
+ if (kind) attrs.kind = kind;
1062
+ if (date) attrs.date = date;
1063
+ out.push({ type: "mention", attrs, children: [] });
1064
+ return;
1065
+ } else if (tag === "span") {
1066
+ const cid = el.getAttribute("data-comment");
1067
+ if (cid)
1068
+ next = add({ name: "comment", attrs: { id: cid } });
1069
+ else {
1070
+ const ts = styleToTextStyleAttrs(el.getAttribute("style"));
1071
+ if (ts || el.getAttribute("data-mark") === "textStyle")
1072
+ next = add({ name: "textStyle", attrs: _nullishCoalesce(ts, () => ( {})) });
1073
+ }
1074
+ } else if (tag === "font") {
1075
+ const attrs = {};
1076
+ const color = el.getAttribute("color");
1077
+ const face = el.getAttribute("face");
1078
+ if (color) attrs.color = color;
1079
+ if (face) attrs.fontFamily = face;
1080
+ if (Object.keys(attrs).length)
1081
+ next = add({ name: "textStyle", attrs });
1082
+ }
1083
+ el.childNodes.forEach((ch) => walk(ch, next));
1084
+ };
1085
+ root.childNodes.forEach((ch) => walk(ch, []));
1086
+ return out.length ? out : [{ text: "" }];
1087
+ }
1088
+ function cellDomToParas(cell) {
1089
+ const paras = [[]];
1090
+ const walk = (node, marks) => {
1091
+ if (node.nodeType === 3) {
1092
+ const t = _nullishCoalesce(node.textContent, () => ( ""));
1093
+ if (t)
1094
+ paras[paras.length - 1].push(marks.length ? { text: t, marks } : { text: t });
1095
+ return;
1096
+ }
1097
+ if (node.nodeType !== 1)
1098
+ return;
1099
+ const el = node;
1100
+ const tag = el.tagName.toLowerCase();
1101
+ if (tag === "br") {
1102
+ paras.push([]);
1103
+ return;
1104
+ }
1105
+ const add = (m) => marks.concat(m);
1106
+ let next = marks;
1107
+ const simple = simpleTagMark(tag);
1108
+ if (simple)
1109
+ next = add({ name: simple });
1110
+ else if (tag === "code") {
1111
+ paras[paras.length - 1].push({ text: _nullishCoalesce(el.textContent, () => ( "")), marks: add({ name: "code" }) });
1112
+ return;
1113
+ } else if (tag === "a")
1114
+ next = add({ name: "link", attrs: { url: _nullishCoalesce(el.getAttribute("href"), () => ( "")) } });
1115
+ else if (tag === "img") {
1116
+ const attrs = { url: _nullishCoalesce(el.getAttribute("src"), () => ( "")) };
1117
+ const w = el.getAttribute("width");
1118
+ const h = el.getAttribute("height");
1119
+ if (w != null && w !== "") attrs.w = Number(w);
1120
+ if (h != null && h !== "") attrs.h = Number(h);
1121
+ paras[paras.length - 1].push({ text: _nullishCoalesce(el.getAttribute("alt"), () => ( "")), marks: add({ name: "image", attrs }) });
1122
+ return;
1123
+ }
1124
+ el.childNodes.forEach((ch) => walk(ch, next));
1125
+ };
1126
+ cell.childNodes.forEach((ch) => walk(ch, []));
1127
+ return paras.map((text) => ({ type: "paragraph", children: text.length ? text : [{ text: "" }] }));
1128
+ }
1129
+ function parseCellStyle(style) {
1130
+ const out = {};
1131
+ for (const decl of style.split(";")) {
1132
+ const i = decl.indexOf(":");
1133
+ if (i < 0)
1134
+ continue;
1135
+ const prop = decl.slice(0, i).trim();
1136
+ const val = decl.slice(i + 1).trim();
1137
+ if (prop === "background" || prop === "background-color")
1138
+ out.bg = val;
1139
+ else if (prop === "border-color")
1140
+ out.border = val;
1141
+ }
1142
+ return out;
1143
+ }
1144
+ function htmlTableToAtom(html, s) {
1145
+ if (typeof DOMParser === "undefined")
1146
+ return null;
1147
+ const table = new DOMParser().parseFromString(html, "text/html").querySelector("table");
1148
+ if (!table)
1149
+ return null;
1150
+ const trs = Array.from(table.querySelectorAll("tr"));
1151
+ const cellsByRow = trs.map((tr) => Array.from(tr.children).filter((el) => el.tagName === "TD" || el.tagName === "TH"));
1152
+ const cols = cellsByRow.reduce((m, row) => Math.max(m, row.reduce((s2, c) => s2 + Math.max(1, Number(_nullishCoalesce(c.getAttribute("colspan"), () => ( 1)))), 0)), 0);
1153
+ const children = [];
1154
+ const owner = [];
1155
+ let rows = 0;
1156
+ const cs = (c) => Math.max(1, Number(_nullishCoalesce(c.getAttribute("colspan"), () => ( 1))));
1157
+ const rs = (c) => Math.max(1, Number(_nullishCoalesce(c.getAttribute("rowspan"), () => ( 1))));
1158
+ cellsByRow.forEach((row, r) => {
1159
+ let c = 0;
1160
+ for (const cell of row) {
1161
+ while (owner[r * cols + c]) c++;
1162
+ const colspan = Math.min(cs(cell), cols - c);
1163
+ const rowspan = rs(cell);
1164
+ for (let dr = 0; dr < rowspan; dr++) for (let dc = 0; dc < colspan; dc++) owner[(r + dr) * cols + (c + dc)] = true;
1165
+ const style = parseCellStyle(_nullishCoalesce(cell.getAttribute("style"), () => ( "")));
1166
+ const attrs2 = {};
1167
+ if (colspan > 1) attrs2.colspan = colspan;
1168
+ if (rowspan > 1) attrs2.rowspan = rowspan;
1169
+ if (style.bg) attrs2.bg = style.bg;
1170
+ if (style.border) attrs2.border = style.border;
1171
+ children.push({ type: "table_cell", ...Object.keys(attrs2).length ? { attrs: attrs2 } : {}, children: cellDomToParas(cell) });
1172
+ rows = Math.max(rows, r + rowspan);
1173
+ c += colspan;
1174
+ }
1175
+ });
1176
+ const attrs = { rows, cols, span: s };
1177
+ const fr = Number(_nullishCoalesce(table.getAttribute("data-freeze-rows"), () => ( 0)));
1178
+ const fc = Number(_nullishCoalesce(table.getAttribute("data-freeze-cols"), () => ( 0)));
1179
+ if (fr > 0) attrs.freezeRows = fr;
1180
+ if (fc > 0) attrs.freezeCols = fc;
1181
+ return { type: "table", attrs, children };
1182
+ }
1183
+ function paragraphToBlocks(children, md, s) {
1184
+ const imgAttrs = (n) => {
1185
+ if (n.type === "image")
1186
+ return { url: n.url, alt: _nullishCoalesce(n.alt, () => ( "")), title: _nullishCoalesce(n.title, () => ( void 0)) };
1187
+ if (n.type === "html" && n.value.trimStart().toLowerCase().startsWith("<img")) {
1188
+ const img = imgHtmlToMark(n.value);
1189
+ if (img)
1190
+ return { ...img.attrs, alt: img.alt };
1191
+ }
1192
+ return null;
1193
+ };
1194
+ const hasImg = children.some((c) => imgAttrs(c));
1195
+ if (!hasImg) {
1196
+ const para = { type: "paragraph", children: phrasingToNodes(children, md) };
1197
+ return [s ? { ...para, attrs: { span: s } } : para];
1198
+ }
1199
+ const out = [];
1200
+ let run = [];
1201
+ const flush = () => {
1202
+ if (run.length) {
1203
+ out.push({ type: "paragraph", children: phrasingToNodes(run, md) });
1204
+ run = [];
1205
+ }
1206
+ };
1207
+ for (const c of children) {
1208
+ const attrs = imgAttrs(c);
1209
+ if (attrs) {
1210
+ flush();
1211
+ out.push({ type: "image", attrs, children: [] });
1212
+ } else {
1213
+ run.push(c);
1214
+ }
1215
+ }
1216
+ flush();
1217
+ if (s && out.length)
1218
+ out[0] = { ...out[0], attrs: { ...out[0].attrs, span: s } };
1219
+ return out;
1220
+ }
1221
+ function alignBlockFromHtml(html) {
1222
+ if (typeof DOMParser === "undefined")
1223
+ return null;
1224
+ const body = new DOMParser().parseFromString(html, "text/html").body;
1225
+ if (body.children.length !== 1)
1226
+ return null;
1227
+ const el = body.children[0];
1228
+ const tag = el.tagName.toLowerCase();
1229
+ const isP = tag === "p";
1230
+ const isH = tag.length === 2 && tag[0] === "h" && tag[1] >= "1" && tag[1] <= "6";
1231
+ if (!isP && !isH)
1232
+ return null;
1233
+ const align = _optionalChain([el, 'access', _57 => _57.getAttribute, 'call', _58 => _58("style"), 'optionalAccess', _59 => _59.split, 'call', _60 => _60(";"), 'access', _61 => _61.map, 'call', _62 => _62((s) => s.trim()), 'access', _63 => _63.find, 'call', _64 => _64((s) => s.startsWith("text-align:")), 'optionalAccess', _65 => _65.slice, 'call', _66 => _66("text-align:".length), 'access', _67 => _67.trim, 'call', _68 => _68()]);
1234
+ if (!align)
1235
+ return null;
1236
+ const leaves2 = inlineHtmlToLeaves(el.innerHTML, []);
1237
+ if (!leaves2)
1238
+ return null;
1239
+ const children = leaves2.length ? leaves2 : [{ text: "" }];
1240
+ return isH ? { type: "heading", attrs: { depth: Number(tag[1]), align }, children } : { type: "paragraph", attrs: { align }, children };
1241
+ }
1242
+ function blockToNode(b, md) {
1243
+ const s = span(b);
1244
+ const withSpan2 = (n) => s ? { ...n, attrs: { ...n.attrs, span: s } } : n;
1245
+ switch (b.type) {
1246
+ case "heading":
1247
+ return withSpan2({ type: "heading", attrs: { depth: b.depth }, children: phrasingToNodes(b.children, md) });
1248
+ case "paragraph":
1249
+ return paragraphToBlocks(b.children, md, s);
1250
+ case "blockquote":
1251
+ return withSpan2({ type: "quote", children: b.children.flatMap((c) => blockToNode(c, md)) });
1252
+ case "list":
1253
+ return withSpan2({ type: "list", attrs: { ordered: !!b.ordered, start: _nullishCoalesce(b.start, () => ( void 0)) }, children: b.children.flatMap((c) => blockToNode(c, md)) });
1254
+ case "listItem":
1255
+ return withSpan2({ type: "list_item", attrs: { checked: _nullishCoalesce(b.checked, () => ( void 0)) }, children: b.children.flatMap((c) => blockToNode(c, md)) });
1256
+ case "code":
1257
+ return withSpan2({ type: "code", attrs: { lang: _nullishCoalesce(b.lang, () => ( void 0)), meta: _nullishCoalesce(b.meta, () => ( void 0)) }, children: [{ text: b.value }] });
1258
+ case "table":
1259
+ return tableToAtom(b, md);
1260
+ case "html": {
1261
+ const trimmed = b.value.trimStart().toLowerCase();
1262
+ if (trimmed.startsWith("<table")) {
1263
+ const atom = htmlTableToAtom(b.value, s);
1264
+ if (atom)
1265
+ return atom;
1266
+ }
1267
+ if (trimmed.startsWith("<figure")) {
1268
+ const fig = figureFromHtml(b.value);
1269
+ if (fig)
1270
+ return withSpan2(fig);
1271
+ }
1272
+ if (trimmed.startsWith("<img")) {
1273
+ const img = imgHtmlToMark(b.value);
1274
+ if (img)
1275
+ return withSpan2({ type: "image", attrs: { ...img.attrs, alt: img.alt }, children: [] });
1276
+ }
1277
+ if (trimmed.startsWith("<div") && b.value.includes("data-embed")) {
1278
+ const emb = embedFromHtml(b.value);
1279
+ if (emb)
1280
+ return withSpan2(emb);
1281
+ }
1282
+ if (trimmed.startsWith("<span") && b.value.includes("data-math")) {
1283
+ const m = mathFromHtml(b.value);
1284
+ if (m)
1285
+ return withSpan2({ type: "paragraph", children: [m] });
1286
+ }
1287
+ if (trimmed.startsWith("<p") || trimmed.length >= 2 && trimmed[0] === "<" && trimmed[1] === "h") {
1288
+ const aligned = alignBlockFromHtml(b.value);
1289
+ if (aligned)
1290
+ return withSpan2(aligned);
1291
+ }
1292
+ return withSpan2({ type: "raw", attrs: { mdType: b.type }, children: [{ text: b.value }] });
1293
+ }
1294
+ default:
1295
+ return withSpan2({ type: "raw", attrs: { mdType: b.type }, children: [{ text: "value" in b && typeof b.value === "string" ? b.value : "" }] });
1296
+ }
1297
+ }
1298
+ function mdToDoc(md) {
1299
+ const tree = _mdastutilfrommarkdown.fromMarkdown.call(void 0, md, mdExt);
1300
+ return { type: "doc", children: stitchContainers(tree.children, md).map((b, i) => ({ ...b, id: `b${i}` })) };
1301
+ }
1302
+ function langFromClass(cls) {
1303
+ if (!cls)
1304
+ return void 0;
1305
+ for (const part of cls.split(" ")) {
1306
+ if (part.startsWith("language-") && part.length > 9)
1307
+ return part.slice(9);
1308
+ if (part.startsWith("lang-") && part.length > 5)
1309
+ return part.slice(5);
1310
+ }
1311
+ return void 0;
1312
+ }
1313
+ function styleAlign(el) {
1314
+ const align = _optionalChain([el, 'access', _69 => _69.getAttribute, 'call', _70 => _70("style"), 'optionalAccess', _71 => _71.split, 'call', _72 => _72(";"), 'access', _73 => _73.map, 'call', _74 => _74((s) => s.trim()), 'access', _75 => _75.find, 'call', _76 => _76((s) => s.startsWith("text-align:")), 'optionalAccess', _77 => _77.slice, 'call', _78 => _78("text-align:".length), 'access', _79 => _79.trim, 'call', _80 => _80()]);
1315
+ return align === "center" || align === "right" || align === "justify" ? align : void 0;
1316
+ }
1317
+ function elevateInlineImages(block) {
1318
+ const out = [];
1319
+ let buf = [];
1320
+ const flush = () => {
1321
+ if (!buf.length)
1322
+ return;
1323
+ out.push({ ...block, children: buf });
1324
+ buf = [];
1325
+ };
1326
+ for (const c of block.children) {
1327
+ if (isText(c)) {
1328
+ const im = _optionalChain([c, 'access', _81 => _81.marks, 'optionalAccess', _82 => _82.find, 'call', _83 => _83((m) => m.name === "image")]);
1329
+ if (im) {
1330
+ flush();
1331
+ out.push({ type: "image", attrs: { ...im.attrs, alt: c.text }, children: [] });
1332
+ continue;
1333
+ }
1334
+ }
1335
+ buf.push(c);
1336
+ }
1337
+ flush();
1338
+ return out.length ? out : [{ ...block, children: [{ text: "" }] }];
1339
+ }
1340
+ function isBlockishTag(tag) {
1341
+ return tag === "p" || tag === "div" || tag === "section" || tag === "article" || tag === "main" || tag === "ul" || tag === "ol" || tag === "li" || tag === "blockquote" || tag === "pre" || tag === "table" || tag === "hr" || tag === "figure" || tag === "img" || tag === "h1" || tag === "h2" || tag === "h3" || tag === "h4" || tag === "h5" || tag === "h6";
1342
+ }
1343
+ function domNodesToBlocks(nodes) {
1344
+ const out = [];
1345
+ for (const n of nodes) {
1346
+ if (n.nodeType === 3) {
1347
+ const t = (_nullishCoalesce(n.textContent, () => ( ""))).split("\xA0").join(" ");
1348
+ if (!t.trim())
1349
+ continue;
1350
+ out.push({ type: "paragraph", children: [{ text: t }] });
1351
+ continue;
1352
+ }
1353
+ if (n.nodeType !== 1)
1354
+ continue;
1355
+ const el = n;
1356
+ const tag = el.tagName.toLowerCase();
1357
+ if (tag === "meta" || tag === "style" || tag === "script" || tag === "link" || tag === "title" || tag === "head")
1358
+ continue;
1359
+ if (tag === "br") {
1360
+ out.push({ type: "paragraph", children: [{ text: "" }] });
1361
+ continue;
1362
+ }
1363
+ if (tag === "p") {
1364
+ const align = styleAlign(el);
1365
+ const kids = domInlineToNodes(el);
1366
+ const b = align ? { type: "paragraph", attrs: { align }, children: kids } : { type: "paragraph", children: kids };
1367
+ out.push(...elevateInlineImages(b));
1368
+ continue;
1369
+ }
1370
+ if (tag.length === 2 && tag[0] === "h" && tag[1] >= "1" && tag[1] <= "6") {
1371
+ const attrs = { depth: Number(tag[1]) };
1372
+ const align = styleAlign(el);
1373
+ if (align)
1374
+ attrs.align = align;
1375
+ out.push(...elevateInlineImages({ type: "heading", attrs, children: domInlineToNodes(el) }));
1376
+ continue;
1377
+ }
1378
+ if (tag === "ul" || tag === "ol") {
1379
+ const items = Array.from(el.children).filter((c) => c.tagName.toLowerCase() === "li");
1380
+ const children = items.map((li) => {
1381
+ const inner = domNodesToBlocks(Array.from(li.childNodes));
1382
+ const body = inner.length ? inner : cellDomToParas(li);
1383
+ return { type: "list_item", children: body.length ? body : [{ type: "paragraph", children: [{ text: "" }] }] };
1384
+ });
1385
+ out.push({ type: "list", attrs: { ordered: tag === "ol" }, children });
1386
+ continue;
1387
+ }
1388
+ if (tag === "blockquote") {
1389
+ const inner = domNodesToBlocks(Array.from(el.childNodes));
1390
+ out.push({ type: "quote", children: inner.length ? inner : [{ type: "paragraph", children: [{ text: "" }] }] });
1391
+ continue;
1392
+ }
1393
+ if (tag === "pre") {
1394
+ const codeEl = _nullishCoalesce(el.querySelector("code"), () => ( el));
1395
+ const lang = langFromClass(codeEl.getAttribute("class"));
1396
+ const text = _nullishCoalesce(codeEl.textContent, () => ( ""));
1397
+ out.push({ type: "code", attrs: lang ? { lang } : {}, children: [{ text }] });
1398
+ continue;
1399
+ }
1400
+ if (tag === "table") {
1401
+ const atom = htmlTableToAtom(el.outerHTML, void 0);
1402
+ if (atom)
1403
+ out.push(atom);
1404
+ continue;
1405
+ }
1406
+ if (tag === "hr") {
1407
+ out.push({ type: "raw", attrs: { mdType: "thematicBreak" }, children: [{ text: "" }] });
1408
+ continue;
1409
+ }
1410
+ if (tag === "figure") {
1411
+ const fig = figureFromHtml(el.outerHTML);
1412
+ if (fig)
1413
+ out.push(fig);
1414
+ continue;
1415
+ }
1416
+ if (tag === "img") {
1417
+ const mark = imgHtmlToMark(el.outerHTML);
1418
+ if (mark)
1419
+ out.push({ type: "image", attrs: { ...mark.attrs, alt: mark.alt }, children: [] });
1420
+ continue;
1421
+ }
1422
+ if (tag === "div" && el.hasAttribute("data-embed")) {
1423
+ const emb = embedFromHtml(el.outerHTML);
1424
+ if (emb)
1425
+ out.push(emb);
1426
+ continue;
1427
+ }
1428
+ if (tag === "span" && el.hasAttribute("data-math")) {
1429
+ const latex = _nullishCoalesce(_nullishCoalesce(el.getAttribute("data-latex"), () => ( el.textContent)), () => ( ""));
1430
+ const display = el.getAttribute("data-display") === "block" ? "block" : "inline";
1431
+ out.push({ type: "paragraph", children: [{ type: "math", attrs: { latex, display }, children: [] }] });
1432
+ continue;
1433
+ }
1434
+ if (tag === "div" || tag === "section" || tag === "article" || tag === "main" || tag === "body" || Array.from(el.children).some((c) => isBlockishTag(c.tagName.toLowerCase()))) {
1435
+ out.push(...domNodesToBlocks(Array.from(el.childNodes)));
1436
+ continue;
1437
+ }
1438
+ const paras = cellDomToParas(el);
1439
+ for (const para of paras) {
1440
+ if (para.children.length === 1 && isText(para.children[0]) && !para.children[0].text.trim() && !para.children[0].marks)
1441
+ continue;
1442
+ out.push(...elevateInlineImages(para));
1443
+ }
1444
+ }
1445
+ return out;
1446
+ }
1447
+ function htmlToBlocks(html) {
1448
+ if (typeof DOMParser === "undefined" || !html.trim())
1449
+ return null;
1450
+ const body = new DOMParser().parseFromString(html, "text/html").body;
1451
+ const blocks = domNodesToBlocks(Array.from(body.childNodes));
1452
+ return blocks.length ? blocks : null;
1453
+ }
1454
+ function isRichHtmlBlocks(blocks) {
1455
+ if (blocks.length !== 1)
1456
+ return true;
1457
+ const b = blocks[0];
1458
+ if (b.type !== "paragraph" && b.type !== "heading")
1459
+ return true;
1460
+ return b.children.some((c) => !isText(c) || (_nullishCoalesce(_optionalChain([c, 'access', _84 => _84.marks, 'optionalAccess', _85 => _85.length]), () => ( 0))) > 0 || c.text.includes("\n"));
1461
+ }
1462
+ var htmlOnlyMarks = /* @__PURE__ */ new Set(["underline", "highlight", "superscript", "subscript", "textStyle", "comment"]);
1463
+ function textToPhrasing(leaf) {
1464
+ if (_optionalChain([leaf, 'access', _86 => _86.marks, 'optionalAccess', _87 => _87.some, 'call', _88 => _88((m) => htmlOnlyMarks.has(m.name))]))
1465
+ return { type: "html", value: leafToHtml(leaf) };
1466
+ let node = { type: "text", value: leaf.text };
1467
+ for (const m of _nullishCoalesce(leaf.marks, () => ( []))) {
1468
+ switch (m.name) {
1469
+ case "bold":
1470
+ node = { type: "strong", children: [node] };
1471
+ break;
1472
+ case "italic":
1473
+ node = { type: "emphasis", children: [node] };
1474
+ break;
1475
+ case "strike":
1476
+ node = { type: "delete", children: [node] };
1477
+ break;
1478
+ case "code":
1479
+ node = { type: "inlineCode", value: leaf.text };
1480
+ break;
1481
+ case "html":
1482
+ node = { type: "html", value: leaf.text };
1483
+ break;
1484
+ case "image":
1485
+ node = _optionalChain([m, 'access', _89 => _89.attrs, 'optionalAccess', _90 => _90.w]) != null || _optionalChain([m, 'access', _91 => _91.attrs, 'optionalAccess', _92 => _92.h]) != null ? { type: "html", value: imgHtml(String(_nullishCoalesce(_optionalChain([m, 'access', _93 => _93.attrs, 'optionalAccess', _94 => _94.url]), () => ( ""))), leaf.text, m.attrs) } : { type: "image", url: String(_nullishCoalesce(_optionalChain([m, 'access', _95 => _95.attrs, 'optionalAccess', _96 => _96.url]), () => ( ""))), title: _nullishCoalesce(_optionalChain([m, 'access', _97 => _97.attrs, 'optionalAccess', _98 => _98.title]), () => ( null)), alt: leaf.text };
1486
+ break;
1487
+ case "link":
1488
+ node = { type: "link", url: String(_nullishCoalesce(_optionalChain([m, 'access', _99 => _99.attrs, 'optionalAccess', _100 => _100.url]), () => ( ""))), title: _nullishCoalesce(_optionalChain([m, 'access', _101 => _101.attrs, 'optionalAccess', _102 => _102.title]), () => ( null)), children: [node] };
1489
+ break;
1490
+ }
1491
+ }
1492
+ return node;
1493
+ }
1494
+ var leaves = (n) => n.children.filter(isText);
1495
+ function mentionHtml(n) {
1496
+ const id = String(_nullishCoalesce(_optionalChain([n, 'access', _103 => _103.attrs, 'optionalAccess', _104 => _104.id]), () => ( "")));
1497
+ const label = typeof _optionalChain([n, 'access', _105 => _105.attrs, 'optionalAccess', _106 => _106.label]) === "string" ? n.attrs.label : id;
1498
+ const kind = typeof _optionalChain([n, 'access', _107 => _107.attrs, 'optionalAccess', _108 => _108.kind]) === "string" && n.attrs.kind !== "person" ? ` data-kind="${escHtml(n.attrs.kind)}"` : "";
1499
+ const date = typeof _optionalChain([n, 'access', _109 => _109.attrs, 'optionalAccess', _110 => _110.date]) === "string" ? ` data-date="${escHtml(n.attrs.date)}"` : "";
1500
+ const glyph = _optionalChain([n, 'access', _111 => _111.attrs, 'optionalAccess', _112 => _112.kind]) === "date" ? "" : "@";
1501
+ return `<span data-mention data-id="${escHtml(id)}" data-label="${escHtml(label)}"${kind}${date}>${glyph}${escHtml(label)}</span>`;
1502
+ }
1503
+ function mathHtml(n) {
1504
+ const latex = String(_nullishCoalesce(_optionalChain([n, 'access', _113 => _113.attrs, 'optionalAccess', _114 => _114.latex]), () => ( "")));
1505
+ const display = _optionalChain([n, 'access', _115 => _115.attrs, 'optionalAccess', _116 => _116.display]) === "block" ? "block" : "inline";
1506
+ const wrap = display === "block" ? "$$" : "$";
1507
+ return `<span data-math data-latex="${escHtml(latex)}" data-display="${display}">${wrap}${escHtml(latex)}${wrap}</span>`;
1508
+ }
1509
+ function embedHtml(n) {
1510
+ const kind = String(_nullishCoalesce(_optionalChain([n, 'access', _117 => _117.attrs, 'optionalAccess', _118 => _118.kind]), () => ( "")));
1511
+ const src = String(_nullishCoalesce(_optionalChain([n, 'access', _119 => _119.attrs, 'optionalAccess', _120 => _120.src]), () => ( "")));
1512
+ const title = typeof _optionalChain([n, 'access', _121 => _121.attrs, 'optionalAccess', _122 => _122.title]) === "string" ? ` data-title="${escHtml(n.attrs.title)}"` : "";
1513
+ const name = typeof _optionalChain([n, 'access', _123 => _123.attrs, 'optionalAccess', _124 => _124.name]) === "string" ? ` data-name="${escHtml(n.attrs.name)}"` : "";
1514
+ return `<div data-embed data-kind="${escHtml(kind)}" data-src="${escHtml(src)}"${title}${name}></div>`;
1515
+ }
1516
+ function phrasingChildren(n) {
1517
+ return n.children.flatMap((c) => {
1518
+ if (isText(c))
1519
+ return [textToPhrasing(c)];
1520
+ if (isInlineAtom(c)) {
1521
+ if (c.type === "hard_break")
1522
+ return [{ type: "break" }];
1523
+ if (c.type === "math")
1524
+ return [{ type: "html", value: mathHtml(c) }];
1525
+ return [{ type: "html", value: mentionHtml(c) }];
1526
+ }
1527
+ return [];
1528
+ });
1529
+ }
1530
+ function cellPhrasing(cell) {
1531
+ const paras = cell.children.filter(isElement);
1532
+ const src = paras.length ? paras : [cell];
1533
+ const out = [];
1534
+ src.forEach((p, i) => {
1535
+ if (i > 0)
1536
+ out.push({ type: "break" });
1537
+ out.push(...leaves(p).map(textToPhrasing));
1538
+ });
1539
+ return out;
1540
+ }
1541
+ function tableToMdast(n) {
1542
+ const cols = Number(_nullishCoalesce(_optionalChain([n, 'access', _125 => _125.attrs, 'optionalAccess', _126 => _126.cols]), () => ( 1)));
1543
+ const align = Array.isArray(_optionalChain([n, 'access', _127 => _127.attrs, 'optionalAccess', _128 => _128.align])) ? n.attrs.align : void 0;
1544
+ const cells = n.children.filter(isElement);
1545
+ const rows = [];
1546
+ for (let r = 0; r * cols < cells.length; r++) {
1547
+ const rowCells = cells.slice(r * cols, (r + 1) * cols).map((cell) => ({
1548
+ type: "tableCell",
1549
+ children: cellPhrasing(cell)
1550
+ }));
1551
+ rows.push({ type: "tableRow", children: rowCells });
1552
+ }
1553
+ return { type: "table", align, children: rows };
1554
+ }
1555
+ function escHtml(s) {
1556
+ let out = "";
1557
+ for (const ch of s) out += ch === "&" ? "&amp;" : ch === "<" ? "&lt;" : ch === ">" ? "&gt;" : ch;
1558
+ return out;
1559
+ }
1560
+ function imgHtml(url, alt, attrs, align = "") {
1561
+ const w = _optionalChain([attrs, 'optionalAccess', _129 => _129.w]);
1562
+ const h = _optionalChain([attrs, 'optionalAccess', _130 => _130.h]);
1563
+ const title = _optionalChain([attrs, 'optionalAccess', _131 => _131.title]);
1564
+ const style = align === "center" ? "display:block;margin-left:auto;margin-right:auto" : align === "right" ? "display:block;margin-left:auto" : "";
1565
+ return `<img src="${escHtml(url)}" alt="${escHtml(alt)}"` + (title != null ? ` title="${escHtml(String(title))}"` : "") + (w != null ? ` width="${Number(w)}"` : "") + (h != null ? ` height="${Number(h)}"` : "") + (style ? ` style="${style}"` : "") + ">";
1566
+ }
1567
+ function figureHtml(url, alt, attrs, caption, align = "") {
1568
+ const fstyle = align === "center" ? ' style="text-align:center"' : align === "right" ? ' style="text-align:right"' : "";
1569
+ return `<figure${fstyle}>${imgHtml(url, alt, attrs)}<figcaption>${escHtml(caption)}</figcaption></figure>`;
1570
+ }
1571
+ function textStyleStyle(attrs) {
1572
+ if (!attrs)
1573
+ return "";
1574
+ const safe = (v) => {
1575
+ let out = "";
1576
+ for (const ch of v) {
1577
+ if (ch === ";" || ch === '"' || ch === "'" || ch === "<" || ch === ">")
1578
+ continue;
1579
+ out += ch;
1580
+ }
1581
+ return out.trim();
1582
+ };
1583
+ const parts = [];
1584
+ if (typeof attrs.color === "string" && attrs.color)
1585
+ parts.push(`color:${safe(attrs.color)}`);
1586
+ if (typeof attrs.backgroundColor === "string" && attrs.backgroundColor)
1587
+ parts.push(`background-color:${safe(attrs.backgroundColor)}`);
1588
+ if (typeof attrs.fontFamily === "string" && attrs.fontFamily)
1589
+ parts.push(`font-family:${safe(attrs.fontFamily)}`);
1590
+ if (typeof attrs.fontSize === "string" && attrs.fontSize)
1591
+ parts.push(`font-size:${safe(attrs.fontSize)}`);
1592
+ return parts.join(";");
1593
+ }
1594
+ function styleToTextStyleAttrs(style) {
1595
+ if (!style)
1596
+ return null;
1597
+ const out = {};
1598
+ for (const part of style.split(";")) {
1599
+ const i = part.indexOf(":");
1600
+ if (i < 0)
1601
+ continue;
1602
+ const prop = part.slice(0, i).trim().toLowerCase();
1603
+ const val = part.slice(i + 1).trim();
1604
+ if (!val)
1605
+ continue;
1606
+ if (prop === "color")
1607
+ out.color = val;
1608
+ else if (prop === "background-color" || prop === "background")
1609
+ out.backgroundColor = val;
1610
+ else if (prop === "font-family")
1611
+ out.fontFamily = val;
1612
+ else if (prop === "font-size")
1613
+ out.fontSize = val;
1614
+ }
1615
+ return Object.keys(out).length ? out : null;
1616
+ }
1617
+ function leafToHtml(leaf) {
1618
+ let s = escHtml(leaf.text);
1619
+ for (const m of _nullishCoalesce(leaf.marks, () => ( []))) {
1620
+ switch (m.name) {
1621
+ case "bold":
1622
+ s = `<strong>${s}</strong>`;
1623
+ break;
1624
+ case "italic":
1625
+ s = `<em>${s}</em>`;
1626
+ break;
1627
+ case "strike":
1628
+ s = `<del>${s}</del>`;
1629
+ break;
1630
+ case "code":
1631
+ s = `<code>${escHtml(leaf.text)}</code>`;
1632
+ break;
1633
+ case "underline":
1634
+ s = `<u>${s}</u>`;
1635
+ break;
1636
+ case "highlight":
1637
+ s = `<mark>${s}</mark>`;
1638
+ break;
1639
+ case "superscript":
1640
+ s = `<sup>${s}</sup>`;
1641
+ break;
1642
+ case "subscript":
1643
+ s = `<sub>${s}</sub>`;
1644
+ break;
1645
+ case "textStyle": {
1646
+ const st = textStyleStyle(m.attrs);
1647
+ s = st ? `<span data-mark="textStyle" style="${escHtml(st)}">${s}</span>` : s;
1648
+ break;
1649
+ }
1650
+ case "comment": {
1651
+ const cid = escHtml(String(_nullishCoalesce(_optionalChain([m, 'access', _132 => _132.attrs, 'optionalAccess', _133 => _133.id]), () => ( ""))));
1652
+ s = `<span data-comment="${cid}">${s}</span>`;
1653
+ break;
1654
+ }
1655
+ case "html":
1656
+ s = leaf.text;
1657
+ break;
1658
+ // 逐字 HTML 叶:不转义
1659
+ case "link":
1660
+ s = `<a href="${escHtml(String(_nullishCoalesce(_optionalChain([m, 'access', _134 => _134.attrs, 'optionalAccess', _135 => _135.url]), () => ( ""))))}">${s}</a>`;
1661
+ break;
1662
+ case "image":
1663
+ s = imgHtml(String(_nullishCoalesce(_optionalChain([m, 'access', _136 => _136.attrs, 'optionalAccess', _137 => _137.url]), () => ( ""))), leaf.text, m.attrs);
1664
+ break;
1665
+ }
1666
+ }
1667
+ return s;
1668
+ }
1669
+ function cellInnerHtml(cell) {
1670
+ const paras = cell.children.filter(isElement);
1671
+ const src = paras.length ? paras : [cell];
1672
+ return src.map((p) => leaves(p).map(leafToHtml).join("")).join("<br>");
1673
+ }
1674
+ function tableHasExtras(n) {
1675
+ if (Number(_nullishCoalesce(_optionalChain([n, 'access', _138 => _138.attrs, 'optionalAccess', _139 => _139.freezeRows]), () => ( 0))) > 0 || Number(_nullishCoalesce(_optionalChain([n, 'access', _140 => _140.attrs, 'optionalAccess', _141 => _141.freezeCols]), () => ( 0))) > 0)
1676
+ return true;
1677
+ return n.children.filter(isElement).some((c) => colspanOf(c) > 1 || rowspanOf(c) > 1 || _optionalChain([c, 'access', _142 => _142.attrs, 'optionalAccess', _143 => _143.bg]) != null || _optionalChain([c, 'access', _144 => _144.attrs, 'optionalAccess', _145 => _145.border]) != null || c.children.filter(isElement).length > 1);
1678
+ }
1679
+ function tableToHtml(n) {
1680
+ const grid = buildGrid(n);
1681
+ const align = Array.isArray(_optionalChain([n, 'access', _146 => _146.attrs, 'optionalAccess', _147 => _147.align])) ? n.attrs.align : null;
1682
+ const freezeRows = Number(_nullishCoalesce(_optionalChain([n, 'access', _148 => _148.attrs, 'optionalAccess', _149 => _149.freezeRows]), () => ( 0)));
1683
+ const freezeCols = Number(_nullishCoalesce(_optionalChain([n, 'access', _150 => _150.attrs, 'optionalAccess', _151 => _151.freezeCols]), () => ( 0)));
1684
+ const rowCells = /* @__PURE__ */ new Map();
1685
+ for (const idx of grid.anchors) {
1686
+ const cell = n.children[idx];
1687
+ const m = grid.cellOf(idx);
1688
+ const a = _optionalChain([align, 'optionalAccess', _152 => _152[m.c]]);
1689
+ const bg = _optionalChain([cell, 'access', _153 => _153.attrs, 'optionalAccess', _154 => _154.bg]);
1690
+ const border = _optionalChain([cell, 'access', _155 => _155.attrs, 'optionalAccess', _156 => _156.border]);
1691
+ const styles = [a && `text-align:${a}`, bg && `background:${bg}`, border && `border-color:${border}`].filter(Boolean).join(";");
1692
+ const attrs = [
1693
+ m.colspan > 1 && ` colspan="${m.colspan}"`,
1694
+ m.rowspan > 1 && ` rowspan="${m.rowspan}"`,
1695
+ styles && ` style="${styles}"`
1696
+ ].filter(Boolean).join("");
1697
+ const tag = m.r === 0 ? "th" : "td";
1698
+ const html = `<${tag}${attrs}>${cellInnerHtml(cell)}</${tag}>`;
1699
+ const arr = _nullishCoalesce(rowCells.get(m.r), () => ( []));
1700
+ arr.push(html);
1701
+ rowCells.set(m.r, arr);
1702
+ }
1703
+ const trs = Array.from(rowCells.keys()).sort((a, b) => a - b).map((r) => `<tr>${rowCells.get(r).join("")}</tr>`);
1704
+ const tableAttrs = [freezeRows > 0 && ` data-freeze-rows="${freezeRows}"`, freezeCols > 0 && ` data-freeze-cols="${freezeCols}"`].filter(Boolean).join("");
1705
+ return `<table${tableAttrs}>${trs.join("")}</table>`;
1706
+ }
1707
+ function containerToHtml(openAttrs, children) {
1708
+ const inner = children.filter(isElement).map((c) => _mdastutiltomarkdown.toMarkdown.call(void 0, { type: "root", children: [nodeToMdast(c)] }, { extensions: [_mdastutilgfm.gfmToMarkdown.call(void 0, )] }).trimEnd()).join("\n\n");
1709
+ return `<div ${openAttrs}>
1710
+
1711
+ ${inner}
1712
+
1713
+ </div>`;
1714
+ }
1715
+ function calloutToHtml(n) {
1716
+ const variant = typeof _optionalChain([n, 'access', _157 => _157.attrs, 'optionalAccess', _158 => _158.variant]) === "string" ? n.attrs.variant : "info";
1717
+ return containerToHtml(`data-callout data-variant="${escHtml(variant)}"`, n.children);
1718
+ }
1719
+ function containerOpenKind(b) {
1720
+ if (b.type !== "html" || !b.value.trimStart().toLowerCase().startsWith("<div"))
1721
+ return null;
1722
+ if (b.value.includes("data-callout"))
1723
+ return "callout";
1724
+ return null;
1725
+ }
1726
+ function isDivOpen(b) {
1727
+ return b.type === "html" && b.value.trimStart().toLowerCase().startsWith("<div");
1728
+ }
1729
+ function isDivClose(b) {
1730
+ return b.type === "html" && b.value.trim().toLowerCase() === "</div>";
1731
+ }
1732
+ function readOpenAttr(openTag, sel, attr, fallback) {
1733
+ if (typeof DOMParser === "undefined")
1734
+ return fallback;
1735
+ const div = new DOMParser().parseFromString(`${openTag}</div>`, "text/html").querySelector(sel);
1736
+ return _nullishCoalesce(_optionalChain([div, 'optionalAccess', _159 => _159.getAttribute, 'call', _160 => _160(attr)]), () => ( fallback));
1737
+ }
1738
+ function stitchContainers(blocks, md) {
1739
+ const out = [];
1740
+ for (let i = 0; i < blocks.length; i++) {
1741
+ const b = blocks[i];
1742
+ const kind = containerOpenKind(b);
1743
+ if (!kind) {
1744
+ out.push(...[blockToNode(b, md)].flat());
1745
+ continue;
1746
+ }
1747
+ let depth = 1;
1748
+ let j = i + 1;
1749
+ for (; j < blocks.length; j++) {
1750
+ if (isDivClose(blocks[j]))
1751
+ depth--;
1752
+ else if (isDivOpen(blocks[j]))
1753
+ depth++;
1754
+ if (depth === 0)
1755
+ break;
1756
+ }
1757
+ if (j >= blocks.length) {
1758
+ out.push(...[blockToNode(b, md)].flat());
1759
+ continue;
1760
+ }
1761
+ const inner = stitchContainers(blocks.slice(i + 1, j), md);
1762
+ const s = span(b);
1763
+ const tag = b.value;
1764
+ const children = inner.length ? inner : [{ type: "paragraph", children: [{ text: "" }] }];
1765
+ out.push({ type: "callout", attrs: { variant: readOpenAttr(tag, "div[data-callout]", "data-variant", "info"), span: s }, children });
1766
+ i = j;
1767
+ }
1768
+ return out;
1769
+ }
1770
+ function nodeToMdast(n) {
1771
+ switch (n.type) {
1772
+ case "heading": {
1773
+ const depth = _nullishCoalesce(_optionalChain([n, 'access', _161 => _161.attrs, 'optionalAccess', _162 => _162.depth]), () => ( 1));
1774
+ const align = _optionalChain([n, 'access', _163 => _163.attrs, 'optionalAccess', _164 => _164.align]);
1775
+ if (align && align !== "left")
1776
+ return { type: "html", value: `<h${depth} style="text-align:${align}">${leaves(n).map(leafToHtml).join("")}</h${depth}>` };
1777
+ return { type: "heading", depth, children: phrasingChildren(n) };
1778
+ }
1779
+ case "paragraph": {
1780
+ const align = _optionalChain([n, 'access', _165 => _165.attrs, 'optionalAccess', _166 => _166.align]);
1781
+ if (align && align !== "left")
1782
+ return { type: "html", value: `<p style="text-align:${align}">${leaves(n).map(leafToHtml).join("")}</p>` };
1783
+ return { type: "paragraph", children: phrasingChildren(n) };
1784
+ }
1785
+ case "quote":
1786
+ return { type: "blockquote", children: n.children.filter(isElement).map(nodeToMdast) };
1787
+ case "callout":
1788
+ return { type: "html", value: calloutToHtml(n) };
1789
+ case "list":
1790
+ return { type: "list", ordered: !!_optionalChain([n, 'access', _167 => _167.attrs, 'optionalAccess', _168 => _168.ordered]), start: _nullishCoalesce(_optionalChain([n, 'access', _169 => _169.attrs, 'optionalAccess', _170 => _170.start]), () => ( null)), children: n.children.filter(isElement).map(nodeToMdast) };
1791
+ case "list_item":
1792
+ return { type: "listItem", checked: _nullishCoalesce(_optionalChain([n, 'access', _171 => _171.attrs, 'optionalAccess', _172 => _172.checked]), () => ( null)), children: n.children.filter(isElement).map(nodeToMdast) };
1793
+ case "code":
1794
+ return { type: "code", lang: _nullishCoalesce(_optionalChain([n, 'access', _173 => _173.attrs, 'optionalAccess', _174 => _174.lang]), () => ( null)), meta: _nullishCoalesce(_optionalChain([n, 'access', _175 => _175.attrs, 'optionalAccess', _176 => _176.meta]), () => ( null)), value: _nullishCoalesce(_optionalChain([leaves, 'call', _177 => _177(n), 'access', _178 => _178[0], 'optionalAccess', _179 => _179.text]), () => ( "")) };
1795
+ case "table":
1796
+ return tableHasExtras(n) ? { type: "html", value: tableToHtml(n) } : tableToMdast(n);
1797
+ case "image": {
1798
+ const a = _nullishCoalesce(n.attrs, () => ( {}));
1799
+ const url = String(_nullishCoalesce(a.url, () => ( "")));
1800
+ const alt = String(_nullishCoalesce(a.alt, () => ( "")));
1801
+ const caption = typeof a.caption === "string" ? a.caption : "";
1802
+ const align = a.align === "center" || a.align === "right" ? a.align : "";
1803
+ if (caption)
1804
+ return { type: "html", value: figureHtml(url, alt, a, caption, align) };
1805
+ if (a.w != null || a.h != null || align)
1806
+ return { type: "html", value: imgHtml(url, alt, a, align) };
1807
+ return { type: "paragraph", children: [{ type: "image", url, title: _nullishCoalesce(a.title, () => ( null)), alt }] };
1808
+ }
1809
+ case "embed":
1810
+ return { type: "html", value: embedHtml(n) };
1811
+ case "raw": {
1812
+ const raw = _nullishCoalesce(_optionalChain([leaves, 'call', _180 => _180(n), 'access', _181 => _181[0], 'optionalAccess', _182 => _182.text]), () => ( ""));
1813
+ return { type: "html", value: raw };
1814
+ }
1815
+ default:
1816
+ return { type: "paragraph", children: leaves(n).map(textToPhrasing) };
1817
+ }
1818
+ }
1819
+ function eq(a, b) {
1820
+ if (a === b)
1821
+ return true;
1822
+ if (typeof a !== "object" || typeof b !== "object" || !a || !b)
1823
+ return false;
1824
+ if (Array.isArray(a) || Array.isArray(b))
1825
+ return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((x, i) => eq(x, b[i]));
1826
+ const ig = (k) => k === "span" || k === "id";
1827
+ const ak = Object.keys(a).filter((k) => !ig(k) && a[k] !== void 0);
1828
+ const bk = Object.keys(b).filter((k) => !ig(k) && b[k] !== void 0);
1829
+ return ak.length === bk.length && ak.every((k) => eq(a[k], b[k]));
1830
+ }
1831
+ function clean(block, srcMd) {
1832
+ const s = _optionalChain([block, 'access', _183 => _183.attrs, 'optionalAccess', _184 => _184.span]);
1833
+ if (!s)
1834
+ return false;
1835
+ const reparsed = mdToDoc(srcMd.slice(s[0], s[1])).children[0];
1836
+ return !!reparsed && !isText(reparsed) && eq(block, reparsed);
1837
+ }
1838
+ var isOpaqueBlock = (n) => !isText(n) && (n.type === "table" || n.type === "image" || n.type === "embed" || n.type === "raw" && _optionalChain([n, 'access', _185 => _185.attrs, 'optionalAccess', _186 => _186.mdType]) === "thematicBreak");
1839
+ var isSynthGapPara = (n) => !isText(n) && n.type === "paragraph" && !_optionalChain([n, 'access', _187 => _187.attrs, 'optionalAccess', _188 => _188.span]) && n.children.length === 1 && isText(n.children[0]) && n.children[0].text === "";
1840
+ function trimSynthGapPara(children) {
1841
+ return children.filter((n, i) => {
1842
+ if (!isSynthGapPara(n))
1843
+ return true;
1844
+ const prev = children[i - 1];
1845
+ const next = children[i + 1];
1846
+ return !(prev && isOpaqueBlock(prev) || next && isOpaqueBlock(next));
1847
+ });
1848
+ }
1849
+ function docToMd(doc, srcMd) {
1850
+ let out = "";
1851
+ let cursor = 0;
1852
+ const blocks = trimSynthGapPara(doc.children);
1853
+ for (const block of blocks) {
1854
+ if (isText(block))
1855
+ continue;
1856
+ const s = _optionalChain([block, 'access', _189 => _189.attrs, 'optionalAccess', _190 => _190.span]);
1857
+ if (s)
1858
+ out += srcMd.slice(cursor, s[0]);
1859
+ if (s && clean(block, srcMd)) {
1860
+ out += srcMd.slice(s[0], s[1]);
1861
+ } else {
1862
+ if (!s && out && !out.endsWith("\n\n"))
1863
+ out += out.endsWith("\n") ? "\n" : "\n\n";
1864
+ out += _mdastutiltomarkdown.toMarkdown.call(void 0, { type: "root", children: [nodeToMdast(block)] }, { extensions: [_mdastutilgfm.gfmToMarkdown.call(void 0, )] }).trimEnd();
1865
+ }
1866
+ if (s)
1867
+ cursor = s[1];
1868
+ }
1869
+ if (cursor < srcMd.length)
1870
+ out += srcMd.slice(cursor);
1871
+ return out;
1872
+ }
1873
+
1874
+ // src/tree/schema.ts
1875
+ var META = {
1876
+ maxNodeTypes: 16,
1877
+ // M1
1878
+ maxDepth: 4,
1879
+ // M2:容器嵌套上界。doc>quote>list>item 四层到顶;
1880
+ // 持有文本的 inline 块(paragraph/heading)是「地板」不算层。
1881
+ maxContentTypes: 8
1882
+ // M3:单条产生式右部种类上界
1883
+ };
1884
+ function checkSchema(schema) {
1885
+ const types = Object.keys(schema.nodes);
1886
+ if (types.length > META.maxNodeTypes)
1887
+ throw new Error(`[M1] node type \u603B\u6570 ${types.length} > ${META.maxNodeTypes}:type \u5F53 attr \u7528\u4E86`);
1888
+ for (const [type, spec] of Object.entries(schema.nodes)) {
1889
+ const childTypes = spec.content.filter((c) => c !== "text");
1890
+ if (type !== "doc" && childTypes.length > META.maxContentTypes)
1891
+ throw new Error(`[M3] ${type} \u5141\u8BB8 ${childTypes.length} \u79CD children > ${META.maxContentTypes}:\u4E07\u80FD\u5BB9\u5668`);
1892
+ for (const c of childTypes) {
1893
+ if (!schema.nodes[c])
1894
+ throw new Error(`${type} \u7684 content \u5F15\u7528\u4E86\u672A\u5B9A\u4E49 type: ${c}`);
1895
+ }
1896
+ }
1897
+ const depth = maxReachableDepth(schema);
1898
+ if (depth > META.maxDepth)
1899
+ throw new Error(`[M2] \u6587\u6CD5\u53EF\u8FBE\u5D4C\u5957\u6DF1\u5EA6 ${depth} > ${META.maxDepth}:\u75C5\u6001\u5D4C\u5957`);
1900
+ }
1901
+ function maxReachableDepth(schema) {
1902
+ function walk(type, seen) {
1903
+ const spec = schema.nodes[type];
1904
+ if (!spec || spec.atom)
1905
+ return 1;
1906
+ if (spec.inline)
1907
+ return 0;
1908
+ let max = 0;
1909
+ for (const c of spec.content) {
1910
+ if (c === "text" || seen.has(c))
1911
+ continue;
1912
+ max = Math.max(max, walk(c, new Set(seen).add(c)));
1913
+ }
1914
+ return 1 + max;
1915
+ }
1916
+ return walk("doc", /* @__PURE__ */ new Set(["doc"]));
1917
+ }
1918
+ function validate(schema, doc) {
1919
+ function check(node, typePath) {
1920
+ if (isText(node))
1921
+ return true;
1922
+ const spec = schema.nodes[node.type];
1923
+ if (!spec)
1924
+ return `${typePath}: \u672A\u77E5 type "${node.type}"`;
1925
+ if (spec.atom)
1926
+ return true;
1927
+ for (const child of node.children) {
1928
+ const childType = isText(child) ? "text" : child.type;
1929
+ if (!spec.content.includes(childType))
1930
+ return `${typePath}/${node.type}: \u4E0D\u5141\u8BB8 child "${childType}"`;
1931
+ const r = check(child, `${typePath}/${node.type}`);
1932
+ if (r !== true)
1933
+ return r;
1934
+ }
1935
+ return true;
1936
+ }
1937
+ return check(doc, "");
1938
+ }
1939
+ function validateAll(schema, doc) {
1940
+ const out = [];
1941
+ function check(node, path) {
1942
+ if (isText(node))
1943
+ return;
1944
+ const spec = schema.nodes[node.type];
1945
+ if (!spec) {
1946
+ out.push({ path, reason: `\u672A\u77E5 type "${node.type}"` });
1947
+ return;
1948
+ }
1949
+ if (spec.atom)
1950
+ return;
1951
+ for (let i = 0; i < node.children.length; i++) {
1952
+ const child = node.children[i];
1953
+ const childType = isText(child) ? "text" : child.type;
1954
+ if (!spec.content.includes(childType))
1955
+ out.push({ path: path.concat(i), reason: `${node.type} \u4E0D\u5141\u8BB8 child "${childType}"` });
1956
+ check(child, path.concat(i));
1957
+ }
1958
+ }
1959
+ check(doc, []);
1960
+ return out;
1961
+ }
1962
+ var basicSchema = {
1963
+ marks: ["bold", "italic", "code", "strike", "link", "underline", "highlight", "superscript", "subscript", "textStyle", "comment"],
1964
+ nodes: {
1965
+ // 折叠内建 heading.attrs.collapsed(H1–H6 折到下一同级/上级标题),无独立 toggle 类型。
1966
+ // math 行内 atom;embed 块级嵌入(youtube/twitch/audio/file 共用 kind attr)。
1967
+ doc: { content: ["paragraph", "heading", "quote", "callout", "list", "code", "table", "image", "embed", "raw", "ai"] },
1968
+ paragraph: { content: ["text", "mention", "hard_break", "math"], inline: true },
1969
+ heading: { content: ["text", "mention", "hard_break", "math"], inline: true },
1970
+ // attrs.depth + collapsed
1971
+ code: { content: ["text"], inline: true, marks: [] },
1972
+ // code 不收 mention/br/math:代码正文纯文本(\n 在叶内)
1973
+ quote: { content: ["paragraph", "list"] },
1974
+ callout: { content: ["paragraph", "list"] },
1975
+ // 高亮块:同 quote 拓扑的容器,variant(info/warn/success/danger)在 attrs
1976
+ // AI 指令壳:children 仅指令段。生成结果是 doc 顶层 paragraph(attrs.aiDraft+aiFrom),确认前淡化。
1977
+ // attrs.status=compose|loading|preview|error
1978
+ ai: { content: ["paragraph"] },
1979
+ list: { content: ["list_item"] },
1980
+ list_item: { content: ["paragraph", "list"] },
1981
+ table: { content: [], atom: true },
1982
+ // 异拓扑黑盒(M4):内部二维模型自管
1983
+ image: { content: [], atom: true },
1984
+ // 块级 atom:无 children,url/alt/w/h 全在 attrs
1985
+ embed: { content: [], atom: true },
1986
+ // 块级 atom:youtube/twitch/audio/file,kind+src 在 attrs
1987
+ mention: { content: [], atom: true, inline: true },
1988
+ // 行内 atom:@提及,占 1 字符位不可下钻,id/label 在 attrs
1989
+ hard_break: { content: [], atom: true, inline: true },
1990
+ // 行内 atom:段内软换行 <br>,Shift+Enter;无 attrs
1991
+ math: { content: [], atom: true, inline: true },
1992
+ // 行内 atom:公式,latex + display(inline|block)在 attrs;块级公式=段内 display:block
1993
+ raw: { content: ["text"], inline: true, marks: [] }
1994
+ // mdToDoc 透传块(thematicBreak/html);源文本存单文本叶,attrs.mdType 定渲染
1995
+ }
1996
+ };
1997
+
1998
+ // src/tree/step.ts
1999
+ function apply(doc, step) {
2000
+ switch (step.kind) {
2001
+ case "insertText": {
2002
+ const leaf = nodeAt(doc, step.path);
2003
+ if (!isText(leaf))
2004
+ throw new Error("insertText \u76EE\u6807\u4E0D\u662F\u6587\u672C\u53F6");
2005
+ const text = leaf.text.slice(0, step.offset) + step.text + leaf.text.slice(step.offset);
2006
+ return replaceAt(doc, step.path, { ...leaf, text });
2007
+ }
2008
+ case "deleteText": {
2009
+ const leaf = nodeAt(doc, step.path);
2010
+ if (!isText(leaf))
2011
+ throw new Error("deleteText \u76EE\u6807\u4E0D\u662F\u6587\u672C\u53F6");
2012
+ const text = leaf.text.slice(0, step.offset) + leaf.text.slice(step.offset + step.length);
2013
+ return replaceAt(doc, step.path, { ...leaf, text });
2014
+ }
2015
+ case "replaceNode":
2016
+ return replaceAt(doc, step.path, step.node);
2017
+ case "spliceChildren":
2018
+ return spliceAt(doc, step.path, step.at, step.remove, step.insert);
2019
+ }
2020
+ }
2021
+ function invert(doc, step) {
2022
+ switch (step.kind) {
2023
+ case "insertText":
2024
+ return { kind: "deleteText", path: step.path, offset: step.offset, length: step.text.length };
2025
+ case "deleteText": {
2026
+ const leaf = nodeAt(doc, step.path);
2027
+ const removed = leaf.text.slice(step.offset, step.offset + step.length);
2028
+ const marks = leaf.marks;
2029
+ return { kind: "insertText", path: step.path, offset: step.offset, text: removed, marks };
2030
+ }
2031
+ case "replaceNode":
2032
+ return { kind: "replaceNode", path: step.path, node: nodeAt(doc, step.path) };
2033
+ case "spliceChildren": {
2034
+ const parent = nodeAt(doc, step.path);
2035
+ const removed = parent.children.slice(step.at, step.at + step.remove);
2036
+ return { kind: "spliceChildren", path: step.path, at: step.at, remove: step.insert.length, insert: removed };
2037
+ }
2038
+ }
2039
+ }
2040
+ function applyAll(doc, steps) {
2041
+ return steps.reduce(apply, doc);
2042
+ }
2043
+ function moveBlock(doc, fromIdx, toGap) {
2044
+ if (toGap === fromIdx || toGap === fromIdx + 1)
2045
+ return [];
2046
+ const block = doc.children[fromIdx];
2047
+ const insertAt = toGap > fromIdx ? toGap - 1 : toGap;
2048
+ return [
2049
+ { kind: "spliceChildren", path: [], at: fromIdx, remove: 1, insert: [] },
2050
+ { kind: "spliceChildren", path: [], at: insertAt, remove: 0, insert: [block] }
2051
+ ];
2052
+ }
2053
+ function invertAll(doc, steps) {
2054
+ const inverses = [];
2055
+ let cur = doc;
2056
+ for (const step of steps) {
2057
+ inverses.push(invert(cur, step));
2058
+ cur = apply(cur, step);
2059
+ }
2060
+ return inverses.reverse();
2061
+ }
2062
+
2063
+ // src/tree/ai.ts
2064
+ function pathOfId(doc, id) {
2065
+ function walk(node, prefix) {
2066
+ if (isText(node))
2067
+ return null;
2068
+ if (node.id === id)
2069
+ return prefix;
2070
+ for (let i = 0; i < node.children.length; i++) {
2071
+ const r = walk(node.children[i], prefix.concat(i));
2072
+ if (r)
2073
+ return r;
2074
+ }
2075
+ return null;
2076
+ }
2077
+ return walk(doc, []);
2078
+ }
2079
+ function buildIdIndex(doc) {
2080
+ const index = /* @__PURE__ */ new Map();
2081
+ function walk(node, prefix) {
2082
+ if (isText(node))
2083
+ return;
2084
+ if (node.id !== void 0 && !index.has(node.id))
2085
+ index.set(node.id, prefix);
2086
+ for (let i = 0; i < node.children.length; i++)
2087
+ walk(node.children[i], prefix.concat(i));
2088
+ }
2089
+ walk(doc, []);
2090
+ return index;
2091
+ }
2092
+ function leafPathAndLen(doc, blockPath) {
2093
+ const block = blockPath.reduce((n, i2) => n.children[i2], doc);
2094
+ if (!isElement(block))
2095
+ throw new Error("\u5757\u4E0D\u662F\u5143\u7D20");
2096
+ const i = block.children.findIndex(isText);
2097
+ if (i === -1)
2098
+ return null;
2099
+ const leaf = block.children[i];
2100
+ return { path: blockPath.concat(i), len: isText(leaf) ? leaf.text.length : 0 };
2101
+ }
2102
+ function resolve2(doc, id, index) {
2103
+ return index ? _nullishCoalesce(index.get(id), () => ( null)) : pathOfId(doc, id);
2104
+ }
2105
+ function collectIds(node, out) {
2106
+ if (isText(node))
2107
+ return;
2108
+ if (node.id !== void 0)
2109
+ out.push(node.id);
2110
+ for (const c of node.children)
2111
+ collectIds(c, out);
2112
+ }
2113
+ function assertFreshIds(existing, inserted) {
2114
+ const ids = [];
2115
+ for (const n of inserted)
2116
+ collectIds(n, ids);
2117
+ const seen = /* @__PURE__ */ new Set();
2118
+ for (const id of ids) {
2119
+ if (existing.has(id))
2120
+ throw new Error(`duplicate id: ${id}`);
2121
+ if (seen.has(id))
2122
+ throw new Error(`duplicate id within insertion: ${id}`);
2123
+ seen.add(id);
2124
+ }
2125
+ }
2126
+ function appendText(doc, blockId, text, index) {
2127
+ const bp = resolve2(doc, blockId, index);
2128
+ if (!bp)
2129
+ throw new Error(`block not found: ${blockId}`);
2130
+ const at = leafPathAndLen(doc, bp);
2131
+ if (!at)
2132
+ return { kind: "spliceChildren", path: bp, at: 0, remove: 0, insert: [{ text }] };
2133
+ return { kind: "insertText", path: at.path, offset: at.len, text };
2134
+ }
2135
+ function badTable(doc) {
2136
+ for (const c of doc.children) {
2137
+ if (!isText(c) && c.type === "table") {
2138
+ const errs = checkTable(c);
2139
+ if (errs.length > 0)
2140
+ return errs[0];
2141
+ }
2142
+ }
2143
+ return null;
2144
+ }
2145
+ function rewriteNode(doc, blockId, node, index, schema) {
2146
+ const bp = resolve2(doc, blockId, index);
2147
+ if (!bp)
2148
+ throw new Error(`block not found: ${blockId}`);
2149
+ const existing = new Set(buildIdIndex(doc).keys());
2150
+ const replaced = [];
2151
+ collectIds(bp.reduce((n, i) => n.children[i], doc), replaced);
2152
+ for (const id of replaced)
2153
+ existing.delete(id);
2154
+ assertFreshIds(existing, [{ ...node, id: blockId }]);
2155
+ const step = { kind: "replaceNode", path: bp, node: { ...node, id: blockId } };
2156
+ if (schema) {
2157
+ const applied = apply(doc, step);
2158
+ const v = validate(schema, applied);
2159
+ if (v !== true)
2160
+ throw new Error(`schema violation: ${v}`);
2161
+ const t = badTable(applied);
2162
+ if (t)
2163
+ throw new Error(`table invariant: ${t}`);
2164
+ }
2165
+ return step;
2166
+ }
2167
+ function insertAfter(doc, afterId, nodes, index, schema) {
2168
+ const bp = resolve2(doc, afterId, index);
2169
+ if (!bp || bp.length === 0)
2170
+ throw new Error(`block not found or is root: ${afterId}`);
2171
+ for (const n of nodes) {
2172
+ if (n.id === void 0)
2173
+ throw new Error("insertAfter: node missing id");
2174
+ }
2175
+ assertFreshIds(new Set(buildIdIndex(doc).keys()), nodes);
2176
+ const parentPath = bp.slice(0, -1);
2177
+ const idx = bp[bp.length - 1];
2178
+ const step = { kind: "spliceChildren", path: parentPath, at: idx + 1, remove: 0, insert: nodes };
2179
+ if (schema) {
2180
+ const applied = applyAll(doc, [step]);
2181
+ const v = validate(schema, applied);
2182
+ if (v !== true)
2183
+ throw new Error(`schema violation: ${v}`);
2184
+ const t = badTable(applied);
2185
+ if (t)
2186
+ throw new Error(`table invariant: ${t}`);
2187
+ }
2188
+ return step;
2189
+ }
2190
+ function idBlocks(doc) {
2191
+ const out = [];
2192
+ function walk(node) {
2193
+ if (isText(node))
2194
+ return;
2195
+ if (node.id)
2196
+ out.push(node);
2197
+ node.children.forEach(walk);
2198
+ }
2199
+ walk(doc);
2200
+ return out;
2201
+ }
2202
+ function diffById(before, after) {
2203
+ const beforeMap = new Map(idBlocks(before).map((b) => [b.id, b]));
2204
+ const afterBlocks = idBlocks(after);
2205
+ const afterIds = new Set(afterBlocks.map((b) => b.id));
2206
+ const out = [];
2207
+ for (const b of afterBlocks) {
2208
+ const prev = beforeMap.get(b.id);
2209
+ if (!prev)
2210
+ out.push({ type: "added", id: b.id, after: b });
2211
+ else if (sameNode(prev, b))
2212
+ out.push({ type: "same", id: b.id });
2213
+ else
2214
+ out.push({ type: "changed", id: b.id, before: prev, after: b });
2215
+ }
2216
+ for (const [id, b] of beforeMap) {
2217
+ if (!afterIds.has(id))
2218
+ out.push({ type: "removed", id, before: b });
2219
+ }
2220
+ return out;
2221
+ }
2222
+ function sameNode(a, b) {
2223
+ return a.id === b.id && a.type === b.type && deepEqual(a.attrs, b.attrs) && deepEqual(a.children, b.children);
2224
+ }
2225
+ function deepEqual(a, b) {
2226
+ if (a === b)
2227
+ return true;
2228
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
2229
+ return false;
2230
+ if (Array.isArray(a) || Array.isArray(b)) {
2231
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
2232
+ return false;
2233
+ return a.every((x, i) => deepEqual(x, b[i]));
2234
+ }
2235
+ const ak = Object.keys(a);
2236
+ const bk = Object.keys(b);
2237
+ if (ak.length !== bk.length)
2238
+ return false;
2239
+ return ak.every((k) => deepEqual(a[k], b[k]));
2240
+ }
2241
+
2242
+
2243
+
2244
+
2245
+
2246
+
2247
+
2248
+
2249
+
2250
+
2251
+
2252
+
2253
+
2254
+
2255
+
2256
+
2257
+
2258
+
2259
+
2260
+
2261
+
2262
+
2263
+
2264
+
2265
+
2266
+
2267
+
2268
+
2269
+
2270
+
2271
+
2272
+
2273
+
2274
+
2275
+
2276
+
2277
+
2278
+
2279
+
2280
+
2281
+
2282
+
2283
+
2284
+
2285
+
2286
+
2287
+
2288
+
2289
+
2290
+
2291
+
2292
+
2293
+
2294
+
2295
+
2296
+
2297
+
2298
+
2299
+
2300
+
2301
+
2302
+
2303
+
2304
+
2305
+ exports.isText = isText; exports.isElement = isElement; exports.isInlineAtom = isInlineAtom; exports.resolve = resolve; exports.firstLeafPath = firstLeafPath; exports.normalizeToLeaf = normalizeToLeaf; exports.lastLeafEnd = lastLeafEnd; exports.nodeAt = nodeAt; exports.replaceAt = replaceAt; exports.spliceAt = spliceAt; exports.tableShape = tableShape; exports.colspanOf = colspanOf; exports.rowspanOf = rowspanOf; exports.buildGrid = buildGrid; exports.cellCaret = cellCaret; exports.caretCell = caretCell; exports.makeTable = makeTable; exports.cellText = cellText; exports.nextCell = nextCell; exports.arrowCell = arrowCell; exports.insertRow = insertRow; exports.deleteRow = deleteRow; exports.insertCol = insertCol; exports.deleteCol = deleteCol; exports.hasSpan = hasSpan; exports.moveRow = moveRow; exports.moveCol = moveCol; exports.tableColWidths = tableColWidths; exports.setColWidths = setColWidths; exports.setAlign = setAlign; exports.mergeCells = mergeCells; exports.splitCell = splitCell; exports.setCellStyle = setCellStyle; exports.clearCells = clearCells; exports.setFreeze = setFreeze; exports.deleteTableBlock = deleteTableBlock; exports.tableAt = tableAt; exports.checkTable = checkTable; exports.tableSchema = tableSchema; exports.mdToDoc = mdToDoc; exports.htmlToBlocks = htmlToBlocks; exports.isRichHtmlBlocks = isRichHtmlBlocks; exports.embedHtml = embedHtml; exports.tableHasExtras = tableHasExtras; exports.tableToHtml = tableToHtml; exports.calloutToHtml = calloutToHtml; exports.docToMd = docToMd; exports.checkSchema = checkSchema; exports.validate = validate; exports.validateAll = validateAll; exports.basicSchema = basicSchema; exports.apply = apply; exports.invert = invert; exports.applyAll = applyAll; exports.moveBlock = moveBlock; exports.invertAll = invertAll; exports.pathOfId = pathOfId; exports.buildIdIndex = buildIdIndex; exports.appendText = appendText; exports.rewriteNode = rewriteNode; exports.insertAfter = insertAfter; exports.diffById = diffById;