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