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