@haklex/rich-editor 0.0.79 → 0.0.81

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,1463 @@
1
+ import { c as setCodeBlockCursorIntent, o as $createCodeBlockEditNode, s as $createBannerEditNode, t as getResolvedEditNodes } from "./node-registry-CeVi2y9f.js";
2
+ import { C as OPEN_IMAGE_UPLOAD_DIALOG_COMMAND, T as FootnoteNode, _ as $createKaTeXBlockNode, b as $createImageNode, d as $createMentionNode, g as KaTeXInlineNode, j as extractTextContent, k as AlertQuoteNode, m as $createKaTeXInlineNode, o as $createSpoilerNode, p as MentionNode, s as SpoilerNode, w as $createFootnoteNode, y as KaTeXBlockNode } from "./theme-DHOUKKSr.js";
3
+ import { a as FootnoteDefinitionsProvider, n as computeImageMeta } from "./KaTeXRenderer-BsyRH5_t.js";
4
+ import { D as BannerNode, _ as $createDetailsNode, a as $createRubyNode, b as CodeBlockNode, f as $isGridContainerNode, g as FootnoteSectionNode, h as $isFootnoteSectionNode, m as $createFootnoteSectionNode, s as RubyNode, v as DetailsNode } from "./config-tfg1FWhG.js";
5
+ import { t as $createAlertQuoteEditNode } from "./AlertQuoteEditNode-BDoonB4u.js";
6
+ import { n as probeFavicon, t as getHostname } from "./favicon-DIWusrrw.js";
7
+ import { CheckListPlugin } from "@lexical/react/LexicalCheckListPlugin";
8
+ import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
9
+ import { ListPlugin } from "@lexical/react/LexicalListPlugin";
10
+ import { TabIndentationPlugin } from "@lexical/react/LexicalTabIndentationPlugin";
11
+ import { TablePlugin } from "@lexical/react/LexicalTablePlugin";
12
+ import { AutoLinkNode, LinkNode, createLinkMatcherWithRegExp, registerAutoLink } from "@lexical/link";
13
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
14
+ import { createContext, use, useCallback, useEffect, useMemo, useRef, useState } from "react";
15
+ import { $createQuoteNode, $isQuoteNode, DRAG_DROP_PASTE, QuoteNode } from "@lexical/rich-text";
16
+ import { $addUpdateTag, $createLineBreakNode, $createNodeSelection, $createParagraphNode, $createTextNode, $getRoot, $getSelection, $getState, $insertNodes, $isDecoratorNode, $isElementNode, $isNodeSelection, $isParagraphNode, $isRangeSelection, $isRootNode, $isTextNode, $nodesOfType, $parseSerializedNode, $setSelection, $setState, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_EDITOR, COMMAND_PRIORITY_HIGH, COMMAND_PRIORITY_LOW, IS_CODE, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_RIGHT_COMMAND, KEY_ARROW_UP_COMMAND, KEY_BACKSPACE_COMMAND, KEY_DELETE_COMMAND, KEY_ENTER_COMMAND, PASTE_COMMAND, createEditor, createState } from "lexical";
17
+ import { $createHorizontalRuleNode, HorizontalRuleNode, INSERT_HORIZONTAL_RULE_COMMAND } from "@lexical/extension";
18
+ import { CODE_BLOCK_NODE_TRANSFORMER, CONTAINER_TRANSFORMER, FOOTNOTE_SECTION_TRANSFORMER, FOOTNOTE_TRANSFORMER, GIT_ALERT_TRANSFORMER, HORIZONTAL_RULE_BLOCK_TRANSFORMER, IMAGE_BLOCK_TRANSFORMER, INSERT_TRANSFORMER, KATEX_BLOCK_TRANSFORMER, KATEX_INLINE_TRANSFORMER, LINK_CARD_BLOCK_TRANSFORMER, MENTION_TRANSFORMER, MERMAID_BLOCK_TRANSFORMER, RUBY_TRANSFORMER, SPOILER_TRANSFORMER, SUBSCRIPT_TRANSFORMER, SUPERSCRIPT_TRANSFORMER, TABLE_BLOCK_TRANSFORMER, VIDEO_BLOCK_TRANSFORMER } from "@haklex/rich-headless/transformers";
19
+ import { $convertFromMarkdownString, CHECK_LIST, CODE, QUOTE, TRANSFORMERS } from "@lexical/markdown";
20
+ import { $createTableCellNode, $createTableNode, $createTableRowNode, TableCellHeaderStates } from "@lexical/table";
21
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
22
+ import { Check, Info, Link2, Upload } from "lucide-react";
23
+ import { MarkdownShortcutPlugin } from "@lexical/react/LexicalMarkdownShortcutPlugin";
24
+ import { nanoid } from "nanoid";
25
+ import { ActionBar, ActionButton, Dialog, DialogPopup, DialogTitle, SegmentedControl } from "@haklex/rich-editor-ui";
26
+ //#region src/plugins/AutoLinkPlugin.tsx
27
+ var DEFAULT_MATCHERS = [createLinkMatcherWithRegExp(/https?:\/\/(?:www\.)?[\w#%+.:=@~-]{1,256}\.[A-Za-z]{2}[\w#%&()+./:=?@~-]*/), createLinkMatcherWithRegExp(/(?:[\w%+.-]+@[\d.a-z-]+\.[a-z]{2,})/i, (text) => `mailto:${text}`)];
28
+ function AutoLinkPlugin({ matchers }) {
29
+ const [editor] = useLexicalComposerContext();
30
+ useEffect(() => {
31
+ return registerAutoLink(editor, {
32
+ matchers: matchers ?? DEFAULT_MATCHERS,
33
+ changeHandlers: [],
34
+ excludeParents: []
35
+ });
36
+ }, [editor, matchers]);
37
+ return null;
38
+ }
39
+ //#endregion
40
+ //#region src/plugins/BlockExitPlugin.tsx
41
+ function selectDecoratorNode(node, cursorPlacement = "start") {
42
+ if (node.getType() === "code-block") setCodeBlockCursorIntent(node.getKey(), cursorPlacement);
43
+ const selection = $createNodeSelection();
44
+ selection.add(node.getKey());
45
+ $setSelection(selection);
46
+ }
47
+ function isAtTopLevelBoundary(selection, direction) {
48
+ const point = selection.anchor;
49
+ const topLevel = point.getNode().getTopLevelElementOrThrow();
50
+ const pointNode = point.getNode();
51
+ if (point.type === "text") {
52
+ if (!$isTextNode(pointNode)) return false;
53
+ const expectedOffset = direction === "start" ? 0 : pointNode.getTextContentSize();
54
+ if (point.offset !== expectedOffset) return false;
55
+ } else {
56
+ if (!$isElementNode(pointNode)) return false;
57
+ const expectedOffset = direction === "start" ? 0 : pointNode.getChildrenSize();
58
+ if (point.offset !== expectedOffset) return false;
59
+ }
60
+ let current = pointNode;
61
+ while (current && current !== topLevel) {
62
+ if ((direction === "start" ? current.getPreviousSibling() : current.getNextSibling()) !== null) return false;
63
+ current = current.getParent();
64
+ }
65
+ return current === topLevel;
66
+ }
67
+ function isSingleLineParagraph(node) {
68
+ return $isParagraphNode(node) && !node.getTextContent().includes("\n");
69
+ }
70
+ function getOutermostNodeWithinTopLevel(node, topLevel) {
71
+ let current = node;
72
+ while (current.getParent() !== topLevel) {
73
+ const parent = current.getParent();
74
+ if (!parent) break;
75
+ current = parent;
76
+ }
77
+ return current;
78
+ }
79
+ function exitInlineCodeAtLineEnd(selection) {
80
+ if (!selection.isCollapsed() || selection.anchor.type !== "text") return false;
81
+ const anchorNode = selection.anchor.getNode();
82
+ if (!$isTextNode(anchorNode) || !anchorNode.hasFormat("code")) return false;
83
+ if (selection.anchor.offset !== anchorNode.getTextContentSize()) return false;
84
+ if (!isAtTopLevelBoundary(selection, "end")) return false;
85
+ const topLevel = anchorNode.getTopLevelElementOrThrow();
86
+ const exitOffset = getOutermostNodeWithinTopLevel(anchorNode, topLevel).getIndexWithinParent() + 1;
87
+ selection.anchor.set(topLevel.getKey(), exitOffset, "element");
88
+ selection.focus.set(topLevel.getKey(), exitOffset, "element");
89
+ selection.setFormat(anchorNode.getFormat() & ~IS_CODE);
90
+ selection.setStyle(anchorNode.getStyle());
91
+ return true;
92
+ }
93
+ function BlockExitPlugin() {
94
+ const [editor] = useLexicalComposerContext();
95
+ useEffect(() => {
96
+ const unregisterArrowRight = editor.registerCommand(KEY_ARROW_RIGHT_COMMAND, (event) => {
97
+ const selection = $getSelection();
98
+ if (!$isRangeSelection(selection)) return false;
99
+ if (!exitInlineCodeAtLineEnd(selection)) return false;
100
+ event?.preventDefault();
101
+ return true;
102
+ }, COMMAND_PRIORITY_CRITICAL);
103
+ const unregisterArrowDown = editor.registerCommand(KEY_ARROW_DOWN_COMMAND, (event) => {
104
+ const selection = $getSelection();
105
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
106
+ const anchorNode = selection.anchor.getNode();
107
+ const topLevelElement = anchorNode.getTopLevelElementOrThrow();
108
+ const shouldSelectNextDecorator = isAtTopLevelBoundary(selection, "end") || isSingleLineParagraph(topLevelElement);
109
+ if (!$isQuoteNode(topLevelElement) && shouldSelectNextDecorator) {
110
+ const next = topLevelElement.getNextSibling();
111
+ if (next && $isDecoratorNode(next) && next.isKeyboardSelectable()) {
112
+ event?.preventDefault();
113
+ selectDecoratorNode(next, "start");
114
+ return true;
115
+ }
116
+ }
117
+ const element = $isElementNode(anchorNode) ? anchorNode : anchorNode.getParentOrThrow();
118
+ let quoteChild = element;
119
+ let quoteNode = null;
120
+ let current = element;
121
+ while (current) {
122
+ const parent = current.getParent();
123
+ if (!parent || $isRootNode(parent)) break;
124
+ if ($isQuoteNode(parent)) {
125
+ quoteNode = parent;
126
+ quoteChild = current;
127
+ break;
128
+ }
129
+ current = parent;
130
+ }
131
+ if (!quoteNode) return false;
132
+ if (quoteChild.getNextSibling() !== null) return false;
133
+ if (!$isParagraphNode(quoteChild) || quoteChild.getTextContent() !== "") return false;
134
+ event?.preventDefault();
135
+ let next = quoteNode.getNextSibling();
136
+ if (!next) {
137
+ next = $createParagraphNode();
138
+ quoteNode.insertAfter(next);
139
+ }
140
+ next.selectStart();
141
+ return true;
142
+ }, COMMAND_PRIORITY_CRITICAL);
143
+ const unregisterCmdEnter = editor.registerCommand(KEY_ENTER_COMMAND, (event) => {
144
+ if (!event?.metaKey && !event?.ctrlKey) return false;
145
+ const selection = $getSelection();
146
+ if ($isNodeSelection(selection)) {
147
+ const nodes = selection.getNodes();
148
+ if (nodes.length !== 1) return false;
149
+ const node = nodes[0];
150
+ if (!$isDecoratorNode(node)) return false;
151
+ event.preventDefault();
152
+ let next = node.getNextSibling();
153
+ if (!next) {
154
+ next = $createParagraphNode();
155
+ node.insertAfter(next);
156
+ }
157
+ if ($isElementNode(next)) next.selectStart();
158
+ else if ($isDecoratorNode(next)) selectDecoratorNode(next, "start");
159
+ return true;
160
+ }
161
+ if (!$isRangeSelection(selection)) return false;
162
+ const topLevelElement = selection.anchor.getNode().getTopLevelElementOrThrow();
163
+ if ($isParagraphNode(topLevelElement)) return false;
164
+ event.preventDefault();
165
+ let next = topLevelElement.getNextSibling();
166
+ if (!next || !$isParagraphNode(next)) {
167
+ next = $createParagraphNode();
168
+ topLevelElement.insertAfter(next);
169
+ }
170
+ next.selectStart();
171
+ return true;
172
+ }, COMMAND_PRIORITY_CRITICAL);
173
+ function handleDeleteDecorator(event) {
174
+ const selection = $getSelection();
175
+ if (!$isNodeSelection(selection)) return false;
176
+ const nodes = selection.getNodes();
177
+ if (nodes.length !== 1) return false;
178
+ const node = nodes[0];
179
+ if (!$isDecoratorNode(node)) return false;
180
+ event?.preventDefault();
181
+ const prev = node.getPreviousSibling();
182
+ const next = node.getNextSibling();
183
+ node.remove();
184
+ if (prev && $isElementNode(prev)) prev.selectEnd();
185
+ else if (prev && $isDecoratorNode(prev)) selectDecoratorNode(prev, "end");
186
+ else if (next && $isElementNode(next)) next.selectStart();
187
+ else if (next && $isDecoratorNode(next)) selectDecoratorNode(next, "start");
188
+ else {
189
+ const root = $getRoot();
190
+ if (root && $isElementNode(root)) {
191
+ const p = $createParagraphNode();
192
+ root.append(p);
193
+ p.selectStart();
194
+ }
195
+ }
196
+ return true;
197
+ }
198
+ const unregisterBackspace = editor.registerCommand(KEY_BACKSPACE_COMMAND, handleDeleteDecorator, COMMAND_PRIORITY_HIGH);
199
+ const unregisterDelete = editor.registerCommand(KEY_DELETE_COMMAND, handleDeleteDecorator, COMMAND_PRIORITY_HIGH);
200
+ const unregisterArrowUpDecorator = editor.registerCommand(KEY_ARROW_UP_COMMAND, (event) => {
201
+ const selection = $getSelection();
202
+ if ($isRangeSelection(selection) && selection.isCollapsed()) {
203
+ const topLevelElement = selection.anchor.getNode().getTopLevelElementOrThrow();
204
+ const shouldSelectPreviousDecorator = isAtTopLevelBoundary(selection, "start") || isSingleLineParagraph(topLevelElement);
205
+ if (!$isQuoteNode(topLevelElement) && shouldSelectPreviousDecorator) {
206
+ const prev = topLevelElement.getPreviousSibling();
207
+ if (prev && $isDecoratorNode(prev) && prev.isKeyboardSelectable()) {
208
+ event?.preventDefault();
209
+ selectDecoratorNode(prev, "end");
210
+ return true;
211
+ }
212
+ }
213
+ }
214
+ if (!$isNodeSelection(selection)) return false;
215
+ const nodes = selection.getNodes();
216
+ if (nodes.length !== 1) return false;
217
+ const node = nodes[0];
218
+ if (!$isDecoratorNode(node)) return false;
219
+ const prev = node.getPreviousSibling();
220
+ if (prev && $isElementNode(prev)) {
221
+ event?.preventDefault();
222
+ prev.selectEnd();
223
+ return true;
224
+ }
225
+ if (prev && $isDecoratorNode(prev)) {
226
+ event?.preventDefault();
227
+ selectDecoratorNode(prev, "end");
228
+ return true;
229
+ }
230
+ return false;
231
+ }, COMMAND_PRIORITY_CRITICAL);
232
+ const unregisterArrowDownDecorator = editor.registerCommand(KEY_ARROW_DOWN_COMMAND, (event) => {
233
+ const selection = $getSelection();
234
+ if (!$isNodeSelection(selection)) return false;
235
+ const nodes = selection.getNodes();
236
+ if (nodes.length !== 1) return false;
237
+ const node = nodes[0];
238
+ if (!$isDecoratorNode(node)) return false;
239
+ const next = node.getNextSibling();
240
+ if (next && $isElementNode(next)) {
241
+ event?.preventDefault();
242
+ next.selectStart();
243
+ return true;
244
+ }
245
+ if (next && $isDecoratorNode(next)) {
246
+ event?.preventDefault();
247
+ selectDecoratorNode(next, "start");
248
+ return true;
249
+ }
250
+ return false;
251
+ }, COMMAND_PRIORITY_CRITICAL);
252
+ return () => {
253
+ unregisterArrowRight();
254
+ unregisterArrowDown();
255
+ unregisterCmdEnter();
256
+ unregisterBackspace();
257
+ unregisterDelete();
258
+ unregisterArrowUpDecorator();
259
+ unregisterArrowDownDecorator();
260
+ };
261
+ }, [editor]);
262
+ return null;
263
+ }
264
+ //#endregion
265
+ //#region src/transformers/horizontal-rule.ts
266
+ var HORIZONTAL_RULE_REGEX = /^(---|\*\*\*|___)\s?$/;
267
+ var HORIZONTAL_RULE_BLOCK_TRANSFORMER$1 = {
268
+ ...HORIZONTAL_RULE_BLOCK_TRANSFORMER,
269
+ dependencies: [HorizontalRuleNode],
270
+ regExp: HORIZONTAL_RULE_REGEX,
271
+ replace: (parentNode) => {
272
+ const hrNode = $createHorizontalRuleNode();
273
+ const paragraph = $createParagraphNode();
274
+ parentNode.replace(hrNode);
275
+ hrNode.insertAfter(paragraph);
276
+ paragraph.selectStart();
277
+ }
278
+ };
279
+ //#endregion
280
+ //#region src/plugins/HorizontalRulePlugin.tsx
281
+ function HorizontalRulePlugin() {
282
+ const [editor] = useLexicalComposerContext();
283
+ useEffect(() => {
284
+ const unregisterInsert = editor.registerCommand(INSERT_HORIZONTAL_RULE_COMMAND, () => {
285
+ const selection = $getSelection();
286
+ if (!$isRangeSelection(selection)) return false;
287
+ const topLevel = selection.focus.getNode().getTopLevelElement();
288
+ if (!topLevel) return false;
289
+ const hrNode = $createHorizontalRuleNode();
290
+ const paragraph = $createParagraphNode();
291
+ topLevel.insertAfter(hrNode);
292
+ hrNode.insertAfter(paragraph);
293
+ paragraph.selectStart();
294
+ return true;
295
+ }, COMMAND_PRIORITY_EDITOR);
296
+ const unregisterEnter = editor.registerCommand(KEY_ENTER_COMMAND, (event) => {
297
+ const selection = $getSelection();
298
+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return false;
299
+ const anchorNode = selection.anchor.getNode();
300
+ if (!$isTextNode(anchorNode)) return false;
301
+ const textContent = anchorNode.getTextContent();
302
+ if (!HORIZONTAL_RULE_REGEX.test(textContent)) return false;
303
+ const parentNode = anchorNode.getParent();
304
+ if (!parentNode) return false;
305
+ event?.preventDefault();
306
+ const hrNode = $createHorizontalRuleNode();
307
+ const paragraph = $createParagraphNode();
308
+ parentNode.replace(hrNode);
309
+ hrNode.insertAfter(paragraph);
310
+ paragraph.selectStart();
311
+ return true;
312
+ }, COMMAND_PRIORITY_LOW);
313
+ return () => {
314
+ unregisterInsert();
315
+ unregisterEnter();
316
+ };
317
+ }, [editor]);
318
+ return null;
319
+ }
320
+ //#endregion
321
+ //#region src/transformers/alert.ts
322
+ var ALERT_TYPE_MAP = {
323
+ NOTE: "note",
324
+ TIP: "tip",
325
+ IMPORTANT: "important",
326
+ WARNING: "warning",
327
+ CAUTION: "caution"
328
+ };
329
+ var GIT_ALERT_TRANSFORMER$1 = {
330
+ ...GIT_ALERT_TRANSFORMER,
331
+ dependencies: [AlertQuoteNode],
332
+ regExp: /^>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/,
333
+ replace: (parentNode, children, match) => {
334
+ const alertNode = $createAlertQuoteEditNode(ALERT_TYPE_MAP[match[1]] || "note", { root: {
335
+ children: [{
336
+ type: "paragraph",
337
+ children: children.map((child) => child.exportJSON()),
338
+ direction: null,
339
+ format: "",
340
+ indent: 0,
341
+ textFormat: 0,
342
+ textStyle: "",
343
+ version: 1
344
+ }],
345
+ direction: null,
346
+ format: "",
347
+ indent: 0,
348
+ type: "root",
349
+ version: 1
350
+ } });
351
+ parentNode.replace(alertNode);
352
+ }
353
+ };
354
+ //#endregion
355
+ //#region src/transformers/code-block.ts
356
+ function findCodeBlockKlass(nodes) {
357
+ return nodes.find((n) => n.getType?.() === "code-block") || CodeBlockNode;
358
+ }
359
+ var CODE_BLOCK_MULTILINE_TRANSFORMER = {
360
+ dependencies: [],
361
+ regExpEnd: {
362
+ optional: true,
363
+ regExp: /[\t ]*```$/
364
+ },
365
+ regExpStart: /^[\t ]*```([\w-]+)?/,
366
+ replace: (rootNode, _children, startMatch, _endMatch, linesInBetween, isImport) => {
367
+ const lang = startMatch[1] || "";
368
+ let code = "";
369
+ if (linesInBetween) {
370
+ const lines = [...linesInBetween];
371
+ while (lines.length > 0 && !lines[0].length) lines.shift();
372
+ while (lines.length > 0 && !lines.at(-1)?.length) lines.pop();
373
+ code = lines.join("\n");
374
+ }
375
+ const node = new (findCodeBlockKlass(getResolvedEditNodes()))(code, lang);
376
+ if (isImport || $isRootNode(rootNode)) rootNode.append(node);
377
+ else rootNode.replace(node);
378
+ const selection = $createNodeSelection();
379
+ selection.add(node.getKey());
380
+ $setSelection(selection);
381
+ },
382
+ type: "multiline-element"
383
+ };
384
+ //#endregion
385
+ //#region src/transformers/container.ts
386
+ var BANNER_TYPE_MAP = {
387
+ note: "note",
388
+ info: "note",
389
+ tip: "tip",
390
+ success: "tip",
391
+ important: "important",
392
+ warning: "warning",
393
+ warn: "warning",
394
+ error: "caution",
395
+ danger: "caution",
396
+ caution: "caution"
397
+ };
398
+ var CONTAINER_TRANSFORMER$1 = {
399
+ ...CONTAINER_TRANSFORMER,
400
+ dependencies: [BannerNode, DetailsNode],
401
+ regExp: /^:::\s*(\w+)(?:\{([^}]*)\})?\s*$/,
402
+ replace: (parentNode, children, match) => {
403
+ const type = match[1];
404
+ const params = match[2];
405
+ if (type in BANNER_TYPE_MAP) {
406
+ const bannerType = BANNER_TYPE_MAP[type];
407
+ const banner = $createBannerEditNode(bannerType, { root: {
408
+ children: [{
409
+ type: "paragraph",
410
+ children: children.map((child) => child.exportJSON()),
411
+ direction: null,
412
+ format: "",
413
+ indent: 0,
414
+ textFormat: 0,
415
+ textStyle: "",
416
+ version: 1
417
+ }],
418
+ direction: null,
419
+ format: "",
420
+ indent: 0,
421
+ type: "root",
422
+ version: 1
423
+ } });
424
+ parentNode.replace(banner);
425
+ return;
426
+ }
427
+ if (type === "details") {
428
+ const summaryMatch = params?.match(/summary="([^"]*)"/);
429
+ const details = $createDetailsNode(summaryMatch ? summaryMatch[1] : "Details");
430
+ children.forEach((child) => {
431
+ details.append(child);
432
+ });
433
+ parentNode.replace(details);
434
+ return;
435
+ }
436
+ const paragraph = $createParagraphNode();
437
+ paragraph.append($createTextNode(`::: ${type}`));
438
+ children.forEach((child) => {
439
+ paragraph.append(child);
440
+ });
441
+ parentNode.replace(paragraph);
442
+ }
443
+ };
444
+ //#endregion
445
+ //#region src/transformers/footnote.ts
446
+ var FOOTNOTE_TRANSFORMER$1 = {
447
+ ...FOOTNOTE_TRANSFORMER,
448
+ dependencies: [FootnoteNode],
449
+ replace: (textNode, match) => {
450
+ const footnoteNode = $createFootnoteNode(match[1]);
451
+ textNode.replace(footnoteNode);
452
+ }
453
+ };
454
+ var FOOTNOTE_SECTION_TRANSFORMER$1 = {
455
+ ...FOOTNOTE_SECTION_TRANSFORMER,
456
+ dependencies: [FootnoteSectionNode],
457
+ regExp: /^\[\^(\w+)\]:[\t ]+(\S.*)$/,
458
+ replace: (parentNode, _children, match) => {
459
+ const identifier = match[1];
460
+ const content = match[2];
461
+ const root = parentNode.getParent();
462
+ if (root) {
463
+ const children = root.getChildren();
464
+ for (const child of children) if ($isFootnoteSectionNode(child)) {
465
+ child.setDefinition(identifier, content);
466
+ parentNode.remove();
467
+ return;
468
+ }
469
+ }
470
+ const sectionNode = $createFootnoteSectionNode({ [identifier]: content });
471
+ parentNode.replace(sectionNode);
472
+ }
473
+ };
474
+ //#endregion
475
+ //#region src/transformers/katex.ts
476
+ var KATEX_INLINE_TRANSFORMER$1 = {
477
+ ...KATEX_INLINE_TRANSFORMER,
478
+ dependencies: [KaTeXInlineNode],
479
+ replace: (textNode, match) => {
480
+ const katexNode = $createKaTeXInlineNode(match[1]);
481
+ textNode.replace(katexNode);
482
+ }
483
+ };
484
+ var KATEX_BLOCK_TRANSFORMER$1 = {
485
+ ...KATEX_BLOCK_TRANSFORMER,
486
+ dependencies: [KaTeXBlockNode],
487
+ replace: (textNode, match) => {
488
+ const katexNode = $createKaTeXBlockNode(match[1]);
489
+ textNode.replace(katexNode);
490
+ }
491
+ };
492
+ //#endregion
493
+ //#region src/transformers/mention.ts
494
+ var MENTION_TRANSFORMER$1 = {
495
+ ...MENTION_TRANSFORMER,
496
+ dependencies: [MentionNode],
497
+ replace: (textNode, match) => {
498
+ const displayName = match[1] || void 0;
499
+ const mentionNode = $createMentionNode(match[2], match[3], displayName);
500
+ textNode.replace(mentionNode);
501
+ }
502
+ };
503
+ //#endregion
504
+ //#region src/transformers/quote.ts
505
+ var QUOTE_TRANSFORMER = {
506
+ dependencies: [QuoteNode],
507
+ export: (node, exportChildren) => {
508
+ if (!$isQuoteNode(node)) return null;
509
+ return exportChildren(node).split("\n").map((line) => `> ${line}`).join("\n");
510
+ },
511
+ regExp: /^>\s/,
512
+ replace: (parentNode, children, _match, isImport) => {
513
+ if (isImport) {
514
+ const previousNode = parentNode.getPreviousSibling();
515
+ if ($isQuoteNode(previousNode)) {
516
+ previousNode.splice(previousNode.getChildrenSize(), 0, [$createLineBreakNode(), ...children]);
517
+ parentNode.remove();
518
+ return;
519
+ }
520
+ }
521
+ const node = $createQuoteNode();
522
+ const paragraph = $createParagraphNode();
523
+ paragraph.append(...children);
524
+ node.append(paragraph);
525
+ parentNode.replace(node);
526
+ if (!isImport) paragraph.select(0, 0);
527
+ },
528
+ type: "element"
529
+ };
530
+ //#endregion
531
+ //#region src/transformers/grid-container.ts
532
+ function quoteAttr(value) {
533
+ return value.replaceAll("\"", "\\\"");
534
+ }
535
+ var GRID_CONTAINER_BLOCK_TRANSFORMER = {
536
+ dependencies: [],
537
+ export: (node) => {
538
+ if (!$isGridContainerNode(node)) return null;
539
+ const body = node.getCellStates().map((state) => extractTextContent(state)).map((content) => `::: cell\n${content}\n:::`).join("\n");
540
+ return `::: grid{cols=${node.getCols()} gap="${quoteAttr(node.getGap())}"}\n${body}\n:::`;
541
+ },
542
+ regExp: /\b\B/,
543
+ replace: () => {},
544
+ type: "element"
545
+ };
546
+ //#endregion
547
+ //#region src/transformers/ruby.ts
548
+ var RUBY_TRANSFORMER$1 = {
549
+ ...RUBY_TRANSFORMER,
550
+ dependencies: [RubyNode],
551
+ replace: (textNode, match) => {
552
+ const rubyNode = $createRubyNode(match[2] ?? "");
553
+ const baseText = match[1] ?? "";
554
+ if (baseText) rubyNode.append($createTextNode(baseText));
555
+ textNode.replace(rubyNode);
556
+ }
557
+ };
558
+ //#endregion
559
+ //#region src/transformers/spoiler.ts
560
+ var SPOILER_TRANSFORMER$1 = {
561
+ ...SPOILER_TRANSFORMER,
562
+ dependencies: [SpoilerNode],
563
+ replace: (textNode, match) => {
564
+ const spoilerNode = $createSpoilerNode();
565
+ spoilerNode.append($createTextNode(match[1]));
566
+ textNode.replace(spoilerNode);
567
+ }
568
+ };
569
+ //#endregion
570
+ //#region src/transformers/table.ts
571
+ var TABLE_ROW_REG_EXP = /^\|(.+)\|\s*$/;
572
+ var TABLE_DIVIDER_REG_EXP = /^\|(?:\s*:?-+:?\s*\|)+\s*$/;
573
+ function parseCells(row) {
574
+ const match = row.match(TABLE_ROW_REG_EXP);
575
+ if (!match) return [];
576
+ return match[1].split("|").map((c) => c.trim());
577
+ }
578
+ //#endregion
579
+ //#region src/transformers/index.ts
580
+ var ALL_TRANSFORMERS = [
581
+ SPOILER_TRANSFORMER$1,
582
+ MENTION_TRANSFORMER$1,
583
+ FOOTNOTE_TRANSFORMER$1,
584
+ INSERT_TRANSFORMER,
585
+ SUPERSCRIPT_TRANSFORMER,
586
+ SUBSCRIPT_TRANSFORMER,
587
+ RUBY_TRANSFORMER$1,
588
+ KATEX_INLINE_TRANSFORMER$1,
589
+ FOOTNOTE_SECTION_TRANSFORMER$1,
590
+ CONTAINER_TRANSFORMER$1,
591
+ GIT_ALERT_TRANSFORMER$1,
592
+ CHECK_LIST,
593
+ KATEX_BLOCK_TRANSFORMER$1,
594
+ IMAGE_BLOCK_TRANSFORMER,
595
+ VIDEO_BLOCK_TRANSFORMER,
596
+ CODE_BLOCK_NODE_TRANSFORMER,
597
+ CODE_BLOCK_MULTILINE_TRANSFORMER,
598
+ LINK_CARD_BLOCK_TRANSFORMER,
599
+ MERMAID_BLOCK_TRANSFORMER,
600
+ GRID_CONTAINER_BLOCK_TRANSFORMER,
601
+ HORIZONTAL_RULE_BLOCK_TRANSFORMER$1,
602
+ {
603
+ dependencies: [],
604
+ export: () => null,
605
+ handleImportAfterStartMatch({ lines, rootNode, startLineIndex }) {
606
+ if (startLineIndex + 1 >= lines.length) return null;
607
+ const dividerLine = lines[startLineIndex + 1];
608
+ if (!TABLE_DIVIDER_REG_EXP.test(dividerLine)) return null;
609
+ const headerCells = parseCells(lines[startLineIndex]);
610
+ if (headerCells.length === 0) return null;
611
+ let endLineIndex = startLineIndex + 1;
612
+ const dataRows = [];
613
+ for (let i = startLineIndex + 2; i < lines.length; i++) {
614
+ if (!TABLE_ROW_REG_EXP.test(lines[i])) break;
615
+ dataRows.push(parseCells(lines[i]));
616
+ endLineIndex = i;
617
+ }
618
+ const tableNode = $createTableNode();
619
+ const headerRow = $createTableRowNode();
620
+ for (const cell of headerCells) {
621
+ const cellNode = $createTableCellNode(TableCellHeaderStates.ROW);
622
+ const p = $createParagraphNode();
623
+ p.append($createTextNode(cell));
624
+ cellNode.append(p);
625
+ headerRow.append(cellNode);
626
+ }
627
+ tableNode.append(headerRow);
628
+ for (const row of dataRows) {
629
+ const rowNode = $createTableRowNode();
630
+ for (let i = 0; i < headerCells.length; i++) {
631
+ const cellNode = $createTableCellNode(TableCellHeaderStates.NO_STATUS);
632
+ const p = $createParagraphNode();
633
+ p.append($createTextNode(row[i] ?? ""));
634
+ cellNode.append(p);
635
+ rowNode.append(cellNode);
636
+ }
637
+ tableNode.append(rowNode);
638
+ }
639
+ rootNode.append(tableNode);
640
+ return [true, endLineIndex];
641
+ },
642
+ regExpEnd: {
643
+ optional: true,
644
+ regExp: TABLE_ROW_REG_EXP
645
+ },
646
+ regExpStart: TABLE_ROW_REG_EXP,
647
+ replace: () => {},
648
+ type: "multiline-element"
649
+ },
650
+ TABLE_BLOCK_TRANSFORMER,
651
+ QUOTE_TRANSFORMER,
652
+ ...TRANSFORMERS.filter((t) => t !== QUOTE && t !== CODE)
653
+ ];
654
+ //#endregion
655
+ //#region src/plugins/MarkdownPastePlugin.tsx
656
+ function getVSCodePasteData(clipboardData) {
657
+ const raw = clipboardData.getData("vscode-editor-data");
658
+ if (!raw) return null;
659
+ try {
660
+ return { language: JSON.parse(raw).mode || "text" };
661
+ } catch {
662
+ return null;
663
+ }
664
+ }
665
+ function hasRichHTML(clipboardData) {
666
+ const html = clipboardData.getData("text/html");
667
+ if (!html) return false;
668
+ if (/data-vscode|vscode-/i.test(html)) return false;
669
+ return new DOMParser().parseFromString(html, "text/html").body.querySelectorAll("strong,em,b,i,h1,h2,h3,h4,h5,h6,ul,ol,table,img,blockquote,pre>code,a[href]").length > 0;
670
+ }
671
+ function detectMarkdown(text) {
672
+ let score = 0;
673
+ if (/^#{1,6}\s+\S/m.test(text)) score += 5;
674
+ if (/^```[\w-]*$/m.test(text)) score += 5;
675
+ if (/\[[^\]]+\]\([^)]+\)/.test(text)) score += 4;
676
+ if (/!\[[^\]]*\]\([^)]+\)/.test(text)) score += 5;
677
+ if (/^\|.+\|$/m.test(text) && /^\|[\s:|-]+\|$/m.test(text)) score += 5;
678
+ if (/^>\s*\[!(?:note|tip|warning|caution|important)\]/im.test(text)) score += 5;
679
+ if (/^[*-]\s+\[[ x]\]/m.test(text)) score += 4;
680
+ if (/\*\*.+?\*\*/.test(text)) score += 2;
681
+ if (/(?<!\*)\*(?!\*)(?!\s).+?(?<!\s)(?<!\*)\*(?!\*)/.test(text)) score += 1;
682
+ if (/^[*+-]\s+\S/m.test(text)) score += 1;
683
+ if (/^\d+\.\s+\S/m.test(text)) score += 1;
684
+ if (/^>\s+\S/m.test(text)) score += 1;
685
+ if (/`.+?`/.test(text)) score += 1;
686
+ if (/^[*_-]{3,}$/m.test(text)) score += 2;
687
+ if (text.split(/\n{2,}/).filter(Boolean).length >= 2) score += 5;
688
+ if (text.length < 20) score -= 3;
689
+ if (!text.includes("\n")) score -= 2;
690
+ return score >= 5;
691
+ }
692
+ function convertAndInsert(markdown) {
693
+ let conversionError = null;
694
+ const tempEditor = createEditor({
695
+ namespace: "markdown-paste-temp",
696
+ nodes: getResolvedEditNodes(),
697
+ onError: (error) => {
698
+ conversionError = error;
699
+ }
700
+ });
701
+ tempEditor.update(() => {
702
+ $convertFromMarkdownString(markdown, ALL_TRANSFORMERS);
703
+ }, { discrete: true });
704
+ if (conversionError) {
705
+ console.error("MarkdownPastePlugin: convertAndInsert error", conversionError);
706
+ return false;
707
+ }
708
+ const serializedChildren = tempEditor.getEditorState().toJSON().root.children;
709
+ if (!serializedChildren.length) return false;
710
+ $insertNodes(serializedChildren.map((s) => $parseSerializedNode(s)));
711
+ return true;
712
+ }
713
+ function MarkdownPastePlugin() {
714
+ const [editor] = useLexicalComposerContext();
715
+ useEffect(() => {
716
+ return editor.registerCommand(PASTE_COMMAND, (event) => {
717
+ const clipboardData = "clipboardData" in event ? event.clipboardData : null;
718
+ if (!clipboardData) return false;
719
+ if (Array.from(clipboardData.files).some((f) => f.type.startsWith("image/"))) return false;
720
+ const vscodeData = getVSCodePasteData(clipboardData);
721
+ if (vscodeData) {
722
+ const code = clipboardData.getData("text/plain");
723
+ if (code) {
724
+ $insertNodes(code.split(/\r?\n{3,}/).filter(Boolean).map((s) => $createCodeBlockEditNode(s.replace(/^\s*\n/, "").replace(/\n\s*$/, ""), vscodeData.language)));
725
+ event.preventDefault();
726
+ return true;
727
+ }
728
+ }
729
+ if (hasRichHTML(clipboardData)) return false;
730
+ const text = clipboardData.getData("text/plain");
731
+ if (!text || !detectMarkdown(text)) return false;
732
+ try {
733
+ if (!convertAndInsert(text)) return false;
734
+ event.preventDefault();
735
+ return true;
736
+ } catch (error) {
737
+ console.error("MarkdownPastePlugin: paste error", error);
738
+ return false;
739
+ }
740
+ }, COMMAND_PRIORITY_HIGH);
741
+ }, [editor]);
742
+ return null;
743
+ }
744
+ //#endregion
745
+ //#region src/plugins/MarkdownShortcutsPlugin.tsx
746
+ function MarkdownShortcutsPlugin() {
747
+ return /* @__PURE__ */ jsx(MarkdownShortcutPlugin, { transformers: ALL_TRANSFORMERS });
748
+ }
749
+ //#endregion
750
+ //#region src/components/CorePlugins.tsx
751
+ function CorePlugins() {
752
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
753
+ /* @__PURE__ */ jsx(ListPlugin, {}),
754
+ /* @__PURE__ */ jsx(LinkPlugin, {}),
755
+ /* @__PURE__ */ jsx(TabIndentationPlugin, {}),
756
+ /* @__PURE__ */ jsx(TablePlugin, {}),
757
+ /* @__PURE__ */ jsx(CheckListPlugin, {}),
758
+ /* @__PURE__ */ jsx(MarkdownShortcutsPlugin, {}),
759
+ /* @__PURE__ */ jsx(MarkdownPastePlugin, {}),
760
+ /* @__PURE__ */ jsx(BlockExitPlugin, {}),
761
+ /* @__PURE__ */ jsx(HorizontalRulePlugin, {}),
762
+ /* @__PURE__ */ jsx(AutoLinkPlugin, {})
763
+ ] });
764
+ }
765
+ //#endregion
766
+ //#region src/context/ImageUploadContext.tsx
767
+ var ImageUploadContext = createContext(null);
768
+ function ImageUploadProvider({ upload, children }) {
769
+ return /* @__PURE__ */ jsx(ImageUploadContext.Provider, {
770
+ value: upload,
771
+ children
772
+ });
773
+ }
774
+ function useImageUpload() {
775
+ return use(ImageUploadContext);
776
+ }
777
+ //#endregion
778
+ //#region src/plugins/BlockIdPlugin.tsx
779
+ var blockIdState = createState("blockId", { parse: (v) => typeof v === "string" ? v : "" });
780
+ var NORMALIZATION_TAG = "block-id-normalization";
781
+ function buildPreviousIdIndex(editorState) {
782
+ return editorState.read(() => {
783
+ const map = /* @__PURE__ */ new Map();
784
+ for (const child of $getRoot().getChildren()) {
785
+ const id = $getState(child, blockIdState);
786
+ if (!id) continue;
787
+ const set = map.get(id) ?? /* @__PURE__ */ new Set();
788
+ set.add(child.getKey());
789
+ map.set(id, set);
790
+ }
791
+ return map;
792
+ });
793
+ }
794
+ function collectRootChildren(editorState) {
795
+ return editorState.read(() => $getRoot().getChildren().map((child) => $getState(child, blockIdState)));
796
+ }
797
+ function hasDuplicateOrMissingId(children) {
798
+ const seen = /* @__PURE__ */ new Set();
799
+ for (const id of children) {
800
+ if (!id || seen.has(id)) return true;
801
+ seen.add(id);
802
+ }
803
+ return false;
804
+ }
805
+ function generateBlockId(used) {
806
+ while (true) {
807
+ const id = nanoid(8);
808
+ if (!used.has(id)) return id;
809
+ }
810
+ }
811
+ function pickKeeperKey(nodes, previousKeys) {
812
+ if (!nodes.length) return null;
813
+ if (previousKeys?.size) {
814
+ for (const node of nodes) if (previousKeys.has(node.getKey())) return node.getKey();
815
+ }
816
+ return nodes[0]?.getKey() ?? null;
817
+ }
818
+ function normalizeRootBlockIds(editor, previousIdIndex) {
819
+ editor.update(() => {
820
+ $addUpdateTag("history-merge");
821
+ const children = $getRoot().getChildren();
822
+ const groupedById = /* @__PURE__ */ new Map();
823
+ for (const child of children) {
824
+ const id = $getState(child, blockIdState);
825
+ if (!id) continue;
826
+ const bucket = groupedById.get(id) ?? [];
827
+ bucket.push(child);
828
+ groupedById.set(id, bucket);
829
+ }
830
+ const keeperById = /* @__PURE__ */ new Map();
831
+ for (const [id, nodes] of groupedById) {
832
+ if (nodes.length <= 1) continue;
833
+ const keeperKey = pickKeeperKey(nodes, previousIdIndex.get(id));
834
+ if (keeperKey) keeperById.set(id, keeperKey);
835
+ }
836
+ const used = /* @__PURE__ */ new Set();
837
+ for (const child of children) {
838
+ let id = $getState(child, blockIdState);
839
+ const keeperKey = id ? keeperById.get(id) : null;
840
+ if (!id || used.has(id) || keeperKey !== void 0 && child.getKey() !== keeperKey) {
841
+ id = generateBlockId(used);
842
+ $setState(child, blockIdState, id);
843
+ }
844
+ used.add(id);
845
+ }
846
+ }, { tag: NORMALIZATION_TAG });
847
+ }
848
+ function BlockIdPlugin() {
849
+ const [editor] = useLexicalComposerContext();
850
+ useEffect(() => {
851
+ if (hasDuplicateOrMissingId(collectRootChildren(editor.getEditorState()))) normalizeRootBlockIds(editor, /* @__PURE__ */ new Map());
852
+ return editor.registerUpdateListener(({ tags, editorState, prevEditorState }) => {
853
+ if (tags.has(NORMALIZATION_TAG)) return;
854
+ if (!hasDuplicateOrMissingId(collectRootChildren(editorState))) return;
855
+ normalizeRootBlockIds(editor, buildPreviousIdIndex(prevEditorState));
856
+ });
857
+ }, [editor]);
858
+ return null;
859
+ }
860
+ //#endregion
861
+ //#region src/plugins/image-upload.css.ts
862
+ var draggingWrapperClass = "rich-image-upload-dragging";
863
+ var toastVariant = {
864
+ info: "_1x58dbf3",
865
+ success: "_1x58dbf4",
866
+ error: "_1x58dbf5"
867
+ };
868
+ var spinner = "_1x58dbf7";
869
+ var dialogPopup = "_1x58dbf8";
870
+ var dialogHeader = "_1x58dbf9";
871
+ var dialogTitle = "_1x58dbfa";
872
+ var dialogBody = "_1x58dbfb";
873
+ var tabWrap = "_1x58dbfc";
874
+ var uploadDropzone = "_1x58dbfd";
875
+ var uploadDropzoneState = {
876
+ idle: "_1x58dbfe",
877
+ active: "_1x58dbff",
878
+ busy: "_1x58dbfg"
879
+ };
880
+ var uploadDropIcon = "_1x58dbfh";
881
+ var uploadDropTitle = "_1x58dbfi";
882
+ var uploadDropDesc = "_1x58dbfj";
883
+ var hiddenInput = "_1x58dbfk";
884
+ var uploadBusyWrap = "_1x58dbfl";
885
+ var uploadProgress = "_1x58dbfm";
886
+ var urlInputRow = "_1x58dbfn";
887
+ var textInput = "_1x58dbfo";
888
+ var helperText = "_1x58dbfr";
889
+ var dialogFooter = "_1x58dbfs";
890
+ //#endregion
891
+ //#region src/plugins/ImageUploadPlugin.tsx
892
+ function isImageFile(file) {
893
+ return file.type.startsWith("image/");
894
+ }
895
+ function hasImageData(dataTransfer) {
896
+ if (!dataTransfer) return false;
897
+ if ([...dataTransfer.files].some(isImageFile)) return true;
898
+ return [...dataTransfer.items].some((item) => item.type.startsWith("image/"));
899
+ }
900
+ var UNSAFE_URL_RE = /^(?:javascript\s*:|vbscript\s*:|data\s*:(?!image\/))/i;
901
+ function isSafeImageUrl(url) {
902
+ return !UNSAFE_URL_RE.test(url);
903
+ }
904
+ function loadImageByUrl(src) {
905
+ return new Promise((resolve, reject) => {
906
+ const image = new Image();
907
+ image.onload = () => {
908
+ resolve({
909
+ width: image.naturalWidth || image.width,
910
+ height: image.naturalHeight || image.height
911
+ });
912
+ };
913
+ image.onerror = () => reject(/* @__PURE__ */ new Error("Failed to load image"));
914
+ image.src = src;
915
+ });
916
+ }
917
+ function readAsDataUrl(file) {
918
+ return new Promise((resolve, reject) => {
919
+ const reader = new FileReader();
920
+ reader.onload = () => resolve(String(reader.result));
921
+ reader.onerror = () => reject(reader.error ?? /* @__PURE__ */ new Error("File read failed"));
922
+ reader.readAsDataURL(file);
923
+ });
924
+ }
925
+ async function defaultImageUpload(file) {
926
+ return {
927
+ src: await readAsDataUrl(file),
928
+ altText: file.name
929
+ };
930
+ }
931
+ function ImageUploadPlugin({ onUpload }) {
932
+ const [editor] = useLexicalComposerContext();
933
+ const uploadRef = useRef(onUpload);
934
+ uploadRef.current = onUpload;
935
+ const fileInputRef = useRef(null);
936
+ const toastTimerRef = useRef(null);
937
+ const [dialogOpen, setDialogOpen] = useState(false);
938
+ const [tab, setTab] = useState("upload");
939
+ const [rootDragActive, setRootDragActive] = useState(false);
940
+ const [dialogDragActive, setDialogDragActive] = useState(false);
941
+ const [pendingUploads, setPendingUploads] = useState(0);
942
+ const [dialogUploading, setDialogUploading] = useState(false);
943
+ const [toast$1, setToast] = useState(null);
944
+ const [urlInput, setUrlInput] = useState("");
945
+ const [urlPreview$1, setUrlPreview] = useState(null);
946
+ const [urlMeta, setUrlMeta] = useState(null);
947
+ const [urlLoading, setUrlLoading] = useState(false);
948
+ const [urlError, setUrlError] = useState(null);
949
+ const tabItems = useMemo(() => [{
950
+ value: "upload",
951
+ label: "Upload"
952
+ }, {
953
+ value: "url",
954
+ label: "URL"
955
+ }], []);
956
+ const pushToast = useCallback((kind, message) => {
957
+ setToast({
958
+ kind,
959
+ message
960
+ });
961
+ if (toastTimerRef.current) window.clearTimeout(toastTimerRef.current);
962
+ toastTimerRef.current = window.setTimeout(setToast, 2200, null);
963
+ }, []);
964
+ const insertByUpload = useCallback(async (file, options) => {
965
+ if (!isImageFile(file)) return false;
966
+ const closeDialog = Boolean(options?.closeDialog);
967
+ setPendingUploads((value) => value + 1);
968
+ if (closeDialog) setDialogUploading(true);
969
+ try {
970
+ const [result, meta] = await Promise.all([uploadRef.current(file), computeImageMeta(file)]);
971
+ editor.update(() => {
972
+ $insertNodes([$createImageNode({
973
+ src: result.src,
974
+ altText: result.altText ?? file.name,
975
+ width: result.width ?? meta.width,
976
+ height: result.height ?? meta.height,
977
+ thumbhash: result.thumbhash ?? meta.thumbhash
978
+ })]);
979
+ });
980
+ if (closeDialog) {
981
+ setDialogOpen(false);
982
+ setUrlInput("");
983
+ setUrlPreview(null);
984
+ setUrlMeta(null);
985
+ setUrlError(null);
986
+ }
987
+ pushToast("success", "Image uploaded");
988
+ return true;
989
+ } catch (err) {
990
+ console.error("[ImageUploadPlugin]", err);
991
+ pushToast("error", "Image upload failed");
992
+ return false;
993
+ } finally {
994
+ setPendingUploads((value) => Math.max(value - 1, 0));
995
+ setDialogUploading(false);
996
+ }
997
+ }, [editor, pushToast]);
998
+ const handleFiles = useCallback((files) => {
999
+ const images = files.filter(isImageFile);
1000
+ if (images.length === 0) return false;
1001
+ for (const file of images) insertByUpload(file);
1002
+ return true;
1003
+ }, [insertByUpload]);
1004
+ useEffect(() => {
1005
+ const unregisterDragDrop = editor.registerCommand(DRAG_DROP_PASTE, (files) => handleFiles(files), COMMAND_PRIORITY_HIGH);
1006
+ const unregisterPaste = editor.registerCommand(PASTE_COMMAND, (event) => {
1007
+ const clipboardData = "clipboardData" in event ? event.clipboardData : null;
1008
+ if (!clipboardData) return false;
1009
+ const files = [...clipboardData.files];
1010
+ if (files.some(isImageFile)) return handleFiles(files);
1011
+ return false;
1012
+ }, COMMAND_PRIORITY_HIGH);
1013
+ const unregisterOpenDialog = editor.registerCommand(OPEN_IMAGE_UPLOAD_DIALOG_COMMAND, () => {
1014
+ setDialogOpen(true);
1015
+ return true;
1016
+ }, COMMAND_PRIORITY_EDITOR);
1017
+ const rootElement = editor.getRootElement();
1018
+ const wrapper = rootElement?.parentElement ?? null;
1019
+ if (!wrapper) return () => {
1020
+ unregisterDragDrop();
1021
+ unregisterPaste();
1022
+ unregisterOpenDialog();
1023
+ };
1024
+ let dragCounter = 0;
1025
+ const setWrapperDragging = (next) => {
1026
+ setRootDragActive(next);
1027
+ wrapper.classList.toggle(draggingWrapperClass, next);
1028
+ };
1029
+ const onDragEnter = (event) => {
1030
+ if (!hasImageData(event.dataTransfer)) return;
1031
+ dragCounter += 1;
1032
+ setWrapperDragging(true);
1033
+ };
1034
+ const onDragOver = (event) => {
1035
+ if (!hasImageData(event.dataTransfer)) return;
1036
+ event.preventDefault();
1037
+ };
1038
+ const onDragLeave = () => {
1039
+ dragCounter = Math.max(dragCounter - 1, 0);
1040
+ if (dragCounter === 0) setWrapperDragging(false);
1041
+ };
1042
+ const onDrop = () => {
1043
+ dragCounter = 0;
1044
+ setWrapperDragging(false);
1045
+ };
1046
+ rootElement?.addEventListener("dragenter", onDragEnter);
1047
+ rootElement?.addEventListener("dragover", onDragOver);
1048
+ rootElement?.addEventListener("dragleave", onDragLeave);
1049
+ rootElement?.addEventListener("drop", onDrop);
1050
+ return () => {
1051
+ if (toastTimerRef.current) window.clearTimeout(toastTimerRef.current);
1052
+ unregisterDragDrop();
1053
+ unregisterPaste();
1054
+ unregisterOpenDialog();
1055
+ setWrapperDragging(false);
1056
+ rootElement?.removeEventListener("dragenter", onDragEnter);
1057
+ rootElement?.removeEventListener("dragover", onDragOver);
1058
+ rootElement?.removeEventListener("dragleave", onDragLeave);
1059
+ rootElement?.removeEventListener("drop", onDrop);
1060
+ };
1061
+ }, [editor, handleFiles]);
1062
+ const resetUrlState = useCallback(() => {
1063
+ setUrlInput("");
1064
+ setUrlPreview(null);
1065
+ setUrlMeta(null);
1066
+ setUrlError(null);
1067
+ setUrlLoading(false);
1068
+ }, []);
1069
+ const handleDialogFile = useCallback(async (file) => {
1070
+ if (!file) return;
1071
+ await insertByUpload(file, { closeDialog: true });
1072
+ }, [insertByUpload]);
1073
+ const handleUrlPreview = useCallback(async () => {
1074
+ const nextUrl = urlInput.trim();
1075
+ if (!nextUrl) return;
1076
+ if (!isSafeImageUrl(nextUrl)) {
1077
+ setUrlError("Unsupported URL scheme");
1078
+ return;
1079
+ }
1080
+ setUrlLoading(true);
1081
+ setUrlError(null);
1082
+ try {
1083
+ setUrlMeta(await loadImageByUrl(nextUrl));
1084
+ setUrlPreview(nextUrl);
1085
+ } catch {
1086
+ setUrlPreview(null);
1087
+ setUrlMeta(null);
1088
+ setUrlError("Could not load this image URL");
1089
+ } finally {
1090
+ setUrlLoading(false);
1091
+ }
1092
+ }, [urlInput]);
1093
+ const handleInsertByUrl = useCallback(() => {
1094
+ if (!urlPreview$1 || !isSafeImageUrl(urlPreview$1)) return;
1095
+ editor.update(() => {
1096
+ $insertNodes([$createImageNode({
1097
+ src: urlPreview$1,
1098
+ altText: "",
1099
+ width: urlMeta?.width,
1100
+ height: urlMeta?.height
1101
+ })]);
1102
+ });
1103
+ pushToast("success", "Image inserted");
1104
+ setDialogOpen(false);
1105
+ resetUrlState();
1106
+ }, [
1107
+ editor,
1108
+ pushToast,
1109
+ resetUrlState,
1110
+ urlMeta,
1111
+ urlPreview$1
1112
+ ]);
1113
+ const helperMessage = pendingUploads > 0 ? `Uploading ${pendingUploads} image${pendingUploads > 1 ? "s" : ""}...` : rootDragActive ? "Drop image files to upload" : null;
1114
+ return /* @__PURE__ */ jsxs(Fragment, { children: [(helperMessage || toast$1) && /* @__PURE__ */ jsxs("div", {
1115
+ className: "_1x58dbf1",
1116
+ children: [helperMessage && /* @__PURE__ */ jsxs("div", {
1117
+ className: `_1x58dbf2 ${toastVariant.info}`,
1118
+ children: [/* @__PURE__ */ jsx("span", { className: "_1x58dbf7" }), helperMessage]
1119
+ }), toast$1 && /* @__PURE__ */ jsxs("div", {
1120
+ className: `_1x58dbf2 ${toastVariant[toast$1.kind]}`,
1121
+ children: [toast$1.kind === "success" ? /* @__PURE__ */ jsx(Check, { size: 12 }) : /* @__PURE__ */ jsx(Info, { size: 12 }), toast$1.message]
1122
+ })]
1123
+ }), /* @__PURE__ */ jsx(Dialog, {
1124
+ open: dialogOpen,
1125
+ onOpenChange: (nextOpen) => {
1126
+ if (!nextOpen && dialogUploading) return;
1127
+ setDialogOpen(nextOpen);
1128
+ if (!nextOpen) {
1129
+ resetUrlState();
1130
+ setDialogUploading(false);
1131
+ setDialogDragActive(false);
1132
+ }
1133
+ },
1134
+ children: /* @__PURE__ */ jsxs(DialogPopup, {
1135
+ className: dialogPopup,
1136
+ showCloseButton: !dialogUploading,
1137
+ children: [
1138
+ /* @__PURE__ */ jsx("div", {
1139
+ className: dialogHeader,
1140
+ children: /* @__PURE__ */ jsx(DialogTitle, {
1141
+ className: dialogTitle,
1142
+ children: "Insert image"
1143
+ })
1144
+ }),
1145
+ /* @__PURE__ */ jsxs("div", {
1146
+ className: dialogBody,
1147
+ children: [/* @__PURE__ */ jsx("div", {
1148
+ className: tabWrap,
1149
+ children: /* @__PURE__ */ jsx(SegmentedControl, {
1150
+ fullWidth: true,
1151
+ items: tabItems,
1152
+ value: tab,
1153
+ onChange: setTab
1154
+ })
1155
+ }), tab === "upload" ? /* @__PURE__ */ jsxs("div", {
1156
+ className: `${uploadDropzone} ${uploadDropzoneState[dialogUploading ? "busy" : dialogDragActive ? "active" : "idle"]}`,
1157
+ role: "button",
1158
+ tabIndex: 0,
1159
+ onDragLeave: () => setDialogDragActive(false),
1160
+ onClick: () => {
1161
+ if (!dialogUploading) fileInputRef.current?.click();
1162
+ },
1163
+ onDragEnter: (event) => {
1164
+ if (hasImageData(event.dataTransfer)) {
1165
+ event.preventDefault();
1166
+ setDialogDragActive(true);
1167
+ }
1168
+ },
1169
+ onDragOver: (event) => {
1170
+ if (hasImageData(event.dataTransfer)) event.preventDefault();
1171
+ },
1172
+ onDrop: (event) => {
1173
+ event.preventDefault();
1174
+ setDialogDragActive(false);
1175
+ handleDialogFile([...event.dataTransfer.files].find(isImageFile) ?? null);
1176
+ },
1177
+ onKeyDown: (event) => {
1178
+ if (event.key !== "Enter" && event.key !== " ") return;
1179
+ event.preventDefault();
1180
+ if (!dialogUploading) fileInputRef.current?.click();
1181
+ },
1182
+ children: [/* @__PURE__ */ jsx("input", {
1183
+ accept: "image/*",
1184
+ className: hiddenInput,
1185
+ ref: fileInputRef,
1186
+ type: "file",
1187
+ onChange: (event) => {
1188
+ handleDialogFile(event.currentTarget.files?.[0] ?? null);
1189
+ event.currentTarget.value = "";
1190
+ }
1191
+ }), dialogUploading ? /* @__PURE__ */ jsx("div", {
1192
+ className: uploadBusyWrap,
1193
+ children: /* @__PURE__ */ jsxs("div", {
1194
+ className: uploadProgress,
1195
+ children: [/* @__PURE__ */ jsx("span", { className: spinner }), "Uploading image..."]
1196
+ })
1197
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1198
+ /* @__PURE__ */ jsx("span", {
1199
+ className: uploadDropIcon,
1200
+ children: /* @__PURE__ */ jsx(Upload, { size: 18 })
1201
+ }),
1202
+ /* @__PURE__ */ jsx("span", {
1203
+ className: uploadDropTitle,
1204
+ children: "Click to upload or drag and drop"
1205
+ }),
1206
+ /* @__PURE__ */ jsx("span", {
1207
+ className: uploadDropDesc,
1208
+ children: "PNG, JPG, GIF, WebP"
1209
+ })
1210
+ ] })]
1211
+ }) : /* @__PURE__ */ jsxs(Fragment, { children: [
1212
+ /* @__PURE__ */ jsxs("div", {
1213
+ className: urlInputRow,
1214
+ children: [
1215
+ /* @__PURE__ */ jsx("input", {
1216
+ className: textInput,
1217
+ placeholder: "https://example.com/image.jpg",
1218
+ type: "url",
1219
+ value: urlInput,
1220
+ onChange: (event) => {
1221
+ setUrlInput(event.target.value);
1222
+ setUrlError(null);
1223
+ setUrlPreview(null);
1224
+ setUrlMeta(null);
1225
+ },
1226
+ onKeyDown: (event) => {
1227
+ if (event.key === "Enter") {
1228
+ event.preventDefault();
1229
+ if (urlPreview$1) handleInsertByUrl();
1230
+ else handleUrlPreview();
1231
+ }
1232
+ }
1233
+ }),
1234
+ /* @__PURE__ */ jsx(ActionButton, {
1235
+ disabled: urlLoading || !urlInput.trim(),
1236
+ size: "md",
1237
+ variant: "outline",
1238
+ onClick: () => void handleUrlPreview(),
1239
+ children: urlLoading ? "Loading" : "Preview"
1240
+ }),
1241
+ /* @__PURE__ */ jsx(ActionButton, {
1242
+ disabled: !urlPreview$1,
1243
+ size: "md",
1244
+ variant: "accent",
1245
+ onClick: handleInsertByUrl,
1246
+ children: "Insert"
1247
+ })
1248
+ ]
1249
+ }),
1250
+ urlError && /* @__PURE__ */ jsxs("span", {
1251
+ className: `_1x58dbfr ${toastVariant.error}`,
1252
+ children: [/* @__PURE__ */ jsx(Info, { size: 12 }), urlError]
1253
+ }),
1254
+ urlPreview$1 && /* @__PURE__ */ jsx("div", {
1255
+ className: "_1x58dbfp",
1256
+ children: /* @__PURE__ */ jsx("img", {
1257
+ alt: "Preview",
1258
+ className: "_1x58dbfq",
1259
+ src: urlPreview$1
1260
+ })
1261
+ })
1262
+ ] })]
1263
+ }),
1264
+ /* @__PURE__ */ jsxs("div", {
1265
+ className: dialogFooter,
1266
+ children: [/* @__PURE__ */ jsxs("span", {
1267
+ className: helperText,
1268
+ children: [/* @__PURE__ */ jsx(Link2, { size: 12 }), "You can also paste images or drag files directly into the editor."]
1269
+ }), /* @__PURE__ */ jsx(ActionBar, { children: /* @__PURE__ */ jsx(ActionButton, {
1270
+ disabled: dialogUploading,
1271
+ size: "md",
1272
+ variant: "outline",
1273
+ onClick: () => setDialogOpen(false),
1274
+ children: "Close"
1275
+ }) })]
1276
+ })
1277
+ ]
1278
+ })
1279
+ })] });
1280
+ }
1281
+ //#endregion
1282
+ //#region src/plugins/LinkFaviconPlugin.tsx
1283
+ function applyFavicon(dom, href) {
1284
+ if (dom.dataset.faviconHref === href) return;
1285
+ dom.dataset.faviconHref = href;
1286
+ const hostname = getHostname(href);
1287
+ if (!hostname) return;
1288
+ probeFavicon(hostname).then((faviconUrl) => {
1289
+ if (faviconUrl) {
1290
+ dom.style.setProperty("--rc-link-favicon", `url(${faviconUrl})`);
1291
+ dom.dataset.favicon = "loaded";
1292
+ }
1293
+ });
1294
+ }
1295
+ function LinkFaviconPlugin() {
1296
+ const [editor] = useLexicalComposerContext();
1297
+ useEffect(() => {
1298
+ const handleMutations = (mutations) => {
1299
+ for (const [nodeKey, mutation] of mutations) {
1300
+ if (mutation === "destroyed") continue;
1301
+ const dom = editor.getElementByKey(nodeKey);
1302
+ if (!dom) continue;
1303
+ const href = dom.getAttribute("href");
1304
+ if (href) applyFavicon(dom, href);
1305
+ }
1306
+ };
1307
+ const unregisterLink = editor.registerMutationListener(LinkNode, handleMutations);
1308
+ const unregisterAutoLink = editor.registerMutationListener(AutoLinkNode, handleMutations);
1309
+ return () => {
1310
+ unregisterLink();
1311
+ unregisterAutoLink();
1312
+ };
1313
+ }, [editor]);
1314
+ return null;
1315
+ }
1316
+ //#endregion
1317
+ //#region src/plugins/AutoFocusPlugin.tsx
1318
+ function AutoFocusPlugin() {
1319
+ const [editor] = useLexicalComposerContext();
1320
+ useEffect(() => {
1321
+ const root = editor.getRootElement();
1322
+ if (root) root.focus({ preventScroll: true });
1323
+ else editor.focus();
1324
+ }, [editor]);
1325
+ return null;
1326
+ }
1327
+ //#endregion
1328
+ //#region src/plugins/EditorRefPlugin.tsx
1329
+ function EditorRefPlugin({ onEditorReady }) {
1330
+ const [editor] = useLexicalComposerContext();
1331
+ const callbackRef = useRef(onEditorReady);
1332
+ callbackRef.current = onEditorReady;
1333
+ useEffect(() => {
1334
+ callbackRef.current?.(editor);
1335
+ return () => callbackRef.current?.(null);
1336
+ }, [editor]);
1337
+ return null;
1338
+ }
1339
+ //#endregion
1340
+ //#region src/plugins/FootnotePlugin.tsx
1341
+ function FootnotePlugin({ children }) {
1342
+ const [editor] = useLexicalComposerContext();
1343
+ const [definitions, setDefinitions] = useState({});
1344
+ const [displayNumberMap, setDisplayNumberMap] = useState({});
1345
+ const pendingUpdateRef = useRef(false);
1346
+ useEffect(() => {
1347
+ return editor.registerUpdateListener(({ editorState }) => {
1348
+ editorState.read(() => {
1349
+ const footnoteNodes = $nodesOfType(FootnoteNode);
1350
+ const seen = /* @__PURE__ */ new Set();
1351
+ const numberMap = {};
1352
+ let counter = 1;
1353
+ for (const node of footnoteNodes) {
1354
+ const id = node.getIdentifier();
1355
+ if (!seen.has(id)) {
1356
+ seen.add(id);
1357
+ numberMap[id] = counter++;
1358
+ }
1359
+ }
1360
+ setDisplayNumberMap(numberMap);
1361
+ const sectionNodes = $nodesOfType(FootnoteSectionNode);
1362
+ if (sectionNodes.length > 0) setDefinitions(sectionNodes[0].getDefinitions());
1363
+ else setDefinitions({});
1364
+ if (!editor.isEditable() || pendingUpdateRef.current) return;
1365
+ if (footnoteNodes.length === 0 && sectionNodes.length > 0) {
1366
+ pendingUpdateRef.current = true;
1367
+ queueMicrotask(() => {
1368
+ editor.update(() => {
1369
+ const sections = $nodesOfType(FootnoteSectionNode);
1370
+ for (const s of sections) s.remove();
1371
+ });
1372
+ pendingUpdateRef.current = false;
1373
+ });
1374
+ return;
1375
+ }
1376
+ if (footnoteNodes.length > 0 && sectionNodes.length === 0) {
1377
+ const seenSnapshot = [...seen];
1378
+ pendingUpdateRef.current = true;
1379
+ queueMicrotask(() => {
1380
+ editor.update(() => {
1381
+ const root = $getRoot();
1382
+ const defs = {};
1383
+ for (const id of seenSnapshot) defs[id] = "";
1384
+ const section = $parseSerializedNode({
1385
+ type: "footnote-section",
1386
+ definitions: defs,
1387
+ version: 1
1388
+ });
1389
+ root.append(section);
1390
+ });
1391
+ pendingUpdateRef.current = false;
1392
+ });
1393
+ } else if (sectionNodes.length > 0) {
1394
+ const existingDefs = sectionNodes[0].getDefinitions();
1395
+ const missingIds = [...seen].filter((id) => !(id in existingDefs));
1396
+ const orphanIds = Object.keys(existingDefs).filter((id) => !seen.has(id));
1397
+ if (missingIds.length > 0 || orphanIds.length > 0) {
1398
+ pendingUpdateRef.current = true;
1399
+ queueMicrotask(() => {
1400
+ editor.update(() => {
1401
+ const freshSections = $nodesOfType(FootnoteSectionNode);
1402
+ if (freshSections.length > 0) {
1403
+ for (const id of missingIds) freshSections[0].setDefinition(id, "");
1404
+ for (const id of orphanIds) freshSections[0].removeDefinition(id);
1405
+ }
1406
+ });
1407
+ pendingUpdateRef.current = false;
1408
+ });
1409
+ }
1410
+ }
1411
+ });
1412
+ });
1413
+ }, [editor]);
1414
+ return /* @__PURE__ */ jsx(FootnoteDefinitionsProvider, {
1415
+ definitions,
1416
+ displayNumberMap,
1417
+ children
1418
+ });
1419
+ }
1420
+ //#endregion
1421
+ //#region src/plugins/OnChangePlugin.tsx
1422
+ function OnChangePlugin({ onChange, debounceMs }) {
1423
+ const [editor] = useLexicalComposerContext();
1424
+ const timerRef = useRef(void 0);
1425
+ const onChangeRef = useRef(onChange);
1426
+ onChangeRef.current = onChange;
1427
+ useEffect(() => {
1428
+ const unregister = editor.registerUpdateListener(({ editorState }) => {
1429
+ const fn = onChangeRef.current;
1430
+ if (!fn) return;
1431
+ if (debounceMs && debounceMs > 0) {
1432
+ clearTimeout(timerRef.current);
1433
+ timerRef.current = setTimeout(() => {
1434
+ fn(editorState.toJSON());
1435
+ }, debounceMs);
1436
+ } else fn(editorState.toJSON());
1437
+ });
1438
+ return () => {
1439
+ clearTimeout(timerRef.current);
1440
+ unregister();
1441
+ };
1442
+ }, [editor, debounceMs]);
1443
+ return null;
1444
+ }
1445
+ //#endregion
1446
+ //#region src/plugins/SubmitShortcutPlugin.tsx
1447
+ function SubmitShortcutPlugin({ onSubmit }) {
1448
+ const [editor] = useLexicalComposerContext();
1449
+ useEffect(() => {
1450
+ if (!onSubmit) return;
1451
+ return editor.registerCommand(KEY_ENTER_COMMAND, (event) => {
1452
+ if (event && (event.metaKey || event.ctrlKey)) {
1453
+ event.preventDefault();
1454
+ onSubmit();
1455
+ return true;
1456
+ }
1457
+ return false;
1458
+ }, COMMAND_PRIORITY_HIGH);
1459
+ }, [editor, onSubmit]);
1460
+ return null;
1461
+ }
1462
+ //#endregion
1463
+ export { HorizontalRulePlugin as _, AutoFocusPlugin as a, defaultImageUpload as c, ImageUploadProvider as d, useImageUpload as f, ALL_TRANSFORMERS as g, MarkdownPastePlugin as h, EditorRefPlugin as i, BlockIdPlugin as l, MarkdownShortcutsPlugin as m, OnChangePlugin as n, LinkFaviconPlugin as o, CorePlugins as p, FootnotePlugin as r, ImageUploadPlugin as s, SubmitShortcutPlugin as t, blockIdState as u, BlockExitPlugin as v, AutoLinkPlugin as y };