Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix: stabilize thread comment editing flow (#6994)

wpxp123456b3b7bbaae999
diff --git a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
index fe9b727ad4..5db4e75391 100644
--- a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
+++ b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
@@ -54,7 +54,19 @@ describe('AddDocCommentComment', () => {
it('should add comment and attach decoration via sequenceExecute', async () => {
const dataSource = new ThreadCommentDataSourceService();
- vi.spyOn(dataSource, 'addComment').mockImplementation(async (c) => ({ ...c, id: 'comment-1', threadId: 'thread-1' }));
+ const addComment = vi.fn(async (c) => ({ ...c, id: 'comment-1', threadId: '' }));
+ dataSource.dataSource = {
+ addComment,
+ updateComment: vi.fn(async () => true),
+ resolveComment: vi.fn(async () => true),
+ deleteComment: vi.fn(async () => true),
+ listComments: vi.fn(async () => []),
+ saveCommentToSnapshot: vi.fn((comment) => ({
+ id: comment.id,
+ threadId: comment.threadId,
+ ref: comment.ref,
+ })),
+ };
injector.add([IThreadCommentDataSourceService, { useValue: dataSource }]);
injector.add([DocSelectionManagerService]);
@@ -100,7 +112,7 @@ describe('AddDocCommentComment', () => {
});
expect(ok).toBe(true);
- expect(dataSource.addComment).toHaveBeenCalled();
+ expect(addComment).toHaveBeenCalled();
expect(executed.map((command) => command.id)).toEqual([
AddCommentMutation.id,
RichTextEditingMutation.id,
@@ -108,9 +120,14 @@ describe('AddDocCommentComment', () => {
]);
expect(executed[0].params).toEqual(expect.objectContaining({
unitId: 'doc-1',
- comment: expect.objectContaining({ id: 'comment-1', threadId: 'thread-1' }),
+ comment: expect.objectContaining({ id: 'comment-1', threadId: 'comment-1' }),
}));
expect(executed[1].params).toEqual(expect.objectContaining({ unitId: 'doc-1' }));
+ expect(executed[2].params).toEqual(expect.objectContaining({
+ unitId: 'doc-1',
+ subUnitId: 'default_doc',
+ commentId: 'comment-1',
+ }));
});
it('should return false when missing params', async () => {
diff --git a/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts
index faad5b405d..2e89d092a0 100644
--- a/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts
@@ -125,4 +125,60 @@ describe('DocThreadCommentSelectionController', () => {
controller.dispose();
});
+
+ it('should keep the temporary adding comment active when selection changes before the comment is saved', () => {
+ const activeCommentId$ = new Subject<any>();
+ const threadCommentPanelService = {
+ activeCommentId: { unitId: 'doc-1', subUnitId: DEFAULT_DOC_SUBUNIT_ID, commentId: '' },
+ activeCommentId$,
+ };
+
+ const doc = {
+ getBody: () => ({ customDecorations: [] }),
+ };
+
+ const univerInstanceService = { getUnit: vi.fn(() => doc) };
+
+ let onExecutedHandler: any;
+ const executeCommand = vi.fn();
+ const commandService = {
+ onCommandExecuted: vi.fn((fn) => {
+ onExecutedHandler = fn;
+ return { dispose: vi.fn() };
+ }),
+ executeCommand,
+ };
+
+ const docThreadCommentService = {
+ addingComment: {
+ unitId: 'doc-1',
+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,
+ id: '',
+ },
+ endAdd: vi.fn(),
+ };
+ const renderManagerService = { getRenderById: vi.fn(() => null) };
+ const threadCommentModel = { getComment: vi.fn(() => null) };
+
+ const controller = new DocThreadCommentSelectionController(
+ threadCommentPanelService as any,
+ univerInstanceService as any,
+ commandService as any,
+ docThreadCommentService as any,
+ renderManagerService as any,
+ threadCommentModel as any
+ );
+
+ onExecutedHandler({
+ id: SetTextSelectionsOperation.id,
+ params: {
+ unitId: 'doc-1',
+ ranges: [{ startOffset: 10, endOffset: 10, collapsed: true }],
+ },
+ });
+
+ expect(executeCommand).not.toHaveBeenCalledWith(SetActiveCommentOperation.id);
+
+ controller.dispose();
+ });
});
diff --git a/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts
index 8e258b4694..ebf59c2df1 100644
--- a/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts
@@ -85,6 +85,17 @@ export class DocThreadCommentSelectionController extends Disposable {
return;
}
+ const addingComment = this._docThreadCommentService.addingComment;
+ const activeComment = this._threadCommentPanelService.activeCommentId;
+ if (
+ addingComment &&
+ activeComment?.unitId === addingComment.unitId &&
+ activeComment?.subUnitId === DEFAULT_DOC_SUBUNIT_ID &&
+ activeComment?.commentId === addingComment.id
+ ) {
+ return;
+ }
+
this._commandService.executeCommand(SetActiveCommentOperation.id);
}
})
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
index ab80f9f7bf..e3a70df535 100644
--- a/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
@@ -79,6 +79,8 @@ describe('DocThreadCommentRenderController', () => {
commandService as any
);
+ expect(threadCommentModel.addComment).not.toHaveBeenCalled();
+
const next = (v: any) => v;
const outActive = handler(
{ id: 'c2' },
@@ -139,6 +141,7 @@ describe('DocThreadCommentRenderController', () => {
});
onCommandExecuted({ id: RichTextEditingMutation.id, params: { unitId: 'doc-1' } });
+ expect(threadCommentModel.addComment).not.toHaveBeenCalled();
expect(threadCommentModel.syncThreadComments).toHaveBeenCalledWith('doc-1', DEFAULT_DOC_SUBUNIT_ID, ['c3']);
controller.dispose();
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
index 0caa45804e..0925fbf2d2 100644
--- a/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts
@@ -94,12 +94,6 @@ export class DocThreadCommentRenderController extends Disposable implements IRen
const unitId = this._context.unit.getUnitId();
const subUnitId = DEFAULT_DOC_SUBUNIT_ID;
const threadIds = this._context.unit.getBody()?.customDecorations?.filter((i) => i.type === CustomDecorationType.COMMENT).map((i) => i.id) ?? [];
- threadIds.forEach((id) => {
- const comment = this._threadCommentModel.getComment(unitId, subUnitId, id);
- if (!comment) {
- this._threadCommentModel.addComment(unitId, subUnitId, { id, threadId: id, ref: '', dT: '', personId: '', text: { dataStream: '' }, unitId, subUnitId });
- }
- });
threadIds.length && this._threadCommentModel.syncThreadComments(this._context.unit.getUnitId(), DEFAULT_DOC_SUBUNIT_ID, threadIds);
let prevThreadIds: string[] = threadIds.sort();
@@ -114,9 +108,7 @@ export class DocThreadCommentRenderController extends Disposable implements IRen
const currentThreadIdsSorted = currentThreadIds.sort();
if (JSON.stringify(prevThreadIds) !== JSON.stringify(currentThreadIdsSorted)) {
const preIds = new Set(prevThreadIds);
- const currentIds = new Set(currentThreadIdsSorted);
const addIds = new Set<string>();
- const deleteIds = new Set<string>();
currentThreadIds.forEach((id) => {
if (!preIds.has(id)) {
@@ -124,24 +116,7 @@ export class DocThreadCommentRenderController extends Disposable implements IRen
}
});
- prevThreadIds.forEach((id) => {
- if (!currentIds.has(id)) {
- deleteIds.add(id);
- }
- });
-
prevThreadIds = currentThreadIdsSorted;
- addIds.forEach((id) => {
- const comment = this._threadCommentModel.getComment(unitId, subUnitId, id);
- if (!comment) {
- this._threadCommentModel.addComment(unitId, subUnitId, { id, threadId: id, ref: '', dT: '', personId: '', text: { dataStream: '' }, unitId, subUnitId });
- }
- });
-
- // deleteIds.forEach((id) => {
- // this._threadCommentModel.deleteThread(unitId, subUnitId, id);
- // });
-
this._threadCommentModel.syncThreadComments(unitId, subUnitId, [...addIds]);
}
}
diff --git a/packages/docs-ui/src/services/editor/editor-manager.service.ts b/packages/docs-ui/src/services/editor/editor-manager.service.ts
index 581d198f73..4949d225f3 100644
--- a/packages/docs-ui/src/services/editor/editor-manager.service.ts
+++ b/packages/docs-ui/src/services/editor/editor-manager.service.ts
@@ -248,7 +248,14 @@ export class EditorService extends Disposable implements IEditorService, IDispos
// Delete scroll bar
if (!config.scrollBar) {
- (render.mainComponent?.getScene() as Scene)?.getViewports()?.[0].getScrollBar()?.dispose();
+ const viewport = (render.mainComponent?.getScene() as Scene)?.getViewports()?.[0];
+ viewport?.getScrollBar()?.dispose();
+ viewport?.updateScrollVal({
+ scrollX: 0,
+ scrollY: 0,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ });
}
}
return toDisposable(() => {
diff --git a/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts b/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts
index f21c8f0125..7041f8025b 100644
--- a/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts
+++ b/packages/docs-ui/src/views/rich-text-editor/hooks/use-resize.ts
@@ -20,7 +20,7 @@ import { debounce } from '@univerjs/core';
import { DocSkeletonManagerService } from '@univerjs/docs';
import { ScrollBar } from '@univerjs/engine-render';
import { useCallback, useEffect, useMemo } from 'react';
-import { VIEWPORT_KEY } from '../../../basics/docs-view-key';
+import { DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../../basics/docs-view-key';
interface IUseResizeReturn {
resize: () => void;
@@ -42,6 +42,13 @@ export const useResize = (editor?: Editor, isSingle = true, autoScrollbar?: bool
});
mainComponent?.resize(width, height);
+ mainComponent?.translate(0, 0);
+ editor.render.components.get(DOCS_VIEW_KEY.BACKGROUND)?.translate(0, 0);
+
+ const selectionRanges = editor.getSelectionRanges();
+ if (selectionRanges.length > 0) {
+ editor.setSelectionRanges(selectionRanges, false);
+ }
}
}, [editor, isSingle]);
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsx b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsx
new file mode 100644
index 0000000000..07a2e5a567
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsx
@@ -0,0 +1,382 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Root } from 'react-dom/client';
+import { UniverInstanceType } from '@univerjs/core';
+import * as React from 'react';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ThreadCommentEditor } from '../index';
+
+const { commandService, localeService, editorService, coreTokens, docsUiTokens, editorHandle } = vi.hoisted(() => {
+ const commandService = {
+ executeCommand: vi.fn(),
+ };
+ const localeService = {
+ t: vi.fn((key: string) => key),
+ };
+ const editorService = {
+ focus: vi.fn(),
+ };
+ const coreTokens = {
+ ICommandService: Symbol('ICommandService'),
+ LocaleService: Symbol('LocaleService'),
+ };
+ const docsUiTokens = {
+ IEditorService: Symbol('IEditorService'),
+ };
+ const editorHandle = {
+ getDocumentData: vi.fn(() => ({
+ body: {
+ dataStream: 'reply body',
+ },
+ })),
+ replaceText: vi.fn(),
+ setSelectionRanges: vi.fn(),
+ blur: vi.fn(),
+ focus: vi.fn(),
+ getEditorId: vi.fn(() => 'editor-id'),
+ setDocumentData: vi.fn(),
+ selectionChange$: {
+ subscribe: vi.fn(() => ({
+ unsubscribe: vi.fn(),
+ })),
+ },
+ };
+
+ return {
+ commandService,
+ localeService,
+ editorService,
+ coreTokens,
+ docsUiTokens,
+ editorHandle,
+ };
+});
+
+vi.mock('@univerjs/core', () => ({
+ BuildTextUtils: {
+ transform: {
+ getPlainText: (value: string) => value,
+ },
+ },
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY: 'doc-editor-id',
+ ICommandService: coreTokens.ICommandService,
+ LocaleService: coreTokens.LocaleService,
+ Tools: {
+ deepClone: <T,>(value: T) => value,
+ },
+ UniverInstanceType: {
+ UNIVER_DOC: 'UNIVER_DOC',
+ },
+}));
+
+vi.mock('@univerjs/docs-ui', () => ({
+ BreakLineCommand: {
+ id: 'break-line',
+ },
+ IEditorService: docsUiTokens.IEditorService,
+ RichTextEditor: ({ autoFocus, editorRef, onFocusChange, placeholder }: any) => {
+ React.useEffect(() => {
+ editorRef.current = editorHandle;
+ if (autoFocus) {
+ onFocusChange?.(true);
+ }
+
+ return () => {
+ editorRef.current = null;
+ };
+ }, [autoFocus, editorRef, onFocusChange]);
+
+ return <div aria-label={placeholder} data-testid="thread-comment-editor-input" />;
+ },
+}));
+
+vi.mock('../../../commands/operations/comment.operations', () => ({
+ SetActiveCommentOperation: {
+ id: 'set-active-comment',
+ },
+}));
+
+vi.mock('@univerjs/design', () => ({
+ Button: ({ children, disabled, onClick, type }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button disabled={disabled} onClick={onClick} type={type}>
+ {children}
+ </button>
+ ),
+ clsx: (...args: unknown[]) => args.filter(Boolean).join(' '),
+}));
+
+vi.mock('@univerjs/ui', () => ({
+ KeyCode: {
+ ENTER: 13,
+ },
+ useDependency: (token: symbol) => {
+ if (token === coreTokens.ICommandService) {
+ return commandService;
+ }
+
+ if (token === coreTokens.LocaleService) {
+ return localeService;
+ }
+
+ if (token === docsUiTokens.IEditorService) {
+ return editorService;
+ }
+
+ throw new Error(`Unexpected dependency token: ${String(token)}`);
+ },
+}));
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('ThreadCommentEditor', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ commandService.executeCommand.mockReset();
+ localeService.t.mockImplementation((key: string) => key);
+ editorService.focus.mockReset();
+ editorHandle.getDocumentData.mockImplementation(() => ({
+ body: {
+ dataStream: 'reply body',
+ },
+ }));
+ editorHandle.replaceText.mockReset();
+ editorHandle.setSelectionRanges.mockReset();
+ editorHandle.blur.mockReset();
+ editorHandle.focus.mockReset();
+ editorHandle.getEditorId.mockImplementation(() => 'editor-id');
+ editorHandle.setDocumentData.mockReset();
+ editorHandle.selectionChange$.subscribe.mockImplementation(() => ({
+ unsubscribe: vi.fn(),
+ }));
+ });
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ vi.clearAllMocks();
+ });
+
+ it('uses non-submit buttons so replying does not submit an outer form', () => {
+ const onSave = vi.fn();
+ const onSubmit = vi.fn((event: React.FormEvent<HTMLFormElement>) => event.preventDefault());
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <form onSubmit={onSubmit}>
+ <ThreadCommentEditor
+ autoFocus
+ editorId="thread-comment-editor"
+ onSave={onSave}
+ subUnitId="subUnit"
+ type={UniverInstanceType.UNIVER_DOC}
+ unitId="unit"
+ />
+ </form>
+ );
+ });
+
+ const buttons = Array.from(container.querySelectorAll('button'));
+ const cancelButton = buttons.find((button) => button.textContent === 'thread-comment-ui.editor.cancel');
+ const replyButton = buttons.find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ expect(cancelButton?.getAttribute('type')).toBe('button');
+ expect(replyButton?.getAttribute('type')).toBe('button');
+
+ act(() => {
+ replyButton?.click();
+ });
+
+ expect(onSave).toHaveBeenCalledTimes(1);
+ expect(onSubmit).not.toHaveBeenCalled();
+ });
+
+ it('blurs the editor before save callbacks can unmount it', () => {
+ const onSave = vi.fn(() => {
+ editorHandle.blur.mockImplementation(() => {
+ throw new Error('blur after save');
+ });
+ });
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ThreadCommentEditor
+ autoFocus
+ editorId="thread-comment-editor"
+ onSave={onSave}
+ subUnitId="subUnit"
+ type={UniverInstanceType.UNIVER_DOC}
+ unitId="unit"
+ />
+ );
+ });
+
+ const replyButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ expect(() => {
+ act(() => {
+ replyButton?.click();
+ });
+ }).not.toThrow();
+ expect(editorHandle.blur).toHaveBeenCalledBefore(onSave);
+ });
+
+ it('blurs the editor before clearing content so active popups are disposed first', () => {
+ const onSave = vi.fn();
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ThreadCommentEditor
+ autoFocus
+ editorId="thread-comment-editor"
+ onSave={onSave}
+ subUnitId="subUnit"
+ type={UniverInstanceType.UNIVER_DOC}
+ unitId="unit"
+ />
+ );
+ });
+
+ const replyButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ act(() => {
+ replyButton?.click();
+ });
+
+ expect(editorHandle.blur).toHaveBeenCalledBefore(editorHandle.replaceText);
+ });
+
+ it('shows action buttons after reply inserts mention text without a focus change event', () => {
+ const ref = React.createRef<{ reply: (text: { dataStream: string }) => void }>();
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ThreadCommentEditor
+ ref={ref as any}
+ autoFocus={false}
+ editorId="thread-comment-editor"
+ subUnitId="subUnit"
+ type={UniverInstanceType.UNIVER_SHEET}
+ unitId="unit"
+ />
+ );
+ });
+
+ expect(container.querySelectorAll('button').length).toBe(0);
+
+ act(() => {
+ ref.current?.reply({ dataStream: '@Owner asdas\r\n' });
+ });
+
+ const replyButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ expect(replyButton).toBeTruthy();
+ expect(replyButton?.disabled).toBe(false);
+ });
+
+ it('shows action buttons after the editor is clicked without a focus change event', () => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ThreadCommentEditor
+ autoFocus={false}
+ editorId="thread-comment-editor"
+ subUnitId="subUnit"
+ type={UniverInstanceType.UNIVER_SHEET}
+ unitId="unit"
+ />
+ );
+ });
+
+ expect(container.querySelectorAll('button').length).toBe(0);
+
+ act(() => {
+ container.querySelector('[data-testid="thread-comment-editor-input"]')?.dispatchEvent(
+ new MouseEvent('mousedown', { bubbles: true })
+ );
+ });
+
+ const replyButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ expect(replyButton).toBeTruthy();
+ });
+
+ it('resets submit state after saving and clearing the editor', () => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <ThreadCommentEditor
+ autoFocus
+ editorId="thread-comment-editor"
+ subUnitId="subUnit"
+ type={UniverInstanceType.UNIVER_SHEET}
+ unitId="unit"
+ />
+ );
+ });
+
+ const firstReplyButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ act(() => {
+ firstReplyButton?.click();
+ });
+
+ act(() => {
+ container.querySelector('[data-testid="thread-comment-editor-input"]')?.dispatchEvent(
+ new MouseEvent('mousedown', { bubbles: true })
+ );
+ });
+
+ const secondReplyButton = Array.from(container.querySelectorAll('button'))
+ .find((button) => button.textContent === 'thread-comment-ui.editor.reply');
+
+ expect(secondReplyButton?.disabled).toBe(true);
+ });
+});
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts
new file mode 100644
index 0000000000..30bf20af6f
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts
@@ -0,0 +1,35 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { focusThreadCommentEditor } from '../util';
+
+describe('focusThreadCommentEditor', () => {
+ it('focuses the editor instance even when the editor service already tracks the id', () => {
+ const editorId = 'comment-editor-id';
+ const editorService = {
+ focus: vi.fn(),
+ };
+ const editor = {
+ focus: vi.fn(),
+ };
+
+ focusThreadCommentEditor(editorService, editorId, editor);
+
+ expect(editorService.focus).toHaveBeenCalledWith(editorId);
+ expect(editor.focus).toHaveBeenCalled();
+ });
+});
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx
index 51c42828cc..f41dd41e14 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/index.tsx
@@ -23,6 +23,7 @@ import { BreakLineCommand, IEditorService, RichTextEditor } from '@univerjs/docs
import { KeyCode, useDependency } from '@univerjs/ui';
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';
+import { focusThreadCommentEditor } from './util';
export interface IThreadCommentEditorProps {
id?: string;
@@ -85,65 +86,92 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThr
if (!editor.current) {
return;
}
- editorService.focus(editor.current!.getEditorId() ?? '');
+ focusThreadCommentEditor(editorService, editorId, editor.current);
const documentData = getSnapshot(text);
editor.current?.setDocumentData(documentData, [{
startOffset: documentData.body!.dataStream.length - 2,
endOffset: documentData.body!.dataStream.length - 2,
collapsed: true,
}]);
+ setCanSubmit(BuildTextUtils.transform.getPlainText(documentData.body!.dataStream));
+ setEditing(true);
},
}));
const handleSave = () => {
- if (editor.current) {
- const newText = Tools.deepClone(editor.current.getDocumentData().body);
+ const currentEditor = editor.current;
+ if (currentEditor) {
+ const newText = Tools.deepClone(currentEditor.getDocumentData().body);
+ currentEditor.blur();
+ currentEditor.replaceText('', false);
+ currentEditor.setSelectionRanges([], false);
+ setCanSubmit('');
setEditing(false);
onSave?.({
...comment,
text: newText!,
});
- editor.current.replaceText('');
- setTimeout(() => {
- editor.current?.setSelectionRanges([]);
- editor.current?.blur();
- }, 10);
}
};
+ const handleEditorMouseDown = () => {
+ focusThreadCommentEditor(editorService, editorId, editor.current);
+ setEditing(true);
+ };
+
+ useEffect(() => {
+ if (!autoFocus) {
+ return;
+ }
+
+ const timer = setTimeout(() => {
+ focusThreadCommentEditor(editorService, editorId, editor.current);
+ });
+
+ return () => clearTimeout(timer);
+ }, [autoFocus, editorId, editorService]);
+
return (
<div onClick={(e) => e.preventDefault()}>
- <RichTextEditor
- className="univer-w-full"
- editorRef={editor}
- editorId={editorId}
- autoFocus={autoFocus}
- keyboardEventConfig={keyboardEventConfig}
- placeholder={localeService.t('thread-comment-ui.editor.placeholder')}
- initialValue={comment?.text && getSnapshot(comment.text)}
- onFocusChange={(isFocus) => isFocus && setEditing(isFocus)}
- isSingle={false}
- maxHeight={64}
- onClickOutside={() => {
- setTimeout(() => {
- editorService.focus(rootEditorId);
- }, 30);
- }}
- />
+ <div onMouseDown={handleEditorMouseDown}>
+ <RichTextEditor
+ className="univer-w-full"
+ editorRef={editor}
+ editorId={editorId}
+ autoFocus={autoFocus}
+ keyboardEventConfig={keyboardEventConfig}
+ placeholder={localeService.t('thread-comment-ui.editor.placeholder')}
+ initialValue={comment?.text && getSnapshot(comment.text)}
+ onFocusChange={(isFocus) => isFocus && setEditing(isFocus)}
+ isSingle={false}
+ maxHeight={64}
+ onClickOutside={() => {
+ setTimeout(() => {
+ editorService.focus(rootEditorId);
+ }, 30);
+ }}
+ />
+ </div>
{editing
? (
<div className="univer-mt-3 univer-flex univer-flex-row univer-justify-end univer-gap-2">
<Button
+ type="button"
onClick={() => {
+ const currentEditor = editor.current;
+ currentEditor?.blur();
+ currentEditor?.replaceText('', false);
+ currentEditor?.setSelectionRanges([], false);
+ setCanSubmit('');
onCancel?.();
setEditing(false);
- editor.current?.replaceText('', true);
commandService.executeCommand(SetActiveCommentOperation.id);
}}
>
{localeService.t('thread-comment-ui.editor.cancel')}
</Button>
<Button
+ type="button"
variant="primary"
disabled={!canSubmit}
onClick={handleSave}
diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
index c0b41431e8..1e736422fb 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/util.ts
@@ -18,6 +18,14 @@ import type { IDocumentBody } from '@univerjs/core';
import type { IThreadCommentMention } from '@univerjs/thread-comment';
import { CustomRangeType, getBodySlice } from '@univerjs/core';
+interface IThreadCommentEditorFocusService {
+ focus: (editorId: string) => void;
+}
+
+interface IFocusableThreadCommentEditor {
+ focus: () => void;
+}
+
export type TextNode = {
type: 'text';
content: string;
@@ -118,3 +126,12 @@ export const transformTextNodes2Document = (nodes: TextNode[]): IDocumentBody =>
customRanges,
};
};
+
+export function focusThreadCommentEditor(
+ editorService: IThreadCommentEditorFocusService,
+ editorId: string,
+ editor?: IFocusableThreadCommentEditor | null
+) {
+ editorService.focus(editorId);
+ editor?.focus();
+}
diff --git a/packages/thread-comment-ui/src/views/thread-comment-panel/__tests__/util.spec.ts b/packages/thread-comment-ui/src/views/thread-comment-panel/__tests__/util.spec.ts
new file mode 100644
index 0000000000..bee90c4705
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-panel/__tests__/util.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IThreadComment } from '@univerjs/thread-comment';
+import { describe, expect, it } from 'vitest';
+import { getThreadCommentPanelItemKey } from '../util';
+
+describe('getThreadCommentPanelItemKey', () => {
+ it('returns unique keys for comments with empty ids', () => {
+ const comments = [
+ {
+ id: '',
+ unitId: 'unit-1',
+ subUnitId: 'sub-unit-1',
+ threadId: '',
+ ref: 'A1',
+ dT: '',
+ },
+ {
+ id: '',
+ unitId: 'unit-1',
+ subUnitId: 'sub-unit-1',
+ threadId: '',
+ ref: 'A1',
+ dT: '',
+ },
+ ] as IThreadComment[];
+
+ const keys = comments.map((comment, index) => getThreadCommentPanelItemKey(comment, index, 'unsolved'));
+
+ expect(new Set(keys).size).toBe(keys.length);
+ expect(keys).not.toContain('');
+ });
+
+ it('keeps persisted comment ids as keys', () => {
+ const comment = {
+ id: 'comment-1',
+ unitId: 'unit-1',
+ subUnitId: 'sub-unit-1',
+ } as IThreadComment;
+
+ expect(getThreadCommentPanelItemKey(comment, 0, 'unsolved')).toBe('comment-1');
+ });
+});
diff --git a/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx
index df6a8ece2b..a991b122b3 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx
+++ b/packages/thread-comment-ui/src/views/thread-comment-panel/index.tsx
@@ -18,6 +18,7 @@ import type { Nullable } from '@univerjs/core';
import type { IThreadComment } from '@univerjs/thread-comment';
import type { Observable } from 'rxjs';
import type { IThreadCommentTreeProps } from '../thread-comment-tree';
+import type { ThreadCommentPanelSection } from './util';
import { ICommandService, LocaleService, UniverInstanceType, UserManagerService } from '@univerjs/core';
import { Button, Select } from '@univerjs/design';
import { IncreaseIcon } from '@univerjs/icons';
@@ -27,6 +28,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';
import { ThreadCommentPanelService } from '../../services/thread-comment-panel.service';
import { ThreadCommentTree, ThreadCommentTreeLocation } from '../thread-comment-tree';
+import { getThreadCommentPanelItemKey } from './util';
export interface IThreadCommentPanelProps {
unitId: string;
@@ -158,11 +160,11 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
document.getElementById(id)?.scrollIntoView({ block: 'center' });
}, [activeCommentId]);
- const renderComment = (comment: IThreadComment) => (
+ const renderComment = (section: ThreadCommentPanelSection) => (comment: IThreadComment, index: number) => (
<ThreadCommentTree
location={location}
getSubUnitName={getSubUnitName}
- key={comment.id}
+ key={getThreadCommentPanelItemKey(comment, index, section)}
id={comment.id}
unitId={comment.unitId}
subUnitId={comment.subUnitId}
@@ -272,13 +274,13 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {
)
: (
<div className="univer-mt-3 univer-flex univer-flex-col univer-gap-3">
- {unSolvedComments.map(renderComment)}
+ {unSolvedComments.map(renderComment('unsolved'))}
{solvedComments.length > 0 && (
<div className="univer-text-xs">
{localeService.t('thread-comment-ui.panel.solved')}
</div>
)}
- {solvedComments.map(renderComment)}
+ {solvedComments.map(renderComment('solved'))}
</div>
)}
</div>
diff --git a/packages/thread-comment-ui/src/views/thread-comment-panel/util.ts b/packages/thread-comment-ui/src/views/thread-comment-panel/util.ts
new file mode 100644
index 0000000000..20c5c05804
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-panel/util.ts
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IThreadComment } from '@univerjs/thread-comment';
+
+export type ThreadCommentPanelSection = 'unsolved' | 'solved';
+
+export function getThreadCommentPanelItemKey(
+ comment: IThreadComment,
+ index: number,
+ section: ThreadCommentPanelSection
+) {
+ if (comment.id) {
+ return comment.id;
+ }
+
+ return [
+ 'thread-comment-panel-temp',
+ section,
+ comment.unitId,
+ comment.subUnitId,
+ comment.threadId,
+ comment.ref,
+ comment.dT,
+ index,
+ ].join('-');
+}
diff --git a/packages/thread-comment-ui/src/views/thread-comment-tree/__tests__/util.spec.ts b/packages/thread-comment-ui/src/views/thread-comment-tree/__tests__/util.spec.ts
new file mode 100644
index 0000000000..81b664c6e7
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-tree/__tests__/util.spec.ts
@@ -0,0 +1,52 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DOCS_COMMENT_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { ThreadCommentTreeLocation } from '..';
+import { getThreadCommentEditorId } from '../util';
+
+describe('getThreadCommentEditorId', () => {
+ it('returns different editor ids for different comments in the same location', () => {
+ const first = getThreadCommentEditorId({
+ location: ThreadCommentTreeLocation.PANEL,
+ unitId: 'unit-1',
+ subUnitId: 'sub-unit-1',
+ commentId: 'comment-1',
+ fallbackId: 'fallback',
+ });
+ const second = getThreadCommentEditorId({
+ location: ThreadCommentTreeLocation.PANEL,
+ unitId: 'unit-1',
+ subUnitId: 'sub-unit-1',
+ commentId: 'comment-2',
+ fallbackId: 'fallback',
+ });
+
+ expect(first).not.toBe(second);
+ expect(first.startsWith(DOCS_COMMENT_EDITOR_UNIT_ID_KEY)).toBe(true);
+ });
+
+ it('uses the fallback id when the comment id is empty', () => {
+ expect(getThreadCommentEditorId({
+ location: ThreadCommentTreeLocation.PANEL,
+ unitId: 'unit-1',
+ subUnitId: 'sub-unit-1',
+ commentId: '',
+ fallbackId: 'fallback-1',
+ })).toBe(`${DOCS_COMMENT_EDITOR_UNIT_ID_KEY}_PANEL_unit-1_sub-unit-1_fallback-1`);
+ });
+});
diff --git a/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx b/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx
index c295d9b98f..bb89f89516 100644
--- a/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx
+++ b/packages/thread-comment-ui/src/views/thread-comment-tree/index.tsx
@@ -18,7 +18,7 @@ import type { IUser, UniverInstanceType } from '@univerjs/core';
import type { IAddCommentCommandParams, IThreadComment, IUpdateCommentCommandParams } from '@univerjs/thread-comment';
import type { IUniverUIConfig } from '@univerjs/ui';
import type { IThreadCommentEditorInstance } from '../thread-comment-editor';
-import { DOCS_COMMENT_EDITOR_UNIT_ID_KEY, generateRandomId, ICommandService, LocaleService, UserManagerService } from '@univerjs/core';
+import { generateRandomId, ICommandService, LocaleService, UserManagerService } from '@univerjs/core';
import { borderClassName, clsx, Dropdown, scrollbarClassName, Tooltip } from '@univerjs/design';
import { DeleteIcon, MoreHorizontalIcon, ReplyToCommentIcon, ResolvedIcon, SolveIcon } from '@univerjs/icons';
import {
@@ -36,6 +36,7 @@ import { debounceTime } from 'rxjs';
import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';
import { ThreadCommentEditor } from '../thread-comment-editor';
import { transformDocument2TextNodes, transformTextNodes2Document } from '../thread-comment-editor/util';
+import { getThreadCommentEditorId } from './util';
export enum ThreadCommentTreeLocation {
CELL = 'CELL',
@@ -303,6 +304,7 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
const resolved = comments?.root.resolved;
const currentUser = useObservable(userManagerService.currentUser$);
const editorRef = useRef<IThreadCommentEditorInstance>(null);
+ const fallbackEditorId = useMemo(() => generateRandomId(6), []);
const renderComments: IThreadComment[] = [
...comments ?
[comments.root] :
@@ -369,7 +371,13 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {
const subUnitName = getSubUnitName(comments?.root.subUnitId ?? subUnitId);
const editorVisible = showEdit && !editingId && !resolved;
const title = `${refStr || comments?.root.ref || ''}${subUnitName ? ' · ' : ''}${subUnitName}`;
- const threadCommentEditorId = `${DOCS_COMMENT_EDITOR_UNIT_ID_KEY}_${location}`;
+ const threadCommentEditorId = getThreadCommentEditorId({
+ location,
+ unitId,
+ subUnitId,
+ commentId: id,
+ fallbackId: fallbackEditorId,
+ });
return (
<div
diff --git a/packages/thread-comment-ui/src/views/thread-comment-tree/util.ts b/packages/thread-comment-ui/src/views/thread-comment-tree/util.ts
new file mode 100644
index 0000000000..13b99734f5
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-tree/util.ts
@@ -0,0 +1,32 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ThreadCommentTreeLocation } from '../thread-comment-tree';
+import { DOCS_COMMENT_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
+
+interface IGetThreadCommentEditorIdParams {
+ location: ThreadCommentTreeLocation;
+ unitId: string;
+ subUnitId: string;
+ commentId?: string;
+ fallbackId: string;
+}
+
+export function getThreadCommentEditorId(params: IGetThreadCommentEditorIdParams) {
+ const { location, unitId, subUnitId, commentId, fallbackId } = params;
+
+ return `${DOCS_COMMENT_EDITOR_UNIT_ID_KEY}_${location}_${unitId}_${subUnitId}_${commentId || fallbackId}`;
+}
diff --git a/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts b/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts
index 33b30c555e..787d5cdcf1 100644
--- a/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts
+++ b/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts
@@ -197,6 +197,38 @@ describe('ThreadCommentModel', () => {
expect(threadCommentModel.getUnit('unit-1').map((thread) => thread.threadId)).toEqual(['keep-root']);
});
+ it('adds synced thread comments even when no placeholder exists locally', async () => {
+ lifecycleService.stage = LifecycleStages.Rendered;
+
+ const root = createComment({ id: 'synced-root', threadId: 'synced-thread', ref: '' });
+ const reply = createComment({
+ id: 'synced-reply',
+ threadId: 'synced-thread',
+ parentId: 'synced-root',
+ ref: '',
+ });
+
+ dataSourceService.dataSource = {
+ addComment: vi.fn(),
+ updateComment: vi.fn(),
+ resolveComment: vi.fn(),
+ deleteComment: vi.fn(),
+ listComments: vi.fn(async () => [{ ...root, children: [reply] }]),
+ saveCommentToSnapshot: vi.fn(),
+ };
+
+ await threadCommentModel.syncThreadComments('unit-1', 'sheet-1', ['synced-thread']);
+
+ expect(threadCommentModel.getThread('unit-1', 'sheet-1', 'synced-thread')).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ threadId: 'synced-thread',
+ root,
+ children: [reply],
+ relativeUsers: new Set(['user-1']),
+ });
+ });
+
it('updates refs, exposes thread lookups, and deletes all comments in a unit', () => {
lifecycleService.stage = LifecycleStages.Rendered;
diff --git a/packages/thread-comment/src/models/thread-comment.model.ts b/packages/thread-comment/src/models/thread-comment.model.ts
index 2f3f844f5d..e28c49a5ab 100644
--- a/packages/thread-comment/src/models/thread-comment.model.ts
+++ b/packages/thread-comment/src/models/thread-comment.model.ts
@@ -153,39 +153,42 @@ export class ThreadCommentModel extends Disposable {
const commentMap = this._ensureCommentMap(unitId, subUnitId);
const currentComment = commentMap.get(comment.id);
- if (currentComment) {
- const { children, ...rest } = comment;
- const newComment = {
- ...rest,
- ref: currentComment.ref,
- };
- commentMap.set(comment.id, newComment);
-
- children?.forEach((child) => {
- commentMap.set(child.id, {
- ...child,
- ref: '',
- });
+ if (!currentComment) {
+ this.addComment(unitId, subUnitId, comment as IThreadComment);
+ return;
+ }
+
+ const { children, ...rest } = comment;
+ const newComment = {
+ ...rest,
+ ref: currentComment.ref,
+ };
+ commentMap.set(comment.id, newComment);
+
+ children?.forEach((child) => {
+ commentMap.set(child.id, {
+ ...child,
+ ref: '',
});
+ });
+
+ this._commentUpdate$.next({
+ unitId,
+ subUnitId,
+ type: 'syncUpdate',
+ payload: newComment,
+ });
+ if (Boolean(comment.resolved) !== Boolean(currentComment.resolved)) {
this._commentUpdate$.next({
unitId,
subUnitId,
- type: 'syncUpdate',
- payload: newComment,
+ type: 'resolve',
+ payload: {
+ commentId: comment.id,
+ resolved: Boolean(comment.resolved),
+ },
});
-
- if (Boolean(comment.resolved) !== Boolean(currentComment.resolved)) {
- this._commentUpdate$.next({
- unitId,
- subUnitId,
- type: 'resolve',
- payload: {
- commentId: comment.id,
- resolved: Boolean(comment.resolved),
- },
- });
- }
}
}
@@ -203,6 +206,10 @@ export class ThreadCommentModel extends Disposable {
}
const deleteThreads = new Set<string>(threadIds);
comments.forEach((comment) => {
+ if (!deleteThreads.has(comment.threadId)) {
+ return;
+ }
+
this._replaceComment(unitId, subUnitId, comment);
deleteThreads.delete(comment.threadId);
});
diff --git a/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts b/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts
index 8c1ab9cbe8..3defb81de0 100644
--- a/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts
+++ b/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts
@@ -71,6 +71,16 @@ describe('ThreadCommentDataSourceService', () => {
});
});
+ it('normalizes an empty threadId to the comment id when no external data source is configured', async () => {
+ const service = new ThreadCommentDataSourceService();
+ const comment = createComment({ id: 'root-1', threadId: '' });
+
+ await expect(service.addComment(comment)).resolves.toEqual({
+ ...comment,
+ threadId: 'root-1',
+ });
+ });
+
it('delegates CRUD, query and snapshot behavior to the configured data source', async () => {
const service = new ThreadCommentDataSourceService();
const comment = createComment({ id: 'root-1' });
@@ -127,4 +137,28 @@ describe('ThreadCommentDataSourceService', () => {
expect(dataSource.listComments).toHaveBeenNthCalledWith(2, 'unit-1', 'sheet-1', ['root-1']);
expect(dataSource.saveCommentToSnapshot).toHaveBeenCalledWith(comment, 0, [comment]);
});
+
+ it('normalizes an empty threadId returned from an external data source to the returned comment id', async () => {
+ const service = new ThreadCommentDataSourceService();
+ const comment = createComment({ id: 'client-id', threadId: '' });
+ const dataSource = {
+ addComment: vi.fn(async (input: IThreadComment) => ({ ...input, id: 'server-id', threadId: '' })),
+ updateComment: vi.fn(async () => true),
+ resolveComment: vi.fn(async () => true),
+ deleteComment: vi.fn(async () => true),
+ listComments: vi.fn(async () => []),
+ saveCommentToSnapshot: vi.fn((input: IThreadComment) => ({
+ id: input.id,
+ threadId: input.threadId,
+ ref: input.ref,
+ })),
+ };
+ service.dataSource = dataSource;
+
+ await expect(service.addComment(comment)).resolves.toEqual({
+ ...comment,
+ id: 'server-id',
+ threadId: 'server-id',
+ });
+ });
});
diff --git a/packages/thread-comment/src/services/tc-datasource.service.ts b/packages/thread-comment/src/services/tc-datasource.service.ts
index 49f2a3162b..ae9f97d1fa 100644
--- a/packages/thread-comment/src/services/tc-datasource.service.ts
+++ b/packages/thread-comment/src/services/tc-datasource.service.ts
@@ -105,10 +105,11 @@ export class ThreadCommentDataSourceService extends Disposable implements IThrea
}
async addComment(comment: IThreadComment) {
- if (this._dataSource) {
- return this._dataSource.addComment(comment);
- }
- return { ...comment, threadId: comment.threadId ?? comment.id };
+ const savedComment = this._dataSource
+ ? await this._dataSource.addComment(comment)
+ : comment;
+
+ return { ...savedComment, threadId: savedComment.threadId || savedComment.id };
}
async updateComment(comment: IThreadComment) {