@sovereignfs/ui 0.107.4 → 0.110.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,2838 @@
1
+ 'use client';
2
+ import {
3
+ Button,
4
+ Dialog,
5
+ FormField,
6
+ Icon,
7
+ Input,
8
+ Menu,
9
+ SegmentedControl,
10
+ SourceEditor,
11
+ diffSequences,
12
+ splitLines
13
+ } from "./chunk-JWLJDBL4.js";
14
+ import "./chunk-E24U223W.js";
15
+
16
+ // src/components/MarkdownEditor/MarkdownEditor.tsx
17
+ import { useRef as useRef3, useState as useState3 } from "react";
18
+
19
+ // src/markdown/schema.ts
20
+ import { Schema } from "prosemirror-model";
21
+ var attrs = (defaults) => Object.fromEntries(Object.entries(defaults).map(([name, value]) => [name, { default: value }]));
22
+ var place = { gap: null, indent: "" };
23
+ var SAFE_SCHEMES = /* @__PURE__ */ new Set(["http", "https", "mailto", "tel"]);
24
+ function schemeOf(address) {
25
+ const read = Array.from(address).filter((char) => char > " ").join("");
26
+ return /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(read)?.[1]?.toLowerCase();
27
+ }
28
+ function isSafeAddress(address) {
29
+ const scheme = schemeOf(address);
30
+ return scheme === void 0 || SAFE_SCHEMES.has(scheme);
31
+ }
32
+ var RUNNING_SCHEMES = /* @__PURE__ */ new Set(["javascript", "vbscript", "data"]);
33
+ var ALIGNMENTS = /* @__PURE__ */ new Set(["left", "center", "right"]);
34
+ var cell = (tag, role) => ({
35
+ content: "inline*",
36
+ // `colspan`, `rowspan` and `colwidth` are the table commands' own; Markdown has one of each.
37
+ attrs: attrs({ align: null, pad: null, colspan: 1, rowspan: 1, colwidth: null }),
38
+ tableRole: role,
39
+ isolating: true,
40
+ parseDOM: [
41
+ {
42
+ tag,
43
+ getAttrs: (dom) => {
44
+ const align2 = dom.style.textAlign || dom.getAttribute("data-align") || "";
45
+ return { align: ALIGNMENTS.has(align2) ? align2 : null };
46
+ }
47
+ }
48
+ ],
49
+ toDOM: (node) => [
50
+ tag,
51
+ node.attrs.align ? { "data-align": String(node.attrs.align) } : {},
52
+ 0
53
+ ]
54
+ });
55
+ var schema = new Schema({
56
+ nodes: {
57
+ // What lay before the first block and after the last.
58
+ doc: { content: "block+", attrs: attrs({ lead: "", tail: "\n" }) },
59
+ paragraph: {
60
+ group: "block",
61
+ content: "inline*",
62
+ attrs: attrs(place),
63
+ parseDOM: [{ tag: "p" }],
64
+ toDOM: () => ["p", 0]
65
+ },
66
+ heading: {
67
+ group: "block",
68
+ content: "inline*",
69
+ defining: true,
70
+ attrs: attrs({ ...place, level: 1, underline: null, hashGap: " ", closing: "" }),
71
+ parseDOM: [1, 2, 3, 4, 5, 6].map((level) => ({ tag: `h${level}`, attrs: { level } })),
72
+ toDOM: (node) => [`h${String(node.attrs.level)}`, 0]
73
+ },
74
+ horizontal_rule: {
75
+ group: "block",
76
+ attrs: attrs({ ...place, markup: null }),
77
+ parseDOM: [{ tag: "hr" }],
78
+ toDOM: () => ["hr"]
79
+ },
80
+ code_block: {
81
+ group: "block",
82
+ content: "text*",
83
+ marks: "",
84
+ code: true,
85
+ defining: true,
86
+ // `indented` is the form with four spaces and no fence.
87
+ attrs: attrs({ ...place, indented: false, fence: null, info: "", close: null, open: false }),
88
+ parseDOM: [
89
+ {
90
+ tag: "pre",
91
+ preserveWhitespace: "full",
92
+ getAttrs: (dom) => ({ info: dom.getAttribute("data-info") ?? "" })
93
+ }
94
+ ],
95
+ toDOM: (node) => [
96
+ "pre",
97
+ node.attrs.info ? { "data-info": String(node.attrs.info) } : {},
98
+ ["code", 0]
99
+ ]
100
+ },
101
+ blockquote: {
102
+ group: "block",
103
+ content: "block+",
104
+ defining: true,
105
+ // `bare` writes `>text` without a space; `blank` is how an empty quoted line is written.
106
+ attrs: attrs({ ...place, bare: false, blank: ">" }),
107
+ parseDOM: [{ tag: "blockquote" }],
108
+ toDOM: () => ["blockquote", 0]
109
+ },
110
+ bullet_list: {
111
+ group: "block",
112
+ content: "list_item+",
113
+ attrs: attrs({ ...place, marker: "-", tight: true }),
114
+ parseDOM: [{ tag: "ul" }],
115
+ toDOM: (node) => ["ul", node.attrs.tight ? { "data-tight": "true" } : {}, 0]
116
+ },
117
+ ordered_list: {
118
+ group: "block",
119
+ content: "list_item+",
120
+ // `numbering`: each item one more than the last (`up`), or every item the first number (`one`).
121
+ attrs: attrs({ ...place, start: 1, delimiter: ".", numbering: "up", tight: true }),
122
+ parseDOM: [
123
+ {
124
+ tag: "ol",
125
+ getAttrs: (dom) => ({ start: Number(dom.getAttribute("start") ?? 1) || 1 })
126
+ }
127
+ ],
128
+ toDOM: (node) => [
129
+ "ol",
130
+ {
131
+ ...node.attrs.start === 1 ? {} : { start: String(node.attrs.start) },
132
+ ...node.attrs.tight ? { "data-tight": "true" } : {}
133
+ },
134
+ 0
135
+ ]
136
+ },
137
+ list_item: {
138
+ content: "block+",
139
+ defining: true,
140
+ attrs: attrs({ gap: null, checked: null, spacing: " ", check: null, checkSpacing: " " }),
141
+ parseDOM: [
142
+ {
143
+ tag: "li",
144
+ getAttrs: (dom) => {
145
+ const checked = dom.getAttribute("data-checked");
146
+ return { checked: checked === null ? null : checked === "true" };
147
+ }
148
+ }
149
+ ],
150
+ toDOM: (node) => [
151
+ "li",
152
+ node.attrs.checked === null ? {} : { "data-checked": String(node.attrs.checked) },
153
+ 0
154
+ ]
155
+ },
156
+ table: {
157
+ group: "block",
158
+ content: "table_row+",
159
+ tableRole: "table",
160
+ isolating: true,
161
+ // The delimiter row as written, whether rows begin and end with a pipe, and whether columns were lined up.
162
+ attrs: attrs({ ...place, delimiter: null, leading: true, trailing: true, aligned: false }),
163
+ parseDOM: [{ tag: "table" }],
164
+ toDOM: () => ["table", ["tbody", 0]]
165
+ },
166
+ table_row: {
167
+ content: "(table_cell | table_header)*",
168
+ attrs: attrs({ after: "" }),
169
+ tableRole: "row",
170
+ parseDOM: [{ tag: "tr" }],
171
+ toDOM: () => ["tr", 0]
172
+ },
173
+ table_header: cell("th", "header_cell"),
174
+ table_cell: cell("td", "cell"),
175
+ // What the editor does not model (raw HTML, definitions, footnotes): kept as written, and shown.
176
+ raw_block: {
177
+ group: "block",
178
+ atom: true,
179
+ attrs: attrs({ ...place, raw: "", kind: "html" }),
180
+ toDOM: (node) => ["pre", { "data-raw": String(node.attrs.kind) }, String(node.attrs.raw)]
181
+ },
182
+ text: { group: "inline" },
183
+ image: {
184
+ group: "inline",
185
+ inline: true,
186
+ draggable: true,
187
+ attrs: attrs({
188
+ src: "",
189
+ alt: "",
190
+ title: null,
191
+ tail: null,
192
+ label: null,
193
+ wasSrc: null,
194
+ wasTitle: null,
195
+ wasAlt: null
196
+ }),
197
+ parseDOM: [
198
+ {
199
+ tag: "img",
200
+ getAttrs: (dom) => {
201
+ const src = dom.getAttribute("data-src") ?? dom.getAttribute("src");
202
+ if (!src) return false;
203
+ return { src, alt: dom.getAttribute("alt") ?? "", title: dom.getAttribute("title") };
204
+ }
205
+ }
206
+ ],
207
+ // Never `src`: the address is the text's, and only the app says what may be loaded for it.
208
+ toDOM: (node) => [
209
+ "img",
210
+ {
211
+ "data-src": String(node.attrs.src),
212
+ alt: String(node.attrs.alt),
213
+ ...node.attrs.title ? { title: String(node.attrs.title) } : {}
214
+ }
215
+ ]
216
+ },
217
+ hard_break: {
218
+ group: "inline",
219
+ inline: true,
220
+ selectable: false,
221
+ attrs: attrs({ markup: null }),
222
+ parseDOM: [{ tag: "br" }],
223
+ toDOM: () => ["br"]
224
+ },
225
+ // A line break in the source that reads as a space.
226
+ soft_break: {
227
+ group: "inline",
228
+ inline: true,
229
+ selectable: false,
230
+ attrs: attrs({ raw: "\n" }),
231
+ parseDOM: [{ tag: "span[data-soft-break]" }],
232
+ toDOM: () => ["span", { "data-soft-break": "" }, " "]
233
+ },
234
+ raw_inline: {
235
+ group: "inline",
236
+ inline: true,
237
+ atom: true,
238
+ attrs: attrs({ raw: "", kind: "html" }),
239
+ toDOM: (node) => ["code", { "data-raw": String(node.attrs.kind) }, String(node.attrs.raw)]
240
+ }
241
+ },
242
+ marks: {
243
+ link: {
244
+ inclusive: false,
245
+ // `form`: `[text](address)`, `<address>` or an address written bare.
246
+ attrs: attrs({
247
+ href: "",
248
+ title: null,
249
+ form: "inline",
250
+ tail: null,
251
+ wasHref: null,
252
+ wasTitle: null,
253
+ depth: 0
254
+ }),
255
+ parseDOM: [
256
+ {
257
+ tag: "a[href], a[data-href]",
258
+ getAttrs: (dom) => {
259
+ const href = dom.getAttribute("data-href") ?? dom.getAttribute("href") ?? "";
260
+ if (RUNNING_SCHEMES.has(schemeOf(href) ?? "")) return false;
261
+ return { href, title: dom.getAttribute("title") };
262
+ }
263
+ }
264
+ ],
265
+ toDOM: (mark) => {
266
+ const href = String(mark.attrs.href);
267
+ return [
268
+ "a",
269
+ {
270
+ ...isSafeAddress(href) ? { href } : {},
271
+ "data-href": href,
272
+ ...mark.attrs.title ? { title: String(mark.attrs.title) } : {},
273
+ rel: "noopener noreferrer"
274
+ },
275
+ 0
276
+ ];
277
+ }
278
+ },
279
+ // `depth` is how far inside other marks the source put it, so that they are written in the same order.
280
+ em: {
281
+ attrs: attrs({ marker: null, depth: 0 }),
282
+ parseDOM: [{ tag: "em" }, { tag: "i" }, { style: "font-style=italic" }],
283
+ toDOM: () => ["em", 0]
284
+ },
285
+ strong: {
286
+ attrs: attrs({ marker: null, depth: 0 }),
287
+ parseDOM: [
288
+ { tag: "strong" },
289
+ { tag: "b", getAttrs: (dom) => dom.style.fontWeight === "normal" ? false : null },
290
+ {
291
+ style: "font-weight",
292
+ getAttrs: (value) => /^(bold|[6-9]00)/.test(value) ? null : false
293
+ }
294
+ ],
295
+ toDOM: () => ["strong", 0]
296
+ },
297
+ strike: {
298
+ attrs: attrs({ marker: null, depth: 0 }),
299
+ parseDOM: [{ tag: "s" }, { tag: "del" }, { style: "text-decoration=line-through" }],
300
+ toDOM: () => ["s", 0]
301
+ },
302
+ code: {
303
+ attrs: attrs({ ticks: null, padded: false }),
304
+ parseDOM: [{ tag: "code" }],
305
+ toDOM: () => ["code", 0]
306
+ },
307
+ // A character the source spelled another way (`\*`, `&amp;`): written back so while it is unchanged.
308
+ source: {
309
+ inclusive: false,
310
+ attrs: attrs({ raw: "", value: "" }),
311
+ toDOM: () => ["span", 0]
312
+ }
313
+ }
314
+ });
315
+
316
+ // src/markdown/tree.ts
317
+ import { fromMarkdown } from "mdast-util-from-markdown";
318
+ import { gfmFromMarkdown } from "mdast-util-gfm";
319
+ import { gfm } from "micromark-extension-gfm";
320
+ function readTree(source) {
321
+ return fromMarkdown(source, {
322
+ extensions: [gfm()],
323
+ mdastExtensions: [gfmFromMarkdown()]
324
+ });
325
+ }
326
+
327
+ // src/markdown/parse.ts
328
+ var startOf = (node) => node.position?.start.offset ?? 0;
329
+ var endOf = (node) => node.position?.end.offset ?? 0;
330
+ function sourceLines(context, from, to) {
331
+ return context.source.slice(from, to).split("\n").map((line, index) => index === 0 ? line : context.strip(line));
332
+ }
333
+ var linesOf = (context, node) => sourceLines(context, startOf(node), endOf(node));
334
+ function blockEnd(context, node) {
335
+ if (node.type === "list" || node.type === "listItem" || node.type === "blockquote") {
336
+ const last = node.children?.[node.children.length - 1];
337
+ if (last) return blockEnd(context, last);
338
+ }
339
+ if (node.type === "code") return endOf(node) - (context.source[endOf(node) - 1] === "\n" ? 1 : 0);
340
+ const own2 = context.source.slice(startOf(node), endOf(node));
341
+ const empty = node.type === "listItem" && !node.children?.length;
342
+ return startOf(node) + (empty ? own2.replace(/\n+$/, "") : own2.trimEnd()).length;
343
+ }
344
+ var ESCAPABLE = /[!-/:-@[-`{-~]/;
345
+ var REFERENCE = /&(?:#[0-9]{1,7}|#[xX][0-9a-fA-F]{1,6}|[A-Za-z][A-Za-z0-9]{1,31});/y;
346
+ var decoded = /* @__PURE__ */ new Map();
347
+ function decode(reference) {
348
+ let value = decoded.get(reference);
349
+ if (value === void 0) {
350
+ value = readTree(reference).children?.[0]?.children?.[0]?.value ?? reference;
351
+ if (decoded.size > 500) decoded.clear();
352
+ decoded.set(reference, value);
353
+ }
354
+ return value;
355
+ }
356
+ function align(value, raw) {
357
+ const pieces = [];
358
+ let plain2 = "";
359
+ const push = (piece) => {
360
+ if (plain2) pieces.push({ kind: "text", value: plain2 });
361
+ plain2 = "";
362
+ pieces.push(piece);
363
+ };
364
+ let i = 0;
365
+ for (let j = 0; j < value.length; ) {
366
+ const char = value[j];
367
+ if (char === "\n") {
368
+ let end = i;
369
+ while (raw[end] === " " || raw[end] === " ") end++;
370
+ if (raw[end] !== "\n") return void 0;
371
+ end++;
372
+ while (raw[end] === " " || raw[end] === " ") end++;
373
+ push({ kind: "break", raw: raw.slice(i, end) });
374
+ i = end;
375
+ j++;
376
+ continue;
377
+ }
378
+ if (raw[i] === "\\" && raw[i + 1] === char && ESCAPABLE.test(char)) {
379
+ push({ kind: "text", value: char, raw: raw.slice(i, i + 2) });
380
+ i += 2;
381
+ j++;
382
+ continue;
383
+ }
384
+ if (raw[i] === "&") {
385
+ REFERENCE.lastIndex = i;
386
+ const reference = REFERENCE.exec(raw)?.[0];
387
+ if (reference) {
388
+ const stands = decode(reference);
389
+ if (stands !== reference && value.startsWith(stands, j)) {
390
+ push({ kind: "text", value: stands, raw: reference });
391
+ i += reference.length;
392
+ j += stands.length;
393
+ continue;
394
+ }
395
+ }
396
+ }
397
+ if (raw[i] !== char) return void 0;
398
+ plain2 += char;
399
+ i++;
400
+ j++;
401
+ }
402
+ if (plain2) pieces.push({ kind: "text", value: plain2 });
403
+ return pieces;
404
+ }
405
+ function textNodes(context, node, marks2) {
406
+ const value = node.value ?? "";
407
+ const aligned = node.position ? align(value, linesOf(context, node).join("\n")) : void 0;
408
+ const pieces = aligned ?? value.split("\n").flatMap((text2, index) => [
409
+ ...index ? [{ kind: "break", raw: "\n" }] : [],
410
+ { kind: "text", value: text2 }
411
+ ]);
412
+ const out = [];
413
+ for (const piece of pieces) {
414
+ if (piece.kind === "break") {
415
+ out.push(schema.node("soft_break", { raw: piece.raw }, void 0, marks2));
416
+ } else if (piece.value) {
417
+ const own2 = piece.raw ? schema.mark("source", { raw: piece.raw, value: piece.value }).addToSet(marks2) : marks2;
418
+ out.push(schema.text(piece.value, own2));
419
+ }
420
+ }
421
+ return out;
422
+ }
423
+ var MARKS = {
424
+ emphasis: "em",
425
+ strong: "strong",
426
+ delete: "strike"
427
+ };
428
+ function inline(context, nodes3, marks2 = [], depth = 0) {
429
+ return nodes3.flatMap((node) => {
430
+ const raw = () => linesOf(context, node).join("\n");
431
+ const kept2 = (kind2) => {
432
+ context.unsupported.push({ reason: kind2, line: node.position?.start.line ?? 1 });
433
+ return [schema.node("raw_inline", { raw: raw(), kind: kind2 }, void 0, marks2)];
434
+ };
435
+ const mark = MARKS[node.type];
436
+ if (mark) {
437
+ const written2 = raw();
438
+ const marker = mark === "em" ? written2.slice(0, 1) : mark === "strong" ? written2.slice(0, 2) : written2.startsWith("~~") ? "~~" : "~";
439
+ const set = schema.mark(mark, { marker, depth }).addToSet(marks2);
440
+ return inline(context, node.children ?? [], set, depth + 1);
441
+ }
442
+ switch (node.type) {
443
+ case "text":
444
+ return textNodes(context, node, marks2);
445
+ case "inlineCode": {
446
+ const written2 = raw();
447
+ let ticks = 0;
448
+ while (written2[ticks] === "`") ticks++;
449
+ const inside = written2.slice(ticks, written2.length - ticks);
450
+ const value = node.value ?? "";
451
+ const padded = inside.length === value.length + 2 && inside === ` ${value} `;
452
+ if (!value) return kept2("unsupported");
453
+ const set = schema.mark("code", { ticks, padded }).addToSet(marks2);
454
+ return [schema.text(value, set)];
455
+ }
456
+ case "link": {
457
+ const written2 = raw();
458
+ const form = written2.startsWith("<") ? "autolink" : written2.startsWith("[") ? "inline" : "literal";
459
+ const children2 = node.children ?? [];
460
+ const last = children2[children2.length - 1];
461
+ const tail = form !== "inline" ? null : sourceLines(context, last ? endOf(last) : startOf(node) + 1, endOf(node)).join("\n");
462
+ const title = node.title ?? null;
463
+ const link = schema.mark("link", {
464
+ href: node.url ?? "",
465
+ title,
466
+ form,
467
+ tail,
468
+ wasHref: node.url ?? "",
469
+ wasTitle: title,
470
+ depth
471
+ });
472
+ if (children2.length === 0) return kept2("unsupported");
473
+ return inline(context, children2, link.addToSet(marks2), depth + 1);
474
+ }
475
+ case "image": {
476
+ const written2 = raw();
477
+ const split = written2.lastIndexOf("](");
478
+ const title = node.title ?? null;
479
+ const alt = node.alt ?? "";
480
+ const src = node.url ?? "";
481
+ return [
482
+ schema.node(
483
+ "image",
484
+ {
485
+ src,
486
+ alt,
487
+ title,
488
+ label: split > 1 ? written2.slice(2, split) : null,
489
+ tail: split > 1 ? written2.slice(split) : null,
490
+ wasSrc: src,
491
+ wasTitle: title,
492
+ wasAlt: alt
493
+ },
494
+ void 0,
495
+ marks2
496
+ )
497
+ ];
498
+ }
499
+ case "break": {
500
+ const markup = raw().split("\n")[0] ?? "";
501
+ return [schema.node("hard_break", { markup }, void 0, marks2)];
502
+ }
503
+ case "html":
504
+ return kept2("html");
505
+ case "footnoteReference":
506
+ return kept2("footnote");
507
+ case "linkReference":
508
+ case "imageReference":
509
+ return kept2("reference");
510
+ default:
511
+ return kept2("unsupported");
512
+ }
513
+ });
514
+ }
515
+ function splitRow(line) {
516
+ const parts = [];
517
+ let part = "";
518
+ for (let i = 0; i < line.length; i++) {
519
+ const char = line[i];
520
+ if (char === "\\") {
521
+ part += char + (line[i + 1] ?? "");
522
+ i++;
523
+ } else if (char === "|") {
524
+ parts.push(part);
525
+ part = "";
526
+ } else part += char;
527
+ }
528
+ parts.push(part);
529
+ const leading = parts.length > 1 && parts[0].trim() === "";
530
+ const trailing = parts.length > 1 && parts[parts.length - 1].trim() === "";
531
+ return {
532
+ cells: parts.slice(leading ? 1 : 0, trailing ? -1 : parts.length),
533
+ leading,
534
+ trailing
535
+ };
536
+ }
537
+ function padding(cell2) {
538
+ if (cell2.trim() === "") return [cell2, ""];
539
+ return [cell2.slice(0, cell2.length - cell2.trimStart().length), cell2.slice(cell2.trimEnd().length)];
540
+ }
541
+ function cellPadding(row, column) {
542
+ const [left, right] = padding(row?.cells[column] ?? " ");
543
+ const open = !row?.trailing && column === (row?.cells.length ?? 0) - 1;
544
+ return [left, open ? "" : right];
545
+ }
546
+ var rowEnd = (line = "") => line.slice(line.trimEnd().length);
547
+ function table(context, node, place2) {
548
+ const lines = linesOf(context, node);
549
+ const delimiter = lines.length > 2 ? lines[1] ?? "" : (lines[1] ?? "").trimEnd();
550
+ const header = splitRow(lines[0] ?? "");
551
+ const written2 = [header, ...lines.slice(2).map(splitRow)];
552
+ const rows = node.children ?? [];
553
+ const widths = [splitRow(delimiter).cells, ...written2.map((row) => row.cells)];
554
+ const columns = header.cells.length;
555
+ const aligned = rows.length > 1 && Array.from(
556
+ { length: columns },
557
+ (_, column) => widths.every((cells) => cells[column]?.length === widths[0]?.[column]?.length)
558
+ ).every(Boolean);
559
+ if (rows.some((row) => (row.children?.length ?? 0) !== columns)) {
560
+ context.unsupported.push({ reason: "unsupported", line: node.position?.start.line ?? 1 });
561
+ }
562
+ return schema.node(
563
+ "table",
564
+ { ...place2, delimiter, leading: header.leading, trailing: header.trailing, aligned },
565
+ rows.map(
566
+ (row, index) => schema.node(
567
+ "table_row",
568
+ // Space at the row's end, unless it is the table's last line, whose end lies between blocks.
569
+ { after: index === rows.length - 1 && index > 0 ? "" : rowEnd(lines[index && index + 1]) },
570
+ (row.children ?? []).map(
571
+ (cell2, column) => schema.node(
572
+ index === 0 ? "table_header" : "table_cell",
573
+ {
574
+ align: node.align?.[column] ?? null,
575
+ pad: cellPadding(written2[index], column)
576
+ },
577
+ inline(context, cell2.children ?? [])
578
+ )
579
+ )
580
+ )
581
+ )
582
+ );
583
+ }
584
+ var FENCE = /^(`{3,}|~{3,})(.*)$/;
585
+ var CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
586
+ var MARKER = /^([-*+]|\d{1,9}[.)])([ \t]*)/;
587
+ function list(context, node, place2) {
588
+ const items = node.children ?? [];
589
+ const markers = items.map((item) => MARKER.exec(linesOf(context, item)[0] ?? ""));
590
+ const first = markers[0]?.[1] ?? (node.ordered ? "1." : "-");
591
+ const built = [];
592
+ items.forEach((item, index) => {
593
+ const lines = linesOf(context, item);
594
+ const marker = markers[index]?.[1] ?? first;
595
+ const spacing = markers[index]?.[2] ?? " ";
596
+ const rest = (lines[0] ?? "").slice(marker.length + spacing.length);
597
+ const task = typeof item.checked === "boolean" ? /^\[([ xX])\]([ \t]*)/.exec(rest) : null;
598
+ const column = marker.length + (spacing.length >= 1 && spacing.length <= 4 && rest ? spacing.length : 1);
599
+ const indent = " ".repeat(column);
600
+ const inner = {
601
+ ...context,
602
+ strip: (line) => {
603
+ const outer = context.strip(line);
604
+ return outer.startsWith(indent) ? outer.slice(column) : outer.trimStart();
605
+ }
606
+ };
607
+ const previous = items[index - 1];
608
+ const gap = previous ? context.source.slice(blockEnd(context, previous), startOf(item)).split("\n").length - 1 : null;
609
+ const children2 = blocks(inner, item.children ?? []);
610
+ built.push(
611
+ schema.node(
612
+ "list_item",
613
+ {
614
+ gap,
615
+ spacing,
616
+ checked: typeof item.checked === "boolean" ? item.checked : null,
617
+ check: task?.[1] ?? null,
618
+ checkSpacing: task?.[2] ?? " "
619
+ },
620
+ children2.length > 0 ? children2 : [schema.node("paragraph")]
621
+ )
622
+ );
623
+ });
624
+ const tight = !node.spread && !items.some((item) => item.spread);
625
+ if (!node.ordered) {
626
+ return schema.node("bullet_list", { ...place2, marker: first, tight }, built);
627
+ }
628
+ const numbers = markers.map((found) => Number.parseInt(found?.[1] ?? "", 10));
629
+ const numbering = numbers.length > 1 && numbers.every((n) => n === numbers[0]) ? "one" : "up";
630
+ return schema.node(
631
+ "ordered_list",
632
+ { ...place2, start: node.start ?? 1, delimiter: first.slice(-1), numbering, tight },
633
+ built
634
+ );
635
+ }
636
+ function quote(context, node, place2) {
637
+ const lines = linesOf(context, node);
638
+ const bare2 = lines.some((line) => /^ {0,3}>(?![ \t]|$)/.test(line));
639
+ const empty = lines.find((line) => /^ {0,3}>[ \t]*$/.test(line));
640
+ const inner = {
641
+ ...context,
642
+ strip: (line) => context.strip(line).replace(/^ {0,3}>[ \t]?/, "")
643
+ };
644
+ const children2 = blocks(inner, node.children ?? []);
645
+ return schema.node(
646
+ "blockquote",
647
+ { ...place2, bare: bare2, blank: empty?.trimStart() ?? ">" },
648
+ children2.length > 0 ? children2 : [schema.node("paragraph")]
649
+ );
650
+ }
651
+ var SET_IN_WHOLE = /* @__PURE__ */ new Set([
652
+ "list",
653
+ "code",
654
+ "blockquote",
655
+ "table",
656
+ "html",
657
+ "definition",
658
+ "footnoteDefinition"
659
+ ]);
660
+ function block(outside, node, place2) {
661
+ const { indent } = place2;
662
+ const context = indent && SET_IN_WHOLE.has(node.type) ? {
663
+ ...outside,
664
+ strip: (line) => {
665
+ const rest = outside.strip(line);
666
+ return rest.startsWith(indent) ? rest.slice(indent.length) : rest;
667
+ }
668
+ } : outside;
669
+ const lines = () => linesOf(context, node);
670
+ switch (node.type) {
671
+ case "paragraph":
672
+ return schema.node("paragraph", place2, inline(context, node.children ?? []));
673
+ case "heading": {
674
+ const written2 = lines();
675
+ const first = written2[0] ?? "";
676
+ const level = node.depth ?? 1;
677
+ const children2 = node.children ?? [];
678
+ const content2 = inline(context, children2);
679
+ const hashes = /^#{1,6}/.exec(first)?.[0];
680
+ if (!hashes) {
681
+ const underline = written2[written2.length - 1]?.trimEnd() ?? null;
682
+ return schema.node("heading", { ...place2, level, underline }, content2);
683
+ }
684
+ const after = first.slice(hashes.length);
685
+ const hashGap = after.slice(0, after.length - after.trimStart().length);
686
+ const last = children2[children2.length - 1];
687
+ const closing = (last ? context.source.slice(endOf(last), endOf(node)) : after.slice(hashGap.length)).trimEnd();
688
+ return schema.node("heading", { ...place2, level, hashGap, closing }, content2);
689
+ }
690
+ case "thematicBreak":
691
+ return schema.node("horizontal_rule", { ...place2, markup: lines()[0]?.trimEnd() ?? null });
692
+ case "code": {
693
+ const written2 = lines();
694
+ const text2 = node.value ? [schema.text(node.value)] : [];
695
+ const fence = FENCE.exec(written2[0] ?? "");
696
+ if (!fence) return schema.node("code_block", { ...place2, indented: true }, text2);
697
+ const marks2 = fence[1];
698
+ const end = written2.length > 1 ? CLOSE.exec(written2[written2.length - 1] ?? "")?.[1] : null;
699
+ const closed = !!end && end[0] === marks2[0] && end.length >= marks2.length;
700
+ return schema.node(
701
+ "code_block",
702
+ {
703
+ ...place2,
704
+ fence: marks2,
705
+ info: fence[2] ?? "",
706
+ close: closed ? written2[written2.length - 1] ?? null : null,
707
+ open: !closed
708
+ },
709
+ text2
710
+ );
711
+ }
712
+ case "blockquote":
713
+ return quote(context, node, place2);
714
+ case "list":
715
+ return list(context, node, place2);
716
+ case "table":
717
+ return table(context, node, place2);
718
+ default: {
719
+ const kind2 = node.type === "html" ? "html" : node.type === "definition" ? "reference" : node.type === "footnoteDefinition" ? "footnote" : "unsupported";
720
+ context.unsupported.push({ reason: kind2, line: node.position?.start.line ?? 1 });
721
+ return schema.node("raw_block", { ...place2, raw: lines().join("\n"), kind: kind2 });
722
+ }
723
+ }
724
+ }
725
+ function blocks(context, nodes3) {
726
+ return nodes3.map((node, index) => {
727
+ const previous = nodes3[index - 1];
728
+ if (!previous) return block(context, node, { gap: null, indent: "" });
729
+ const between = context.source.slice(blockEnd(context, previous), startOf(node));
730
+ const lineStart = context.source.lastIndexOf("\n", startOf(node) - 1) + 1;
731
+ const before = context.strip(context.source.slice(lineStart, startOf(node)));
732
+ return block(context, node, {
733
+ gap: between.split("\n").length - 1,
734
+ indent: before.trim() === "" ? before : ""
735
+ });
736
+ });
737
+ }
738
+ var asRead = /* @__PURE__ */ new WeakSet();
739
+ function parseMarkdown(source) {
740
+ const context = { source, strip: (line) => line, unsupported: [] };
741
+ const nodes3 = readTree(source).children ?? [];
742
+ let lead = source;
743
+ let end = 0;
744
+ const built = nodes3.map((node, index) => {
745
+ const lineStart = source.lastIndexOf("\n", startOf(node) - 1) + 1;
746
+ if (index === 0) lead = source.slice(0, lineStart);
747
+ const gap = index === 0 ? null : source.slice(end, lineStart);
748
+ end = blockEnd(context, node);
749
+ return block(context, node, { gap, indent: source.slice(lineStart, startOf(node)) });
750
+ });
751
+ for (const node of built) asRead.add(node);
752
+ const doc = built.length > 0 ? schema.node("doc", { lead, tail: source.slice(end) }, built) : (
753
+ // A text with nothing in it: what is written into it ends with a line break.
754
+ schema.node("doc", { lead: source, tail: "\n" }, [schema.node("paragraph")])
755
+ );
756
+ return { doc, unsupported: context.unsupported };
757
+ }
758
+
759
+ // src/markdown/serialize.ts
760
+ import { defaultHandlers, toMarkdown } from "mdast-util-to-markdown";
761
+ import { gfmToMarkdown } from "mdast-util-gfm";
762
+
763
+ // src/markdown/meaning.ts
764
+ var SAID = {
765
+ heading: ["level"],
766
+ ordered_list: ["start"],
767
+ list_item: ["checked"],
768
+ image: ["src", "alt", "title"],
769
+ raw_block: ["raw"],
770
+ raw_inline: ["raw"]
771
+ };
772
+ function standsFor(label, href) {
773
+ return [label, `mailto:${label}`, `http://${label}`].includes(href);
774
+ }
775
+ function marksOf(marks2, space, implicit) {
776
+ const said = [];
777
+ for (const mark of marks2) {
778
+ const name = mark.type.name;
779
+ if (name === "source" || implicit && mark.eq(implicit)) continue;
780
+ if (space && (name === "em" || name === "strong" || name === "strike")) continue;
781
+ said.push(
782
+ name === "link" ? `link ${JSON.stringify([mark.attrs.href, mark.attrs.title || null])}` : name
783
+ );
784
+ }
785
+ return said.sort().join(",");
786
+ }
787
+ function runs(node) {
788
+ const out = [];
789
+ const oneLine2 = node.type.name !== "paragraph";
790
+ const text2 = (value, marks2, implicit) => {
791
+ for (const part of value.split(/(\s+)/)) {
792
+ if (!part) continue;
793
+ const space = /^\s/.test(part);
794
+ const own2 = marksOf(marks2, space, implicit);
795
+ const code = marks2.some((mark) => mark.type.name === "code");
796
+ const said = space && !code && part.includes("\n") ? "\n" : part;
797
+ const last2 = out[out.length - 1];
798
+ if (last2 && "text" in last2 && last2.marks === own2) last2.text += said;
799
+ else out.push({ text: said, marks: own2 });
800
+ }
801
+ };
802
+ node.forEach((child, _, index) => {
803
+ if (child.isText) {
804
+ const link = child.marks.find((mark) => mark.type.name === "link");
805
+ const alone = link?.attrs.form === "literal" && standsFor(child.text ?? "", String(link.attrs.href)) && !(index > 0 && link.isInSet(node.child(index - 1).marks)) && !(index + 1 < node.childCount && link.isInSet(node.child(index + 1).marks));
806
+ text2(child.text ?? "", child.marks, alone ? link : void 0);
807
+ return;
808
+ }
809
+ const marks2 = child.marks.filter((mark) => mark.type.name !== "code");
810
+ const isBreak2 = child.type.name === "soft_break" || child.type.name === "hard_break";
811
+ if (isBreak2 && oneLine2) text2(" ", marks2);
812
+ else if (child.type.name === "soft_break") text2("\n", marks2);
813
+ else {
814
+ out.push({
815
+ node: meaning(child),
816
+ marks: marksOf(marks2, child.type.name === "hard_break")
817
+ });
818
+ }
819
+ });
820
+ for (const run2 of out) {
821
+ if ("text" in run2) run2.text = run2.text.replace(/[^\S\n]*\n\s*/g, "\n");
822
+ }
823
+ while (out.length > 0) {
824
+ const end = out[out.length - 1];
825
+ const idle = "text" in end ? end.text.trim() === "" : end.node.type === "hard_break";
826
+ if (!idle) break;
827
+ out.pop();
828
+ }
829
+ const first = out[0];
830
+ if (first && "text" in first) first.text = first.text.replace(/^\s+/, "");
831
+ const last = out[out.length - 1];
832
+ if (last && "text" in last) last.text = last.text.replace(/\s+$/, "");
833
+ return out.filter((run2) => !("text" in run2) || run2.text !== "");
834
+ }
835
+ var isEmpty = (node) => node.type.name === "paragraph" && runs(node).length === 0;
836
+ function saying(node) {
837
+ const blocks2 = Array.from({ length: node.childCount }, (_, i) => node.child(i)).filter(
838
+ (child) => !isEmpty(child)
839
+ );
840
+ const out = [];
841
+ for (const block2 of blocks2) {
842
+ let shown = block2;
843
+ if (isList(block2) && out[out.length - 1]?.type.name === "paragraph") {
844
+ let from = 0;
845
+ while (from < block2.childCount && saysNothing(block2.child(from))) from++;
846
+ if (from === block2.childCount) shown = void 0;
847
+ else if (from > 0) {
848
+ shown = block2.copy(block2.content.cut(offsetOf(block2, from)));
849
+ }
850
+ }
851
+ if (shown) out.push(shown);
852
+ }
853
+ return out;
854
+ }
855
+ var isList = (node) => node.type.name === "bullet_list" || node.type.name === "ordered_list";
856
+ var saysNothing = (item) => Array.from({ length: item.childCount }, (_, i) => item.child(i)).every(isEmpty);
857
+ var offsetOf = (node, index) => {
858
+ let offset = 0;
859
+ for (let i = 0; i < index; i++) offset += node.child(i).nodeSize;
860
+ return offset;
861
+ };
862
+ function runTogether(first, second) {
863
+ if (second === "paragraph") return ["paragraph", "list", "quote", "table"].includes(first);
864
+ if (second === "table") return ["paragraph", "list", "quote", "table"].includes(first);
865
+ if (second === "rule") return first === "paragraph";
866
+ return second === "quote" && first === "quote";
867
+ }
868
+ var KINDS = {
869
+ paragraph: "paragraph",
870
+ bullet_list: "list",
871
+ ordered_list: "list",
872
+ blockquote: "quote",
873
+ table: "table",
874
+ horizontal_rule: "rule",
875
+ heading: "heading",
876
+ code_block: "code"
877
+ };
878
+ var kind = (node) => KINDS[node.type.name] ?? "other";
879
+ function isLoose(list2) {
880
+ const items = Array.from({ length: list2.childCount }, (_, i) => saying(list2.child(i)));
881
+ const parted = items.some(
882
+ (blocks2) => blocks2.some((block2, i) => i > 0 && runTogether(kind(blocks2[i - 1]), kind(block2)))
883
+ );
884
+ if (parted) return true;
885
+ if (items.length === 1 && (items[0]?.length ?? 0) < 2) return false;
886
+ return !list2.attrs.tight;
887
+ }
888
+ function meaning(node, header = false) {
889
+ const name = node.type.name;
890
+ const said = { type: name === "table_header" ? "table_cell" : name };
891
+ for (const attribute of SAID[name] ?? []) said[attribute] = node.attrs[attribute] || null;
892
+ if (name === "list_item" && saying(node)[0]?.type.name !== "paragraph") said.checked = null;
893
+ else if (name === "list_item") said.checked = node.attrs.checked;
894
+ if (node.type.spec.tableRole === "cell" || node.type.spec.tableRole === "header_cell") {
895
+ said.align = header ? node.attrs.align || null : null;
896
+ }
897
+ if (name === "bullet_list" || name === "ordered_list") said.loose = isLoose(node);
898
+ if (name === "code_block") {
899
+ said.info = String(node.attrs.info).trim();
900
+ said.text = node.textContent;
901
+ } else if (node.inlineContent) {
902
+ said.content = runs(node);
903
+ } else if (node.childCount > 0) {
904
+ said.content = saying(node).map(
905
+ (child, index) => meaning(child, name === "table" ? index === 0 : header)
906
+ );
907
+ }
908
+ if (name === "table") rectangle(said.content);
909
+ return said;
910
+ }
911
+ function rectangle(rows) {
912
+ const columns = Math.max(0, ...rows.map((row) => row.content?.length ?? 0));
913
+ for (const row of rows) {
914
+ const cells = row.content ??= [];
915
+ while (cells.length < columns) {
916
+ cells.push({ type: "table_cell", align: null, content: [] });
917
+ }
918
+ }
919
+ }
920
+ var sameMeaning = (a, b) => JSON.stringify(a) === JSON.stringify(b);
921
+
922
+ // src/markdown/serialize.ts
923
+ var OPEN = "";
924
+ var SHUT = "";
925
+ var SHOWN = /^(?!\\)[\p{P}\p{S}]$/u;
926
+ function kept(value) {
927
+ const characters = Array.from(value);
928
+ const first = characters.length > 1 && SHOWN.test(characters[0]) ? 1 : 0;
929
+ const last = characters.length > first + 1 && SHOWN.test(characters[characters.length - 1]) ? 1 : 0;
930
+ const end = characters.length - last;
931
+ return [
932
+ ...characters.slice(0, first),
933
+ OPEN,
934
+ ...characters.slice(first, end),
935
+ SHUT,
936
+ ...characters.slice(end)
937
+ ].join("");
938
+ }
939
+ var bare = (value) => value.replaceAll(OPEN, "").replaceAll(SHUT, "");
940
+ var isBreak = (node) => node.type === "break" || node.type === "svSoft";
941
+ function emphasis(type, sv, children2) {
942
+ const inside = [...children2];
943
+ const before = [];
944
+ const after = [];
945
+ for (let first = inside[0]; first; first = inside[0]) {
946
+ const space = first.type === "text" ? /^\s+/.exec(first.value ?? "")?.[0] ?? "" : "";
947
+ if (isBreak(first)) before.push(inside.shift());
948
+ else if (space) {
949
+ before.push({ type: "text", value: space });
950
+ const rest = first.value.slice(space.length);
951
+ if (rest) inside[0] = { type: "text", value: rest };
952
+ else inside.shift();
953
+ } else break;
954
+ }
955
+ for (let last = inside[inside.length - 1]; last; last = inside[inside.length - 1]) {
956
+ const value = last.type === "text" ? last.value ?? "" : "";
957
+ const rest = value.trimEnd();
958
+ if (isBreak(last)) after.unshift(inside.pop());
959
+ else if (rest.length < value.length) {
960
+ after.unshift({ type: "text", value: value.slice(rest.length) });
961
+ if (rest) inside[inside.length - 1] = { type: "text", value: rest };
962
+ else inside.pop();
963
+ } else break;
964
+ }
965
+ return [...before, ...inside.length > 0 ? [{ type, sv, children: inside }] : [], ...after];
966
+ }
967
+ var MARK_NODES = {
968
+ em: "emphasis",
969
+ strong: "strong",
970
+ strike: "delete"
971
+ };
972
+ var RANK = ["link", "strong", "em", "strike"];
973
+ var own = (mark) => mark.type.name !== "source" && mark.type.name !== "code";
974
+ function leaf(node, flat) {
975
+ const { attrs: attrs2 } = node;
976
+ switch (node.type.name) {
977
+ case "soft_break":
978
+ return flat ? { type: "text", value: " " } : { type: "svSoft", value: String(attrs2.raw) };
979
+ case "hard_break":
980
+ return { type: "break", sv: attrs2 };
981
+ case "image":
982
+ return {
983
+ type: "image",
984
+ url: String(attrs2.src),
985
+ alt: String(attrs2.alt),
986
+ title: attrs2.title,
987
+ sv: attrs2
988
+ };
989
+ default:
990
+ return { type: "svRaw", value: String(attrs2.raw) };
991
+ }
992
+ }
993
+ function phrasing(items, applied, flat) {
994
+ const address = applied.some((mark) => mark.type.name === "link" && mark.attrs.form !== "inline");
995
+ const out = [];
996
+ const pending = (node) => node.marks.filter((mark) => own(mark) && !applied.some((other) => other.eq(mark)));
997
+ for (let i = 0; i < items.length; ) {
998
+ const item = items[i];
999
+ const marks2 = pending(item);
1000
+ if (marks2.length > 0) {
1001
+ let best = marks2[0];
1002
+ let length = 0;
1003
+ for (const mark of marks2) {
1004
+ let end = i;
1005
+ while (end < items.length && mark.isInSet(items[end].marks)) end++;
1006
+ const better = end - i > length || end - i === length && (Number(mark.attrs.depth) - Number(best.attrs.depth) || RANK.indexOf(mark.type.name) - RANK.indexOf(best.type.name)) < 0;
1007
+ if (better) {
1008
+ best = mark;
1009
+ length = end - i;
1010
+ }
1011
+ }
1012
+ const children2 = phrasing(items.slice(i, i + length), [...applied, best], flat);
1013
+ if (best.type.name === "link") {
1014
+ out.push({
1015
+ type: "link",
1016
+ url: String(best.attrs.href),
1017
+ title: best.attrs.title,
1018
+ sv: best.attrs,
1019
+ children: children2
1020
+ });
1021
+ } else {
1022
+ out.push(...emphasis(MARK_NODES[best.type.name], best.attrs, children2));
1023
+ }
1024
+ i += length;
1025
+ continue;
1026
+ }
1027
+ const code = item.marks.find((mark) => mark.type.name === "code");
1028
+ if (code && item.isText) {
1029
+ let value2 = "";
1030
+ for (; i < items.length; i++) {
1031
+ const next = items[i];
1032
+ if (!next.isText || !code.isInSet(next.marks) || pending(next).length > 0) break;
1033
+ value2 += next.text;
1034
+ }
1035
+ out.push({ type: "inlineCode", value: value2, sv: code.attrs });
1036
+ continue;
1037
+ }
1038
+ i++;
1039
+ if (!item.isText) {
1040
+ out.push(leaf(item, flat));
1041
+ continue;
1042
+ }
1043
+ const text2 = item.text ?? "";
1044
+ const source = item.marks.find((mark) => mark.type.name === "source");
1045
+ const value = String(source?.attrs.value ?? "");
1046
+ const times = value ? text2.length / value.length : 0;
1047
+ if (!address && source && Number.isInteger(times) && value.repeat(times) === text2) {
1048
+ out.push({ type: "svRaw", value: String(source.attrs.raw).repeat(times) });
1049
+ continue;
1050
+ }
1051
+ const last = out[out.length - 1];
1052
+ if (last?.type === "text") last.value += text2;
1053
+ else out.push({ type: "text", value: text2 });
1054
+ }
1055
+ return out;
1056
+ }
1057
+ var children = (node) => Array.from({ length: node.childCount }, (_, i) => node.child(i));
1058
+ var isCode = (node) => node.marks.some((mark) => mark.type.name === "code");
1059
+ function content(node) {
1060
+ const items = children(node);
1061
+ const idle = (item) => !!item && (item.type.name === "hard_break" || item.type.name === "soft_break" || item.isText && !isCode(item) && item.text?.trim() === "");
1062
+ while (idle(items[items.length - 1])) items.pop();
1063
+ const leads = (item) => idle(item) && (item?.type.name !== "hard_break" || node.type.name !== "paragraph");
1064
+ while (leads(items[0])) items.shift();
1065
+ const trim = (at, how) => {
1066
+ const item = items[at];
1067
+ if (!item?.isText || isCode(item)) return;
1068
+ const text2 = how(item.text ?? "");
1069
+ if (text2 !== item.text) items[at] = item.type.schema.text(text2, item.marks);
1070
+ };
1071
+ trim(0, (text2) => text2.replace(/^[ \t\n]+/, ""));
1072
+ trim(items.length - 1, (text2) => text2.replace(/[ \t\n]+$/, ""));
1073
+ return items;
1074
+ }
1075
+ var isList2 = (node) => node.type.name === "bullet_list" || node.type.name === "ordered_list";
1076
+ function markerOf(list2, before) {
1077
+ const marker = String(
1078
+ list2.type.name === "bullet_list" ? list2.attrs.marker : list2.attrs.delimiter
1079
+ );
1080
+ if (!before || before.node.type !== list2.type || before.marker !== marker) return marker;
1081
+ if (list2.type.name === "ordered_list") return marker === "." ? ")" : ".";
1082
+ return marker === "-" ? "*" : "-";
1083
+ }
1084
+ function spaced(items, loose) {
1085
+ const gaps = (node) => [node.sv?.gap, ...(node.children ?? []).map((c) => c.sv?.gap)];
1086
+ const parted = items.some((item) => gaps(item).some((gap) => typeof gap === "number" && gap > 1));
1087
+ if (loose === parted) return items;
1088
+ const set = (node, gap) => ({ ...node, sv: { ...node.sv, gap } });
1089
+ return items.map((item, index) => ({
1090
+ ...index > 0 ? set(item, loose ? 2 : 1) : item,
1091
+ children: item.children?.map((block2, at) => at > 0 ? set(block2, loose ? 2 : 1) : block2)
1092
+ }));
1093
+ }
1094
+ function blocksOf(node) {
1095
+ const full = saying(node);
1096
+ const shown = full.length > 0 ? full : children(node).slice(0, 1);
1097
+ let list2;
1098
+ return shown.map((child, index) => {
1099
+ const marker = isList2(child) ? markerOf(child, list2) : void 0;
1100
+ list2 = marker ? { node: child, marker } : void 0;
1101
+ const previous = shown[index - 1];
1102
+ return convert(child, {
1103
+ afterList: !!previous && isList2(previous),
1104
+ last: index === shown.length - 1,
1105
+ marker
1106
+ });
1107
+ });
1108
+ }
1109
+ function convert(node, setting) {
1110
+ const { attrs: attrs2 } = node;
1111
+ const place2 = { gap: attrs2.gap, indent: attrs2.indent };
1112
+ switch (node.type.name) {
1113
+ case "paragraph":
1114
+ return { type: "paragraph", sv: place2, children: phrasing(content(node), [], false) };
1115
+ case "heading": {
1116
+ const level = Number(attrs2.level);
1117
+ const underline = String(attrs2.underline ?? "").trim();
1118
+ const setext = level <= 2 && underline.startsWith(level === 1 ? "=" : "-") && node.content.size > 0;
1119
+ return {
1120
+ type: "heading",
1121
+ depth: level,
1122
+ sv: { ...attrs2, setext },
1123
+ // A heading with `#` is one line.
1124
+ children: phrasing(content(node), [], !setext)
1125
+ };
1126
+ }
1127
+ case "horizontal_rule":
1128
+ return { type: "thematicBreak", sv: attrs2 };
1129
+ case "code_block":
1130
+ return { type: "code", value: node.textContent, sv: { ...attrs2, ...setting } };
1131
+ case "blockquote":
1132
+ return { type: "blockquote", sv: attrs2, children: blocksOf(node) };
1133
+ case "bullet_list":
1134
+ case "ordered_list": {
1135
+ const ordered = node.type.name === "ordered_list";
1136
+ const marker = setting.marker ?? markerOf(node, void 0);
1137
+ const loose = isLoose(node);
1138
+ const items = children(node).map((item, index) => {
1139
+ const number = attrs2.numbering === "one" ? 0 : index;
1140
+ const mark = ordered ? `${Number(attrs2.start) + number}${marker}` : marker;
1141
+ const blocks2 = blocksOf(item);
1142
+ const first = blocks2[0];
1143
+ if (first?.type === "thematicBreak") {
1144
+ const written2 = String(first.sv?.markup ?? "---").trim();
1145
+ if (written2.startsWith(marker)) {
1146
+ blocks2[0] = { ...first, sv: { ...first.sv, markup: marker === "*" ? "___" : "***" } };
1147
+ }
1148
+ }
1149
+ return {
1150
+ type: "listItem",
1151
+ // A box to tick begins a paragraph that says something.
1152
+ checked: first?.type === "paragraph" && first.children?.length ? item.attrs.checked : null,
1153
+ spread: loose,
1154
+ sv: { ...item.attrs, mark },
1155
+ children: blocks2
1156
+ };
1157
+ });
1158
+ return {
1159
+ type: "list",
1160
+ ordered,
1161
+ start: ordered ? Number(attrs2.start) : null,
1162
+ spread: loose,
1163
+ sv: attrs2,
1164
+ children: spaced(items, loose)
1165
+ };
1166
+ }
1167
+ case "table": {
1168
+ const columns = Math.max(0, ...children(node).map((row) => row.childCount));
1169
+ return {
1170
+ type: "table",
1171
+ align: Array.from(
1172
+ { length: columns },
1173
+ (_, i) => node.firstChild?.maybeChild(i)?.attrs.align ?? null
1174
+ ),
1175
+ sv: attrs2,
1176
+ children: children(node).map((row) => ({
1177
+ type: "tableRow",
1178
+ sv: row.attrs,
1179
+ children: Array.from({ length: columns }, (_, i) => {
1180
+ const cell2 = row.maybeChild(i);
1181
+ return {
1182
+ type: "tableCell",
1183
+ sv: cell2?.attrs,
1184
+ children: cell2 ? phrasing(content(cell2), [], true) : []
1185
+ };
1186
+ })
1187
+ }))
1188
+ };
1189
+ }
1190
+ default:
1191
+ return { type: "svRawBlock", value: String(attrs2.raw), sv: attrs2 };
1192
+ }
1193
+ }
1194
+ var asWritten = true;
1195
+ var handle = (run2, extra = {}) => Object.assign(run2, extra);
1196
+ var text = (value) => typeof value === "string" ? value : "";
1197
+ var usual = (type, node, parent, state, info) => defaultHandlers[type]?.(node, parent, state, info) ?? "";
1198
+ function setIn(node, value, whole) {
1199
+ const indent = text(node.sv?.indent);
1200
+ if (!indent) return value;
1201
+ if (!whole) return kept(indent) + value;
1202
+ return value.split("\n").map((line) => line ? indent + line : line).join("\n");
1203
+ }
1204
+ function attention(type) {
1205
+ const marks2 = (node) => {
1206
+ const marker = text(node.sv?.marker);
1207
+ if (type === "delete") {
1208
+ return {
1209
+ construct: "strikethrough",
1210
+ markers: ["~"],
1211
+ sizes: marker === "~" ? [1, 2] : [2, 1]
1212
+ };
1213
+ }
1214
+ const first = marker.startsWith("_") ? "_" : "*";
1215
+ const other = first === "*" ? "_" : "*";
1216
+ return {
1217
+ construct: type,
1218
+ // The serialiser changes marker where two meet; a source that wrote them so is followed while it reads the same.
1219
+ markers: asWritten && marker ? [first] : [first, other],
1220
+ sizes: [type === "strong" ? 2 : 1]
1221
+ };
1222
+ };
1223
+ return handle((node, parent, state, info) => usual(type, node, parent, state, info), {
1224
+ attention: marks2,
1225
+ peek: (node) => marks2(node).markers[0]
1226
+ });
1227
+ }
1228
+ function destination(state, before, url, title) {
1229
+ let value = "](";
1230
+ const angled = !url || url.startsWith("<") || Array.from(url).some((c) => c <= " " || c === "\x7F");
1231
+ const exit = state.enter(angled ? "destinationLiteral" : "destinationRaw");
1232
+ if (angled && (url || title)) {
1233
+ value += `<${state.safe(url, { before: `${before}](<`, after: ">" })}>`;
1234
+ } else if (url) {
1235
+ value += state.safe(url, { before: `${before}](`, after: title ? " " : ")" });
1236
+ }
1237
+ exit();
1238
+ if (title) {
1239
+ const done = state.enter("titleQuote");
1240
+ value += ` "${state.safe(title, { before: `${value} "`, after: '"' })}"`;
1241
+ done();
1242
+ }
1243
+ return `${value})`;
1244
+ }
1245
+ var inCell = (state, value) => state.stack.includes("tableCell") ? value.replace(/(?<!\\)\|/g, "\\|") : value;
1246
+ var handlers = {
1247
+ svRaw: handle((node) => kept(text(node.value)), {
1248
+ peek: (node) => text(node.value).slice(0, 1)
1249
+ }),
1250
+ // A line break and the space around it: the break itself stays in sight, so that what follows it is escaped as a line's start.
1251
+ svSoft: handle(
1252
+ (node) => {
1253
+ const raw = text(node.value);
1254
+ const at = raw.indexOf("\n");
1255
+ const before = raw.slice(0, at);
1256
+ return `${before ? kept(before) : ""}
1257
+ ${raw.slice(at + 1)}`;
1258
+ },
1259
+ { peek: () => "\n" }
1260
+ ),
1261
+ svRawBlock: handle((node) => setIn(node, kept(text(node.value)), true)),
1262
+ emphasis: attention("emphasis"),
1263
+ strong: attention("strong"),
1264
+ delete: attention("delete"),
1265
+ inlineCode: handle(
1266
+ (node, parent, state, info) => {
1267
+ const value = node.value ?? "";
1268
+ const ticks = Number(node.sv?.ticks ?? 0);
1269
+ const run2 = "`".repeat(ticks);
1270
+ const runs2 = value.match(/`+/g) ?? [];
1271
+ const fits = ticks > 0 && !value.includes("\n") && !runs2.includes(run2) && (node.sv?.padded === true || !/^`|`$|^ .* $/.test(value));
1272
+ const written2 = fits ? node.sv?.padded ? `${run2} ${value} ${run2}` : run2 + value + run2 : usual("inlineCode", node, parent, state, info);
1273
+ return kept(inCell(state, written2));
1274
+ },
1275
+ { peek: () => "`" }
1276
+ ),
1277
+ link: handle(
1278
+ (node, _parent, state) => {
1279
+ const sv = node.sv ?? {};
1280
+ const url = node.url ?? "";
1281
+ const only = node.children?.length === 1 ? node.children[0] : void 0;
1282
+ const label = only?.type === "text" ? only.value ?? "" : void 0;
1283
+ if (label !== void 0 && !node.title && !/[\s<>]/.test(label) && standsFor(label, url)) {
1284
+ if (sv.form === "literal") return kept(label);
1285
+ if (sv.form === "autolink") return kept(`<${label}>`);
1286
+ }
1287
+ const exit = state.enter("link");
1288
+ const inside = state.enter("label");
1289
+ const written2 = state.containerPhrasing(node, { before: "[", after: "](" });
1290
+ inside();
1291
+ const same = url === sv.wasHref && (node.title ?? null) === sv.wasTitle;
1292
+ const tail = same && typeof sv.tail === "string" ? kept(sv.tail) : destination(state, `[${written2}`, url, node.title);
1293
+ exit();
1294
+ return `[${written2}${tail}`;
1295
+ },
1296
+ { peek: () => "[" }
1297
+ ),
1298
+ image: handle(
1299
+ (node, _parent, state) => {
1300
+ const sv = node.sv ?? {};
1301
+ const url = node.url ?? "";
1302
+ const alt = node.alt ?? "";
1303
+ const exit = state.enter("image");
1304
+ const inside = state.enter("label");
1305
+ const label = alt === sv.wasAlt && typeof sv.label === "string" ? kept(sv.label) : state.safe(alt, { before: "![", after: "]" });
1306
+ inside();
1307
+ const same = url === sv.wasSrc && (node.title ?? null) === sv.wasTitle;
1308
+ const tail = same && typeof sv.tail === "string" ? kept(sv.tail) : destination(state, `![${label}`, url, node.title);
1309
+ exit();
1310
+ return `![${label}${tail}`;
1311
+ },
1312
+ { peek: () => "!" }
1313
+ ),
1314
+ break: handle(
1315
+ (node, _parent, state) => {
1316
+ if (state.stack.includes("tableCell") || state.stack.includes("headingAtx")) return " ";
1317
+ return `${kept(text(node.sv?.markup) || "\\")}
1318
+ `;
1319
+ },
1320
+ { peek: () => "\\" }
1321
+ ),
1322
+ paragraph: handle(
1323
+ (node, parent, state, info) => setIn(node, usual("paragraph", node, parent, state, info), false)
1324
+ ),
1325
+ heading: handle((node, _parent, state) => {
1326
+ const sv = node.sv ?? {};
1327
+ const exit = state.enter(sv.setext ? "headingSetext" : "headingAtx");
1328
+ const inside = state.enter("phrasing");
1329
+ let value = state.containerPhrasing(node, {
1330
+ before: sv.setext ? "\n" : "# ",
1331
+ after: "\n"
1332
+ });
1333
+ inside();
1334
+ exit();
1335
+ if (sv.setext) return setIn(node, `${value}
1336
+ ${kept(text(sv.underline))}`, false);
1337
+ const hashes = "#".repeat(node.depth ?? 1);
1338
+ const closing = text(sv.closing);
1339
+ if (/^[ \t]/.test(value)) value = `&#x20;${value.slice(1)}`;
1340
+ const gap = text(sv.hashGap) || (value || closing ? " " : "");
1341
+ return setIn(
1342
+ node,
1343
+ `${hashes}${value || closing ? gap : ""}${value}${closing ? kept(closing) : ""}`,
1344
+ false
1345
+ );
1346
+ }),
1347
+ thematicBreak: handle((node) => setIn(node, kept(text(node.sv?.markup) || "---"), false)),
1348
+ code: handle((node) => {
1349
+ const sv = node.sv ?? {};
1350
+ const value = node.value ?? "";
1351
+ if (sv.indented && !sv.afterList && value.trim() && !/^[ \t]*\n|\n[ \t]*$/.test(value)) {
1352
+ const lines = value.split("\n").map((line) => line ? ` ${line}` : line);
1353
+ return setIn(node, kept(lines.join("\n")), true);
1354
+ }
1355
+ const fence = text(sv.fence) || "```";
1356
+ const info = text(sv.info);
1357
+ const char = fence.startsWith("`") && info.includes("`") ? "~" : fence[0];
1358
+ const inside = value.split("\n").map((line) => /^[ \t]*([`~]+)/.exec(line)?.[1] ?? "").filter((run3) => run3.startsWith(char)).map((run3) => run3.length);
1359
+ const written2 = fence.startsWith(char) ? fence.length : 3;
1360
+ const run2 = char.repeat(Math.max(3, written2, ...inside.map((length) => length + 1)));
1361
+ const open = sv.open === true && sv.last === true;
1362
+ const close = run2 === fence && typeof sv.close === "string" ? sv.close : run2;
1363
+ const body = value ? `${value}
1364
+ ` : "";
1365
+ const whole = `${run2}${info}
1366
+ ${body}${open ? "" : close}`;
1367
+ return setIn(node, kept(open ? whole.replace(/\n$/, "") : whole), true);
1368
+ }),
1369
+ blockquote: handle((node, _parent, state, info) => {
1370
+ const exit = state.enter("blockquote");
1371
+ const tracker = state.createTracker(info);
1372
+ tracker.move("> ");
1373
+ tracker.shift(2);
1374
+ const sv = node.sv ?? {};
1375
+ const value = state.indentLines(
1376
+ state.containerFlow(node, tracker.current()),
1377
+ (line, _index, blank) => blank ? text(sv.blank) || ">" : `${sv.bare ? ">" : "> "}${line}`
1378
+ );
1379
+ exit();
1380
+ return setIn(node, value, true);
1381
+ }),
1382
+ list: handle((node, _parent, state, info) => {
1383
+ const exit = state.enter("list");
1384
+ let out = "";
1385
+ (node.children ?? []).forEach((item, index) => {
1386
+ if (index > 0) {
1387
+ const gap = item.sv?.gap;
1388
+ out += "\n".repeat(typeof gap === "number" ? Math.max(1, gap) : node.spread ? 2 : 1);
1389
+ }
1390
+ out += state.handle(item, node, state, info);
1391
+ });
1392
+ exit();
1393
+ return setIn(node, out, true);
1394
+ }),
1395
+ listItem: handle((node, _parent, state, info) => {
1396
+ const sv = node.sv ?? {};
1397
+ const mark = text(sv.mark) || "-";
1398
+ const spacing = text(sv.spacing);
1399
+ const exit = state.enter("listItem");
1400
+ const tracker = state.createTracker(info);
1401
+ tracker.shift(mark.length + 1);
1402
+ const content2 = state.containerFlow(node, tracker.current());
1403
+ exit();
1404
+ const box = typeof node.checked === "boolean" ? `[${node.checked ? sv.check === "X" ? "X" : "x" : " "}]${content2 ? text(sv.checkSpacing) || " " : ""}` : "";
1405
+ const body = box + content2;
1406
+ if (!body) return mark + spacing;
1407
+ const width = spacing.length >= 1 && spacing.length <= 4 ? spacing.length : 1;
1408
+ const indent = " ".repeat(mark.length + width);
1409
+ return state.indentLines(
1410
+ body,
1411
+ (line, index, blank) => index === 0 ? mark + " ".repeat(width) + line : blank ? "" : indent + line
1412
+ );
1413
+ }),
1414
+ table: handle((node, _parent, state) => {
1415
+ const sv = node.sv ?? {};
1416
+ const done = state.enter("table");
1417
+ const rows = (node.children ?? []).map(
1418
+ (row) => (row.children ?? []).map((cell2) => {
1419
+ const exit = state.enter("tableCell");
1420
+ const inside = state.enter("phrasing");
1421
+ const value = state.containerPhrasing(cell2, { before: "|", after: "|" });
1422
+ inside();
1423
+ exit();
1424
+ const pad = cell2.sv?.pad;
1425
+ const [left, right] = !pad || value && !pad[1] && pad[0].length > 1 ? [" ", " "] : pad;
1426
+ return { value, left, right, length: bare(value).length };
1427
+ })
1428
+ );
1429
+ done();
1430
+ const align2 = node.align ?? [];
1431
+ const written2 = splitDelimiter(text(sv.delimiter));
1432
+ const fits = written2.length === align2.length && written2.every((cell2, i) => alignmentOf(cell2) === (align2[i] ?? null));
1433
+ const widths = align2.map((_, column) => {
1434
+ const sizes = rows.map((row) => {
1435
+ const cell2 = row[column];
1436
+ return cell2 ? cell2.left.length + cell2.length + cell2.right.length : 0;
1437
+ });
1438
+ if (fits) sizes.push(written2[column].length);
1439
+ return { even: new Set(sizes).size === 1, needed: 0 };
1440
+ });
1441
+ const leading = sv.leading !== false || align2.length === 1 || rows.some((row) => !row[0]?.value);
1442
+ const trailing = sv.trailing !== false || align2.length === 1 || rows.some((row) => !row.at(-1)?.value);
1443
+ const realign = sv.aligned === true && sv.leading !== false && sv.trailing !== false && (!fits || widths.some((width) => !width.even));
1444
+ if (realign) {
1445
+ widths.forEach((width, column) => {
1446
+ width.needed = Math.max(3, ...rows.map((row) => row[column]?.length ?? 0)) + 2;
1447
+ });
1448
+ }
1449
+ const edge = (line) => {
1450
+ const begun = leading ? `|${line}` : line.trimStart();
1451
+ return trailing ? `${begun}|` : begun.trimEnd();
1452
+ };
1453
+ const ends = (node.children ?? []).map(
1454
+ (row, index) => index === 0 || index < rows.length - 1 ? text(row.sv?.after) : ""
1455
+ );
1456
+ const lines = rows.map(
1457
+ (row, index) => edge(
1458
+ row.map((cell2, column) => {
1459
+ const width = widths[column]?.needed;
1460
+ if (!realign || !width) return cell2.left + cell2.value + cell2.right;
1461
+ const free = width - 2 - cell2.length;
1462
+ const side = align2[column];
1463
+ const before = side === "right" ? free : side === "center" ? Math.floor(free / 2) : 0;
1464
+ return ` ${" ".repeat(before)}${cell2.value}${" ".repeat(free - before)} `;
1465
+ }).join("|")
1466
+ ).concat(ends[index] ?? "")
1467
+ );
1468
+ const delimiter = fits && !realign ? text(sv.delimiter) : edge(
1469
+ align2.map((side, column) => {
1470
+ const width = (realign ? widths[column]?.needed ?? 5 : 5) - 2;
1471
+ const start = side === "left" || side === "center" ? ":" : "";
1472
+ const end = side === "right" || side === "center" ? ":" : "";
1473
+ return ` ${start}${"-".repeat(width - start.length - end.length)}${end} `;
1474
+ }).join("|")
1475
+ );
1476
+ lines.splice(1, 0, delimiter);
1477
+ return setIn(node, lines.join("\n"), true);
1478
+ })
1479
+ };
1480
+ function splitDelimiter(row) {
1481
+ if (!row.trim()) return [];
1482
+ const parts = row.split("|");
1483
+ if (parts.length > 1 && parts[0]?.trim() === "") parts.shift();
1484
+ if (parts.length > 1 && parts[parts.length - 1]?.trim() === "") parts.pop();
1485
+ return parts;
1486
+ }
1487
+ function alignmentOf(cell2) {
1488
+ const value = cell2.trim();
1489
+ const start = value.startsWith(":");
1490
+ const end = value.endsWith(":");
1491
+ return start && end ? "center" : start ? "left" : end ? "right" : null;
1492
+ }
1493
+ var KINDS2 = {
1494
+ paragraph: "paragraph",
1495
+ list: "list",
1496
+ blockquote: "quote",
1497
+ table: "table",
1498
+ thematicBreak: "rule",
1499
+ heading: "heading",
1500
+ code: "code"
1501
+ };
1502
+ var options = {
1503
+ extensions: [gfmToMarkdown()],
1504
+ handlers,
1505
+ join: [
1506
+ (left, right) => {
1507
+ const gap = right.sv?.gap;
1508
+ if (typeof gap === "number" && gap > 1) return gap - 1;
1509
+ if (runTogether(KINDS2[left.type] ?? "other", KINDS2[right.type] ?? "other")) return 1;
1510
+ if (typeof gap === "number") return 0;
1511
+ const begins = !right.ordered || right.start === 1;
1512
+ return left.type === "list" && right.type === "list" && begins ? 0 : void 0;
1513
+ }
1514
+ ]
1515
+ };
1516
+ function marksKept(value) {
1517
+ let out = "";
1518
+ let held = false;
1519
+ const referred = (char) => /[!-/:-@[-`{-~]/.test(char) ? char : `&#x${(char.codePointAt(0) ?? 0).toString(16).toUpperCase()};`;
1520
+ for (let i = 0; i < value.length; i++) {
1521
+ const char = value[i];
1522
+ if (char === OPEN) held = true;
1523
+ else if (char === SHUT) held = false;
1524
+ else if (!held && refersTo(value, i, OPEN)) {
1525
+ const next = String.fromCodePoint(value.codePointAt(i + 5) ?? 0);
1526
+ out += OPEN + referred(next);
1527
+ held = true;
1528
+ i += 4 + next.length;
1529
+ continue;
1530
+ } else if (held && refersTo(value, i, SHUT) && !shutFollows(value, i + 5)) {
1531
+ const last = Array.from(out).pop() ?? "";
1532
+ out = out.slice(0, out.length - last.length) + referred(last) + SHUT;
1533
+ held = false;
1534
+ i += 4;
1535
+ continue;
1536
+ }
1537
+ out += char;
1538
+ }
1539
+ return out;
1540
+ }
1541
+ function refersTo(value, at, mark) {
1542
+ if (!value.startsWith(`&#x${mark.charCodeAt(0)};`, at)) return false;
1543
+ let backslashes = 0;
1544
+ while (value[at - 1 - backslashes] === "\\") backslashes++;
1545
+ return backslashes % 2 === 0;
1546
+ }
1547
+ function shutFollows(value, from) {
1548
+ for (let i = from; i < value.length; i++) {
1549
+ if (value[i] === SHUT) return true;
1550
+ if (value[i] === OPEN || refersTo(value, i, OPEN)) return false;
1551
+ }
1552
+ return false;
1553
+ }
1554
+ var run = (tree) => marksKept(
1555
+ toMarkdown(
1556
+ { type: "root", children: [tree] },
1557
+ options
1558
+ ).replace(/\n$/, "")
1559
+ );
1560
+ function plain(tree) {
1561
+ const keep2 = tree.type === "listItem" ? { mark: tree.sv?.mark, spacing: " " } : void 0;
1562
+ const { sv: _sv, ...rest } = tree;
1563
+ const raw = tree.type === "svRawBlock";
1564
+ return {
1565
+ ...rest,
1566
+ ...raw || tree.type === "code" || tree.type === "heading" ? { sv: unstyled(tree) } : {},
1567
+ ...keep2 ? { sv: keep2 } : {},
1568
+ ...tree.type === "svSoft" ? { type: "text", value: "\n" } : {},
1569
+ ...tree.children ? { children: tree.children.map(plain) } : {}
1570
+ };
1571
+ }
1572
+ function unstyled({ type, sv = {} }) {
1573
+ return type === "code" ? { info: sv.info, last: sv.last, afterList: sv.afterList } : {};
1574
+ }
1575
+ var has = (node, type) => {
1576
+ if (node.type.name === type) return true;
1577
+ return children(node).some((child) => has(child, type));
1578
+ };
1579
+ function fewestEscapes(written2, holds) {
1580
+ const escapes = [];
1581
+ let held = false;
1582
+ for (let i = 0; i < written2.length; i++) {
1583
+ const char = written2[i];
1584
+ if (char === OPEN) held = true;
1585
+ else if (char === SHUT) held = false;
1586
+ else if (!held && char === "\\" && /[!-/:-@[-`{-~]/.test(written2[i + 1] ?? "")) {
1587
+ escapes.push(i);
1588
+ i++;
1589
+ }
1590
+ }
1591
+ const without = (value2, at) => at.reduceRight((rest, i) => rest.slice(0, i) + rest.slice(i + 1), value2);
1592
+ if (escapes.length === 0) return bare(written2);
1593
+ const none = bare(without(written2, escapes));
1594
+ if (holds(none)) return none;
1595
+ let value = written2;
1596
+ for (let i = escapes.length - 1; i >= 0; i--) {
1597
+ const candidate = without(value, [escapes[i]]);
1598
+ if (holds(bare(candidate))) value = candidate;
1599
+ }
1600
+ return bare(value);
1601
+ }
1602
+ function write(node, setting) {
1603
+ const first = writeOnce(node, setting);
1604
+ if (asRead.has(node)) return first.value;
1605
+ const read = parseMarkdown(first.value).doc;
1606
+ if (!first.styled || read.childCount !== 1) return first.value;
1607
+ const again = writeOnce(read.firstChild, setting);
1608
+ return again.styled && first.holds(again.value) ? again.value : first.value;
1609
+ }
1610
+ function writeOnce(node, setting) {
1611
+ const tree = convert(node, setting);
1612
+ const attempt = (form, strict) => {
1613
+ asWritten = strict;
1614
+ const value = run(form);
1615
+ asWritten = true;
1616
+ return value;
1617
+ };
1618
+ const styled = attempt(tree, true);
1619
+ const target = meaning(node);
1620
+ const followed = !setting.last && !asRead.has(node);
1621
+ const holds = (value) => {
1622
+ const read = parseMarkdown(`${value}
1623
+ ${followed ? "\n> x\n" : ""}`).doc;
1624
+ return read.childCount === (followed ? 2 : 1) && sameMeaning(meaning(read.firstChild), target);
1625
+ };
1626
+ const done = (value, as = true) => ({ value, styled: as, holds });
1627
+ if (has(node, "raw_block") || has(node, "raw_inline")) return done(bare(styled), false);
1628
+ if (holds(bare(styled))) return done(fewestEscapes(styled, holds));
1629
+ const other = attempt(tree, false);
1630
+ if (holds(bare(other))) return done(fewestEscapes(other, holds));
1631
+ const simple = attempt(plain(tree), false);
1632
+ return done(holds(bare(simple)) ? fewestEscapes(simple, holds) : bare(simple));
1633
+ }
1634
+ var written = /* @__PURE__ */ new WeakMap();
1635
+ function blockText(node, setting) {
1636
+ const key = `${setting.afterList ? 1 : 0}${setting.last ? 1 : 0}${setting.marker ?? ""}`;
1637
+ let forms = written.get(node);
1638
+ if (!forms) written.set(node, forms = /* @__PURE__ */ new Map());
1639
+ let value = forms.get(key);
1640
+ if (value === void 0) forms.set(key, value = write(node, setting));
1641
+ return value;
1642
+ }
1643
+ function apart(first, gap, second) {
1644
+ const read = parseMarkdown(first[1] + gap + second[1]).doc;
1645
+ return read.childCount === 2 && sameMeaning(meaning(read.child(0)), meaning(first[0])) && sameMeaning(meaning(read.child(1)), meaning(second[0]));
1646
+ }
1647
+ var BLANK_LINE = /\n[ \t]*\n/;
1648
+ var joined = /* @__PURE__ */ new WeakMap();
1649
+ function serializeMarkdown(doc) {
1650
+ const blocks2 = children(doc).filter((node) => !isEmpty(node));
1651
+ let out = "";
1652
+ let before;
1653
+ let list2;
1654
+ blocks2.forEach((node, index) => {
1655
+ const marker = isList2(node) ? markerOf(node, list2) : void 0;
1656
+ const value = blockText(node, {
1657
+ afterList: !!before && isList2(before.node),
1658
+ last: index === blocks2.length - 1,
1659
+ marker
1660
+ });
1661
+ if (before) {
1662
+ let gap = typeof node.attrs.gap === "string" ? node.attrs.gap : "\n\n";
1663
+ if (!gap.includes("\n")) gap = "\n\n";
1664
+ if (!BLANK_LINE.test(gap)) {
1665
+ let known = joined.get(before.node);
1666
+ if (!known) joined.set(before.node, known = /* @__PURE__ */ new WeakMap());
1667
+ let holds = known.get(node);
1668
+ if (holds === void 0) {
1669
+ holds = apart([before.node, before.text], gap, [node, value]);
1670
+ known.set(node, holds);
1671
+ }
1672
+ if (!holds) gap = "\n\n";
1673
+ }
1674
+ out += gap;
1675
+ }
1676
+ out += value;
1677
+ before = { node, text: value };
1678
+ list2 = marker ? { node, marker } : void 0;
1679
+ });
1680
+ return blocks2.length === 0 ? String(doc.attrs.lead) : `${String(doc.attrs.lead)}${out}${String(doc.attrs.tail)}`;
1681
+ }
1682
+
1683
+ // src/markdown/check.ts
1684
+ var BOM = "\uFEFF";
1685
+ var MOST_ISSUES = 20;
1686
+ function openMarkdown(text2) {
1687
+ try {
1688
+ return readAndCheck(text2);
1689
+ } catch {
1690
+ return {
1691
+ doc: schema.node("doc", null, schema.node("code_block", null, text2 ? schema.text(text2) : [])),
1692
+ format: { mark: false, ending: "\n" },
1693
+ editable: false,
1694
+ issues: [{ reason: "unsupported", line: 1 }]
1695
+ };
1696
+ }
1697
+ }
1698
+ function readAndCheck(text2) {
1699
+ const mark = text2.startsWith(BOM);
1700
+ const body = mark ? text2.slice(1) : text2;
1701
+ const lines = splitLines(body);
1702
+ const ending = lines.find((line) => line.ending !== "")?.ending || "\n";
1703
+ const issues = [];
1704
+ const other = lines.findIndex((line) => line.ending !== "" && line.ending !== ending);
1705
+ if (other !== -1) issues.push({ reason: "line-endings", line: other + 1 });
1706
+ const source = body.replace(/\r\n?/g, "\n");
1707
+ const { doc, unsupported } = parseMarkdown(source);
1708
+ for (const { reason, line } of unsupported) {
1709
+ if (!issues.some((issue) => issue.reason === reason && issue.line === line)) {
1710
+ issues.push({ reason, line });
1711
+ }
1712
+ }
1713
+ const found = ["", ""].map((mark2) => source.indexOf(mark2)).filter((at) => at >= 0);
1714
+ const control = found.length > 0 ? Math.min(...found) : -1;
1715
+ if (control !== -1) {
1716
+ issues.push({ reason: "unsupported", line: source.slice(0, control).split("\n").length });
1717
+ }
1718
+ if (unsupported.length === 0 && control === -1) {
1719
+ const back = serializeMarkdown(doc);
1720
+ if (back !== source) {
1721
+ const before = source.split("\n");
1722
+ const after = back.split("\n");
1723
+ for (const run2 of diffSequences(before, after)) {
1724
+ if (run2.equal) continue;
1725
+ issues.push({
1726
+ reason: "formatting",
1727
+ line: Math.min(run2.aStart + 1, before.length),
1728
+ found: before.slice(run2.aStart, run2.aEnd).join("\n"),
1729
+ written: after.slice(run2.bStart, run2.bEnd).join("\n")
1730
+ });
1731
+ }
1732
+ }
1733
+ }
1734
+ issues.sort((a, b) => a.line - b.line);
1735
+ return {
1736
+ doc,
1737
+ format: { mark, ending },
1738
+ editable: issues.length === 0,
1739
+ issues: issues.slice(0, MOST_ISSUES)
1740
+ };
1741
+ }
1742
+ function writeMarkdown(doc, { mark, ending }) {
1743
+ const text2 = serializeMarkdown(doc);
1744
+ return (mark ? BOM : "") + (ending === "\n" ? text2 : text2.replace(/\n/g, ending));
1745
+ }
1746
+ function checkMarkdownRoundTrip(text2) {
1747
+ const { editable, issues } = openMarkdown(text2);
1748
+ return { editable, issues };
1749
+ }
1750
+ var REASONS = {
1751
+ html: "Raw HTML",
1752
+ footnote: "A footnote",
1753
+ reference: "A reference-style link or its definition",
1754
+ "line-endings": "Line breaks of more than one kind",
1755
+ formatting: "Formatting that would be rewritten",
1756
+ unsupported: "Something the rich view cannot hold"
1757
+ };
1758
+ function describeMarkdownIssue(issue) {
1759
+ return `Line ${issue.line}: ${REASONS[issue.reason]}.`;
1760
+ }
1761
+
1762
+ // src/components/MarkdownEditor/commands.ts
1763
+ import { chainCommands, exitCode, lift, setBlockType, toggleMark } from "prosemirror-commands";
1764
+ import { liftListItem, sinkListItem, splitListItem, wrapInList } from "prosemirror-schema-list";
1765
+ import {
1766
+ Selection,
1767
+ TextSelection
1768
+ } from "prosemirror-state";
1769
+ import { addRowAfter, goToNextCell, isInTable, selectedRect } from "prosemirror-tables";
1770
+ var { nodes, marks } = schema;
1771
+ function around(state) {
1772
+ const { $from } = state.selection;
1773
+ const out = [];
1774
+ for (let depth = $from.depth; depth > 0; depth--) {
1775
+ out.push({ node: $from.node(depth), pos: $from.before(depth), depth });
1776
+ }
1777
+ return out;
1778
+ }
1779
+ var within = (state, type) => around(state).find(({ node }) => node.type === type);
1780
+ var isList3 = (node) => node.type === nodes.bullet_list || node.type === nodes.ordered_list;
1781
+ var nearestList = (state) => around(state).find(({ node }) => isList3(node));
1782
+ function markIsOn(state, type) {
1783
+ const { from, to, empty, $from } = state.selection;
1784
+ if (empty) return !!type.isInSet(state.storedMarks ?? $from.marks());
1785
+ return state.doc.rangeHasMark(from, to, type);
1786
+ }
1787
+ function blockStyle(state) {
1788
+ const { parent } = state.selection.$from;
1789
+ if (parent.type === nodes.code_block) return "code";
1790
+ if (parent.type === nodes.heading) return Number(parent.attrs.level);
1791
+ return "paragraph";
1792
+ }
1793
+ var makeCode = (state, dispatch) => {
1794
+ if (!setBlockType(nodes.code_block)(state)) return false;
1795
+ const { from, to } = state.selection;
1796
+ const breaks = [];
1797
+ state.doc.nodesBetween(from, to, (node, pos) => {
1798
+ if (!node.inlineContent) return true;
1799
+ node.forEach((child, offset) => {
1800
+ if (child.type === nodes.soft_break || child.type === nodes.hard_break) {
1801
+ breaks.push(pos + 1 + offset);
1802
+ }
1803
+ });
1804
+ return false;
1805
+ });
1806
+ const tr = state.tr;
1807
+ for (const at of breaks) tr.replaceWith(at, at + 1, schema.text("\n"));
1808
+ dispatch?.(tr.setBlockType(from, to, nodes.code_block).scrollIntoView());
1809
+ return true;
1810
+ };
1811
+ function setStyle(style) {
1812
+ if (style === "paragraph") return setBlockType(nodes.paragraph);
1813
+ if (style === "code") return makeCode;
1814
+ return setBlockType(nodes.heading, { level: style });
1815
+ }
1816
+ function listKind(state) {
1817
+ const list2 = nearestList(state)?.node;
1818
+ if (!list2) return void 0;
1819
+ if (within(state, nodes.list_item)?.node.attrs.checked !== null) return "task";
1820
+ return list2.type === nodes.ordered_list ? "ordered" : "bullet";
1821
+ }
1822
+ function setBoxes(on) {
1823
+ return (state, dispatch) => {
1824
+ const list2 = nearestList(state);
1825
+ if (!list2) return false;
1826
+ const tr = state.tr;
1827
+ list2.node.forEach((item, offset) => {
1828
+ const checked = on ? item.attrs.checked ?? false : null;
1829
+ tr.setNodeMarkup(list2.pos + 1 + offset, void 0, { ...item.attrs, checked });
1830
+ });
1831
+ dispatch?.(tr);
1832
+ return true;
1833
+ };
1834
+ }
1835
+ function toggleList(kind2) {
1836
+ const type = kind2 === "ordered" ? nodes.ordered_list : nodes.bullet_list;
1837
+ return (state, dispatch, view) => {
1838
+ const current = listKind(state);
1839
+ if (current === kind2) return liftListItem(nodes.list_item)(state, dispatch, view);
1840
+ const list2 = nearestList(state);
1841
+ if (!list2) {
1842
+ let wrapped;
1843
+ if (!wrapInList(type)(state, (tr2) => wrapped = tr2) || !wrapped) return false;
1844
+ if (kind2 === "task") {
1845
+ const tr2 = wrapped;
1846
+ setBoxes(true)(state.apply(tr2), (boxes) => boxes.steps.forEach((step) => tr2.step(step)));
1847
+ }
1848
+ dispatch?.(wrapped);
1849
+ return true;
1850
+ }
1851
+ const tr = state.tr;
1852
+ if (kind2 !== "task" && list2.node.type !== type) {
1853
+ tr.setNodeMarkup(list2.pos, type, { gap: list2.node.attrs.gap, tight: list2.node.attrs.tight });
1854
+ }
1855
+ list2.node.forEach((item, offset) => {
1856
+ const checked = kind2 === "task" ? item.attrs.checked ?? false : null;
1857
+ tr.setNodeMarkup(list2.pos + 1 + offset, void 0, { ...item.attrs, checked });
1858
+ });
1859
+ dispatch?.(tr.scrollIntoView());
1860
+ return true;
1861
+ };
1862
+ }
1863
+ var toggleTick = (state, dispatch) => {
1864
+ const item = within(state, nodes.list_item);
1865
+ if (!item || item.node.attrs.checked === null) return false;
1866
+ dispatch?.(
1867
+ state.tr.setNodeMarkup(item.pos, void 0, {
1868
+ ...item.node.attrs,
1869
+ checked: !item.node.attrs.checked
1870
+ })
1871
+ );
1872
+ return true;
1873
+ };
1874
+ var isQuoted = (state) => !!within(state, nodes.blockquote);
1875
+ var toggleQuote = (state, dispatch, view) => {
1876
+ if (isQuoted(state)) return lift(state, dispatch, view);
1877
+ const { $from, $to } = state.selection;
1878
+ const range = $from.blockRange($to, (parent) => !isList3(parent));
1879
+ if (!range?.parent.canReplaceWith(range.startIndex, range.endIndex, nodes.blockquote)) {
1880
+ return false;
1881
+ }
1882
+ dispatch?.(state.tr.wrap(range, [{ type: nodes.blockquote }]).scrollIntoView());
1883
+ return true;
1884
+ };
1885
+ function insertBlock(block2, enter) {
1886
+ return (state, dispatch) => {
1887
+ const { $from } = state.selection;
1888
+ if ($from.parent.type.spec.code || isInTable(state)) return false;
1889
+ const tr = state.tr.replaceSelectionWith(block2, false);
1890
+ let at = -1;
1891
+ tr.doc.descendants((node, pos) => {
1892
+ if (node === block2) at = pos;
1893
+ });
1894
+ if (at < 0) return false;
1895
+ const after = at + block2.nodeSize;
1896
+ const next = tr.doc.resolve(after).nodeAfter;
1897
+ if (!next?.isTextblock) tr.insert(after, nodes.paragraph.create());
1898
+ tr.setSelection(
1899
+ enter ? Selection.near(tr.doc.resolve(at + 1)) : TextSelection.create(tr.doc, after + 1)
1900
+ );
1901
+ dispatch?.(tr.scrollIntoView());
1902
+ return true;
1903
+ };
1904
+ }
1905
+ var insertRule = (state, dispatch, view) => insertBlock(nodes.horizontal_rule.create(), false)(state, dispatch, view);
1906
+ var insertTable = (state, dispatch, view) => {
1907
+ const row = (type) => nodes.table_row.create(null, [type.create(), type.create()]);
1908
+ const table2 = nodes.table.create(null, [row(nodes.table_header), row(nodes.table_cell)]);
1909
+ return insertBlock(table2, true)(state, dispatch, view);
1910
+ };
1911
+ function insertInline(node) {
1912
+ return (state, dispatch) => {
1913
+ const { parent } = state.selection.$from;
1914
+ if (!parent.inlineContent || parent.type.spec.code) return false;
1915
+ dispatch?.(state.tr.replaceSelectionWith(node, false).scrollIntoView());
1916
+ return true;
1917
+ };
1918
+ }
1919
+ var insertImage = (src, alt, title) => insertInline(nodes.image.create({ src, alt, title: title || null }));
1920
+ var insertBreak = (state, dispatch, view) => {
1921
+ const { parent } = state.selection.$from;
1922
+ if (parent.type !== nodes.paragraph) return false;
1923
+ return insertInline(nodes.hard_break.create())(state, dispatch, view);
1924
+ };
1925
+ var hardBreak = chainCommands(exitCode, insertBreak);
1926
+ function linkAt(state) {
1927
+ const { from, to, empty, $from } = state.selection;
1928
+ let start = from;
1929
+ let end = to;
1930
+ const found = empty ? $from.marks().concat($from.nodeAfter?.marks ?? []) : state.doc.nodeAt(from)?.marks ?? [];
1931
+ const mark = marks.link.isInSet(found);
1932
+ if (mark) {
1933
+ const parent = $from.parent;
1934
+ let offset = $from.start();
1935
+ let runStart = -1;
1936
+ parent.forEach((child) => {
1937
+ const next = offset + child.nodeSize;
1938
+ if (mark.isInSet(child.marks)) {
1939
+ if (runStart < 0) runStart = offset;
1940
+ if (runStart <= from && next >= from) {
1941
+ start = Math.min(from, runStart);
1942
+ end = Math.max(to, next);
1943
+ }
1944
+ } else runStart = -1;
1945
+ offset = next;
1946
+ });
1947
+ }
1948
+ return {
1949
+ exists: !!mark,
1950
+ href: String(mark?.attrs.href ?? ""),
1951
+ title: String(mark?.attrs.title ?? ""),
1952
+ text: state.doc.textBetween(start, end),
1953
+ from: start,
1954
+ to: end
1955
+ };
1956
+ }
1957
+ function setLink({ from, to }, href, title, text2) {
1958
+ return (state, dispatch) => {
1959
+ const parent = state.doc.resolve(from).parent;
1960
+ if (!parent.inlineContent || parent.type.spec.code) return false;
1961
+ const tr = state.tr.removeMark(from, to, marks.link);
1962
+ if (href) {
1963
+ const mark = marks.link.create({ href, title: title || null });
1964
+ if (from === to) {
1965
+ const shown = text2 || href;
1966
+ tr.insertText(shown, from);
1967
+ tr.addMark(from, from + shown.length, mark);
1968
+ tr.setSelection(TextSelection.create(tr.doc, from + shown.length));
1969
+ } else tr.addMark(from, to, mark);
1970
+ }
1971
+ dispatch?.(tr.scrollIntoView());
1972
+ return true;
1973
+ };
1974
+ }
1975
+ var toggle = (name) => toggleMark(marks[name]);
1976
+ var splitItem = (state, dispatch, view) => {
1977
+ const item = within(state, nodes.list_item)?.node;
1978
+ if (!item) return false;
1979
+ const attrs2 = { checked: item.attrs.checked === null ? null : false };
1980
+ return splitListItem(nodes.list_item, attrs2)(state, dispatch, view);
1981
+ };
1982
+ var indentItem = sinkListItem(nodes.list_item);
1983
+ var outdentItem = liftListItem(nodes.list_item);
1984
+ var cellBelow = (state, dispatch) => {
1985
+ if (!isInTable(state)) return false;
1986
+ const rect = selectedRect(state);
1987
+ const row = rect.bottom;
1988
+ if (row < rect.map.height) {
1989
+ const cell2 = rect.tableStart + rect.map.positionAt(row, rect.left, rect.table);
1990
+ dispatch?.(state.tr.setSelection(Selection.near(state.doc.resolve(cell2 + 1))).scrollIntoView());
1991
+ return true;
1992
+ }
1993
+ if (!dispatch) return true;
1994
+ return addRowAfter(state, (tr) => {
1995
+ const table2 = tr.doc.nodeAt(rect.tableStart - 1);
1996
+ if (!table2) return dispatch(tr);
1997
+ let cell2 = rect.tableStart;
1998
+ for (let i = 0; i < table2.childCount - 1; i++) cell2 += table2.child(i).nodeSize;
1999
+ cell2 += 1;
2000
+ for (let i = 0; i < rect.left; i++) cell2 += table2.lastChild?.child(i).nodeSize ?? 0;
2001
+ dispatch(tr.setSelection(Selection.near(tr.doc.resolve(cell2 + 1))).scrollIntoView());
2002
+ });
2003
+ };
2004
+ var nextCell = goToNextCell(1);
2005
+ var previousCell = goToNextCell(-1);
2006
+
2007
+ // src/components/MarkdownEditor/Dialogs.tsx
2008
+ import { useId, useState } from "react";
2009
+ import styles from "./MarkdownEditor.module.css";
2010
+ import { jsx, jsxs } from "react/jsx-runtime";
2011
+ function keep(event) {
2012
+ event.preventDefault();
2013
+ event.stopPropagation();
2014
+ }
2015
+ function LinkDialog({
2016
+ link,
2017
+ onApply,
2018
+ onClose
2019
+ }) {
2020
+ const [href, setHref] = useState(link.href);
2021
+ const [title, setTitle] = useState(link.title);
2022
+ const [text2, setText] = useState("");
2023
+ const form = useId();
2024
+ const submit = (event) => {
2025
+ keep(event);
2026
+ onApply(href.trim(), title.trim(), text2);
2027
+ };
2028
+ return /* @__PURE__ */ jsx(
2029
+ Dialog,
2030
+ {
2031
+ open: true,
2032
+ onClose,
2033
+ size: "sm",
2034
+ "aria-label": "Link",
2035
+ title: "Link",
2036
+ footer: /* @__PURE__ */ jsxs("div", { className: styles.actions, children: [
2037
+ link.exists && /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: () => onApply("", "", ""), children: "Remove link" }),
2038
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", onClick: onClose, children: "Cancel" }),
2039
+ /* @__PURE__ */ jsx(Button, { type: "submit", form, children: "Apply" })
2040
+ ] }),
2041
+ children: /* @__PURE__ */ jsxs("form", { id: form, className: styles.form, onSubmit: submit, children: [
2042
+ /* @__PURE__ */ jsx(FormField, { label: "Address", required: true, children: (field) => /* @__PURE__ */ jsx(Input, { ...field, value: href, onChange: (event) => setHref(event.target.value) }) }),
2043
+ link.from === link.to && /* @__PURE__ */ jsx(FormField, { label: "Text", hint: "Left empty, the address is shown.", children: (field) => /* @__PURE__ */ jsx(Input, { ...field, value: text2, onChange: (event) => setText(event.target.value) }) }),
2044
+ /* @__PURE__ */ jsx(FormField, { label: "Title", hint: "Optional: shown on pointing at the link.", children: (field) => /* @__PURE__ */ jsx(Input, { ...field, value: title, onChange: (event) => setTitle(event.target.value) }) })
2045
+ ] })
2046
+ }
2047
+ );
2048
+ }
2049
+ function ImageDialog({
2050
+ onApply,
2051
+ onClose
2052
+ }) {
2053
+ const [src, setSrc] = useState("");
2054
+ const [alt, setAlt] = useState("");
2055
+ const [title, setTitle] = useState("");
2056
+ const form = useId();
2057
+ const submit = (event) => {
2058
+ keep(event);
2059
+ if (src.trim()) onApply(src.trim(), alt.trim(), title.trim());
2060
+ };
2061
+ return /* @__PURE__ */ jsx(
2062
+ Dialog,
2063
+ {
2064
+ open: true,
2065
+ onClose,
2066
+ size: "sm",
2067
+ "aria-label": "Image",
2068
+ title: "Image",
2069
+ footer: /* @__PURE__ */ jsxs("div", { className: styles.actions, children: [
2070
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "secondary", onClick: onClose, children: "Cancel" }),
2071
+ /* @__PURE__ */ jsx(Button, { type: "submit", form, children: "Insert" })
2072
+ ] }),
2073
+ children: /* @__PURE__ */ jsxs("form", { id: form, className: styles.form, onSubmit: submit, children: [
2074
+ /* @__PURE__ */ jsx(FormField, { label: "Address", hint: "As it is to be written in the text.", required: true, children: (field) => /* @__PURE__ */ jsx(Input, { ...field, value: src, onChange: (event) => setSrc(event.target.value) }) }),
2075
+ /* @__PURE__ */ jsx(FormField, { label: "Description", hint: "Read in place of the image.", children: (field) => /* @__PURE__ */ jsx(Input, { ...field, value: alt, onChange: (event) => setAlt(event.target.value) }) }),
2076
+ /* @__PURE__ */ jsx(FormField, { label: "Title", hint: "Optional.", children: (field) => /* @__PURE__ */ jsx(Input, { ...field, value: title, onChange: (event) => setTitle(event.target.value) }) })
2077
+ ] })
2078
+ }
2079
+ );
2080
+ }
2081
+
2082
+ // src/components/MarkdownEditor/RichView.tsx
2083
+ import { useEffect, useLayoutEffect, useRef } from "react";
2084
+ import { EditorState } from "prosemirror-state";
2085
+ import { EditorView } from "prosemirror-view";
2086
+
2087
+ // src/components/MarkdownEditor/nodeViews.ts
2088
+ import styles2 from "./MarkdownEditor.module.css";
2089
+ var classed = (tag, className) => {
2090
+ const element = document.createElement(tag);
2091
+ element.className = className ?? "";
2092
+ return element;
2093
+ };
2094
+ function imageView(resolve) {
2095
+ return (node) => {
2096
+ const source = String(node.attrs.src);
2097
+ const alt = String(node.attrs.alt);
2098
+ const dom = classed("span", styles2.image);
2099
+ const address = source ? resolve?.(source) : null;
2100
+ dom.dataset.image = source;
2101
+ dom.dataset.address = address ?? "";
2102
+ if (address) {
2103
+ const picture = document.createElement("img");
2104
+ picture.alt = alt;
2105
+ if (node.attrs.title) picture.title = String(node.attrs.title);
2106
+ picture.src = address;
2107
+ dom.append(picture);
2108
+ } else {
2109
+ const missing = classed("span", styles2.missing);
2110
+ missing.setAttribute("role", "img");
2111
+ missing.setAttribute("aria-label", alt || "Image without a description");
2112
+ missing.textContent = alt || "Image";
2113
+ missing.title = source;
2114
+ dom.append(missing);
2115
+ }
2116
+ return { dom };
2117
+ };
2118
+ }
2119
+ function imagesChanged(root, resolve) {
2120
+ return Array.from(root.querySelectorAll("[data-image]")).some(({ dataset }) => {
2121
+ const source = dataset.image ?? "";
2122
+ return (source && resolve?.(source) || "") !== dataset.address;
2123
+ });
2124
+ }
2125
+ var itemView = (initial, view, position) => {
2126
+ let node = initial;
2127
+ const dom = document.createElement("li");
2128
+ let box;
2129
+ let content2 = dom;
2130
+ if (node.attrs.checked !== null) {
2131
+ dom.className = styles2.task ?? "";
2132
+ box = classed("input", styles2.box);
2133
+ box.type = "checkbox";
2134
+ box.tabIndex = -1;
2135
+ box.setAttribute("aria-label", "Done");
2136
+ box.contentEditable = "false";
2137
+ box.checked = node.attrs.checked === true;
2138
+ box.disabled = !view.editable;
2139
+ box.addEventListener("change", () => {
2140
+ const at = position();
2141
+ if (at === void 0 || !view.editable) return;
2142
+ const checked = box?.checked ?? false;
2143
+ view.dispatch(view.state.tr.setNodeMarkup(at, void 0, { ...node.attrs, checked }));
2144
+ });
2145
+ content2 = classed("div", styles2.taskText);
2146
+ dom.append(box, content2);
2147
+ }
2148
+ return {
2149
+ dom,
2150
+ contentDOM: content2,
2151
+ update(next) {
2152
+ if (next.type !== node.type || next.attrs.checked === null !== (box === void 0)) {
2153
+ return false;
2154
+ }
2155
+ node = next;
2156
+ if (box) box.checked = next.attrs.checked === true;
2157
+ return true;
2158
+ },
2159
+ stopEvent: (event) => event.target === box,
2160
+ ignoreMutation: (mutation) => mutation.target === box
2161
+ };
2162
+ };
2163
+ var nodeViews = (resolve) => ({
2164
+ image: imageView(resolve),
2165
+ list_item: itemView
2166
+ });
2167
+
2168
+ // src/components/MarkdownEditor/plugins.ts
2169
+ import { baseKeymap, chainCommands as chainCommands2 } from "prosemirror-commands";
2170
+ import { gapCursor } from "prosemirror-gapcursor";
2171
+ import { history, redo, undo } from "prosemirror-history";
2172
+ import {
2173
+ inputRules,
2174
+ InputRule,
2175
+ textblockTypeInputRule,
2176
+ undoInputRule,
2177
+ wrappingInputRule
2178
+ } from "prosemirror-inputrules";
2179
+ import { keymap } from "prosemirror-keymap";
2180
+ import { Plugin, TextSelection as TextSelection2 } from "prosemirror-state";
2181
+ import { tableEditing } from "prosemirror-tables";
2182
+ var { nodes: nodes2 } = schema;
2183
+ var typing = inputRules({
2184
+ rules: [
2185
+ textblockTypeInputRule(/^(#{1,6})\s$/, nodes2.heading, (match) => ({
2186
+ level: match[1]?.length ?? 1
2187
+ })),
2188
+ wrappingInputRule(/^([-*+])\s$/, nodes2.bullet_list, (match) => ({ marker: match[1] })),
2189
+ wrappingInputRule(
2190
+ /^(\d{1,9})([.)])\s$/,
2191
+ nodes2.ordered_list,
2192
+ (match) => ({ start: Number(match[1]), delimiter: match[2] }),
2193
+ (match, node) => node.childCount + Number(node.attrs.start) === Number(match[1])
2194
+ ),
2195
+ wrappingInputRule(/^>\s$/, nodes2.blockquote),
2196
+ textblockTypeInputRule(/^```$/, nodes2.code_block),
2197
+ // A box, typed at the start of a list's item.
2198
+ new InputRule(/^\[([ xX])\]\s$/, (state, match, start, end) => {
2199
+ const { $from } = state.selection;
2200
+ const item = $from.node(-1);
2201
+ if (item?.type !== nodes2.list_item || $from.index(-1) !== 0) return null;
2202
+ const tr = state.tr.delete(start, end);
2203
+ return tr.setNodeMarkup($from.before(-1), void 0, {
2204
+ ...item.attrs,
2205
+ checked: match[1] !== " "
2206
+ });
2207
+ }),
2208
+ // Three dashes alone make a rule, with a paragraph to go on in.
2209
+ new InputRule(/^(?:---|\*\*\*)$/, (state, _match, start, end) => {
2210
+ const { $from } = state.selection;
2211
+ if ($from.parent.type !== nodes2.paragraph || $from.depth !== 1 || end !== $from.end()) {
2212
+ return null;
2213
+ }
2214
+ const from = start - 1;
2215
+ const tr = state.tr.replaceWith(from, $from.after(), [
2216
+ nodes2.horizontal_rule.create(),
2217
+ nodes2.paragraph.create()
2218
+ ]);
2219
+ return tr.setSelection(TextSelection2.create(tr.doc, from + 2));
2220
+ })
2221
+ ]
2222
+ });
2223
+ function leaving() {
2224
+ let leave = false;
2225
+ return {
2226
+ plugin: new Plugin({
2227
+ props: {
2228
+ handleKeyDown: (_view, event) => {
2229
+ if (event.key === "Escape") leave = true;
2230
+ else if (event.key !== "Tab" && event.key !== "Shift") leave = false;
2231
+ return false;
2232
+ }
2233
+ }
2234
+ }),
2235
+ keys: (command) => (state, dispatch, view) => {
2236
+ if (leave) {
2237
+ leave = false;
2238
+ return false;
2239
+ }
2240
+ return command(state, dispatch, view);
2241
+ }
2242
+ };
2243
+ }
2244
+ function plugins({ link }) {
2245
+ const way = leaving();
2246
+ const keys = {
2247
+ "Mod-z": undo,
2248
+ "Shift-Mod-z": redo,
2249
+ "Mod-y": redo,
2250
+ Backspace: chainCommands2(undoInputRule, baseKeymap.Backspace),
2251
+ "Mod-b": toggle("strong"),
2252
+ "Mod-i": toggle("em"),
2253
+ "Mod-e": toggle("code"),
2254
+ "Shift-Mod-x": toggle("strike"),
2255
+ "Mod-k": () => {
2256
+ link();
2257
+ return true;
2258
+ },
2259
+ "Mod-Alt-0": setStyle("paragraph"),
2260
+ "Shift-Mod-7": toggleList("ordered"),
2261
+ "Shift-Mod-8": toggleList("bullet"),
2262
+ "Shift-Mod-9": toggleList("task"),
2263
+ "Mod->": toggleQuote,
2264
+ "Shift-Enter": hardBreak,
2265
+ "Mod-Enter": chainCommands2(toggleTick, hardBreak),
2266
+ Enter: chainCommands2(splitItem, cellBelow, baseKeymap.Enter),
2267
+ Tab: way.keys(chainCommands2(nextCell, indentItem)),
2268
+ "Shift-Tab": way.keys(chainCommands2(previousCell, outdentItem))
2269
+ };
2270
+ for (let level = 1; level <= 6; level++) keys[`Mod-Alt-${level}`] = setStyle(level);
2271
+ return [
2272
+ typing,
2273
+ way.plugin,
2274
+ keymap(keys),
2275
+ keymap(baseKeymap),
2276
+ history(),
2277
+ gapCursor(),
2278
+ shape(),
2279
+ tableEditing()
2280
+ ];
2281
+ }
2282
+ function shape() {
2283
+ return new Plugin({
2284
+ appendTransaction(transactions, _before, state) {
2285
+ if (!transactions.some((tr2) => tr2.docChanged)) return null;
2286
+ const tr = state.tr;
2287
+ const breaks = [];
2288
+ state.doc.descendants((node, pos) => {
2289
+ if (node.type === nodes2.table) alignCells(tr, node, pos);
2290
+ if (!node.inlineContent) return true;
2291
+ if (oneLine(node)) {
2292
+ node.forEach((child, offset) => {
2293
+ const at = pos + 1 + offset;
2294
+ const { marks: marks2 } = child;
2295
+ if (child.type === nodes2.hard_break) breaks.push({ at, marks: marks2 });
2296
+ for (let i = 0; (i = (child.text ?? "").indexOf("\n", i)) >= 0; i++) {
2297
+ breaks.push({ at: at + i, marks: marks2 });
2298
+ }
2299
+ });
2300
+ }
2301
+ return false;
2302
+ });
2303
+ for (const { at, marks: marks2 } of breaks) tr.replaceWith(at, at + 1, schema.text(" ", marks2));
2304
+ return tr.docChanged ? tr : null;
2305
+ }
2306
+ });
2307
+ }
2308
+ var oneLine = (node) => node.type === nodes2.table_header || node.type === nodes2.table_cell || node.type === nodes2.heading && node.attrs.underline === null;
2309
+ function alignCells(tr, table2, tablePos) {
2310
+ const aligns = [];
2311
+ table2.forEach(
2312
+ (row) => row.forEach((cell2, _offset, column) => {
2313
+ aligns[column] ??= cell2.attrs.align;
2314
+ })
2315
+ );
2316
+ table2.forEach((row, rowOffset, rowIndex) => {
2317
+ row.forEach((cell2, cellOffset, column) => {
2318
+ const type = rowIndex === 0 ? nodes2.table_header : nodes2.table_cell;
2319
+ const align2 = aligns[column] ?? null;
2320
+ if (cell2.type !== type || cell2.attrs.align !== align2) {
2321
+ tr.setNodeMarkup(tablePos + 1 + rowOffset + 1 + cellOffset, type, {
2322
+ ...cell2.attrs,
2323
+ align: align2
2324
+ });
2325
+ }
2326
+ });
2327
+ });
2328
+ }
2329
+
2330
+ // src/components/MarkdownEditor/RichView.tsx
2331
+ import styles3 from "./MarkdownEditor.module.css";
2332
+ import { jsx as jsx2 } from "react/jsx-runtime";
2333
+ var withoutStyleSheets = (html) => html.replace(/<style[\s/>][^]*?(?:<\/style\s*>|$)/gi, "");
2334
+ function keepLinks(_view, event) {
2335
+ if (event.target?.closest?.("a")) event.preventDefault();
2336
+ return false;
2337
+ }
2338
+ function RichView(props) {
2339
+ const host = useRef(null);
2340
+ const view = useRef(null);
2341
+ const latest = useRef(props);
2342
+ const made = useRef(null);
2343
+ const format = useRef({ mark: false, ending: "\n" });
2344
+ const allowed = useRef(false);
2345
+ const taking = useRef(null);
2346
+ useLayoutEffect(() => {
2347
+ latest.current = props;
2348
+ });
2349
+ useLayoutEffect(() => {
2350
+ const element = host.current;
2351
+ if (!element) return;
2352
+ const editable = () => allowed.current && !latest.current.readOnly;
2353
+ const read = (text2) => {
2354
+ const opened = openMarkdown(text2);
2355
+ made.current = text2;
2356
+ format.current = opened.format;
2357
+ allowed.current = opened.editable;
2358
+ latest.current.onOpen(opened);
2359
+ return EditorState.create({
2360
+ doc: opened.doc,
2361
+ plugins: plugins({ link: () => latest.current.onLink() })
2362
+ });
2363
+ };
2364
+ const created = new EditorView(element, {
2365
+ state: read(latest.current.text),
2366
+ editable,
2367
+ attributes: () => {
2368
+ const { label, describedBy } = latest.current;
2369
+ return {
2370
+ class: styles3.content ?? "",
2371
+ role: "textbox",
2372
+ "aria-multiline": "true",
2373
+ "aria-label": label,
2374
+ ...describedBy ? { "aria-describedby": describedBy } : {},
2375
+ // A text only read can still be reached, to be read and scrolled by keyboard.
2376
+ ...editable() ? {} : { "aria-readonly": "true", tabindex: "0" }
2377
+ };
2378
+ },
2379
+ // The app's function as it is now: another one draws nothing again by itself.
2380
+ nodeViews: nodeViews((source) => latest.current.imageSrc?.(source)),
2381
+ handleDOMEvents: { click: keepLinks, auxclick: keepLinks },
2382
+ transformPastedHTML: withoutStyleSheets,
2383
+ dispatchTransaction(transaction) {
2384
+ const before = created.state.doc;
2385
+ const next = created.state.apply(transaction);
2386
+ created.updateState(next);
2387
+ if (next.doc !== before) {
2388
+ const text2 = writeMarkdown(next.doc, format.current);
2389
+ if (text2 !== made.current) {
2390
+ made.current = text2;
2391
+ latest.current.onChange(text2);
2392
+ }
2393
+ }
2394
+ latest.current.onState(next);
2395
+ }
2396
+ });
2397
+ view.current = created;
2398
+ latest.current.onState(created.state);
2399
+ latest.current.handle.current = {
2400
+ run(command) {
2401
+ if (!editable()) return;
2402
+ command(created.state, (transaction) => created.dispatch(transaction), created);
2403
+ created.focus();
2404
+ },
2405
+ state: () => created.state
2406
+ };
2407
+ const take = (text2) => {
2408
+ if (text2 === made.current) return;
2409
+ created.updateState(read(text2));
2410
+ latest.current.onState(created.state);
2411
+ };
2412
+ taking.current = take;
2413
+ return () => {
2414
+ view.current = null;
2415
+ latest.current.handle.current = null;
2416
+ taking.current = null;
2417
+ created.destroy();
2418
+ };
2419
+ }, []);
2420
+ useLayoutEffect(() => {
2421
+ taking.current?.(props.text);
2422
+ }, [props.text]);
2423
+ useLayoutEffect(() => {
2424
+ view.current?.setProps({});
2425
+ }, [props.readOnly, props.label, props.describedBy]);
2426
+ useEffect(() => {
2427
+ if (!host.current || !imagesChanged(host.current, props.imageSrc)) return;
2428
+ view.current?.setProps({
2429
+ nodeViews: nodeViews((source) => latest.current.imageSrc?.(source))
2430
+ });
2431
+ }, [props.imageSrc]);
2432
+ useEffect(() => {
2433
+ const boxes = host.current?.querySelectorAll(`.${styles3.box ?? "box"}`);
2434
+ boxes?.forEach((box) => {
2435
+ box.disabled = !view.current?.editable;
2436
+ });
2437
+ });
2438
+ return /* @__PURE__ */ jsx2("div", { ref: host, className: styles3.surface });
2439
+ }
2440
+
2441
+ // src/components/MarkdownEditor/Toolbar.tsx
2442
+ import { useRef as useRef2, useState as useState2 } from "react";
2443
+ import { redo as redo2, redoDepth, undo as undo2, undoDepth } from "prosemirror-history";
2444
+ import {
2445
+ addColumnAfter,
2446
+ addColumnBefore,
2447
+ addRowAfter as addRowAfter2,
2448
+ addRowBefore,
2449
+ deleteColumn,
2450
+ deleteRow,
2451
+ deleteTable,
2452
+ isInTable as isInTable2
2453
+ } from "prosemirror-tables";
2454
+ import styles4 from "./MarkdownEditor.module.css";
2455
+ import { Fragment, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
2456
+ var STYLES = [
2457
+ ["paragraph", "Paragraph"],
2458
+ [1, "Heading 1"],
2459
+ [2, "Heading 2"],
2460
+ [3, "Heading 3"],
2461
+ [4, "Heading 4"],
2462
+ [5, "Heading 5"],
2463
+ [6, "Heading 6"],
2464
+ ["code", "Code block"]
2465
+ ];
2466
+ function Tool({ label, icon, pressed, disabled, onClick }) {
2467
+ return /* @__PURE__ */ jsx3(
2468
+ "button",
2469
+ {
2470
+ type: "button",
2471
+ className: styles4.tool,
2472
+ "aria-label": label,
2473
+ "aria-pressed": pressed,
2474
+ title: label,
2475
+ "aria-disabled": disabled || void 0,
2476
+ tabIndex: -1,
2477
+ onClick: disabled ? void 0 : onClick,
2478
+ children: /* @__PURE__ */ jsx3(Icon, { name: icon, size: "sm", "aria-hidden": true })
2479
+ }
2480
+ );
2481
+ }
2482
+ function Toolbar({ state, run: run2, onLink, onImage }) {
2483
+ const bar = useRef2(null);
2484
+ const [current, setCurrent] = useState2(0);
2485
+ const [menu, setMenu] = useState2(null);
2486
+ const style = blockStyle(state);
2487
+ const code = style === "code";
2488
+ const list2 = listKind(state);
2489
+ const inTable = isInTable2(state);
2490
+ const styleName = STYLES.find(([value]) => value === style)?.[1] ?? "Paragraph";
2491
+ const tools = () => Array.from(
2492
+ bar.current?.querySelectorAll("[data-tool] > button, button") ?? []
2493
+ ).filter((button) => !button.closest('[role="menu"]'));
2494
+ const stop = (element) => {
2495
+ bar.current = element;
2496
+ tools().forEach((button, index) => {
2497
+ button.tabIndex = index === Math.min(current, tools().length - 1) ? 0 : -1;
2498
+ });
2499
+ };
2500
+ const move = (event) => {
2501
+ const all = tools();
2502
+ const at = all.indexOf(event.target);
2503
+ if (at < 0) return;
2504
+ const to = {
2505
+ ArrowRight: (at + 1) % all.length,
2506
+ ArrowLeft: (at - 1 + all.length) % all.length,
2507
+ Home: 0,
2508
+ End: all.length - 1
2509
+ }[event.key];
2510
+ if (to === void 0) return;
2511
+ event.preventDefault();
2512
+ all[to]?.focus();
2513
+ };
2514
+ const group = (children2) => /* @__PURE__ */ jsx3("div", { className: styles4.group, children: children2 });
2515
+ const mark = (name, label, icon) => /* @__PURE__ */ jsx3(
2516
+ Tool,
2517
+ {
2518
+ label,
2519
+ icon,
2520
+ pressed: markIsOn(state, schema.marks[name]),
2521
+ disabled: code,
2522
+ onClick: () => run2(toggle(name))
2523
+ }
2524
+ );
2525
+ return (
2526
+ // The keys move between the buttons inside, which are what takes the focus.
2527
+ /* @__PURE__ */ jsxs2(
2528
+ "div",
2529
+ {
2530
+ ref: stop,
2531
+ role: "toolbar",
2532
+ tabIndex: -1,
2533
+ "aria-label": "Formatting",
2534
+ className: styles4.toolbar,
2535
+ onKeyDown: move,
2536
+ onFocus: (event) => {
2537
+ const at = tools().indexOf(event.target);
2538
+ if (at >= 0 && at !== current) setCurrent(at);
2539
+ },
2540
+ onMouseDown: (event) => event.preventDefault(),
2541
+ children: [
2542
+ /* @__PURE__ */ jsx3(
2543
+ Menu,
2544
+ {
2545
+ "aria-label": "Block style",
2546
+ align: "left",
2547
+ width: 200,
2548
+ open: menu === "style",
2549
+ onClose: () => setMenu(null),
2550
+ items: STYLES.map(([value, label]) => ({
2551
+ label,
2552
+ checked: value === style,
2553
+ onSelect: () => run2(setStyle(value))
2554
+ })),
2555
+ trigger: /* @__PURE__ */ jsxs2(
2556
+ "button",
2557
+ {
2558
+ type: "button",
2559
+ className: styles4.style,
2560
+ "aria-haspopup": "menu",
2561
+ "aria-expanded": menu === "style",
2562
+ "aria-label": `Block style: ${styleName}`,
2563
+ tabIndex: -1,
2564
+ onClick: () => setMenu(menu === "style" ? null : "style"),
2565
+ children: [
2566
+ /* @__PURE__ */ jsx3("span", { children: styleName }),
2567
+ /* @__PURE__ */ jsx3(Icon, { name: "chevron-down", size: "sm", "aria-hidden": true })
2568
+ ]
2569
+ }
2570
+ )
2571
+ }
2572
+ ),
2573
+ group(
2574
+ /* @__PURE__ */ jsxs2(Fragment, { children: [
2575
+ mark("strong", "Bold", "bold"),
2576
+ mark("em", "Italic", "italic"),
2577
+ mark("strike", "Strikethrough", "strikethrough"),
2578
+ mark("code", "Code", "code"),
2579
+ /* @__PURE__ */ jsx3(
2580
+ Tool,
2581
+ {
2582
+ label: "Link",
2583
+ icon: "link",
2584
+ pressed: markIsOn(state, schema.marks.link),
2585
+ disabled: code,
2586
+ onClick: onLink
2587
+ }
2588
+ )
2589
+ ] })
2590
+ ),
2591
+ group(
2592
+ /* @__PURE__ */ jsxs2(Fragment, { children: [
2593
+ /* @__PURE__ */ jsx3(
2594
+ Tool,
2595
+ {
2596
+ label: "Bulleted list",
2597
+ icon: "list",
2598
+ pressed: list2 === "bullet",
2599
+ onClick: () => run2(toggleList("bullet"))
2600
+ }
2601
+ ),
2602
+ /* @__PURE__ */ jsx3(
2603
+ Tool,
2604
+ {
2605
+ label: "Numbered list",
2606
+ icon: "list-ordered",
2607
+ pressed: list2 === "ordered",
2608
+ onClick: () => run2(toggleList("ordered"))
2609
+ }
2610
+ ),
2611
+ /* @__PURE__ */ jsx3(
2612
+ Tool,
2613
+ {
2614
+ label: "Task list",
2615
+ icon: "list-todo",
2616
+ pressed: list2 === "task",
2617
+ onClick: () => run2(toggleList("task"))
2618
+ }
2619
+ ),
2620
+ /* @__PURE__ */ jsx3(
2621
+ Tool,
2622
+ {
2623
+ label: "Quote",
2624
+ icon: "text-quote",
2625
+ pressed: isQuoted(state),
2626
+ onClick: () => run2(toggleQuote)
2627
+ }
2628
+ )
2629
+ ] })
2630
+ ),
2631
+ group(
2632
+ /* @__PURE__ */ jsxs2(Fragment, { children: [
2633
+ /* @__PURE__ */ jsx3(Tool, { label: "Image", icon: "image", disabled: code, onClick: onImage }),
2634
+ inTable ? /* @__PURE__ */ jsx3(
2635
+ Menu,
2636
+ {
2637
+ "aria-label": "Table",
2638
+ align: "left",
2639
+ width: 220,
2640
+ open: menu === "table",
2641
+ onClose: () => setMenu(null),
2642
+ items: [
2643
+ { label: "Add row above", onSelect: () => run2(addRowBefore) },
2644
+ { label: "Add row below", onSelect: () => run2(addRowAfter2) },
2645
+ { label: "Add column left", onSelect: () => run2(addColumnBefore) },
2646
+ { label: "Add column right", onSelect: () => run2(addColumnAfter) },
2647
+ { type: "separator" },
2648
+ { label: "Delete row", destructive: true, onSelect: () => run2(deleteRow) },
2649
+ { label: "Delete column", destructive: true, onSelect: () => run2(deleteColumn) },
2650
+ { label: "Delete table", destructive: true, onSelect: () => run2(deleteTable) }
2651
+ ],
2652
+ trigger: /* @__PURE__ */ jsx3(
2653
+ "button",
2654
+ {
2655
+ type: "button",
2656
+ className: styles4.tool,
2657
+ "aria-label": "Table options",
2658
+ "aria-haspopup": "menu",
2659
+ "aria-expanded": menu === "table",
2660
+ title: "Table options",
2661
+ tabIndex: -1,
2662
+ onClick: () => setMenu(menu === "table" ? null : "table"),
2663
+ children: /* @__PURE__ */ jsx3(Icon, { name: "table", size: "sm", "aria-hidden": true })
2664
+ }
2665
+ )
2666
+ }
2667
+ ) : /* @__PURE__ */ jsx3(
2668
+ Tool,
2669
+ {
2670
+ label: "Insert table",
2671
+ icon: "table",
2672
+ disabled: code,
2673
+ onClick: () => run2(insertTable)
2674
+ }
2675
+ ),
2676
+ /* @__PURE__ */ jsx3(
2677
+ Tool,
2678
+ {
2679
+ label: "Divider",
2680
+ icon: "minus",
2681
+ disabled: code || inTable,
2682
+ onClick: () => run2(insertRule)
2683
+ }
2684
+ )
2685
+ ] })
2686
+ ),
2687
+ group(
2688
+ /* @__PURE__ */ jsxs2(Fragment, { children: [
2689
+ /* @__PURE__ */ jsx3(Tool, { label: "Undo", icon: "undo-2", disabled: !undoDepth(state), onClick: () => run2(undo2) }),
2690
+ /* @__PURE__ */ jsx3(Tool, { label: "Redo", icon: "redo-2", disabled: !redoDepth(state), onClick: () => run2(redo2) })
2691
+ ] })
2692
+ )
2693
+ ]
2694
+ }
2695
+ )
2696
+ );
2697
+ }
2698
+
2699
+ // src/components/MarkdownEditor/MarkdownEditor.tsx
2700
+ import styles5 from "./MarkdownEditor.module.css";
2701
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
2702
+ var VIEWS = [
2703
+ { value: "rich", label: "Rich" },
2704
+ { value: "markdown", label: "Markdown" }
2705
+ ];
2706
+ var SHOWN_ISSUES = 3;
2707
+ function MarkdownEditor({
2708
+ value,
2709
+ defaultValue,
2710
+ onChange,
2711
+ view,
2712
+ defaultView = "rich",
2713
+ onViewChange,
2714
+ imageSrc,
2715
+ readOnly = false,
2716
+ "aria-label": label,
2717
+ "aria-describedby": describedBy,
2718
+ className
2719
+ }) {
2720
+ const [own2, setOwn] = useState3(defaultValue ?? "");
2721
+ const text2 = value ?? own2;
2722
+ const [ownView, setOwnView] = useState3(defaultView);
2723
+ const shown = view ?? ownView;
2724
+ const [check, setCheck] = useState3();
2725
+ const [state, setState] = useState3();
2726
+ const [dialog, setDialog] = useState3();
2727
+ const rich = useRef3(null);
2728
+ const change = (next) => {
2729
+ setOwn(next);
2730
+ onChange?.(next);
2731
+ };
2732
+ const show = (next) => {
2733
+ setOwnView(next);
2734
+ onViewChange?.(next);
2735
+ };
2736
+ const editing = shown === "rich" && !readOnly && check?.editable === true;
2737
+ const open = (kind2) => {
2738
+ const current = rich.current?.state();
2739
+ if (current) setDialog({ kind: kind2, state: current });
2740
+ };
2741
+ const openLink = () => open("link");
2742
+ const apply = (command) => {
2743
+ const opened = dialog?.state.doc;
2744
+ setDialog(void 0);
2745
+ if (opened && rich.current?.state()?.doc === opened) rich.current.run(command);
2746
+ };
2747
+ const rest = (check?.issues.length ?? 0) - SHOWN_ISSUES;
2748
+ return /* @__PURE__ */ jsxs3("div", { className: [styles5.root, className].filter(Boolean).join(" "), children: [
2749
+ /* @__PURE__ */ jsxs3("div", { className: styles5.bar, children: [
2750
+ /* @__PURE__ */ jsx4(
2751
+ SegmentedControl,
2752
+ {
2753
+ "aria-label": "View",
2754
+ size: "sm",
2755
+ value: shown,
2756
+ onChange: show,
2757
+ options: [...VIEWS]
2758
+ }
2759
+ ),
2760
+ editing && state && /* @__PURE__ */ jsx4(
2761
+ Toolbar,
2762
+ {
2763
+ state,
2764
+ run: (command) => rich.current?.run(command),
2765
+ onLink: openLink,
2766
+ onImage: () => open("image")
2767
+ }
2768
+ )
2769
+ ] }),
2770
+ shown === "rich" ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2771
+ check && !check.editable && /* @__PURE__ */ jsxs3("div", { className: styles5.refused, role: "status", children: [
2772
+ /* @__PURE__ */ jsx4("p", { children: readOnly ? "The rich view would change this text." : "Shown read only: the rich view would change this text." }),
2773
+ /* @__PURE__ */ jsx4("ul", { children: check.issues.slice(0, SHOWN_ISSUES).map((issue) => /* @__PURE__ */ jsx4("li", { children: describeMarkdownIssue(issue) }, `${issue.reason}-${issue.line}`)) }),
2774
+ rest > 0 && /* @__PURE__ */ jsxs3("p", { children: [
2775
+ "And ",
2776
+ rest,
2777
+ " more."
2778
+ ] }),
2779
+ !readOnly && /* @__PURE__ */ jsx4(
2780
+ Button,
2781
+ {
2782
+ type: "button",
2783
+ variant: "secondary",
2784
+ size: "sm",
2785
+ onClick: () => show("markdown"),
2786
+ children: "Edit as Markdown"
2787
+ }
2788
+ )
2789
+ ] }),
2790
+ /* @__PURE__ */ jsx4(
2791
+ RichView,
2792
+ {
2793
+ text: text2,
2794
+ readOnly,
2795
+ label,
2796
+ describedBy,
2797
+ imageSrc,
2798
+ handle: rich,
2799
+ onChange: change,
2800
+ onOpen: setCheck,
2801
+ onState: setState,
2802
+ onLink: openLink
2803
+ }
2804
+ )
2805
+ ] }) : /* @__PURE__ */ jsx4(
2806
+ SourceEditor,
2807
+ {
2808
+ className: styles5.source,
2809
+ "aria-label": label,
2810
+ "aria-describedby": describedBy,
2811
+ language: "markdown",
2812
+ value: text2,
2813
+ onChange: change,
2814
+ readOnly
2815
+ }
2816
+ ),
2817
+ dialog?.kind === "link" && /* @__PURE__ */ jsx4(
2818
+ LinkDialog,
2819
+ {
2820
+ link: linkAt(dialog.state),
2821
+ onClose: () => setDialog(void 0),
2822
+ onApply: (href, title, words) => apply(setLink(linkAt(dialog.state), href, title, words))
2823
+ }
2824
+ ),
2825
+ dialog?.kind === "image" && /* @__PURE__ */ jsx4(
2826
+ ImageDialog,
2827
+ {
2828
+ onClose: () => setDialog(void 0),
2829
+ onApply: (src, alt, title) => apply(insertImage(src, alt, title))
2830
+ }
2831
+ )
2832
+ ] });
2833
+ }
2834
+ export {
2835
+ MarkdownEditor,
2836
+ checkMarkdownRoundTrip,
2837
+ describeMarkdownIssue
2838
+ };