@tiptap/core 2.0.0-beta.209 → 2.0.0-beta.210

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