@oakjs/addon-lexical 0.0.0-stage → 4.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +125 -2
  2. package/dist/addons-DQNB8pRc.js +1365 -0
  3. package/dist/addons-DQNB8pRc.js.map +1 -0
  4. package/dist/addons-Pp5mwM60.cjs +1406 -0
  5. package/dist/addons-Pp5mwM60.cjs.map +1 -0
  6. package/dist/addons.cjs +5 -0
  7. package/dist/addons.js +2 -0
  8. package/dist/index.cjs +10 -0
  9. package/dist/index.js +2 -0
  10. package/dist/oak-addon-lexical.min.css +2 -0
  11. package/dist/oak-addon-lexical.min.css.map +1 -0
  12. package/dist/types/Field/ColorDropdown.d.ts +9 -0
  13. package/dist/types/Field/ColorDropdown.d.ts.map +1 -0
  14. package/dist/types/Field/Cursors.d.ts +24 -0
  15. package/dist/types/Field/Cursors.d.ts.map +1 -0
  16. package/dist/types/Field/Icon.d.ts +14 -0
  17. package/dist/types/Field/Icon.d.ts.map +1 -0
  18. package/dist/types/Field/LinkDropdown.d.ts +9 -0
  19. package/dist/types/Field/LinkDropdown.d.ts.map +1 -0
  20. package/dist/types/Field/MenuItem.d.ts +10 -0
  21. package/dist/types/Field/MenuItem.d.ts.map +1 -0
  22. package/dist/types/Field/SyncPlugin.d.ts +17 -0
  23. package/dist/types/Field/SyncPlugin.d.ts.map +1 -0
  24. package/dist/types/Field/TableSizePicker.d.ts +11 -0
  25. package/dist/types/Field/TableSizePicker.d.ts.map +1 -0
  26. package/dist/types/Field/Toolbar.d.ts +12 -0
  27. package/dist/types/Field/Toolbar.d.ts.map +1 -0
  28. package/dist/types/Field/ToolbarButton.d.ts +11 -0
  29. package/dist/types/Field/ToolbarButton.d.ts.map +1 -0
  30. package/dist/types/Field/ToolbarDropdown.d.ts +21 -0
  31. package/dist/types/Field/ToolbarDropdown.d.ts.map +1 -0
  32. package/dist/types/Field/context.d.ts +16 -0
  33. package/dist/types/Field/context.d.ts.map +1 -0
  34. package/dist/types/Field/html.d.ts +17 -0
  35. package/dist/types/Field/html.d.ts.map +1 -0
  36. package/dist/types/Field/index.d.ts +21 -0
  37. package/dist/types/Field/index.d.ts.map +1 -0
  38. package/dist/types/Field/measure.d.ts +12 -0
  39. package/dist/types/Field/measure.d.ts.map +1 -0
  40. package/dist/types/Field/positions.d.ts +24 -0
  41. package/dist/types/Field/positions.d.ts.map +1 -0
  42. package/dist/types/Field/testUtils.d.ts +3 -0
  43. package/dist/types/Field/testUtils.d.ts.map +1 -0
  44. package/dist/types/Field/theme.d.ts +7 -0
  45. package/dist/types/Field/theme.d.ts.map +1 -0
  46. package/dist/types/Field/types.d.ts +19 -0
  47. package/dist/types/Field/types.d.ts.map +1 -0
  48. package/dist/types/Field/useToolbarState.d.ts +22 -0
  49. package/dist/types/Field/useToolbarState.d.ts.map +1 -0
  50. package/dist/types/addons.d.ts +12 -0
  51. package/dist/types/addons.d.ts.map +1 -0
  52. package/dist/types/index.d.ts +7 -0
  53. package/dist/types/index.d.ts.map +1 -0
  54. package/dist/types/types.d.ts +20 -0
  55. package/dist/types/types.d.ts.map +1 -0
  56. package/package.json +84 -4
@@ -0,0 +1,1365 @@
1
+ 'use client';
2
+ import { Fragment, createContext, use, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { LexicalComposer } from "@lexical/react/LexicalComposer";
4
+ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";
5
+ import { ContentEditable } from "@lexical/react/LexicalContentEditable";
6
+ import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
7
+ import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
8
+ import { ListPlugin } from "@lexical/react/LexicalListPlugin";
9
+ import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
10
+ import { TablePlugin } from "@lexical/react/LexicalTablePlugin";
11
+ import { HorizontalRulePlugin } from "@lexical/react/LexicalHorizontalRulePlugin";
12
+ import { HorizontalRuleNode, INSERT_HORIZONTAL_RULE_COMMAND } from "@lexical/react/LexicalHorizontalRuleNode";
13
+ import { $createHeadingNode, $createQuoteNode, $isHeadingNode, $isQuoteNode, HeadingNode, QuoteNode } from "@lexical/rich-text";
14
+ import { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND, ListItemNode, ListNode, REMOVE_LIST_COMMAND } from "@lexical/list";
15
+ import { $createLinkNode, $isLinkNode, $toggleLink, AutoLinkNode, LinkNode } from "@lexical/link";
16
+ import { $deleteTableColumnAtSelection, $deleteTableRowAtSelection, $insertTableColumnAtSelection, $insertTableRowAtSelection, $isTableCellNode, $isTableNode, $isTableSelection, INSERT_TABLE_COMMAND, TableCellNode, TableNode, TableRowNode } from "@lexical/table";
17
+ import { Button, ColorField, Dropdown, DropdownMenu, DropdownToggle, TextField, Toggle, classNames, omit } from "@junipero/react";
18
+ import { $createParagraphNode, $createRangeSelection, $createTextNode, $getNodeByKey, $getRoot, $getSelection, $insertNodes, $isDecoratorNode, $isElementNode, $isRangeSelection, $isRootNode, $isTextNode, $setSelection, BLUR_COMMAND, CAN_REDO_COMMAND, CAN_UNDO_COMMAND, CLEAR_HISTORY_COMMAND, COMMAND_PRIORITY_CRITICAL, COMMAND_PRIORITY_LOW, FOCUS_COMMAND, FORMAT_ELEMENT_COMMAND, FORMAT_TEXT_COMMAND, HISTORIC_TAG, HISTORY_MERGE_TAG, INDENT_CONTENT_COMMAND, OUTDENT_CONTENT_COMMAND, REDO_COMMAND, TextNode, UNDO_COMMAND } from "lexical";
19
+ import { $generateHtmlFromNodes, $generateNodesFromDOM } from "@lexical/html";
20
+ import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
21
+ import { $getSelectionStyleValueForProperty, $patchStyleText, $setBlocksType, createDOMRange, createRectsFromDOMRange } from "@lexical/selection";
22
+ import { $findMatchingParent, $getNearestNodeOfType, mergeRegister } from "@lexical/utils";
23
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
24
+ // lib/Field/context.ts
25
+ const LexicalFieldContext = createContext({ t: (_, def) => def });
26
+ /**
27
+ * Field-level context, so that the field doesn't depend on a specific
28
+ * builder's context (`@oakjs/react` or `@oakjs/ash`)
29
+ */
30
+ const useLexicalField = () => use(LexicalFieldContext);
31
+ // lib/Field/theme.ts
32
+ /**
33
+ * Classes used to display the content inside the editor. They're removed from
34
+ * the html given to `onChange`, which only relies on tags & inline styles.
35
+ */
36
+ const theme = {
37
+ paragraph: "oak-lexical-paragraph",
38
+ quote: "oak-lexical-quote",
39
+ heading: {
40
+ h1: "oak-lexical-h1",
41
+ h2: "oak-lexical-h2",
42
+ h3: "oak-lexical-h3",
43
+ h4: "oak-lexical-h4",
44
+ h5: "oak-lexical-h5",
45
+ h6: "oak-lexical-h6"
46
+ },
47
+ list: {
48
+ ul: "oak-lexical-ul",
49
+ ol: "oak-lexical-ol",
50
+ listitem: "oak-lexical-li",
51
+ nested: { listitem: "oak-lexical-nested-li" }
52
+ },
53
+ link: "oak-lexical-link",
54
+ hr: "oak-lexical-hr",
55
+ indent: "oak-lexical-indent",
56
+ table: "oak-lexical-table",
57
+ tableRow: "oak-lexical-tr",
58
+ tableCell: "oak-lexical-td",
59
+ tableCellHeader: "oak-lexical-th",
60
+ tableSelection: "oak-lexical-table-selection",
61
+ tableCellSelected: "oak-lexical-td-selected",
62
+ text: {
63
+ bold: "oak-lexical-bold",
64
+ italic: "oak-lexical-italic",
65
+ underline: "oak-lexical-underline",
66
+ strikethrough: "oak-lexical-strikethrough",
67
+ underlineStrikethrough: "oak-lexical-underline-strikethrough"
68
+ }
69
+ };
70
+ // lib/Field/html.ts
71
+ const KEPT_STYLES = [
72
+ "color",
73
+ "background-color",
74
+ "font-size",
75
+ "font-family"
76
+ ];
77
+ /**
78
+ * Lexical only keeps formats (bold, italic...) from styled spans: colors &
79
+ * font sizes are kept as well
80
+ */
81
+ const htmlConfig = { import: { span: (span) => {
82
+ const original = TextNode.importDOM()?.span?.(span);
83
+ if (!original) return null;
84
+ return {
85
+ priority: Math.min(4, (original.priority ?? 0) + 1),
86
+ conversion: (element) => {
87
+ const output = original.conversion(element);
88
+ const style = KEPT_STYLES.map((p) => [p, element.style.getPropertyValue(p)]).filter(([, value]) => value).map(([p, value]) => `${p}: ${value};`).join(" ");
89
+ if (!output || !style) return output;
90
+ return {
91
+ ...output,
92
+ forChild: (child, parent) => {
93
+ const result = output.forChild ? output.forChild(child, parent) : child;
94
+ if ($isTextNode(result)) result.setStyle([style, result.getStyle()].filter(Boolean).join(" "));
95
+ return result;
96
+ }
97
+ };
98
+ }
99
+ };
100
+ } } };
101
+ /**
102
+ * Replaces the editor's content with an html string. Inline contents (e.g.
103
+ * a plain text) are wrapped in paragraphs.
104
+ */
105
+ const $importHtml = (editor, html) => {
106
+ const dom = new DOMParser().parseFromString(html || "", "text/html");
107
+ const nodes = $generateNodesFromDOM(editor, dom);
108
+ const root = $getRoot();
109
+ root.clear();
110
+ let paragraph = null;
111
+ nodes.forEach((node) => {
112
+ if (($isElementNode(node) || $isDecoratorNode(node)) && !node.isInline()) {
113
+ paragraph = null;
114
+ root.append(node);
115
+ return;
116
+ }
117
+ if (!paragraph) {
118
+ paragraph = $createParagraphNode();
119
+ root.append(paragraph);
120
+ }
121
+ paragraph.append(node);
122
+ });
123
+ if (!root.getChildrenSize()) root.append($createParagraphNode());
124
+ };
125
+ /**
126
+ * Returns the editor's content as html, without the editor's own classes (an
127
+ * empty editor returns an empty string)
128
+ */
129
+ const $exportHtml = (editor) => {
130
+ const root = $getRoot();
131
+ const first = root.getFirstChild();
132
+ if (root.getChildrenSize() <= 1 && (!first || $isElementNode(first) && first.isEmpty())) return "";
133
+ const container = document.createElement("div");
134
+ container.innerHTML = $generateHtmlFromNodes(editor, null);
135
+ container.querySelectorAll("*").forEach((element) => {
136
+ element.removeAttribute("class");
137
+ Array.from(element.attributes).filter((a) => a.name.startsWith("data-lexical-")).forEach((a) => element.removeAttribute(a.name));
138
+ if (element.style.whiteSpace === "pre-wrap") element.style.removeProperty("white-space");
139
+ if (element.hasAttribute("style") && !element.getAttribute("style")) element.removeAttribute("style");
140
+ });
141
+ container.querySelectorAll("li[value]").forEach((li) => {
142
+ li.removeAttribute("value");
143
+ });
144
+ container.querySelectorAll("span, b, i").forEach((element) => {
145
+ const child = element.firstElementChild;
146
+ if (element.childNodes.length === 1 && child && !element.attributes.length && (element.tagName === "B" && child.tagName === "STRONG" || element.tagName === "I" && child.tagName === "EM")) element.replaceWith(child);
147
+ else if (element.tagName === "SPAN" && !element.attributes.length) element.replaceWith(...Array.from(element.childNodes));
148
+ });
149
+ return container.innerHTML;
150
+ };
151
+ // lib/Field/useToolbarState.ts
152
+ const INITIAL_STATE = {
153
+ bold: false,
154
+ italic: false,
155
+ underline: false,
156
+ strikethrough: false,
157
+ link: null,
158
+ color: "",
159
+ fontSize: "",
160
+ block: "paragraph",
161
+ align: "",
162
+ inTable: false,
163
+ canUndo: false,
164
+ canRedo: false
165
+ };
166
+ const $readState = () => {
167
+ const selection = $getSelection();
168
+ if ($isTableSelection(selection)) return { inTable: true };
169
+ if (!$isRangeSelection(selection)) return {};
170
+ const anchor = selection.anchor.getNode();
171
+ const link = $findMatchingParent(anchor, $isLinkNode);
172
+ const list = $getNearestNodeOfType(anchor, ListNode);
173
+ const blockNode = $isElementNode(anchor) && !anchor.isInline() ? anchor : $findMatchingParent(anchor, (n) => $isElementNode(n) && !n.isInline());
174
+ const quote = $findMatchingParent(anchor, $isQuoteNode);
175
+ const heading = $findMatchingParent(anchor, $isHeadingNode);
176
+ return {
177
+ bold: selection.hasFormat("bold"),
178
+ italic: selection.hasFormat("italic"),
179
+ underline: selection.hasFormat("underline"),
180
+ strikethrough: selection.hasFormat("strikethrough"),
181
+ link: link ? {
182
+ url: link.getURL(),
183
+ target: link.getTarget()
184
+ } : null,
185
+ color: $getSelectionStyleValueForProperty(selection, "color", ""),
186
+ fontSize: $getSelectionStyleValueForProperty(selection, "font-size", ""),
187
+ block: list ? list.getListType() : quote ? "quote" : heading ? heading.getTag() : "paragraph",
188
+ align: $isElementNode(blockNode) ? blockNode.getFormatType() : "",
189
+ inTable: !!$findMatchingParent(anchor, $isTableCellNode)
190
+ };
191
+ };
192
+ /** State of the toolbar buttons, updated with the editor */
193
+ const useToolbarState = (editor) => {
194
+ const [state, setState] = useState(INITIAL_STATE);
195
+ useEffect(() => mergeRegister(editor.registerUpdateListener(() => {
196
+ const next = editor.read($readState);
197
+ setState((s) => ({
198
+ ...s,
199
+ ...next
200
+ }));
201
+ }), editor.registerCommand(CAN_UNDO_COMMAND, (canUndo) => {
202
+ setState((s) => ({
203
+ ...s,
204
+ canUndo
205
+ }));
206
+ return false;
207
+ }, COMMAND_PRIORITY_CRITICAL), editor.registerCommand(CAN_REDO_COMMAND, (canRedo) => {
208
+ setState((s) => ({
209
+ ...s,
210
+ canRedo
211
+ }));
212
+ return false;
213
+ }, COMMAND_PRIORITY_CRITICAL)), [editor]);
214
+ return state;
215
+ };
216
+ // lib/Field/ToolbarButton.tsx
217
+ /**
218
+ * Doesn't take the focus from the editor when clicked, so that the selection
219
+ * is kept
220
+ */
221
+ const ToolbarButton = ({ active, label, className, onMouseDown, ...rest }) => /* @__PURE__ */ jsx("button", {
222
+ type: "button",
223
+ title: label,
224
+ "aria-label": label,
225
+ "aria-pressed": active,
226
+ className: classNames("oak-lexical-button", { active }, className),
227
+ onMouseDown: (e) => {
228
+ e.preventDefault();
229
+ onMouseDown?.(e);
230
+ },
231
+ ...rest
232
+ });
233
+ ToolbarButton.displayName = "ToolbarButton";
234
+ // lib/Field/Icon.tsx
235
+ const ICONS = {
236
+ undo: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("path", { d: "M9 14 4 9l5-5" }), /* @__PURE__ */ jsx("path", { d: "M4 9h10.5a5.5 5.5 0 0 1 0 11H11" })] }),
237
+ redo: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("path", { d: "m15 14 5-5-5-5" }), /* @__PURE__ */ jsx("path", { d: "M20 9H9.5a5.5 5.5 0 0 0 0 11H13" })] }),
238
+ bold: /* @__PURE__ */ jsx("path", { d: "M7 12h8a4 4 0 0 1 0 8H7V4h7a4 4 0 0 1 0 8" }),
239
+ italic: /* @__PURE__ */ jsxs(Fragment$1, { children: [
240
+ /* @__PURE__ */ jsx("path", { d: "M19 4h-9" }),
241
+ /* @__PURE__ */ jsx("path", { d: "M14 20H5" }),
242
+ /* @__PURE__ */ jsx("path", { d: "M15 4 9 20" })
243
+ ] }),
244
+ underline: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("path", { d: "M6 4v6a6 6 0 0 0 12 0V4" }), /* @__PURE__ */ jsx("path", { d: "M4 20h16" })] }),
245
+ strikethrough: /* @__PURE__ */ jsxs(Fragment$1, { children: [
246
+ /* @__PURE__ */ jsx("path", { d: "M16 4H9a3 3 0 0 0-2.83 4" }),
247
+ /* @__PURE__ */ jsx("path", { d: "M14 12a4 4 0 0 1 0 8H6" }),
248
+ /* @__PURE__ */ jsx("path", { d: "M4 12h16" })
249
+ ] }),
250
+ link: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("path", { d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ jsx("path", { d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" })] }),
251
+ fontColor: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("path", { d: "m6 15 6-12 6 12" }), /* @__PURE__ */ jsx("path", { d: "M8.5 10h7" })] }),
252
+ fontSize: /* @__PURE__ */ jsxs(Fragment$1, { children: [
253
+ /* @__PURE__ */ jsx("path", { d: "M3 7V5h11v2" }),
254
+ /* @__PURE__ */ jsx("path", { d: "M8.5 5v14" }),
255
+ /* @__PURE__ */ jsx("path", { d: "M6.5 19h4" }),
256
+ /* @__PURE__ */ jsx("path", { d: "M14 13v-1h7v1" }),
257
+ /* @__PURE__ */ jsx("path", { d: "M17.5 12v7" }),
258
+ /* @__PURE__ */ jsx("path", { d: "M16 19h3" })
259
+ ] }),
260
+ bulletedList: /* @__PURE__ */ jsxs(Fragment$1, { children: [
261
+ /* @__PURE__ */ jsx("path", { d: "M9 6h11" }),
262
+ /* @__PURE__ */ jsx("path", { d: "M9 12h11" }),
263
+ /* @__PURE__ */ jsx("path", { d: "M9 18h11" }),
264
+ /* @__PURE__ */ jsx("circle", {
265
+ cx: "4.5",
266
+ cy: "6",
267
+ r: ".5"
268
+ }),
269
+ /* @__PURE__ */ jsx("circle", {
270
+ cx: "4.5",
271
+ cy: "12",
272
+ r: ".5"
273
+ }),
274
+ /* @__PURE__ */ jsx("circle", {
275
+ cx: "4.5",
276
+ cy: "18",
277
+ r: ".5"
278
+ })
279
+ ] }),
280
+ numberedList: /* @__PURE__ */ jsxs(Fragment$1, { children: [
281
+ /* @__PURE__ */ jsx("path", { d: "M10 6h10" }),
282
+ /* @__PURE__ */ jsx("path", { d: "M10 12h10" }),
283
+ /* @__PURE__ */ jsx("path", { d: "M10 18h10" }),
284
+ /* @__PURE__ */ jsx("path", { d: "M4 4h1v4" }),
285
+ /* @__PURE__ */ jsx("path", { d: "M4 8h2" }),
286
+ /* @__PURE__ */ jsx("path", { d: "M6 20H4c0-1 2-2 2-3s-1-1.5-2-1" })
287
+ ] }),
288
+ removeFormat: /* @__PURE__ */ jsxs(Fragment$1, { children: [
289
+ /* @__PURE__ */ jsx("path", { d: "M4 7V4h16v3" }),
290
+ /* @__PURE__ */ jsx("path", { d: "M5 20h6" }),
291
+ /* @__PURE__ */ jsx("path", { d: "M13 4 8 20" }),
292
+ /* @__PURE__ */ jsx("path", { d: "m15 15 5 5" }),
293
+ /* @__PURE__ */ jsx("path", { d: "m20 15-5 5" })
294
+ ] }),
295
+ outdent: /* @__PURE__ */ jsxs(Fragment$1, { children: [
296
+ /* @__PURE__ */ jsx("path", { d: "m7 8-4 4 4 4" }),
297
+ /* @__PURE__ */ jsx("path", { d: "M21 6H11" }),
298
+ /* @__PURE__ */ jsx("path", { d: "M21 12H11" }),
299
+ /* @__PURE__ */ jsx("path", { d: "M21 18H11" })
300
+ ] }),
301
+ indent: /* @__PURE__ */ jsxs(Fragment$1, { children: [
302
+ /* @__PURE__ */ jsx("path", { d: "m3 8 4 4-4 4" }),
303
+ /* @__PURE__ */ jsx("path", { d: "M21 6H11" }),
304
+ /* @__PURE__ */ jsx("path", { d: "M21 12H11" }),
305
+ /* @__PURE__ */ jsx("path", { d: "M21 18H11" })
306
+ ] }),
307
+ alignLeft: /* @__PURE__ */ jsxs(Fragment$1, { children: [
308
+ /* @__PURE__ */ jsx("path", { d: "M21 6H3" }),
309
+ /* @__PURE__ */ jsx("path", { d: "M15 12H3" }),
310
+ /* @__PURE__ */ jsx("path", { d: "M17 18H3" })
311
+ ] }),
312
+ alignCenter: /* @__PURE__ */ jsxs(Fragment$1, { children: [
313
+ /* @__PURE__ */ jsx("path", { d: "M21 6H3" }),
314
+ /* @__PURE__ */ jsx("path", { d: "M17 12H7" }),
315
+ /* @__PURE__ */ jsx("path", { d: "M19 18H5" })
316
+ ] }),
317
+ alignRight: /* @__PURE__ */ jsxs(Fragment$1, { children: [
318
+ /* @__PURE__ */ jsx("path", { d: "M21 6H3" }),
319
+ /* @__PURE__ */ jsx("path", { d: "M21 12H9" }),
320
+ /* @__PURE__ */ jsx("path", { d: "M21 18H7" })
321
+ ] }),
322
+ alignJustify: /* @__PURE__ */ jsxs(Fragment$1, { children: [
323
+ /* @__PURE__ */ jsx("path", { d: "M21 6H3" }),
324
+ /* @__PURE__ */ jsx("path", { d: "M21 12H3" }),
325
+ /* @__PURE__ */ jsx("path", { d: "M21 18H3" })
326
+ ] }),
327
+ horizontalLine: /* @__PURE__ */ jsxs(Fragment$1, { children: [
328
+ /* @__PURE__ */ jsx("path", { d: "M3 12h18" }),
329
+ /* @__PURE__ */ jsx("path", {
330
+ d: "M8 6h8",
331
+ opacity: ".4"
332
+ }),
333
+ /* @__PURE__ */ jsx("path", {
334
+ d: "M8 18h8",
335
+ opacity: ".4"
336
+ })
337
+ ] }),
338
+ blockQuote: /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("path", { d: "M5 17c3-1 4-3 4-6V7H4v5h5" }), /* @__PURE__ */ jsx("path", { d: "M15 17c3-1 4-3 4-6V7h-5v5h5" })] }),
339
+ insertTable: /* @__PURE__ */ jsxs(Fragment$1, { children: [
340
+ /* @__PURE__ */ jsx("rect", {
341
+ x: "3",
342
+ y: "3",
343
+ width: "18",
344
+ height: "18",
345
+ rx: "2"
346
+ }),
347
+ /* @__PURE__ */ jsx("path", { d: "M3 9h18" }),
348
+ /* @__PURE__ */ jsx("path", { d: "M3 15h18" }),
349
+ /* @__PURE__ */ jsx("path", { d: "M12 3v18" })
350
+ ] }),
351
+ heading: /* @__PURE__ */ jsxs(Fragment$1, { children: [
352
+ /* @__PURE__ */ jsx("path", { d: "M6 4v16" }),
353
+ /* @__PURE__ */ jsx("path", { d: "M18 4v16" }),
354
+ /* @__PURE__ */ jsx("path", { d: "M6 12h12" })
355
+ ] }),
356
+ chevron: /* @__PURE__ */ jsx("path", { d: "m6 9 6 6 6-6" })
357
+ };
358
+ const Icon = ({ name, color, size = 18, ...rest }) => /* @__PURE__ */ jsxs("svg", {
359
+ viewBox: "0 0 24 24",
360
+ width: size,
361
+ height: size,
362
+ fill: "none",
363
+ stroke: "currentColor",
364
+ strokeWidth: 2,
365
+ strokeLinecap: "round",
366
+ strokeLinejoin: "round",
367
+ "aria-hidden": true,
368
+ className: "oak-lexical-icon",
369
+ ...rest,
370
+ children: [ICONS[name], name === "fontColor" && /* @__PURE__ */ jsx("rect", {
371
+ x: "4",
372
+ y: "18",
373
+ width: "16",
374
+ height: "3",
375
+ rx: "1",
376
+ stroke: "none",
377
+ fill: color || "currentColor"
378
+ })]
379
+ });
380
+ Icon.displayName = "Icon";
381
+ // lib/Field/ToolbarDropdown.tsx
382
+ const ToolbarDropdown = ({ ref, label, icon, active, disabled, className, menuClassName, children, onToggle }) => {
383
+ const { container } = useLexicalField();
384
+ const dropdownRef = useRef(null);
385
+ useImperativeHandle(ref, () => ({ close: () => dropdownRef.current?.close() }));
386
+ return /* @__PURE__ */ jsxs(Dropdown, {
387
+ ref: dropdownRef,
388
+ container,
389
+ disabled,
390
+ placement: "bottom-start",
391
+ className: classNames("oak-lexical-dropdown", className),
392
+ onToggle: ({ opened }) => onToggle?.(opened),
393
+ children: [/* @__PURE__ */ jsx(DropdownToggle, { children: /* @__PURE__ */ jsxs(ToolbarButton, {
394
+ label,
395
+ active,
396
+ disabled,
397
+ className: "oak-lexical-dropdown-toggle",
398
+ children: [icon, /* @__PURE__ */ jsx(Icon, {
399
+ name: "chevron",
400
+ size: 12
401
+ })]
402
+ }) }), /* @__PURE__ */ jsx(DropdownMenu, {
403
+ className: classNames("oak-lexical-menu", menuClassName),
404
+ children
405
+ })]
406
+ });
407
+ };
408
+ ToolbarDropdown.displayName = "ToolbarDropdown";
409
+ // lib/Field/MenuItem.tsx
410
+ /** Dropdown entry that doesn't take the focus from the editor */
411
+ const MenuItem = ({ active, className, ...rest }) => /* @__PURE__ */ jsx("li", {
412
+ className: "oak-lexical-menu-item",
413
+ children: /* @__PURE__ */ jsx("button", {
414
+ type: "button",
415
+ className: classNames({ active }, className),
416
+ onMouseDown: (e) => e.preventDefault(),
417
+ ...rest
418
+ })
419
+ });
420
+ MenuItem.displayName = "MenuItem";
421
+ // lib/Field/TableSizePicker.tsx
422
+ /**
423
+ * Grid of cells to choose the size of a new table (like CKEditor's): cells
424
+ * are highlighted from the top left corner to the hovered one
425
+ */
426
+ const TableSizePicker = ({ max = 6, onSelect }) => {
427
+ const { t } = useLexicalField();
428
+ const gridRef = useRef(null);
429
+ const [size, setSize] = useState({
430
+ rows: 1,
431
+ columns: 1
432
+ });
433
+ const cells = Array.from({ length: max }, (_, i) => i + 1);
434
+ const focusCell = (rows, columns) => {
435
+ gridRef.current?.querySelector(`[data-rows="${rows}"][data-columns="${columns}"]`)?.focus();
436
+ };
437
+ const onKeyDown = (e) => {
438
+ const move = {
439
+ ArrowUp: [-1, 0],
440
+ ArrowDown: [1, 0],
441
+ ArrowLeft: [0, -1],
442
+ ArrowRight: [0, 1]
443
+ }[e.key];
444
+ if (!move) return;
445
+ e.preventDefault();
446
+ focusCell(Math.min(max, Math.max(1, size.rows + move[0])), Math.min(max, Math.max(1, size.columns + move[1])));
447
+ };
448
+ const label = (rows, columns) => t("addons.lexical.fields.editor.table.size", "{rows} × {columns}").replace("{rows}", String(rows)).replace("{columns}", String(columns));
449
+ return /* @__PURE__ */ jsxs("li", {
450
+ className: "oak-lexical-table-picker",
451
+ children: [/* @__PURE__ */ jsx("div", {
452
+ ref: gridRef,
453
+ role: "grid",
454
+ className: "oak-lexical-table-grid",
455
+ style: { gridTemplateColumns: `repeat(${max}, auto)` },
456
+ onKeyDown,
457
+ children: cells.map((rows) => cells.map((columns) => /* @__PURE__ */ jsx("button", {
458
+ type: "button",
459
+ "data-rows": rows,
460
+ "data-columns": columns,
461
+ "aria-label": label(rows, columns),
462
+ tabIndex: rows === size.rows && columns === size.columns ? 0 : -1,
463
+ className: classNames("oak-lexical-table-cell", { active: rows <= size.rows && columns <= size.columns }),
464
+ onMouseEnter: () => setSize({
465
+ rows,
466
+ columns
467
+ }),
468
+ onFocus: () => setSize({
469
+ rows,
470
+ columns
471
+ }),
472
+ onMouseDown: (e) => e.preventDefault(),
473
+ onClick: () => onSelect(rows, columns)
474
+ }, `${rows}-${columns}`)))
475
+ }), /* @__PURE__ */ jsx("div", {
476
+ className: "oak-lexical-table-size",
477
+ "aria-live": "polite",
478
+ children: label(size.rows, size.columns)
479
+ })]
480
+ });
481
+ };
482
+ TableSizePicker.displayName = "TableSizePicker";
483
+ // lib/Field/LinkDropdown.tsx
484
+ const LinkDropdown = ({ state }) => {
485
+ const [editor] = useLexicalComposerContext();
486
+ const { t } = useLexicalField();
487
+ const dropdownRef = useRef(null);
488
+ const selection = useRef(null);
489
+ const [url, setUrl] = useState("");
490
+ const [blank, setBlank] = useState(false);
491
+ const onToggle = (opened) => {
492
+ if (!opened) return;
493
+ selection.current = editor.read(() => $getSelection()?.clone() ?? null);
494
+ setUrl(state.link?.url || "");
495
+ setBlank(state.link?.target === "_blank");
496
+ };
497
+ const apply = (href) => {
498
+ editor.update(() => {
499
+ if (selection.current) $setSelection(selection.current.clone());
500
+ const current = $getSelection();
501
+ const attributes = blank ? {
502
+ target: "_blank",
503
+ rel: "noopener noreferrer"
504
+ } : {
505
+ target: null,
506
+ rel: null
507
+ };
508
+ if (href && $isRangeSelection(current) && current.isCollapsed() && !state.link) {
509
+ const link = $createLinkNode(href, attributes);
510
+ link.append($createTextNode(href));
511
+ $insertNodes([link]);
512
+ return;
513
+ }
514
+ $toggleLink(href ? {
515
+ url: href,
516
+ ...attributes
517
+ } : null);
518
+ });
519
+ dropdownRef.current?.close();
520
+ editor.focus();
521
+ };
522
+ const onSubmit = (e) => {
523
+ e.preventDefault();
524
+ apply(url.trim() || null);
525
+ };
526
+ return /* @__PURE__ */ jsx(ToolbarDropdown, {
527
+ ref: dropdownRef,
528
+ label: t("addons.lexical.fields.editor.link", "Link"),
529
+ icon: /* @__PURE__ */ jsx(Icon, { name: "link" }),
530
+ active: !!state.link,
531
+ menuClassName: "oak-lexical-link-menu",
532
+ onToggle,
533
+ children: /* @__PURE__ */ jsxs("form", {
534
+ className: "oak-lexical-link-form",
535
+ onSubmit,
536
+ children: [
537
+ /* @__PURE__ */ jsx(TextField, {
538
+ autoFocus: true,
539
+ value: url,
540
+ placeholder: t("addons.lexical.fields.editor.linkPlaceholder", "https://"),
541
+ onChange: ({ value }) => setUrl(String(value ?? ""))
542
+ }),
543
+ /* @__PURE__ */ jsx(Toggle, {
544
+ checked: blank,
545
+ onChange: ({ checked }) => setBlank(checked),
546
+ children: t("addons.lexical.fields.editor.blank", "Open in a new tab")
547
+ }),
548
+ /* @__PURE__ */ jsxs("div", {
549
+ className: "oak-lexical-link-actions",
550
+ children: [state.link && /* @__PURE__ */ jsx(Button, {
551
+ type: "button",
552
+ className: "subtle",
553
+ onClick: () => apply(null),
554
+ children: t("addons.lexical.fields.editor.unlink", "Remove link")
555
+ }), /* @__PURE__ */ jsx(Button, {
556
+ type: "submit",
557
+ className: "primary",
558
+ disabled: !url.trim(),
559
+ children: t("addons.lexical.fields.editor.save", "Save")
560
+ })]
561
+ })
562
+ ]
563
+ })
564
+ });
565
+ };
566
+ LinkDropdown.displayName = "LinkDropdown";
567
+ // lib/Field/ColorDropdown.tsx
568
+ /**
569
+ * Junipero's color field, displayed inside the menu (its picker is rendered
570
+ * inline, so that using it doesn't close the menu)
571
+ */
572
+ const ColorPicker = ({ value, onChange }) => {
573
+ const fieldRef = useRef(null);
574
+ useEffect(() => {
575
+ fieldRef.current?.open();
576
+ }, []);
577
+ return /* @__PURE__ */ jsx("li", {
578
+ className: "oak-lexical-color-picker",
579
+ children: /* @__PURE__ */ jsx(ColorField, {
580
+ ref: fieldRef,
581
+ trigger: "manual",
582
+ value,
583
+ onChange: ({ value: color, valid }) => {
584
+ if (valid !== false && color) onChange(color);
585
+ }
586
+ })
587
+ });
588
+ };
589
+ const ColorDropdown = ({ state }) => {
590
+ const [editor] = useLexicalComposerContext();
591
+ const { t } = useLexicalField();
592
+ const dropdownRef = useRef(null);
593
+ const selection = useRef(null);
594
+ const changed = useRef(false);
595
+ const [color, setColor] = useState("");
596
+ const apply = (value) => {
597
+ editor.update(() => {
598
+ if (selection.current) $setSelection(selection.current.clone());
599
+ const current = $getSelection();
600
+ if (current) $patchStyleText(current, { color: value });
601
+ }, changed.current ? { tag: HISTORY_MERGE_TAG } : void 0);
602
+ changed.current = true;
603
+ };
604
+ const onToggle = (opened) => {
605
+ if (opened) {
606
+ selection.current = editor.read(() => $getSelection()?.clone() ?? null);
607
+ changed.current = false;
608
+ setColor(state.color || "#000000");
609
+ }
610
+ };
611
+ return /* @__PURE__ */ jsxs(ToolbarDropdown, {
612
+ ref: dropdownRef,
613
+ label: t("addons.lexical.fields.editor.fontColor", "Font color"),
614
+ icon: /* @__PURE__ */ jsx(Icon, {
615
+ name: "fontColor",
616
+ color: state.color || void 0
617
+ }),
618
+ active: !!state.color,
619
+ menuClassName: "oak-lexical-color-menu",
620
+ onToggle,
621
+ children: [/* @__PURE__ */ jsx(MenuItem, {
622
+ className: "oak-lexical-color-reset",
623
+ onClick: () => {
624
+ apply(null);
625
+ dropdownRef.current?.close();
626
+ editor.focus();
627
+ },
628
+ children: t("addons.lexical.fields.editor.removeColor", "Remove color")
629
+ }), /* @__PURE__ */ jsx(ColorPicker, {
630
+ value: color,
631
+ onChange: apply
632
+ })]
633
+ });
634
+ };
635
+ ColorDropdown.displayName = "ColorDropdown";
636
+ // lib/Field/Toolbar.tsx
637
+ const DEFAULT_FONT_SIZES = [
638
+ {
639
+ label: "Tiny",
640
+ value: "0.7em"
641
+ },
642
+ {
643
+ label: "Small",
644
+ value: "0.85em"
645
+ },
646
+ {
647
+ label: "Default",
648
+ value: null
649
+ },
650
+ {
651
+ label: "Big",
652
+ value: "1.4em"
653
+ },
654
+ {
655
+ label: "Huge",
656
+ value: "1.8em"
657
+ }
658
+ ];
659
+ const ALIGNMENTS = [
660
+ {
661
+ value: "left",
662
+ icon: "alignLeft",
663
+ label: "Align left"
664
+ },
665
+ {
666
+ value: "center",
667
+ icon: "alignCenter",
668
+ label: "Align center"
669
+ },
670
+ {
671
+ value: "right",
672
+ icon: "alignRight",
673
+ label: "Align right"
674
+ },
675
+ {
676
+ value: "justify",
677
+ icon: "alignJustify",
678
+ label: "Justify"
679
+ }
680
+ ];
681
+ const HEADINGS = [
682
+ {
683
+ value: "paragraph",
684
+ label: "Paragraph"
685
+ },
686
+ {
687
+ value: "h2",
688
+ label: "Heading 2"
689
+ },
690
+ {
691
+ value: "h3",
692
+ label: "Heading 3"
693
+ },
694
+ {
695
+ value: "h4",
696
+ label: "Heading 4"
697
+ }
698
+ ];
699
+ const TEXT_FORMATS = {
700
+ bold: {
701
+ format: "bold",
702
+ label: "Bold"
703
+ },
704
+ italic: {
705
+ format: "italic",
706
+ label: "Italic"
707
+ },
708
+ underline: {
709
+ format: "underline",
710
+ label: "Underline"
711
+ },
712
+ strikethrough: {
713
+ format: "strikethrough",
714
+ label: "Strikethrough"
715
+ }
716
+ };
717
+ const Toolbar = ({ items, fontSizes }) => {
718
+ const [editor] = useLexicalComposerContext();
719
+ const { t } = useLexicalField();
720
+ const state = useToolbarState(editor);
721
+ const fontSizeRef = useRef(null);
722
+ const alignmentRef = useRef(null);
723
+ const headingRef = useRef(null);
724
+ const tableRef = useRef(null);
725
+ const label = (key, def) => t(`addons.lexical.fields.editor.${key}`, def);
726
+ const setBlock = (create) => {
727
+ editor.update(() => {
728
+ $setBlocksType($getSelection(), create);
729
+ });
730
+ };
731
+ const removeFormat = () => {
732
+ editor.update(() => {
733
+ const selection = $getSelection();
734
+ if (!$isRangeSelection(selection)) return;
735
+ selection.extract().forEach((node) => {
736
+ if ($isTextNode(node)) {
737
+ node.setFormat(0);
738
+ node.setStyle("");
739
+ }
740
+ });
741
+ selection.setFormat(0);
742
+ selection.setStyle("");
743
+ });
744
+ };
745
+ const tableAction = (action) => {
746
+ editor.update(action);
747
+ tableRef.current?.close();
748
+ };
749
+ const renderItem = (item, i) => {
750
+ const format = TEXT_FORMATS[item];
751
+ if (format) return /* @__PURE__ */ jsx(ToolbarButton, {
752
+ label: label(item, format.label),
753
+ active: state[format.format],
754
+ onClick: () => editor.dispatchCommand(FORMAT_TEXT_COMMAND, format.format),
755
+ children: /* @__PURE__ */ jsx(Icon, { name: item })
756
+ }, item);
757
+ switch (item) {
758
+ case "|": return /* @__PURE__ */ jsx("span", { className: "oak-lexical-separator" }, `separator-${i}`);
759
+ case "undo": return /* @__PURE__ */ jsx(ToolbarButton, {
760
+ label: label("undo", "Undo"),
761
+ disabled: !state.canUndo,
762
+ onClick: () => editor.dispatchCommand(UNDO_COMMAND, void 0),
763
+ children: /* @__PURE__ */ jsx(Icon, { name: "undo" })
764
+ }, item);
765
+ case "redo": return /* @__PURE__ */ jsx(ToolbarButton, {
766
+ label: label("redo", "Redo"),
767
+ disabled: !state.canRedo,
768
+ onClick: () => editor.dispatchCommand(REDO_COMMAND, void 0),
769
+ children: /* @__PURE__ */ jsx(Icon, { name: "redo" })
770
+ }, item);
771
+ case "heading": return /* @__PURE__ */ jsx(ToolbarDropdown, {
772
+ ref: headingRef,
773
+ label: label("heading", "Heading"),
774
+ icon: /* @__PURE__ */ jsx(Icon, { name: "heading" }),
775
+ active: state.block.startsWith("h"),
776
+ children: HEADINGS.map((h) => /* @__PURE__ */ jsx(MenuItem, {
777
+ active: state.block === h.value,
778
+ className: `oak-lexical-heading-${h.value}`,
779
+ onClick: () => {
780
+ setBlock(() => h.value === "paragraph" ? $createParagraphNode() : $createHeadingNode(h.value));
781
+ headingRef.current?.close();
782
+ },
783
+ children: label(`heading.${h.value}`, h.label)
784
+ }, h.value))
785
+ }, item);
786
+ case "link": return /* @__PURE__ */ jsx(LinkDropdown, { state }, item);
787
+ case "fontColor": return /* @__PURE__ */ jsx(ColorDropdown, { state }, item);
788
+ case "fontSize": return /* @__PURE__ */ jsx(ToolbarDropdown, {
789
+ ref: fontSizeRef,
790
+ label: label("fontSize", "Font size"),
791
+ icon: /* @__PURE__ */ jsx(Icon, { name: "fontSize" }),
792
+ active: !!state.fontSize,
793
+ children: fontSizes.map((size) => /* @__PURE__ */ jsx(MenuItem, {
794
+ active: (state.fontSize || null) === size.value,
795
+ style: size.value ? { fontSize: size.value } : void 0,
796
+ onClick: () => {
797
+ editor.update(() => {
798
+ const selection = $getSelection();
799
+ if (selection) $patchStyleText(selection, { "font-size": size.value });
800
+ });
801
+ fontSizeRef.current?.close();
802
+ },
803
+ children: label(`fontSize.${size.label.toLowerCase()}`, size.label)
804
+ }, size.label))
805
+ }, item);
806
+ case "bulletedList": return /* @__PURE__ */ jsx(ToolbarButton, {
807
+ label: label("bulletedList", "Bulleted list"),
808
+ active: state.block === "bullet",
809
+ onClick: () => state.block === "bullet" ? editor.dispatchCommand(REMOVE_LIST_COMMAND, void 0) : editor.dispatchCommand(INSERT_UNORDERED_LIST_COMMAND, void 0),
810
+ children: /* @__PURE__ */ jsx(Icon, { name: "bulletedList" })
811
+ }, item);
812
+ case "numberedList": return /* @__PURE__ */ jsx(ToolbarButton, {
813
+ label: label("numberedList", "Numbered list"),
814
+ active: state.block === "number",
815
+ onClick: () => state.block === "number" ? editor.dispatchCommand(REMOVE_LIST_COMMAND, void 0) : editor.dispatchCommand(INSERT_ORDERED_LIST_COMMAND, void 0),
816
+ children: /* @__PURE__ */ jsx(Icon, { name: "numberedList" })
817
+ }, item);
818
+ case "removeFormat": return /* @__PURE__ */ jsx(ToolbarButton, {
819
+ label: label("removeFormat", "Remove format"),
820
+ onClick: removeFormat,
821
+ children: /* @__PURE__ */ jsx(Icon, { name: "removeFormat" })
822
+ }, item);
823
+ case "outdent": return /* @__PURE__ */ jsx(ToolbarButton, {
824
+ label: label("outdent", "Decrease indent"),
825
+ onClick: () => editor.dispatchCommand(OUTDENT_CONTENT_COMMAND, void 0),
826
+ children: /* @__PURE__ */ jsx(Icon, { name: "outdent" })
827
+ }, item);
828
+ case "indent": return /* @__PURE__ */ jsx(ToolbarButton, {
829
+ label: label("indent", "Increase indent"),
830
+ onClick: () => editor.dispatchCommand(INDENT_CONTENT_COMMAND, void 0),
831
+ children: /* @__PURE__ */ jsx(Icon, { name: "indent" })
832
+ }, item);
833
+ case "alignment": {
834
+ const current = ALIGNMENTS.find((a) => a.value === state.align);
835
+ return /* @__PURE__ */ jsx(ToolbarDropdown, {
836
+ ref: alignmentRef,
837
+ label: label("alignment", "Text alignment"),
838
+ icon: /* @__PURE__ */ jsx(Icon, { name: current?.icon || "alignLeft" }),
839
+ active: !!current && current.value !== "left",
840
+ menuClassName: "oak-lexical-alignment-menu",
841
+ children: ALIGNMENTS.map((a) => /* @__PURE__ */ jsx(MenuItem, {
842
+ active: state.align === a.value,
843
+ title: label(`align.${a.value}`, a.label),
844
+ "aria-label": label(`align.${a.value}`, a.label),
845
+ onClick: () => {
846
+ editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, a.value);
847
+ alignmentRef.current?.close();
848
+ },
849
+ children: /* @__PURE__ */ jsx(Icon, { name: a.icon })
850
+ }, a.value))
851
+ }, item);
852
+ }
853
+ case "horizontalLine": return /* @__PURE__ */ jsx(ToolbarButton, {
854
+ label: label("horizontalLine", "Horizontal line"),
855
+ onClick: () => editor.dispatchCommand(INSERT_HORIZONTAL_RULE_COMMAND, void 0),
856
+ children: /* @__PURE__ */ jsx(Icon, { name: "horizontalLine" })
857
+ }, item);
858
+ case "blockQuote": return /* @__PURE__ */ jsx(ToolbarButton, {
859
+ label: label("blockQuote", "Block quote"),
860
+ active: state.block === "quote",
861
+ onClick: () => setBlock(() => state.block === "quote" ? $createParagraphNode() : $createQuoteNode()),
862
+ children: /* @__PURE__ */ jsx(Icon, { name: "blockQuote" })
863
+ }, item);
864
+ case "insertTable": return /* @__PURE__ */ jsx(ToolbarDropdown, {
865
+ ref: tableRef,
866
+ label: label("table", "Table"),
867
+ icon: /* @__PURE__ */ jsx(Icon, { name: "insertTable" }),
868
+ active: state.inTable,
869
+ children: !state.inTable ? /* @__PURE__ */ jsx(TableSizePicker, { onSelect: (rows, columns) => {
870
+ editor.dispatchCommand(INSERT_TABLE_COMMAND, {
871
+ rows: String(rows),
872
+ columns: String(columns),
873
+ includeHeaders: false
874
+ });
875
+ tableRef.current?.close();
876
+ editor.focus();
877
+ } }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [
878
+ /* @__PURE__ */ jsx(MenuItem, {
879
+ onClick: () => tableAction(() => $insertTableRowAtSelection(false)),
880
+ children: label("table.rowAbove", "Insert row above")
881
+ }),
882
+ /* @__PURE__ */ jsx(MenuItem, {
883
+ onClick: () => tableAction(() => $insertTableRowAtSelection(true)),
884
+ children: label("table.rowBelow", "Insert row below")
885
+ }),
886
+ /* @__PURE__ */ jsx(MenuItem, {
887
+ onClick: () => tableAction(() => $insertTableColumnAtSelection(false)),
888
+ children: label("table.columnLeft", "Insert column left")
889
+ }),
890
+ /* @__PURE__ */ jsx(MenuItem, {
891
+ onClick: () => tableAction(() => $insertTableColumnAtSelection(true)),
892
+ children: label("table.columnRight", "Insert column right")
893
+ }),
894
+ /* @__PURE__ */ jsx(MenuItem, {
895
+ onClick: () => tableAction($deleteTableRowAtSelection),
896
+ children: label("table.deleteRow", "Delete row")
897
+ }),
898
+ /* @__PURE__ */ jsx(MenuItem, {
899
+ onClick: () => tableAction($deleteTableColumnAtSelection),
900
+ children: label("table.deleteColumn", "Delete column")
901
+ }),
902
+ /* @__PURE__ */ jsx(MenuItem, {
903
+ onClick: () => tableAction(() => {
904
+ const node = $getSelection()?.getNodes()[0];
905
+ (node && ($isTableNode(node) ? node : $findMatchingParent(node, $isTableNode)))?.remove();
906
+ }),
907
+ children: label("table.delete", "Delete table")
908
+ })
909
+ ] })
910
+ }, item);
911
+ default: return null;
912
+ }
913
+ };
914
+ return /* @__PURE__ */ jsx("div", {
915
+ className: "oak-lexical-toolbar",
916
+ role: "toolbar",
917
+ children: items.map((item, i) => /* @__PURE__ */ jsx(Fragment, { children: renderItem(item, i) }, `${item}-${i}`))
918
+ });
919
+ };
920
+ Toolbar.displayName = "Toolbar";
921
+ // lib/Field/positions.ts
922
+ const ELEMENT_START = "";
923
+ const ELEMENT_END = "";
924
+ const OTHER = "";
925
+ const $getSize = (node) => {
926
+ if ($isTextNode(node)) return node.getTextContentSize();
927
+ if ($isElementNode(node)) return node.getChildren().reduce((s, c) => s + $getSize(c), 2);
928
+ return 1;
929
+ };
930
+ const $serializeNode = (node) => {
931
+ if ($isTextNode(node)) return node.getTextContent();
932
+ if ($isElementNode(node)) return ELEMENT_START + node.getChildren().map($serializeNode).join("") + ELEMENT_END;
933
+ return OTHER;
934
+ };
935
+ /** Linear representation of the document */
936
+ const $serialize = () => $getRoot().getChildren().map($serializeNode).join("");
937
+ /** Offset of a selection point */
938
+ const $getPointOffset = (point) => {
939
+ const node = point.getNode();
940
+ let offset = 0;
941
+ if ($isTextNode(node)) offset = point.offset;
942
+ else if ($isElementNode(node)) offset = node.getChildren().slice(0, point.offset).reduce((s, c) => s + $getSize(c), $isRootNode(node) ? 0 : 1);
943
+ let current = node;
944
+ while (current && !$isRootNode(current)) {
945
+ let sibling = current.getPreviousSibling();
946
+ while (sibling) {
947
+ offset += $getSize(sibling);
948
+ sibling = sibling.getPreviousSibling();
949
+ }
950
+ current = current.getParent();
951
+ if (current && !$isRootNode(current)) offset += 1;
952
+ }
953
+ return offset;
954
+ };
955
+ const $findPoint = (element, offset) => {
956
+ const children = element.getChildren();
957
+ let remaining = offset;
958
+ for (let i = 0; i < children.length; i++) {
959
+ const child = children[i];
960
+ const size = $getSize(child);
961
+ if ($isTextNode(child) && remaining <= size) return {
962
+ key: child.getKey(),
963
+ offset: remaining,
964
+ type: "text"
965
+ };
966
+ if ($isElementNode(child) && remaining < size) return $findPoint(child, Math.max(0, Math.min(remaining - 1, size - 2)));
967
+ if (!$isTextNode(child) && !$isElementNode(child) && remaining === 0) return {
968
+ key: element.getKey(),
969
+ offset: i,
970
+ type: "element"
971
+ };
972
+ remaining -= size;
973
+ }
974
+ return {
975
+ key: element.getKey(),
976
+ offset: children.length,
977
+ type: "element"
978
+ };
979
+ };
980
+ /** Selection point at an offset (clamped to the document) */
981
+ const $getPointAt = (offset) => $findPoint($getRoot(), Math.max(0, offset));
982
+ /**
983
+ * Where a position ends up when `a` is changed into `b` (a single contiguous
984
+ * change between the common prefix & suffix)
985
+ */
986
+ const mapPosition = (position, a, b) => {
987
+ let start = 0;
988
+ const max = Math.min(a.length, b.length);
989
+ while (start < max && a[start] === b[start]) start++;
990
+ let endA = a.length;
991
+ let endB = b.length;
992
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
993
+ endA--;
994
+ endB--;
995
+ }
996
+ if (position <= start) return position;
997
+ if (position >= endA) return position + endB - endA;
998
+ return endB;
999
+ };
1000
+ const $selectOffsets = (anchor, focus) => {
1001
+ const a = $getPointAt(anchor);
1002
+ const f = $getPointAt(focus);
1003
+ const selection = $createRangeSelection();
1004
+ selection.anchor.set(a.key, a.offset, a.type);
1005
+ selection.focus.set(f.key, f.offset, f.type);
1006
+ $setSelection(selection);
1007
+ };
1008
+ // lib/Field/measure.ts
1009
+ /**
1010
+ * Measures where a selection (offsets, see `positions.ts`) is displayed in
1011
+ * the editor, relative to `container`
1012
+ */
1013
+ const measureSelection = (editor, container, { anchor, head }) => {
1014
+ const origin = container.getBoundingClientRect();
1015
+ const relative = (r, width = r.width) => ({
1016
+ top: r.top - origin.top,
1017
+ left: r.left - origin.left,
1018
+ width,
1019
+ height: r.height
1020
+ });
1021
+ return editor.read(() => {
1022
+ let caret = null;
1023
+ let selection = [];
1024
+ try {
1025
+ const h = $getPointAt(head);
1026
+ const headNode = $getNodeByKey(h.key);
1027
+ if (headNode) {
1028
+ let rect = createDOMRange(editor, headNode, h.offset, headNode, h.offset)?.getClientRects()[0];
1029
+ if (!rect || !rect.height) rect = editor.getElementByKey(h.key)?.getBoundingClientRect();
1030
+ if (rect) caret = relative(rect, 0);
1031
+ }
1032
+ if (anchor !== head) {
1033
+ const a = $getPointAt(anchor);
1034
+ const anchorNode = $getNodeByKey(a.key);
1035
+ if (anchorNode && headNode) {
1036
+ const range = createDOMRange(editor, anchorNode, a.offset, headNode, h.offset);
1037
+ if (range) selection = createRectsFromDOMRange(editor, range).filter((r) => r.width > 0).map((r) => relative(r));
1038
+ }
1039
+ }
1040
+ } catch {}
1041
+ return {
1042
+ caret,
1043
+ selection
1044
+ };
1045
+ });
1046
+ };
1047
+ // lib/Field/SyncPlugin.tsx
1048
+ const EXTERNAL_TAG = "oak-external-change";
1049
+ const isFocused = (editor) => {
1050
+ const root = editor.getRootElement();
1051
+ return !!root && root.ownerDocument.activeElement === root;
1052
+ };
1053
+ /**
1054
+ * Keeps the editor in sync with the field's value (changes made outside of
1055
+ * the editor, e.g. by another user, keep the selection), and shares the
1056
+ * local selection & displays the other users' ones
1057
+ */
1058
+ const SyncPlugin = ({ value, onChange, collaborators, onSelectionChange, containerRef, onCursorsChange }) => {
1059
+ const [editor] = useLexicalComposerContext();
1060
+ const lastValue = useRef(value);
1061
+ const baseline = useRef(null);
1062
+ const onChangeRef = useRef(onChange);
1063
+ onChangeRef.current = onChange;
1064
+ const onSelectionChangeRef = useRef(onSelectionChange);
1065
+ onSelectionChangeRef.current = onSelectionChange;
1066
+ const [layoutVersion, setLayoutVersion] = useState(0);
1067
+ const lastSelection = useRef(null);
1068
+ const frame = useRef(null);
1069
+ const reportSelection = useRef(() => {
1070
+ cancelAnimationFrame(frame.current);
1071
+ frame.current = requestAnimationFrame(() => {
1072
+ const selection = isFocused(editor) ? editor.read(() => {
1073
+ const s = $getSelection();
1074
+ return $isRangeSelection(s) ? {
1075
+ anchor: $getPointOffset(s.anchor),
1076
+ head: $getPointOffset(s.focus)
1077
+ } : null;
1078
+ }) : null;
1079
+ const serialized = JSON.stringify(selection);
1080
+ if (serialized !== lastSelection.current) {
1081
+ lastSelection.current = serialized;
1082
+ onSelectionChangeRef.current?.(selection);
1083
+ }
1084
+ });
1085
+ }).current;
1086
+ useEffect(() => () => cancelAnimationFrame(frame.current), []);
1087
+ useEffect(() => {
1088
+ baseline.current = editor.read(() => $exportHtml(editor));
1089
+ return mergeRegister(editor.registerUpdateListener(({ dirtyElements, dirtyLeaves, tags }) => {
1090
+ reportSelection();
1091
+ setLayoutVersion((v) => v + 1);
1092
+ if (!dirtyElements.size && !dirtyLeaves.size) return;
1093
+ const html = editor.read(() => $exportHtml(editor));
1094
+ if (tags.has(EXTERNAL_TAG) || html === baseline.current) {
1095
+ baseline.current = html;
1096
+ return;
1097
+ }
1098
+ baseline.current = html;
1099
+ lastValue.current = html;
1100
+ onChangeRef.current?.(html);
1101
+ }), editor.registerCommand(FOCUS_COMMAND, () => {
1102
+ reportSelection();
1103
+ return false;
1104
+ }, COMMAND_PRIORITY_LOW), editor.registerCommand(BLUR_COMMAND, () => {
1105
+ reportSelection();
1106
+ return false;
1107
+ }, COMMAND_PRIORITY_LOW));
1108
+ }, [editor, reportSelection]);
1109
+ useEffect(() => {
1110
+ if (value === void 0 || value === lastValue.current) return;
1111
+ lastValue.current = value;
1112
+ const current = editor.read(() => $exportHtml(editor));
1113
+ if (current === value) {
1114
+ baseline.current = current;
1115
+ return;
1116
+ }
1117
+ const focused = isFocused(editor);
1118
+ editor.update(() => {
1119
+ const selection = $getSelection();
1120
+ const saved = focused && $isRangeSelection(selection) ? {
1121
+ text: $serialize(),
1122
+ anchor: $getPointOffset(selection.anchor),
1123
+ focus: $getPointOffset(selection.focus)
1124
+ } : null;
1125
+ $importHtml(editor, value);
1126
+ if (!saved) {
1127
+ $setSelection(null);
1128
+ return;
1129
+ }
1130
+ const text = $serialize();
1131
+ try {
1132
+ $selectOffsets(mapPosition(saved.anchor, saved.text, text), mapPosition(saved.focus, saved.text, text));
1133
+ } catch {
1134
+ $setSelection(null);
1135
+ }
1136
+ }, {
1137
+ tag: [EXTERNAL_TAG, HISTORIC_TAG],
1138
+ discrete: true
1139
+ });
1140
+ baseline.current = editor.read(() => $exportHtml(editor));
1141
+ editor.dispatchCommand(CLEAR_HISTORY_COMMAND, void 0);
1142
+ }, [value, editor]);
1143
+ useLayoutEffect(() => {
1144
+ const container = containerRef.current;
1145
+ if (!container || !collaborators?.length) {
1146
+ onCursorsChange([]);
1147
+ return;
1148
+ }
1149
+ onCursorsChange(collaborators.map((c) => ({
1150
+ ...c,
1151
+ ...measureSelection(editor, container, c)
1152
+ })));
1153
+ }, [
1154
+ collaborators,
1155
+ layoutVersion,
1156
+ editor,
1157
+ containerRef,
1158
+ onCursorsChange
1159
+ ]);
1160
+ const hasCollaborators = !!collaborators?.length;
1161
+ useEffect(() => {
1162
+ const root = editor.getRootElement();
1163
+ if (!root || !hasCollaborators) return;
1164
+ const observer = new ResizeObserver(() => setLayoutVersion((v) => v + 1));
1165
+ observer.observe(root);
1166
+ return () => observer.disconnect();
1167
+ }, [editor, hasCollaborators]);
1168
+ return null;
1169
+ };
1170
+ SyncPlugin.displayName = "SyncPlugin";
1171
+ // lib/Field/Cursors.tsx
1172
+ /**
1173
+ * Displays the carets & selections of other users over a field. Must be
1174
+ * rendered inside a positioned container, the rects being relative to it.
1175
+ * Copy of @oakjs/ash's `FieldCursors` (this package doesn't depend on ash).
1176
+ */
1177
+ const FieldCursors = ({ cursors, labelDuration = 2e3 }) => {
1178
+ const positions = useRef(/* @__PURE__ */ new Map());
1179
+ const [labels, setLabels] = useState({});
1180
+ useEffect(() => {
1181
+ const now = Date.now();
1182
+ const moved = {};
1183
+ cursors.forEach((c) => {
1184
+ const position = `${c.anchor}:${c.head}`;
1185
+ if (positions.current.get(c.id) !== position) {
1186
+ positions.current.set(c.id, position);
1187
+ moved[c.id] = now;
1188
+ }
1189
+ });
1190
+ if (Object.keys(moved).length) setLabels((l) => ({
1191
+ ...l,
1192
+ ...moved
1193
+ }));
1194
+ }, [cursors]);
1195
+ useEffect(() => {
1196
+ const ids = Object.keys(labels);
1197
+ if (!ids.length) return;
1198
+ const next = Math.min(...ids.map((id) => labels[id])) + labelDuration;
1199
+ const timeout = setTimeout(() => {
1200
+ const now = Date.now();
1201
+ setLabels((l) => Object.fromEntries(Object.entries(l).filter(([, t]) => now - t < labelDuration)));
1202
+ }, Math.max(0, next - Date.now()) + 16);
1203
+ return () => clearTimeout(timeout);
1204
+ }, [labels, labelDuration]);
1205
+ if (!cursors.length) return null;
1206
+ return /* @__PURE__ */ jsx("div", {
1207
+ "aria-hidden": true,
1208
+ className: "oak-field-cursors",
1209
+ style: {
1210
+ position: "absolute",
1211
+ inset: 0,
1212
+ pointerEvents: "none",
1213
+ zIndex: 2
1214
+ },
1215
+ children: cursors.map((c) => /* @__PURE__ */ jsxs(Fragment, { children: [c.selection.map((rect, i) => /* @__PURE__ */ jsx("div", { style: {
1216
+ position: "absolute",
1217
+ ...rect,
1218
+ background: `color-mix(in srgb, ${c.color} 30%, transparent)`
1219
+ } }, i)), c.caret && /* @__PURE__ */ jsx("div", {
1220
+ style: {
1221
+ position: "absolute",
1222
+ top: c.caret.top,
1223
+ left: c.caret.left - 1,
1224
+ width: 2,
1225
+ height: c.caret.height,
1226
+ background: c.color
1227
+ },
1228
+ children: c.name && /* @__PURE__ */ jsx("span", {
1229
+ style: {
1230
+ position: "absolute",
1231
+ bottom: "100%",
1232
+ left: 0,
1233
+ padding: "0 4px",
1234
+ borderRadius: "3px 3px 3px 0",
1235
+ background: c.color,
1236
+ color: "var(--junipero-onyx)",
1237
+ fontSize: 10,
1238
+ fontWeight: 600,
1239
+ lineHeight: "14px",
1240
+ whiteSpace: "nowrap",
1241
+ opacity: labels[c.id] ? 1 : 0,
1242
+ transition: "opacity .2s ease-in-out"
1243
+ },
1244
+ children: c.name
1245
+ })
1246
+ })] }, c.id))
1247
+ });
1248
+ };
1249
+ FieldCursors.displayName = "FieldCursors";
1250
+ // lib/Field/index.tsx
1251
+ const DEFAULT_TOOLBAR = [
1252
+ "undo",
1253
+ "redo",
1254
+ "|",
1255
+ "bold",
1256
+ "italic",
1257
+ "strikethrough",
1258
+ "underline",
1259
+ "link",
1260
+ "fontColor",
1261
+ "fontSize",
1262
+ "bulletedList",
1263
+ "numberedList",
1264
+ "|",
1265
+ "removeFormat",
1266
+ "|",
1267
+ "outdent",
1268
+ "indent",
1269
+ "alignment",
1270
+ "|",
1271
+ "horizontalLine",
1272
+ "blockQuote",
1273
+ "insertTable"
1274
+ ];
1275
+ const NODES = [
1276
+ HeadingNode,
1277
+ QuoteNode,
1278
+ ListNode,
1279
+ ListItemNode,
1280
+ LinkNode,
1281
+ AutoLinkNode,
1282
+ TableNode,
1283
+ TableRowNode,
1284
+ TableCellNode,
1285
+ HorizontalRuleNode
1286
+ ];
1287
+ const LexicalField = ({ className, value, toolbar = DEFAULT_TOOLBAR, fontSizes = DEFAULT_FONT_SIZES, fieldOptions, onChange, ...rest }) => {
1288
+ const t = fieldOptions?.t;
1289
+ const container = fieldOptions?.floatingsRef?.current || void 0;
1290
+ const context = useMemo(() => ({
1291
+ t: (key, def) => t?.(key, def) ?? def,
1292
+ container
1293
+ }), [t, container]);
1294
+ const containerRef = useRef(null);
1295
+ const [cursors, setCursors] = useState([]);
1296
+ const initialValue = useRef(value);
1297
+ const initialConfig = useMemo(() => ({
1298
+ namespace: "oak-lexical",
1299
+ theme,
1300
+ nodes: NODES,
1301
+ html: htmlConfig,
1302
+ onError: (error) => {
1303
+ console.error("[oak] Lexical field error:", error);
1304
+ },
1305
+ editorState: (editor) => $importHtml(editor, initialValue.current)
1306
+ }), []);
1307
+ const onChange_ = useCallback((html) => {
1308
+ onChange?.({ value: html });
1309
+ }, [onChange]);
1310
+ const onCursorsChange = useCallback((next) => {
1311
+ setCursors((c) => !c.length && !next.length ? c : next);
1312
+ }, []);
1313
+ return /* @__PURE__ */ jsx(LexicalFieldContext, {
1314
+ value: context,
1315
+ children: /* @__PURE__ */ jsxs("div", {
1316
+ ...rest,
1317
+ ref: containerRef,
1318
+ className: classNames("oak-lexical-field", className),
1319
+ children: [/* @__PURE__ */ jsxs(LexicalComposer, {
1320
+ initialConfig,
1321
+ children: [
1322
+ /* @__PURE__ */ jsx(Toolbar, {
1323
+ items: toolbar,
1324
+ fontSizes
1325
+ }),
1326
+ /* @__PURE__ */ jsx(RichTextPlugin, {
1327
+ contentEditable: /* @__PURE__ */ jsx(ContentEditable, { className: "oak-lexical-editor" }),
1328
+ ErrorBoundary: LexicalErrorBoundary
1329
+ }),
1330
+ /* @__PURE__ */ jsx(HistoryPlugin, {}),
1331
+ /* @__PURE__ */ jsx(ListPlugin, {}),
1332
+ /* @__PURE__ */ jsx(LinkPlugin, {}),
1333
+ /* @__PURE__ */ jsx(TablePlugin, {
1334
+ hasCellMerge: false,
1335
+ hasCellBackgroundColor: false
1336
+ }),
1337
+ /* @__PURE__ */ jsx(HorizontalRulePlugin, {}),
1338
+ /* @__PURE__ */ jsx(SyncPlugin, {
1339
+ value,
1340
+ onChange: onChange_,
1341
+ collaborators: fieldOptions?.collaborators,
1342
+ onSelectionChange: fieldOptions?.onSelectionChange,
1343
+ containerRef,
1344
+ onCursorsChange
1345
+ })
1346
+ ]
1347
+ }), /* @__PURE__ */ jsx(FieldCursors, { cursors })]
1348
+ })
1349
+ });
1350
+ };
1351
+ LexicalField.displayName = "LexicalField";
1352
+ // lib/addons.ts
1353
+ const lexicalField = ({ toolbar, fontSizes, ...props } = {}) => ({
1354
+ type: "lexical",
1355
+ render: LexicalField,
1356
+ ...omit(props, ["onChange"]),
1357
+ props: {
1358
+ ...toolbar && { toolbar },
1359
+ ...fontSizes && { fontSizes }
1360
+ }
1361
+ });
1362
+ const lexicalFieldAddon = (props) => ({ fields: [lexicalField(props)] });
1363
+ export { DEFAULT_FONT_SIZES as a, LexicalField as i, lexicalFieldAddon as n, $exportHtml as o, DEFAULT_TOOLBAR as r, $importHtml as s, lexicalField as t };
1364
+
1365
+ //# sourceMappingURL=addons-DQNB8pRc.js.map