@dou-ui/editor 0.1.0-alpha.17 → 0.1.0-alpha.18

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 (38) hide show
  1. package/dist/collaboration/binding.js +39 -49
  2. package/dist/collaboration/binding.js.map +1 -1
  3. package/dist/collaboration/inline-diff.js +138 -0
  4. package/dist/collaboration/inline-diff.js.map +1 -0
  5. package/dist/collaboration/merged-props.js +10 -10
  6. package/dist/collaboration/merged-props.js.map +1 -1
  7. package/dist/collaboration/order.js +41 -1
  8. package/dist/collaboration/order.js.map +1 -1
  9. package/dist/collaboration/table.js +64 -25
  10. package/dist/collaboration/table.js.map +1 -1
  11. package/dist/collaboration/text.js +213 -1
  12. package/dist/collaboration/text.js.map +1 -1
  13. package/dist/core/comments.js +85 -3
  14. package/dist/core/comments.js.map +1 -1
  15. package/dist/define-block.js +6 -3
  16. package/dist/define-block.js.map +1 -1
  17. package/dist/editor.js.map +1 -1
  18. package/dist/flow/board-block.js.map +1 -1
  19. package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +70 -9
  20. package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -1
  21. package/dist/flow/board.js +124 -5
  22. package/dist/flow/board.js.map +1 -1
  23. package/dist/flow/index.js +5 -2
  24. package/dist/flow/index.js.map +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/types/collaboration/inline-diff.d.ts +9 -0
  27. package/dist/types/collaboration/order.d.ts +5 -0
  28. package/dist/types/collaboration/table.d.ts +5 -1
  29. package/dist/types/collaboration/text.d.ts +20 -0
  30. package/dist/types/core/comments.d.ts +39 -3
  31. package/dist/types/define-block.d.ts +16 -4
  32. package/dist/types/editor.d.ts +9 -1
  33. package/dist/types/flow/board.d.ts +15 -2
  34. package/dist/types/flow/index.d.ts +8 -2
  35. package/dist/types/index.d.ts +1 -1
  36. package/dist/use-comments.js +2 -2
  37. package/dist/use-comments.js.map +1 -1
  38. package/package.json +7 -7
@@ -1,4 +1,6 @@
1
+ import { diffLists } from "./inline-diff.js";
1
2
  import { Mark } from "prosemirror-model";
3
+ import { Mapping, StepMap, Transform } from "prosemirror-transform";
2
4
  // src/collaboration/text.ts
3
5
  var COMMENT = "comment";
4
6
  var COMMENT_PREFIX = "comment:";
@@ -86,6 +88,216 @@ function updateText(text, before, after) {
86
88
  if (end.a > start) text.delete(start, end.a - start);
87
89
  if (end.b > start) insertInline(text, start, after, start, end.b);
88
90
  }
89
- export { inlineFrom, insertInline, markAttributes, updateText };
91
+ /** Inline characters and embeds, with offsets matching ProseMirror and Y.Text. */
92
+ function units(node) {
93
+ const values = [];
94
+ const offsets = [];
95
+ node.forEach((child, at) => {
96
+ if (child.isText) {
97
+ let offset = at;
98
+ for (const character of child.text) {
99
+ offsets.push(offset);
100
+ values.push("t:" + character);
101
+ offset += character.length;
102
+ }
103
+ } else {
104
+ offsets.push(at);
105
+ values.push("n:" + JSON.stringify([child.type.name, child.attrs]));
106
+ }
107
+ });
108
+ offsets.push(node.content.size);
109
+ return {
110
+ values,
111
+ offsets
112
+ };
113
+ }
114
+ /** Exact content changes, at UTF-16 offsets, never inside a surrogate pair. */
115
+ function inlineChanges(before, after, budget) {
116
+ const a = units(before);
117
+ const b = units(after);
118
+ return diffLists(a.values, b.values, budget).map(([from, to, start, end]) => [
119
+ a.offsets[from],
120
+ a.offsets[to],
121
+ b.offsets[start],
122
+ b.offsets[end]
123
+ ]);
124
+ }
125
+ var markKey = (mark) => mark.type.name === COMMENT ? COMMENT_PREFIX + mark.attrs.id : mark.type.name;
126
+ var markRuns = (node) => {
127
+ const result = [];
128
+ node.forEach((child, at) => result.push({
129
+ end: at + child.nodeSize,
130
+ marks: child.marks
131
+ }));
132
+ return result;
133
+ };
134
+ var mappingOf = (changes) => {
135
+ const mapping = new Mapping();
136
+ let shift = 0;
137
+ for (const [from, to, start, end] of changes) {
138
+ mapping.appendMap(new StepMap([
139
+ from + shift,
140
+ to - from,
141
+ end - start
142
+ ]));
143
+ shift += end - start - (to - from);
144
+ }
145
+ return mapping;
146
+ };
147
+ /**
148
+ * Apply base → written edits to the current inline content. Offsets are
149
+ * mapped through the room's edits first; overlapping replacements use
150
+ * written content, while edits elsewhere and their marks remain intact.
151
+ */
152
+ function prepareTextFromBase(base, written, current, budget) {
153
+ written = keepInlineComments(base, written, budget);
154
+ const writes = [];
155
+ if (base.content.eq(written.content)) return () => {};
156
+ const remote = base.content.eq(current.content) ? [] : inlineChanges(base, current, budget);
157
+ const own = inlineChanges(base, written, budget);
158
+ const roomMap = mappingOf(remote);
159
+ const writtenMap = mappingOf(own);
160
+ const ranges = [];
161
+ let remoteAt = 0;
162
+ for (const [start, end] of own) {
163
+ let from = start;
164
+ let to = end;
165
+ while (remoteAt < remote.length && remote[remoteAt][1] <= from) remoteAt++;
166
+ for (let i = remoteAt; i < remote.length; i++) {
167
+ const [left, right] = remote[i];
168
+ if (left >= to) break;
169
+ if (left < to && right > from) {
170
+ from = Math.min(from, left);
171
+ to = Math.max(to, right);
172
+ }
173
+ }
174
+ const last = ranges[ranges.length - 1];
175
+ if (last && from <= last.to) last.to = Math.max(last.to, to);
176
+ else ranges.push({
177
+ from,
178
+ to
179
+ });
180
+ }
181
+ const tr = new Transform(current);
182
+ for (let i = ranges.length - 1; i >= 0; i--) {
183
+ const { from, to } = ranges[i];
184
+ const start = roomMap.map(from, 1);
185
+ const end = Math.max(start, roomMap.map(to, -1));
186
+ const writtenStart = writtenMap.map(from, -1);
187
+ const writtenEnd = writtenMap.map(to, 1);
188
+ tr.replaceWith(start, end, written.content.cut(writtenStart, writtenEnd));
189
+ writes.push((text) => {
190
+ if (end > start) text.delete(start, end - start);
191
+ if (writtenEnd > writtenStart) insertInline(text, start, written, writtenStart, writtenEnd);
192
+ });
193
+ }
194
+ let formatted = false;
195
+ base.forEach((node) => {
196
+ formatted ||= node.marks.length > 0;
197
+ });
198
+ written.forEach((node) => {
199
+ formatted ||= node.marks.length > 0;
200
+ });
201
+ if (!formatted) return (text) => {
202
+ for (const write of writes) write(text);
203
+ };
204
+ let run = null;
205
+ const flush = () => {
206
+ if (!run) return;
207
+ const attributes = {};
208
+ for (const mark of run.remove) attributes[markKey(mark)] = null;
209
+ for (const mark of run.add) attributes[markKey(mark)] = mark.type.name === COMMENT || !Object.keys(mark.attrs).length ? true : { ...mark.attrs };
210
+ const { from, to } = run;
211
+ writes.push((text) => text.format(from, to - from, attributes));
212
+ run = null;
213
+ };
214
+ const baseRuns = markRuns(base);
215
+ const writtenRuns = markRuns(written);
216
+ let baseRun = 0;
217
+ let writtenRun = 0;
218
+ let changed = 0;
219
+ for (let i = 0; i < base.content.size; i++) {
220
+ while (changed < own.length && own[changed][1] <= i) changed++;
221
+ if (changed < own.length && own[changed][0] <= i && i < own[changed][1]) continue;
222
+ const j = writtenMap.map(i, 1);
223
+ while (baseRuns[baseRun] && baseRuns[baseRun].end <= i) baseRun++;
224
+ while (writtenRuns[writtenRun] && writtenRuns[writtenRun].end <= j) writtenRun++;
225
+ const was = baseRuns[baseRun]?.marks ?? [];
226
+ const next = writtenRuns[writtenRun]?.marks ?? [];
227
+ const old = new Map(was.map((mark) => [markKey(mark), mark]));
228
+ const fresh = new Map(next.map((mark) => [markKey(mark), mark]));
229
+ const remove = was.filter((mark) => !fresh.get(markKey(mark))?.eq(mark));
230
+ const add = next.filter((mark) => !old.get(markKey(mark))?.eq(mark));
231
+ if (!remove.length && !add.length) continue;
232
+ const from = tr.mapping.map(roomMap.map(i, 1), 1);
233
+ const to = tr.mapping.map(roomMap.map(i + 1, -1), -1);
234
+ if (to <= from) continue;
235
+ const key = JSON.stringify([remove.map((mark) => mark.toJSON()), add.map((mark) => mark.toJSON())]);
236
+ if (run && run.to === from && run.key === key) run.to = to;
237
+ else {
238
+ flush();
239
+ run = {
240
+ from,
241
+ to,
242
+ remove,
243
+ add,
244
+ key
245
+ };
246
+ }
247
+ }
248
+ flush();
249
+ return (text) => {
250
+ for (const write of writes) write(text);
251
+ };
252
+ }
253
+ /**
254
+ * `after` with the comment marks of `before` on all unchanged inline
255
+ * fragments, when `after` has none: a version read from Markdown, which
256
+ * doesn't carry them, leaves the threads where the text stays the same.
257
+ */
258
+ function keepInlineComments(before, after, budget) {
259
+ const type = after.type.schema.marks.comment;
260
+ if (!type || !after.inlineContent || !before.inlineContent || before.type !== after.type) return after;
261
+ let theirs = false;
262
+ after.descendants((node) => {
263
+ if (type.isInSet(node.marks)) theirs = true;
264
+ });
265
+ if (theirs) return after;
266
+ const ranges = [];
267
+ before.forEach((child, pos) => {
268
+ for (const mark of child.marks) if (mark.type === type) ranges.push({
269
+ from: pos,
270
+ to: pos + child.nodeSize,
271
+ mark
272
+ });
273
+ });
274
+ if (!ranges.length) return after;
275
+ const changes = inlineChanges(before, after, budget);
276
+ const same = [];
277
+ let left = 0;
278
+ let right = 0;
279
+ for (const [from, to, , end] of changes) {
280
+ if (from > left) same.push({
281
+ from: left,
282
+ to: from,
283
+ shift: right - left
284
+ });
285
+ left = to;
286
+ right = end;
287
+ }
288
+ if (left < before.content.size) same.push({
289
+ from: left,
290
+ to: before.content.size,
291
+ shift: right - left
292
+ });
293
+ const tr = new Transform(after);
294
+ for (const { from, to, mark } of ranges) for (const fragment of same) {
295
+ const start = Math.max(from, fragment.from);
296
+ const end = Math.min(to, fragment.to);
297
+ if (end > start) tr.addMark(start + fragment.shift, end + fragment.shift, mark);
298
+ }
299
+ return tr.doc;
300
+ }
301
+ export { inlineChanges, inlineFrom, insertInline, keepInlineComments, markAttributes, prepareTextFromBase, updateText };
90
302
 
91
303
  //# sourceMappingURL=text.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"text.js","names":[],"sources":["../../src/collaboration/text.ts"],"sourcesContent":["import { Mark, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport type * as Y from 'yjs'\n\n/* inline content ↔ Y.Text */\n\nexport type Attributes = Record<string, unknown>\n\n/*\n * A text can be in several comment threads at once, each added and\n * removed on its own, also by two people at the same time: every thread\n * is its own attribute, `comment:<thread id>`.\n */\nconst COMMENT = 'comment'\nconst COMMENT_PREFIX = 'comment:'\n\nexport function markAttributes(marks: readonly Mark[], schema: Schema): Attributes {\n // every mark is named, so `insert` doesn't inherit formatting from the left\n // (comment attributes the text doesn't have are cleared by `insert` itself)\n const attributes: Attributes = {}\n for (const name of Object.keys(schema.marks)) if (name !== COMMENT) attributes[name] = null\n for (const mark of marks) {\n if (mark.type.name === COMMENT) attributes[COMMENT_PREFIX + mark.attrs.id] = true\n else attributes[mark.type.name] = Object.keys(mark.attrs).length ? { ...mark.attrs } : true\n }\n return attributes\n}\n\n/** The comment attributes of the inline content from `from` to `to`. */\nfunction commentAttributes(node: PMNode, from: number, to: number): Set<string> {\n const keys = new Set<string>()\n node.nodesBetween(from, to, (child) => {\n for (const mark of child.marks)\n if (mark.type.name === COMMENT) keys.add(COMMENT_PREFIX + mark.attrs.id)\n })\n return keys\n}\n\ninterface Embed {\n node: string\n attrs?: Attributes\n}\n\n/** Write `content`'s inline nodes from `from` to `to` into `text` at `at`. */\nexport function insertInline(text: Y.Text, at: number, content: PMNode, from: number, to: number) {\n const schema = content.type.schema\n let offset = at\n content.forEach((child, pos) => {\n const start = Math.max(pos, from)\n const end = Math.min(pos + child.nodeSize, to)\n if (start >= end) return\n if (child.isText) {\n const piece = child.text!.slice(start - pos, end - pos)\n text.insert(offset, piece, markAttributes(child.marks, schema))\n offset += piece.length\n } else {\n const embed: Embed = { node: child.type.name }\n if (Object.keys(child.attrs).length) embed.attrs = { ...child.attrs }\n text.insertEmbed(offset, embed, markAttributes(child.marks, schema))\n offset += 1\n }\n })\n}\n\nfunction marksFrom(attributes: Attributes | undefined, schema: Schema): Mark[] {\n const marks: Mark[] = []\n for (const [name, value] of Object.entries(attributes ?? {})) {\n if (name.startsWith(COMMENT_PREFIX)) {\n if (value === true && schema.marks[COMMENT])\n marks.push(schema.marks[COMMENT].create({ id: name.slice(COMMENT_PREFIX.length) }))\n continue\n }\n const type = schema.marks[name]\n if (!type || value === null || value === undefined) continue\n marks.push(type.create(value === true ? null : (value as Attributes)))\n }\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineFrom(text: Y.Text, schema: Schema, code: boolean): PMNode[] {\n const nodes: PMNode[] = []\n for (const op of text.toDelta() as { insert: string | Embed; attributes?: Attributes }[]) {\n if (typeof op.insert === 'string') {\n if (op.insert)\n nodes.push(schema.text(op.insert, code ? [] : marksFrom(op.attributes, schema)))\n } else {\n const type = schema.nodes[op.insert.node]\n if (type?.isInline)\n nodes.push(type.create(op.insert.attrs ?? null, null, marksFrom(op.attributes, schema)))\n }\n }\n return nodes\n}\n\n/** Bring `text` from `before`'s inline content to `after`'s, changing only what differs. */\nexport function updateText(text: Y.Text, before: PMNode, after: PMNode) {\n const start = before.content.findDiffStart(after.content)\n if (start === null) return\n const end = before.content.findDiffEnd(after.content)!\n // the ends can overlap the start when the change repeats nearby text\n const overlap = start - Math.min(end.a, end.b)\n if (overlap > 0) {\n end.a += overlap\n end.b += overlap\n }\n const sameText =\n end.a - start === end.b - start &&\n before.textBetween(start, end.a, '\\n', '') === after.textBetween(start, end.b, '\\n', '')\n if (sameText) {\n // only the formatting changed: keep the characters, so edits on them merge\n const schema = after.type.schema\n const comments = commentAttributes(before, start, end.a)\n after.content.forEach((child, pos) => {\n const from = Math.max(pos, start)\n const to = Math.min(pos + child.nodeSize, end.b)\n if (from >= to) return\n const attributes = markAttributes(child.marks, schema)\n // threads taken off this text\n for (const key of comments) if (!(key in attributes)) attributes[key] = null\n text.format(from, to - from, attributes)\n })\n return\n }\n if (end.a > start) text.delete(start, end.a - start)\n if (end.b > start) insertInline(text, start, after, start, end.b)\n}\n"],"mappings":";;AAYA,IAAM,UAAU;AAChB,IAAM,iBAAiB;AAEvB,SAAgB,eAAe,OAAwB,QAA4B;CAGjF,MAAM,aAAyB,CAAC;CAChC,KAAK,MAAM,QAAQ,OAAO,KAAK,OAAO,KAAK,GAAG,IAAI,SAAS,SAAS,WAAW,QAAQ;CACvF,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MAAM,YAAY,OAAO,IAAI,GAAG,MAAM,GAAG,GAC7E;EAEZ,MAAM,SAAS,MAAM,KAAK;EAC1B,MAAM,WAAW,kBAAkB,QAAQ,OAAO,IAAI,CAAC;EACvD,MAAM,QAAQ,SAAS,OAAO,QAAQ;GACpC,MAAM,OAAO,KAAK,IAAI,KAAK,KAAK;GAChC,MAAM,KAAK,KAAK,IAAI,MAAM,MAAM,UAAU,IAAI,CAAC;GAC/C,IAAI,QAAQ,IAAI;GAChB,MAAM,aAAa,eAAe,MAAM,OAAO,MAAM;GAErD,KAAK,MAAM,OAAO,UAAU,IAAI,EAAE,OAAO,aAAa,WAAW,OAAO;GACxE,KAAK,OAAO,MAAM,KAAK,MAAM,UAAU;EACzC,CAAC;EACD;CACF;CACA,IAAI,IAAI,IAAI,OAAO,KAAK,OAAO,OAAO,IAAI,IAAI,KAAK;CACnD,IAAI,IAAI,IAAI,OAAO,aAAa,MAAM,OAAO,OAAO,OAAO,IAAI,CAAC;AAClE"}
1
+ {"version":3,"file":"text.js","names":[],"sources":["../../src/collaboration/text.ts"],"sourcesContent":["import { Mark, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport type * as Y from 'yjs'\nimport { Mapping, StepMap, Transform } from 'prosemirror-transform'\nimport { diffLists, type DiffBudget } from './inline-diff'\n\n/* inline content ↔ Y.Text */\n\nexport type Attributes = Record<string, unknown>\n\n/*\n * A text can be in several comment threads at once, each added and\n * removed on its own, also by two people at the same time: every thread\n * is its own attribute, `comment:<thread id>`.\n */\nconst COMMENT = 'comment'\nconst COMMENT_PREFIX = 'comment:'\n\nexport function markAttributes(marks: readonly Mark[], schema: Schema): Attributes {\n // every mark is named, so `insert` doesn't inherit formatting from the left\n // (comment attributes the text doesn't have are cleared by `insert` itself)\n const attributes: Attributes = {}\n for (const name of Object.keys(schema.marks)) if (name !== COMMENT) attributes[name] = null\n for (const mark of marks) {\n if (mark.type.name === COMMENT) attributes[COMMENT_PREFIX + mark.attrs.id] = true\n else attributes[mark.type.name] = Object.keys(mark.attrs).length ? { ...mark.attrs } : true\n }\n return attributes\n}\n\n/** The comment attributes of the inline content from `from` to `to`. */\nfunction commentAttributes(node: PMNode, from: number, to: number): Set<string> {\n const keys = new Set<string>()\n node.nodesBetween(from, to, (child) => {\n for (const mark of child.marks)\n if (mark.type.name === COMMENT) keys.add(COMMENT_PREFIX + mark.attrs.id)\n })\n return keys\n}\n\ninterface Embed {\n node: string\n attrs?: Attributes\n}\n\n/** Write `content`'s inline nodes from `from` to `to` into `text` at `at`. */\nexport function insertInline(text: Y.Text, at: number, content: PMNode, from: number, to: number) {\n const schema = content.type.schema\n let offset = at\n content.forEach((child, pos) => {\n const start = Math.max(pos, from)\n const end = Math.min(pos + child.nodeSize, to)\n if (start >= end) return\n if (child.isText) {\n const piece = child.text!.slice(start - pos, end - pos)\n text.insert(offset, piece, markAttributes(child.marks, schema))\n offset += piece.length\n } else {\n const embed: Embed = { node: child.type.name }\n if (Object.keys(child.attrs).length) embed.attrs = { ...child.attrs }\n text.insertEmbed(offset, embed, markAttributes(child.marks, schema))\n offset += 1\n }\n })\n}\n\nfunction marksFrom(attributes: Attributes | undefined, schema: Schema): Mark[] {\n const marks: Mark[] = []\n for (const [name, value] of Object.entries(attributes ?? {})) {\n if (name.startsWith(COMMENT_PREFIX)) {\n if (value === true && schema.marks[COMMENT])\n marks.push(schema.marks[COMMENT].create({ id: name.slice(COMMENT_PREFIX.length) }))\n continue\n }\n const type = schema.marks[name]\n if (!type || value === null || value === undefined) continue\n marks.push(type.create(value === true ? null : (value as Attributes)))\n }\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineFrom(text: Y.Text, schema: Schema, code: boolean): PMNode[] {\n const nodes: PMNode[] = []\n for (const op of text.toDelta() as { insert: string | Embed; attributes?: Attributes }[]) {\n if (typeof op.insert === 'string') {\n if (op.insert)\n nodes.push(schema.text(op.insert, code ? [] : marksFrom(op.attributes, schema)))\n } else {\n const type = schema.nodes[op.insert.node]\n if (type?.isInline)\n nodes.push(type.create(op.insert.attrs ?? null, null, marksFrom(op.attributes, schema)))\n }\n }\n return nodes\n}\n\n/** Bring `text` from `before`'s inline content to `after`'s, changing only what differs. */\nexport function updateText(text: Y.Text, before: PMNode, after: PMNode) {\n const start = before.content.findDiffStart(after.content)\n if (start === null) return\n const end = before.content.findDiffEnd(after.content)!\n // the ends can overlap the start when the change repeats nearby text\n const overlap = start - Math.min(end.a, end.b)\n if (overlap > 0) {\n end.a += overlap\n end.b += overlap\n }\n const sameText =\n end.a - start === end.b - start &&\n before.textBetween(start, end.a, '\\n', '') === after.textBetween(start, end.b, '\\n', '')\n if (sameText) {\n // only the formatting changed: keep the characters, so edits on them merge\n const schema = after.type.schema\n const comments = commentAttributes(before, start, end.a)\n after.content.forEach((child, pos) => {\n const from = Math.max(pos, start)\n const to = Math.min(pos + child.nodeSize, end.b)\n if (from >= to) return\n const attributes = markAttributes(child.marks, schema)\n // threads taken off this text\n for (const key of comments) if (!(key in attributes)) attributes[key] = null\n text.format(from, to - from, attributes)\n })\n return\n }\n if (end.a > start) text.delete(start, end.a - start)\n if (end.b > start) insertInline(text, start, after, start, end.b)\n}\n\n/** Inline characters and embeds, with offsets matching ProseMirror and Y.Text. */\nfunction units(node: PMNode) {\n const values: string[] = []\n const offsets: number[] = []\n node.forEach((child, at) => {\n if (child.isText) {\n let offset = at\n for (const character of child.text!) {\n offsets.push(offset)\n values.push('t:' + character)\n offset += character.length\n }\n } else {\n offsets.push(at)\n values.push('n:' + JSON.stringify([child.type.name, child.attrs]))\n }\n })\n offsets.push(node.content.size)\n return { values, offsets }\n}\n\n/** Exact content changes, at UTF-16 offsets, never inside a surrogate pair. */\nexport function inlineChanges(before: PMNode, after: PMNode, budget?: DiffBudget): InlineChange[] {\n const a = units(before)\n const b = units(after)\n return diffLists(a.values, b.values, budget).map(([from, to, start, end]) => [\n a.offsets[from]!,\n a.offsets[to]!,\n b.offsets[start]!,\n b.offsets[end]!,\n ])\n}\n\nexport type TextUpdatePlan = (text: Y.Text) => void\n\nconst markKey = (mark: Mark) =>\n mark.type.name === COMMENT ? COMMENT_PREFIX + mark.attrs.id : mark.type.name\n\nconst markRuns = (node: PMNode) => {\n const result: { end: number; marks: readonly Mark[] }[] = []\n node.forEach((child, at) => result.push({ end: at + child.nodeSize, marks: child.marks }))\n return result\n}\n\ntype InlineChange = [number, number, number, number]\nconst mappingOf = (changes: InlineChange[]) => {\n const mapping = new Mapping()\n let shift = 0\n for (const [from, to, start, end] of changes) {\n mapping.appendMap(new StepMap([from + shift, to - from, end - start]))\n shift += end - start - (to - from)\n }\n return mapping\n}\n\n/**\n * Apply base → written edits to the current inline content. Offsets are\n * mapped through the room's edits first; overlapping replacements use\n * written content, while edits elsewhere and their marks remain intact.\n */\nexport function prepareTextFromBase(\n base: PMNode,\n written: PMNode,\n current: PMNode,\n budget?: DiffBudget,\n): TextUpdatePlan {\n written = keepInlineComments(base, written, budget)\n const writes: TextUpdatePlan[] = []\n if (base.content.eq(written.content)) return () => {}\n const remote = base.content.eq(current.content) ? [] : inlineChanges(base, current, budget)\n const own = inlineChanges(base, written, budget)\n const roomMap = mappingOf(remote)\n const writtenMap = mappingOf(own)\n // An edit inside a replacement conflicts with that replacement as a\n // whole. Join such edits before mapping, so their ranges cannot cross.\n const ranges: { from: number; to: number }[] = []\n let remoteAt = 0\n for (const [start, end] of own) {\n let from = start\n let to = end\n while (remoteAt < remote.length && remote[remoteAt]![1] <= from) remoteAt++\n for (let i = remoteAt; i < remote.length; i++) {\n const [left, right] = remote[i]!\n if (left >= to) break\n if (left < to && right > from) {\n from = Math.min(from, left)\n to = Math.max(to, right)\n }\n }\n const last = ranges[ranges.length - 1]\n if (last && from <= last.to) last.to = Math.max(last.to, to)\n else ranges.push({ from, to })\n }\n const tr = new Transform(current)\n for (let i = ranges.length - 1; i >= 0; i--) {\n const { from, to } = ranges[i]!\n const start = roomMap.map(from, 1)\n const end = Math.max(start, roomMap.map(to, -1))\n const writtenStart = writtenMap.map(from, -1)\n const writtenEnd = writtenMap.map(to, 1)\n tr.replaceWith(start, end, written.content.cut(writtenStart, writtenEnd))\n writes.push((text) => {\n if (end > start) text.delete(start, end - start)\n if (writtenEnd > writtenStart) insertInline(text, start, written, writtenStart, writtenEnd)\n })\n }\n // Formatting is a field change, not a text replacement. Only marks\n // actually changed by the writer are applied to surviving characters.\n let formatted = false\n base.forEach((node) => {\n formatted ||= node.marks.length > 0\n })\n written.forEach((node) => {\n formatted ||= node.marks.length > 0\n })\n if (!formatted)\n return (text) => {\n for (const write of writes) write(text)\n }\n let run: { from: number; to: number; remove: Mark[]; add: Mark[]; key: string } | null = null\n const flush = () => {\n if (!run) return\n const attributes: Attributes = {}\n for (const mark of run.remove) attributes[markKey(mark)] = null\n for (const mark of run.add)\n attributes[markKey(mark)] =\n mark.type.name === COMMENT || !Object.keys(mark.attrs).length ? true : { ...mark.attrs }\n const { from, to } = run\n writes.push((text) => text.format(from, to - from, attributes))\n run = null\n }\n const baseRuns = markRuns(base)\n const writtenRuns = markRuns(written)\n let baseRun = 0\n let writtenRun = 0\n let changed = 0\n for (let i = 0; i < base.content.size; i++) {\n while (changed < own.length && own[changed]![1] <= i) changed++\n if (changed < own.length && own[changed]![0] <= i && i < own[changed]![1]) continue\n const j = writtenMap.map(i, 1)\n while (baseRuns[baseRun] && baseRuns[baseRun]!.end <= i) baseRun++\n while (writtenRuns[writtenRun] && writtenRuns[writtenRun]!.end <= j) writtenRun++\n const was = baseRuns[baseRun]?.marks ?? []\n const next = writtenRuns[writtenRun]?.marks ?? []\n const old = new Map(was.map((mark) => [markKey(mark), mark]))\n const fresh = new Map(next.map((mark) => [markKey(mark), mark]))\n const remove = was.filter((mark) => !fresh.get(markKey(mark))?.eq(mark))\n const add = next.filter((mark) => !old.get(markKey(mark))?.eq(mark))\n if (!remove.length && !add.length) continue\n const from = tr.mapping.map(roomMap.map(i, 1), 1)\n const to = tr.mapping.map(roomMap.map(i + 1, -1), -1)\n if (to <= from) continue\n const key = JSON.stringify([\n remove.map((mark) => mark.toJSON()),\n add.map((mark) => mark.toJSON()),\n ])\n if (run && run.to === from && run.key === key) run.to = to\n else {\n flush()\n run = { from, to, remove, add, key }\n }\n }\n flush()\n return (text) => {\n for (const write of writes) write(text)\n }\n}\n\n/** Used after a complete preflight, so no diff can fail after a map write. */\nexport function updateTextFromBase(text: Y.Text, base: PMNode, written: PMNode, current: PMNode) {\n prepareTextFromBase(base, written, current)(text)\n}\n\n/**\n * `after` with the comment marks of `before` on all unchanged inline\n * fragments, when `after` has none: a version read from Markdown, which\n * doesn't carry them, leaves the threads where the text stays the same.\n */\nexport function keepInlineComments(before: PMNode, after: PMNode, budget?: DiffBudget): PMNode {\n const type = after.type.schema.marks.comment\n if (!type || !after.inlineContent || !before.inlineContent || before.type !== after.type)\n return after\n let theirs = false\n after.descendants((node) => {\n if (type.isInSet(node.marks)) theirs = true\n })\n if (theirs) return after\n const ranges: { from: number; to: number; mark: Mark }[] = []\n before.forEach((child, pos) => {\n for (const mark of child.marks)\n if (mark.type === type) ranges.push({ from: pos, to: pos + child.nodeSize, mark })\n })\n if (!ranges.length) return after\n const changes = inlineChanges(before, after, budget)\n const same: { from: number; to: number; shift: number }[] = []\n let left = 0\n let right = 0\n for (const [from, to, , end] of changes) {\n if (from > left) same.push({ from: left, to: from, shift: right - left })\n left = to\n right = end\n }\n if (left < before.content.size)\n same.push({ from: left, to: before.content.size, shift: right - left })\n const tr = new Transform(after)\n for (const { from, to, mark } of ranges) {\n for (const fragment of same) {\n const start = Math.max(from, fragment.from)\n const end = Math.min(to, fragment.to)\n if (end > start) tr.addMark(start + fragment.shift, end + fragment.shift, mark)\n }\n }\n return tr.doc\n}\n"],"mappings":";;;;AAcA,IAAM,UAAU;AAChB,IAAM,iBAAiB;AAEvB,SAAgB,eAAe,OAAwB,QAA4B;CAGjF,MAAM,aAAyB,CAAC;CAChC,KAAK,MAAM,QAAQ,OAAO,KAAK,OAAO,KAAK,GAAG,IAAI,SAAS,SAAS,WAAW,QA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,CAAC;CACrF,CAAC;CACD,IAAI,CAAC,OAAO,QAAQ,OAAO;CAC3B,MAAM,UAAU,cAAc,QAAQ,OAAO,MAAM;CACnD,MAAM,OAAsD,CAAC;CAC7D,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,MAAM,MAAM,QAAQ,SAAS;EACvC,IAAI,OAAO,MAAM,KAAK,KAAK;GAAE,MAAM;GAAM,IAAI;GAAM,OAAO,QAAQ;EAAK,CAAC;EACxE,OAAO;EACP,QAAQ;CACV;CACA,IAAI,OAAO,OAAO,QAAQ,MACxB,KAAK,KAAK;EAAE,MAAM;EAAM,IAAI,OAAO,QAAQ;EAAM,OAAO,QAAQ;CAAK,CAAC;CACxE,MAAM,KAAK,IAAI,UAAU,KAAK;CAC9B,KAAK,MAAM,EAAE,MAAM,IAAI,UAAU,QAC/B,KAAK,MAAM,YAAY,MAAM;EAC3B,MAAM,QAAQ,KAAK,IAAI,MAAM,SAAS,IAAI;EAC1C,MAAM,MAAM,KAAK,IAAI,IAAI,SAAS,EAAE;EACpC,IAAI,MAAM,OAAO,GAAG,QAAQ,QAAQ,SAAS,OAAO,MAAM,SAAS,OAAO,IAAI;CAChF;CAEF,OAAO,GAAG;AACZ"}
@@ -2,7 +2,10 @@ import { blockAround } from "./blocks.js";
2
2
  import { Plugin, PluginKey } from "prosemirror-state";
3
3
  import { Fragment, Slice } from "prosemirror-model";
4
4
  import { Decoration, DecorationSet } from "prosemirror-view";
5
+ import { isHistoryTransaction } from "prosemirror-history";
5
6
  // src/core/comments.ts
7
+ /** The `comments` of a node's spec: a block type that keeps threads inside. */
8
+ var blockCommentsOf = (node) => node.type.spec.comments;
6
9
  var commentKey = new PluginKey("dou-editor-comments");
7
10
  var pendingDecorations = (doc, range) => range && range.to > range.from ? DecorationSet.create(doc, [Decoration.inline(range.from, range.to, { class: "dou-editor__comment-pending" })]) : DecorationSet.empty;
8
11
  /** The ids of the threads at `pos`, the shortest (innermost) first. */
@@ -40,6 +43,23 @@ function rangeLength(doc, id, pos) {
40
43
  function commentAnchors(doc) {
41
44
  const anchors = /* @__PURE__ */ new Map();
42
45
  doc.descendants((node, pos) => {
46
+ const inside = blockCommentsOf(node);
47
+ if (inside) {
48
+ const block = doc.resolve(pos).parent.attrs.id ?? "";
49
+ for (const [id, at] of Object.entries(inside.anchors(node.attrs))) {
50
+ if (anchors.has(id)) continue;
51
+ const to = pos + node.nodeSize;
52
+ anchors.set(id, {
53
+ block,
54
+ text: at.text,
55
+ from: pos,
56
+ to,
57
+ type: node.type.name,
58
+ target: at.target
59
+ });
60
+ }
61
+ return false;
62
+ }
43
63
  if (!node.isText) return true;
44
64
  for (const mark of node.marks) {
45
65
  if (mark.type.name !== "comment") continue;
@@ -88,11 +108,22 @@ function anchorComment(view, range, id) {
88
108
  tr.setMeta("addToHistory", false);
89
109
  view.dispatch(tr);
90
110
  }
91
- /** Takes a removed thread's anchor off the text. */
111
+ /** Sets the props of the block content at `pos` that differ in `next`. */
112
+ function setProps(tr, pos, before, next) {
113
+ for (const [name, value] of Object.entries(next)) if (Object.hasOwn(before, name) && before[name] !== value) tr.setNodeAttribute(pos, name, value);
114
+ }
115
+ /** The id of the block around the content node at `pos`. */
116
+ var blockIdAt = (doc, pos) => doc.resolve(pos).parent.attrs.id ?? "";
117
+ /** Takes a removed thread's anchor off the text, or out of the block it is inside. */
92
118
  function unanchorComment(view, id) {
93
119
  const type = view.state.schema.marks.comment;
94
120
  const tr = view.state.tr;
95
121
  view.state.doc.descendants((node, pos) => {
122
+ const inside = blockCommentsOf(node);
123
+ if (inside) {
124
+ if (Object.hasOwn(inside.anchors(node.attrs), id)) setProps(tr, pos, node.attrs, inside.strip(node.attrs, (other) => other !== id));
125
+ return false;
126
+ }
96
127
  if (!node.isText) return true;
97
128
  const mark = node.marks.find((m) => m.type === type && m.attrs.id === id);
98
129
  if (mark) tr.removeMark(pos, pos + node.nodeSize, mark);
@@ -115,27 +146,78 @@ function dropCopiedComments(slice, state, known) {
115
146
  let any = false;
116
147
  slice.content.descendants((node) => {
117
148
  if (node.marks.some((mark) => mark.type.name === "comment")) any = true;
149
+ const inside = blockCommentsOf(node);
150
+ if (inside && Object.keys(inside.anchors(node.attrs)).length) any = true;
118
151
  return !any;
119
152
  });
120
153
  if (!any) return slice;
121
154
  state.doc.descendants((node) => {
122
155
  for (const mark of node.marks) if (mark.type.name === "comment") inDoc.add(mark.attrs.id);
156
+ const inside = blockCommentsOf(node);
157
+ if (inside) for (const id of Object.keys(inside.anchors(node.attrs))) inDoc.add(id);
123
158
  return true;
124
159
  });
125
160
  const keep = (id) => !inDoc.has(id) && (!known || known.has(id));
126
161
  const strip = (fragment) => {
127
162
  const nodes = [];
128
163
  fragment.forEach((node) => {
164
+ const inside = blockCommentsOf(node);
129
165
  if (node.isText) nodes.push(node.mark(node.marks.filter((m) => m.type.name !== "comment" || keep(m.attrs.id))));
130
- else nodes.push(node.copy(strip(node.content)));
166
+ else if (inside) {
167
+ const attrs = {
168
+ ...node.attrs,
169
+ ...inside.strip(node.attrs, keep)
170
+ };
171
+ nodes.push(node.type.create(attrs, strip(node.content), node.marks));
172
+ } else nodes.push(node.copy(strip(node.content)));
131
173
  });
132
174
  return Fragment.from(nodes);
133
175
  };
134
176
  return new Slice(strip(slice.content), slice.openStart, slice.openEnd);
135
177
  }
178
+ /** The threads inside each block that keeps them, by block id. */
179
+ function blockAnchors(doc) {
180
+ const found = /* @__PURE__ */ new Map();
181
+ doc.descendants((node, pos) => {
182
+ const inside = blockCommentsOf(node);
183
+ if (!inside) return true;
184
+ found.set(blockIdAt(doc, pos), inside.anchors(node.attrs));
185
+ return false;
186
+ });
187
+ return found;
188
+ }
189
+ /**
190
+ * Undo and redo bring back a block's props as they were, threads included,
191
+ * but starting and deleting threads aren't steps of the history: each block
192
+ * keeps the threads it had before, put back where they were if that is
193
+ * still there, and those it comes back with that are still threads (on a
194
+ * node brought back, say), not those deleted since. A block brought back by
195
+ * the undo keeps what it comes with.
196
+ */
197
+ function keepBlockComments(before, state, known) {
198
+ const had = blockAnchors(before);
199
+ if (!had.size) return null;
200
+ const tr = state.tr;
201
+ state.doc.descendants((node, pos) => {
202
+ const inside = blockCommentsOf(node);
203
+ if (!inside) return true;
204
+ const anchors = had.get(blockIdAt(state.doc, pos));
205
+ if (!anchors) return false;
206
+ let props = inside.strip(node.attrs, (id) => Object.hasOwn(anchors, id) || !known || known.has(id));
207
+ const now = inside.anchors(props);
208
+ for (const [id, at] of Object.entries(anchors)) {
209
+ if (Object.hasOwn(now, id)) continue;
210
+ props = inside.place(props, id, at.target) ?? props;
211
+ }
212
+ if (props !== node.attrs) setProps(tr, pos, node.attrs, props);
213
+ return false;
214
+ });
215
+ return tr.docChanged ? tr.setMeta("addToHistory", false) : null;
216
+ }
136
217
  function commentPlugin(options) {
137
218
  return new Plugin({
138
219
  key: commentKey,
220
+ appendTransaction: (trs, before, state) => trs.some((tr) => tr.docChanged && isHistoryTransaction(tr)) ? keepBlockComments(before.doc, state, options.known()) : null,
139
221
  state: {
140
222
  init: () => ({
141
223
  pending: null,
@@ -181,6 +263,6 @@ function commentPlugin(options) {
181
263
  }
182
264
  });
183
265
  }
184
- export { anchorComment, commentAnchors, commentKey, commentPlugin, commentRange, commentsAt, setPendingComment, unanchorComment };
266
+ export { anchorComment, blockCommentsOf, commentAnchors, commentKey, commentPlugin, commentRange, commentsAt, setPendingComment, unanchorComment };
185
267
 
186
268
  //# sourceMappingURL=comments.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"comments.js","names":[],"sources":["../../src/core/comments.ts"],"sourcesContent":["import { Fragment, Slice, type Node as PMNode } from 'prosemirror-model'\nimport { Plugin, PluginKey, type EditorState, type Transaction } from 'prosemirror-state'\nimport { Decoration, DecorationSet, type EditorView } from 'prosemirror-view'\nimport { blockAround } from './blocks'\n\n/*\n * Comment threads are anchored by a `comment` mark carrying the thread's\n * id on the text they are about. The threads themselves (comments,\n * replies, resolved) are kept outside the document.\n */\n\n/** A range of the document, as positions. */\nexport interface CommentRange {\n from: number\n to: number\n}\n\n/** Where a thread is anchored: the block and the text it is about. */\nexport interface CommentAnchor {\n /** The id of the (first) block holding the text. */\n block: string\n /** The text the thread is about. */\n text: string\n from: number\n to: number\n}\n\nexport interface CommentPluginState {\n /** The text a thread is being started on, until its first comment is sent. */\n pending: CommentRange | null\n decorations: DecorationSet\n}\n\nexport const commentKey = new PluginKey<CommentPluginState>('dou-editor-comments')\n\ntype CommentMeta = { pending: CommentRange | null }\n\nexport interface CommentPluginOptions {\n /** The ids of the threads there are, or `null` when comments are off. */\n known: () => ReadonlySet<string> | null\n /** A click on text that is in threads, with their ids, innermost first; `[]` elsewhere. */\n onClick: (ids: string[]) => void\n onPending: (range: CommentRange | null) => void\n /** Text got selected (a range, not a cursor). */\n onSelect: () => void\n}\n\nconst pendingDecorations = (doc: PMNode, range: CommentRange | null) =>\n range && range.to > range.from\n ? DecorationSet.create(doc, [\n Decoration.inline(range.from, range.to, { class: 'dou-editor__comment-pending' }),\n ])\n : DecorationSet.empty\n\n/** The ids of the threads at `pos`, the shortest (innermost) first. */\nexport function commentsAt(state: EditorState, pos: number): string[] {\n const $pos = state.doc.resolve(pos)\n const node = $pos.parent.childAfter($pos.parentOffset).node\n if (!node) return []\n const ids = node.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (ids.length < 2) return ids\n const length = new Map(ids.map((id) => [id, rangeLength(state.doc, id, pos)]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh list\n return ids.sort((a, b) => length.get(a)! - length.get(b)!)\n}\n\n/** How long the run of `id`'s text around `pos` is, within its textblock. */\nfunction rangeLength(doc: PMNode, id: string, pos: number): number {\n const $pos = doc.resolve(pos)\n const start = $pos.start()\n let runStart = -1\n let around = false\n let length = Infinity\n $pos.parent.forEach((child, offset) => {\n const at = start + offset\n const end = at + child.nodeSize\n if (child.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (runStart < 0) runStart = at\n if (at <= pos && pos <= end) around = true\n if (around) length = end - runStart\n } else {\n if (around) around = false\n runStart = -1\n }\n })\n return length\n}\n\n/** Every thread's anchor in the document, by id: the first and last positions of its text. */\nexport function commentAnchors(doc: PMNode): Map<string, CommentAnchor> {\n const anchors = new Map<string, CommentAnchor>()\n doc.descendants((node, pos) => {\n if (!node.isText) return true\n for (const mark of node.marks) {\n if (mark.type.name !== 'comment') continue\n const id = mark.attrs.id as string\n const end = pos + node.nodeSize\n const anchor = anchors.get(id)\n if (anchor) {\n anchor.to = end\n anchor.text += node.text\n } else {\n const block = blockAround(doc.resolve(pos))\n anchors.set(id, {\n block: (block?.node.attrs.id as string | undefined) ?? '',\n text: node.text ?? '',\n from: pos,\n to: end,\n })\n }\n }\n return false\n })\n return anchors\n}\n\n/** The text of `id`'s anchor that a thread card points at: its first and last positions. */\nexport function commentRange(doc: PMNode, id: string): CommentRange | null {\n let from = -1\n let to = -1\n doc.descendants((node, pos) => {\n if (!node.isText) return true\n if (node.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (from < 0) from = pos\n to = pos + node.nodeSize\n }\n return false\n })\n return from < 0 ? null : { from, to }\n}\n\n/** Marks `range` as the text of a new thread. Not undone with the edits around it. */\nexport function anchorComment(view: EditorView, range: CommentRange, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr.addMark(range.from, range.to, type.create({ id }))\n tr.setMeta(commentKey, { pending: null } satisfies CommentMeta)\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\n/** Takes a removed thread's anchor off the text. */\nexport function unanchorComment(view: EditorView, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr\n view.state.doc.descendants((node, pos) => {\n if (!node.isText) return true\n const mark = node.marks.find((m) => m.type === type && m.attrs.id === id)\n if (mark) tr.removeMark(pos, pos + node.nodeSize, mark)\n return false\n })\n if (!tr.docChanged) return\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\nexport function setPendingComment(view: EditorView, range: CommentRange | null) {\n view.dispatch(view.state.tr.setMeta(commentKey, { pending: range } satisfies CommentMeta))\n}\n\n/**\n * A pasted copy of commented text doesn't take the thread along: the\n * thread keeps its one anchor. Text that was cut is no longer in the\n * document, so its threads come along with it.\n */\nfunction dropCopiedComments(slice: Slice, state: EditorState, known: ReadonlySet<string> | null) {\n const inDoc = new Set<string>()\n let any = false\n slice.content.descendants((node) => {\n if (node.marks.some((mark) => mark.type.name === 'comment')) any = true\n return !any\n })\n if (!any) return slice\n state.doc.descendants((node) => {\n for (const mark of node.marks) if (mark.type.name === 'comment') inDoc.add(mark.attrs.id)\n return true\n })\n const keep = (id: string) => !inDoc.has(id) && (!known || known.has(id))\n const strip = (fragment: Fragment): Fragment => {\n const nodes: PMNode[] = []\n fragment.forEach((node) => {\n if (node.isText) {\n nodes.push(\n node.mark(node.marks.filter((m) => m.type.name !== 'comment' || keep(m.attrs.id))),\n )\n } else nodes.push(node.copy(strip(node.content)))\n })\n return Fragment.from(nodes)\n }\n return new Slice(strip(slice.content), slice.openStart, slice.openEnd)\n}\n\nexport function commentPlugin(options: CommentPluginOptions): Plugin<CommentPluginState> {\n return new Plugin<CommentPluginState>({\n key: commentKey,\n state: {\n init: () => ({ pending: null, decorations: DecorationSet.empty }),\n apply(tr: Transaction, value: CommentPluginState): CommentPluginState {\n const meta = tr.getMeta(commentKey) as CommentMeta | undefined\n let pending = value.pending\n if (meta) pending = meta.pending\n else if (pending && tr.docChanged) {\n const from = tr.mapping.map(pending.from, 1)\n const to = tr.mapping.map(pending.to, -1)\n pending = to > from ? { from, to } : null\n }\n if (pending === value.pending && !tr.docChanged) return value\n return { pending, decorations: pendingDecorations(tr.doc, pending) }\n },\n },\n view: () => {\n let last: CommentRange | null = null\n return {\n update(view, previous) {\n const pending = commentKey.getState(view.state)!.pending\n if (pending !== last) options.onPending((last = pending))\n const { selection } = view.state\n // a selection made by the user, not one moved along by an edit\n if (\n !selection.empty &&\n view.state.doc === previous.doc &&\n !selection.eq(previous.selection)\n )\n options.onSelect()\n },\n }\n },\n props: {\n decorations: (state) => commentKey.getState(state)!.decorations,\n transformPasted: (slice, view) => dropCopiedComments(slice, view.state, options.known()),\n handleClick(view, pos, event) {\n if (event.button !== 0 || !options.known()) return false\n const known = options.known()!\n options.onClick(commentsAt(view.state, pos).filter((id) => known.has(id)))\n return false\n },\n },\n })\n}\n"],"mappings":";;;;;AAiCA,IAAa,aAAa,IAAI,UAA8B,qBAAqB;AAcjF,IAAM,sBAAsB,KAAa,UACvC,SAAS,MAAM,KAAK,MAAM,OACtB,cAAc,OAAO,KAAK,CACxB,WAAW,OAAO,MAAM,MAAM,MAAM,IAAI,EAAE,OAAO,8BAA8B,CAAC,CAClF,CAAC,IACD,cAAc;;AAGpB,SAAgB,WAAW,OAAoB,KAAuB;CACpE,MAAM,OAAO,MAAM,IAAI,QAAQ,GAAG;CAClC,MAAM,OAAO,KAAK,OAAO,WAAW,KAAK,YAAY,CAAC,CAAC;CACvD,IAAI,CAAC,MAAM,OAAO,CAAC;CACnB,MAAM,MAAM,KAAK,MACd,QAAQ,SAAS,KAAK,KAAK,SAAS,SAAS,CAAC,CAC9C,KAAK,SAAS,KAAK,MAAM,EAAY;CACxC,IAAI,IAAI,SAAS,GAAG,OAAO;CAC3B,MAAM,SAAS,IAAI,IAAI,IAAI,KAAK,OAAO,CAAC,IAAI,YAAY,MAAM,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC;CAE7E,OAAO,IAAI,MAAM,GAAG,MAAM,OAAO,IAAI,CAAC,IAAK,OAAO,IAAI,CAAC,CAAE;AAC3D;;AAGA,SAAS,YAAY,KAAa,IAAY,KAAqB;CACjE,MAAM,OAAO,IAAI,QAAQ,GAAG;CAC5B,MAAM,QAAQ,KAAK,MAAM;CACzB,IAAI,WAAW;CACf,IAAI,SAAS;CACb,IAAI,SAAS;CACb,KAAK,OAAO,SAAS,OAAO,WAAW;EACrC,MAAM,KAAK,QAAQ;EACnB,MAAM,MAA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AAC,CAAE;IACjD,IAAI,YAAY,MAAM,QAAQ,UAAW,OAAO,OAAQ;IACxD,MAAM,EAAE,cAAc,KAAK;IAE3B,IACE,CAAC,UAAU,SACX,KAAK,MAAM,QAAQ,SAAS,OAC5B,CAAC,UAAU,GAAG,SAAS,SAAS,GAEhC,QAAQ,SAAS;GACrB,EACF;EACF;EACA,OAAO;GACL,cAAc,UAAU,WAAW,SAAS,KAAK,CAAC,CAAE;GACpD,kBAAkB,OAAO,SAAS,mBAAmB,OAAO,KAAK,OAAO,QAAQ,MAAM,CAAC;GACvF,YAAY,MAAM,KAAK,OAAO;IAC5B,IAAI,MAAM,WAAW,KAAK,CAAC,QAAQ,MAAM,GAAG,OAAO;IACnD,MAAM,QAAQ,QAAQ,MAAM;IAC5B,QAAQ,QAAQ,WAAW,KAAK,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC;IACzE,OAAO;GACT;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"comments.js","names":[],"sources":["../../src/core/comments.ts"],"sourcesContent":["import { Fragment, Slice, type Node as PMNode } from 'prosemirror-model'\nimport { isHistoryTransaction } from 'prosemirror-history'\nimport { Plugin, PluginKey, type EditorState, type Transaction } from 'prosemirror-state'\nimport { Decoration, DecorationSet, type EditorView } from 'prosemirror-view'\nimport { blockAround } from './blocks'\nimport type { BlockProps } from './model'\n\n/*\n * Comment threads are anchored by a `comment` mark carrying the thread's\n * id on the text they are about, or inside a block that keeps them in its\n * props (its spec's `comments`, e.g. the nodes of a whiteboard). The\n * threads themselves (comments, replies, resolved) are kept outside the\n * document.\n */\n\n/** Where a thread is inside a block: what to show for it, and the block's own description of the spot. */\nexport interface BlockCommentAnchor<Target = unknown> {\n /** The text of what the thread is about, e.g. a node's label; `''` when it has none. */\n text: string\n /** Where in the block, as the block describes it, e.g. `{ node: 'n1' }`. */\n target: Target\n}\n\n/**\n * How a block type keeps comment threads on what is inside it, in its\n * props: the `comments` field of its spec. The block's component starts\n * and shows those threads itself (see `useEditor().comments`); the editor\n * lists them in `getCommentAnchors()`, leaves them out of pasted copies,\n * and puts them back after undo and redo, which restore older props.\n */\nexport interface BlockCommentsSpec<Target = unknown> {\n /** The threads in the block, by id. */\n anchors: (props: BlockProps) => Record<string, BlockCommentAnchor<Target>>\n /** The props with thread `id` on `target`; `null` when that isn't in the block any more. */\n place: (props: BlockProps, id: string, target: Target) => BlockProps | null\n /** The props with only the threads `keep` says yes to. */\n strip: (props: BlockProps, keep: (id: string) => boolean) => BlockProps\n}\n\ndeclare module 'prosemirror-model' {\n interface NodeSpec {\n /** Comment threads kept inside the block's props, see `BlockCommentsSpec`. */\n // oxlint-disable-next-line typescript/no-explicit-any -- each block type has its own target\n comments?: BlockCommentsSpec<any>\n }\n}\n\n/** The `comments` of a node's spec: a block type that keeps threads inside. */\nexport const blockCommentsOf = (node: PMNode) =>\n node.type.spec.comments as BlockCommentsSpec | undefined\n\n/** A range of the document, as positions. */\nexport interface CommentRange {\n from: number\n to: number\n}\n\n/** Where a thread is anchored: the block and the text it is about. */\nexport interface CommentAnchor {\n /** The id of the (first) block holding the text, or of the block the thread is inside. */\n block: string\n /** The text the thread is about; inside a block, what the block shows for it (e.g. a node's label). */\n text: string\n /** The text's first and last positions; inside a block, the block's. */\n from: number\n to: number\n /** Inside a block: the block's type. */\n type?: string\n /** Inside a block: where, as the block describes it (e.g. `{ node: 'n1' }` on a whiteboard). */\n target?: unknown\n}\n\nexport interface CommentPluginState {\n /** The text a thread is being started on, until its first comment is sent. */\n pending: CommentRange | null\n decorations: DecorationSet\n}\n\nexport const commentKey = new PluginKey<CommentPluginState>('dou-editor-comments')\n\ntype CommentMeta = { pending: CommentRange | null }\n\nexport interface CommentPluginOptions {\n /** The ids of the threads there are, or `null` when comments are off. */\n known: () => ReadonlySet<string> | null\n /** A click on text that is in threads, with their ids, innermost first; `[]` elsewhere. */\n onClick: (ids: string[]) => void\n onPending: (range: CommentRange | null) => void\n /** Text got selected (a range, not a cursor). */\n onSelect: () => void\n}\n\nconst pendingDecorations = (doc: PMNode, range: CommentRange | null) =>\n range && range.to > range.from\n ? DecorationSet.create(doc, [\n Decoration.inline(range.from, range.to, { class: 'dou-editor__comment-pending' }),\n ])\n : DecorationSet.empty\n\n/** The ids of the threads at `pos`, the shortest (innermost) first. */\nexport function commentsAt(state: EditorState, pos: number): string[] {\n const $pos = state.doc.resolve(pos)\n const node = $pos.parent.childAfter($pos.parentOffset).node\n if (!node) return []\n const ids = node.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (ids.length < 2) return ids\n const length = new Map(ids.map((id) => [id, rangeLength(state.doc, id, pos)]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh list\n return ids.sort((a, b) => length.get(a)! - length.get(b)!)\n}\n\n/** How long the run of `id`'s text around `pos` is, within its textblock. */\nfunction rangeLength(doc: PMNode, id: string, pos: number): number {\n const $pos = doc.resolve(pos)\n const start = $pos.start()\n let runStart = -1\n let around = false\n let length = Infinity\n $pos.parent.forEach((child, offset) => {\n const at = start + offset\n const end = at + child.nodeSize\n if (child.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (runStart < 0) runStart = at\n if (at <= pos && pos <= end) around = true\n if (around) length = end - runStart\n } else {\n if (around) around = false\n runStart = -1\n }\n })\n return length\n}\n\n/** Every thread's anchor in the document, by id: the first and last positions of its text. */\nexport function commentAnchors(doc: PMNode): Map<string, CommentAnchor> {\n const anchors = new Map<string, CommentAnchor>()\n doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (inside) {\n const block = (doc.resolve(pos).parent.attrs.id as string | undefined) ?? ''\n for (const [id, at] of Object.entries(inside.anchors(node.attrs))) {\n if (anchors.has(id)) continue\n const to = pos + node.nodeSize\n anchors.set(id, {\n block,\n text: at.text,\n from: pos,\n to,\n type: node.type.name,\n target: at.target,\n })\n }\n return false\n }\n if (!node.isText) return true\n for (const mark of node.marks) {\n if (mark.type.name !== 'comment') continue\n const id = mark.attrs.id as string\n const end = pos + node.nodeSize\n const anchor = anchors.get(id)\n if (anchor) {\n anchor.to = end\n anchor.text += node.text\n } else {\n const block = blockAround(doc.resolve(pos))\n anchors.set(id, {\n block: (block?.node.attrs.id as string | undefined) ?? '',\n text: node.text ?? '',\n from: pos,\n to: end,\n })\n }\n }\n return false\n })\n return anchors\n}\n\n/** The text of `id`'s anchor that a thread card points at: its first and last positions. */\nexport function commentRange(doc: PMNode, id: string): CommentRange | null {\n let from = -1\n let to = -1\n doc.descendants((node, pos) => {\n if (!node.isText) return true\n if (node.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (from < 0) from = pos\n to = pos + node.nodeSize\n }\n return false\n })\n return from < 0 ? null : { from, to }\n}\n\n/** Marks `range` as the text of a new thread. Not undone with the edits around it. */\nexport function anchorComment(view: EditorView, range: CommentRange, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr.addMark(range.from, range.to, type.create({ id }))\n tr.setMeta(commentKey, { pending: null } satisfies CommentMeta)\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\n/** Sets the props of the block content at `pos` that differ in `next`. */\nfunction setProps(tr: Transaction, pos: number, before: BlockProps, next: BlockProps) {\n for (const [name, value] of Object.entries(next))\n if (Object.hasOwn(before, name) && before[name] !== value) tr.setNodeAttribute(pos, name, value)\n}\n\n/** The id of the block around the content node at `pos`. */\nconst blockIdAt = (doc: PMNode, pos: number) =>\n (doc.resolve(pos).parent.attrs.id as string | undefined) ?? ''\n\n/** Takes a removed thread's anchor off the text, or out of the block it is inside. */\nexport function unanchorComment(view: EditorView, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr\n view.state.doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (inside) {\n if (Object.hasOwn(inside.anchors(node.attrs), id))\n setProps(\n tr,\n pos,\n node.attrs,\n inside.strip(node.attrs, (other) => other !== id),\n )\n return false\n }\n if (!node.isText) return true\n const mark = node.marks.find((m) => m.type === type && m.attrs.id === id)\n if (mark) tr.removeMark(pos, pos + node.nodeSize, mark)\n return false\n })\n if (!tr.docChanged) return\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\nexport function setPendingComment(view: EditorView, range: CommentRange | null) {\n view.dispatch(view.state.tr.setMeta(commentKey, { pending: range } satisfies CommentMeta))\n}\n\n/**\n * A pasted copy of commented text doesn't take the thread along: the\n * thread keeps its one anchor. Text that was cut is no longer in the\n * document, so its threads come along with it.\n */\nfunction dropCopiedComments(slice: Slice, state: EditorState, known: ReadonlySet<string> | null) {\n const inDoc = new Set<string>()\n let any = false\n slice.content.descendants((node) => {\n if (node.marks.some((mark) => mark.type.name === 'comment')) any = true\n const inside = blockCommentsOf(node)\n if (inside && Object.keys(inside.anchors(node.attrs)).length) any = true\n return !any\n })\n if (!any) return slice\n state.doc.descendants((node) => {\n for (const mark of node.marks) if (mark.type.name === 'comment') inDoc.add(mark.attrs.id)\n const inside = blockCommentsOf(node)\n if (inside) for (const id of Object.keys(inside.anchors(node.attrs))) inDoc.add(id)\n return true\n })\n const keep = (id: string) => !inDoc.has(id) && (!known || known.has(id))\n const strip = (fragment: Fragment): Fragment => {\n const nodes: PMNode[] = []\n fragment.forEach((node) => {\n const inside = blockCommentsOf(node)\n if (node.isText) {\n nodes.push(\n node.mark(node.marks.filter((m) => m.type.name !== 'comment' || keep(m.attrs.id))),\n )\n } else if (inside) {\n const attrs = { ...node.attrs, ...inside.strip(node.attrs, keep) }\n nodes.push(node.type.create(attrs, strip(node.content), node.marks))\n } else nodes.push(node.copy(strip(node.content)))\n })\n return Fragment.from(nodes)\n }\n return new Slice(strip(slice.content), slice.openStart, slice.openEnd)\n}\n\n/** The threads inside each block that keeps them, by block id. */\nfunction blockAnchors(doc: PMNode) {\n const found = new Map<string, Record<string, BlockCommentAnchor>>()\n doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (!inside) return true\n found.set(blockIdAt(doc, pos), inside.anchors(node.attrs))\n return false\n })\n return found\n}\n\n/**\n * Undo and redo bring back a block's props as they were, threads included,\n * but starting and deleting threads aren't steps of the history: each block\n * keeps the threads it had before, put back where they were if that is\n * still there, and those it comes back with that are still threads (on a\n * node brought back, say), not those deleted since. A block brought back by\n * the undo keeps what it comes with.\n */\nfunction keepBlockComments(\n before: PMNode,\n state: EditorState,\n known: ReadonlySet<string> | null,\n): Transaction | null {\n const had = blockAnchors(before)\n if (!had.size) return null\n const tr = state.tr\n state.doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (!inside) return true\n const anchors = had.get(blockIdAt(state.doc, pos))\n if (!anchors) return false\n let props = inside.strip(\n node.attrs,\n (id) => Object.hasOwn(anchors, id) || !known || known.has(id),\n )\n const now = inside.anchors(props)\n for (const [id, at] of Object.entries(anchors)) {\n if (Object.hasOwn(now, id)) continue\n props = inside.place(props, id, at.target) ?? props\n }\n if (props !== node.attrs) setProps(tr, pos, node.attrs, props)\n return false\n })\n return tr.docChanged ? tr.setMeta('addToHistory', false) : null\n}\n\nexport function commentPlugin(options: CommentPluginOptions): Plugin<CommentPluginState> {\n return new Plugin<CommentPluginState>({\n key: commentKey,\n appendTransaction: (trs, before, state) =>\n trs.some((tr) => tr.docChanged && isHistoryTransaction(tr))\n ? keepBlockComments(before.doc, state, options.known())\n : null,\n state: {\n init: () => ({ pending: null, decorations: DecorationSet.empty }),\n apply(tr: Transaction, value: CommentPluginState): CommentPluginState {\n const meta = tr.getMeta(commentKey) as CommentMeta | undefined\n let pending = value.pending\n if (meta) pending = meta.pending\n else if (pending && tr.docChanged) {\n const from = tr.mapping.map(pending.from, 1)\n const to = tr.mapping.map(pending.to, -1)\n pending = to > from ? { from, to } : null\n }\n if (pending === value.pending && !tr.docChanged) return value\n return { pending, decorations: pendingDecorations(tr.doc, pending) }\n },\n },\n view: () => {\n let last: CommentRange | null = null\n return {\n update(view, previous) {\n const pending = commentKey.getState(view.state)!.pending\n if (pending !== last) options.onPending((last = pending))\n const { selection } = view.state\n // a selection made by the user, not one moved along by an edit\n if (\n !selection.empty &&\n view.state.doc === previous.doc &&\n !selection.eq(previous.selection)\n )\n options.onSelect()\n },\n }\n },\n props: {\n decorations: (state) => commentKey.getState(state)!.decorations,\n transformPasted: (slice, view) => dropCopiedComments(slice, view.state, options.known()),\n handleClick(view, pos, event) {\n if (event.button !== 0 || !options.known()) return false\n const known = options.known()!\n options.onClick(commentsAt(view.state, pos).filter((id) => known.has(id)))\n return false\n },\n },\n })\n}\n"],"mappings":";;;;;;;AAgDA,IAAa,mBAAmB,SAC9B,KAAK,KAAK,KAAK;AA6BjB,IAAa,aAAa,IAAI,UAA8B,qBAAqB;AAcjF,IAAM,sBAAsB,KAAa,UACvC,SAAS,MAAM,KAAK,MAAM,OACtB,cAAc,OAAO,KAAK,CACxB,WAAW,OAAO,MAAM,MAAM,MAAM,IAAI,EAAE,OAAO,8BAA8B,CAAC,CAClF,CAAC,IACD,cAAc;;AAGpB,SAAgB,WAAW,OAAoB,KAAuB;CACpE,MAAM,OAAO,MAAM,IAAI,QAAQ,GAAG;CAClC,MAAM,OAAO,KAAK,OAAO,WAAW,KAAK,YAAY,CAAC,CAAC;CACvD,IAAI,CAAC,MAAM,OAAO,CAAC;CACnB,MAAM,MAAM,KAAK,MACd,QAAQ,SAAS,KAAK,KAAK,SAAS,SAAS,CAAC,CAC9C,KAAK,SAAS,KAAK,MAAM,EAAY;CACxC,IAAI,IAAI,SAAS,GAAG,OAAO;CAC3B,MAAM,SAAS,IAAI,IAAI,IAAI,KAAK,OAAO,CAAC,IAAI,YAAY,MAAM,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC;CAE7E,OAAO,IAAI,MAAM,GAAG,MAAM,OAAO,IAAI,CAAC,IAAK,OAAO,IAAI,CAAC,CAAE;AAC3D;;AAGA,SAAS,YAAY,KAAa,IAAY,KAAqB;CACjE,MAAM,OAAO,IAAI,QAAQ,GAAG;CAC5B,MAAM,QAAQ,KA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OAAO;MAAE;MAAM;KAAG,IAAI;IACvC;IACA,IAAI,YAAY,MAAM,WAAW,CAAC,GAAG,YAAY,OAAO;IACxD,OAAO;KAAE;KAAS,aAAa,mBAAmB,GAAG,KAAK,OAAO;IAAE;GACrE;EACF;EACA,YAAY;GACV,IAAI,OAA4B;GAChC,OAAO,EACL,OAAO,MAAM,UAAU;IACrB,MAAM,UAAU,WAAW,SAAS,KAAK,KAAK,CAAC,CAAE;IACjD,IAAI,YAAY,MAAM,QAAQ,UAAW,OAAO,OAAQ;IACxD,MAAM,EAAE,cAAc,KAAK;IAE3B,IACE,CAAC,UAAU,SACX,KAAK,MAAM,QAAQ,SAAS,OAC5B,CAAC,UAAU,GAAG,SAAS,SAAS,GAEhC,QAAQ,SAAS;GACrB,EACF;EACF;EACA,OAAO;GACL,cAAc,UAAU,WAAW,SAAS,KAAK,CAAC,CAAE;GACpD,kBAAkB,OAAO,SAAS,mBAAmB,OAAO,KAAK,OAAO,QAAQ,MAAM,CAAC;GACvF,YAAY,MAAM,KAAK,OAAO;IAC5B,IAAI,MAAM,WAAW,KAAK,CAAC,QAAQ,MAAM,GAAG,OAAO;IACnD,MAAM,QAAQ,QAAQ,MAAM;IAC5B,QAAQ,QAAQ,WAAW,KAAK,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC;IACzE,OAAO;GACT;EACF;CACF,CAAC;AACH"}
@@ -71,15 +71,17 @@ function vueNodeView(component, appContext, provides = []) {
71
71
  },
72
72
  selected: false,
73
73
  editable: view.editable,
74
- updateProps(props) {
74
+ updateProps(props, options) {
75
75
  const pos = getPos();
76
76
  if (pos === void 0) return;
77
77
  const current = view.state.doc.nodeAt(pos);
78
78
  if (!current) return;
79
- view.dispatch(view.state.tr.setNodeMarkup(pos, void 0, {
79
+ const tr = view.state.tr.setNodeMarkup(pos, void 0, {
80
80
  ...current.attrs,
81
81
  ...props
82
- }));
82
+ });
83
+ if (options?.history === false) tr.setMeta("addToHistory", false);
84
+ view.dispatch(tr);
83
85
  }
84
86
  });
85
87
  const Root = defineComponent({ setup() {
@@ -144,6 +146,7 @@ function defineBlock(options) {
144
146
  },
145
147
  continues: options.continues,
146
148
  component: options.component,
149
+ comments: options.comments,
147
150
  parseDOM: [{
148
151
  tag: `div[data-content-type="${type}"]`,
149
152
  getAttrs: (dom) => readDataAttrs(dom, names)
@@ -1 +1 @@
1
- {"version":3,"file":"define-block.js","names":[],"sources":["../src/define-block.ts"],"sourcesContent":["import type { NodeSpec } from 'prosemirror-model'\nimport type { NodeView, NodeViewConstructor } from 'prosemirror-view'\nimport {\n defineComponent,\n h,\n inject,\n onMounted,\n provide,\n render,\n shallowReactive,\n shallowRef,\n type AppContext,\n type Component,\n type InjectionKey,\n type PropType,\n} from 'vue'\nimport type { BlockOption, EditorExtension, Label, MountComponent } from './core/extension'\nimport type { BlockProps } from './core/model'\n\n/** What a block's Vue component receives. */\nexport interface BlockViewProps {\n /** The block's id, type and current props. */\n block: { id: string; type: string; props: BlockProps }\n /** Change props; the change goes into the document, the undo history and collaboration. */\n updateProps: (props: BlockProps) => void\n /** The block is selected as a whole (a block without text was clicked). */\n selected: boolean\n editable: boolean\n}\n\nexport interface DefineBlockOptions {\n type: string\n /** The props and their defaults. They are stored in the document, as `Block.props`. */\n props?: Record<string, unknown>\n /** `inline` holds formatted text; `none` has no text (an image, an embed). Defaults to `inline`. */\n content?: 'inline' | 'none'\n /** Renders the block. Put `<EditorContent />` where the text goes. */\n component?: Component\n /** `Enter` at the end continues with the same type, like a list. */\n continues?: boolean\n /** Entries for the slash menu and the “turn into” menus; one is made from `menu` when given. */\n menu?: Omit<BlockOption, 'key' | 'type'> & { key?: string }\n /** Override the ProseMirror spec, e.g. `parseDOM` for pasting HTML from elsewhere. */\n spec?: Partial<NodeSpec>\n}\n\nconst contentKey: InjectionKey<HTMLElement | null> = Symbol('DouEditorContent')\n\n/** Where a block component's text goes. */\nexport const EditorContent = defineComponent({\n name: 'DouEditorContent',\n props: { as: { type: String as PropType<string>, default: 'div' } },\n setup(props) {\n const content = inject(contentKey, null)\n const host = shallowRef<HTMLElement | null>(null)\n onMounted(() => {\n if (content && host.value) host.value.append(content)\n })\n return () => h(props.as, { ref: host, class: 'dou-editor__text' })\n },\n})\n\n/** Store props as `data-prop-*` attributes, so copy and paste keep them. */\nconst dataAttrs = (props: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => [`data-prop-${name}`, JSON.stringify(value)]),\n )\n\nfunction readDataAttrs(dom: HTMLElement, names: string[]) {\n const attrs: Record<string, unknown> = {}\n for (const name of names) {\n const raw = dom.getAttribute(`data-prop-${name}`)\n if (raw === null) continue\n try {\n attrs[name] = JSON.parse(raw)\n } catch {\n // ignore attributes that are not ours\n }\n }\n return attrs\n}\n\n/** Renders components inside an app, with values provided to them. */\nexport function componentMounter(\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): MountComponent {\n return (component, props, element) => {\n const Root = defineComponent({\n setup() {\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...props })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, element)\n return () => render(null, element)\n }\n}\n\n/**\n * A node view that renders a Vue component. Everything the component shows\n * besides the text is outside the editable content, so its buttons and\n * inputs work as usual.\n */\nexport function vueNodeView(\n component: Component,\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): NodeViewConstructor {\n return (node, view, getPos) => {\n // the id lives on the block around the content node\n const idOf = () => {\n const pos = getPos()\n if (pos === undefined) return ''\n return (view.state.doc.resolve(pos).parent.attrs.id as string | null) ?? ''\n }\n const type = node.type.name\n const dom = document.createElement('div')\n dom.className = `dou-editor__content dou-editor__content--${type} dou-editor__content--custom`\n dom.dataset.contentType = type\n const contentElement = node.isTextblock ? document.createElement('div') : null\n const state = shallowReactive<BlockViewProps>({\n block: { id: idOf(), type, props: { ...node.attrs } },\n selected: false,\n editable: view.editable,\n updateProps(props) {\n const pos = getPos()\n if (pos === undefined) return\n const current = view.state.doc.nodeAt(pos)\n if (!current) return\n view.dispatch(view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...props }))\n },\n })\n const Root = defineComponent({\n setup() {\n provide(contentKey, contentElement)\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...state })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, dom)\n let current = node\n const nodeView: NodeView = {\n dom,\n contentDOM: contentElement,\n update(next) {\n if (next.type !== current.type) return false\n current = next\n state.block = { id: idOf(), type, props: { ...next.attrs } }\n state.editable = view.editable\n return true\n },\n selectNode() {\n state.selected = true\n },\n deselectNode() {\n state.selected = false\n },\n // the component's own controls (and anything marked `data-editor-control`)\n // handle their events; the editor gets the rest, so a click on a block\n // without text still selects it\n stopEvent: (event) => {\n const target = event.target as HTMLElement\n if (contentElement?.contains(target)) return false\n const control = target.closest?.(\n 'input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]',\n )\n // only inside the block: the editor around it is contenteditable too\n return !!control && control !== dom && dom.contains(control)\n },\n ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),\n destroy() {\n render(null, dom)\n },\n }\n return nodeView\n }\n}\n\n/**\n * Declare a block type rendered by a Vue component (or by plain DOM), with\n * its props stored in the document. Returns an extension for `extensions`.\n */\nexport function defineBlock(options: DefineBlockOptions): EditorExtension {\n const { type } = options\n const props = options.props ?? {}\n const names = Object.keys(props)\n const inline = (options.content ?? 'inline') === 'inline'\n const spec: NodeSpec = {\n attrs: Object.fromEntries(names.map((name) => [name, { default: props[name] }])),\n ...(inline ? { content: 'inline*', defining: true } : { atom: true, selectable: true }),\n continues: options.continues,\n component: options.component,\n parseDOM: [\n {\n tag: `div[data-content-type=\"${type}\"]`,\n getAttrs: (dom) => readDataAttrs(dom as HTMLElement, names),\n },\n ],\n toDOM: (node) => {\n const attrs = {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...dataAttrs(node.attrs),\n }\n return inline ? ['div', attrs, 0] : ['div', attrs]\n },\n ...options.spec,\n }\n const menu = options.menu\n return {\n name: `block:${type}`,\n blocks: { [type]: spec },\n blockOptions: menu ? [{ ...menu, key: menu.key ?? type, type }] : [],\n }\n}\n\nexport type { Label }\n"],"mappings":";;AA8CA,IAAM,aAA+C,OAAO,kBAAkB;;AAG9E,IAAa,gBAAgB,gBAAgB;CAC3C,MAAM;CACN,OAAO,EAAE,IAAI;EAAE,MAAM;EAA4B,SAAS;CAAM,EAAE;CAClE,MAAM,OAAO;EACX,MAAM,UAAU,OAAO,YAAY,IAAI;EACvC,MAAM,OAAO,WAA+B,IAAI;EAChD,gBAAgB;GACd,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,OAAO,OAAO;EACtD,CAAC;EACD,aAAa,EAAE,MAAM,IAAI;GAAE,KAAK;GAAM,OAAO;EAAmB,CAAC;CACnE;AACF,CAAC;;AAGD,IAAM,aAAa,UACjB,OAAO,YACL,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,aAAa,QAAQ,KAAK,UAAU,KAAK,CAAC,CAAC,CAC3F;AAEF,SAAS,cAAc,KAAkB,OAAiB;CACxD,MAAM,QAAiC,CAAC;CACxC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,MAAM,IAAI,aAAa,aAAa,MAAM;EAChD,IAAI,QAAQ,MAAM;EAClB,IAAI;GACF,MAAM,QAAQ,KAAK,MAAM,GAAG;EAC9B,QAAQ,CAER;CACF;CACA,OAAO;AACT;;AAGA,SAAgB,iBACd,YACA,WAA+C,CAAC,GAChC;CAChB,QAAQ,WAAW,OAAO,YAAY;EACpC,MAAM,OAAO,gBAAgB,EAC3B,QAAQ;GACN,KAAK,MAAM,CAAC,KAAK,UAAU,UAAU,QAAQ,KAAK,KAAK;GACvD,aAAa,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;EACxC,EACF,CAAC;EACD,MA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;IAAO;IAAO;GAAC,IAAI,CAAC,OAAO,KAAK;EACnD;EACA,GAAG,QAAQ;CACb;CACA,MAAM,OAAO,QAAQ;CACrB,OAAO;EACL,MAAM,SAAS;EACf,QAAQ,GAAG,OAAO,KAAK;EACvB,cAAc,OAAO,CAAC;GAAE,GAAG;GAAM,KAAK,KAAK,OAAO;GAAM;EAAK,CAAC,IAAI,CAAC;CACrE;AACF"}
1
+ {"version":3,"file":"define-block.js","names":[],"sources":["../src/define-block.ts"],"sourcesContent":["import type { NodeSpec } from 'prosemirror-model'\nimport type { NodeView, NodeViewConstructor } from 'prosemirror-view'\nimport {\n defineComponent,\n h,\n inject,\n onMounted,\n provide,\n render,\n shallowReactive,\n shallowRef,\n type AppContext,\n type Component,\n type InjectionKey,\n type PropType,\n} from 'vue'\nimport type { BlockCommentsSpec } from './core/comments'\nimport type { BlockOption, EditorExtension, Label, MountComponent } from './core/extension'\nimport type { BlockProps } from './core/model'\n\n/** What a block's Vue component receives. */\nexport interface BlockViewProps {\n /** The block's id, type and current props. */\n block: { id: string; type: string; props: BlockProps }\n /**\n * Change props; the change goes into the document, the undo history and\n * collaboration. `history: false` keeps it out of the undo history, e.g.\n * for the id of a comment thread put inside the block.\n */\n updateProps: (props: BlockProps, options?: { history?: boolean }) => void\n /** The block is selected as a whole (a block without text was clicked). */\n selected: boolean\n editable: boolean\n}\n\nexport interface DefineBlockOptions<Target = unknown> {\n type: string\n /** The props and their defaults. They are stored in the document, as `Block.props`. */\n props?: Record<string, unknown>\n /** `inline` holds formatted text; `none` has no text (an image, an embed). Defaults to `inline`. */\n content?: 'inline' | 'none'\n /** Renders the block. Put `<EditorContent />` where the text goes. */\n component?: Component\n /** `Enter` at the end continues with the same type, like a list. */\n continues?: boolean\n /**\n * Comment threads on what is inside the block, kept in its props: how\n * to find, put back and strip them. See `BlockCommentsSpec`.\n */\n comments?: BlockCommentsSpec<Target>\n /** Entries for the slash menu and the “turn into” menus; one is made from `menu` when given. */\n menu?: Omit<BlockOption, 'key' | 'type'> & { key?: string }\n /** Override the ProseMirror spec, e.g. `parseDOM` for pasting HTML from elsewhere. */\n spec?: Partial<NodeSpec>\n}\n\nconst contentKey: InjectionKey<HTMLElement | null> = Symbol('DouEditorContent')\n\n/** Where a block component's text goes. */\nexport const EditorContent = defineComponent({\n name: 'DouEditorContent',\n props: { as: { type: String as PropType<string>, default: 'div' } },\n setup(props) {\n const content = inject(contentKey, null)\n const host = shallowRef<HTMLElement | null>(null)\n onMounted(() => {\n if (content && host.value) host.value.append(content)\n })\n return () => h(props.as, { ref: host, class: 'dou-editor__text' })\n },\n})\n\n/** Store props as `data-prop-*` attributes, so copy and paste keep them. */\nconst dataAttrs = (props: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => [`data-prop-${name}`, JSON.stringify(value)]),\n )\n\nfunction readDataAttrs(dom: HTMLElement, names: string[]) {\n const attrs: Record<string, unknown> = {}\n for (const name of names) {\n const raw = dom.getAttribute(`data-prop-${name}`)\n if (raw === null) continue\n try {\n attrs[name] = JSON.parse(raw)\n } catch {\n // ignore attributes that are not ours\n }\n }\n return attrs\n}\n\n/** Renders components inside an app, with values provided to them. */\nexport function componentMounter(\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): MountComponent {\n return (component, props, element) => {\n const Root = defineComponent({\n setup() {\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...props })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, element)\n return () => render(null, element)\n }\n}\n\n/**\n * A node view that renders a Vue component. Everything the component shows\n * besides the text is outside the editable content, so its buttons and\n * inputs work as usual.\n */\nexport function vueNodeView(\n component: Component,\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): NodeViewConstructor {\n return (node, view, getPos) => {\n // the id lives on the block around the content node\n const idOf = () => {\n const pos = getPos()\n if (pos === undefined) return ''\n return (view.state.doc.resolve(pos).parent.attrs.id as string | null) ?? ''\n }\n const type = node.type.name\n const dom = document.createElement('div')\n dom.className = `dou-editor__content dou-editor__content--${type} dou-editor__content--custom`\n dom.dataset.contentType = type\n const contentElement = node.isTextblock ? document.createElement('div') : null\n const state = shallowReactive<BlockViewProps>({\n block: { id: idOf(), type, props: { ...node.attrs } },\n selected: false,\n editable: view.editable,\n updateProps(props, options) {\n const pos = getPos()\n if (pos === undefined) return\n const current = view.state.doc.nodeAt(pos)\n if (!current) return\n const tr = view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...props })\n if (options?.history === false) tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n },\n })\n const Root = defineComponent({\n setup() {\n provide(contentKey, contentElement)\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...state })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, dom)\n let current = node\n const nodeView: NodeView = {\n dom,\n contentDOM: contentElement,\n update(next) {\n if (next.type !== current.type) return false\n current = next\n state.block = { id: idOf(), type, props: { ...next.attrs } }\n state.editable = view.editable\n return true\n },\n selectNode() {\n state.selected = true\n },\n deselectNode() {\n state.selected = false\n },\n // the component's own controls (and anything marked `data-editor-control`)\n // handle their events; the editor gets the rest, so a click on a block\n // without text still selects it\n stopEvent: (event) => {\n const target = event.target as HTMLElement\n if (contentElement?.contains(target)) return false\n const control = target.closest?.(\n 'input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]',\n )\n // only inside the block: the editor around it is contenteditable too\n return !!control && control !== dom && dom.contains(control)\n },\n ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),\n destroy() {\n render(null, dom)\n },\n }\n return nodeView\n }\n}\n\n/**\n * Declare a block type rendered by a Vue component (or by plain DOM), with\n * its props stored in the document. Returns an extension for `extensions`.\n */\nexport function defineBlock<Target = unknown>(\n options: DefineBlockOptions<Target>,\n): EditorExtension {\n const { type } = options\n const props = options.props ?? {}\n const names = Object.keys(props)\n const inline = (options.content ?? 'inline') === 'inline'\n const spec: NodeSpec = {\n attrs: Object.fromEntries(names.map((name) => [name, { default: props[name] }])),\n ...(inline ? { content: 'inline*', defining: true } : { atom: true, selectable: true }),\n continues: options.continues,\n component: options.component,\n comments: options.comments,\n parseDOM: [\n {\n tag: `div[data-content-type=\"${type}\"]`,\n getAttrs: (dom) => readDataAttrs(dom as HTMLElement, names),\n },\n ],\n toDOM: (node) => {\n const attrs = {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...dataAttrs(node.attrs),\n }\n return inline ? ['div', attrs, 0] : ['div', attrs]\n },\n ...options.spec,\n }\n const menu = options.menu\n return {\n name: `block:${type}`,\n blocks: { [type]: spec },\n blockOptions: menu ? [{ ...menu, key: menu.key ?? type, type }] : [],\n }\n}\n\nexport type { Label }\n"],"mappings":";;AAwDA,IAAM,aAA+C,OAAO,kBAAkB;;AAG9E,IAAa,gBAAgB,gBAAgB;CAC3C,MAAM;CACN,OAAO,EAAE,IAAI;EAAE,MAAM;EAA4B,SAAS;CAAM,EAAE;CAClE,MAAM,OAAO;EACX,MAAM,UAAU,OAAO,YAAY,IAAI;EACvC,MAAM,OAAO,WAA+B,IAAI;EAChD,gBAAgB;GACd,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,OAAO,OAAO;EACtD,CAAC;EACD,aAAa,EAAE,MAAM,IAAI;GAAE,KAAK;GAAM,OAAO;EAAmB,CAAC;CACnE;AACF,CAAC;;AAGD,IAAM,aAAa,UACjB,OAAO,YACL,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAAC,aAAa,QAAQ,KAAK,UAAU,KAAK,CAAC,CAAC,CAC3F;AAEF,SAAS,cAAc,KAAkB,OAAiB;CACxD,MAAM,QAAiC,CAAC;CACxC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,MAAM,IAAI,aAAa,aAAa,MAAM;EAChD,IAAI,QAAQ,MAAM;EAClB,IAAI;GACF,MAAM,QAAQ,KAAK,MAAM,GAAG;EAC9B,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