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

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