@tiptap/core 2.0.0-beta.193 → 2.0.0-beta.195

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