@notum-cz/strapi-plugin-tiptap-editor 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +160 -0
  3. package/dist/_chunks/AccentCursive-CpAPpH9C.mjs +3383 -0
  4. package/dist/_chunks/AccentCursive-CpAPpH9C.mjs.map +1 -0
  5. package/dist/_chunks/AccentCursive-D6sTlhub.js +3384 -0
  6. package/dist/_chunks/AccentCursive-D6sTlhub.js.map +1 -0
  7. package/dist/_chunks/FormattedHeadingInput-DycgfIze.mjs +101 -0
  8. package/dist/_chunks/FormattedHeadingInput-DycgfIze.mjs.map +1 -0
  9. package/dist/_chunks/FormattedHeadingInput-FFjiRSEJ.js +101 -0
  10. package/dist/_chunks/FormattedHeadingInput-FFjiRSEJ.js.map +1 -0
  11. package/dist/_chunks/RichTextInput-BZQ2iVqa.mjs +4481 -0
  12. package/dist/_chunks/RichTextInput-BZQ2iVqa.mjs.map +1 -0
  13. package/dist/_chunks/RichTextInput-BbbQxPc-.js +4414 -0
  14. package/dist/_chunks/RichTextInput-BbbQxPc-.js.map +1 -0
  15. package/dist/_chunks/RichTextInput-BjLR2pi0.js +4416 -0
  16. package/dist/_chunks/RichTextInput-BjLR2pi0.js.map +1 -0
  17. package/dist/_chunks/RichTextInput-BlxoJMa2.js +4488 -0
  18. package/dist/_chunks/RichTextInput-BlxoJMa2.js.map +1 -0
  19. package/dist/_chunks/RichTextInput-Bm3X8fR2.mjs +4400 -0
  20. package/dist/_chunks/RichTextInput-Bm3X8fR2.mjs.map +1 -0
  21. package/dist/_chunks/RichTextInput-Bms-gSvK.js +4407 -0
  22. package/dist/_chunks/RichTextInput-Bms-gSvK.js.map +1 -0
  23. package/dist/_chunks/RichTextInput-BtNjPJRN.mjs +4400 -0
  24. package/dist/_chunks/RichTextInput-BtNjPJRN.mjs.map +1 -0
  25. package/dist/_chunks/RichTextInput-Bw3tcXfp.js +4407 -0
  26. package/dist/_chunks/RichTextInput-Bw3tcXfp.js.map +1 -0
  27. package/dist/_chunks/RichTextInput-CsgNpoxq.mjs +4409 -0
  28. package/dist/_chunks/RichTextInput-CsgNpoxq.mjs.map +1 -0
  29. package/dist/_chunks/RichTextInput-CwTvEMda.js +4407 -0
  30. package/dist/_chunks/RichTextInput-CwTvEMda.js.map +1 -0
  31. package/dist/_chunks/RichTextInput-DG-36krM.js +1181 -0
  32. package/dist/_chunks/RichTextInput-DG-36krM.js.map +1 -0
  33. package/dist/_chunks/RichTextInput-DLac-zNQ.mjs +4400 -0
  34. package/dist/_chunks/RichTextInput-DLac-zNQ.mjs.map +1 -0
  35. package/dist/_chunks/RichTextInput-DSXttrvi.js +4407 -0
  36. package/dist/_chunks/RichTextInput-DSXttrvi.js.map +1 -0
  37. package/dist/_chunks/RichTextInput-DeJ6Exto.mjs +4400 -0
  38. package/dist/_chunks/RichTextInput-DeJ6Exto.mjs.map +1 -0
  39. package/dist/_chunks/RichTextInput-DgT88AkO.mjs +1175 -0
  40. package/dist/_chunks/RichTextInput-DgT88AkO.mjs.map +1 -0
  41. package/dist/_chunks/RichTextInput-DlMaDJQF.mjs +4400 -0
  42. package/dist/_chunks/RichTextInput-DlMaDJQF.mjs.map +1 -0
  43. package/dist/_chunks/RichTextInput-DtaYdjCs.mjs +4400 -0
  44. package/dist/_chunks/RichTextInput-DtaYdjCs.mjs.map +1 -0
  45. package/dist/_chunks/RichTextInput-YTKXo5oq.js +4407 -0
  46. package/dist/_chunks/RichTextInput-YTKXo5oq.js.map +1 -0
  47. package/dist/_chunks/RichTextInput-tmg-oMJk.mjs +4407 -0
  48. package/dist/_chunks/RichTextInput-tmg-oMJk.mjs.map +1 -0
  49. package/dist/_chunks/RichTextInput-umhMsI5o.js +4407 -0
  50. package/dist/_chunks/RichTextInput-umhMsI5o.js.map +1 -0
  51. package/dist/_chunks/en-B4KWt_jN.js +5 -0
  52. package/dist/_chunks/en-B4KWt_jN.js.map +1 -0
  53. package/dist/_chunks/en-Byx4XI2L.mjs +5 -0
  54. package/dist/_chunks/en-Byx4XI2L.mjs.map +1 -0
  55. package/dist/admin/index.js +71 -0
  56. package/dist/admin/index.js.map +1 -0
  57. package/dist/admin/index.mjs +72 -0
  58. package/dist/admin/index.mjs.map +1 -0
  59. package/dist/admin/src/components/BaseTiptapInput.d.ts +12 -0
  60. package/dist/admin/src/components/FormattedHeadingInput.d.ts +4 -0
  61. package/dist/admin/src/components/Initializer.d.ts +5 -0
  62. package/dist/admin/src/components/LinkDialog.d.ts +14 -0
  63. package/dist/admin/src/components/RichTextInput.d.ts +4 -0
  64. package/dist/admin/src/components/Spacer.d.ts +3 -0
  65. package/dist/admin/src/components/TableSizeDialog.d.ts +10 -0
  66. package/dist/admin/src/components/TiptapInput.d.ts +7 -0
  67. package/dist/admin/src/components/TiptapInputStyles.d.ts +2 -0
  68. package/dist/admin/src/components/ToolbarButton.d.ts +11 -0
  69. package/dist/admin/src/extensions/AccentCursive.d.ts +18 -0
  70. package/dist/admin/src/extensions/Heading.d.ts +8 -0
  71. package/dist/admin/src/extensions/Link.d.ts +7 -0
  72. package/dist/admin/src/extensions/Script.d.ts +7 -0
  73. package/dist/admin/src/extensions/StarterKit.d.ts +13 -0
  74. package/dist/admin/src/extensions/Table.d.ts +11 -0
  75. package/dist/admin/src/extensions/TextAlign.d.ts +9 -0
  76. package/dist/admin/src/fields/formattedHeadingField.d.ts +20 -0
  77. package/dist/admin/src/fields/richTextField.d.ts +20 -0
  78. package/dist/admin/src/icons/TextAlignCenter.d.ts +2 -0
  79. package/dist/admin/src/icons/TextAlignJustify.d.ts +2 -0
  80. package/dist/admin/src/icons/TextAlignLeft.d.ts +2 -0
  81. package/dist/admin/src/icons/TextAlignRight.d.ts +2 -0
  82. package/dist/admin/src/index.d.ts +10 -0
  83. package/dist/admin/src/pluginId.d.ts +1 -0
  84. package/dist/admin/src/utils/getTranslation.d.ts +2 -0
  85. package/dist/admin/src/utils/tiptapUtils.d.ts +18 -0
  86. package/dist/server/index.js +44 -0
  87. package/dist/server/index.js.map +1 -0
  88. package/dist/server/index.mjs +45 -0
  89. package/dist/server/index.mjs.map +1 -0
  90. package/dist/server/src/bootstrap.d.ts +5 -0
  91. package/dist/server/src/config/index.d.ts +5 -0
  92. package/dist/server/src/content-types/index.d.ts +2 -0
  93. package/dist/server/src/controllers/index.d.ts +2 -0
  94. package/dist/server/src/destroy.d.ts +5 -0
  95. package/dist/server/src/fields/richTextField.d.ts +2 -0
  96. package/dist/server/src/index.d.ts +25 -0
  97. package/dist/server/src/middlewares/index.d.ts +2 -0
  98. package/dist/server/src/policies/index.d.ts +2 -0
  99. package/dist/server/src/register.d.ts +5 -0
  100. package/dist/server/src/routes/index.d.ts +2 -0
  101. package/dist/server/src/services/index.d.ts +2 -0
  102. package/dist/shared/fields.d.ts +1 -0
  103. package/dist/shared/pluginId.d.ts +1 -0
  104. package/package.json +80 -0
@@ -0,0 +1,4400 @@
1
+ import { jsxs, jsx, Fragment as Fragment$1 } from "react/jsx-runtime";
2
+ import { Field, Box, Flex, Tooltip, Button, Dialog, TextInput, SingleSelect, SingleSelectOption } from "@strapi/design-system";
3
+ import { EditorContent, useEditor, useEditorState } from "@tiptap/react";
4
+ import styled from "styled-components";
5
+ import React, { forwardRef, useState, useRef, useEffect } from "react";
6
+ import { useField } from "@strapi/strapi/admin";
7
+ import StarterKit from "@tiptap/starter-kit";
8
+ import { Quotes, Code, NumberList, BulletList, StrikeThrough, Underline, Italic, Bold, Link, GridNine } from "@strapi/icons";
9
+ import { RemoveMarkStep, Transform, liftTarget, joinPoint, canSplit, ReplaceStep, ReplaceAroundStep, canJoin } from "@tiptap/pm/transform";
10
+ import { createParagraphNear as createParagraphNear$1, deleteSelection as deleteSelection$1, exitCode as exitCode$1, joinUp as joinUp$1, joinDown as joinDown$1, joinBackward as joinBackward$1, joinForward as joinForward$1, joinTextblockBackward as joinTextblockBackward$1, joinTextblockForward as joinTextblockForward$1, lift as lift$1, liftEmptyBlock as liftEmptyBlock$1, newlineInCode as newlineInCode$1, selectNodeBackward as selectNodeBackward$1, selectNodeForward as selectNodeForward$1, selectParentNode as selectParentNode$1, selectTextblockEnd as selectTextblockEnd$1, selectTextblockStart as selectTextblockStart$1, setBlockType, wrapIn as wrapIn$1 } from "@tiptap/pm/commands";
11
+ import { Plugin, PluginKey, Selection, NodeSelection, TextSelection, AllSelection } from "@tiptap/pm/state";
12
+ import { Fragment, Slice, Node, Schema, DOMParser } from "@tiptap/pm/model";
13
+ import { liftListItem as liftListItem$1, sinkListItem as sinkListItem$1, wrapInList as wrapInList$1 } from "@tiptap/pm/schema-list";
14
+ import { DecorationSet, Decoration } from "@tiptap/pm/view";
15
+ import "@tiptap/pm/keymap";
16
+ import Superscript from "@tiptap/extension-superscript";
17
+ import Subscript from "@tiptap/extension-subscript";
18
+ import { TableKit } from "@tiptap/extension-table";
19
+ import { dropCursor } from "@tiptap/pm/dropcursor";
20
+ import { gapCursor } from "@tiptap/pm/gapcursor";
21
+ import { history, redo, undo } from "@tiptap/pm/history";
22
+ import TextAlign from "@tiptap/extension-text-align";
23
+ const TiptapInputStyles = styled.div`
24
+ .editor-toolbar {
25
+ margin-bottom: 0.25rem;
26
+ padding-bottom: 0.25rem;
27
+ }
28
+
29
+ .ProseMirror {
30
+ font-size: 1.4rem; /* Increase editor font size to match Strapi default */
31
+ outline: none;
32
+ max-height: 60vh;
33
+ min-height: 15vh;
34
+ overflow-y: auto;
35
+ padding: 1rem;
36
+ }
37
+
38
+ /* Remove unnecessary margin at the top of the editor */
39
+ .ProseMirror *:first-child {
40
+ margin-top: 0;
41
+ }
42
+
43
+ /* --- Basic text styles --- */
44
+
45
+ .ProseMirror p {
46
+ margin: 0 0 12px;
47
+ }
48
+
49
+ .ProseMirror p:last-child {
50
+ margin-bottom: 0;
51
+ }
52
+
53
+ .ProseMirror h1,
54
+ .ProseMirror h2,
55
+ .ProseMirror h3,
56
+ .ProseMirror h4 {
57
+ font-weight: 600;
58
+ line-height: 1.25;
59
+ margin: 1em 0 0.5em;
60
+ }
61
+
62
+ .ProseMirror h1 {
63
+ font-size: 4rem;
64
+ }
65
+
66
+ .ProseMirror h2 {
67
+ font-size: 3.2rem;
68
+ }
69
+
70
+ .ProseMirror h3 {
71
+ font-size: 2.5rem;
72
+ }
73
+
74
+ .ProseMirror h4 {
75
+ font-size: 2rem;
76
+ }
77
+
78
+ .ProseMirror ul,
79
+ .ProseMirror ol {
80
+ margin: 0.75em 0 1em;
81
+ padding-left: 1.5rem;
82
+ }
83
+
84
+ .ProseMirror ul {
85
+ list-style: disc;
86
+ }
87
+
88
+ .ProseMirror ol {
89
+ list-style: decimal;
90
+ }
91
+
92
+ .ProseMirror li {
93
+ margin: 0.25em 0;
94
+ }
95
+
96
+ .ProseMirror blockquote {
97
+ border-left: 3px solid #222;
98
+ margin: 1em 0;
99
+ padding: 0.25em 1rem;
100
+ font-style: italic;
101
+ background: #fafafa;
102
+ }
103
+
104
+ .ProseMirror code {
105
+ background: #f3f3f3;
106
+ padding: 2px 4px;
107
+ border-radius: 4px;
108
+ font-family:
109
+ ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', monospace;
110
+ font-size: 0.9em;
111
+ }
112
+
113
+ .ProseMirror a {
114
+ color: #0c75af;
115
+ text-decoration: underline;
116
+ }
117
+
118
+ .ProseMirror strong {
119
+ font-weight: 600;
120
+ }
121
+
122
+ .ProseMirror em {
123
+ font-style: italic;
124
+ }
125
+
126
+ .ProseMirror u {
127
+ text-decoration: underline;
128
+ }
129
+
130
+ .ProseMirror s {
131
+ text-decoration: line-through;
132
+ }
133
+
134
+ // Source: https://tiptap.dev/docs/editor/extensions/nodes/table
135
+
136
+ .ProseMirror {
137
+ table {
138
+ border-collapse: collapse;
139
+ margin: 0;
140
+ overflow: hidden;
141
+ table-layout: fixed;
142
+ width: 100%;
143
+
144
+ td,
145
+ th {
146
+ border: 1px solid #ddd;
147
+ box-sizing: border-box;
148
+ min-width: 1em;
149
+ padding: 6px 8px;
150
+ position: relative;
151
+ vertical-align: top;
152
+
153
+ > * {
154
+ margin-bottom: 0;
155
+ }
156
+ }
157
+
158
+ /* It is not possible to distinguish header vs body cells when rendering
159
+ content in React. So we render all as td and the user should use bold text
160
+ in cells. */
161
+ th {
162
+ background-color: inherit;
163
+ font-weight: normal;
164
+ text-align: left;
165
+ }
166
+
167
+ .selectedCell:after {
168
+ background: rgba(0, 37, 159, 0.32);
169
+ content: '';
170
+ left: 0;
171
+ right: 0;
172
+ top: 0;
173
+ bottom: 0;
174
+ pointer-events: none;
175
+ position: absolute;
176
+ z-index: 2;
177
+ }
178
+
179
+ .column-resize-handle {
180
+ background-color: purple;
181
+ bottom: -2px;
182
+ pointer-events: none;
183
+ position: absolute;
184
+ right: -2px;
185
+ top: 0;
186
+ width: 4px;
187
+ }
188
+ }
189
+
190
+ .tableWrapper {
191
+ margin: 1.5rem 0;
192
+ overflow-x: auto;
193
+ }
194
+
195
+ &.resize-cursor {
196
+ cursor: ew-resize;
197
+ cursor: col-resize;
198
+ }
199
+ }
200
+
201
+ /* --- Only Cursive --- */
202
+ /* How the only cursive text looks like in editor */
203
+
204
+ .only-cursive {
205
+ font-style: italic;
206
+ font-weight: bold;
207
+ }
208
+ `;
209
+ const BaseTiptapInput = forwardRef(
210
+ ({ hint, disabled = false, labelAction, label, name, required = false, editor, field, children }, forwardedRef) => {
211
+ const borderColor = field.error ? "danger600" : "neutral200";
212
+ const background = disabled ? "neutral200" : "neutral100";
213
+ return /* @__PURE__ */ jsxs(Field.Root, { name, id: name, hint, error: field.error, required, children: [
214
+ /* @__PURE__ */ jsx(Field.Label, { action: labelAction, children: label }),
215
+ /* @__PURE__ */ jsx(TiptapInputStyles, { children: /* @__PURE__ */ jsxs(
216
+ Box,
217
+ {
218
+ className: `tiptap-editor-wrapper ${field.error ? "has-error" : ""} ${disabled ? "is-disabled" : ""}`,
219
+ hasRadius: true,
220
+ borderColor,
221
+ background,
222
+ paddingTop: 1,
223
+ paddingBottom: 0,
224
+ paddingLeft: 0,
225
+ paddingRight: 0,
226
+ children: [
227
+ /* @__PURE__ */ jsx(Box, { className: "editor-toolbar", paddingLeft: 2, paddingRight: 2, paddingBottom: 2, children: /* @__PURE__ */ jsx(Flex, { gap: 1, wrap: "wrap", children }) }),
228
+ /* @__PURE__ */ jsx(
229
+ Box,
230
+ {
231
+ className: "editor-content",
232
+ background: "neutral0",
233
+ paddingTop: 2,
234
+ paddingBottom: 2,
235
+ paddingLeft: 2,
236
+ paddingRight: 2,
237
+ children: /* @__PURE__ */ jsx(EditorContent, { editor, disabled, ref: forwardedRef })
238
+ }
239
+ )
240
+ ]
241
+ }
242
+ ) }),
243
+ /* @__PURE__ */ jsx(Field.Hint, {}),
244
+ /* @__PURE__ */ jsx(Field.Error, {})
245
+ ] });
246
+ }
247
+ );
248
+ function tiptapContent(text) {
249
+ return {
250
+ type: "doc",
251
+ content: [
252
+ {
253
+ type: "paragraph",
254
+ content: [
255
+ {
256
+ type: "text",
257
+ text
258
+ }
259
+ ]
260
+ }
261
+ ]
262
+ };
263
+ }
264
+ function parseJSONContent(value, defaultValue) {
265
+ if (!value) {
266
+ return tiptapContent(defaultValue);
267
+ }
268
+ try {
269
+ return typeof value === "string" ? JSON.parse(value) : value;
270
+ } catch (e) {
271
+ console.error("Failed to parse JSON content:", e);
272
+ return tiptapContent(`
273
+ This component's content is malformed. Please change it or remove this component.
274
+ Original content: ${JSON.stringify(value)}
275
+ `);
276
+ }
277
+ }
278
+ function useTiptapEditor(name, defaultValue = "", extensions2 = []) {
279
+ const field = useField(name);
280
+ const editor = useEditor({
281
+ extensions: extensions2,
282
+ content: parseJSONContent(field.value, defaultValue),
283
+ onUpdate: ({ editor: editor2 }) => {
284
+ const json = editor2.getJSON();
285
+ field.onChange(name, JSON.stringify(json));
286
+ }
287
+ });
288
+ return { editor, field };
289
+ }
290
+ function toolbarButton(key, {
291
+ onClick,
292
+ icon,
293
+ active,
294
+ disabled,
295
+ tooltip,
296
+ marginLeft,
297
+ hidden
298
+ }) {
299
+ return /* @__PURE__ */ jsx(Tooltip, { description: tooltip, children: /* @__PURE__ */ jsx(
300
+ Button,
301
+ {
302
+ onClick,
303
+ variant: "tertiary",
304
+ size: "S",
305
+ paddingLeft: 2,
306
+ paddingRight: 2,
307
+ marginLeft: marginLeft ?? 1,
308
+ disabled,
309
+ style: {
310
+ color: active ? "black" : void 0,
311
+ backgroundColor: active ? "#d9d8ff" : void 0,
312
+ display: hidden ? "none" : void 0
313
+ },
314
+ children: icon
315
+ }
316
+ ) }, key);
317
+ }
318
+ function spacer(width) {
319
+ return /* @__PURE__ */ jsx("div", { style: { width: width + "px" } });
320
+ }
321
+ function useStarterKit(editor, props = { disabled: false }) {
322
+ const editorState = useEditorState({
323
+ editor,
324
+ selector: (ctx) => {
325
+ return {
326
+ isBold: ctx.editor.isActive("bold") ?? false,
327
+ canBold: ctx.editor.can().chain().toggleBold().run() ?? false,
328
+ isItalic: ctx.editor.isActive("italic") ?? false,
329
+ canItalic: ctx.editor.can().chain().toggleItalic().run() ?? false,
330
+ isUnderline: ctx.editor.isActive("underline") ?? false,
331
+ canUnderline: ctx.editor.can().chain().toggleUnderline().run() ?? false,
332
+ isStrike: ctx.editor.isActive("strike") ?? false,
333
+ canStrike: ctx.editor.can().chain().toggleStrike().run() ?? false,
334
+ isCode: ctx.editor.isActive("code") ?? false,
335
+ canCode: ctx.editor.can().chain().toggleCode().run() ?? false,
336
+ isBulletList: ctx.editor.isActive("bulletList") ?? false,
337
+ canToggleBulletList: ctx.editor.can().chain().toggleBulletList().run() ?? false,
338
+ isOrderedList: ctx.editor.isActive("orderedList") ?? false,
339
+ canToggleOrderedList: ctx.editor.can().chain().toggleOrderedList().run() ?? false,
340
+ isBlockquote: ctx.editor.isActive("blockquote") ?? false,
341
+ canToggleBlockquote: ctx.editor.can().chain().toggleBlockquote().run() ?? false
342
+ };
343
+ }
344
+ });
345
+ const toggleBold = () => editor?.chain().focus().toggleBold().run();
346
+ const toggleItalic = () => editor?.chain().focus().toggleItalic().run();
347
+ const toggleUnderline = () => editor?.chain().focus().toggleUnderline().run();
348
+ const toggleStrike = () => editor?.chain().focus().toggleStrike().run();
349
+ const toggleCode = () => editor?.chain().focus().toggleCode().run();
350
+ const toggleBulletList = () => editor?.chain().focus().toggleBulletList().run();
351
+ const toggleOrderedList = () => editor?.chain().focus().toggleOrderedList().run();
352
+ const toggleBlockquote = () => editor?.chain().focus().toggleBlockquote().run();
353
+ return {
354
+ boldButton: toolbarButton("bold", {
355
+ onClick: toggleBold,
356
+ icon: /* @__PURE__ */ jsx(Bold, {}),
357
+ active: editorState.isBold,
358
+ disabled: props.disabled || !editor || !editorState.canBold,
359
+ tooltip: "Bold"
360
+ }),
361
+ italicButton: toolbarButton("italic", {
362
+ onClick: toggleItalic,
363
+ icon: /* @__PURE__ */ jsx(Italic, {}),
364
+ active: editorState.isItalic,
365
+ disabled: props.disabled || !editor || !editorState.canItalic,
366
+ tooltip: "Italic"
367
+ }),
368
+ underlineButton: toolbarButton("underline", {
369
+ onClick: toggleUnderline,
370
+ icon: /* @__PURE__ */ jsx(Underline, {}),
371
+ active: editorState.isUnderline,
372
+ disabled: props.disabled || !editor || !editorState.canUnderline,
373
+ tooltip: "Underline"
374
+ }),
375
+ strikeButton: toolbarButton("strike", {
376
+ onClick: toggleStrike,
377
+ icon: /* @__PURE__ */ jsx(StrikeThrough, {}),
378
+ active: editorState.isStrike,
379
+ disabled: props.disabled || !editor || !editorState.canStrike,
380
+ tooltip: "Strikethrough"
381
+ }),
382
+ bulletButton: toolbarButton("bullet", {
383
+ onClick: toggleBulletList,
384
+ icon: /* @__PURE__ */ jsx(BulletList, {}),
385
+ active: editorState.isBulletList,
386
+ disabled: props.disabled || !editor || !editorState.canToggleBulletList,
387
+ tooltip: "Bullet list"
388
+ }),
389
+ orderedButton: toolbarButton("ordered", {
390
+ onClick: toggleOrderedList,
391
+ icon: /* @__PURE__ */ jsx(NumberList, {}),
392
+ active: editorState.isOrderedList,
393
+ disabled: props.disabled || !editor || !editorState.canToggleOrderedList,
394
+ tooltip: "Numbered list"
395
+ }),
396
+ codeButton: toolbarButton("code", {
397
+ onClick: toggleCode,
398
+ icon: /* @__PURE__ */ jsx(Code, {}),
399
+ active: editorState.isCode,
400
+ disabled: props.disabled || !editor || !editorState.canCode,
401
+ tooltip: "Inline code"
402
+ }),
403
+ blockquoteButton: toolbarButton("quote", {
404
+ onClick: toggleBlockquote,
405
+ icon: /* @__PURE__ */ jsx(Quotes, {}),
406
+ active: editorState.isBlockquote,
407
+ disabled: props.disabled || !editor || !editorState.canToggleBlockquote,
408
+ tooltip: "Quote"
409
+ })
410
+ };
411
+ }
412
+ const LinkDialog = ({
413
+ open,
414
+ url,
415
+ mode,
416
+ onClose,
417
+ onSave,
418
+ onRemove
419
+ }) => {
420
+ const [value, setValue] = React.useState(url || "");
421
+ React.useEffect(() => {
422
+ if (open) {
423
+ setValue(url || "");
424
+ }
425
+ }, [open, url, mode]);
426
+ const handleSave = () => {
427
+ onSave({ url: value.trim() });
428
+ };
429
+ const isSaveDisabled = mode === "add" ? value.trim() === "" : false;
430
+ return /* @__PURE__ */ jsx(
431
+ Dialog.Root,
432
+ {
433
+ open,
434
+ onOpenChange: (v) => {
435
+ if (!v) onClose();
436
+ },
437
+ children: open && /* @__PURE__ */ jsxs(Dialog.Content, { children: [
438
+ /* @__PURE__ */ jsx(Dialog.Header, { children: mode === "add" ? "Add link" : "Edit link" }),
439
+ /* @__PURE__ */ jsx(Dialog.Body, { children: /* @__PURE__ */ jsxs(Field.Root, { width: "100%", children: [
440
+ /* @__PURE__ */ jsx(Field.Label, { children: "URL" }),
441
+ /* @__PURE__ */ jsx(
442
+ TextInput,
443
+ {
444
+ name: "link-url",
445
+ placeholder: "https://example.com",
446
+ value,
447
+ onChange: (e) => setValue(e.target.value)
448
+ }
449
+ )
450
+ ] }) }),
451
+ /* @__PURE__ */ jsxs(Dialog.Footer, { children: [
452
+ /* @__PURE__ */ jsx(Dialog.Cancel, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", fullWidth: true, onClick: onClose, children: "Cancel" }) }),
453
+ mode === "edit" && /* @__PURE__ */ jsx(Button, { variant: "danger-light", fullWidth: true, onClick: onRemove, children: "Remove link" }),
454
+ /* @__PURE__ */ jsx(Dialog.Action, { children: /* @__PURE__ */ jsx(
455
+ Button,
456
+ {
457
+ fullWidth: true,
458
+ variant: "success-light",
459
+ onClick: handleSave,
460
+ disabled: isSaveDisabled,
461
+ children: "Save"
462
+ }
463
+ ) })
464
+ ] })
465
+ ] })
466
+ }
467
+ );
468
+ };
469
+ function useLink(editor, props = { disabled: false }) {
470
+ const editorState = useEditorState({
471
+ editor,
472
+ selector: (ctx) => {
473
+ return {
474
+ isLink: ctx.editor.isActive("link") ?? false,
475
+ canSetLink: ctx.editor.can().setLink?.({ href: "https://example.com" }) ?? true
476
+ };
477
+ }
478
+ });
479
+ const [showLinkDialog, setShowLinkDialog] = useState(false);
480
+ const [currentLinkUrl, setCurrentLinkUrl] = useState("");
481
+ const [linkDialogMode, setLinkDialogMode] = useState("add");
482
+ const selectionRef = useRef(null);
483
+ const openAddLinkDialog = () => {
484
+ if (!editor) return;
485
+ const { from, to } = editor.state.selection;
486
+ selectionRef.current = { from, to };
487
+ setCurrentLinkUrl("");
488
+ setLinkDialogMode("add");
489
+ setShowLinkDialog(true);
490
+ };
491
+ const openEditLinkDialog = () => {
492
+ if (!editor) return;
493
+ const { from, to } = editor.state.selection;
494
+ selectionRef.current = { from, to };
495
+ const currentHref = editor.getAttributes("link").href || "";
496
+ setCurrentLinkUrl(currentHref);
497
+ setLinkDialogMode("edit");
498
+ setShowLinkDialog(true);
499
+ };
500
+ const toggleLink = () => {
501
+ if (!editor) return;
502
+ if (editorState.isLink) {
503
+ openEditLinkDialog();
504
+ } else {
505
+ openAddLinkDialog();
506
+ }
507
+ };
508
+ const restoreSelection = () => {
509
+ if (!editor) return;
510
+ const sel = selectionRef.current;
511
+ if (sel) {
512
+ editor.chain().setTextSelection({ from: sel.from, to: sel.to }).run();
513
+ }
514
+ };
515
+ const handleSaveEditedLink = ({ url }) => {
516
+ if (!editor) return;
517
+ restoreSelection();
518
+ const chain = editor.chain().focus().extendMarkRange("link");
519
+ if (url === "") {
520
+ chain.unsetLink().run();
521
+ } else {
522
+ chain.updateAttributes("link", { href: url }).run();
523
+ }
524
+ setShowLinkDialog(false);
525
+ };
526
+ const handleRemoveLink = () => {
527
+ if (!editor) return;
528
+ restoreSelection();
529
+ editor.chain().focus().extendMarkRange("link").unsetLink().run();
530
+ setShowLinkDialog(false);
531
+ };
532
+ const handleSaveNewLink = ({ url }) => {
533
+ if (!editor) return;
534
+ restoreSelection();
535
+ editor.chain().focus().setLink({ href: url }).run();
536
+ setShowLinkDialog(false);
537
+ };
538
+ return {
539
+ linkButton: toolbarButton("link", {
540
+ onClick: toggleLink,
541
+ icon: /* @__PURE__ */ jsx(Link, {}),
542
+ active: editorState.isLink,
543
+ disabled: props.disabled || !editor || !editorState.canSetLink,
544
+ tooltip: editorState.isLink ? "Edit or remove link" : "Add link"
545
+ }),
546
+ linkDialog: /* @__PURE__ */ jsx(
547
+ LinkDialog,
548
+ {
549
+ open: showLinkDialog,
550
+ url: currentLinkUrl,
551
+ mode: linkDialogMode,
552
+ onClose: () => setShowLinkDialog(false),
553
+ onSave: linkDialogMode === "add" ? handleSaveNewLink : handleSaveEditedLink,
554
+ onRemove: handleRemoveLink
555
+ }
556
+ )
557
+ };
558
+ }
559
+ var __defProp = Object.defineProperty;
560
+ var __export = (target, all) => {
561
+ for (var name in all)
562
+ __defProp(target, name, { get: all[name], enumerable: true });
563
+ };
564
+ function createChainableState(config) {
565
+ const { state, transaction } = config;
566
+ let { selection } = transaction;
567
+ let { doc } = transaction;
568
+ let { storedMarks } = transaction;
569
+ return {
570
+ ...state,
571
+ apply: state.apply.bind(state),
572
+ applyTransaction: state.applyTransaction.bind(state),
573
+ plugins: state.plugins,
574
+ schema: state.schema,
575
+ reconfigure: state.reconfigure.bind(state),
576
+ toJSON: state.toJSON.bind(state),
577
+ get storedMarks() {
578
+ return storedMarks;
579
+ },
580
+ get selection() {
581
+ return selection;
582
+ },
583
+ get doc() {
584
+ return doc;
585
+ },
586
+ get tr() {
587
+ selection = transaction.selection;
588
+ doc = transaction.doc;
589
+ storedMarks = transaction.storedMarks;
590
+ return transaction;
591
+ }
592
+ };
593
+ }
594
+ var CommandManager = class {
595
+ constructor(props) {
596
+ this.editor = props.editor;
597
+ this.rawCommands = this.editor.extensionManager.commands;
598
+ this.customState = props.state;
599
+ }
600
+ get hasCustomState() {
601
+ return !!this.customState;
602
+ }
603
+ get state() {
604
+ return this.customState || this.editor.state;
605
+ }
606
+ get commands() {
607
+ const { rawCommands, editor, state } = this;
608
+ const { view } = editor;
609
+ const { tr } = state;
610
+ const props = this.buildProps(tr);
611
+ return Object.fromEntries(
612
+ Object.entries(rawCommands).map(([name, command2]) => {
613
+ const method = (...args) => {
614
+ const callback = command2(...args)(props);
615
+ if (!tr.getMeta("preventDispatch") && !this.hasCustomState) {
616
+ view.dispatch(tr);
617
+ }
618
+ return callback;
619
+ };
620
+ return [name, method];
621
+ })
622
+ );
623
+ }
624
+ get chain() {
625
+ return () => this.createChain();
626
+ }
627
+ get can() {
628
+ return () => this.createCan();
629
+ }
630
+ createChain(startTr, shouldDispatch = true) {
631
+ const { rawCommands, editor, state } = this;
632
+ const { view } = editor;
633
+ const callbacks = [];
634
+ const hasStartTransaction = !!startTr;
635
+ const tr = startTr || state.tr;
636
+ const run3 = () => {
637
+ if (!hasStartTransaction && shouldDispatch && !tr.getMeta("preventDispatch") && !this.hasCustomState) {
638
+ view.dispatch(tr);
639
+ }
640
+ return callbacks.every((callback) => callback === true);
641
+ };
642
+ const chain = {
643
+ ...Object.fromEntries(
644
+ Object.entries(rawCommands).map(([name, command2]) => {
645
+ const chainedCommand = (...args) => {
646
+ const props = this.buildProps(tr, shouldDispatch);
647
+ const callback = command2(...args)(props);
648
+ callbacks.push(callback);
649
+ return chain;
650
+ };
651
+ return [name, chainedCommand];
652
+ })
653
+ ),
654
+ run: run3
655
+ };
656
+ return chain;
657
+ }
658
+ createCan(startTr) {
659
+ const { rawCommands, state } = this;
660
+ const dispatch = false;
661
+ const tr = startTr || state.tr;
662
+ const props = this.buildProps(tr, dispatch);
663
+ const formattedCommands = Object.fromEntries(
664
+ Object.entries(rawCommands).map(([name, command2]) => {
665
+ return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
666
+ })
667
+ );
668
+ return {
669
+ ...formattedCommands,
670
+ chain: () => this.createChain(tr, dispatch)
671
+ };
672
+ }
673
+ buildProps(tr, shouldDispatch = true) {
674
+ const { rawCommands, editor, state } = this;
675
+ const { view } = editor;
676
+ const props = {
677
+ tr,
678
+ editor,
679
+ view,
680
+ state: createChainableState({
681
+ state,
682
+ transaction: tr
683
+ }),
684
+ dispatch: shouldDispatch ? () => void 0 : void 0,
685
+ chain: () => this.createChain(tr, shouldDispatch),
686
+ can: () => this.createCan(tr),
687
+ get commands() {
688
+ return Object.fromEntries(
689
+ Object.entries(rawCommands).map(([name, command2]) => {
690
+ return [name, (...args) => command2(...args)(props)];
691
+ })
692
+ );
693
+ }
694
+ };
695
+ return props;
696
+ }
697
+ };
698
+ var commands_exports = {};
699
+ __export(commands_exports, {
700
+ blur: () => blur,
701
+ clearContent: () => clearContent,
702
+ clearNodes: () => clearNodes,
703
+ command: () => command,
704
+ createParagraphNear: () => createParagraphNear,
705
+ cut: () => cut,
706
+ deleteCurrentNode: () => deleteCurrentNode,
707
+ deleteNode: () => deleteNode,
708
+ deleteRange: () => deleteRange,
709
+ deleteSelection: () => deleteSelection,
710
+ enter: () => enter,
711
+ exitCode: () => exitCode,
712
+ extendMarkRange: () => extendMarkRange,
713
+ first: () => first,
714
+ focus: () => focus,
715
+ forEach: () => forEach,
716
+ insertContent: () => insertContent,
717
+ insertContentAt: () => insertContentAt,
718
+ joinBackward: () => joinBackward,
719
+ joinDown: () => joinDown,
720
+ joinForward: () => joinForward,
721
+ joinItemBackward: () => joinItemBackward,
722
+ joinItemForward: () => joinItemForward,
723
+ joinTextblockBackward: () => joinTextblockBackward,
724
+ joinTextblockForward: () => joinTextblockForward,
725
+ joinUp: () => joinUp,
726
+ keyboardShortcut: () => keyboardShortcut,
727
+ lift: () => lift,
728
+ liftEmptyBlock: () => liftEmptyBlock,
729
+ liftListItem: () => liftListItem,
730
+ newlineInCode: () => newlineInCode,
731
+ resetAttributes: () => resetAttributes,
732
+ scrollIntoView: () => scrollIntoView,
733
+ selectAll: () => selectAll,
734
+ selectNodeBackward: () => selectNodeBackward,
735
+ selectNodeForward: () => selectNodeForward,
736
+ selectParentNode: () => selectParentNode,
737
+ selectTextblockEnd: () => selectTextblockEnd,
738
+ selectTextblockStart: () => selectTextblockStart,
739
+ setContent: () => setContent,
740
+ setMark: () => setMark,
741
+ setMeta: () => setMeta,
742
+ setNode: () => setNode,
743
+ setNodeSelection: () => setNodeSelection,
744
+ setTextDirection: () => setTextDirection,
745
+ setTextSelection: () => setTextSelection,
746
+ sinkListItem: () => sinkListItem,
747
+ splitBlock: () => splitBlock,
748
+ splitListItem: () => splitListItem,
749
+ toggleList: () => toggleList,
750
+ toggleMark: () => toggleMark,
751
+ toggleNode: () => toggleNode,
752
+ toggleWrap: () => toggleWrap,
753
+ undoInputRule: () => undoInputRule,
754
+ unsetAllMarks: () => unsetAllMarks,
755
+ unsetMark: () => unsetMark,
756
+ unsetTextDirection: () => unsetTextDirection,
757
+ updateAttributes: () => updateAttributes,
758
+ wrapIn: () => wrapIn,
759
+ wrapInList: () => wrapInList
760
+ });
761
+ var blur = () => ({ editor, view }) => {
762
+ requestAnimationFrame(() => {
763
+ var _a;
764
+ if (!editor.isDestroyed) {
765
+ view.dom.blur();
766
+ (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges();
767
+ }
768
+ });
769
+ return true;
770
+ };
771
+ var clearContent = (emitUpdate = true) => ({ commands }) => {
772
+ return commands.setContent("", { emitUpdate });
773
+ };
774
+ var clearNodes = () => ({ state, tr, dispatch }) => {
775
+ const { selection } = tr;
776
+ const { ranges } = selection;
777
+ if (!dispatch) {
778
+ return true;
779
+ }
780
+ ranges.forEach(({ $from, $to }) => {
781
+ state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
782
+ if (node.type.isText) {
783
+ return;
784
+ }
785
+ const { doc, mapping } = tr;
786
+ const $mappedFrom = doc.resolve(mapping.map(pos));
787
+ const $mappedTo = doc.resolve(mapping.map(pos + node.nodeSize));
788
+ const nodeRange = $mappedFrom.blockRange($mappedTo);
789
+ if (!nodeRange) {
790
+ return;
791
+ }
792
+ const targetLiftDepth = liftTarget(nodeRange);
793
+ if (node.type.isTextblock) {
794
+ const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
795
+ tr.setNodeMarkup(nodeRange.start, defaultType);
796
+ }
797
+ if (targetLiftDepth || targetLiftDepth === 0) {
798
+ tr.lift(nodeRange, targetLiftDepth);
799
+ }
800
+ });
801
+ });
802
+ return true;
803
+ };
804
+ var command = (fn) => (props) => {
805
+ return fn(props);
806
+ };
807
+ var createParagraphNear = () => ({ state, dispatch }) => {
808
+ return createParagraphNear$1(state, dispatch);
809
+ };
810
+ var cut = (originRange, targetPos) => ({ editor, tr }) => {
811
+ const { state } = editor;
812
+ const contentSlice = state.doc.slice(originRange.from, originRange.to);
813
+ tr.deleteRange(originRange.from, originRange.to);
814
+ const newPos = tr.mapping.map(targetPos);
815
+ tr.insert(newPos, contentSlice.content);
816
+ tr.setSelection(new TextSelection(tr.doc.resolve(Math.max(newPos - 1, 0))));
817
+ return true;
818
+ };
819
+ var deleteCurrentNode = () => ({ tr, dispatch }) => {
820
+ const { selection } = tr;
821
+ const currentNode = selection.$anchor.node();
822
+ if (currentNode.content.size > 0) {
823
+ return false;
824
+ }
825
+ const $pos = tr.selection.$anchor;
826
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
827
+ const node = $pos.node(depth);
828
+ if (node.type === currentNode.type) {
829
+ if (dispatch) {
830
+ const from = $pos.before(depth);
831
+ const to = $pos.after(depth);
832
+ tr.delete(from, to).scrollIntoView();
833
+ }
834
+ return true;
835
+ }
836
+ }
837
+ return false;
838
+ };
839
+ function getNodeType(nameOrType, schema) {
840
+ if (typeof nameOrType === "string") {
841
+ if (!schema.nodes[nameOrType]) {
842
+ throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
843
+ }
844
+ return schema.nodes[nameOrType];
845
+ }
846
+ return nameOrType;
847
+ }
848
+ var deleteNode = (typeOrName) => ({ tr, state, dispatch }) => {
849
+ const type = getNodeType(typeOrName, state.schema);
850
+ const $pos = tr.selection.$anchor;
851
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
852
+ const node = $pos.node(depth);
853
+ if (node.type === type) {
854
+ if (dispatch) {
855
+ const from = $pos.before(depth);
856
+ const to = $pos.after(depth);
857
+ tr.delete(from, to).scrollIntoView();
858
+ }
859
+ return true;
860
+ }
861
+ }
862
+ return false;
863
+ };
864
+ var deleteRange = (range) => ({ tr, dispatch }) => {
865
+ const { from, to } = range;
866
+ if (dispatch) {
867
+ tr.delete(from, to);
868
+ }
869
+ return true;
870
+ };
871
+ var deleteSelection = () => ({ state, dispatch }) => {
872
+ return deleteSelection$1(state, dispatch);
873
+ };
874
+ var enter = () => ({ commands }) => {
875
+ return commands.keyboardShortcut("Enter");
876
+ };
877
+ var exitCode = () => ({ state, dispatch }) => {
878
+ return exitCode$1(state, dispatch);
879
+ };
880
+ function isRegExp(value) {
881
+ return Object.prototype.toString.call(value) === "[object RegExp]";
882
+ }
883
+ function objectIncludes(object1, object2, options = { strict: true }) {
884
+ const keys = Object.keys(object2);
885
+ if (!keys.length) {
886
+ return true;
887
+ }
888
+ return keys.every((key) => {
889
+ if (options.strict) {
890
+ return object2[key] === object1[key];
891
+ }
892
+ if (isRegExp(object2[key])) {
893
+ return object2[key].test(object1[key]);
894
+ }
895
+ return object2[key] === object1[key];
896
+ });
897
+ }
898
+ function findMarkInSet(marks, type, attributes = {}) {
899
+ return marks.find((item) => {
900
+ return item.type === type && objectIncludes(
901
+ // Only check equality for the attributes that are provided
902
+ Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])),
903
+ attributes
904
+ );
905
+ });
906
+ }
907
+ function isMarkInSet(marks, type, attributes = {}) {
908
+ return !!findMarkInSet(marks, type, attributes);
909
+ }
910
+ function getMarkRange($pos, type, attributes) {
911
+ var _a;
912
+ if (!$pos || !type) {
913
+ return;
914
+ }
915
+ let start = $pos.parent.childAfter($pos.parentOffset);
916
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
917
+ start = $pos.parent.childBefore($pos.parentOffset);
918
+ }
919
+ if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
920
+ return;
921
+ }
922
+ attributes = attributes || ((_a = start.node.marks[0]) == null ? void 0 : _a.attrs);
923
+ const mark = findMarkInSet([...start.node.marks], type, attributes);
924
+ if (!mark) {
925
+ return;
926
+ }
927
+ let startIndex = start.index;
928
+ let startPos = $pos.start() + start.offset;
929
+ let endIndex = startIndex + 1;
930
+ let endPos = startPos + start.node.nodeSize;
931
+ while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
932
+ startIndex -= 1;
933
+ startPos -= $pos.parent.child(startIndex).nodeSize;
934
+ }
935
+ while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
936
+ endPos += $pos.parent.child(endIndex).nodeSize;
937
+ endIndex += 1;
938
+ }
939
+ return {
940
+ from: startPos,
941
+ to: endPos
942
+ };
943
+ }
944
+ function getMarkType(nameOrType, schema) {
945
+ if (typeof nameOrType === "string") {
946
+ if (!schema.marks[nameOrType]) {
947
+ throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
948
+ }
949
+ return schema.marks[nameOrType];
950
+ }
951
+ return nameOrType;
952
+ }
953
+ var extendMarkRange = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
954
+ const type = getMarkType(typeOrName, state.schema);
955
+ const { doc, selection } = tr;
956
+ const { $from, from, to } = selection;
957
+ if (dispatch) {
958
+ const range = getMarkRange($from, type, attributes);
959
+ if (range && range.from <= from && range.to >= to) {
960
+ const newSelection = TextSelection.create(doc, range.from, range.to);
961
+ tr.setSelection(newSelection);
962
+ }
963
+ }
964
+ return true;
965
+ };
966
+ var first = (commands) => (props) => {
967
+ const items = typeof commands === "function" ? commands(props) : commands;
968
+ for (let i = 0; i < items.length; i += 1) {
969
+ if (items[i](props)) {
970
+ return true;
971
+ }
972
+ }
973
+ return false;
974
+ };
975
+ function isTextSelection(value) {
976
+ return value instanceof TextSelection;
977
+ }
978
+ function minMax(value = 0, min = 0, max = 0) {
979
+ return Math.min(Math.max(value, min), max);
980
+ }
981
+ function resolveFocusPosition(doc, position = null) {
982
+ if (!position) {
983
+ return null;
984
+ }
985
+ const selectionAtStart = Selection.atStart(doc);
986
+ const selectionAtEnd = Selection.atEnd(doc);
987
+ if (position === "start" || position === true) {
988
+ return selectionAtStart;
989
+ }
990
+ if (position === "end") {
991
+ return selectionAtEnd;
992
+ }
993
+ const minPos = selectionAtStart.from;
994
+ const maxPos = selectionAtEnd.to;
995
+ if (position === "all") {
996
+ return TextSelection.create(doc, minMax(0, minPos, maxPos), minMax(doc.content.size, minPos, maxPos));
997
+ }
998
+ return TextSelection.create(doc, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos));
999
+ }
1000
+ function isAndroid() {
1001
+ return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
1002
+ }
1003
+ function isiOS() {
1004
+ return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection
1005
+ navigator.userAgent.includes("Mac") && "ontouchend" in document;
1006
+ }
1007
+ function isSafari() {
1008
+ return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
1009
+ }
1010
+ var focus = (position = null, options = {}) => ({ editor, view, tr, dispatch }) => {
1011
+ options = {
1012
+ scrollIntoView: true,
1013
+ ...options
1014
+ };
1015
+ const delayedFocus = () => {
1016
+ if (isiOS() || isAndroid()) {
1017
+ view.dom.focus();
1018
+ }
1019
+ if (isSafari() && !isiOS() && !isAndroid()) {
1020
+ view.dom.focus({ preventScroll: true });
1021
+ }
1022
+ requestAnimationFrame(() => {
1023
+ if (!editor.isDestroyed) {
1024
+ view.focus();
1025
+ if (options == null ? void 0 : options.scrollIntoView) {
1026
+ editor.commands.scrollIntoView();
1027
+ }
1028
+ }
1029
+ });
1030
+ };
1031
+ try {
1032
+ if (view.hasFocus() && position === null || position === false) {
1033
+ return true;
1034
+ }
1035
+ } catch {
1036
+ return false;
1037
+ }
1038
+ if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
1039
+ delayedFocus();
1040
+ return true;
1041
+ }
1042
+ const selection = resolveFocusPosition(tr.doc, position) || editor.state.selection;
1043
+ const isSameSelection = editor.state.selection.eq(selection);
1044
+ if (dispatch) {
1045
+ if (!isSameSelection) {
1046
+ tr.setSelection(selection);
1047
+ }
1048
+ if (isSameSelection && tr.storedMarks) {
1049
+ tr.setStoredMarks(tr.storedMarks);
1050
+ }
1051
+ delayedFocus();
1052
+ }
1053
+ return true;
1054
+ };
1055
+ var forEach = (items, fn) => (props) => {
1056
+ return items.every((item, index) => fn(item, { ...props, index }));
1057
+ };
1058
+ var insertContent = (value, options) => ({ tr, commands }) => {
1059
+ return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options);
1060
+ };
1061
+ var removeWhitespaces = (node) => {
1062
+ const children = node.childNodes;
1063
+ for (let i = children.length - 1; i >= 0; i -= 1) {
1064
+ const child = children[i];
1065
+ if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) {
1066
+ node.removeChild(child);
1067
+ } else if (child.nodeType === 1) {
1068
+ removeWhitespaces(child);
1069
+ }
1070
+ }
1071
+ return node;
1072
+ };
1073
+ function elementFromString(value) {
1074
+ if (typeof window === "undefined") {
1075
+ throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");
1076
+ }
1077
+ const wrappedValue = `<body>${value}</body>`;
1078
+ const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
1079
+ return removeWhitespaces(html);
1080
+ }
1081
+ function createNodeFromContent(content, schema, options) {
1082
+ if (content instanceof Node || content instanceof Fragment) {
1083
+ return content;
1084
+ }
1085
+ options = {
1086
+ slice: true,
1087
+ parseOptions: {},
1088
+ ...options
1089
+ };
1090
+ const isJSONContent = typeof content === "object" && content !== null;
1091
+ const isTextContent = typeof content === "string";
1092
+ if (isJSONContent) {
1093
+ try {
1094
+ const isArrayContent = Array.isArray(content) && content.length > 0;
1095
+ if (isArrayContent) {
1096
+ return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item)));
1097
+ }
1098
+ const node = schema.nodeFromJSON(content);
1099
+ if (options.errorOnInvalidContent) {
1100
+ node.check();
1101
+ }
1102
+ return node;
1103
+ } catch (error) {
1104
+ if (options.errorOnInvalidContent) {
1105
+ throw new Error("[tiptap error]: Invalid JSON content", { cause: error });
1106
+ }
1107
+ console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error);
1108
+ return createNodeFromContent("", schema, options);
1109
+ }
1110
+ }
1111
+ if (isTextContent) {
1112
+ if (options.errorOnInvalidContent) {
1113
+ let hasInvalidContent = false;
1114
+ let invalidContent = "";
1115
+ const contentCheckSchema = new Schema({
1116
+ topNode: schema.spec.topNode,
1117
+ marks: schema.spec.marks,
1118
+ // Prosemirror's schemas are executed such that: the last to execute, matches last
1119
+ // 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
1120
+ nodes: schema.spec.nodes.append({
1121
+ __tiptap__private__unknown__catch__all__node: {
1122
+ content: "inline*",
1123
+ group: "block",
1124
+ parseDOM: [
1125
+ {
1126
+ tag: "*",
1127
+ getAttrs: (e) => {
1128
+ hasInvalidContent = true;
1129
+ invalidContent = typeof e === "string" ? e : e.outerHTML;
1130
+ return null;
1131
+ }
1132
+ }
1133
+ ]
1134
+ }
1135
+ })
1136
+ });
1137
+ if (options.slice) {
1138
+ DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions);
1139
+ } else {
1140
+ DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions);
1141
+ }
1142
+ if (options.errorOnInvalidContent && hasInvalidContent) {
1143
+ throw new Error("[tiptap error]: Invalid HTML content", {
1144
+ cause: new Error(`Invalid element found: ${invalidContent}`)
1145
+ });
1146
+ }
1147
+ }
1148
+ const parser = DOMParser.fromSchema(schema);
1149
+ if (options.slice) {
1150
+ return parser.parseSlice(elementFromString(content), options.parseOptions).content;
1151
+ }
1152
+ return parser.parse(elementFromString(content), options.parseOptions);
1153
+ }
1154
+ return createNodeFromContent("", schema, options);
1155
+ }
1156
+ function selectionToInsertionEnd(tr, startLen, bias) {
1157
+ const last = tr.steps.length - 1;
1158
+ if (last < startLen) {
1159
+ return;
1160
+ }
1161
+ const step = tr.steps[last];
1162
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
1163
+ return;
1164
+ }
1165
+ const map = tr.mapping.maps[last];
1166
+ let end = 0;
1167
+ map.forEach((_from, _to, _newFrom, newTo) => {
1168
+ if (end === 0) {
1169
+ end = newTo;
1170
+ }
1171
+ });
1172
+ tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
1173
+ }
1174
+ var isFragment = (nodeOrFragment) => {
1175
+ return !("type" in nodeOrFragment);
1176
+ };
1177
+ var insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {
1178
+ var _a;
1179
+ if (dispatch) {
1180
+ options = {
1181
+ parseOptions: editor.options.parseOptions,
1182
+ updateSelection: true,
1183
+ applyInputRules: false,
1184
+ applyPasteRules: false,
1185
+ ...options
1186
+ };
1187
+ let content;
1188
+ const emitContentError = (error) => {
1189
+ editor.emit("contentError", {
1190
+ editor,
1191
+ error,
1192
+ disableCollaboration: () => {
1193
+ if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) {
1194
+ editor.storage.collaboration.isDisabled = true;
1195
+ }
1196
+ }
1197
+ });
1198
+ };
1199
+ const parseOptions = {
1200
+ preserveWhitespace: "full",
1201
+ ...options.parseOptions
1202
+ };
1203
+ if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {
1204
+ try {
1205
+ createNodeFromContent(value, editor.schema, {
1206
+ parseOptions,
1207
+ errorOnInvalidContent: true
1208
+ });
1209
+ } catch (e) {
1210
+ emitContentError(e);
1211
+ }
1212
+ }
1213
+ try {
1214
+ content = createNodeFromContent(value, editor.schema, {
1215
+ parseOptions,
1216
+ errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck
1217
+ });
1218
+ } catch (e) {
1219
+ emitContentError(e);
1220
+ return false;
1221
+ }
1222
+ let { from, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to };
1223
+ let isOnlyTextContent = true;
1224
+ let isOnlyBlockContent = true;
1225
+ const nodes = isFragment(content) ? content : [content];
1226
+ nodes.forEach((node) => {
1227
+ node.check();
1228
+ isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;
1229
+ isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;
1230
+ });
1231
+ if (from === to && isOnlyBlockContent) {
1232
+ const { parent } = tr.doc.resolve(from);
1233
+ const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
1234
+ if (isEmptyTextBlock) {
1235
+ from -= 1;
1236
+ to += 1;
1237
+ }
1238
+ }
1239
+ let newContent;
1240
+ if (isOnlyTextContent) {
1241
+ if (Array.isArray(value)) {
1242
+ newContent = value.map((v) => v.text || "").join("");
1243
+ } else if (value instanceof Fragment) {
1244
+ let text = "";
1245
+ value.forEach((node) => {
1246
+ if (node.text) {
1247
+ text += node.text;
1248
+ }
1249
+ });
1250
+ newContent = text;
1251
+ } else if (typeof value === "object" && !!value && !!value.text) {
1252
+ newContent = value.text;
1253
+ } else {
1254
+ newContent = value;
1255
+ }
1256
+ tr.insertText(newContent, from, to);
1257
+ } else {
1258
+ newContent = content;
1259
+ const $from = tr.doc.resolve(from);
1260
+ const $fromNode = $from.node();
1261
+ const fromSelectionAtStart = $from.parentOffset === 0;
1262
+ const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock;
1263
+ const hasContent = $fromNode.content.size > 0;
1264
+ if (fromSelectionAtStart && isTextSelection2 && hasContent) {
1265
+ from = Math.max(0, from - 1);
1266
+ }
1267
+ tr.replaceWith(from, to, newContent);
1268
+ }
1269
+ if (options.updateSelection) {
1270
+ selectionToInsertionEnd(tr, tr.steps.length - 1, -1);
1271
+ }
1272
+ if (options.applyInputRules) {
1273
+ tr.setMeta("applyInputRules", { from, text: newContent });
1274
+ }
1275
+ if (options.applyPasteRules) {
1276
+ tr.setMeta("applyPasteRules", { from, text: newContent });
1277
+ }
1278
+ }
1279
+ return true;
1280
+ };
1281
+ var joinUp = () => ({ state, dispatch }) => {
1282
+ return joinUp$1(state, dispatch);
1283
+ };
1284
+ var joinDown = () => ({ state, dispatch }) => {
1285
+ return joinDown$1(state, dispatch);
1286
+ };
1287
+ var joinBackward = () => ({ state, dispatch }) => {
1288
+ return joinBackward$1(state, dispatch);
1289
+ };
1290
+ var joinForward = () => ({ state, dispatch }) => {
1291
+ return joinForward$1(state, dispatch);
1292
+ };
1293
+ var joinItemBackward = () => ({ state, dispatch, tr }) => {
1294
+ try {
1295
+ const point = joinPoint(state.doc, state.selection.$from.pos, -1);
1296
+ if (point === null || point === void 0) {
1297
+ return false;
1298
+ }
1299
+ tr.join(point, 2);
1300
+ if (dispatch) {
1301
+ dispatch(tr);
1302
+ }
1303
+ return true;
1304
+ } catch {
1305
+ return false;
1306
+ }
1307
+ };
1308
+ var joinItemForward = () => ({ state, dispatch, tr }) => {
1309
+ try {
1310
+ const point = joinPoint(state.doc, state.selection.$from.pos, 1);
1311
+ if (point === null || point === void 0) {
1312
+ return false;
1313
+ }
1314
+ tr.join(point, 2);
1315
+ if (dispatch) {
1316
+ dispatch(tr);
1317
+ }
1318
+ return true;
1319
+ } catch {
1320
+ return false;
1321
+ }
1322
+ };
1323
+ var joinTextblockBackward = () => ({ state, dispatch }) => {
1324
+ return joinTextblockBackward$1(state, dispatch);
1325
+ };
1326
+ var joinTextblockForward = () => ({ state, dispatch }) => {
1327
+ return joinTextblockForward$1(state, dispatch);
1328
+ };
1329
+ function isMacOS() {
1330
+ return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
1331
+ }
1332
+ function normalizeKeyName(name) {
1333
+ const parts = name.split(/-(?!$)/);
1334
+ let result = parts[parts.length - 1];
1335
+ if (result === "Space") {
1336
+ result = " ";
1337
+ }
1338
+ let alt;
1339
+ let ctrl;
1340
+ let shift;
1341
+ let meta;
1342
+ for (let i = 0; i < parts.length - 1; i += 1) {
1343
+ const mod = parts[i];
1344
+ if (/^(cmd|meta|m)$/i.test(mod)) {
1345
+ meta = true;
1346
+ } else if (/^a(lt)?$/i.test(mod)) {
1347
+ alt = true;
1348
+ } else if (/^(c|ctrl|control)$/i.test(mod)) {
1349
+ ctrl = true;
1350
+ } else if (/^s(hift)?$/i.test(mod)) {
1351
+ shift = true;
1352
+ } else if (/^mod$/i.test(mod)) {
1353
+ if (isiOS() || isMacOS()) {
1354
+ meta = true;
1355
+ } else {
1356
+ ctrl = true;
1357
+ }
1358
+ } else {
1359
+ throw new Error(`Unrecognized modifier name: ${mod}`);
1360
+ }
1361
+ }
1362
+ if (alt) {
1363
+ result = `Alt-${result}`;
1364
+ }
1365
+ if (ctrl) {
1366
+ result = `Ctrl-${result}`;
1367
+ }
1368
+ if (meta) {
1369
+ result = `Meta-${result}`;
1370
+ }
1371
+ if (shift) {
1372
+ result = `Shift-${result}`;
1373
+ }
1374
+ return result;
1375
+ }
1376
+ var keyboardShortcut = (name) => ({ editor, view, tr, dispatch }) => {
1377
+ const keys = normalizeKeyName(name).split(/-(?!$)/);
1378
+ const key = keys.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
1379
+ const event = new KeyboardEvent("keydown", {
1380
+ key: key === "Space" ? " " : key,
1381
+ altKey: keys.includes("Alt"),
1382
+ ctrlKey: keys.includes("Ctrl"),
1383
+ metaKey: keys.includes("Meta"),
1384
+ shiftKey: keys.includes("Shift"),
1385
+ bubbles: true,
1386
+ cancelable: true
1387
+ });
1388
+ const capturedTransaction = editor.captureTransaction(() => {
1389
+ view.someProp("handleKeyDown", (f) => f(view, event));
1390
+ });
1391
+ capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => {
1392
+ const newStep = step.map(tr.mapping);
1393
+ if (newStep && dispatch) {
1394
+ tr.maybeStep(newStep);
1395
+ }
1396
+ });
1397
+ return true;
1398
+ };
1399
+ function isNodeActive(state, typeOrName, attributes = {}) {
1400
+ const { from, to, empty } = state.selection;
1401
+ const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
1402
+ const nodeRanges = [];
1403
+ state.doc.nodesBetween(from, to, (node, pos) => {
1404
+ if (node.isText) {
1405
+ return;
1406
+ }
1407
+ const relativeFrom = Math.max(from, pos);
1408
+ const relativeTo = Math.min(to, pos + node.nodeSize);
1409
+ nodeRanges.push({
1410
+ node,
1411
+ from: relativeFrom,
1412
+ to: relativeTo
1413
+ });
1414
+ });
1415
+ const selectionRange = to - from;
1416
+ const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
1417
+ if (!type) {
1418
+ return true;
1419
+ }
1420
+ return type.name === nodeRange.node.type.name;
1421
+ }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
1422
+ if (empty) {
1423
+ return !!matchedNodeRanges.length;
1424
+ }
1425
+ const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
1426
+ return range >= selectionRange;
1427
+ }
1428
+ var lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1429
+ const type = getNodeType(typeOrName, state.schema);
1430
+ const isActive2 = isNodeActive(state, type, attributes);
1431
+ if (!isActive2) {
1432
+ return false;
1433
+ }
1434
+ return lift$1(state, dispatch);
1435
+ };
1436
+ var liftEmptyBlock = () => ({ state, dispatch }) => {
1437
+ return liftEmptyBlock$1(state, dispatch);
1438
+ };
1439
+ var liftListItem = (typeOrName) => ({ state, dispatch }) => {
1440
+ const type = getNodeType(typeOrName, state.schema);
1441
+ return liftListItem$1(type)(state, dispatch);
1442
+ };
1443
+ var newlineInCode = () => ({ state, dispatch }) => {
1444
+ return newlineInCode$1(state, dispatch);
1445
+ };
1446
+ function getSchemaTypeNameByName(name, schema) {
1447
+ if (schema.nodes[name]) {
1448
+ return "node";
1449
+ }
1450
+ if (schema.marks[name]) {
1451
+ return "mark";
1452
+ }
1453
+ return null;
1454
+ }
1455
+ function deleteProps(obj, propOrProps) {
1456
+ const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
1457
+ return Object.keys(obj).reduce((newObj, prop) => {
1458
+ if (!props.includes(prop)) {
1459
+ newObj[prop] = obj[prop];
1460
+ }
1461
+ return newObj;
1462
+ }, {});
1463
+ }
1464
+ var resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
1465
+ let nodeType = null;
1466
+ let markType = null;
1467
+ const schemaType = getSchemaTypeNameByName(
1468
+ typeof typeOrName === "string" ? typeOrName : typeOrName.name,
1469
+ state.schema
1470
+ );
1471
+ if (!schemaType) {
1472
+ return false;
1473
+ }
1474
+ if (schemaType === "node") {
1475
+ nodeType = getNodeType(typeOrName, state.schema);
1476
+ }
1477
+ if (schemaType === "mark") {
1478
+ markType = getMarkType(typeOrName, state.schema);
1479
+ }
1480
+ let canReset = false;
1481
+ tr.selection.ranges.forEach((range) => {
1482
+ state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
1483
+ if (nodeType && nodeType === node.type) {
1484
+ canReset = true;
1485
+ if (dispatch) {
1486
+ tr.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes));
1487
+ }
1488
+ }
1489
+ if (markType && node.marks.length) {
1490
+ node.marks.forEach((mark) => {
1491
+ if (markType === mark.type) {
1492
+ canReset = true;
1493
+ if (dispatch) {
1494
+ tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));
1495
+ }
1496
+ }
1497
+ });
1498
+ }
1499
+ });
1500
+ });
1501
+ return canReset;
1502
+ };
1503
+ var scrollIntoView = () => ({ tr, dispatch }) => {
1504
+ if (dispatch) {
1505
+ tr.scrollIntoView();
1506
+ }
1507
+ return true;
1508
+ };
1509
+ var selectAll = () => ({ tr, dispatch }) => {
1510
+ if (dispatch) {
1511
+ const selection = new AllSelection(tr.doc);
1512
+ tr.setSelection(selection);
1513
+ }
1514
+ return true;
1515
+ };
1516
+ var selectNodeBackward = () => ({ state, dispatch }) => {
1517
+ return selectNodeBackward$1(state, dispatch);
1518
+ };
1519
+ var selectNodeForward = () => ({ state, dispatch }) => {
1520
+ return selectNodeForward$1(state, dispatch);
1521
+ };
1522
+ var selectParentNode = () => ({ state, dispatch }) => {
1523
+ return selectParentNode$1(state, dispatch);
1524
+ };
1525
+ var selectTextblockEnd = () => ({ state, dispatch }) => {
1526
+ return selectTextblockEnd$1(state, dispatch);
1527
+ };
1528
+ var selectTextblockStart = () => ({ state, dispatch }) => {
1529
+ return selectTextblockStart$1(state, dispatch);
1530
+ };
1531
+ function createDocument(content, schema, parseOptions = {}, options = {}) {
1532
+ return createNodeFromContent(content, schema, {
1533
+ slice: false,
1534
+ parseOptions,
1535
+ errorOnInvalidContent: options.errorOnInvalidContent
1536
+ });
1537
+ }
1538
+ var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr, dispatch, commands }) => {
1539
+ const { doc } = tr;
1540
+ if (parseOptions.preserveWhitespace !== "full") {
1541
+ const document2 = createDocument(content, editor.schema, parseOptions, {
1542
+ errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
1543
+ });
1544
+ if (dispatch) {
1545
+ tr.replaceWith(0, doc.content.size, document2).setMeta("preventUpdate", !emitUpdate);
1546
+ }
1547
+ return true;
1548
+ }
1549
+ if (dispatch) {
1550
+ tr.setMeta("preventUpdate", !emitUpdate);
1551
+ }
1552
+ return commands.insertContentAt({ from: 0, to: doc.content.size }, content, {
1553
+ parseOptions,
1554
+ errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
1555
+ });
1556
+ };
1557
+ function getMarkAttributes(state, typeOrName) {
1558
+ const type = getMarkType(typeOrName, state.schema);
1559
+ const { from, to, empty } = state.selection;
1560
+ const marks = [];
1561
+ if (empty) {
1562
+ if (state.storedMarks) {
1563
+ marks.push(...state.storedMarks);
1564
+ }
1565
+ marks.push(...state.selection.$head.marks());
1566
+ } else {
1567
+ state.doc.nodesBetween(from, to, (node) => {
1568
+ marks.push(...node.marks);
1569
+ });
1570
+ }
1571
+ const mark = marks.find((markItem) => markItem.type.name === type.name);
1572
+ if (!mark) {
1573
+ return {};
1574
+ }
1575
+ return { ...mark.attrs };
1576
+ }
1577
+ function combineTransactionSteps(oldDoc, transactions) {
1578
+ const transform = new Transform(oldDoc);
1579
+ transactions.forEach((transaction) => {
1580
+ transaction.steps.forEach((step) => {
1581
+ transform.step(step);
1582
+ });
1583
+ });
1584
+ return transform;
1585
+ }
1586
+ function defaultBlockAt(match) {
1587
+ for (let i = 0; i < match.edgeCount; i += 1) {
1588
+ const { type } = match.edge(i);
1589
+ if (type.isTextblock && !type.hasRequiredAttrs()) {
1590
+ return type;
1591
+ }
1592
+ }
1593
+ return null;
1594
+ }
1595
+ function findParentNodeClosestToPos($pos, predicate) {
1596
+ for (let i = $pos.depth; i > 0; i -= 1) {
1597
+ const node = $pos.node(i);
1598
+ if (predicate(node)) {
1599
+ return {
1600
+ pos: i > 0 ? $pos.before(i) : 0,
1601
+ start: $pos.start(i),
1602
+ depth: i,
1603
+ node
1604
+ };
1605
+ }
1606
+ }
1607
+ }
1608
+ function findParentNode(predicate) {
1609
+ return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
1610
+ }
1611
+ function getExtensionField(extension, field, context) {
1612
+ if (extension.config[field] === void 0 && extension.parent) {
1613
+ return getExtensionField(extension.parent, field, context);
1614
+ }
1615
+ if (typeof extension.config[field] === "function") {
1616
+ const value = extension.config[field].bind({
1617
+ ...context,
1618
+ parent: extension.parent ? getExtensionField(extension.parent, field, context) : null
1619
+ });
1620
+ return value;
1621
+ }
1622
+ return extension.config[field];
1623
+ }
1624
+ function isFunction(value) {
1625
+ return typeof value === "function";
1626
+ }
1627
+ function callOrReturn(value, context = void 0, ...props) {
1628
+ if (isFunction(value)) {
1629
+ if (context) {
1630
+ return value.bind(context)(...props);
1631
+ }
1632
+ return value(...props);
1633
+ }
1634
+ return value;
1635
+ }
1636
+ function splitExtensions(extensions2) {
1637
+ const baseExtensions = extensions2.filter((extension) => extension.type === "extension");
1638
+ const nodeExtensions = extensions2.filter((extension) => extension.type === "node");
1639
+ const markExtensions = extensions2.filter((extension) => extension.type === "mark");
1640
+ return {
1641
+ baseExtensions,
1642
+ nodeExtensions,
1643
+ markExtensions
1644
+ };
1645
+ }
1646
+ function mergeAttributes(...objects) {
1647
+ return objects.filter((item) => !!item).reduce((items, item) => {
1648
+ const mergedAttributes = { ...items };
1649
+ Object.entries(item).forEach(([key, value]) => {
1650
+ const exists = mergedAttributes[key];
1651
+ if (!exists) {
1652
+ mergedAttributes[key] = value;
1653
+ return;
1654
+ }
1655
+ if (key === "class") {
1656
+ const valueClasses = value ? String(value).split(" ") : [];
1657
+ const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : [];
1658
+ const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass));
1659
+ mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" ");
1660
+ } else if (key === "style") {
1661
+ const newStyles = value ? value.split(";").map((style2) => style2.trim()).filter(Boolean) : [];
1662
+ const existingStyles = mergedAttributes[key] ? mergedAttributes[key].split(";").map((style2) => style2.trim()).filter(Boolean) : [];
1663
+ const styleMap = /* @__PURE__ */ new Map();
1664
+ existingStyles.forEach((style2) => {
1665
+ const [property, val] = style2.split(":").map((part) => part.trim());
1666
+ styleMap.set(property, val);
1667
+ });
1668
+ newStyles.forEach((style2) => {
1669
+ const [property, val] = style2.split(":").map((part) => part.trim());
1670
+ styleMap.set(property, val);
1671
+ });
1672
+ mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; ");
1673
+ } else {
1674
+ mergedAttributes[key] = value;
1675
+ }
1676
+ });
1677
+ return mergedAttributes;
1678
+ }, {});
1679
+ }
1680
+ function getTextBetween(startNode, range, options) {
1681
+ const { from, to } = range;
1682
+ const { blockSeparator = "\n\n", textSerializers = {} } = options || {};
1683
+ let text = "";
1684
+ startNode.nodesBetween(from, to, (node, pos, parent, index) => {
1685
+ var _a;
1686
+ if (node.isBlock && pos > from) {
1687
+ text += blockSeparator;
1688
+ }
1689
+ const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name];
1690
+ if (textSerializer) {
1691
+ if (parent) {
1692
+ text += textSerializer({
1693
+ node,
1694
+ pos,
1695
+ parent,
1696
+ index,
1697
+ range
1698
+ });
1699
+ }
1700
+ return false;
1701
+ }
1702
+ if (node.isText) {
1703
+ text += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos);
1704
+ }
1705
+ });
1706
+ return text;
1707
+ }
1708
+ function getTextSerializersFromSchema(schema) {
1709
+ return Object.fromEntries(
1710
+ Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText])
1711
+ );
1712
+ }
1713
+ function removeDuplicates(array, by = JSON.stringify) {
1714
+ const seen = {};
1715
+ return array.filter((item) => {
1716
+ const key = by(item);
1717
+ return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true;
1718
+ });
1719
+ }
1720
+ function simplifyChangedRanges(changes) {
1721
+ const uniqueChanges = removeDuplicates(changes);
1722
+ return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => {
1723
+ const rest = uniqueChanges.filter((_, i) => i !== index);
1724
+ return !rest.some((otherChange) => {
1725
+ 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;
1726
+ });
1727
+ });
1728
+ }
1729
+ function getChangedRanges(transform) {
1730
+ const { mapping, steps } = transform;
1731
+ const changes = [];
1732
+ mapping.maps.forEach((stepMap, index) => {
1733
+ const ranges = [];
1734
+ if (!stepMap.ranges.length) {
1735
+ const { from, to } = steps[index];
1736
+ if (from === void 0 || to === void 0) {
1737
+ return;
1738
+ }
1739
+ ranges.push({ from, to });
1740
+ } else {
1741
+ stepMap.forEach((from, to) => {
1742
+ ranges.push({ from, to });
1743
+ });
1744
+ }
1745
+ ranges.forEach(({ from, to }) => {
1746
+ const newStart = mapping.slice(index).map(from, -1);
1747
+ const newEnd = mapping.slice(index).map(to);
1748
+ const oldStart = mapping.invert().map(newStart, -1);
1749
+ const oldEnd = mapping.invert().map(newEnd);
1750
+ changes.push({
1751
+ oldRange: {
1752
+ from: oldStart,
1753
+ to: oldEnd
1754
+ },
1755
+ newRange: {
1756
+ from: newStart,
1757
+ to: newEnd
1758
+ }
1759
+ });
1760
+ });
1761
+ });
1762
+ return simplifyChangedRanges(changes);
1763
+ }
1764
+ function getSplittedAttributes(extensionAttributes, typeName, attributes) {
1765
+ return Object.fromEntries(
1766
+ Object.entries(attributes).filter(([name]) => {
1767
+ const extensionAttribute = extensionAttributes.find((item) => {
1768
+ return item.type === typeName && item.name === name;
1769
+ });
1770
+ if (!extensionAttribute) {
1771
+ return false;
1772
+ }
1773
+ return extensionAttribute.attribute.keepOnSplit;
1774
+ })
1775
+ );
1776
+ }
1777
+ function isMarkActive(state, typeOrName, attributes = {}) {
1778
+ const { empty, ranges } = state.selection;
1779
+ const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
1780
+ if (empty) {
1781
+ return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => {
1782
+ if (!type) {
1783
+ return true;
1784
+ }
1785
+ return type.name === mark.type.name;
1786
+ }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false }));
1787
+ }
1788
+ let selectionRange = 0;
1789
+ const markRanges = [];
1790
+ ranges.forEach(({ $from, $to }) => {
1791
+ const from = $from.pos;
1792
+ const to = $to.pos;
1793
+ state.doc.nodesBetween(from, to, (node, pos) => {
1794
+ if (!node.isText && !node.marks.length) {
1795
+ return;
1796
+ }
1797
+ const relativeFrom = Math.max(from, pos);
1798
+ const relativeTo = Math.min(to, pos + node.nodeSize);
1799
+ const range2 = relativeTo - relativeFrom;
1800
+ selectionRange += range2;
1801
+ markRanges.push(
1802
+ ...node.marks.map((mark) => ({
1803
+ mark,
1804
+ from: relativeFrom,
1805
+ to: relativeTo
1806
+ }))
1807
+ );
1808
+ });
1809
+ });
1810
+ if (selectionRange === 0) {
1811
+ return false;
1812
+ }
1813
+ const matchedRange = markRanges.filter((markRange) => {
1814
+ if (!type) {
1815
+ return true;
1816
+ }
1817
+ return type.name === markRange.mark.type.name;
1818
+ }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1819
+ const excludedRange = markRanges.filter((markRange) => {
1820
+ if (!type) {
1821
+ return true;
1822
+ }
1823
+ return markRange.mark.type !== type && markRange.mark.type.excludes(type);
1824
+ }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1825
+ const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
1826
+ return range >= selectionRange;
1827
+ }
1828
+ function isList(name, extensions2) {
1829
+ const { nodeExtensions } = splitExtensions(extensions2);
1830
+ const extension = nodeExtensions.find((item) => item.name === name);
1831
+ if (!extension) {
1832
+ return false;
1833
+ }
1834
+ const context = {
1835
+ name: extension.name,
1836
+ options: extension.options,
1837
+ storage: extension.storage
1838
+ };
1839
+ const group = callOrReturn(getExtensionField(extension, "group", context));
1840
+ if (typeof group !== "string") {
1841
+ return false;
1842
+ }
1843
+ return group.split(" ").includes("list");
1844
+ }
1845
+ function isNodeEmpty(node, {
1846
+ checkChildren = true,
1847
+ ignoreWhitespace = false
1848
+ } = {}) {
1849
+ var _a;
1850
+ if (ignoreWhitespace) {
1851
+ if (node.type.name === "hardBreak") {
1852
+ return true;
1853
+ }
1854
+ if (node.isText) {
1855
+ return /^\s*$/m.test((_a = node.text) != null ? _a : "");
1856
+ }
1857
+ }
1858
+ if (node.isText) {
1859
+ return !node.text;
1860
+ }
1861
+ if (node.isAtom || node.isLeaf) {
1862
+ return false;
1863
+ }
1864
+ if (node.content.childCount === 0) {
1865
+ return true;
1866
+ }
1867
+ if (checkChildren) {
1868
+ let isContentEmpty = true;
1869
+ node.content.forEach((childNode) => {
1870
+ if (isContentEmpty === false) {
1871
+ return;
1872
+ }
1873
+ if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
1874
+ isContentEmpty = false;
1875
+ }
1876
+ });
1877
+ return isContentEmpty;
1878
+ }
1879
+ return false;
1880
+ }
1881
+ function isNodeSelection(value) {
1882
+ return value instanceof NodeSelection;
1883
+ }
1884
+ function canSetMark(state, tr, newMarkType) {
1885
+ var _a;
1886
+ const { selection } = tr;
1887
+ let cursor = null;
1888
+ if (isTextSelection(selection)) {
1889
+ cursor = selection.$cursor;
1890
+ }
1891
+ if (cursor) {
1892
+ const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks();
1893
+ const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType);
1894
+ return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType)));
1895
+ }
1896
+ const { ranges } = selection;
1897
+ return ranges.some(({ $from, $to }) => {
1898
+ let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
1899
+ state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {
1900
+ if (someNodeSupportsMark) {
1901
+ return false;
1902
+ }
1903
+ if (node.isInline) {
1904
+ const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);
1905
+ const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
1906
+ someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
1907
+ }
1908
+ return !someNodeSupportsMark;
1909
+ });
1910
+ return someNodeSupportsMark;
1911
+ });
1912
+ }
1913
+ var setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1914
+ const { selection } = tr;
1915
+ const { empty, ranges } = selection;
1916
+ const type = getMarkType(typeOrName, state.schema);
1917
+ if (dispatch) {
1918
+ if (empty) {
1919
+ const oldAttributes = getMarkAttributes(state, type);
1920
+ tr.addStoredMark(
1921
+ type.create({
1922
+ ...oldAttributes,
1923
+ ...attributes
1924
+ })
1925
+ );
1926
+ } else {
1927
+ ranges.forEach((range) => {
1928
+ const from = range.$from.pos;
1929
+ const to = range.$to.pos;
1930
+ state.doc.nodesBetween(from, to, (node, pos) => {
1931
+ const trimmedFrom = Math.max(pos, from);
1932
+ const trimmedTo = Math.min(pos + node.nodeSize, to);
1933
+ const someHasMark = node.marks.find((mark) => mark.type === type);
1934
+ if (someHasMark) {
1935
+ node.marks.forEach((mark) => {
1936
+ if (type === mark.type) {
1937
+ tr.addMark(
1938
+ trimmedFrom,
1939
+ trimmedTo,
1940
+ type.create({
1941
+ ...mark.attrs,
1942
+ ...attributes
1943
+ })
1944
+ );
1945
+ }
1946
+ });
1947
+ } else {
1948
+ tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));
1949
+ }
1950
+ });
1951
+ });
1952
+ }
1953
+ }
1954
+ return canSetMark(state, tr, type);
1955
+ };
1956
+ var setMeta = (key, value) => ({ tr }) => {
1957
+ tr.setMeta(key, value);
1958
+ return true;
1959
+ };
1960
+ var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
1961
+ const type = getNodeType(typeOrName, state.schema);
1962
+ let attributesToCopy;
1963
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
1964
+ attributesToCopy = state.selection.$anchor.parent.attrs;
1965
+ }
1966
+ if (!type.isTextblock) {
1967
+ console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
1968
+ return false;
1969
+ }
1970
+ return chain().command(({ commands }) => {
1971
+ const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state);
1972
+ if (canSetBlock) {
1973
+ return true;
1974
+ }
1975
+ return commands.clearNodes();
1976
+ }).command(({ state: updatedState }) => {
1977
+ return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
1978
+ }).run();
1979
+ };
1980
+ var setNodeSelection = (position) => ({ tr, dispatch }) => {
1981
+ if (dispatch) {
1982
+ const { doc } = tr;
1983
+ const from = minMax(position, 0, doc.content.size);
1984
+ const selection = NodeSelection.create(doc, from);
1985
+ tr.setSelection(selection);
1986
+ }
1987
+ return true;
1988
+ };
1989
+ var setTextDirection = (direction, position) => ({ tr, state, dispatch }) => {
1990
+ const { selection } = state;
1991
+ let from;
1992
+ let to;
1993
+ if (typeof position === "number") {
1994
+ from = position;
1995
+ to = position;
1996
+ } else if (position && "from" in position && "to" in position) {
1997
+ from = position.from;
1998
+ to = position.to;
1999
+ } else {
2000
+ from = selection.from;
2001
+ to = selection.to;
2002
+ }
2003
+ if (dispatch) {
2004
+ tr.doc.nodesBetween(from, to, (node, pos) => {
2005
+ if (node.isText) {
2006
+ return;
2007
+ }
2008
+ tr.setNodeMarkup(pos, void 0, {
2009
+ ...node.attrs,
2010
+ dir: direction
2011
+ });
2012
+ });
2013
+ }
2014
+ return true;
2015
+ };
2016
+ var setTextSelection = (position) => ({ tr, dispatch }) => {
2017
+ if (dispatch) {
2018
+ const { doc } = tr;
2019
+ const { from, to } = typeof position === "number" ? { from: position, to: position } : position;
2020
+ const minPos = TextSelection.atStart(doc).from;
2021
+ const maxPos = TextSelection.atEnd(doc).to;
2022
+ const resolvedFrom = minMax(from, minPos, maxPos);
2023
+ const resolvedEnd = minMax(to, minPos, maxPos);
2024
+ const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd);
2025
+ tr.setSelection(selection);
2026
+ }
2027
+ return true;
2028
+ };
2029
+ var sinkListItem = (typeOrName) => ({ state, dispatch }) => {
2030
+ const type = getNodeType(typeOrName, state.schema);
2031
+ return sinkListItem$1(type)(state, dispatch);
2032
+ };
2033
+ function ensureMarks(state, splittableMarks) {
2034
+ const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
2035
+ if (marks) {
2036
+ const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name));
2037
+ state.tr.ensureMarks(filteredMarks);
2038
+ }
2039
+ }
2040
+ var splitBlock = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor }) => {
2041
+ const { selection, doc } = tr;
2042
+ const { $from, $to } = selection;
2043
+ const extensionAttributes = editor.extensionManager.attributes;
2044
+ const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
2045
+ if (selection instanceof NodeSelection && selection.node.isBlock) {
2046
+ if (!$from.parentOffset || !canSplit(doc, $from.pos)) {
2047
+ return false;
2048
+ }
2049
+ if (dispatch) {
2050
+ if (keepMarks) {
2051
+ ensureMarks(state, editor.extensionManager.splittableMarks);
2052
+ }
2053
+ tr.split($from.pos).scrollIntoView();
2054
+ }
2055
+ return true;
2056
+ }
2057
+ if (!$from.parent.isBlock) {
2058
+ return false;
2059
+ }
2060
+ const atEnd = $to.parentOffset === $to.parent.content.size;
2061
+ const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
2062
+ let types = atEnd && deflt ? [
2063
+ {
2064
+ type: deflt,
2065
+ attrs: newAttributes
2066
+ }
2067
+ ] : void 0;
2068
+ let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
2069
+ if (!types && !can && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) {
2070
+ can = true;
2071
+ types = deflt ? [
2072
+ {
2073
+ type: deflt,
2074
+ attrs: newAttributes
2075
+ }
2076
+ ] : void 0;
2077
+ }
2078
+ if (dispatch) {
2079
+ if (can) {
2080
+ if (selection instanceof TextSelection) {
2081
+ tr.deleteSelection();
2082
+ }
2083
+ tr.split(tr.mapping.map($from.pos), 1, types);
2084
+ if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) {
2085
+ const first2 = tr.mapping.map($from.before());
2086
+ const $first = tr.doc.resolve(first2);
2087
+ if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
2088
+ tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
2089
+ }
2090
+ }
2091
+ }
2092
+ if (keepMarks) {
2093
+ ensureMarks(state, editor.extensionManager.splittableMarks);
2094
+ }
2095
+ tr.scrollIntoView();
2096
+ }
2097
+ return can;
2098
+ };
2099
+ var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr, state, dispatch, editor }) => {
2100
+ var _a;
2101
+ const type = getNodeType(typeOrName, state.schema);
2102
+ const { $from, $to } = state.selection;
2103
+ const node = state.selection.node;
2104
+ if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
2105
+ return false;
2106
+ }
2107
+ const grandParent = $from.node(-1);
2108
+ if (grandParent.type !== type) {
2109
+ return false;
2110
+ }
2111
+ const extensionAttributes = editor.extensionManager.attributes;
2112
+ if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
2113
+ if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
2114
+ return false;
2115
+ }
2116
+ if (dispatch) {
2117
+ let wrap = Fragment.empty;
2118
+ const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
2119
+ for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
2120
+ wrap = Fragment.from($from.node(d).copy(wrap));
2121
+ }
2122
+ const depthAfter = (
2123
+ // eslint-disable-next-line no-nested-ternary
2124
+ $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3
2125
+ );
2126
+ const newNextTypeAttributes2 = {
2127
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
2128
+ ...overrideAttrs
2129
+ };
2130
+ const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0;
2131
+ wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType2) || void 0));
2132
+ const start = $from.before($from.depth - (depthBefore - 1));
2133
+ tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));
2134
+ let sel = -1;
2135
+ tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {
2136
+ if (sel > -1) {
2137
+ return false;
2138
+ }
2139
+ if (n.isTextblock && n.content.size === 0) {
2140
+ sel = pos + 1;
2141
+ }
2142
+ });
2143
+ if (sel > -1) {
2144
+ tr.setSelection(TextSelection.near(tr.doc.resolve(sel)));
2145
+ }
2146
+ tr.scrollIntoView();
2147
+ }
2148
+ return true;
2149
+ }
2150
+ const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
2151
+ const newTypeAttributes = {
2152
+ ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
2153
+ ...overrideAttrs
2154
+ };
2155
+ const newNextTypeAttributes = {
2156
+ ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
2157
+ ...overrideAttrs
2158
+ };
2159
+ tr.delete($from.pos, $to.pos);
2160
+ const types = nextType ? [
2161
+ { type, attrs: newTypeAttributes },
2162
+ { type: nextType, attrs: newNextTypeAttributes }
2163
+ ] : [{ type, attrs: newTypeAttributes }];
2164
+ if (!canSplit(tr.doc, $from.pos, 2)) {
2165
+ return false;
2166
+ }
2167
+ if (dispatch) {
2168
+ const { selection, storedMarks } = state;
2169
+ const { splittableMarks } = editor.extensionManager;
2170
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
2171
+ tr.split($from.pos, 2, types).scrollIntoView();
2172
+ if (!marks || !dispatch) {
2173
+ return true;
2174
+ }
2175
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
2176
+ tr.ensureMarks(filteredMarks);
2177
+ }
2178
+ return true;
2179
+ };
2180
+ var joinListBackwards = (tr, listType) => {
2181
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
2182
+ if (!list) {
2183
+ return true;
2184
+ }
2185
+ const before = tr.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth);
2186
+ if (before === void 0) {
2187
+ return true;
2188
+ }
2189
+ const nodeBefore = tr.doc.nodeAt(before);
2190
+ const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr.doc, list.pos);
2191
+ if (!canJoinBackwards) {
2192
+ return true;
2193
+ }
2194
+ tr.join(list.pos);
2195
+ return true;
2196
+ };
2197
+ var joinListForwards = (tr, listType) => {
2198
+ const list = findParentNode((node) => node.type === listType)(tr.selection);
2199
+ if (!list) {
2200
+ return true;
2201
+ }
2202
+ const after = tr.doc.resolve(list.start).after(list.depth);
2203
+ if (after === void 0) {
2204
+ return true;
2205
+ }
2206
+ const nodeAfter = tr.doc.nodeAt(after);
2207
+ const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr.doc, after);
2208
+ if (!canJoinForwards) {
2209
+ return true;
2210
+ }
2211
+ tr.join(after);
2212
+ return true;
2213
+ };
2214
+ var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr, state, dispatch, chain, commands, can }) => {
2215
+ const { extensions: extensions2, splittableMarks } = editor.extensionManager;
2216
+ const listType = getNodeType(listTypeOrName, state.schema);
2217
+ const itemType = getNodeType(itemTypeOrName, state.schema);
2218
+ const { selection, storedMarks } = state;
2219
+ const { $from, $to } = selection;
2220
+ const range = $from.blockRange($to);
2221
+ const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
2222
+ if (!range) {
2223
+ return false;
2224
+ }
2225
+ const parentList = findParentNode((node) => isList(node.type.name, extensions2))(selection);
2226
+ if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
2227
+ if (parentList.node.type === listType) {
2228
+ return commands.liftListItem(itemType);
2229
+ }
2230
+ if (isList(parentList.node.type.name, extensions2) && listType.validContent(parentList.node.content) && dispatch) {
2231
+ return chain().command(() => {
2232
+ tr.setNodeMarkup(parentList.pos, listType);
2233
+ return true;
2234
+ }).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
2235
+ }
2236
+ }
2237
+ if (!keepMarks || !marks || !dispatch) {
2238
+ return chain().command(() => {
2239
+ const canWrapInList = can().wrapInList(listType, attributes);
2240
+ if (canWrapInList) {
2241
+ return true;
2242
+ }
2243
+ return commands.clearNodes();
2244
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
2245
+ }
2246
+ return chain().command(() => {
2247
+ const canWrapInList = can().wrapInList(listType, attributes);
2248
+ const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
2249
+ tr.ensureMarks(filteredMarks);
2250
+ if (canWrapInList) {
2251
+ return true;
2252
+ }
2253
+ return commands.clearNodes();
2254
+ }).wrapInList(listType, attributes).command(() => joinListBackwards(tr, listType)).command(() => joinListForwards(tr, listType)).run();
2255
+ };
2256
+ var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {
2257
+ const { extendEmptyMarkRange = false } = options;
2258
+ const type = getMarkType(typeOrName, state.schema);
2259
+ const isActive2 = isMarkActive(state, type, attributes);
2260
+ if (isActive2) {
2261
+ return commands.unsetMark(type, { extendEmptyMarkRange });
2262
+ }
2263
+ return commands.setMark(type, attributes);
2264
+ };
2265
+ var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
2266
+ const type = getNodeType(typeOrName, state.schema);
2267
+ const toggleType = getNodeType(toggleTypeOrName, state.schema);
2268
+ const isActive2 = isNodeActive(state, type, attributes);
2269
+ let attributesToCopy;
2270
+ if (state.selection.$anchor.sameParent(state.selection.$head)) {
2271
+ attributesToCopy = state.selection.$anchor.parent.attrs;
2272
+ }
2273
+ if (isActive2) {
2274
+ return commands.setNode(toggleType, attributesToCopy);
2275
+ }
2276
+ return commands.setNode(type, { ...attributesToCopy, ...attributes });
2277
+ };
2278
+ var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => {
2279
+ const type = getNodeType(typeOrName, state.schema);
2280
+ const isActive2 = isNodeActive(state, type, attributes);
2281
+ if (isActive2) {
2282
+ return commands.lift(type);
2283
+ }
2284
+ return commands.wrapIn(type, attributes);
2285
+ };
2286
+ var undoInputRule = () => ({ state, dispatch }) => {
2287
+ const plugins = state.plugins;
2288
+ for (let i = 0; i < plugins.length; i += 1) {
2289
+ const plugin = plugins[i];
2290
+ let undoable;
2291
+ if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
2292
+ if (dispatch) {
2293
+ const tr = state.tr;
2294
+ const toUndo = undoable.transform;
2295
+ for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
2296
+ tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
2297
+ }
2298
+ if (undoable.text) {
2299
+ const marks = tr.doc.resolve(undoable.from).marks();
2300
+ tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
2301
+ } else {
2302
+ tr.delete(undoable.from, undoable.to);
2303
+ }
2304
+ }
2305
+ return true;
2306
+ }
2307
+ }
2308
+ return false;
2309
+ };
2310
+ var unsetAllMarks = () => ({ tr, dispatch }) => {
2311
+ const { selection } = tr;
2312
+ const { empty, ranges } = selection;
2313
+ if (empty) {
2314
+ return true;
2315
+ }
2316
+ if (dispatch) {
2317
+ ranges.forEach((range) => {
2318
+ tr.removeMark(range.$from.pos, range.$to.pos);
2319
+ });
2320
+ }
2321
+ return true;
2322
+ };
2323
+ var unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {
2324
+ var _a;
2325
+ const { extendEmptyMarkRange = false } = options;
2326
+ const { selection } = tr;
2327
+ const type = getMarkType(typeOrName, state.schema);
2328
+ const { $from, empty, ranges } = selection;
2329
+ if (!dispatch) {
2330
+ return true;
2331
+ }
2332
+ if (empty && extendEmptyMarkRange) {
2333
+ let { from, to } = selection;
2334
+ const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs;
2335
+ const range = getMarkRange($from, type, attrs);
2336
+ if (range) {
2337
+ from = range.from;
2338
+ to = range.to;
2339
+ }
2340
+ tr.removeMark(from, to, type);
2341
+ } else {
2342
+ ranges.forEach((range) => {
2343
+ tr.removeMark(range.$from.pos, range.$to.pos, type);
2344
+ });
2345
+ }
2346
+ tr.removeStoredMark(type);
2347
+ return true;
2348
+ };
2349
+ var unsetTextDirection = (position) => ({ tr, state, dispatch }) => {
2350
+ const { selection } = state;
2351
+ let from;
2352
+ let to;
2353
+ if (typeof position === "number") {
2354
+ from = position;
2355
+ to = position;
2356
+ } else if (position && "from" in position && "to" in position) {
2357
+ from = position.from;
2358
+ to = position.to;
2359
+ } else {
2360
+ from = selection.from;
2361
+ to = selection.to;
2362
+ }
2363
+ if (dispatch) {
2364
+ tr.doc.nodesBetween(from, to, (node, pos) => {
2365
+ if (node.isText) {
2366
+ return;
2367
+ }
2368
+ const newAttrs = { ...node.attrs };
2369
+ delete newAttrs.dir;
2370
+ tr.setNodeMarkup(pos, void 0, newAttrs);
2371
+ });
2372
+ }
2373
+ return true;
2374
+ };
2375
+ var updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
2376
+ let nodeType = null;
2377
+ let markType = null;
2378
+ const schemaType = getSchemaTypeNameByName(
2379
+ typeof typeOrName === "string" ? typeOrName : typeOrName.name,
2380
+ state.schema
2381
+ );
2382
+ if (!schemaType) {
2383
+ return false;
2384
+ }
2385
+ if (schemaType === "node") {
2386
+ nodeType = getNodeType(typeOrName, state.schema);
2387
+ }
2388
+ if (schemaType === "mark") {
2389
+ markType = getMarkType(typeOrName, state.schema);
2390
+ }
2391
+ let canUpdate = false;
2392
+ tr.selection.ranges.forEach((range) => {
2393
+ const from = range.$from.pos;
2394
+ const to = range.$to.pos;
2395
+ let lastPos;
2396
+ let lastNode;
2397
+ let trimmedFrom;
2398
+ let trimmedTo;
2399
+ if (tr.selection.empty) {
2400
+ state.doc.nodesBetween(from, to, (node, pos) => {
2401
+ if (nodeType && nodeType === node.type) {
2402
+ canUpdate = true;
2403
+ trimmedFrom = Math.max(pos, from);
2404
+ trimmedTo = Math.min(pos + node.nodeSize, to);
2405
+ lastPos = pos;
2406
+ lastNode = node;
2407
+ }
2408
+ });
2409
+ } else {
2410
+ state.doc.nodesBetween(from, to, (node, pos) => {
2411
+ if (pos < from && nodeType && nodeType === node.type) {
2412
+ canUpdate = true;
2413
+ trimmedFrom = Math.max(pos, from);
2414
+ trimmedTo = Math.min(pos + node.nodeSize, to);
2415
+ lastPos = pos;
2416
+ lastNode = node;
2417
+ }
2418
+ if (pos >= from && pos <= to) {
2419
+ if (nodeType && nodeType === node.type) {
2420
+ canUpdate = true;
2421
+ if (dispatch) {
2422
+ tr.setNodeMarkup(pos, void 0, {
2423
+ ...node.attrs,
2424
+ ...attributes
2425
+ });
2426
+ }
2427
+ }
2428
+ if (markType && node.marks.length) {
2429
+ node.marks.forEach((mark) => {
2430
+ if (markType === mark.type) {
2431
+ canUpdate = true;
2432
+ if (dispatch) {
2433
+ const trimmedFrom2 = Math.max(pos, from);
2434
+ const trimmedTo2 = Math.min(pos + node.nodeSize, to);
2435
+ tr.addMark(
2436
+ trimmedFrom2,
2437
+ trimmedTo2,
2438
+ markType.create({
2439
+ ...mark.attrs,
2440
+ ...attributes
2441
+ })
2442
+ );
2443
+ }
2444
+ }
2445
+ });
2446
+ }
2447
+ }
2448
+ });
2449
+ }
2450
+ if (lastNode) {
2451
+ if (lastPos !== void 0 && dispatch) {
2452
+ tr.setNodeMarkup(lastPos, void 0, {
2453
+ ...lastNode.attrs,
2454
+ ...attributes
2455
+ });
2456
+ }
2457
+ if (markType && lastNode.marks.length) {
2458
+ lastNode.marks.forEach((mark) => {
2459
+ if (markType === mark.type && dispatch) {
2460
+ tr.addMark(
2461
+ trimmedFrom,
2462
+ trimmedTo,
2463
+ markType.create({
2464
+ ...mark.attrs,
2465
+ ...attributes
2466
+ })
2467
+ );
2468
+ }
2469
+ });
2470
+ }
2471
+ }
2472
+ });
2473
+ return canUpdate;
2474
+ };
2475
+ var wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2476
+ const type = getNodeType(typeOrName, state.schema);
2477
+ return wrapIn$1(type, attributes)(state, dispatch);
2478
+ };
2479
+ var wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2480
+ const type = getNodeType(typeOrName, state.schema);
2481
+ return wrapInList$1(type, attributes)(state, dispatch);
2482
+ };
2483
+ var InputRule = class {
2484
+ constructor(config) {
2485
+ var _a;
2486
+ this.find = config.find;
2487
+ this.handler = config.handler;
2488
+ this.undoable = (_a = config.undoable) != null ? _a : true;
2489
+ }
2490
+ };
2491
+ function getType(value) {
2492
+ return Object.prototype.toString.call(value).slice(8, -1);
2493
+ }
2494
+ function isPlainObject(value) {
2495
+ if (getType(value) !== "Object") {
2496
+ return false;
2497
+ }
2498
+ return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
2499
+ }
2500
+ function mergeDeep(target, source) {
2501
+ const output = { ...target };
2502
+ if (isPlainObject(target) && isPlainObject(source)) {
2503
+ Object.keys(source).forEach((key) => {
2504
+ if (isPlainObject(source[key]) && isPlainObject(target[key])) {
2505
+ output[key] = mergeDeep(target[key], source[key]);
2506
+ } else {
2507
+ output[key] = source[key];
2508
+ }
2509
+ });
2510
+ }
2511
+ return output;
2512
+ }
2513
+ var Extendable = class {
2514
+ constructor(config = {}) {
2515
+ this.type = "extendable";
2516
+ this.parent = null;
2517
+ this.child = null;
2518
+ this.name = "";
2519
+ this.config = {
2520
+ name: this.name
2521
+ };
2522
+ this.config = {
2523
+ ...this.config,
2524
+ ...config
2525
+ };
2526
+ this.name = this.config.name;
2527
+ }
2528
+ get options() {
2529
+ return {
2530
+ ...callOrReturn(
2531
+ getExtensionField(this, "addOptions", {
2532
+ name: this.name
2533
+ })
2534
+ ) || {}
2535
+ };
2536
+ }
2537
+ get storage() {
2538
+ return {
2539
+ ...callOrReturn(
2540
+ getExtensionField(this, "addStorage", {
2541
+ name: this.name,
2542
+ options: this.options
2543
+ })
2544
+ ) || {}
2545
+ };
2546
+ }
2547
+ configure(options = {}) {
2548
+ const extension = this.extend({
2549
+ ...this.config,
2550
+ addOptions: () => {
2551
+ return mergeDeep(this.options, options);
2552
+ }
2553
+ });
2554
+ extension.name = this.name;
2555
+ extension.parent = this.parent;
2556
+ return extension;
2557
+ }
2558
+ extend(extendedConfig = {}) {
2559
+ const extension = new this.constructor({ ...this.config, ...extendedConfig });
2560
+ extension.parent = this;
2561
+ this.child = extension;
2562
+ extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name;
2563
+ return extension;
2564
+ }
2565
+ };
2566
+ var extensions_exports = {};
2567
+ __export(extensions_exports, {
2568
+ ClipboardTextSerializer: () => ClipboardTextSerializer,
2569
+ Commands: () => Commands,
2570
+ Delete: () => Delete,
2571
+ Drop: () => Drop,
2572
+ Editable: () => Editable,
2573
+ FocusEvents: () => FocusEvents,
2574
+ Keymap: () => Keymap,
2575
+ Paste: () => Paste,
2576
+ Tabindex: () => Tabindex,
2577
+ TextDirection: () => TextDirection,
2578
+ focusEventsPluginKey: () => focusEventsPluginKey
2579
+ });
2580
+ var Extension = class _Extension extends Extendable {
2581
+ constructor() {
2582
+ super(...arguments);
2583
+ this.type = "extension";
2584
+ }
2585
+ /**
2586
+ * Create a new Extension instance
2587
+ * @param config - Extension configuration object or a function that returns a configuration object
2588
+ */
2589
+ static create(config = {}) {
2590
+ const resolvedConfig = typeof config === "function" ? config() : config;
2591
+ return new _Extension(resolvedConfig);
2592
+ }
2593
+ configure(options) {
2594
+ return super.configure(options);
2595
+ }
2596
+ extend(extendedConfig) {
2597
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
2598
+ return super.extend(resolvedConfig);
2599
+ }
2600
+ };
2601
+ var ClipboardTextSerializer = Extension.create({
2602
+ name: "clipboardTextSerializer",
2603
+ addOptions() {
2604
+ return {
2605
+ blockSeparator: void 0
2606
+ };
2607
+ },
2608
+ addProseMirrorPlugins() {
2609
+ return [
2610
+ new Plugin({
2611
+ key: new PluginKey("clipboardTextSerializer"),
2612
+ props: {
2613
+ clipboardTextSerializer: () => {
2614
+ const { editor } = this;
2615
+ const { state, schema } = editor;
2616
+ const { doc, selection } = state;
2617
+ const { ranges } = selection;
2618
+ const from = Math.min(...ranges.map((range2) => range2.$from.pos));
2619
+ const to = Math.max(...ranges.map((range2) => range2.$to.pos));
2620
+ const textSerializers = getTextSerializersFromSchema(schema);
2621
+ const range = { from, to };
2622
+ return getTextBetween(doc, range, {
2623
+ ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {},
2624
+ textSerializers
2625
+ });
2626
+ }
2627
+ }
2628
+ })
2629
+ ];
2630
+ }
2631
+ });
2632
+ var Commands = Extension.create({
2633
+ name: "commands",
2634
+ addCommands() {
2635
+ return {
2636
+ ...commands_exports
2637
+ };
2638
+ }
2639
+ });
2640
+ var Delete = Extension.create({
2641
+ name: "delete",
2642
+ onUpdate({ transaction, appendedTransactions }) {
2643
+ var _a, _b, _c;
2644
+ const callback = () => {
2645
+ var _a2, _b2, _c2, _d;
2646
+ 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$")) {
2647
+ return;
2648
+ }
2649
+ const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]);
2650
+ const changes = getChangedRanges(nextTransaction);
2651
+ changes.forEach((change) => {
2652
+ if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) {
2653
+ nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from) => {
2654
+ const to = from + node.nodeSize - 2;
2655
+ const isFullyWithinRange = change.oldRange.from <= from && to <= change.oldRange.to;
2656
+ this.editor.emit("delete", {
2657
+ type: "node",
2658
+ node,
2659
+ from,
2660
+ to,
2661
+ newFrom: nextTransaction.mapping.map(from),
2662
+ newTo: nextTransaction.mapping.map(to),
2663
+ deletedRange: change.oldRange,
2664
+ newRange: change.newRange,
2665
+ partial: !isFullyWithinRange,
2666
+ editor: this.editor,
2667
+ transaction,
2668
+ combinedTransform: nextTransaction
2669
+ });
2670
+ });
2671
+ }
2672
+ });
2673
+ const mapping = nextTransaction.mapping;
2674
+ nextTransaction.steps.forEach((step, index) => {
2675
+ var _a3, _b3;
2676
+ if (step instanceof RemoveMarkStep) {
2677
+ const newStart = mapping.slice(index).map(step.from, -1);
2678
+ const newEnd = mapping.slice(index).map(step.to);
2679
+ const oldStart = mapping.invert().map(newStart, -1);
2680
+ const oldEnd = mapping.invert().map(newEnd);
2681
+ const foundBeforeMark = (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark));
2682
+ const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark));
2683
+ this.editor.emit("delete", {
2684
+ type: "mark",
2685
+ mark: step.mark,
2686
+ from: step.from,
2687
+ to: step.to,
2688
+ deletedRange: {
2689
+ from: oldStart,
2690
+ to: oldEnd
2691
+ },
2692
+ newRange: {
2693
+ from: newStart,
2694
+ to: newEnd
2695
+ },
2696
+ partial: Boolean(foundAfterMark || foundBeforeMark),
2697
+ editor: this.editor,
2698
+ transaction,
2699
+ combinedTransform: nextTransaction
2700
+ });
2701
+ }
2702
+ });
2703
+ };
2704
+ if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) {
2705
+ setTimeout(callback, 0);
2706
+ } else {
2707
+ callback();
2708
+ }
2709
+ }
2710
+ });
2711
+ var Drop = Extension.create({
2712
+ name: "drop",
2713
+ addProseMirrorPlugins() {
2714
+ return [
2715
+ new Plugin({
2716
+ key: new PluginKey("tiptapDrop"),
2717
+ props: {
2718
+ handleDrop: (_, e, slice, moved) => {
2719
+ this.editor.emit("drop", {
2720
+ editor: this.editor,
2721
+ event: e,
2722
+ slice,
2723
+ moved
2724
+ });
2725
+ }
2726
+ }
2727
+ })
2728
+ ];
2729
+ }
2730
+ });
2731
+ var Editable = Extension.create({
2732
+ name: "editable",
2733
+ addProseMirrorPlugins() {
2734
+ return [
2735
+ new Plugin({
2736
+ key: new PluginKey("editable"),
2737
+ props: {
2738
+ editable: () => this.editor.options.editable
2739
+ }
2740
+ })
2741
+ ];
2742
+ }
2743
+ });
2744
+ var focusEventsPluginKey = new PluginKey("focusEvents");
2745
+ var FocusEvents = Extension.create({
2746
+ name: "focusEvents",
2747
+ addProseMirrorPlugins() {
2748
+ const { editor } = this;
2749
+ return [
2750
+ new Plugin({
2751
+ key: focusEventsPluginKey,
2752
+ props: {
2753
+ handleDOMEvents: {
2754
+ focus: (view, event) => {
2755
+ editor.isFocused = true;
2756
+ const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
2757
+ view.dispatch(transaction);
2758
+ return false;
2759
+ },
2760
+ blur: (view, event) => {
2761
+ editor.isFocused = false;
2762
+ const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
2763
+ view.dispatch(transaction);
2764
+ return false;
2765
+ }
2766
+ }
2767
+ }
2768
+ })
2769
+ ];
2770
+ }
2771
+ });
2772
+ var Keymap = Extension.create({
2773
+ name: "keymap",
2774
+ addKeyboardShortcuts() {
2775
+ const handleBackspace = () => this.editor.commands.first(({ commands }) => [
2776
+ () => commands.undoInputRule(),
2777
+ // maybe convert first text block node to default node
2778
+ () => commands.command(({ tr }) => {
2779
+ const { selection, doc } = tr;
2780
+ const { empty, $anchor } = selection;
2781
+ const { pos, parent } = $anchor;
2782
+ const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr.doc.resolve(pos - 1) : $anchor;
2783
+ const parentIsIsolating = $parentPos.parent.type.spec.isolating;
2784
+ const parentPos = $anchor.pos - $anchor.parentOffset;
2785
+ const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc).from === pos;
2786
+ if (!empty || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
2787
+ return false;
2788
+ }
2789
+ return commands.clearNodes();
2790
+ }),
2791
+ () => commands.deleteSelection(),
2792
+ () => commands.joinBackward(),
2793
+ () => commands.selectNodeBackward()
2794
+ ]);
2795
+ const handleDelete = () => this.editor.commands.first(({ commands }) => [
2796
+ () => commands.deleteSelection(),
2797
+ () => commands.deleteCurrentNode(),
2798
+ () => commands.joinForward(),
2799
+ () => commands.selectNodeForward()
2800
+ ]);
2801
+ const handleEnter = () => this.editor.commands.first(({ commands }) => [
2802
+ () => commands.newlineInCode(),
2803
+ () => commands.createParagraphNear(),
2804
+ () => commands.liftEmptyBlock(),
2805
+ () => commands.splitBlock()
2806
+ ]);
2807
+ const baseKeymap = {
2808
+ Enter: handleEnter,
2809
+ "Mod-Enter": () => this.editor.commands.exitCode(),
2810
+ Backspace: handleBackspace,
2811
+ "Mod-Backspace": handleBackspace,
2812
+ "Shift-Backspace": handleBackspace,
2813
+ Delete: handleDelete,
2814
+ "Mod-Delete": handleDelete,
2815
+ "Mod-a": () => this.editor.commands.selectAll()
2816
+ };
2817
+ const pcKeymap = {
2818
+ ...baseKeymap
2819
+ };
2820
+ const macKeymap = {
2821
+ ...baseKeymap,
2822
+ "Ctrl-h": handleBackspace,
2823
+ "Alt-Backspace": handleBackspace,
2824
+ "Ctrl-d": handleDelete,
2825
+ "Ctrl-Alt-Backspace": handleDelete,
2826
+ "Alt-Delete": handleDelete,
2827
+ "Alt-d": handleDelete,
2828
+ "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
2829
+ "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
2830
+ };
2831
+ if (isiOS() || isMacOS()) {
2832
+ return macKeymap;
2833
+ }
2834
+ return pcKeymap;
2835
+ },
2836
+ addProseMirrorPlugins() {
2837
+ return [
2838
+ // With this plugin we check if the whole document was selected and deleted.
2839
+ // In this case we will additionally call `clearNodes()` to convert e.g. a heading
2840
+ // to a paragraph if necessary.
2841
+ // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
2842
+ // with many other commands.
2843
+ new Plugin({
2844
+ key: new PluginKey("clearDocument"),
2845
+ appendTransaction: (transactions, oldState, newState) => {
2846
+ if (transactions.some((tr2) => tr2.getMeta("composition"))) {
2847
+ return;
2848
+ }
2849
+ const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
2850
+ const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument"));
2851
+ if (!docChanges || ignoreTr) {
2852
+ return;
2853
+ }
2854
+ const { empty, from, to } = oldState.selection;
2855
+ const allFrom = Selection.atStart(oldState.doc).from;
2856
+ const allEnd = Selection.atEnd(oldState.doc).to;
2857
+ const allWasSelected = from === allFrom && to === allEnd;
2858
+ if (empty || !allWasSelected) {
2859
+ return;
2860
+ }
2861
+ const isEmpty = isNodeEmpty(newState.doc);
2862
+ if (!isEmpty) {
2863
+ return;
2864
+ }
2865
+ const tr = newState.tr;
2866
+ const state = createChainableState({
2867
+ state: newState,
2868
+ transaction: tr
2869
+ });
2870
+ const { commands } = new CommandManager({
2871
+ editor: this.editor,
2872
+ state
2873
+ });
2874
+ commands.clearNodes();
2875
+ if (!tr.steps.length) {
2876
+ return;
2877
+ }
2878
+ return tr;
2879
+ }
2880
+ })
2881
+ ];
2882
+ }
2883
+ });
2884
+ var Paste = Extension.create({
2885
+ name: "paste",
2886
+ addProseMirrorPlugins() {
2887
+ return [
2888
+ new Plugin({
2889
+ key: new PluginKey("tiptapPaste"),
2890
+ props: {
2891
+ handlePaste: (_view, e, slice) => {
2892
+ this.editor.emit("paste", {
2893
+ editor: this.editor,
2894
+ event: e,
2895
+ slice
2896
+ });
2897
+ }
2898
+ }
2899
+ })
2900
+ ];
2901
+ }
2902
+ });
2903
+ var Tabindex = Extension.create({
2904
+ name: "tabindex",
2905
+ addProseMirrorPlugins() {
2906
+ return [
2907
+ new Plugin({
2908
+ key: new PluginKey("tabindex"),
2909
+ props: {
2910
+ attributes: () => this.editor.isEditable ? { tabindex: "0" } : {}
2911
+ }
2912
+ })
2913
+ ];
2914
+ }
2915
+ });
2916
+ var TextDirection = Extension.create({
2917
+ name: "textDirection",
2918
+ addOptions() {
2919
+ return {
2920
+ direction: void 0
2921
+ };
2922
+ },
2923
+ addGlobalAttributes() {
2924
+ if (!this.options.direction) {
2925
+ return [];
2926
+ }
2927
+ const { nodeExtensions } = splitExtensions(this.extensions);
2928
+ return [
2929
+ {
2930
+ types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name),
2931
+ attributes: {
2932
+ dir: {
2933
+ default: this.options.direction,
2934
+ parseHTML: (element) => {
2935
+ const dir = element.getAttribute("dir");
2936
+ if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) {
2937
+ return dir;
2938
+ }
2939
+ return this.options.direction;
2940
+ },
2941
+ renderHTML: (attributes) => {
2942
+ if (!attributes.dir) {
2943
+ return {};
2944
+ }
2945
+ return {
2946
+ dir: attributes.dir
2947
+ };
2948
+ }
2949
+ }
2950
+ }
2951
+ }
2952
+ ];
2953
+ },
2954
+ addProseMirrorPlugins() {
2955
+ return [
2956
+ new Plugin({
2957
+ key: new PluginKey("textDirection"),
2958
+ props: {
2959
+ attributes: () => {
2960
+ const direction = this.options.direction;
2961
+ if (!direction) {
2962
+ return {};
2963
+ }
2964
+ return {
2965
+ dir: direction
2966
+ };
2967
+ }
2968
+ }
2969
+ })
2970
+ ];
2971
+ }
2972
+ });
2973
+ function textblockTypeInputRule(config) {
2974
+ return new InputRule({
2975
+ find: config.find,
2976
+ handler: ({ state, range, match }) => {
2977
+ const $start = state.doc.resolve(range.from);
2978
+ const attributes = callOrReturn(config.getAttributes, void 0, match) || {};
2979
+ if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {
2980
+ return null;
2981
+ }
2982
+ state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes);
2983
+ },
2984
+ undoable: config.undoable
2985
+ });
2986
+ }
2987
+ var markdown_exports = {};
2988
+ __export(markdown_exports, {
2989
+ createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec,
2990
+ createBlockMarkdownSpec: () => createBlockMarkdownSpec,
2991
+ createInlineMarkdownSpec: () => createInlineMarkdownSpec,
2992
+ parseAttributes: () => parseAttributes,
2993
+ parseIndentedBlocks: () => parseIndentedBlocks,
2994
+ renderNestedMarkdownContent: () => renderNestedMarkdownContent,
2995
+ serializeAttributes: () => serializeAttributes
2996
+ });
2997
+ function parseAttributes(attrString) {
2998
+ if (!(attrString == null ? void 0 : attrString.trim())) {
2999
+ return {};
3000
+ }
3001
+ const attributes = {};
3002
+ const quotedStrings = [];
3003
+ const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => {
3004
+ quotedStrings.push(match);
3005
+ return `__QUOTED_${quotedStrings.length - 1}__`;
3006
+ });
3007
+ const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);
3008
+ if (classMatches) {
3009
+ const classes = classMatches.map((match) => match.trim().slice(1));
3010
+ attributes.class = classes.join(" ");
3011
+ }
3012
+ const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);
3013
+ if (idMatch) {
3014
+ attributes.id = idMatch[1];
3015
+ }
3016
+ const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;
3017
+ const kvMatches = Array.from(tempString.matchAll(kvRegex));
3018
+ kvMatches.forEach(([, key, quotedRef]) => {
3019
+ var _a;
3020
+ const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10);
3021
+ const quotedValue = quotedStrings[quotedIndex];
3022
+ if (quotedValue) {
3023
+ attributes[key] = quotedValue.slice(1, -1);
3024
+ }
3025
+ });
3026
+ 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();
3027
+ if (cleanString) {
3028
+ const booleanAttrs = cleanString.split(/\s+/).filter(Boolean);
3029
+ booleanAttrs.forEach((attr) => {
3030
+ if (attr.match(/^[a-zA-Z][\w-]*$/)) {
3031
+ attributes[attr] = true;
3032
+ }
3033
+ });
3034
+ }
3035
+ return attributes;
3036
+ }
3037
+ function serializeAttributes(attributes) {
3038
+ if (!attributes || Object.keys(attributes).length === 0) {
3039
+ return "";
3040
+ }
3041
+ const parts = [];
3042
+ if (attributes.class) {
3043
+ const classes = String(attributes.class).split(/\s+/).filter(Boolean);
3044
+ classes.forEach((cls) => parts.push(`.${cls}`));
3045
+ }
3046
+ if (attributes.id) {
3047
+ parts.push(`#${attributes.id}`);
3048
+ }
3049
+ Object.entries(attributes).forEach(([key, value]) => {
3050
+ if (key === "class" || key === "id") {
3051
+ return;
3052
+ }
3053
+ if (value === true) {
3054
+ parts.push(key);
3055
+ } else if (value !== false && value != null) {
3056
+ parts.push(`${key}="${String(value)}"`);
3057
+ }
3058
+ });
3059
+ return parts.join(" ");
3060
+ }
3061
+ function createAtomBlockMarkdownSpec(options) {
3062
+ const {
3063
+ nodeName,
3064
+ name: markdownName,
3065
+ parseAttributes: parseAttributes2 = parseAttributes,
3066
+ serializeAttributes: serializeAttributes2 = serializeAttributes,
3067
+ defaultAttributes = {},
3068
+ requiredAttributes = [],
3069
+ allowedAttributes
3070
+ } = options;
3071
+ const blockName = markdownName || nodeName;
3072
+ const filterAttributes = (attrs) => {
3073
+ if (!allowedAttributes) {
3074
+ return attrs;
3075
+ }
3076
+ const filtered = {};
3077
+ allowedAttributes.forEach((key) => {
3078
+ if (key in attrs) {
3079
+ filtered[key] = attrs[key];
3080
+ }
3081
+ });
3082
+ return filtered;
3083
+ };
3084
+ return {
3085
+ parseMarkdown: (token, h2) => {
3086
+ const attrs = { ...defaultAttributes, ...token.attributes };
3087
+ return h2.createNode(nodeName, attrs, []);
3088
+ },
3089
+ markdownTokenizer: {
3090
+ name: nodeName,
3091
+ level: "block",
3092
+ start(src) {
3093
+ var _a;
3094
+ const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m");
3095
+ const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
3096
+ return index !== void 0 ? index : -1;
3097
+ },
3098
+ tokenize(src, _tokens, _lexer) {
3099
+ const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`);
3100
+ const match = src.match(regex);
3101
+ if (!match) {
3102
+ return void 0;
3103
+ }
3104
+ const attrString = match[1] || "";
3105
+ const attributes = parseAttributes2(attrString);
3106
+ const missingRequired = requiredAttributes.find((required) => !(required in attributes));
3107
+ if (missingRequired) {
3108
+ return void 0;
3109
+ }
3110
+ return {
3111
+ type: nodeName,
3112
+ raw: match[0],
3113
+ attributes
3114
+ };
3115
+ }
3116
+ },
3117
+ renderMarkdown: (node) => {
3118
+ const filteredAttrs = filterAttributes(node.attrs || {});
3119
+ const attrs = serializeAttributes2(filteredAttrs);
3120
+ const attrString = attrs ? ` {${attrs}}` : "";
3121
+ return `:::${blockName}${attrString} :::`;
3122
+ }
3123
+ };
3124
+ }
3125
+ function createBlockMarkdownSpec(options) {
3126
+ const {
3127
+ nodeName,
3128
+ name: markdownName,
3129
+ getContent,
3130
+ parseAttributes: parseAttributes2 = parseAttributes,
3131
+ serializeAttributes: serializeAttributes2 = serializeAttributes,
3132
+ defaultAttributes = {},
3133
+ content = "block",
3134
+ allowedAttributes
3135
+ } = options;
3136
+ const blockName = markdownName || nodeName;
3137
+ const filterAttributes = (attrs) => {
3138
+ if (!allowedAttributes) {
3139
+ return attrs;
3140
+ }
3141
+ const filtered = {};
3142
+ allowedAttributes.forEach((key) => {
3143
+ if (key in attrs) {
3144
+ filtered[key] = attrs[key];
3145
+ }
3146
+ });
3147
+ return filtered;
3148
+ };
3149
+ return {
3150
+ parseMarkdown: (token, h2) => {
3151
+ let nodeContent;
3152
+ if (getContent) {
3153
+ const contentResult = getContent(token);
3154
+ nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult;
3155
+ } else if (content === "block") {
3156
+ nodeContent = h2.parseChildren(token.tokens || []);
3157
+ } else {
3158
+ nodeContent = h2.parseInline(token.tokens || []);
3159
+ }
3160
+ const attrs = { ...defaultAttributes, ...token.attributes };
3161
+ return h2.createNode(nodeName, attrs, nodeContent);
3162
+ },
3163
+ markdownTokenizer: {
3164
+ name: nodeName,
3165
+ level: "block",
3166
+ start(src) {
3167
+ var _a;
3168
+ const regex = new RegExp(`^:::${blockName}`, "m");
3169
+ const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
3170
+ return index !== void 0 ? index : -1;
3171
+ },
3172
+ tokenize(src, _tokens, lexer) {
3173
+ var _a;
3174
+ const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`);
3175
+ const openingMatch = src.match(openingRegex);
3176
+ if (!openingMatch) {
3177
+ return void 0;
3178
+ }
3179
+ const [openingTag, attrString = ""] = openingMatch;
3180
+ const attributes = parseAttributes2(attrString);
3181
+ let level = 1;
3182
+ const position = openingTag.length;
3183
+ let matchedContent = "";
3184
+ const blockPattern = /^:::([\w-]*)(\s.*)?/gm;
3185
+ const remaining = src.slice(position);
3186
+ blockPattern.lastIndex = 0;
3187
+ for (; ; ) {
3188
+ const match = blockPattern.exec(remaining);
3189
+ if (match === null) {
3190
+ break;
3191
+ }
3192
+ const matchPos = match.index;
3193
+ const blockType = match[1];
3194
+ if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) {
3195
+ continue;
3196
+ }
3197
+ if (blockType) {
3198
+ level += 1;
3199
+ } else {
3200
+ level -= 1;
3201
+ if (level === 0) {
3202
+ const rawContent = remaining.slice(0, matchPos);
3203
+ matchedContent = rawContent.trim();
3204
+ const fullMatch = src.slice(0, position + matchPos + match[0].length);
3205
+ let contentTokens = [];
3206
+ if (matchedContent) {
3207
+ if (content === "block") {
3208
+ contentTokens = lexer.blockTokens(rawContent);
3209
+ contentTokens.forEach((token) => {
3210
+ if (token.text && (!token.tokens || token.tokens.length === 0)) {
3211
+ token.tokens = lexer.inlineTokens(token.text);
3212
+ }
3213
+ });
3214
+ while (contentTokens.length > 0) {
3215
+ const lastToken = contentTokens[contentTokens.length - 1];
3216
+ if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) {
3217
+ contentTokens.pop();
3218
+ } else {
3219
+ break;
3220
+ }
3221
+ }
3222
+ } else {
3223
+ contentTokens = lexer.inlineTokens(matchedContent);
3224
+ }
3225
+ }
3226
+ return {
3227
+ type: nodeName,
3228
+ raw: fullMatch,
3229
+ attributes,
3230
+ content: matchedContent,
3231
+ tokens: contentTokens
3232
+ };
3233
+ }
3234
+ }
3235
+ }
3236
+ return void 0;
3237
+ }
3238
+ },
3239
+ renderMarkdown: (node, h2) => {
3240
+ const filteredAttrs = filterAttributes(node.attrs || {});
3241
+ const attrs = serializeAttributes2(filteredAttrs);
3242
+ const attrString = attrs ? ` {${attrs}}` : "";
3243
+ const renderedContent = h2.renderChildren(node.content || [], "\n\n");
3244
+ return `:::${blockName}${attrString}
3245
+
3246
+ ${renderedContent}
3247
+
3248
+ :::`;
3249
+ }
3250
+ };
3251
+ }
3252
+ function parseShortcodeAttributes(attrString) {
3253
+ if (!attrString.trim()) {
3254
+ return {};
3255
+ }
3256
+ const attributes = {};
3257
+ const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g;
3258
+ let match = regex.exec(attrString);
3259
+ while (match !== null) {
3260
+ const [, key, doubleQuoted, singleQuoted] = match;
3261
+ attributes[key] = doubleQuoted || singleQuoted;
3262
+ match = regex.exec(attrString);
3263
+ }
3264
+ return attributes;
3265
+ }
3266
+ function serializeShortcodeAttributes(attrs) {
3267
+ return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" ");
3268
+ }
3269
+ function createInlineMarkdownSpec(options) {
3270
+ const {
3271
+ nodeName,
3272
+ name: shortcodeName,
3273
+ getContent,
3274
+ parseAttributes: parseAttributes2 = parseShortcodeAttributes,
3275
+ serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes,
3276
+ defaultAttributes = {},
3277
+ selfClosing = false,
3278
+ allowedAttributes
3279
+ } = options;
3280
+ const shortcode = shortcodeName || nodeName;
3281
+ const filterAttributes = (attrs) => {
3282
+ if (!allowedAttributes) {
3283
+ return attrs;
3284
+ }
3285
+ const filtered = {};
3286
+ allowedAttributes.forEach((attr) => {
3287
+ const attrName = typeof attr === "string" ? attr : attr.name;
3288
+ const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault;
3289
+ if (attrName in attrs) {
3290
+ const value = attrs[attrName];
3291
+ if (skipIfDefault !== void 0 && value === skipIfDefault) {
3292
+ return;
3293
+ }
3294
+ filtered[attrName] = value;
3295
+ }
3296
+ });
3297
+ return filtered;
3298
+ };
3299
+ const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3300
+ return {
3301
+ parseMarkdown: (token, h2) => {
3302
+ const attrs = { ...defaultAttributes, ...token.attributes };
3303
+ if (selfClosing) {
3304
+ return h2.createNode(nodeName, attrs);
3305
+ }
3306
+ const content = getContent ? getContent(token) : token.content || "";
3307
+ if (content) {
3308
+ return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]);
3309
+ }
3310
+ return h2.createNode(nodeName, attrs, []);
3311
+ },
3312
+ markdownTokenizer: {
3313
+ name: nodeName,
3314
+ level: "inline",
3315
+ start(src) {
3316
+ const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`);
3317
+ const match = src.match(startPattern);
3318
+ const index = match == null ? void 0 : match.index;
3319
+ return index !== void 0 ? index : -1;
3320
+ },
3321
+ tokenize(src, _tokens, _lexer) {
3322
+ const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`);
3323
+ const match = src.match(tokenPattern);
3324
+ if (!match) {
3325
+ return void 0;
3326
+ }
3327
+ let content = "";
3328
+ let attrString = "";
3329
+ if (selfClosing) {
3330
+ const [, attrs] = match;
3331
+ attrString = attrs;
3332
+ } else {
3333
+ const [, attrs, contentMatch] = match;
3334
+ attrString = attrs;
3335
+ content = contentMatch || "";
3336
+ }
3337
+ const attributes = parseAttributes2(attrString.trim());
3338
+ return {
3339
+ type: nodeName,
3340
+ raw: match[0],
3341
+ content: content.trim(),
3342
+ attributes
3343
+ };
3344
+ }
3345
+ },
3346
+ renderMarkdown: (node) => {
3347
+ let content = "";
3348
+ if (getContent) {
3349
+ content = getContent(node);
3350
+ } else if (node.content && node.content.length > 0) {
3351
+ content = node.content.filter((child) => child.type === "text").map((child) => child.text).join("");
3352
+ }
3353
+ const filteredAttrs = filterAttributes(node.attrs || {});
3354
+ const attrs = serializeAttributes2(filteredAttrs);
3355
+ const attrString = attrs ? ` ${attrs}` : "";
3356
+ if (selfClosing) {
3357
+ return `[${shortcode}${attrString}]`;
3358
+ }
3359
+ return `[${shortcode}${attrString}]${content}[/${shortcode}]`;
3360
+ }
3361
+ };
3362
+ }
3363
+ function parseIndentedBlocks(src, config, lexer) {
3364
+ var _a, _b, _c, _d;
3365
+ const lines = src.split("\n");
3366
+ const items = [];
3367
+ let totalRaw = "";
3368
+ let i = 0;
3369
+ const baseIndentSize = config.baseIndentSize || 2;
3370
+ while (i < lines.length) {
3371
+ const currentLine = lines[i];
3372
+ const itemMatch = currentLine.match(config.itemPattern);
3373
+ if (!itemMatch) {
3374
+ if (items.length > 0) {
3375
+ break;
3376
+ } else if (currentLine.trim() === "") {
3377
+ i += 1;
3378
+ totalRaw = `${totalRaw}${currentLine}
3379
+ `;
3380
+ continue;
3381
+ } else {
3382
+ return void 0;
3383
+ }
3384
+ }
3385
+ const itemData = config.extractItemData(itemMatch);
3386
+ const { indentLevel, mainContent } = itemData;
3387
+ totalRaw = `${totalRaw}${currentLine}
3388
+ `;
3389
+ const itemContent = [mainContent];
3390
+ i += 1;
3391
+ while (i < lines.length) {
3392
+ const nextLine = lines[i];
3393
+ if (nextLine.trim() === "") {
3394
+ const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== "");
3395
+ if (nextNonEmptyIndex === -1) {
3396
+ break;
3397
+ }
3398
+ const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex];
3399
+ const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0;
3400
+ if (nextIndent2 > indentLevel) {
3401
+ itemContent.push(nextLine);
3402
+ totalRaw = `${totalRaw}${nextLine}
3403
+ `;
3404
+ i += 1;
3405
+ continue;
3406
+ } else {
3407
+ break;
3408
+ }
3409
+ }
3410
+ const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0;
3411
+ if (nextIndent > indentLevel) {
3412
+ itemContent.push(nextLine);
3413
+ totalRaw = `${totalRaw}${nextLine}
3414
+ `;
3415
+ i += 1;
3416
+ } else {
3417
+ break;
3418
+ }
3419
+ }
3420
+ let nestedTokens;
3421
+ const nestedContent = itemContent.slice(1);
3422
+ if (nestedContent.length > 0) {
3423
+ const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n");
3424
+ if (dedentedNested.trim()) {
3425
+ if (config.customNestedParser) {
3426
+ nestedTokens = config.customNestedParser(dedentedNested);
3427
+ } else {
3428
+ nestedTokens = lexer.blockTokens(dedentedNested);
3429
+ }
3430
+ }
3431
+ }
3432
+ const token = config.createToken(itemData, nestedTokens);
3433
+ items.push(token);
3434
+ }
3435
+ if (items.length === 0) {
3436
+ return void 0;
3437
+ }
3438
+ return {
3439
+ items,
3440
+ raw: totalRaw
3441
+ };
3442
+ }
3443
+ function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) {
3444
+ if (!node || !Array.isArray(node.content)) {
3445
+ return "";
3446
+ }
3447
+ const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator;
3448
+ const [content, ...children] = node.content;
3449
+ const mainContent = h2.renderChildren([content]);
3450
+ const output = [`${prefix}${mainContent}`];
3451
+ if (children && children.length > 0) {
3452
+ children.forEach((child) => {
3453
+ const childContent = h2.renderChildren([child]);
3454
+ if (childContent) {
3455
+ const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : "").join("\n");
3456
+ output.push(indentedChild);
3457
+ }
3458
+ });
3459
+ }
3460
+ return output.join("\n");
3461
+ }
3462
+ var Node3 = class _Node extends Extendable {
3463
+ constructor() {
3464
+ super(...arguments);
3465
+ this.type = "node";
3466
+ }
3467
+ /**
3468
+ * Create a new Node instance
3469
+ * @param config - Node configuration object or a function that returns a configuration object
3470
+ */
3471
+ static create(config = {}) {
3472
+ const resolvedConfig = typeof config === "function" ? config() : config;
3473
+ return new _Node(resolvedConfig);
3474
+ }
3475
+ configure(options) {
3476
+ return super.configure(options);
3477
+ }
3478
+ extend(extendedConfig) {
3479
+ const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
3480
+ return super.extend(resolvedConfig);
3481
+ }
3482
+ };
3483
+ var Heading = Node3.create({
3484
+ name: "heading",
3485
+ addOptions() {
3486
+ return {
3487
+ levels: [1, 2, 3, 4, 5, 6],
3488
+ HTMLAttributes: {}
3489
+ };
3490
+ },
3491
+ content: "inline*",
3492
+ group: "block",
3493
+ defining: true,
3494
+ addAttributes() {
3495
+ return {
3496
+ level: {
3497
+ default: 1,
3498
+ rendered: false
3499
+ }
3500
+ };
3501
+ },
3502
+ parseHTML() {
3503
+ return this.options.levels.map((level) => ({
3504
+ tag: `h${level}`,
3505
+ attrs: { level }
3506
+ }));
3507
+ },
3508
+ renderHTML({ node, HTMLAttributes }) {
3509
+ const hasLevel = this.options.levels.includes(node.attrs.level);
3510
+ const level = hasLevel ? node.attrs.level : this.options.levels[0];
3511
+ return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
3512
+ },
3513
+ parseMarkdown: (token, helpers) => {
3514
+ return helpers.createNode("heading", { level: token.depth || 1 }, helpers.parseInline(token.tokens || []));
3515
+ },
3516
+ renderMarkdown: (node, h) => {
3517
+ var _a;
3518
+ const level = ((_a = node.attrs) == null ? void 0 : _a.level) ? parseInt(node.attrs.level, 10) : 1;
3519
+ const headingChars = "#".repeat(level);
3520
+ if (!node.content) {
3521
+ return "";
3522
+ }
3523
+ return `${headingChars} ${h.renderChildren(node.content)}`;
3524
+ },
3525
+ addCommands() {
3526
+ return {
3527
+ setHeading: (attributes) => ({ commands }) => {
3528
+ if (!this.options.levels.includes(attributes.level)) {
3529
+ return false;
3530
+ }
3531
+ return commands.setNode(this.name, attributes);
3532
+ },
3533
+ toggleHeading: (attributes) => ({ commands }) => {
3534
+ if (!this.options.levels.includes(attributes.level)) {
3535
+ return false;
3536
+ }
3537
+ return commands.toggleNode(this.name, "paragraph", attributes);
3538
+ }
3539
+ };
3540
+ },
3541
+ addKeyboardShortcuts() {
3542
+ return this.options.levels.reduce(
3543
+ (items, level) => ({
3544
+ ...items,
3545
+ ...{
3546
+ [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level })
3547
+ }
3548
+ }),
3549
+ {}
3550
+ );
3551
+ },
3552
+ addInputRules() {
3553
+ return this.options.levels.map((level) => {
3554
+ return textblockTypeInputRule({
3555
+ find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\s$`),
3556
+ type: this.type,
3557
+ getAttributes: {
3558
+ level
3559
+ }
3560
+ });
3561
+ });
3562
+ }
3563
+ });
3564
+ var index_default = Heading;
3565
+ const HeadingWithSEOTag = index_default.extend({
3566
+ addAttributes() {
3567
+ return {
3568
+ ...this.parent?.(),
3569
+ // must cast to any to avoid TS error
3570
+ tag: { default: null }
3571
+ };
3572
+ }
3573
+ }).configure({ levels: [1, 2, 3, 4] });
3574
+ function useHeading(editor, props = { disabled: false }) {
3575
+ const editorState = useEditorState({
3576
+ editor,
3577
+ selector: (ctx) => {
3578
+ return {
3579
+ headingLevel: ctx.editor.getAttributes("heading").level,
3580
+ headingTag: ctx.editor.getAttributes("heading").tag,
3581
+ isParagraph: ctx.editor.isActive("paragraph") ?? false
3582
+ };
3583
+ }
3584
+ });
3585
+ const onChangeHeading = (value) => {
3586
+ if (!editor) return;
3587
+ editor.chain().focus();
3588
+ if (value === "p") {
3589
+ editor.chain().focus().setParagraph().run();
3590
+ return;
3591
+ }
3592
+ const level = Number(value[1]);
3593
+ editor.chain().focus().setHeading({ level }).run();
3594
+ if (!editorState.headingTag) {
3595
+ editor.chain().focus().updateAttributes("heading", { tag: `h${level}` }).run();
3596
+ }
3597
+ };
3598
+ const onChangeHeadingTag = (value) => {
3599
+ if (!editor) return;
3600
+ if (!editorState.headingLevel) return;
3601
+ editor.chain().focus().updateAttributes("heading", { tag: value }).run();
3602
+ };
3603
+ return {
3604
+ headingSelect: /* @__PURE__ */ jsxs(
3605
+ SingleSelect,
3606
+ {
3607
+ placeholder: "Style",
3608
+ "aria-label": "Text style",
3609
+ value: editorState.headingLevel ? `h${editorState.headingLevel}` : "p",
3610
+ onChange: (v) => v && onChangeHeading(v),
3611
+ disabled: !editor || props.disabled,
3612
+ size: "S",
3613
+ children: [
3614
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "p", children: "Paragraph" }),
3615
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h1", children: "Heading 1" }),
3616
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h2", children: "Heading 2" }),
3617
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h3", children: "Heading 3" }),
3618
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h4", children: "Heading 4" })
3619
+ ]
3620
+ }
3621
+ ),
3622
+ headingTagSelect: /* @__PURE__ */ jsxs(
3623
+ SingleSelect,
3624
+ {
3625
+ placeholder: "SEO Tag",
3626
+ "aria-label": "Heading's HTML tag for SEO purposes",
3627
+ value: editorState.headingTag,
3628
+ onChange: (v) => v && onChangeHeadingTag(v),
3629
+ disabled: !editor || props.disabled || !editorState.headingLevel,
3630
+ size: "S",
3631
+ children: [
3632
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h1", children: "h1" }),
3633
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h2", children: "h2" }),
3634
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h3", children: "h3" }),
3635
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h4", children: "h4" }),
3636
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h5", children: "h5" }),
3637
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "h6", children: "h6" })
3638
+ ]
3639
+ }
3640
+ )
3641
+ };
3642
+ }
3643
+ function useScript(editor, props = { disabled: false }) {
3644
+ const editorState = useEditorState({
3645
+ editor,
3646
+ selector: (ctx) => {
3647
+ return {
3648
+ isSuperscript: ctx.editor.isActive("superscript") ?? false,
3649
+ canToggleSuperscript: ctx.editor.can().chain().toggleSuperscript().run() ?? false,
3650
+ isSubscript: ctx.editor.isActive("subscript") ?? false,
3651
+ canToggleSubscript: ctx.editor.can().chain().toggleSubscript().run() ?? false
3652
+ };
3653
+ }
3654
+ });
3655
+ const toggleSuperscript = () => {
3656
+ editor?.chain().focus().toggleSuperscript().run();
3657
+ };
3658
+ const toggleSubscript = () => {
3659
+ editor?.chain().focus().toggleSubscript().run();
3660
+ };
3661
+ return {
3662
+ superscriptButton: toolbarButton("superscript", {
3663
+ onClick: toggleSuperscript,
3664
+ icon: /* @__PURE__ */ jsxs(Fragment$1, { children: [
3665
+ "x",
3666
+ /* @__PURE__ */ jsx("sup", { children: "2" })
3667
+ ] }),
3668
+ active: editorState.isSuperscript,
3669
+ disabled: props.disabled || !editor || !editorState.canToggleSuperscript,
3670
+ tooltip: "Superscript"
3671
+ }),
3672
+ subscriptButton: toolbarButton("subscript", {
3673
+ onClick: toggleSubscript,
3674
+ icon: /* @__PURE__ */ jsxs(Fragment$1, { children: [
3675
+ "x",
3676
+ /* @__PURE__ */ jsx("sub", { children: "2" })
3677
+ ] }),
3678
+ active: editorState.isSubscript,
3679
+ disabled: props.disabled || !editor || !editorState.canToggleSubscript,
3680
+ tooltip: "Subscript"
3681
+ })
3682
+ };
3683
+ }
3684
+ Extension.create({
3685
+ name: "characterCount",
3686
+ addOptions() {
3687
+ return {
3688
+ limit: null,
3689
+ mode: "textSize",
3690
+ textCounter: (text) => text.length,
3691
+ wordCounter: (text) => text.split(" ").filter((word) => word !== "").length
3692
+ };
3693
+ },
3694
+ addStorage() {
3695
+ return {
3696
+ characters: () => 0,
3697
+ words: () => 0
3698
+ };
3699
+ },
3700
+ onBeforeCreate() {
3701
+ this.storage.characters = (options) => {
3702
+ const node = (options == null ? void 0 : options.node) || this.editor.state.doc;
3703
+ const mode = (options == null ? void 0 : options.mode) || this.options.mode;
3704
+ if (mode === "textSize") {
3705
+ const text = node.textBetween(0, node.content.size, void 0, " ");
3706
+ return this.options.textCounter(text);
3707
+ }
3708
+ return node.nodeSize;
3709
+ };
3710
+ this.storage.words = (options) => {
3711
+ const node = (options == null ? void 0 : options.node) || this.editor.state.doc;
3712
+ const text = node.textBetween(0, node.content.size, " ", " ");
3713
+ return this.options.wordCounter(text);
3714
+ };
3715
+ },
3716
+ addProseMirrorPlugins() {
3717
+ let initialEvaluationDone = false;
3718
+ return [
3719
+ new Plugin({
3720
+ key: new PluginKey("characterCount"),
3721
+ appendTransaction: (transactions, oldState, newState) => {
3722
+ if (initialEvaluationDone) {
3723
+ return;
3724
+ }
3725
+ const limit = this.options.limit;
3726
+ if (limit === null || limit === void 0 || limit === 0) {
3727
+ initialEvaluationDone = true;
3728
+ return;
3729
+ }
3730
+ const initialContentSize = this.storage.characters({ node: newState.doc });
3731
+ if (initialContentSize > limit) {
3732
+ const over = initialContentSize - limit;
3733
+ const from = 0;
3734
+ const to = over;
3735
+ console.warn(
3736
+ `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`
3737
+ );
3738
+ const tr = newState.tr.deleteRange(from, to);
3739
+ initialEvaluationDone = true;
3740
+ return tr;
3741
+ }
3742
+ initialEvaluationDone = true;
3743
+ },
3744
+ filterTransaction: (transaction, state) => {
3745
+ const limit = this.options.limit;
3746
+ if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) {
3747
+ return true;
3748
+ }
3749
+ const oldSize = this.storage.characters({ node: state.doc });
3750
+ const newSize = this.storage.characters({ node: transaction.doc });
3751
+ if (newSize <= limit) {
3752
+ return true;
3753
+ }
3754
+ if (oldSize > limit && newSize > limit && newSize <= oldSize) {
3755
+ return true;
3756
+ }
3757
+ if (oldSize > limit && newSize > limit && newSize > oldSize) {
3758
+ return false;
3759
+ }
3760
+ const isPaste = transaction.getMeta("paste");
3761
+ if (!isPaste) {
3762
+ return false;
3763
+ }
3764
+ const pos = transaction.selection.$head.pos;
3765
+ const over = newSize - limit;
3766
+ const from = pos - over;
3767
+ const to = pos;
3768
+ transaction.deleteRange(from, to);
3769
+ const updatedSize = this.storage.characters({ node: transaction.doc });
3770
+ if (updatedSize > limit) {
3771
+ return false;
3772
+ }
3773
+ return true;
3774
+ }
3775
+ })
3776
+ ];
3777
+ }
3778
+ });
3779
+ Extension.create({
3780
+ name: "dropCursor",
3781
+ addOptions() {
3782
+ return {
3783
+ color: "currentColor",
3784
+ width: 1,
3785
+ class: void 0
3786
+ };
3787
+ },
3788
+ addProseMirrorPlugins() {
3789
+ return [dropCursor(this.options)];
3790
+ }
3791
+ });
3792
+ Extension.create({
3793
+ name: "focus",
3794
+ addOptions() {
3795
+ return {
3796
+ className: "has-focus",
3797
+ mode: "all"
3798
+ };
3799
+ },
3800
+ addProseMirrorPlugins() {
3801
+ return [
3802
+ new Plugin({
3803
+ key: new PluginKey("focus"),
3804
+ props: {
3805
+ decorations: ({ doc, selection }) => {
3806
+ const { isEditable, isFocused } = this.editor;
3807
+ const { anchor } = selection;
3808
+ const decorations = [];
3809
+ if (!isEditable || !isFocused) {
3810
+ return DecorationSet.create(doc, []);
3811
+ }
3812
+ let maxLevels = 0;
3813
+ if (this.options.mode === "deepest") {
3814
+ doc.descendants((node, pos) => {
3815
+ if (node.isText) {
3816
+ return;
3817
+ }
3818
+ const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1;
3819
+ if (!isCurrent) {
3820
+ return false;
3821
+ }
3822
+ maxLevels += 1;
3823
+ });
3824
+ }
3825
+ let currentLevel = 0;
3826
+ doc.descendants((node, pos) => {
3827
+ if (node.isText) {
3828
+ return false;
3829
+ }
3830
+ const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1;
3831
+ if (!isCurrent) {
3832
+ return false;
3833
+ }
3834
+ currentLevel += 1;
3835
+ const outOfScope = this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1;
3836
+ if (outOfScope) {
3837
+ return this.options.mode === "deepest";
3838
+ }
3839
+ decorations.push(
3840
+ Decoration.node(pos, pos + node.nodeSize, {
3841
+ class: this.options.className
3842
+ })
3843
+ );
3844
+ });
3845
+ return DecorationSet.create(doc, decorations);
3846
+ }
3847
+ }
3848
+ })
3849
+ ];
3850
+ }
3851
+ });
3852
+ var Gapcursor = Extension.create({
3853
+ name: "gapCursor",
3854
+ addProseMirrorPlugins() {
3855
+ return [gapCursor()];
3856
+ },
3857
+ extendNodeSchema(extension) {
3858
+ var _a;
3859
+ const context = {
3860
+ name: extension.name,
3861
+ options: extension.options,
3862
+ storage: extension.storage
3863
+ };
3864
+ return {
3865
+ allowGapCursor: (_a = callOrReturn(getExtensionField(extension, "allowGapCursor", context))) != null ? _a : null
3866
+ };
3867
+ }
3868
+ });
3869
+ var DEFAULT_DATA_ATTRIBUTE = "placeholder";
3870
+ function preparePlaceholderAttribute(attr) {
3871
+ return attr.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9-]/g, "").replace(/^[0-9-]+/, "").replace(/^-+/, "").toLowerCase();
3872
+ }
3873
+ Extension.create({
3874
+ name: "placeholder",
3875
+ addOptions() {
3876
+ return {
3877
+ emptyEditorClass: "is-editor-empty",
3878
+ emptyNodeClass: "is-empty",
3879
+ dataAttribute: DEFAULT_DATA_ATTRIBUTE,
3880
+ placeholder: "Write something …",
3881
+ showOnlyWhenEditable: true,
3882
+ showOnlyCurrent: true,
3883
+ includeChildren: false
3884
+ };
3885
+ },
3886
+ addProseMirrorPlugins() {
3887
+ const dataAttribute = this.options.dataAttribute ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}` : `data-${DEFAULT_DATA_ATTRIBUTE}`;
3888
+ return [
3889
+ new Plugin({
3890
+ key: new PluginKey("placeholder"),
3891
+ props: {
3892
+ decorations: ({ doc, selection }) => {
3893
+ const active = this.editor.isEditable || !this.options.showOnlyWhenEditable;
3894
+ const { anchor } = selection;
3895
+ const decorations = [];
3896
+ if (!active) {
3897
+ return null;
3898
+ }
3899
+ const isEmptyDoc = this.editor.isEmpty;
3900
+ doc.descendants((node, pos) => {
3901
+ const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
3902
+ const isEmpty = !node.isLeaf && isNodeEmpty(node);
3903
+ if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
3904
+ const classes = [this.options.emptyNodeClass];
3905
+ if (isEmptyDoc) {
3906
+ classes.push(this.options.emptyEditorClass);
3907
+ }
3908
+ const decoration = Decoration.node(pos, pos + node.nodeSize, {
3909
+ class: classes.join(" "),
3910
+ [dataAttribute]: typeof this.options.placeholder === "function" ? this.options.placeholder({
3911
+ editor: this.editor,
3912
+ node,
3913
+ pos,
3914
+ hasAnchor
3915
+ }) : this.options.placeholder
3916
+ });
3917
+ decorations.push(decoration);
3918
+ }
3919
+ return this.options.includeChildren;
3920
+ });
3921
+ return DecorationSet.create(doc, decorations);
3922
+ }
3923
+ }
3924
+ })
3925
+ ];
3926
+ }
3927
+ });
3928
+ Extension.create({
3929
+ name: "selection",
3930
+ addOptions() {
3931
+ return {
3932
+ className: "selection"
3933
+ };
3934
+ },
3935
+ addProseMirrorPlugins() {
3936
+ const { editor, options } = this;
3937
+ return [
3938
+ new Plugin({
3939
+ key: new PluginKey("selection"),
3940
+ props: {
3941
+ decorations(state) {
3942
+ if (state.selection.empty || editor.isFocused || !editor.isEditable || isNodeSelection(state.selection) || editor.view.dragging) {
3943
+ return null;
3944
+ }
3945
+ return DecorationSet.create(state.doc, [
3946
+ Decoration.inline(state.selection.from, state.selection.to, {
3947
+ class: options.className
3948
+ })
3949
+ ]);
3950
+ }
3951
+ }
3952
+ })
3953
+ ];
3954
+ }
3955
+ });
3956
+ function nodeEqualsType({ types, node }) {
3957
+ return node && Array.isArray(types) && types.includes(node.type) || (node == null ? void 0 : node.type) === types;
3958
+ }
3959
+ Extension.create({
3960
+ name: "trailingNode",
3961
+ addOptions() {
3962
+ return {
3963
+ node: void 0,
3964
+ notAfter: []
3965
+ };
3966
+ },
3967
+ addProseMirrorPlugins() {
3968
+ var _a;
3969
+ const plugin = new PluginKey(this.name);
3970
+ const defaultNode = this.options.node || ((_a = this.editor.schema.topNodeType.contentMatch.defaultType) == null ? void 0 : _a.name) || "paragraph";
3971
+ const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node) => (this.options.notAfter || []).concat(defaultNode).includes(node.name));
3972
+ return [
3973
+ new Plugin({
3974
+ key: plugin,
3975
+ appendTransaction: (_, __, state) => {
3976
+ const { doc, tr, schema } = state;
3977
+ const shouldInsertNodeAtEnd = plugin.getState(state);
3978
+ const endPosition = doc.content.size;
3979
+ const type = schema.nodes[defaultNode];
3980
+ if (!shouldInsertNodeAtEnd) {
3981
+ return;
3982
+ }
3983
+ return tr.insert(endPosition, type.create());
3984
+ },
3985
+ state: {
3986
+ init: (_, state) => {
3987
+ const lastNode = state.tr.doc.lastChild;
3988
+ return !nodeEqualsType({ node: lastNode, types: disabledNodes });
3989
+ },
3990
+ apply: (tr, value) => {
3991
+ if (!tr.docChanged) {
3992
+ return value;
3993
+ }
3994
+ if (tr.getMeta("__uniqueIDTransaction")) {
3995
+ return value;
3996
+ }
3997
+ const lastNode = tr.doc.lastChild;
3998
+ return !nodeEqualsType({ node: lastNode, types: disabledNodes });
3999
+ }
4000
+ }
4001
+ })
4002
+ ];
4003
+ }
4004
+ });
4005
+ Extension.create({
4006
+ name: "undoRedo",
4007
+ addOptions() {
4008
+ return {
4009
+ depth: 100,
4010
+ newGroupDelay: 500
4011
+ };
4012
+ },
4013
+ addCommands() {
4014
+ return {
4015
+ undo: () => ({ state, dispatch }) => {
4016
+ return undo(state, dispatch);
4017
+ },
4018
+ redo: () => ({ state, dispatch }) => {
4019
+ return redo(state, dispatch);
4020
+ }
4021
+ };
4022
+ },
4023
+ addProseMirrorPlugins() {
4024
+ return [history(this.options)];
4025
+ },
4026
+ addKeyboardShortcuts() {
4027
+ return {
4028
+ "Mod-z": () => this.editor.commands.undo(),
4029
+ "Shift-Mod-z": () => this.editor.commands.redo(),
4030
+ "Mod-y": () => this.editor.commands.redo(),
4031
+ // Russian keyboard layouts
4032
+ "Mod-я": () => this.editor.commands.undo(),
4033
+ "Shift-Mod-я": () => this.editor.commands.redo()
4034
+ };
4035
+ }
4036
+ });
4037
+ const clamp = (val, min, max) => Math.max(min, Math.min(max, val));
4038
+ const parseNum = (value, fallback) => {
4039
+ const n = Number(value);
4040
+ return Number.isFinite(n) ? n : fallback;
4041
+ };
4042
+ const TableSizeDialog = ({
4043
+ open,
4044
+ defaultRows = 3,
4045
+ defaultCols = 3,
4046
+ onClose,
4047
+ onSave
4048
+ }) => {
4049
+ const [rows, setRows] = useState(defaultRows);
4050
+ const [cols, setCols] = useState(defaultCols);
4051
+ useEffect(() => {
4052
+ if (open) {
4053
+ setRows(defaultRows);
4054
+ setCols(defaultCols);
4055
+ }
4056
+ }, [open, defaultRows, defaultCols]);
4057
+ const min = 1;
4058
+ const max = 10;
4059
+ const isValid = rows >= min && rows <= max && cols >= min && cols <= max;
4060
+ const handleSave = () => {
4061
+ if (!isValid) return;
4062
+ onSave(clamp(rows, min, max), clamp(cols, min, max));
4063
+ };
4064
+ return /* @__PURE__ */ jsx(
4065
+ Dialog.Root,
4066
+ {
4067
+ open,
4068
+ onOpenChange: (v) => {
4069
+ if (!v) onClose();
4070
+ },
4071
+ children: open && /* @__PURE__ */ jsxs(Dialog.Content, { children: [
4072
+ /* @__PURE__ */ jsx(Dialog.Header, { children: "Insert table" }),
4073
+ /* @__PURE__ */ jsx(Dialog.Body, { children: /* @__PURE__ */ jsxs(Flex, { gap: 4, alignItems: "flex-end", children: [
4074
+ /* @__PURE__ */ jsxs(Field.Root, { width: "100%", children: [
4075
+ /* @__PURE__ */ jsx(Field.Label, { children: "Rows" }),
4076
+ /* @__PURE__ */ jsx(
4077
+ TextInput,
4078
+ {
4079
+ name: "table-rows",
4080
+ type: "number",
4081
+ value: String(rows),
4082
+ onChange: (e) => setRows(clamp(parseNum(e.target.value, rows), min, max)),
4083
+ placeholder: String(defaultRows)
4084
+ }
4085
+ ),
4086
+ /* @__PURE__ */ jsxs(Field.Hint, { children: [
4087
+ "Min ",
4088
+ min,
4089
+ ", max ",
4090
+ max
4091
+ ] })
4092
+ ] }),
4093
+ /* @__PURE__ */ jsxs(Field.Root, { width: "100%", children: [
4094
+ /* @__PURE__ */ jsx(Field.Label, { children: "Columns" }),
4095
+ /* @__PURE__ */ jsx(
4096
+ TextInput,
4097
+ {
4098
+ name: "table-cols",
4099
+ type: "number",
4100
+ value: String(cols),
4101
+ onChange: (e) => setCols(clamp(parseNum(e.target.value, cols), min, max)),
4102
+ placeholder: String(defaultCols)
4103
+ }
4104
+ ),
4105
+ /* @__PURE__ */ jsxs(Field.Hint, { children: [
4106
+ "Min ",
4107
+ min,
4108
+ ", max ",
4109
+ max
4110
+ ] })
4111
+ ] })
4112
+ ] }) }),
4113
+ /* @__PURE__ */ jsxs(Dialog.Footer, { children: [
4114
+ /* @__PURE__ */ jsx(Dialog.Cancel, { children: /* @__PURE__ */ jsx(Button, { variant: "tertiary", fullWidth: true, onClick: onClose, children: "Cancel" }) }),
4115
+ /* @__PURE__ */ jsx(Dialog.Action, { children: /* @__PURE__ */ jsx(Button, { fullWidth: true, variant: "success-light", onClick: handleSave, disabled: !isValid, children: "Insert" }) })
4116
+ ] })
4117
+ ] })
4118
+ }
4119
+ );
4120
+ };
4121
+ function useTable(editor, props = { disabled: false }) {
4122
+ const editorState = useEditorState({
4123
+ editor,
4124
+ selector: (ctx) => {
4125
+ return {
4126
+ isTable: ctx.editor.isActive("table") ?? false,
4127
+ canInsertTable: ctx.editor.can().chain().insertTable().run() ?? false,
4128
+ canAddColumn: ctx.editor.can().chain().addColumnAfter().run() ?? false,
4129
+ canDeleteColumn: ctx.editor.can().chain().deleteColumn().run() ?? false,
4130
+ canAddRow: ctx.editor.can().chain().addRowAfter().run() ?? false,
4131
+ canDeleteRow: ctx.editor.can().chain().deleteRow().run() ?? false
4132
+ };
4133
+ }
4134
+ });
4135
+ const [open, setOpen] = useState(false);
4136
+ const handleOpenDialog = () => {
4137
+ if (!editor) return;
4138
+ setOpen(true);
4139
+ };
4140
+ const handleInsert = (rows, cols) => {
4141
+ if (!editor) return;
4142
+ editor.chain().focus().insertTable({ rows, cols, withHeaderRow: true }).run();
4143
+ setOpen(false);
4144
+ };
4145
+ const addColumn = () => editor?.chain().focus().addColumnAfter().run();
4146
+ const removeColumn = () => editor?.chain().focus().deleteColumn().run();
4147
+ const addRow = () => editor?.chain().focus().addRowAfter().run();
4148
+ const removeRow = () => editor?.chain().focus().deleteRow().run();
4149
+ return {
4150
+ tableButton: toolbarButton("table", {
4151
+ onClick: handleOpenDialog,
4152
+ icon: /* @__PURE__ */ jsx(GridNine, {}),
4153
+ active: editorState.isTable,
4154
+ disabled: props.disabled || !editor || !editorState.canInsertTable,
4155
+ tooltip: "Table"
4156
+ }),
4157
+ // Adding table manipulation buttons
4158
+ addColumnButton: toolbarButton("tableAddColumn", {
4159
+ onClick: addColumn,
4160
+ icon: /* @__PURE__ */ jsx(Fragment$1, { children: "+Col" }),
4161
+ active: false,
4162
+ hidden: props.disabled || !editor || !editorState.canAddColumn,
4163
+ tooltip: "Add column (to the right)"
4164
+ }),
4165
+ removeColumnButton: toolbarButton("tableRemoveColumn", {
4166
+ onClick: removeColumn,
4167
+ icon: /* @__PURE__ */ jsx(Fragment$1, { children: "-Col" }),
4168
+ active: false,
4169
+ hidden: props.disabled || !editor || !editorState.canDeleteColumn,
4170
+ tooltip: "Remove column"
4171
+ }),
4172
+ addRowButton: toolbarButton("tableAddRow", {
4173
+ onClick: addRow,
4174
+ icon: /* @__PURE__ */ jsx(Fragment$1, { children: "+Row" }),
4175
+ active: false,
4176
+ hidden: props.disabled || !editor || !editorState.canAddRow,
4177
+ tooltip: "Add row (below)"
4178
+ }),
4179
+ removeRowButton: toolbarButton("tableRemoveRow", {
4180
+ onClick: removeRow,
4181
+ icon: /* @__PURE__ */ jsx(Fragment$1, { children: "-Row" }),
4182
+ active: false,
4183
+ hidden: props.disabled || !editor || !editorState.canDeleteRow,
4184
+ tooltip: "Remove row"
4185
+ }),
4186
+ tableDialog: /* @__PURE__ */ jsx(
4187
+ TableSizeDialog,
4188
+ {
4189
+ open,
4190
+ onClose: () => setOpen(false),
4191
+ onSave: handleInsert,
4192
+ defaultRows: 3,
4193
+ defaultCols: 3
4194
+ }
4195
+ )
4196
+ };
4197
+ }
4198
+ function TextAlignLeft(props) {
4199
+ return /* @__PURE__ */ jsx(
4200
+ "svg",
4201
+ {
4202
+ width: "16",
4203
+ height: "16",
4204
+ viewBox: "0 0 24 24",
4205
+ fill: "currentColor",
4206
+ xmlns: "http://www.w3.org/2000/svg",
4207
+ ...props,
4208
+ children: /* @__PURE__ */ jsx(
4209
+ "path",
4210
+ {
4211
+ d: "M3 10H16M3 14H21M3 18H16M3 6H21",
4212
+ stroke: "#000000",
4213
+ "stroke-width": "2",
4214
+ "stroke-linecap": "round",
4215
+ "stroke-linejoin": "round"
4216
+ }
4217
+ )
4218
+ }
4219
+ );
4220
+ }
4221
+ function TextAlignJustify(props) {
4222
+ return /* @__PURE__ */ jsx(
4223
+ "svg",
4224
+ {
4225
+ width: "16",
4226
+ height: "16",
4227
+ viewBox: "0 0 24 24",
4228
+ fill: "currentColor",
4229
+ xmlns: "http://www.w3.org/2000/svg",
4230
+ ...props,
4231
+ children: /* @__PURE__ */ jsx(
4232
+ "path",
4233
+ {
4234
+ d: "M3 10H21M3 14H21M3 18H21M3 6H21",
4235
+ stroke: "currentColor",
4236
+ "stroke-width": "2",
4237
+ "stroke-linecap": "round",
4238
+ "stroke-linejoin": "round"
4239
+ }
4240
+ )
4241
+ }
4242
+ );
4243
+ }
4244
+ function TextAlignRight(props) {
4245
+ return /* @__PURE__ */ jsx(
4246
+ "svg",
4247
+ {
4248
+ width: "16",
4249
+ height: "16",
4250
+ viewBox: "0 0 24 24",
4251
+ fill: "currentColor",
4252
+ xmlns: "http://www.w3.org/2000/svg",
4253
+ ...props,
4254
+ children: /* @__PURE__ */ jsx(
4255
+ "path",
4256
+ {
4257
+ d: "M8 10H21M3 14H21M8 18H21M3 6H21",
4258
+ stroke: "#000000",
4259
+ "stroke-width": "2",
4260
+ "stroke-linecap": "round",
4261
+ "stroke-linejoin": "round"
4262
+ }
4263
+ )
4264
+ }
4265
+ );
4266
+ }
4267
+ function TextAlignCenter(props) {
4268
+ return /* @__PURE__ */ jsx(
4269
+ "svg",
4270
+ {
4271
+ width: "16",
4272
+ height: "16",
4273
+ viewBox: "0 0 24 24",
4274
+ fill: "currentColor",
4275
+ xmlns: "http://www.w3.org/2000/svg",
4276
+ ...props,
4277
+ children: /* @__PURE__ */ jsx(
4278
+ "path",
4279
+ {
4280
+ d: "M3 6H21M3 14H21M17 10H7M17 18H7",
4281
+ stroke: "currentColor",
4282
+ "stroke-width": "2",
4283
+ "stroke-linecap": "round",
4284
+ "stroke-linejoin": "round"
4285
+ }
4286
+ )
4287
+ }
4288
+ );
4289
+ }
4290
+ function useTextAlign(editor, props = { disabled: false }) {
4291
+ const editorState = useEditorState({
4292
+ editor,
4293
+ selector: (ctx) => {
4294
+ return {
4295
+ isTextAlignLeft: ctx.editor.isActive({ textAlign: "left" }) ?? false,
4296
+ isTextAlignRight: ctx.editor.isActive({ textAlign: "right" }) ?? false,
4297
+ isTextAlignCenter: ctx.editor.isActive({ textAlign: "center" }) ?? false,
4298
+ isTextAlignJustify: ctx.editor.isActive({ textAlign: "justify" }) ?? false,
4299
+ canToggleAlign: ctx.editor.can().chain().setTextAlign("left").run() ?? false
4300
+ };
4301
+ }
4302
+ });
4303
+ const setTextAlign = (alignment) => {
4304
+ editor.chain().focus().setTextAlign(alignment).run();
4305
+ };
4306
+ return {
4307
+ textAlignLeftButton: toolbarButton("text-align-left", {
4308
+ onClick: () => setTextAlign("left"),
4309
+ icon: /* @__PURE__ */ jsx(TextAlignLeft, {}),
4310
+ active: editorState.isTextAlignLeft,
4311
+ disabled: props.disabled || !editor || !editorState.canToggleAlign,
4312
+ tooltip: "Text Align Left"
4313
+ }),
4314
+ textAlignCenterButton: toolbarButton("text-align-center", {
4315
+ onClick: () => setTextAlign("center"),
4316
+ icon: /* @__PURE__ */ jsx(TextAlignCenter, {}),
4317
+ active: editorState.isTextAlignCenter,
4318
+ disabled: props.disabled || !editor || !editorState.canToggleAlign,
4319
+ tooltip: "Text Align Center"
4320
+ }),
4321
+ textAlignRightButton: toolbarButton("text-align-right", {
4322
+ onClick: () => setTextAlign("right"),
4323
+ icon: /* @__PURE__ */ jsx(TextAlignRight, {}),
4324
+ active: editorState.isTextAlignRight,
4325
+ disabled: props.disabled || !editor || !editorState.canToggleAlign,
4326
+ tooltip: "Text Align Right"
4327
+ }),
4328
+ textAlignJustifyButton: toolbarButton("text-align-justify", {
4329
+ onClick: () => setTextAlign("justify"),
4330
+ icon: /* @__PURE__ */ jsx(TextAlignJustify, {}),
4331
+ active: editorState.isTextAlignJustify,
4332
+ disabled: props.disabled || !editor || !editorState.canToggleAlign,
4333
+ tooltip: "Text Align Justify"
4334
+ })
4335
+ };
4336
+ }
4337
+ const extensions = [
4338
+ StarterKit.configure({
4339
+ heading: false,
4340
+ // disable default so we can use our custom version
4341
+ link: {
4342
+ openOnClick: false
4343
+ }
4344
+ }),
4345
+ HeadingWithSEOTag,
4346
+ Superscript,
4347
+ Subscript,
4348
+ Gapcursor,
4349
+ // cursor for resizing tables
4350
+ TableKit.configure({
4351
+ table: { resizable: true }
4352
+ }),
4353
+ TextAlign.configure({
4354
+ types: ["heading", "paragraph"]
4355
+ })
4356
+ ];
4357
+ const RichTextInput = forwardRef((props, forwardedRef) => {
4358
+ const { editor, field } = useTiptapEditor(props.name, "", extensions);
4359
+ const starterKit = useStarterKit(editor, { disabled: props.disabled });
4360
+ const heading = useHeading(editor, { disabled: props.disabled });
4361
+ const link = useLink(editor, { disabled: props.disabled });
4362
+ const script = useScript(editor, { disabled: props.disabled });
4363
+ const table = useTable(editor, { disabled: props.disabled });
4364
+ const textAlign = useTextAlign(editor, { disabled: props.disabled });
4365
+ return /* @__PURE__ */ jsxs(BaseTiptapInput, { editor, field, ...props, ref: forwardedRef, children: [
4366
+ heading.headingSelect,
4367
+ heading.headingTagSelect,
4368
+ spacer(8),
4369
+ starterKit.boldButton,
4370
+ starterKit.italicButton,
4371
+ starterKit.underlineButton,
4372
+ starterKit.strikeButton,
4373
+ script.superscriptButton,
4374
+ script.subscriptButton,
4375
+ spacer(8),
4376
+ textAlign.textAlignLeftButton,
4377
+ textAlign.textAlignCenterButton,
4378
+ textAlign.textAlignRightButton,
4379
+ textAlign.textAlignJustifyButton,
4380
+ spacer(8),
4381
+ starterKit.bulletButton,
4382
+ starterKit.orderedButton,
4383
+ spacer(8),
4384
+ starterKit.codeButton,
4385
+ starterKit.blockquoteButton,
4386
+ link.linkButton,
4387
+ link.linkDialog,
4388
+ spacer(8),
4389
+ table.tableButton,
4390
+ table.addColumnButton,
4391
+ table.removeColumnButton,
4392
+ table.addRowButton,
4393
+ table.removeRowButton,
4394
+ table.tableDialog
4395
+ ] });
4396
+ });
4397
+ export {
4398
+ RichTextInput as default
4399
+ };
4400
+ //# sourceMappingURL=RichTextInput-DtaYdjCs.mjs.map