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