@astryx-vue/richtext 0.0.0-stage → 0.5.1

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,2492 @@
1
+ import { $createHorizontalRuleNode, $isHorizontalRuleNode, HorizontalRuleNode } from "@lexical/extension";
2
+ import { $isAutoLinkNode, $isLinkNode, AutoLinkNode, LinkNode } from "@lexical/link";
3
+ import { $createListItemNode, $createListNode, $isListItemNode, $isListNode, ListItemNode, ListNode } from "@lexical/list";
4
+ import { $convertFromMarkdownString, $convertToMarkdownString, CODE, HEADING, LINK, ORDERED_LIST, QUOTE, TEXT_FORMAT_TRANSFORMERS, TEXT_MATCH_TRANSFORMERS, TRANSFORMERS } from "@lexical/markdown";
5
+ import { $isHeadingNode, HeadingNode, QuoteNode } from "@lexical/rich-text";
6
+ import { $createTableCellNode, $createTableNode, $createTableRowNode, $isTableCellNode, $isTableNode, $isTableRowNode, TableCellHeaderStates, TableCellNode, TableNode, TableRowNode } from "@lexical/table";
7
+ import { $createParagraphNode, $createTextNode, $getRoot, $getSelection, $getState, $isElementNode, $isLineBreakNode, $isNodeSelection, $isParagraphNode, $isRangeSelection, $isTextNode, $setState, COMMAND_PRIORITY_LOW, DecoratorNode, INSERT_PARAGRAPH_COMMAND, KEY_ENTER_COMMAND, LineBreakNode, TEXT_TYPE_TO_FORMAT, TextNode, createState } from "lexical";
8
+ import { $createCodeNode, $isCodeNode, CodeHighlightNode, CodeNode } from "@lexical/code";
9
+ import { $dfs, $findMatchingParent, mergeRegister as mergeRegister$1 } from "@lexical/utils";
10
+ import { decodeMarkdownCharacterReferences, parseInlineAst, parseMarkdownAst } from "@astryx-vue/core/Markdown/parser";
11
+ import { getMarkdownPluginCapabilities } from "@astryx-vue/core/Markdown/plugins";
12
+ import { createHeadlessEditor } from "@lexical/headless";
13
+ //#region src/markdownExtensionNode.ts
14
+ /** Reads stored facts defensively: a missing field becomes an empty value. */
15
+ function factsFrom(value) {
16
+ const { plugin, apiVersion, name, display, data, source } = value;
17
+ return {
18
+ plugin: typeof plugin === "string" ? plugin : "",
19
+ apiVersion: typeof apiVersion === "number" ? apiVersion : 0,
20
+ name: typeof name === "string" ? name : "",
21
+ display: display === "block" ? "block" : "inline",
22
+ data: data ?? null,
23
+ source: typeof source === "string" ? source : ""
24
+ };
25
+ }
26
+ const decorators = /* @__PURE__ */ new WeakMap();
27
+ /** Sets how `editor` draws plugin nodes; returns a function that unsets it. */
28
+ function setRichTextExtensionNodeDecorator(editor, decorator) {
29
+ decorators.set(editor, decorator);
30
+ return () => {
31
+ if (decorators.get(editor) === decorator) decorators.delete(editor);
32
+ };
33
+ }
34
+ /**
35
+ * The attribute that carries a node's facts and formats in its element, so
36
+ * copying it as HTML — the browser's own copy, or the editor's HTML export —
37
+ * and pasting it into any RichText editor brings back the same node with the
38
+ * same source and marks.
39
+ */
40
+ const FACTS_ATTRIBUTE = "data-markdown-extension";
41
+ function factsAttribute(node) {
42
+ return JSON.stringify({
43
+ ...node.__facts,
44
+ format: node.__format
45
+ });
46
+ }
47
+ function convertExtensionElement(element) {
48
+ let node = null;
49
+ try {
50
+ const parsed = JSON.parse(element.getAttribute(FACTS_ATTRIBUTE) ?? "");
51
+ if (parsed != null && typeof parsed === "object") {
52
+ const value = parsed;
53
+ node = $createRichTextExtensionNode(factsFrom(value), typeof value.format === "number" ? value.format : 0);
54
+ }
55
+ } catch {
56
+ node = null;
57
+ }
58
+ return {
59
+ node,
60
+ forChild: () => null
61
+ };
62
+ }
63
+ function importExtensionElement(element) {
64
+ return element.hasAttribute(FACTS_ATTRIBUTE) ? {
65
+ conversion: convertExtensionElement,
66
+ priority: 4
67
+ } : null;
68
+ }
69
+ var RichTextExtensionNode = class RichTextExtensionNode extends DecoratorNode {
70
+ __facts;
71
+ /**
72
+ * The text formats the node sits inside, as a text node's format bits. Only
73
+ * inline nodes carry any.
74
+ */
75
+ __format;
76
+ static getType() {
77
+ return "astryx-markdown-extension";
78
+ }
79
+ static clone(node) {
80
+ return new RichTextExtensionNode(node.__facts, node.__format, node.__key);
81
+ }
82
+ static importJSON(serialized) {
83
+ const { format } = serialized;
84
+ return $createRichTextExtensionNode(factsFrom(serialized), typeof format === "number" ? format : 0).updateFromJSON(serialized);
85
+ }
86
+ static importDOM() {
87
+ return {
88
+ span: importExtensionElement,
89
+ div: importExtensionElement
90
+ };
91
+ }
92
+ constructor(facts, format = 0, key) {
93
+ super(key);
94
+ this.__facts = facts;
95
+ this.__format = facts.display === "inline" ? format : 0;
96
+ }
97
+ exportJSON() {
98
+ const latest = this.getLatest();
99
+ return {
100
+ ...super.exportJSON(),
101
+ ...latest.__facts,
102
+ format: latest.__format
103
+ };
104
+ }
105
+ /** The node's identity, data, and source. */
106
+ getFacts() {
107
+ return this.getLatest().__facts;
108
+ }
109
+ /** The exact Markdown the node was read from. */
110
+ getSource() {
111
+ return this.getLatest().__facts.source;
112
+ }
113
+ /** The text formats the node sits inside, as a text node's format bits. */
114
+ getFormat() {
115
+ return this.getLatest().__format;
116
+ }
117
+ hasFormat(type) {
118
+ return (this.getFormat() & TEXT_TYPE_TO_FORMAT[type]) !== 0;
119
+ }
120
+ /** Puts the node inside, or takes it out of, one text format. */
121
+ setFormatFlag(type, isOn) {
122
+ const writable = this.getWritable();
123
+ const flag = TEXT_TYPE_TO_FORMAT[type];
124
+ writable.__format = isOn ? writable.__format | flag : writable.__format & ~flag;
125
+ return writable;
126
+ }
127
+ createDOM(config) {
128
+ const element = document.createElement(this.__facts.display === "inline" ? "span" : "div");
129
+ element.setAttribute(FACTS_ATTRIBUTE, factsAttribute(this));
130
+ if (this.__facts.display === "block") {
131
+ const className = config.theme.markdownExtensionBlock;
132
+ if (typeof className === "string" && className !== "") element.className = className;
133
+ }
134
+ return element;
135
+ }
136
+ exportDOM() {
137
+ const element = document.createElement(this.__facts.display === "inline" ? "span" : "div");
138
+ element.setAttribute(FACTS_ATTRIBUTE, factsAttribute(this));
139
+ element.textContent = this.__facts.source;
140
+ return { element };
141
+ }
142
+ updateDOM(prevNode, dom) {
143
+ if (prevNode.__format !== this.__format) dom.setAttribute(FACTS_ATTRIBUTE, factsAttribute(this));
144
+ return false;
145
+ }
146
+ isInline() {
147
+ return this.__facts.display === "inline";
148
+ }
149
+ /** The node's text is its source, so plain-text copies and search see it. */
150
+ getTextContent() {
151
+ return this.getLatest().__facts.source;
152
+ }
153
+ decorate(editor) {
154
+ return decorators.get(editor)?.(this.__facts, this.__format, this.__key) ?? this.__facts.source;
155
+ }
156
+ };
157
+ function $createRichTextExtensionNode(facts, format = 0) {
158
+ return new RichTextExtensionNode(facts, format);
159
+ }
160
+ function $isRichTextExtensionNode(node) {
161
+ return node instanceof RichTextExtensionNode;
162
+ }
163
+ /**
164
+ * The first text node a range selects characters of, as Lexical's formatText
165
+ * reads it: a range that starts at the end of a text node starts in the next.
166
+ * Null when the range selects no text, only nodes.
167
+ */
168
+ function $firstSelectedText(selection) {
169
+ const texts = selection.getNodes().filter($isTextNode);
170
+ const isBackward = selection.isBackward();
171
+ const start = isBackward ? selection.focus : selection.anchor;
172
+ const end = isBackward ? selection.anchor : selection.focus;
173
+ let first = texts[0];
174
+ let startOffset = start.type === "element" ? 0 : start.offset;
175
+ if (first != null && start.type === "text" && startOffset === first.getTextContentSize()) {
176
+ first = texts[1];
177
+ startOffset = 0;
178
+ }
179
+ const last = texts[texts.length - 1];
180
+ if (first == null || last == null) return null;
181
+ const endOffset = end.type === "text" ? end.offset : last.getTextContentSize();
182
+ return first.is(last) && startOffset === endOffset ? null : first;
183
+ }
184
+ /**
185
+ * The inline plugin nodes a selection holds when it holds nothing else: a
186
+ * range that selects no text, only nodes, or a node selection of plugin
187
+ * nodes alone. Null otherwise. A format shown or toggled then belongs to
188
+ * them.
189
+ */
190
+ function $selectedExtensionNodesOnly(selection) {
191
+ if ($isNodeSelection(selection)) {
192
+ const selected = selection.getNodes();
193
+ return selected.length > 0 && selected.every((node) => $isRichTextExtensionNode(node) && node.isInline()) ? selected : null;
194
+ }
195
+ const nodes = selection.getNodes().filter((node) => $isRichTextExtensionNode(node) && node.isInline());
196
+ return nodes.length > 0 && $firstSelectedText(selection) == null ? nodes : null;
197
+ }
198
+ //#endregion
199
+ //#region src/editorNodes.ts
200
+ /**
201
+ * The default OSS node set registered with the editor: headings, quotes,
202
+ * lists, links, code, and tables. Extend via the `nodes` prop / option rather
203
+ * than editing this list.
204
+ */
205
+ const DEFAULT_NODES = [
206
+ HeadingNode,
207
+ QuoteNode,
208
+ ListNode,
209
+ ListItemNode,
210
+ LinkNode,
211
+ AutoLinkNode,
212
+ CodeNode,
213
+ CodeHighlightNode,
214
+ TableNode,
215
+ TableRowNode,
216
+ TableCellNode,
217
+ HorizontalRuleNode,
218
+ RichTextExtensionNode
219
+ ];
220
+ //#endregion
221
+ //#region src/markdownCodeFence.ts
222
+ /**
223
+ * The tilde fence a code block was opened with; null for a backtick block.
224
+ * Lexical's own fence state holds only backtick fences.
225
+ */
226
+ const tildeFence = createState("astryxTildeFence", { parse: (value) => typeof value === "string" && /^~{3,}$/.test(value) ? value : null });
227
+ /**
228
+ * The backtick fence a code block was opened with, when longer than three:
229
+ * Lexical's own fence state is set only by its transformer, which this file
230
+ * does not use to build blocks.
231
+ */
232
+ const backtickFence = createState("astryxBacktickFence", { parse: (value) => typeof value === "string" && /^`{4,}$/.test(value) ? value : null });
233
+ /** The info string a code block's opening fence carried, as written. */
234
+ const fenceInfo = createState("astryxFenceInfo", { parse: (value) => typeof value === "string" && value !== "" ? value : null });
235
+ /** The language core Markdown reads from an info string, or null. */
236
+ function languageOf(info) {
237
+ return /^\S+/.exec(info.trimStart())?.[0] ?? null;
238
+ }
239
+ /**
240
+ * Reads an opening fence line: up to three spaces of indentation, then the
241
+ * fence (CommonMark 0.31 §4.5), as core Markdown reads it.
242
+ */
243
+ function readOpening(line) {
244
+ const match = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line);
245
+ if (match == null) return null;
246
+ const [, indentation, fence, info] = match;
247
+ return fence.startsWith("`") && info.includes("`") ? null : {
248
+ indentation: indentation.length,
249
+ fence,
250
+ info
251
+ };
252
+ }
253
+ /** The longest run of three or more of `character` in `text`, or 0. */
254
+ function longestFenceRun(text, character) {
255
+ return Math.max(0, ...(text.match(character === "`" ? /`{3,}/g : /~{3,}/g) ?? []).map((run) => run.length));
256
+ }
257
+ /**
258
+ * Builds the code block an opening line starts, from the lines after it up
259
+ * to its closing fence, and returns the index of the last line it used.
260
+ */
261
+ function $importFencedCode(rootNode, lines, startLineIndex, opening) {
262
+ const { indentation, fence, info } = opening;
263
+ const closing = new RegExp(`^ {0,3}${fence[0] === "`" ? "`" : "~"}{${fence.length},}[ \\t]*$`);
264
+ const fenceIndentation = new RegExp(`^ {0,${indentation}}`);
265
+ let end = startLineIndex + 1;
266
+ while (end < lines.length && !closing.test(lines[end])) end++;
267
+ const codeEnd = end === lines.length && end > startLineIndex + 1 && lines[end - 1] === "" ? end - 1 : end;
268
+ const block = $createCodeNode(languageOf(info) ?? void 0);
269
+ block.append($createTextNode(lines.slice(startLineIndex + 1, codeEnd).map((line) => line.replace(fenceIndentation, "")).join("\n")));
270
+ rootNode.append(block);
271
+ if (fence.startsWith("~")) $setState(block, tildeFence, fence);
272
+ else if (fence.length > 3) $setState(block, backtickFence, fence);
273
+ $setState(block, fenceInfo, info.trimEnd());
274
+ return Math.min(end, lines.length - 1);
275
+ }
276
+ /** Writes a code block that keeps its fence or info string; null otherwise. */
277
+ const exportFencedCode = (node) => {
278
+ if (!$isCodeNode(node)) return null;
279
+ const tilde = $getState(node, tildeFence);
280
+ const backticks = $getState(node, backtickFence);
281
+ const info = $getState(node, fenceInfo);
282
+ if (tilde == null && backticks == null && info == null) return null;
283
+ const text = node.getTextContent();
284
+ const language = node.getLanguage() ?? "";
285
+ let written = info ?? "";
286
+ if ((languageOf(written) ?? "") !== language) {
287
+ const previous = languageOf(written);
288
+ const rest = previous == null ? "" : written.trimStart().slice(previous.length).trim();
289
+ written = rest === "" ? language : `${language} ${rest}`;
290
+ }
291
+ const fence = tilde != null ? "~".repeat(Math.max(tilde.length, longestFenceRun(text, "~") + 1)) : "`".repeat(Math.max((backticks ?? "```").length, longestFenceRun(text, "`") + 1));
292
+ return `${fence}${written}${text === "" ? "" : `\n${text}`}\n${fence}`;
293
+ };
294
+ const BACKTICK_CODE = {
295
+ ...CODE,
296
+ handleImportAfterStartMatch: (args) => {
297
+ const opening = readOpening(args.lines[args.startLineIndex]);
298
+ if (opening == null) return CODE.handleImportAfterStartMatch?.(args) ?? null;
299
+ return [true, $importFencedCode(args.rootNode, args.lines, args.startLineIndex, opening)];
300
+ },
301
+ export: (node, exportChildren) => exportFencedCode(node, exportChildren) ?? CODE.export?.(node, exportChildren) ?? null
302
+ };
303
+ const TILDE_CODE = {
304
+ ...CODE,
305
+ regExpStart: /^( {0,3}~{3,})(.*)$/,
306
+ regExpEnd: {
307
+ optional: true,
308
+ regExp: /^ {0,3}~{3,}[ \t]*$/
309
+ },
310
+ handleImportAfterStartMatch: ({ lines, rootNode, startLineIndex }) => {
311
+ const opening = readOpening(lines[startLineIndex]);
312
+ return opening == null ? null : [true, $importFencedCode(rootNode, lines, startLineIndex, opening)];
313
+ },
314
+ export: (node, exportChildren) => exportFencedCode(node, exportChildren) ?? null
315
+ };
316
+ //#endregion
317
+ //#region src/markdownHardLineBreak.ts
318
+ /** Whether Lexical's Markdown import marked this line break as a hard one. */
319
+ function isMarkedHardLineBreak(node) {
320
+ const serialized = node.exportJSON();
321
+ return typeof serialized.$?.mdHardLineBreak === "string" && serialized.$.mdHardLineBreak !== "";
322
+ }
323
+ const HARD_LINE_BREAK = {
324
+ dependencies: [LineBreakNode],
325
+ export: (node) => $isLineBreakNode(node) && !isMarkedHardLineBreak(node) && $findMatchingParent(node, $isHeadingNode) == null ? "\\\n" : null,
326
+ regExp: /(?!)/,
327
+ type: "text-match"
328
+ };
329
+ //#endregion
330
+ //#region src/markdownHeading.ts
331
+ /** Lexical's own heading marker, which the typing shortcut keeps using. */
332
+ const SHORTCUT_MARKER$1 = /^(#{1,6})\s/;
333
+ /**
334
+ * An ATX heading marker: up to three spaces of indentation, then one to six
335
+ * `#` and a space, so ` # h` imports as a heading, as in core Markdown. A
336
+ * typed line becomes a heading only at Lexical's own `# `, so typing
337
+ * ` # ` changes nothing new.
338
+ */
339
+ const HEADING_MARKERS = {
340
+ ...HEADING,
341
+ regExp: /^ {0,3}(#{1,6})\s/,
342
+ replace: (parentNode, children, match, isImport) => isImport || SHORTCUT_MARKER$1.test(match[0]) ? HEADING.replace(parentNode, children, match, isImport) : false
343
+ };
344
+ //#endregion
345
+ //#region src/markdownLink.ts
346
+ /** Whether every `)` in `url` closes an earlier `(` and every `(` closes. */
347
+ function isBalanced(url) {
348
+ let depth = 0;
349
+ for (const character of url) if (character === "(") depth++;
350
+ else if (character === ")") {
351
+ depth--;
352
+ if (depth < 0) return false;
353
+ }
354
+ return depth === 0;
355
+ }
356
+ /**
357
+ * `value` with every `&` that would start a character reference written as
358
+ * `&#38;`, since import decodes references in a destination and a title.
359
+ */
360
+ function escapeCharacterReferences(value) {
361
+ return value.replace(/&(?=#\d+;|#X[\dA-F]+;|[A-Z][\dA-Z]*;)/gi, "&#38;");
362
+ }
363
+ /** `url` as a Markdown destination that reads back as `url`. */
364
+ function markdownDestination(url) {
365
+ if (/\s/.test(url) || url.startsWith("<")) return `<${url.replace(/[\\<>]/g, "\\$&")}>`;
366
+ return url.replace(isBalanced(url) ? /\\/g : /[\\()]/g, "\\$&");
367
+ }
368
+ const LINK_KEEPING_DESTINATIONS = {
369
+ ...LINK,
370
+ export: (node, exportChildren, exportFormat) => {
371
+ if (!$isLinkNode(node) || $isAutoLinkNode(node)) return null;
372
+ const url = node.getURL();
373
+ const destination = markdownDestination(url);
374
+ if (destination === url) return LINK.export?.(node, exportChildren, exportFormat) ?? null;
375
+ const text = exportChildren(node);
376
+ const written = escapeCharacterReferences(destination);
377
+ const title = node.getTitle();
378
+ return title == null || title === "" ? `[${text}](${written})` : `[${text}](${written} "${escapeCharacterReferences(title).replace(/([\\"])/g, "\\$1")}")`;
379
+ }
380
+ };
381
+ //#endregion
382
+ //#region src/markdownTaskList.ts
383
+ const taskKind = createState("astryxTask", { parse: (value) => value === true });
384
+ const taskChecked = createState("astryxTaskChecked", { parse: (value) => value === true });
385
+ /**
386
+ * Whether `item` is a task and whether it is checked; null for a plain item.
387
+ * An item in one of Lexical's own checkbox lists is a task too.
388
+ */
389
+ function $getTaskState(item) {
390
+ if ($getState(item, taskKind)) return $getState(item, taskChecked) ? "checked" : "unchecked";
391
+ const list = item.getParent();
392
+ if ($isListNode(list) && list.getListType() === "check") return item.getChecked() === true ? "checked" : "unchecked";
393
+ return null;
394
+ }
395
+ /** Makes `item` a task in the given state, or a plain item for null. */
396
+ function $setTaskState(item, state) {
397
+ const list = item.getParent();
398
+ if ($isListNode(list) && list.getListType() === "check") {
399
+ item.setChecked(state === "checked");
400
+ return;
401
+ }
402
+ $setState(item, taskKind, state != null);
403
+ $setState(item, taskChecked, state === "checked");
404
+ }
405
+ const TASK_ITEM = /^(\s*)([-*+])\s\[([ x])\]\s/i;
406
+ /** Nesting depth from leading whitespace, counted as Lexical's lists do. */
407
+ function indentOf(whitespace) {
408
+ const tabs = whitespace.match(/\t/g)?.length ?? 0;
409
+ const spaces = whitespace.match(/ /g)?.length ?? 0;
410
+ return tabs + Math.floor(spaces / 4);
411
+ }
412
+ const TASK_LIST = {
413
+ dependencies: [ListNode, ListItemNode],
414
+ export: () => null,
415
+ regExp: TASK_ITEM,
416
+ replace: (parentNode, children, match, isImport) => {
417
+ const item = $createListItemNode();
418
+ $setState(item, taskKind, true);
419
+ $setState(item, taskChecked, match[3] !== " ");
420
+ const previous = parentNode.getPreviousSibling();
421
+ const next = parentNode.getNextSibling();
422
+ if ($isListNode(next) && next.getListType() === "bullet") {
423
+ const first = next.getFirstChild();
424
+ if (first == null) next.append(item);
425
+ else first.insertBefore(item);
426
+ parentNode.remove();
427
+ } else if ($isListNode(previous) && previous.getListType() === "bullet") {
428
+ previous.append(item);
429
+ parentNode.remove();
430
+ } else {
431
+ const list = $createListNode("bullet");
432
+ list.append(item);
433
+ parentNode.replace(list);
434
+ }
435
+ item.append(...children);
436
+ if (!isImport) item.select(0, 0);
437
+ const indent = indentOf(match[1]);
438
+ if (indent > 0) item.setIndent(indent);
439
+ },
440
+ type: "element"
441
+ };
442
+ /** The task item holding the selection's anchor, if any. */
443
+ function $selectedTaskItem() {
444
+ const selection = $getSelection();
445
+ if (!$isRangeSelection(selection)) return null;
446
+ return $findMatchingParent(selection.anchor.getNode(), (node) => $isListItemNode(node) && $getTaskState(node) != null);
447
+ }
448
+ /**
449
+ * Task editing in an editor:
450
+ *
451
+ * - Enter in a task makes the new item a task, unchecked, as Lexical's own
452
+ * checkbox items do. Lexical copies the item to make the new one, state and
453
+ * all, so the new item's state is set here, where Enter makes it — never
454
+ * inferred later from content, which would uncheck a written `- [x]` with
455
+ * no text. Enter at the start of a task leaves its text, and its state, on
456
+ * the item that holds it, and puts the new, unchecked item before it. Enter
457
+ * in an empty task is left to the list, which ends the list there.
458
+ * - Mod+Enter checks or unchecks the task holding the caret.
459
+ */
460
+ function registerTaskListEditing(editor) {
461
+ return mergeRegister$1(editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => {
462
+ const selection = $getSelection();
463
+ const item = $selectedTaskItem();
464
+ if (item == null || !$isRangeSelection(selection) || item.getTextContent().trim() === "") return false;
465
+ const state = $getTaskState(item);
466
+ const isAtStart = selection.isCollapsed() && selection.anchor.offset === 0 && (selection.anchor.getNode().is(item) || selection.anchor.getNode().is(item.getFirstDescendant()));
467
+ const created = selection.insertParagraph();
468
+ if (!$isListItemNode(created) || $getTaskState(created) == null) return true;
469
+ if (isAtStart) {
470
+ $setTaskState(created, state);
471
+ $setTaskState(item, "unchecked");
472
+ } else $setTaskState(created, "unchecked");
473
+ return true;
474
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ENTER_COMMAND, (event) => {
475
+ const item = event != null && (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey ? $selectedTaskItem() : null;
476
+ if (item == null) return false;
477
+ event?.preventDefault();
478
+ $setTaskState(item, $getTaskState(item) === "checked" ? "unchecked" : "checked");
479
+ return true;
480
+ }, COMMAND_PRIORITY_LOW));
481
+ }
482
+ //#endregion
483
+ //#region src/markdownListExport.ts
484
+ /** The bullet Lexical recorded for a list on import (`-`, `*`, or `+`). */
485
+ function bulletOf(list) {
486
+ const marker = list.getLatest().exportJSON().$?.mdListMarker;
487
+ return marker === "*" || marker === "+" ? marker : "-";
488
+ }
489
+ function exportList(list, exportChildren, indent) {
490
+ const lines = [];
491
+ const type = list.getListType();
492
+ let index = 0;
493
+ let childIndent = `${indent} `;
494
+ for (const item of list.getChildren()) {
495
+ if (!$isListItemNode(item)) continue;
496
+ const first = item.getFirstChild();
497
+ if (item.getChildrenSize() === 1 && $isListNode(first)) {
498
+ lines.push(exportList(first, exportChildren, childIndent));
499
+ continue;
500
+ }
501
+ const marker = type === "number" ? `${list.getStart() + index}. ` : `${bulletOf(list)} `;
502
+ const task = type === "number" ? null : $getTaskState(item);
503
+ const checkbox = task == null ? "" : `[${task === "checked" ? "x" : " "}] `;
504
+ let text = exportChildren(item);
505
+ if (type !== "number") text = text.replace(/^(\s{0,3}\d+)(\.\s)/, "$1\\$2");
506
+ lines.push(indent + marker + checkbox + text);
507
+ childIndent = indent + " ".repeat(marker.length);
508
+ index++;
509
+ }
510
+ return lines.join("\n");
511
+ }
512
+ const LIST_EXPORT = {
513
+ dependencies: [ListNode, ListItemNode],
514
+ export: (node, exportChildren) => $isListNode(node) ? exportList(node, exportChildren, "") : null,
515
+ regExp: /(?!)/,
516
+ replace: () => false,
517
+ type: "element"
518
+ };
519
+ //#endregion
520
+ //#region src/markdownOrderedList.ts
521
+ /**
522
+ * The list `item` was indented into: the last item under `list`, followed
523
+ * down through the wrapper items Lexical nests lists in.
524
+ */
525
+ function nestedListOfLastItem(list) {
526
+ let current = list;
527
+ for (;;) {
528
+ const last = current.getLastChild();
529
+ const nested = $isListItemNode(last) ? last.getFirstChild() : null;
530
+ if (!$isListItemNode(last) || last.getChildrenSize() !== 1 || !$isListNode(nested)) return current;
531
+ current = nested;
532
+ }
533
+ }
534
+ const ORDERED_LIST_KEEPING_START = {
535
+ ...ORDERED_LIST,
536
+ replace: (parentNode, children, match, isImport) => {
537
+ const previous = parentNode.getPreviousSibling();
538
+ const result = ORDERED_LIST.replace(parentNode, children, match, isImport);
539
+ if ($isListNode(previous) && previous.getListType() === "number") {
540
+ const nested = nestedListOfLastItem(previous);
541
+ if (nested !== previous && nested.getListType() === "number" && nested.getChildrenSize() === 1) nested.setStart(Number(match[2]));
542
+ }
543
+ return result;
544
+ }
545
+ };
546
+ //#endregion
547
+ //#region src/markdownQuote.ts
548
+ /** Lexical's own quote marker, which the typing shortcut keeps using. */
549
+ const SHORTCUT_MARKER = /^>\s/;
550
+ /**
551
+ * A block quote marker: up to three spaces of indentation, then `>` and the
552
+ * one space or tab that may follow it, so `>a` and ` > a` import as quotes,
553
+ * as in core Markdown. A typed line becomes a quote only at Lexical's own
554
+ * `> `, so typing `>` and Enter, or ` > `, changes nothing new. RichText
555
+ * quotes do not nest: the marker of a quote inside a quote stays in the
556
+ * outer quote's text.
557
+ */
558
+ const QUOTE_MARKERS = {
559
+ ...QUOTE,
560
+ regExp: /^ {0,3}>[ \t]?/,
561
+ replace: (parentNode, children, match, isImport) => isImport || SHORTCUT_MARKER.test(match[0]) ? QUOTE.replace(parentNode, children, match, isImport) : false
562
+ };
563
+ //#endregion
564
+ //#region src/markdownCodeRanges.ts
565
+ const FENCE_OPEN$2 = /^ {0,3}(`{3,}|~{3,})/;
566
+ /**
567
+ * The ranges of `text` that are code: fenced code blocks, and code spans,
568
+ * where a backtick run opens a span only if a later run of the same length
569
+ * closes it (CommonMark 0.31). One scan collects the runs; runs of each length
570
+ * are searched by position, so the whole is O(n log n).
571
+ */
572
+ function codeRanges(text) {
573
+ const { fenced, spans } = codeRangesByKind(text);
574
+ return [...fenced, ...spans].sort((a, b) => a[0] - b[0]);
575
+ }
576
+ /** The fenced code blocks of `text`, and its code spans, each in order. */
577
+ function codeRangesByKind(text) {
578
+ const ranges = [];
579
+ let lineStart = 0;
580
+ let fence = null;
581
+ while (lineStart <= text.length) {
582
+ const lineEnd = text.indexOf("\n", lineStart);
583
+ const end = lineEnd === -1 ? text.length : lineEnd;
584
+ const line = text.slice(lineStart, end);
585
+ if (fence == null) {
586
+ const open = FENCE_OPEN$2.exec(line);
587
+ if (open != null) fence = {
588
+ marker: open[1],
589
+ start: lineStart
590
+ };
591
+ } else if (new RegExp(`^ {0,3}\\${fence.marker[0]}{${fence.marker.length},}[ \\t]*$`).test(line)) {
592
+ ranges.push([fence.start, end]);
593
+ fence = null;
594
+ }
595
+ if (lineEnd === -1) break;
596
+ lineStart = lineEnd + 1;
597
+ }
598
+ if (fence != null) ranges.push([fence.start, text.length]);
599
+ const fencedCount = ranges.length;
600
+ const runs = [];
601
+ let index = 0;
602
+ let fenceIndex = 0;
603
+ while (index < text.length) {
604
+ const current = ranges[fenceIndex];
605
+ if (current != null && index >= current[0]) {
606
+ index = current[1];
607
+ fenceIndex++;
608
+ continue;
609
+ }
610
+ if (text[index] === "`") {
611
+ let end = index;
612
+ while (text[end] === "`") end++;
613
+ runs.push({
614
+ start: index,
615
+ length: end - index
616
+ });
617
+ index = end;
618
+ continue;
619
+ }
620
+ index++;
621
+ }
622
+ const byLength = /* @__PURE__ */ new Map();
623
+ for (const run of runs) {
624
+ const starts = byLength.get(run.length) ?? [];
625
+ starts.push(run.start);
626
+ byLength.set(run.length, starts);
627
+ }
628
+ const nextRunAfter = (length, after) => {
629
+ const starts = byLength.get(length);
630
+ if (starts == null) return null;
631
+ let low = 0;
632
+ let high = starts.length;
633
+ while (low < high) {
634
+ const middle = low + high >> 1;
635
+ if (starts[middle] < after) low = middle + 1;
636
+ else high = middle;
637
+ }
638
+ return starts[low] ?? null;
639
+ };
640
+ let resumeAt = 0;
641
+ for (const run of runs) {
642
+ if (run.start < resumeAt) continue;
643
+ let backslashes = 0;
644
+ while (text[run.start - 1 - backslashes] === "\\") backslashes++;
645
+ const isEscaped = backslashes % 2 === 1;
646
+ const openStart = isEscaped ? run.start + 1 : run.start;
647
+ const openLength = isEscaped ? run.length - 1 : run.length;
648
+ if (openLength === 0) continue;
649
+ const closer = nextRunAfter(openLength, run.start + run.length);
650
+ if (closer == null) continue;
651
+ ranges.push([openStart, closer + openLength]);
652
+ resumeAt = closer + openLength;
653
+ }
654
+ return {
655
+ fenced: ranges.slice(0, fencedCount),
656
+ spans: ranges.slice(fencedCount).sort((a, b) => a[0] - b[0])
657
+ };
658
+ }
659
+ //#endregion
660
+ //#region src/markdownStandIns.ts
661
+ const PRIVATE_USE_RANGES$2 = [
662
+ [57344, 63743],
663
+ [983040, 1048573],
664
+ [1048576, 1114109]
665
+ ];
666
+ /** Private-use characters that do not occur in `text`, in order. */
667
+ function* absentCharacters$1(text) {
668
+ const present = new Set(text);
669
+ for (const [first, last] of PRIVATE_USE_RANGES$2) for (let codePoint = first; codePoint <= last; codePoint++) {
670
+ const character = String.fromCodePoint(codePoint);
671
+ if (!present.has(character)) yield character;
672
+ }
673
+ }
674
+ //#endregion
675
+ //#region src/markdownRefusedLinks.ts
676
+ /**
677
+ * For each `[`, `]`, `(`, and `)` in `text` outside code and not escaped,
678
+ * the index of the bracket or parenthesis it pairs with by nesting; -1 for
679
+ * the rest. One pass, so a candidate never rescans the text.
680
+ */
681
+ function pairedDelimiters(text, code) {
682
+ const pair = new Int32Array(text.length).fill(-1);
683
+ const brackets = [];
684
+ const parentheses = [];
685
+ let codeIndex = 0;
686
+ for (let index = 0; index < text.length; index++) {
687
+ while (codeIndex < code.length && code[codeIndex][1] <= index) codeIndex++;
688
+ if (codeIndex < code.length && code[codeIndex][0] <= index) {
689
+ index = code[codeIndex][1] - 1;
690
+ continue;
691
+ }
692
+ const character = text[index];
693
+ const open = character === "]" ? brackets.pop() : character === ")" ? parentheses.pop() : void 0;
694
+ if (character === "\\") index++;
695
+ else if (character === "[") brackets.push(index);
696
+ else if (character === "(") parentheses.push(index);
697
+ else if (open !== void 0) {
698
+ pair[index] = open;
699
+ pair[open] = index;
700
+ }
701
+ }
702
+ return pair;
703
+ }
704
+ /**
705
+ * Where a destination that opens with `<` ends — the index of the `)` that
706
+ * closes the link — read as core Markdown reads it (CommonMark 0.31 §6.3):
707
+ * `'refused'` when it opens with `<` but is no angle-bracket destination,
708
+ * and null when the content after `open` (the `(`) does not open with `<`.
709
+ * Inside the brackets parentheses are plain characters; a line ending, even
710
+ * escaped, or an unescaped `<` makes it no destination; after the `>` come
711
+ * only spaces, an optional title, and the `)`.
712
+ */
713
+ function angleDestinationEnd(text, open) {
714
+ let index = open + 1;
715
+ while (text[index] === " " || text[index] === " ") index++;
716
+ if (text[index] !== "<") return null;
717
+ for (index++; index < text.length; index++) {
718
+ const character = text[index];
719
+ if (character === "\\" && text[index + 1] !== "\n" && text[index + 1] !== "\r") index++;
720
+ else if (character === "\n" || character === "\r" || character === "<") return "refused";
721
+ else if (character === ">") break;
722
+ }
723
+ if (index >= text.length) return "refused";
724
+ index++;
725
+ while (/\s/.test(text[index] ?? "")) index++;
726
+ const quote = text[index];
727
+ if (quote === "\"" || quote === "'" || quote === "(") {
728
+ const closer = quote === "(" ? ")" : quote;
729
+ for (index++; index < text.length && text[index] !== closer; index++) if (text[index] === "\\") index++;
730
+ else if (quote === "(" && text[index] === "(") return "refused";
731
+ index++;
732
+ while (/\s/.test(text[index] ?? "")) index++;
733
+ }
734
+ return text[index] === ")" ? index : "refused";
735
+ }
736
+ /**
737
+ * Whether core Markdown refuses a link to `destination`, as written in the
738
+ * source: its own parser decides, so both surfaces refuse the same
739
+ * destinations by one policy.
740
+ */
741
+ function coreRefusesDestination(destination) {
742
+ const probe = `[x](${destination})`;
743
+ const [only, ...rest] = parseInlineAst(probe);
744
+ return rest.length === 0 && only?.type === "text" && only.value === probe;
745
+ }
746
+ /**
747
+ * Whether core Markdown refuses a link to `url`, a destination already
748
+ * decoded: the probe writes it back with every special character escaped.
749
+ * A URL that cannot be written back is refused.
750
+ */
751
+ function coreRefusesUrl(url) {
752
+ if (/[\n\r]/.test(url)) return true;
753
+ const escaped = url.replace(/[<>]/g, (character) => character === "<" ? "%3C" : "%3E").replace(/[\\()&[\]"']/g, (character) => `\\${character}`);
754
+ return coreRefusesDestination(/\s/.test(url) ? `<${escaped}>` : escaped);
755
+ }
756
+ /**
757
+ * Returns `markdown` with each inline link whose destination core Markdown
758
+ * refuses — `javascript:` and the like — kept from becoming a link
759
+ * (spec:AST-061 FR7). Where core shows the link as its source text, exactly
760
+ * as written, the whole source becomes one stand-in that comes back as that
761
+ * text. Where core reads no link there at all (its link text holds brackets
762
+ * of its own), only the `(` that opens the destination becomes a stand-in,
763
+ * so the text around it reads as core reads it, marks included. Brackets and
764
+ * parentheses pair by nesting, so link text holding brackets is found whole.
765
+ * Linear in the source: pairs come from one pass, and a destination inside a
766
+ * found link is not probed again. Run first, on the source as written;
767
+ * `$unwrapRefusedLinks` catches any link the editor still makes.
768
+ */
769
+ function protectRefusedLinks(markdown) {
770
+ const standIns = /* @__PURE__ */ new Map();
771
+ if (!markdown.includes("](")) return {
772
+ markdown,
773
+ standIns
774
+ };
775
+ const pair = pairedDelimiters(markdown, codeRanges(markdown));
776
+ const refused = [];
777
+ let probedTo = -1;
778
+ for (let index = markdown.indexOf("]("); index !== -1; index = markdown.indexOf("](", index + 1)) {
779
+ const open = pair[index];
780
+ const angleClose = angleDestinationEnd(markdown, index + 1);
781
+ const close = typeof angleClose === "number" ? angleClose : pair[index + 1];
782
+ if (index < probedTo || open === -1 || close === -1) continue;
783
+ probedTo = close;
784
+ if (!coreRefusesDestination(markdown.slice(index + 2, close))) continue;
785
+ const source = markdown.slice(open, close + 1);
786
+ const [only, ...rest] = parseInlineAst(source);
787
+ if (rest.length === 0 && only?.type === "text" && only.value === source) {
788
+ while (refused.length > 0 && refused[refused.length - 1].start >= open) refused.pop();
789
+ refused.push({
790
+ start: open,
791
+ end: close + 1,
792
+ whole: true
793
+ });
794
+ } else refused.push({
795
+ start: index + 1,
796
+ end: index + 2,
797
+ whole: false
798
+ });
799
+ }
800
+ if (refused.length === 0) return {
801
+ markdown,
802
+ standIns
803
+ };
804
+ const available = absentCharacters$1(markdown);
805
+ let output = "";
806
+ let copied = 0;
807
+ for (const { start, end, whole } of refused) {
808
+ const next = available.next();
809
+ if (next.done === true || start < copied) break;
810
+ standIns.set(next.value, whole ? {
811
+ kind: "literal",
812
+ text: markdown.slice(start, end)
813
+ } : {
814
+ kind: "escape",
815
+ character: "("
816
+ });
817
+ output += markdown.slice(copied, start) + next.value;
818
+ copied = end;
819
+ }
820
+ return {
821
+ markdown: output + markdown.slice(copied),
822
+ standIns
823
+ };
824
+ }
825
+ /**
826
+ * Takes every link under `node` whose URL core Markdown refuses out of its
827
+ * link, leaving its text in place, so no form of link text or destination
828
+ * the source pass did not find can store or draw an unsafe URL.
829
+ */
830
+ function $unwrapRefusedLinks(node) {
831
+ for (const { node: descendant } of $dfs(node)) if ($isLinkNode(descendant) && coreRefusesUrl(descendant.getURL())) {
832
+ for (const child of descendant.getChildren()) descendant.insertBefore(child);
833
+ descendant.remove();
834
+ }
835
+ }
836
+ /**
837
+ * Returns `markdown` with every parenthesis inside an inline link
838
+ * destination — between the destination's own parentheses, balanced, as core
839
+ * Markdown and CommonMark read them — replaced by a private-use stand-in for
840
+ * itself, outside code. Run after protectBackslashEscapes, so an escaped
841
+ * parenthesis is already a stand-in and never counts toward the balance.
842
+ */
843
+ function protectLinkDestinationParentheses(markdown) {
844
+ const standIns = /* @__PURE__ */ new Map();
845
+ if (!markdown.includes("](")) return {
846
+ markdown,
847
+ standIns
848
+ };
849
+ const available = absentCharacters$1(markdown);
850
+ const byCharacter = /* @__PURE__ */ new Map();
851
+ const standInFor = (character) => {
852
+ const existing = byCharacter.get(character);
853
+ if (existing != null) return existing;
854
+ const next = available.next();
855
+ if (next.done === true) return null;
856
+ byCharacter.set(character, next.value);
857
+ standIns.set(next.value, {
858
+ kind: "escape",
859
+ character
860
+ });
861
+ return next.value;
862
+ };
863
+ const code = codeRanges(markdown);
864
+ const inner = [];
865
+ let codeIndex = 0;
866
+ let index = markdown.indexOf("](");
867
+ while (index !== -1) {
868
+ while (code[codeIndex] != null && code[codeIndex][1] <= index) codeIndex++;
869
+ const range = code[codeIndex];
870
+ if (range != null && range[0] <= index) {
871
+ index = markdown.indexOf("](", range[1]);
872
+ continue;
873
+ }
874
+ const parentheses = [];
875
+ let depth = 1;
876
+ let position = index + 2;
877
+ let isLink = markdown[position] !== "<";
878
+ for (; isLink && position < markdown.length; position++) {
879
+ const character = markdown[position];
880
+ if (/\s/.test(character)) {
881
+ isLink = depth === 1;
882
+ break;
883
+ }
884
+ if (character === "(") {
885
+ depth++;
886
+ parentheses.push(position);
887
+ } else if (character === ")") {
888
+ depth--;
889
+ if (depth === 0) break;
890
+ parentheses.push(position);
891
+ }
892
+ }
893
+ if (isLink && depth <= 1) inner.push(...parentheses);
894
+ index = markdown.indexOf("](", position + 1);
895
+ }
896
+ if (inner.length === 0) return {
897
+ markdown,
898
+ standIns
899
+ };
900
+ let output = "";
901
+ let copied = 0;
902
+ for (const position of inner) {
903
+ const standIn = standInFor(markdown[position]);
904
+ if (standIn == null) break;
905
+ output += markdown.slice(copied, position) + standIn;
906
+ copied = position + 1;
907
+ }
908
+ return {
909
+ markdown: output + markdown.slice(copied),
910
+ standIns
911
+ };
912
+ }
913
+ //#endregion
914
+ //#region src/markdownCodeSpans.ts
915
+ /** Whether `text` holds a `|` with no backslash before it. */
916
+ function hasUnescapedPipe(text) {
917
+ for (let index = text.indexOf("|"); index !== -1;) {
918
+ let backslashes = 0;
919
+ while (text[index - 1 - backslashes] === "\\") backslashes++;
920
+ if (backslashes % 2 === 0) return true;
921
+ index = text.indexOf("|", index + 1);
922
+ }
923
+ return false;
924
+ }
925
+ /**
926
+ * A GFM table's delimiter row: cells of hyphens with optional colons. The
927
+ * group is the repeated cell pattern, which the rule needs to repeat; only
928
+ * whether the row matches matters, not what it captured.
929
+ */
930
+ const TABLE_DELIMITER_ROW = /^\s*(?:\|\s*)?:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
931
+ /**
932
+ * The ranges of `markdown` a code span must not start in: inline link
933
+ * destinations and titles, from the `(` after a `]` to its paired `)`. The
934
+ * link reads its destination before any code span there, as core and
935
+ * CommonMark read it.
936
+ */
937
+ function linkTargetRanges(markdown, code) {
938
+ const ranges = [];
939
+ if (!markdown.includes("](")) return ranges;
940
+ const pair = pairedDelimiters(markdown, code);
941
+ for (let index = markdown.indexOf("]("); index !== -1; index = markdown.indexOf("](", index + 1)) {
942
+ const angleClose = angleDestinationEnd(markdown, index + 1);
943
+ const close = typeof angleClose === "number" ? angleClose : pair[index + 1];
944
+ if (pair[index] !== -1 && close !== -1) ranges.push([index + 1, close + 1]);
945
+ }
946
+ return ranges;
947
+ }
948
+ /** The ranges of `markdown` that are GFM table rows, header row included. */
949
+ function tableRowRanges(markdown) {
950
+ const ranges = [];
951
+ const lines = markdown.split("\n");
952
+ const starts = [];
953
+ let offset = 0;
954
+ for (const line of lines) {
955
+ starts.push(offset);
956
+ offset += line.length + 1;
957
+ }
958
+ for (let index = 1; index < lines.length; index++) {
959
+ const line = lines[index];
960
+ if (line.includes("|") && TABLE_DELIMITER_ROW.test(line) && lines[index - 1].includes("|")) {
961
+ let end = index + 1;
962
+ while (end < lines.length && lines[end].trim() !== "") end++;
963
+ ranges.push([starts[index - 1], starts[end - 1] + lines[end - 1].length]);
964
+ index = end;
965
+ }
966
+ }
967
+ return ranges;
968
+ }
969
+ /**
970
+ * Returns `markdown` with each code span outside fenced code replaced by a
971
+ * private-use stand-in, and the code each stands for, as core Markdown reads
972
+ * it. Code spans bind tighter than emphasis and links (CommonMark 0.31
973
+ * §6.1), but Lexical's import applies a code span before an earlier mark on
974
+ * the same line, which breaks every mark around code that follows another
975
+ * (`~~a~~ ~~`c`~~`); with the code out of the way, the marks pair first and
976
+ * the code comes back inside them. Backticks in a link's destination or
977
+ * title are the link's, never a code span: they become stand-ins too, put
978
+ * back into the link's address and title after import, so Lexical cannot
979
+ * pair them into code either. In a table row, a span holding an unescaped
980
+ * `|` is left alone, so the row still splits its cells there, as GFM does.
981
+ */
982
+ function protectCodeSpans(markdown) {
983
+ const spans = /* @__PURE__ */ new Map();
984
+ const standIns = /* @__PURE__ */ new Map();
985
+ if (!markdown.includes("`")) return {
986
+ markdown,
987
+ spans,
988
+ standIns
989
+ };
990
+ const code = codeRangesByKind(markdown);
991
+ const targets = linkTargetRanges(markdown, [...code.fenced, ...code.spans]);
992
+ const rows = tableRowRanges(markdown);
993
+ const cursor = (ranges) => {
994
+ let next = 0;
995
+ let coveredTo = -1;
996
+ return (position) => {
997
+ while (next < ranges.length && ranges[next][0] <= position) {
998
+ coveredTo = Math.max(coveredTo, ranges[next][1]);
999
+ next++;
1000
+ }
1001
+ return position < coveredTo;
1002
+ };
1003
+ };
1004
+ const inTarget = cursor(targets);
1005
+ const inRow = cursor(rows);
1006
+ const replacements = [];
1007
+ for (const [start, end] of code.spans) {
1008
+ const source = markdown.slice(start, end);
1009
+ const isInRow = inRow(start);
1010
+ if (inTarget(start) || isInRow && hasUnescapedPipe(source)) continue;
1011
+ const [only, ...rest] = parseInlineAst(source);
1012
+ if (rest.length > 0 || only?.type !== "inlineCode") continue;
1013
+ replacements.push({
1014
+ start,
1015
+ end,
1016
+ code: only.value
1017
+ });
1018
+ }
1019
+ for (const [from, to] of targets) for (let index = markdown.indexOf("`", from); index !== -1 && index < to; index = markdown.indexOf("`", index + 1)) replacements.push({
1020
+ start: index,
1021
+ end: index + 1,
1022
+ code: null
1023
+ });
1024
+ replacements.sort((a, b) => a.start - b.start);
1025
+ const available = absentCharacters$1(markdown);
1026
+ let output = "";
1027
+ let copied = 0;
1028
+ for (const { start, end, code: content } of replacements) {
1029
+ if (start < copied) continue;
1030
+ const next = available.next();
1031
+ if (next.done === true) break;
1032
+ if (content == null) standIns.set(next.value, {
1033
+ kind: "literal",
1034
+ text: "`"
1035
+ });
1036
+ else spans.set(next.value, content);
1037
+ output += markdown.slice(copied, start) + next.value;
1038
+ copied = end;
1039
+ }
1040
+ return {
1041
+ markdown: output + markdown.slice(copied),
1042
+ spans,
1043
+ standIns
1044
+ };
1045
+ }
1046
+ /**
1047
+ * Puts each code span back where its stand-in sits under `node`: the code as
1048
+ * text with the code format, inside whatever marks the stand-in took. In a
1049
+ * table cell an escaped `\|` in code is a `|`, as GFM reads cells.
1050
+ */
1051
+ function $restoreCodeSpans(node, spans) {
1052
+ if (spans.size === 0) return;
1053
+ for (const text of node.getAllTextNodes()) {
1054
+ const content = text.getTextContent();
1055
+ const offsets = [];
1056
+ let offset = 0;
1057
+ for (const character of content) {
1058
+ if (spans.has(character)) offsets.push(offset, offset + character.length);
1059
+ offset += character.length;
1060
+ }
1061
+ if (offsets.length === 0) continue;
1062
+ const pieces = text.splitText(...offsets.filter((point) => point > 0 && point < content.length));
1063
+ for (const piece of pieces) {
1064
+ const code = spans.get(piece.getTextContent());
1065
+ if (code == null) continue;
1066
+ const inCell = $findMatchingParent(piece, $isTableCellNode) != null;
1067
+ piece.setTextContent(inCell ? code.replace(/\\\|/g, "|") : code);
1068
+ if (!piece.hasFormat("code")) piece.toggleFormat("code");
1069
+ }
1070
+ }
1071
+ }
1072
+ //#endregion
1073
+ //#region src/markdownEscapes.ts
1074
+ /** The characters a backslash escapes (CommonMark 0.31 §2.4). */
1075
+ const ESCAPABLE = /* @__PURE__ */ new Set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~");
1076
+ /**
1077
+ * Returns `markdown` with every backslash escape outside code — a backslash
1078
+ * before ASCII punctuation — replaced by a private-use stand-in for the
1079
+ * escaped character, and every backslash in code by a stand-in for itself,
1080
+ * which Lexical would otherwise drop from a code span — except before `|`,
1081
+ * which a table reads before its code. A backslash before anything else
1082
+ * outside code stays as written. One pass over the source.
1083
+ */
1084
+ function protectBackslashEscapes(markdown) {
1085
+ const standIns = /* @__PURE__ */ new Map();
1086
+ if (!markdown.includes("\\")) return {
1087
+ markdown,
1088
+ standIns
1089
+ };
1090
+ const available = absentCharacters$1(markdown);
1091
+ const byKey = /* @__PURE__ */ new Map();
1092
+ const standInFor = (key, value) => {
1093
+ const existing = byKey.get(key);
1094
+ if (existing != null) return existing;
1095
+ const next = available.next();
1096
+ if (next.done === true) return null;
1097
+ byKey.set(key, next.value);
1098
+ standIns.set(next.value, value);
1099
+ return next.value;
1100
+ };
1101
+ const code = codeRanges(markdown);
1102
+ let output = "";
1103
+ let copied = 0;
1104
+ let codeIndex = 0;
1105
+ let index = markdown.indexOf("\\");
1106
+ while (index !== -1) {
1107
+ while (code[codeIndex] != null && code[codeIndex][1] <= index) codeIndex++;
1108
+ const range = code[codeIndex];
1109
+ const character = markdown[index + 1];
1110
+ const inCode = range != null && range[0] <= index;
1111
+ if (inCode && character === "|") {
1112
+ index = markdown.indexOf("\\", index + 2);
1113
+ continue;
1114
+ }
1115
+ const isEscape = !inCode && character != null && ESCAPABLE.has(character);
1116
+ if (inCode || isEscape) {
1117
+ const standIn = inCode ? standInFor("code", { kind: "backslash" }) : standInFor(`escape:${character}`, {
1118
+ kind: "escape",
1119
+ character: character ?? ""
1120
+ });
1121
+ if (standIn == null) break;
1122
+ output += markdown.slice(copied, index) + standIn;
1123
+ copied = index + (inCode ? 1 : 2);
1124
+ index = markdown.indexOf("\\", copied);
1125
+ continue;
1126
+ }
1127
+ index = markdown.indexOf("\\", index + 1);
1128
+ }
1129
+ return {
1130
+ markdown: output + markdown.slice(copied),
1131
+ standIns
1132
+ };
1133
+ }
1134
+ //#endregion
1135
+ //#region src/markdownCharacterReferences.ts
1136
+ const REFERENCE_LIKE = /&(?:#x[0-9a-f]+|#\d+|[A-Z][A-Z0-9]*);/iy;
1137
+ /**
1138
+ * Returns `markdown` with every character reference outside code replaced by
1139
+ * a private-use stand-in that occurs nowhere else in it, and the escaped `&`
1140
+ * of an escaped reference replaced by one too. One pass over the source.
1141
+ */
1142
+ function protectCharacterReferences(markdown) {
1143
+ const standIns = /* @__PURE__ */ new Map();
1144
+ if (!markdown.includes("&")) return {
1145
+ markdown,
1146
+ standIns
1147
+ };
1148
+ const available = absentCharacters$1(markdown);
1149
+ const byReference = /* @__PURE__ */ new Map();
1150
+ let ampersand = null;
1151
+ const standInFor = (reference) => {
1152
+ const existing = reference == null ? ampersand : byReference.get(reference);
1153
+ if (existing != null) return existing;
1154
+ const next = available.next();
1155
+ if (next.done === true) return null;
1156
+ if (reference == null) {
1157
+ ampersand = next.value;
1158
+ standIns.set(next.value, { kind: "ampersand" });
1159
+ } else {
1160
+ byReference.set(reference, next.value);
1161
+ standIns.set(next.value, {
1162
+ kind: "reference",
1163
+ source: reference
1164
+ });
1165
+ }
1166
+ return next.value;
1167
+ };
1168
+ const code = codeRanges(markdown);
1169
+ let output = "";
1170
+ let copied = 0;
1171
+ let codeIndex = 0;
1172
+ let index = markdown.indexOf("&");
1173
+ while (index !== -1) {
1174
+ while (code[codeIndex] != null && code[codeIndex][1] <= index) codeIndex++;
1175
+ const range = code[codeIndex];
1176
+ if (range != null && range[0] <= index) {
1177
+ index = markdown.indexOf("&", range[1]);
1178
+ continue;
1179
+ }
1180
+ REFERENCE_LIKE.lastIndex = index;
1181
+ const match = REFERENCE_LIKE.exec(markdown);
1182
+ if (match == null) {
1183
+ index = markdown.indexOf("&", index + 1);
1184
+ continue;
1185
+ }
1186
+ let backslashes = 0;
1187
+ while (markdown[index - 1 - backslashes] === "\\") backslashes++;
1188
+ const reference = match[0];
1189
+ const end = index + reference.length;
1190
+ if (backslashes % 2 === 1) {
1191
+ const standIn = standInFor(null);
1192
+ if (standIn != null) {
1193
+ output += markdown.slice(copied, index - 1) + standIn;
1194
+ copied = index + 1;
1195
+ }
1196
+ } else if (decodeMarkdownCharacterReferences(reference) !== reference) {
1197
+ const standIn = standInFor(reference);
1198
+ if (standIn != null) {
1199
+ output += markdown.slice(copied, index) + standIn;
1200
+ copied = end;
1201
+ }
1202
+ } else if (reference.startsWith("&#")) {
1203
+ const standIn = standInFor(null);
1204
+ if (standIn != null) {
1205
+ output += markdown.slice(copied, index) + standIn;
1206
+ copied = index + 1;
1207
+ }
1208
+ }
1209
+ index = markdown.indexOf("&", end);
1210
+ }
1211
+ return {
1212
+ markdown: output + markdown.slice(copied),
1213
+ standIns
1214
+ };
1215
+ }
1216
+ /** `text` with each stand-in replaced as `replace` says. */
1217
+ function restored(text, standIns, replace) {
1218
+ let output = "";
1219
+ let changed = false;
1220
+ for (const character of text) {
1221
+ const standIn = standIns.get(character);
1222
+ if (standIn == null) output += character;
1223
+ else {
1224
+ output += replace(standIn);
1225
+ changed = true;
1226
+ }
1227
+ }
1228
+ return changed ? output : text;
1229
+ }
1230
+ function decoded(standIn) {
1231
+ switch (standIn.kind) {
1232
+ case "literal": return standIn.text;
1233
+ case "ampersand": return "&";
1234
+ case "backslash": return "\\";
1235
+ case "escape": return standIn.character;
1236
+ case "reference": return decodeMarkdownCharacterReferences(standIn.source);
1237
+ }
1238
+ }
1239
+ function asWritten(standIn) {
1240
+ switch (standIn.kind) {
1241
+ case "literal": return standIn.text;
1242
+ case "ampersand": return "&";
1243
+ case "backslash": return "\\";
1244
+ case "escape": return `\\${standIn.character}`;
1245
+ case "reference": return standIn.source;
1246
+ }
1247
+ }
1248
+ /**
1249
+ * Replaces the stand-ins under `node` with the characters their references
1250
+ * name or their escapes stand for — or, in code Lexical read as code, with
1251
+ * the references and escapes as written — in text, link destinations, and
1252
+ * link titles. One pass over the text.
1253
+ */
1254
+ function $restoreCharacterReferences(node, standIns) {
1255
+ if (standIns.size === 0) return;
1256
+ const visit = (current, inCode) => {
1257
+ if ($isTextNode(current)) {
1258
+ const text = current.getTextContent();
1259
+ const next = restored(text, standIns, inCode || current.hasFormat("code") ? asWritten : decoded);
1260
+ if (next !== text) current.setTextContent(next);
1261
+ return;
1262
+ }
1263
+ if ($isLinkNode(current)) {
1264
+ const url = restored(current.getURL(), standIns, decoded);
1265
+ if (url !== current.getURL()) current.setURL(url);
1266
+ const title = current.getTitle();
1267
+ if (title != null) {
1268
+ const nextTitle = restored(title, standIns, decoded);
1269
+ if (nextTitle !== title) current.setTitle(nextTitle);
1270
+ }
1271
+ }
1272
+ if ($isElementNode(current)) {
1273
+ const isCode = inCode || $isCodeNode(current);
1274
+ for (const child of current.getChildren()) visit(child, isCode);
1275
+ }
1276
+ };
1277
+ visit(node, false);
1278
+ }
1279
+ //#endregion
1280
+ //#region src/markdownSpaceRuns.ts
1281
+ /**
1282
+ * A run of spaces with other characters on both sides, long enough for
1283
+ * Lexical's pattern to cost noticeably more than one step per space; shorter
1284
+ * runs, as ordinary text has, export as they are.
1285
+ */
1286
+ const INNER_SPACE_RUN = /(?<=\S)\s{64,}(?=\S)/g;
1287
+ /** Whether Lexical exports the text node's text as written, untouched. */
1288
+ function isLiteralText(node) {
1289
+ return $isTextNode(node) && (node.hasFormat("code") || $isCodeNode(node.getParent()));
1290
+ }
1291
+ /**
1292
+ * Lexical's `$convertToMarkdownString(transformers, root)`, with every long
1293
+ * run of spaces inside a text exported as stand-ins and put back, so the
1294
+ * export takes time linear in the text. The tree is read through views, never
1295
+ * changed; a tree with no long run exports directly.
1296
+ */
1297
+ function $convertToMarkdownKeepingTimeLinear(transformers, root) {
1298
+ const spaces = /* @__PURE__ */ new Set();
1299
+ const findRuns = (node) => {
1300
+ if ($isTextNode(node)) {
1301
+ if (!isLiteralText(node)) for (const run of node.getTextContent().match(INNER_SPACE_RUN) ?? []) for (const space of run) spaces.add(space);
1302
+ } else if ($isElementNode(node) && !$isCodeNode(node)) node.getChildren().forEach(findRuns);
1303
+ };
1304
+ root.getChildren().forEach(findRuns);
1305
+ if (spaces.size === 0) return $convertToMarkdownString(transformers, root);
1306
+ const written = [];
1307
+ const collect = (node) => {
1308
+ written.push(JSON.stringify(node.exportJSON()));
1309
+ if ($isTextNode(node)) written.push(node.getTextContent());
1310
+ else if ($isElementNode(node)) node.getChildren().forEach(collect);
1311
+ };
1312
+ root.getChildren().forEach(collect);
1313
+ const free = absentCharacters$1(written.join(""));
1314
+ const standIns = /* @__PURE__ */ new Map();
1315
+ for (const space of spaces) {
1316
+ const standIn = free.next().value;
1317
+ if (standIn == null) return $convertToMarkdownString(transformers, root);
1318
+ standIns.set(space, standIn);
1319
+ }
1320
+ const placed = { count: 0 };
1321
+ const children = viewsOf(root.getChildren(), standIns, placed);
1322
+ const view = Object.create(root);
1323
+ view.getChildren = () => children;
1324
+ let markdown = $convertToMarkdownString(transformers, view);
1325
+ let found = 0;
1326
+ for (const standIn of standIns.values()) found += markdown.split(standIn).length - 1;
1327
+ if (found !== placed.count) return $convertToMarkdownString(transformers, root);
1328
+ for (const [space, standIn] of standIns) markdown = markdown.split(standIn).join(space);
1329
+ return markdown;
1330
+ }
1331
+ /**
1332
+ * Views of `nodes` whose texts hold stand-ins for their inner runs of
1333
+ * spaces; a node with no such run is itself. Each view's siblings are the
1334
+ * views beside it, as Lexical's exporter reads neighbors to place marks.
1335
+ */
1336
+ function viewsOf(nodes, standIns, placed) {
1337
+ const views = nodes.map((node) => viewOf(node, standIns, placed));
1338
+ views.forEach((view, index) => {
1339
+ if (view !== nodes[index]) {
1340
+ view.getPreviousSibling = () => views[index - 1] ?? null;
1341
+ view.getNextSibling = () => views[index + 1] ?? null;
1342
+ }
1343
+ });
1344
+ return views;
1345
+ }
1346
+ function viewOf(node, standIns, placed) {
1347
+ if ($isTextNode(node)) {
1348
+ if (isLiteralText(node)) return node;
1349
+ const text = node.getTextContent();
1350
+ const stood = text.replace(INNER_SPACE_RUN, (run) => {
1351
+ placed.count += run.length;
1352
+ return Array.from(run, (space) => standIns.get(space) ?? space).join("");
1353
+ });
1354
+ if (stood === text) return node;
1355
+ const view = Object.create(node);
1356
+ view.getTextContent = () => stood;
1357
+ return view;
1358
+ }
1359
+ if ($isElementNode(node) && !$isCodeNode(node)) {
1360
+ const original = node.getChildren();
1361
+ const children = viewsOf(original, standIns, placed);
1362
+ if (children.every((child, index) => child === original[index])) return node;
1363
+ const view = Object.create(node);
1364
+ view.getChildren = () => children;
1365
+ return view;
1366
+ }
1367
+ return node;
1368
+ }
1369
+ //#endregion
1370
+ //#region src/markdownThematicBreak.ts
1371
+ /**
1372
+ * Three or more `-`, `*`, or `_` of one kind, optionally spaced, indented at
1373
+ * most three spaces (CommonMark 0.31, thematic breaks).
1374
+ */
1375
+ const THEMATIC_BREAK_LINE$1 = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
1376
+ /**
1377
+ * A setext heading underline made of dashes: no spaces between them, so
1378
+ * `- - -` under a paragraph is still a thematic break (CommonMark 0.31).
1379
+ */
1380
+ const SETEXT_UNDERLINE = /^ {0,3}-+[ \t]*$/;
1381
+ const THEMATIC_BREAK = {
1382
+ dependencies: [HorizontalRuleNode],
1383
+ export: (node) => $isHorizontalRuleNode(node) ? "---" : null,
1384
+ regExp: THEMATIC_BREAK_LINE$1,
1385
+ replace: (parentNode, children, match, isImport) => {
1386
+ const previous = parentNode.getPreviousSibling();
1387
+ if (isImport && SETEXT_UNDERLINE.test(match[0]) && $isParagraphNode(previous) && previous.getTextContentSize() > 0) {
1388
+ const [line] = children;
1389
+ if ($isTextNode(line)) line.setTextContent(match[0]);
1390
+ return false;
1391
+ }
1392
+ const rule = $createHorizontalRuleNode();
1393
+ if (isImport || parentNode.getNextSibling() != null) parentNode.replace(rule);
1394
+ else parentNode.insertBefore(rule);
1395
+ rule.selectNext();
1396
+ },
1397
+ type: "element"
1398
+ };
1399
+ //#endregion
1400
+ //#region src/markdownTable.ts
1401
+ /**
1402
+ * Cells hold inline Markdown only, so they are imported and exported with the
1403
+ * inline transformers.
1404
+ */
1405
+ const CELL_TRANSFORMERS = [...TEXT_FORMAT_TRANSFORMERS, ...TEXT_MATCH_TRANSFORMERS.map((transformer) => transformer === LINK ? LINK_KEEPING_DESTINATIONS : transformer)];
1406
+ /**
1407
+ * Splits a row into trimmed cell sources: the row's indentation, one leading
1408
+ * pipe, trailing spaces, and one trailing pipe are dropped, and the rest
1409
+ * splits on unescaped pipes. An escaped pipe stays escaped for the cell's
1410
+ * inline import.
1411
+ */
1412
+ function splitTableRow(line) {
1413
+ let start = 0;
1414
+ let end = line.length;
1415
+ while (start < end && (line[start] === " " || line[start] === " ")) start++;
1416
+ if (line[start] === "|") {
1417
+ start++;
1418
+ while (start < end && line[start] === " ") start++;
1419
+ }
1420
+ while (end > start && line[end - 1] === " ") end--;
1421
+ if (end > start && line[end - 1] === "|") end--;
1422
+ const content = line.slice(start, end);
1423
+ const cells = [];
1424
+ let current = "";
1425
+ for (let index = 0; index < content.length; index++) {
1426
+ const character = content[index];
1427
+ if (character === "\\" && content[index + 1] === "|") {
1428
+ current += "\\|";
1429
+ index++;
1430
+ } else if (character === "|") {
1431
+ cells.push(current.trim());
1432
+ current = "";
1433
+ } else current += character;
1434
+ }
1435
+ cells.push(current.trim());
1436
+ return cells;
1437
+ }
1438
+ /** A delimiter row: every non-empty cell is dashes with optional colons. */
1439
+ function isDelimiterRow(line) {
1440
+ if (line == null || !line.includes("|")) return false;
1441
+ const cells = line.split("|").map((cell) => cell.trim()).filter((cell) => cell.length > 0);
1442
+ return cells.length > 0 && cells.every((cell) => /^:?-+:?$/.test(cell));
1443
+ }
1444
+ function columnAlignment(delimiterCell) {
1445
+ const left = delimiterCell.startsWith(":");
1446
+ const right = delimiterCell.endsWith(":");
1447
+ if (left && right) return "center";
1448
+ return right ? "right" : left ? "left" : null;
1449
+ }
1450
+ /**
1451
+ * Alignment is stored as the cell's element format. Left and right map to
1452
+ * logical start and end, so an aligned column follows the reading direction
1453
+ * the way core Markdown's table does.
1454
+ */
1455
+ const ALIGNMENT_FORMAT = {
1456
+ left: "start",
1457
+ center: "center",
1458
+ right: "end"
1459
+ };
1460
+ function delimiterFor(format) {
1461
+ switch (format) {
1462
+ case "left":
1463
+ case "start": return ":---";
1464
+ case "center": return ":---:";
1465
+ case "right":
1466
+ case "end": return "---:";
1467
+ default: return "---";
1468
+ }
1469
+ }
1470
+ function $createCell(source, isHeader, alignment) {
1471
+ const cell = $createTableCellNode(isHeader ? TableCellHeaderStates.ROW : TableCellHeaderStates.NO_STATUS);
1472
+ $convertFromMarkdownString(source.replace(/\\\|/g, "|"), CELL_TRANSFORMERS, cell);
1473
+ if (alignment != null) cell.setFormat(ALIGNMENT_FORMAT[alignment]);
1474
+ return cell;
1475
+ }
1476
+ function cellMarkdown(cell) {
1477
+ return oneLine($convertToMarkdownKeepingTimeLinear(CELL_TRANSFORMERS, cell)).replace(/\|/g, "\\|").trim();
1478
+ }
1479
+ /**
1480
+ * `markdown` with each run of spaces that holds a line break made one space.
1481
+ * Read line by line: a pattern matching optional spaces around line breaks
1482
+ * retries from every space in a long run without a line break, so its time
1483
+ * grows with the square of the run.
1484
+ */
1485
+ function oneLine(markdown) {
1486
+ if (!markdown.includes("\n")) return markdown;
1487
+ const lines = markdown.split("\n");
1488
+ let joined = lines[0].trimEnd();
1489
+ for (let index = 1; index < lines.length; index++) {
1490
+ const isLast = index === lines.length - 1;
1491
+ const line = isLast ? lines[index].trimStart() : lines[index].trim();
1492
+ if (line !== "" || isLast) joined += ` ${line}`;
1493
+ }
1494
+ return joined;
1495
+ }
1496
+ /**
1497
+ * GFM pipe tables. The header row is the first row and renders as header
1498
+ * cells; delimiter-row colons set each column's alignment; rows shorter than
1499
+ * the widest row gain empty cells, so no cell is dropped. Export writes the
1500
+ * canonical form: outer pipes, one space of padding, and three-dash delimiters.
1501
+ */
1502
+ const TABLE = {
1503
+ dependencies: [
1504
+ TableNode,
1505
+ TableRowNode,
1506
+ TableCellNode
1507
+ ],
1508
+ export(node) {
1509
+ if (!$isTableNode(node)) return null;
1510
+ const rows = node.getChildren().filter($isTableRowNode);
1511
+ const lines = [];
1512
+ rows.forEach((row, rowIndex) => {
1513
+ const cells = row.getChildren().filter($isTableCellNode);
1514
+ lines.push(`| ${cells.map(cellMarkdown).join(" | ")} |`);
1515
+ if (rowIndex === 0) lines.push(`| ${cells.map((cell) => delimiterFor(cell.getFormatType())).join(" | ")} |`);
1516
+ });
1517
+ return lines.join("\n");
1518
+ },
1519
+ regExpStart: /\|/,
1520
+ handleImportAfterStartMatch({ lines, rootNode, startLineIndex }) {
1521
+ if (!isDelimiterRow(lines[startLineIndex + 1])) return null;
1522
+ const alignments = splitTableRow(lines[startLineIndex + 1]).map(columnAlignment);
1523
+ const rowSources = [splitTableRow(lines[startLineIndex])];
1524
+ let lastLineIndex = startLineIndex + 1;
1525
+ while (lastLineIndex + 1 < lines.length && lines[lastLineIndex + 1].includes("|") && lines[lastLineIndex + 1].trim() !== "") {
1526
+ lastLineIndex++;
1527
+ rowSources.push(splitTableRow(lines[lastLineIndex]));
1528
+ }
1529
+ const columnCount = Math.max(...rowSources.map((cells) => cells.length));
1530
+ const table = $createTableNode();
1531
+ rowSources.forEach((cells, rowIndex) => {
1532
+ const row = $createTableRowNode();
1533
+ for (let column = 0; column < columnCount; column++) row.append($createCell(cells[column] ?? "", rowIndex === 0, alignments[column] ?? null));
1534
+ table.append(row);
1535
+ });
1536
+ rootNode.append(table);
1537
+ return [true, lastLineIndex];
1538
+ },
1539
+ replace() {
1540
+ return false;
1541
+ },
1542
+ type: "multiline-element"
1543
+ };
1544
+ /**
1545
+ * The editor's default Markdown transformers: thematic breaks, list export
1546
+ * that nests to each parent's content column, GFM task list items, Lexical's
1547
+ * standard set (with `~~~` fences beside its backtick ones, both reading the
1548
+ * opening line's info string as core does, its ordered list keeping each
1549
+ * nested list's start, and its
1550
+ * link writing an unbalanced destination's parentheses escaped), hard line
1551
+ * breaks for breaks typed in the editor, and GFM tables. Thematic breaks come first so a line such as `* * *` is a rule
1552
+ * rather than a list item, and task items before bullets so `- [ ] text` is a
1553
+ * task rather than a bullet that starts with `[ ]`.
1554
+ */
1555
+ const DEFAULT_TRANSFORMERS = [
1556
+ THEMATIC_BREAK,
1557
+ LIST_EXPORT,
1558
+ TASK_LIST,
1559
+ TILDE_CODE,
1560
+ ...TRANSFORMERS.map((transformer) => transformer === ORDERED_LIST ? ORDERED_LIST_KEEPING_START : transformer === LINK ? LINK_KEEPING_DESTINATIONS : transformer === CODE ? BACKTICK_CODE : transformer === QUOTE ? QUOTE_MARKERS : transformer === HEADING ? HEADING_MARKERS : transformer),
1561
+ HARD_LINE_BREAK,
1562
+ TABLE
1563
+ ];
1564
+ //#endregion
1565
+ //#region src/markdownExtensions.ts
1566
+ const extensionPlugin = Symbol("RichTextMarkdownExtension.plugin");
1567
+ /** Why RichText refused a plugin or a configuration (spec:AST-064 FR4, FR6). */
1568
+ var RichTextExtensionError = class extends Error {
1569
+ /** The plugin RichText refused, or that a configuration claims twice. */
1570
+ plugin;
1571
+ /** What RichText cannot honor: `transform`, or what was claimed twice. */
1572
+ capability;
1573
+ /** The transformer or second extension that claims the same thing. */
1574
+ claimant;
1575
+ constructor(plugin, capability, claimant) {
1576
+ super(claimant == null ? `RichText cannot adopt Markdown plugin "${plugin}": RichText does not run its ${capability}.` : `RichText cannot use Markdown plugin "${plugin}" with ${claimant}: both claim its ${capability}.`);
1577
+ this.name = "RichTextExtensionError";
1578
+ this.plugin = plugin;
1579
+ this.capability = capability;
1580
+ this.claimant = claimant;
1581
+ }
1582
+ };
1583
+ /**
1584
+ * Adopts a Markdown plugin for RichText (spec:AST-064 FR1, FR4). RichText
1585
+ * recognizes the plugin's syntax with core's parser and keeps each node's
1586
+ * source; it never runs the plugin's immutable transform, so a plugin that
1587
+ * declares one is refused with a `RichTextExtensionError` here, before any
1588
+ * surface uses it.
1589
+ *
1590
+ * @example
1591
+ * ```
1592
+ * const mentions = createRichTextExtension(mentionsPlugin);
1593
+ * markdownToEditorStateJSON(markdown, {extensions: [mentions]});
1594
+ * ```
1595
+ */
1596
+ function createRichTextExtension(plugin) {
1597
+ if (getMarkdownPluginCapabilities(plugin).transform) throw new RichTextExtensionError(plugin.name, "transform", null);
1598
+ return Object.freeze({
1599
+ name: plugin.name,
1600
+ [extensionPlugin]: plugin
1601
+ });
1602
+ }
1603
+ /**
1604
+ * The plugins behind `extensions`, after checking that the configuration is
1605
+ * one RichText can honor (spec:AST-064 FR6): no plugin adopted twice, and no
1606
+ * transformer that imports or exports plugin nodes.
1607
+ */
1608
+ function pluginsOf(extensions, transformers) {
1609
+ const seen = /* @__PURE__ */ new Set();
1610
+ for (const extension of extensions) {
1611
+ if (seen.has(extension.name)) throw new RichTextExtensionError(extension.name, "syntax", `a second extension for "${extension.name}"`);
1612
+ seen.add(extension.name);
1613
+ }
1614
+ const [first] = extensions;
1615
+ if (first != null) transformers.forEach((transformer, index) => {
1616
+ if ("dependencies" in transformer && transformer.dependencies.includes(RichTextExtensionNode)) throw new RichTextExtensionError(first.name, "nodes", `transformer ${index} (${transformer.type})`);
1617
+ });
1618
+ return extensions.map((extension) => extension[extensionPlugin]);
1619
+ }
1620
+ const PRIVATE_USE_RANGES$1 = [
1621
+ [57344, 63743],
1622
+ [983040, 1048573],
1623
+ [1048576, 1114109]
1624
+ ];
1625
+ /** Private-use characters that do not occur in `text`, in order. */
1626
+ function* absentCharacters(text) {
1627
+ const present = new Set(text);
1628
+ for (const [first, last] of PRIVATE_USE_RANGES$1) for (let codePoint = first; codePoint <= last; codePoint++) {
1629
+ const character = String.fromCodePoint(codePoint);
1630
+ if (!present.has(character)) yield character;
1631
+ }
1632
+ }
1633
+ /**
1634
+ * The extension nodes core recognizes in `markdown`, in document order: inline
1635
+ * nodes anywhere, and block nodes at the top level only (block syntax nested
1636
+ * in a list item, quote, or table cell stays text in RichText).
1637
+ */
1638
+ function recognizedNodes(markdown, plugins) {
1639
+ const adoptable = [];
1640
+ let total = 0;
1641
+ const visit = (node, isTopLevel) => {
1642
+ if (node == null || typeof node !== "object") return;
1643
+ const candidate = node;
1644
+ if (candidate.type === "extension") {
1645
+ total++;
1646
+ const extension = node;
1647
+ if (typeof extension.source === "string" && (extension.display === "inline" || isTopLevel)) adoptable.push(extension);
1648
+ return;
1649
+ }
1650
+ if (Array.isArray(candidate.children)) for (const child of candidate.children) visit(child, false);
1651
+ };
1652
+ const root = parseMarkdownAst(markdown, { plugins: [...plugins] });
1653
+ for (const block of root.children) visit(block, true);
1654
+ return {
1655
+ adoptable,
1656
+ total
1657
+ };
1658
+ }
1659
+ /**
1660
+ * Replaces the source of every plugin node core recognizes in `markdown` with
1661
+ * a stand-in, so Lexical's transformers never read plugin source as base
1662
+ * Markdown (spec:AST-064 FR5). A node whose source core does not recognize at
1663
+ * any one occurrence — a span split across a container's line markers — stays
1664
+ * text.
1665
+ */
1666
+ function shieldExtensionSources(markdown, plugins) {
1667
+ const standIns = /* @__PURE__ */ new Map();
1668
+ if (plugins.length === 0) return {
1669
+ markdown,
1670
+ standIns
1671
+ };
1672
+ const { adoptable, total } = recognizedNodes(markdown, plugins);
1673
+ if (adoptable.length === 0) return {
1674
+ markdown,
1675
+ standIns
1676
+ };
1677
+ const versions = new Map(plugins.map((plugin) => [plugin.name, plugin.apiVersion]));
1678
+ const tokens = absentCharacters(markdown);
1679
+ const remaining = /* @__PURE__ */ new Map();
1680
+ for (const node of adoptable) {
1681
+ const source = node.source ?? "";
1682
+ remaining.set(source, (remaining.get(source) ?? 0) + 1);
1683
+ }
1684
+ let text = markdown;
1685
+ let shielded = 0;
1686
+ let searchFrom = 0;
1687
+ for (const node of adoptable) {
1688
+ const source = node.source ?? "";
1689
+ const token = tokens.next().value;
1690
+ if (token == null || source === "") break;
1691
+ const first = text.indexOf(source, searchFrom);
1692
+ const isEveryOccurrence = occurrences(text, source, searchFrom) === (remaining.get(source) ?? 0);
1693
+ remaining.set(source, (remaining.get(source) ?? 1) - 1);
1694
+ for (let at = first; at !== -1; at = text.indexOf(source, at + 1)) {
1695
+ const candidate = text.slice(0, at) + token + text.slice(at + source.length);
1696
+ if (isEveryOccurrence || recognizedNodes(candidate, plugins).total === total - shielded - 1) {
1697
+ text = candidate;
1698
+ shielded++;
1699
+ searchFrom = at + token.length;
1700
+ standIns.set(token, {
1701
+ node,
1702
+ apiVersion: versions.get(node.plugin) ?? 1
1703
+ });
1704
+ break;
1705
+ }
1706
+ }
1707
+ }
1708
+ return {
1709
+ markdown: text,
1710
+ standIns
1711
+ };
1712
+ }
1713
+ /** How many times `source` occurs in `text` from `from`, overlaps included. */
1714
+ function occurrences(text, source, from) {
1715
+ let count = 0;
1716
+ for (let at = text.indexOf(source, from); at !== -1; at = text.indexOf(source, at + 1)) count++;
1717
+ return count;
1718
+ }
1719
+ function $nodeFor({ node, apiVersion }, format = 0) {
1720
+ return $createRichTextExtensionNode({
1721
+ plugin: node.plugin,
1722
+ apiVersion,
1723
+ name: node.name,
1724
+ display: node.display,
1725
+ data: node.data,
1726
+ source: node.source ?? ""
1727
+ }, format);
1728
+ }
1729
+ /**
1730
+ * Puts a RichTextExtensionNode in place of every stand-in Lexical imported
1731
+ * into `holder`: inline nodes where their stand-in is, and a block node in
1732
+ * place of the paragraph that holds only its stand-in.
1733
+ */
1734
+ function $restoreExtensionSources(holder, standIns) {
1735
+ if (standIns.size === 0) return;
1736
+ for (const textNode of holder.getAllTextNodes()) $restoreInText(textNode, holder, standIns);
1737
+ }
1738
+ function $restoreInText(textNode, holder, standIns) {
1739
+ const text = textNode.getTextContent();
1740
+ const offsets = /* @__PURE__ */ new Set();
1741
+ let offset = 0;
1742
+ for (const character of text) {
1743
+ if (standIns.has(character)) {
1744
+ offsets.add(offset);
1745
+ offsets.add(offset + character.length);
1746
+ }
1747
+ offset += character.length;
1748
+ }
1749
+ offsets.delete(0);
1750
+ offsets.delete(text.length);
1751
+ if (offsets.size === 0 && !standIns.has(text)) return;
1752
+ const pieces = offsets.size === 0 ? [textNode] : textNode.splitText(...[...offsets].sort((a, b) => a - b));
1753
+ for (const piece of pieces) {
1754
+ const shielded = standIns.get(piece.getTextContent());
1755
+ if (shielded == null) continue;
1756
+ if (shielded.node.display === "inline") {
1757
+ piece.replace($nodeFor(shielded, piece.getFormat()));
1758
+ continue;
1759
+ }
1760
+ const paragraph = piece.getParent();
1761
+ if ($isParagraphNode(paragraph) && paragraph.getParent()?.is(holder) === true) $placeBlockNode(paragraph, piece, $nodeFor(shielded));
1762
+ else piece.replace($createTextNode(shielded.node.source ?? ""));
1763
+ }
1764
+ }
1765
+ /**
1766
+ * Puts a block node where its stand-in sits in `paragraph`, splitting the
1767
+ * paragraph around it: lines before the stand-in stay a paragraph, the node
1768
+ * follows as its own top-level block, and lines after it become a new
1769
+ * paragraph — as core reads a block that starts on the line after a paragraph
1770
+ * line.
1771
+ */
1772
+ function $placeBlockNode(paragraph, standIn, block) {
1773
+ const after = standIn.getNextSiblings();
1774
+ const before = standIn.getPreviousSiblings();
1775
+ if ($isLineBreakNode(before[before.length - 1])) before[before.length - 1]?.remove();
1776
+ if ($isLineBreakNode(after[0])) {
1777
+ after[0]?.remove();
1778
+ after.shift();
1779
+ }
1780
+ standIn.remove();
1781
+ if (after.length > 0) {
1782
+ const rest = $createParagraphNode();
1783
+ rest.append(...after);
1784
+ paragraph.insertAfter(rest);
1785
+ }
1786
+ paragraph.insertAfter(block);
1787
+ if (paragraph.getChildrenSize() === 0) paragraph.remove();
1788
+ }
1789
+ const NEVER = /(?!)/;
1790
+ /**
1791
+ * Exports every plugin node as its exact source (spec:AST-064 FR10). Always
1792
+ * part of RichText's export, whatever transformers the caller passes, so no
1793
+ * transformer set can drop a plugin node's source.
1794
+ */
1795
+ const EXTENSION_EXPORT_TRANSFORMERS = [{
1796
+ dependencies: [RichTextExtensionNode],
1797
+ export: (node) => $isRichTextExtensionNode(node) && !node.isInline() ? node.getSource() : null,
1798
+ regExp: NEVER,
1799
+ replace: () => false,
1800
+ type: "element"
1801
+ }, {
1802
+ dependencies: [RichTextExtensionNode],
1803
+ export: (node) => $isRichTextExtensionNode(node) && node.isInline() ? node.getSource() : null,
1804
+ importRegExp: NEVER,
1805
+ regExp: NEVER,
1806
+ replace: () => {},
1807
+ type: "text-match"
1808
+ }];
1809
+ /**
1810
+ * A text view of an inline plugin node for Lexical's exporter: it reads as
1811
+ * text holding `placeholder`, with the node's formats, so emphasis, strong, or
1812
+ * strikethrough around the node wraps it instead of closing before it. The
1813
+ * caller writes the node's source in place of the placeholder.
1814
+ */
1815
+ function extensionTextView(node, placeholder) {
1816
+ const view = Object.create(TextNode.prototype);
1817
+ Object.assign(view, { __key: node.getKey() });
1818
+ view.getTextContent = () => placeholder;
1819
+ view.getParent = () => node.getParent();
1820
+ return view;
1821
+ }
1822
+ const withExport = /* @__PURE__ */ new WeakMap();
1823
+ /**
1824
+ * `transformers` with the plugin node export first, the same array for the
1825
+ * same transformers so callers that cache by transformer list keep hitting.
1826
+ */
1827
+ function withExtensionExport(transformers) {
1828
+ let combined = withExport.get(transformers);
1829
+ if (combined == null) {
1830
+ combined = [...EXTENSION_EXPORT_TRANSFORMERS, ...transformers];
1831
+ withExport.set(transformers, combined);
1832
+ }
1833
+ return combined;
1834
+ }
1835
+ //#endregion
1836
+ //#region src/markdownSourceText.ts
1837
+ /** Lines without the carriage return before each line feed. */
1838
+ function withoutCarriageReturns(text) {
1839
+ return text.replace(/\r(?=\n|$)/g, "");
1840
+ }
1841
+ /** The first line ending in `text`, or `fallback` when it has none. */
1842
+ function lineEndingOf(text, fallback) {
1843
+ const index = text.indexOf("\n");
1844
+ if (index === -1) return fallback;
1845
+ return index > 0 && text[index - 1] === "\r" ? "\r\n" : "\n";
1846
+ }
1847
+ /** Rewrites every line ending in `text` as `lineEnding`. */
1848
+ function withLineEnding(text, lineEnding) {
1849
+ const lf = text.replace(/\r\n/g, "\n");
1850
+ return lineEnding === "\n" ? lf : lf.replace(/\n/g, lineEnding);
1851
+ }
1852
+ /**
1853
+ * A 64-bit hash of `text`, from two independent 32-bit FNV-1a passes. Only
1854
+ * equality matters: it tells an unchanged group from a changed one without
1855
+ * storing the canonical Markdown itself.
1856
+ */
1857
+ function hashOf(text) {
1858
+ let first = 2166136261;
1859
+ let second = 16777619 ^ text.length;
1860
+ for (let index = 0; index < text.length; index++) {
1861
+ const code = text.charCodeAt(index);
1862
+ first = Math.imul(first ^ code, 16777619) >>> 0;
1863
+ second = Math.imul(second ^ code, 1540483477) >>> 0;
1864
+ }
1865
+ return first.toString(36) + second.toString(36).padStart(7, "0");
1866
+ }
1867
+ //#endregion
1868
+ //#region src/markdownSourceCanonical.ts
1869
+ /**
1870
+ * An element that lists `nodes` as its children without adopting them, so
1871
+ * Lexical's exporter can read a run of top-level nodes on its own. The
1872
+ * exporter only ever asks the root it is given for its children.
1873
+ */
1874
+ function childrenOf(nodes) {
1875
+ return { getChildren: () => [...nodes] };
1876
+ }
1877
+ /** Every node in the runs' subtrees, in document order. */
1878
+ function descendantsOf(nodes) {
1879
+ const out = [];
1880
+ const visit = (node) => {
1881
+ out.push(node);
1882
+ if ($isElementNode(node)) node.getChildren().forEach(visit);
1883
+ };
1884
+ nodes.forEach(visit);
1885
+ return out;
1886
+ }
1887
+ /**
1888
+ * Canonical Markdown per run of nodes, keyed by the run's first node. Lexical
1889
+ * keeps a node's object across editor states until that node itself changes,
1890
+ * so a run whose every descendant is the same object as last time is
1891
+ * unchanged and costs a walk instead of an export.
1892
+ */
1893
+ const canonicalCache = /* @__PURE__ */ new WeakMap();
1894
+ function $canonicalMarkdown(nodes, transformers) {
1895
+ const descendants = descendantsOf(nodes);
1896
+ const cached = canonicalCache.get(nodes[0]);
1897
+ if (cached != null && cached.transformers === transformers && cached.descendants.length === descendants.length && cached.descendants.every((node, index) => node === descendants[index])) return cached;
1898
+ const { placeholders, sources } = extensionPlaceholders(descendants, descendants.map((node) => node.getTextContent()).join(""));
1899
+ let markdown = $convertToMarkdownKeepingTimeLinear(withExtensionExport(transformers), childrenOf(placeholders.size === 0 ? nodes : nodes.map((node) => markedView(node, null, placeholders))));
1900
+ for (const [placeholder, source] of sources) markdown = markdown.split(placeholder).join(source);
1901
+ const entry = {
1902
+ descendants,
1903
+ transformers,
1904
+ markdown,
1905
+ hash: hashOf(markdown)
1906
+ };
1907
+ canonicalCache.set(nodes[0], entry);
1908
+ return entry;
1909
+ }
1910
+ /**
1911
+ * Line starts that would turn literal text into a block structure. Each match
1912
+ * is the spaces before the marker, where the escape goes: block markers may
1913
+ * follow up to three spaces (CommonMark 0.31), and a list item's continuation
1914
+ * line adds its own indentation, so any spaces count.
1915
+ */
1916
+ const LINE_START_SYNTAX = [
1917
+ /^ *(?=>|#{1,6}(?:[ \t]|$))/,
1918
+ /^ *(?=[-+](?:[ \t]|$))/,
1919
+ /^ *(?=[=-][=\- \t]*$)/,
1920
+ /^ *(?=[|:][\t :|]*-[-\t :|]*$)/
1921
+ ];
1922
+ const ORDERED_LIST_START = /^( *\d{1,9})(?=[.)](?:[ \t]|$))/;
1923
+ const INLINE_SYNTAX = /[[\]]|&(?=#\d{1,7};|#x[0-9a-f]{1,6};|[A-Z][A-Z0-9]*;)/gi;
1924
+ const PRIVATE_USE_RANGES = [
1925
+ [57344, 63743],
1926
+ [983040, 1048573],
1927
+ [1048576, 1114109]
1928
+ ];
1929
+ /**
1930
+ * A token that appears nowhere in `text`. There are 137,468 private-use code
1931
+ * points, so a text shorter than that always misses one of them; a longer
1932
+ * text cannot contain every one of the 137,468² ordered pairs.
1933
+ */
1934
+ function absentToken(text) {
1935
+ const present = new Set(text);
1936
+ for (const [first, last] of PRIVATE_USE_RANGES) for (let codePoint = first; codePoint <= last; codePoint++) {
1937
+ const candidate = String.fromCodePoint(codePoint);
1938
+ if (!present.has(candidate)) return candidate;
1939
+ }
1940
+ for (const [first, last] of PRIVATE_USE_RANGES) for (let a = first; a <= last; a++) for (let b = first; b <= last; b++) {
1941
+ const candidate = String.fromCodePoint(a, b);
1942
+ if (!text.includes(candidate)) return candidate;
1943
+ }
1944
+ throw new Error("No escape token is absent from the text");
1945
+ }
1946
+ /**
1947
+ * A view of `node` whose text marks every character that needs a backslash
1948
+ * with `token` (none when `token` is null), and whose inline plugin nodes read
1949
+ * as text holding their placeholders. Views delegate everything else to the
1950
+ * node they wrap, so Lexical's exporter reads them like the real tree without
1951
+ * changing it.
1952
+ */
1953
+ function markedView(node, token, placeholders) {
1954
+ const placeholder = placeholders.get(node.getKey());
1955
+ if (placeholder != null && $isRichTextExtensionNode(node)) return extensionTextView(node, placeholder);
1956
+ if ($isTextNode(node)) {
1957
+ if (node.hasFormat("code") || $isCodeNode(node.getParent())) return node;
1958
+ if (token == null) return Object.create(node);
1959
+ let text = node.getTextContent().replace(INLINE_SYNTAX, (match) => token + match);
1960
+ const previous = node.getPreviousSibling();
1961
+ if (previous == null || $isLineBreakNode(previous)) {
1962
+ const ordered = ORDERED_LIST_START.exec(text);
1963
+ const start = LINE_START_SYNTAX.map((pattern) => pattern.exec(text)).find((match) => match != null);
1964
+ const before = ordered?.[1] ?? start?.[0];
1965
+ if (before != null) text = before + token + text.slice(before.length);
1966
+ }
1967
+ const view = Object.create(node);
1968
+ view.getTextContent = () => text;
1969
+ return view;
1970
+ }
1971
+ if ($isElementNode(node) && !$isCodeNode(node)) {
1972
+ const original = node.getChildren();
1973
+ const children = original.map((child) => markedView(child, token, placeholders));
1974
+ children.forEach((child, index) => {
1975
+ if (child !== original[index]) {
1976
+ child.getPreviousSibling = () => children[index - 1] ?? null;
1977
+ child.getNextSibling = () => children[index + 1] ?? null;
1978
+ }
1979
+ });
1980
+ const view = Object.create(node);
1981
+ view.getChildren = () => children;
1982
+ return view;
1983
+ }
1984
+ return node;
1985
+ }
1986
+ /**
1987
+ * A placeholder for each inline plugin node among `nodes`, absent from
1988
+ * `text`, and the source each placeholder stands for.
1989
+ */
1990
+ function extensionPlaceholders(nodes, text) {
1991
+ const placeholders = /* @__PURE__ */ new Map();
1992
+ const sources = /* @__PURE__ */ new Map();
1993
+ const free = absentCharacters$1(text);
1994
+ for (const node of nodes) if ($isRichTextExtensionNode(node) && node.isInline()) {
1995
+ const placeholder = free.next().value;
1996
+ if (placeholder == null) break;
1997
+ placeholders.set(node.getKey(), placeholder);
1998
+ sources.set(placeholder, node.getSource());
1999
+ }
2000
+ return {
2001
+ placeholders,
2002
+ sources
2003
+ };
2004
+ }
2005
+ /**
2006
+ * The canonical Markdown of a changed group, with literal text escaped so it
2007
+ * imports again as the structure the editor showed (spec:AST-062 FR3).
2008
+ */
2009
+ function $regeneratedMarkdown(nodes, canonical, transformers) {
2010
+ const text = canonical + nodes.map((node) => node.getTextContent()).join("");
2011
+ const token = absentToken(text);
2012
+ const { placeholders, sources } = extensionPlaceholders(descendantsOf(nodes), text + token);
2013
+ let marked = $convertToMarkdownKeepingTimeLinear(withExtensionExport(transformers), childrenOf(nodes.map((node) => markedView(node, token, placeholders)))).split(token).join("\\");
2014
+ for (const [placeholder, source] of sources) marked = marked.split(placeholder).join(source);
2015
+ return marked;
2016
+ }
2017
+ //#endregion
2018
+ //#region src/markdownSourceChunks.ts
2019
+ const BLANK_LINE$1 = /^[ \t]*\r?$/;
2020
+ const FENCE_OPEN$1 = /^ {0,3}(`{3,}|~{3,})/;
2021
+ const THEMATIC_BREAK_LINE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*\r?$/;
2022
+ const SETEXT_DASHES = /^ {0,3}-+[ \t]*\r?$/;
2023
+ const BLOCK_START = /^ {0,3}(?:[-*+][ \t]|\d{1,9}[.)][ \t]|>|#{1,6}(?:[ \t]|\r?$)|\|)/;
2024
+ /**
2025
+ * The chunks of `markdown` that cover the same lines as `like`, the chunks of
2026
+ * text with the same line count. Rewriting indentation can move a line across
2027
+ * a chunk boundary rule — a thematic break indented into a list item becomes
2028
+ * a break of its own — so the chunks follow the authored text, not the rule.
2029
+ */
2030
+ function sameLines(markdown, like) {
2031
+ const lines = markdown.split("\n");
2032
+ const lineEndings = (text) => text.split("\n").length - 1;
2033
+ let line = 0;
2034
+ return like.map((chunk) => {
2035
+ line += lineEndings(chunk.leading);
2036
+ const count = lineEndings(chunk.content) + 1;
2037
+ const content = lines.slice(line, line + count).join("\n");
2038
+ line += count - 1 + lineEndings(chunk.trailing);
2039
+ return {
2040
+ ...chunk,
2041
+ content
2042
+ };
2043
+ });
2044
+ }
2045
+ /**
2046
+ * Splits Markdown into chunks: runs of non-blank lines, with a fenced code
2047
+ * block kept whole across blank lines, and a thematic break always a chunk of
2048
+ * its own, so editing the block beside a rule never rewrites the rule
2049
+ * (spec:AST-062 FR2). A dash-only line under paragraph lines underlines them
2050
+ * instead, and stays with them. Joining every chunk's leading, content, and
2051
+ * trailing text gives back the input exactly.
2052
+ */
2053
+ function splitMarkdownChunks(markdown) {
2054
+ const lines = markdown.split("\n");
2055
+ const chunks = [];
2056
+ let leading = "";
2057
+ let index = 0;
2058
+ while (index < lines.length && BLANK_LINE$1.test(lines[index])) {
2059
+ if (index === lines.length - 1) return [];
2060
+ leading += `${lines[index]}\n`;
2061
+ index++;
2062
+ }
2063
+ while (index < lines.length) {
2064
+ const start = index;
2065
+ let fence = null;
2066
+ let isParagraph = true;
2067
+ while (index < lines.length) {
2068
+ const line = lines[index];
2069
+ if (fence != null) {
2070
+ index++;
2071
+ if (new RegExp(`^ {0,3}${fence[0]}{${fence.length},}[ \\t]*\\r?$`).test(line)) fence = null;
2072
+ continue;
2073
+ }
2074
+ if (BLANK_LINE$1.test(line)) break;
2075
+ const isRule = THEMATIC_BREAK_LINE.test(line) && !(isParagraph && index > start && SETEXT_DASHES.test(line));
2076
+ if (isRule && index > start) break;
2077
+ const open = FENCE_OPEN$1.exec(line);
2078
+ if (open != null) fence = open[1];
2079
+ if (open != null || BLOCK_START.test(line)) isParagraph = false;
2080
+ index++;
2081
+ if (isRule) break;
2082
+ }
2083
+ let content = lines.slice(start, index).join("\n");
2084
+ let trailing = "";
2085
+ if (content.endsWith("\r")) {
2086
+ content = content.slice(0, -1);
2087
+ trailing = "\r";
2088
+ }
2089
+ while (index < lines.length && BLANK_LINE$1.test(lines[index])) {
2090
+ trailing += `\n${lines[index]}`;
2091
+ index++;
2092
+ }
2093
+ if (index < lines.length) trailing += "\n";
2094
+ chunks.push({
2095
+ leading: chunks.length === 0 ? leading : "",
2096
+ content,
2097
+ trailing
2098
+ });
2099
+ }
2100
+ return chunks;
2101
+ }
2102
+ //#endregion
2103
+ //#region src/markdownSourceRecords.ts
2104
+ function parseGroupRecord(value) {
2105
+ if (typeof value !== "object" || value === null) return null;
2106
+ const serialized = value;
2107
+ if (typeof serialized.g !== "string") return null;
2108
+ if (typeof serialized.s !== "string") return { group: serialized.g };
2109
+ return {
2110
+ group: serialized.g,
2111
+ size: typeof serialized.n === "number" ? serialized.n : 1,
2112
+ content: serialized.s,
2113
+ trailing: typeof serialized.t === "string" ? serialized.t : "\n\n",
2114
+ canonicalHash: typeof serialized.h === "string" ? serialized.h : "",
2115
+ lineEnding: typeof serialized.e === "string" ? serialized.e : "\n",
2116
+ ...typeof serialized.x === "string" ? { next: serialized.x } : {}
2117
+ };
2118
+ }
2119
+ function unparseGroupRecord(record) {
2120
+ if (record == null) return null;
2121
+ const serialized = { g: record.group };
2122
+ if (record.content != null) {
2123
+ serialized.s = record.content;
2124
+ if (record.size !== 1) serialized.n = record.size;
2125
+ if (record.trailing !== "\n\n") serialized.t = record.trailing;
2126
+ serialized.h = record.canonicalHash;
2127
+ if (record.next != null) serialized.x = record.next;
2128
+ if (record.lineEnding !== "\n") serialized.e = record.lineEnding;
2129
+ }
2130
+ return serialized;
2131
+ }
2132
+ function isDocumentRecord(value) {
2133
+ return typeof value === "object" && value !== null && typeof value.importId === "string";
2134
+ }
2135
+ const groupState = createState("astryxMd", {
2136
+ parse: parseGroupRecord,
2137
+ unparse: unparseGroupRecord
2138
+ });
2139
+ const documentState = createState("astryxMdDocument", { parse: (value) => isDocumentRecord(value) ? value : null });
2140
+ let importCount = 0;
2141
+ /** An id no other import in this or any other document shares. */
2142
+ function nextImportId() {
2143
+ importCount++;
2144
+ return `${Math.random().toString(36).slice(2, 8)}${importCount.toString(36)}`;
2145
+ }
2146
+ const ENDS_WITH_BLANK_LINE = /\n[ \t]*\r?\n[ \t\r]*$/;
2147
+ //#endregion
2148
+ //#region src/markdownListIndentation.ts
2149
+ /**
2150
+ * @file markdownListIndentation.ts
2151
+ * @input Markdown source text.
2152
+ * @output Exports normalizeListIndentation, which rewrites the indentation of
2153
+ * every list item line so its nesting reads the same to Lexical as it does
2154
+ * to CommonMark.
2155
+ * @position Used by markdownSource.ts on the text it imports (never on the
2156
+ * bytes it records). Lexical nests a list item one level per four spaces or
2157
+ * one tab; CommonMark nests an item under the item whose content it is
2158
+ * indented to, so `- a` / ` - b` (two spaces) and `1. a` / ` 1. b`
2159
+ * (three) are nested lists that Lexical would flatten (spec:AST-061 FR5).
2160
+ */
2161
+ /** A list item line: indentation, marker, and the spaces after it. */
2162
+ const LIST_ITEM = /^([ \t]*)([-+*]|\d{1,9}[.)])( {1,4}|\t|$)/;
2163
+ const FENCE_OPEN = /^[ \t]*(`{3,}|~{3,})/;
2164
+ const BLANK_LINE = /^[ \t]*\r?$/;
2165
+ /** A thematic break after its indentation: three or more of one marker. */
2166
+ const THEMATIC_BREAK_CONTENT = /^([-*_])(?:[ \t]*\1){2,}[ \t]*\r?$/;
2167
+ /** Columns of leading whitespace, with tabs stopping every four columns. */
2168
+ function columnsOf(whitespace) {
2169
+ let columns = 0;
2170
+ for (const character of whitespace) columns = character === " " ? columns + 4 - columns % 4 : columns + 1;
2171
+ return columns;
2172
+ }
2173
+ /**
2174
+ * Rewrites each list item line's indentation as four spaces per CommonMark
2175
+ * nesting level, leaving every other line, and every line inside fenced code,
2176
+ * as it is. The line count and every line's content after its indentation
2177
+ * are unchanged.
2178
+ */
2179
+ function normalizeListIndentation(markdown) {
2180
+ const lines = markdown.split("\n");
2181
+ const open = [];
2182
+ let fence = null;
2183
+ let afterBlankLine = false;
2184
+ for (let index = 0; index < lines.length; index++) {
2185
+ const line = lines[index];
2186
+ if (fence != null) {
2187
+ if (new RegExp(`^[ \\t]*${fence[0]}{${fence.length},}[ \\t]*\\r?$`).test(line)) fence = null;
2188
+ continue;
2189
+ }
2190
+ if (BLANK_LINE.test(line)) {
2191
+ afterBlankLine = true;
2192
+ continue;
2193
+ }
2194
+ const leading = /^[ \t]*/.exec(line)?.[0] ?? "";
2195
+ const indent = columnsOf(leading);
2196
+ if (THEMATIC_BREAK_CONTENT.test(line.slice(leading.length))) {
2197
+ while (open.length > 0 && indent < open[open.length - 1]) open.pop();
2198
+ if (open.length > 0) lines[index] = line.slice(leading.length);
2199
+ afterBlankLine = false;
2200
+ continue;
2201
+ }
2202
+ const item = LIST_ITEM.exec(line);
2203
+ if (item == null) {
2204
+ const opening = FENCE_OPEN.exec(line);
2205
+ if (opening != null) fence = opening[1];
2206
+ if (afterBlankLine) while (open.length > 0 && indent < open[open.length - 1]) open.pop();
2207
+ afterBlankLine = false;
2208
+ continue;
2209
+ }
2210
+ afterBlankLine = false;
2211
+ while (open.length > 0 && indent < open[open.length - 1]) open.pop();
2212
+ const depth = open.length;
2213
+ const markerEnd = columnsOf(item[0]) + (item[3] === "" ? 1 : 0);
2214
+ open.push(markerEnd);
2215
+ lines[index] = " ".repeat(depth * 4) + line.slice(item[1].length);
2216
+ }
2217
+ return lines.join("\n");
2218
+ }
2219
+ //#endregion
2220
+ //#region src/markdownSourceImport.ts
2221
+ /**
2222
+ * Imports Markdown into the editor's root and records its authored bytes. Runs
2223
+ * two discrete updates: the first imports every chunk and stamps its nodes
2224
+ * with the chunk's group id; the second runs after node transforms have
2225
+ * settled the tree (adjacent lists merge, for example), so each group covers
2226
+ * exactly the chunks that ended up in its nodes.
2227
+ */
2228
+ function importMarkdownKeepingSource(editor, markdown, transformers, plugins = []) {
2229
+ const importId = nextImportId();
2230
+ const byteOrderMark = markdown.startsWith("");
2231
+ const body = byteOrderMark ? markdown.slice(1) : markdown;
2232
+ const chunks = splitMarkdownChunks(body);
2233
+ const importChunks = sameLines(normalizeListIndentation(body), chunks);
2234
+ const lineEnding = lineEndingOf(body, "\n");
2235
+ editor.update(() => {
2236
+ const root = $getRoot();
2237
+ root.clear();
2238
+ chunks.forEach((chunk, index) => {
2239
+ const holder = $createParagraphNode();
2240
+ root.append(holder);
2241
+ const shielded = shieldExtensionSources(withoutCarriageReturns(importChunks[index]?.content ?? chunk.content), plugins);
2242
+ const refused = protectRefusedLinks(shielded.markdown);
2243
+ const code = protectCodeSpans(refused.markdown);
2244
+ const escaped = protectBackslashEscapes(code.markdown);
2245
+ const destinations = protectLinkDestinationParentheses(escaped.markdown);
2246
+ const referenced = protectCharacterReferences(destinations.markdown);
2247
+ $convertFromMarkdownString(referenced.markdown, transformers, holder);
2248
+ $restoreCharacterReferences(holder, new Map([
2249
+ ...refused.standIns,
2250
+ ...code.standIns,
2251
+ ...escaped.standIns,
2252
+ ...destinations.standIns,
2253
+ ...referenced.standIns
2254
+ ]));
2255
+ $restoreCodeSpans(holder, code.spans);
2256
+ $unwrapRefusedLinks(holder);
2257
+ $restoreExtensionSources(holder, shielded.standIns);
2258
+ $joinSoftLineBreaks(holder);
2259
+ for (const node of holder.getChildren()) $setState(node, groupState, { group: `${importId}:${index}` });
2260
+ for (const node of holder.getChildren()) holder.insertBefore(node);
2261
+ holder.remove();
2262
+ });
2263
+ $nestFollowingLists(root);
2264
+ if (root.getChildrenSize() === 0) root.append($createParagraphNode());
2265
+ }, { discrete: true });
2266
+ editor.update(() => {
2267
+ $recordGroups(chunks, importId, transformers);
2268
+ const root = $getRoot();
2269
+ const hasGroups = root.getChildren().some((node) => $getState(node, groupState)?.content != null);
2270
+ $setState(root, documentState, {
2271
+ importId,
2272
+ byteOrderMark,
2273
+ leading: hasGroups ? chunks[0]?.leading ?? "" : "",
2274
+ trailing: hasGroups ? chunks[chunks.length - 1]?.trailing ?? "" : body,
2275
+ lineEnding
2276
+ });
2277
+ }, { discrete: true });
2278
+ }
2279
+ /**
2280
+ * Joins the lines of a paragraph, list item, or block quote across soft line
2281
+ * breaks: a line ending without two trailing spaces or a backslash continues
2282
+ * the block, as one space (CommonMark, soft line breaks; spec:AST-061 FR5).
2283
+ * Lexical imports every line ending as a line break and marks the hard ones,
2284
+ * so the unmarked ones outside code are the soft breaks.
2285
+ */
2286
+ function $joinSoftLineBreaks(element) {
2287
+ for (const child of element.getChildren()) if ($isElementNode(child) && !$isCodeNode(child)) $joinSoftLineBreaks(child);
2288
+ for (const child of element.getChildren()) {
2289
+ if (!$isLineBreakNode(child) || isMarkedHardLineBreak(child)) continue;
2290
+ const previous = child.getPreviousSibling();
2291
+ if ($isTextNode(previous) && !previous.hasFormat("code")) {
2292
+ const text = previous.getTextContent();
2293
+ let end = text.length;
2294
+ while (end > 0 && (text[end - 1] === " " || text[end - 1] === " ")) end--;
2295
+ previous.setTextContent(text.slice(0, end));
2296
+ }
2297
+ const next = child.getNextSibling();
2298
+ if ($isTextNode(next) && !next.hasFormat("code")) next.setTextContent(next.getTextContent().replace(/^[ \t]+/, ""));
2299
+ child.replace($createTextNode(" "));
2300
+ }
2301
+ }
2302
+ /**
2303
+ * Moves a list that begins nested right after another list into that list's
2304
+ * last item. Lexical starts a new top-level list for an item of a different
2305
+ * type (a bullet under `1. item`) and nests it there, while CommonMark nests
2306
+ * it inside the item above; without this, writing it back would lose the
2307
+ * nesting (spec:AST-061 FR5, spec:AST-062 FR3).
2308
+ */
2309
+ function $nestFollowingLists(root) {
2310
+ for (const node of root.getChildren()) {
2311
+ const previous = node.getPreviousSibling();
2312
+ if (!$isListNode(node) || !$isListNode(previous)) continue;
2313
+ let first = node.getFirstChild();
2314
+ while ($isListItemNode(first) && first.getChildrenSize() === 1 && $isListNode(first.getFirstChild())) {
2315
+ previous.append(first);
2316
+ first = node.getFirstChild();
2317
+ }
2318
+ if (node.getChildrenSize() === 0) node.remove();
2319
+ }
2320
+ }
2321
+ /**
2322
+ * Turns the first pass's chunk stamps into groups. Consecutive nodes stamped
2323
+ * with one chunk form a group, and the group also covers every later chunk up
2324
+ * to the next group's: those chunks merged into its nodes or imported to
2325
+ * nothing. Chunks before the first group become part of it.
2326
+ */
2327
+ function $recordGroups(chunks, importId, transformers) {
2328
+ const children = $getRoot().getChildren();
2329
+ const chunkOf = (node) => {
2330
+ const group = $getState(node, groupState)?.group;
2331
+ if (group == null || !group.startsWith(`${importId}:`)) return null;
2332
+ return Number(group.slice(importId.length + 1));
2333
+ };
2334
+ let index = 0;
2335
+ let isFirstGroup = true;
2336
+ while (index < children.length) {
2337
+ const firstChunk = chunkOf(children[index]);
2338
+ if (firstChunk == null) {
2339
+ index++;
2340
+ continue;
2341
+ }
2342
+ const group = [];
2343
+ while (index < children.length && chunkOf(children[index]) === firstChunk) {
2344
+ group.push(children[index]);
2345
+ index++;
2346
+ }
2347
+ const nextChunk = index === children.length ? chunks.length : chunkOf(children[index]) ?? chunks.length;
2348
+ const startChunk = isFirstGroup ? 0 : firstChunk;
2349
+ isFirstGroup = false;
2350
+ const covered = chunks.slice(startChunk, nextChunk);
2351
+ const content = covered.map((chunk, position) => (position === 0 ? "" : chunk.leading) + (position === covered.length - 1 ? chunk.content : chunk.content + chunk.trailing)).join("");
2352
+ const isLastGroup = index === children.length;
2353
+ const trailing = isLastGroup ? "" : covered[covered.length - 1]?.trailing ?? "";
2354
+ const record = {
2355
+ group: `${importId}:${firstChunk}`,
2356
+ size: group.length,
2357
+ content,
2358
+ trailing,
2359
+ canonicalHash: $canonicalMarkdown(group, transformers).hash,
2360
+ lineEnding: lineEndingOf(content + (covered[covered.length - 1]?.trailing ?? ""), "\n"),
2361
+ ...!isLastGroup && !ENDS_WITH_BLANK_LINE.test(trailing) ? { next: `${importId}:${nextChunk}` } : {}
2362
+ };
2363
+ group.forEach((node, position) => {
2364
+ $setState(node, groupState, position === 0 ? record : { group: record.group });
2365
+ });
2366
+ }
2367
+ }
2368
+ //#endregion
2369
+ //#region src/markdownSource.ts
2370
+ /** Whether `text` is one thematic break line, as written. */
2371
+ function isRuleLine(text) {
2372
+ return !text.includes("\n") && THEMATIC_BREAK_LINE.test(text);
2373
+ }
2374
+ /**
2375
+ * Whether the bytes recorded after `piece` still separate it from `next`.
2376
+ * Bytes ending in a blank line separate any two blocks. A single line break
2377
+ * only follows or precedes a thematic break (a rule is a chunk of its own),
2378
+ * and it belongs to the block it follows:
2379
+ *
2380
+ * - after a rule as written, it stays whatever comes next, because no line
2381
+ * after a rule can join it;
2382
+ * - between the same two blocks, both as written, it stays;
2383
+ * - after a changed block, it stays only above the same rule as written when
2384
+ * that rule cannot underline the block as a heading (`***`, `___`, or
2385
+ * spaced dashes, not `---`).
2386
+ *
2387
+ * Everywhere else — next to a moved, inserted, deleted, or changed block — a
2388
+ * blank line separates the two, so no block can join its neighbor.
2389
+ */
2390
+ function keepsRecordedTrailing(piece, next) {
2391
+ if (piece.trailing == null || !piece.trailing.includes("\n")) return false;
2392
+ if (ENDS_WITH_BLANK_LINE.test(piece.trailing)) return true;
2393
+ if (piece.isAsWritten && isRuleLine(piece.text)) return true;
2394
+ if (piece.next == null || piece.next !== next.group || !next.isAsWritten) return false;
2395
+ return piece.isAsWritten || isRuleLine(next.text) && !SETEXT_DASHES.test(next.text);
2396
+ }
2397
+ /**
2398
+ * Exports the root per spec:AST-062: unchanged groups as authored, changed and
2399
+ * new blocks in canonical form, all in the document's envelope. Reads the tree
2400
+ * without changing it, so it runs in a read of the live editor state.
2401
+ */
2402
+ function $exportMarkdownKeepingSource(transformers) {
2403
+ const transformerList = transformers;
2404
+ const root = $getRoot();
2405
+ const document = $getState(root, documentState);
2406
+ const lineEnding = document?.lineEnding ?? "\n";
2407
+ const children = root.getChildren();
2408
+ const pieces = [];
2409
+ let index = 0;
2410
+ while (index < children.length) {
2411
+ const first = children[index];
2412
+ const record = $getState(first, groupState);
2413
+ const group = [first];
2414
+ index++;
2415
+ if (record?.content != null) while (index < children.length && $getState(children[index], groupState)?.group === record.group && $getState(children[index], groupState)?.content == null) {
2416
+ group.push(children[index]);
2417
+ index++;
2418
+ }
2419
+ const canonical = $canonicalMarkdown(group, transformerList);
2420
+ const isOwn = document != null && record?.group.startsWith(`${document.importId}:`) === true;
2421
+ if (record?.content != null && group.length === record.size && canonical.hash === record.canonicalHash) {
2422
+ pieces.push({
2423
+ text: isOwn ? record.content : withLineEnding(record.content, lineEnding),
2424
+ trailing: isOwn ? record.trailing ?? null : null,
2425
+ isAsWritten: isOwn,
2426
+ group: record.group,
2427
+ next: record.next ?? null
2428
+ });
2429
+ continue;
2430
+ }
2431
+ const regenerated = $regeneratedMarkdown(group, canonical.markdown, transformerList);
2432
+ pieces.push({
2433
+ text: withLineEnding(regenerated, isOwn && record?.lineEnding != null ? record.lineEnding : lineEnding),
2434
+ trailing: isOwn ? record?.trailing ?? null : null,
2435
+ isAsWritten: false,
2436
+ group: record?.group ?? null,
2437
+ next: isOwn ? record?.next ?? null : null
2438
+ });
2439
+ }
2440
+ const separator = lineEnding + lineEnding;
2441
+ let output = (document?.byteOrderMark === true ? "" : "") + (document?.leading ?? "");
2442
+ pieces.forEach((piece, position) => {
2443
+ output += piece.text;
2444
+ if (position < pieces.length - 1) output += keepsRecordedTrailing(piece, pieces[position + 1]) ? piece.trailing ?? "" : separator;
2445
+ });
2446
+ return output + (document?.trailing ?? "");
2447
+ }
2448
+ //#endregion
2449
+ //#region src/markdownSerializers.ts
2450
+ function createSerializerEditor(nodes) {
2451
+ return createHeadlessEditor({
2452
+ namespace: "astryx-editor-serializer",
2453
+ nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
2454
+ onError(error) {
2455
+ throw error;
2456
+ }
2457
+ });
2458
+ }
2459
+ /**
2460
+ * Convert a Markdown string to a serialized Lexical `EditorState` JSON string
2461
+ * — the same shape `RichTextEditor`'s `defaultValue` expects. Runs headless
2462
+ * (no DOM), so it is safe in Node / SSR.
2463
+ *
2464
+ * @example
2465
+ * ```
2466
+ * const value = markdownToEditorStateJSON('# Title\n\nHello');
2467
+ * <RichTextEditor label="Notes" defaultValue={value} />
2468
+ * ```
2469
+ */
2470
+ function markdownToEditorStateJSON(markdown, options = {}) {
2471
+ const { transformers = DEFAULT_TRANSFORMERS, nodes, extensions = [] } = options;
2472
+ const plugins = pluginsOf(extensions, transformers);
2473
+ const editor = createSerializerEditor(nodes);
2474
+ importMarkdownKeepingSource(editor, markdown, [...transformers], plugins);
2475
+ return JSON.stringify(editor.getEditorState().toJSON());
2476
+ }
2477
+ /**
2478
+ * Convert a serialized Lexical `EditorState` JSON string (e.g. the value
2479
+ * produced by `RichTextEditor`'s `onChange` or `defaultValue`) to a Markdown
2480
+ * string. Runs headless (no DOM), so it is safe in Node / SSR.
2481
+ *
2482
+ * @example
2483
+ * ```
2484
+ * const md = editorStateJSONToMarkdown(savedJson);
2485
+ * ```
2486
+ */
2487
+ function editorStateJSONToMarkdown(editorStateJSON, options = {}) {
2488
+ const { transformers = DEFAULT_TRANSFORMERS, nodes } = options;
2489
+ return createSerializerEditor(nodes).parseEditorState(editorStateJSON).read(() => $exportMarkdownKeepingSource([...transformers]));
2490
+ }
2491
+ //#endregion
2492
+ export { createRichTextExtension as a, $getTaskState as c, DEFAULT_NODES as d, $firstSelectedText as f, setRichTextExtensionNodeDecorator as g, RichTextExtensionNode as h, RichTextExtensionError as i, $setTaskState as l, $selectedExtensionNodesOnly as m, markdownToEditorStateJSON as n, pluginsOf as o, $isRichTextExtensionNode as p, $exportMarkdownKeepingSource as r, DEFAULT_TRANSFORMERS as s, editorStateJSONToMarkdown as t, registerTaskListEditing as u };