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