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