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