@tiptap/core 2.0.0-beta.135 → 2.0.0-beta.136

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 (143) hide show
  1. package/dist/packages/core/src/CommandManager.d.ts +20 -0
  2. package/dist/packages/core/src/Editor.d.ts +145 -0
  3. package/dist/packages/core/src/EventEmitter.d.ts +11 -0
  4. package/dist/packages/core/src/Extension.d.ts +227 -0
  5. package/dist/packages/core/src/ExtensionManager.d.ts +18 -0
  6. package/dist/packages/core/src/InputRule.d.ts +42 -0
  7. package/dist/packages/core/src/Mark.d.ts +319 -0
  8. package/dist/packages/core/src/Node.d.ts +388 -0
  9. package/dist/packages/core/src/NodeView.d.ts +27 -0
  10. package/dist/packages/core/src/PasteRule.d.ts +42 -0
  11. package/dist/packages/core/src/Tracker.d.ts +11 -0
  12. package/dist/packages/core/src/commands/blur.d.ts +12 -0
  13. package/dist/packages/core/src/commands/clearContent.d.ts +12 -0
  14. package/dist/packages/core/src/commands/clearNodes.d.ts +12 -0
  15. package/dist/packages/core/src/commands/command.d.ts +12 -0
  16. package/dist/packages/core/src/commands/createParagraphNear.d.ts +12 -0
  17. package/dist/packages/core/src/commands/deleteNode.d.ts +13 -0
  18. package/dist/packages/core/src/commands/deleteRange.d.ts +12 -0
  19. package/dist/packages/core/src/commands/deleteSelection.d.ts +12 -0
  20. package/dist/packages/core/src/commands/enter.d.ts +12 -0
  21. package/dist/packages/core/src/commands/exitCode.d.ts +12 -0
  22. package/dist/packages/core/src/commands/extendMarkRange.d.ts +13 -0
  23. package/dist/packages/core/src/commands/first.d.ts +12 -0
  24. package/dist/packages/core/src/commands/focus.d.ts +12 -0
  25. package/dist/packages/core/src/commands/forEach.d.ts +14 -0
  26. package/dist/packages/core/src/commands/insertContent.d.ts +16 -0
  27. package/dist/packages/core/src/commands/insertContentAt.d.ts +16 -0
  28. package/dist/packages/core/src/commands/joinBackward.d.ts +12 -0
  29. package/dist/packages/core/src/commands/joinForward.d.ts +12 -0
  30. package/dist/packages/core/src/commands/keyboardShortcut.d.ts +12 -0
  31. package/dist/packages/core/src/commands/lift.d.ts +13 -0
  32. package/dist/packages/core/src/commands/liftEmptyBlock.d.ts +12 -0
  33. package/dist/packages/core/src/commands/liftListItem.d.ts +13 -0
  34. package/dist/packages/core/src/commands/newlineInCode.d.ts +12 -0
  35. package/dist/packages/core/src/commands/resetAttributes.d.ts +13 -0
  36. package/dist/packages/core/src/commands/scrollIntoView.d.ts +12 -0
  37. package/dist/packages/core/src/commands/selectAll.d.ts +12 -0
  38. package/dist/packages/core/src/commands/selectNodeBackward.d.ts +12 -0
  39. package/dist/packages/core/src/commands/selectNodeForward.d.ts +12 -0
  40. package/dist/packages/core/src/commands/selectParentNode.d.ts +12 -0
  41. package/dist/packages/core/src/commands/setContent.d.ts +13 -0
  42. package/dist/packages/core/src/commands/setMark.d.ts +13 -0
  43. package/dist/packages/core/src/commands/setMeta.d.ts +12 -0
  44. package/dist/packages/core/src/commands/setNode.d.ts +13 -0
  45. package/dist/packages/core/src/commands/setNodeSelection.d.ts +12 -0
  46. package/dist/packages/core/src/commands/setTextSelection.d.ts +12 -0
  47. package/dist/packages/core/src/commands/sinkListItem.d.ts +13 -0
  48. package/dist/packages/core/src/commands/splitBlock.d.ts +14 -0
  49. package/dist/packages/core/src/commands/splitListItem.d.ts +13 -0
  50. package/dist/packages/core/src/commands/toggleList.d.ts +13 -0
  51. package/dist/packages/core/src/commands/toggleMark.d.ts +18 -0
  52. package/dist/packages/core/src/commands/toggleNode.d.ts +13 -0
  53. package/dist/packages/core/src/commands/toggleWrap.d.ts +13 -0
  54. package/dist/packages/core/src/commands/undoInputRule.d.ts +12 -0
  55. package/dist/packages/core/src/commands/unsetAllMarks.d.ts +12 -0
  56. package/dist/packages/core/src/commands/unsetMark.d.ts +18 -0
  57. package/dist/packages/core/src/commands/updateAttributes.d.ts +13 -0
  58. package/dist/packages/core/src/commands/wrapIn.d.ts +13 -0
  59. package/dist/packages/core/src/commands/wrapInList.d.ts +13 -0
  60. package/dist/packages/core/src/extensions/clipboardTextSerializer.d.ts +2 -0
  61. package/dist/packages/core/src/extensions/commands.d.ts +98 -0
  62. package/dist/packages/core/src/extensions/editable.d.ts +2 -0
  63. package/dist/packages/core/src/extensions/focusEvents.d.ts +2 -0
  64. package/dist/packages/core/src/extensions/index.d.ts +6 -0
  65. package/dist/packages/core/src/extensions/keymap.d.ts +2 -0
  66. package/dist/packages/core/src/extensions/tabindex.d.ts +2 -0
  67. package/dist/packages/core/src/helpers/createChainableState.d.ts +5 -0
  68. package/dist/packages/core/src/helpers/createDocument.d.ts +3 -0
  69. package/dist/packages/core/src/helpers/createNodeFromContent.d.ts +7 -0
  70. package/dist/packages/core/src/helpers/findChildren.d.ts +3 -0
  71. package/dist/packages/core/src/helpers/findChildrenInRange.d.ts +6 -0
  72. package/dist/packages/core/src/helpers/findParentNode.d.ts +9 -0
  73. package/dist/packages/core/src/helpers/findParentNodeClosestToPos.d.ts +8 -0
  74. package/dist/packages/core/src/helpers/generateHTML.d.ts +2 -0
  75. package/dist/packages/core/src/helpers/generateJSON.d.ts +2 -0
  76. package/dist/packages/core/src/helpers/generateText.d.ts +5 -0
  77. package/dist/packages/core/src/helpers/getAttributes.d.ts +3 -0
  78. package/dist/packages/core/src/helpers/getAttributesFromExtensions.d.ts +6 -0
  79. package/dist/packages/core/src/helpers/getDebugJSON.d.ts +8 -0
  80. package/dist/packages/core/src/helpers/getExtensionField.d.ts +2 -0
  81. package/dist/packages/core/src/helpers/getHTMLFromFragment.d.ts +2 -0
  82. package/dist/packages/core/src/helpers/getMarkAttributes.d.ts +3 -0
  83. package/dist/packages/core/src/helpers/getMarkRange.d.ts +3 -0
  84. package/dist/packages/core/src/helpers/getMarkType.d.ts +2 -0
  85. package/dist/packages/core/src/helpers/getMarksBetween.d.ts +3 -0
  86. package/dist/packages/core/src/helpers/getNodeAttributes.d.ts +3 -0
  87. package/dist/packages/core/src/helpers/getNodeType.d.ts +2 -0
  88. package/dist/packages/core/src/helpers/getRenderedAttributes.d.ts +3 -0
  89. package/dist/packages/core/src/helpers/getSchema.d.ts +3 -0
  90. package/dist/packages/core/src/helpers/getSchemaByResolvedExtensions.d.ts +3 -0
  91. package/dist/packages/core/src/helpers/getSchemaTypeByName.d.ts +2 -0
  92. package/dist/packages/core/src/helpers/getSchemaTypeNameByName.d.ts +2 -0
  93. package/dist/packages/core/src/helpers/getSplittedAttributes.d.ts +2 -0
  94. package/dist/packages/core/src/helpers/getText.d.ts +6 -0
  95. package/dist/packages/core/src/helpers/getTextBetween.d.ts +6 -0
  96. package/dist/packages/core/src/helpers/getTextSeralizersFromSchema.d.ts +3 -0
  97. package/dist/packages/core/src/helpers/injectExtensionAttributesToParseRule.d.ts +9 -0
  98. package/dist/packages/core/src/helpers/isActive.d.ts +2 -0
  99. package/dist/packages/core/src/helpers/isList.d.ts +2 -0
  100. package/dist/packages/core/src/helpers/isMarkActive.d.ts +3 -0
  101. package/dist/packages/core/src/helpers/isNodeActive.d.ts +3 -0
  102. package/dist/packages/core/src/helpers/isNodeEmpty.d.ts +2 -0
  103. package/dist/packages/core/src/helpers/isNodeSelection.d.ts +2 -0
  104. package/dist/packages/core/src/helpers/isTextSelection.d.ts +2 -0
  105. package/dist/packages/core/src/helpers/posToDOMRect.d.ts +2 -0
  106. package/dist/packages/core/src/helpers/selectionToInsertionEnd.d.ts +2 -0
  107. package/dist/packages/core/src/helpers/splitExtensions.d.ts +9 -0
  108. package/dist/packages/core/src/index.d.ts +57 -0
  109. package/dist/packages/core/src/inputRules/markInputRule.d.ts +12 -0
  110. package/dist/packages/core/src/inputRules/nodeInputRule.d.ts +12 -0
  111. package/dist/packages/core/src/inputRules/textInputRule.d.ts +9 -0
  112. package/dist/packages/core/src/inputRules/textblockTypeInputRule.d.ts +14 -0
  113. package/dist/packages/core/src/inputRules/wrappingInputRule.d.ts +23 -0
  114. package/dist/packages/core/src/pasteRules/markPasteRule.d.ts +12 -0
  115. package/dist/packages/core/src/pasteRules/textPasteRule.d.ts +9 -0
  116. package/dist/packages/core/src/style.d.ts +2 -0
  117. package/dist/packages/core/src/types.d.ts +209 -0
  118. package/dist/packages/core/src/utilities/callOrReturn.d.ts +9 -0
  119. package/dist/packages/core/src/utilities/createStyleTag.d.ts +1 -0
  120. package/dist/packages/core/src/utilities/deleteProps.d.ts +6 -0
  121. package/dist/packages/core/src/utilities/elementFromString.d.ts +1 -0
  122. package/dist/packages/core/src/utilities/findDuplicates.d.ts +1 -0
  123. package/dist/packages/core/src/utilities/fromString.d.ts +1 -0
  124. package/dist/packages/core/src/utilities/isClass.d.ts +1 -0
  125. package/dist/packages/core/src/utilities/isEmptyObject.d.ts +1 -0
  126. package/dist/packages/core/src/utilities/isFunction.d.ts +1 -0
  127. package/dist/packages/core/src/utilities/isNumber.d.ts +1 -0
  128. package/dist/packages/core/src/utilities/isObject.d.ts +1 -0
  129. package/dist/packages/core/src/utilities/isPlainObject.d.ts +1 -0
  130. package/dist/packages/core/src/utilities/isRegExp.d.ts +1 -0
  131. package/dist/packages/core/src/utilities/isiOS.d.ts +1 -0
  132. package/dist/packages/core/src/utilities/mergeAttributes.d.ts +1 -0
  133. package/dist/packages/core/src/utilities/mergeDeep.d.ts +1 -0
  134. package/dist/packages/core/src/utilities/minMax.d.ts +1 -0
  135. package/dist/packages/core/src/utilities/objectIncludes.d.ts +8 -0
  136. package/dist/packages/core/src/utilities/removeElement.d.ts +1 -0
  137. package/dist/tiptap-core.cjs.js +4133 -0
  138. package/dist/tiptap-core.cjs.js.map +1 -0
  139. package/dist/tiptap-core.esm.js +4082 -0
  140. package/dist/tiptap-core.esm.js.map +1 -0
  141. package/dist/tiptap-core.umd.js +4131 -0
  142. package/dist/tiptap-core.umd.js.map +1 -0
  143. package/package.json +2 -2
@@ -0,0 +1,4082 @@
1
+ import { Plugin, PluginKey, TextSelection, Selection, NodeSelection, EditorState } from 'prosemirror-state';
2
+ import { liftTarget, ReplaceStep, ReplaceAroundStep, canSplit, findWrapping, canJoin } from 'prosemirror-transform';
3
+ import { createParagraphNear as createParagraphNear$2, deleteSelection as deleteSelection$2, exitCode as exitCode$2, joinBackward as joinBackward$2, joinForward as joinForward$2, lift as lift$2, liftEmptyBlock as liftEmptyBlock$2, newlineInCode as newlineInCode$2, selectNodeBackward as selectNodeBackward$2, selectNodeForward as selectNodeForward$2, selectParentNode as selectParentNode$2, setBlockType, wrapIn as wrapIn$2 } from 'prosemirror-commands';
4
+ import { Fragment, DOMParser, Slice, DOMSerializer, Schema, Node as Node$1 } from 'prosemirror-model';
5
+ import { liftListItem as liftListItem$2, sinkListItem as sinkListItem$2, wrapInList as wrapInList$2 } from 'prosemirror-schema-list';
6
+ import { EditorView } from 'prosemirror-view';
7
+ import { keymap } from 'prosemirror-keymap';
8
+
9
+ // see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts
10
+ function getType(value) {
11
+ return Object.prototype.toString.call(value).slice(8, -1);
12
+ }
13
+ function isPlainObject(value) {
14
+ if (getType(value) !== 'Object')
15
+ return false;
16
+ return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
17
+ }
18
+
19
+ function mergeDeep(target, source) {
20
+ const output = { ...target };
21
+ if (isPlainObject(target) && isPlainObject(source)) {
22
+ Object.keys(source).forEach(key => {
23
+ if (isPlainObject(source[key])) {
24
+ if (!(key in target)) {
25
+ Object.assign(output, { [key]: source[key] });
26
+ }
27
+ else {
28
+ output[key] = mergeDeep(target[key], source[key]);
29
+ }
30
+ }
31
+ else {
32
+ Object.assign(output, { [key]: source[key] });
33
+ }
34
+ });
35
+ }
36
+ return output;
37
+ }
38
+
39
+ function isObject$1(value) {
40
+ return typeof value === 'function';
41
+ }
42
+
43
+ /**
44
+ * Optionally calls `value` as a function.
45
+ * Otherwise it is returned directly.
46
+ * @param value Function or any value.
47
+ * @param context Optional context to bind to function.
48
+ * @param props Optional props to pass to function.
49
+ */
50
+ function callOrReturn(value, context = undefined, ...props) {
51
+ if (isObject$1(value)) {
52
+ if (context) {
53
+ return value.bind(context)(...props);
54
+ }
55
+ return value(...props);
56
+ }
57
+ return value;
58
+ }
59
+
60
+ function getExtensionField(extension, field, context) {
61
+ if (extension.config[field] === undefined && extension.parent) {
62
+ return getExtensionField(extension.parent, field, context);
63
+ }
64
+ if (typeof extension.config[field] === 'function') {
65
+ const value = extension.config[field].bind({
66
+ ...context,
67
+ parent: extension.parent
68
+ ? getExtensionField(extension.parent, field, context)
69
+ : null,
70
+ });
71
+ return value;
72
+ }
73
+ return extension.config[field];
74
+ }
75
+
76
+ class Extension {
77
+ constructor(config = {}) {
78
+ this.type = 'extension';
79
+ this.name = 'extension';
80
+ this.parent = null;
81
+ this.child = null;
82
+ this.config = {
83
+ name: this.name,
84
+ defaultOptions: {},
85
+ };
86
+ this.config = {
87
+ ...this.config,
88
+ ...config,
89
+ };
90
+ this.name = this.config.name;
91
+ if (config.defaultOptions) {
92
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
93
+ }
94
+ // TODO: remove `addOptions` fallback
95
+ this.options = this.config.defaultOptions;
96
+ if (this.config.addOptions) {
97
+ this.options = callOrReturn(getExtensionField(this, 'addOptions', {
98
+ name: this.name,
99
+ }));
100
+ }
101
+ this.storage = callOrReturn(getExtensionField(this, 'addStorage', {
102
+ name: this.name,
103
+ options: this.options,
104
+ })) || {};
105
+ }
106
+ static create(config = {}) {
107
+ return new Extension(config);
108
+ }
109
+ configure(options = {}) {
110
+ // return a new instance so we can use the same extension
111
+ // with different calls of `configure`
112
+ const extension = this.extend();
113
+ extension.options = mergeDeep(this.options, options);
114
+ extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {
115
+ name: extension.name,
116
+ options: extension.options,
117
+ }));
118
+ return extension;
119
+ }
120
+ extend(extendedConfig = {}) {
121
+ const extension = new Extension(extendedConfig);
122
+ extension.parent = this;
123
+ this.child = extension;
124
+ extension.name = extendedConfig.name
125
+ ? extendedConfig.name
126
+ : extension.parent.name;
127
+ if (extendedConfig.defaultOptions) {
128
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
129
+ }
130
+ // TODO: remove `addOptions` fallback
131
+ extension.options = extendedConfig.defaultOptions
132
+ ? extendedConfig.defaultOptions
133
+ : extension.parent.options;
134
+ if (extendedConfig.addOptions) {
135
+ extension.options = callOrReturn(getExtensionField(extension, 'addOptions', {
136
+ name: extension.name,
137
+ }));
138
+ }
139
+ extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {
140
+ name: extension.name,
141
+ options: extension.options,
142
+ }));
143
+ return extension;
144
+ }
145
+ }
146
+
147
+ function getTextBetween(startNode, range, options) {
148
+ const { from, to } = range;
149
+ const { blockSeparator = '\n\n', textSerializers = {}, } = options || {};
150
+ let text = '';
151
+ let separated = true;
152
+ startNode.nodesBetween(from, to, (node, pos, parent, index) => {
153
+ var _a;
154
+ const textSerializer = textSerializers === null || textSerializers === void 0 ? void 0 : textSerializers[node.type.name];
155
+ if (textSerializer) {
156
+ if (node.isBlock && !separated) {
157
+ text += blockSeparator;
158
+ separated = true;
159
+ }
160
+ text += textSerializer({
161
+ node,
162
+ pos,
163
+ parent,
164
+ index,
165
+ });
166
+ }
167
+ else if (node.isText) {
168
+ text += (_a = node === null || node === void 0 ? void 0 : node.text) === null || _a === void 0 ? void 0 : _a.slice(Math.max(from, pos) - pos, to - pos);
169
+ separated = false;
170
+ }
171
+ else if (node.isBlock && !separated) {
172
+ text += blockSeparator;
173
+ separated = true;
174
+ }
175
+ });
176
+ return text;
177
+ }
178
+
179
+ function getTextSeralizersFromSchema(schema) {
180
+ return Object.fromEntries(Object
181
+ .entries(schema.nodes)
182
+ .filter(([, node]) => node.spec.toText)
183
+ .map(([name, node]) => [name, node.spec.toText]));
184
+ }
185
+
186
+ const ClipboardTextSerializer = Extension.create({
187
+ name: 'clipboardTextSerializer',
188
+ addProseMirrorPlugins() {
189
+ return [
190
+ new Plugin({
191
+ key: new PluginKey('clipboardTextSerializer'),
192
+ props: {
193
+ clipboardTextSerializer: () => {
194
+ const { editor } = this;
195
+ const { state, schema } = editor;
196
+ const { doc, selection } = state;
197
+ const { from, to } = selection;
198
+ const textSerializers = getTextSeralizersFromSchema(schema);
199
+ const range = { from, to };
200
+ return getTextBetween(doc, range, {
201
+ textSerializers,
202
+ });
203
+ },
204
+ },
205
+ }),
206
+ ];
207
+ },
208
+ });
209
+
210
+ const blur = () => ({ editor, view }) => {
211
+ requestAnimationFrame(() => {
212
+ if (!editor.isDestroyed) {
213
+ view.dom.blur();
214
+ }
215
+ });
216
+ return true;
217
+ };
218
+
219
+ var blur$1 = /*#__PURE__*/Object.freeze({
220
+ __proto__: null,
221
+ blur: blur
222
+ });
223
+
224
+ const clearContent = (emitUpdate = false) => ({ commands }) => {
225
+ return commands.setContent('', emitUpdate);
226
+ };
227
+
228
+ var clearContent$1 = /*#__PURE__*/Object.freeze({
229
+ __proto__: null,
230
+ clearContent: clearContent
231
+ });
232
+
233
+ const clearNodes = () => ({ state, tr, dispatch }) => {
234
+ const { selection } = tr;
235
+ const { ranges } = selection;
236
+ ranges.forEach(range => {
237
+ state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
238
+ if (node.type.isText) {
239
+ return;
240
+ }
241
+ const $fromPos = tr.doc.resolve(tr.mapping.map(pos));
242
+ const $toPos = tr.doc.resolve(tr.mapping.map(pos + node.nodeSize));
243
+ const nodeRange = $fromPos.blockRange($toPos);
244
+ if (!nodeRange) {
245
+ return;
246
+ }
247
+ const targetLiftDepth = liftTarget(nodeRange);
248
+ if (node.type.isTextblock && dispatch) {
249
+ const { defaultType } = $fromPos.parent.contentMatchAt($fromPos.index());
250
+ tr.setNodeMarkup(nodeRange.start, defaultType);
251
+ }
252
+ if ((targetLiftDepth || targetLiftDepth === 0) && dispatch) {
253
+ tr.lift(nodeRange, targetLiftDepth);
254
+ }
255
+ });
256
+ });
257
+ return true;
258
+ };
259
+
260
+ var clearNodes$1 = /*#__PURE__*/Object.freeze({
261
+ __proto__: null,
262
+ clearNodes: clearNodes
263
+ });
264
+
265
+ const command = fn => props => {
266
+ return fn(props);
267
+ };
268
+
269
+ var command$1 = /*#__PURE__*/Object.freeze({
270
+ __proto__: null,
271
+ command: command
272
+ });
273
+
274
+ const createParagraphNear = () => ({ state, dispatch }) => {
275
+ return createParagraphNear$2(state, dispatch);
276
+ };
277
+
278
+ var createParagraphNear$1 = /*#__PURE__*/Object.freeze({
279
+ __proto__: null,
280
+ createParagraphNear: createParagraphNear
281
+ });
282
+
283
+ function getNodeType(nameOrType, schema) {
284
+ if (typeof nameOrType === 'string') {
285
+ if (!schema.nodes[nameOrType]) {
286
+ throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
287
+ }
288
+ return schema.nodes[nameOrType];
289
+ }
290
+ return nameOrType;
291
+ }
292
+
293
+ const deleteNode = typeOrName => ({ tr, state, dispatch }) => {
294
+ const type = getNodeType(typeOrName, state.schema);
295
+ const $pos = tr.selection.$anchor;
296
+ for (let depth = $pos.depth; depth > 0; depth -= 1) {
297
+ const node = $pos.node(depth);
298
+ if (node.type === type) {
299
+ if (dispatch) {
300
+ const from = $pos.before(depth);
301
+ const to = $pos.after(depth);
302
+ tr.delete(from, to).scrollIntoView();
303
+ }
304
+ return true;
305
+ }
306
+ }
307
+ return false;
308
+ };
309
+
310
+ var deleteNode$1 = /*#__PURE__*/Object.freeze({
311
+ __proto__: null,
312
+ deleteNode: deleteNode
313
+ });
314
+
315
+ const deleteRange = range => ({ tr, dispatch }) => {
316
+ const { from, to } = range;
317
+ if (dispatch) {
318
+ tr.delete(from, to);
319
+ }
320
+ return true;
321
+ };
322
+
323
+ var deleteRange$1 = /*#__PURE__*/Object.freeze({
324
+ __proto__: null,
325
+ deleteRange: deleteRange
326
+ });
327
+
328
+ const deleteSelection = () => ({ state, dispatch }) => {
329
+ return deleteSelection$2(state, dispatch);
330
+ };
331
+
332
+ var deleteSelection$1 = /*#__PURE__*/Object.freeze({
333
+ __proto__: null,
334
+ deleteSelection: deleteSelection
335
+ });
336
+
337
+ const enter = () => ({ commands }) => {
338
+ return commands.keyboardShortcut('Enter');
339
+ };
340
+
341
+ var enter$1 = /*#__PURE__*/Object.freeze({
342
+ __proto__: null,
343
+ enter: enter
344
+ });
345
+
346
+ const exitCode = () => ({ state, dispatch }) => {
347
+ return exitCode$2(state, dispatch);
348
+ };
349
+
350
+ var exitCode$1 = /*#__PURE__*/Object.freeze({
351
+ __proto__: null,
352
+ exitCode: exitCode
353
+ });
354
+
355
+ function getMarkType(nameOrType, schema) {
356
+ if (typeof nameOrType === 'string') {
357
+ if (!schema.marks[nameOrType]) {
358
+ throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
359
+ }
360
+ return schema.marks[nameOrType];
361
+ }
362
+ return nameOrType;
363
+ }
364
+
365
+ function isRegExp(value) {
366
+ return Object.prototype.toString.call(value) === '[object RegExp]';
367
+ }
368
+
369
+ /**
370
+ * Check if object1 includes object2
371
+ * @param object1 Object
372
+ * @param object2 Object
373
+ */
374
+ function objectIncludes(object1, object2, options = { strict: true }) {
375
+ const keys = Object.keys(object2);
376
+ if (!keys.length) {
377
+ return true;
378
+ }
379
+ return keys.every(key => {
380
+ if (options.strict) {
381
+ return object2[key] === object1[key];
382
+ }
383
+ if (isRegExp(object2[key])) {
384
+ return object2[key].test(object1[key]);
385
+ }
386
+ return object2[key] === object1[key];
387
+ });
388
+ }
389
+
390
+ function findMarkInSet(marks, type, attributes = {}) {
391
+ return marks.find(item => {
392
+ return item.type === type && objectIncludes(item.attrs, attributes);
393
+ });
394
+ }
395
+ function isMarkInSet(marks, type, attributes = {}) {
396
+ return !!findMarkInSet(marks, type, attributes);
397
+ }
398
+ function getMarkRange($pos, type, attributes = {}) {
399
+ if (!$pos || !type) {
400
+ return;
401
+ }
402
+ const start = $pos.parent.childAfter($pos.parentOffset);
403
+ if (!start.node) {
404
+ return;
405
+ }
406
+ const mark = findMarkInSet(start.node.marks, type, attributes);
407
+ if (!mark) {
408
+ return;
409
+ }
410
+ let startIndex = $pos.index();
411
+ let startPos = $pos.start() + start.offset;
412
+ let endIndex = startIndex + 1;
413
+ let endPos = startPos + start.node.nodeSize;
414
+ findMarkInSet(start.node.marks, type, attributes);
415
+ while (startIndex > 0 && mark.isInSet($pos.parent.child(startIndex - 1).marks)) {
416
+ startIndex -= 1;
417
+ startPos -= $pos.parent.child(startIndex).nodeSize;
418
+ }
419
+ while (endIndex < $pos.parent.childCount
420
+ && isMarkInSet($pos.parent.child(endIndex).marks, type, attributes)) {
421
+ endPos += $pos.parent.child(endIndex).nodeSize;
422
+ endIndex += 1;
423
+ }
424
+ return {
425
+ from: startPos,
426
+ to: endPos,
427
+ };
428
+ }
429
+
430
+ const extendMarkRange = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
431
+ const type = getMarkType(typeOrName, state.schema);
432
+ const { doc, selection } = tr;
433
+ const { $from, from, to } = selection;
434
+ if (dispatch) {
435
+ const range = getMarkRange($from, type, attributes);
436
+ if (range && range.from <= from && range.to >= to) {
437
+ const newSelection = TextSelection.create(doc, range.from, range.to);
438
+ tr.setSelection(newSelection);
439
+ }
440
+ }
441
+ return true;
442
+ };
443
+
444
+ var extendMarkRange$1 = /*#__PURE__*/Object.freeze({
445
+ __proto__: null,
446
+ extendMarkRange: extendMarkRange
447
+ });
448
+
449
+ const first = commands => props => {
450
+ const items = typeof commands === 'function'
451
+ ? commands(props)
452
+ : commands;
453
+ for (let i = 0; i < items.length; i += 1) {
454
+ if (items[i](props)) {
455
+ return true;
456
+ }
457
+ }
458
+ return false;
459
+ };
460
+
461
+ var first$1 = /*#__PURE__*/Object.freeze({
462
+ __proto__: null,
463
+ first: first
464
+ });
465
+
466
+ function minMax(value = 0, min = 0, max = 0) {
467
+ return Math.min(Math.max(value, min), max);
468
+ }
469
+
470
+ function isClass(value) {
471
+ var _a;
472
+ if (((_a = value.constructor) === null || _a === void 0 ? void 0 : _a.toString().substring(0, 5)) !== 'class') {
473
+ return false;
474
+ }
475
+ return true;
476
+ }
477
+
478
+ function isObject(value) {
479
+ return (value
480
+ && typeof value === 'object'
481
+ && !Array.isArray(value)
482
+ && !isClass(value));
483
+ }
484
+
485
+ function isTextSelection(value) {
486
+ return isObject(value) && value instanceof TextSelection;
487
+ }
488
+
489
+ function isiOS() {
490
+ return [
491
+ 'iPad Simulator',
492
+ 'iPhone Simulator',
493
+ 'iPod Simulator',
494
+ 'iPad',
495
+ 'iPhone',
496
+ 'iPod',
497
+ ].includes(navigator.platform)
498
+ // iPad on iOS 13 detection
499
+ || (navigator.userAgent.includes('Mac') && 'ontouchend' in document);
500
+ }
501
+
502
+ function resolveSelection(state, position = null) {
503
+ if (!position) {
504
+ return null;
505
+ }
506
+ if (position === 'start' || position === true) {
507
+ return {
508
+ from: 0,
509
+ to: 0,
510
+ };
511
+ }
512
+ if (position === 'end') {
513
+ const { size } = state.doc.content;
514
+ return {
515
+ from: size,
516
+ to: size,
517
+ };
518
+ }
519
+ return {
520
+ from: position,
521
+ to: position,
522
+ };
523
+ }
524
+ const focus = (position = null) => ({ editor, view, tr, dispatch, }) => {
525
+ const delayedFocus = () => {
526
+ // focus within `requestAnimationFrame` breaks focus on iOS
527
+ // so we have to call this
528
+ if (isiOS()) {
529
+ view.dom.focus();
530
+ }
531
+ // For React we have to focus asynchronously. Otherwise wild things happen.
532
+ // see: https://github.com/ueberdosis/tiptap/issues/1520
533
+ requestAnimationFrame(() => {
534
+ if (!editor.isDestroyed) {
535
+ view.focus();
536
+ editor.commands.scrollIntoView();
537
+ }
538
+ });
539
+ };
540
+ if ((view.hasFocus() && position === null) || position === false) {
541
+ return true;
542
+ }
543
+ // we don’t try to resolve a NodeSelection or CellSelection
544
+ if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
545
+ delayedFocus();
546
+ return true;
547
+ }
548
+ const { from, to } = resolveSelection(editor.state, position) || editor.state.selection;
549
+ const { doc, storedMarks } = tr;
550
+ const minPos = Selection.atStart(doc).from;
551
+ const maxPos = Selection.atEnd(doc).to;
552
+ const resolvedFrom = minMax(from, minPos, maxPos);
553
+ const resolvedEnd = minMax(to, minPos, maxPos);
554
+ const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd);
555
+ const isSameSelection = editor.state.selection.eq(selection);
556
+ if (dispatch) {
557
+ if (!isSameSelection) {
558
+ tr.setSelection(selection);
559
+ }
560
+ // `tr.setSelection` resets the stored marks
561
+ // so we’ll restore them if the selection is the same as before
562
+ if (isSameSelection && storedMarks) {
563
+ tr.setStoredMarks(storedMarks);
564
+ }
565
+ delayedFocus();
566
+ }
567
+ return true;
568
+ };
569
+
570
+ var focus$1 = /*#__PURE__*/Object.freeze({
571
+ __proto__: null,
572
+ focus: focus
573
+ });
574
+
575
+ const forEach = (items, fn) => props => {
576
+ return items.every((item, index) => fn(item, { ...props, index }));
577
+ };
578
+
579
+ var forEach$1 = /*#__PURE__*/Object.freeze({
580
+ __proto__: null,
581
+ forEach: forEach
582
+ });
583
+
584
+ const insertContent = (value, options) => ({ tr, commands }) => {
585
+ return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options);
586
+ };
587
+
588
+ var insertContent$1 = /*#__PURE__*/Object.freeze({
589
+ __proto__: null,
590
+ insertContent: insertContent
591
+ });
592
+
593
+ function elementFromString(value) {
594
+ // add a wrapper to preserve leading and trailing whitespace
595
+ const wrappedValue = `<body>${value}</body>`;
596
+ return new window.DOMParser().parseFromString(wrappedValue, 'text/html').body;
597
+ }
598
+
599
+ function createNodeFromContent(content, schema, options) {
600
+ options = {
601
+ slice: true,
602
+ parseOptions: {},
603
+ ...options,
604
+ };
605
+ if (typeof content === 'object' && content !== null) {
606
+ try {
607
+ if (Array.isArray(content)) {
608
+ return Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)));
609
+ }
610
+ return schema.nodeFromJSON(content);
611
+ }
612
+ catch (error) {
613
+ console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error);
614
+ return createNodeFromContent('', schema, options);
615
+ }
616
+ }
617
+ if (typeof content === 'string') {
618
+ const parser = DOMParser.fromSchema(schema);
619
+ return options.slice
620
+ ? parser.parseSlice(elementFromString(content), options.parseOptions).content
621
+ : parser.parse(elementFromString(content), options.parseOptions);
622
+ }
623
+ return createNodeFromContent('', schema, options);
624
+ }
625
+
626
+ // source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466
627
+ function selectionToInsertionEnd(tr, startLen, bias) {
628
+ const last = tr.steps.length - 1;
629
+ if (last < startLen) {
630
+ return;
631
+ }
632
+ const step = tr.steps[last];
633
+ if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
634
+ return;
635
+ }
636
+ const map = tr.mapping.maps[last];
637
+ let end = 0;
638
+ map.forEach((_from, _to, _newFrom, newTo) => {
639
+ if (end === 0) {
640
+ end = newTo;
641
+ }
642
+ });
643
+ tr.setSelection(Selection.near(tr.doc.resolve(end), bias));
644
+ }
645
+
646
+ const insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {
647
+ if (dispatch) {
648
+ options = {
649
+ parseOptions: {},
650
+ updateSelection: true,
651
+ ...options,
652
+ };
653
+ const content = createNodeFromContent(value, editor.schema, {
654
+ parseOptions: {
655
+ preserveWhitespace: 'full',
656
+ ...options.parseOptions,
657
+ },
658
+ });
659
+ // don’t dispatch an empty fragment because this can lead to strange errors
660
+ if (content.toString() === '<>') {
661
+ return true;
662
+ }
663
+ let { from, to } = typeof position === 'number'
664
+ ? { from: position, to: position }
665
+ : position;
666
+ let isOnlyBlockContent = true;
667
+ content.forEach(node => {
668
+ isOnlyBlockContent = isOnlyBlockContent
669
+ ? node.isBlock
670
+ : false;
671
+ });
672
+ // check if we can replace the wrapping node by
673
+ // the newly inserted content
674
+ // example:
675
+ // replace an empty paragraph by an inserted image
676
+ // instead of inserting the image below the paragraph
677
+ if (from === to && isOnlyBlockContent) {
678
+ const $from = tr.doc.resolve(from);
679
+ const isEmptyTextBlock = $from.parent.isTextblock
680
+ && !$from.parent.type.spec.code
681
+ && !$from.parent.textContent;
682
+ if (isEmptyTextBlock) {
683
+ from -= 1;
684
+ to += 1;
685
+ }
686
+ }
687
+ tr.replaceWith(from, to, content);
688
+ // set cursor at end of inserted content
689
+ if (options.updateSelection) {
690
+ selectionToInsertionEnd(tr, tr.steps.length - 1, -1);
691
+ }
692
+ }
693
+ return true;
694
+ };
695
+
696
+ var insertContentAt$1 = /*#__PURE__*/Object.freeze({
697
+ __proto__: null,
698
+ insertContentAt: insertContentAt
699
+ });
700
+
701
+ const joinBackward = () => ({ state, dispatch }) => {
702
+ return joinBackward$2(state, dispatch);
703
+ };
704
+
705
+ var joinBackward$1 = /*#__PURE__*/Object.freeze({
706
+ __proto__: null,
707
+ joinBackward: joinBackward
708
+ });
709
+
710
+ const joinForward = () => ({ state, dispatch }) => {
711
+ return joinForward$2(state, dispatch);
712
+ };
713
+
714
+ var joinForward$1 = /*#__PURE__*/Object.freeze({
715
+ __proto__: null,
716
+ joinForward: joinForward
717
+ });
718
+
719
+ const mac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false;
720
+ function normalizeKeyName(name) {
721
+ const parts = name.split(/-(?!$)/);
722
+ let result = parts[parts.length - 1];
723
+ if (result === 'Space') {
724
+ result = ' ';
725
+ }
726
+ let alt;
727
+ let ctrl;
728
+ let shift;
729
+ let meta;
730
+ for (let i = 0; i < parts.length - 1; i += 1) {
731
+ const mod = parts[i];
732
+ if (/^(cmd|meta|m)$/i.test(mod)) {
733
+ meta = true;
734
+ }
735
+ else if (/^a(lt)?$/i.test(mod)) {
736
+ alt = true;
737
+ }
738
+ else if (/^(c|ctrl|control)$/i.test(mod)) {
739
+ ctrl = true;
740
+ }
741
+ else if (/^s(hift)?$/i.test(mod)) {
742
+ shift = true;
743
+ }
744
+ else if (/^mod$/i.test(mod)) {
745
+ if (mac) {
746
+ meta = true;
747
+ }
748
+ else {
749
+ ctrl = true;
750
+ }
751
+ }
752
+ else {
753
+ throw new Error(`Unrecognized modifier name: ${mod}`);
754
+ }
755
+ }
756
+ if (alt) {
757
+ result = `Alt-${result}`;
758
+ }
759
+ if (ctrl) {
760
+ result = `Ctrl-${result}`;
761
+ }
762
+ if (meta) {
763
+ result = `Meta-${result}`;
764
+ }
765
+ if (shift) {
766
+ result = `Shift-${result}`;
767
+ }
768
+ return result;
769
+ }
770
+ const keyboardShortcut = name => ({ editor, view, tr, dispatch, }) => {
771
+ const keys = normalizeKeyName(name).split(/-(?!$)/);
772
+ const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item));
773
+ const event = new KeyboardEvent('keydown', {
774
+ key: key === 'Space'
775
+ ? ' '
776
+ : key,
777
+ altKey: keys.includes('Alt'),
778
+ ctrlKey: keys.includes('Ctrl'),
779
+ metaKey: keys.includes('Meta'),
780
+ shiftKey: keys.includes('Shift'),
781
+ bubbles: true,
782
+ cancelable: true,
783
+ });
784
+ const capturedTransaction = editor.captureTransaction(() => {
785
+ view.someProp('handleKeyDown', f => f(view, event));
786
+ });
787
+ capturedTransaction === null || capturedTransaction === void 0 ? void 0 : capturedTransaction.steps.forEach(step => {
788
+ const newStep = step.map(tr.mapping);
789
+ if (newStep && dispatch) {
790
+ tr.maybeStep(newStep);
791
+ }
792
+ });
793
+ return true;
794
+ };
795
+
796
+ var keyboardShortcut$1 = /*#__PURE__*/Object.freeze({
797
+ __proto__: null,
798
+ keyboardShortcut: keyboardShortcut
799
+ });
800
+
801
+ function isNodeActive(state, typeOrName, attributes = {}) {
802
+ const { from, to, empty } = state.selection;
803
+ const type = typeOrName
804
+ ? getNodeType(typeOrName, state.schema)
805
+ : null;
806
+ const nodeRanges = [];
807
+ state.doc.nodesBetween(from, to, (node, pos) => {
808
+ if (node.isText) {
809
+ return;
810
+ }
811
+ const relativeFrom = Math.max(from, pos);
812
+ const relativeTo = Math.min(to, pos + node.nodeSize);
813
+ nodeRanges.push({
814
+ node,
815
+ from: relativeFrom,
816
+ to: relativeTo,
817
+ });
818
+ });
819
+ const selectionRange = to - from;
820
+ const matchedNodeRanges = nodeRanges
821
+ .filter(nodeRange => {
822
+ if (!type) {
823
+ return true;
824
+ }
825
+ return type.name === nodeRange.node.type.name;
826
+ })
827
+ .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
828
+ if (empty) {
829
+ return !!matchedNodeRanges.length;
830
+ }
831
+ const range = matchedNodeRanges
832
+ .reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
833
+ return range >= selectionRange;
834
+ }
835
+
836
+ const lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
837
+ const type = getNodeType(typeOrName, state.schema);
838
+ const isActive = isNodeActive(state, type, attributes);
839
+ if (!isActive) {
840
+ return false;
841
+ }
842
+ return lift$2(state, dispatch);
843
+ };
844
+
845
+ var lift$1 = /*#__PURE__*/Object.freeze({
846
+ __proto__: null,
847
+ lift: lift
848
+ });
849
+
850
+ const liftEmptyBlock = () => ({ state, dispatch }) => {
851
+ return liftEmptyBlock$2(state, dispatch);
852
+ };
853
+
854
+ var liftEmptyBlock$1 = /*#__PURE__*/Object.freeze({
855
+ __proto__: null,
856
+ liftEmptyBlock: liftEmptyBlock
857
+ });
858
+
859
+ const liftListItem = typeOrName => ({ state, dispatch }) => {
860
+ const type = getNodeType(typeOrName, state.schema);
861
+ return liftListItem$2(type)(state, dispatch);
862
+ };
863
+
864
+ var liftListItem$1 = /*#__PURE__*/Object.freeze({
865
+ __proto__: null,
866
+ liftListItem: liftListItem
867
+ });
868
+
869
+ const newlineInCode = () => ({ state, dispatch }) => {
870
+ return newlineInCode$2(state, dispatch);
871
+ };
872
+
873
+ var newlineInCode$1 = /*#__PURE__*/Object.freeze({
874
+ __proto__: null,
875
+ newlineInCode: newlineInCode
876
+ });
877
+
878
+ function getSchemaTypeNameByName(name, schema) {
879
+ if (schema.nodes[name]) {
880
+ return 'node';
881
+ }
882
+ if (schema.marks[name]) {
883
+ return 'mark';
884
+ }
885
+ return null;
886
+ }
887
+
888
+ /**
889
+ * Remove a property or an array of properties from an object
890
+ * @param obj Object
891
+ * @param key Key to remove
892
+ */
893
+ function deleteProps(obj, propOrProps) {
894
+ const props = typeof propOrProps === 'string'
895
+ ? [propOrProps]
896
+ : propOrProps;
897
+ return Object
898
+ .keys(obj)
899
+ .reduce((newObj, prop) => {
900
+ if (!props.includes(prop)) {
901
+ newObj[prop] = obj[prop];
902
+ }
903
+ return newObj;
904
+ }, {});
905
+ }
906
+
907
+ const resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
908
+ let nodeType = null;
909
+ let markType = null;
910
+ const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string'
911
+ ? typeOrName
912
+ : typeOrName.name, state.schema);
913
+ if (!schemaType) {
914
+ return false;
915
+ }
916
+ if (schemaType === 'node') {
917
+ nodeType = getNodeType(typeOrName, state.schema);
918
+ }
919
+ if (schemaType === 'mark') {
920
+ markType = getMarkType(typeOrName, state.schema);
921
+ }
922
+ if (dispatch) {
923
+ tr.selection.ranges.forEach(range => {
924
+ state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
925
+ if (nodeType && nodeType === node.type) {
926
+ tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes));
927
+ }
928
+ if (markType && node.marks.length) {
929
+ node.marks.forEach(mark => {
930
+ if (markType === mark.type) {
931
+ tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));
932
+ }
933
+ });
934
+ }
935
+ });
936
+ });
937
+ }
938
+ return true;
939
+ };
940
+
941
+ var resetAttributes$1 = /*#__PURE__*/Object.freeze({
942
+ __proto__: null,
943
+ resetAttributes: resetAttributes
944
+ });
945
+
946
+ const scrollIntoView = () => ({ tr, dispatch }) => {
947
+ if (dispatch) {
948
+ tr.scrollIntoView();
949
+ }
950
+ return true;
951
+ };
952
+
953
+ var scrollIntoView$1 = /*#__PURE__*/Object.freeze({
954
+ __proto__: null,
955
+ scrollIntoView: scrollIntoView
956
+ });
957
+
958
+ const selectAll = () => ({ tr, commands }) => {
959
+ return commands.setTextSelection({
960
+ from: 0,
961
+ to: tr.doc.content.size,
962
+ });
963
+ };
964
+
965
+ var selectAll$1 = /*#__PURE__*/Object.freeze({
966
+ __proto__: null,
967
+ selectAll: selectAll
968
+ });
969
+
970
+ const selectNodeBackward = () => ({ state, dispatch }) => {
971
+ return selectNodeBackward$2(state, dispatch);
972
+ };
973
+
974
+ var selectNodeBackward$1 = /*#__PURE__*/Object.freeze({
975
+ __proto__: null,
976
+ selectNodeBackward: selectNodeBackward
977
+ });
978
+
979
+ const selectNodeForward = () => ({ state, dispatch }) => {
980
+ return selectNodeForward$2(state, dispatch);
981
+ };
982
+
983
+ var selectNodeForward$1 = /*#__PURE__*/Object.freeze({
984
+ __proto__: null,
985
+ selectNodeForward: selectNodeForward
986
+ });
987
+
988
+ const selectParentNode = () => ({ state, dispatch }) => {
989
+ return selectParentNode$2(state, dispatch);
990
+ };
991
+
992
+ var selectParentNode$1 = /*#__PURE__*/Object.freeze({
993
+ __proto__: null,
994
+ selectParentNode: selectParentNode
995
+ });
996
+
997
+ function createDocument(content, schema, parseOptions = {}) {
998
+ return createNodeFromContent(content, schema, { slice: false, parseOptions });
999
+ }
1000
+
1001
+ const setContent = (content, emitUpdate = false, parseOptions = {}) => ({ tr, editor, dispatch }) => {
1002
+ const { doc } = tr;
1003
+ const document = createDocument(content, editor.schema, parseOptions);
1004
+ const selection = TextSelection.create(doc, 0, doc.content.size);
1005
+ if (dispatch) {
1006
+ tr.setSelection(selection)
1007
+ .replaceSelectionWith(document, false)
1008
+ .setMeta('preventUpdate', !emitUpdate);
1009
+ }
1010
+ return true;
1011
+ };
1012
+
1013
+ var setContent$1 = /*#__PURE__*/Object.freeze({
1014
+ __proto__: null,
1015
+ setContent: setContent
1016
+ });
1017
+
1018
+ function getMarkAttributes(state, typeOrName) {
1019
+ const type = getMarkType(typeOrName, state.schema);
1020
+ const { from, to, empty } = state.selection;
1021
+ const marks = [];
1022
+ if (empty) {
1023
+ if (state.storedMarks) {
1024
+ marks.push(...state.storedMarks);
1025
+ }
1026
+ marks.push(...state.selection.$head.marks());
1027
+ }
1028
+ else {
1029
+ state.doc.nodesBetween(from, to, node => {
1030
+ marks.push(...node.marks);
1031
+ });
1032
+ }
1033
+ const mark = marks.find(markItem => markItem.type.name === type.name);
1034
+ if (!mark) {
1035
+ return {};
1036
+ }
1037
+ return { ...mark.attrs };
1038
+ }
1039
+
1040
+ const setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1041
+ const { selection } = tr;
1042
+ const { empty, ranges } = selection;
1043
+ const type = getMarkType(typeOrName, state.schema);
1044
+ if (dispatch) {
1045
+ if (empty) {
1046
+ const oldAttributes = getMarkAttributes(state, type);
1047
+ tr.addStoredMark(type.create({
1048
+ ...oldAttributes,
1049
+ ...attributes,
1050
+ }));
1051
+ }
1052
+ else {
1053
+ ranges.forEach(range => {
1054
+ const from = range.$from.pos;
1055
+ const to = range.$to.pos;
1056
+ state.doc.nodesBetween(from, to, (node, pos) => {
1057
+ const trimmedFrom = Math.max(pos, from);
1058
+ const trimmedTo = Math.min(pos + node.nodeSize, to);
1059
+ const someHasMark = node.marks.find(mark => mark.type === type);
1060
+ // if there is already a mark of this type
1061
+ // we know that we have to merge its attributes
1062
+ // otherwise we add a fresh new mark
1063
+ if (someHasMark) {
1064
+ node.marks.forEach(mark => {
1065
+ if (type === mark.type) {
1066
+ tr.addMark(trimmedFrom, trimmedTo, type.create({
1067
+ ...mark.attrs,
1068
+ ...attributes,
1069
+ }));
1070
+ }
1071
+ });
1072
+ }
1073
+ else {
1074
+ tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));
1075
+ }
1076
+ });
1077
+ });
1078
+ }
1079
+ }
1080
+ return true;
1081
+ };
1082
+
1083
+ var setMark$1 = /*#__PURE__*/Object.freeze({
1084
+ __proto__: null,
1085
+ setMark: setMark
1086
+ });
1087
+
1088
+ const setMeta = (key, value) => ({ tr }) => {
1089
+ tr.setMeta(key, value);
1090
+ return true;
1091
+ };
1092
+
1093
+ var setMeta$1 = /*#__PURE__*/Object.freeze({
1094
+ __proto__: null,
1095
+ setMeta: setMeta
1096
+ });
1097
+
1098
+ const setNode = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1099
+ const type = getNodeType(typeOrName, state.schema);
1100
+ return setBlockType(type, attributes)(state, dispatch);
1101
+ };
1102
+
1103
+ var setNode$1 = /*#__PURE__*/Object.freeze({
1104
+ __proto__: null,
1105
+ setNode: setNode
1106
+ });
1107
+
1108
+ const setNodeSelection = position => ({ tr, dispatch }) => {
1109
+ if (dispatch) {
1110
+ const { doc } = tr;
1111
+ const minPos = Selection.atStart(doc).from;
1112
+ const maxPos = Selection.atEnd(doc).to;
1113
+ const resolvedPos = minMax(position, minPos, maxPos);
1114
+ const selection = NodeSelection.create(doc, resolvedPos);
1115
+ tr.setSelection(selection);
1116
+ }
1117
+ return true;
1118
+ };
1119
+
1120
+ var setNodeSelection$1 = /*#__PURE__*/Object.freeze({
1121
+ __proto__: null,
1122
+ setNodeSelection: setNodeSelection
1123
+ });
1124
+
1125
+ const setTextSelection = position => ({ tr, dispatch }) => {
1126
+ if (dispatch) {
1127
+ const { doc } = tr;
1128
+ const { from, to } = typeof position === 'number'
1129
+ ? { from: position, to: position }
1130
+ : position;
1131
+ const minPos = Selection.atStart(doc).from;
1132
+ const maxPos = Selection.atEnd(doc).to;
1133
+ const resolvedFrom = minMax(from, minPos, maxPos);
1134
+ const resolvedEnd = minMax(to, minPos, maxPos);
1135
+ const selection = TextSelection.create(doc, resolvedFrom, resolvedEnd);
1136
+ tr.setSelection(selection);
1137
+ }
1138
+ return true;
1139
+ };
1140
+
1141
+ var setTextSelection$1 = /*#__PURE__*/Object.freeze({
1142
+ __proto__: null,
1143
+ setTextSelection: setTextSelection
1144
+ });
1145
+
1146
+ const sinkListItem = typeOrName => ({ state, dispatch }) => {
1147
+ const type = getNodeType(typeOrName, state.schema);
1148
+ return sinkListItem$2(type)(state, dispatch);
1149
+ };
1150
+
1151
+ var sinkListItem$1 = /*#__PURE__*/Object.freeze({
1152
+ __proto__: null,
1153
+ sinkListItem: sinkListItem
1154
+ });
1155
+
1156
+ function getSplittedAttributes(extensionAttributes, typeName, attributes) {
1157
+ return Object.fromEntries(Object
1158
+ .entries(attributes)
1159
+ .filter(([name]) => {
1160
+ const extensionAttribute = extensionAttributes.find(item => {
1161
+ return item.type === typeName && item.name === name;
1162
+ });
1163
+ if (!extensionAttribute) {
1164
+ return false;
1165
+ }
1166
+ return extensionAttribute.attribute.keepOnSplit;
1167
+ }));
1168
+ }
1169
+
1170
+ function defaultBlockAt(match) {
1171
+ for (let i = 0; i < match.edgeCount; i += 1) {
1172
+ const { type } = match.edge(i);
1173
+ if (type.isTextblock && !type.hasRequiredAttrs()) {
1174
+ return type;
1175
+ }
1176
+ }
1177
+ return null;
1178
+ }
1179
+ function ensureMarks(state, splittableMarks) {
1180
+ const marks = state.storedMarks
1181
+ || (state.selection.$to.parentOffset && state.selection.$from.marks());
1182
+ if (marks) {
1183
+ const filteredMarks = marks.filter(mark => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name));
1184
+ state.tr.ensureMarks(filteredMarks);
1185
+ }
1186
+ }
1187
+ const splitBlock = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor, }) => {
1188
+ const { selection, doc } = tr;
1189
+ const { $from, $to } = selection;
1190
+ const extensionAttributes = editor.extensionManager.attributes;
1191
+ const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
1192
+ if (selection instanceof NodeSelection && selection.node.isBlock) {
1193
+ if (!$from.parentOffset || !canSplit(doc, $from.pos)) {
1194
+ return false;
1195
+ }
1196
+ if (dispatch) {
1197
+ if (keepMarks) {
1198
+ ensureMarks(state, editor.extensionManager.splittableMarks);
1199
+ }
1200
+ tr.split($from.pos).scrollIntoView();
1201
+ }
1202
+ return true;
1203
+ }
1204
+ if (!$from.parent.isBlock) {
1205
+ return false;
1206
+ }
1207
+ if (dispatch) {
1208
+ const atEnd = $to.parentOffset === $to.parent.content.size;
1209
+ if (selection instanceof TextSelection) {
1210
+ tr.deleteSelection();
1211
+ }
1212
+ const deflt = $from.depth === 0
1213
+ ? undefined
1214
+ : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
1215
+ let types = atEnd && deflt
1216
+ ? [{
1217
+ type: deflt,
1218
+ attrs: newAttributes,
1219
+ }]
1220
+ : undefined;
1221
+ let can = canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
1222
+ if (!types
1223
+ && !can
1224
+ && canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {
1225
+ can = true;
1226
+ types = deflt
1227
+ ? [{
1228
+ type: deflt,
1229
+ attrs: newAttributes,
1230
+ }]
1231
+ : undefined;
1232
+ }
1233
+ if (can) {
1234
+ tr.split(tr.mapping.map($from.pos), 1, types);
1235
+ if (deflt
1236
+ && !atEnd
1237
+ && !$from.parentOffset
1238
+ && $from.parent.type !== deflt) {
1239
+ const first = tr.mapping.map($from.before());
1240
+ const $first = tr.doc.resolve(first);
1241
+ if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
1242
+ tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
1243
+ }
1244
+ }
1245
+ }
1246
+ if (keepMarks) {
1247
+ ensureMarks(state, editor.extensionManager.splittableMarks);
1248
+ }
1249
+ tr.scrollIntoView();
1250
+ }
1251
+ return true;
1252
+ };
1253
+
1254
+ var splitBlock$1 = /*#__PURE__*/Object.freeze({
1255
+ __proto__: null,
1256
+ splitBlock: splitBlock
1257
+ });
1258
+
1259
+ const splitListItem = typeOrName => ({ tr, state, dispatch, editor, }) => {
1260
+ var _a;
1261
+ const type = getNodeType(typeOrName, state.schema);
1262
+ const { $from, $to } = state.selection;
1263
+ // @ts-ignore
1264
+ // eslint-disable-next-line
1265
+ const node = state.selection.node;
1266
+ if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {
1267
+ return false;
1268
+ }
1269
+ const grandParent = $from.node(-1);
1270
+ if (grandParent.type !== type) {
1271
+ return false;
1272
+ }
1273
+ const extensionAttributes = editor.extensionManager.attributes;
1274
+ if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
1275
+ // In an empty block. If this is a nested list, the wrapping
1276
+ // list item should be split. Otherwise, bail out and let next
1277
+ // command handle lifting.
1278
+ if ($from.depth === 2
1279
+ || $from.node(-3).type !== type
1280
+ || $from.index(-2) !== $from.node(-2).childCount - 1) {
1281
+ return false;
1282
+ }
1283
+ if (dispatch) {
1284
+ let wrap = Fragment.empty;
1285
+ // eslint-disable-next-line
1286
+ const depthBefore = $from.index(-1)
1287
+ ? 1
1288
+ : $from.index(-2)
1289
+ ? 2
1290
+ : 3;
1291
+ // Build a fragment containing empty versions of the structure
1292
+ // from the outer list item to the parent node of the cursor
1293
+ for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
1294
+ wrap = Fragment.from($from.node(d).copy(wrap));
1295
+ }
1296
+ // eslint-disable-next-line
1297
+ const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount
1298
+ ? 1
1299
+ : $from.indexAfter(-2) < $from.node(-3).childCount
1300
+ ? 2
1301
+ : 3;
1302
+ // Add a second list item with an empty default start node
1303
+ const newNextTypeAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
1304
+ const nextType = ((_a = type.contentMatch.defaultType) === null || _a === void 0 ? void 0 : _a.createAndFill(newNextTypeAttributes)) || undefined;
1305
+ wrap = wrap.append(Fragment.from(type.createAndFill(null, nextType) || undefined));
1306
+ const start = $from.before($from.depth - (depthBefore - 1));
1307
+ tr.replace(start, $from.after(-depthAfter), new Slice(wrap, 4 - depthBefore, 0));
1308
+ let sel = -1;
1309
+ tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {
1310
+ if (sel > -1) {
1311
+ return false;
1312
+ }
1313
+ if (n.isTextblock && n.content.size === 0) {
1314
+ sel = pos + 1;
1315
+ }
1316
+ });
1317
+ if (sel > -1) {
1318
+ tr.setSelection(TextSelection.near(tr.doc.resolve(sel)));
1319
+ }
1320
+ tr.scrollIntoView();
1321
+ }
1322
+ return true;
1323
+ }
1324
+ const nextType = $to.pos === $from.end()
1325
+ ? grandParent.contentMatchAt(0).defaultType
1326
+ : null;
1327
+ const newTypeAttributes = getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs);
1328
+ const newNextTypeAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
1329
+ tr.delete($from.pos, $to.pos);
1330
+ const types = nextType
1331
+ ? [{ type, attrs: newTypeAttributes }, { type: nextType, attrs: newNextTypeAttributes }]
1332
+ : [{ type, attrs: newTypeAttributes }];
1333
+ if (!canSplit(tr.doc, $from.pos, 2)) {
1334
+ return false;
1335
+ }
1336
+ if (dispatch) {
1337
+ tr.split($from.pos, 2, types).scrollIntoView();
1338
+ }
1339
+ return true;
1340
+ };
1341
+
1342
+ var splitListItem$1 = /*#__PURE__*/Object.freeze({
1343
+ __proto__: null,
1344
+ splitListItem: splitListItem
1345
+ });
1346
+
1347
+ function findParentNodeClosestToPos($pos, predicate) {
1348
+ for (let i = $pos.depth; i > 0; i -= 1) {
1349
+ const node = $pos.node(i);
1350
+ if (predicate(node)) {
1351
+ return {
1352
+ pos: i > 0 ? $pos.before(i) : 0,
1353
+ start: $pos.start(i),
1354
+ depth: i,
1355
+ node,
1356
+ };
1357
+ }
1358
+ }
1359
+ }
1360
+
1361
+ function findParentNode(predicate) {
1362
+ return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
1363
+ }
1364
+
1365
+ function splitExtensions(extensions) {
1366
+ const baseExtensions = extensions.filter(extension => extension.type === 'extension');
1367
+ const nodeExtensions = extensions.filter(extension => extension.type === 'node');
1368
+ const markExtensions = extensions.filter(extension => extension.type === 'mark');
1369
+ return {
1370
+ baseExtensions,
1371
+ nodeExtensions,
1372
+ markExtensions,
1373
+ };
1374
+ }
1375
+
1376
+ function isList(name, extensions) {
1377
+ const { nodeExtensions } = splitExtensions(extensions);
1378
+ const extension = nodeExtensions.find(item => item.name === name);
1379
+ if (!extension) {
1380
+ return false;
1381
+ }
1382
+ const context = {
1383
+ name: extension.name,
1384
+ options: extension.options,
1385
+ storage: extension.storage,
1386
+ };
1387
+ const group = callOrReturn(getExtensionField(extension, 'group', context));
1388
+ if (typeof group !== 'string') {
1389
+ return false;
1390
+ }
1391
+ return group.split(' ').includes('list');
1392
+ }
1393
+
1394
+ const toggleList = (listTypeOrName, itemTypeOrName) => ({ editor, tr, state, dispatch, chain, commands, can, }) => {
1395
+ const { extensions } = editor.extensionManager;
1396
+ const listType = getNodeType(listTypeOrName, state.schema);
1397
+ const itemType = getNodeType(itemTypeOrName, state.schema);
1398
+ const { selection } = state;
1399
+ const { $from, $to } = selection;
1400
+ const range = $from.blockRange($to);
1401
+ if (!range) {
1402
+ return false;
1403
+ }
1404
+ const parentList = findParentNode(node => isList(node.type.name, extensions))(selection);
1405
+ if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
1406
+ // remove list
1407
+ if (parentList.node.type === listType) {
1408
+ return commands.liftListItem(itemType);
1409
+ }
1410
+ // change list type
1411
+ if (isList(parentList.node.type.name, extensions)
1412
+ && listType.validContent(parentList.node.content)
1413
+ && dispatch) {
1414
+ tr.setNodeMarkup(parentList.pos, listType);
1415
+ return true;
1416
+ }
1417
+ }
1418
+ const canWrapInList = can().wrapInList(listType);
1419
+ // try to convert node to paragraph if needed
1420
+ if (!canWrapInList) {
1421
+ return chain()
1422
+ .clearNodes()
1423
+ .wrapInList(listType)
1424
+ .run();
1425
+ }
1426
+ return commands.wrapInList(listType);
1427
+ };
1428
+
1429
+ var toggleList$1 = /*#__PURE__*/Object.freeze({
1430
+ __proto__: null,
1431
+ toggleList: toggleList
1432
+ });
1433
+
1434
+ function isMarkActive(state, typeOrName, attributes = {}) {
1435
+ const { empty, ranges } = state.selection;
1436
+ const type = typeOrName
1437
+ ? getMarkType(typeOrName, state.schema)
1438
+ : null;
1439
+ if (empty) {
1440
+ return !!(state.storedMarks || state.selection.$from.marks())
1441
+ .filter(mark => {
1442
+ if (!type) {
1443
+ return true;
1444
+ }
1445
+ return type.name === mark.type.name;
1446
+ })
1447
+ .find(mark => objectIncludes(mark.attrs, attributes, { strict: false }));
1448
+ }
1449
+ let selectionRange = 0;
1450
+ const markRanges = [];
1451
+ ranges.forEach(({ $from, $to }) => {
1452
+ const from = $from.pos;
1453
+ const to = $to.pos;
1454
+ state.doc.nodesBetween(from, to, (node, pos) => {
1455
+ if (!node.isText && !node.marks.length) {
1456
+ return;
1457
+ }
1458
+ const relativeFrom = Math.max(from, pos);
1459
+ const relativeTo = Math.min(to, pos + node.nodeSize);
1460
+ const range = relativeTo - relativeFrom;
1461
+ selectionRange += range;
1462
+ markRanges.push(...node.marks.map(mark => ({
1463
+ mark,
1464
+ from: relativeFrom,
1465
+ to: relativeTo,
1466
+ })));
1467
+ });
1468
+ });
1469
+ if (selectionRange === 0) {
1470
+ return false;
1471
+ }
1472
+ // calculate range of matched mark
1473
+ const matchedRange = markRanges
1474
+ .filter(markRange => {
1475
+ if (!type) {
1476
+ return true;
1477
+ }
1478
+ return type.name === markRange.mark.type.name;
1479
+ })
1480
+ .filter(markRange => objectIncludes(markRange.mark.attrs, attributes, { strict: false }))
1481
+ .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1482
+ // calculate range of marks that excludes the searched mark
1483
+ // for example `code` doesn’t allow any other marks
1484
+ const excludedRange = markRanges
1485
+ .filter(markRange => {
1486
+ if (!type) {
1487
+ return true;
1488
+ }
1489
+ return markRange.mark.type !== type
1490
+ && markRange.mark.type.excludes(type);
1491
+ })
1492
+ .reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
1493
+ // we only include the result of `excludedRange`
1494
+ // if there is a match at all
1495
+ const range = matchedRange > 0
1496
+ ? matchedRange + excludedRange
1497
+ : matchedRange;
1498
+ return range >= selectionRange;
1499
+ }
1500
+
1501
+ const toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {
1502
+ const { extendEmptyMarkRange = false } = options;
1503
+ const type = getMarkType(typeOrName, state.schema);
1504
+ const isActive = isMarkActive(state, type, attributes);
1505
+ if (isActive) {
1506
+ return commands.unsetMark(type, { extendEmptyMarkRange });
1507
+ }
1508
+ return commands.setMark(type, attributes);
1509
+ };
1510
+
1511
+ var toggleMark$1 = /*#__PURE__*/Object.freeze({
1512
+ __proto__: null,
1513
+ toggleMark: toggleMark
1514
+ });
1515
+
1516
+ const toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
1517
+ const type = getNodeType(typeOrName, state.schema);
1518
+ const toggleType = getNodeType(toggleTypeOrName, state.schema);
1519
+ const isActive = isNodeActive(state, type, attributes);
1520
+ if (isActive) {
1521
+ return commands.setNode(toggleType);
1522
+ }
1523
+ return commands.setNode(type, attributes);
1524
+ };
1525
+
1526
+ var toggleNode$1 = /*#__PURE__*/Object.freeze({
1527
+ __proto__: null,
1528
+ toggleNode: toggleNode
1529
+ });
1530
+
1531
+ const toggleWrap = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1532
+ const type = getNodeType(typeOrName, state.schema);
1533
+ const isActive = isNodeActive(state, type, attributes);
1534
+ if (isActive) {
1535
+ return lift$2(state, dispatch);
1536
+ }
1537
+ return wrapIn$2(type, attributes)(state, dispatch);
1538
+ };
1539
+
1540
+ var toggleWrap$1 = /*#__PURE__*/Object.freeze({
1541
+ __proto__: null,
1542
+ toggleWrap: toggleWrap
1543
+ });
1544
+
1545
+ const undoInputRule = () => ({ state, dispatch }) => {
1546
+ const plugins = state.plugins;
1547
+ for (let i = 0; i < plugins.length; i += 1) {
1548
+ const plugin = plugins[i];
1549
+ let undoable;
1550
+ // @ts-ignore
1551
+ // eslint-disable-next-line
1552
+ if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
1553
+ if (dispatch) {
1554
+ const tr = state.tr;
1555
+ const toUndo = undoable.transform;
1556
+ for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
1557
+ tr.step(toUndo.steps[j].invert(toUndo.docs[j]));
1558
+ }
1559
+ if (undoable.text) {
1560
+ const marks = tr.doc.resolve(undoable.from).marks();
1561
+ tr.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
1562
+ }
1563
+ else {
1564
+ tr.delete(undoable.from, undoable.to);
1565
+ }
1566
+ }
1567
+ return true;
1568
+ }
1569
+ }
1570
+ return false;
1571
+ };
1572
+
1573
+ var undoInputRule$1 = /*#__PURE__*/Object.freeze({
1574
+ __proto__: null,
1575
+ undoInputRule: undoInputRule
1576
+ });
1577
+
1578
+ const unsetAllMarks = () => ({ tr, state, dispatch }) => {
1579
+ const { selection } = tr;
1580
+ const { empty, ranges } = selection;
1581
+ if (empty) {
1582
+ return true;
1583
+ }
1584
+ if (dispatch) {
1585
+ Object
1586
+ .entries(state.schema.marks)
1587
+ .forEach(([, mark]) => {
1588
+ ranges.forEach(range => {
1589
+ tr.removeMark(range.$from.pos, range.$to.pos, mark);
1590
+ });
1591
+ });
1592
+ }
1593
+ return true;
1594
+ };
1595
+
1596
+ var unsetAllMarks$1 = /*#__PURE__*/Object.freeze({
1597
+ __proto__: null,
1598
+ unsetAllMarks: unsetAllMarks
1599
+ });
1600
+
1601
+ const unsetMark = (typeOrName, options = {}) => ({ tr, state, dispatch }) => {
1602
+ var _a;
1603
+ const { extendEmptyMarkRange = false } = options;
1604
+ const { selection } = tr;
1605
+ const type = getMarkType(typeOrName, state.schema);
1606
+ const { $from, empty, ranges } = selection;
1607
+ if (!dispatch) {
1608
+ return true;
1609
+ }
1610
+ if (empty && extendEmptyMarkRange) {
1611
+ let { from, to } = selection;
1612
+ const attrs = (_a = $from.marks().find(mark => mark.type === type)) === null || _a === void 0 ? void 0 : _a.attrs;
1613
+ const range = getMarkRange($from, type, attrs);
1614
+ if (range) {
1615
+ from = range.from;
1616
+ to = range.to;
1617
+ }
1618
+ tr.removeMark(from, to, type);
1619
+ }
1620
+ else {
1621
+ ranges.forEach(range => {
1622
+ tr.removeMark(range.$from.pos, range.$to.pos, type);
1623
+ });
1624
+ }
1625
+ tr.removeStoredMark(type);
1626
+ return true;
1627
+ };
1628
+
1629
+ var unsetMark$1 = /*#__PURE__*/Object.freeze({
1630
+ __proto__: null,
1631
+ unsetMark: unsetMark
1632
+ });
1633
+
1634
+ const updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1635
+ let nodeType = null;
1636
+ let markType = null;
1637
+ const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string'
1638
+ ? typeOrName
1639
+ : typeOrName.name, state.schema);
1640
+ if (!schemaType) {
1641
+ return false;
1642
+ }
1643
+ if (schemaType === 'node') {
1644
+ nodeType = getNodeType(typeOrName, state.schema);
1645
+ }
1646
+ if (schemaType === 'mark') {
1647
+ markType = getMarkType(typeOrName, state.schema);
1648
+ }
1649
+ if (dispatch) {
1650
+ tr.selection.ranges.forEach(range => {
1651
+ const from = range.$from.pos;
1652
+ const to = range.$to.pos;
1653
+ state.doc.nodesBetween(from, to, (node, pos) => {
1654
+ if (nodeType && nodeType === node.type) {
1655
+ tr.setNodeMarkup(pos, undefined, {
1656
+ ...node.attrs,
1657
+ ...attributes,
1658
+ });
1659
+ }
1660
+ if (markType && node.marks.length) {
1661
+ node.marks.forEach(mark => {
1662
+ if (markType === mark.type) {
1663
+ const trimmedFrom = Math.max(pos, from);
1664
+ const trimmedTo = Math.min(pos + node.nodeSize, to);
1665
+ tr.addMark(trimmedFrom, trimmedTo, markType.create({
1666
+ ...mark.attrs,
1667
+ ...attributes,
1668
+ }));
1669
+ }
1670
+ });
1671
+ }
1672
+ });
1673
+ });
1674
+ }
1675
+ return true;
1676
+ };
1677
+
1678
+ var updateAttributes$1 = /*#__PURE__*/Object.freeze({
1679
+ __proto__: null,
1680
+ updateAttributes: updateAttributes
1681
+ });
1682
+
1683
+ const wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1684
+ const type = getNodeType(typeOrName, state.schema);
1685
+ const isActive = isNodeActive(state, type, attributes);
1686
+ if (isActive) {
1687
+ return false;
1688
+ }
1689
+ return wrapIn$2(type, attributes)(state, dispatch);
1690
+ };
1691
+
1692
+ var wrapIn$1 = /*#__PURE__*/Object.freeze({
1693
+ __proto__: null,
1694
+ wrapIn: wrapIn
1695
+ });
1696
+
1697
+ const wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1698
+ const type = getNodeType(typeOrName, state.schema);
1699
+ return wrapInList$2(type, attributes)(state, dispatch);
1700
+ };
1701
+
1702
+ var wrapInList$1 = /*#__PURE__*/Object.freeze({
1703
+ __proto__: null,
1704
+ wrapInList: wrapInList
1705
+ });
1706
+
1707
+ const Commands = Extension.create({
1708
+ name: 'commands',
1709
+ addCommands() {
1710
+ return {
1711
+ ...blur$1,
1712
+ ...clearContent$1,
1713
+ ...clearNodes$1,
1714
+ ...command$1,
1715
+ ...createParagraphNear$1,
1716
+ ...deleteNode$1,
1717
+ ...deleteRange$1,
1718
+ ...deleteSelection$1,
1719
+ ...enter$1,
1720
+ ...exitCode$1,
1721
+ ...extendMarkRange$1,
1722
+ ...first$1,
1723
+ ...focus$1,
1724
+ ...forEach$1,
1725
+ ...insertContent$1,
1726
+ ...insertContentAt$1,
1727
+ ...joinBackward$1,
1728
+ ...joinForward$1,
1729
+ ...keyboardShortcut$1,
1730
+ ...lift$1,
1731
+ ...liftEmptyBlock$1,
1732
+ ...liftListItem$1,
1733
+ ...newlineInCode$1,
1734
+ ...resetAttributes$1,
1735
+ ...scrollIntoView$1,
1736
+ ...selectAll$1,
1737
+ ...selectNodeBackward$1,
1738
+ ...selectNodeForward$1,
1739
+ ...selectParentNode$1,
1740
+ ...setContent$1,
1741
+ ...setMark$1,
1742
+ ...setMeta$1,
1743
+ ...setNode$1,
1744
+ ...setNodeSelection$1,
1745
+ ...setTextSelection$1,
1746
+ ...sinkListItem$1,
1747
+ ...splitBlock$1,
1748
+ ...splitListItem$1,
1749
+ ...toggleList$1,
1750
+ ...toggleMark$1,
1751
+ ...toggleNode$1,
1752
+ ...toggleWrap$1,
1753
+ ...undoInputRule$1,
1754
+ ...unsetAllMarks$1,
1755
+ ...unsetMark$1,
1756
+ ...updateAttributes$1,
1757
+ ...wrapIn$1,
1758
+ ...wrapInList$1,
1759
+ };
1760
+ },
1761
+ });
1762
+
1763
+ const Editable = Extension.create({
1764
+ name: 'editable',
1765
+ addProseMirrorPlugins() {
1766
+ return [
1767
+ new Plugin({
1768
+ key: new PluginKey('editable'),
1769
+ props: {
1770
+ editable: () => this.editor.options.editable,
1771
+ },
1772
+ }),
1773
+ ];
1774
+ },
1775
+ });
1776
+
1777
+ const FocusEvents = Extension.create({
1778
+ name: 'focusEvents',
1779
+ addProseMirrorPlugins() {
1780
+ const { editor } = this;
1781
+ return [
1782
+ new Plugin({
1783
+ key: new PluginKey('focusEvents'),
1784
+ props: {
1785
+ handleDOMEvents: {
1786
+ focus: (view, event) => {
1787
+ editor.isFocused = true;
1788
+ const transaction = editor.state.tr
1789
+ .setMeta('focus', { event })
1790
+ .setMeta('addToHistory', false);
1791
+ view.dispatch(transaction);
1792
+ return false;
1793
+ },
1794
+ blur: (view, event) => {
1795
+ editor.isFocused = false;
1796
+ const transaction = editor.state.tr
1797
+ .setMeta('blur', { event })
1798
+ .setMeta('addToHistory', false);
1799
+ view.dispatch(transaction);
1800
+ return false;
1801
+ },
1802
+ },
1803
+ },
1804
+ }),
1805
+ ];
1806
+ },
1807
+ });
1808
+
1809
+ const Keymap = Extension.create({
1810
+ name: 'keymap',
1811
+ addKeyboardShortcuts() {
1812
+ const handleBackspace = () => this.editor.commands.first(({ commands }) => [
1813
+ () => commands.undoInputRule(),
1814
+ () => commands.deleteSelection(),
1815
+ () => commands.joinBackward(),
1816
+ () => commands.selectNodeBackward(),
1817
+ ]);
1818
+ const handleDelete = () => this.editor.commands.first(({ commands }) => [
1819
+ () => commands.deleteSelection(),
1820
+ () => commands.joinForward(),
1821
+ () => commands.selectNodeForward(),
1822
+ ]);
1823
+ return {
1824
+ Enter: () => this.editor.commands.first(({ commands }) => [
1825
+ () => commands.newlineInCode(),
1826
+ () => commands.createParagraphNear(),
1827
+ () => commands.liftEmptyBlock(),
1828
+ () => commands.splitBlock(),
1829
+ ]),
1830
+ 'Mod-Enter': () => this.editor.commands.exitCode(),
1831
+ Backspace: handleBackspace,
1832
+ 'Mod-Backspace': handleBackspace,
1833
+ 'Shift-Backspace': handleBackspace,
1834
+ Delete: handleDelete,
1835
+ 'Mod-Delete': handleDelete,
1836
+ 'Mod-a': () => this.editor.commands.selectAll(),
1837
+ };
1838
+ },
1839
+ });
1840
+
1841
+ const Tabindex = Extension.create({
1842
+ name: 'tabindex',
1843
+ addProseMirrorPlugins() {
1844
+ return [
1845
+ new Plugin({
1846
+ key: new PluginKey('tabindex'),
1847
+ props: {
1848
+ attributes: {
1849
+ tabindex: '0',
1850
+ },
1851
+ },
1852
+ }),
1853
+ ];
1854
+ },
1855
+ });
1856
+
1857
+ var extensions = /*#__PURE__*/Object.freeze({
1858
+ __proto__: null,
1859
+ ClipboardTextSerializer: ClipboardTextSerializer,
1860
+ Commands: Commands,
1861
+ Editable: Editable,
1862
+ FocusEvents: FocusEvents,
1863
+ Keymap: Keymap,
1864
+ Tabindex: Tabindex
1865
+ });
1866
+
1867
+ function getNodeAttributes(state, typeOrName) {
1868
+ const type = getNodeType(typeOrName, state.schema);
1869
+ const { from, to } = state.selection;
1870
+ const nodes = [];
1871
+ state.doc.nodesBetween(from, to, node => {
1872
+ nodes.push(node);
1873
+ });
1874
+ const node = nodes
1875
+ .reverse()
1876
+ .find(nodeItem => nodeItem.type.name === type.name);
1877
+ if (!node) {
1878
+ return {};
1879
+ }
1880
+ return { ...node.attrs };
1881
+ }
1882
+
1883
+ function getAttributes(state, typeOrName) {
1884
+ const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string'
1885
+ ? typeOrName
1886
+ : typeOrName.name, state.schema);
1887
+ if (schemaType === 'node') {
1888
+ return getNodeAttributes(state, typeOrName);
1889
+ }
1890
+ if (schemaType === 'mark') {
1891
+ return getMarkAttributes(state, typeOrName);
1892
+ }
1893
+ return {};
1894
+ }
1895
+
1896
+ function isActive(state, name, attributes = {}) {
1897
+ if (!name) {
1898
+ return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes);
1899
+ }
1900
+ const schemaType = getSchemaTypeNameByName(name, state.schema);
1901
+ if (schemaType === 'node') {
1902
+ return isNodeActive(state, name, attributes);
1903
+ }
1904
+ if (schemaType === 'mark') {
1905
+ return isMarkActive(state, name, attributes);
1906
+ }
1907
+ return false;
1908
+ }
1909
+
1910
+ function removeElement(element) {
1911
+ if (element === null || element === void 0 ? void 0 : element.parentNode) {
1912
+ element.parentNode.removeChild(element);
1913
+ }
1914
+ }
1915
+
1916
+ function getHTMLFromFragment(fragment, schema) {
1917
+ const documentFragment = DOMSerializer
1918
+ .fromSchema(schema)
1919
+ .serializeFragment(fragment);
1920
+ const temporaryDocument = document.implementation.createHTMLDocument();
1921
+ const container = temporaryDocument.createElement('div');
1922
+ container.appendChild(documentFragment);
1923
+ return container.innerHTML;
1924
+ }
1925
+
1926
+ function getText(node, options) {
1927
+ const range = {
1928
+ from: 0,
1929
+ to: node.content.size,
1930
+ };
1931
+ return getTextBetween(node, range, options);
1932
+ }
1933
+
1934
+ function isNodeEmpty(node) {
1935
+ var _a;
1936
+ const defaultContent = (_a = node.type.createAndFill()) === null || _a === void 0 ? void 0 : _a.toJSON();
1937
+ const content = node.toJSON();
1938
+ return JSON.stringify(defaultContent) === JSON.stringify(content);
1939
+ }
1940
+
1941
+ function createStyleTag(style) {
1942
+ const tipTapStyleTag = document.querySelector('style[data-tiptap-style]');
1943
+ if (tipTapStyleTag !== null) {
1944
+ return tipTapStyleTag;
1945
+ }
1946
+ const styleNode = document.createElement('style');
1947
+ styleNode.setAttribute('data-tiptap-style', '');
1948
+ styleNode.innerHTML = style;
1949
+ document.getElementsByTagName('head')[0].appendChild(styleNode);
1950
+ return styleNode;
1951
+ }
1952
+
1953
+ function createChainableState(config) {
1954
+ const { state, transaction } = config;
1955
+ let { selection } = transaction;
1956
+ let { doc } = transaction;
1957
+ let { storedMarks } = transaction;
1958
+ return {
1959
+ ...state,
1960
+ schema: state.schema,
1961
+ plugins: state.plugins,
1962
+ apply: state.apply.bind(state),
1963
+ applyTransaction: state.applyTransaction.bind(state),
1964
+ reconfigure: state.reconfigure.bind(state),
1965
+ toJSON: state.toJSON.bind(state),
1966
+ get storedMarks() {
1967
+ return storedMarks;
1968
+ },
1969
+ get selection() {
1970
+ return selection;
1971
+ },
1972
+ get doc() {
1973
+ return doc;
1974
+ },
1975
+ get tr() {
1976
+ selection = transaction.selection;
1977
+ doc = transaction.doc;
1978
+ storedMarks = transaction.storedMarks;
1979
+ return transaction;
1980
+ },
1981
+ };
1982
+ }
1983
+
1984
+ class CommandManager {
1985
+ constructor(props) {
1986
+ this.editor = props.editor;
1987
+ this.rawCommands = this.editor.extensionManager.commands;
1988
+ this.customState = props.state;
1989
+ }
1990
+ get hasCustomState() {
1991
+ return !!this.customState;
1992
+ }
1993
+ get state() {
1994
+ return this.customState || this.editor.state;
1995
+ }
1996
+ get commands() {
1997
+ const { rawCommands, editor, state } = this;
1998
+ const { view } = editor;
1999
+ const { tr } = state;
2000
+ const props = this.buildProps(tr);
2001
+ return Object.fromEntries(Object
2002
+ .entries(rawCommands)
2003
+ .map(([name, command]) => {
2004
+ const method = (...args) => {
2005
+ const callback = command(...args)(props);
2006
+ if (!tr.getMeta('preventDispatch') && !this.hasCustomState) {
2007
+ view.dispatch(tr);
2008
+ }
2009
+ return callback;
2010
+ };
2011
+ return [name, method];
2012
+ }));
2013
+ }
2014
+ get chain() {
2015
+ return () => this.createChain();
2016
+ }
2017
+ get can() {
2018
+ return () => this.createCan();
2019
+ }
2020
+ createChain(startTr, shouldDispatch = true) {
2021
+ const { rawCommands, editor, state } = this;
2022
+ const { view } = editor;
2023
+ const callbacks = [];
2024
+ const hasStartTransaction = !!startTr;
2025
+ const tr = startTr || state.tr;
2026
+ const run = () => {
2027
+ if (!hasStartTransaction
2028
+ && shouldDispatch
2029
+ && !tr.getMeta('preventDispatch')
2030
+ && !this.hasCustomState) {
2031
+ view.dispatch(tr);
2032
+ }
2033
+ return callbacks.every(callback => callback === true);
2034
+ };
2035
+ const chain = {
2036
+ ...Object.fromEntries(Object.entries(rawCommands).map(([name, command]) => {
2037
+ const chainedCommand = (...args) => {
2038
+ const props = this.buildProps(tr, shouldDispatch);
2039
+ const callback = command(...args)(props);
2040
+ callbacks.push(callback);
2041
+ return chain;
2042
+ };
2043
+ return [name, chainedCommand];
2044
+ })),
2045
+ run,
2046
+ };
2047
+ return chain;
2048
+ }
2049
+ createCan(startTr) {
2050
+ const { rawCommands, state } = this;
2051
+ const dispatch = undefined;
2052
+ const tr = startTr || state.tr;
2053
+ const props = this.buildProps(tr, dispatch);
2054
+ const formattedCommands = Object.fromEntries(Object
2055
+ .entries(rawCommands)
2056
+ .map(([name, command]) => {
2057
+ return [name, (...args) => command(...args)({ ...props, dispatch })];
2058
+ }));
2059
+ return {
2060
+ ...formattedCommands,
2061
+ chain: () => this.createChain(tr, dispatch),
2062
+ };
2063
+ }
2064
+ buildProps(tr, shouldDispatch = true) {
2065
+ const { rawCommands, editor, state } = this;
2066
+ const { view } = editor;
2067
+ if (state.storedMarks) {
2068
+ tr.setStoredMarks(state.storedMarks);
2069
+ }
2070
+ const props = {
2071
+ tr,
2072
+ editor,
2073
+ view,
2074
+ state: createChainableState({
2075
+ state,
2076
+ transaction: tr,
2077
+ }),
2078
+ dispatch: shouldDispatch
2079
+ ? () => undefined
2080
+ : undefined,
2081
+ chain: () => this.createChain(tr),
2082
+ can: () => this.createCan(tr),
2083
+ get commands() {
2084
+ return Object.fromEntries(Object
2085
+ .entries(rawCommands)
2086
+ .map(([name, command]) => {
2087
+ return [name, (...args) => command(...args)(props)];
2088
+ }));
2089
+ },
2090
+ };
2091
+ return props;
2092
+ }
2093
+ }
2094
+
2095
+ class InputRule {
2096
+ constructor(config) {
2097
+ this.find = config.find;
2098
+ this.handler = config.handler;
2099
+ }
2100
+ }
2101
+ const inputRuleMatcherHandler = (text, find) => {
2102
+ if (isRegExp(find)) {
2103
+ return find.exec(text);
2104
+ }
2105
+ const inputRuleMatch = find(text);
2106
+ if (!inputRuleMatch) {
2107
+ return null;
2108
+ }
2109
+ const result = [];
2110
+ result.push(inputRuleMatch.text);
2111
+ result.index = inputRuleMatch.index;
2112
+ result.input = text;
2113
+ result.data = inputRuleMatch.data;
2114
+ if (inputRuleMatch.replaceWith) {
2115
+ if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
2116
+ console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".');
2117
+ }
2118
+ result.push(inputRuleMatch.replaceWith);
2119
+ }
2120
+ return result;
2121
+ };
2122
+ function run$1(config) {
2123
+ var _a;
2124
+ const { editor, from, to, text, rules, plugin, } = config;
2125
+ const { view } = editor;
2126
+ if (view.composing) {
2127
+ return false;
2128
+ }
2129
+ const $from = view.state.doc.resolve(from);
2130
+ if (
2131
+ // check for code node
2132
+ $from.parent.type.spec.code
2133
+ // check for code mark
2134
+ || !!((_a = ($from.nodeBefore || $from.nodeAfter)) === null || _a === void 0 ? void 0 : _a.marks.find(mark => mark.type.spec.code))) {
2135
+ return false;
2136
+ }
2137
+ let matched = false;
2138
+ const maxMatch = 500;
2139
+ const textBefore = $from.parent.textBetween(Math.max(0, $from.parentOffset - maxMatch), $from.parentOffset, undefined, '\ufffc') + text;
2140
+ rules.forEach(rule => {
2141
+ if (matched) {
2142
+ return;
2143
+ }
2144
+ const match = inputRuleMatcherHandler(textBefore, rule.find);
2145
+ if (!match) {
2146
+ return;
2147
+ }
2148
+ const tr = view.state.tr;
2149
+ const state = createChainableState({
2150
+ state: view.state,
2151
+ transaction: tr,
2152
+ });
2153
+ const range = {
2154
+ from: from - (match[0].length - text.length),
2155
+ to,
2156
+ };
2157
+ const { commands, chain, can } = new CommandManager({
2158
+ editor,
2159
+ state,
2160
+ });
2161
+ rule.handler({
2162
+ state,
2163
+ range,
2164
+ match,
2165
+ commands,
2166
+ chain,
2167
+ can,
2168
+ });
2169
+ // stop if there are no changes
2170
+ if (!tr.steps.length) {
2171
+ return;
2172
+ }
2173
+ // store transform as meta data
2174
+ // so we can undo input rules within the `undoInputRules` command
2175
+ tr.setMeta(plugin, {
2176
+ transform: tr,
2177
+ from,
2178
+ to,
2179
+ text,
2180
+ });
2181
+ view.dispatch(tr);
2182
+ matched = true;
2183
+ });
2184
+ return matched;
2185
+ }
2186
+ /**
2187
+ * Create an input rules plugin. When enabled, it will cause text
2188
+ * input that matches any of the given rules to trigger the rule’s
2189
+ * action.
2190
+ */
2191
+ function inputRulesPlugin(props) {
2192
+ const { editor, rules } = props;
2193
+ const plugin = new Plugin({
2194
+ state: {
2195
+ init() {
2196
+ return null;
2197
+ },
2198
+ apply(tr, prev) {
2199
+ const stored = tr.getMeta(this);
2200
+ if (stored) {
2201
+ return stored;
2202
+ }
2203
+ return tr.selectionSet || tr.docChanged
2204
+ ? null
2205
+ : prev;
2206
+ },
2207
+ },
2208
+ props: {
2209
+ handleTextInput(view, from, to, text) {
2210
+ return run$1({
2211
+ editor,
2212
+ from,
2213
+ to,
2214
+ text,
2215
+ rules,
2216
+ plugin,
2217
+ });
2218
+ },
2219
+ handleDOMEvents: {
2220
+ compositionend: view => {
2221
+ setTimeout(() => {
2222
+ const { $cursor } = view.state.selection;
2223
+ if ($cursor) {
2224
+ run$1({
2225
+ editor,
2226
+ from: $cursor.pos,
2227
+ to: $cursor.pos,
2228
+ text: '',
2229
+ rules,
2230
+ plugin,
2231
+ });
2232
+ }
2233
+ });
2234
+ return false;
2235
+ },
2236
+ },
2237
+ // add support for input rules to trigger on enter
2238
+ // this is useful for example for code blocks
2239
+ handleKeyDown(view, event) {
2240
+ if (event.key !== 'Enter') {
2241
+ return false;
2242
+ }
2243
+ const { $cursor } = view.state.selection;
2244
+ if ($cursor) {
2245
+ return run$1({
2246
+ editor,
2247
+ from: $cursor.pos,
2248
+ to: $cursor.pos,
2249
+ text: '\n',
2250
+ rules,
2251
+ plugin,
2252
+ });
2253
+ }
2254
+ return false;
2255
+ },
2256
+ },
2257
+ // @ts-ignore
2258
+ isInputRules: true,
2259
+ });
2260
+ return plugin;
2261
+ }
2262
+
2263
+ function isNumber(value) {
2264
+ return typeof value === 'number';
2265
+ }
2266
+
2267
+ class PasteRule {
2268
+ constructor(config) {
2269
+ this.find = config.find;
2270
+ this.handler = config.handler;
2271
+ }
2272
+ }
2273
+ const pasteRuleMatcherHandler = (text, find) => {
2274
+ if (isRegExp(find)) {
2275
+ return [...text.matchAll(find)];
2276
+ }
2277
+ const matches = find(text);
2278
+ if (!matches) {
2279
+ return [];
2280
+ }
2281
+ return matches.map(pasteRuleMatch => {
2282
+ const result = [];
2283
+ result.push(pasteRuleMatch.text);
2284
+ result.index = pasteRuleMatch.index;
2285
+ result.input = text;
2286
+ result.data = pasteRuleMatch.data;
2287
+ if (pasteRuleMatch.replaceWith) {
2288
+ if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {
2289
+ console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".');
2290
+ }
2291
+ result.push(pasteRuleMatch.replaceWith);
2292
+ }
2293
+ return result;
2294
+ });
2295
+ };
2296
+ function run(config) {
2297
+ const { editor, state, from, to, rules, } = config;
2298
+ const { commands, chain, can } = new CommandManager({
2299
+ editor,
2300
+ state,
2301
+ });
2302
+ state.doc.nodesBetween(from, to, (node, pos) => {
2303
+ if (!node.isTextblock || node.type.spec.code) {
2304
+ return;
2305
+ }
2306
+ const resolvedFrom = Math.max(from, pos);
2307
+ const resolvedTo = Math.min(to, pos + node.content.size);
2308
+ const textToMatch = node.textBetween(resolvedFrom - pos, resolvedTo - pos, undefined, '\ufffc');
2309
+ rules.forEach(rule => {
2310
+ const matches = pasteRuleMatcherHandler(textToMatch, rule.find);
2311
+ matches.forEach(match => {
2312
+ if (match.index === undefined) {
2313
+ return;
2314
+ }
2315
+ const start = resolvedFrom + match.index + 1;
2316
+ const end = start + match[0].length;
2317
+ const range = {
2318
+ from: state.tr.mapping.map(start),
2319
+ to: state.tr.mapping.map(end),
2320
+ };
2321
+ rule.handler({
2322
+ state,
2323
+ range,
2324
+ match,
2325
+ commands,
2326
+ chain,
2327
+ can,
2328
+ });
2329
+ });
2330
+ });
2331
+ });
2332
+ }
2333
+ /**
2334
+ * Create an paste rules plugin. When enabled, it will cause pasted
2335
+ * text that matches any of the given rules to trigger the rule’s
2336
+ * action.
2337
+ */
2338
+ function pasteRulesPlugin(props) {
2339
+ const { editor, rules } = props;
2340
+ let isProseMirrorHTML = false;
2341
+ const plugin = new Plugin({
2342
+ props: {
2343
+ handlePaste: (view, event) => {
2344
+ var _a;
2345
+ const html = (_a = event.clipboardData) === null || _a === void 0 ? void 0 : _a.getData('text/html');
2346
+ isProseMirrorHTML = !!(html === null || html === void 0 ? void 0 : html.includes('data-pm-slice'));
2347
+ return false;
2348
+ },
2349
+ },
2350
+ appendTransaction: (transactions, oldState, state) => {
2351
+ const transaction = transactions[0];
2352
+ // stop if there is not a paste event
2353
+ if (!transaction.getMeta('paste') || isProseMirrorHTML) {
2354
+ return;
2355
+ }
2356
+ // stop if there is no changed range
2357
+ const { doc, before } = transaction;
2358
+ const from = before.content.findDiffStart(doc.content);
2359
+ const to = before.content.findDiffEnd(doc.content);
2360
+ if (!isNumber(from) || !to || from === to.b) {
2361
+ return;
2362
+ }
2363
+ // build a chainable state
2364
+ // so we can use a single transaction for all paste rules
2365
+ const tr = state.tr;
2366
+ const chainableState = createChainableState({
2367
+ state,
2368
+ transaction: tr,
2369
+ });
2370
+ run({
2371
+ editor,
2372
+ state: chainableState,
2373
+ from: Math.max(from - 1, 0),
2374
+ to: to.b,
2375
+ rules,
2376
+ plugin,
2377
+ });
2378
+ // stop if there are no changes
2379
+ if (!tr.steps.length) {
2380
+ return;
2381
+ }
2382
+ return tr;
2383
+ },
2384
+ // @ts-ignore
2385
+ isPasteRules: true,
2386
+ });
2387
+ return plugin;
2388
+ }
2389
+
2390
+ /**
2391
+ * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.
2392
+ * @param extensions List of extensions
2393
+ */
2394
+ function getAttributesFromExtensions(extensions) {
2395
+ const extensionAttributes = [];
2396
+ const { nodeExtensions, markExtensions } = splitExtensions(extensions);
2397
+ const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions];
2398
+ const defaultAttribute = {
2399
+ default: null,
2400
+ rendered: true,
2401
+ renderHTML: null,
2402
+ parseHTML: null,
2403
+ keepOnSplit: true,
2404
+ };
2405
+ extensions.forEach(extension => {
2406
+ const context = {
2407
+ name: extension.name,
2408
+ options: extension.options,
2409
+ storage: extension.storage,
2410
+ };
2411
+ const addGlobalAttributes = getExtensionField(extension, 'addGlobalAttributes', context);
2412
+ if (!addGlobalAttributes) {
2413
+ return;
2414
+ }
2415
+ // TODO: remove `as GlobalAttributes`
2416
+ const globalAttributes = addGlobalAttributes();
2417
+ globalAttributes.forEach(globalAttribute => {
2418
+ globalAttribute.types.forEach(type => {
2419
+ Object
2420
+ .entries(globalAttribute.attributes)
2421
+ .forEach(([name, attribute]) => {
2422
+ extensionAttributes.push({
2423
+ type,
2424
+ name,
2425
+ attribute: {
2426
+ ...defaultAttribute,
2427
+ ...attribute,
2428
+ },
2429
+ });
2430
+ });
2431
+ });
2432
+ });
2433
+ });
2434
+ nodeAndMarkExtensions.forEach(extension => {
2435
+ const context = {
2436
+ name: extension.name,
2437
+ options: extension.options,
2438
+ storage: extension.storage,
2439
+ };
2440
+ const addAttributes = getExtensionField(extension, 'addAttributes', context);
2441
+ if (!addAttributes) {
2442
+ return;
2443
+ }
2444
+ // TODO: remove `as Attributes`
2445
+ const attributes = addAttributes();
2446
+ Object
2447
+ .entries(attributes)
2448
+ .forEach(([name, attribute]) => {
2449
+ extensionAttributes.push({
2450
+ type: extension.name,
2451
+ name,
2452
+ attribute: {
2453
+ ...defaultAttribute,
2454
+ ...attribute,
2455
+ },
2456
+ });
2457
+ });
2458
+ });
2459
+ return extensionAttributes;
2460
+ }
2461
+
2462
+ function mergeAttributes(...objects) {
2463
+ return objects
2464
+ .filter(item => !!item)
2465
+ .reduce((items, item) => {
2466
+ const mergedAttributes = { ...items };
2467
+ Object.entries(item).forEach(([key, value]) => {
2468
+ const exists = mergedAttributes[key];
2469
+ if (!exists) {
2470
+ mergedAttributes[key] = value;
2471
+ return;
2472
+ }
2473
+ if (key === 'class') {
2474
+ mergedAttributes[key] = [mergedAttributes[key], value].join(' ');
2475
+ }
2476
+ else if (key === 'style') {
2477
+ mergedAttributes[key] = [mergedAttributes[key], value].join('; ');
2478
+ }
2479
+ else {
2480
+ mergedAttributes[key] = value;
2481
+ }
2482
+ });
2483
+ return mergedAttributes;
2484
+ }, {});
2485
+ }
2486
+
2487
+ function getRenderedAttributes(nodeOrMark, extensionAttributes) {
2488
+ return extensionAttributes
2489
+ .filter(item => item.attribute.rendered)
2490
+ .map(item => {
2491
+ if (!item.attribute.renderHTML) {
2492
+ return {
2493
+ [item.name]: nodeOrMark.attrs[item.name],
2494
+ };
2495
+ }
2496
+ return item.attribute.renderHTML(nodeOrMark.attrs) || {};
2497
+ })
2498
+ .reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {});
2499
+ }
2500
+
2501
+ function isEmptyObject(value = {}) {
2502
+ return Object.keys(value).length === 0 && value.constructor === Object;
2503
+ }
2504
+
2505
+ function fromString(value) {
2506
+ if (typeof value !== 'string') {
2507
+ return value;
2508
+ }
2509
+ if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) {
2510
+ return Number(value);
2511
+ }
2512
+ if (value === 'true') {
2513
+ return true;
2514
+ }
2515
+ if (value === 'false') {
2516
+ return false;
2517
+ }
2518
+ return value;
2519
+ }
2520
+
2521
+ /**
2522
+ * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).
2523
+ * Cancels when `getAttrs` returned `false`.
2524
+ * @param parseRule ProseMirror ParseRule
2525
+ * @param extensionAttributes List of attributes to inject
2526
+ */
2527
+ function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) {
2528
+ if (parseRule.style) {
2529
+ return parseRule;
2530
+ }
2531
+ return {
2532
+ ...parseRule,
2533
+ getAttrs: node => {
2534
+ const oldAttributes = parseRule.getAttrs
2535
+ ? parseRule.getAttrs(node)
2536
+ : parseRule.attrs;
2537
+ if (oldAttributes === false) {
2538
+ return false;
2539
+ }
2540
+ const newAttributes = extensionAttributes
2541
+ .filter(item => item.attribute.rendered)
2542
+ .reduce((items, item) => {
2543
+ const value = item.attribute.parseHTML
2544
+ ? item.attribute.parseHTML(node)
2545
+ : fromString(node.getAttribute(item.name));
2546
+ if (isObject(value)) {
2547
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "parseHTML" for your attribute "${item.name}" returns an object but should return the value itself. If this is expected you can ignore this message. This warning will be removed in one of the next releases. Further information: https://github.com/ueberdosis/tiptap/issues/1863`);
2548
+ }
2549
+ if (value === null || value === undefined) {
2550
+ return items;
2551
+ }
2552
+ return {
2553
+ ...items,
2554
+ [item.name]: value,
2555
+ };
2556
+ }, {});
2557
+ return { ...oldAttributes, ...newAttributes };
2558
+ },
2559
+ };
2560
+ }
2561
+
2562
+ function cleanUpSchemaItem(data) {
2563
+ return Object.fromEntries(Object.entries(data).filter(([key, value]) => {
2564
+ if (key === 'attrs' && isEmptyObject(value)) {
2565
+ return false;
2566
+ }
2567
+ return value !== null && value !== undefined;
2568
+ }));
2569
+ }
2570
+ function getSchemaByResolvedExtensions(extensions) {
2571
+ var _a;
2572
+ const allAttributes = getAttributesFromExtensions(extensions);
2573
+ const { nodeExtensions, markExtensions } = splitExtensions(extensions);
2574
+ const topNode = (_a = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))) === null || _a === void 0 ? void 0 : _a.name;
2575
+ const nodes = Object.fromEntries(nodeExtensions.map(extension => {
2576
+ const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name);
2577
+ const context = {
2578
+ name: extension.name,
2579
+ options: extension.options,
2580
+ storage: extension.storage,
2581
+ };
2582
+ const extraNodeFields = extensions.reduce((fields, e) => {
2583
+ const extendNodeSchema = getExtensionField(e, 'extendNodeSchema', context);
2584
+ return {
2585
+ ...fields,
2586
+ ...(extendNodeSchema ? extendNodeSchema(extension) : {}),
2587
+ };
2588
+ }, {});
2589
+ const schema = cleanUpSchemaItem({
2590
+ ...extraNodeFields,
2591
+ content: callOrReturn(getExtensionField(extension, 'content', context)),
2592
+ marks: callOrReturn(getExtensionField(extension, 'marks', context)),
2593
+ group: callOrReturn(getExtensionField(extension, 'group', context)),
2594
+ inline: callOrReturn(getExtensionField(extension, 'inline', context)),
2595
+ atom: callOrReturn(getExtensionField(extension, 'atom', context)),
2596
+ selectable: callOrReturn(getExtensionField(extension, 'selectable', context)),
2597
+ draggable: callOrReturn(getExtensionField(extension, 'draggable', context)),
2598
+ code: callOrReturn(getExtensionField(extension, 'code', context)),
2599
+ defining: callOrReturn(getExtensionField(extension, 'defining', context)),
2600
+ isolating: callOrReturn(getExtensionField(extension, 'isolating', context)),
2601
+ attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {
2602
+ var _a;
2603
+ return [extensionAttribute.name, { default: (_a = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a === void 0 ? void 0 : _a.default }];
2604
+ })),
2605
+ });
2606
+ const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context));
2607
+ if (parseHTML) {
2608
+ schema.parseDOM = parseHTML
2609
+ .map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));
2610
+ }
2611
+ const renderHTML = getExtensionField(extension, 'renderHTML', context);
2612
+ if (renderHTML) {
2613
+ schema.toDOM = node => renderHTML({
2614
+ node,
2615
+ HTMLAttributes: getRenderedAttributes(node, extensionAttributes),
2616
+ });
2617
+ }
2618
+ const renderText = getExtensionField(extension, 'renderText', context);
2619
+ if (renderText) {
2620
+ schema.toText = renderText;
2621
+ }
2622
+ return [extension.name, schema];
2623
+ }));
2624
+ const marks = Object.fromEntries(markExtensions.map(extension => {
2625
+ const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name);
2626
+ const context = {
2627
+ name: extension.name,
2628
+ options: extension.options,
2629
+ storage: extension.storage,
2630
+ };
2631
+ const extraMarkFields = extensions.reduce((fields, e) => {
2632
+ const extendMarkSchema = getExtensionField(e, 'extendMarkSchema', context);
2633
+ return {
2634
+ ...fields,
2635
+ ...(extendMarkSchema ? extendMarkSchema(extension) : {}),
2636
+ };
2637
+ }, {});
2638
+ const schema = cleanUpSchemaItem({
2639
+ ...extraMarkFields,
2640
+ inclusive: callOrReturn(getExtensionField(extension, 'inclusive', context)),
2641
+ excludes: callOrReturn(getExtensionField(extension, 'excludes', context)),
2642
+ group: callOrReturn(getExtensionField(extension, 'group', context)),
2643
+ spanning: callOrReturn(getExtensionField(extension, 'spanning', context)),
2644
+ code: callOrReturn(getExtensionField(extension, 'code', context)),
2645
+ attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {
2646
+ var _a;
2647
+ return [extensionAttribute.name, { default: (_a = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a === void 0 ? void 0 : _a.default }];
2648
+ })),
2649
+ });
2650
+ const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context));
2651
+ if (parseHTML) {
2652
+ schema.parseDOM = parseHTML
2653
+ .map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));
2654
+ }
2655
+ const renderHTML = getExtensionField(extension, 'renderHTML', context);
2656
+ if (renderHTML) {
2657
+ schema.toDOM = mark => renderHTML({
2658
+ mark,
2659
+ HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),
2660
+ });
2661
+ }
2662
+ return [extension.name, schema];
2663
+ }));
2664
+ return new Schema({
2665
+ topNode,
2666
+ nodes,
2667
+ marks,
2668
+ });
2669
+ }
2670
+
2671
+ function getSchemaTypeByName(name, schema) {
2672
+ return schema.nodes[name] || schema.marks[name] || null;
2673
+ }
2674
+
2675
+ function findDuplicates(items) {
2676
+ const filtered = items.filter((el, index) => items.indexOf(el) !== index);
2677
+ return [...new Set(filtered)];
2678
+ }
2679
+
2680
+ class ExtensionManager {
2681
+ constructor(extensions, editor) {
2682
+ this.splittableMarks = [];
2683
+ this.editor = editor;
2684
+ this.extensions = ExtensionManager.resolve(extensions);
2685
+ this.schema = getSchemaByResolvedExtensions(this.extensions);
2686
+ this.extensions.forEach(extension => {
2687
+ var _a;
2688
+ // store extension storage in editor
2689
+ this.editor.extensionStorage[extension.name] = extension.storage;
2690
+ const context = {
2691
+ name: extension.name,
2692
+ options: extension.options,
2693
+ storage: extension.storage,
2694
+ editor: this.editor,
2695
+ type: getSchemaTypeByName(extension.name, this.schema),
2696
+ };
2697
+ if (extension.type === 'mark') {
2698
+ const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, 'keepOnSplit', context))) !== null && _a !== void 0 ? _a : true;
2699
+ if (keepOnSplit) {
2700
+ this.splittableMarks.push(extension.name);
2701
+ }
2702
+ }
2703
+ const onBeforeCreate = getExtensionField(extension, 'onBeforeCreate', context);
2704
+ if (onBeforeCreate) {
2705
+ this.editor.on('beforeCreate', onBeforeCreate);
2706
+ }
2707
+ const onCreate = getExtensionField(extension, 'onCreate', context);
2708
+ if (onCreate) {
2709
+ this.editor.on('create', onCreate);
2710
+ }
2711
+ const onUpdate = getExtensionField(extension, 'onUpdate', context);
2712
+ if (onUpdate) {
2713
+ this.editor.on('update', onUpdate);
2714
+ }
2715
+ const onSelectionUpdate = getExtensionField(extension, 'onSelectionUpdate', context);
2716
+ if (onSelectionUpdate) {
2717
+ this.editor.on('selectionUpdate', onSelectionUpdate);
2718
+ }
2719
+ const onTransaction = getExtensionField(extension, 'onTransaction', context);
2720
+ if (onTransaction) {
2721
+ this.editor.on('transaction', onTransaction);
2722
+ }
2723
+ const onFocus = getExtensionField(extension, 'onFocus', context);
2724
+ if (onFocus) {
2725
+ this.editor.on('focus', onFocus);
2726
+ }
2727
+ const onBlur = getExtensionField(extension, 'onBlur', context);
2728
+ if (onBlur) {
2729
+ this.editor.on('blur', onBlur);
2730
+ }
2731
+ const onDestroy = getExtensionField(extension, 'onDestroy', context);
2732
+ if (onDestroy) {
2733
+ this.editor.on('destroy', onDestroy);
2734
+ }
2735
+ });
2736
+ }
2737
+ static resolve(extensions) {
2738
+ const resolvedExtensions = ExtensionManager.sort(ExtensionManager.flatten(extensions));
2739
+ const duplicatedNames = findDuplicates(resolvedExtensions.map(extension => extension.name));
2740
+ if (duplicatedNames.length) {
2741
+ console.warn(`[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map(item => `'${item}'`).join(', ')}]. This can lead to issues.`);
2742
+ }
2743
+ return resolvedExtensions;
2744
+ }
2745
+ static flatten(extensions) {
2746
+ return extensions
2747
+ .map(extension => {
2748
+ const context = {
2749
+ name: extension.name,
2750
+ options: extension.options,
2751
+ storage: extension.storage,
2752
+ };
2753
+ const addExtensions = getExtensionField(extension, 'addExtensions', context);
2754
+ if (addExtensions) {
2755
+ return [
2756
+ extension,
2757
+ ...this.flatten(addExtensions()),
2758
+ ];
2759
+ }
2760
+ return extension;
2761
+ })
2762
+ // `Infinity` will break TypeScript so we set a number that is probably high enough
2763
+ .flat(10);
2764
+ }
2765
+ static sort(extensions) {
2766
+ const defaultPriority = 100;
2767
+ return extensions.sort((a, b) => {
2768
+ const priorityA = getExtensionField(a, 'priority') || defaultPriority;
2769
+ const priorityB = getExtensionField(b, 'priority') || defaultPriority;
2770
+ if (priorityA > priorityB) {
2771
+ return -1;
2772
+ }
2773
+ if (priorityA < priorityB) {
2774
+ return 1;
2775
+ }
2776
+ return 0;
2777
+ });
2778
+ }
2779
+ get commands() {
2780
+ return this.extensions.reduce((commands, extension) => {
2781
+ const context = {
2782
+ name: extension.name,
2783
+ options: extension.options,
2784
+ storage: extension.storage,
2785
+ editor: this.editor,
2786
+ type: getSchemaTypeByName(extension.name, this.schema),
2787
+ };
2788
+ const addCommands = getExtensionField(extension, 'addCommands', context);
2789
+ if (!addCommands) {
2790
+ return commands;
2791
+ }
2792
+ return {
2793
+ ...commands,
2794
+ ...addCommands(),
2795
+ };
2796
+ }, {});
2797
+ }
2798
+ get plugins() {
2799
+ const { editor } = this;
2800
+ // With ProseMirror, first plugins within an array are executed first.
2801
+ // In tiptap, we provide the ability to override plugins,
2802
+ // so it feels more natural to run plugins at the end of an array first.
2803
+ // That’s why we have to reverse the `extensions` array and sort again
2804
+ // based on the `priority` option.
2805
+ const extensions = ExtensionManager.sort([...this.extensions].reverse());
2806
+ const inputRules = [];
2807
+ const pasteRules = [];
2808
+ const allPlugins = extensions
2809
+ .map(extension => {
2810
+ const context = {
2811
+ name: extension.name,
2812
+ options: extension.options,
2813
+ storage: extension.storage,
2814
+ editor,
2815
+ type: getSchemaTypeByName(extension.name, this.schema),
2816
+ };
2817
+ const plugins = [];
2818
+ const addKeyboardShortcuts = getExtensionField(extension, 'addKeyboardShortcuts', context);
2819
+ if (addKeyboardShortcuts) {
2820
+ const bindings = Object.fromEntries(Object
2821
+ .entries(addKeyboardShortcuts())
2822
+ .map(([shortcut, method]) => {
2823
+ return [shortcut, () => method({ editor })];
2824
+ }));
2825
+ const keyMapPlugin = keymap(bindings);
2826
+ plugins.push(keyMapPlugin);
2827
+ }
2828
+ const addInputRules = getExtensionField(extension, 'addInputRules', context);
2829
+ if (editor.options.enableInputRules && addInputRules) {
2830
+ inputRules.push(...addInputRules());
2831
+ }
2832
+ const addPasteRules = getExtensionField(extension, 'addPasteRules', context);
2833
+ if (editor.options.enablePasteRules && addPasteRules) {
2834
+ pasteRules.push(...addPasteRules());
2835
+ }
2836
+ const addProseMirrorPlugins = getExtensionField(extension, 'addProseMirrorPlugins', context);
2837
+ if (addProseMirrorPlugins) {
2838
+ const proseMirrorPlugins = addProseMirrorPlugins();
2839
+ plugins.push(...proseMirrorPlugins);
2840
+ }
2841
+ return plugins;
2842
+ })
2843
+ .flat();
2844
+ return [
2845
+ inputRulesPlugin({
2846
+ editor,
2847
+ rules: inputRules,
2848
+ }),
2849
+ pasteRulesPlugin({
2850
+ editor,
2851
+ rules: pasteRules,
2852
+ }),
2853
+ ...allPlugins,
2854
+ ];
2855
+ }
2856
+ get attributes() {
2857
+ return getAttributesFromExtensions(this.extensions);
2858
+ }
2859
+ get nodeViews() {
2860
+ const { editor } = this;
2861
+ const { nodeExtensions } = splitExtensions(this.extensions);
2862
+ return Object.fromEntries(nodeExtensions
2863
+ .filter(extension => !!getExtensionField(extension, 'addNodeView'))
2864
+ .map(extension => {
2865
+ const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name);
2866
+ const context = {
2867
+ name: extension.name,
2868
+ options: extension.options,
2869
+ storage: extension.storage,
2870
+ editor,
2871
+ type: getNodeType(extension.name, this.schema),
2872
+ };
2873
+ const addNodeView = getExtensionField(extension, 'addNodeView', context);
2874
+ if (!addNodeView) {
2875
+ return [];
2876
+ }
2877
+ const nodeview = (node, view, getPos, decorations) => {
2878
+ const HTMLAttributes = getRenderedAttributes(node, extensionAttributes);
2879
+ return addNodeView()({
2880
+ editor,
2881
+ node,
2882
+ getPos,
2883
+ decorations,
2884
+ HTMLAttributes,
2885
+ extension,
2886
+ });
2887
+ };
2888
+ return [extension.name, nodeview];
2889
+ }));
2890
+ }
2891
+ }
2892
+
2893
+ class EventEmitter {
2894
+ constructor() {
2895
+ this.callbacks = {};
2896
+ }
2897
+ on(event, fn) {
2898
+ if (!this.callbacks[event]) {
2899
+ this.callbacks[event] = [];
2900
+ }
2901
+ this.callbacks[event].push(fn);
2902
+ return this;
2903
+ }
2904
+ emit(event, ...args) {
2905
+ const callbacks = this.callbacks[event];
2906
+ if (callbacks) {
2907
+ callbacks.forEach(callback => callback.apply(this, args));
2908
+ }
2909
+ return this;
2910
+ }
2911
+ off(event, fn) {
2912
+ const callbacks = this.callbacks[event];
2913
+ if (callbacks) {
2914
+ if (fn) {
2915
+ this.callbacks[event] = callbacks.filter(callback => callback !== fn);
2916
+ }
2917
+ else {
2918
+ delete this.callbacks[event];
2919
+ }
2920
+ }
2921
+ return this;
2922
+ }
2923
+ removeAllListeners() {
2924
+ this.callbacks = {};
2925
+ }
2926
+ }
2927
+
2928
+ const style = `.ProseMirror {
2929
+ position: relative;
2930
+ }
2931
+
2932
+ .ProseMirror {
2933
+ word-wrap: break-word;
2934
+ white-space: pre-wrap;
2935
+ white-space: break-spaces;
2936
+ -webkit-font-variant-ligatures: none;
2937
+ font-variant-ligatures: none;
2938
+ font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
2939
+ }
2940
+
2941
+ .ProseMirror [contenteditable="false"] {
2942
+ white-space: normal;
2943
+ }
2944
+
2945
+ .ProseMirror [contenteditable="false"] [contenteditable="true"] {
2946
+ white-space: pre-wrap;
2947
+ }
2948
+
2949
+ .ProseMirror pre {
2950
+ white-space: pre-wrap;
2951
+ }
2952
+
2953
+ img.ProseMirror-separator {
2954
+ display: inline !important;
2955
+ border: none !important;
2956
+ margin: 0 !important;
2957
+ width: 1px !important;
2958
+ height: 1px !important;
2959
+ }
2960
+
2961
+ .ProseMirror-gapcursor {
2962
+ display: none;
2963
+ pointer-events: none;
2964
+ position: absolute;
2965
+ }
2966
+
2967
+ .ProseMirror-gapcursor:after {
2968
+ content: "";
2969
+ display: block;
2970
+ position: absolute;
2971
+ top: -2px;
2972
+ width: 20px;
2973
+ border-top: 1px solid black;
2974
+ animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
2975
+ }
2976
+
2977
+ @keyframes ProseMirror-cursor-blink {
2978
+ to {
2979
+ visibility: hidden;
2980
+ }
2981
+ }
2982
+
2983
+ .ProseMirror-hideselection *::selection {
2984
+ background: transparent;
2985
+ }
2986
+
2987
+ .ProseMirror-hideselection *::-moz-selection {
2988
+ background: transparent;
2989
+ }
2990
+
2991
+ .ProseMirror-hideselection * {
2992
+ caret-color: transparent;
2993
+ }
2994
+
2995
+ .ProseMirror-focused .ProseMirror-gapcursor {
2996
+ display: block;
2997
+ }
2998
+
2999
+ .tippy-box[data-animation=fade][data-state=hidden] {
3000
+ opacity: 0
3001
+ }`;
3002
+
3003
+ class Editor extends EventEmitter {
3004
+ constructor(options = {}) {
3005
+ super();
3006
+ this.isFocused = false;
3007
+ this.extensionStorage = {};
3008
+ this.options = {
3009
+ element: document.createElement('div'),
3010
+ content: '',
3011
+ injectCSS: true,
3012
+ extensions: [],
3013
+ autofocus: false,
3014
+ editable: true,
3015
+ editorProps: {},
3016
+ parseOptions: {},
3017
+ enableInputRules: true,
3018
+ enablePasteRules: true,
3019
+ enableCoreExtensions: true,
3020
+ onBeforeCreate: () => null,
3021
+ onCreate: () => null,
3022
+ onUpdate: () => null,
3023
+ onSelectionUpdate: () => null,
3024
+ onTransaction: () => null,
3025
+ onFocus: () => null,
3026
+ onBlur: () => null,
3027
+ onDestroy: () => null,
3028
+ };
3029
+ this.isCapturingTransaction = false;
3030
+ this.capturedTransaction = null;
3031
+ this.setOptions(options);
3032
+ this.createExtensionManager();
3033
+ this.createCommandManager();
3034
+ this.createSchema();
3035
+ this.on('beforeCreate', this.options.onBeforeCreate);
3036
+ this.emit('beforeCreate', { editor: this });
3037
+ this.createView();
3038
+ this.injectCSS();
3039
+ this.on('create', this.options.onCreate);
3040
+ this.on('update', this.options.onUpdate);
3041
+ this.on('selectionUpdate', this.options.onSelectionUpdate);
3042
+ this.on('transaction', this.options.onTransaction);
3043
+ this.on('focus', this.options.onFocus);
3044
+ this.on('blur', this.options.onBlur);
3045
+ this.on('destroy', this.options.onDestroy);
3046
+ window.setTimeout(() => {
3047
+ if (this.isDestroyed) {
3048
+ return;
3049
+ }
3050
+ this.commands.focus(this.options.autofocus);
3051
+ this.emit('create', { editor: this });
3052
+ }, 0);
3053
+ }
3054
+ /**
3055
+ * Returns the editor storage.
3056
+ */
3057
+ get storage() {
3058
+ return this.extensionStorage;
3059
+ }
3060
+ /**
3061
+ * An object of all registered commands.
3062
+ */
3063
+ get commands() {
3064
+ return this.commandManager.commands;
3065
+ }
3066
+ /**
3067
+ * Create a command chain to call multiple commands at once.
3068
+ */
3069
+ chain() {
3070
+ return this.commandManager.chain();
3071
+ }
3072
+ /**
3073
+ * Check if a command or a command chain can be executed. Without executing it.
3074
+ */
3075
+ can() {
3076
+ return this.commandManager.can();
3077
+ }
3078
+ /**
3079
+ * Inject CSS styles.
3080
+ */
3081
+ injectCSS() {
3082
+ if (this.options.injectCSS && document) {
3083
+ this.css = createStyleTag(style);
3084
+ }
3085
+ }
3086
+ /**
3087
+ * Update editor options.
3088
+ *
3089
+ * @param options A list of options
3090
+ */
3091
+ setOptions(options = {}) {
3092
+ this.options = {
3093
+ ...this.options,
3094
+ ...options,
3095
+ };
3096
+ if (!this.view || !this.state || this.isDestroyed) {
3097
+ return;
3098
+ }
3099
+ if (this.options.editorProps) {
3100
+ this.view.setProps(this.options.editorProps);
3101
+ }
3102
+ this.view.updateState(this.state);
3103
+ }
3104
+ /**
3105
+ * Update editable state of the editor.
3106
+ */
3107
+ setEditable(editable) {
3108
+ this.setOptions({ editable });
3109
+ }
3110
+ /**
3111
+ * Returns whether the editor is editable.
3112
+ */
3113
+ get isEditable() {
3114
+ // since plugins are applied after creating the view
3115
+ // `editable` is always `true` for one tick.
3116
+ // that’s why we also have to check for `options.editable`
3117
+ return this.options.editable
3118
+ && this.view
3119
+ && this.view.editable;
3120
+ }
3121
+ /**
3122
+ * Returns the editor state.
3123
+ */
3124
+ get state() {
3125
+ return this.view.state;
3126
+ }
3127
+ /**
3128
+ * Register a ProseMirror plugin.
3129
+ *
3130
+ * @param plugin A ProseMirror plugin
3131
+ * @param handlePlugins Control how to merge the plugin into the existing plugins.
3132
+ */
3133
+ registerPlugin(plugin, handlePlugins) {
3134
+ const plugins = isObject$1(handlePlugins)
3135
+ ? handlePlugins(plugin, this.state.plugins)
3136
+ : [...this.state.plugins, plugin];
3137
+ const state = this.state.reconfigure({ plugins });
3138
+ this.view.updateState(state);
3139
+ }
3140
+ /**
3141
+ * Unregister a ProseMirror plugin.
3142
+ *
3143
+ * @param nameOrPluginKey The plugins name
3144
+ */
3145
+ unregisterPlugin(nameOrPluginKey) {
3146
+ if (this.isDestroyed) {
3147
+ return;
3148
+ }
3149
+ const name = typeof nameOrPluginKey === 'string'
3150
+ ? `${nameOrPluginKey}$`
3151
+ // @ts-ignore
3152
+ : nameOrPluginKey.key;
3153
+ const state = this.state.reconfigure({
3154
+ // @ts-ignore
3155
+ plugins: this.state.plugins.filter(plugin => !plugin.key.startsWith(name)),
3156
+ });
3157
+ this.view.updateState(state);
3158
+ }
3159
+ /**
3160
+ * Creates an extension manager.
3161
+ */
3162
+ createExtensionManager() {
3163
+ const coreExtensions = this.options.enableCoreExtensions
3164
+ ? Object.values(extensions)
3165
+ : [];
3166
+ const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {
3167
+ return ['extension', 'node', 'mark'].includes(extension === null || extension === void 0 ? void 0 : extension.type);
3168
+ });
3169
+ this.extensionManager = new ExtensionManager(allExtensions, this);
3170
+ }
3171
+ /**
3172
+ * Creates an command manager.
3173
+ */
3174
+ createCommandManager() {
3175
+ this.commandManager = new CommandManager({
3176
+ editor: this,
3177
+ });
3178
+ }
3179
+ /**
3180
+ * Creates a ProseMirror schema.
3181
+ */
3182
+ createSchema() {
3183
+ this.schema = this.extensionManager.schema;
3184
+ }
3185
+ /**
3186
+ * Creates a ProseMirror view.
3187
+ */
3188
+ createView() {
3189
+ this.view = new EditorView(this.options.element, {
3190
+ ...this.options.editorProps,
3191
+ dispatchTransaction: this.dispatchTransaction.bind(this),
3192
+ state: EditorState.create({
3193
+ doc: createDocument(this.options.content, this.schema, this.options.parseOptions),
3194
+ }),
3195
+ });
3196
+ // `editor.view` is not yet available at this time.
3197
+ // Therefore we will add all plugins and node views directly afterwards.
3198
+ const newState = this.state.reconfigure({
3199
+ plugins: this.extensionManager.plugins,
3200
+ });
3201
+ this.view.updateState(newState);
3202
+ this.createNodeViews();
3203
+ // Let’s store the editor instance in the DOM element.
3204
+ // So we’ll have access to it for tests.
3205
+ const dom = this.view.dom;
3206
+ dom.editor = this;
3207
+ }
3208
+ /**
3209
+ * Creates all node views.
3210
+ */
3211
+ createNodeViews() {
3212
+ this.view.setProps({
3213
+ nodeViews: this.extensionManager.nodeViews,
3214
+ });
3215
+ }
3216
+ captureTransaction(fn) {
3217
+ this.isCapturingTransaction = true;
3218
+ fn();
3219
+ this.isCapturingTransaction = false;
3220
+ const tr = this.capturedTransaction;
3221
+ this.capturedTransaction = null;
3222
+ return tr;
3223
+ }
3224
+ /**
3225
+ * The callback over which to send transactions (state updates) produced by the view.
3226
+ *
3227
+ * @param transaction An editor state transaction
3228
+ */
3229
+ dispatchTransaction(transaction) {
3230
+ if (this.isCapturingTransaction) {
3231
+ if (!this.capturedTransaction) {
3232
+ this.capturedTransaction = transaction;
3233
+ return;
3234
+ }
3235
+ transaction.steps.forEach(step => { var _a; return (_a = this.capturedTransaction) === null || _a === void 0 ? void 0 : _a.step(step); });
3236
+ return;
3237
+ }
3238
+ const state = this.state.apply(transaction);
3239
+ const selectionHasChanged = !this.state.selection.eq(state.selection);
3240
+ this.view.updateState(state);
3241
+ this.emit('transaction', {
3242
+ editor: this,
3243
+ transaction,
3244
+ });
3245
+ if (selectionHasChanged) {
3246
+ this.emit('selectionUpdate', {
3247
+ editor: this,
3248
+ transaction,
3249
+ });
3250
+ }
3251
+ const focus = transaction.getMeta('focus');
3252
+ const blur = transaction.getMeta('blur');
3253
+ if (focus) {
3254
+ this.emit('focus', {
3255
+ editor: this,
3256
+ event: focus.event,
3257
+ transaction,
3258
+ });
3259
+ }
3260
+ if (blur) {
3261
+ this.emit('blur', {
3262
+ editor: this,
3263
+ event: blur.event,
3264
+ transaction,
3265
+ });
3266
+ }
3267
+ if (!transaction.docChanged || transaction.getMeta('preventUpdate')) {
3268
+ return;
3269
+ }
3270
+ this.emit('update', {
3271
+ editor: this,
3272
+ transaction,
3273
+ });
3274
+ }
3275
+ /**
3276
+ * Get attributes of the currently selected node or mark.
3277
+ */
3278
+ getAttributes(nameOrType) {
3279
+ return getAttributes(this.state, nameOrType);
3280
+ }
3281
+ isActive(nameOrAttributes, attributesOrUndefined) {
3282
+ const name = typeof nameOrAttributes === 'string'
3283
+ ? nameOrAttributes
3284
+ : null;
3285
+ const attributes = typeof nameOrAttributes === 'string'
3286
+ ? attributesOrUndefined
3287
+ : nameOrAttributes;
3288
+ return isActive(this.state, name, attributes);
3289
+ }
3290
+ /**
3291
+ * Get the document as JSON.
3292
+ */
3293
+ getJSON() {
3294
+ return this.state.doc.toJSON();
3295
+ }
3296
+ /**
3297
+ * Get the document as HTML.
3298
+ */
3299
+ getHTML() {
3300
+ return getHTMLFromFragment(this.state.doc.content, this.schema);
3301
+ }
3302
+ /**
3303
+ * Get the document as text.
3304
+ */
3305
+ getText(options) {
3306
+ const { blockSeparator = '\n\n', textSerializers = {}, } = options || {};
3307
+ return getText(this.state.doc, {
3308
+ blockSeparator,
3309
+ textSerializers: {
3310
+ ...textSerializers,
3311
+ ...getTextSeralizersFromSchema(this.schema),
3312
+ },
3313
+ });
3314
+ }
3315
+ /**
3316
+ * Check if there is no content.
3317
+ */
3318
+ get isEmpty() {
3319
+ return isNodeEmpty(this.state.doc);
3320
+ }
3321
+ /**
3322
+ * Get the number of characters for the current document.
3323
+ */
3324
+ getCharacterCount() {
3325
+ return this.state.doc.content.size - 2;
3326
+ }
3327
+ /**
3328
+ * Destroy the editor.
3329
+ */
3330
+ destroy() {
3331
+ this.emit('destroy');
3332
+ if (this.view) {
3333
+ this.view.destroy();
3334
+ }
3335
+ this.removeAllListeners();
3336
+ removeElement(this.css);
3337
+ }
3338
+ /**
3339
+ * Check if the editor is already destroyed.
3340
+ */
3341
+ get isDestroyed() {
3342
+ var _a;
3343
+ // @ts-ignore
3344
+ return !((_a = this.view) === null || _a === void 0 ? void 0 : _a.docView);
3345
+ }
3346
+ }
3347
+
3348
+ class Node {
3349
+ constructor(config = {}) {
3350
+ this.type = 'node';
3351
+ this.name = 'node';
3352
+ this.parent = null;
3353
+ this.child = null;
3354
+ this.config = {
3355
+ name: this.name,
3356
+ defaultOptions: {},
3357
+ };
3358
+ this.config = {
3359
+ ...this.config,
3360
+ ...config,
3361
+ };
3362
+ this.name = this.config.name;
3363
+ if (config.defaultOptions) {
3364
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
3365
+ }
3366
+ // TODO: remove `addOptions` fallback
3367
+ this.options = this.config.defaultOptions;
3368
+ if (this.config.addOptions) {
3369
+ this.options = callOrReturn(getExtensionField(this, 'addOptions', {
3370
+ name: this.name,
3371
+ }));
3372
+ }
3373
+ this.storage = callOrReturn(getExtensionField(this, 'addStorage', {
3374
+ name: this.name,
3375
+ options: this.options,
3376
+ })) || {};
3377
+ }
3378
+ static create(config = {}) {
3379
+ return new Node(config);
3380
+ }
3381
+ configure(options = {}) {
3382
+ // return a new instance so we can use the same extension
3383
+ // with different calls of `configure`
3384
+ const extension = this.extend();
3385
+ extension.options = mergeDeep(this.options, options);
3386
+ extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {
3387
+ name: extension.name,
3388
+ options: extension.options,
3389
+ }));
3390
+ return extension;
3391
+ }
3392
+ extend(extendedConfig = {}) {
3393
+ const extension = new Node(extendedConfig);
3394
+ extension.parent = this;
3395
+ this.child = extension;
3396
+ extension.name = extendedConfig.name
3397
+ ? extendedConfig.name
3398
+ : extension.parent.name;
3399
+ if (extendedConfig.defaultOptions) {
3400
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
3401
+ }
3402
+ // TODO: remove `addOptions` fallback
3403
+ extension.options = extendedConfig.defaultOptions
3404
+ ? extendedConfig.defaultOptions
3405
+ : extension.parent.options;
3406
+ if (extendedConfig.addOptions) {
3407
+ extension.options = callOrReturn(getExtensionField(extension, 'addOptions', {
3408
+ name: extension.name,
3409
+ }));
3410
+ }
3411
+ extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {
3412
+ name: extension.name,
3413
+ options: extension.options,
3414
+ }));
3415
+ return extension;
3416
+ }
3417
+ }
3418
+
3419
+ class Mark {
3420
+ constructor(config = {}) {
3421
+ this.type = 'mark';
3422
+ this.name = 'mark';
3423
+ this.parent = null;
3424
+ this.child = null;
3425
+ this.config = {
3426
+ name: this.name,
3427
+ defaultOptions: {},
3428
+ };
3429
+ this.config = {
3430
+ ...this.config,
3431
+ ...config,
3432
+ };
3433
+ this.name = this.config.name;
3434
+ if (config.defaultOptions) {
3435
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`);
3436
+ }
3437
+ // TODO: remove `addOptions` fallback
3438
+ this.options = this.config.defaultOptions;
3439
+ if (this.config.addOptions) {
3440
+ this.options = callOrReturn(getExtensionField(this, 'addOptions', {
3441
+ name: this.name,
3442
+ }));
3443
+ }
3444
+ this.storage = callOrReturn(getExtensionField(this, 'addStorage', {
3445
+ name: this.name,
3446
+ options: this.options,
3447
+ })) || {};
3448
+ }
3449
+ static create(config = {}) {
3450
+ return new Mark(config);
3451
+ }
3452
+ configure(options = {}) {
3453
+ // return a new instance so we can use the same extension
3454
+ // with different calls of `configure`
3455
+ const extension = this.extend();
3456
+ extension.options = mergeDeep(this.options, options);
3457
+ extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {
3458
+ name: extension.name,
3459
+ options: extension.options,
3460
+ }));
3461
+ return extension;
3462
+ }
3463
+ extend(extendedConfig = {}) {
3464
+ const extension = new Mark(extendedConfig);
3465
+ extension.parent = this;
3466
+ this.child = extension;
3467
+ extension.name = extendedConfig.name
3468
+ ? extendedConfig.name
3469
+ : extension.parent.name;
3470
+ if (extendedConfig.defaultOptions) {
3471
+ console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${extension.name}".`);
3472
+ }
3473
+ // TODO: remove `addOptions` fallback
3474
+ extension.options = extendedConfig.defaultOptions
3475
+ ? extendedConfig.defaultOptions
3476
+ : extension.parent.options;
3477
+ if (extendedConfig.addOptions) {
3478
+ extension.options = callOrReturn(getExtensionField(extension, 'addOptions', {
3479
+ name: extension.name,
3480
+ }));
3481
+ }
3482
+ extension.storage = callOrReturn(getExtensionField(extension, 'addStorage', {
3483
+ name: extension.name,
3484
+ options: extension.options,
3485
+ }));
3486
+ return extension;
3487
+ }
3488
+ }
3489
+
3490
+ class NodeView {
3491
+ constructor(component, props, options) {
3492
+ this.isDragging = false;
3493
+ this.component = component;
3494
+ this.editor = props.editor;
3495
+ this.options = {
3496
+ stopEvent: null,
3497
+ ignoreMutation: null,
3498
+ ...options,
3499
+ };
3500
+ this.extension = props.extension;
3501
+ this.node = props.node;
3502
+ this.decorations = props.decorations;
3503
+ this.getPos = props.getPos;
3504
+ this.mount();
3505
+ }
3506
+ mount() {
3507
+ // eslint-disable-next-line
3508
+ return;
3509
+ }
3510
+ get dom() {
3511
+ return null;
3512
+ }
3513
+ get contentDOM() {
3514
+ return null;
3515
+ }
3516
+ onDragStart(event) {
3517
+ var _a, _b, _c;
3518
+ const { view } = this.editor;
3519
+ const target = event.target;
3520
+ // get the drag handle element
3521
+ // `closest` is not available for text nodes so we may have to use its parent
3522
+ const dragHandle = target.nodeType === 3
3523
+ ? (_a = target.parentElement) === null || _a === void 0 ? void 0 : _a.closest('[data-drag-handle]')
3524
+ : target.closest('[data-drag-handle]');
3525
+ if (!this.dom
3526
+ || ((_b = this.contentDOM) === null || _b === void 0 ? void 0 : _b.contains(target))
3527
+ || !dragHandle) {
3528
+ return;
3529
+ }
3530
+ let x = 0;
3531
+ let y = 0;
3532
+ // calculate offset for drag element if we use a different drag handle element
3533
+ if (this.dom !== dragHandle) {
3534
+ const domBox = this.dom.getBoundingClientRect();
3535
+ const handleBox = dragHandle.getBoundingClientRect();
3536
+ x = handleBox.x - domBox.x + event.offsetX;
3537
+ y = handleBox.y - domBox.y + event.offsetY;
3538
+ }
3539
+ (_c = event.dataTransfer) === null || _c === void 0 ? void 0 : _c.setDragImage(this.dom, x, y);
3540
+ // we need to tell ProseMirror that we want to move the whole node
3541
+ // so we create a NodeSelection
3542
+ const selection = NodeSelection.create(view.state.doc, this.getPos());
3543
+ const transaction = view.state.tr.setSelection(selection);
3544
+ view.dispatch(transaction);
3545
+ }
3546
+ stopEvent(event) {
3547
+ var _a;
3548
+ if (!this.dom) {
3549
+ return false;
3550
+ }
3551
+ if (typeof this.options.stopEvent === 'function') {
3552
+ return this.options.stopEvent({ event });
3553
+ }
3554
+ const target = event.target;
3555
+ const isInElement = this.dom.contains(target) && !((_a = this.contentDOM) === null || _a === void 0 ? void 0 : _a.contains(target));
3556
+ // any event from child nodes should be handled by ProseMirror
3557
+ if (!isInElement) {
3558
+ return false;
3559
+ }
3560
+ const isDropEvent = event.type === 'drop';
3561
+ const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName)
3562
+ || target.isContentEditable;
3563
+ // any input event within node views should be ignored by ProseMirror
3564
+ if (isInput && !isDropEvent) {
3565
+ return true;
3566
+ }
3567
+ const { isEditable } = this.editor;
3568
+ const { isDragging } = this;
3569
+ const isDraggable = !!this.node.type.spec.draggable;
3570
+ const isSelectable = NodeSelection.isSelectable(this.node);
3571
+ const isCopyEvent = event.type === 'copy';
3572
+ const isPasteEvent = event.type === 'paste';
3573
+ const isCutEvent = event.type === 'cut';
3574
+ const isClickEvent = event.type === 'mousedown';
3575
+ const isDragEvent = event.type.startsWith('drag');
3576
+ // ProseMirror tries to drag selectable nodes
3577
+ // even if `draggable` is set to `false`
3578
+ // this fix prevents that
3579
+ if (!isDraggable && isSelectable && isDragEvent) {
3580
+ event.preventDefault();
3581
+ }
3582
+ if (isDraggable && isDragEvent && !isDragging) {
3583
+ event.preventDefault();
3584
+ return false;
3585
+ }
3586
+ // we have to store that dragging started
3587
+ if (isDraggable && isEditable && !isDragging && isClickEvent) {
3588
+ const dragHandle = target.closest('[data-drag-handle]');
3589
+ const isValidDragHandle = dragHandle
3590
+ && (this.dom === dragHandle || (this.dom.contains(dragHandle)));
3591
+ if (isValidDragHandle) {
3592
+ this.isDragging = true;
3593
+ document.addEventListener('dragend', () => {
3594
+ this.isDragging = false;
3595
+ }, { once: true });
3596
+ document.addEventListener('mouseup', () => {
3597
+ this.isDragging = false;
3598
+ }, { once: true });
3599
+ }
3600
+ }
3601
+ // these events are handled by prosemirror
3602
+ if (isDragging
3603
+ || isDropEvent
3604
+ || isCopyEvent
3605
+ || isPasteEvent
3606
+ || isCutEvent
3607
+ || (isClickEvent && isSelectable)) {
3608
+ return false;
3609
+ }
3610
+ return true;
3611
+ }
3612
+ ignoreMutation(mutation) {
3613
+ if (!this.dom || !this.contentDOM) {
3614
+ return true;
3615
+ }
3616
+ if (typeof this.options.ignoreMutation === 'function') {
3617
+ return this.options.ignoreMutation({ mutation });
3618
+ }
3619
+ // a leaf/atom node is like a black box for ProseMirror
3620
+ // and should be fully handled by the node view
3621
+ if (this.node.isLeaf || this.node.isAtom) {
3622
+ return true;
3623
+ }
3624
+ // ProseMirror should handle any selections
3625
+ if (mutation.type === 'selection') {
3626
+ return false;
3627
+ }
3628
+ // try to prevent a bug on iOS that will break node views on enter
3629
+ // this is because ProseMirror can’t preventDispatch on enter
3630
+ // this will lead to a re-render of the node view on enter
3631
+ // see: https://github.com/ueberdosis/tiptap/issues/1214
3632
+ if (this.dom.contains(mutation.target) && mutation.type === 'childList' && isiOS()) {
3633
+ const changedNodes = [
3634
+ ...Array.from(mutation.addedNodes),
3635
+ ...Array.from(mutation.removedNodes),
3636
+ ];
3637
+ // we’ll check if every changed node is contentEditable
3638
+ // to make sure it’s probably mutated by ProseMirror
3639
+ if (changedNodes.every(node => node.isContentEditable)) {
3640
+ return false;
3641
+ }
3642
+ }
3643
+ // we will allow mutation contentDOM with attributes
3644
+ // so we can for example adding classes within our node view
3645
+ if (this.contentDOM === mutation.target && mutation.type === 'attributes') {
3646
+ return true;
3647
+ }
3648
+ // ProseMirror should handle any changes within contentDOM
3649
+ if (this.contentDOM.contains(mutation.target)) {
3650
+ return false;
3651
+ }
3652
+ return true;
3653
+ }
3654
+ updateAttributes(attributes) {
3655
+ this.editor.commands.command(({ tr }) => {
3656
+ const pos = this.getPos();
3657
+ tr.setNodeMarkup(pos, undefined, {
3658
+ ...this.node.attrs,
3659
+ ...attributes,
3660
+ });
3661
+ return true;
3662
+ });
3663
+ }
3664
+ deleteNode() {
3665
+ const from = this.getPos();
3666
+ const to = from + this.node.nodeSize;
3667
+ this.editor.commands.deleteRange({ from, to });
3668
+ }
3669
+ }
3670
+
3671
+ class Tracker {
3672
+ constructor(transaction) {
3673
+ this.transaction = transaction;
3674
+ this.currentStep = this.transaction.steps.length;
3675
+ }
3676
+ map(position) {
3677
+ let deleted = false;
3678
+ const mappedPosition = this.transaction.steps
3679
+ .slice(this.currentStep)
3680
+ .reduce((newPosition, step) => {
3681
+ const mapResult = step
3682
+ .getMap()
3683
+ .mapResult(newPosition);
3684
+ if (mapResult.deleted) {
3685
+ deleted = true;
3686
+ }
3687
+ return mapResult.pos;
3688
+ }, position);
3689
+ return {
3690
+ position: mappedPosition,
3691
+ deleted,
3692
+ };
3693
+ }
3694
+ }
3695
+
3696
+ /**
3697
+ * Build an input rule that adds a node when the
3698
+ * matched text is typed into it.
3699
+ */
3700
+ function nodeInputRule(config) {
3701
+ return new InputRule({
3702
+ find: config.find,
3703
+ handler: ({ state, range, match }) => {
3704
+ const attributes = callOrReturn(config.getAttributes, undefined, match) || {};
3705
+ const { tr } = state;
3706
+ const start = range.from;
3707
+ let end = range.to;
3708
+ if (match[1]) {
3709
+ const offset = match[0].lastIndexOf(match[1]);
3710
+ let matchStart = start + offset;
3711
+ if (matchStart > end) {
3712
+ matchStart = end;
3713
+ }
3714
+ else {
3715
+ end = matchStart + match[1].length;
3716
+ }
3717
+ // insert last typed character
3718
+ const lastChar = match[0][match[0].length - 1];
3719
+ tr.insertText(lastChar, start + match[0].length - 1);
3720
+ // insert node from input rule
3721
+ tr.replaceWith(matchStart, end, config.type.create(attributes));
3722
+ }
3723
+ else if (match[0]) {
3724
+ tr.replaceWith(start, end, config.type.create(attributes));
3725
+ }
3726
+ },
3727
+ });
3728
+ }
3729
+
3730
+ function getMarksBetween(from, to, state) {
3731
+ const marks = [];
3732
+ state.doc.nodesBetween(from, to, (node, pos) => {
3733
+ marks.push(...node.marks.map(mark => ({
3734
+ from: pos,
3735
+ to: pos + node.nodeSize,
3736
+ mark,
3737
+ })));
3738
+ });
3739
+ return marks;
3740
+ }
3741
+
3742
+ /**
3743
+ * Build an input rule that adds a mark when the
3744
+ * matched text is typed into it.
3745
+ */
3746
+ function markInputRule(config) {
3747
+ return new InputRule({
3748
+ find: config.find,
3749
+ handler: ({ state, range, match }) => {
3750
+ const attributes = callOrReturn(config.getAttributes, undefined, match);
3751
+ if (attributes === false || attributes === null) {
3752
+ return;
3753
+ }
3754
+ const { tr } = state;
3755
+ const captureGroup = match[match.length - 1];
3756
+ const fullMatch = match[0];
3757
+ let markEnd = range.to;
3758
+ if (captureGroup) {
3759
+ const startSpaces = fullMatch.search(/\S/);
3760
+ const textStart = range.from + fullMatch.indexOf(captureGroup);
3761
+ const textEnd = textStart + captureGroup.length;
3762
+ const excludedMarks = getMarksBetween(range.from, range.to, state)
3763
+ .filter(item => {
3764
+ // @ts-ignore
3765
+ const excluded = item.mark.type.excluded;
3766
+ return excluded.find(type => type === config.type && type !== item.mark.type);
3767
+ })
3768
+ .filter(item => item.to > textStart);
3769
+ if (excludedMarks.length) {
3770
+ return null;
3771
+ }
3772
+ if (textEnd < range.to) {
3773
+ tr.delete(textEnd, range.to);
3774
+ }
3775
+ if (textStart > range.from) {
3776
+ tr.delete(range.from + startSpaces, textStart);
3777
+ }
3778
+ markEnd = range.from + startSpaces + captureGroup.length;
3779
+ tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));
3780
+ tr.removeStoredMark(config.type);
3781
+ }
3782
+ },
3783
+ });
3784
+ }
3785
+
3786
+ /**
3787
+ * Build an input rule that changes the type of a textblock when the
3788
+ * matched text is typed into it. When using a regular expresion you’ll
3789
+ * probably want the regexp to start with `^`, so that the pattern can
3790
+ * only occur at the start of a textblock.
3791
+ */
3792
+ function textblockTypeInputRule(config) {
3793
+ return new InputRule({
3794
+ find: config.find,
3795
+ handler: ({ state, range, match }) => {
3796
+ const $start = state.doc.resolve(range.from);
3797
+ const attributes = callOrReturn(config.getAttributes, undefined, match) || {};
3798
+ if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {
3799
+ return null;
3800
+ }
3801
+ state.tr
3802
+ .delete(range.from, range.to)
3803
+ .setBlockType(range.from, range.from, config.type, attributes);
3804
+ },
3805
+ });
3806
+ }
3807
+
3808
+ /**
3809
+ * Build an input rule that replaces text when the
3810
+ * matched text is typed into it.
3811
+ */
3812
+ function textInputRule(config) {
3813
+ return new InputRule({
3814
+ find: config.find,
3815
+ handler: ({ state, range, match }) => {
3816
+ let insert = config.replace;
3817
+ let start = range.from;
3818
+ const end = range.to;
3819
+ if (match[1]) {
3820
+ const offset = match[0].lastIndexOf(match[1]);
3821
+ insert += match[0].slice(offset + match[1].length);
3822
+ start += offset;
3823
+ const cutOff = start - end;
3824
+ if (cutOff > 0) {
3825
+ insert = match[0].slice(offset - cutOff, offset) + insert;
3826
+ start = end;
3827
+ }
3828
+ }
3829
+ state.tr.insertText(insert, start, end);
3830
+ },
3831
+ });
3832
+ }
3833
+
3834
+ /**
3835
+ * Build an input rule for automatically wrapping a textblock when a
3836
+ * given string is typed. When using a regular expresion you’ll
3837
+ * probably want the regexp to start with `^`, so that the pattern can
3838
+ * only occur at the start of a textblock.
3839
+ *
3840
+ * `type` is the type of node to wrap in.
3841
+ *
3842
+ * By default, if there’s a node with the same type above the newly
3843
+ * wrapped node, the rule will try to join those
3844
+ * two nodes. You can pass a join predicate, which takes a regular
3845
+ * expression match and the node before the wrapped node, and can
3846
+ * return a boolean to indicate whether a join should happen.
3847
+ */
3848
+ function wrappingInputRule(config) {
3849
+ return new InputRule({
3850
+ find: config.find,
3851
+ handler: ({ state, range, match }) => {
3852
+ const attributes = callOrReturn(config.getAttributes, undefined, match) || {};
3853
+ const tr = state.tr.delete(range.from, range.to);
3854
+ const $start = tr.doc.resolve(range.from);
3855
+ const blockRange = $start.blockRange();
3856
+ const wrapping = blockRange && findWrapping(blockRange, config.type, attributes);
3857
+ if (!wrapping) {
3858
+ return null;
3859
+ }
3860
+ tr.wrap(blockRange, wrapping);
3861
+ const before = tr.doc.resolve(range.from - 1).nodeBefore;
3862
+ if (before
3863
+ && before.type === config.type
3864
+ && canJoin(tr.doc, range.from - 1)
3865
+ && (!config.joinPredicate || config.joinPredicate(match, before))) {
3866
+ tr.join(range.from - 1);
3867
+ }
3868
+ },
3869
+ });
3870
+ }
3871
+
3872
+ /**
3873
+ * Build an paste rule that adds a mark when the
3874
+ * matched text is pasted into it.
3875
+ */
3876
+ function markPasteRule(config) {
3877
+ return new PasteRule({
3878
+ find: config.find,
3879
+ handler: ({ state, range, match }) => {
3880
+ const attributes = callOrReturn(config.getAttributes, undefined, match);
3881
+ if (attributes === false || attributes === null) {
3882
+ return;
3883
+ }
3884
+ const { tr } = state;
3885
+ const captureGroup = match[match.length - 1];
3886
+ const fullMatch = match[0];
3887
+ let markEnd = range.to;
3888
+ if (captureGroup) {
3889
+ const startSpaces = fullMatch.search(/\S/);
3890
+ const textStart = range.from + fullMatch.indexOf(captureGroup);
3891
+ const textEnd = textStart + captureGroup.length;
3892
+ const excludedMarks = getMarksBetween(range.from, range.to, state)
3893
+ .filter(item => {
3894
+ // @ts-ignore
3895
+ const excluded = item.mark.type.excluded;
3896
+ return excluded.find(type => type === config.type && type !== item.mark.type);
3897
+ })
3898
+ .filter(item => item.to > textStart);
3899
+ if (excludedMarks.length) {
3900
+ return null;
3901
+ }
3902
+ if (textEnd < range.to) {
3903
+ tr.delete(textEnd, range.to);
3904
+ }
3905
+ if (textStart > range.from) {
3906
+ tr.delete(range.from + startSpaces, textStart);
3907
+ }
3908
+ markEnd = range.from + startSpaces + captureGroup.length;
3909
+ tr.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));
3910
+ tr.removeStoredMark(config.type);
3911
+ }
3912
+ },
3913
+ });
3914
+ }
3915
+
3916
+ /**
3917
+ * Build an paste rule that replaces text when the
3918
+ * matched text is pasted into it.
3919
+ */
3920
+ function textPasteRule(config) {
3921
+ return new PasteRule({
3922
+ find: config.find,
3923
+ handler: ({ state, range, match }) => {
3924
+ let insert = config.replace;
3925
+ let start = range.from;
3926
+ const end = range.to;
3927
+ if (match[1]) {
3928
+ const offset = match[0].lastIndexOf(match[1]);
3929
+ insert += match[0].slice(offset + match[1].length);
3930
+ start += offset;
3931
+ const cutOff = start - end;
3932
+ if (cutOff > 0) {
3933
+ insert = match[0].slice(offset - cutOff, offset) + insert;
3934
+ start = end;
3935
+ }
3936
+ }
3937
+ state.tr.insertText(insert, start, end);
3938
+ },
3939
+ });
3940
+ }
3941
+
3942
+ function findChildren(node, predicate) {
3943
+ const nodesWithPos = [];
3944
+ node.descendants((child, pos) => {
3945
+ if (predicate(child)) {
3946
+ nodesWithPos.push({
3947
+ node: child,
3948
+ pos,
3949
+ });
3950
+ }
3951
+ });
3952
+ return nodesWithPos;
3953
+ }
3954
+
3955
+ /**
3956
+ * Same as `findChildren` but searches only within a `range`.
3957
+ */
3958
+ function findChildrenInRange(node, range, predicate) {
3959
+ const nodesWithPos = [];
3960
+ // if (range.from === range.to) {
3961
+ // const nodeAt = node.nodeAt(range.from)
3962
+ // if (nodeAt) {
3963
+ // nodesWithPos.push({
3964
+ // node: nodeAt,
3965
+ // pos: range.from,
3966
+ // })
3967
+ // }
3968
+ // }
3969
+ node.nodesBetween(range.from, range.to, (child, pos) => {
3970
+ if (predicate(child)) {
3971
+ nodesWithPos.push({
3972
+ node: child,
3973
+ pos,
3974
+ });
3975
+ }
3976
+ });
3977
+ return nodesWithPos;
3978
+ }
3979
+
3980
+ function getSchema(extensions) {
3981
+ const resolvedExtensions = ExtensionManager.resolve(extensions);
3982
+ return getSchemaByResolvedExtensions(resolvedExtensions);
3983
+ }
3984
+
3985
+ function generateHTML(doc, extensions) {
3986
+ const schema = getSchema(extensions);
3987
+ const contentNode = Node$1.fromJSON(schema, doc);
3988
+ return getHTMLFromFragment(contentNode.content, schema);
3989
+ }
3990
+
3991
+ function generateJSON(html, extensions) {
3992
+ const schema = getSchema(extensions);
3993
+ const dom = elementFromString(html);
3994
+ return DOMParser.fromSchema(schema)
3995
+ .parse(dom)
3996
+ .toJSON();
3997
+ }
3998
+
3999
+ function generateText(doc, extensions, options) {
4000
+ const { blockSeparator = '\n\n', textSerializers = {}, } = options || {};
4001
+ const schema = getSchema(extensions);
4002
+ const contentNode = Node$1.fromJSON(schema, doc);
4003
+ return getText(contentNode, {
4004
+ blockSeparator,
4005
+ textSerializers: {
4006
+ ...textSerializers,
4007
+ ...getTextSeralizersFromSchema(schema),
4008
+ },
4009
+ });
4010
+ }
4011
+
4012
+ function getDebugJSON(node, startOffset = 0) {
4013
+ const isTopNode = node.type === node.type.schema.topNodeType;
4014
+ const increment = isTopNode ? 0 : 1;
4015
+ const from = startOffset; // + offset
4016
+ const to = from + node.nodeSize;
4017
+ const marks = node.marks.map(mark => ({
4018
+ type: mark.type.name,
4019
+ attrs: { ...mark.attrs },
4020
+ }));
4021
+ const attrs = { ...node.attrs };
4022
+ const output = {
4023
+ type: node.type.name,
4024
+ from,
4025
+ to,
4026
+ };
4027
+ if (Object.keys(attrs).length) {
4028
+ output.attrs = attrs;
4029
+ }
4030
+ if (marks.length) {
4031
+ output.marks = marks;
4032
+ }
4033
+ if (node.content.childCount) {
4034
+ output.content = [];
4035
+ node.forEach((child, offset) => {
4036
+ var _a;
4037
+ (_a = output.content) === null || _a === void 0 ? void 0 : _a.push(getDebugJSON(child, startOffset + offset + increment));
4038
+ });
4039
+ }
4040
+ if (node.text) {
4041
+ output.text = node.text;
4042
+ }
4043
+ return output;
4044
+ }
4045
+
4046
+ function isNodeSelection(value) {
4047
+ return isObject(value) && value instanceof NodeSelection;
4048
+ }
4049
+
4050
+ function posToDOMRect(view, from, to) {
4051
+ const minPos = 0;
4052
+ const maxPos = view.state.doc.content.size;
4053
+ const resolvedFrom = minMax(from, minPos, maxPos);
4054
+ const resolvedEnd = minMax(to, minPos, maxPos);
4055
+ const start = view.coordsAtPos(resolvedFrom);
4056
+ const end = view.coordsAtPos(resolvedEnd, -1);
4057
+ const top = Math.min(start.top, end.top);
4058
+ const bottom = Math.max(start.bottom, end.bottom);
4059
+ const left = Math.min(start.left, end.left);
4060
+ const right = Math.max(start.right, end.right);
4061
+ const width = right - left;
4062
+ const height = bottom - top;
4063
+ const x = left;
4064
+ const y = top;
4065
+ const data = {
4066
+ top,
4067
+ bottom,
4068
+ left,
4069
+ right,
4070
+ width,
4071
+ height,
4072
+ x,
4073
+ y,
4074
+ };
4075
+ return {
4076
+ ...data,
4077
+ toJSON: () => data,
4078
+ };
4079
+ }
4080
+
4081
+ export { Editor, Extension, InputRule, Mark, Node, NodeView, PasteRule, Tracker, callOrReturn, extensions, findChildren, findChildrenInRange, findParentNode, findParentNodeClosestToPos, generateHTML, generateJSON, generateText, getAttributes, getDebugJSON, getExtensionField, getHTMLFromFragment, getMarkAttributes, getMarkRange, getMarkType, getMarksBetween, getNodeAttributes, getNodeType, getSchema, getText, getTextBetween, inputRulesPlugin, isActive, isList, isMarkActive, isNodeActive, isNodeEmpty, isNodeSelection, isTextSelection, markInputRule, markPasteRule, mergeAttributes, nodeInputRule, pasteRulesPlugin, posToDOMRect, textInputRule, textPasteRule, textblockTypeInputRule, wrappingInputRule };
4082
+ //# sourceMappingURL=tiptap-core.esm.js.map