@fab1o978/react-ui 0.1.2 → 0.1.5

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 (31) hide show
  1. package/dist/components/ColorPicker/index.cjs +12 -1
  2. package/dist/components/ColorPicker/index.cjs.map +1 -1
  3. package/dist/components/ColorPicker/index.css +1 -2
  4. package/dist/components/ColorPicker/index.css.map +1 -1
  5. package/dist/components/ColorPicker/index.js +12 -1
  6. package/dist/components/ColorPicker/index.js.map +1 -1
  7. package/dist/components/RichTextEditor/index.cjs +3553 -0
  8. package/dist/components/RichTextEditor/index.cjs.map +1 -0
  9. package/dist/components/RichTextEditor/index.css +356 -0
  10. package/dist/components/RichTextEditor/index.css.map +1 -0
  11. package/dist/components/RichTextEditor/index.d.cts +30 -0
  12. package/dist/components/RichTextEditor/index.d.ts +30 -0
  13. package/dist/components/RichTextEditor/index.js +3538 -0
  14. package/dist/components/RichTextEditor/index.js.map +1 -0
  15. package/dist/components/SlidingCounter/index.cjs +181 -0
  16. package/dist/components/SlidingCounter/index.cjs.map +1 -0
  17. package/dist/components/SlidingCounter/index.css +133 -0
  18. package/dist/components/SlidingCounter/index.css.map +1 -0
  19. package/dist/components/SlidingCounter/index.d.cts +19 -0
  20. package/dist/components/SlidingCounter/index.d.ts +19 -0
  21. package/dist/components/SlidingCounter/index.js +179 -0
  22. package/dist/components/SlidingCounter/index.js.map +1 -0
  23. package/dist/index.cjs +3577 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.css +486 -2
  26. package/dist/index.css.map +1 -1
  27. package/dist/index.d.cts +4 -0
  28. package/dist/index.d.ts +4 -0
  29. package/dist/index.js +3567 -3
  30. package/dist/index.js.map +1 -1
  31. package/package.json +8 -1
@@ -0,0 +1,3538 @@
1
+ import { useRef, useState, useEffect } from 'react';
2
+ import { EditorProvider, useCurrentEditor } from '@tiptap/react';
3
+ export { useCurrentEditor } from '@tiptap/react';
4
+ import StarterKit from '@tiptap/starter-kit';
5
+ import Underline from '@tiptap/extension-underline';
6
+ import Placeholder from '@tiptap/extension-placeholder';
7
+ import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
8
+ import { RemoveMarkStep, Transform, liftTarget, joinPoint, canSplit, ReplaceStep, ReplaceAroundStep, canJoin } from '@tiptap/pm/transform';
9
+ import { createParagraphNear as createParagraphNear$1, exitCode as exitCode$1, joinUp as joinUp$1, joinDown as joinDown$1, joinBackward as joinBackward$1, joinForward as joinForward$1, joinTextblockBackward as joinTextblockBackward$1, joinTextblockForward as joinTextblockForward$1, lift as lift$1, liftEmptyBlock as liftEmptyBlock$1, newlineInCode as newlineInCode$1, selectNodeBackward as selectNodeBackward$1, selectNodeForward as selectNodeForward$1, selectParentNode as selectParentNode$1, selectTextblockEnd as selectTextblockEnd$1, selectTextblockStart as selectTextblockStart$1, setBlockType, wrapIn as wrapIn$1 } from '@tiptap/pm/commands';
10
+ import { Plugin, PluginKey, Selection, TextSelection, AllSelection, NodeSelection } from '@tiptap/pm/state';
11
+ import { Fragment, Slice, Node, Schema, DOMParser } from '@tiptap/pm/model';
12
+ import { liftListItem as liftListItem$1, sinkListItem as sinkListItem$1, wrapInList as wrapInList$1 } from '@tiptap/pm/schema-list';
13
+ import '@tiptap/pm/view';
14
+ import '@tiptap/pm/keymap';
15
+
16
+ // src/components/RichTextEditor/RichTextEditor.tsx
17
+
18
+ // src/components/RichTextEditor/RichTextEditor.module.scss
19
+ var RichTextEditor_module_default = {
20
+ root: "RichTextEditor_module_root2",
21
+ readOnly: "RichTextEditor_module_readOnly2",
22
+ toolbar: "RichTextEditor_module_toolbar2",
23
+ toolbarGroup: "RichTextEditor_module_toolbarGroup2",
24
+ divider: "RichTextEditor_module_divider2",
25
+ toolbarButton: "RichTextEditor_module_toolbarButton2",
26
+ active: "RichTextEditor_module_active2",
27
+ headingButton: "RichTextEditor_module_headingButton2",
28
+ bubbleMenu: "RichTextEditor_module_bubbleMenu2",
29
+ editorContent: "RichTextEditor_module_editorContent2"};
30
+
31
+ // src/utils/color.ts
32
+ function hexToHsl(hex) {
33
+ const r = parseInt(hex.slice(1, 3), 16) / 255;
34
+ const g = parseInt(hex.slice(3, 5), 16) / 255;
35
+ const b = parseInt(hex.slice(5, 7), 16) / 255;
36
+ const max = Math.max(r, g, b);
37
+ const min = Math.min(r, g, b);
38
+ const l = (max + min) / 2;
39
+ let h = 0;
40
+ let s = 0;
41
+ if (max !== min) {
42
+ const d = max - min;
43
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
44
+ switch (max) {
45
+ case r:
46
+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
47
+ break;
48
+ case g:
49
+ h = ((b - r) / d + 2) / 6;
50
+ break;
51
+ case b:
52
+ h = ((r - g) / d + 4) / 6;
53
+ break;
54
+ }
55
+ }
56
+ return [h * 360, s * 100, l * 100];
57
+ }
58
+ function hslToHex(h, s, l) {
59
+ const sl = s / 100;
60
+ const ll = l / 100;
61
+ const a = sl * Math.min(ll, 1 - ll);
62
+ const f = (n) => {
63
+ const k = (n + h / 30) % 12;
64
+ const color = ll - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
65
+ return Math.round(255 * color).toString(16).padStart(2, "0");
66
+ };
67
+ return `#${f(0)}${f(8)}${f(4)}`;
68
+ }
69
+ function hslToRgb(h, s, l) {
70
+ const sl = s / 100;
71
+ const ll = l / 100;
72
+ const a = sl * Math.min(ll, 1 - ll);
73
+ const f = (n) => {
74
+ const k = (n + h / 30) % 12;
75
+ return Math.round(255 * (ll - a * Math.max(Math.min(k - 3, 9 - k, 1), -1)));
76
+ };
77
+ return { r: f(0), g: f(8), b: f(4) };
78
+ }
79
+ function hslToRgba(h, s, l, alpha) {
80
+ const { r, g, b } = hslToRgb(h, s, l);
81
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`;
82
+ }
83
+ function deriveAccent(hex) {
84
+ const [h, s, l] = hexToHsl(hex);
85
+ return {
86
+ base: hex,
87
+ dot: hslToHex(h, s, Math.min(l + 12, 95)),
88
+ track: hex,
89
+ ring: hex,
90
+ glow: hslToRgba(h, s, l, 0.3),
91
+ light: hslToHex(h, Math.max(s - 20, 0), Math.min(l + 45, 96))
92
+ };
93
+ }
94
+ function accentToCssVars(tokens, prefix) {
95
+ return {
96
+ [`--${prefix}-accent`]: tokens.base,
97
+ [`--${prefix}-accent-dot`]: tokens.dot,
98
+ [`--${prefix}-accent-track`]: tokens.track,
99
+ [`--${prefix}-accent-ring`]: tokens.ring,
100
+ [`--${prefix}-accent-glow`]: tokens.glow,
101
+ [`--${prefix}-accent-light`]: tokens.light
102
+ };
103
+ }
104
+ var BulletListIcon = () => /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
105
+ /* @__PURE__ */ jsx("circle", { cx: "2.5", cy: "4", r: "1.5", fill: "currentColor" }),
106
+ /* @__PURE__ */ jsx("line", { x1: "6", y1: "4", x2: "14", y2: "4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
107
+ /* @__PURE__ */ jsx("circle", { cx: "2.5", cy: "8", r: "1.5", fill: "currentColor" }),
108
+ /* @__PURE__ */ jsx("line", { x1: "6", y1: "8", x2: "14", y2: "8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
109
+ /* @__PURE__ */ jsx("circle", { cx: "2.5", cy: "12", r: "1.5", fill: "currentColor" }),
110
+ /* @__PURE__ */ jsx("line", { x1: "6", y1: "12", x2: "14", y2: "12", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
111
+ ] });
112
+ var OrderedListIcon = () => /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
113
+ /* @__PURE__ */ jsx("text", { x: "0.5", y: "5.5", fontSize: "5.5", fill: "currentColor", fontFamily: "system-ui, sans-serif", children: "1." }),
114
+ /* @__PURE__ */ jsx("line", { x1: "7", y1: "4", x2: "14", y2: "4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
115
+ /* @__PURE__ */ jsx("text", { x: "0.5", y: "9.5", fontSize: "5.5", fill: "currentColor", fontFamily: "system-ui, sans-serif", children: "2." }),
116
+ /* @__PURE__ */ jsx("line", { x1: "7", y1: "8", x2: "14", y2: "8", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }),
117
+ /* @__PURE__ */ jsx("text", { x: "0.5", y: "13.5", fontSize: "5.5", fill: "currentColor", fontFamily: "system-ui, sans-serif", children: "3." }),
118
+ /* @__PURE__ */ jsx("line", { x1: "7", y1: "12", x2: "14", y2: "12", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
119
+ ] });
120
+ var Toolbar = ({ slotBefore }) => {
121
+ const { editor } = useCurrentEditor();
122
+ if (!editor) return null;
123
+ return /* @__PURE__ */ jsxs("div", { className: RichTextEditor_module_default.toolbar, role: "toolbar", "aria-label": "Text formatting", children: [
124
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: [
125
+ { render: () => /* @__PURE__ */ jsx("strong", { children: "B" }), title: "Bold", action: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold") },
126
+ { render: () => /* @__PURE__ */ jsx("em", { children: "I" }), title: "Italic", action: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic") },
127
+ { render: () => /* @__PURE__ */ jsx("u", { children: "U" }), title: "Underline", action: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline") },
128
+ { render: () => /* @__PURE__ */ jsx("s", { children: "S" }), title: "Strikethrough", action: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike") }
129
+ ].map(({ render, title, action, active }) => /* @__PURE__ */ jsx(
130
+ "button",
131
+ {
132
+ type: "button",
133
+ title,
134
+ "aria-label": title,
135
+ "aria-pressed": active,
136
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
137
+ onMouseDown: (e) => {
138
+ e.preventDefault();
139
+ action();
140
+ },
141
+ children: render()
142
+ },
143
+ title
144
+ )) }),
145
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.divider, "aria-hidden": "true" }),
146
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: [1, 2, 3].map((level) => /* @__PURE__ */ jsxs(
147
+ "button",
148
+ {
149
+ type: "button",
150
+ title: `Heading ${level}`,
151
+ "aria-label": `Heading ${level}`,
152
+ "aria-pressed": editor.isActive("heading", { level }),
153
+ className: [
154
+ RichTextEditor_module_default.toolbarButton,
155
+ RichTextEditor_module_default.headingButton,
156
+ editor.isActive("heading", { level }) ? RichTextEditor_module_default.active : ""
157
+ ].filter(Boolean).join(" "),
158
+ onMouseDown: (e) => {
159
+ e.preventDefault();
160
+ editor.chain().focus().toggleHeading({ level }).run();
161
+ },
162
+ children: [
163
+ "H",
164
+ level
165
+ ]
166
+ },
167
+ `h${level}`
168
+ )) }),
169
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.divider, "aria-hidden": "true" }),
170
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: [
171
+ { icon: /* @__PURE__ */ jsx(BulletListIcon, {}), title: "Bullet list", action: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList") },
172
+ { icon: /* @__PURE__ */ jsx(OrderedListIcon, {}), title: "Ordered list", action: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList") }
173
+ ].map(({ icon, title, action, active }) => /* @__PURE__ */ jsx(
174
+ "button",
175
+ {
176
+ type: "button",
177
+ title,
178
+ "aria-label": title,
179
+ "aria-pressed": active,
180
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
181
+ onMouseDown: (e) => {
182
+ e.preventDefault();
183
+ action();
184
+ },
185
+ children: icon
186
+ },
187
+ title
188
+ )) }),
189
+ slotBefore && /* @__PURE__ */ jsxs(Fragment$1, { children: [
190
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.divider, "aria-hidden": "true" }),
191
+ /* @__PURE__ */ jsx("div", { className: RichTextEditor_module_default.toolbarGroup, children: slotBefore })
192
+ ] })
193
+ ] });
194
+ };
195
+ var BubbleMenu = () => {
196
+ const { editor } = useCurrentEditor();
197
+ const menuRef = useRef(null);
198
+ const [pos, setPos] = useState(null);
199
+ useEffect(() => {
200
+ if (!editor) return;
201
+ const update = () => {
202
+ const { selection } = editor.state;
203
+ if (selection.empty) {
204
+ setPos(null);
205
+ return;
206
+ }
207
+ const { from, to } = selection;
208
+ const start = editor.view.coordsAtPos(from);
209
+ const end = editor.view.coordsAtPos(to);
210
+ const halfW = (menuRef.current?.offsetWidth ?? 0) / 2;
211
+ const menuH = menuRef.current?.offsetHeight ?? 0;
212
+ const rawX = (start.left + end.left) / 2;
213
+ const clampedX = Math.max(halfW + 8, Math.min(rawX, window.innerWidth - halfW - 8));
214
+ const toolbarBottom = document.querySelector("[role='toolbar']")?.getBoundingClientRect().bottom ?? 0;
215
+ const flip = start.top - menuH - 8 < toolbarBottom + 8;
216
+ setPos({ x: clampedX, y: flip ? start.bottom : start.top, flip });
217
+ };
218
+ editor.on("selectionUpdate", update);
219
+ editor.on("blur", () => setPos(null));
220
+ return () => {
221
+ editor.off("selectionUpdate", update);
222
+ editor.off("blur", () => setPos(null));
223
+ };
224
+ }, [editor]);
225
+ if (!editor) return null;
226
+ const visible = pos !== null;
227
+ return /* @__PURE__ */ jsx(
228
+ "div",
229
+ {
230
+ ref: menuRef,
231
+ className: RichTextEditor_module_default.bubbleMenu,
232
+ "aria-hidden": !visible,
233
+ style: {
234
+ position: "fixed",
235
+ left: pos?.x ?? 0,
236
+ top: pos?.y ?? 0,
237
+ transform: pos?.flip ? "translate(-50%, 8px)" : "translate(-50%, calc(-100% - 8px))",
238
+ zIndex: 50,
239
+ visibility: visible ? "visible" : "hidden",
240
+ pointerEvents: visible ? "auto" : "none"
241
+ },
242
+ children: [
243
+ { render: () => /* @__PURE__ */ jsx("strong", { children: "B" }), title: "Bold", action: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold") },
244
+ { render: () => /* @__PURE__ */ jsx("em", { children: "I" }), title: "Italic", action: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic") },
245
+ { render: () => /* @__PURE__ */ jsx("u", { children: "U" }), title: "Underline", action: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline") },
246
+ { render: () => /* @__PURE__ */ jsx("s", { children: "S" }), title: "Strikethrough", action: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike") }
247
+ ].map(({ render, title, action, active }) => /* @__PURE__ */ jsx(
248
+ "button",
249
+ {
250
+ type: "button",
251
+ title,
252
+ "aria-label": title,
253
+ "aria-pressed": active,
254
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
255
+ onMouseDown: (e) => {
256
+ e.preventDefault();
257
+ action();
258
+ },
259
+ children: render()
260
+ },
261
+ title
262
+ ))
263
+ }
264
+ );
265
+ };
266
+ var RichTextEditor = ({
267
+ value,
268
+ placeholder = "Start writing...",
269
+ readOnly = false,
270
+ minHeight = 200,
271
+ maxHeight,
272
+ accent,
273
+ extensions = [],
274
+ slotBefore,
275
+ slotAfter,
276
+ onChangeHTML,
277
+ onChangeJSON
278
+ }) => {
279
+ const accentVars = accent ? accentToCssVars(deriveAccent(accent), "rich-text-editor") : {};
280
+ const minHeightValue = typeof minHeight === "number" ? `${minHeight}px` : minHeight;
281
+ const maxHeightValue = maxHeight !== void 0 ? typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight : void 0;
282
+ return /* @__PURE__ */ jsx(
283
+ "div",
284
+ {
285
+ className: [RichTextEditor_module_default.root, readOnly ? RichTextEditor_module_default.readOnly : ""].filter(Boolean).join(" "),
286
+ style: { ...accentVars, "--rte-min-height": minHeightValue, "--rte-max-height": maxHeightValue },
287
+ children: /* @__PURE__ */ jsx(
288
+ EditorProvider,
289
+ {
290
+ extensions: [
291
+ StarterKit.configure({ heading: { levels: [1, 2, 3] } }),
292
+ Underline,
293
+ Placeholder.configure({ placeholder }),
294
+ ...extensions
295
+ ],
296
+ content: value,
297
+ editable: !readOnly,
298
+ onUpdate: ({ editor }) => {
299
+ onChangeHTML?.(editor.getHTML());
300
+ onChangeJSON?.(editor.getJSON());
301
+ },
302
+ slotBefore: !readOnly ? /* @__PURE__ */ jsx(Toolbar, { slotBefore }) : void 0,
303
+ slotAfter,
304
+ editorContainerProps: { className: RichTextEditor_module_default.editorContent },
305
+ children: !readOnly && /* @__PURE__ */ jsx(BubbleMenu, {})
306
+ }
307
+ )
308
+ }
309
+ );
310
+ };
311
+ var __defProp = Object.defineProperty;
312
+ var __export = (target, all) => {
313
+ for (var name in all)
314
+ __defProp(target, name, { get: all[name], enumerable: true });
315
+ };
316
+ function createChainableState(config) {
317
+ const { state, transaction } = config;
318
+ let { selection } = transaction;
319
+ let { doc } = transaction;
320
+ let { storedMarks } = transaction;
321
+ return {
322
+ ...state,
323
+ apply: state.apply.bind(state),
324
+ applyTransaction: state.applyTransaction.bind(state),
325
+ plugins: state.plugins,
326
+ schema: state.schema,
327
+ reconfigure: state.reconfigure.bind(state),
328
+ toJSON: state.toJSON.bind(state),
329
+ get storedMarks() {
330
+ return storedMarks;
331
+ },
332
+ get selection() {
333
+ return selection;
334
+ },
335
+ get doc() {
336
+ return doc;
337
+ },
338
+ get tr() {
339
+ selection = transaction.selection;
340
+ doc = transaction.doc;
341
+ storedMarks = transaction.storedMarks;
342
+ return transaction;
343
+ }
344
+ };
345
+ }
346
+ var CommandManager = class {
347
+ constructor(props) {
348
+ this.editor = props.editor;
349
+ this.rawCommands = this.editor.extensionManager.commands;
350
+ this.customState = props.state;
351
+ }
352
+ get hasCustomState() {
353
+ return !!this.customState;
354
+ }
355
+ get state() {
356
+ return this.customState || this.editor.state;
357
+ }
358
+ get commands() {
359
+ const { rawCommands, editor, state } = this;
360
+ const { view } = editor;
361
+ const { tr } = state;
362
+ const props = this.buildProps(tr);
363
+ return Object.fromEntries(
364
+ Object.entries(rawCommands).map(([name, command2]) => {
365
+ const method = (...args) => {
366
+ const callback = command2(...args)(props);
367
+ if (!tr.getMeta("preventDispatch") && !this.hasCustomState) {
368
+ view.dispatch(tr);
369
+ }
370
+ return callback;
371
+ };
372
+ return [name, method];
373
+ })
374
+ );
375
+ }
376
+ get chain() {
377
+ return () => this.createChain();
378
+ }
379
+ get can() {
380
+ return () => this.createCan();
381
+ }
382
+ createChain(startTr, shouldDispatch = true) {
383
+ const { rawCommands, editor, state } = this;
384
+ const { view } = editor;
385
+ const callbacks = [];
386
+ const hasStartTransaction = !!startTr;
387
+ const tr = startTr || state.tr;
388
+ const run3 = () => {
389
+ if (!hasStartTransaction && shouldDispatch && !tr.getMeta("preventDispatch") && !this.hasCustomState) {
390
+ view.dispatch(tr);
391
+ }
392
+ return callbacks.every((callback) => callback === true);
393
+ };
394
+ const chain = {
395
+ ...Object.fromEntries(
396
+ Object.entries(rawCommands).map(([name, command2]) => {
397
+ const chainedCommand = (...args) => {
398
+ const props = this.buildProps(tr, shouldDispatch);
399
+ const callback = command2(...args)(props);
400
+ callbacks.push(callback);
401
+ return chain;
402
+ };
403
+ return [name, chainedCommand];
404
+ })
405
+ ),
406
+ run: run3
407
+ };
408
+ return chain;
409
+ }
410
+ createCan(startTr) {
411
+ const { rawCommands, state } = this;
412
+ const dispatch = false;
413
+ const tr = startTr || state.tr;
414
+ const props = this.buildProps(tr, dispatch);
415
+ const formattedCommands = Object.fromEntries(
416
+ Object.entries(rawCommands).map(([name, command2]) => {
417
+ return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
418
+ })
419
+ );
420
+ return {
421
+ ...formattedCommands,
422
+ chain: () => this.createChain(tr, dispatch)
423
+ };
424
+ }
425
+ buildProps(tr, shouldDispatch = true) {
426
+ const { rawCommands, editor, state } = this;
427
+ const { view } = editor;
428
+ const props = {
429
+ tr,
430
+ editor,
431
+ view,
432
+ state: createChainableState({
433
+ state,
434
+ transaction: tr
435
+ }),
436
+ dispatch: shouldDispatch ? () => void 0 : void 0,
437
+ chain: () => this.createChain(tr, shouldDispatch),
438
+ can: () => this.createCan(tr),
439
+ get commands() {
440
+ return Object.fromEntries(
441
+ Object.entries(rawCommands).map(([name, command2]) => {
442
+ return [name, (...args) => command2(...args)(props)];
443
+ })
444
+ );
445
+ }
446
+ };
447
+ return props;
448
+ }
449
+ };
450
+ var commands_exports = {};
451
+ __export(commands_exports, {
452
+ blur: () => blur,
453
+ clearContent: () => clearContent,
454
+ clearNodes: () => clearNodes,
455
+ command: () => command,
456
+ createParagraphNear: () => createParagraphNear,
457
+ cut: () => cut,
458
+ deleteCurrentNode: () => deleteCurrentNode,
459
+ deleteNode: () => deleteNode,
460
+ deleteRange: () => deleteRange,
461
+ deleteSelection: () => deleteSelection,
462
+ enter: () => enter,
463
+ exitCode: () => exitCode,
464
+ extendMarkRange: () => extendMarkRange,
465
+ first: () => first,
466
+ focus: () => focus,
467
+ forEach: () => forEach,
468
+ insertContent: () => insertContent,
469
+ insertContentAt: () => insertContentAt,
470
+ joinBackward: () => joinBackward,
471
+ joinDown: () => joinDown,
472
+ joinForward: () => joinForward,
473
+ joinItemBackward: () => joinItemBackward,
474
+ joinItemForward: () => joinItemForward,
475
+ joinTextblockBackward: () => joinTextblockBackward,
476
+ joinTextblockForward: () => joinTextblockForward,
477
+ joinUp: () => joinUp,
478
+ keyboardShortcut: () => keyboardShortcut,
479
+ lift: () => lift,
480
+ liftEmptyBlock: () => liftEmptyBlock,
481
+ liftListItem: () => liftListItem,
482
+ newlineInCode: () => newlineInCode,
483
+ resetAttributes: () => resetAttributes,
484
+ scrollIntoView: () => scrollIntoView,
485
+ selectAll: () => selectAll,
486
+ selectNodeBackward: () => selectNodeBackward,
487
+ selectNodeForward: () => selectNodeForward,
488
+ selectParentNode: () => selectParentNode,
489
+ selectTextblockEnd: () => selectTextblockEnd,
490
+ selectTextblockStart: () => selectTextblockStart,
491
+ setContent: () => setContent,
492
+ setMark: () => setMark,
493
+ setMeta: () => setMeta,
494
+ setNode: () => setNode,
495
+ setNodeSelection: () => setNodeSelection,
496
+ setTextDirection: () => setTextDirection,
497
+ setTextSelection: () => setTextSelection,
498
+ sinkListItem: () => sinkListItem,
499
+ splitBlock: () => splitBlock,
500
+ splitListItem: () => splitListItem,
501
+ toggleList: () => toggleList,
502
+ toggleMark: () => toggleMark,
503
+ toggleNode: () => toggleNode,
504
+ toggleWrap: () => toggleWrap,
505
+ undoInputRule: () => undoInputRule,
506
+ unsetAllMarks: () => unsetAllMarks,
507
+ unsetMark: () => unsetMark,
508
+ unsetTextDirection: () => unsetTextDirection,
509
+ updateAttributes: () => updateAttributes,
510
+ wrapIn: () => wrapIn,
511
+ wrapInList: () => wrapInList
512
+ });
513
+ var blur = () => ({ editor, view }) => {
514
+ requestAnimationFrame(() => {
515
+ var _a;
516
+ if (!editor.isDestroyed) {
517
+ view.dom.blur();
518
+ (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges();
519
+ }
520
+ });
521
+ return true;
522
+ };
523
+ var clearContent = (emitUpdate = true) => ({ commands }) => {
524
+ return commands.setContent("", { emitUpdate });
525
+ };
526
+ var clearNodes = () => ({ state, tr, dispatch }) => {
527
+ const { selection } = tr;
528
+ const { ranges } = selection;
529
+ if (!dispatch) {
530
+ return true;
531
+ }
532
+ ranges.forEach(({ $from, $to }) => {
533
+ state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
534
+ if (node.type.isText) {
535
+ return;
536
+ }
537
+ const { doc, mapping } = tr;
538
+ const $mappedFrom = doc.resolve(mapping.map(pos));
539
+ const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize));
540
+ const nodeRange = $mappedFrom.blockRange($mappedTo);
541
+ if (!nodeRange) {
542
+ return;
543
+ }
544
+ const targetLiftDepth = liftTarget(nodeRange);
545
+ if (node.type.isTextblock) {
546
+ const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
547
+ tr.setNodeMarkup(nodeRange.start, defaultType);
548
+ }
549
+ if (targetLiftDepth || targetLiftDepth === 0) {
550
+ tr.lift(nodeRange, targetLiftDepth);
551
+ }
552
+ });
553
+ });
554
+ return true;
555
+ };
556
+ var command = (fn) => (props) => {
557
+ return fn(props);
558
+ };
559
+ var createParagraphNear = () => ({ state, dispatch }) => {
560
+ return createParagraphNear$1(state, dispatch);
561
+ };
562
+ var cut = (originRange, targetPos) => ({ editor, tr }) => {
563
+ const { state } = editor;
564
+ const contentSlice = state.doc.slice(originRange.from, originRange.to);
565
+ tr.deleteRange(originRange.from, originRange.to);
566
+ const newPos = tr.mapping.map(targetPos);
567
+ tr.insert(newPos, contentSlice.content);
568
+ tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))));
569
+ return true;
570
+ };
571
+ var deleteCurrentNode = () => ({ tr, dispatch }) => {
572
+ const { selection } = tr;
573
+ const currentNode = selection.$anchor.node();
574
+ if (currentNode.content.size > 0) {
575
+ return false;
576
+ }
577
+ const $pos = tr.selection.$anchor;
578
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
579
+ const node = $pos.node(depth);
580
+ if (node.type === currentNode.type) {
581
+ if (dispatch) {
582
+ const from = $pos.before(depth);
583
+ const to = $pos.after(depth);
584
+ tr.delete(from, to).scrollIntoView();
585
+ }
586
+ return true;
587
+ }
588
+ }
589
+ return false;
590
+ };
591
+ function getNodeType(nameOrType, schema) {
592
+ if (typeof nameOrType === "string") {
593
+ if (!schema.nodes[nameOrType]) {
594
+ throw Error(
595
+ `There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`
596
+ );
597
+ }
598
+ return schema.nodes[nameOrType];
599
+ }
600
+ return nameOrType;
601
+ }
602
+ var deleteNode = (typeOrName) => ({ tr, state, dispatch }) => {
603
+ const type = getNodeType(typeOrName, state.schema);
604
+ const $pos = tr.selection.$anchor;
605
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
606
+ const node = $pos.node(depth);
607
+ if (node.type === type) {
608
+ if (dispatch) {
609
+ const from = $pos.before(depth);
610
+ const to = $pos.after(depth);
611
+ tr.delete(from, to).scrollIntoView();
612
+ }
613
+ return true;
614
+ }
615
+ }
616
+ return false;
617
+ };
618
+ var deleteRange = (range) => ({ tr, dispatch }) => {
619
+ const { from, to } = range;
620
+ if (dispatch) {
621
+ tr.delete(from, to);
622
+ }
623
+ return true;
624
+ };
625
+ var hasTextContent = (nodeSpec) => {
626
+ if (!nodeSpec.content) {
627
+ return false;
628
+ }
629
+ const textRegex = /^text(\*|\+)/;
630
+ return textRegex.test(nodeSpec.content);
631
+ };
632
+ var expandSelectionForSide = ($pos, schema, side) => {
633
+ if (!$pos.parent.isInline) {
634
+ return $pos.pos;
635
+ }
636
+ if (side === "left" && $pos.pos > $pos.start() || side === "right" && $pos.pos < $pos.end()) {
637
+ return $pos.pos;
638
+ }
639
+ const parentContent = schema.nodes[$pos.parent.type.name].spec;
640
+ if (!hasTextContent(parentContent)) {
641
+ return $pos.pos;
642
+ }
643
+ return side === "left" ? $pos.start() - 1 : $pos.end() + 1;
644
+ };
645
+ var expandSelectionForInlineText = ($from, $to, schema) => {
646
+ const from = expandSelectionForSide($from, schema, "left");
647
+ const to = expandSelectionForSide($to, schema, "right");
648
+ return { from, to };
649
+ };
650
+ var deleteSelection = () => ({ state, dispatch }) => {
651
+ const { $from, $to } = state.selection;
652
+ if (state.selection.empty) {
653
+ return false;
654
+ }
655
+ const { from, to } = expandSelectionForInlineText($from, $to, state.schema);
656
+ if (dispatch) {
657
+ state.tr.deleteRange(from, to).scrollIntoView();
658
+ dispatch(state.tr);
659
+ }
660
+ return true;
661
+ };
662
+ var enter = () => ({ commands }) => {
663
+ return commands.keyboardShortcut("Enter");
664
+ };
665
+ var exitCode = () => ({ state, dispatch }) => {
666
+ return exitCode$1(state, dispatch);
667
+ };
668
+ function isRegExp(value) {
669
+ return Object.prototype.toString.call(value) === "[object RegExp]";
670
+ }
671
+ function objectIncludes(object1, object2, options = { strict: true }) {
672
+ const keys = Object.keys(object2);
673
+ if (!keys.length) {
674
+ return true;
675
+ }
676
+ return keys.every((key) => {
677
+ if (options.strict) {
678
+ return object2[key] === object1[key];
679
+ }
680
+ if (isRegExp(object2[key])) {
681
+ return object2[key].test(object1[key]);
682
+ }
683
+ return object2[key] === object1[key];
684
+ });
685
+ }
686
+ function findMarkInSet(marks, type, attributes = {}) {
687
+ return marks.find((item) => {
688
+ return item.type === type && objectIncludes(
689
+ // Only check equality for the attributes that are provided
690
+ Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])),
691
+ attributes
692
+ );
693
+ });
694
+ }
695
+ function isMarkInSet(marks, type, attributes = {}) {
696
+ return !!findMarkInSet(marks, type, attributes);
697
+ }
698
+ function getMarkRange($pos, type, attributes) {
699
+ if (!$pos || !type) {
700
+ return;
701
+ }
702
+ let start = $pos.parent.childAfter($pos.parentOffset);
703
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
704
+ start = $pos.parent.childBefore($pos.parentOffset);
705
+ }
706
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
707
+ return;
708
+ }
709
+ if (!attributes) {
710
+ const firstMark = start.node.marks.find((mark2) => mark2.type === type);
711
+ if (firstMark) {
712
+ attributes = firstMark.attrs;
713
+ }
714
+ }
715
+ const mark = findMarkInSet([...start.node.marks], type, attributes);
716
+ if (!mark) {
717
+ return;
718
+ }
719
+ let startIndex = start.index;
720
+ let startPos = $pos.start() + start.offset;
721
+ let endIndex = startIndex + 1;
722
+ let endPos = startPos + start.node.nodeSize;
723
+ while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
724
+ startIndex -= 1;
725
+ startPos -= $pos.parent.child(startIndex).nodeSize;
726
+ }
727
+ while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
728
+ endPos += $pos.parent.child(endIndex).nodeSize;
729
+ endIndex += 1;
730
+ }
731
+ return {
732
+ from: startPos,
733
+ to: endPos
734
+ };
735
+ }
736
+ function getMarkType(nameOrType, schema) {
737
+ if (typeof nameOrType === "string") {
738
+ if (!schema.marks[nameOrType]) {
739
+ throw Error(
740
+ `There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`
741
+ );
742
+ }
743
+ return schema.marks[nameOrType];
744
+ }
745
+ return nameOrType;
746
+ }
747
+ var extendMarkRange = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
748
+ const type = getMarkType(typeOrName, state.schema);
749
+ const { doc, selection } = tr;
750
+ const { $from, from, to } = selection;
751
+ if (dispatch) {
752
+ const range = getMarkRange($from, type, attributes);
753
+ if (range && range.from <= from && range.to >= to) {
754
+ const newSelection = TextSelection.create(doc, range.from, range.to);
755
+ tr.setSelection(newSelection);
756
+ }
757
+ }
758
+ return true;
759
+ };
760
+ var first = (commands) => (props) => {
761
+ const items = typeof commands === "function" ? commands(props) : commands;
762
+ for (let i = 0; i < items.length; i += 1) {
763
+ if (items[i](props)) {
764
+ return true;
765
+ }
766
+ }
767
+ return false;
768
+ };
769
+ function isTextSelection(value) {
770
+ return value instanceof TextSelection;
771
+ }
772
+ function minMax(value = 0, min = 0, max = 0) {
773
+ return Math.min(Math.max(value, min), max);
774
+ }
775
+ function resolveFocusPosition(doc, position = null) {
776
+ if (!position) {
777
+ return null;
778
+ }
779
+ const selectionAtStart = Selection.atStart(doc);
780
+ const selectionAtEnd = Selection.atEnd(doc);
781
+ if (position === "start" || position === true) {
782
+ return selectionAtStart;
783
+ }
784
+ if (position === "end") {
785
+ return selectionAtEnd;
786
+ }
787
+ const minPos = selectionAtStart.from;
788
+ const maxPos = selectionAtEnd.to;
789
+ if (position === "all") {
790
+ return TextSelection.create(
791
+ doc,
792
+ minMax(0, minPos, maxPos),
793
+ minMax(doc.content.size, minPos, maxPos)
794
+ );
795
+ }
796
+ return TextSelection.create(
797
+ doc,
798
+ minMax(position, minPos, maxPos),
799
+ minMax(position, minPos, maxPos)
800
+ );
801
+ }
802
+ function isAndroid() {
803
+ return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
804
+ }
805
+ function isiOS() {
806
+ return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(
807
+ navigator.platform
808
+ ) || // iPad on iOS 13 detection
809
+ navigator.userAgent.includes("Mac") && "ontouchend" in document;
810
+ }
811
+ function isSafari() {
812
+ return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
813
+ }
814
+ var focus = (position = null, options = {}) => ({ editor, view, tr, dispatch }) => {
815
+ options = {
816
+ scrollIntoView: true,
817
+ ...options
818
+ };
819
+ const delayedFocus = () => {
820
+ if (isiOS() || isAndroid()) {
821
+ view.dom.focus();
822
+ }
823
+ if (isSafari() && !isiOS() && !isAndroid()) {
824
+ view.dom.focus({ preventScroll: true });
825
+ }
826
+ requestAnimationFrame(() => {
827
+ if (!editor.isDestroyed) {
828
+ view.focus();
829
+ if (options == null ? void 0 : options.scrollIntoView) {
830
+ editor.commands.scrollIntoView();
831
+ }
832
+ }
833
+ });
834
+ };
835
+ try {
836
+ if (view.hasFocus() && position === null || position === false) {
837
+ return true;
838
+ }
839
+ } catch {
840
+ return false;
841
+ }
842
+ if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
843
+ delayedFocus();
844
+ return true;
845
+ }
846
+ const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection;
847
+ const isSameSelection = editor.state.selection.eq(selection);
848
+ if (dispatch) {
849
+ if (!isSameSelection) {
850
+ tr.setSelection(selection);
851
+ }
852
+ if (isSameSelection && tr.storedMarks) {
853
+ tr.setStoredMarks(tr.storedMarks);
854
+ }
855
+ delayedFocus();
856
+ }
857
+ return true;
858
+ };
859
+ var forEach = (items, fn) => (props) => {
860
+ return items.every((item, index) => fn(item, { ...props, index }));
861
+ };
862
+ var insertContent = (value, options) => ({ tr, commands }) => {
863
+ return commands.insertContentAt(
864
+ { from: tr.selection.from, to: tr.selection.to },
865
+ value,
866
+ options
867
+ );
868
+ };
869
+ var removeWhitespaces = (node) => {
870
+ const children = node.childNodes;
871
+ for (let i = children.length - 1; i >= 0; i -= 1) {
872
+ const child = children[i];
873
+ if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) {
874
+ node.removeChild(child);
875
+ } else if (child.nodeType === 1) {
876
+ removeWhitespaces(child);
877
+ }
878
+ }
879
+ return node;
880
+ };
881
+ function elementFromString(value) {
882
+ if (typeof window === "undefined") {
883
+ throw new Error(
884
+ "[tiptap error]: there is no window object available, so this function cannot be used"
885
+ );
886
+ }
887
+ const wrappedValue = `<body>${value}</body>`;
888
+ const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
889
+ return removeWhitespaces(html);
890
+ }
891
+ function createNodeFromContent(content, schema, options) {
892
+ if (content instanceof Node || content instanceof Fragment) {
893
+ return content;
894
+ }
895
+ options = {
896
+ slice: true,
897
+ parseOptions: {},
898
+ ...options
899
+ };
900
+ const isJSONContent = typeof content === "object" && content !== null;
901
+ const isTextContent = typeof content === "string";
902
+ if (isJSONContent) {
903
+ try {
904
+ const isArrayContent = Array.isArray(content) && content.length > 0;
905
+ if (isArrayContent) {
906
+ return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item)));
907
+ }
908
+ const node = schema.nodeFromJSON(content);
909
+ if (options.errorOnInvalidContent) {
910
+ node.check();
911
+ }
912
+ return node;
913
+ } catch (error) {
914
+ if (options.errorOnInvalidContent) {
915
+ throw new Error("[tiptap error]: Invalid JSON content", { cause: error });
916
+ }
917
+ console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error);
918
+ return createNodeFromContent("", schema, options);
919
+ }
920
+ }
921
+ if (isTextContent) {
922
+ if (options.errorOnInvalidContent) {
923
+ let hasInvalidContent = false;
924
+ let invalidContent = "";
925
+ const contentCheckSchema = new Schema({
926
+ topNode: schema.spec.topNode,
927
+ marks: schema.spec.marks,
928
+ // Prosemirror's schemas are executed such that: the last to execute, matches last
929
+ // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle
930
+ nodes: schema.spec.nodes.append({
931
+ __tiptap__private__unknown__catch__all__node: {
932
+ content: "inline*",
933
+ group: "block",
934
+ parseDOM: [
935
+ {
936
+ tag: "*",
937
+ getAttrs: (e) => {
938
+ hasInvalidContent = true;
939
+ invalidContent = typeof e === "string" ? e : e.outerHTML;
940
+ return null;
941
+ }
942
+ }
943
+ ]
944
+ }
945
+ })
946
+ });
947
+ if (options.slice) {
948
+ DOMParser.fromSchema(contentCheckSchema).parseSlice(
949
+ elementFromString(content),
950
+ options.parseOptions
951
+ );
952
+ } else {
953
+ DOMParser.fromSchema(contentCheckSchema).parse(
954
+ elementFromString(content),
955
+ options.parseOptions
956
+ );
957
+ }
958
+ if (options.errorOnInvalidContent && hasInvalidContent) {
959
+ throw new Error("[tiptap error]: Invalid HTML content", {
960
+ cause: new Error(`Invalid element found: ${invalidContent}`)
961
+ });
962
+ }
963
+ }
964
+ const parser = DOMParser.fromSchema(schema);
965
+ if (options.slice) {
966
+ return parser.parseSlice(elementFromString(content), options.parseOptions).content;
967
+ }
968
+ return parser.parse(elementFromString(content), options.parseOptions);
969
+ }
970
+ return createNodeFromContent("", schema, options);
971
+ }
972
+ function selectionToInsertionEnd(tr, startLen, bias) {
973
+ const last = tr.steps.length - 1;
974
+ if (last < startLen) {
975
+ return;
976
+ }
977
+ const step = tr.steps[last];
978
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
979
+ return;
980
+ }
981
+ const map = tr.mapping.maps[last];
982
+ let end = 0;
983
+ map.forEach((_from, _to, _newFrom, newTo) => {
984
+ if (end === 0) {
985
+ end = newTo;
986
+ }
987
+ });
988
+ tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
989
+ }
990
+ var isFragment = (nodeOrFragment) => {
991
+ return !("type" in nodeOrFragment);
992
+ };
993
+ var insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {
994
+ var _a;
995
+ if (dispatch) {
996
+ options = {
997
+ parseOptions: editor.options.parseOptions,
998
+ updateSelection: true,
999
+ applyInputRules: false,
1000
+ applyPasteRules: false,
1001
+ ...options
1002
+ };
1003
+ let content;
1004
+ const emitContentError = (error) => {
1005
+ editor.emit("contentError", {
1006
+ editor,
1007
+ error,
1008
+ disableCollaboration: () => {
1009
+ if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) {
1010
+ editor.storage.collaboration.isDisabled = true;
1011
+ }
1012
+ }
1013
+ });
1014
+ };
1015
+ const parseOptions = {
1016
+ preserveWhitespace: "full",
1017
+ ...options.parseOptions
1018
+ };
1019
+ if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {
1020
+ try {
1021
+ createNodeFromContent(value, editor.schema, {
1022
+ parseOptions,
1023
+ errorOnInvalidContent: true
1024
+ });
1025
+ } catch (e) {
1026
+ emitContentError(e);
1027
+ }
1028
+ }
1029
+ try {
1030
+ content = createNodeFromContent(value, editor.schema, {
1031
+ parseOptions,
1032
+ errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck
1033
+ });
1034
+ } catch (e) {
1035
+ emitContentError(e);
1036
+ return false;
1037
+ }
1038
+ let { from, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to };
1039
+ let isOnlyTextContent = true;
1040
+ let isOnlyBlockContent = true;
1041
+ const nodes = isFragment(content) ? content : [content];
1042
+ nodes.forEach((node) => {
1043
+ node.check();
1044
+ isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;
1045
+ isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;
1046
+ });
1047
+ if (from === to && isOnlyBlockContent) {
1048
+ const { parent } = tr.doc.resolve(from);
1049
+ const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
1050
+ if (isEmptyTextBlock) {
1051
+ from -= 1;
1052
+ to += 1;
1053
+ }
1054
+ }
1055
+ let newContent;
1056
+ if (isOnlyTextContent) {
1057
+ if (Array.isArray(value)) {
1058
+ newContent = value.map((v) => v.text || "").join("");
1059
+ } else if (value instanceof Fragment) {
1060
+ let text = "";
1061
+ value.forEach((node) => {
1062
+ if (node.text) {
1063
+ text += node.text;
1064
+ }
1065
+ });
1066
+ newContent = text;
1067
+ } else if (typeof value === "object" && !!value && !!value.text) {
1068
+ newContent = value.text;
1069
+ } else {
1070
+ newContent = value;
1071
+ }
1072
+ tr.insertText(newContent, from, to);
1073
+ } else {
1074
+ newContent = content;
1075
+ const $from = tr.doc.resolve(from);
1076
+ const $fromNode = $from.node();
1077
+ const fromSelectionAtStart = $from.parentOffset === 0;
1078
+ const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock;
1079
+ const hasContent = $fromNode.content.size > 0;
1080
+ if (fromSelectionAtStart && isTextSelection2 && hasContent && isOnlyBlockContent) {
1081
+ from = Math.max(0, from - 1);
1082
+ }
1083
+ tr.replaceWith(from, to, newContent);
1084
+ }
1085
+ if (options.updateSelection) {
1086
+ selectionToInsertionEnd(tr, tr.steps.length - 1, -1);
1087
+ }
1088
+ if (options.applyInputRules) {
1089
+ tr.setMeta("applyInputRules", { from, text: newContent });
1090
+ }
1091
+ if (options.applyPasteRules) {
1092
+ tr.setMeta("applyPasteRules", { from, text: newContent });
1093
+ }
1094
+ }
1095
+ return true;
1096
+ };
1097
+ var joinUp = () => ({ state, dispatch }) => {
1098
+ return joinUp$1(state, dispatch);
1099
+ };
1100
+ var joinDown = () => ({ state, dispatch }) => {
1101
+ return joinDown$1(state, dispatch);
1102
+ };
1103
+ var joinBackward = () => ({ state, dispatch }) => {
1104
+ return joinBackward$1(state, dispatch);
1105
+ };
1106
+ var joinForward = () => ({ state, dispatch }) => {
1107
+ return joinForward$1(state, dispatch);
1108
+ };
1109
+ var joinItemBackward = () => ({ state, dispatch, tr }) => {
1110
+ try {
1111
+ const point = joinPoint(state.doc, state.selection.$from.pos, -1);
1112
+ if (point === null || point === void 0) {
1113
+ return false;
1114
+ }
1115
+ tr.join(point, 2);
1116
+ if (dispatch) {
1117
+ dispatch(tr);
1118
+ }
1119
+ return true;
1120
+ } catch {
1121
+ return false;
1122
+ }
1123
+ };
1124
+ var joinItemForward = () => ({ state, dispatch, tr }) => {
1125
+ try {
1126
+ const point = joinPoint(state.doc, state.selection.$from.pos, 1);
1127
+ if (point === null || point === void 0) {
1128
+ return false;
1129
+ }
1130
+ tr.join(point, 2);
1131
+ if (dispatch) {
1132
+ dispatch(tr);
1133
+ }
1134
+ return true;
1135
+ } catch {
1136
+ return false;
1137
+ }
1138
+ };
1139
+ var joinTextblockBackward = () => ({ state, dispatch }) => {
1140
+ return joinTextblockBackward$1(state, dispatch);
1141
+ };
1142
+ var joinTextblockForward = () => ({ state, dispatch }) => {
1143
+ return joinTextblockForward$1(state, dispatch);
1144
+ };
1145
+ function isMacOS() {
1146
+ return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
1147
+ }
1148
+ function normalizeKeyName(name) {
1149
+ const parts = name.split(/-(?!$)/);
1150
+ let result = parts[parts.length - 1];
1151
+ if (result === "Space") {
1152
+ result = " ";
1153
+ }
1154
+ let alt;
1155
+ let ctrl;
1156
+ let shift;
1157
+ let meta;
1158
+ for (let i = 0; i < parts.length - 1; i += 1) {
1159
+ const mod = parts[i];
1160
+ if (/^(cmd|meta|m)$/i.test(mod)) {
1161
+ meta = true;
1162
+ } else if (/^a(lt)?$/i.test(mod)) {
1163
+ alt = true;
1164
+ } else if (/^(c|ctrl|control)$/i.test(mod)) {
1165
+ ctrl = true;
1166
+ } else if (/^s(hift)?$/i.test(mod)) {
1167
+ shift = true;
1168
+ } else if (/^mod$/i.test(mod)) {
1169
+ if (isiOS() || isMacOS()) {
1170
+ meta = true;
1171
+ } else {
1172
+ ctrl = true;
1173
+ }
1174
+ } else {
1175
+ throw new Error(`Unrecognized modifier name: ${mod}`);
1176
+ }
1177
+ }
1178
+ if (alt) {
1179
+ result = `Alt-${result}`;
1180
+ }
1181
+ if (ctrl) {
1182
+ result = `Ctrl-${result}`;
1183
+ }
1184
+ if (meta) {
1185
+ result = `Meta-${result}`;
1186
+ }
1187
+ if (shift) {
1188
+ result = `Shift-${result}`;
1189
+ }
1190
+ return result;
1191
+ }
1192
+ var keyboardShortcut = (name) => ({ editor, view, tr, dispatch }) => {
1193
+ const keys = normalizeKeyName(name).split(/-(?!$)/);
1194
+ const key = keys.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
1195
+ const event = new KeyboardEvent("keydown", {
1196
+ key: key === "Space" ? " " : key,
1197
+ altKey: keys.includes("Alt"),
1198
+ ctrlKey: keys.includes("Ctrl"),
1199
+ metaKey: keys.includes("Meta"),
1200
+ shiftKey: keys.includes("Shift"),
1201
+ bubbles: true,
1202
+ cancelable: true
1203
+ });
1204
+ const capturedTransaction = editor.captureTransaction(() => {
1205
+ view.someProp("handleKeyDown", (f) => f(view, event));
1206
+ });
1207
+ capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => {
1208
+ const newStep = step.map(tr.mapping);
1209
+ if (newStep && dispatch) {
1210
+ tr.maybeStep(newStep);
1211
+ }
1212
+ });
1213
+ return true;
1214
+ };
1215
+ function isNodeActive(state, typeOrName, attributes = {}) {
1216
+ const { from, to, empty } = state.selection;
1217
+ const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
1218
+ const nodeRanges = [];
1219
+ state.doc.nodesBetween(from, to, (node, pos) => {
1220
+ if (node.isText) {
1221
+ return;
1222
+ }
1223
+ const relativeFrom = Math.max(from, pos);
1224
+ const relativeTo = Math.min(to, pos + node.nodeSize);
1225
+ nodeRanges.push({
1226
+ node,
1227
+ from: relativeFrom,
1228
+ to: relativeTo
1229
+ });
1230
+ });
1231
+ const selectionRange = to - from;
1232
+ const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
1233
+ if (!type) {
1234
+ return true;
1235
+ }
1236
+ return type.name === nodeRange.node.type.name;
1237
+ }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
1238
+ if (empty) {
1239
+ return !!matchedNodeRanges.length;
1240
+ }
1241
+ const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
1242
+ return range >= selectionRange;
1243
+ }
1244
+ var lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1245
+ const type = getNodeType(typeOrName, state.schema);
1246
+ const isActive2 = isNodeActive(state, type, attributes);
1247
+ if (!isActive2) {
1248
+ return false;
1249
+ }
1250
+ return lift$1(state, dispatch);
1251
+ };
1252
+ var liftEmptyBlock = () => ({ state, dispatch }) => {
1253
+ return liftEmptyBlock$1(state, dispatch);
1254
+ };
1255
+ var liftListItem = (typeOrName) => ({ state, dispatch }) => {
1256
+ const type = getNodeType(typeOrName, state.schema);
1257
+ return liftListItem$1(type)(state, dispatch);
1258
+ };
1259
+ var newlineInCode = () => ({ state, dispatch }) => {
1260
+ return newlineInCode$1(state, dispatch);
1261
+ };
1262
+ function getSchemaTypeNameByName(name, schema) {
1263
+ if (schema.nodes[name]) {
1264
+ return "node";
1265
+ }
1266
+ if (schema.marks[name]) {
1267
+ return "mark";
1268
+ }
1269
+ return null;
1270
+ }
1271
+ function deleteProps(obj, propOrProps) {
1272
+ const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
1273
+ return Object.keys(obj).reduce((newObj, prop) => {
1274
+ if (!props.includes(prop)) {
1275
+ newObj[prop] = obj[prop];
1276
+ }
1277
+ return newObj;
1278
+ }, {});
1279
+ }
1280
+ var resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
1281
+ let nodeType = null;
1282
+ let markType = null;
1283
+ const schemaType = getSchemaTypeNameByName(
1284
+ typeof typeOrName === "string" ? typeOrName : typeOrName.name,
1285
+ state.schema
1286
+ );
1287
+ if (!schemaType) {
1288
+ return false;
1289
+ }
1290
+ if (schemaType === "node") {
1291
+ nodeType = getNodeType(typeOrName, state.schema);
1292
+ }
1293
+ if (schemaType === "mark") {
1294
+ markType = getMarkType(typeOrName, state.schema);
1295
+ }
1296
+ let canReset = false;
1297
+ tr.selection.ranges.forEach((range) => {
1298
+ state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
1299
+ if (nodeType && nodeType === node.type) {
1300
+ canReset = true;
1301
+ if (dispatch) {
1302
+ tr.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes));
1303
+ }
1304
+ }
1305
+ if (markType && node.marks.length) {
1306
+ node.marks.forEach((mark) => {
1307
+ if (markType === mark.type) {
1308
+ canReset = true;
1309
+ if (dispatch) {
1310
+ tr.addMark(
1311
+ pos,
1312
+ pos + node.nodeSize,
1313
+ markType.create(deleteProps(mark.attrs, attributes))
1314
+ );
1315
+ }
1316
+ }
1317
+ });
1318
+ }
1319
+ });
1320
+ });
1321
+ return canReset;
1322
+ };
1323
+ var scrollIntoView = () => ({ tr, dispatch }) => {
1324
+ if (dispatch) {
1325
+ tr.scrollIntoView();
1326
+ }
1327
+ return true;
1328
+ };
1329
+ var selectAll = () => ({ tr, dispatch }) => {
1330
+ if (dispatch) {
1331
+ const selection = new AllSelection(tr.doc);
1332
+ tr.setSelection(selection);
1333
+ }
1334
+ return true;
1335
+ };
1336
+ var selectNodeBackward = () => ({ state, dispatch }) => {
1337
+ return selectNodeBackward$1(state, dispatch);
1338
+ };
1339
+ var selectNodeForward = () => ({ state, dispatch }) => {
1340
+ return selectNodeForward$1(state, dispatch);
1341
+ };
1342
+ var selectParentNode = () => ({ state, dispatch }) => {
1343
+ return selectParentNode$1(state, dispatch);
1344
+ };
1345
+ var selectTextblockEnd = () => ({ state, dispatch }) => {
1346
+ return selectTextblockEnd$1(state, dispatch);
1347
+ };
1348
+ var selectTextblockStart = () => ({ state, dispatch }) => {
1349
+ return selectTextblockStart$1(state, dispatch);
1350
+ };
1351
+ function createDocument(content, schema, parseOptions = {}, options = {}) {
1352
+ return createNodeFromContent(content, schema, {
1353
+ slice: false,
1354
+ parseOptions,
1355
+ errorOnInvalidContent: options.errorOnInvalidContent
1356
+ });
1357
+ }
1358
+ var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr, dispatch, commands }) => {
1359
+ const { doc } = tr;
1360
+ if (parseOptions.preserveWhitespace !== "full") {
1361
+ const document2 = createDocument(content, editor.schema, parseOptions, {
1362
+ errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
1363
+ });
1364
+ if (dispatch) {
1365
+ tr.replaceWith(0, doc.content.size, document2).setMeta("preventUpdate", !emitUpdate);
1366
+ }
1367
+ return true;
1368
+ }
1369
+ if (dispatch) {
1370
+ tr.setMeta("preventUpdate", !emitUpdate);
1371
+ }
1372
+ return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {
1373
+ parseOptions,
1374
+ errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
1375
+ });
1376
+ };
1377
+ function getMarkAttributes(state, typeOrName) {
1378
+ const type = getMarkType(typeOrName, state.schema);
1379
+ const { from, to, empty } = state.selection;
1380
+ const marks = [];
1381
+ if (empty) {
1382
+ if (state.storedMarks) {
1383
+ marks.push(...state.storedMarks);
1384
+ }
1385
+ marks.push(...state.selection.$head.marks());
1386
+ } else {
1387
+ state.doc.nodesBetween(from, to, (node) => {
1388
+ marks.push(...node.marks);
1389
+ });
1390
+ }
1391
+ const mark = marks.find((markItem) => markItem.type.name === type.name);
1392
+ if (!mark) {
1393
+ return {};
1394
+ }
1395
+ return { ...mark.attrs };
1396
+ }
1397
+ function combineTransactionSteps(oldDoc, transactions) {
1398
+ const transform = new Transform(oldDoc);
1399
+ transactions.forEach((transaction) => {
1400
+ transaction.steps.forEach((step) => {
1401
+ transform.step(step);
1402
+ });
1403
+ });
1404
+ return transform;
1405
+ }
1406
+ function defaultBlockAt(match) {
1407
+ for (let i = 0; i < match.edgeCount; i += 1) {
1408
+ const { type } = match.edge(i);
1409
+ if (type.isTextblock && !type.hasRequiredAttrs()) {
1410
+ return type;
1411
+ }
1412
+ }
1413
+ return null;
1414
+ }
1415
+ function findParentNodeClosestToPos($pos, predicate) {
1416
+ for (let i = $pos.depth; i > 0; i -= 1) {
1417
+ const node = $pos.node(i);
1418
+ if (predicate(node)) {
1419
+ return {
1420
+ pos: i > 0 ? $pos.before(i) : 0,
1421
+ start: $pos.start(i),
1422
+ depth: i,
1423
+ node
1424
+ };
1425
+ }
1426
+ }
1427
+ }
1428
+ function findParentNode(predicate) {
1429
+ return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
1430
+ }
1431
+ function getExtensionField(extension, field, context) {
1432
+ if (extension.config[field] === void 0 && extension.parent) {
1433
+ return getExtensionField(extension.parent, field, context);
1434
+ }
1435
+ if (typeof extension.config[field] === "function") {
1436
+ const value = extension.config[field].bind({
1437
+ ...context,
1438
+ parent: extension.parent ? getExtensionField(extension.parent, field, context) : null
1439
+ });
1440
+ return value;
1441
+ }
1442
+ return extension.config[field];
1443
+ }
1444
+ function isFunction(value) {
1445
+ return typeof value === "function";
1446
+ }
1447
+ function callOrReturn(value, context = void 0, ...props) {
1448
+ if (isFunction(value)) {
1449
+ if (context) {
1450
+ return value.bind(context)(...props);
1451
+ }
1452
+ return value(...props);
1453
+ }
1454
+ return value;
1455
+ }
1456
+ function splitExtensions(extensions) {
1457
+ const baseExtensions = extensions.filter(
1458
+ (extension) => extension.type === "extension"
1459
+ );
1460
+ const nodeExtensions = extensions.filter((extension) => extension.type === "node");
1461
+ const markExtensions = extensions.filter((extension) => extension.type === "mark");
1462
+ return {
1463
+ baseExtensions,
1464
+ nodeExtensions,
1465
+ markExtensions
1466
+ };
1467
+ }
1468
+ function splitStyleDeclarations(styles) {
1469
+ const result = [];
1470
+ let current = "";
1471
+ let inSingleQuote = false;
1472
+ let inDoubleQuote = false;
1473
+ let parenDepth = 0;
1474
+ const length = styles.length;
1475
+ for (let i = 0; i < length; i += 1) {
1476
+ const char = styles[i];
1477
+ if (char === "'" && !inDoubleQuote) {
1478
+ inSingleQuote = !inSingleQuote;
1479
+ current += char;
1480
+ continue;
1481
+ }
1482
+ if (char === '"' && !inSingleQuote) {
1483
+ inDoubleQuote = !inDoubleQuote;
1484
+ current += char;
1485
+ continue;
1486
+ }
1487
+ if (!inSingleQuote && !inDoubleQuote) {
1488
+ if (char === "(") {
1489
+ parenDepth += 1;
1490
+ current += char;
1491
+ continue;
1492
+ }
1493
+ if (char === ")" && parenDepth > 0) {
1494
+ parenDepth -= 1;
1495
+ current += char;
1496
+ continue;
1497
+ }
1498
+ if (char === ";" && parenDepth === 0) {
1499
+ result.push(current);
1500
+ current = "";
1501
+ continue;
1502
+ }
1503
+ }
1504
+ current += char;
1505
+ }
1506
+ if (current) {
1507
+ result.push(current);
1508
+ }
1509
+ return result;
1510
+ }
1511
+ function parseStyleEntries(styles) {
1512
+ const pairs = [];
1513
+ const declarations = splitStyleDeclarations(styles || "");
1514
+ const numDeclarations = declarations.length;
1515
+ for (let i = 0; i < numDeclarations; i += 1) {
1516
+ const declaration = declarations[i];
1517
+ const firstColonIndex = declaration.indexOf(":");
1518
+ if (firstColonIndex === -1) {
1519
+ continue;
1520
+ }
1521
+ const property = declaration.slice(0, firstColonIndex).trim();
1522
+ const value = declaration.slice(firstColonIndex + 1).trim();
1523
+ if (property && value) {
1524
+ pairs.push([property, value]);
1525
+ }
1526
+ }
1527
+ return pairs;
1528
+ }
1529
+ function mergeAttributes(...objects) {
1530
+ return objects.filter((item) => !!item).reduce((items, item) => {
1531
+ const mergedAttributes = { ...items };
1532
+ Object.entries(item).forEach(([key, value]) => {
1533
+ const exists = mergedAttributes[key];
1534
+ if (!exists) {
1535
+ mergedAttributes[key] = value;
1536
+ return;
1537
+ }
1538
+ if (key === "class") {
1539
+ const valueClasses = value ? String(value).split(" ") : [];
1540
+ const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : [];
1541
+ const insertClasses = valueClasses.filter(
1542
+ (valueClass) => !existingClasses.includes(valueClass)
1543
+ );
1544
+ mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" ");
1545
+ } else if (key === "style") {
1546
+ const styleMap = new Map([
1547
+ ...parseStyleEntries(mergedAttributes[key]),
1548
+ ...parseStyleEntries(value)
1549
+ ]);
1550
+ mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; ");
1551
+ } else {
1552
+ mergedAttributes[key] = value;
1553
+ }
1554
+ });
1555
+ return mergedAttributes;
1556
+ }, {});
1557
+ }
1558
+ function getTextBetween(startNode, range, options) {
1559
+ const { from, to } = range;
1560
+ const { blockSeparator = "\n\n", textSerializers = {} } = options || {};
1561
+ let text = "";
1562
+ startNode.nodesBetween(from, to, (node, pos, parent, index) => {
1563
+ var _a;
1564
+ if (node.isBlock && pos > from) {
1565
+ text += blockSeparator;
1566
+ }
1567
+ const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name];
1568
+ if (textSerializer) {
1569
+ if (parent) {
1570
+ text += textSerializer({
1571
+ node,
1572
+ pos,
1573
+ parent,
1574
+ index,
1575
+ range
1576
+ });
1577
+ }
1578
+ return false;
1579
+ }
1580
+ if (node.isText) {
1581
+ text += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos);
1582
+ }
1583
+ });
1584
+ return text;
1585
+ }
1586
+ function getTextSerializersFromSchema(schema) {
1587
+ return Object.fromEntries(
1588
+ Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText])
1589
+ );
1590
+ }
1591
+ function removeDuplicates(array, by = JSON.stringify) {
1592
+ const seen = {};
1593
+ return array.filter((item) => {
1594
+ const key = by(item);
1595
+ return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true;
1596
+ });
1597
+ }
1598
+ function simplifyChangedRanges(changes) {
1599
+ const uniqueChanges = removeDuplicates(changes);
1600
+ return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => {
1601
+ const rest = uniqueChanges.filter((_, i) => i !== index);
1602
+ return !rest.some((otherChange) => {
1603
+ return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to;
1604
+ });
1605
+ });
1606
+ }
1607
+ function getChangedRanges(transform) {
1608
+ const { mapping, steps } = transform;
1609
+ const changes = [];
1610
+ mapping.maps.forEach((stepMap, index) => {
1611
+ const ranges = [];
1612
+ if (!stepMap.ranges.length) {
1613
+ const { from, to } = steps[index];
1614
+ if (from === void 0 || to === void 0) {
1615
+ return;
1616
+ }
1617
+ ranges.push({ from, to });
1618
+ } else {
1619
+ stepMap.forEach((from, to) => {
1620
+ ranges.push({ from, to });
1621
+ });
1622
+ }
1623
+ ranges.forEach(({ from, to }) => {
1624
+ const newStart = mapping.slice(index).map(from, -1);
1625
+ const newEnd = mapping.slice(index).map(to);
1626
+ const oldStart = mapping.invert().map(newStart, -1);
1627
+ const oldEnd = mapping.invert().map(newEnd);
1628
+ changes.push({
1629
+ oldRange: {
1630
+ from: oldStart,
1631
+ to: oldEnd
1632
+ },
1633
+ newRange: {
1634
+ from: newStart,
1635
+ to: newEnd
1636
+ }
1637
+ });
1638
+ });
1639
+ });
1640
+ return simplifyChangedRanges(changes);
1641
+ }
1642
+ function getSplittedAttributes(extensionAttributes, typeName, attributes) {
1643
+ return Object.fromEntries(
1644
+ Object.entries(attributes).filter(([name]) => {
1645
+ const extensionAttribute = extensionAttributes.find((item) => {
1646
+ return item.type === typeName && item.name === name;
1647
+ });
1648
+ if (!extensionAttribute) {
1649
+ return false;
1650
+ }
1651
+ return extensionAttribute.attribute.keepOnSplit;
1652
+ })
1653
+ );
1654
+ }
1655
+ function isMarkActive(state, typeOrName, attributes = {}) {
1656
+ const { empty, ranges } = state.selection;
1657
+ const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
1658
+ if (empty) {
1659
+ return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => {
1660
+ if (!type) {
1661
+ return true;
1662
+ }
1663
+ return type.name === mark.type.name;
1664
+ }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false }));
1665
+ }
1666
+ let selectionRange = 0;
1667
+ const markRanges = [];
1668
+ ranges.forEach(({ $from, $to }) => {
1669
+ const from = $from.pos;
1670
+ const to = $to.pos;
1671
+ state.doc.nodesBetween(from, to, (node, pos) => {
1672
+ if (type && node.inlineContent && !node.type.allowsMarkType(type)) {
1673
+ return false;
1674
+ }
1675
+ if (!node.isText && !node.marks.length) {
1676
+ return;
1677
+ }
1678
+ const relativeFrom = Math.max(from, pos);
1679
+ const relativeTo = Math.min(to, pos + node.nodeSize);
1680
+ const range2 = relativeTo - relativeFrom;
1681
+ selectionRange += range2;
1682
+ markRanges.push(
1683
+ ...node.marks.map((mark) => ({
1684
+ mark,
1685
+ from: relativeFrom,
1686
+ to: relativeTo
1687
+ }))
1688
+ );
1689
+ });
1690
+ });
1691
+ if (selectionRange === 0) {
1692
+ return false;
1693
+ }
1694
+ const matchedRange = markRanges.filter((markRange) => {
1695
+ if (!type) {
1696
+ return true;
1697
+ }
1698
+ return type.name === markRange.mark.type.name;
1699
+ }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1700
+ const excludedRange = markRanges.filter((markRange) => {
1701
+ if (!type) {
1702
+ return true;
1703
+ }
1704
+ return markRange.mark.type !== type && markRange.mark.type.excludes(type);
1705
+ }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1706
+ const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
1707
+ return range >= selectionRange;
1708
+ }
1709
+ function isList(name, extensions) {
1710
+ const { nodeExtensions } = splitExtensions(extensions);
1711
+ const extension = nodeExtensions.find((item) => item.name === name);
1712
+ if (!extension) {
1713
+ return false;
1714
+ }
1715
+ const context = {
1716
+ name: extension.name,
1717
+ options: extension.options,
1718
+ storage: extension.storage
1719
+ };
1720
+ const group = callOrReturn(getExtensionField(extension, "group", context));
1721
+ if (typeof group !== "string") {
1722
+ return false;
1723
+ }
1724
+ return group.split(" ").includes("list");
1725
+ }
1726
+ function isNodeEmpty(node, {
1727
+ checkChildren = true,
1728
+ ignoreWhitespace = false
1729
+ } = {}) {
1730
+ var _a;
1731
+ if (ignoreWhitespace) {
1732
+ if (node.type.name === "hardBreak") {
1733
+ return true;
1734
+ }
1735
+ if (node.isText) {
1736
+ return !/\S/.test((_a = node.text) != null ? _a : "");
1737
+ }
1738
+ }
1739
+ if (node.isText) {
1740
+ return !node.text;
1741
+ }
1742
+ if (node.isAtom || node.isLeaf) {
1743
+ return false;
1744
+ }
1745
+ if (node.content.childCount === 0) {
1746
+ return true;
1747
+ }
1748
+ if (checkChildren) {
1749
+ let isContentEmpty = true;
1750
+ node.content.forEach((childNode) => {
1751
+ if (isContentEmpty === false) {
1752
+ return;
1753
+ }
1754
+ if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
1755
+ isContentEmpty = false;
1756
+ }
1757
+ });
1758
+ return isContentEmpty;
1759
+ }
1760
+ return false;
1761
+ }
1762
+ function canSetMark(state, tr, newMarkType) {
1763
+ var _a;
1764
+ const { selection } = tr;
1765
+ let cursor = null;
1766
+ if (isTextSelection(selection)) {
1767
+ cursor = selection.$cursor;
1768
+ }
1769
+ if (cursor) {
1770
+ const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks();
1771
+ const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType);
1772
+ return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType)));
1773
+ }
1774
+ const { ranges } = selection;
1775
+ return ranges.some(({ $from, $to }) => {
1776
+ let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
1777
+ state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {
1778
+ if (someNodeSupportsMark) {
1779
+ return false;
1780
+ }
1781
+ if (node.isInline) {
1782
+ const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);
1783
+ const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
1784
+ someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
1785
+ }
1786
+ return !someNodeSupportsMark;
1787
+ });
1788
+ return someNodeSupportsMark;
1789
+ });
1790
+ }
1791
+ var setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1792
+ const { selection } = tr;
1793
+ const { empty, ranges } = selection;
1794
+ const type = getMarkType(typeOrName, state.schema);
1795
+ if (dispatch) {
1796
+ if (empty) {
1797
+ const oldAttributes = getMarkAttributes(state, type);
1798
+ tr.addStoredMark(
1799
+ type.create({
1800
+ ...oldAttributes,
1801
+ ...attributes
1802
+ })
1803
+ );
1804
+ } else {
1805
+ ranges.forEach((range) => {
1806
+ const from = range.$from.pos;
1807
+ const to = range.$to.pos;
1808
+ state.doc.nodesBetween(from, to, (node, pos) => {
1809
+ const trimmedFrom = Math.max(pos, from);
1810
+ const trimmedTo = Math.min(pos + node.nodeSize, to);
1811
+ const someHasMark = node.marks.find((mark) => mark.type === type);
1812
+ if (someHasMark) {
1813
+ node.marks.forEach((mark) => {
1814
+ if (type === mark.type) {
1815
+ tr.addMark(
1816
+ trimmedFrom,
1817
+ trimmedTo,
1818
+ type.create({
1819
+ ...mark.attrs,
1820
+ ...attributes
1821
+ })
1822
+ );
1823
+ }
1824
+ });
1825
+ } else {
1826
+ tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));
1827
+ }
1828
+ });
1829
+ });
1830
+ }
1831
+ }
1832
+ return canSetMark(state, tr, type);
1833
+ };
1834
+ var setMeta = (key, value) => ({ tr }) => {
1835
+ tr.setMeta(key, value);
1836
+ return true;
1837
+ };
1838
+ var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
1839
+ const type = getNodeType(typeOrName, state.schema);
1840
+ let attributesToCopy;
1841
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
1842
+ attributesToCopy = state.selection.$anchor.parent.attrs;
1843
+ }
1844
+ if (!type.isTextblock) {
1845
+ console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
1846
+ return false;
1847
+ }
1848
+ return chain().command(({ commands }) => {
1849
+ const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state);
1850
+ if (canSetBlock) {
1851
+ return true;
1852
+ }
1853
+ return commands.clearNodes();
1854
+ }).command(({ state: updatedState }) => {
1855
+ return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
1856
+ }).run();
1857
+ };
1858
+ var setNodeSelection = (position) => ({ tr, dispatch }) => {
1859
+ if (dispatch) {
1860
+ const { doc } = tr;
1861
+ const from = minMax(position, 0, doc.content.size);
1862
+ const selection = NodeSelection.create(doc, from);
1863
+ tr.setSelection(selection);
1864
+ }
1865
+ return true;
1866
+ };
1867
+ var setTextDirection = (direction, position) => ({ tr, state, dispatch }) => {
1868
+ const { selection } = state;
1869
+ let from;
1870
+ let to;
1871
+ if (typeof position === "number") {
1872
+ from = position;
1873
+ to = position;
1874
+ } else if (position && "from" in position && "to" in position) {
1875
+ from = position.from;
1876
+ to = position.to;
1877
+ } else {
1878
+ from = selection.from;
1879
+ to = selection.to;
1880
+ }
1881
+ if (dispatch) {
1882
+ tr.doc.nodesBetween(from, to, (node, pos) => {
1883
+ if (node.isText) {
1884
+ return;
1885
+ }
1886
+ tr.setNodeMarkup(pos, void 0, {
1887
+ ...node.attrs,
1888
+ dir: direction
1889
+ });
1890
+ });
1891
+ }
1892
+ return true;
1893
+ };
1894
+ var setTextSelection = (position) => ({ tr, dispatch }) => {
1895
+ if (dispatch) {
1896
+ const { doc } = tr;
1897
+ const { from, to } = typeof position === "number" ? { from: position, to: position } : position;
1898
+ const minPos = TextSelection.atStart(doc).from;
1899
+ const maxPos = TextSelection.atEnd(doc).to;
1900
+ const resolvedFrom = minMax(from, minPos, maxPos);
1901
+ const resolvedEnd = minMax(to, minPos, maxPos);
1902
+ const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd);
1903
+ tr.setSelection(selection);
1904
+ }
1905
+ return true;
1906
+ };
1907
+ var sinkListItem = (typeOrName) => ({ state, dispatch }) => {
1908
+ const type = getNodeType(typeOrName, state.schema);
1909
+ return sinkListItem$1(type)(state, dispatch);
1910
+ };
1911
+ function ensureMarks(state, splittableMarks) {
1912
+ const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
1913
+ if (marks) {
1914
+ const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name));
1915
+ state.tr.ensureMarks(filteredMarks);
1916
+ }
1917
+ }
1918
+ var splitBlock = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor }) => {
1919
+ const { selection, doc } = tr;
1920
+ const { $from, $to } = selection;
1921
+ const extensionAttributes = editor.extensionManager.attributes;
1922
+ const newAttributes = getSplittedAttributes(
1923
+ extensionAttributes,
1924
+ $from.node().type.name,
1925
+ $from.node().attrs
1926
+ );
1927
+ if (selection instanceof NodeSelection && selection.node.isBlock) {
1928
+ if (!$from.parentOffset || !canSplit(doc, $from.pos)) {
1929
+ return false;
1930
+ }
1931
+ if (dispatch) {
1932
+ if (keepMarks) {
1933
+ ensureMarks(state, editor.extensionManager.splittableMarks);
1934
+ }
1935
+ tr.split($from.pos).scrollIntoView();
1936
+ }
1937
+ return true;
1938
+ }
1939
+ if (!$from.parent.isBlock) {
1940
+ return false;
1941
+ }
1942
+ const atEnd = $to.parentOffset === $to.parent.content.size;
1943
+ const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
1944
+ let types = atEnd && deflt ? [
1945
+ {
1946
+ type: deflt,
1947
+ attrs: newAttributes
1948
+ }
1949
+ ] : void 0;
1950
+ let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
1951
+ if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
1952
+ can = true;
1953
+ types = deflt ? [
1954
+ {
1955
+ type: deflt,
1956
+ attrs: newAttributes
1957
+ }
1958
+ ] : void 0;
1959
+ }
1960
+ if (dispatch) {
1961
+ if (can) {
1962
+ if (selection instanceof TextSelection) {
1963
+ tr.deleteSelection();
1964
+ }
1965
+ tr.split(tr.mapping.map($from.pos), 1, types);
1966
+ if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {
1967
+ const first2 = tr.mapping.map($from.before());
1968
+ const $first = tr.doc.resolve(first2);
1969
+ if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
1970
+ tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
1971
+ }
1972
+ }
1973
+ }
1974
+ if (keepMarks) {
1975
+ ensureMarks(state, editor.extensionManager.splittableMarks);
1976
+ }
1977
+ tr.scrollIntoView();
1978
+ }
1979
+ return can;
1980
+ };
1981
+ var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr, state, dispatch, editor }) => {
1982
+ var _a;
1983
+ const type = getNodeType(typeOrName, state.schema);
1984
+ const { $from, $to } = state.selection;
1985
+ const node = state.selection.node;
1986
+ if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
1987
+ return false;
1988
+ }
1989
+ const grandParent = $from.node(-1);
1990
+ if (grandParent.type !== type) {
1991
+ return false;
1992
+ }
1993
+ const extensionAttributes = editor.extensionManager.attributes;
1994
+ if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
1995
+ if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
1996
+ return false;
1997
+ }
1998
+ if (dispatch) {
1999
+ let wrap = Fragment.empty;
2000
+ const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
2001
+ for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
2002
+ wrap = Fragment.from($from.node(d).copy(wrap));
2003
+ }
2004
+ const depthAfter = (
2005
+ // oxlint-disable-next-line no-nested-ternary
2006
+ $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3
2007
+ );
2008
+ const newNextTypeAttributes2 = {
2009
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
2010
+ ...overrideAttrs
2011
+ };
2012
+ const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0;
2013
+ wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType2) || void 0));
2014
+ const start = $from.before($from.depth - (depthBefore - 1));
2015
+ tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));
2016
+ let sel = -1;
2017
+ tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {
2018
+ if (sel > -1) {
2019
+ return false;
2020
+ }
2021
+ if (n.isTextblock && n.content.size === 0) {
2022
+ sel = pos + 1;
2023
+ }
2024
+ });
2025
+ if (sel > -1) {
2026
+ tr.setSelection(TextSelection.near(tr.doc.resolve(sel)));
2027
+ }
2028
+ tr.scrollIntoView();
2029
+ }
2030
+ return true;
2031
+ }
2032
+ const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
2033
+ const newTypeAttributes = {
2034
+ ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
2035
+ ...overrideAttrs
2036
+ };
2037
+ const newNextTypeAttributes = {
2038
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
2039
+ ...overrideAttrs
2040
+ };
2041
+ tr.delete($from.pos, $to.pos);
2042
+ const types = nextType ? [
2043
+ { type, attrs: newTypeAttributes },
2044
+ { type: nextType, attrs: newNextTypeAttributes }
2045
+ ] : [{ type, attrs: newTypeAttributes }];
2046
+ if (!canSplit(tr.doc, $from.pos, 2)) {
2047
+ return false;
2048
+ }
2049
+ if (dispatch) {
2050
+ const { selection, storedMarks } = state;
2051
+ const { splittableMarks } = editor.extensionManager;
2052
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
2053
+ tr.split($from.pos, 2, types).scrollIntoView();
2054
+ if (!marks || !dispatch) {
2055
+ return true;
2056
+ }
2057
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
2058
+ tr.ensureMarks(filteredMarks);
2059
+ }
2060
+ return true;
2061
+ };
2062
+ var joinListBackwards = (tr, listType) => {
2063
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
2064
+ if (!list) {
2065
+ return true;
2066
+ }
2067
+ const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth);
2068
+ if (before === void 0) {
2069
+ return true;
2070
+ }
2071
+ const nodeBefore = tr.doc.nodeAt(before);
2072
+ const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr.doc, list.pos);
2073
+ if (!canJoinBackwards) {
2074
+ return true;
2075
+ }
2076
+ tr.join(list.pos);
2077
+ return true;
2078
+ };
2079
+ var joinListForwards = (tr, listType) => {
2080
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
2081
+ if (!list) {
2082
+ return true;
2083
+ }
2084
+ const after = tr.doc.resolve(list.start).after(list.depth);
2085
+ if (after === void 0) {
2086
+ return true;
2087
+ }
2088
+ const nodeAfter = tr.doc.nodeAt(after);
2089
+ const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr.doc, after);
2090
+ if (!canJoinForwards) {
2091
+ return true;
2092
+ }
2093
+ tr.join(after);
2094
+ return true;
2095
+ };
2096
+ function createInnerSelectionForWholeDocList(tr) {
2097
+ const doc = tr.doc;
2098
+ const list = doc.firstChild;
2099
+ if (!list) {
2100
+ return null;
2101
+ }
2102
+ const $start = doc.resolve(1);
2103
+ const $end = doc.resolve(list.nodeSize - 1);
2104
+ return TextSelection.between($start, $end);
2105
+ }
2106
+ var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr, state, dispatch, chain, commands, can }) => {
2107
+ const { extensions, splittableMarks } = editor.extensionManager;
2108
+ const listType = getNodeType(listTypeOrName, state.schema);
2109
+ const itemType = getNodeType(itemTypeOrName, state.schema);
2110
+ const { selection, storedMarks } = state;
2111
+ const { $from, $to } = selection;
2112
+ const range = $from.blockRange($to);
2113
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
2114
+ if (!range) {
2115
+ return false;
2116
+ }
2117
+ const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection);
2118
+ const isAllSelection = selection.from === 0 && selection.to === state.doc.content.size;
2119
+ const topLevelNodes = state.doc.content.content;
2120
+ const soleTopLevelNode = topLevelNodes.length === 1 ? topLevelNodes[0] : null;
2121
+ const allSelectionList = isAllSelection && soleTopLevelNode && isList(soleTopLevelNode.type.name, extensions) ? {
2122
+ node: soleTopLevelNode,
2123
+ pos: 0} : null;
2124
+ const currentList = parentList != null ? parentList : allSelectionList;
2125
+ const isInsideExistingList = !!parentList && range.depth >= 1 && range.depth - parentList.depth <= 1;
2126
+ const hasWholeDocSelectedList = !!allSelectionList;
2127
+ if ((isInsideExistingList || hasWholeDocSelectedList) && currentList) {
2128
+ if (currentList.node.type === listType) {
2129
+ if (isAllSelection && hasWholeDocSelectedList) {
2130
+ return chain().command(({ tr: trx, dispatch: disp }) => {
2131
+ const nextSelection = createInnerSelectionForWholeDocList(trx);
2132
+ if (!nextSelection) {
2133
+ return false;
2134
+ }
2135
+ trx.setSelection(nextSelection);
2136
+ if (disp) {
2137
+ disp(trx);
2138
+ }
2139
+ return true;
2140
+ }).liftListItem(itemType).run();
2141
+ }
2142
+ return commands.liftListItem(itemType);
2143
+ }
2144
+ if (isList(currentList.node.type.name, extensions) && listType.validContent(currentList.node.content)) {
2145
+ return chain().command(() => {
2146
+ tr.setNodeMarkup(currentList.pos, listType);
2147
+ return true;
2148
+ }).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
2149
+ }
2150
+ }
2151
+ if (!keepMarks || !marks || !dispatch) {
2152
+ return chain().command(() => {
2153
+ const canWrapInList = can().wrapInList(listType, attributes);
2154
+ if (canWrapInList) {
2155
+ return true;
2156
+ }
2157
+ return commands.clearNodes();
2158
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
2159
+ }
2160
+ return chain().command(() => {
2161
+ const canWrapInList = can().wrapInList(listType, attributes);
2162
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
2163
+ tr.ensureMarks(filteredMarks);
2164
+ if (canWrapInList) {
2165
+ return true;
2166
+ }
2167
+ return commands.clearNodes();
2168
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
2169
+ };
2170
+ var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {
2171
+ const { extendEmptyMarkRange = false } = options;
2172
+ const type = getMarkType(typeOrName, state.schema);
2173
+ const isActive2 = isMarkActive(state, type, attributes);
2174
+ if (isActive2) {
2175
+ return commands.unsetMark(type, { extendEmptyMarkRange });
2176
+ }
2177
+ return commands.setMark(type, attributes);
2178
+ };
2179
+ var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
2180
+ const type = getNodeType(typeOrName, state.schema);
2181
+ const toggleType = getNodeType(toggleTypeOrName, state.schema);
2182
+ const isActive2 = isNodeActive(state, type, attributes);
2183
+ let attributesToCopy;
2184
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
2185
+ attributesToCopy = state.selection.$anchor.parent.attrs;
2186
+ }
2187
+ if (isActive2) {
2188
+ return commands.setNode(toggleType, attributesToCopy);
2189
+ }
2190
+ return commands.setNode(type, { ...attributesToCopy, ...attributes });
2191
+ };
2192
+ var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => {
2193
+ const type = getNodeType(typeOrName, state.schema);
2194
+ const isActive2 = isNodeActive(state, type, attributes);
2195
+ if (isActive2) {
2196
+ return commands.lift(type);
2197
+ }
2198
+ return commands.wrapIn(type, attributes);
2199
+ };
2200
+ var undoInputRule = () => ({ state, dispatch }) => {
2201
+ const plugins = state.plugins;
2202
+ for (let i = 0; i < plugins.length; i += 1) {
2203
+ const plugin = plugins[i];
2204
+ let undoable;
2205
+ if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
2206
+ if (dispatch) {
2207
+ const tr = state.tr;
2208
+ const toUndo = undoable.transform;
2209
+ for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
2210
+ tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
2211
+ }
2212
+ if (undoable.text) {
2213
+ const marks = tr.doc.resolve(undoable.from).marks();
2214
+ tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
2215
+ } else {
2216
+ tr.delete(undoable.from, undoable.to);
2217
+ }
2218
+ }
2219
+ return true;
2220
+ }
2221
+ }
2222
+ return false;
2223
+ };
2224
+ var unsetAllMarks = (options = {}) => ({ tr, dispatch, editor }) => {
2225
+ const { ignoreClearable = false } = options;
2226
+ const { selection } = tr;
2227
+ const { empty, ranges } = selection;
2228
+ if (empty) {
2229
+ return true;
2230
+ }
2231
+ const { nonClearableMarks } = editor.extensionManager;
2232
+ if (dispatch) {
2233
+ const clearableMarkTypes = Object.values(editor.schema.marks).filter(
2234
+ (markType) => ignoreClearable || !nonClearableMarks.includes(markType.name)
2235
+ );
2236
+ ranges.forEach((range) => {
2237
+ for (const markType of clearableMarkTypes) {
2238
+ tr.removeMark(range.$from.pos, range.$to.pos, markType);
2239
+ }
2240
+ });
2241
+ }
2242
+ return true;
2243
+ };
2244
+ var unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {
2245
+ var _a;
2246
+ const { extendEmptyMarkRange = false } = options;
2247
+ const { selection } = tr;
2248
+ const type = getMarkType(typeOrName, state.schema);
2249
+ const { $from, empty, ranges } = selection;
2250
+ if (!dispatch) {
2251
+ return true;
2252
+ }
2253
+ if (empty && extendEmptyMarkRange) {
2254
+ let { from, to } = selection;
2255
+ const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs;
2256
+ const range = getMarkRange($from, type, attrs);
2257
+ if (range) {
2258
+ from = range.from;
2259
+ to = range.to;
2260
+ }
2261
+ tr.removeMark(from, to, type);
2262
+ } else {
2263
+ ranges.forEach((range) => {
2264
+ tr.removeMark(range.$from.pos, range.$to.pos, type);
2265
+ });
2266
+ }
2267
+ tr.removeStoredMark(type);
2268
+ return true;
2269
+ };
2270
+ var unsetTextDirection = (position) => ({ tr, state, dispatch }) => {
2271
+ const { selection } = state;
2272
+ let from;
2273
+ let to;
2274
+ if (typeof position === "number") {
2275
+ from = position;
2276
+ to = position;
2277
+ } else if (position && "from" in position && "to" in position) {
2278
+ from = position.from;
2279
+ to = position.to;
2280
+ } else {
2281
+ from = selection.from;
2282
+ to = selection.to;
2283
+ }
2284
+ if (dispatch) {
2285
+ tr.doc.nodesBetween(from, to, (node, pos) => {
2286
+ if (node.isText) {
2287
+ return;
2288
+ }
2289
+ const newAttrs = { ...node.attrs };
2290
+ delete newAttrs.dir;
2291
+ tr.setNodeMarkup(pos, void 0, newAttrs);
2292
+ });
2293
+ }
2294
+ return true;
2295
+ };
2296
+ var updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
2297
+ let nodeType = null;
2298
+ let markType = null;
2299
+ const schemaType = getSchemaTypeNameByName(
2300
+ typeof typeOrName === "string" ? typeOrName : typeOrName.name,
2301
+ state.schema
2302
+ );
2303
+ if (!schemaType) {
2304
+ return false;
2305
+ }
2306
+ if (schemaType === "node") {
2307
+ nodeType = getNodeType(typeOrName, state.schema);
2308
+ }
2309
+ if (schemaType === "mark") {
2310
+ markType = getMarkType(typeOrName, state.schema);
2311
+ }
2312
+ let canUpdate = false;
2313
+ tr.selection.ranges.forEach((range) => {
2314
+ const from = range.$from.pos;
2315
+ const to = range.$to.pos;
2316
+ let lastPos;
2317
+ let lastNode;
2318
+ let trimmedFrom;
2319
+ let trimmedTo;
2320
+ if (tr.selection.empty) {
2321
+ state.doc.nodesBetween(from, to, (node, pos) => {
2322
+ if (nodeType && nodeType === node.type) {
2323
+ canUpdate = true;
2324
+ trimmedFrom = Math.max(pos, from);
2325
+ trimmedTo = Math.min(pos + node.nodeSize, to);
2326
+ lastPos = pos;
2327
+ lastNode = node;
2328
+ }
2329
+ });
2330
+ } else {
2331
+ state.doc.nodesBetween(from, to, (node, pos) => {
2332
+ if (pos < from && nodeType && nodeType === node.type) {
2333
+ canUpdate = true;
2334
+ trimmedFrom = Math.max(pos, from);
2335
+ trimmedTo = Math.min(pos + node.nodeSize, to);
2336
+ lastPos = pos;
2337
+ lastNode = node;
2338
+ }
2339
+ if (pos >= from && pos <= to) {
2340
+ if (nodeType && nodeType === node.type) {
2341
+ canUpdate = true;
2342
+ if (dispatch) {
2343
+ tr.setNodeMarkup(pos, void 0, {
2344
+ ...node.attrs,
2345
+ ...attributes
2346
+ });
2347
+ }
2348
+ }
2349
+ if (markType && node.marks.length) {
2350
+ node.marks.forEach((mark) => {
2351
+ if (markType === mark.type) {
2352
+ canUpdate = true;
2353
+ if (dispatch) {
2354
+ const trimmedFrom2 = Math.max(pos, from);
2355
+ const trimmedTo2 = Math.min(pos + node.nodeSize, to);
2356
+ tr.addMark(
2357
+ trimmedFrom2,
2358
+ trimmedTo2,
2359
+ markType.create({
2360
+ ...mark.attrs,
2361
+ ...attributes
2362
+ })
2363
+ );
2364
+ }
2365
+ }
2366
+ });
2367
+ }
2368
+ }
2369
+ });
2370
+ }
2371
+ if (lastNode) {
2372
+ if (lastPos !== void 0 && dispatch) {
2373
+ tr.setNodeMarkup(lastPos, void 0, {
2374
+ ...lastNode.attrs,
2375
+ ...attributes
2376
+ });
2377
+ }
2378
+ if (markType && lastNode.marks.length) {
2379
+ lastNode.marks.forEach((mark) => {
2380
+ if (markType === mark.type && dispatch) {
2381
+ tr.addMark(
2382
+ trimmedFrom,
2383
+ trimmedTo,
2384
+ markType.create({
2385
+ ...mark.attrs,
2386
+ ...attributes
2387
+ })
2388
+ );
2389
+ }
2390
+ });
2391
+ }
2392
+ }
2393
+ });
2394
+ return canUpdate;
2395
+ };
2396
+ var wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2397
+ const type = getNodeType(typeOrName, state.schema);
2398
+ return wrapIn$1(type, attributes)(state, dispatch);
2399
+ };
2400
+ var wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2401
+ const type = getNodeType(typeOrName, state.schema);
2402
+ return wrapInList$1(type, attributes)(state, dispatch);
2403
+ };
2404
+ function getType(value) {
2405
+ return Object.prototype.toString.call(value).slice(8, -1);
2406
+ }
2407
+ function isPlainObject(value) {
2408
+ if (getType(value) !== "Object") {
2409
+ return false;
2410
+ }
2411
+ return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
2412
+ }
2413
+ function mergeDeep(target, source) {
2414
+ const output = { ...target };
2415
+ if (isPlainObject(target) && isPlainObject(source)) {
2416
+ Object.keys(source).forEach((key) => {
2417
+ if (isPlainObject(source[key]) && isPlainObject(target[key])) {
2418
+ output[key] = mergeDeep(target[key], source[key]);
2419
+ } else {
2420
+ output[key] = source[key];
2421
+ }
2422
+ });
2423
+ }
2424
+ return output;
2425
+ }
2426
+ var Extendable = class {
2427
+ constructor(config = {}) {
2428
+ this.type = "extendable";
2429
+ this.parent = null;
2430
+ this.child = null;
2431
+ this.name = "";
2432
+ this.config = {
2433
+ name: this.name
2434
+ };
2435
+ this.config = {
2436
+ ...this.config,
2437
+ ...config
2438
+ };
2439
+ this.name = this.config.name;
2440
+ }
2441
+ get options() {
2442
+ return {
2443
+ ...callOrReturn(
2444
+ getExtensionField(this, "addOptions", {
2445
+ name: this.name
2446
+ })
2447
+ )
2448
+ };
2449
+ }
2450
+ get storage() {
2451
+ return {
2452
+ ...callOrReturn(
2453
+ getExtensionField(this, "addStorage", {
2454
+ name: this.name,
2455
+ options: this.options
2456
+ })
2457
+ )
2458
+ };
2459
+ }
2460
+ configure(options = {}) {
2461
+ const extension = this.extend({
2462
+ ...this.config,
2463
+ addOptions: () => {
2464
+ return mergeDeep(this.options, options);
2465
+ }
2466
+ });
2467
+ extension.name = this.name;
2468
+ extension.parent = this.parent;
2469
+ this.child = null;
2470
+ return extension;
2471
+ }
2472
+ extend(extendedConfig = {}) {
2473
+ const extension = new this.constructor({ ...this.config, ...extendedConfig });
2474
+ extension.parent = this;
2475
+ this.child = extension;
2476
+ extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name;
2477
+ return extension;
2478
+ }
2479
+ };
2480
+ var Mark = class _Mark extends Extendable {
2481
+ constructor() {
2482
+ super(...arguments);
2483
+ this.type = "mark";
2484
+ }
2485
+ /**
2486
+ * Create a new Mark instance
2487
+ * @param config - Mark configuration object or a function that returns a configuration object
2488
+ */
2489
+ static create(config = {}) {
2490
+ const resolvedConfig = typeof config === "function" ? config() : config;
2491
+ return new _Mark(resolvedConfig);
2492
+ }
2493
+ static handleExit({ editor, mark }) {
2494
+ const { tr } = editor.state;
2495
+ const currentPos = editor.state.selection.$from;
2496
+ const isAtEnd = currentPos.pos === currentPos.end();
2497
+ if (isAtEnd) {
2498
+ const currentMarks = currentPos.marks();
2499
+ const isInMark = !!currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name);
2500
+ if (!isInMark) {
2501
+ return false;
2502
+ }
2503
+ const removeMark = currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name);
2504
+ if (removeMark) {
2505
+ tr.removeStoredMark(removeMark);
2506
+ }
2507
+ tr.insertText(" ", currentPos.pos);
2508
+ editor.view.dispatch(tr);
2509
+ return true;
2510
+ }
2511
+ return false;
2512
+ }
2513
+ configure(options) {
2514
+ return super.configure(options);
2515
+ }
2516
+ extend(extendedConfig) {
2517
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
2518
+ return super.extend(resolvedConfig);
2519
+ }
2520
+ };
2521
+ var extensions_exports = {};
2522
+ __export(extensions_exports, {
2523
+ ClipboardTextSerializer: () => ClipboardTextSerializer,
2524
+ Commands: () => Commands,
2525
+ Delete: () => Delete,
2526
+ Drop: () => Drop,
2527
+ Editable: () => Editable,
2528
+ FocusEvents: () => FocusEvents,
2529
+ Keymap: () => Keymap,
2530
+ Paste: () => Paste,
2531
+ Tabindex: () => Tabindex,
2532
+ TextDirection: () => TextDirection,
2533
+ focusEventsPluginKey: () => focusEventsPluginKey
2534
+ });
2535
+ var Extension = class _Extension extends Extendable {
2536
+ constructor() {
2537
+ super(...arguments);
2538
+ this.type = "extension";
2539
+ }
2540
+ /**
2541
+ * Create a new Extension instance
2542
+ * @param config - Extension configuration object or a function that returns a configuration object
2543
+ */
2544
+ static create(config = {}) {
2545
+ const resolvedConfig = typeof config === "function" ? config() : config;
2546
+ return new _Extension(resolvedConfig);
2547
+ }
2548
+ configure(options) {
2549
+ return super.configure(options);
2550
+ }
2551
+ extend(extendedConfig) {
2552
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
2553
+ return super.extend(resolvedConfig);
2554
+ }
2555
+ };
2556
+ var ClipboardTextSerializer = Extension.create({
2557
+ name: "clipboardTextSerializer",
2558
+ addOptions() {
2559
+ return {
2560
+ blockSeparator: void 0
2561
+ };
2562
+ },
2563
+ addProseMirrorPlugins() {
2564
+ return [
2565
+ new Plugin({
2566
+ key: new PluginKey("clipboardTextSerializer"),
2567
+ props: {
2568
+ clipboardTextSerializer: () => {
2569
+ const { editor } = this;
2570
+ const { state, schema } = editor;
2571
+ const { doc, selection } = state;
2572
+ const textSerializers = getTextSerializersFromSchema(schema);
2573
+ const { blockSeparator } = this.options;
2574
+ const options = {
2575
+ ...blockSeparator !== void 0 ? { blockSeparator } : {},
2576
+ textSerializers
2577
+ };
2578
+ const sortedRanges = [...selection.ranges].sort((a, b) => a.$from.pos - b.$from.pos);
2579
+ return sortedRanges.map(
2580
+ ({ $from, $to }) => getTextBetween(doc, { from: $from.pos, to: $to.pos }, options)
2581
+ ).join(blockSeparator != null ? blockSeparator : "\n\n");
2582
+ }
2583
+ }
2584
+ })
2585
+ ];
2586
+ }
2587
+ });
2588
+ var Commands = Extension.create({
2589
+ name: "commands",
2590
+ addCommands() {
2591
+ return {
2592
+ ...commands_exports
2593
+ };
2594
+ }
2595
+ });
2596
+ var Delete = Extension.create({
2597
+ name: "delete",
2598
+ onUpdate({ transaction, appendedTransactions }) {
2599
+ var _a, _b, _c;
2600
+ const callback = () => {
2601
+ var _a2, _b2, _c2, _d;
2602
+ if ((_d = (_c2 = (_b2 = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) {
2603
+ return;
2604
+ }
2605
+ const nextTransaction = combineTransactionSteps(transaction.before, [
2606
+ transaction,
2607
+ ...appendedTransactions
2608
+ ]);
2609
+ const changes = getChangedRanges(nextTransaction);
2610
+ changes.forEach((change) => {
2611
+ if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) {
2612
+ nextTransaction.before.nodesBetween(
2613
+ change.oldRange.from,
2614
+ change.oldRange.to,
2615
+ (node, from) => {
2616
+ const to = from + node.nodeSize - 2;
2617
+ const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to;
2618
+ this.editor.emit("delete", {
2619
+ type: "node",
2620
+ node,
2621
+ from,
2622
+ to,
2623
+ newFrom: nextTransaction.mapping.map(from),
2624
+ newTo: nextTransaction.mapping.map(to),
2625
+ deletedRange: change.oldRange,
2626
+ newRange: change.newRange,
2627
+ partial: !isFullyWithinRange,
2628
+ editor: this.editor,
2629
+ transaction,
2630
+ combinedTransform: nextTransaction
2631
+ });
2632
+ }
2633
+ );
2634
+ }
2635
+ });
2636
+ const mapping = nextTransaction.mapping;
2637
+ nextTransaction.steps.forEach((step, index) => {
2638
+ var _a3, _b3;
2639
+ if (step instanceof RemoveMarkStep) {
2640
+ const newStart = mapping.slice(index).map(step.from, -1);
2641
+ const newEnd = mapping.slice(index).map(step.to);
2642
+ const oldStart = mapping.invert().map(newStart, -1);
2643
+ const oldEnd = mapping.invert().map(newEnd);
2644
+ const foundBeforeMark = newStart > 0 ? (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark)) : false;
2645
+ const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark));
2646
+ this.editor.emit("delete", {
2647
+ type: "mark",
2648
+ mark: step.mark,
2649
+ from: step.from,
2650
+ to: step.to,
2651
+ deletedRange: {
2652
+ from: oldStart,
2653
+ to: oldEnd
2654
+ },
2655
+ newRange: {
2656
+ from: newStart,
2657
+ to: newEnd
2658
+ },
2659
+ partial: Boolean(foundAfterMark || foundBeforeMark),
2660
+ editor: this.editor,
2661
+ transaction,
2662
+ combinedTransform: nextTransaction
2663
+ });
2664
+ }
2665
+ });
2666
+ };
2667
+ if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) {
2668
+ setTimeout(callback, 0);
2669
+ } else {
2670
+ callback();
2671
+ }
2672
+ }
2673
+ });
2674
+ var Drop = Extension.create({
2675
+ name: "drop",
2676
+ addProseMirrorPlugins() {
2677
+ return [
2678
+ new Plugin({
2679
+ key: new PluginKey("tiptapDrop"),
2680
+ props: {
2681
+ handleDrop: (_, e, slice, moved) => {
2682
+ this.editor.emit("drop", {
2683
+ editor: this.editor,
2684
+ event: e,
2685
+ slice,
2686
+ moved
2687
+ });
2688
+ }
2689
+ }
2690
+ })
2691
+ ];
2692
+ }
2693
+ });
2694
+ var Editable = Extension.create({
2695
+ name: "editable",
2696
+ addProseMirrorPlugins() {
2697
+ return [
2698
+ new Plugin({
2699
+ key: new PluginKey("editable"),
2700
+ props: {
2701
+ editable: () => this.editor.options.editable
2702
+ }
2703
+ })
2704
+ ];
2705
+ }
2706
+ });
2707
+ var focusEventsPluginKey = new PluginKey("focusEvents");
2708
+ var FocusEvents = Extension.create({
2709
+ name: "focusEvents",
2710
+ addProseMirrorPlugins() {
2711
+ const { editor } = this;
2712
+ return [
2713
+ new Plugin({
2714
+ key: focusEventsPluginKey,
2715
+ props: {
2716
+ handleDOMEvents: {
2717
+ focus: (view, event) => {
2718
+ editor.isFocused = true;
2719
+ const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
2720
+ view.dispatch(transaction);
2721
+ return false;
2722
+ },
2723
+ blur: (view, event) => {
2724
+ editor.isFocused = false;
2725
+ const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
2726
+ view.dispatch(transaction);
2727
+ return false;
2728
+ }
2729
+ }
2730
+ }
2731
+ })
2732
+ ];
2733
+ }
2734
+ });
2735
+ var Keymap = Extension.create({
2736
+ name: "keymap",
2737
+ addKeyboardShortcuts() {
2738
+ const handleBackspace = () => this.editor.commands.first(({ commands }) => [
2739
+ () => commands.undoInputRule(),
2740
+ // maybe convert first text block node to default node
2741
+ () => commands.command(({ tr }) => {
2742
+ const { selection, doc } = tr;
2743
+ const { empty, $anchor } = selection;
2744
+ const { pos, parent } = $anchor;
2745
+ const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor;
2746
+ const parentIsIsolating = $parentPos.parent.type.spec.isolating;
2747
+ const parentPos = $anchor.pos - $anchor.parentOffset;
2748
+ const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc).from === pos;
2749
+ if (!empty || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
2750
+ return false;
2751
+ }
2752
+ return commands.clearNodes();
2753
+ }),
2754
+ () => commands.deleteSelection(),
2755
+ () => commands.joinBackward(),
2756
+ () => commands.selectNodeBackward()
2757
+ ]);
2758
+ const handleDelete = () => this.editor.commands.first(({ commands }) => [
2759
+ () => commands.deleteSelection(),
2760
+ () => commands.deleteCurrentNode(),
2761
+ () => commands.joinForward(),
2762
+ () => commands.selectNodeForward()
2763
+ ]);
2764
+ const handleEnter = () => this.editor.commands.first(({ commands }) => [
2765
+ () => commands.newlineInCode(),
2766
+ () => commands.createParagraphNear(),
2767
+ () => commands.liftEmptyBlock(),
2768
+ () => commands.splitBlock()
2769
+ ]);
2770
+ const baseKeymap = {
2771
+ Enter: handleEnter,
2772
+ "Mod-Enter": () => this.editor.commands.exitCode(),
2773
+ Backspace: handleBackspace,
2774
+ "Mod-Backspace": handleBackspace,
2775
+ "Shift-Backspace": handleBackspace,
2776
+ Delete: handleDelete,
2777
+ "Mod-Delete": handleDelete,
2778
+ "Mod-a": () => this.editor.commands.selectAll()
2779
+ };
2780
+ const pcKeymap = {
2781
+ ...baseKeymap
2782
+ };
2783
+ const macKeymap = {
2784
+ ...baseKeymap,
2785
+ "Ctrl-h": handleBackspace,
2786
+ "Alt-Backspace": handleBackspace,
2787
+ "Ctrl-d": handleDelete,
2788
+ "Ctrl-Alt-Backspace": handleDelete,
2789
+ "Alt-Delete": handleDelete,
2790
+ "Alt-d": handleDelete,
2791
+ "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
2792
+ "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
2793
+ };
2794
+ if (isiOS() || isMacOS()) {
2795
+ return macKeymap;
2796
+ }
2797
+ return pcKeymap;
2798
+ },
2799
+ addProseMirrorPlugins() {
2800
+ return [
2801
+ // With this plugin we check if the whole document was selected and deleted.
2802
+ // In this case we will additionally call `clearNodes()` to convert e.g. a heading
2803
+ // to a paragraph if necessary.
2804
+ // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
2805
+ // with many other commands.
2806
+ new Plugin({
2807
+ key: new PluginKey("clearDocument"),
2808
+ appendTransaction: (transactions, oldState, newState) => {
2809
+ if (transactions.some((tr2) => tr2.getMeta("composition"))) {
2810
+ return;
2811
+ }
2812
+ const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
2813
+ const ignoreTr = transactions.some(
2814
+ (transaction) => transaction.getMeta("preventClearDocument")
2815
+ );
2816
+ if (!docChanges || ignoreTr) {
2817
+ return;
2818
+ }
2819
+ const { empty, from, to } = oldState.selection;
2820
+ const allFrom = Selection.atStart(oldState.doc).from;
2821
+ const allEnd = Selection.atEnd(oldState.doc).to;
2822
+ const allWasSelected = from === allFrom && to === allEnd;
2823
+ if (empty || !allWasSelected) {
2824
+ return;
2825
+ }
2826
+ const isEmpty = isNodeEmpty(newState.doc);
2827
+ if (!isEmpty) {
2828
+ return;
2829
+ }
2830
+ const tr = newState.tr;
2831
+ const state = createChainableState({
2832
+ state: newState,
2833
+ transaction: tr
2834
+ });
2835
+ const { commands } = new CommandManager({
2836
+ editor: this.editor,
2837
+ state
2838
+ });
2839
+ commands.clearNodes();
2840
+ if (!tr.steps.length) {
2841
+ return;
2842
+ }
2843
+ return tr;
2844
+ }
2845
+ })
2846
+ ];
2847
+ }
2848
+ });
2849
+ var Paste = Extension.create({
2850
+ name: "paste",
2851
+ addProseMirrorPlugins() {
2852
+ return [
2853
+ new Plugin({
2854
+ key: new PluginKey("tiptapPaste"),
2855
+ props: {
2856
+ handlePaste: (_view, e, slice) => {
2857
+ this.editor.emit("paste", {
2858
+ editor: this.editor,
2859
+ event: e,
2860
+ slice
2861
+ });
2862
+ }
2863
+ }
2864
+ })
2865
+ ];
2866
+ }
2867
+ });
2868
+ var Tabindex = Extension.create({
2869
+ name: "tabindex",
2870
+ addOptions() {
2871
+ return {
2872
+ value: void 0
2873
+ };
2874
+ },
2875
+ addProseMirrorPlugins() {
2876
+ return [
2877
+ new Plugin({
2878
+ key: new PluginKey("tabindex"),
2879
+ props: {
2880
+ attributes: () => {
2881
+ var _a;
2882
+ if (!this.editor.isEditable && this.options.value === void 0) {
2883
+ return {};
2884
+ }
2885
+ return { tabindex: (_a = this.options.value) != null ? _a : "0" };
2886
+ }
2887
+ }
2888
+ })
2889
+ ];
2890
+ }
2891
+ });
2892
+ var TextDirection = Extension.create({
2893
+ name: "textDirection",
2894
+ addOptions() {
2895
+ return {
2896
+ direction: void 0
2897
+ };
2898
+ },
2899
+ addGlobalAttributes() {
2900
+ if (!this.options.direction) {
2901
+ return [];
2902
+ }
2903
+ const { nodeExtensions } = splitExtensions(this.extensions);
2904
+ return [
2905
+ {
2906
+ types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name),
2907
+ attributes: {
2908
+ dir: {
2909
+ default: this.options.direction,
2910
+ parseHTML: (element) => {
2911
+ const dir = element.getAttribute("dir");
2912
+ if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) {
2913
+ return dir;
2914
+ }
2915
+ return this.options.direction;
2916
+ },
2917
+ renderHTML: (attributes) => {
2918
+ if (!attributes.dir) {
2919
+ return {};
2920
+ }
2921
+ return {
2922
+ dir: attributes.dir
2923
+ };
2924
+ }
2925
+ }
2926
+ }
2927
+ }
2928
+ ];
2929
+ },
2930
+ addProseMirrorPlugins() {
2931
+ return [
2932
+ new Plugin({
2933
+ key: new PluginKey("textDirection"),
2934
+ props: {
2935
+ attributes: () => {
2936
+ const direction = this.options.direction;
2937
+ if (!direction) {
2938
+ return {};
2939
+ }
2940
+ return {
2941
+ dir: direction
2942
+ };
2943
+ }
2944
+ }
2945
+ })
2946
+ ];
2947
+ }
2948
+ });
2949
+ var markdown_exports = {};
2950
+ __export(markdown_exports, {
2951
+ createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec,
2952
+ createBlockMarkdownSpec: () => createBlockMarkdownSpec,
2953
+ createInlineMarkdownSpec: () => createInlineMarkdownSpec,
2954
+ parseAttributes: () => parseAttributes,
2955
+ parseIndentedBlocks: () => parseIndentedBlocks,
2956
+ renderNestedMarkdownContent: () => renderNestedMarkdownContent,
2957
+ serializeAttributes: () => serializeAttributes
2958
+ });
2959
+ function parseAttributes(attrString) {
2960
+ if (!(attrString == null ? void 0 : attrString.trim())) {
2961
+ return {};
2962
+ }
2963
+ const attributes = {};
2964
+ const quotedStrings = [];
2965
+ const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => {
2966
+ quotedStrings.push(match);
2967
+ return `__QUOTED_${quotedStrings.length - 1}__`;
2968
+ });
2969
+ const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);
2970
+ if (classMatches) {
2971
+ const classes = classMatches.map((match) => match.trim().slice(1));
2972
+ attributes.class = classes.join(" ");
2973
+ }
2974
+ const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);
2975
+ if (idMatch) {
2976
+ attributes.id = idMatch[1];
2977
+ }
2978
+ const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;
2979
+ const kvMatches = Array.from(tempString.matchAll(kvRegex));
2980
+ kvMatches.forEach(([, key, quotedRef]) => {
2981
+ var _a;
2982
+ const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10);
2983
+ const quotedValue = quotedStrings[quotedIndex];
2984
+ if (quotedValue) {
2985
+ attributes[key] = quotedValue.slice(1, -1);
2986
+ }
2987
+ });
2988
+ const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim();
2989
+ if (cleanString) {
2990
+ const booleanAttrs = cleanString.split(/\s+/).filter(Boolean);
2991
+ booleanAttrs.forEach((attr) => {
2992
+ if (attr.match(/^[a-zA-Z][\w-]*$/)) {
2993
+ attributes[attr] = true;
2994
+ }
2995
+ });
2996
+ }
2997
+ return attributes;
2998
+ }
2999
+ function serializeAttributes(attributes) {
3000
+ if (!attributes || Object.keys(attributes).length === 0) {
3001
+ return "";
3002
+ }
3003
+ const parts = [];
3004
+ if (attributes.class) {
3005
+ const classes = String(attributes.class).split(/\s+/).filter(Boolean);
3006
+ classes.forEach((cls) => parts.push(`.${cls}`));
3007
+ }
3008
+ if (attributes.id) {
3009
+ parts.push(`#${attributes.id}`);
3010
+ }
3011
+ Object.entries(attributes).forEach(([key, value]) => {
3012
+ if (key === "class" || key === "id") {
3013
+ return;
3014
+ }
3015
+ if (value === true) {
3016
+ parts.push(key);
3017
+ } else if (value !== false && value != null) {
3018
+ parts.push(`${key}="${String(value)}"`);
3019
+ }
3020
+ });
3021
+ return parts.join(" ");
3022
+ }
3023
+ function createAtomBlockMarkdownSpec(options) {
3024
+ const {
3025
+ nodeName,
3026
+ name: markdownName,
3027
+ parseAttributes: parseAttributes2 = parseAttributes,
3028
+ serializeAttributes: serializeAttributes2 = serializeAttributes,
3029
+ defaultAttributes = {},
3030
+ requiredAttributes = [],
3031
+ allowedAttributes
3032
+ } = options;
3033
+ const blockName = markdownName || nodeName;
3034
+ const filterAttributes = (attrs) => {
3035
+ if (!allowedAttributes) {
3036
+ return attrs;
3037
+ }
3038
+ const filtered = {};
3039
+ allowedAttributes.forEach((key) => {
3040
+ if (key in attrs) {
3041
+ filtered[key] = attrs[key];
3042
+ }
3043
+ });
3044
+ return filtered;
3045
+ };
3046
+ return {
3047
+ parseMarkdown: (token, h2) => {
3048
+ const attrs = { ...defaultAttributes, ...token.attributes };
3049
+ return h2.createNode(nodeName, attrs, []);
3050
+ },
3051
+ markdownTokenizer: {
3052
+ name: nodeName,
3053
+ level: "block",
3054
+ start(src) {
3055
+ var _a;
3056
+ const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m");
3057
+ const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
3058
+ return index !== void 0 ? index : -1;
3059
+ },
3060
+ tokenize(src, _tokens, _lexer) {
3061
+ const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`);
3062
+ const match = src.match(regex);
3063
+ if (!match) {
3064
+ return void 0;
3065
+ }
3066
+ const attrString = match[1] || "";
3067
+ const attributes = parseAttributes2(attrString);
3068
+ const missingRequired = requiredAttributes.find((required) => !(required in attributes));
3069
+ if (missingRequired) {
3070
+ return void 0;
3071
+ }
3072
+ return {
3073
+ type: nodeName,
3074
+ raw: match[0],
3075
+ attributes
3076
+ };
3077
+ }
3078
+ },
3079
+ renderMarkdown: (node) => {
3080
+ const filteredAttrs = filterAttributes(node.attrs || {});
3081
+ const attrs = serializeAttributes2(filteredAttrs);
3082
+ const attrString = attrs ? ` {${attrs}}` : "";
3083
+ return `:::${blockName}${attrString} :::`;
3084
+ }
3085
+ };
3086
+ }
3087
+ function createBlockMarkdownSpec(options) {
3088
+ const {
3089
+ nodeName,
3090
+ name: markdownName,
3091
+ getContent,
3092
+ parseAttributes: parseAttributes2 = parseAttributes,
3093
+ serializeAttributes: serializeAttributes2 = serializeAttributes,
3094
+ defaultAttributes = {},
3095
+ content = "block",
3096
+ allowedAttributes
3097
+ } = options;
3098
+ const blockName = markdownName || nodeName;
3099
+ const filterAttributes = (attrs) => {
3100
+ if (!allowedAttributes) {
3101
+ return attrs;
3102
+ }
3103
+ const filtered = {};
3104
+ allowedAttributes.forEach((key) => {
3105
+ if (key in attrs) {
3106
+ filtered[key] = attrs[key];
3107
+ }
3108
+ });
3109
+ return filtered;
3110
+ };
3111
+ return {
3112
+ parseMarkdown: (token, h2) => {
3113
+ let nodeContent;
3114
+ if (getContent) {
3115
+ const contentResult = getContent(token);
3116
+ nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult;
3117
+ } else if (content === "block") {
3118
+ nodeContent = h2.parseChildren(token.tokens || []);
3119
+ } else {
3120
+ nodeContent = h2.parseInline(token.tokens || []);
3121
+ }
3122
+ const attrs = { ...defaultAttributes, ...token.attributes };
3123
+ return h2.createNode(nodeName, attrs, nodeContent);
3124
+ },
3125
+ markdownTokenizer: {
3126
+ name: nodeName,
3127
+ level: "block",
3128
+ start(src) {
3129
+ var _a;
3130
+ const regex = new RegExp(`^:::${blockName}`, "m");
3131
+ const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
3132
+ return index !== void 0 ? index : -1;
3133
+ },
3134
+ tokenize(src, _tokens, lexer) {
3135
+ var _a;
3136
+ const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`);
3137
+ const openingMatch = src.match(openingRegex);
3138
+ if (!openingMatch) {
3139
+ return void 0;
3140
+ }
3141
+ const [openingTag, attrString = ""] = openingMatch;
3142
+ const attributes = parseAttributes2(attrString);
3143
+ let level = 1;
3144
+ const position = openingTag.length;
3145
+ let matchedContent = "";
3146
+ const blockPattern = /^:::([\w-]*)(\s.*)?/gm;
3147
+ const remaining = src.slice(position);
3148
+ blockPattern.lastIndex = 0;
3149
+ for (; ; ) {
3150
+ const match = blockPattern.exec(remaining);
3151
+ if (match === null) {
3152
+ break;
3153
+ }
3154
+ const matchPos = match.index;
3155
+ const blockType = match[1];
3156
+ if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) {
3157
+ continue;
3158
+ }
3159
+ if (blockType) {
3160
+ level += 1;
3161
+ } else {
3162
+ level -= 1;
3163
+ if (level === 0) {
3164
+ const rawContent = remaining.slice(0, matchPos);
3165
+ matchedContent = rawContent.trim();
3166
+ const fullMatch = src.slice(0, position + matchPos + match[0].length);
3167
+ let contentTokens = [];
3168
+ if (matchedContent) {
3169
+ if (content === "block") {
3170
+ contentTokens = lexer.blockTokens(rawContent);
3171
+ contentTokens.forEach((token) => {
3172
+ if (token.text && (!token.tokens || token.tokens.length === 0)) {
3173
+ token.tokens = lexer.inlineTokens(token.text);
3174
+ }
3175
+ });
3176
+ while (contentTokens.length > 0) {
3177
+ const lastToken = contentTokens[contentTokens.length - 1];
3178
+ if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) {
3179
+ contentTokens.pop();
3180
+ } else {
3181
+ break;
3182
+ }
3183
+ }
3184
+ } else {
3185
+ contentTokens = lexer.inlineTokens(matchedContent);
3186
+ }
3187
+ }
3188
+ return {
3189
+ type: nodeName,
3190
+ raw: fullMatch,
3191
+ attributes,
3192
+ content: matchedContent,
3193
+ tokens: contentTokens
3194
+ };
3195
+ }
3196
+ }
3197
+ }
3198
+ return void 0;
3199
+ }
3200
+ },
3201
+ renderMarkdown: (node, h2) => {
3202
+ const filteredAttrs = filterAttributes(node.attrs || {});
3203
+ const attrs = serializeAttributes2(filteredAttrs);
3204
+ const attrString = attrs ? ` {${attrs}}` : "";
3205
+ const renderedContent = h2.renderChildren(node.content || [], "\n\n");
3206
+ return `:::${blockName}${attrString}
3207
+
3208
+ ${renderedContent}
3209
+
3210
+ :::`;
3211
+ }
3212
+ };
3213
+ }
3214
+ function parseShortcodeAttributes(attrString) {
3215
+ if (!attrString.trim()) {
3216
+ return {};
3217
+ }
3218
+ const attributes = {};
3219
+ const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g;
3220
+ let match = regex.exec(attrString);
3221
+ while (match !== null) {
3222
+ const [, key, doubleQuoted, singleQuoted] = match;
3223
+ attributes[key] = doubleQuoted || singleQuoted;
3224
+ match = regex.exec(attrString);
3225
+ }
3226
+ return attributes;
3227
+ }
3228
+ function serializeShortcodeAttributes(attrs) {
3229
+ return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" ");
3230
+ }
3231
+ function createInlineMarkdownSpec(options) {
3232
+ const {
3233
+ nodeName,
3234
+ name: shortcodeName,
3235
+ getContent,
3236
+ parseAttributes: parseAttributes2 = parseShortcodeAttributes,
3237
+ serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes,
3238
+ defaultAttributes = {},
3239
+ selfClosing = false,
3240
+ allowedAttributes
3241
+ } = options;
3242
+ const shortcode = shortcodeName || nodeName;
3243
+ const filterAttributes = (attrs) => {
3244
+ if (!allowedAttributes) {
3245
+ return attrs;
3246
+ }
3247
+ const filtered = {};
3248
+ allowedAttributes.forEach((attr) => {
3249
+ const attrName = typeof attr === "string" ? attr : attr.name;
3250
+ const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault;
3251
+ if (attrName in attrs) {
3252
+ const value = attrs[attrName];
3253
+ if (skipIfDefault !== void 0 && value === skipIfDefault) {
3254
+ return;
3255
+ }
3256
+ filtered[attrName] = value;
3257
+ }
3258
+ });
3259
+ return filtered;
3260
+ };
3261
+ const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3262
+ return {
3263
+ parseMarkdown: (token, h2) => {
3264
+ const attrs = { ...defaultAttributes, ...token.attributes };
3265
+ if (selfClosing) {
3266
+ return h2.createNode(nodeName, attrs);
3267
+ }
3268
+ const content = getContent ? getContent(token) : token.content || "";
3269
+ if (content) {
3270
+ return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]);
3271
+ }
3272
+ return h2.createNode(nodeName, attrs, []);
3273
+ },
3274
+ markdownTokenizer: {
3275
+ name: nodeName,
3276
+ level: "inline",
3277
+ start(src) {
3278
+ const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`);
3279
+ const match = src.match(startPattern);
3280
+ const index = match == null ? void 0 : match.index;
3281
+ return index !== void 0 ? index : -1;
3282
+ },
3283
+ tokenize(src, _tokens, _lexer) {
3284
+ const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(
3285
+ `^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`
3286
+ );
3287
+ const match = src.match(tokenPattern);
3288
+ if (!match) {
3289
+ return void 0;
3290
+ }
3291
+ let content = "";
3292
+ let attrString = "";
3293
+ if (selfClosing) {
3294
+ const [, attrs] = match;
3295
+ attrString = attrs;
3296
+ } else {
3297
+ const [, attrs, contentMatch] = match;
3298
+ attrString = attrs;
3299
+ content = contentMatch || "";
3300
+ }
3301
+ const attributes = parseAttributes2(attrString.trim());
3302
+ return {
3303
+ type: nodeName,
3304
+ raw: match[0],
3305
+ content: content.trim(),
3306
+ attributes
3307
+ };
3308
+ }
3309
+ },
3310
+ renderMarkdown: (node) => {
3311
+ let content = "";
3312
+ if (getContent) {
3313
+ content = getContent(node);
3314
+ } else if (node.content && node.content.length > 0) {
3315
+ content = node.content.filter((child) => child.type === "text").map((child) => child.text).join("");
3316
+ }
3317
+ const filteredAttrs = filterAttributes(node.attrs || {});
3318
+ const attrs = serializeAttributes2(filteredAttrs);
3319
+ const attrString = attrs ? ` ${attrs}` : "";
3320
+ if (selfClosing) {
3321
+ return `[${shortcode}${attrString}]`;
3322
+ }
3323
+ return `[${shortcode}${attrString}]${content}[/${shortcode}]`;
3324
+ }
3325
+ };
3326
+ }
3327
+ function parseIndentedBlocks(src, config, lexer) {
3328
+ var _a, _b, _c, _d;
3329
+ const lines = src.split("\n");
3330
+ const items = [];
3331
+ let totalRaw = "";
3332
+ let i = 0;
3333
+ const baseIndentSize = config.baseIndentSize || 2;
3334
+ while (i < lines.length) {
3335
+ const currentLine = lines[i];
3336
+ const itemMatch = currentLine.match(config.itemPattern);
3337
+ if (!itemMatch) {
3338
+ if (items.length > 0) {
3339
+ break;
3340
+ } else if (currentLine.trim() === "") {
3341
+ i += 1;
3342
+ totalRaw = `${totalRaw}${currentLine}
3343
+ `;
3344
+ continue;
3345
+ } else {
3346
+ return void 0;
3347
+ }
3348
+ }
3349
+ const itemData = config.extractItemData(itemMatch);
3350
+ const { indentLevel, mainContent } = itemData;
3351
+ totalRaw = `${totalRaw}${currentLine}
3352
+ `;
3353
+ const itemContent = [mainContent];
3354
+ i += 1;
3355
+ while (i < lines.length) {
3356
+ const nextLine = lines[i];
3357
+ if (nextLine.trim() === "") {
3358
+ const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== "");
3359
+ if (nextNonEmptyIndex === -1) {
3360
+ break;
3361
+ }
3362
+ const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex];
3363
+ const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0;
3364
+ if (nextIndent2 > indentLevel) {
3365
+ itemContent.push(nextLine);
3366
+ totalRaw = `${totalRaw}${nextLine}
3367
+ `;
3368
+ i += 1;
3369
+ continue;
3370
+ } else {
3371
+ break;
3372
+ }
3373
+ }
3374
+ const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0;
3375
+ if (nextIndent > indentLevel) {
3376
+ itemContent.push(nextLine);
3377
+ totalRaw = `${totalRaw}${nextLine}
3378
+ `;
3379
+ i += 1;
3380
+ } else {
3381
+ break;
3382
+ }
3383
+ }
3384
+ let nestedTokens;
3385
+ const nestedContent = itemContent.slice(1);
3386
+ if (nestedContent.length > 0) {
3387
+ const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n");
3388
+ if (dedentedNested.trim()) {
3389
+ if (config.customNestedParser) {
3390
+ nestedTokens = config.customNestedParser(dedentedNested);
3391
+ } else {
3392
+ nestedTokens = lexer.blockTokens(dedentedNested);
3393
+ }
3394
+ }
3395
+ }
3396
+ const token = config.createToken(itemData, nestedTokens);
3397
+ items.push(token);
3398
+ }
3399
+ if (items.length === 0) {
3400
+ return void 0;
3401
+ }
3402
+ return {
3403
+ items,
3404
+ raw: totalRaw
3405
+ };
3406
+ }
3407
+ function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) {
3408
+ if (!node || !Array.isArray(node.content)) {
3409
+ return "";
3410
+ }
3411
+ const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator;
3412
+ const [content, ...children] = node.content;
3413
+ const mainContent = h2.renderChildren([content]);
3414
+ let output = `${prefix}${mainContent}`;
3415
+ if (children && children.length > 0) {
3416
+ children.forEach((child, index) => {
3417
+ var _a, _b;
3418
+ const childContent = (_b = (_a = h2.renderChild) == null ? void 0 : _a.call(h2, child, index + 1)) != null ? _b : h2.renderChildren([child]);
3419
+ if (childContent !== void 0 && childContent !== null) {
3420
+ const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : h2.indent("")).join("\n");
3421
+ output += child.type === "paragraph" ? `
3422
+
3423
+ ${indentedChild}` : `
3424
+ ${indentedChild}`;
3425
+ }
3426
+ });
3427
+ }
3428
+ return output;
3429
+ }
3430
+ var Node3 = class _Node extends Extendable {
3431
+ constructor() {
3432
+ super(...arguments);
3433
+ this.type = "node";
3434
+ }
3435
+ /**
3436
+ * Create a new Node instance
3437
+ * @param config - Node configuration object or a function that returns a configuration object
3438
+ */
3439
+ static create(config = {}) {
3440
+ const resolvedConfig = typeof config === "function" ? config() : config;
3441
+ return new _Node(resolvedConfig);
3442
+ }
3443
+ configure(options) {
3444
+ return super.configure(options);
3445
+ }
3446
+ extend(extendedConfig) {
3447
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
3448
+ return super.extend(resolvedConfig);
3449
+ }
3450
+ };
3451
+
3452
+ // src/components/RichTextEditor/extensions/Highlight.ts
3453
+ var Highlight = Mark.create({
3454
+ name: "highlight",
3455
+ renderHTML({ HTMLAttributes }) {
3456
+ return ["mark", { style: "background: #fef08a; border-radius: 2px; padding: 0 2px;", ...HTMLAttributes }, 0];
3457
+ },
3458
+ parseHTML() {
3459
+ return [{ tag: "mark" }];
3460
+ },
3461
+ addKeyboardShortcuts() {
3462
+ return {
3463
+ "Mod-Shift-h": () => this.editor.commands.toggleMark(this.name)
3464
+ };
3465
+ }
3466
+ });
3467
+ var HighlightIcon = () => /* @__PURE__ */ jsxs("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": "true", children: [
3468
+ /* @__PURE__ */ jsx("rect", { x: "1", y: "8", width: "12", height: "3", rx: "1", fill: "#fef08a", stroke: "currentColor", strokeWidth: "1" }),
3469
+ /* @__PURE__ */ jsx("path", { d: "M4 8L5.5 3h3L10 8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeLinejoin: "round" }),
3470
+ /* @__PURE__ */ jsx("line", { x1: "4.5", y1: "6", x2: "9.5", y2: "6", stroke: "currentColor", strokeWidth: "1", strokeLinecap: "round" })
3471
+ ] });
3472
+ var HighlightButton = () => {
3473
+ const { editor } = useCurrentEditor();
3474
+ if (!editor) return null;
3475
+ const active = editor.isActive("highlight");
3476
+ return /* @__PURE__ */ jsx(
3477
+ "button",
3478
+ {
3479
+ type: "button",
3480
+ title: "Highlight (Mod+Shift+H)",
3481
+ "aria-label": "Highlight",
3482
+ "aria-pressed": active,
3483
+ className: [RichTextEditor_module_default.toolbarButton, active ? RichTextEditor_module_default.active : ""].filter(Boolean).join(" "),
3484
+ onMouseDown: (e) => {
3485
+ e.preventDefault();
3486
+ editor.chain().focus().toggleMark("highlight").run();
3487
+ },
3488
+ children: /* @__PURE__ */ jsx(HighlightIcon, {})
3489
+ }
3490
+ );
3491
+ };
3492
+
3493
+ // src/components/RichTextEditor/extensions/PageBreak.ts
3494
+ var PageBreak = Node3.create({
3495
+ name: "pageBreak",
3496
+ group: "block",
3497
+ atom: true,
3498
+ parseHTML() {
3499
+ return [{ tag: 'div[data-type="page-break"]' }];
3500
+ },
3501
+ renderHTML({ HTMLAttributes }) {
3502
+ return ["div", mergeAttributes(HTMLAttributes, { "data-type": "page-break" })];
3503
+ },
3504
+ addKeyboardShortcuts() {
3505
+ return {
3506
+ "Mod-Enter": () => this.editor.commands.insertContent({ type: this.name })
3507
+ };
3508
+ }
3509
+ });
3510
+ var PageBreakIcon = () => /* @__PURE__ */ jsxs("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", children: [
3511
+ /* @__PURE__ */ jsx("rect", { x: "3", y: "1", width: "10", height: "6", rx: "1", stroke: "currentColor", strokeWidth: "1.2" }),
3512
+ /* @__PURE__ */ jsx("rect", { x: "3", y: "9", width: "10", height: "6", rx: "1", stroke: "currentColor", strokeWidth: "1.2" }),
3513
+ /* @__PURE__ */ jsx("line", { x1: "1", y1: "8", x2: "5", y2: "8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeDasharray: "1.5 1.5" }),
3514
+ /* @__PURE__ */ jsx("line", { x1: "7", y1: "8", x2: "9", y2: "8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeDasharray: "1.5 1.5" }),
3515
+ /* @__PURE__ */ jsx("line", { x1: "11", y1: "8", x2: "15", y2: "8", stroke: "currentColor", strokeWidth: "1.2", strokeLinecap: "round", strokeDasharray: "1.5 1.5" })
3516
+ ] });
3517
+ var PageBreakButton = () => {
3518
+ const { editor } = useCurrentEditor();
3519
+ if (!editor) return null;
3520
+ return /* @__PURE__ */ jsx(
3521
+ "button",
3522
+ {
3523
+ type: "button",
3524
+ title: "Page break (Mod+Enter)",
3525
+ "aria-label": "Insert page break",
3526
+ className: RichTextEditor_module_default.toolbarButton,
3527
+ onMouseDown: (e) => {
3528
+ e.preventDefault();
3529
+ editor.chain().focus().insertContent({ type: "pageBreak" }).run();
3530
+ },
3531
+ children: /* @__PURE__ */ jsx(PageBreakIcon, {})
3532
+ }
3533
+ );
3534
+ };
3535
+
3536
+ export { Highlight, HighlightButton, PageBreak, PageBreakButton, RichTextEditor };
3537
+ //# sourceMappingURL=index.js.map
3538
+ //# sourceMappingURL=index.js.map