@tiptap/core 2.0.0-beta.99 → 2.0.0-rc.1

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 (297) hide show
  1. package/README.md +3 -3
  2. package/dist/index.cjs +4360 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/{tiptap-core.esm.js → index.js} +2349 -1447
  5. package/dist/index.js.map +1 -0
  6. package/dist/index.umd.js +4358 -0
  7. package/dist/index.umd.js.map +1 -0
  8. package/dist/packages/core/src/CommandManager.d.ts +14 -7
  9. package/dist/packages/core/src/Editor.d.ts +25 -11
  10. package/dist/packages/core/src/EventEmitter.d.ts +8 -4
  11. package/dist/packages/core/src/Extension.d.ts +63 -29
  12. package/dist/packages/core/src/ExtensionManager.d.ts +3 -4
  13. package/dist/packages/core/src/InputRule.d.ts +42 -0
  14. package/dist/packages/core/src/Mark.d.ts +94 -36
  15. package/dist/packages/core/src/Node.d.ts +104 -45
  16. package/dist/packages/core/src/NodeView.d.ts +8 -8
  17. package/dist/packages/core/src/PasteRule.d.ts +42 -0
  18. package/dist/packages/core/src/Tracker.d.ts +1 -1
  19. package/dist/packages/core/src/commands/deleteCurrentNode.d.ts +12 -0
  20. package/dist/packages/core/src/commands/deleteNode.d.ts +1 -1
  21. package/dist/packages/core/src/commands/deleteRange.d.ts +1 -1
  22. package/dist/packages/core/src/commands/extendMarkRange.d.ts +1 -1
  23. package/dist/packages/core/src/commands/focus.d.ts +4 -2
  24. package/dist/packages/core/src/commands/index.d.ts +50 -0
  25. package/dist/packages/core/src/commands/insertContent.d.ts +6 -3
  26. package/dist/packages/core/src/commands/insertContentAt.d.ts +6 -3
  27. package/dist/packages/core/src/commands/join.d.ts +33 -0
  28. package/dist/packages/core/src/commands/lift.d.ts +1 -1
  29. package/dist/packages/core/src/commands/liftListItem.d.ts +1 -1
  30. package/dist/packages/core/src/commands/resetAttributes.d.ts +1 -1
  31. package/dist/packages/core/src/commands/selectTextblockEnd.d.ts +12 -0
  32. package/dist/packages/core/src/commands/selectTextblockStart.d.ts +12 -0
  33. package/dist/packages/core/src/commands/setContent.d.ts +2 -2
  34. package/dist/packages/core/src/commands/setMark.d.ts +1 -1
  35. package/dist/packages/core/src/commands/setNode.d.ts +1 -1
  36. package/dist/packages/core/src/commands/setTextSelection.d.ts +1 -1
  37. package/dist/packages/core/src/commands/sinkListItem.d.ts +1 -1
  38. package/dist/packages/core/src/commands/splitListItem.d.ts +1 -1
  39. package/dist/packages/core/src/commands/toggleList.d.ts +2 -2
  40. package/dist/packages/core/src/commands/toggleMark.d.ts +7 -2
  41. package/dist/packages/core/src/commands/toggleNode.d.ts +1 -1
  42. package/dist/packages/core/src/commands/toggleWrap.d.ts +1 -1
  43. package/dist/packages/core/src/commands/unsetMark.d.ts +7 -2
  44. package/dist/packages/core/src/commands/updateAttributes.d.ts +1 -1
  45. package/dist/packages/core/src/commands/wrapIn.d.ts +1 -1
  46. package/dist/packages/core/src/commands/wrapInList.d.ts +1 -1
  47. package/dist/packages/core/src/extensions/clipboardTextSerializer.d.ts +1 -1
  48. package/dist/packages/core/src/extensions/commands.d.ts +2 -97
  49. package/dist/packages/core/src/extensions/editable.d.ts +1 -1
  50. package/dist/packages/core/src/extensions/focusEvents.d.ts +1 -1
  51. package/dist/packages/core/src/extensions/index.d.ts +1 -0
  52. package/dist/packages/core/src/extensions/keymap.d.ts +1 -1
  53. package/dist/packages/core/src/extensions/tabindex.d.ts +2 -0
  54. package/dist/packages/core/src/helpers/combineTransactionSteps.d.ts +7 -0
  55. package/dist/packages/core/src/helpers/createChainableState.d.ts +5 -0
  56. package/dist/packages/core/src/helpers/createDocument.d.ts +2 -2
  57. package/dist/packages/core/src/helpers/createNodeFromContent.d.ts +2 -2
  58. package/dist/packages/core/src/helpers/defaultBlockAt.d.ts +2 -0
  59. package/dist/packages/core/src/helpers/findChildren.d.ts +3 -3
  60. package/dist/packages/core/src/helpers/findChildrenInRange.d.ts +3 -3
  61. package/dist/packages/core/src/helpers/findParentNode.d.ts +3 -4
  62. package/dist/packages/core/src/helpers/findParentNodeClosestToPos.d.ts +3 -3
  63. package/dist/packages/core/src/helpers/generateHTML.d.ts +1 -1
  64. package/dist/packages/core/src/helpers/generateJSON.d.ts +1 -1
  65. package/dist/packages/core/src/helpers/generateText.d.ts +5 -0
  66. package/dist/packages/core/src/helpers/getAttributes.d.ts +3 -3
  67. package/dist/packages/core/src/helpers/getAttributesFromExtensions.d.ts +2 -2
  68. package/dist/packages/core/src/helpers/getChangedRanges.d.ts +11 -0
  69. package/dist/packages/core/src/helpers/getDebugJSON.d.ts +2 -5
  70. package/dist/packages/core/src/helpers/getExtensionField.d.ts +2 -2
  71. package/dist/packages/core/src/helpers/getHTMLFromFragment.d.ts +2 -2
  72. package/dist/packages/core/src/helpers/getMarkAttributes.d.ts +3 -3
  73. package/dist/packages/core/src/helpers/getMarkRange.d.ts +2 -2
  74. package/dist/packages/core/src/helpers/getMarkType.d.ts +2 -2
  75. package/dist/packages/core/src/helpers/getMarksBetween.d.ts +2 -2
  76. package/dist/packages/core/src/helpers/getNodeAttributes.d.ts +3 -3
  77. package/dist/packages/core/src/helpers/getNodeType.d.ts +2 -2
  78. package/dist/packages/core/src/helpers/getRenderedAttributes.d.ts +2 -2
  79. package/dist/packages/core/src/helpers/getSchema.d.ts +2 -2
  80. package/dist/packages/core/src/helpers/getSchemaByResolvedExtensions.d.ts +2 -2
  81. package/dist/packages/core/src/helpers/getSchemaTypeByName.d.ts +2 -2
  82. package/dist/packages/core/src/helpers/getSchemaTypeNameByName.d.ts +2 -2
  83. package/dist/packages/core/src/helpers/getSplittedAttributes.d.ts +1 -1
  84. package/dist/packages/core/src/helpers/getText.d.ts +6 -0
  85. package/dist/packages/core/src/helpers/getTextBetween.d.ts +6 -0
  86. package/dist/packages/core/src/helpers/getTextContentFromNodes.d.ts +2 -0
  87. package/dist/packages/core/src/helpers/getTextSerializersFromSchema.d.ts +3 -0
  88. package/dist/packages/core/src/helpers/index.d.ts +47 -0
  89. package/dist/packages/core/src/helpers/injectExtensionAttributesToParseRule.d.ts +2 -2
  90. package/dist/packages/core/src/helpers/isActive.d.ts +2 -2
  91. package/dist/packages/core/src/helpers/isExtensionRulesEnabled.d.ts +2 -0
  92. package/dist/packages/core/src/helpers/isList.d.ts +1 -1
  93. package/dist/packages/core/src/helpers/isMarkActive.d.ts +3 -3
  94. package/dist/packages/core/src/helpers/isNodeActive.d.ts +3 -3
  95. package/dist/packages/core/src/helpers/isNodeEmpty.d.ts +2 -2
  96. package/dist/packages/core/src/helpers/isNodeSelection.d.ts +2 -2
  97. package/dist/packages/core/src/helpers/isTextSelection.d.ts +2 -2
  98. package/dist/packages/core/src/helpers/posToDOMRect.d.ts +2 -2
  99. package/dist/packages/core/src/helpers/resolveFocusPosition.d.ts +4 -0
  100. package/dist/packages/core/src/helpers/selectionToInsertionEnd.d.ts +2 -2
  101. package/dist/packages/core/src/helpers/splitExtensions.d.ts +6 -6
  102. package/dist/packages/core/src/index.d.ts +12 -34
  103. package/dist/packages/core/src/inputRules/index.d.ts +5 -0
  104. package/dist/packages/core/src/inputRules/markInputRule.d.ts +12 -3
  105. package/dist/packages/core/src/inputRules/nodeInputRule.d.ts +12 -3
  106. package/dist/packages/core/src/inputRules/textInputRule.d.ts +9 -0
  107. package/dist/packages/core/src/inputRules/textblockTypeInputRule.d.ts +14 -0
  108. package/dist/packages/core/src/inputRules/wrappingInputRule.d.ts +27 -0
  109. package/dist/packages/core/src/pasteRules/index.d.ts +3 -0
  110. package/dist/packages/core/src/pasteRules/markPasteRule.d.ts +12 -3
  111. package/dist/packages/core/src/pasteRules/nodePasteRule.d.ts +12 -0
  112. package/dist/packages/core/src/pasteRules/textPasteRule.d.ts +9 -0
  113. package/dist/packages/core/src/style.d.ts +1 -2
  114. package/dist/packages/core/src/types.d.ts +70 -40
  115. package/dist/packages/core/src/utilities/callOrReturn.d.ts +1 -1
  116. package/dist/packages/core/src/utilities/createStyleTag.d.ts +1 -1
  117. package/dist/packages/core/src/utilities/deleteProps.d.ts +1 -1
  118. package/dist/packages/core/src/utilities/elementFromString.d.ts +1 -1
  119. package/dist/packages/core/src/utilities/escapeForRegEx.d.ts +1 -0
  120. package/dist/packages/core/src/utilities/findDuplicates.d.ts +1 -0
  121. package/dist/packages/core/src/utilities/fromString.d.ts +1 -1
  122. package/dist/packages/core/src/utilities/index.d.ts +20 -0
  123. package/dist/packages/core/src/utilities/isEmptyObject.d.ts +1 -1
  124. package/dist/packages/core/src/utilities/isFunction.d.ts +1 -0
  125. package/dist/packages/core/src/utilities/isMacOS.d.ts +1 -0
  126. package/dist/packages/core/src/utilities/isNumber.d.ts +1 -0
  127. package/dist/packages/core/src/utilities/isPlainObject.d.ts +1 -1
  128. package/dist/packages/core/src/utilities/isRegExp.d.ts +1 -0
  129. package/dist/packages/core/src/utilities/isString.d.ts +1 -0
  130. package/dist/packages/core/src/utilities/isiOS.d.ts +1 -1
  131. package/dist/packages/core/src/utilities/mergeAttributes.d.ts +1 -1
  132. package/dist/packages/core/src/utilities/mergeDeep.d.ts +1 -1
  133. package/dist/packages/core/src/utilities/minMax.d.ts +1 -1
  134. package/dist/packages/core/src/utilities/objectIncludes.d.ts +3 -1
  135. package/dist/packages/core/src/utilities/removeDuplicates.d.ts +8 -0
  136. package/package.json +25 -24
  137. package/src/CommandManager.ts +73 -83
  138. package/src/Editor.ts +101 -53
  139. package/src/EventEmitter.ts +14 -4
  140. package/src/Extension.ts +244 -138
  141. package/src/ExtensionManager.ts +153 -152
  142. package/src/InputRule.ts +260 -0
  143. package/src/Mark.ts +365 -204
  144. package/src/Node.ts +406 -253
  145. package/src/NodeView.ts +59 -38
  146. package/src/PasteRule.ts +240 -0
  147. package/src/Tracker.ts +4 -8
  148. package/src/commands/blur.ts +4 -0
  149. package/src/commands/clearNodes.ts +15 -9
  150. package/src/commands/createParagraphNear.ts +3 -2
  151. package/src/commands/deleteCurrentNode.ts +41 -0
  152. package/src/commands/deleteNode.ts +3 -2
  153. package/src/commands/deleteRange.ts +1 -1
  154. package/src/commands/deleteSelection.ts +3 -2
  155. package/src/commands/exitCode.ts +3 -2
  156. package/src/commands/extendMarkRange.ts +9 -5
  157. package/src/commands/focus.ts +31 -42
  158. package/src/commands/index.ts +50 -0
  159. package/src/commands/insertContent.ts +15 -4
  160. package/src/commands/insertContentAt.ts +71 -14
  161. package/src/commands/join.ts +53 -0
  162. package/src/commands/keyboardShortcut.ts +3 -3
  163. package/src/commands/lift.ts +6 -5
  164. package/src/commands/liftEmptyBlock.ts +2 -1
  165. package/src/commands/liftListItem.ts +5 -4
  166. package/src/commands/newlineInCode.ts +3 -2
  167. package/src/commands/resetAttributes.ts +16 -10
  168. package/src/commands/selectAll.ts +5 -3
  169. package/src/commands/selectNodeBackward.ts +3 -2
  170. package/src/commands/selectNodeForward.ts +3 -2
  171. package/src/commands/selectParentNode.ts +3 -2
  172. package/src/commands/selectTextblockEnd.ts +20 -0
  173. package/src/commands/selectTextblockStart.ts +20 -0
  174. package/src/commands/setContent.ts +6 -9
  175. package/src/commands/setMark.ts +66 -13
  176. package/src/commands/setNode.ts +30 -6
  177. package/src/commands/setNodeSelection.ts +6 -7
  178. package/src/commands/setTextSelection.ts +8 -9
  179. package/src/commands/sinkListItem.ts +5 -4
  180. package/src/commands/splitBlock.ts +23 -38
  181. package/src/commands/splitListItem.ts +30 -27
  182. package/src/commands/toggleList.ts +108 -19
  183. package/src/commands/toggleMark.ts +17 -6
  184. package/src/commands/toggleNode.ts +9 -4
  185. package/src/commands/toggleWrap.ts +8 -8
  186. package/src/commands/undoInputRule.ts +31 -2
  187. package/src/commands/unsetAllMarks.ts +4 -8
  188. package/src/commands/unsetMark.ts +34 -21
  189. package/src/commands/updateAttributes.ts +18 -12
  190. package/src/commands/wrapIn.ts +5 -10
  191. package/src/commands/wrapInList.ts +5 -4
  192. package/src/extensions/clipboardTextSerializer.ts +15 -36
  193. package/src/extensions/commands.ts +3 -144
  194. package/src/extensions/editable.ts +2 -1
  195. package/src/extensions/focusEvents.ts +4 -6
  196. package/src/extensions/index.ts +1 -0
  197. package/src/extensions/keymap.ts +111 -13
  198. package/src/extensions/tabindex.ts +18 -0
  199. package/src/helpers/combineTransactionSteps.ts +21 -0
  200. package/src/helpers/createChainableState.ts +38 -0
  201. package/src/helpers/createDocument.ts +4 -3
  202. package/src/helpers/createNodeFromContent.ts +10 -15
  203. package/src/helpers/defaultBlockAt.ts +13 -0
  204. package/src/helpers/findChildren.ts +4 -3
  205. package/src/helpers/findChildrenInRange.ts +8 -3
  206. package/src/helpers/findParentNode.ts +4 -3
  207. package/src/helpers/findParentNodeClosestToPos.ts +13 -7
  208. package/src/helpers/generateHTML.ts +6 -5
  209. package/src/helpers/generateJSON.ts +6 -7
  210. package/src/helpers/generateText.ts +27 -0
  211. package/src/helpers/getAttributes.ts +8 -9
  212. package/src/helpers/getAttributesFromExtensions.ts +25 -12
  213. package/src/helpers/getChangedRanges.ts +83 -0
  214. package/src/helpers/getDebugJSON.ts +42 -38
  215. package/src/helpers/getExtensionField.ts +3 -3
  216. package/src/helpers/getHTMLFromFragment.ts +5 -6
  217. package/src/helpers/getMarkAttributes.ts +18 -10
  218. package/src/helpers/getMarkRange.ts +13 -8
  219. package/src/helpers/getMarkType.ts +5 -3
  220. package/src/helpers/getMarksBetween.ts +34 -10
  221. package/src/helpers/getNodeAttributes.ts +14 -12
  222. package/src/helpers/getNodeType.ts +5 -3
  223. package/src/helpers/getRenderedAttributes.ts +8 -6
  224. package/src/helpers/getSchema.ts +5 -4
  225. package/src/helpers/getSchemaByResolvedExtensions.ts +165 -111
  226. package/src/helpers/getSchemaTypeByName.ts +3 -11
  227. package/src/helpers/getSchemaTypeNameByName.ts +2 -2
  228. package/src/helpers/getSplittedAttributes.ts +1 -1
  229. package/src/helpers/getText.ts +19 -0
  230. package/src/helpers/getTextBetween.ts +46 -0
  231. package/src/helpers/getTextContentFromNodes.ts +26 -0
  232. package/src/helpers/getTextSerializersFromSchema.ts +11 -0
  233. package/src/helpers/index.ts +47 -0
  234. package/src/helpers/injectExtensionAttributesToParseRule.ts +22 -23
  235. package/src/helpers/isActive.ts +10 -5
  236. package/src/helpers/isExtensionRulesEnabled.ts +15 -0
  237. package/src/helpers/isList.ts +6 -5
  238. package/src/helpers/isMarkActive.ts +32 -35
  239. package/src/helpers/isNodeActive.ts +27 -37
  240. package/src/helpers/isNodeEmpty.ts +2 -2
  241. package/src/helpers/isNodeSelection.ts +3 -4
  242. package/src/helpers/isTextSelection.ts +3 -4
  243. package/src/helpers/posToDOMRect.ts +10 -4
  244. package/src/helpers/resolveFocusPosition.ts +42 -0
  245. package/src/helpers/selectionToInsertionEnd.ts +3 -3
  246. package/src/helpers/splitExtensions.ts +3 -3
  247. package/src/index.ts +12 -37
  248. package/src/inputRules/index.ts +5 -0
  249. package/src/inputRules/markInputRule.ts +59 -40
  250. package/src/inputRules/nodeInputRule.ts +45 -12
  251. package/src/inputRules/textInputRule.ts +35 -0
  252. package/src/inputRules/textblockTypeInputRule.ts +37 -0
  253. package/src/inputRules/wrappingInputRule.ts +84 -0
  254. package/src/pasteRules/index.ts +3 -0
  255. package/src/pasteRules/markPasteRule.ts +49 -56
  256. package/src/pasteRules/nodePasteRule.ts +37 -0
  257. package/src/pasteRules/textPasteRule.ts +35 -0
  258. package/src/style.ts +12 -3
  259. package/src/types.ts +140 -106
  260. package/src/utilities/callOrReturn.ts +3 -2
  261. package/src/utilities/createStyleTag.ts +8 -4
  262. package/src/utilities/deleteProps.ts +1 -1
  263. package/src/utilities/elementFromString.ts +1 -1
  264. package/src/utilities/escapeForRegEx.ts +4 -0
  265. package/src/utilities/findDuplicates.ts +5 -0
  266. package/src/utilities/fromString.ts +2 -2
  267. package/src/utilities/index.ts +20 -0
  268. package/src/utilities/isEmptyObject.ts +2 -2
  269. package/src/utilities/isFunction.ts +3 -0
  270. package/src/utilities/isMacOS.ts +5 -0
  271. package/src/utilities/isNumber.ts +3 -0
  272. package/src/utilities/isPlainObject.ts +8 -5
  273. package/src/utilities/isRegExp.ts +3 -0
  274. package/src/utilities/isString.ts +3 -0
  275. package/src/utilities/isiOS.ts +1 -1
  276. package/src/utilities/mergeAttributes.ts +2 -1
  277. package/src/utilities/mergeDeep.ts +2 -2
  278. package/src/utilities/minMax.ts +1 -1
  279. package/src/utilities/objectIncludes.ts +18 -4
  280. package/src/utilities/removeDuplicates.ts +15 -0
  281. package/CHANGELOG.md +0 -1190
  282. package/LICENSE.md +0 -21
  283. package/dist/packages/core/src/commands/joinBackward.d.ts +0 -12
  284. package/dist/packages/core/src/commands/joinForward.d.ts +0 -12
  285. package/dist/packages/core/src/utilities/isClass.d.ts +0 -1
  286. package/dist/packages/core/src/utilities/isObject.d.ts +0 -1
  287. package/dist/packages/core/src/utilities/removeElement.d.ts +0 -1
  288. package/dist/tiptap-core.cjs.js +0 -3408
  289. package/dist/tiptap-core.cjs.js.map +0 -1
  290. package/dist/tiptap-core.esm.js.map +0 -1
  291. package/dist/tiptap-core.umd.js +0 -3405
  292. package/dist/tiptap-core.umd.js.map +0 -1
  293. package/src/commands/joinBackward.ts +0 -17
  294. package/src/commands/joinForward.ts +0 -17
  295. package/src/utilities/isClass.ts +0 -7
  296. package/src/utilities/isObject.ts +0 -10
  297. package/src/utilities/removeElement.ts +0 -5
@@ -1,3408 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var prosemirrorState = require('prosemirror-state');
6
- var prosemirrorView = require('prosemirror-view');
7
- var prosemirrorModel = require('prosemirror-model');
8
- var prosemirrorKeymap = require('prosemirror-keymap');
9
- var prosemirrorInputrules = require('prosemirror-inputrules');
10
- var prosemirrorTransform = require('prosemirror-transform');
11
- var prosemirrorCommands = require('prosemirror-commands');
12
- var prosemirrorSchemaList = require('prosemirror-schema-list');
13
-
14
- function getSchemaTypeNameByName(name, schema) {
15
- if (schema.nodes[name]) {
16
- return 'node';
17
- }
18
- if (schema.marks[name]) {
19
- return 'mark';
20
- }
21
- return null;
22
- }
23
-
24
- function getNodeType(nameOrType, schema) {
25
- if (typeof nameOrType === 'string') {
26
- if (!schema.nodes[nameOrType]) {
27
- throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
28
- }
29
- return schema.nodes[nameOrType];
30
- }
31
- return nameOrType;
32
- }
33
-
34
- function getNodeAttributes(state, typeOrName) {
35
- const type = getNodeType(typeOrName, state.schema);
36
- const { from, to } = state.selection;
37
- let nodes = [];
38
- state.doc.nodesBetween(from, to, node => {
39
- nodes = [...nodes, node];
40
- });
41
- const node = nodes
42
- .reverse()
43
- .find(nodeItem => nodeItem.type.name === type.name);
44
- if (node) {
45
- return { ...node.attrs };
46
- }
47
- return {};
48
- }
49
-
50
- function getMarkType(nameOrType, schema) {
51
- if (typeof nameOrType === 'string') {
52
- if (!schema.marks[nameOrType]) {
53
- throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
54
- }
55
- return schema.marks[nameOrType];
56
- }
57
- return nameOrType;
58
- }
59
-
60
- function getMarkAttributes(state, typeOrName) {
61
- const type = getMarkType(typeOrName, state.schema);
62
- const { from, to, empty } = state.selection;
63
- let marks = [];
64
- if (empty) {
65
- marks = state.selection.$head.marks();
66
- }
67
- else {
68
- state.doc.nodesBetween(from, to, node => {
69
- marks = [...marks, ...node.marks];
70
- });
71
- }
72
- const mark = marks.find(markItem => markItem.type.name === type.name);
73
- if (mark) {
74
- return { ...mark.attrs };
75
- }
76
- return {};
77
- }
78
-
79
- function getAttributes(state, typeOrName) {
80
- const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string'
81
- ? typeOrName
82
- : typeOrName.name, state.schema);
83
- if (schemaType === 'node') {
84
- return getNodeAttributes(state, typeOrName);
85
- }
86
- if (schemaType === 'mark') {
87
- return getMarkAttributes(state, typeOrName);
88
- }
89
- return {};
90
- }
91
-
92
- /**
93
- * Check if object1 includes object2
94
- * @param object1 Object
95
- * @param object2 Object
96
- */
97
- function objectIncludes(object1, object2) {
98
- const keys = Object.keys(object2);
99
- if (!keys.length) {
100
- return true;
101
- }
102
- return !!keys
103
- .filter(key => object2[key] === object1[key])
104
- .length;
105
- }
106
-
107
- function isNodeActive(state, typeOrName, attributes = {}) {
108
- const { from, to, empty } = state.selection;
109
- const type = typeOrName
110
- ? getNodeType(typeOrName, state.schema)
111
- : null;
112
- let nodeRanges = [];
113
- state.doc.nodesBetween(from, to, (node, pos) => {
114
- if (!node.isText) {
115
- const relativeFrom = Math.max(from, pos);
116
- const relativeTo = Math.min(to, pos + node.nodeSize);
117
- nodeRanges = [...nodeRanges, {
118
- node,
119
- from: relativeFrom,
120
- to: relativeTo,
121
- }];
122
- }
123
- });
124
- if (empty) {
125
- return !!nodeRanges
126
- .filter(nodeRange => {
127
- if (!type) {
128
- return true;
129
- }
130
- return type.name === nodeRange.node.type.name;
131
- })
132
- .find(nodeRange => objectIncludes(nodeRange.node.attrs, attributes));
133
- }
134
- const selectionRange = to - from;
135
- const range = nodeRanges
136
- .filter(nodeRange => {
137
- if (!type) {
138
- return true;
139
- }
140
- return type.name === nodeRange.node.type.name;
141
- })
142
- .filter(nodeRange => objectIncludes(nodeRange.node.attrs, attributes))
143
- .reduce((sum, nodeRange) => {
144
- const size = nodeRange.to - nodeRange.from;
145
- return sum + size;
146
- }, 0);
147
- return range >= selectionRange;
148
- }
149
-
150
- function isMarkActive(state, typeOrName, attributes = {}) {
151
- const { from, to, empty } = state.selection;
152
- const type = typeOrName
153
- ? getMarkType(typeOrName, state.schema)
154
- : null;
155
- if (empty) {
156
- return !!(state.storedMarks || state.selection.$from.marks())
157
- .filter(mark => {
158
- if (!type) {
159
- return true;
160
- }
161
- return type.name === mark.type.name;
162
- })
163
- .find(mark => objectIncludes(mark.attrs, attributes));
164
- }
165
- let selectionRange = 0;
166
- let markRanges = [];
167
- state.doc.nodesBetween(from, to, (node, pos) => {
168
- if (node.isText) {
169
- const relativeFrom = Math.max(from, pos);
170
- const relativeTo = Math.min(to, pos + node.nodeSize);
171
- const range = relativeTo - relativeFrom;
172
- selectionRange += range;
173
- markRanges = [...markRanges, ...node.marks.map(mark => ({
174
- mark,
175
- from: relativeFrom,
176
- to: relativeTo,
177
- }))];
178
- }
179
- });
180
- if (selectionRange === 0) {
181
- return false;
182
- }
183
- // calculate range of matched mark
184
- const matchedRange = markRanges
185
- .filter(markRange => {
186
- if (!type) {
187
- return true;
188
- }
189
- return type.name === markRange.mark.type.name;
190
- })
191
- .filter(markRange => objectIncludes(markRange.mark.attrs, attributes))
192
- .reduce((sum, markRange) => {
193
- const size = markRange.to - markRange.from;
194
- return sum + size;
195
- }, 0);
196
- // calculate range of marks that excludes the searched mark
197
- // for example `code` doesn’t allow any other marks
198
- const excludedRange = markRanges
199
- .filter(markRange => {
200
- if (!type) {
201
- return true;
202
- }
203
- return markRange.mark.type !== type
204
- && markRange.mark.type.excludes(type);
205
- })
206
- .reduce((sum, markRange) => {
207
- const size = markRange.to - markRange.from;
208
- return sum + size;
209
- }, 0);
210
- // we only include the result of `excludedRange`
211
- // if there is a match at all
212
- const range = matchedRange > 0
213
- ? matchedRange + excludedRange
214
- : matchedRange;
215
- return range >= selectionRange;
216
- }
217
-
218
- function isActive(state, name, attributes = {}) {
219
- if (!name) {
220
- return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes);
221
- }
222
- const schemaType = getSchemaTypeNameByName(name, state.schema);
223
- if (schemaType === 'node') {
224
- return isNodeActive(state, name, attributes);
225
- }
226
- if (schemaType === 'mark') {
227
- return isMarkActive(state, name, attributes);
228
- }
229
- return false;
230
- }
231
-
232
- function removeElement(element) {
233
- if (element && element.parentNode) {
234
- element.parentNode.removeChild(element);
235
- }
236
- }
237
-
238
- function elementFromString(value) {
239
- // add a wrapper to preserve leading and trailing whitespace
240
- const wrappedValue = `<body>${value}</body>`;
241
- return new window.DOMParser().parseFromString(wrappedValue, 'text/html').body;
242
- }
243
-
244
- function createNodeFromContent(content, schema, options) {
245
- options = {
246
- slice: true,
247
- parseOptions: {},
248
- ...options,
249
- };
250
- if (typeof content === 'object' && content !== null) {
251
- try {
252
- if (Array.isArray(content)) {
253
- return prosemirrorModel.Fragment.fromArray(content.map(item => schema.nodeFromJSON(item)));
254
- }
255
- return schema.nodeFromJSON(content);
256
- }
257
- catch (error) {
258
- console.warn('[tiptap warn]: Invalid content.', 'Passed value:', content, 'Error:', error);
259
- return createNodeFromContent('', schema, options);
260
- }
261
- }
262
- if (typeof content === 'string') {
263
- const parser = prosemirrorModel.DOMParser.fromSchema(schema);
264
- return options.slice
265
- ? parser.parseSlice(elementFromString(content), options.parseOptions).content
266
- : parser.parse(elementFromString(content), options.parseOptions);
267
- }
268
- return createNodeFromContent('', schema, options);
269
- }
270
-
271
- function createDocument(content, schema, parseOptions = {}) {
272
- return createNodeFromContent(content, schema, { slice: false, parseOptions });
273
- }
274
-
275
- function getHTMLFromFragment(doc, schema) {
276
- const fragment = prosemirrorModel.DOMSerializer
277
- .fromSchema(schema)
278
- .serializeFragment(doc.content);
279
- const temporaryDocument = document.implementation.createHTMLDocument();
280
- const container = temporaryDocument.createElement('div');
281
- container.appendChild(fragment);
282
- return container.innerHTML;
283
- }
284
-
285
- function isNodeEmpty(node) {
286
- var _a;
287
- const defaultContent = (_a = node.type.createAndFill()) === null || _a === void 0 ? void 0 : _a.toJSON();
288
- const content = node.toJSON();
289
- return JSON.stringify(defaultContent) === JSON.stringify(content);
290
- }
291
-
292
- function createStyleTag(style) {
293
- const tipTapStyleTag = document.querySelector('style[data-tiptap-style]');
294
- if (tipTapStyleTag !== null) {
295
- return tipTapStyleTag;
296
- }
297
- const styleNode = document.createElement('style');
298
- styleNode.setAttribute('data-tiptap-style', '');
299
- styleNode.innerHTML = style;
300
- document.getElementsByTagName('head')[0].appendChild(styleNode);
301
- return styleNode;
302
- }
303
-
304
- class CommandManager {
305
- constructor(editor, commands) {
306
- this.editor = editor;
307
- this.commands = commands;
308
- }
309
- createCommands() {
310
- const { commands, editor } = this;
311
- const { state, view } = editor;
312
- const { tr } = state;
313
- const props = this.buildProps(tr);
314
- return Object.fromEntries(Object
315
- .entries(commands)
316
- .map(([name, command]) => {
317
- const method = (...args) => {
318
- const callback = command(...args)(props);
319
- if (!tr.getMeta('preventDispatch')) {
320
- view.dispatch(tr);
321
- }
322
- return callback;
323
- };
324
- return [name, method];
325
- }));
326
- }
327
- createChain(startTr, shouldDispatch = true) {
328
- const { commands, editor } = this;
329
- const { state, view } = editor;
330
- const callbacks = [];
331
- const hasStartTransaction = !!startTr;
332
- const tr = startTr || state.tr;
333
- const run = () => {
334
- if (!hasStartTransaction && shouldDispatch && !tr.getMeta('preventDispatch')) {
335
- view.dispatch(tr);
336
- }
337
- return callbacks.every(callback => callback === true);
338
- };
339
- const chain = {
340
- ...Object.fromEntries(Object.entries(commands).map(([name, command]) => {
341
- const chainedCommand = (...args) => {
342
- const props = this.buildProps(tr, shouldDispatch);
343
- const callback = command(...args)(props);
344
- callbacks.push(callback);
345
- return chain;
346
- };
347
- return [name, chainedCommand];
348
- })),
349
- run,
350
- };
351
- return chain;
352
- }
353
- createCan(startTr) {
354
- const { commands, editor } = this;
355
- const { state } = editor;
356
- const dispatch = undefined;
357
- const tr = startTr || state.tr;
358
- const props = this.buildProps(tr, dispatch);
359
- const formattedCommands = Object.fromEntries(Object
360
- .entries(commands)
361
- .map(([name, command]) => {
362
- return [name, (...args) => command(...args)({ ...props, dispatch })];
363
- }));
364
- return {
365
- ...formattedCommands,
366
- chain: () => this.createChain(tr, dispatch),
367
- };
368
- }
369
- buildProps(tr, shouldDispatch = true) {
370
- const { editor, commands } = this;
371
- const { state, view } = editor;
372
- if (state.storedMarks) {
373
- tr.setStoredMarks(state.storedMarks);
374
- }
375
- const props = {
376
- tr,
377
- editor,
378
- view,
379
- state: this.chainableState(tr, state),
380
- dispatch: shouldDispatch
381
- ? () => undefined
382
- : undefined,
383
- chain: () => this.createChain(tr),
384
- can: () => this.createCan(tr),
385
- get commands() {
386
- return Object.fromEntries(Object
387
- .entries(commands)
388
- .map(([name, command]) => {
389
- return [name, (...args) => command(...args)(props)];
390
- }));
391
- },
392
- };
393
- return props;
394
- }
395
- chainableState(tr, state) {
396
- let { selection } = tr;
397
- let { doc } = tr;
398
- let { storedMarks } = tr;
399
- return {
400
- ...state,
401
- schema: state.schema,
402
- plugins: state.plugins,
403
- apply: state.apply.bind(state),
404
- applyTransaction: state.applyTransaction.bind(state),
405
- reconfigure: state.reconfigure.bind(state),
406
- toJSON: state.toJSON.bind(state),
407
- get storedMarks() {
408
- return storedMarks;
409
- },
410
- get selection() {
411
- return selection;
412
- },
413
- get doc() {
414
- return doc;
415
- },
416
- get tr() {
417
- selection = tr.selection;
418
- doc = tr.doc;
419
- storedMarks = tr.storedMarks;
420
- return tr;
421
- },
422
- };
423
- }
424
- }
425
-
426
- function getExtensionField(extension, field, context = {}) {
427
- if (extension.config[field] === undefined && extension.parent) {
428
- return getExtensionField(extension.parent, field, context);
429
- }
430
- if (typeof extension.config[field] === 'function') {
431
- const value = extension.config[field].bind({
432
- ...context,
433
- parent: extension.parent
434
- ? getExtensionField(extension.parent, field, context)
435
- : null,
436
- });
437
- return value;
438
- }
439
- return extension.config[field];
440
- }
441
-
442
- function splitExtensions(extensions) {
443
- const baseExtensions = extensions.filter(extension => extension.type === 'extension');
444
- const nodeExtensions = extensions.filter(extension => extension.type === 'node');
445
- const markExtensions = extensions.filter(extension => extension.type === 'mark');
446
- return {
447
- baseExtensions,
448
- nodeExtensions,
449
- markExtensions,
450
- };
451
- }
452
-
453
- /**
454
- * Get a list of all extension attributes defined in `addAttribute` and `addGlobalAttribute`.
455
- * @param extensions List of extensions
456
- */
457
- function getAttributesFromExtensions(extensions) {
458
- const extensionAttributes = [];
459
- const { nodeExtensions, markExtensions } = splitExtensions(extensions);
460
- const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions];
461
- const defaultAttribute = {
462
- default: null,
463
- rendered: true,
464
- renderHTML: null,
465
- parseHTML: null,
466
- keepOnSplit: true,
467
- };
468
- extensions.forEach(extension => {
469
- const context = {
470
- name: extension.name,
471
- options: extension.options,
472
- };
473
- const addGlobalAttributes = getExtensionField(extension, 'addGlobalAttributes', context);
474
- if (!addGlobalAttributes) {
475
- return;
476
- }
477
- // TODO: remove `as GlobalAttributes`
478
- const globalAttributes = addGlobalAttributes();
479
- globalAttributes.forEach(globalAttribute => {
480
- globalAttribute.types.forEach(type => {
481
- Object
482
- .entries(globalAttribute.attributes)
483
- .forEach(([name, attribute]) => {
484
- extensionAttributes.push({
485
- type,
486
- name,
487
- attribute: {
488
- ...defaultAttribute,
489
- ...attribute,
490
- },
491
- });
492
- });
493
- });
494
- });
495
- });
496
- nodeAndMarkExtensions.forEach(extension => {
497
- const context = {
498
- name: extension.name,
499
- options: extension.options,
500
- };
501
- const addAttributes = getExtensionField(extension, 'addAttributes', context);
502
- if (!addAttributes) {
503
- return;
504
- }
505
- // TODO: remove `as Attributes`
506
- const attributes = addAttributes();
507
- Object
508
- .entries(attributes)
509
- .forEach(([name, attribute]) => {
510
- extensionAttributes.push({
511
- type: extension.name,
512
- name,
513
- attribute: {
514
- ...defaultAttribute,
515
- ...attribute,
516
- },
517
- });
518
- });
519
- });
520
- return extensionAttributes;
521
- }
522
-
523
- function mergeAttributes(...objects) {
524
- return objects
525
- .filter(item => !!item)
526
- .reduce((items, item) => {
527
- const mergedAttributes = { ...items };
528
- Object.entries(item).forEach(([key, value]) => {
529
- const exists = mergedAttributes[key];
530
- if (!exists) {
531
- mergedAttributes[key] = value;
532
- return;
533
- }
534
- if (key === 'class') {
535
- mergedAttributes[key] = [mergedAttributes[key], value].join(' ');
536
- }
537
- else if (key === 'style') {
538
- mergedAttributes[key] = [mergedAttributes[key], value].join('; ');
539
- }
540
- else {
541
- mergedAttributes[key] = value;
542
- }
543
- });
544
- return mergedAttributes;
545
- }, {});
546
- }
547
-
548
- function getRenderedAttributes(nodeOrMark, extensionAttributes) {
549
- return extensionAttributes
550
- .filter(item => item.attribute.rendered)
551
- .map(item => {
552
- if (!item.attribute.renderHTML) {
553
- return {
554
- [item.name]: nodeOrMark.attrs[item.name],
555
- };
556
- }
557
- return item.attribute.renderHTML(nodeOrMark.attrs) || {};
558
- })
559
- .reduce((attributes, attribute) => {
560
- return mergeAttributes(attributes, attribute);
561
- }, {});
562
- }
563
-
564
- function isEmptyObject(object = {}) {
565
- return Object.keys(object).length === 0 && object.constructor === Object;
566
- }
567
-
568
- function fromString(value) {
569
- if (typeof value !== 'string') {
570
- return value;
571
- }
572
- if (value.match(/^\d*(\.\d+)?$/)) {
573
- return Number(value);
574
- }
575
- if (value === 'true') {
576
- return true;
577
- }
578
- if (value === 'false') {
579
- return false;
580
- }
581
- return value;
582
- }
583
-
584
- /**
585
- * This function merges extension attributes into parserule attributes (`attrs` or `getAttrs`).
586
- * Cancels when `getAttrs` returned `false`.
587
- * @param parseRule ProseMirror ParseRule
588
- * @param extensionAttributes List of attributes to inject
589
- */
590
- function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) {
591
- if (parseRule.style) {
592
- return parseRule;
593
- }
594
- return {
595
- ...parseRule,
596
- getAttrs: node => {
597
- const oldAttributes = parseRule.getAttrs
598
- ? parseRule.getAttrs(node)
599
- : parseRule.attrs;
600
- if (oldAttributes === false) {
601
- return false;
602
- }
603
- const newAttributes = extensionAttributes
604
- .filter(item => item.attribute.rendered)
605
- .reduce((items, item) => {
606
- const attributes = item.attribute.parseHTML
607
- ? item.attribute.parseHTML(node) || {}
608
- : {
609
- [item.name]: fromString(node.getAttribute(item.name)),
610
- };
611
- const filteredAttributes = Object.fromEntries(Object.entries(attributes)
612
- .filter(([, value]) => value !== undefined && value !== null));
613
- return {
614
- ...items,
615
- ...filteredAttributes,
616
- };
617
- }, {});
618
- return { ...oldAttributes, ...newAttributes };
619
- },
620
- };
621
- }
622
-
623
- /**
624
- * Optionally calls `value` as a function.
625
- * Otherwise it is returned directly.
626
- * @param value Function or any value.
627
- * @param context Optional context to bind to function.
628
- * @param props Optional props to pass to function.
629
- */
630
- function callOrReturn(value, context = undefined, ...props) {
631
- if (typeof value === 'function') {
632
- if (context) {
633
- return value.bind(context)(...props);
634
- }
635
- return value(...props);
636
- }
637
- return value;
638
- }
639
-
640
- function cleanUpSchemaItem(data) {
641
- return Object.fromEntries(Object.entries(data).filter(([key, value]) => {
642
- if (key === 'attrs' && isEmptyObject(value)) {
643
- return false;
644
- }
645
- return value !== null && value !== undefined;
646
- }));
647
- }
648
- function getSchemaByResolvedExtensions(extensions) {
649
- var _a;
650
- const allAttributes = getAttributesFromExtensions(extensions);
651
- const { nodeExtensions, markExtensions } = splitExtensions(extensions);
652
- const topNode = (_a = nodeExtensions.find(extension => getExtensionField(extension, 'topNode'))) === null || _a === void 0 ? void 0 : _a.name;
653
- const nodes = Object.fromEntries(nodeExtensions.map(extension => {
654
- const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name);
655
- const context = {
656
- name: extension.name,
657
- options: extension.options,
658
- };
659
- const extraNodeFields = extensions.reduce((fields, e) => {
660
- const extendNodeSchema = getExtensionField(e, 'extendNodeSchema', context);
661
- return {
662
- ...fields,
663
- ...(extendNodeSchema ? extendNodeSchema(extension) : {}),
664
- };
665
- }, {});
666
- const schema = cleanUpSchemaItem({
667
- ...extraNodeFields,
668
- content: callOrReturn(getExtensionField(extension, 'content', context)),
669
- marks: callOrReturn(getExtensionField(extension, 'marks', context)),
670
- group: callOrReturn(getExtensionField(extension, 'group', context)),
671
- inline: callOrReturn(getExtensionField(extension, 'inline', context)),
672
- atom: callOrReturn(getExtensionField(extension, 'atom', context)),
673
- selectable: callOrReturn(getExtensionField(extension, 'selectable', context)),
674
- draggable: callOrReturn(getExtensionField(extension, 'draggable', context)),
675
- code: callOrReturn(getExtensionField(extension, 'code', context)),
676
- defining: callOrReturn(getExtensionField(extension, 'defining', context)),
677
- isolating: callOrReturn(getExtensionField(extension, 'isolating', context)),
678
- attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {
679
- var _a;
680
- return [extensionAttribute.name, { default: (_a = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a === void 0 ? void 0 : _a.default }];
681
- })),
682
- });
683
- const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context));
684
- if (parseHTML) {
685
- schema.parseDOM = parseHTML
686
- .map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));
687
- }
688
- const renderHTML = getExtensionField(extension, 'renderHTML', context);
689
- if (renderHTML) {
690
- schema.toDOM = node => renderHTML({
691
- node,
692
- HTMLAttributes: getRenderedAttributes(node, extensionAttributes),
693
- });
694
- }
695
- return [extension.name, schema];
696
- }));
697
- const marks = Object.fromEntries(markExtensions.map(extension => {
698
- const extensionAttributes = allAttributes.filter(attribute => attribute.type === extension.name);
699
- const context = {
700
- name: extension.name,
701
- options: extension.options,
702
- };
703
- const extraMarkFields = extensions.reduce((fields, e) => {
704
- const extendMarkSchema = getExtensionField(e, 'extendMarkSchema', context);
705
- return {
706
- ...fields,
707
- ...(extendMarkSchema ? extendMarkSchema(extension) : {}),
708
- };
709
- }, {});
710
- const schema = cleanUpSchemaItem({
711
- ...extraMarkFields,
712
- inclusive: callOrReturn(getExtensionField(extension, 'inclusive', context)),
713
- excludes: callOrReturn(getExtensionField(extension, 'excludes', context)),
714
- group: callOrReturn(getExtensionField(extension, 'group', context)),
715
- spanning: callOrReturn(getExtensionField(extension, 'spanning', context)),
716
- attrs: Object.fromEntries(extensionAttributes.map(extensionAttribute => {
717
- var _a;
718
- return [extensionAttribute.name, { default: (_a = extensionAttribute === null || extensionAttribute === void 0 ? void 0 : extensionAttribute.attribute) === null || _a === void 0 ? void 0 : _a.default }];
719
- })),
720
- });
721
- const parseHTML = callOrReturn(getExtensionField(extension, 'parseHTML', context));
722
- if (parseHTML) {
723
- schema.parseDOM = parseHTML
724
- .map(parseRule => injectExtensionAttributesToParseRule(parseRule, extensionAttributes));
725
- }
726
- const renderHTML = getExtensionField(extension, 'renderHTML', context);
727
- if (renderHTML) {
728
- schema.toDOM = mark => renderHTML({
729
- mark,
730
- HTMLAttributes: getRenderedAttributes(mark, extensionAttributes),
731
- });
732
- }
733
- return [extension.name, schema];
734
- }));
735
- return new prosemirrorModel.Schema({
736
- topNode,
737
- nodes,
738
- marks,
739
- });
740
- }
741
-
742
- function getSchemaTypeByName(name, schema) {
743
- if (schema.nodes[name]) {
744
- return schema.nodes[name];
745
- }
746
- if (schema.marks[name]) {
747
- return schema.marks[name];
748
- }
749
- return null;
750
- }
751
-
752
- class ExtensionManager {
753
- constructor(extensions, editor) {
754
- this.splittableMarks = [];
755
- this.editor = editor;
756
- this.extensions = ExtensionManager.resolve(extensions);
757
- this.schema = getSchemaByResolvedExtensions(this.extensions);
758
- this.extensions.forEach(extension => {
759
- var _a;
760
- const context = {
761
- name: extension.name,
762
- options: extension.options,
763
- editor: this.editor,
764
- type: getSchemaTypeByName(extension.name, this.schema),
765
- };
766
- if (extension.type === 'mark') {
767
- const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, 'keepOnSplit', context))) !== null && _a !== void 0 ? _a : true;
768
- if (keepOnSplit) {
769
- this.splittableMarks.push(extension.name);
770
- }
771
- }
772
- const onBeforeCreate = getExtensionField(extension, 'onBeforeCreate', context);
773
- if (onBeforeCreate) {
774
- this.editor.on('beforeCreate', onBeforeCreate);
775
- }
776
- const onCreate = getExtensionField(extension, 'onCreate', context);
777
- if (onCreate) {
778
- this.editor.on('create', onCreate);
779
- }
780
- const onUpdate = getExtensionField(extension, 'onUpdate', context);
781
- if (onUpdate) {
782
- this.editor.on('update', onUpdate);
783
- }
784
- const onSelectionUpdate = getExtensionField(extension, 'onSelectionUpdate', context);
785
- if (onSelectionUpdate) {
786
- this.editor.on('selectionUpdate', onSelectionUpdate);
787
- }
788
- const onTransaction = getExtensionField(extension, 'onTransaction', context);
789
- if (onTransaction) {
790
- this.editor.on('transaction', onTransaction);
791
- }
792
- const onFocus = getExtensionField(extension, 'onFocus', context);
793
- if (onFocus) {
794
- this.editor.on('focus', onFocus);
795
- }
796
- const onBlur = getExtensionField(extension, 'onBlur', context);
797
- if (onBlur) {
798
- this.editor.on('blur', onBlur);
799
- }
800
- const onDestroy = getExtensionField(extension, 'onDestroy', context);
801
- if (onDestroy) {
802
- this.editor.on('destroy', onDestroy);
803
- }
804
- });
805
- }
806
- static resolve(extensions) {
807
- return ExtensionManager.sort(ExtensionManager.flatten(extensions));
808
- }
809
- static flatten(extensions) {
810
- return extensions
811
- .map(extension => {
812
- const context = {
813
- name: extension.name,
814
- options: extension.options,
815
- };
816
- const addExtensions = getExtensionField(extension, 'addExtensions', context);
817
- if (addExtensions) {
818
- return [
819
- extension,
820
- ...this.flatten(addExtensions()),
821
- ];
822
- }
823
- return extension;
824
- })
825
- // `Infinity` will break TypeScript so we set a number that is probably high enough
826
- .flat(10);
827
- }
828
- static sort(extensions) {
829
- const defaultPriority = 100;
830
- return extensions.sort((a, b) => {
831
- const priorityA = getExtensionField(a, 'priority') || defaultPriority;
832
- const priorityB = getExtensionField(b, 'priority') || defaultPriority;
833
- if (priorityA > priorityB) {
834
- return -1;
835
- }
836
- if (priorityA < priorityB) {
837
- return 1;
838
- }
839
- return 0;
840
- });
841
- }
842
- get commands() {
843
- return this.extensions.reduce((commands, extension) => {
844
- const context = {
845
- name: extension.name,
846
- options: extension.options,
847
- editor: this.editor,
848
- type: getSchemaTypeByName(extension.name, this.schema),
849
- };
850
- const addCommands = getExtensionField(extension, 'addCommands', context);
851
- if (!addCommands) {
852
- return commands;
853
- }
854
- return {
855
- ...commands,
856
- ...addCommands(),
857
- };
858
- }, {});
859
- }
860
- get plugins() {
861
- return [...this.extensions]
862
- .reverse()
863
- .map(extension => {
864
- const context = {
865
- name: extension.name,
866
- options: extension.options,
867
- editor: this.editor,
868
- type: getSchemaTypeByName(extension.name, this.schema),
869
- };
870
- const plugins = [];
871
- const addKeyboardShortcuts = getExtensionField(extension, 'addKeyboardShortcuts', context);
872
- if (addKeyboardShortcuts) {
873
- const bindings = Object.fromEntries(Object
874
- .entries(addKeyboardShortcuts())
875
- .map(([shortcut, method]) => {
876
- return [shortcut, () => method({ editor: this.editor })];
877
- }));
878
- const keyMapPlugin = prosemirrorKeymap.keymap(bindings);
879
- plugins.push(keyMapPlugin);
880
- }
881
- const addInputRules = getExtensionField(extension, 'addInputRules', context);
882
- if (this.editor.options.enableInputRules && addInputRules) {
883
- const inputRules = addInputRules();
884
- const inputRulePlugins = inputRules.length
885
- ? [prosemirrorInputrules.inputRules({ rules: inputRules })]
886
- : [];
887
- plugins.push(...inputRulePlugins);
888
- }
889
- const addPasteRules = getExtensionField(extension, 'addPasteRules', context);
890
- if (this.editor.options.enablePasteRules && addPasteRules) {
891
- const pasteRulePlugins = addPasteRules();
892
- plugins.push(...pasteRulePlugins);
893
- }
894
- const addProseMirrorPlugins = getExtensionField(extension, 'addProseMirrorPlugins', context);
895
- if (addProseMirrorPlugins) {
896
- const proseMirrorPlugins = addProseMirrorPlugins();
897
- plugins.push(...proseMirrorPlugins);
898
- }
899
- return plugins;
900
- })
901
- .flat();
902
- }
903
- get attributes() {
904
- return getAttributesFromExtensions(this.extensions);
905
- }
906
- get nodeViews() {
907
- const { editor } = this;
908
- const { nodeExtensions } = splitExtensions(this.extensions);
909
- return Object.fromEntries(nodeExtensions
910
- .filter(extension => !!getExtensionField(extension, 'addNodeView'))
911
- .map(extension => {
912
- const extensionAttributes = this.attributes.filter(attribute => attribute.type === extension.name);
913
- const context = {
914
- name: extension.name,
915
- options: extension.options,
916
- editor,
917
- type: getNodeType(extension.name, this.schema),
918
- };
919
- const addNodeView = getExtensionField(extension, 'addNodeView', context);
920
- if (!addNodeView) {
921
- return [];
922
- }
923
- const nodeview = (node, view, getPos, decorations) => {
924
- const HTMLAttributes = getRenderedAttributes(node, extensionAttributes);
925
- return addNodeView()({
926
- editor,
927
- node,
928
- getPos,
929
- decorations,
930
- HTMLAttributes,
931
- extension,
932
- });
933
- };
934
- return [extension.name, nodeview];
935
- }));
936
- }
937
- get textSerializers() {
938
- const { editor } = this;
939
- const { nodeExtensions } = splitExtensions(this.extensions);
940
- return Object.fromEntries(nodeExtensions
941
- .filter(extension => !!getExtensionField(extension, 'renderText'))
942
- .map(extension => {
943
- const context = {
944
- name: extension.name,
945
- options: extension.options,
946
- editor,
947
- type: getNodeType(extension.name, this.schema),
948
- };
949
- const renderText = getExtensionField(extension, 'renderText', context);
950
- if (!renderText) {
951
- return [];
952
- }
953
- const textSerializer = (props) => renderText(props);
954
- return [extension.name, textSerializer];
955
- }));
956
- }
957
- }
958
-
959
- class EventEmitter {
960
- constructor() {
961
- this.callbacks = {};
962
- }
963
- on(event, fn) {
964
- if (!this.callbacks[event]) {
965
- this.callbacks[event] = [];
966
- }
967
- this.callbacks[event].push(fn);
968
- return this;
969
- }
970
- emit(event, ...args) {
971
- const callbacks = this.callbacks[event];
972
- if (callbacks) {
973
- callbacks.forEach(callback => callback.apply(this, args));
974
- }
975
- return this;
976
- }
977
- off(event, fn) {
978
- const callbacks = this.callbacks[event];
979
- if (callbacks) {
980
- if (fn) {
981
- this.callbacks[event] = callbacks.filter(callback => callback !== fn);
982
- }
983
- else {
984
- delete this.callbacks[event];
985
- }
986
- }
987
- return this;
988
- }
989
- removeAllListeners() {
990
- this.callbacks = {};
991
- }
992
- }
993
-
994
- // see: https://github.com/mesqueeb/is-what/blob/88d6e4ca92fb2baab6003c54e02eedf4e729e5ab/src/index.ts
995
- function getType(payload) {
996
- return Object.prototype.toString.call(payload).slice(8, -1);
997
- }
998
- function isPlainObject(payload) {
999
- if (getType(payload) !== 'Object')
1000
- return false;
1001
- return payload.constructor === Object && Object.getPrototypeOf(payload) === Object.prototype;
1002
- }
1003
-
1004
- function mergeDeep(target, source) {
1005
- const output = { ...target };
1006
- if (isPlainObject(target) && isPlainObject(source)) {
1007
- Object.keys(source).forEach(key => {
1008
- if (isPlainObject(source[key])) {
1009
- if (!(key in target)) {
1010
- Object.assign(output, { [key]: source[key] });
1011
- }
1012
- else {
1013
- output[key] = mergeDeep(target[key], source[key]);
1014
- }
1015
- }
1016
- else {
1017
- Object.assign(output, { [key]: source[key] });
1018
- }
1019
- });
1020
- }
1021
- return output;
1022
- }
1023
-
1024
- class Extension {
1025
- constructor(config = {}) {
1026
- this.type = 'extension';
1027
- this.name = 'extension';
1028
- this.parent = null;
1029
- this.child = null;
1030
- this.config = {
1031
- name: this.name,
1032
- defaultOptions: {},
1033
- };
1034
- this.config = {
1035
- ...this.config,
1036
- ...config,
1037
- };
1038
- this.name = this.config.name;
1039
- this.options = this.config.defaultOptions;
1040
- }
1041
- static create(config = {}) {
1042
- return new Extension(config);
1043
- }
1044
- configure(options = {}) {
1045
- // return a new instance so we can use the same extension
1046
- // with different calls of `configure`
1047
- const extension = this.extend();
1048
- extension.options = mergeDeep(this.options, options);
1049
- return extension;
1050
- }
1051
- extend(extendedConfig = {}) {
1052
- const extension = new Extension(extendedConfig);
1053
- extension.parent = this;
1054
- this.child = extension;
1055
- extension.name = extendedConfig.name
1056
- ? extendedConfig.name
1057
- : extension.parent.name;
1058
- extension.options = extendedConfig.defaultOptions
1059
- ? extendedConfig.defaultOptions
1060
- : extension.parent.options;
1061
- return extension;
1062
- }
1063
- }
1064
-
1065
- const textBetween = (editor, from, to, blockSeparator, leafText) => {
1066
- let text = '';
1067
- let separated = true;
1068
- editor.state.doc.nodesBetween(from, to, (node, pos) => {
1069
- var _a;
1070
- const textSerializer = editor.extensionManager.textSerializers[node.type.name];
1071
- if (textSerializer) {
1072
- text += textSerializer({ node });
1073
- separated = !blockSeparator;
1074
- }
1075
- else if (node.isText) {
1076
- 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);
1077
- separated = !blockSeparator;
1078
- }
1079
- else if (node.isLeaf && leafText) {
1080
- text += leafText;
1081
- separated = !blockSeparator;
1082
- }
1083
- else if (!separated && node.isBlock) {
1084
- text += blockSeparator;
1085
- separated = true;
1086
- }
1087
- }, 0);
1088
- return text;
1089
- };
1090
- const ClipboardTextSerializer = Extension.create({
1091
- name: 'editable',
1092
- addProseMirrorPlugins() {
1093
- return [
1094
- new prosemirrorState.Plugin({
1095
- key: new prosemirrorState.PluginKey('clipboardTextSerializer'),
1096
- props: {
1097
- clipboardTextSerializer: () => {
1098
- const { editor } = this;
1099
- const { from, to } = editor.state.selection;
1100
- return textBetween(editor, from, to, '\n');
1101
- },
1102
- },
1103
- }),
1104
- ];
1105
- },
1106
- });
1107
-
1108
- const blur = () => ({ editor, view }) => {
1109
- requestAnimationFrame(() => {
1110
- if (!editor.isDestroyed) {
1111
- view.dom.blur();
1112
- }
1113
- });
1114
- return true;
1115
- };
1116
-
1117
- var blur$1 = /*#__PURE__*/Object.freeze({
1118
- __proto__: null,
1119
- blur: blur
1120
- });
1121
-
1122
- const clearContent = (emitUpdate = false) => ({ commands }) => {
1123
- return commands.setContent('', emitUpdate);
1124
- };
1125
-
1126
- var clearContent$1 = /*#__PURE__*/Object.freeze({
1127
- __proto__: null,
1128
- clearContent: clearContent
1129
- });
1130
-
1131
- const clearNodes = () => ({ state, tr, dispatch }) => {
1132
- const { selection } = tr;
1133
- const { ranges } = selection;
1134
- ranges.forEach(range => {
1135
- state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
1136
- if (node.type.isText) {
1137
- return;
1138
- }
1139
- const $fromPos = tr.doc.resolve(tr.mapping.map(pos));
1140
- const $toPos = tr.doc.resolve(tr.mapping.map(pos + node.nodeSize));
1141
- const nodeRange = $fromPos.blockRange($toPos);
1142
- if (!nodeRange) {
1143
- return;
1144
- }
1145
- const targetLiftDepth = prosemirrorTransform.liftTarget(nodeRange);
1146
- if (node.type.isTextblock && dispatch) {
1147
- const { defaultType } = $fromPos.parent.contentMatchAt($fromPos.index());
1148
- tr.setNodeMarkup(nodeRange.start, defaultType);
1149
- }
1150
- if ((targetLiftDepth || targetLiftDepth === 0) && dispatch) {
1151
- tr.lift(nodeRange, targetLiftDepth);
1152
- }
1153
- });
1154
- });
1155
- return true;
1156
- };
1157
-
1158
- var clearNodes$1 = /*#__PURE__*/Object.freeze({
1159
- __proto__: null,
1160
- clearNodes: clearNodes
1161
- });
1162
-
1163
- const command = fn => props => {
1164
- return fn(props);
1165
- };
1166
-
1167
- var command$1 = /*#__PURE__*/Object.freeze({
1168
- __proto__: null,
1169
- command: command
1170
- });
1171
-
1172
- const createParagraphNear = () => ({ state, dispatch }) => {
1173
- return prosemirrorCommands.createParagraphNear(state, dispatch);
1174
- };
1175
-
1176
- var createParagraphNear$1 = /*#__PURE__*/Object.freeze({
1177
- __proto__: null,
1178
- createParagraphNear: createParagraphNear
1179
- });
1180
-
1181
- const deleteNode = typeOrName => ({ tr, state, dispatch }) => {
1182
- const type = getNodeType(typeOrName, state.schema);
1183
- const $pos = tr.selection.$anchor;
1184
- for (let depth = $pos.depth; depth > 0; depth -= 1) {
1185
- const node = $pos.node(depth);
1186
- if (node.type === type) {
1187
- if (dispatch) {
1188
- const from = $pos.before(depth);
1189
- const to = $pos.after(depth);
1190
- tr.delete(from, to).scrollIntoView();
1191
- }
1192
- return true;
1193
- }
1194
- }
1195
- return false;
1196
- };
1197
-
1198
- var deleteNode$1 = /*#__PURE__*/Object.freeze({
1199
- __proto__: null,
1200
- deleteNode: deleteNode
1201
- });
1202
-
1203
- const deleteRange = range => ({ tr, dispatch }) => {
1204
- const { from, to } = range;
1205
- if (dispatch) {
1206
- tr.delete(from, to);
1207
- }
1208
- return true;
1209
- };
1210
-
1211
- var deleteRange$1 = /*#__PURE__*/Object.freeze({
1212
- __proto__: null,
1213
- deleteRange: deleteRange
1214
- });
1215
-
1216
- const deleteSelection = () => ({ state, dispatch }) => {
1217
- return prosemirrorCommands.deleteSelection(state, dispatch);
1218
- };
1219
-
1220
- var deleteSelection$1 = /*#__PURE__*/Object.freeze({
1221
- __proto__: null,
1222
- deleteSelection: deleteSelection
1223
- });
1224
-
1225
- const enter = () => ({ commands }) => {
1226
- return commands.keyboardShortcut('Enter');
1227
- };
1228
-
1229
- var enter$1 = /*#__PURE__*/Object.freeze({
1230
- __proto__: null,
1231
- enter: enter
1232
- });
1233
-
1234
- const exitCode = () => ({ state, dispatch }) => {
1235
- return prosemirrorCommands.exitCode(state, dispatch);
1236
- };
1237
-
1238
- var exitCode$1 = /*#__PURE__*/Object.freeze({
1239
- __proto__: null,
1240
- exitCode: exitCode
1241
- });
1242
-
1243
- function findMarkInSet(marks, type, attributes = {}) {
1244
- return marks.find(item => {
1245
- return item.type === type && objectIncludes(item.attrs, attributes);
1246
- });
1247
- }
1248
- function isMarkInSet(marks, type, attributes = {}) {
1249
- return !!findMarkInSet(marks, type, attributes);
1250
- }
1251
- function getMarkRange($pos, type, attributes = {}) {
1252
- if (!$pos || !type) {
1253
- return;
1254
- }
1255
- const start = $pos.parent.childAfter($pos.parentOffset);
1256
- if (!start.node) {
1257
- return;
1258
- }
1259
- const mark = findMarkInSet(start.node.marks, type, attributes);
1260
- if (!mark) {
1261
- return;
1262
- }
1263
- let startIndex = $pos.index();
1264
- let startPos = $pos.start() + start.offset;
1265
- let endIndex = startIndex + 1;
1266
- let endPos = startPos + start.node.nodeSize;
1267
- findMarkInSet(start.node.marks, type, attributes);
1268
- while (startIndex > 0 && mark.isInSet($pos.parent.child(startIndex - 1).marks)) {
1269
- startIndex -= 1;
1270
- startPos -= $pos.parent.child(startIndex).nodeSize;
1271
- }
1272
- while (endIndex < $pos.parent.childCount
1273
- && isMarkInSet($pos.parent.child(endIndex).marks, type, attributes)) {
1274
- endPos += $pos.parent.child(endIndex).nodeSize;
1275
- endIndex += 1;
1276
- }
1277
- return {
1278
- from: startPos,
1279
- to: endPos,
1280
- };
1281
- }
1282
-
1283
- const extendMarkRange = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1284
- const type = getMarkType(typeOrName, state.schema);
1285
- const { doc, selection } = tr;
1286
- const { $from, from, to } = selection;
1287
- if (dispatch) {
1288
- const range = getMarkRange($from, type, attributes);
1289
- if (range && range.from <= from && range.to >= to) {
1290
- const newSelection = prosemirrorState.TextSelection.create(doc, range.from, range.to);
1291
- tr.setSelection(newSelection);
1292
- }
1293
- }
1294
- return true;
1295
- };
1296
-
1297
- var extendMarkRange$1 = /*#__PURE__*/Object.freeze({
1298
- __proto__: null,
1299
- extendMarkRange: extendMarkRange
1300
- });
1301
-
1302
- const first = commands => props => {
1303
- const items = typeof commands === 'function'
1304
- ? commands(props)
1305
- : commands;
1306
- for (let i = 0; i < items.length; i += 1) {
1307
- if (items[i](props)) {
1308
- return true;
1309
- }
1310
- }
1311
- return false;
1312
- };
1313
-
1314
- var first$1 = /*#__PURE__*/Object.freeze({
1315
- __proto__: null,
1316
- first: first
1317
- });
1318
-
1319
- function minMax(value = 0, min = 0, max = 0) {
1320
- return Math.min(Math.max(value, min), max);
1321
- }
1322
-
1323
- function isClass(item) {
1324
- var _a;
1325
- if (((_a = item.constructor) === null || _a === void 0 ? void 0 : _a.toString().substring(0, 5)) !== 'class') {
1326
- return false;
1327
- }
1328
- return true;
1329
- }
1330
-
1331
- function isObject(item) {
1332
- return (item
1333
- && typeof item === 'object'
1334
- && !Array.isArray(item)
1335
- && !isClass(item));
1336
- }
1337
-
1338
- function isTextSelection(value) {
1339
- return isObject(value) && value instanceof prosemirrorState.TextSelection;
1340
- }
1341
-
1342
- function resolveSelection(state, position = null) {
1343
- if (!position) {
1344
- return null;
1345
- }
1346
- if (position === 'start' || position === true) {
1347
- return {
1348
- from: 0,
1349
- to: 0,
1350
- };
1351
- }
1352
- if (position === 'end') {
1353
- const { size } = state.doc.content;
1354
- return {
1355
- from: size,
1356
- to: size,
1357
- };
1358
- }
1359
- return {
1360
- from: position,
1361
- to: position,
1362
- };
1363
- }
1364
- const focus = (position = null) => ({ editor, view, tr, dispatch, }) => {
1365
- const delayedFocus = () => {
1366
- // For React we have to focus asynchronously. Otherwise wild things happen.
1367
- // see: https://github.com/ueberdosis/tiptap/issues/1520
1368
- requestAnimationFrame(() => {
1369
- if (!editor.isDestroyed) {
1370
- view.focus();
1371
- }
1372
- });
1373
- };
1374
- if ((view.hasFocus() && position === null) || position === false) {
1375
- return true;
1376
- }
1377
- // we don’t try to resolve a NodeSelection or CellSelection
1378
- if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
1379
- delayedFocus();
1380
- return true;
1381
- }
1382
- const { from, to } = resolveSelection(editor.state, position) || editor.state.selection;
1383
- const { doc, storedMarks } = tr;
1384
- const minPos = prosemirrorState.Selection.atStart(doc).from;
1385
- const maxPos = prosemirrorState.Selection.atEnd(doc).to;
1386
- const resolvedFrom = minMax(from, minPos, maxPos);
1387
- const resolvedEnd = minMax(to, minPos, maxPos);
1388
- const selection = prosemirrorState.TextSelection.create(doc, resolvedFrom, resolvedEnd);
1389
- const isSameSelection = editor.state.selection.eq(selection);
1390
- if (dispatch) {
1391
- if (!isSameSelection) {
1392
- tr.setSelection(selection);
1393
- }
1394
- // `tr.setSelection` resets the stored marks
1395
- // so we’ll restore them if the selection is the same as before
1396
- if (isSameSelection && storedMarks) {
1397
- tr.setStoredMarks(storedMarks);
1398
- }
1399
- delayedFocus();
1400
- }
1401
- return true;
1402
- };
1403
-
1404
- var focus$1 = /*#__PURE__*/Object.freeze({
1405
- __proto__: null,
1406
- focus: focus
1407
- });
1408
-
1409
- const forEach = (items, fn) => props => {
1410
- return items.every((item, index) => fn(item, { ...props, index }));
1411
- };
1412
-
1413
- var forEach$1 = /*#__PURE__*/Object.freeze({
1414
- __proto__: null,
1415
- forEach: forEach
1416
- });
1417
-
1418
- const insertContent = (value, options) => ({ tr, commands }) => {
1419
- return commands.insertContentAt({ from: tr.selection.from, to: tr.selection.to }, value, options);
1420
- };
1421
-
1422
- var insertContent$1 = /*#__PURE__*/Object.freeze({
1423
- __proto__: null,
1424
- insertContent: insertContent
1425
- });
1426
-
1427
- // source: https://github.com/ProseMirror/prosemirror-state/blob/master/src/selection.js#L466
1428
- function selectionToInsertionEnd(tr, startLen, bias) {
1429
- const last = tr.steps.length - 1;
1430
- if (last < startLen) {
1431
- return;
1432
- }
1433
- const step = tr.steps[last];
1434
- if (!(step instanceof prosemirrorTransform.ReplaceStep || step instanceof prosemirrorTransform.ReplaceAroundStep)) {
1435
- return;
1436
- }
1437
- const map = tr.mapping.maps[last];
1438
- let end = 0;
1439
- map.forEach((_from, _to, _newFrom, newTo) => {
1440
- if (end === 0) {
1441
- end = newTo;
1442
- }
1443
- });
1444
- tr.setSelection(prosemirrorState.Selection.near(tr.doc.resolve(end), bias));
1445
- }
1446
-
1447
- const insertContentAt = (position, value, options) => ({ tr, dispatch, editor }) => {
1448
- if (dispatch) {
1449
- const content = createNodeFromContent(value, editor.schema, {
1450
- parseOptions: {
1451
- preserveWhitespace: 'full',
1452
- },
1453
- ...(options || {}),
1454
- });
1455
- // don’t dispatch an empty fragment because this can lead to strange errors
1456
- if (content.toString() === '<>') {
1457
- return true;
1458
- }
1459
- const { from, to } = typeof position === 'number'
1460
- ? { from: position, to: position }
1461
- : position;
1462
- tr.replaceWith(from, to, content);
1463
- // set cursor at end of inserted content
1464
- selectionToInsertionEnd(tr, tr.steps.length - 1, 1);
1465
- }
1466
- return true;
1467
- };
1468
-
1469
- var insertContentAt$1 = /*#__PURE__*/Object.freeze({
1470
- __proto__: null,
1471
- insertContentAt: insertContentAt
1472
- });
1473
-
1474
- const joinBackward = () => ({ state, dispatch }) => {
1475
- return prosemirrorCommands.joinBackward(state, dispatch);
1476
- };
1477
-
1478
- var joinBackward$1 = /*#__PURE__*/Object.freeze({
1479
- __proto__: null,
1480
- joinBackward: joinBackward
1481
- });
1482
-
1483
- const joinForward = () => ({ state, dispatch }) => {
1484
- return prosemirrorCommands.joinForward(state, dispatch);
1485
- };
1486
-
1487
- var joinForward$1 = /*#__PURE__*/Object.freeze({
1488
- __proto__: null,
1489
- joinForward: joinForward
1490
- });
1491
-
1492
- const mac = typeof navigator !== 'undefined' ? /Mac/.test(navigator.platform) : false;
1493
- function normalizeKeyName(name) {
1494
- const parts = name.split(/-(?!$)/);
1495
- let result = parts[parts.length - 1];
1496
- if (result === 'Space') {
1497
- result = ' ';
1498
- }
1499
- let alt;
1500
- let ctrl;
1501
- let shift;
1502
- let meta;
1503
- for (let i = 0; i < parts.length - 1; i += 1) {
1504
- const mod = parts[i];
1505
- if (/^(cmd|meta|m)$/i.test(mod)) {
1506
- meta = true;
1507
- }
1508
- else if (/^a(lt)?$/i.test(mod)) {
1509
- alt = true;
1510
- }
1511
- else if (/^(c|ctrl|control)$/i.test(mod)) {
1512
- ctrl = true;
1513
- }
1514
- else if (/^s(hift)?$/i.test(mod)) {
1515
- shift = true;
1516
- }
1517
- else if (/^mod$/i.test(mod)) {
1518
- if (mac) {
1519
- meta = true;
1520
- }
1521
- else {
1522
- ctrl = true;
1523
- }
1524
- }
1525
- else {
1526
- throw new Error(`Unrecognized modifier name: ${mod}`);
1527
- }
1528
- }
1529
- if (alt) {
1530
- result = `Alt-${result}`;
1531
- }
1532
- if (ctrl) {
1533
- result = `Ctrl-${result}`;
1534
- }
1535
- if (meta) {
1536
- result = `Meta-${result}`;
1537
- }
1538
- if (shift) {
1539
- result = `Shift-${result}`;
1540
- }
1541
- return result;
1542
- }
1543
- const keyboardShortcut = name => ({ editor, view, tr, dispatch, }) => {
1544
- const keys = normalizeKeyName(name).split(/-(?!$)/);
1545
- const key = keys.find(item => !['Alt', 'Ctrl', 'Meta', 'Shift'].includes(item));
1546
- const event = new KeyboardEvent('keydown', {
1547
- key: key === 'Space'
1548
- ? ' '
1549
- : key,
1550
- altKey: keys.includes('Alt'),
1551
- ctrlKey: keys.includes('Ctrl'),
1552
- metaKey: keys.includes('Meta'),
1553
- shiftKey: keys.includes('Shift'),
1554
- bubbles: true,
1555
- cancelable: true,
1556
- });
1557
- const capturedTransaction = editor.captureTransaction(() => {
1558
- view.someProp('handleKeyDown', f => f(view, event));
1559
- });
1560
- capturedTransaction === null || capturedTransaction === void 0 ? void 0 : capturedTransaction.steps.forEach(step => {
1561
- const newStep = step.map(tr.mapping);
1562
- if (newStep && dispatch) {
1563
- tr.maybeStep(newStep);
1564
- }
1565
- });
1566
- return true;
1567
- };
1568
-
1569
- var keyboardShortcut$1 = /*#__PURE__*/Object.freeze({
1570
- __proto__: null,
1571
- keyboardShortcut: keyboardShortcut
1572
- });
1573
-
1574
- const lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1575
- const type = getNodeType(typeOrName, state.schema);
1576
- const isActive = isNodeActive(state, type, attributes);
1577
- if (!isActive) {
1578
- return false;
1579
- }
1580
- return prosemirrorCommands.lift(state, dispatch);
1581
- };
1582
-
1583
- var lift$1 = /*#__PURE__*/Object.freeze({
1584
- __proto__: null,
1585
- lift: lift
1586
- });
1587
-
1588
- const liftEmptyBlock = () => ({ state, dispatch }) => {
1589
- return prosemirrorCommands.liftEmptyBlock(state, dispatch);
1590
- };
1591
-
1592
- var liftEmptyBlock$1 = /*#__PURE__*/Object.freeze({
1593
- __proto__: null,
1594
- liftEmptyBlock: liftEmptyBlock
1595
- });
1596
-
1597
- const liftListItem = typeOrName => ({ state, dispatch }) => {
1598
- const type = getNodeType(typeOrName, state.schema);
1599
- return prosemirrorSchemaList.liftListItem(type)(state, dispatch);
1600
- };
1601
-
1602
- var liftListItem$1 = /*#__PURE__*/Object.freeze({
1603
- __proto__: null,
1604
- liftListItem: liftListItem
1605
- });
1606
-
1607
- const newlineInCode = () => ({ state, dispatch }) => {
1608
- return prosemirrorCommands.newlineInCode(state, dispatch);
1609
- };
1610
-
1611
- var newlineInCode$1 = /*#__PURE__*/Object.freeze({
1612
- __proto__: null,
1613
- newlineInCode: newlineInCode
1614
- });
1615
-
1616
- /**
1617
- * Remove a property or an array of properties from an object
1618
- * @param obj Object
1619
- * @param key Key to remove
1620
- */
1621
- function deleteProps(obj, propOrProps) {
1622
- const props = typeof propOrProps === 'string'
1623
- ? [propOrProps]
1624
- : propOrProps;
1625
- return Object
1626
- .keys(obj)
1627
- .reduce((newObj, prop) => {
1628
- if (!props.includes(prop)) {
1629
- newObj[prop] = obj[prop];
1630
- }
1631
- return newObj;
1632
- }, {});
1633
- }
1634
-
1635
- const resetAttributes = (typeOrName, attributes) => ({ tr, state, dispatch }) => {
1636
- let nodeType = null;
1637
- let markType = null;
1638
- const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string'
1639
- ? typeOrName
1640
- : typeOrName.name, state.schema);
1641
- if (!schemaType) {
1642
- return false;
1643
- }
1644
- if (schemaType === 'node') {
1645
- nodeType = getNodeType(typeOrName, state.schema);
1646
- }
1647
- if (schemaType === 'mark') {
1648
- markType = getMarkType(typeOrName, state.schema);
1649
- }
1650
- if (dispatch) {
1651
- tr.selection.ranges.forEach(range => {
1652
- state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
1653
- if (nodeType && nodeType === node.type) {
1654
- tr.setNodeMarkup(pos, undefined, deleteProps(node.attrs, attributes));
1655
- }
1656
- if (markType && node.marks.length) {
1657
- node.marks.forEach(mark => {
1658
- if (markType === mark.type) {
1659
- tr.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));
1660
- }
1661
- });
1662
- }
1663
- });
1664
- });
1665
- }
1666
- return true;
1667
- };
1668
-
1669
- var resetAttributes$1 = /*#__PURE__*/Object.freeze({
1670
- __proto__: null,
1671
- resetAttributes: resetAttributes
1672
- });
1673
-
1674
- const scrollIntoView = () => ({ tr, dispatch }) => {
1675
- if (dispatch) {
1676
- tr.scrollIntoView();
1677
- }
1678
- return true;
1679
- };
1680
-
1681
- var scrollIntoView$1 = /*#__PURE__*/Object.freeze({
1682
- __proto__: null,
1683
- scrollIntoView: scrollIntoView
1684
- });
1685
-
1686
- const selectAll = () => ({ state, dispatch }) => {
1687
- return prosemirrorCommands.selectAll(state, dispatch);
1688
- };
1689
-
1690
- var selectAll$1 = /*#__PURE__*/Object.freeze({
1691
- __proto__: null,
1692
- selectAll: selectAll
1693
- });
1694
-
1695
- const selectNodeBackward = () => ({ state, dispatch }) => {
1696
- return prosemirrorCommands.selectNodeBackward(state, dispatch);
1697
- };
1698
-
1699
- var selectNodeBackward$1 = /*#__PURE__*/Object.freeze({
1700
- __proto__: null,
1701
- selectNodeBackward: selectNodeBackward
1702
- });
1703
-
1704
- const selectNodeForward = () => ({ state, dispatch }) => {
1705
- return prosemirrorCommands.selectNodeForward(state, dispatch);
1706
- };
1707
-
1708
- var selectNodeForward$1 = /*#__PURE__*/Object.freeze({
1709
- __proto__: null,
1710
- selectNodeForward: selectNodeForward
1711
- });
1712
-
1713
- const selectParentNode = () => ({ state, dispatch }) => {
1714
- return prosemirrorCommands.selectParentNode(state, dispatch);
1715
- };
1716
-
1717
- var selectParentNode$1 = /*#__PURE__*/Object.freeze({
1718
- __proto__: null,
1719
- selectParentNode: selectParentNode
1720
- });
1721
-
1722
- const setContent = (content, emitUpdate = false, parseOptions = {}) => ({ tr, editor, dispatch }) => {
1723
- const { doc } = tr;
1724
- const document = createDocument(content, editor.schema, parseOptions);
1725
- const selection = prosemirrorState.TextSelection.create(doc, 0, doc.content.size);
1726
- if (dispatch) {
1727
- tr.setSelection(selection)
1728
- .replaceSelectionWith(document, false)
1729
- .setMeta('preventUpdate', !emitUpdate);
1730
- }
1731
- return true;
1732
- };
1733
-
1734
- var setContent$1 = /*#__PURE__*/Object.freeze({
1735
- __proto__: null,
1736
- setContent: setContent
1737
- });
1738
-
1739
- const setMark = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
1740
- const { selection } = tr;
1741
- const { empty, ranges } = selection;
1742
- const type = getMarkType(typeOrName, state.schema);
1743
- if (dispatch) {
1744
- if (empty) {
1745
- const oldAttributes = getMarkAttributes(state, type);
1746
- tr.addStoredMark(type.create({
1747
- ...oldAttributes,
1748
- ...attributes,
1749
- }));
1750
- }
1751
- else {
1752
- ranges.forEach(range => {
1753
- const from = range.$from.pos;
1754
- const to = range.$to.pos;
1755
- state.doc.nodesBetween(from, to, (node, pos) => {
1756
- const trimmedFrom = Math.max(pos, from);
1757
- const trimmedTo = Math.min(pos + node.nodeSize, to);
1758
- const someHasMark = node.marks.find(mark => mark.type === type);
1759
- // if there is already a mark of this type
1760
- // we know that we have to merge its attributes
1761
- // otherwise we add a fresh new mark
1762
- if (someHasMark) {
1763
- node.marks.forEach(mark => {
1764
- if (type === mark.type) {
1765
- tr.addMark(trimmedFrom, trimmedTo, type.create({
1766
- ...mark.attrs,
1767
- ...attributes,
1768
- }));
1769
- }
1770
- });
1771
- }
1772
- else {
1773
- tr.addMark(trimmedFrom, trimmedTo, type.create(attributes));
1774
- }
1775
- });
1776
- });
1777
- }
1778
- }
1779
- return true;
1780
- };
1781
-
1782
- var setMark$1 = /*#__PURE__*/Object.freeze({
1783
- __proto__: null,
1784
- setMark: setMark
1785
- });
1786
-
1787
- const setMeta = (key, value) => ({ tr }) => {
1788
- tr.setMeta(key, value);
1789
- return true;
1790
- };
1791
-
1792
- var setMeta$1 = /*#__PURE__*/Object.freeze({
1793
- __proto__: null,
1794
- setMeta: setMeta
1795
- });
1796
-
1797
- const setNode = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
1798
- const type = getNodeType(typeOrName, state.schema);
1799
- return prosemirrorCommands.setBlockType(type, attributes)(state, dispatch);
1800
- };
1801
-
1802
- var setNode$1 = /*#__PURE__*/Object.freeze({
1803
- __proto__: null,
1804
- setNode: setNode
1805
- });
1806
-
1807
- const setNodeSelection = position => ({ tr, dispatch }) => {
1808
- if (dispatch) {
1809
- const { doc } = tr;
1810
- const minPos = prosemirrorState.Selection.atStart(doc).from;
1811
- const maxPos = prosemirrorState.Selection.atEnd(doc).to;
1812
- const resolvedPos = minMax(position, minPos, maxPos);
1813
- const selection = prosemirrorState.NodeSelection.create(doc, resolvedPos);
1814
- tr.setSelection(selection);
1815
- }
1816
- return true;
1817
- };
1818
-
1819
- var setNodeSelection$1 = /*#__PURE__*/Object.freeze({
1820
- __proto__: null,
1821
- setNodeSelection: setNodeSelection
1822
- });
1823
-
1824
- const setTextSelection = position => ({ tr, dispatch }) => {
1825
- if (dispatch) {
1826
- const { doc } = tr;
1827
- const { from, to } = typeof position === 'number'
1828
- ? { from: position, to: position }
1829
- : position;
1830
- const minPos = prosemirrorState.Selection.atStart(doc).from;
1831
- const maxPos = prosemirrorState.Selection.atEnd(doc).to;
1832
- const resolvedFrom = minMax(from, minPos, maxPos);
1833
- const resolvedEnd = minMax(to, minPos, maxPos);
1834
- const selection = prosemirrorState.TextSelection.create(doc, resolvedFrom, resolvedEnd);
1835
- tr.setSelection(selection);
1836
- }
1837
- return true;
1838
- };
1839
-
1840
- var setTextSelection$1 = /*#__PURE__*/Object.freeze({
1841
- __proto__: null,
1842
- setTextSelection: setTextSelection
1843
- });
1844
-
1845
- const sinkListItem = typeOrName => ({ state, dispatch }) => {
1846
- const type = getNodeType(typeOrName, state.schema);
1847
- return prosemirrorSchemaList.sinkListItem(type)(state, dispatch);
1848
- };
1849
-
1850
- var sinkListItem$1 = /*#__PURE__*/Object.freeze({
1851
- __proto__: null,
1852
- sinkListItem: sinkListItem
1853
- });
1854
-
1855
- function getSplittedAttributes(extensionAttributes, typeName, attributes) {
1856
- return Object.fromEntries(Object
1857
- .entries(attributes)
1858
- .filter(([name]) => {
1859
- const extensionAttribute = extensionAttributes.find(item => {
1860
- return item.type === typeName && item.name === name;
1861
- });
1862
- if (!extensionAttribute) {
1863
- return false;
1864
- }
1865
- return extensionAttribute.attribute.keepOnSplit;
1866
- }));
1867
- }
1868
-
1869
- function defaultBlockAt(match) {
1870
- for (let i = 0; i < match.edgeCount; i += 1) {
1871
- const { type } = match.edge(i);
1872
- if (type.isTextblock && !type.hasRequiredAttrs()) {
1873
- return type;
1874
- }
1875
- }
1876
- return null;
1877
- }
1878
- function ensureMarks(state, splittableMarks) {
1879
- const marks = state.storedMarks
1880
- || (state.selection.$to.parentOffset && state.selection.$from.marks());
1881
- if (marks) {
1882
- const filteredMarks = marks.filter(mark => splittableMarks === null || splittableMarks === void 0 ? void 0 : splittableMarks.includes(mark.type.name));
1883
- state.tr.ensureMarks(filteredMarks);
1884
- }
1885
- }
1886
- const splitBlock = ({ keepMarks = true } = {}) => ({ tr, state, dispatch, editor, }) => {
1887
- const { selection, doc } = tr;
1888
- const { $from, $to } = selection;
1889
- const extensionAttributes = editor.extensionManager.attributes;
1890
- const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
1891
- if (selection instanceof prosemirrorState.NodeSelection && selection.node.isBlock) {
1892
- if (!$from.parentOffset || !prosemirrorTransform.canSplit(doc, $from.pos)) {
1893
- return false;
1894
- }
1895
- if (dispatch) {
1896
- if (keepMarks) {
1897
- ensureMarks(state, editor.extensionManager.splittableMarks);
1898
- }
1899
- tr.split($from.pos).scrollIntoView();
1900
- }
1901
- return true;
1902
- }
1903
- if (!$from.parent.isBlock) {
1904
- return false;
1905
- }
1906
- if (dispatch) {
1907
- const atEnd = $to.parentOffset === $to.parent.content.size;
1908
- if (selection instanceof prosemirrorState.TextSelection) {
1909
- tr.deleteSelection();
1910
- }
1911
- const deflt = $from.depth === 0
1912
- ? undefined
1913
- : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1)));
1914
- let types = atEnd && deflt
1915
- ? [{
1916
- type: deflt,
1917
- attrs: newAttributes,
1918
- }]
1919
- : undefined;
1920
- let can = prosemirrorTransform.canSplit(tr.doc, tr.mapping.map($from.pos), 1, types);
1921
- if (!types
1922
- && !can
1923
- && prosemirrorTransform.canSplit(tr.doc, tr.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : undefined)) {
1924
- can = true;
1925
- types = deflt
1926
- ? [{
1927
- type: deflt,
1928
- attrs: newAttributes,
1929
- }]
1930
- : undefined;
1931
- }
1932
- if (can) {
1933
- tr.split(tr.mapping.map($from.pos), 1, types);
1934
- if (deflt
1935
- && !atEnd
1936
- && !$from.parentOffset
1937
- && $from.parent.type !== deflt) {
1938
- const first = tr.mapping.map($from.before());
1939
- const $first = tr.doc.resolve(first);
1940
- if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) {
1941
- tr.setNodeMarkup(tr.mapping.map($from.before()), deflt);
1942
- }
1943
- }
1944
- }
1945
- if (keepMarks) {
1946
- ensureMarks(state, editor.extensionManager.splittableMarks);
1947
- }
1948
- tr.scrollIntoView();
1949
- }
1950
- return true;
1951
- };
1952
-
1953
- var splitBlock$1 = /*#__PURE__*/Object.freeze({
1954
- __proto__: null,
1955
- splitBlock: splitBlock
1956
- });
1957
-
1958
- const splitListItem = typeOrName => ({ tr, state, dispatch, editor, }) => {
1959
- var _a;
1960
- const type = getNodeType(typeOrName, state.schema);
1961
- const { $from, $to } = state.selection;
1962
- // @ts-ignore
1963
- // eslint-disable-next-line
1964
- const node = state.selection.node;
1965
- if ((node && node.isBlock) || $from.depth < 2 || !$from.sameParent($to)) {
1966
- return false;
1967
- }
1968
- const grandParent = $from.node(-1);
1969
- if (grandParent.type !== type) {
1970
- return false;
1971
- }
1972
- const extensionAttributes = editor.extensionManager.attributes;
1973
- if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
1974
- // In an empty block. If this is a nested list, the wrapping
1975
- // list item should be split. Otherwise, bail out and let next
1976
- // command handle lifting.
1977
- if ($from.depth === 2
1978
- || $from.node(-3).type !== type
1979
- || $from.index(-2) !== $from.node(-2).childCount - 1) {
1980
- return false;
1981
- }
1982
- if (dispatch) {
1983
- let wrap = prosemirrorModel.Fragment.empty;
1984
- // eslint-disable-next-line
1985
- const depthBefore = $from.index(-1)
1986
- ? 1
1987
- : $from.index(-2)
1988
- ? 2
1989
- : 3;
1990
- // Build a fragment containing empty versions of the structure
1991
- // from the outer list item to the parent node of the cursor
1992
- for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) {
1993
- wrap = prosemirrorModel.Fragment.from($from.node(d).copy(wrap));
1994
- }
1995
- // eslint-disable-next-line
1996
- const depthAfter = $from.indexAfter(-1) < $from.node(-2).childCount
1997
- ? 1
1998
- : $from.indexAfter(-2) < $from.node(-3).childCount
1999
- ? 2
2000
- : 3;
2001
- // Add a second list item with an empty default start node
2002
- const newNextTypeAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
2003
- const nextType = ((_a = type.contentMatch.defaultType) === null || _a === void 0 ? void 0 : _a.createAndFill(newNextTypeAttributes)) || undefined;
2004
- wrap = wrap.append(prosemirrorModel.Fragment.from(type.createAndFill(null, nextType) || undefined));
2005
- const start = $from.before($from.depth - (depthBefore - 1));
2006
- tr.replace(start, $from.after(-depthAfter), new prosemirrorModel.Slice(wrap, 4 - depthBefore, 0));
2007
- let sel = -1;
2008
- tr.doc.nodesBetween(start, tr.doc.content.size, (n, pos) => {
2009
- if (sel > -1) {
2010
- return false;
2011
- }
2012
- if (n.isTextblock && n.content.size === 0) {
2013
- sel = pos + 1;
2014
- }
2015
- });
2016
- if (sel > -1) {
2017
- tr.setSelection(prosemirrorState.TextSelection.near(tr.doc.resolve(sel)));
2018
- }
2019
- tr.scrollIntoView();
2020
- }
2021
- return true;
2022
- }
2023
- const nextType = $to.pos === $from.end()
2024
- ? grandParent.contentMatchAt(0).defaultType
2025
- : null;
2026
- const newTypeAttributes = getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs);
2027
- const newNextTypeAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
2028
- tr.delete($from.pos, $to.pos);
2029
- const types = nextType
2030
- ? [{ type, attrs: newTypeAttributes }, { type: nextType, attrs: newNextTypeAttributes }]
2031
- : [{ type, attrs: newTypeAttributes }];
2032
- if (!prosemirrorTransform.canSplit(tr.doc, $from.pos, 2)) {
2033
- return false;
2034
- }
2035
- if (dispatch) {
2036
- tr.split($from.pos, 2, types).scrollIntoView();
2037
- }
2038
- return true;
2039
- };
2040
-
2041
- var splitListItem$1 = /*#__PURE__*/Object.freeze({
2042
- __proto__: null,
2043
- splitListItem: splitListItem
2044
- });
2045
-
2046
- function findParentNodeClosestToPos($pos, predicate) {
2047
- for (let i = $pos.depth; i > 0; i -= 1) {
2048
- const node = $pos.node(i);
2049
- if (predicate(node)) {
2050
- return {
2051
- pos: i > 0 ? $pos.before(i) : 0,
2052
- start: $pos.start(i),
2053
- depth: i,
2054
- node,
2055
- };
2056
- }
2057
- }
2058
- }
2059
-
2060
- function findParentNode(predicate) {
2061
- return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
2062
- }
2063
-
2064
- function isList(name, extensions) {
2065
- const { nodeExtensions } = splitExtensions(extensions);
2066
- const extension = nodeExtensions.find(item => item.name === name);
2067
- if (!extension) {
2068
- return false;
2069
- }
2070
- const context = {
2071
- name: extension.name,
2072
- options: extension.options,
2073
- };
2074
- const group = callOrReturn(getExtensionField(extension, 'group', context));
2075
- if (typeof group !== 'string') {
2076
- return false;
2077
- }
2078
- return group.split(' ').includes('list');
2079
- }
2080
-
2081
- const toggleList = (listTypeOrName, itemTypeOrName) => ({ editor, tr, state, dispatch, chain, commands, can, }) => {
2082
- const { extensions } = editor.extensionManager;
2083
- const listType = getNodeType(listTypeOrName, state.schema);
2084
- const itemType = getNodeType(itemTypeOrName, state.schema);
2085
- const { selection } = state;
2086
- const { $from, $to } = selection;
2087
- const range = $from.blockRange($to);
2088
- if (!range) {
2089
- return false;
2090
- }
2091
- const parentList = findParentNode(node => isList(node.type.name, extensions))(selection);
2092
- if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
2093
- // remove list
2094
- if (parentList.node.type === listType) {
2095
- return commands.liftListItem(itemType);
2096
- }
2097
- // change list type
2098
- if (isList(parentList.node.type.name, extensions)
2099
- && listType.validContent(parentList.node.content)
2100
- && dispatch) {
2101
- tr.setNodeMarkup(parentList.pos, listType);
2102
- return true;
2103
- }
2104
- }
2105
- const canWrapInList = can().wrapInList(listType);
2106
- // try to convert node to paragraph if needed
2107
- if (!canWrapInList) {
2108
- return chain()
2109
- .clearNodes()
2110
- .wrapInList(listType)
2111
- .run();
2112
- }
2113
- return commands.wrapInList(listType);
2114
- };
2115
-
2116
- var toggleList$1 = /*#__PURE__*/Object.freeze({
2117
- __proto__: null,
2118
- toggleList: toggleList
2119
- });
2120
-
2121
- const toggleMark = (typeOrName, attributes = {}) => ({ state, commands }) => {
2122
- const type = getMarkType(typeOrName, state.schema);
2123
- const isActive = isMarkActive(state, type, attributes);
2124
- if (isActive) {
2125
- return commands.unsetMark(type);
2126
- }
2127
- return commands.setMark(type, attributes);
2128
- };
2129
-
2130
- var toggleMark$1 = /*#__PURE__*/Object.freeze({
2131
- __proto__: null,
2132
- toggleMark: toggleMark
2133
- });
2134
-
2135
- const toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
2136
- const type = getNodeType(typeOrName, state.schema);
2137
- const toggleType = getNodeType(toggleTypeOrName, state.schema);
2138
- const isActive = isNodeActive(state, type, attributes);
2139
- if (isActive) {
2140
- return commands.setNode(toggleType);
2141
- }
2142
- return commands.setNode(type, attributes);
2143
- };
2144
-
2145
- var toggleNode$1 = /*#__PURE__*/Object.freeze({
2146
- __proto__: null,
2147
- toggleNode: toggleNode
2148
- });
2149
-
2150
- const toggleWrap = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2151
- const type = getNodeType(typeOrName, state.schema);
2152
- const isActive = isNodeActive(state, type, attributes);
2153
- if (isActive) {
2154
- return prosemirrorCommands.lift(state, dispatch);
2155
- }
2156
- return prosemirrorCommands.wrapIn(type, attributes)(state, dispatch);
2157
- };
2158
-
2159
- var toggleWrap$1 = /*#__PURE__*/Object.freeze({
2160
- __proto__: null,
2161
- toggleWrap: toggleWrap
2162
- });
2163
-
2164
- const undoInputRule = () => ({ state, dispatch }) => {
2165
- return prosemirrorInputrules.undoInputRule(state, dispatch);
2166
- };
2167
-
2168
- var undoInputRule$1 = /*#__PURE__*/Object.freeze({
2169
- __proto__: null,
2170
- undoInputRule: undoInputRule
2171
- });
2172
-
2173
- const unsetAllMarks = () => ({ tr, state, dispatch }) => {
2174
- const { selection } = tr;
2175
- const { empty, ranges } = selection;
2176
- if (empty) {
2177
- return true;
2178
- }
2179
- if (dispatch) {
2180
- Object
2181
- .entries(state.schema.marks)
2182
- .forEach(([, mark]) => {
2183
- ranges.forEach(range => {
2184
- tr.removeMark(range.$from.pos, range.$to.pos, mark);
2185
- });
2186
- });
2187
- }
2188
- return true;
2189
- };
2190
-
2191
- var unsetAllMarks$1 = /*#__PURE__*/Object.freeze({
2192
- __proto__: null,
2193
- unsetAllMarks: unsetAllMarks
2194
- });
2195
-
2196
- const unsetMark = typeOrName => ({ tr, state, dispatch }) => {
2197
- const { selection } = tr;
2198
- const type = getMarkType(typeOrName, state.schema);
2199
- const { $from, empty, ranges } = selection;
2200
- if (dispatch) {
2201
- if (empty) {
2202
- let { from, to } = selection;
2203
- const range = getMarkRange($from, type);
2204
- if (range) {
2205
- from = range.from;
2206
- to = range.to;
2207
- }
2208
- tr.removeMark(from, to, type);
2209
- }
2210
- else {
2211
- ranges.forEach(range => {
2212
- tr.removeMark(range.$from.pos, range.$to.pos, type);
2213
- });
2214
- }
2215
- tr.removeStoredMark(type);
2216
- }
2217
- return true;
2218
- };
2219
-
2220
- var unsetMark$1 = /*#__PURE__*/Object.freeze({
2221
- __proto__: null,
2222
- unsetMark: unsetMark
2223
- });
2224
-
2225
- const updateAttributes = (typeOrName, attributes = {}) => ({ tr, state, dispatch }) => {
2226
- let nodeType = null;
2227
- let markType = null;
2228
- const schemaType = getSchemaTypeNameByName(typeof typeOrName === 'string'
2229
- ? typeOrName
2230
- : typeOrName.name, state.schema);
2231
- if (!schemaType) {
2232
- return false;
2233
- }
2234
- if (schemaType === 'node') {
2235
- nodeType = getNodeType(typeOrName, state.schema);
2236
- }
2237
- if (schemaType === 'mark') {
2238
- markType = getMarkType(typeOrName, state.schema);
2239
- }
2240
- if (dispatch) {
2241
- tr.selection.ranges.forEach(range => {
2242
- const from = range.$from.pos;
2243
- const to = range.$to.pos;
2244
- state.doc.nodesBetween(from, to, (node, pos) => {
2245
- if (nodeType && nodeType === node.type) {
2246
- tr.setNodeMarkup(pos, undefined, {
2247
- ...node.attrs,
2248
- ...attributes,
2249
- });
2250
- }
2251
- if (markType && node.marks.length) {
2252
- node.marks.forEach(mark => {
2253
- if (markType === mark.type) {
2254
- const trimmedFrom = Math.max(pos, from);
2255
- const trimmedTo = Math.min(pos + node.nodeSize, to);
2256
- tr.addMark(trimmedFrom, trimmedTo, markType.create({
2257
- ...mark.attrs,
2258
- ...attributes,
2259
- }));
2260
- }
2261
- });
2262
- }
2263
- });
2264
- });
2265
- }
2266
- return true;
2267
- };
2268
-
2269
- var updateAttributes$1 = /*#__PURE__*/Object.freeze({
2270
- __proto__: null,
2271
- updateAttributes: updateAttributes
2272
- });
2273
-
2274
- const wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2275
- const type = getNodeType(typeOrName, state.schema);
2276
- const isActive = isNodeActive(state, type, attributes);
2277
- if (isActive) {
2278
- return false;
2279
- }
2280
- return prosemirrorCommands.wrapIn(type, attributes)(state, dispatch);
2281
- };
2282
-
2283
- var wrapIn$1 = /*#__PURE__*/Object.freeze({
2284
- __proto__: null,
2285
- wrapIn: wrapIn
2286
- });
2287
-
2288
- const wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
2289
- const type = getNodeType(typeOrName, state.schema);
2290
- return prosemirrorSchemaList.wrapInList(type, attributes)(state, dispatch);
2291
- };
2292
-
2293
- var wrapInList$1 = /*#__PURE__*/Object.freeze({
2294
- __proto__: null,
2295
- wrapInList: wrapInList
2296
- });
2297
-
2298
- const Commands = Extension.create({
2299
- name: 'commands',
2300
- addCommands() {
2301
- return {
2302
- ...blur$1,
2303
- ...clearContent$1,
2304
- ...clearNodes$1,
2305
- ...command$1,
2306
- ...createParagraphNear$1,
2307
- ...deleteNode$1,
2308
- ...deleteRange$1,
2309
- ...deleteSelection$1,
2310
- ...enter$1,
2311
- ...exitCode$1,
2312
- ...extendMarkRange$1,
2313
- ...first$1,
2314
- ...focus$1,
2315
- ...forEach$1,
2316
- ...insertContent$1,
2317
- ...insertContentAt$1,
2318
- ...joinBackward$1,
2319
- ...joinForward$1,
2320
- ...keyboardShortcut$1,
2321
- ...lift$1,
2322
- ...liftEmptyBlock$1,
2323
- ...liftListItem$1,
2324
- ...newlineInCode$1,
2325
- ...resetAttributes$1,
2326
- ...scrollIntoView$1,
2327
- ...selectAll$1,
2328
- ...selectNodeBackward$1,
2329
- ...selectNodeForward$1,
2330
- ...selectParentNode$1,
2331
- ...setContent$1,
2332
- ...setMark$1,
2333
- ...setMeta$1,
2334
- ...setNode$1,
2335
- ...setNodeSelection$1,
2336
- ...setTextSelection$1,
2337
- ...sinkListItem$1,
2338
- ...splitBlock$1,
2339
- ...splitListItem$1,
2340
- ...toggleList$1,
2341
- ...toggleMark$1,
2342
- ...toggleNode$1,
2343
- ...toggleWrap$1,
2344
- ...undoInputRule$1,
2345
- ...unsetAllMarks$1,
2346
- ...unsetMark$1,
2347
- ...updateAttributes$1,
2348
- ...wrapIn$1,
2349
- ...wrapInList$1,
2350
- };
2351
- },
2352
- });
2353
-
2354
- const Editable = Extension.create({
2355
- name: 'editable',
2356
- addProseMirrorPlugins() {
2357
- return [
2358
- new prosemirrorState.Plugin({
2359
- key: new prosemirrorState.PluginKey('editable'),
2360
- props: {
2361
- editable: () => this.editor.options.editable,
2362
- },
2363
- }),
2364
- ];
2365
- },
2366
- });
2367
-
2368
- const FocusEvents = Extension.create({
2369
- name: 'focusEvents',
2370
- addProseMirrorPlugins() {
2371
- const { editor } = this;
2372
- return [
2373
- new prosemirrorState.Plugin({
2374
- key: new prosemirrorState.PluginKey('focusEvents'),
2375
- props: {
2376
- attributes: {
2377
- tabindex: '0',
2378
- },
2379
- handleDOMEvents: {
2380
- focus: (view, event) => {
2381
- editor.isFocused = true;
2382
- const transaction = editor.state.tr
2383
- .setMeta('focus', { event })
2384
- .setMeta('addToHistory', false);
2385
- view.dispatch(transaction);
2386
- return false;
2387
- },
2388
- blur: (view, event) => {
2389
- editor.isFocused = false;
2390
- const transaction = editor.state.tr
2391
- .setMeta('blur', { event })
2392
- .setMeta('addToHistory', false);
2393
- view.dispatch(transaction);
2394
- return false;
2395
- },
2396
- },
2397
- },
2398
- }),
2399
- ];
2400
- },
2401
- });
2402
-
2403
- const Keymap = Extension.create({
2404
- name: 'keymap',
2405
- addKeyboardShortcuts() {
2406
- const handleBackspace = () => this.editor.commands.first(({ commands }) => [
2407
- () => commands.undoInputRule(),
2408
- () => commands.deleteSelection(),
2409
- () => commands.joinBackward(),
2410
- () => commands.selectNodeBackward(),
2411
- ]);
2412
- const handleDelete = () => this.editor.commands.first(({ commands }) => [
2413
- () => commands.deleteSelection(),
2414
- () => commands.joinForward(),
2415
- () => commands.selectNodeForward(),
2416
- ]);
2417
- return {
2418
- Enter: () => this.editor.commands.first(({ commands }) => [
2419
- () => commands.newlineInCode(),
2420
- () => commands.createParagraphNear(),
2421
- () => commands.liftEmptyBlock(),
2422
- () => commands.splitBlock(),
2423
- ]),
2424
- 'Mod-Enter': () => this.editor.commands.exitCode(),
2425
- Backspace: () => handleBackspace(),
2426
- 'Mod-Backspace': () => handleBackspace(),
2427
- Delete: () => handleDelete(),
2428
- 'Mod-Delete': () => handleDelete(),
2429
- // we don’t need a custom `selectAll` for now
2430
- // 'Mod-a': () => this.editor.commands.selectAll(),
2431
- };
2432
- },
2433
- });
2434
-
2435
- var extensions = /*#__PURE__*/Object.freeze({
2436
- __proto__: null,
2437
- ClipboardTextSerializer: ClipboardTextSerializer,
2438
- Commands: Commands,
2439
- Editable: Editable,
2440
- FocusEvents: FocusEvents,
2441
- Keymap: Keymap
2442
- });
2443
-
2444
- const style = `.ProseMirror {
2445
- position: relative;
2446
- }
2447
-
2448
- .ProseMirror {
2449
- word-wrap: break-word;
2450
- white-space: pre-wrap;
2451
- -webkit-font-variant-ligatures: none;
2452
- font-variant-ligatures: none;
2453
- }
2454
-
2455
- .ProseMirror [contenteditable="false"] {
2456
- white-space: normal;
2457
- }
2458
-
2459
- .ProseMirror [contenteditable="false"] [contenteditable="true"] {
2460
- white-space: pre-wrap;
2461
- }
2462
-
2463
- .ProseMirror pre {
2464
- white-space: pre-wrap;
2465
- }
2466
-
2467
- .ProseMirror-gapcursor {
2468
- display: none;
2469
- pointer-events: none;
2470
- position: absolute;
2471
- }
2472
-
2473
- .ProseMirror-gapcursor:after {
2474
- content: "";
2475
- display: block;
2476
- position: absolute;
2477
- top: -2px;
2478
- width: 20px;
2479
- border-top: 1px solid black;
2480
- animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
2481
- }
2482
-
2483
- @keyframes ProseMirror-cursor-blink {
2484
- to {
2485
- visibility: hidden;
2486
- }
2487
- }
2488
-
2489
- .ProseMirror-hideselection *::selection {
2490
- background: transparent;
2491
- }
2492
-
2493
- .ProseMirror-hideselection *::-moz-selection {
2494
- background: transparent;
2495
- }
2496
-
2497
- .ProseMirror-hideselection * {
2498
- caret-color: transparent;
2499
- }
2500
-
2501
- .ProseMirror-focused .ProseMirror-gapcursor {
2502
- display: block;
2503
- }
2504
-
2505
- .tippy-box[data-animation=fade][data-state=hidden] {
2506
- opacity: 0
2507
- }`;
2508
-
2509
- class Editor extends EventEmitter {
2510
- constructor(options = {}) {
2511
- super();
2512
- this.isFocused = false;
2513
- this.options = {
2514
- element: document.createElement('div'),
2515
- content: '',
2516
- injectCSS: true,
2517
- extensions: [],
2518
- autofocus: false,
2519
- editable: true,
2520
- editorProps: {},
2521
- parseOptions: {},
2522
- enableInputRules: true,
2523
- enablePasteRules: true,
2524
- onBeforeCreate: () => null,
2525
- onCreate: () => null,
2526
- onUpdate: () => null,
2527
- onSelectionUpdate: () => null,
2528
- onTransaction: () => null,
2529
- onFocus: () => null,
2530
- onBlur: () => null,
2531
- onDestroy: () => null,
2532
- };
2533
- this.isCapturingTransaction = false;
2534
- this.capturedTransaction = null;
2535
- this.setOptions(options);
2536
- this.createExtensionManager();
2537
- this.createCommandManager();
2538
- this.createSchema();
2539
- this.on('beforeCreate', this.options.onBeforeCreate);
2540
- this.emit('beforeCreate', { editor: this });
2541
- this.createView();
2542
- this.injectCSS();
2543
- this.on('create', this.options.onCreate);
2544
- this.on('update', this.options.onUpdate);
2545
- this.on('selectionUpdate', this.options.onSelectionUpdate);
2546
- this.on('transaction', this.options.onTransaction);
2547
- this.on('focus', this.options.onFocus);
2548
- this.on('blur', this.options.onBlur);
2549
- this.on('destroy', this.options.onDestroy);
2550
- window.setTimeout(() => {
2551
- if (this.isDestroyed) {
2552
- return;
2553
- }
2554
- this.commands.focus(this.options.autofocus);
2555
- this.emit('create', { editor: this });
2556
- }, 0);
2557
- }
2558
- /**
2559
- * An object of all registered commands.
2560
- */
2561
- get commands() {
2562
- return this.commandManager.createCommands();
2563
- }
2564
- /**
2565
- * Create a command chain to call multiple commands at once.
2566
- */
2567
- chain() {
2568
- return this.commandManager.createChain();
2569
- }
2570
- /**
2571
- * Check if a command or a command chain can be executed. Without executing it.
2572
- */
2573
- can() {
2574
- return this.commandManager.createCan();
2575
- }
2576
- /**
2577
- * Inject CSS styles.
2578
- */
2579
- injectCSS() {
2580
- if (this.options.injectCSS && document) {
2581
- this.css = createStyleTag(style);
2582
- }
2583
- }
2584
- /**
2585
- * Update editor options.
2586
- *
2587
- * @param options A list of options
2588
- */
2589
- setOptions(options = {}) {
2590
- this.options = {
2591
- ...this.options,
2592
- ...options,
2593
- };
2594
- if (!this.view || !this.state || this.isDestroyed) {
2595
- return;
2596
- }
2597
- if (this.options.editorProps) {
2598
- this.view.setProps(this.options.editorProps);
2599
- }
2600
- this.view.updateState(this.state);
2601
- }
2602
- /**
2603
- * Update editable state of the editor.
2604
- */
2605
- setEditable(editable) {
2606
- this.setOptions({ editable });
2607
- }
2608
- /**
2609
- * Returns whether the editor is editable.
2610
- */
2611
- get isEditable() {
2612
- // since plugins are applied after creating the view
2613
- // `editable` is always `true` for one tick.
2614
- // that’s why we also have to check for `options.editable`
2615
- return this.options.editable
2616
- && this.view
2617
- && this.view.editable;
2618
- }
2619
- /**
2620
- * Returns the editor state.
2621
- */
2622
- get state() {
2623
- return this.view.state;
2624
- }
2625
- /**
2626
- * Register a ProseMirror plugin.
2627
- *
2628
- * @param plugin A ProseMirror plugin
2629
- * @param handlePlugins Control how to merge the plugin into the existing plugins.
2630
- */
2631
- registerPlugin(plugin, handlePlugins) {
2632
- const plugins = typeof handlePlugins === 'function'
2633
- ? handlePlugins(plugin, this.state.plugins)
2634
- : [...this.state.plugins, plugin];
2635
- const state = this.state.reconfigure({ plugins });
2636
- this.view.updateState(state);
2637
- }
2638
- /**
2639
- * Unregister a ProseMirror plugin.
2640
- *
2641
- * @param name The plugins name
2642
- */
2643
- unregisterPlugin(nameOrPluginKey) {
2644
- if (this.isDestroyed) {
2645
- return;
2646
- }
2647
- const name = typeof nameOrPluginKey === 'string'
2648
- ? `${nameOrPluginKey}$`
2649
- // @ts-ignore
2650
- : nameOrPluginKey.key;
2651
- const state = this.state.reconfigure({
2652
- // @ts-ignore
2653
- plugins: this.state.plugins.filter(plugin => !plugin.key.startsWith(name)),
2654
- });
2655
- this.view.updateState(state);
2656
- }
2657
- /**
2658
- * Creates an extension manager.
2659
- */
2660
- createExtensionManager() {
2661
- const coreExtensions = Object.entries(extensions).map(([, extension]) => extension);
2662
- const allExtensions = [...coreExtensions, ...this.options.extensions].filter(extension => {
2663
- return ['extension', 'node', 'mark'].includes(extension === null || extension === void 0 ? void 0 : extension.type);
2664
- });
2665
- this.extensionManager = new ExtensionManager(allExtensions, this);
2666
- }
2667
- /**
2668
- * Creates an command manager.
2669
- */
2670
- createCommandManager() {
2671
- this.commandManager = new CommandManager(this, this.extensionManager.commands);
2672
- }
2673
- /**
2674
- * Creates a ProseMirror schema.
2675
- */
2676
- createSchema() {
2677
- this.schema = this.extensionManager.schema;
2678
- }
2679
- /**
2680
- * Creates a ProseMirror view.
2681
- */
2682
- createView() {
2683
- this.view = new prosemirrorView.EditorView(this.options.element, {
2684
- ...this.options.editorProps,
2685
- dispatchTransaction: this.dispatchTransaction.bind(this),
2686
- state: prosemirrorState.EditorState.create({
2687
- doc: createDocument(this.options.content, this.schema, this.options.parseOptions),
2688
- }),
2689
- });
2690
- // `editor.view` is not yet available at this time.
2691
- // Therefore we will add all plugins and node views directly afterwards.
2692
- const newState = this.state.reconfigure({
2693
- plugins: this.extensionManager.plugins,
2694
- });
2695
- this.view.updateState(newState);
2696
- this.createNodeViews();
2697
- // Let’s store the editor instance in the DOM element.
2698
- // So we’ll have access to it for tests.
2699
- const dom = this.view.dom;
2700
- dom.editor = this;
2701
- }
2702
- /**
2703
- * Creates all node views.
2704
- */
2705
- createNodeViews() {
2706
- this.view.setProps({
2707
- nodeViews: this.extensionManager.nodeViews,
2708
- });
2709
- }
2710
- captureTransaction(fn) {
2711
- this.isCapturingTransaction = true;
2712
- fn();
2713
- this.isCapturingTransaction = false;
2714
- const tr = this.capturedTransaction;
2715
- this.capturedTransaction = null;
2716
- return tr;
2717
- }
2718
- /**
2719
- * The callback over which to send transactions (state updates) produced by the view.
2720
- *
2721
- * @param transaction An editor state transaction
2722
- */
2723
- dispatchTransaction(transaction) {
2724
- if (this.isCapturingTransaction) {
2725
- if (!this.capturedTransaction) {
2726
- this.capturedTransaction = transaction;
2727
- return;
2728
- }
2729
- transaction.steps.forEach(step => { var _a; return (_a = this.capturedTransaction) === null || _a === void 0 ? void 0 : _a.step(step); });
2730
- return;
2731
- }
2732
- const state = this.state.apply(transaction);
2733
- const selectionHasChanged = !this.state.selection.eq(state.selection);
2734
- this.view.updateState(state);
2735
- this.emit('transaction', {
2736
- editor: this,
2737
- transaction,
2738
- });
2739
- if (selectionHasChanged) {
2740
- this.emit('selectionUpdate', {
2741
- editor: this,
2742
- transaction,
2743
- });
2744
- }
2745
- const focus = transaction.getMeta('focus');
2746
- const blur = transaction.getMeta('blur');
2747
- if (focus) {
2748
- this.emit('focus', {
2749
- editor: this,
2750
- event: focus.event,
2751
- transaction,
2752
- });
2753
- }
2754
- if (blur) {
2755
- this.emit('blur', {
2756
- editor: this,
2757
- event: blur.event,
2758
- transaction,
2759
- });
2760
- }
2761
- if (!transaction.docChanged || transaction.getMeta('preventUpdate')) {
2762
- return;
2763
- }
2764
- this.emit('update', {
2765
- editor: this,
2766
- transaction,
2767
- });
2768
- }
2769
- /**
2770
- * Get attributes of the currently selected node or mark.
2771
- */
2772
- getAttributes(nameOrType) {
2773
- return getAttributes(this.state, nameOrType);
2774
- }
2775
- isActive(nameOrAttributes, attributesOrUndefined) {
2776
- const name = typeof nameOrAttributes === 'string'
2777
- ? nameOrAttributes
2778
- : null;
2779
- const attributes = typeof nameOrAttributes === 'string'
2780
- ? attributesOrUndefined
2781
- : nameOrAttributes;
2782
- return isActive(this.state, name, attributes);
2783
- }
2784
- /**
2785
- * Get the document as JSON.
2786
- */
2787
- getJSON() {
2788
- return this.state.doc.toJSON();
2789
- }
2790
- /**
2791
- * Get the document as HTML.
2792
- */
2793
- getHTML() {
2794
- return getHTMLFromFragment(this.state.doc, this.schema);
2795
- }
2796
- /**
2797
- * Check if there is no content.
2798
- */
2799
- get isEmpty() {
2800
- return isNodeEmpty(this.state.doc);
2801
- }
2802
- /**
2803
- * Get the number of characters for the current document.
2804
- */
2805
- getCharacterCount() {
2806
- return this.state.doc.content.size - 2;
2807
- }
2808
- /**
2809
- * Destroy the editor.
2810
- */
2811
- destroy() {
2812
- this.emit('destroy');
2813
- if (this.view) {
2814
- this.view.destroy();
2815
- }
2816
- this.removeAllListeners();
2817
- removeElement(this.css);
2818
- }
2819
- /**
2820
- * Check if the editor is already destroyed.
2821
- */
2822
- get isDestroyed() {
2823
- var _a;
2824
- // @ts-ignore
2825
- return !((_a = this.view) === null || _a === void 0 ? void 0 : _a.docView);
2826
- }
2827
- }
2828
-
2829
- class Node {
2830
- constructor(config = {}) {
2831
- this.type = 'node';
2832
- this.name = 'node';
2833
- this.parent = null;
2834
- this.child = null;
2835
- this.config = {
2836
- name: this.name,
2837
- defaultOptions: {},
2838
- };
2839
- this.config = {
2840
- ...this.config,
2841
- ...config,
2842
- };
2843
- this.name = this.config.name;
2844
- this.options = this.config.defaultOptions;
2845
- }
2846
- static create(config = {}) {
2847
- return new Node(config);
2848
- }
2849
- configure(options = {}) {
2850
- // return a new instance so we can use the same extension
2851
- // with different calls of `configure`
2852
- const extension = this.extend();
2853
- extension.options = mergeDeep(this.options, options);
2854
- return extension;
2855
- }
2856
- extend(extendedConfig = {}) {
2857
- const extension = new Node(extendedConfig);
2858
- extension.parent = this;
2859
- this.child = extension;
2860
- extension.name = extendedConfig.name
2861
- ? extendedConfig.name
2862
- : extension.parent.name;
2863
- extension.options = extendedConfig.defaultOptions
2864
- ? extendedConfig.defaultOptions
2865
- : extension.parent.options;
2866
- return extension;
2867
- }
2868
- }
2869
-
2870
- class Mark {
2871
- constructor(config = {}) {
2872
- this.type = 'mark';
2873
- this.name = 'mark';
2874
- this.parent = null;
2875
- this.child = null;
2876
- this.config = {
2877
- name: this.name,
2878
- defaultOptions: {},
2879
- };
2880
- this.config = {
2881
- ...this.config,
2882
- ...config,
2883
- };
2884
- this.name = this.config.name;
2885
- this.options = this.config.defaultOptions;
2886
- }
2887
- static create(config = {}) {
2888
- return new Mark(config);
2889
- }
2890
- configure(options = {}) {
2891
- // return a new instance so we can use the same extension
2892
- // with different calls of `configure`
2893
- const extension = this.extend();
2894
- extension.options = mergeDeep(this.options, options);
2895
- return extension;
2896
- }
2897
- extend(extendedConfig = {}) {
2898
- const extension = new Mark(extendedConfig);
2899
- extension.parent = this;
2900
- this.child = extension;
2901
- extension.name = extendedConfig.name
2902
- ? extendedConfig.name
2903
- : extension.parent.name;
2904
- extension.options = extendedConfig.defaultOptions
2905
- ? extendedConfig.defaultOptions
2906
- : extension.parent.options;
2907
- return extension;
2908
- }
2909
- }
2910
-
2911
- function isiOS() {
2912
- return [
2913
- 'iPad Simulator',
2914
- 'iPhone Simulator',
2915
- 'iPod Simulator',
2916
- 'iPad',
2917
- 'iPhone',
2918
- 'iPod',
2919
- ].includes(navigator.platform)
2920
- // iPad on iOS 13 detection
2921
- || (navigator.userAgent.includes('Mac') && 'ontouchend' in document);
2922
- }
2923
-
2924
- class NodeView {
2925
- constructor(component, props, options) {
2926
- this.isDragging = false;
2927
- this.component = component;
2928
- this.editor = props.editor;
2929
- this.options = {
2930
- stopEvent: null,
2931
- ignoreMutation: null,
2932
- ...options,
2933
- };
2934
- this.extension = props.extension;
2935
- this.node = props.node;
2936
- this.decorations = props.decorations;
2937
- this.getPos = props.getPos;
2938
- this.mount();
2939
- }
2940
- mount() {
2941
- // eslint-disable-next-line
2942
- return;
2943
- }
2944
- get dom() {
2945
- return null;
2946
- }
2947
- get contentDOM() {
2948
- return null;
2949
- }
2950
- onDragStart(event) {
2951
- var _a, _b, _c;
2952
- const { view } = this.editor;
2953
- const target = event.target;
2954
- // get the drag handle element
2955
- // `closest` is not available for text nodes so we may have to use its parent
2956
- const dragHandle = target.nodeType === 3
2957
- ? (_a = target.parentElement) === null || _a === void 0 ? void 0 : _a.closest('[data-drag-handle]')
2958
- : target.closest('[data-drag-handle]');
2959
- if (!this.dom
2960
- || ((_b = this.contentDOM) === null || _b === void 0 ? void 0 : _b.contains(target))
2961
- || !dragHandle) {
2962
- return;
2963
- }
2964
- let x = 0;
2965
- let y = 0;
2966
- // calculate offset for drag element if we use a different drag handle element
2967
- if (this.dom !== dragHandle) {
2968
- const domBox = this.dom.getBoundingClientRect();
2969
- const handleBox = dragHandle.getBoundingClientRect();
2970
- x = handleBox.x - domBox.x + event.offsetX;
2971
- y = handleBox.y - domBox.y + event.offsetY;
2972
- }
2973
- (_c = event.dataTransfer) === null || _c === void 0 ? void 0 : _c.setDragImage(this.dom, x, y);
2974
- // we need to tell ProseMirror that we want to move the whole node
2975
- // so we create a NodeSelection
2976
- const selection = prosemirrorState.NodeSelection.create(view.state.doc, this.getPos());
2977
- const transaction = view.state.tr.setSelection(selection);
2978
- view.dispatch(transaction);
2979
- }
2980
- stopEvent(event) {
2981
- var _a;
2982
- if (!this.dom) {
2983
- return false;
2984
- }
2985
- if (typeof this.options.stopEvent === 'function') {
2986
- return this.options.stopEvent({ event });
2987
- }
2988
- const target = event.target;
2989
- const isInElement = this.dom.contains(target) && !((_a = this.contentDOM) === null || _a === void 0 ? void 0 : _a.contains(target));
2990
- // any event from child nodes should be handled by ProseMirror
2991
- if (!isInElement) {
2992
- return false;
2993
- }
2994
- const isInput = ['INPUT', 'BUTTON', 'SELECT', 'TEXTAREA'].includes(target.tagName)
2995
- || target.isContentEditable;
2996
- // any input event within node views should be ignored by ProseMirror
2997
- if (isInput) {
2998
- return true;
2999
- }
3000
- const { isEditable } = this.editor;
3001
- const { isDragging } = this;
3002
- const isDraggable = !!this.node.type.spec.draggable;
3003
- const isSelectable = prosemirrorState.NodeSelection.isSelectable(this.node);
3004
- const isCopyEvent = event.type === 'copy';
3005
- const isPasteEvent = event.type === 'paste';
3006
- const isCutEvent = event.type === 'cut';
3007
- const isClickEvent = event.type === 'mousedown';
3008
- const isDragEvent = event.type.startsWith('drag') || event.type === 'drop';
3009
- // ProseMirror tries to drag selectable nodes
3010
- // even if `draggable` is set to `false`
3011
- // this fix prevents that
3012
- if (!isDraggable && isSelectable && isDragEvent) {
3013
- event.preventDefault();
3014
- }
3015
- if (isDraggable && isDragEvent && !isDragging) {
3016
- event.preventDefault();
3017
- return false;
3018
- }
3019
- // we have to store that dragging started
3020
- if (isDraggable && isEditable && !isDragging && isClickEvent) {
3021
- const dragHandle = target.closest('[data-drag-handle]');
3022
- const isValidDragHandle = dragHandle
3023
- && (this.dom === dragHandle || (this.dom.contains(dragHandle)));
3024
- if (isValidDragHandle) {
3025
- this.isDragging = true;
3026
- document.addEventListener('dragend', () => {
3027
- this.isDragging = false;
3028
- }, { once: true });
3029
- document.addEventListener('mouseup', () => {
3030
- this.isDragging = false;
3031
- }, { once: true });
3032
- }
3033
- }
3034
- // these events are handled by prosemirror
3035
- if (isDragging
3036
- || isCopyEvent
3037
- || isPasteEvent
3038
- || isCutEvent
3039
- || (isClickEvent && isSelectable)) {
3040
- return false;
3041
- }
3042
- return true;
3043
- }
3044
- ignoreMutation(mutation) {
3045
- if (!this.dom || !this.contentDOM) {
3046
- return true;
3047
- }
3048
- if (typeof this.options.ignoreMutation === 'function') {
3049
- return this.options.ignoreMutation({ mutation });
3050
- }
3051
- // a leaf/atom node is like a black box for ProseMirror
3052
- // and should be fully handled by the node view
3053
- if (this.node.isLeaf || this.node.isAtom) {
3054
- return true;
3055
- }
3056
- // ProseMirror should handle any selections
3057
- if (mutation.type === 'selection') {
3058
- return false;
3059
- }
3060
- // try to prevent a bug on iOS that will break node views on enter
3061
- // this is because ProseMirror can’t preventDispatch on enter
3062
- // this will lead to a re-render of the node view on enter
3063
- // see: https://github.com/ueberdosis/tiptap/issues/1214
3064
- if (this.dom.contains(mutation.target) && mutation.type === 'childList' && isiOS()) {
3065
- const changedNodes = [
3066
- ...Array.from(mutation.addedNodes),
3067
- ...Array.from(mutation.removedNodes),
3068
- ];
3069
- // we’ll check if every changed node is contentEditable
3070
- // to make sure it’s probably mutated by ProseMirror
3071
- if (changedNodes.every(node => node.isContentEditable)) {
3072
- return false;
3073
- }
3074
- }
3075
- // we will allow mutation contentDOM with attributes
3076
- // so we can for example adding classes within our node view
3077
- if (this.contentDOM === mutation.target && mutation.type === 'attributes') {
3078
- return true;
3079
- }
3080
- // ProseMirror should handle any changes within contentDOM
3081
- if (this.contentDOM.contains(mutation.target)) {
3082
- return false;
3083
- }
3084
- return true;
3085
- }
3086
- updateAttributes(attributes) {
3087
- this.editor.commands.command(({ tr }) => {
3088
- const pos = this.getPos();
3089
- tr.setNodeMarkup(pos, undefined, {
3090
- ...this.node.attrs,
3091
- ...attributes,
3092
- });
3093
- return true;
3094
- });
3095
- }
3096
- deleteNode() {
3097
- const from = this.getPos();
3098
- const to = from + this.node.nodeSize;
3099
- this.editor.commands.deleteRange({ from, to });
3100
- }
3101
- }
3102
-
3103
- class Tracker {
3104
- constructor(transaction) {
3105
- this.transaction = transaction;
3106
- this.currentStep = this.transaction.steps.length;
3107
- }
3108
- map(position) {
3109
- let deleted = false;
3110
- const mappedPosition = this.transaction.steps
3111
- .slice(this.currentStep)
3112
- .reduce((newPosition, step) => {
3113
- const mapResult = step
3114
- .getMap()
3115
- .mapResult(newPosition);
3116
- if (mapResult.deleted) {
3117
- deleted = true;
3118
- }
3119
- return mapResult.pos;
3120
- }, position);
3121
- return {
3122
- position: mappedPosition,
3123
- deleted,
3124
- };
3125
- }
3126
- }
3127
-
3128
- function nodeInputRule (regexp, type, getAttributes) {
3129
- return new prosemirrorInputrules.InputRule(regexp, (state, match, start, end) => {
3130
- const attributes = getAttributes instanceof Function
3131
- ? getAttributes(match)
3132
- : getAttributes;
3133
- const { tr } = state;
3134
- if (match[0]) {
3135
- tr.replaceWith(start - 1, end, type.create(attributes));
3136
- }
3137
- return tr;
3138
- });
3139
- }
3140
-
3141
- function getMarksBetween(from, to, state) {
3142
- let marks = [];
3143
- state.doc.nodesBetween(from, to, (node, pos) => {
3144
- marks = [...marks, ...node.marks.map(mark => ({
3145
- from: pos,
3146
- to: pos + node.nodeSize,
3147
- mark,
3148
- }))];
3149
- });
3150
- return marks;
3151
- }
3152
-
3153
- function markInputRule (regexp, markType, getAttributes) {
3154
- return new prosemirrorInputrules.InputRule(regexp, (state, match, start, end) => {
3155
- const attributes = getAttributes instanceof Function
3156
- ? getAttributes(match)
3157
- : getAttributes;
3158
- const { tr } = state;
3159
- const captureGroup = match[match.length - 1];
3160
- const fullMatch = match[0];
3161
- let markEnd = end;
3162
- if (captureGroup) {
3163
- const startSpaces = fullMatch.search(/\S/);
3164
- const textStart = start + fullMatch.indexOf(captureGroup);
3165
- const textEnd = textStart + captureGroup.length;
3166
- const excludedMarks = getMarksBetween(start, end, state)
3167
- .filter(item => {
3168
- // TODO: PR to add excluded to MarkType
3169
- // @ts-ignore
3170
- const { excluded } = item.mark.type;
3171
- return excluded.find((type) => type.name === markType.name);
3172
- })
3173
- .filter(item => item.to > textStart);
3174
- if (excludedMarks.length) {
3175
- return null;
3176
- }
3177
- if (textEnd < end) {
3178
- tr.delete(textEnd, end);
3179
- }
3180
- if (textStart > start) {
3181
- tr.delete(start + startSpaces, textStart);
3182
- }
3183
- markEnd = start + startSpaces + captureGroup.length;
3184
- tr.addMark(start + startSpaces, markEnd, markType.create(attributes));
3185
- tr.removeStoredMark(markType);
3186
- }
3187
- return tr;
3188
- });
3189
- }
3190
-
3191
- function markPasteRule (regexp, type, getAttributes) {
3192
- const handler = (fragment, parent) => {
3193
- const nodes = [];
3194
- fragment.forEach(child => {
3195
- if (child.isText && child.text) {
3196
- const { text } = child;
3197
- let pos = 0;
3198
- let match;
3199
- // eslint-disable-next-line
3200
- while ((match = regexp.exec(text)) !== null) {
3201
- const outerMatch = Math.max(match.length - 2, 0);
3202
- const innerMatch = Math.max(match.length - 1, 0);
3203
- if (parent === null || parent === void 0 ? void 0 : parent.type.allowsMarkType(type)) {
3204
- const start = match.index;
3205
- const matchStart = start + match[0].indexOf(match[outerMatch]);
3206
- const matchEnd = matchStart + match[outerMatch].length;
3207
- const textStart = matchStart + match[outerMatch].lastIndexOf(match[innerMatch]);
3208
- const textEnd = textStart + match[innerMatch].length;
3209
- const attrs = getAttributes instanceof Function
3210
- ? getAttributes(match)
3211
- : getAttributes;
3212
- if (!attrs && attrs !== undefined) {
3213
- continue;
3214
- }
3215
- // adding text before markdown to nodes
3216
- if (matchStart > 0) {
3217
- nodes.push(child.cut(pos, matchStart));
3218
- }
3219
- // adding the markdown part to nodes
3220
- nodes.push(child
3221
- .cut(textStart, textEnd)
3222
- .mark(type.create(attrs).addToSet(child.marks)));
3223
- pos = matchEnd;
3224
- }
3225
- }
3226
- // adding rest of text to nodes
3227
- if (pos < text.length) {
3228
- nodes.push(child.cut(pos));
3229
- }
3230
- }
3231
- else {
3232
- nodes.push(child.copy(handler(child.content, child)));
3233
- }
3234
- });
3235
- return prosemirrorModel.Fragment.fromArray(nodes);
3236
- };
3237
- return new prosemirrorState.Plugin({
3238
- key: new prosemirrorState.PluginKey('markPasteRule'),
3239
- props: {
3240
- transformPasted: slice => {
3241
- return new prosemirrorModel.Slice(handler(slice.content), slice.openStart, slice.openEnd);
3242
- },
3243
- },
3244
- });
3245
- }
3246
-
3247
- function findChildren(node, predicate) {
3248
- const nodesWithPos = [];
3249
- node.descendants((child, pos) => {
3250
- if (predicate(child)) {
3251
- nodesWithPos.push({
3252
- node: child,
3253
- pos,
3254
- });
3255
- }
3256
- });
3257
- return nodesWithPos;
3258
- }
3259
-
3260
- /**
3261
- * Same as `findChildren` but searches only within a `range`.
3262
- */
3263
- function findChildrenInRange(node, range, predicate) {
3264
- const nodesWithPos = [];
3265
- // if (range.from === range.to) {
3266
- // const nodeAt = node.nodeAt(range.from)
3267
- // if (nodeAt) {
3268
- // nodesWithPos.push({
3269
- // node: nodeAt,
3270
- // pos: range.from,
3271
- // })
3272
- // }
3273
- // }
3274
- node.nodesBetween(range.from, range.to, (child, pos) => {
3275
- if (predicate(child)) {
3276
- nodesWithPos.push({
3277
- node: child,
3278
- pos,
3279
- });
3280
- }
3281
- });
3282
- return nodesWithPos;
3283
- }
3284
-
3285
- function getSchema(extensions) {
3286
- const resolvedExtensions = ExtensionManager.resolve(extensions);
3287
- return getSchemaByResolvedExtensions(resolvedExtensions);
3288
- }
3289
-
3290
- function generateHTML(doc, extensions) {
3291
- const schema = getSchema(extensions);
3292
- const contentNode = prosemirrorModel.Node.fromJSON(schema, doc);
3293
- return getHTMLFromFragment(contentNode, schema);
3294
- }
3295
-
3296
- function generateJSON(html, extensions) {
3297
- const schema = getSchema(extensions);
3298
- const dom = elementFromString(html);
3299
- return prosemirrorModel.DOMParser.fromSchema(schema)
3300
- .parse(dom)
3301
- .toJSON();
3302
- }
3303
-
3304
- /**
3305
- * Returns a node tree with node positions.
3306
- */
3307
- function getDebugJSON(node, startOffset = 0) {
3308
- const nodes = [];
3309
- node.forEach((n, offset) => {
3310
- const from = startOffset + offset;
3311
- const to = from + n.nodeSize;
3312
- const marks = n.marks.map(mark => ({
3313
- type: mark.type.name,
3314
- attrs: { ...mark.attrs },
3315
- }));
3316
- const attrs = { ...n.attrs };
3317
- const content = getDebugJSON(n, from + 1);
3318
- const output = {
3319
- type: n.type.name,
3320
- from,
3321
- to,
3322
- };
3323
- if (Object.keys(attrs).length) {
3324
- output.attrs = attrs;
3325
- }
3326
- if (marks.length) {
3327
- output.marks = marks;
3328
- }
3329
- if (content.length) {
3330
- output.content = content;
3331
- }
3332
- if (n.text) {
3333
- output.text = n.text;
3334
- }
3335
- nodes.push(output);
3336
- });
3337
- return nodes;
3338
- }
3339
-
3340
- function isNodeSelection(value) {
3341
- return isObject(value) && value instanceof prosemirrorState.NodeSelection;
3342
- }
3343
-
3344
- function posToDOMRect(view, from, to) {
3345
- const start = view.coordsAtPos(from);
3346
- const end = view.coordsAtPos(to, -1);
3347
- const top = Math.min(start.top, end.top);
3348
- const bottom = Math.max(start.bottom, end.bottom);
3349
- const left = Math.min(start.left, end.left);
3350
- const right = Math.max(start.right, end.right);
3351
- const width = right - left;
3352
- const height = bottom - top;
3353
- const x = left;
3354
- const y = top;
3355
- const data = {
3356
- top,
3357
- bottom,
3358
- left,
3359
- right,
3360
- width,
3361
- height,
3362
- x,
3363
- y,
3364
- };
3365
- return {
3366
- ...data,
3367
- toJSON: () => data,
3368
- };
3369
- }
3370
-
3371
- exports.Editor = Editor;
3372
- exports.Extension = Extension;
3373
- exports.Mark = Mark;
3374
- exports.Node = Node;
3375
- exports.NodeView = NodeView;
3376
- exports.Tracker = Tracker;
3377
- exports.callOrReturn = callOrReturn;
3378
- exports.extensions = extensions;
3379
- exports.findChildren = findChildren;
3380
- exports.findChildrenInRange = findChildrenInRange;
3381
- exports.findParentNode = findParentNode;
3382
- exports.findParentNodeClosestToPos = findParentNodeClosestToPos;
3383
- exports.generateHTML = generateHTML;
3384
- exports.generateJSON = generateJSON;
3385
- exports.getAttributes = getAttributes;
3386
- exports.getDebugJSON = getDebugJSON;
3387
- exports.getExtensionField = getExtensionField;
3388
- exports.getHTMLFromFragment = getHTMLFromFragment;
3389
- exports.getMarkAttributes = getMarkAttributes;
3390
- exports.getMarkRange = getMarkRange;
3391
- exports.getMarkType = getMarkType;
3392
- exports.getMarksBetween = getMarksBetween;
3393
- exports.getNodeAttributes = getNodeAttributes;
3394
- exports.getNodeType = getNodeType;
3395
- exports.getSchema = getSchema;
3396
- exports.isActive = isActive;
3397
- exports.isList = isList;
3398
- exports.isMarkActive = isMarkActive;
3399
- exports.isNodeActive = isNodeActive;
3400
- exports.isNodeEmpty = isNodeEmpty;
3401
- exports.isNodeSelection = isNodeSelection;
3402
- exports.isTextSelection = isTextSelection;
3403
- exports.markInputRule = markInputRule;
3404
- exports.markPasteRule = markPasteRule;
3405
- exports.mergeAttributes = mergeAttributes;
3406
- exports.nodeInputRule = nodeInputRule;
3407
- exports.posToDOMRect = posToDOMRect;
3408
- //# sourceMappingURL=tiptap-core.cjs.js.map