@tiptap/extension-unique-id 2.0.0-beta.3 → 2.22.0

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 (31) hide show
  1. package/README.md +14 -0
  2. package/dist/helpers/findDuplicates.d.ts +5 -0
  3. package/dist/helpers/findDuplicates.d.ts.map +1 -0
  4. package/dist/helpers/removeDuplicates.d.ts +9 -0
  5. package/dist/helpers/removeDuplicates.d.ts.map +1 -0
  6. package/dist/{tiptap-extension-unique-id.cjs.js → index.cjs} +253 -280
  7. package/dist/index.cjs.map +1 -0
  8. package/dist/index.d.ts +4 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/{tiptap-extension-unique-id.esm.js → index.js} +253 -280
  11. package/dist/index.js.map +1 -0
  12. package/dist/{tiptap-extension-unique-id.umd.js → index.umd.js} +255 -281
  13. package/dist/index.umd.js.map +1 -0
  14. package/dist/{tiptap-pro/packages/extension-unique-id/src/unique-id.d.ts → unique-id.d.ts} +10 -9
  15. package/dist/unique-id.d.ts.map +1 -0
  16. package/package.json +31 -13
  17. package/src/helpers/findDuplicates.ts +2 -2
  18. package/src/helpers/removeDuplicates.ts +1 -1
  19. package/src/index.ts +2 -2
  20. package/src/unique-id.ts +104 -38
  21. package/dist/tiptap-extension-unique-id.cjs.js.map +0 -1
  22. package/dist/tiptap-extension-unique-id.esm.js.map +0 -1
  23. package/dist/tiptap-extension-unique-id.umd.js.map +0 -1
  24. package/dist/tiptap-pro/packages/extension-unique-id/src/helpers/combineTransactionSteps.d.ts +0 -7
  25. package/dist/tiptap-pro/packages/extension-unique-id/src/helpers/findDuplicates.d.ts +0 -4
  26. package/dist/tiptap-pro/packages/extension-unique-id/src/helpers/getChangedRanges.d.ts +0 -12
  27. package/dist/tiptap-pro/packages/extension-unique-id/src/helpers/removeDuplicates.d.ts +0 -8
  28. package/dist/tiptap-pro/packages/extension-unique-id/src/index.d.ts +0 -3
  29. package/src/helpers/arrayDifference.ts +0 -35
  30. package/src/helpers/combineTransactionSteps.ts +0 -18
  31. package/src/helpers/getChangedRanges.ts +0 -78
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/helpers/removeDuplicates.ts","../src/helpers/findDuplicates.ts","../src/unique-id.ts"],"sourcesContent":["/**\n * Removes duplicated values within an array.\n * Supports numbers, strings and objects.\n */\nexport function removeDuplicates<T>(array: T[], by = JSON.stringify): T[] {\n const seen: Record<any, any> = {}\n\n return array.filter(item => {\n const key = by(item)\n\n return Object.prototype.hasOwnProperty.call(seen, key)\n ? false\n : (seen[key] = true)\n })\n}\n","import { removeDuplicates } from './removeDuplicates.js'\n\n/**\n * Returns a list of duplicated items within an array.\n */\nexport function findDuplicates(items: any[]): any[] {\n const filtered = items.filter((el, index) => items.indexOf(el) !== index)\n const duplicates = removeDuplicates(filtered)\n\n return duplicates\n}\n","import {\n combineTransactionSteps,\n Extension,\n findChildren,\n findChildrenInRange,\n getChangedRanges,\n} from '@tiptap/core'\nimport { Fragment, Node as ProseMirrorNode, Slice } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, Transaction } from '@tiptap/pm/state'\nimport { v4 as uuidv4 } from 'uuid'\n\nimport { findDuplicates } from './helpers/findDuplicates.js'\n\nexport interface UniqueIDOptions {\n attributeName: string,\n types: string[],\n generateID: () => any,\n filterTransaction: ((transaction: Transaction) => boolean) | null,\n}\n\nexport const UniqueID = Extension.create<UniqueIDOptions>({\n name: 'uniqueID',\n\n // we’ll set a very high priority to make sure this runs first\n // and is compatible with `appendTransaction` hooks of other extensions\n priority: 10000,\n\n addOptions() {\n return {\n attributeName: 'id',\n types: [],\n generateID: () => uuidv4(),\n filterTransaction: null,\n }\n },\n\n addGlobalAttributes() {\n return [\n {\n types: this.options.types,\n attributes: {\n [this.options.attributeName]: {\n default: null,\n parseHTML: element => element.getAttribute(`data-${this.options.attributeName}`),\n renderHTML: attributes => {\n if (!attributes[this.options.attributeName]) {\n return {}\n }\n\n return {\n [`data-${this.options.attributeName}`]: attributes[this.options.attributeName],\n }\n },\n },\n },\n },\n ]\n },\n\n // check initial content for missing ids\n onCreate() {\n const collab = this.editor.extensionManager.extensions.find(ext => ext.name === 'collaboration')\n const provider = collab?.options ? collab.options.provider : undefined\n\n const createIds = () => {\n const { view, state } = this.editor\n const { tr, doc } = state\n const { types, attributeName, generateID } = this.options\n const nodesWithoutId = findChildren(doc, node => {\n return types.includes(node.type.name) && node.attrs[attributeName] === null\n })\n\n nodesWithoutId.forEach(({ node, pos }) => {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n [attributeName]: generateID(),\n })\n })\n\n tr.setMeta('addToHistory', false)\n\n view.dispatch(tr)\n\n if (provider) {\n provider.off('synced', createIds)\n }\n }\n\n /**\n * We need to handle collaboration a bit different here\n * because we can't automatically add IDs when the provider is not yet synced\n * otherwise we end up with empty paragraphs\n */\n if (collab) {\n if (!provider) {\n return createIds()\n }\n\n provider.on('synced', createIds)\n } else {\n return createIds()\n }\n },\n\n addProseMirrorPlugins() {\n let dragSourceElement: Element | null = null\n let transformPasted = false\n\n return [\n new Plugin({\n key: new PluginKey('uniqueID'),\n\n appendTransaction: (transactions, oldState, newState) => {\n const hasDocChanges = transactions.some(transaction => transaction.docChanged)\n && !oldState.doc.eq(newState.doc)\n const filterTransactions = this.options.filterTransaction\n && transactions.some(tr => !this.options.filterTransaction?.(tr))\n\n const isCollabTransaction = transactions.find(tr => tr.getMeta('y-sync$'))\n\n if (isCollabTransaction) {\n return\n }\n\n if (!hasDocChanges || filterTransactions) {\n return\n }\n\n const { tr } = newState\n\n const { types, attributeName, generateID } = this.options\n const transform = combineTransactionSteps(oldState.doc, transactions as Transaction[])\n const { mapping } = transform\n\n // get changed ranges based on the old state\n const changes = getChangedRanges(transform)\n\n changes.forEach(({ newRange }) => {\n const newNodes = findChildrenInRange(newState.doc, newRange, node => {\n return types.includes(node.type.name)\n })\n\n const newIds = newNodes\n .map(({ node }) => node.attrs[attributeName])\n .filter(id => id !== null)\n\n newNodes.forEach(({ node, pos }, i) => {\n // instead of checking `node.attrs[attributeName]` directly\n // we look at the current state of the node within `tr.doc`.\n // this helps to prevent adding new ids to the same node\n // if the node changed multiple times within one transaction\n const id = tr.doc.nodeAt(pos)?.attrs[attributeName]\n\n if (id === null) {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n [attributeName]: generateID(),\n })\n\n return\n }\n\n const nextNode = newNodes[i + 1]\n\n if (nextNode && node.content.size === 0) {\n tr.setNodeMarkup(nextNode.pos, undefined, {\n ...nextNode.node.attrs,\n [attributeName]: id,\n })\n newIds[i + 1] = id\n\n if (nextNode.node.attrs[attributeName]) {\n return\n }\n\n const generatedId = generateID()\n\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n [attributeName]: generatedId,\n })\n newIds[i] = generatedId\n\n return tr\n }\n\n const duplicatedNewIds = findDuplicates(newIds)\n\n // check if the node doesn’t exist in the old state\n const { deleted } = mapping.invert().mapResult(pos)\n\n const newNode = deleted && duplicatedNewIds.includes(id)\n\n if (newNode) {\n tr.setNodeMarkup(pos, undefined, {\n ...node.attrs,\n [attributeName]: generateID(),\n })\n }\n })\n\n })\n\n if (!tr.steps.length) {\n return\n }\n\n // `tr.setNodeMarkup` resets the stored marks\n // so we’ll restore them if they exist\n tr.setStoredMarks(newState.tr.storedMarks)\n\n return tr\n },\n\n // we register a global drag handler to track the current drag source element\n view(view) {\n const handleDragstart = (event: DragEvent) => {\n dragSourceElement = view.dom.parentElement?.contains(event.target as Element)\n ? view.dom.parentElement\n : null\n }\n\n window.addEventListener('dragstart', handleDragstart)\n\n return {\n destroy() {\n window.removeEventListener('dragstart', handleDragstart)\n },\n }\n },\n\n props: {\n // `handleDOMEvents` is called before `transformPasted`\n // so we can do some checks before\n handleDOMEvents: {\n // only create new ids for dropped content\n // or dropped content while holding `alt`\n // or content is dragged from another editor\n drop: (view, event) => {\n if (\n dragSourceElement !== view.dom.parentElement\n || event.dataTransfer?.effectAllowed === 'copyMove'\n || event.dataTransfer?.effectAllowed === 'copy'\n ) {\n dragSourceElement = null\n transformPasted = true\n }\n\n return false\n },\n // always create new ids on pasted content\n paste: () => {\n transformPasted = true\n\n return false\n },\n },\n\n // we’ll remove ids for every pasted node\n // so we can create a new one within `appendTransaction`\n transformPasted: slice => {\n if (!transformPasted) {\n return slice\n }\n\n const { types, attributeName } = this.options\n const removeId = (fragment: Fragment): Fragment => {\n const list: ProseMirrorNode[] = []\n\n fragment.forEach(node => {\n // don’t touch text nodes\n if (node.isText) {\n list.push(node)\n\n return\n }\n\n // check for any other child nodes\n if (!types.includes(node.type.name)) {\n list.push(node.copy(removeId(node.content)))\n\n return\n }\n\n // remove id\n const nodeWithoutId = node.type.create(\n {\n ...node.attrs,\n [attributeName]: null,\n },\n removeId(node.content),\n node.marks,\n )\n\n list.push(nodeWithoutId)\n })\n\n return Fragment.from(list)\n }\n\n // reset check\n transformPasted = false\n\n return new Slice(removeId(slice.content), slice.openStart, slice.openEnd)\n },\n },\n }),\n ]\n },\n\n})\n"],"names":["Extension","uuidv4","findChildren","Plugin","PluginKey","combineTransactionSteps","getChangedRanges","findChildrenInRange","Fragment","Slice"],"mappings":";;;;;;;;;AAAA;;;AAGG;AACG,SAAU,gBAAgB,CAAI,KAAU,EAAE,EAAE,GAAG,IAAI,CAAC,SAAS,EAAA;IACjE,MAAM,IAAI,GAAqB,EAAE;AAEjC,IAAA,OAAO,KAAK,CAAC,MAAM,CAAC,IAAI,IAAG;AACzB,QAAA,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC;QAEpB,OAAO,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG;AACnD,cAAE;eACC,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;AACxB,KAAC,CAAC;AACJ;;ACZA;;AAEG;AACG,SAAU,cAAc,CAAC,KAAY,EAAA;IACzC,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC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M,QAAQ,GAAG,CAAC,QAAkB,KAAc;4BAChD,MAAM,IAAI,GAAsB,EAAE;AAElC,4BAAA,QAAQ,CAAC,OAAO,CAAC,IAAI,IAAG;;AAEtB,gCAAA,IAAI,IAAI,CAAC,MAAM,EAAE;AACf,oCAAA,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;oCAEf;;;AAIF,gCAAA,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;AACnC,oCAAA,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;oCAE5C;;;AAIF,gCAAA,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CACpC;oCACE,GAAG,IAAI,CAAC,KAAK;oCACb,CAAC,aAAa,GAAG,IAAI;iCACtB,EACD,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,EACtB,IAAI,CAAC,KAAK,CACX;AAED,gCAAA,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC;AAC1B,6BAAC,CAAC;AAEF,4BAAA,OAAOC,cAAQ,CAAC,IAAI,CAAC,IAAI,CAAC;AAC5B,yBAAC;;wBAGD,eAAe,GAAG,KAAK;AAEvB,wBAAA,OAAO,IAAIC,WAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC;qBAC1E;AACF,iBAAA;aACF,CAAC;SACH;KACF;AAEF,CAAA;;;;;"}
@@ -0,0 +1,4 @@
1
+ import { UniqueID } from './unique-id.js';
2
+ export * from './unique-id.js';
3
+ export default UniqueID;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEzC,cAAc,gBAAgB,CAAA;AAE9B,eAAe,QAAQ,CAAA"}
@@ -1,289 +1,262 @@
1
- import { Extension, findChildren, findChildrenInRange } from '@tiptap/core';
2
- import { Plugin, PluginKey } from 'prosemirror-state';
3
- import { Slice, Fragment } from 'prosemirror-model';
1
+ import { Extension, combineTransactionSteps, getChangedRanges, findChildrenInRange, findChildren } from '@tiptap/core';
2
+ import { Slice, Fragment } from '@tiptap/pm/model';
3
+ import { Plugin, PluginKey } from '@tiptap/pm/state';
4
4
  import { v4 } from 'uuid';
5
- import { Transform } from 'prosemirror-transform';
6
5
 
7
- /**
8
- * Returns a new `Transform` based on all steps of the passed transactions.
9
- */
10
- function combineTransactionSteps(oldDoc, transactions) {
11
- const transform = new Transform(oldDoc);
12
- transactions.forEach(transaction => {
13
- transaction.steps.forEach(step => {
14
- transform.step(step);
15
- });
16
- });
17
- return transform;
6
+ /**
7
+ * Removes duplicated values within an array.
8
+ * Supports numbers, strings and objects.
9
+ */
10
+ function removeDuplicates(array, by = JSON.stringify) {
11
+ const seen = {};
12
+ return array.filter(item => {
13
+ const key = by(item);
14
+ return Object.prototype.hasOwnProperty.call(seen, key)
15
+ ? false
16
+ : (seen[key] = true);
17
+ });
18
18
  }
19
19
 
20
- /**
21
- * Removes duplicated values within an array.
22
- * Supports numbers, strings and objects.
23
- */
24
- function removeDuplicates(array, by = JSON.stringify) {
25
- const seen = {};
26
- return array.filter(item => {
27
- const key = by(item);
28
- return Object.prototype.hasOwnProperty.call(seen, key)
29
- ? false
30
- : (seen[key] = true);
31
- });
20
+ /**
21
+ * Returns a list of duplicated items within an array.
22
+ */
23
+ function findDuplicates(items) {
24
+ const filtered = items.filter((el, index) => items.indexOf(el) !== index);
25
+ const duplicates = removeDuplicates(filtered);
26
+ return duplicates;
32
27
  }
33
28
 
34
- /**
35
- * Removes duplicated ranges and ranges that are
36
- * fully captured by other ranges.
37
- */
38
- function simplifyChangedRanges(changes) {
39
- const uniqueChanges = removeDuplicates(changes);
40
- return uniqueChanges.length === 1
41
- ? uniqueChanges
42
- : uniqueChanges.filter((change, index) => {
43
- const rest = uniqueChanges.filter((_, i) => i !== index);
44
- return !rest.some(otherChange => {
45
- return change.oldStart >= otherChange.oldStart
46
- && change.oldEnd <= otherChange.oldEnd
47
- && change.newStart >= otherChange.newStart
48
- && change.newEnd <= otherChange.newEnd;
49
- });
50
- });
51
- }
52
- /**
53
- * Returns a list of changed ranges
54
- * based on the first and last state of all steps.
55
- */
56
- function getChangedRanges(transform) {
57
- const { mapping, steps } = transform;
58
- const changes = [];
59
- mapping.maps.forEach((stepMap, index) => {
60
- // This accounts for step changes where no range was actually altered
61
- // e.g. when setting a mark, node attribute, etc.
62
- // @ts-ignore
63
- if (!stepMap.ranges.length) {
64
- const step = steps[index];
65
- if (step.from === undefined || step.to === undefined) {
66
- return;
67
- }
68
- changes.push({
69
- oldStart: step.from,
70
- oldEnd: step.to,
71
- newStart: step.from,
72
- newEnd: step.to,
73
- });
74
- }
75
- else {
76
- stepMap.forEach((from, to) => {
77
- const newStart = mapping.slice(index).map(from, -1);
78
- const newEnd = mapping.slice(index).map(to);
79
- const oldStart = mapping.invert().map(newStart, -1);
80
- const oldEnd = mapping.invert().map(newEnd);
81
- changes.push({
82
- oldStart,
83
- oldEnd,
84
- newStart,
85
- newEnd,
86
- });
87
- });
88
- }
89
- });
90
- return simplifyChangedRanges(changes);
91
- }
92
-
93
- /**
94
- * Returns a list of duplicated items within an array.
95
- */
96
- function findDuplicates(items) {
97
- const filtered = items.filter((el, index) => items.indexOf(el) !== index);
98
- const duplicates = removeDuplicates(filtered);
99
- return duplicates;
100
- }
101
-
102
- const UniqueID = Extension.create({
103
- name: 'uniqueID',
104
- // we’ll set a very high priority to make sure this runs first
105
- // and is compatible with `appendTransaction` hooks of other extensions
106
- priority: 10000,
107
- defaultOptions: {
108
- attributeName: 'id',
109
- types: [],
110
- generateID: () => v4(),
111
- filterTransaction: null,
112
- },
113
- addGlobalAttributes() {
114
- return [
115
- {
116
- types: this.options.types,
117
- attributes: {
118
- [this.options.attributeName]: {
119
- default: null,
120
- parseHTML: element => element.getAttribute(`data-${this.options.attributeName}`),
121
- renderHTML: attributes => {
122
- if (!attributes[this.options.attributeName]) {
123
- return {};
124
- }
125
- return {
126
- [`data-${this.options.attributeName}`]: attributes[this.options.attributeName],
127
- };
128
- },
129
- },
130
- },
131
- },
132
- ];
133
- },
134
- // check initial content for missing ids
135
- onCreate() {
136
- const { view, state } = this.editor;
137
- const { tr, doc } = state;
138
- const { types, attributeName, generateID } = this.options;
139
- const nodesWithoutId = findChildren(doc, node => {
140
- return types.includes(node.type.name)
141
- && node.attrs[attributeName] === null;
142
- });
143
- nodesWithoutId.forEach(({ node, pos }) => {
144
- tr.setNodeMarkup(pos, undefined, {
145
- ...node.attrs,
146
- [attributeName]: generateID(),
147
- });
148
- });
149
- view.dispatch(tr);
150
- },
151
- addProseMirrorPlugins() {
152
- let dragSourceElement = null;
153
- let transformPasted = false;
154
- return [
155
- new Plugin({
156
- key: new PluginKey('uniqueID'),
157
- appendTransaction: (transactions, oldState, newState) => {
158
- const docChanges = transactions.some(transaction => transaction.docChanged)
159
- && !oldState.doc.eq(newState.doc);
160
- const filterTransactions = this.options.filterTransaction
161
- && transactions.some(tr => { var _a, _b; return !((_b = (_a = this.options).filterTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, tr)); });
162
- if (!docChanges || filterTransactions) {
163
- return;
164
- }
165
- const { tr } = newState;
166
- const { types, attributeName, generateID } = this.options;
167
- const transform = combineTransactionSteps(oldState.doc, transactions);
168
- const { mapping } = transform;
169
- // get changed ranges based on the old state
170
- const changes = getChangedRanges(transform);
171
- changes.forEach(change => {
172
- const newRange = {
173
- from: change.newStart,
174
- to: change.newEnd,
175
- };
176
- const newNodes = findChildrenInRange(newState.doc, newRange, node => {
177
- return types.includes(node.type.name);
178
- });
179
- const newIds = newNodes
180
- .map(({ node }) => node.attrs[attributeName])
181
- .filter(id => id !== null);
182
- const duplicatedNewIds = findDuplicates(newIds);
183
- newNodes.forEach(({ node, pos }) => {
184
- var _a;
185
- // instead of checking `node.attrs[attributeName]` directly
186
- // we look at the current state of the node within `tr.doc`.
187
- // this helps to prevent adding new ids to the same node
188
- // if the node changed multiple times within one transaction
189
- const id = (_a = tr.doc.nodeAt(pos)) === null || _a === void 0 ? void 0 : _a.attrs[attributeName];
190
- if (id === null) {
191
- tr.setNodeMarkup(pos, undefined, {
192
- ...node.attrs,
193
- [attributeName]: generateID(),
194
- });
195
- return;
196
- }
197
- // check if the node doesn’t exist in the old state
198
- const { deleted } = mapping.invert().mapResult(pos);
199
- const newNode = deleted && duplicatedNewIds.includes(id);
200
- if (newNode) {
201
- tr.setNodeMarkup(pos, undefined, {
202
- ...node.attrs,
203
- [attributeName]: generateID(),
204
- });
205
- }
206
- });
207
- });
208
- if (!tr.steps.length) {
209
- return;
210
- }
211
- return tr;
212
- },
213
- // we register a global drag handler to track the current drag source element
214
- view(view) {
215
- const handleDragstart = (event) => {
216
- var _a;
217
- dragSourceElement = ((_a = view.dom.parentElement) === null || _a === void 0 ? void 0 : _a.contains(event.target))
218
- ? view.dom.parentElement
219
- : null;
220
- };
221
- window.addEventListener('dragstart', handleDragstart);
222
- return {
223
- destroy() {
224
- window.removeEventListener('dragstart', handleDragstart);
225
- },
226
- };
227
- },
228
- props: {
229
- // `handleDOMEvents` is called before `transformPasted`
230
- // so we can do some checks before
231
- handleDOMEvents: {
232
- // only create new ids for dropped content while holding `alt`
233
- // or content is dragged from another editor
234
- drop: (view, event) => {
235
- var _a;
236
- if (dragSourceElement !== view.dom.parentElement
237
- || ((_a = event.dataTransfer) === null || _a === void 0 ? void 0 : _a.effectAllowed) === 'copy') {
238
- dragSourceElement = null;
239
- transformPasted = true;
240
- }
241
- return false;
242
- },
243
- // always create new ids on pasted content
244
- paste: () => {
245
- transformPasted = true;
246
- return false;
247
- },
248
- },
249
- // we’ll remove ids for every pasted node
250
- // so we can create a new one within `appendTransaction`
251
- transformPasted: slice => {
252
- if (!transformPasted) {
253
- return slice;
254
- }
255
- const { types, attributeName } = this.options;
256
- const removeId = (fragment) => {
257
- const list = [];
258
- fragment.forEach(node => {
259
- // don’t touch text nodes
260
- if (node.isText) {
261
- list.push(node);
262
- return;
263
- }
264
- // check for any other child nodes
265
- if (!types.includes(node.type.name)) {
266
- list.push(node.copy(removeId(node.content)));
267
- return;
268
- }
269
- // remove id
270
- const nodeWithoutId = node.type.create({
271
- ...node.attrs,
272
- [attributeName]: null,
273
- }, removeId(node.content), node.marks);
274
- list.push(nodeWithoutId);
275
- });
276
- return Fragment.from(list);
277
- };
278
- // reset check
279
- transformPasted = false;
280
- return new Slice(removeId(slice.content), slice.openStart, slice.openEnd);
281
- },
282
- },
283
- }),
284
- ];
285
- },
29
+ const UniqueID = Extension.create({
30
+ name: 'uniqueID',
31
+ // we’ll set a very high priority to make sure this runs first
32
+ // and is compatible with `appendTransaction` hooks of other extensions
33
+ priority: 10000,
34
+ addOptions() {
35
+ return {
36
+ attributeName: 'id',
37
+ types: [],
38
+ generateID: () => v4(),
39
+ filterTransaction: null,
40
+ };
41
+ },
42
+ addGlobalAttributes() {
43
+ return [
44
+ {
45
+ types: this.options.types,
46
+ attributes: {
47
+ [this.options.attributeName]: {
48
+ default: null,
49
+ parseHTML: element => element.getAttribute(`data-${this.options.attributeName}`),
50
+ renderHTML: attributes => {
51
+ if (!attributes[this.options.attributeName]) {
52
+ return {};
53
+ }
54
+ return {
55
+ [`data-${this.options.attributeName}`]: attributes[this.options.attributeName],
56
+ };
57
+ },
58
+ },
59
+ },
60
+ },
61
+ ];
62
+ },
63
+ // check initial content for missing ids
64
+ onCreate() {
65
+ const collab = this.editor.extensionManager.extensions.find(ext => ext.name === 'collaboration');
66
+ const provider = (collab === null || collab === void 0 ? void 0 : collab.options) ? collab.options.provider : undefined;
67
+ const createIds = () => {
68
+ const { view, state } = this.editor;
69
+ const { tr, doc } = state;
70
+ const { types, attributeName, generateID } = this.options;
71
+ const nodesWithoutId = findChildren(doc, node => {
72
+ return types.includes(node.type.name) && node.attrs[attributeName] === null;
73
+ });
74
+ nodesWithoutId.forEach(({ node, pos }) => {
75
+ tr.setNodeMarkup(pos, undefined, {
76
+ ...node.attrs,
77
+ [attributeName]: generateID(),
78
+ });
79
+ });
80
+ tr.setMeta('addToHistory', false);
81
+ view.dispatch(tr);
82
+ if (provider) {
83
+ provider.off('synced', createIds);
84
+ }
85
+ };
86
+ /**
87
+ * We need to handle collaboration a bit different here
88
+ * because we can't automatically add IDs when the provider is not yet synced
89
+ * otherwise we end up with empty paragraphs
90
+ */
91
+ if (collab) {
92
+ if (!provider) {
93
+ return createIds();
94
+ }
95
+ provider.on('synced', createIds);
96
+ }
97
+ else {
98
+ return createIds();
99
+ }
100
+ },
101
+ addProseMirrorPlugins() {
102
+ let dragSourceElement = null;
103
+ let transformPasted = false;
104
+ return [
105
+ new Plugin({
106
+ key: new PluginKey('uniqueID'),
107
+ appendTransaction: (transactions, oldState, newState) => {
108
+ const hasDocChanges = transactions.some(transaction => transaction.docChanged)
109
+ && !oldState.doc.eq(newState.doc);
110
+ const filterTransactions = this.options.filterTransaction
111
+ && transactions.some(tr => { var _a, _b; return !((_b = (_a = this.options).filterTransaction) === null || _b === void 0 ? void 0 : _b.call(_a, tr)); });
112
+ const isCollabTransaction = transactions.find(tr => tr.getMeta('y-sync$'));
113
+ if (isCollabTransaction) {
114
+ return;
115
+ }
116
+ if (!hasDocChanges || filterTransactions) {
117
+ return;
118
+ }
119
+ const { tr } = newState;
120
+ const { types, attributeName, generateID } = this.options;
121
+ const transform = combineTransactionSteps(oldState.doc, transactions);
122
+ const { mapping } = transform;
123
+ // get changed ranges based on the old state
124
+ const changes = getChangedRanges(transform);
125
+ changes.forEach(({ newRange }) => {
126
+ const newNodes = findChildrenInRange(newState.doc, newRange, node => {
127
+ return types.includes(node.type.name);
128
+ });
129
+ const newIds = newNodes
130
+ .map(({ node }) => node.attrs[attributeName])
131
+ .filter(id => id !== null);
132
+ newNodes.forEach(({ node, pos }, i) => {
133
+ var _a;
134
+ // instead of checking `node.attrs[attributeName]` directly
135
+ // we look at the current state of the node within `tr.doc`.
136
+ // this helps to prevent adding new ids to the same node
137
+ // if the node changed multiple times within one transaction
138
+ const id = (_a = tr.doc.nodeAt(pos)) === null || _a === void 0 ? void 0 : _a.attrs[attributeName];
139
+ if (id === null) {
140
+ tr.setNodeMarkup(pos, undefined, {
141
+ ...node.attrs,
142
+ [attributeName]: generateID(),
143
+ });
144
+ return;
145
+ }
146
+ const nextNode = newNodes[i + 1];
147
+ if (nextNode && node.content.size === 0) {
148
+ tr.setNodeMarkup(nextNode.pos, undefined, {
149
+ ...nextNode.node.attrs,
150
+ [attributeName]: id,
151
+ });
152
+ newIds[i + 1] = id;
153
+ if (nextNode.node.attrs[attributeName]) {
154
+ return;
155
+ }
156
+ const generatedId = generateID();
157
+ tr.setNodeMarkup(pos, undefined, {
158
+ ...node.attrs,
159
+ [attributeName]: generatedId,
160
+ });
161
+ newIds[i] = generatedId;
162
+ return tr;
163
+ }
164
+ const duplicatedNewIds = findDuplicates(newIds);
165
+ // check if the node doesn’t exist in the old state
166
+ const { deleted } = mapping.invert().mapResult(pos);
167
+ const newNode = deleted && duplicatedNewIds.includes(id);
168
+ if (newNode) {
169
+ tr.setNodeMarkup(pos, undefined, {
170
+ ...node.attrs,
171
+ [attributeName]: generateID(),
172
+ });
173
+ }
174
+ });
175
+ });
176
+ if (!tr.steps.length) {
177
+ return;
178
+ }
179
+ // `tr.setNodeMarkup` resets the stored marks
180
+ // so we’ll restore them if they exist
181
+ tr.setStoredMarks(newState.tr.storedMarks);
182
+ return tr;
183
+ },
184
+ // we register a global drag handler to track the current drag source element
185
+ view(view) {
186
+ const handleDragstart = (event) => {
187
+ var _a;
188
+ dragSourceElement = ((_a = view.dom.parentElement) === null || _a === void 0 ? void 0 : _a.contains(event.target))
189
+ ? view.dom.parentElement
190
+ : null;
191
+ };
192
+ window.addEventListener('dragstart', handleDragstart);
193
+ return {
194
+ destroy() {
195
+ window.removeEventListener('dragstart', handleDragstart);
196
+ },
197
+ };
198
+ },
199
+ props: {
200
+ // `handleDOMEvents` is called before `transformPasted`
201
+ // so we can do some checks before
202
+ handleDOMEvents: {
203
+ // only create new ids for dropped content
204
+ // or dropped content while holding `alt`
205
+ // or content is dragged from another editor
206
+ drop: (view, event) => {
207
+ var _a, _b;
208
+ if (dragSourceElement !== view.dom.parentElement
209
+ || ((_a = event.dataTransfer) === null || _a === void 0 ? void 0 : _a.effectAllowed) === 'copyMove'
210
+ || ((_b = event.dataTransfer) === null || _b === void 0 ? void 0 : _b.effectAllowed) === 'copy') {
211
+ dragSourceElement = null;
212
+ transformPasted = true;
213
+ }
214
+ return false;
215
+ },
216
+ // always create new ids on pasted content
217
+ paste: () => {
218
+ transformPasted = true;
219
+ return false;
220
+ },
221
+ },
222
+ // we’ll remove ids for every pasted node
223
+ // so we can create a new one within `appendTransaction`
224
+ transformPasted: slice => {
225
+ if (!transformPasted) {
226
+ return slice;
227
+ }
228
+ const { types, attributeName } = this.options;
229
+ const removeId = (fragment) => {
230
+ const list = [];
231
+ fragment.forEach(node => {
232
+ // don’t touch text nodes
233
+ if (node.isText) {
234
+ list.push(node);
235
+ return;
236
+ }
237
+ // check for any other child nodes
238
+ if (!types.includes(node.type.name)) {
239
+ list.push(node.copy(removeId(node.content)));
240
+ return;
241
+ }
242
+ // remove id
243
+ const nodeWithoutId = node.type.create({
244
+ ...node.attrs,
245
+ [attributeName]: null,
246
+ }, removeId(node.content), node.marks);
247
+ list.push(nodeWithoutId);
248
+ });
249
+ return Fragment.from(list);
250
+ };
251
+ // reset check
252
+ transformPasted = false;
253
+ return new Slice(removeId(slice.content), slice.openStart, slice.openEnd);
254
+ },
255
+ },
256
+ }),
257
+ ];
258
+ },
286
259
  });
287
260
 
288
261
  export { UniqueID, UniqueID as default };
289
- //# sourceMappingURL=tiptap-extension-unique-id.esm.js.map
262
+ //# sourceMappingURL=index.js.map