@univerjs/thread-comment 1.0.0-insiders.20260809-70eefdd → 1.0.0-rc.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.
package/lib/cjs/index.js CHANGED
@@ -58,18 +58,29 @@ var ThreadCommentDataSourceService = class extends _univerjs_core.Disposable {
58
58
  constructor() {
59
59
  super();
60
60
  _defineProperty(this, "_dataSource", null);
61
+ _defineProperty(this, "_pendingAdds", /* @__PURE__ */ new Map());
61
62
  _defineProperty(this, "syncUpdateMutationToColla", true);
62
63
  }
63
64
  async getThreadComment(unitId, subUnitId, threadId) {
64
65
  if (this._dataSource) return (await this._dataSource.listComments(unitId, subUnitId, [threadId]))[0];
65
66
  return null;
66
67
  }
67
- async addComment(comment) {
68
- const savedComment = this._dataSource ? await this._dataSource.addComment(comment) : comment;
69
- return {
70
- ...savedComment,
71
- threadId: savedComment.threadId || savedComment.id
72
- };
68
+ addComment(comment) {
69
+ const key = `${comment.unitId}\0${comment.subUnitId}\0${comment.id}`;
70
+ const pending = this._pendingAdds.get(key);
71
+ if (pending) return pending;
72
+ const request = (async () => {
73
+ const savedComment = this._dataSource ? await this._dataSource.addComment(comment) : comment;
74
+ return {
75
+ ...savedComment,
76
+ threadId: savedComment.threadId || savedComment.id
77
+ };
78
+ })();
79
+ this._pendingAdds.set(key, request);
80
+ request.finally(() => {
81
+ if (this._pendingAdds.get(key) === request) this._pendingAdds.delete(key);
82
+ }).catch(() => void 0);
83
+ return request;
73
84
  }
74
85
  async updateComment(comment) {
75
86
  if (this._dataSource) return this._dataSource.updateComment(comment);
@@ -83,11 +94,16 @@ var ThreadCommentDataSourceService = class extends _univerjs_core.Disposable {
83
94
  if (this._dataSource) return this._dataSource.deleteComment(unitId, subUnitId, threadId, commentId);
84
95
  return true;
85
96
  }
97
+ async deleteThread(unitId, subUnitId, threadId) {
98
+ var _this$_dataSource;
99
+ if ((_this$_dataSource = this._dataSource) === null || _this$_dataSource === void 0 ? void 0 : _this$_dataSource.deleteThread) return this._dataSource.deleteThread(unitId, subUnitId, threadId);
100
+ return this.deleteComment(unitId, subUnitId, threadId, threadId);
101
+ }
86
102
  async listThreadComments(unitId, subUnitId, threadIds) {
87
103
  if (this.dataSource) return this.dataSource.listComments(unitId, subUnitId, threadIds);
88
104
  return false;
89
105
  }
90
- saveToSnapshot(unitComments, unitId) {
106
+ saveToSnapshot(unitComments, _unitId) {
91
107
  if (this._dataSource) {
92
108
  const map = {};
93
109
  Object.keys(unitComments).forEach((subUnitId) => {
@@ -101,6 +117,86 @@ var ThreadCommentDataSourceService = class extends _univerjs_core.Disposable {
101
117
  };
102
118
  const IThreadCommentDataSourceService = (0, _univerjs_core.createIdentifier)("univer.thread-comment.data-source-service");
103
119
 
120
+ //#endregion
121
+ //#region src/types/comment-anchor.ts
122
+ /**
123
+ * Copyright 2023-present DreamNum Co., Ltd.
124
+ *
125
+ * Licensed under the Apache License, Version 2.0 (the "License");
126
+ * you may not use this file except in compliance with the License.
127
+ * You may obtain a copy of the License at
128
+ *
129
+ * http://www.apache.org/licenses/LICENSE-2.0
130
+ *
131
+ * Unless required by applicable law or agreed to in writing, software
132
+ * distributed under the License is distributed on an "AS IS" BASIS,
133
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
134
+ * See the License for the specific language governing permissions and
135
+ * limitations under the License.
136
+ */
137
+ let ThreadCommentAnchorKind = /* @__PURE__ */ function(ThreadCommentAnchorKind) {
138
+ /** A cell comment managed by the Sheets range Facade. */
139
+ ThreadCommentAnchorKind["SHEET_CELL"] = "sheet-cell";
140
+ /** A Sheet image, chart, Shape, or other drawing element. */
141
+ ThreadCommentAnchorKind["SHEET_DRAWING"] = "sheet-drawing";
142
+ /** A fixed text range comment managed by the Docs text range Facade. */
143
+ ThreadCommentAnchorKind["DOC_TEXT_RANGE"] = "doc-text-range";
144
+ /** A Document image, chart, Shape, or other drawing element. */
145
+ ThreadCommentAnchorKind["DOC_DRAWING"] = "doc-drawing";
146
+ /** A Slide page element identified by a stable element ID. */
147
+ ThreadCommentAnchorKind["SLIDE_ELEMENT"] = "slide-element";
148
+ /** A free position normalized to the Slide page size. */
149
+ ThreadCommentAnchorKind["SLIDE_POSITION"] = "slide-position";
150
+ /** A Board element identified by a stable element ID. */
151
+ ThreadCommentAnchorKind["BOARD_ELEMENT"] = "board-element";
152
+ /** A free position in Board world coordinates. */
153
+ ThreadCommentAnchorKind["BOARD_POSITION"] = "board-position";
154
+ /** A Base record identified by stable table and record IDs. */
155
+ ThreadCommentAnchorKind["BASE_RECORD"] = "base-record";
156
+ return ThreadCommentAnchorKind;
157
+ }({});
158
+ const THREAD_COMMENT_ANCHOR_PREFIX = "univer-comment-anchor:";
159
+ function isNonEmptyString(value) {
160
+ return typeof value === "string" && value.length > 0;
161
+ }
162
+ function isOptionalString(value) {
163
+ return value === void 0 || isNonEmptyString(value);
164
+ }
165
+ function isFiniteNumber(value) {
166
+ return typeof value === "number" && Number.isFinite(value);
167
+ }
168
+ function isThreadCommentAnchor(value) {
169
+ if (!value || typeof value !== "object") return false;
170
+ switch (Reflect.get(value, "kind")) {
171
+ case "sheet-drawing":
172
+ case "doc-drawing":
173
+ case "slide-element":
174
+ case "board-element": return isNonEmptyString(Reflect.get(value, "elementId")) && isOptionalString(Reflect.get(value, "pageId"));
175
+ case "slide-position":
176
+ case "board-position": return isFiniteNumber(Reflect.get(value, "x")) && isFiniteNumber(Reflect.get(value, "y")) && isOptionalString(Reflect.get(value, "pageId"));
177
+ case "base-record": return isNonEmptyString(Reflect.get(value, "tableId")) && isNonEmptyString(Reflect.get(value, "recordId"));
178
+ default: return false;
179
+ }
180
+ }
181
+ function serializeThreadCommentAnchor(anchor) {
182
+ if (!isThreadCommentAnchor(anchor)) throw new TypeError("Invalid thread comment anchor");
183
+ return `${THREAD_COMMENT_ANCHOR_PREFIX}${JSON.stringify({
184
+ v: 1,
185
+ anchor
186
+ })}`;
187
+ }
188
+ function deserializeThreadCommentAnchor(ref) {
189
+ if (!ref.startsWith(THREAD_COMMENT_ANCHOR_PREFIX)) return null;
190
+ try {
191
+ const value = JSON.parse(ref.slice(22));
192
+ if (!value || typeof value !== "object" || Reflect.get(value, "v") !== 1) return null;
193
+ const anchor = Reflect.get(value, "anchor");
194
+ return isThreadCommentAnchor(anchor) ? anchor : null;
195
+ } catch {
196
+ return null;
197
+ }
198
+ }
199
+
104
200
  //#endregion
105
201
  //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
106
202
  function __decorateParam(paramIndex, decorator) {
@@ -121,12 +217,15 @@ function __decorate(decorators, target, key, desc) {
121
217
  //#endregion
122
218
  //#region src/models/thread-comment.model.ts
123
219
  let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposable {
124
- constructor(_dataSourceService, _lifecycleService) {
220
+ constructor(_dataSourceService, _lifecycleService, _univerInstanceService) {
125
221
  super();
126
222
  this._dataSourceService = _dataSourceService;
127
223
  this._lifecycleService = _lifecycleService;
224
+ this._univerInstanceService = _univerInstanceService;
128
225
  _defineProperty(this, "_commentsMap", /* @__PURE__ */ new Map());
129
226
  _defineProperty(this, "_threadMap", /* @__PURE__ */ new Map());
227
+ _defineProperty(this, "_syncVersions", /* @__PURE__ */ new Map());
228
+ _defineProperty(this, "_nextSyncVersion", 0);
130
229
  _defineProperty(this, "_commentUpdate$", new rxjs.Subject());
131
230
  _defineProperty(this, "commentUpdate$", this._commentUpdate$.asObservable());
132
231
  _defineProperty(this, "_tasks", []);
@@ -187,22 +286,44 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
187
286
  }
188
287
  return subUnitMap;
189
288
  }
289
+ _syncKey(unitId, subUnitId, threadId) {
290
+ return `${unitId}\0${subUnitId}\0${threadId}`;
291
+ }
292
+ _invalidateSync(unitId, subUnitId, threadId) {
293
+ this._syncVersions.delete(this._syncKey(unitId, subUnitId, threadId));
294
+ }
190
295
  _replaceComment(unitId, subUnitId, comment) {
191
296
  const commentMap = this._ensureCommentMap(unitId, subUnitId);
192
297
  const currentComment = commentMap.get(comment.id);
193
298
  if (!currentComment) {
194
- this.addComment(unitId, subUnitId, comment);
299
+ if ("ref" in comment && typeof comment.ref === "string") this.addComment(unitId, subUnitId, {
300
+ ...comment,
301
+ ref: comment.ref
302
+ });
195
303
  return;
196
304
  }
197
- const { children, ...rest } = comment;
305
+ const { children = [], ...rest } = comment;
306
+ const seenChildIds = /* @__PURE__ */ new Set([comment.id]);
307
+ const safeChildren = children.filter((child) => {
308
+ const current = commentMap.get(child.id);
309
+ if (child.threadId !== comment.threadId || seenChildIds.has(child.id) || current && current.threadId !== comment.threadId) return false;
310
+ seenChildIds.add(child.id);
311
+ return true;
312
+ });
198
313
  const newComment = {
199
314
  ...rest,
200
315
  ref: currentComment.ref
201
316
  };
202
317
  commentMap.set(comment.id, newComment);
203
- children === null || children === void 0 || children.forEach((child) => {
318
+ if (!newComment.parentId) this._ensureThreadMap(unitId, subUnitId).set(newComment.threadId, newComment);
319
+ const remoteCommentIds = /* @__PURE__ */ new Set([comment.id, ...safeChildren.map((child) => child.id)]);
320
+ commentMap.forEach((localComment, commentId) => {
321
+ if (localComment.threadId === comment.threadId && !remoteCommentIds.has(commentId)) this._deleteComment(unitId, subUnitId, commentId);
322
+ });
323
+ safeChildren.forEach((child) => {
204
324
  commentMap.set(child.id, {
205
325
  ...child,
326
+ parentId: comment.id,
206
327
  ref: ""
207
328
  });
208
329
  });
@@ -231,11 +352,39 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
231
352
  });
232
353
  return;
233
354
  }
355
+ const versions = new Map(threadIds.map((threadId) => {
356
+ const key = this._syncKey(unitId, subUnitId, threadId);
357
+ const version = ++this._nextSyncVersion;
358
+ this._syncVersions.set(key, version);
359
+ return [threadId, {
360
+ key,
361
+ version
362
+ }];
363
+ }));
364
+ const releaseVersions = () => versions.forEach(({ key, version }) => {
365
+ if (this._syncVersions.get(key) === version) this._syncVersions.delete(key);
366
+ });
367
+ let comments;
368
+ try {
369
+ comments = await this._dataSourceService.listThreadComments(unitId, subUnitId, threadIds);
370
+ } catch (error) {
371
+ releaseVersions();
372
+ throw error;
373
+ }
374
+ if (!comments) {
375
+ releaseVersions();
376
+ return;
377
+ }
378
+ const deleteThreads = new Set(threadIds.filter((threadId) => {
379
+ const request = versions.get(threadId);
380
+ return this._syncVersions.get(request.key) === request.version;
381
+ }));
382
+ if (!deleteThreads.size) {
383
+ releaseVersions();
384
+ return;
385
+ }
234
386
  const threadMap = this._ensureThreadMap(unitId, subUnitId);
235
387
  const commentMap = this._ensureCommentMap(unitId, subUnitId);
236
- const comments = await this._dataSourceService.listThreadComments(unitId, subUnitId, threadIds);
237
- if (!comments) return;
238
- const deleteThreads = new Set(threadIds);
239
388
  comments.forEach((comment) => {
240
389
  if (!deleteThreads.has(comment.threadId)) return;
241
390
  this._replaceComment(unitId, subUnitId, comment);
@@ -244,18 +393,21 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
244
393
  deleteThreads.forEach((id) => {
245
394
  threadMap.delete(id);
246
395
  commentMap.forEach((comment, commentId) => {
247
- if (comment.threadId === id) commentMap.delete(commentId);
396
+ if (comment.threadId === id) this._deleteComment(unitId, subUnitId, commentId);
248
397
  });
249
398
  });
399
+ releaseVersions();
250
400
  }
251
401
  addComment(unitId, subUnitId, origin, shouldSync) {
252
402
  const commentMap = this._ensureCommentMap(unitId, subUnitId);
403
+ if (commentMap.has(origin.id)) return true;
253
404
  const { parentId, children = [], ...rest } = origin;
254
405
  const comment = {
255
406
  ...rest,
256
407
  parentId: parentId === origin.id ? void 0 : parentId
257
408
  };
258
409
  if (!comment.threadId) comment.threadId = comment.parentId || comment.id;
410
+ this._invalidateSync(unitId, subUnitId, comment.threadId);
259
411
  const addCommentItem = (item) => {
260
412
  commentMap.set(item.id, item);
261
413
  this._commentUpdate$.next({
@@ -270,14 +422,22 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
270
422
  const threadMap = this._ensureThreadMap(unitId, subUnitId);
271
423
  if (!comment.parentId) {
272
424
  threadMap.set(comment.threadId, comment);
273
- for (const child of children) addCommentItem(child);
425
+ for (const child of children) {
426
+ if (child.id === comment.id || child.threadId !== comment.threadId || commentMap.has(child.id)) continue;
427
+ addCommentItem({
428
+ ...child,
429
+ parentId: comment.id,
430
+ ref: ""
431
+ });
432
+ }
274
433
  }
275
434
  if (shouldSync) this.syncThreadComments(unitId, subUnitId, [comment.threadId]);
276
435
  return true;
277
436
  }
278
437
  updateComment(unitId, subUnitId, payload, silent) {
279
438
  const oldComment = this._ensureCommentMap(unitId, subUnitId).get(payload.commentId);
280
- if (!oldComment) return true;
439
+ if (!oldComment) return false;
440
+ this._invalidateSync(unitId, subUnitId, oldComment.threadId);
281
441
  oldComment.updated = true;
282
442
  oldComment.text = payload.text;
283
443
  oldComment.attachments = payload.attachments;
@@ -294,6 +454,7 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
294
454
  updateCommentRef(unitId, subUnitId, payload, silent) {
295
455
  const oldComment = this._ensureCommentMap(unitId, subUnitId).get(payload.commentId);
296
456
  if (!oldComment) return false;
457
+ this._invalidateSync(unitId, subUnitId, oldComment.threadId);
297
458
  oldComment.ref = payload.ref;
298
459
  this._commentUpdate$.next({
299
460
  unitId,
@@ -308,6 +469,7 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
308
469
  resolveComment(unitId, subUnitId, commentId, resolved) {
309
470
  const oldComment = this._ensureCommentMap(unitId, subUnitId).get(commentId);
310
471
  if (!oldComment) return false;
472
+ this._invalidateSync(unitId, subUnitId, oldComment.threadId);
311
473
  oldComment.resolved = resolved;
312
474
  this._commentUpdate$.next({
313
475
  unitId,
@@ -356,6 +518,7 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
356
518
  const commentMap = this._ensureCommentMap(unitId, subUnitId);
357
519
  const current = commentMap.get(commentId);
358
520
  if (!current) return;
521
+ this._invalidateSync(unitId, subUnitId, current.threadId);
359
522
  commentMap.delete(commentId);
360
523
  this._commentUpdate$.next({
361
524
  unitId,
@@ -369,6 +532,7 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
369
532
  });
370
533
  }
371
534
  deleteThread(unitId, subUnitId, threadId) {
535
+ this._invalidateSync(unitId, subUnitId, threadId);
372
536
  this._ensureThreadMap(unitId, subUnitId).delete(threadId);
373
537
  this._ensureCommentMap(unitId, subUnitId).forEach((comment) => {
374
538
  if (comment.threadId === threadId) this._deleteComment(unitId, subUnitId, comment.id);
@@ -383,21 +547,46 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
383
547
  }
384
548
  deleteUnit(unitId) {
385
549
  const unitMap = this._commentsMap.get(unitId);
386
- if (!unitMap) return;
387
- unitMap.forEach((subUnitMap, subUnitId) => {
550
+ unitMap === null || unitMap === void 0 || unitMap.forEach((subUnitMap, subUnitId) => {
388
551
  subUnitMap.forEach((comment) => {
389
552
  this.deleteComment(unitId, subUnitId, comment.id);
390
553
  });
391
554
  });
555
+ this._commentsMap.delete(unitId);
556
+ this._threadMap.delete(unitId);
557
+ this._tasks = this._tasks.filter((task) => task.unitId !== unitId);
558
+ const syncPrefix = `${unitId}\0`;
559
+ this._syncVersions.forEach((_version, key) => {
560
+ if (key.startsWith(syncPrefix)) this._syncVersions.delete(key);
561
+ });
392
562
  }
393
563
  getUnit(unitId) {
394
- const unitMap = this._threadMap.get(unitId);
564
+ const unitMap = this._commentsMap.get(unitId);
395
565
  if (!unitMap) return [];
396
566
  const threads = [];
397
- unitMap.forEach((subUnitSet, subUnitId) => {
398
- subUnitSet.forEach((threadComment, threadId) => {
399
- const thread = this.getThread(unitId, subUnitId, threadId);
400
- if (thread) threads.push(thread);
567
+ unitMap.forEach((commentMap, subUnitId) => {
568
+ const threadInfos = /* @__PURE__ */ new Map();
569
+ commentMap.forEach((comment) => {
570
+ let thread = threadInfos.get(comment.threadId);
571
+ if (!thread) {
572
+ thread = {
573
+ unitId,
574
+ subUnitId,
575
+ threadId: comment.threadId,
576
+ children: [],
577
+ relativeUsers: /* @__PURE__ */ new Set()
578
+ };
579
+ threadInfos.set(comment.threadId, thread);
580
+ }
581
+ if (comment.parentId) thread.children.push(comment);
582
+ else thread.root = comment;
583
+ thread.relativeUsers.add(comment.personId);
584
+ });
585
+ threadInfos.forEach((thread) => {
586
+ if (thread.root) threads.push({
587
+ ...thread,
588
+ root: thread.root
589
+ });
401
590
  });
402
591
  });
403
592
  return threads;
@@ -412,8 +601,40 @@ let ThreadCommentModel = class ThreadCommentModel extends _univerjs_core.Disposa
412
601
  });
413
602
  return all;
414
603
  }
604
+ getAnchorKind(unitId, ref) {
605
+ const anchor = deserializeThreadCommentAnchor(ref);
606
+ if (anchor) return anchor.kind;
607
+ switch (this._univerInstanceService.getUnitType(unitId)) {
608
+ case _univerjs_core.UniverInstanceType.UNIVER_SHEET: return "sheet-cell";
609
+ case _univerjs_core.UniverInstanceType.UNIVER_DOC: return "doc-text-range";
610
+ default: return null;
611
+ }
612
+ }
613
+ query(query = {}) {
614
+ const unitIds = query.unitIds ? new Set(query.unitIds) : null;
615
+ const subUnitIds = query.subUnitIds ? new Set(query.subUnitIds) : null;
616
+ const anchorKinds = query.anchorKinds ? new Set(query.anchorKinds) : null;
617
+ const authorIds = query.authorIds ? new Set(query.authorIds) : null;
618
+ return this.getAll().flatMap(({ unitId, threads }) => {
619
+ if (unitIds && !unitIds.has(unitId)) return [];
620
+ return threads.filter((thread) => {
621
+ if (subUnitIds && !subUnitIds.has(thread.subUnitId)) return false;
622
+ if (query.resolved !== void 0 && Boolean(thread.root.resolved) !== query.resolved) return false;
623
+ if (anchorKinds) {
624
+ const anchorKind = this.getAnchorKind(unitId, thread.root.ref);
625
+ if (!anchorKind || !anchorKinds.has(anchorKind)) return false;
626
+ }
627
+ if (authorIds && ![thread.root, ...thread.children].some((comment) => authorIds.has(comment.personId))) return false;
628
+ return true;
629
+ });
630
+ });
631
+ }
415
632
  };
416
- ThreadCommentModel = __decorate([__decorateParam(0, (0, _univerjs_core.Inject)(IThreadCommentDataSourceService)), __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))], ThreadCommentModel);
633
+ ThreadCommentModel = __decorate([
634
+ __decorateParam(0, (0, _univerjs_core.Inject)(IThreadCommentDataSourceService)),
635
+ __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService)),
636
+ __decorateParam(2, _univerjs_core.IUniverInstanceService)
637
+ ], ThreadCommentModel);
417
638
 
418
639
  //#endregion
419
640
  //#region src/commands/mutations/comment.mutation.ts
@@ -471,17 +692,48 @@ const DeleteCommentMutation = {
471
692
 
472
693
  //#endregion
473
694
  //#region src/commands/commands/comment.command.ts
695
+ const latestWriteVersions = /* @__PURE__ */ new WeakMap();
696
+ function startCommentWrite(comment, kind) {
697
+ const versions = latestWriteVersions.get(comment) ?? {
698
+ resolve: 0,
699
+ update: 0
700
+ };
701
+ const version = versions[kind] + 1;
702
+ versions[kind] = version;
703
+ latestWriteVersions.set(comment, versions);
704
+ return version;
705
+ }
706
+ function isLatestCommentWrite(comment, kind, version) {
707
+ var _latestWriteVersions$;
708
+ return ((_latestWriteVersions$ = latestWriteVersions.get(comment)) === null || _latestWriteVersions$ === void 0 ? void 0 : _latestWriteVersions$[kind]) === version;
709
+ }
474
710
  const AddCommentCommand = {
475
711
  id: "thread-comment.command.add-comment",
476
712
  type: _univerjs_core.CommandType.COMMAND,
477
713
  async handler(accessor, params) {
714
+ var _threadCommentModel$g, _threadCommentModel$g2;
478
715
  if (!params) return false;
479
716
  const commandService = accessor.get(_univerjs_core.ICommandService);
480
717
  const dataSourceService = accessor.get(IThreadCommentDataSourceService);
718
+ const threadCommentModel = accessor.get(ThreadCommentModel);
481
719
  const { comment: originComment } = params;
482
- const comment = await dataSourceService.addComment(originComment);
483
- const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;
484
720
  const isRoot = !originComment.parentId;
721
+ if (!isRoot && ((_threadCommentModel$g = threadCommentModel.getRootComment(params.unitId, params.subUnitId, originComment.threadId)) === null || _threadCommentModel$g === void 0 ? void 0 : _threadCommentModel$g.id) !== originComment.parentId) return false;
722
+ const comment = {
723
+ ...await dataSourceService.addComment(originComment),
724
+ unitId: params.unitId,
725
+ subUnitId: params.subUnitId,
726
+ ref: originComment.ref,
727
+ parentId: originComment.parentId,
728
+ ...!isRoot ? { threadId: originComment.threadId } : {}
729
+ };
730
+ const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;
731
+ if (!isRoot && ((_threadCommentModel$g2 = threadCommentModel.getRootComment(params.unitId, params.subUnitId, originComment.threadId)) === null || _threadCommentModel$g2 === void 0 ? void 0 : _threadCommentModel$g2.id) !== originComment.parentId) {
732
+ try {
733
+ await dataSourceService.deleteComment(params.unitId, params.subUnitId, comment.threadId, comment.id);
734
+ } catch {}
735
+ return false;
736
+ }
485
737
  const redo = {
486
738
  id: AddCommentMutation.id,
487
739
  params: {
@@ -506,16 +758,16 @@ const UpdateCommentCommand = {
506
758
  const current = threadCommentModel.getComment(unitId, subUnitId, payload.commentId);
507
759
  if (!current) return false;
508
760
  const { children, ...currentComment } = current;
761
+ const writeVersion = startCommentWrite(current, "update");
509
762
  if (!await dataSourceService.updateComment({
510
763
  ...currentComment,
511
764
  ...payload
512
- })) return false;
765
+ }) || threadCommentModel.getComment(unitId, subUnitId, payload.commentId) !== current || !isLatestCommentWrite(current, "update", writeVersion)) return false;
513
766
  const redo = {
514
767
  id: UpdateCommentMutation.id,
515
768
  params
516
769
  };
517
- commandService.executeCommand(redo.id, redo.params, { onlyLocal: !syncUpdateMutationToColla });
518
- return true;
770
+ return commandService.executeCommand(redo.id, redo.params, { onlyLocal: !syncUpdateMutationToColla });
519
771
  }
520
772
  };
521
773
  const ResolveCommentCommand = {
@@ -525,13 +777,15 @@ const ResolveCommentCommand = {
525
777
  if (!params) return false;
526
778
  const { unitId, subUnitId, resolved, commentId } = params;
527
779
  const dataSourceService = accessor.get(IThreadCommentDataSourceService);
528
- const currentComment = accessor.get(ThreadCommentModel).getComment(unitId, subUnitId, commentId);
780
+ const threadCommentModel = accessor.get(ThreadCommentModel);
781
+ const currentComment = threadCommentModel.getComment(unitId, subUnitId, commentId);
529
782
  const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;
530
783
  if (!currentComment) return false;
784
+ const writeVersion = startCommentWrite(currentComment, "resolve");
531
785
  if (!await dataSourceService.resolveComment({
532
786
  ...currentComment,
533
787
  resolved
534
- })) return false;
788
+ }) || threadCommentModel.getComment(unitId, subUnitId, commentId) !== currentComment || !isLatestCommentWrite(currentComment, "resolve", writeVersion)) return false;
535
789
  return accessor.get(_univerjs_core.ICommandService).executeCommand(ResolveCommentMutation.id, params, { onlyLocal: !syncUpdateMutationToColla });
536
790
  }
537
791
  };
@@ -569,7 +823,7 @@ const DeleteCommentTreeCommand = {
569
823
  const { unitId, subUnitId, commentId } = params;
570
824
  const commentWithChildren = threadCommentModel.getCommentWithChildren(unitId, subUnitId, commentId);
571
825
  if (!commentWithChildren) return false;
572
- if (!await dataSourceService.deleteComment(unitId, subUnitId, commentWithChildren.root.threadId, commentId)) return false;
826
+ if (!(dataSourceService.deleteThread ? await dataSourceService.deleteThread(unitId, subUnitId, commentWithChildren.root.threadId) : await dataSourceService.deleteComment(unitId, subUnitId, commentWithChildren.root.threadId, commentWithChildren.root.id))) return false;
573
827
  return await commandService.executeCommand(DeleteCommentMutation.id, {
574
828
  unitId,
575
829
  subUnitId,
@@ -600,90 +854,224 @@ function getDT(date) {
600
854
  }
601
855
 
602
856
  //#endregion
603
- //#region src/types/const/index.ts
604
- /**
605
- * Copyright 2023-present DreamNum Co., Ltd.
606
- *
607
- * Licensed under the Apache License, Version 2.0 (the "License");
608
- * you may not use this file except in compliance with the License.
609
- * You may obtain a copy of the License at
610
- *
611
- * http://www.apache.org/licenses/LICENSE-2.0
612
- *
613
- * Unless required by applicable law or agreed to in writing, software
614
- * distributed under the License is distributed on an "AS IS" BASIS,
615
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
616
- * See the License for the specific language governing permissions and
617
- * limitations under the License.
618
- */
619
- const TC_PLUGIN_NAME = "UNIVER_THREAD_COMMENT_PLUGIN";
857
+ //#region src/services/thread-comment-api.service.ts
858
+ const DOCUMENT_BODY_ARRAY_FIELDS = [
859
+ "renderedPageBreaks",
860
+ "textRuns",
861
+ "paragraphs",
862
+ "sectionBreaks",
863
+ "customBlocks",
864
+ "tables",
865
+ "columnGroups",
866
+ "blockRanges",
867
+ "customRanges",
868
+ "customDecorations"
869
+ ];
870
+ function isThreadCommentDocumentBody(value) {
871
+ if (!value || typeof value !== "object") return false;
872
+ if (typeof Reflect.get(value, "dataStream") !== "string") return false;
873
+ if (DOCUMENT_BODY_ARRAY_FIELDS.some((field) => {
874
+ const fieldValue = Reflect.get(value, field);
875
+ return fieldValue !== void 0 && !Array.isArray(fieldValue);
876
+ })) return false;
877
+ const payloads = Reflect.get(value, "payloads");
878
+ return payloads === void 0 || payloads !== null && typeof payloads === "object" && !Array.isArray(payloads) && Object.values(payloads).every((item) => typeof item === "string");
879
+ }
880
+ function normalizeThreadCommentContent(content) {
881
+ if (typeof content !== "string") {
882
+ if (!isThreadCommentDocumentBody(content)) throw new TypeError("Invalid thread comment content");
883
+ if (!content.dataStream.replace(/[\r\n]/g, "").trim()) throw new TypeError("Thread comment content cannot be empty");
884
+ return content;
885
+ }
886
+ if (!content.trim()) throw new TypeError("Thread comment content cannot be empty");
887
+ return { dataStream: content.replace(/\r\n?|\n/g, "\r").replace(/\r*$/, "\r\n") };
888
+ }
889
+ function toFacadeInfo(thread, anchorKind) {
890
+ return {
891
+ unitId: thread.unitId,
892
+ subUnitId: thread.subUnitId,
893
+ threadId: thread.threadId,
894
+ root: thread.root,
895
+ children: thread.children,
896
+ anchorKind,
897
+ anchor: deserializeThreadCommentAnchor(thread.root.ref),
898
+ relativeUserIds: Array.from(thread.relativeUsers)
899
+ };
900
+ }
901
+ let ThreadCommentFacadeService = class ThreadCommentFacadeService {
902
+ constructor(_commandService, _model, _userManagerService) {
903
+ this._commandService = _commandService;
904
+ this._model = _model;
905
+ this._userManagerService = _userManagerService;
906
+ }
907
+ createCommentAsync(options) {
908
+ const id = options.id ?? (0, _univerjs_core.generateRandomId)();
909
+ const threadId = options.threadId ?? id;
910
+ const personId = options.personId ?? this._userManagerService.getCurrentUser().userID;
911
+ return this._commandService.executeCommand(AddCommentCommand.id, {
912
+ unitId: options.unitId,
913
+ subUnitId: options.subUnitId,
914
+ comment: {
915
+ id,
916
+ threadId,
917
+ unitId: options.unitId,
918
+ subUnitId: options.subUnitId,
919
+ ref: serializeThreadCommentAnchor(options.anchor),
920
+ text: normalizeThreadCommentContent(options.content),
921
+ attachments: options.attachments ?? [],
922
+ dT: getDT(options.dateTime),
923
+ personId
924
+ }
925
+ });
926
+ }
927
+ replyCommentAsync(options) {
928
+ const root = this._model.getRootComment(options.unitId, options.subUnitId, options.threadId);
929
+ if (!root) return Promise.resolve(false);
930
+ return this._commandService.executeCommand(AddCommentCommand.id, {
931
+ unitId: options.unitId,
932
+ subUnitId: options.subUnitId,
933
+ comment: {
934
+ id: options.id ?? (0, _univerjs_core.generateRandomId)(),
935
+ threadId: options.threadId,
936
+ parentId: root.id,
937
+ unitId: options.unitId,
938
+ subUnitId: options.subUnitId,
939
+ ref: root.ref,
940
+ text: normalizeThreadCommentContent(options.content),
941
+ attachments: options.attachments ?? [],
942
+ dT: getDT(options.dateTime),
943
+ personId: options.personId ?? this._userManagerService.getCurrentUser().userID
944
+ }
945
+ });
946
+ }
947
+ updateCommentAsync(options) {
948
+ return this._commandService.executeCommand(UpdateCommentCommand.id, {
949
+ unitId: options.unitId,
950
+ subUnitId: options.subUnitId,
951
+ payload: {
952
+ commentId: options.commentId,
953
+ text: normalizeThreadCommentContent(options.content),
954
+ attachments: options.attachments,
955
+ updateT: getDT(options.dateTime)
956
+ }
957
+ });
958
+ }
959
+ deleteCommentAsync(options) {
960
+ return this._commandService.executeCommand(options.deleteThread ? DeleteCommentTreeCommand.id : DeleteCommentCommand.id, {
961
+ unitId: options.unitId,
962
+ subUnitId: options.subUnitId,
963
+ commentId: options.commentId
964
+ });
965
+ }
966
+ resolveCommentAsync(options) {
967
+ return this._commandService.executeCommand(ResolveCommentCommand.id, {
968
+ unitId: options.unitId,
969
+ subUnitId: options.subUnitId,
970
+ commentId: options.commentId,
971
+ resolved: options.resolved ?? true
972
+ });
973
+ }
974
+ getComments(query = {}) {
975
+ return this._model.query(query).map((thread) => toFacadeInfo(thread, this._model.getAnchorKind(thread.unitId, thread.root.ref)));
976
+ }
977
+ async listCommentsAsync(query = {}) {
978
+ const knownThreads = this._model.query({
979
+ unitIds: query.unitIds,
980
+ subUnitIds: query.subUnitIds
981
+ });
982
+ const groups = /* @__PURE__ */ new Map();
983
+ knownThreads.forEach((thread) => {
984
+ const key = `${thread.unitId}\0${thread.subUnitId}`;
985
+ const group = groups.get(key) ?? {
986
+ unitId: thread.unitId,
987
+ subUnitId: thread.subUnitId,
988
+ threadIds: []
989
+ };
990
+ group.threadIds.push(thread.threadId);
991
+ groups.set(key, group);
992
+ });
993
+ await Promise.all(Array.from(groups.values()).map((group) => this._model.syncThreadComments(group.unitId, group.subUnitId, group.threadIds)));
994
+ return this._model.query(query).map((thread) => toFacadeInfo(thread, this._model.getAnchorKind(thread.unitId, thread.root.ref)));
995
+ }
996
+ };
997
+ ThreadCommentFacadeService = __decorate([
998
+ __decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_core.ICommandService)),
999
+ __decorateParam(1, (0, _univerjs_core.Inject)(ThreadCommentModel)),
1000
+ __decorateParam(2, (0, _univerjs_core.Inject)(_univerjs_core.UserManagerService))
1001
+ ], ThreadCommentFacadeService);
620
1002
 
621
1003
  //#endregion
622
- //#region src/controllers/tc-resource.controller.ts
623
- const SHEET_UNIVER_THREAD_COMMENT_PLUGIN = `SHEET_${TC_PLUGIN_NAME}`;
624
- let ThreadCommentResourceController = class ThreadCommentResourceController extends _univerjs_core.Disposable {
625
- constructor(_resourceManagerService, _threadCommentModel, _threadCommentDataSourceService) {
626
- super();
627
- this._resourceManagerService = _resourceManagerService;
628
- this._threadCommentModel = _threadCommentModel;
629
- this._threadCommentDataSourceService = _threadCommentDataSourceService;
630
- this._initSnapshot();
631
- }
632
- _initSnapshot() {
633
- const toJson = (unitID) => {
634
- const map = this._threadCommentModel.getUnit(unitID);
1004
+ //#region src/common/tc-resource.ts
1005
+ function isStringArray(value) {
1006
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
1007
+ }
1008
+ function isSnapshotComment(value, allowChildren = true) {
1009
+ if (!value || typeof value !== "object") return false;
1010
+ const comment = value;
1011
+ return typeof comment.id === "string" && comment.id.length > 0 && typeof comment.threadId === "string" && comment.threadId.length > 0 && typeof comment.ref === "string" && (comment.text === void 0 || isThreadCommentDocumentBody(comment.text)) && (comment.attachments === void 0 || isStringArray(comment.attachments)) && (comment.mentions === void 0 || isStringArray(comment.mentions)) && (!allowChildren || comment.children === void 0 || Array.isArray(comment.children) && comment.children.every((child) => isSnapshotComment(child, false)));
1012
+ }
1013
+ function createThreadCommentResourceHook(threadCommentModel, threadCommentDataSourceService, pluginName, businesses) {
1014
+ return {
1015
+ pluginName,
1016
+ businesses,
1017
+ toJson: (unitID) => {
1018
+ const map = threadCommentModel.getUnit(unitID);
635
1019
  const resultMap = {};
636
- if (map) {
637
- map.forEach((info) => {
638
- const subUnitComments = resultMap[info.subUnitId] ?? [];
639
- subUnitComments.push({
640
- ...info.root,
641
- children: info.children
642
- });
643
- resultMap[info.subUnitId] = subUnitComments;
1020
+ map.forEach((info) => {
1021
+ const subUnitComments = resultMap[info.subUnitId] ?? [];
1022
+ subUnitComments.push({
1023
+ ...info.root,
1024
+ children: info.children
644
1025
  });
645
- return JSON.stringify(this._threadCommentDataSourceService.saveToSnapshot(resultMap, unitID));
646
- }
647
- return "";
648
- };
649
- const parseJson = (json) => {
1026
+ resultMap[info.subUnitId] = subUnitComments;
1027
+ });
1028
+ return JSON.stringify(threadCommentDataSourceService.saveToSnapshot(resultMap, unitID));
1029
+ },
1030
+ parseJson: (json) => {
650
1031
  if (!json) return {};
651
1032
  try {
652
- return JSON.parse(json);
653
- } catch (err) {
1033
+ const value = JSON.parse(json);
1034
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1035
+ return Object.fromEntries(Object.entries(value).flatMap(([subUnitId, comments]) => Array.isArray(comments) ? [[subUnitId, comments.filter((comment) => isSnapshotComment(comment))]] : []));
1036
+ } catch {
654
1037
  return {};
655
1038
  }
656
- };
657
- this.disposeWithMe(this._resourceManagerService.registerPluginResource({
658
- pluginName: SHEET_UNIVER_THREAD_COMMENT_PLUGIN,
659
- businesses: [_univerjs_core.UniverInstanceType.UNIVER_SHEET, _univerjs_core.UniverInstanceType.UNIVER_DOC],
660
- toJson: (unitID) => toJson(unitID),
661
- parseJson: (json) => parseJson(json),
662
- onUnLoad: (unitID) => {
663
- this._threadCommentModel.deleteUnit(unitID);
664
- },
665
- onLoad: async (unitID, value) => {
666
- Object.keys(value).forEach((subunitId) => {
667
- const commentList = value[subunitId];
668
- commentList.forEach((comment) => {
669
- this._threadCommentModel.addComment(unitID, subunitId, comment);
1039
+ },
1040
+ onUnLoad: (unitID) => {
1041
+ threadCommentModel.deleteUnit(unitID);
1042
+ },
1043
+ onLoad: (unitID, value) => {
1044
+ Object.keys(value).forEach((subunitId) => {
1045
+ const commentList = value[subunitId];
1046
+ commentList.forEach((comment) => {
1047
+ var _comment$children;
1048
+ const seenIds = /* @__PURE__ */ new Set([comment.id]);
1049
+ const children = (_comment$children = comment.children) === null || _comment$children === void 0 ? void 0 : _comment$children.filter((child) => {
1050
+ if (child.threadId !== comment.threadId || seenIds.has(child.id)) return false;
1051
+ seenIds.add(child.id);
1052
+ return true;
1053
+ }).map((child) => ({
1054
+ ...child,
1055
+ unitId: unitID,
1056
+ subUnitId: subunitId
1057
+ }));
1058
+ threadCommentModel.addComment(unitID, subunitId, {
1059
+ ...comment,
1060
+ unitId: unitID,
1061
+ subUnitId: subunitId,
1062
+ children
670
1063
  });
671
- this._threadCommentModel.syncThreadComments(unitID, subunitId, commentList.map((i) => i.threadId));
672
1064
  });
673
- }
674
- }));
675
- }
676
- };
677
- ThreadCommentResourceController = __decorate([
678
- __decorateParam(0, _univerjs_core.IResourceManagerService),
679
- __decorateParam(1, (0, _univerjs_core.Inject)(ThreadCommentModel)),
680
- __decorateParam(2, IThreadCommentDataSourceService)
681
- ], ThreadCommentResourceController);
1065
+ threadCommentModel.syncThreadComments(unitID, subunitId, commentList.map((i) => i.threadId));
1066
+ });
1067
+ }
1068
+ };
1069
+ }
682
1070
 
683
1071
  //#endregion
684
1072
  //#region package.json
685
1073
  var name = "@univerjs/thread-comment";
686
- var version = "1.0.0-insiders.20260809-70eefdd";
1074
+ var version = "1.0.0-rc.0";
687
1075
 
688
1076
  //#endregion
689
1077
  //#region src/config/config.ts
@@ -691,6 +1079,25 @@ const THREAD_COMMENT_PLUGIN_CONFIG_KEY = "thread-comment.config";
691
1079
  const configSymbol = Symbol(THREAD_COMMENT_PLUGIN_CONFIG_KEY);
692
1080
  const defaultPluginConfig = {};
693
1081
 
1082
+ //#endregion
1083
+ //#region src/types/const/index.ts
1084
+ /**
1085
+ * Copyright 2023-present DreamNum Co., Ltd.
1086
+ *
1087
+ * Licensed under the Apache License, Version 2.0 (the "License");
1088
+ * you may not use this file except in compliance with the License.
1089
+ * You may obtain a copy of the License at
1090
+ *
1091
+ * http://www.apache.org/licenses/LICENSE-2.0
1092
+ *
1093
+ * Unless required by applicable law or agreed to in writing, software
1094
+ * distributed under the License is distributed on an "AS IS" BASIS,
1095
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1096
+ * See the License for the specific language governing permissions and
1097
+ * limitations under the License.
1098
+ */
1099
+ const TC_PLUGIN_NAME = "UNIVER_THREAD_COMMENT_PLUGIN";
1100
+
694
1101
  //#endregion
695
1102
  //#region src/plugin.ts
696
1103
  let UniverThreadCommentPlugin = class UniverThreadCommentPlugin extends _univerjs_core.Plugin {
@@ -708,7 +1115,7 @@ let UniverThreadCommentPlugin = class UniverThreadCommentPlugin extends _univerj
708
1115
  (0, _univerjs_core.mergeOverrideWithDependencies)([
709
1116
  [IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }],
710
1117
  [ThreadCommentModel],
711
- [ThreadCommentResourceController]
1118
+ [ThreadCommentFacadeService]
712
1119
  ], (_this$_config = this._config) === null || _this$_config === void 0 ? void 0 : _this$_config.overrides).forEach((d) => {
713
1120
  this._injector.add(d);
714
1121
  });
@@ -726,7 +1133,6 @@ let UniverThreadCommentPlugin = class UniverThreadCommentPlugin extends _univerj
726
1133
  ].forEach((command) => {
727
1134
  this._commandService.registerCommand(command);
728
1135
  });
729
- this._injector.get(ThreadCommentResourceController);
730
1136
  }
731
1137
  };
732
1138
  _defineProperty(UniverThreadCommentPlugin, "pluginName", TC_PLUGIN_NAME);
@@ -748,19 +1154,19 @@ exports.DeleteCommentTreeCommand = DeleteCommentTreeCommand;
748
1154
  exports.IThreadCommentDataSourceService = IThreadCommentDataSourceService;
749
1155
  exports.ResolveCommentCommand = ResolveCommentCommand;
750
1156
  exports.ResolveCommentMutation = ResolveCommentMutation;
751
- exports.SHEET_UNIVER_THREAD_COMMENT_PLUGIN = SHEET_UNIVER_THREAD_COMMENT_PLUGIN;
752
1157
  exports.TC_PLUGIN_NAME = TC_PLUGIN_NAME;
1158
+ exports.ThreadCommentAnchorKind = ThreadCommentAnchorKind;
753
1159
  exports.ThreadCommentDataSourceService = ThreadCommentDataSourceService;
754
- Object.defineProperty(exports, 'ThreadCommentModel', {
1160
+ Object.defineProperty(exports, 'ThreadCommentFacadeService', {
755
1161
  enumerable: true,
756
1162
  get: function () {
757
- return ThreadCommentModel;
1163
+ return ThreadCommentFacadeService;
758
1164
  }
759
1165
  });
760
- Object.defineProperty(exports, 'ThreadCommentResourceController', {
1166
+ Object.defineProperty(exports, 'ThreadCommentModel', {
761
1167
  enumerable: true,
762
1168
  get: function () {
763
- return ThreadCommentResourceController;
1169
+ return ThreadCommentModel;
764
1170
  }
765
1171
  });
766
1172
  Object.defineProperty(exports, 'UniverThreadCommentPlugin', {
@@ -772,4 +1178,10 @@ Object.defineProperty(exports, 'UniverThreadCommentPlugin', {
772
1178
  exports.UpdateCommentCommand = UpdateCommentCommand;
773
1179
  exports.UpdateCommentMutation = UpdateCommentMutation;
774
1180
  exports.UpdateCommentRefMutation = UpdateCommentRefMutation;
775
- exports.getDT = getDT;
1181
+ exports.createThreadCommentResourceHook = createThreadCommentResourceHook;
1182
+ exports.deserializeThreadCommentAnchor = deserializeThreadCommentAnchor;
1183
+ exports.getDT = getDT;
1184
+ exports.isThreadCommentAnchor = isThreadCommentAnchor;
1185
+ exports.isThreadCommentDocumentBody = isThreadCommentDocumentBody;
1186
+ exports.normalizeThreadCommentContent = normalizeThreadCommentContent;
1187
+ exports.serializeThreadCommentAnchor = serializeThreadCommentAnchor;