@reactloom/editor 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,791 @@
1
+ "use client";
2
+ import { VisuallyHidden } from "./_internal/primitives/visually-hidden.js";
3
+ import { cx } from "./_internal/utils/cx.js";
4
+ import { dataAttr } from "./_internal/utils/data-attr.js";
5
+ import { defaultFormats, extensionsFor, isEmptyDocument, isSafeImageUrl, isSafeUrl, normalizeUrl, renderHtml } from "./document.js";
6
+ import { defaultMessages } from "./messages.js";
7
+ import editor_module_default from "./editor.module.js";
8
+ import { forwardRef, useEffect, useId, useMemo, useRef, useState } from "react";
9
+ import { EditorContent, useEditor, useEditorState } from "@tiptap/react";
10
+ import { Placeholder } from "@tiptap/extensions";
11
+ import { jsx, jsxs } from "react/jsx-runtime";
12
+ import { BoldIcon, CodeIcon, HeadingIcon, ImageIcon, ItalicIcon, LayoutGridIcon, LinkIcon, ListIcon, ListOrderedIcon, MinusIcon, PlusIcon, QuoteIcon, RedoIcon, StrikethroughIcon, TerminalIcon, TrashIcon, UndoIcon } from "@reactloom/icons";
13
+ import { Button, Checkbox, FormDescription, FormError, FormLabel, Input, PopoverContent, PopoverRoot, PopoverTrigger, Stack } from "@reactloom/ui";
14
+ // src/rich-text-editor.tsx
15
+ var EMPTY = {
16
+ type: "doc",
17
+ content: [{ type: "paragraph" }]
18
+ };
19
+ var MOD = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform) ? "Meta" : "Control";
20
+ /**
21
+ * A labelled rich-text field (ADR-0011): Tiptap/ProseMirror editing with a roving-focus toolbar,
22
+ * a link dialog that only accepts safe URLs, and a JSON value. The schema follows `formats`, so
23
+ * pasted formatting that a field does not allow is dropped.
24
+ */
25
+ var RichTextEditor = /*#__PURE__*/ forwardRef(function RichTextEditor(props, ref) {
26
+ const { label, hideLabel, description, error, invalid, required, disabled = false, readOnly = false, placeholder, name, minHeight = 120, maxHeight, toolbar = true, autoFocus, className } = props;
27
+ const formats = props.formats ?? defaultFormats;
28
+ const messages = {
29
+ ...defaultMessages,
30
+ ...props.messages
31
+ };
32
+ const uid = useId();
33
+ const id = props.id ?? `${uid}-editor`;
34
+ const labelId = `${id}-label`;
35
+ const descriptionId = description ? `${id}-description` : void 0;
36
+ const errorId = error ? `${id}-error` : void 0;
37
+ const hintId = `${id}-hint`;
38
+ const isInvalid = Boolean(invalid || error);
39
+ const editable = !disabled && !readOnly;
40
+ const [inner, setInner] = useState(props.defaultValue ?? EMPTY);
41
+ const current = props.value !== void 0 ? props.value ?? EMPTY : inner;
42
+ const lastEmitted = useRef(JSON.stringify(current));
43
+ const onValueChange = useRef(props.onValueChange);
44
+ useEffect(() => {
45
+ onValueChange.current = props.onValueChange;
46
+ });
47
+ const controlled = props.value !== void 0;
48
+ const optionsKey = JSON.stringify([
49
+ formats,
50
+ props.headingLevels,
51
+ props.allowRelativeLinks,
52
+ placeholder
53
+ ]);
54
+ const messagesKey = JSON.stringify(props.messages ?? null);
55
+ const extensions = useMemo(() => [...extensionsFor({
56
+ formats,
57
+ headingLevels: props.headingLevels,
58
+ allowRelativeLinks: props.allowRelativeLinks
59
+ }), ...placeholder ? [Placeholder.configure({ placeholder })] : []], [optionsKey]);
60
+ const ariaAttributes = useMemo(() => ({
61
+ id,
62
+ role: "textbox",
63
+ "aria-multiline": "true",
64
+ "aria-labelledby": labelId,
65
+ "aria-describedby": [
66
+ descriptionId,
67
+ errorId,
68
+ editable && toolbar ? hintId : void 0
69
+ ].filter(Boolean).join(" ") || "",
70
+ "aria-invalid": isInvalid ? "true" : "false",
71
+ ...required ? { "aria-required": "true" } : {},
72
+ ...readOnly ? { "aria-readonly": "true" } : {},
73
+ ...disabled ? { "aria-disabled": "true" } : {},
74
+ ...placeholder ? { "aria-placeholder": placeholder } : {},
75
+ class: editor_module_default.content ?? "",
76
+ spellcheck: "true"
77
+ }), [
78
+ id,
79
+ labelId,
80
+ descriptionId,
81
+ errorId,
82
+ hintId,
83
+ isInvalid,
84
+ required,
85
+ readOnly,
86
+ disabled,
87
+ placeholder,
88
+ editable,
89
+ toolbar
90
+ ]);
91
+ const toolbarRef = useRef(null);
92
+ const [linkOpen, setLinkOpen] = useState(false);
93
+ const [imageOpen, setImageOpen] = useState(false);
94
+ const editor = useEditor({
95
+ extensions,
96
+ content: current,
97
+ editable,
98
+ autofocus: autoFocus ? "end" : false,
99
+ immediatelyRender: false,
100
+ editorProps: {
101
+ attributes: ariaAttributes,
102
+ handleKeyDown: (_view, event) => {
103
+ if (event.altKey && event.key === "F10") {
104
+ event.preventDefault();
105
+ focusToolbar(toolbarRef.current);
106
+ return true;
107
+ }
108
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k" && formats.includes("link")) {
109
+ event.preventDefault();
110
+ setLinkOpen(true);
111
+ return true;
112
+ }
113
+ return false;
114
+ }
115
+ },
116
+ onUpdate: ({ editor: ed }) => {
117
+ const json = ed.getJSON();
118
+ lastEmitted.current = JSON.stringify(json);
119
+ if (!controlled) setInner(json);
120
+ onValueChange.current?.(json);
121
+ },
122
+ onFocus: () => props.onFocus?.(),
123
+ onBlur: () => props.onBlur?.()
124
+ }, [extensions]);
125
+ useEffect(() => {
126
+ if (!editor || !controlled) return;
127
+ const next = JSON.stringify(current);
128
+ if (next !== lastEmitted.current) {
129
+ lastEmitted.current = next;
130
+ editor.commands.setContent(current, { emitUpdate: false });
131
+ }
132
+ }, [
133
+ editor,
134
+ controlled,
135
+ current
136
+ ]);
137
+ useEffect(() => {
138
+ editor?.setEditable(editable, false);
139
+ }, [editor, editable]);
140
+ useEffect(() => {
141
+ editor?.setOptions({ editorProps: {
142
+ ...editor.options.editorProps,
143
+ attributes: ariaAttributes
144
+ } });
145
+ }, [editor, ariaAttributes]);
146
+ const tools = useMemo(() => {
147
+ const has = (f) => formats.includes(f);
148
+ const list = [];
149
+ if (has("bold")) list.push({
150
+ id: "bold",
151
+ label: messages.bold,
152
+ icon: BoldIcon,
153
+ keys: `${MOD}+B`,
154
+ toggle: true,
155
+ group: 0
156
+ });
157
+ if (has("italic")) list.push({
158
+ id: "italic",
159
+ label: messages.italic,
160
+ icon: ItalicIcon,
161
+ keys: `${MOD}+I`,
162
+ toggle: true,
163
+ group: 0
164
+ });
165
+ if (has("strike")) list.push({
166
+ id: "strike",
167
+ label: messages.strike,
168
+ icon: StrikethroughIcon,
169
+ keys: `${MOD}+Shift+S`,
170
+ toggle: true,
171
+ group: 0
172
+ });
173
+ if (has("code")) list.push({
174
+ id: "code",
175
+ label: messages.code,
176
+ icon: CodeIcon,
177
+ keys: `${MOD}+E`,
178
+ toggle: true,
179
+ group: 0
180
+ });
181
+ if (has("heading")) for (const level of props.headingLevels ?? [2, 3]) list.push({
182
+ id: `heading-${level}`,
183
+ label: messages.heading(level),
184
+ icon: HeadingIcon,
185
+ keys: `${MOD}+Alt+${level}`,
186
+ toggle: true,
187
+ group: 1
188
+ });
189
+ if (has("bulletList")) list.push({
190
+ id: "bulletList",
191
+ label: messages.bulletList,
192
+ icon: ListIcon,
193
+ keys: `${MOD}+Shift+8`,
194
+ toggle: true,
195
+ group: 2
196
+ });
197
+ if (has("orderedList")) list.push({
198
+ id: "orderedList",
199
+ label: messages.orderedList,
200
+ icon: ListOrderedIcon,
201
+ keys: `${MOD}+Shift+7`,
202
+ toggle: true,
203
+ group: 2
204
+ });
205
+ if (has("blockquote")) list.push({
206
+ id: "blockquote",
207
+ label: messages.blockquote,
208
+ icon: QuoteIcon,
209
+ keys: `${MOD}+Shift+B`,
210
+ toggle: true,
211
+ group: 2
212
+ });
213
+ if (has("codeBlock")) list.push({
214
+ id: "codeBlock",
215
+ label: messages.codeBlock,
216
+ icon: TerminalIcon,
217
+ keys: `${MOD}+Alt+C`,
218
+ toggle: true,
219
+ group: 2
220
+ });
221
+ if (has("link")) list.push({
222
+ id: "link",
223
+ label: messages.link,
224
+ icon: LinkIcon,
225
+ keys: `${MOD}+K`,
226
+ toggle: true,
227
+ group: 3
228
+ });
229
+ if (has("image")) list.push({
230
+ id: "image",
231
+ label: messages.image,
232
+ icon: ImageIcon,
233
+ toggle: false,
234
+ group: 3
235
+ });
236
+ if (has("table")) list.push({
237
+ id: "table",
238
+ label: messages.table,
239
+ icon: LayoutGridIcon,
240
+ toggle: false,
241
+ group: 3
242
+ });
243
+ list.push({
244
+ id: "undo",
245
+ label: messages.undo,
246
+ icon: UndoIcon,
247
+ keys: `${MOD}+Z`,
248
+ toggle: false,
249
+ group: 4
250
+ });
251
+ list.push({
252
+ id: "redo",
253
+ label: messages.redo,
254
+ icon: RedoIcon,
255
+ keys: `${MOD}+Shift+Z`,
256
+ toggle: false,
257
+ group: 4
258
+ });
259
+ return list;
260
+ }, [optionsKey, messagesKey]);
261
+ const tableTools = useMemo(() => [
262
+ {
263
+ id: "addRow",
264
+ label: messages.addRow,
265
+ icon: PlusIcon,
266
+ toggle: false,
267
+ group: 5,
268
+ text: "Row"
269
+ },
270
+ {
271
+ id: "addColumn",
272
+ label: messages.addColumn,
273
+ icon: PlusIcon,
274
+ toggle: false,
275
+ group: 5,
276
+ text: "Col"
277
+ },
278
+ {
279
+ id: "deleteRow",
280
+ label: messages.deleteRow,
281
+ icon: MinusIcon,
282
+ toggle: false,
283
+ group: 5,
284
+ text: "Row"
285
+ },
286
+ {
287
+ id: "deleteColumn",
288
+ label: messages.deleteColumn,
289
+ icon: MinusIcon,
290
+ toggle: false,
291
+ group: 5,
292
+ text: "Col"
293
+ },
294
+ {
295
+ id: "deleteTable",
296
+ label: messages.deleteTable,
297
+ icon: TrashIcon,
298
+ toggle: false,
299
+ group: 5
300
+ }
301
+ ], [messagesKey]);
302
+ const state = useEditorState({
303
+ editor,
304
+ selector: ({ editor: ed }) => {
305
+ if (!ed) return null;
306
+ const active = {};
307
+ for (const t of tools) if (t.id.startsWith("heading-")) active[t.id] = ed.isActive("heading", { level: Number(t.id.slice(8)) });
308
+ else if (t.toggle) active[t.id] = ed.isActive(t.id);
309
+ return {
310
+ active,
311
+ canUndo: ed.can().undo(),
312
+ canRedo: ed.can().redo(),
313
+ href: String(ed.getAttributes("link").href ?? ""),
314
+ inTable: formats.includes("table") && ed.isActive("table")
315
+ };
316
+ }
317
+ });
318
+ const run = (tool) => {
319
+ if (!editor) return;
320
+ const chain = editor.chain();
321
+ switch (tool.id) {
322
+ case "bold":
323
+ chain.toggleBold().run();
324
+ break;
325
+ case "italic":
326
+ chain.toggleItalic().run();
327
+ break;
328
+ case "strike":
329
+ chain.toggleStrike().run();
330
+ break;
331
+ case "code":
332
+ chain.toggleCode().run();
333
+ break;
334
+ case "bulletList":
335
+ chain.toggleBulletList().run();
336
+ break;
337
+ case "orderedList":
338
+ chain.toggleOrderedList().run();
339
+ break;
340
+ case "blockquote":
341
+ chain.toggleBlockquote().run();
342
+ break;
343
+ case "codeBlock":
344
+ chain.toggleCodeBlock().run();
345
+ break;
346
+ case "table":
347
+ chain.insertTable({
348
+ rows: 3,
349
+ cols: 3,
350
+ withHeaderRow: true
351
+ }).run();
352
+ break;
353
+ case "addRow":
354
+ chain.addRowAfter().run();
355
+ break;
356
+ case "addColumn":
357
+ chain.addColumnAfter().run();
358
+ break;
359
+ case "deleteRow":
360
+ chain.deleteRow().run();
361
+ break;
362
+ case "deleteColumn":
363
+ chain.deleteColumn().run();
364
+ break;
365
+ case "deleteTable":
366
+ chain.deleteTable().run();
367
+ break;
368
+ case "undo":
369
+ chain.undo().run();
370
+ break;
371
+ case "redo":
372
+ chain.redo().run();
373
+ break;
374
+ default: if (tool.id.startsWith("heading-")) chain.toggleHeading({ level: Number(tool.id.slice(8)) }).run();
375
+ }
376
+ };
377
+ const visibleTools = state?.inTable ? [...tools, ...tableTools] : tools;
378
+ const [focusIndex, setFocusIndex] = useState(0);
379
+ const onToolbarKeyDown = (event) => {
380
+ const buttons = Array.from(event.currentTarget.querySelectorAll("button[data-tool]"));
381
+ const index = buttons.indexOf(event.target);
382
+ if (index === -1) return;
383
+ const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
384
+ let next;
385
+ if (event.key === (rtl ? "ArrowLeft" : "ArrowRight")) next = (index + 1) % buttons.length;
386
+ else if (event.key === (rtl ? "ArrowRight" : "ArrowLeft")) next = (index - 1 + buttons.length) % buttons.length;
387
+ else if (event.key === "Home") next = 0;
388
+ else if (event.key === "End") next = buttons.length - 1;
389
+ else if (event.key === "Escape") {
390
+ event.preventDefault();
391
+ editor?.commands.focus();
392
+ return;
393
+ } else return;
394
+ event.preventDefault();
395
+ setFocusIndex(next);
396
+ buttons[next]?.focus();
397
+ };
398
+ const staticHtml = useMemo(() => {
399
+ if (editor) return "";
400
+ try {
401
+ return renderHtml(current, {
402
+ formats,
403
+ headingLevels: props.headingLevels,
404
+ allowRelativeLinks: props.allowRelativeLinks
405
+ });
406
+ } catch {
407
+ return "";
408
+ }
409
+ }, [editor]);
410
+ const size = (v) => typeof v === "number" ? `${v}px` : v;
411
+ const showToolbar = toolbar && !readOnly;
412
+ const empty = isEmptyDocument(current);
413
+ return /* @__PURE__ */ jsxs("div", {
414
+ ref,
415
+ className: cx(editor_module_default.root, className),
416
+ "data-disabled": dataAttr(disabled),
417
+ "data-readonly": dataAttr(readOnly),
418
+ "data-invalid": dataAttr(isInvalid),
419
+ "data-empty": dataAttr(empty),
420
+ style: {
421
+ "--_min-h": size(minHeight),
422
+ "--_max-h": size(maxHeight)
423
+ },
424
+ children: [
425
+ hideLabel ? /* @__PURE__ */ jsx(VisuallyHidden, {
426
+ id: labelId,
427
+ children: label
428
+ }) : /* @__PURE__ */ jsx(FormLabel, {
429
+ id: labelId,
430
+ required,
431
+ disabled,
432
+ onClick: () => editor?.commands.focus(),
433
+ children: label
434
+ }),
435
+ description && /* @__PURE__ */ jsx(FormDescription, {
436
+ id: descriptionId,
437
+ children: description
438
+ }),
439
+ /* @__PURE__ */ jsxs("div", {
440
+ className: editor_module_default.frame,
441
+ children: [
442
+ showToolbar && /* @__PURE__ */ jsx("div", {
443
+ ref: toolbarRef,
444
+ role: "toolbar",
445
+ "aria-label": messages.toolbar,
446
+ "aria-controls": id,
447
+ "aria-disabled": disabled || void 0,
448
+ className: editor_module_default.toolbar,
449
+ onKeyDown: onToolbarKeyDown,
450
+ children: visibleTools.map((tool, index) => {
451
+ const Icon = tool.icon;
452
+ const pressed = state?.active[tool.id] ?? false;
453
+ const unavailable = disabled || !editor || tool.id === "undo" && !state?.canUndo || tool.id === "redo" && !state?.canRedo;
454
+ const separator = index > 0 && visibleTools[index - 1]?.group !== tool.group;
455
+ const button = /* @__PURE__ */ jsxs("button", {
456
+ type: "button",
457
+ "data-tool": tool.id,
458
+ className: editor_module_default.tool,
459
+ "aria-label": tool.label,
460
+ title: tool.label,
461
+ "aria-pressed": tool.toggle ? pressed : void 0,
462
+ "aria-keyshortcuts": tool.keys,
463
+ "aria-disabled": unavailable || void 0,
464
+ tabIndex: index === Math.min(focusIndex, visibleTools.length - 1) ? 0 : -1,
465
+ onMouseDown: (e) => e.preventDefault(),
466
+ onFocus: () => setFocusIndex(index),
467
+ onClick: () => {
468
+ if (!unavailable && tool.id !== "link" && tool.id !== "image") run(tool);
469
+ },
470
+ children: [
471
+ /* @__PURE__ */ jsx(Icon, {}),
472
+ tool.id.startsWith("heading-") && /* @__PURE__ */ jsx("span", {
473
+ className: editor_module_default.level,
474
+ children: tool.id.slice(8)
475
+ }),
476
+ tool.text && /* @__PURE__ */ jsx("span", {
477
+ className: editor_module_default.level,
478
+ children: tool.text
479
+ })
480
+ ]
481
+ });
482
+ return /* @__PURE__ */ jsx("span", {
483
+ className: editor_module_default.toolSlot,
484
+ "data-separator": dataAttr(separator),
485
+ children: tool.id === "link" && editor ? /* @__PURE__ */ jsx(LinkDialog, {
486
+ editor,
487
+ open: linkOpen,
488
+ onOpenChange: (next) => setLinkOpen(next && !disabled),
489
+ href: state?.href ?? "",
490
+ messages,
491
+ allowRelative: props.allowRelativeLinks,
492
+ children: button
493
+ }) : tool.id === "image" && editor ? /* @__PURE__ */ jsx(ImageDialog, {
494
+ editor,
495
+ open: imageOpen,
496
+ onOpenChange: (next) => setImageOpen(next && !disabled),
497
+ messages,
498
+ allowRelative: props.allowRelativeLinks,
499
+ children: button
500
+ }) : button
501
+ }, tool.id);
502
+ })
503
+ }),
504
+ editor ? /* @__PURE__ */ jsx(EditorContent, {
505
+ editor,
506
+ className: editor_module_default.editorHost
507
+ }) : /* @__PURE__ */ jsx("div", {
508
+ className: editor_module_default.editorHost,
509
+ children: /* @__PURE__ */ jsx("div", {
510
+ className: editor_module_default.content,
511
+ role: "textbox",
512
+ "aria-multiline": "true",
513
+ "aria-labelledby": labelId,
514
+ "aria-readonly": "true",
515
+ "data-static": "",
516
+ dangerouslySetInnerHTML: { __html: staticHtml }
517
+ })
518
+ }),
519
+ editable && toolbar && /* @__PURE__ */ jsx(VisuallyHidden, {
520
+ id: hintId,
521
+ children: messages.keyboardHint
522
+ })
523
+ ]
524
+ }),
525
+ error && /* @__PURE__ */ jsx(FormError, {
526
+ id: errorId,
527
+ children: error
528
+ }),
529
+ name && /* @__PURE__ */ jsx("input", {
530
+ type: "hidden",
531
+ name,
532
+ value: JSON.stringify(current)
533
+ })
534
+ ]
535
+ });
536
+ });
537
+ function focusToolbar(toolbar) {
538
+ toolbar?.querySelector("button[data-tool][tabindex=\"0\"]")?.focus();
539
+ }
540
+ function LinkDialog({ editor, open, onOpenChange, href, messages, allowRelative, children }) {
541
+ const inputRef = useRef(null);
542
+ const titleId = useId();
543
+ const close = () => {
544
+ onOpenChange(false);
545
+ editor.commands.focus();
546
+ };
547
+ return /* @__PURE__ */ jsxs(PopoverRoot, {
548
+ open,
549
+ onOpenChange: (next) => next ? onOpenChange(true) : close(),
550
+ placement: "bottom-start",
551
+ children: [/* @__PURE__ */ jsx(PopoverTrigger, {
552
+ asChild: true,
553
+ children
554
+ }), /* @__PURE__ */ jsx(PopoverContent, {
555
+ size: "sm",
556
+ initialFocusRef: inputRef,
557
+ "aria-labelledby": titleId,
558
+ className: editor_module_default.linkDialog,
559
+ children: open && /* @__PURE__ */ jsx(LinkForm, {
560
+ editor,
561
+ href,
562
+ messages,
563
+ allowRelative,
564
+ inputRef,
565
+ titleId,
566
+ onDone: () => onOpenChange(false),
567
+ onCancel: close
568
+ })
569
+ })]
570
+ });
571
+ }
572
+ /** Mounted each time the dialog opens, so it starts from the current link. */
573
+ function LinkForm({ editor, href, messages, allowRelative, inputRef, titleId, onDone, onCancel }) {
574
+ const [draft, setDraft] = useState(href);
575
+ const [error, setError] = useState();
576
+ const apply = () => {
577
+ const url = normalizeUrl(draft);
578
+ if (!isSafeUrl(url, allowRelative)) {
579
+ setError(messages.linkInvalid);
580
+ inputRef.current?.focus();
581
+ return;
582
+ }
583
+ const { empty } = editor.state.selection;
584
+ if (empty && !editor.isActive("link")) editor.chain().focus().insertContent({
585
+ type: "text",
586
+ text: draft.trim(),
587
+ marks: [{
588
+ type: "link",
589
+ attrs: { href: url }
590
+ }]
591
+ }).run();
592
+ else editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
593
+ onDone();
594
+ };
595
+ const remove = () => {
596
+ editor.chain().focus().extendMarkRange("link").unsetLink().run();
597
+ onDone();
598
+ };
599
+ return /* @__PURE__ */ jsx("form", {
600
+ onSubmit: (e) => {
601
+ e.preventDefault();
602
+ apply();
603
+ },
604
+ children: /* @__PURE__ */ jsxs(Stack, {
605
+ gap: "3",
606
+ children: [
607
+ /* @__PURE__ */ jsx("span", {
608
+ id: titleId,
609
+ className: editor_module_default.linkTitle,
610
+ children: messages.linkDialogTitle
611
+ }),
612
+ /* @__PURE__ */ jsx(Input, {
613
+ ref: inputRef,
614
+ label: messages.linkAddress,
615
+ description: messages.linkHint,
616
+ error,
617
+ value: draft,
618
+ onChange: (e) => {
619
+ setDraft(e.target.value);
620
+ setError(void 0);
621
+ },
622
+ inputMode: "url",
623
+ autoComplete: "off",
624
+ size: "sm"
625
+ }),
626
+ /* @__PURE__ */ jsxs(Stack, {
627
+ direction: "row",
628
+ gap: "2",
629
+ justify: "end",
630
+ wrap: true,
631
+ children: [
632
+ href && /* @__PURE__ */ jsx(Button, {
633
+ type: "button",
634
+ variant: "ghost",
635
+ size: "sm",
636
+ onClick: remove,
637
+ children: messages.removeLink
638
+ }),
639
+ /* @__PURE__ */ jsx(Button, {
640
+ type: "button",
641
+ variant: "secondary",
642
+ size: "sm",
643
+ onClick: onCancel,
644
+ children: messages.cancel
645
+ }),
646
+ /* @__PURE__ */ jsx(Button, {
647
+ type: "submit",
648
+ size: "sm",
649
+ children: messages.applyLink
650
+ })
651
+ ]
652
+ })
653
+ ]
654
+ })
655
+ });
656
+ }
657
+ function ImageDialog({ editor, open, onOpenChange, messages, allowRelative, children }) {
658
+ const inputRef = useRef(null);
659
+ const titleId = useId();
660
+ const close = () => {
661
+ onOpenChange(false);
662
+ editor.commands.focus();
663
+ };
664
+ return /* @__PURE__ */ jsxs(PopoverRoot, {
665
+ open,
666
+ onOpenChange: (next) => next ? onOpenChange(true) : close(),
667
+ placement: "bottom-start",
668
+ children: [/* @__PURE__ */ jsx(PopoverTrigger, {
669
+ asChild: true,
670
+ children
671
+ }), /* @__PURE__ */ jsx(PopoverContent, {
672
+ size: "md",
673
+ initialFocusRef: inputRef,
674
+ "aria-labelledby": titleId,
675
+ className: editor_module_default.linkDialog,
676
+ children: open && /* @__PURE__ */ jsx(ImageForm, {
677
+ editor,
678
+ messages,
679
+ allowRelative,
680
+ inputRef,
681
+ titleId,
682
+ onDone: () => onOpenChange(false),
683
+ onCancel: close
684
+ })
685
+ })]
686
+ });
687
+ }
688
+ /** Image address and alternative text; an image needs a description or an explicit "decorative". */
689
+ function ImageForm({ editor, messages, allowRelative, inputRef, titleId, onDone, onCancel }) {
690
+ const altRef = useRef(null);
691
+ const [src, setSrc] = useState("");
692
+ const [alt, setAlt] = useState("");
693
+ const [decorative, setDecorative] = useState(false);
694
+ const [errors, setErrors] = useState({});
695
+ const insert = () => {
696
+ const url = normalizeUrl(src);
697
+ const next = {
698
+ src: isSafeImageUrl(url, allowRelative) ? void 0 : messages.imageInvalid,
699
+ alt: decorative || alt.trim() ? void 0 : messages.imageAltRequired
700
+ };
701
+ setErrors(next);
702
+ if (next.src) return inputRef.current?.focus();
703
+ if (next.alt) return altRef.current?.focus();
704
+ editor.chain().focus().setImage({
705
+ src: url,
706
+ alt: decorative ? "" : alt.trim()
707
+ }).run();
708
+ onDone();
709
+ };
710
+ return /* @__PURE__ */ jsx("form", {
711
+ onSubmit: (e) => {
712
+ e.preventDefault();
713
+ insert();
714
+ },
715
+ children: /* @__PURE__ */ jsxs(Stack, {
716
+ gap: "3",
717
+ children: [
718
+ /* @__PURE__ */ jsx("span", {
719
+ id: titleId,
720
+ className: editor_module_default.linkTitle,
721
+ children: messages.imageDialogTitle
722
+ }),
723
+ /* @__PURE__ */ jsx(Input, {
724
+ ref: inputRef,
725
+ label: messages.imageAddress,
726
+ error: errors.src,
727
+ value: src,
728
+ onChange: (e) => {
729
+ setSrc(e.target.value);
730
+ setErrors((x) => ({
731
+ ...x,
732
+ src: void 0
733
+ }));
734
+ },
735
+ inputMode: "url",
736
+ autoComplete: "off",
737
+ size: "sm"
738
+ }),
739
+ /* @__PURE__ */ jsx(Input, {
740
+ ref: altRef,
741
+ label: messages.imageAlt,
742
+ description: messages.imageAltHint,
743
+ error: errors.alt,
744
+ value: alt,
745
+ disabled: decorative,
746
+ onChange: (e) => {
747
+ setAlt(e.target.value);
748
+ setErrors((x) => ({
749
+ ...x,
750
+ alt: void 0
751
+ }));
752
+ },
753
+ autoComplete: "off",
754
+ size: "sm"
755
+ }),
756
+ /* @__PURE__ */ jsx(Checkbox, {
757
+ label: messages.imageDecorative,
758
+ checked: decorative,
759
+ onCheckedChange: (checked) => {
760
+ setDecorative(checked);
761
+ setErrors((x) => ({
762
+ ...x,
763
+ alt: void 0
764
+ }));
765
+ },
766
+ size: "sm"
767
+ }),
768
+ /* @__PURE__ */ jsxs(Stack, {
769
+ direction: "row",
770
+ gap: "2",
771
+ justify: "end",
772
+ wrap: true,
773
+ children: [/* @__PURE__ */ jsx(Button, {
774
+ type: "button",
775
+ variant: "secondary",
776
+ size: "sm",
777
+ onClick: onCancel,
778
+ children: messages.cancel
779
+ }), /* @__PURE__ */ jsx(Button, {
780
+ type: "submit",
781
+ size: "sm",
782
+ children: messages.insertImage
783
+ })]
784
+ })
785
+ ]
786
+ })
787
+ });
788
+ }
789
+ export { RichTextEditor };
790
+
791
+ //# sourceMappingURL=rich-text-editor.js.map