@tiptap/core 2.0.0-beta.213 → 2.0.0-beta.215

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