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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(thread-comment): support server intercept for comment & docs-comment (#2619)
zhangw02dff8212bca
diff --git a/examples/package.json b/examples/package.jsonindex 9fab8f5181..1789ada5da 100644--- a/examples/package.json+++ b/examples/package.json@@ -19,6 +19,7 @@"@univerjs/docs": "workspace:*","@univerjs/docs-drawing": "workspace:*","@univerjs/docs-drawing-ui": "workspace:*",+ "@univerjs/docs-thread-comment-ui": "workspace:*","@univerjs/docs-ui": "workspace:*","@univerjs/drawing": "workspace:*","@univerjs/drawing-ui": "workspace:*",diff --git a/examples/src/docs/main.ts b/examples/src/docs/main.tsindex 9bd7211c3b..c21215f20b 100644--- a/examples/src/docs/main.ts+++ b/examples/src/docs/main.ts@@ -15,8 +15,7 @@*//* eslint-disable node/prefer-global/process */--import { LocaleType, Univer, UniverInstanceType } from '@univerjs/core';+import { LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService } from '@univerjs/core';import { defaultTheme } from '@univerjs/design';import { UniverDocsPlugin } from '@univerjs/docs';import { UniverDocsUIPlugin } from '@univerjs/docs-ui';@@ -25,7 +24,7 @@ import { UniverUIPlugin } from '@univerjs/ui';import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { UniverDebuggerPlugin } from '@univerjs/debugger';import { UniverDocsDrawingUIPlugin } from '@univerjs/docs-drawing-ui';-+import { UniverDocsCommentUIPlugin } from '@univerjs/docs-thread-comment-ui';import { DEFAULT_DOCUMENT_DATA_CN } from '../data';import { enUS, ruRU, zhCN } from '../locales';@@ -47,6 +46,7 @@ const univer = new Univer({[LocaleType.EN_US]: enUS,[LocaleType.RU_RU]: ruRU,},+ logLevel: LogLevel.VERBOSE,});// core plugins@@ -69,6 +69,7 @@ univer.registerPlugin(UniverDocsUIPlugin, {});univer.registerPlugin(UniverDocsDrawingUIPlugin);+univer.registerPlugin(UniverDocsCommentUIPlugin);univer.createUnit(UniverInstanceType.UNIVER_DOC, DEFAULT_DOCUMENT_DATA_CN);@@ -81,3 +82,14 @@ declare global {}window.univer = univer;+const injector = univer.__getInjector();+const userManagerService = injector.get(UserManagerService);++const mockUser = {+ userID: 'Owner_qxVnhPbQ',+ name: 'Owner',+ avatar: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAInSURBVHgBtZU9TxtBEIbfWRzFSIdkikhBSqRQkJqkCKTCFkqVInSUSaT0wC8w/gXxD4gU2nRJkXQWhAZowDUUWKIwEgWWbEEB3mVmx3dn4DA2nB/ppNuPeWd29mMIPXDr+RxwtgRHeW6+guNPRxogqnL7Dwz9psJ27S4NShaeZTH3kwXy6I81dlRKcmRui88swdq9AcSFL7Buz1Vmlns64MiLsCjzwnIYHLH57tbfFbs7KRaXyEU8FVZofqccOfA5l7Q8LPIkGrwnb2RPNEXWFVMUF3L+kDCk0btDDAMzOm5YfAHDwp4tG74wnzAsiOYMnJ3GoDybA7IT98/jm5+JNnfiIzAS6LlqHQBN/i6b2t/cV1Hh6BfwYlHnHP4AXi5q/8kmMMpOs8+BixZw/Fd6xUEHEbnkgclvQP2fGp7uShRKnQ3G32rkjV1th8JhIGG7tR/JyjGteSOZELwGMmNqIIigRCLRh2OZIE6BjItdd7pCW6Uhm1zzkUtungSxwEUzNpQ+GQumtH1ej1MqgmNT6vwmhCq5yuwq56EYTbgeQUz3yvrpV1b4ok3nYJ+eYhgYmjRUqErx2EDq0Fr8FhG++iqVGqxlUJI/70Ar0UgJaWHj6hYVHJrfKssAHot1JfqwE9WVWzXZVd5z2Ws/4PnmtEjkXeKJDvxUecLbWOXH/DP6QQ4J72NS0adedp1aseBfXP8odlZFfPvBF7SN/8hky1TYuPOAXAEipMx15u5ToAAAAABJRU5ErkJggg==',+ anonymous: false,+ canBindAnonymous: false,+};+userManagerService.setCurrentUser(mockUser);diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex 1ece1430cb..08c09a9908 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import { LocaleType, LogLevel, Univer, UniverInstanceType, UserManagerService } from '@univerjs/core';import { defaultTheme } from '@univerjs/design';import { UniverDocsPlugin } from '@univerjs/docs';@@ -26,6 +27,7 @@ import { UniverSheetsConditionalFormattingUIPlugin } from '@univerjs/sheets-condimport { UniverSheetsThreadCommentPlugin } from '@univerjs/sheets-thread-comment';import { UniverDebuggerPlugin } from '@univerjs/debugger';import { UniverSheetsHyperLinkUIPlugin } from '@univerjs/sheets-hyper-link-ui';+import type { IThreadCommentMentionDataSource } from '@univerjs/thread-comment-ui';import { IThreadCommentMentionDataService, UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import type { IUniverRPCMainThreadConfig } from '@univerjs/rpc';@@ -115,6 +117,7 @@ const mockUser = {};class CustomMentionDataService implements IThreadCommentMentionDataService {+ dataSource: Nullable<IThreadCommentMentionDataSource>;trigger: string = '@';async getMentions() {diff --git a/packages/core/src/docs/data-model/document-data-model.ts b/packages/core/src/docs/data-model/document-data-model.tsindex 6e127e6930..4ee8fcc6c1 100644--- a/packages/core/src/docs/data-model/document-data-model.ts+++ b/packages/core/src/docs/data-model/document-data-model.ts@@ -233,6 +233,14 @@ export class DocumentDataModel extends DocumentDataModelSimple {return this.snapshot.drawingsOrder;}+ getCustomRanges() {+ return this.snapshot.body?.customRanges;+ }++ getCustomDecorations() {+ return this.snapshot.body?.customDecorations;+ }+getRev(): number {return this.snapshot.rev ?? 1;}diff --git a/packages/core/src/docs/data-model/text-x/action-iterator.ts b/packages/core/src/docs/data-model/text-x/action-iterator.tsindex 935d4a423c..6f78df7480 100644--- a/packages/core/src/docs/data-model/text-x/action-iterator.ts+++ b/packages/core/src/docs/data-model/text-x/action-iterator.ts@@ -66,6 +66,7 @@ export class ActionIterator {});} else {// handle condition: (nextAction.t === TextXActionType.INSERT || nextAction.t === TextXActionType.RETAIN && nextAction.body)+return Tools.deepClone({...nextAction,len: length,diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts b/packages/core/src/docs/data-model/text-x/apply-utils/common.tsindex faefea6713..289b6c14d6 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/common.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/common.ts@@ -19,6 +19,7 @@ import { horizontalLineSegmentsSubtraction, sortRulesFactory, Tools } from '../.import { isSameStyleTextRun } from '../../../../shared/compare';import type {ICustomBlock,+ ICustomDecoration,ICustomRange,IDocumentBody,IParagraph,@@ -364,29 +365,40 @@ export function insertCustomRanges(textLength: number,currentIndex: number) {- const { customRanges } = body;-- if (customRanges == null) {- return;+ if (!body.customRanges) {+ body.customRanges = [];}+ const { customRanges } = body;+ const customRangeMap: Record<string, ICustomRange> = {};for (let i = 0, len = customRanges.length; i < len; i++) {const customRange = customRanges[i];+ customRangeMap[customRange.rangeId] = customRange;const { startIndex, endIndex } = customRange;- if (startIndex > currentIndex) {+ if (startIndex >= currentIndex) {customRange.startIndex += textLength;customRange.endIndex += textLength;- } else if (endIndex >= currentIndex - 1) {+ } else if (endIndex > currentIndex - 1) {customRange.endIndex += textLength;}}- const insertCustomRanges = insertBody.customRanges;- if (insertCustomRanges) {- for (let i = 0, len = insertCustomRanges.length; i < len; i++) {- const customRange = insertCustomRanges[i];- customRange.startIndex += currentIndex;- customRange.endIndex += currentIndex;+ const insertCustomRanges: ICustomRange[] = [];+ if (insertBody.customRanges) {+ for (let i = 0, len = insertBody.customRanges.length; i < len; i++) {+ const customRange = insertBody.customRanges[i];+ const oldCustomRange = customRangeMap[customRange.rangeId];+ if (oldCustomRange) {+ if (insertBody.dataStream === DataStreamTreeTokenType.CUSTOM_RANGE_END) {+ oldCustomRange.endIndex = customRange.endIndex + currentIndex;+ } else if (insertBody.dataStream === DataStreamTreeTokenType.CUSTOM_RANGE_START) {+ oldCustomRange.startIndex = customRange.startIndex + currentIndex;+ }+ } else {+ insertCustomRanges.push(customRange);+ customRange.startIndex += currentIndex;+ customRange.endIndex += currentIndex;+ }}customRanges.push(...insertCustomRanges);@@ -394,6 +406,86 @@ export function insertCustomRanges(}}+interface IIndexRange {+ startIndex: number;+ endIndex: number;+}++function mergeRanges<T extends IIndexRange>(lineSegments: T[]): T[] {+ lineSegments.sort((a, b) => a.startIndex - b.startIndex); // 按照起始值排序++ const mergedSegments: T[] = [];+ let currentSegment = lineSegments[0];++ for (let i = 1; i < lineSegments.length; i++) {+ if (currentSegment.endIndex + 1 >= lineSegments[i].startIndex) { // 判断是否连续+ currentSegment.endIndex = Math.max(currentSegment.endIndex, lineSegments[i].endIndex);+ } else {+ mergedSegments.push(currentSegment);+ currentSegment = lineSegments[i];+ }+ }++ mergedSegments.push(currentSegment);++ return mergedSegments;+}++export function mergeDecorations(customDecorations: ICustomDecoration[]) {+ const customDecorationMap: Record<string, ICustomDecoration[]> = {};+ for (let i = 0, len = customDecorations.length; i < len; i++) {+ const customDecoration = customDecorations[i];+ const currentDecorations = customDecorationMap[customDecoration.id];+ customDecorationMap[customDecoration.id] = [...currentDecorations ?? [], customDecoration];+ }++ Object.keys(customDecorationMap).forEach((id) => {+ const decorations = customDecorationMap[id];+ const newRanges = mergeRanges(decorations);+ customDecorationMap[id] = newRanges;+ });++ return Object.values(customDecorationMap).flat();+}++export function insertCustomDecorations(+ body: IDocumentBody,+ insertBody: IDocumentBody,+ textLength: number,+ currentIndex: number+) {+ if (!body.customDecorations) {+ body.customDecorations = [];+ }+ const { customDecorations } = body;+ if (textLength > 0) {+ for (let i = 0, len = customDecorations.length; i < len; i++) {+ const customDecoration = customDecorations[i];+ const { startIndex, endIndex } = customDecoration;+ if (startIndex >= currentIndex) {+ customDecoration.startIndex += textLength;+ customDecoration.endIndex += textLength;+ } else if (endIndex > currentIndex - 1) {+ customDecoration.endIndex += textLength;+ }+ }+ }++ if (insertBody.customDecorations) {+ const insertCustomDecorations: ICustomDecoration[] = [];+ for (let i = 0, len = insertBody.customDecorations.length; i < len; i++) {+ const customDecoration = insertBody.customDecorations[i];+ insertCustomDecorations.push(customDecoration);+ customDecoration.startIndex += currentIndex;+ customDecoration.endIndex += currentIndex;+ }++ customDecorations.push(...insertCustomDecorations);+ body.customDecorations = mergeDecorations(customDecorations);+ body.customDecorations.sort(sortRulesFactory('startIndex'));+ }+}+// eslint-disable-next-line max-lines-per-functionexport function deleteTextRuns(body: IDocumentBody, textLength: number, currentIndex: number) {const { textRuns } = body;@@ -662,7 +754,8 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, currfor (let i = 0, len = customRanges.length; i < len; i++) {const customRange = customRanges[i];const { startIndex: st, endIndex: ed } = customRange;- if (startIndex <= st && endIndex >= ed) {+ // delete custom-range start means delete custom-range+ if (startIndex <= st && endIndex >= st) {removeCustomRanges.push({...customRange,startIndex: st - currentIndex,@@ -684,3 +777,36 @@ export function deleteCustomRanges(body: IDocumentBody, textLength: number, curr}return removeCustomRanges;}++export function deleteCustomDecorations(body: IDocumentBody, textLength: number, currentIndex: number, needOffset = true) {+ const { customDecorations } = body;++ const startIndex = currentIndex;+ const endIndex = currentIndex + textLength - 1;+ const removeCustomDecorations: ICustomDecoration[] = [];+ if (customDecorations) {+ const newCustomDecorations = [];+ for (let i = 0, len = customDecorations.length; i < len; i++) {+ const customDecoration = customDecorations[i];+ const { startIndex: st, endIndex: ed } = customDecoration;+ // delete decoration+ if (st >= startIndex && ed <= endIndex) {+ removeCustomDecorations.push(customDecoration);+ continue;+ // substr decoration+ } else if (Math.max(startIndex, st) <= Math.min(endIndex, ed)) {+ const segments = horizontalLineSegmentsSubtraction(st, ed, startIndex, endIndex);+ customDecoration.startIndex = segments[0];+ customDecoration.endIndex = segments[1];+ } else if (endIndex < st) {+ if (needOffset) {+ customDecoration.startIndex -= textLength;+ customDecoration.endIndex -= textLength;+ }+ }+ newCustomDecorations.push(customDecoration);+ }+ body.customDecorations = newCustomDecorations;+ }+ return removeCustomDecorations;+}diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.tsindex 3589a8f8cc..69b5873de3 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/delete-apply.ts@@ -18,6 +18,7 @@ import { deleteContent } from '../../../../shared';import type { IDocumentBody } from '../../../../types/interfaces';import {deleteCustomBlocks,+ deleteCustomDecorations,deleteCustomRanges,deleteParagraphs,deleteSectionBreaks,@@ -44,6 +45,8 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,const removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);+ const removeCustomDecorations = deleteCustomDecorations(body, textLength, currentIndex);+let removeDataStream = '';if (dataStream) {body.dataStream = deleteContent(dataStream, startIndex, endIndex);@@ -59,6 +62,7 @@ export function updateAttributeByDelete(body: IDocumentBody, textLength: number,customBlocks: removeCustomBlocks,tables: removeTables,customRanges: removeCustomRanges,+ customDecorations: removeCustomDecorations,};}diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.tsindex 83cf669ed0..a2bc6cbb22 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/insert-apply.ts@@ -18,6 +18,7 @@ import { insertTextToContent } from '../../../../shared';import type { IDocumentBody } from '../../../../types/interfaces';import {insertCustomBlocks,+ insertCustomDecorations,insertCustomRanges,insertParagraphs,insertSectionBreaks,@@ -44,4 +45,6 @@ export function updateAttributeByInsert(insertTables(body, insertBody, textLength, currentIndex);insertCustomRanges(body, insertBody, textLength, currentIndex);++ insertCustomDecorations(body, insertBody, textLength, currentIndex);}diff --git a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.tsindex f60d1b873c..7bbc4bcfbd 100644--- a/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts+++ b/packages/core/src/docs/data-model/text-x/apply-utils/update-apply.ts@@ -18,6 +18,7 @@ import type { Nullable } from '../../../../shared';import { Tools, UpdateDocsAttributeType } from '../../../../shared';import type {ICustomBlock,+ ICustomDecoration,ICustomRange,IDocumentBody,IParagraph,@@ -28,12 +29,15 @@ import type {import { PresetListType } from '../../preset-list-type';import {deleteCustomBlocks,+ deleteCustomDecorations,deleteCustomRanges,deleteParagraphs,deleteSectionBreaks,deleteTables,deleteTextRuns,insertCustomBlocks,+ insertCustomDecorations,+ insertCustomRanges,insertParagraphs,insertTables,insertTextRuns,@@ -53,6 +57,7 @@ export function updateAttribute(const removeCustomBlocks = updateCustomBlocks(body, updateBody, textLength, currentIndex, coverType);const removeTables = updateTables(body, updateBody, textLength, currentIndex, coverType);const removeCustomRanges = updateCustomRanges(body, updateBody, textLength, currentIndex, coverType);+ const removeCustomDecorations = updateCustomDecorations(body, updateBody, textLength, currentIndex, coverType);return {dataStream: '',@@ -62,6 +67,7 @@ export function updateAttribute(customBlocks: removeCustomBlocks,tables: removeTables,customRanges: removeCustomRanges,+ customDecorations: removeCustomDecorations,};}@@ -431,6 +437,7 @@ function updateTables(return removeTables;}+// retainfunction updateCustomRanges(body: IDocumentBody,updateBody: IDocumentBody,@@ -438,43 +445,44 @@ function updateCustomRanges(currentIndex: number,coverType: UpdateDocsAttributeType) {+ if (!body.customRanges) {+ body.customRanges = [];+ }const { customRanges } = body;- const { tables: updateDataCustomRanges } = updateBody;+ const { customRanges: updateDataCustomRanges } = updateBody;if (customRanges == null || updateDataCustomRanges == null) {return;}- const removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);- if (coverType !== UpdateDocsAttributeType.REPLACE) {- const newUpdateCustomRanges: ICustomRange[] = [];- for (const updateCustomRange of updateDataCustomRanges) {- const { startIndex: updateStartIndex, endIndex: updateEndIndex } = updateCustomRange;- let splitUpdateCustomRanges: ICustomRange[] = [];- for (const removeCustomRange of removeCustomRanges) {- const { startIndex: removeStartIndex, endIndex: removeEndIndex } = removeCustomRange;- if (removeStartIndex >= updateStartIndex && removeEndIndex <= updateEndIndex) {- if (coverType === UpdateDocsAttributeType.COVER) {- splitUpdateCustomRanges.push({- ...removeCustomRange,- ...updateCustomRange,- });- } else {- splitUpdateCustomRanges.push({- ...updateCustomRange,- ...removeCustomRange,- });- }- break;- }- }- newUpdateCustomRanges.push(...splitUpdateCustomRanges);- splitUpdateCustomRanges = [];- }- updateBody.customRanges = newUpdateCustomRanges;+ let removeCustomRanges: ICustomRange[] = [];+ if (coverType === UpdateDocsAttributeType.REPLACE) {+ removeCustomRanges = deleteCustomRanges(body, textLength, currentIndex);}- insertTables(body, updateBody, textLength, currentIndex);+ // retain+ insertCustomRanges(body, updateBody, 0, currentIndex);return removeCustomRanges;}++// retain+function updateCustomDecorations(+ body: IDocumentBody,+ updateBody: IDocumentBody,+ textLength: number,+ currentIndex: number,+ coverType: UpdateDocsAttributeType+) {+ if (!body.customDecorations) {+ body.customDecorations = [];+ }++ let removeCustomDecorations: ICustomDecoration[] = [];+ if (coverType === UpdateDocsAttributeType.REPLACE) {+ removeCustomDecorations = deleteCustomDecorations(body, textLength, currentIndex, false);+ }++ insertCustomDecorations(body, updateBody, 0, currentIndex);+ return removeCustomDecorations;+}diff --git a/packages/core/src/docs/data-model/text-x/text-x.ts b/packages/core/src/docs/data-model/text-x/text-x.tsindex ab7ca44e96..357417fafb 100644--- a/packages/core/src/docs/data-model/text-x/text-x.ts+++ b/packages/core/src/docs/data-model/text-x/text-x.ts@@ -161,11 +161,11 @@ export class TextX {}if (action.t === TextXActionType.RETAIN && action.body != null) {- const { textRuns } = getBodySlice(doc, index, index + action.len, true);-+ const { textRuns, customDecorations } = getBodySlice(doc, index, index + action.len, true);action.oldBody = {dataStream: '',textRuns,+ customDecorations,};}@@ -175,7 +175,6 @@ export class TextX {index += action.len;}}-return invertibleActions;}@@ -191,7 +190,6 @@ export class TextX {};this.push(insertAction);-return this;}diff --git a/packages/core/src/docs/data-model/text-x/utils.ts b/packages/core/src/docs/data-model/text-x/utils.tsindex 365e481680..c9f9b0535d 100644--- a/packages/core/src/docs/data-model/text-x/utils.ts+++ b/packages/core/src/docs/data-model/text-x/utils.ts@@ -16,7 +16,7 @@import { UpdateDocsAttributeType } from '../../../shared/command-enum';import { Tools } from '../../../shared/tools';-import type { IDocumentBody, IParagraph, ITextRun } from '../../../types/interfaces/i-document-data';+import type { ICustomDecoration, ICustomRange, IDocumentBody, IParagraph, ITextRun } from '../../../types/interfaces/i-document-data';import type { IRetainAction } from './action-types';import { coverTextRuns } from './apply-utils/update-apply';@@ -93,9 +93,66 @@ export function getBodySlice(}));}+ docBody.customRanges = getDeleteCustomRange(body, startOffset, endOffset);+ docBody.customDecorations = getCustomDecorationSlice(body, startOffset, endOffset);return docBody;}+export function getDeleteCustomRange(body: IDocumentBody, startOffset: number, endOffset: number) {+ const { customRanges = [] } = body;++ const deletedCustomRange: ICustomRange[] = [];+ customRanges.forEach((range) => {+ // custom-range contain slice-range+ if (startOffset <= range.startIndex && endOffset > range.endIndex) {+ const copy = Tools.deepClone(range);+ deletedCustomRange.push({+ ...copy,+ startIndex: copy.startIndex - startOffset,+ endIndex: copy.endIndex - startOffset,+ });+ // delete custom-range start tag, only happened in cancel custom-range+ } else if (startOffset <= range.startIndex && endOffset > range.startIndex) {+ const copy = Tools.deepClone(range);+ deletedCustomRange.push({+ ...copy,+ startIndex: copy.startIndex - startOffset,+ endIndex: copy.startIndex - startOffset,+ });+ // slice-range contain custom-range+ } else if (endOffset > range.endIndex && range.endIndex >= startOffset) {+ const copy = Tools.deepClone(range);+ deletedCustomRange.push({+ ...copy,+ startIndex: copy.endIndex - startOffset,+ endIndex: copy.endIndex - startOffset,+ });+ }+ });++ return deletedCustomRange;+}++export function getCustomDecorationSlice(body: IDocumentBody, startOffset: number, endOffset: number) {+ const { customDecorations = [] } = body;++ const customDecorationSlice: ICustomDecoration[] = [];+ customDecorations.forEach((range) => {+ // 34 35+ // ranges and selection has overlap+ if (Math.max(range.startIndex, startOffset) <= Math.min(range.endIndex, endOffset - 1)) {+ const copy = Tools.deepClone(range);+ customDecorationSlice.push({+ ...copy,+ startIndex: Math.max(copy.startIndex - startOffset, 0),+ endIndex: Math.min(copy.endIndex, endOffset) - startOffset,+ });+ }+ });++ return customDecorationSlice;+}+export function composeBody(thisBody: IDocumentBody,otherBody: IDocumentBody,@@ -153,7 +210,6 @@ export function composeBody(if (paragraphs.length) {retBody.paragraphs = paragraphs;}-return retBody;}diff --git a/packages/core/src/docs/data-model/types.ts b/packages/core/src/docs/data-model/types.tsindex 825e22ddfd..ebaa949f01 100644--- a/packages/core/src/docs/data-model/types.ts+++ b/packages/core/src/docs/data-model/types.ts@@ -42,8 +42,8 @@ export enum DataStreamTreeTokenType {TABLE_ROW_START = '\x1B', // 表格开始TABLE_CELL_START = '\x1C', // 表格开始TABLE_CELL_END = '\x1D', // 表格开始- TABLE_ROW_END = '\x1E', // 表格开始- TABLE_END = '\x1F', // 表格结束+ TABLE_ROW_END = '\x2A', // 表格开始+ TABLE_END = '\x2B', // 表格结束CUSTOM_RANGE_START = '\x1F', // 自定义范围开始CUSTOM_RANGE_END = '\x1E', // 自定义范围结束diff --git a/packages/core/src/services/command/command.service.ts b/packages/core/src/services/command/command.service.tsindex 022ef9d0fc..4b3a0d0701 100644--- a/packages/core/src/services/command/command.service.ts+++ b/packages/core/src/services/command/command.service.ts@@ -124,6 +124,8 @@ export interface IExecutionOptions {/** This command is from collaboration peers. */fromCollab?: boolean;+ fromChangeset?: boolean;+[key: PropertyKey]: string | number | boolean | undefined;}diff --git a/packages/core/src/services/resource-loader/resource-loader.service.ts b/packages/core/src/services/resource-loader/resource-loader.service.tsindex 85f17f645f..3dd9f642f3 100644--- a/packages/core/src/services/resource-loader/resource-loader.service.ts+++ b/packages/core/src/services/resource-loader/resource-loader.service.ts@@ -22,6 +22,7 @@ import { IResourceManagerService } from '../resource-manager/type';import { IUniverInstanceService } from '../instance/instance.service';import { Disposable, toDisposable } from '../../shared/lifecycle';import { UniverInstanceType } from '../../common/unit';+import type { DocumentDataModel } from '../../docs';import type { IResourceLoaderService } from './type';export class ResourceLoaderService extends Disposable implements IResourceLoaderService {@@ -41,7 +42,18 @@ export class ResourceLoaderService extends Disposable implements IResourceLoadercase UniverInstanceType.UNIVER_UNKNOWN:case UniverInstanceType.UNIVER_SLIDE:case UniverInstanceType.UNIVER_DOC: {- // TODO@gggpound: wait to support.+ this._univerInstanceService.getAllUnitsForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).forEach((doc) => {+ const snapshotResource = doc.getSnapshot().resources || [];+ const plugin = snapshotResource.find((r) => r.name === hook.pluginName);+ if (plugin) {+ try {+ const data = hook.parseJson(plugin.data);+ hook.onLoad(doc.getUnitId(), data);+ } catch (err) {+ console.error(`Load Document{${doc.getUnitId()}} Resources{${hook.pluginName}} Data Error.`);+ }+ }+ });break;}case UniverInstanceType.UNIVER_SHEET: {@@ -95,4 +107,12 @@ export class ResourceLoaderService extends Disposable implements IResourceLoadersnapshot.resources = resources;return snapshot;};++ saveDoc(doc: DocumentDataModel) {+ const unitId = doc.getUnitId();+ const resources = this._resourceManagerService.getResourcesByType(unitId, UniverInstanceType.UNIVER_DOC) || [];+ const snapshot = doc.getSnapshot();+ snapshot.resources = resources;+ return snapshot;+ };}diff --git a/packages/core/src/services/resource-loader/type.ts b/packages/core/src/services/resource-loader/type.tsindex c7358ed445..5e0e547786 100644--- a/packages/core/src/services/resource-loader/type.ts+++ b/packages/core/src/services/resource-loader/type.ts@@ -18,9 +18,12 @@ import { createIdentifier } from '@wendellhu/redi';import type { Workbook } from '../../sheets/workbook';import type { IWorkbookData } from '../../types/interfaces/i-workbook-data';import { LifecycleStages, runOnLifecycle } from '../lifecycle/lifecycle';+import type { IDocumentData } from '../../types/interfaces';+import type { DocumentDataModel } from '../../docs';export interface IResourceLoaderService {saveWorkbook: (workbook: Workbook) => IWorkbookData;+ saveDoc: (doc: DocumentDataModel) => IDocumentData;}export const IResourceLoaderService = createIdentifier<IResourceLoaderService>('resource-loader-service');runOnLifecycle(LifecycleStages.Ready, IResourceLoaderService);diff --git a/packages/core/src/services/resource-manager/resource-manager.service.ts b/packages/core/src/services/resource-manager/resource-manager.service.tsindex 717d63e3d0..0ab09b773a 100644--- a/packages/core/src/services/resource-manager/resource-manager.service.ts+++ b/packages/core/src/services/resource-manager/resource-manager.service.ts@@ -17,6 +17,7 @@import { Subject } from 'rxjs';import { Disposable, toDisposable } from '../../shared/lifecycle';import type { IWorkbookData } from '../../types/interfaces/i-workbook-data';+import type { UniverInstanceType } from '../../common/unit';import type { IResourceHook, IResourceManagerService, IResourceName } from './type';export class ResourceManagerService extends Disposable implements IResourceManagerService {@@ -42,6 +43,18 @@ export class ResourceManagerService extends Disposable implements IResourceManagreturn resources;}+ public getResourcesByType(unitId: string, type: UniverInstanceType) {+ const resourceHooks = this.getAllResourceHooks().filter((hook) => hook.businesses.includes(type));+ const resources = resourceHooks.map((resourceHook) => {+ const data = resourceHook.toJson(unitId);+ return {+ name: resourceHook.pluginName,+ data,+ };+ });+ return resources;+ }+public registerPluginResource<T = unknown>(hook: IResourceHook<T>) {const resourceName = hook.pluginName;if (this._resourceMap.has(resourceName)) {diff --git a/packages/core/src/services/resource-manager/type.ts b/packages/core/src/services/resource-manager/type.tsindex 1cef7403af..d9d65d1496 100644--- a/packages/core/src/services/resource-manager/type.ts+++ b/packages/core/src/services/resource-manager/type.ts@@ -37,8 +37,8 @@ export interface IResourceManagerService {disposePluginResource: (pluginName: IResourceName) => void;getAllResourceHooks: () => IResourceHook[];getResources: (unitId: string) => IWorkbookData['resources'];+ getResourcesByType: (unitId: string, type: UniverInstanceType) => IWorkbookData['resources'];loadResources: (unitId: string, resources: IWorkbookData['resources']) => void;-unloadResources(unitId: string): void;}diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex a98ac4f520..8b0b609f46 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -129,6 +129,7 @@ export interface IDocumentBody {// links?: { [index: number]: IHyperlink }; // linkscustomRanges?: ICustomRange[]; // plugin register,implement special logic for streams, hyperlink, field,structured document tags, bookmark,comment+ customDecorations?: ICustomDecoration[];}export interface IDocStyle {@@ -272,6 +273,16 @@ export interface ICustomRange {rangeType: CustomRangeType;}+export interface ICustomRangeForInterceptor extends ICustomRange {+ active?: boolean;+ show?: boolean;+}++export interface ICustomDecorationForInterceptor extends ICustomDecoration {+ active?: boolean;+ show?: boolean;+}+export enum CustomRangeType {HYPERLINK,FIELD, // 17.16 Fields and Hyperlinks@@ -292,6 +303,17 @@ export interface ICustomBlock {blockId: string;}+export enum CustomDecorationType {+ COMMENT,+}++export interface ICustomDecoration {+ startIndex: number;+ endIndex: number;+ id: string;+ type: CustomDecorationType;+}+/*** Type of block*/diff --git a/packages/core/src/types/interfaces/i-style-data.ts b/packages/core/src/types/interfaces/i-style-data.tsindex 2a0d17d184..18c22625b6 100644--- a/packages/core/src/types/interfaces/i-style-data.ts+++ b/packages/core/src/types/interfaces/i-style-data.ts@@ -147,6 +147,11 @@ export interface IStyleBase {* underline*/ul?: ITextDecoration;++ /**+ * bottomBorerLine+ */+ bbl?: ITextDecoration;/*** strikethrough*/diff --git a/packages/debugger/src/commands/commands/float-dom.command.ts b/packages/debugger/src/commands/commands/float-dom.command.tsindex 0e5ad6e791..90a57afcc1 100644--- a/packages/debugger/src/commands/commands/float-dom.command.ts+++ b/packages/debugger/src/commands/commands/float-dom.command.ts@@ -32,6 +32,9 @@ export const CreateFloatDomCommand: ICommand = {endY: 400,},componentKey: 'ImageDemo',+ props: {+ a: 1,+ },});return true;},diff --git a/packages/debugger/src/commands/operations/save-snapshot.operations.ts b/packages/debugger/src/commands/operations/save-snapshot.operations.tsindex 87a7053dbc..d3f4aecaf3 100644--- a/packages/debugger/src/commands/operations/save-snapshot.operations.ts+++ b/packages/debugger/src/commands/operations/save-snapshot.operations.ts@@ -15,7 +15,7 @@*//* eslint-disable node/prefer-global/process */-import type { ICommand, IStyleData, IWorkbookData, Workbook } from '@univerjs/core';+import type { DocumentDataModel, ICommand, IStyleData, IWorkbookData, Workbook } from '@univerjs/core';import { CommandType, IResourceLoaderService, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';import type { IAccessor } from '@wendellhu/redi';import { RecordController } from '../../controllers/local-save/record.controller';@@ -51,18 +51,29 @@ export const SaveSnapshotOptions: ICommand = {const resourceLoaderService = accessor.get(IResourceLoaderService);const exportController = accessor.get(ExportController);const recordController = accessor.get(RecordController);+ const gitHash = process.env.GIT_COMMIT_HASH;+ const gitBranch = process.env.GIT_REF_NAME;+ const buildTime = process.env.BUILD_TIME;+ const preName = new Date().toLocaleString();const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ if (!workbook) {+ const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;+ const snapshot = resourceLoaderService.saveDoc(doc);+ (snapshot as any).__env__ = { gitHash, gitBranch, buildTime };+ const text = JSON.stringify(snapshot, null, 2);+ exportController.exportJson(text, `${preName} snapshot`);+ return true;+ }+const worksheet = workbook.getActiveSheet();if (!worksheet) {return false;}const snapshot = resourceLoaderService.saveWorkbook(workbook);- const gitHash = process.env.GIT_COMMIT_HASH;- const gitBranch = process.env.GIT_REF_NAME;- const buildTime = process.env.BUILD_TIME;+(snapshot as any).__env__ = { gitHash, gitBranch, buildTime };- const preName = new Date().toLocaleString();+switch (params.value) {case 'sheet': {const sheetId = worksheet.getSheetId();diff --git a/packages/docs-thread-comment-ui/README-zh.md b/packages/docs-thread-comment-ui/README-zh.mdnew file mode 100644index 0000000000..8e078a2bf3--- /dev/null+++ b/packages/docs-thread-comment-ui/README-zh.md@@ -0,0 +1,60 @@+# @univerjs/docs-thread-comment-ui++[](https://npmjs.org/packages/@univerjs/docs-thread-comment-ui)+[](https://img.shields.io/npm/l/@univerjs/docs-thread-comment-ui)++## 简介++`@univerjs/docs-thread-comment-ui` 提供了 Univer Docs 的评论/批注功能。+++## 使用指南++### 安装++```shell+# 使用 npm+npm install @univerjs/docs-thread-comment-ui++# 使用 pnpm+pnpm add @univerjs/docs-thread-comment-ui+```++### 使用+```js+import { UniverSheetsThreadCommentPlugin, IThreadCommentMentionDataService } from '@univerjs/docs-thread-comment-ui';++const mockUser = {+ userID: 'mockId',+ name: 'MockUser',+ avatar: 'avatar-icon-url',+ anonymous: false,+ canBindAnonymous: false,+};++class CustomMentionDataService implements IThreadCommentMentionDataService {+ trigger: string = '@';++ // 获取提及用户的通用接口实现+ async getMentions(search: string) {+ return [+ {+ id: mockUser.userID,+ label: mockUser.name,+ type: 'user',+ icon: mockUser.avatar,+ },+ {+ id: '2',+ label: 'User2',+ type: 'user',+ icon: mockUser.avatar,+ },+ ];+ }+}++univer.registerPlugin(UniverSheetsThreadCommentPlugin, {+ overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]],+});+```diff --git a/packages/docs-thread-comment-ui/README.md b/packages/docs-thread-comment-ui/README.mdnew file mode 100644index 0000000000..6af55ce216--- /dev/null+++ b/packages/docs-thread-comment-ui/README.md@@ -0,0 +1,60 @@+# @univerjs/sheets-thread-comment++[](https://npmjs.org/packages/@univerjs/sheets-thread-comment )+[](https://img.shields.io/npm/l/@univerjs/sheets- thread-comment)++## Introduction++`@univerjs/sheets-thread-comment` provides the comment/annotation function of Univer Sheets.+++## Usage++### Install++```shell+# Use npm+npm install @univerjs/sheets-thread-comment++# Use pnpm+pnpm add @univerjs/sheets-thread-comment+```++### use+```js+import { UniverSheetsThreadCommentPlugin, IThreadCommentMentionDataService} from '@univerjs/sheets-thread-comment';++const mockUser = {+ userID: 'mockId',+ name: 'MockUser',+ avatar: 'icon-url',+ anonymous: false,+ canBindAnonymous: false,+};++class CustomMentionDataService implements IThreadCommentMentionDataService {+ trigger: string = '@';++ // Get the common interface implementation of the mentioned user+ async getMentions(search: string) {+ return [+ {+ id: mockUser.userID,+ label: mockUser.name,+ type: 'user',+ icon: mockUser.avatar,+ },+ {+ id: '2',+ label: 'User2',+ type: 'user',+ icon: mockUser.avatar,+ },+ ];+ }+}++univer.registerPlugin(UniverSheetsThreadCommentPlugin, {+ overrides: [[IThreadCommentMentionDataService, { useClass: CustomMentionDataService }]],+});+```diff --git a/packages/docs-thread-comment-ui/package.json b/packages/docs-thread-comment-ui/package.jsonnew file mode 100644index 0000000000..12dbf311ab--- /dev/null+++ b/packages/docs-thread-comment-ui/package.json@@ -0,0 +1,105 @@+{+ "name": "@univerjs/docs-thread-comment-ui",+ "version": "0.1.14",+ "private": false,+ "description": "Univer thread comment plugin",+ "author": "DreamNum <[email protected]>",+ "license": "Apache-2.0",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/univer"+ },+ "homepage": "https://univer.ai",+ "repository": {+ "type": "git",+ "url": "https://github.com/dream-num/univer"+ },+ "bugs": {+ "url": "https://github.com/dream-num/univer/issues"+ },+ "keywords": [],+ "exports": {+ ".": "./src/index.ts",+ "./*": "./src/*"+ },+ "main": "./lib/cjs/index.js",+ "module": "./lib/es/index.js",+ "types": "./lib/types/index.d.ts",+ "publishConfig": {+ "access": "public",+ "main": "./lib/cjs/index.js",+ "module": "./lib/es/index.js",+ "exports": {+ ".": {+ "import": "./lib/es/index.js",+ "require": "./lib/cjs/index.js",+ "types": "./lib/types/index.d.ts"+ },+ "./*": {+ "import": "./lib/es/*",+ "require": "./lib/cjs/*",+ "types": "./lib/types/index.d.ts"+ },+ "./lib/*": "./lib/*"+ }+ },+ "directories": {+ "lib": "lib"+ },+ "files": [+ "lib"+ ],+ "scripts": {+ "test": "vitest run",+ "test:watch": "vitest",+ "coverage": "vitest run --coverage",+ "lint:types": "tsc --noEmit",+ "build": "tsc && vite build"+ },+ "peerDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/docs": "workspace:*",+ "@univerjs/docs-ui": "workspace:*",+ "@univerjs/engine-render": "workspace:*",+ "@univerjs/thread-comment": "workspace:*",+ "@univerjs/thread-comment-ui": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.15.4",+ "react": "^16.9.0 || ^17.0.0 || ^18.0.0",+ "rxjs": ">=7.0.0"+ },+ "dependencies": {+ "@univerjs/icons": "^0.1.56",+ "@univerjs/thread-comment": "workspace:*",+ "@univerjs/thread-comment-ui": "workspace:*"+ },+ "devDependencies": {+ "@univerjs/core": "workspace:*",+ "@univerjs/design": "workspace:*",+ "@univerjs/engine-formula": "workspace:*",+ "@univerjs/shared": "workspace:*",+ "@univerjs/thread-comment": "workspace:*",+ "@univerjs/thread-comment-ui": "workspace:*",+ "@univerjs/ui": "workspace:*",+ "@wendellhu/redi": "0.15.4",+ "clsx": "^2.1.1",+ "react": "18.3.1",+ "rxjs": "^7.8.1",+ "typescript": "^5.4.5",+ "vite": "^5.2.12",+ "vitest": "^1.6.0"+ },+ "univerSpace": {+ ".": {+ "import": "./lib/es/index.js",+ "require": "./lib/cjs/index.js",+ "types": "./lib/types/index.d.ts"+ },+ "./*": {+ "import": "./lib/es/*",+ "require": "./lib/cjs/*",+ "types": "./lib/types/index.d.ts"+ },+ "./lib/*": "./lib/*"+ }+}diff --git a/packages/docs-thread-comment-ui/src/commands/commands/add-doc-comment.command.ts b/packages/docs-thread-comment-ui/src/commands/commands/add-doc-comment.command.tsnew file mode 100644index 0000000000..03a8a16b46--- /dev/null+++ b/packages/docs-thread-comment-ui/src/commands/commands/add-doc-comment.command.ts@@ -0,0 +1,75 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ICommand, ITextRange } from '@univerjs/core';+import { CommandType, CustomDecorationType, ICommandService, sequenceExecuteAsync } from '@univerjs/core';+import { addCustomDecorationBySelectionFactory } from '@univerjs/docs';+import type { IThreadComment } from '@univerjs/thread-comment';+import { AddCommentMutation, IThreadCommentDataSourceService } from '@univerjs/thread-comment';+import { SetActiveCommentOperation } from '@univerjs/thread-comment-ui';+import { DEFAULT_DOC_SUBUNIT_ID } from '../../common/const';++export interface IAddDocCommentComment {+ unitId: string;+ comment: IThreadComment;+ range: ITextRange;+}++export const AddDocCommentComment: ICommand<IAddDocCommentComment> = {+ id: 'docs.command.add-comment',+ type: CommandType.COMMAND,+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const { comment: originComment, unitId } = params;+ const dataSourceService = accessor.get(IThreadCommentDataSourceService);+ const comment = await dataSourceService.addComment(originComment);+ const commandService = accessor.get(ICommandService);++ const doMutation = addCustomDecorationBySelectionFactory(+ accessor,+ {+ id: comment.id,+ type: CustomDecorationType.COMMENT,+ }+ );+ if (doMutation) {+ const commentMutation = {+ id: AddCommentMutation.id,+ params: {+ unitId,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ comment,+ },+ };++ const activeOperation = {+ id: SetActiveCommentOperation.id,+ params: {+ unitId,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ commentId: comment.id,+ },+ };++ return (await sequenceExecuteAsync([commentMutation, doMutation, activeOperation], commandService)).result;+ }++ return false;+ },+};+diff --git a/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.ts b/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.tsnew file mode 100644index 0000000000..a22cec6116--- /dev/null+++ b/packages/docs-thread-comment-ui/src/commands/commands/delete-doc-comment.command.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ICommand } from '@univerjs/core';+import { CommandType, ICommandService, sequenceExecute } from '@univerjs/core';+import { deleteCustomDecorationFactory } from '@univerjs/docs';++export interface IDeleteDocCommentComment {+ unitId: string;+ commentId: string;+}++export const DeleteDocCommentComment: ICommand<IDeleteDocCommentComment> = {+ id: 'docs.command.delete-comment',+ type: CommandType.COMMAND,+ async handler(accessor, params) {+ if (!params) {+ return false;+ }+ const { commentId, unitId } = params;+ const commandService = accessor.get(ICommandService);++ const doMutation = deleteCustomDecorationFactory(accessor, {+ id: commentId,+ unitId,+ });++ if (doMutation) {+ return (await sequenceExecute([doMutation], commandService)).result;+ }++ return false;+ },+};+diff --git a/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.tsnew file mode 100644index 0000000000..6325b92740--- /dev/null+++ b/packages/docs-thread-comment-ui/src/commands/operations/show-comment-panel.operation.ts@@ -0,0 +1,117 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel, ICommand } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core';+import type { ActiveCommentInfo } from '@univerjs/thread-comment-ui';+import { getDT, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { ISidebarService } from '@univerjs/ui';+import { getSelectionText, TextSelectionManagerService } from '@univerjs/docs';+import { DocThreadCommentPanel } from '../../views/doc-thread-comment-panel';+import { DEFAULT_DOC_SUBUNIT_ID } from '../../common/const';+import { DocThreadCommentService } from '../../services/doc-thread-comment.service';++export interface IShowCommentPanelOperationParams {+ activeComment: ActiveCommentInfo;+}++export const ShowCommentPanelOperation: ICommand<IShowCommentPanelOperationParams> = {+ id: 'docs.operation.show-comment-panel',+ type: CommandType.OPERATION,+ handler(accessor, params) {+ const panelService = accessor.get(ThreadCommentPanelService);+ const sidebarService = accessor.get(ISidebarService);++ if (!panelService.panelVisible) {+ sidebarService.open({+ header: { title: 'threadCommentUI.panel.title' },+ children: { label: DocThreadCommentPanel.componentKey },+ width: 320,+ onClose: () => panelService.setPanelVisible(false),+ });+ panelService.setPanelVisible(true);+ }+ if (params) {+ panelService.setActiveComment(params?.activeComment);+ }++ return true;+ },+};++export const StartAddCommentOperation: ICommand = {+ id: 'docs.operation.start-add-comment',+ type: CommandType.OPERATION,+ handler(accessor) {+ const panelService = accessor.get(ThreadCommentPanelService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const doc = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const userManagerService = accessor.get(UserManagerService);+ const docCommentService = accessor.get(DocThreadCommentService);+ const commandService = accessor.get(ICommandService);+ const sidebarService = accessor.get(ISidebarService);++ const textRange = textSelectionManagerService.getActiveRange();+ if (!doc || !textRange) {+ return false;+ }++ if (textRange.collapsed) {+ if (panelService.panelVisible) {+ panelService.setPanelVisible(false);+ sidebarService.close();+ } else {+ commandService.executeCommand(ShowCommentPanelOperation.id);+ }+ return true;+ }++ if (!panelService.panelVisible) {+ commandService.executeCommand(ShowCommentPanelOperation.id);+ }++ const unitId = doc.getUnitId();+ const text = getSelectionText(doc.getBody()?.dataStream ?? '', textRange.startOffset, textRange.endOffset);+ const subUnitId = DEFAULT_DOC_SUBUNIT_ID;+ const commentId = '';++ const comment = {+ unitId,+ subUnitId,+ id: commentId,+ ref: text,+ dT: getDT(),+ personId: userManagerService.getCurrentUser().userID,+ text: {+ dataStream: '\r\n',+ },+ startOffset: textRange.startOffset!,+ endOffset: textRange.endOffset!,+ collapsed: true,+ threadId: commentId,+ };++ docCommentService.startAdd(comment);+ panelService.setActiveComment({+ unitId,+ subUnitId,+ commentId,+ });++ return true;+ },+};diff --git a/packages/docs-thread-comment-ui/src/common/const.ts b/packages/docs-thread-comment-ui/src/common/const.tsnew file mode 100644index 0000000000..abffdff6c6--- /dev/null+++ b/packages/docs-thread-comment-ui/src/common/const.ts@@ -0,0 +1,21 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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.+ */++export const PLUGIN_NAME = 'DOC_THREAD_COMMENT_UI_PLUGIN';++export const DEFAULT_DOC_SUBUNIT_ID = 'default_doc';++export const DEFAULT_TEMP_COMMENT_ID = 'default_comment';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.tsnew file mode 100644index 0000000000..daaf6cd2ce--- /dev/null+++ b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-selection.controller.ts@@ -0,0 +1,102 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel } from '@univerjs/core';+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';+import type { ISetTextSelectionsOperationParams } from '@univerjs/docs';+import { SetTextSelectionsOperation } from '@univerjs/docs';+import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { Inject } from '@wendellhu/redi';+import { DocBackScrollRenderController } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';+import { DEFAULT_DOC_SUBUNIT_ID } from '../common/const';+import { DocThreadCommentService } from '../services/doc-thread-comment.service';+import { ShowCommentPanelOperation } from '../commands/operations/show-comment-panel.operation';++@OnLifecycle(LifecycleStages.Rendered, DocThreadCommentSelectionController)+export class DocThreadCommentSelectionController extends Disposable {+ constructor(+ @Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(DocThreadCommentService) private readonly _docThreadCommentService: DocThreadCommentService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService+ ) {+ super();++ this._initSelectionChange();+ this._initActiveCommandChange();+ }++ private _initSelectionChange() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === SetTextSelectionsOperation.id) {+ const params = commandInfo.params as ISetTextSelectionsOperationParams;+ const { unitId, ranges } = params;+ const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);+ const primary = ranges[0];+ if (primary && doc) {+ const { startOffset, endOffset, collapsed } = primary;+ let customRange;++ if (collapsed) { // cursor+ customRange = doc.getBody()?.customDecorations?.find((value) => value.startIndex <= startOffset && value.endIndex >= (endOffset - 1));+ } else { // range+ customRange = doc.getBody()?.customDecorations?.find((value) => value.startIndex <= startOffset && value.endIndex >= (endOffset - 1));+ }++ if (customRange) {+ this._commandService.executeCommand(ShowCommentPanelOperation.id, {+ activeComment: {+ unitId,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ commentId: customRange.id,+ },+ });+ return;+ }+ }++ this._commandService.executeCommand(SetActiveCommentOperation.id);+ }+ })+ );+ }++ private _initActiveCommandChange() {+ this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.subscribe((activeComment) => {+ if (activeComment) {+ const doc = this._univerInstanceService.getUnit<DocumentDataModel>(activeComment.unitId);+ if (doc) {+ const backScrollController = this._renderManagerService.getRenderById(activeComment.unitId)?.with(DocBackScrollRenderController);+ const customRange = doc.getCustomRanges()?.find((range) => range.rangeId === activeComment.commentId);+ if (customRange && backScrollController) {+ backScrollController.scrollToRange(activeComment.unitId, {+ startOffset: customRange.startIndex,+ endOffset: customRange.endIndex,+ collapsed: false,+ });+ }+ }+ }++ if (!activeComment || activeComment.commentId !== this._docThreadCommentService.addingComment?.id) {+ this._docThreadCommentService.endAdd();+ }+ }));+ }+}diff --git a/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-ui.controller.ts b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-ui.controller.tsnew file mode 100644index 0000000000..ecafbf5b9c--- /dev/null+++ b/packages/docs-thread-comment-ui/src/controllers/doc-thread-comment-ui.controller.ts@@ -0,0 +1,71 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';+import type { MenuConfig } from '@univerjs/ui';+import { ComponentManager, IMenuService } from '@univerjs/ui';+import { Inject, Injector } from '@wendellhu/redi';+import { CommentSingle } from '@univerjs/icons';+import { AddDocCommentComment } from '../commands/commands/add-doc-comment.command';+import { DocThreadCommentPanel } from '../views/doc-thread-comment-panel';+import { ShowCommentPanelOperation, StartAddCommentOperation } from '../commands/operations/show-comment-panel.operation';+import { DeleteDocCommentComment } from '../commands/commands/delete-doc-comment.command';+import { AddDocCommentMenuItemFactory } from './menu';++export interface IDocThreadCommentUIConfig {+ menu: MenuConfig;+}++@OnLifecycle(LifecycleStages.Rendered, DocThreadCommentUIController)+export class DocThreadCommentUIController extends Disposable {+ constructor(+ private _config: IDocThreadCommentUIConfig,+ @ICommandService private readonly _commandService: ICommandService,+ @IMenuService private readonly _menuService: IMenuService,+ @Inject(Injector) private readonly _injector: Injector,+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ ) {+ super();+ this._initCommands();+ this._initMenus();+ this._initComponents();+ }++ private _initCommands() {+ [+ AddDocCommentComment,+ DeleteDocCommentComment,+ ShowCommentPanelOperation,+ StartAddCommentOperation,+ ].forEach((command) => {+ this.disposeWithMe(this._commandService.registerCommand(command));+ });+ }++ private _initMenus() {+ [AddDocCommentMenuItemFactory].forEach((menuFactory) => {+ this.disposeWithMe(this._menuService.addMenuItem(menuFactory(this._injector), this._config.menu));+ });+ }++ private _initComponents() {+ [DocThreadCommentPanel].forEach((comp) => {+ this.disposeWithMe(this._componentManager.register(comp.componentKey, comp));+ });++ this.disposeWithMe(this._componentManager.register('CommentSingle', CommentSingle));+ }+}diff --git a/packages/docs-thread-comment-ui/src/controllers/menu.ts b/packages/docs-thread-comment-ui/src/controllers/menu.tsnew file mode 100644index 0000000000..4dd3728f1c--- /dev/null+++ b/packages/docs-thread-comment-ui/src/controllers/menu.ts@@ -0,0 +1,34 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { IAccessor } from '@wendellhu/redi';+import { UniverInstanceType } from '@univerjs/core';+import type { IMenuButtonItem } from '@univerjs/ui';+import { getMenuHiddenObservable, MenuGroup, MenuItemType, MenuPosition } from '@univerjs/ui';+import { StartAddCommentOperation } from '../commands/operations/show-comment-panel.operation';++export function AddDocCommentMenuItemFactory(accessor: IAccessor): IMenuButtonItem {+ return {+ id: StartAddCommentOperation.id,+ group: MenuGroup.TOOLBAR_LAYOUT,+ type: MenuItemType.BUTTON,+ icon: 'CommentSingle',+ title: 'threadCommentUI.panel.addComment',+ tooltip: 'threadCommentUI.panel.addComment',+ positions: [MenuPosition.TOOLBAR_START, MenuPosition.CONTEXT_MENU],+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_DOC),+ };+}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.tsnew file mode 100644index 0000000000..4715a6ce06--- /dev/null+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/render.controller.ts@@ -0,0 +1,118 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel } from '@univerjs/core';+import { Disposable, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';+import { DOC_INTERCEPTOR_POINT, DocInterceptorService } from '@univerjs/docs';+import { DocRenderController } from '@univerjs/docs-ui';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';+import { ThreadCommentModel } from '@univerjs/thread-comment';+import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { Inject } from '@wendellhu/redi';+import { DEFAULT_DOC_SUBUNIT_ID } from '../../common/const';++@OnLifecycle(LifecycleStages.Starting, DocThreadCommentRenderController)+export class DocThreadCommentRenderController extends Disposable implements IRenderModule {+ constructor(+ private readonly _context: IRenderContext<DocumentDataModel>,+ @Inject(DocInterceptorService) private readonly _docInterceptorService: DocInterceptorService,+ @Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService,+ @Inject(DocRenderController) private readonly _docRenderController: DocRenderController,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(ThreadCommentModel) private readonly _threadCommentModel: ThreadCommentModel+ ) {+ super();++ this._interceptorViewModel();+ this._initReRender();+ }++ private _initReRender() {+ this.disposeWithMe(this._threadCommentPanelService.activeCommentId$.subscribe((activeComment) => {+ if (activeComment) {+ this._docRenderController.reRender(activeComment.unitId);+ return;+ }++ const unitId = this._univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_DOC)?.getUnitId();+ if (unitId) {+ this._docRenderController.reRender(unitId);+ }+ }));++ this.disposeWithMe(this._threadCommentModel.commentUpdate$.subscribe((update) => {+ if (update.type === 'resolve') {+ this._docRenderController.reRender(update.unitId);+ }+ }));+ }++ private _interceptorViewModel() {+ this._docInterceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {+ handler: (data, pos, next) => {+ if (!data) {+ return next(data);+ }+ const { unitId, index, customRanges } = pos;+ const activeComment = this._threadCommentPanelService.activeCommentId;+ const { commentId, unitId: commentUnitID } = activeComment || {};+ const activeCustomRange = customRanges.find((i) => i.rangeId === commentId);+ const comment = this._threadCommentModel.getComment(unitId, DEFAULT_DOC_SUBUNIT_ID, data.rangeId);+ if (!comment) {+ return next({+ ...data,+ show: false,+ });+ }++ const isActiveIndex = activeCustomRange && index >= activeCustomRange.startIndex && index <= activeCustomRange.endIndex;+ const isActive = commentUnitID === unitId && data.rangeId === commentId;+ return next({+ ...data,+ active: isActive || isActiveIndex,+ show: !comment.resolved,+ });+ },+ });++ this._docInterceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_DECORATION, {+ handler: (data, pos, next) => {+ if (!data) {+ return next(data);+ }+ const { unitId, index, customDecorations } = pos;+ const activeComment = this._threadCommentPanelService.activeCommentId;+ const { commentId, unitId: commentUnitID } = activeComment || {};+ const activeCustomDecoration = customDecorations.find((i) => i.id === commentId);+ const comment = this._threadCommentModel.getComment(unitId, DEFAULT_DOC_SUBUNIT_ID, data.id);+ if (!comment) {+ return next({+ ...data,+ show: false,+ });+ }++ const isActiveIndex = activeCustomDecoration && index >= activeCustomDecoration.startIndex && index <= activeCustomDecoration.endIndex;+ const isActive = commentUnitID === unitId && data.id === commentId;+ return next({+ ...data,+ active: isActive || isActiveIndex,+ show: !comment.resolved,+ });+ },+ });+ }+}diff --git a/packages/docs-thread-comment-ui/src/index.ts b/packages/docs-thread-comment-ui/src/index.tsnew file mode 100644index 0000000000..aadd7d044a--- /dev/null+++ b/packages/docs-thread-comment-ui/src/index.ts@@ -0,0 +1,27 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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.+ */++export { UniverDocsCommentUIPlugin } from './plugin';++// #region - all commands+export { AddDocCommentComment } from './commands/commands/add-doc-comment.command';+export type { IAddDocCommentComment } from './commands/commands/add-doc-comment.command';+export { ShowCommentPanelOperation, StartAddCommentOperation } from './commands/operations/show-comment-panel.operation';+export type { IShowCommentPanelOperationParams } from './commands/operations/show-comment-panel.operation';+export { DeleteDocCommentComment } from './commands/commands/delete-doc-comment.command';+export type { IDeleteDocCommentComment } from './commands/commands/delete-doc-comment.command';++// #endregiondiff --git a/packages/docs-thread-comment-ui/src/plugin.ts b/packages/docs-thread-comment-ui/src/plugin.tsnew file mode 100644index 0000000000..71c9d1ebbd--- /dev/null+++ b/packages/docs-thread-comment-ui/src/plugin.ts@@ -0,0 +1,67 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DependentOn, Plugin, UniverInstanceType } from '@univerjs/core';+import type { Dependency } from '@wendellhu/redi';+import { Inject, Injector } from '@wendellhu/redi';+import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';+import { IRenderManagerService } from '@univerjs/engine-render';+import { PLUGIN_NAME } from './common/const';+import type { IDocThreadCommentUIConfig } from './controllers/doc-thread-comment-ui.controller';+import { DocThreadCommentUIController } from './controllers/doc-thread-comment-ui.controller';+import { DocThreadCommentService } from './services/doc-thread-comment.service';+import { DocThreadCommentSelectionController } from './controllers/doc-thread-comment-selection.controller';+import { DocThreadCommentRenderController } from './controllers/render-controllers/render.controller';++@DependentOn(UniverThreadCommentUIPlugin)+export class UniverDocsCommentUIPlugin extends Plugin {+ static override pluginName = PLUGIN_NAME;+ static override type = UniverInstanceType.UNIVER_DOC;++ constructor(+ private _config: IDocThreadCommentUIConfig = { menu: {} },+ @Inject(Injector) protected _injector: Injector,+ @IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService+ ) {+ super();+ }++ override onStarting(injector: Injector): void {+ ([+ [+ DocThreadCommentUIController,+ {+ useFactory: () => this._injector.createInstance(DocThreadCommentUIController, this._config),+ },+ ],+ [DocThreadCommentSelectionController],++ [DocThreadCommentService],+ ] as Dependency[]).forEach((dep) => {+ injector.add(dep);+ });+ }++ override onRendered(): void {+ this._initRenderModule();+ }++ private _initRenderModule() {+ [DocThreadCommentRenderController].forEach((dep) => {+ this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, dep);+ });+ }+}diff --git a/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.ts b/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.tsnew file mode 100644index 0000000000..c4a50bdd18--- /dev/null+++ b/packages/docs-thread-comment-ui/src/services/doc-thread-comment.service.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ITextRange, Nullable } from '@univerjs/core';+import type { IThreadComment } from '@univerjs/thread-comment';+import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { ISidebarService } from '@univerjs/ui';+import { Inject } from '@wendellhu/redi';+import { BehaviorSubject } from 'rxjs';++export class DocThreadCommentService {+ private _addingComment$ = new BehaviorSubject<Nullable<IThreadComment & ITextRange>>(undefined);+ readonly addingComment$ = this._addingComment$.asObservable();++ get addingComment() {+ return this._addingComment$.getValue();+ }++ constructor(+ @ISidebarService private readonly _sidebarService: ISidebarService,+ @Inject(ThreadCommentPanelService) private readonly _threadCommentPanelService: ThreadCommentPanelService+ ) {+ }++ startAdd(comment: IThreadComment & ITextRange) {+ this._addingComment$.next(comment);+ }++ endAdd() {+ this._addingComment$.next(undefined);+ }+}diff --git a/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsx b/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsxnew file mode 100644index 0000000000..520c02af1e--- /dev/null+++ b/packages/docs-thread-comment-ui/src/views/doc-thread-comment-panel/index.tsx@@ -0,0 +1,116 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { ThreadCommentPanel } from '@univerjs/thread-comment-ui';+import { useDependency, useObservable } from '@wendellhu/redi/react-bindings';+import React, { useEffect, useMemo, useState } from 'react';+import { Observable } from 'rxjs';+import { RichTextEditingMutation, TextSelectionManagerService } from '@univerjs/docs';+import { DEFAULT_DOC_SUBUNIT_ID } from '../../common/const';+import { StartAddCommentOperation } from '../../commands/operations/show-comment-panel.operation';+import { DocThreadCommentService } from '../../services/doc-thread-comment.service';+import type { IAddDocCommentComment } from '../../commands/commands/add-doc-comment.command';+import { AddDocCommentComment } from '../../commands/commands/add-doc-comment.command';+import { DeleteDocCommentComment, type IDeleteDocCommentComment } from '../../commands/commands/delete-doc-comment.command';++export const DocThreadCommentPanel = () => {+ const univerInstanceService = useDependency(IUniverInstanceService);+ const doc$ = useMemo(() => univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC), [univerInstanceService]);+ const doc = useObservable(doc$);+ const subUnitId$ = useMemo(() => new Observable<string>((sub) => sub.next(DEFAULT_DOC_SUBUNIT_ID)), []);+ const textSelectionManagerService = useDependency(TextSelectionManagerService);+ const textRange = useObservable(textSelectionManagerService.textSelection$)?.textRanges[0];+ const commandService = useDependency(ICommandService);+ const docCommentService = useDependency(DocThreadCommentService);+ const tempComment = useObservable(docCommentService.addingComment$);+ const [commentIds, setCommentIds] = useState<string[]>([]);++ useEffect(() => {+ const set = new Set<string>();+ const customRanges = doc?.getCustomDecorations();+ setCommentIds(customRanges?.map((r) => r.id).filter((i) => {+ const hasRepeat = set.has(i);+ set.add(i);+ return !hasRepeat;+ }) ?? []);++ const dispose = commandService.onCommandExecuted((command) => {+ if (command.id === RichTextEditingMutation.id) {+ const set = new Set<string>();+ const customRanges = doc?.getCustomDecorations();+ setCommentIds(customRanges?.map((r) => r.id).filter((i) => {+ const hasRepeat = set.has(i);+ set.add(i);+ return !hasRepeat;+ }) ?? []);+ }+ });+ return () => {+ dispose.dispose();+ };+ }, [commandService, doc]);++ if (!doc) {+ return null;+ }+ const isInValidSelection = textRange && textRange.endOffset === textRange.startOffset;+ const unitId = doc.getUnitId();++ return (+ <ThreadCommentPanel+ unitId={unitId}+ subUnitId$={subUnitId$}+ type={UniverInstanceType.UNIVER_DOC}+ onAdd={() => {+ commandService.executeCommand(StartAddCommentOperation.id);+ }}+ getSubUnitName={() => ''}+ disableAdd={isInValidSelection}+ tempComment={tempComment}+ onAddComment={(comment) => {+ // attach an comment to an custom-range+ if (!comment.parentId) {+ const params: IAddDocCommentComment = {+ unitId,+ range: tempComment!,+ comment,+ };+ commandService.executeCommand(AddDocCommentComment.id, params);+ docCommentService.endAdd();+ return false;+ }++ return true;+ }}+ onDeleteComment={(comment) => {+ if (!comment.parentId) {+ const params: IDeleteDocCommentComment = {+ unitId,+ commentId: comment.id,+ };+ commandService.executeCommand(DeleteDocCommentComment.id, params);+ return false;+ }+ return true;+ }}+ showComments={commentIds}+ />+ );+};++DocThreadCommentPanel.componentKey = 'univer.doc.thread-comment-panel';diff --git a/packages/docs-thread-comment-ui/src/vite-env.d.ts b/packages/docs-thread-comment-ui/src/vite-env.d.tsnew file mode 100644index 0000000000..11f02fe2a0--- /dev/null+++ b/packages/docs-thread-comment-ui/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/packages/docs-thread-comment-ui/tsconfig.json b/packages/docs-thread-comment-ui/tsconfig.jsonnew file mode 100644index 0000000000..d676ad2a20--- /dev/null+++ b/packages/docs-thread-comment-ui/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "@univerjs/shared/tsconfigs/base",+ "compilerOptions": {+ "rootDir": "src",+ "outDir": "lib/types"+ },+ "references": [{ "path": "./tsconfig.node.json" }],+ "include": ["src"]+}diff --git a/packages/docs-thread-comment-ui/tsconfig.node.json b/packages/docs-thread-comment-ui/tsconfig.node.jsonnew file mode 100644index 0000000000..e53dac8868--- /dev/null+++ b/packages/docs-thread-comment-ui/tsconfig.node.json@@ -0,0 +1,4 @@+{+ "extends": "@univerjs/shared/tsconfigs/node",+ "include": ["vite.config.ts"]+}diff --git a/packages/docs-thread-comment-ui/vite.config.ts b/packages/docs-thread-comment-ui/vite.config.tsnew file mode 100644index 0000000000..925b530b4d--- /dev/null+++ b/packages/docs-thread-comment-ui/vite.config.ts@@ -0,0 +1,12 @@+import createViteConfig from '@univerjs/shared/vite';+import pkg from './package.json';++export default ({ mode }) => createViteConfig({}, {+ mode,+ pkg,+ features: {+ react: false,+ css: true,+ dom: true,+ },+});diff --git a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.tsindex d634f08cc6..c48c14607b 100644--- a/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/back-scroll.render-controller.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import type { DocumentDataModel } from '@univerjs/core';-import { RxDisposable } from '@univerjs/core';-import { DocSkeletonManagerService, neoGetDocObject, TextSelectionManagerService, VIEWPORT_KEY } from '@univerjs/docs';-import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';-import { getAnchorBounding, NodePositionConvertToCursor } from '@univerjs/engine-render';+import type { DocumentDataModel, ITextRange, Nullable } from '@univerjs/core';+import { IUniverInstanceService, RxDisposable } from '@univerjs/core';+import { DocSkeletonManagerService, getDocObject, TextSelectionManagerService, VIEWPORT_KEY } from '@univerjs/docs';+import type { INodePosition, IRenderContext, IRenderModule } from '@univerjs/engine-render';+import { getAnchorBounding, IRenderManagerService, NodePositionConvertToCursor } from '@univerjs/engine-render';import { IEditorService } from '@univerjs/ui';import { Inject } from '@wendellhu/redi';import { takeUntil } from 'rxjs';@@ -28,9 +28,10 @@ const ANCHOR_WIDTH = 1.5;export class DocBackScrollRenderController extends RxDisposable implements IRenderModule {constructor(private readonly _context: IRenderContext<DocumentDataModel>,- @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,- @IEditorService private readonly _editorService: IEditorService+ @IEditorService private readonly _editorService: IEditorService,+ @Inject(IUniverInstanceService) private readonly _univerInstanceService: IUniverInstanceService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -51,19 +52,24 @@ export class DocBackScrollRenderController extends RxDisposable implements IRend});}- // Let the selection show on the current screen.- private _scrollToSelection(unitId: string) {- const activeTextRange = this._textSelectionManagerService.getActiveRange();- const docObject = neoGetDocObject(this._context);- const skeleton = this._docSkeletonManagerService.getSkeleton();-- if (activeTextRange == null || docObject == null) {+ scrollToRange(unitId: string, range: ITextRange) {+ const docSkeletonManagerService = this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);+ const skeleton = docSkeletonManagerService?.getSkeleton();+ if (!skeleton) {return;}+ const { startOffset } = range;+ const anchorNodePosition = skeleton.findNodePositionByCharIndex(startOffset);+ // const focusNodePosition = startOffset !== endOffset ? skeleton.findNodePositionByCharIndex(endOffset) : null;+ this.scrollToNode(unitId, anchorNodePosition);+ }- const { collapsed, startNodePosition } = activeTextRange;+ scrollToNode(unitId: string, startNodePosition: Nullable<INodePosition>) {+ const docObject = this._getDocObject();+ const docSkeletonManagerService = this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);+ const skeleton = docSkeletonManagerService?.getSkeleton();- if (!collapsed) {+ if (docObject == null || skeleton == null) {return;}@@ -101,7 +107,7 @@ export class DocBackScrollRenderController extends RxDisposable implements IRendconst delta = isEditor ? 0 : 100;if (top < boundTop) {- offsetY = top - boundTop;+ offsetY = top - boundTop - delta;} else if (top > boundBottom - height) {offsetY = top - boundBottom + height + delta;}@@ -115,4 +121,24 @@ export class DocBackScrollRenderController extends RxDisposable implements IRendconst config = viewportMain.transViewportScroll2ScrollValue(offsetX, offsetY);viewportMain.scrollBy(config);}++ // Let the selection show on the current screen.+ private _scrollToSelection(unitId: string) {+ const activeTextRange = this._textSelectionManagerService.getActiveRange();+ if (activeTextRange == null) {+ return;+ }++ const { collapsed, startNodePosition } = activeTextRange;++ if (!collapsed) {+ return;+ }++ this.scrollToNode(unitId, startNodePosition);+ }++ private _getDocObject() {+ return getDocObject(this._univerInstanceService, this._renderManagerService);+ }}diff --git a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.tsindex a81d67077a..a4972da02b 100644--- a/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts+++ b/packages/docs-ui/src/controllers/render-controllers/doc.render-controller.ts@@ -19,7 +19,7 @@ import { ICommandService, IConfigService, RxDisposable } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import { DOCS_COMPONENT_BACKGROUND_LAYER_INDEX, DOCS_COMPONENT_DEFAULT_Z_INDEX, DOCS_COMPONENT_HEADER_LAYER_INDEX, DOCS_COMPONENT_MAIN_LAYER_INDEX, DOCS_VIEW_KEY, DocSkeletonManagerService, RichTextEditingMutation, VIEWPORT_KEY } from '@univerjs/docs';import type { DocumentSkeleton, IRenderContext, IRenderModule, IWheelEvent } from '@univerjs/engine-render';-import { DocBackground, Documents, Layer, PageLayoutType, ScrollBar, Viewport } from '@univerjs/engine-render';+import { DocBackground, Documents, IRenderManagerService, Layer, PageLayoutType, ScrollBar, Viewport } from '@univerjs/engine-render';import { IEditorService } from '@univerjs/ui';import { Inject } from '@wendellhu/redi';import { takeUntil } from 'rxjs';@@ -30,7 +30,8 @@ export class DocRenderController extends RxDisposable implements IRenderModule {@ICommandService private readonly _commandService: ICommandService,@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,@IConfigService private readonly _configService: IConfigService,- @IEditorService private readonly _editorService: IEditorService+ @IEditorService private readonly _editorService: IEditorService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -39,6 +40,30 @@ export class DocRenderController extends RxDisposable implements IRenderModule {this._initCommandListener();}+ reRender(unitId: string) {+ const docSkeletonManagerService = this._renderManagerService.getRenderById(unitId)?.with(DocSkeletonManagerService);+ const skeleton = docSkeletonManagerService?.getSkeleton();+ if (!skeleton) {+ return;+ }++ // TODO: `disabled` is only used for read only demo, and will be removed in the future.+ const disabled = !!skeleton.getViewModel().getDataModel().getSnapshot().disabled;+ if (disabled) {+ return;+ }++ skeleton.calculate();++ if (this._editorService.isEditor(unitId)) {+ this._context.mainComponent?.makeDirty();++ return;+ }++ this._recalculateSizeBySkeleton(skeleton);+ }+private _addNewRender() {const { scene, engine, unit } = this._context;@@ -156,26 +181,7 @@ export class DocRenderController extends RxDisposable implements IRenderModule {const params = command.params as IRichTextEditingMutationParams;const { unitId } = params;- const skeleton = this._docSkeletonManagerService.getSkeleton();- if (!skeleton) {- return;- }-- // TODO: `disabled` is only used for read only demo, and will be removed in the future.- const disabled = !!skeleton.getViewModel().getDataModel().getSnapshot().disabled;- if (disabled) {- return;- }-- skeleton.calculate();-- if (this._editorService.isEditor(unitId)) {- this._context.mainComponent?.makeDirty();-- return;- }-- this._recalculateSizeBySkeleton(skeleton);+ this.reRender(unitId);}}));}diff --git a/packages/docs-ui/src/docs-ui-plugin.ts b/packages/docs-ui/src/docs-ui-plugin.tsindex 8c6fef3531..945e619deb 100644--- a/packages/docs-ui/src/docs-ui-plugin.ts+++ b/packages/docs-ui/src/docs-ui-plugin.ts@@ -27,7 +27,7 @@ import { Inject, Injector } from '@wendellhu/redi';import { IEditorService, IShortcutService } from '@univerjs/ui';import { IRenderManagerService } from '@univerjs/engine-render';-import { DocSkeletonManagerService } from '@univerjs/docs';+import { DocInterceptorService, DocSkeletonManagerService } from '@univerjs/docs';import {MoveCursorDownShortcut,MoveCursorLeftShortcut,@@ -140,6 +140,7 @@ export class UniverDocsUIPlugin extends Plugin {private _initRenderBasics(): void {([DocSkeletonManagerService,+ DocInterceptorService,DocRenderController,DocZoomRenderController,]).forEach((m) => {diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex 2246dad68e..846db4e6ab 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -14,6 +14,7 @@* limitations under the License.*/+export { DocBackScrollRenderController } from './controllers/render-controllers/back-scroll.render-controller';export * from './basics';export * from './docs-ui-plugin';export { DocRenderController } from './controllers/render-controllers/doc.render-controller';diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex a5b07a0c00..8cb4fd9fa4 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -14,13 +14,13 @@* limitations under the License.*/-import type { IDocumentBody, IParagraph } from '@univerjs/core';+import type { ICustomRange, IDocumentBody, IParagraph } from '@univerjs/core';import { Disposable, ICommandService, ILogService, IUniverInstanceService, toDisposable } from '@univerjs/core';import { HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, PLAIN_TEXT_CLIPBOARD_MIME_TYPE } from '@univerjs/ui';import type { IDisposable } from '@wendellhu/redi';import { createIdentifier, Inject } from '@wendellhu/redi';-import { CutContentCommand, InnerPasteCommand, TextSelectionManagerService } from '@univerjs/docs';+import { CutContentCommand, getDeleteSelection, InnerPasteCommand, TextSelectionManagerService } from '@univerjs/docs';import { copyContentCache, extractId, genId } from './copy-content-cache';import { HtmlToUDMService } from './html-to-udm/converter';import PastePluginLark from './html-to-udm/paste-plugins/plugin-lark';@@ -131,7 +131,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServreturn false;}- // Set content to clipboard.+ // Set content to clipboard.this.copy();try {@@ -176,7 +176,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}try {- // When doc has multiple selections, the cursor moves to the last pasted content's end.+ // When doc has multiple selections, the cursor moves to the last pasted content's end.let cursor = activeEndOffset;for (const range of ranges) {const { startOffset, endOffset } = range;@@ -208,12 +208,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServprivate async _setClipboardData(documentBodyList: IDocumentBody[]): Promise<void> {const copyId = genId();const text =- documentBodyList.length > 1- ? documentBodyList.map((body) => body.dataStream).join('\n')- : documentBodyList[0].dataStream;+ documentBodyList.length > 1+ ? documentBodyList.map((body) => body.dataStream).join('\n')+ : documentBodyList[0].dataStream;let html = this._umdToHtml.convert(documentBodyList);- // Only cache copy content when the range is 1.+ // Only cache copy content when the range is 1.if (documentBodyList.length === 1) {html = html.replace(/(<[a-z]+)/, (_p0, p1) => `${p1} data-copy-id="${copyId}"`);copyContentCache.set(copyId, documentBodyList[0]);@@ -238,8 +238,9 @@ export class DocClipboardService extends Disposable implements IDocClipboardServconst ranges = this._textSelectionManagerService.getSelections();const doc = this._univerInstanceService.getCurrentUniverDocInstance();const results: IDocumentBody[] = [];+ const body = doc?.getBody();- if (ranges == null || !doc) {+ if (ranges == null || !doc || !body) {return results;}@@ -253,12 +254,32 @@ export class DocClipboardService extends Disposable implements IDocClipboardServif (startOffset == null || endOffset == null) {continue;}+ const deleteRange = getDeleteSelection({ startOffset, endOffset, collapsed }, body);- const docBody = doc.sliceBody(startOffset, endOffset);+ const docBody = doc.sliceBody(deleteRange.startOffset, deleteRange.endOffset);if (docBody == null) {continue;}+ if (docBody.customRanges) {+ const deleteRange: ICustomRange[] = [];+ docBody.customRanges.forEach((range) => {+ // should be delete+ if (range.startIndex === range.endIndex) {+ deleteRange.push(range);+ }+ });+ docBody.customRanges = docBody.customRanges.filter((range) => deleteRange.indexOf(range) === -1);+ let text = '';+ let cursor = 0;+ deleteRange.forEach((range) => {+ text += docBody.dataStream.slice(cursor, range.endIndex);+ cursor = range.endIndex + 1;+ });+ text += docBody.dataStream.slice(cursor, docBody.dataStream.length);+ docBody.dataStream = text;+ }+results.push(docBody);}@@ -267,7 +288,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServprivate async _generateBodyFromClipboardItems(items: ClipboardItem[]): Promise<IDocumentBody> {try {- // TODO: support paste image.+ // TODO: support paste image.let html = '';let text = '';diff --git a/packages/docs-ui/src/services/doc-mark-selection.service.ts b/packages/docs-ui/src/services/doc-mark-selection.service.tsnew file mode 100644index 0000000000..a80cd99e97--- /dev/null+++ b/packages/docs-ui/src/services/doc-mark-selection.service.ts@@ -0,0 +1,111 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel } from '@univerjs/core';+import { IUniverInstanceService, Tools, UniverInstanceType } from '@univerjs/core';+import { type BaseObject, IRenderManagerService, type ITextRangeWithStyle } from '@univerjs/engine-render';++export interface IDocMarkSelectionService {+ addShape(selection: ITextRangeWithStyle, zIndex?: number): string | null;+ removeShape(id: string): void;+ removeAllShapes(): void;+ refreshShapes(): void;+ getShapeMap(): Map<string, IDocMarkSelectionInfo>;+}++export interface IDocMarkSelectionInfo {+ control: BaseObject[] | null;+ unitId: string;+ selection: ITextRangeWithStyle;+ zIndex: number;+}++const DEFAULT_Z_INDEX = 10000;++export class DocMarkSelectionService implements IDocMarkSelectionService {+ private _shapeMap: Map<string, IDocMarkSelectionInfo> = new Map();++ constructor(+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService+ ) {}++ addShape(selection: ITextRangeWithStyle, zIndex = DEFAULT_Z_INDEX): string | null {+ const doc = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!doc) return null;+ const id = Tools.generateRandomId();++ this._shapeMap.set(id, {+ selection,+ unitId: doc.getUnitId(),+ zIndex,+ control: null,+ });++ this.refreshShapes();+ return id;+ }++ removeShape(id: string): void {+ const shapeInfo = this._shapeMap.get(id);+ if (!shapeInfo) return;+ const { control } = shapeInfo;+ control && control.forEach((obj) => obj.dispose());+ this._shapeMap.delete(id);+ }++ removeAllShapes(): void {+ for (const shape of this._shapeMap.values()) {+ const { control } = shape;+ control && control.forEach((obj) => obj.dispose());+ }+ this._shapeMap.clear();+ }++ refreshShapes() {+ const doc = this._univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!doc) return;++ const currentUnitId = doc.getUnitId();+ this._shapeMap.forEach((shape) => {+ const { unitId, selection, control: oldControl, zIndex } = shape;++ oldControl && oldControl.forEach((obj) => obj.dispose());++ if (unitId !== currentUnitId) {+ return;+ }++ const { style } = selection;+ const renderUnit = this._renderManagerService.getRenderById(unitId);+ const scene = renderUnit?.scene;+ // const { rangeWithCoord, primaryWithCoord } =+ // this._selectionRenderService.attachSelectionWithCoord(selection);++ // const skeleton = this._renderManagerService.withCurrentTypeOfUnit(UniverInstanceType.UNIVER_SHEET, SheetSkeletonManagerService)?.getCurrentSkeleton();+ // if (!scene || !skeleton) return;++ // const { rowHeaderWidth, columnHeaderHeight } = skeleton;+ // const control = new SelectionShape(scene, zIndex, false, this._themeService);+ // control.update(rangeWithCoord, rowHeaderWidth, columnHeaderHeight, style, primaryWithCoord);+ // shape.control = control;+ });+ }++ getShapeMap(): Map<string, IDocMarkSelectionInfo> {+ return this._shapeMap;+ }+}diff --git a/packages/docs/src/basics/custom-decoration-factory.ts b/packages/docs/src/basics/custom-decoration-factory.tsnew file mode 100644index 0000000000..03937528cc--- /dev/null+++ b/packages/docs/src/basics/custom-decoration-factory.ts@@ -0,0 +1,188 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { CustomDecorationType, DocumentDataModel, IMutationInfo, ITextRange } from '@univerjs/core';+import { getBodySlice, IUniverInstanceService, JSONX, TextX, TextXActionType, Tools, UniverInstanceType, UpdateDocsAttributeType } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';+import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';+import { TextSelectionManagerService } from '../services/text-selection-manager.service';++interface IAddCustomDecorationParam {+ unitId: string;+ range: ITextRange;+ segmentId?: string;+ id: string;+ type: CustomDecorationType;+}++export function addCustomDecorationFactory(param: IAddCustomDecorationParam) {+ const { unitId, range, id, type, segmentId } = param;++ const { startOffset: start, endOffset: end } = range;+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges: undefined,+ },+ };++ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ if (start > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: start,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.RETAIN,+ body: {+ dataStream: '',+ customDecorations: [{+ id,+ type,+ startIndex: 0,+ endIndex: end - start - 1,+ }],+ },+ len: end - start,+ segmentId,+ });++ doMutation.params.actions = jsonX.editOp(textX.serialize());+ return doMutation;+}++interface IAddCustomDecorationFactoryParam {+ segmentId?: string;+ id: string;+ type: CustomDecorationType;+}++export function addCustomDecorationBySelectionFactory(accessor: IAccessor, param: IAddCustomDecorationFactoryParam) {+ const { segmentId, id, type } = param;+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const selection = textSelectionManagerService.getActiveRange();+ if (!selection) {+ return false;+ }++ const documentDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!documentDataModel) {+ return false;+ }+ const body = documentDataModel.getBody();+ const unitId = documentDataModel.getUnitId();+ if (!body) {+ return false;+ }++ const doMutation = addCustomDecorationFactory(+ {+ unitId,+ range: {+ startOffset: selection.startOffset,+ endOffset: selection.endOffset,+ collapsed: true,+ },+ id,+ type,+ segmentId,+ }+ );++ return doMutation;+}++export interface IDeleteCustomRangeParam {+ unitId: string;+ id: string;+ segmentId?: string;+}++export function deleteCustomDecorationFactory(accessor: IAccessor, params: IDeleteCustomRangeParam) {+ const { unitId, id, segmentId } = params;+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);+ const body = documentDataModel?.getBody();+ if (!documentDataModel || !body) {+ return false;+ }++ const decorations = documentDataModel.getBody()?.customDecorations?.filter((d) => d.id === id);+ if (!decorations?.length) {+ return false;+ }++ const oldBodySlices = decorations.map((i) => {+ const bodySlice = getBodySlice(body, i.startIndex, i.endIndex + 1);+ // bodySlice.customDecorations = bodySlice.customDecorations?.filter((decoration) => decoration.id !== id);+ return bodySlice;+ });++ const bodySlices = oldBodySlices.map((bodySlice) => {+ const copy = Tools.deepClone(bodySlice);+ copy.customDecorations = copy.customDecorations?.filter((decoration) => decoration.id !== id);+ return copy;+ });++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges: undefined,+ },+ };++ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ let cursor = 0;+ decorations.forEach((decoration, i) => {+ const bodySlice = bodySlices[i];+ const oldBody = oldBodySlices[i];+ if (decoration.startIndex !== cursor) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: decoration.startIndex - cursor,+ segmentId,+ });+ }+ cursor = (decoration.startIndex);+ textX.push({+ t: TextXActionType.RETAIN,+ len: decoration.endIndex - decoration.startIndex + 1,+ segmentId,+ body: bodySlice,+ oldBody,+ coverType: UpdateDocsAttributeType.REPLACE,+ });+ cursor = cursor + (decoration.endIndex - decoration.startIndex + 1);+ });++ doMutation.params.actions = jsonX.editOp(textX.serialize());+ return doMutation;+}diff --git a/packages/docs/src/basics/custom-range-factory.ts b/packages/docs/src/basics/custom-range-factory.tsnew file mode 100644index 0000000000..024751396f--- /dev/null+++ b/packages/docs/src/basics/custom-range-factory.ts@@ -0,0 +1,217 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { CustomRangeType, DocumentDataModel, IDocumentBody, IMutationInfo, ITextRange } from '@univerjs/core';+import { DataStreamTreeTokenType, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';+import type { IAccessor } from '@wendellhu/redi';+import type { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';+import { RichTextEditingMutation } from '../commands/mutations/core-editing.mutation';+import { TextSelectionManagerService } from '../services/text-selection-manager.service';+import { getSelectionForAddCustomRange } from './selection';++interface IAddCustomRangeParam {+ unitId: string;+ range: ITextRange;+ segmentId?: string;+ rangeId: string;+ rangeType: CustomRangeType;+}++export function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocumentBody) {+ const { unitId, range, rangeId, rangeType, segmentId } = param;+ const actualRange = getSelectionForAddCustomRange(range, body);+ if (!actualRange) {+ return null;+ }++ const { startOffset: start, endOffset: end } = actualRange;+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges: undefined,+ },+ };++ const textX = new TextX();+ const jsonX = JSONX.getInstance();++ if (start > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: start,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.INSERT,+ body: {+ dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_START,+ customRanges: [+ {+ rangeId,+ rangeType,+ startIndex: 0,+ endIndex: 0,+ },+ ],+ },+ len: 1,+ line: 0,+ });++ textX.push({+ t: TextXActionType.RETAIN,+ body: {+ dataStream: '',+ },+ len: end - start,+ segmentId,+ });++ textX.push({+ t: TextXActionType.INSERT,+ body: {+ dataStream: DataStreamTreeTokenType.CUSTOM_RANGE_END,+ customRanges: [+ {+ rangeId,+ rangeType,+ startIndex: 0,+ endIndex: 0,+ },+ ],+ },+ len: 1,+ line: 0,+ });++ doMutation.params.actions = jsonX.editOp(textX.serialize());+ return doMutation;+}++interface IAddCustomRangeFactoryParam {+ segmentId?: string;+ rangeId: string;+ rangeType: CustomRangeType;+}++export function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAddCustomRangeFactoryParam) {+ const { segmentId, rangeId, rangeType } = param;+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const selection = textSelectionManagerService.getActiveRange();+ if (!selection) {+ return false;+ }++ const documentDataModel = univerInstanceService.getCurrentUnitForType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);+ if (!documentDataModel) {+ return false;+ }+ const body = documentDataModel.getBody();+ const unitId = documentDataModel.getUnitId();+ if (!body) {+ return false;+ }++ const doMutation = addCustomRangeFactory(+ {+ unitId,+ range: {+ startOffset: selection.startOffset,+ endOffset: selection.endOffset,+ collapsed: true,+ },+ rangeId,+ rangeType,+ segmentId,+ },+ body+ );++ return doMutation;+}++export interface IDeleteCustomRangeParam {+ unitId: string;+ rangeId: string;+ segmentId?: string;+}++export function deleteCustomRange(accessor: IAccessor, params: IDeleteCustomRangeParam) {+ const { unitId, rangeId, segmentId } = params;+ const univerInstanceService = accessor.get(IUniverInstanceService);++ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId);+ if (!documentDataModel) {+ return false;+ }++ const range = documentDataModel.getBody()?.customRanges?.find((r) => r.rangeId === rangeId);+ if (!range) {+ return false;+ }+ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ actions: [],+ textRanges: undefined,+ },+ };++ const { startIndex, endIndex } = range;+ const textX = new TextX();+ const jsonX = JSONX.getInstance();+ const len = endIndex - startIndex + 1;++ if (startIndex > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: startIndex,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len: 1,+ segmentId,+ line: 0,+ });++ if (len - 2 > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: len - 2,+ segmentId,+ });+ }++ textX.push({+ t: TextXActionType.DELETE,+ len: 1,+ segmentId,+ line: 0,+ });++ doMutation.params.actions = jsonX.editOp(textX.serialize());+ return doMutation;+}diff --git a/packages/docs/src/basics/custom-range.ts b/packages/docs/src/basics/custom-range.tsnew file mode 100644index 0000000000..ca28fb0916--- /dev/null+++ b/packages/docs/src/basics/custom-range.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ICustomRange } from '@univerjs/core';+import { DataStreamTreeTokenType } from '@univerjs/core';++export function isCustomRangeSplitSymbol(text: string) {+ return text === DataStreamTreeTokenType.CUSTOM_RANGE_END || text === DataStreamTreeTokenType.CUSTOM_RANGE_START;+}++export function isIntersecting(line1Start: number, line1End: number, line2Start: number, line2End: number) {+ if ((line1Start <= line2Start && line1End >= line2Start) ||+ (line1Start >= line2Start && line1Start <= line2End)) {+ return true;+ }+ return false;+}++export function shouldDeleteCustomRange(deleteStart: number, deleteLen: number, customRange: ICustomRange, dataStream: string) {+ const dataStreamSlice = dataStream.slice(customRange.startIndex + 1, customRange.endIndex);+ const start = Math.max(deleteStart - (customRange.startIndex + 1), 0);+ const end = (deleteStart + deleteLen - 1) - (customRange.startIndex + 1);++ if (end < 0) {+ return false;+ }++ if (start === 0 && end >= dataStreamSlice.length) {+ return true;+ }++ const result = dataStreamSlice.slice(0, start) + dataStreamSlice.slice(start + deleteLen);++ for (let i = 0, len = result.length; i < len; i++) {+ const letter = result[i];+ if (!isCustomRangeSplitSymbol(letter)) {+ return false;+ }+ }++ return true;+}diff --git a/packages/docs/src/basics/retain-delete-params.ts b/packages/docs/src/basics/retain-delete-params.tsindex 8e057b29ea..2ffb1befe9 100644--- a/packages/docs/src/basics/retain-delete-params.ts+++ b/packages/docs/src/basics/retain-delete-params.ts@@ -14,18 +14,40 @@* limitations under the License.*/-import { type IDeleteAction, type IRetainAction, type ITextRange, TextXActionType } from '@univerjs/core';+import type { IDeleteAction, IDocumentBody, IRetainAction, ITextRange } from '@univerjs/core';+import { TextXActionType } from '@univerjs/core';+import { isIntersecting, shouldDeleteCustomRange } from './custom-range';export function getRetainAndDeleteFromReplace(range: ITextRange,segmentId: string = '',- memoryCursor: number = 0-): Array<IRetainAction | IDeleteAction> {+ memoryCursor: number,+ body: IDocumentBody+) {const { startOffset, endOffset } = range;const dos: Array<IRetainAction | IDeleteAction> = [];-const textStart = startOffset - memoryCursor;const textEnd = endOffset - memoryCursor;+ const dataStream = body.dataStream;+ const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset));+ const toDeleteRanges = new Set(relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(startOffset, endOffset - startOffset, customRange, dataStream)));+ const retainPoints = new Set<number>();+ relativeCustomRanges?.forEach((range) => {+ if (toDeleteRanges.has(range)) {+ return;+ }++ if (range.startIndex - memoryCursor >= textStart &&+ range.startIndex - memoryCursor <= textEnd &&+ range.endIndex - memoryCursor > textEnd) {+ retainPoints.add(range.startIndex);+ }+ if (range.endIndex - memoryCursor >= textStart &&+ range.endIndex - memoryCursor <= textEnd &&+ range.startIndex < textStart) {+ retainPoints.add(range.endIndex);+ }+ });if (textStart > 0) {dos.push({@@ -35,12 +57,39 @@ export function getRetainAndDeleteFromReplace(});}- dos.push({- t: TextXActionType.DELETE,- len: textEnd - textStart,- line: 0,- segmentId,+ const sortedRetains = [...retainPoints].sort();+ let cursor = textStart;+ sortedRetains.forEach((pos) => {+ const len = pos - cursor;+ if (len > 0) {+ dos.push({+ t: TextXActionType.DELETE,+ len,+ line: 0,+ segmentId,+ });+ }+ dos.push({+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId,+ });+ cursor = pos + 1;});- return dos;+ if (cursor < textEnd) {+ dos.push({+ t: TextXActionType.DELETE,+ len: textEnd - cursor,+ line: 0,+ segmentId,+ });+ cursor = textEnd + 1;+ }++ return {+ dos,+ cursor,+ retain: retainPoints.size,+ };}diff --git a/packages/docs/src/basics/selection.ts b/packages/docs/src/basics/selection.tsnew file mode 100644index 0000000000..d53e6c812c--- /dev/null+++ b/packages/docs/src/basics/selection.ts@@ -0,0 +1,212 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { IDocumentBody, ITextRange, Nullable } from '@univerjs/core';+import { DataStreamTreeTokenType } from '@univerjs/core';+import { isCustomRangeSplitSymbol } from './custom-range';++export function normalizeSelection(selection: ITextRange) {+ const { startOffset, endOffset, collapsed } = selection;+ const start = Math.min(startOffset, endOffset);+ const end = Math.max(startOffset, endOffset);++ return {+ startOffset: start,+ endOffset: end,+ collapsed,+ };+}++export function getSelectionWithSymbolMax(selection: ITextRange, body: IDocumentBody) {+ let { startOffset, endOffset } = normalizeSelection(selection);+ while (body.dataStream[startOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {+ startOffset -= 1;+ }++ while (body.dataStream[endOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {+ endOffset += 1;+ }++ return {+ startOffset,+ endOffset,+ };+}++export function getSelectionWithNoSymbolSide(selection: ITextRange, body: IDocumentBody) {+ let { startOffset, endOffset } = normalizeSelection(selection);+ while (isCustomRangeSplitSymbol(body.dataStream[startOffset])) {+ startOffset += 1;+ }++ while (isCustomRangeSplitSymbol(body.dataStream[endOffset - 1])) {+ endOffset -= 1;+ }++ return {+ startOffset,+ endOffset,+ };+}++export function getDeleteSelection(selection: ITextRange, body: IDocumentBody) {+ let { startOffset, endOffset, collapsed } = normalizeSelection(selection);++ if (collapsed) {+ while (isCustomRangeSplitSymbol(body.dataStream[startOffset - 1])) {+ endOffset -= 1;+ startOffset -= 1;+ }++ return {+ startOffset,+ endOffset,+ collapsed,+ };+ } else {+ return {+ ...getSelectionWithSymbolMax(selection, body),+ collapsed: false,+ };+ }+}++export function getInsertSelection(selection: ITextRange, body: IDocumentBody): ITextRange {+ let { startOffset, endOffset, collapsed } = normalizeSelection(selection);++ if (collapsed) {+ while (body.dataStream[endOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {+ endOffset += 1;+ startOffset += 1;+ }++ while (body.dataStream[endOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {+ endOffset -= 1;+ startOffset -= 1;+ }++ // while (body.dataStream[endOffset - 1] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {+ // endOffset -= 1;+ // startOffset -= 1;+ // }++ // while (body.dataStream[endOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {+ // endOffset += 1;+ // startOffset += 1;+ // }++ return {+ startOffset,+ endOffset,+ collapsed,+ };+ } else {+ return {+ ...getSelectionWithSymbolMax(selection, body),+ collapsed: false,+ };+ }+}++/**+ * Ensure custom-range has a correct order,+ * when range contains range, it won't be present as intersect. <br/>+ * For Example `\s1\s2 text \s1\s2` is not allowed, expect `\s1\s2 text \s2\s1`+ */+export function getSelectionForAddCustomRange(selection: ITextRange, body: IDocumentBody): Nullable<ITextRange> {+ if (selection.startOffset === selection.endOffset) {+ return null;+ }++ const customRanges = body.customRanges;+ if (!customRanges) {+ return normalizeSelection(selection);+ }++ let { startOffset, endOffset } = getSelectionWithSymbolMax(selection, body);+ while (isCustomRangeSplitSymbol(body.dataStream[startOffset])) {+ if (body.dataStream[startOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_START) {+ const customRange = customRanges.find((range) => range.startIndex === startOffset);+ if (!customRange) {+ throw new Error('No custom-range matched');+ }+ if (customRange.endIndex === endOffset - 1) {+ return {+ startOffset,+ endOffset,+ collapsed: false,+ };+ } else if (customRange.endIndex < endOffset - 1) {+ break;+ }+ }++ startOffset += 1;+ }++ while (isCustomRangeSplitSymbol(body.dataStream[endOffset - 1])) {+ if (body.dataStream[startOffset] === DataStreamTreeTokenType.CUSTOM_RANGE_END) {+ const customRange = customRanges.find((range) => range.endIndex === endOffset - 1);+ if (!customRange) {+ throw new Error('No custom-range matched');+ }++ // but actually not possible+ if (customRange.startIndex === startOffset) {+ return {+ startOffset,+ endOffset,+ collapsed: false,+ };+ } else if (customRange.startIndex > startOffset) {+ break;+ }+ }+ endOffset -= 1;+ }++ if (endOffset <= startOffset) {+ return null;+ }++ return {+ startOffset,+ endOffset,+ collapsed: false,+ };+}+const tags = [+ DataStreamTreeTokenType.PARAGRAPH, // 段落+ DataStreamTreeTokenType.SECTION_BREAK, // 章节+ DataStreamTreeTokenType.TABLE_START, // 表格开始+ DataStreamTreeTokenType.TABLE_ROW_START, // 表格开始+ DataStreamTreeTokenType.TABLE_CELL_START, // 表格开始+ DataStreamTreeTokenType.TABLE_CELL_END, // 表格开始+ DataStreamTreeTokenType.TABLE_ROW_END, // 表格开始+ DataStreamTreeTokenType.TABLE_END, // 表格结束+ DataStreamTreeTokenType.CUSTOM_RANGE_START, // 自定义范围开始+ DataStreamTreeTokenType.CUSTOM_RANGE_END, // 自定义范围结束+ DataStreamTreeTokenType.COLUMN_BREAK, // 换列+ DataStreamTreeTokenType.PAGE_BREAK, // 换页+ DataStreamTreeTokenType.DOCS_END, // 文档结尾+ DataStreamTreeTokenType.TAB, // 制表符+ DataStreamTreeTokenType.CUSTOM_BLOCK, // 图片 mention 等不参与文档流的场景++];+export function getSelectionText(dataStream: string, start: number, end: number) {+ const text = dataStream.slice(start, end);+ return tags.reduce((res, curr) => res.replaceAll(curr, ''), text);+}diff --git a/packages/docs/src/commands/commands/break-line.command.ts b/packages/docs/src/commands/commands/break-line.command.tsindex b1c32e783e..7ec6d5c77f 100644--- a/packages/docs/src/commands/commands/break-line.command.ts+++ b/packages/docs/src/commands/commands/break-line.command.ts@@ -71,16 +71,7 @@ export const BreakLineCommand: ICommand = {}const unitId = docDataModel.getUnitId();- const { startOffset, segmentId, style } = activeRange;-- // move selection- const textRanges = [- {- startOffset: startOffset + 1,- endOffset: startOffset + 1,- style,- },- ];+ const { startOffset, segmentId } = activeRange;const paragraphs = docDataModel.getBody()?.paragraphs ?? [];const prevParagraph = paragraphs.find((p) => p.startIndex >= startOffset);@@ -93,7 +84,6 @@ export const BreakLineCommand: ICommand = {paragraphs: generateParagraphs(DataStreamTreeTokenType.PARAGRAPH, prevParagraph),},range: activeRange,- textRanges,segmentId,});diff --git a/packages/docs/src/commands/commands/clipboard.inner.command.ts b/packages/docs/src/commands/commands/clipboard.inner.command.tsindex 736148de28..846856f2a7 100644--- a/packages/docs/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs/src/commands/commands/clipboard.inner.command.ts@@ -33,11 +33,12 @@ import {TextXActionType,} from '@univerjs/core';import type { ITextRangeWithStyle } from '@univerjs/engine-render';-import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';import { TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';+import { isIntersecting, shouldDeleteCustomRange } from '../../basics/custom-range';+import { getDeleteSelection } from '../../basics/selection';export interface IInnerPasteCommandParams {segmentId: string;@@ -63,7 +64,8 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {}const docsModel = univerInstanceService.getCurrentUniverDocInstance();- if (!docsModel) {+ const originBody = docsModel?.getBody();+ if (!docsModel || !originBody) {return false;}@@ -97,7 +99,13 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {segmentId,});} else {- textX.push(...getRetainAndDeleteFromReplace(selection, segmentId, memoryCursor.cursor));+ const { dos } = getRetainAndDeleteFromReplace(selection, segmentId, memoryCursor.cursor, originBody);+ textX.push(...dos);+ // doMutation.params.textRanges = [{+ // startOffset: cursor + body.dataStream.length,+ // endOffset: cursor + body.dataStream.length,+ // collapsed,+ // }];}textX.push({@@ -204,16 +212,17 @@ export const CutContentCommand: ICommand<IInnerCutCommandParams> = {// If the selection contains line breaks,// paragraph information needs to be preserved when performing the CUT operation+// eslint-disable-next-line max-lines-per-functionfunction getRetainAndDeleteAndExcludeLineBreak(- range: ITextRange,+ selection: ITextRange,body: IDocumentBody,segmentId: string = '',memoryCursor: number = 0): Array<IRetainAction | IDeleteAction> {- const { startOffset, endOffset } = range;+ const { startOffset, endOffset } = getDeleteSelection(selection, body);const dos: Array<IRetainAction | IDeleteAction> = [];- const { paragraphs = [] } = body;+ const { paragraphs = [], dataStream } = body;const textStart = startOffset - memoryCursor;const textEnd = endOffset - memoryCursor;@@ -222,6 +231,27 @@ function getRetainAndDeleteAndExcludeLineBreak((p) => p.startIndex - memoryCursor >= textStart && p.startIndex - memoryCursor <= textEnd);+ const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, startOffset, endOffset));+ const toDeleteRanges = new Set(relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(startOffset, endOffset - startOffset, customRange, dataStream)));+ const retainPoints = new Set<number>();++ relativeCustomRanges?.forEach((range) => {+ if (toDeleteRanges.has(range)) {+ return;+ }++ if (range.startIndex - memoryCursor >= textStart &&+ range.startIndex - memoryCursor <= textEnd &&+ range.endIndex - memoryCursor > textEnd) {+ retainPoints.add(range.startIndex);+ }+ if (range.endIndex - memoryCursor >= textStart &&+ range.endIndex - memoryCursor <= textEnd &&+ range.startIndex < textStart) {+ retainPoints.add(range.endIndex);+ }+ });+if (textStart > 0) {dos.push({t: TextXActionType.RETAIN,@@ -232,36 +262,37 @@ function getRetainAndDeleteAndExcludeLineBreak(if (paragraphInRange && paragraphInRange.startIndex - memoryCursor > textStart) {const paragraphIndex = paragraphInRange.startIndex - memoryCursor;+ retainPoints.add(paragraphIndex);+ }- dos.push({- t: TextXActionType.DELETE,- len: paragraphIndex - textStart,- line: 0,- segmentId,- });-- dos.push({- t: TextXActionType.RETAIN,- len: 1,- segmentId,- });+ const sortedRetains = [...retainPoints].sort();- if (textEnd > paragraphIndex + 1) {+ let cursor = textStart;+ sortedRetains.forEach((pos) => {+ const len = pos - cursor;+ if (len > 0) {dos.push({t: TextXActionType.DELETE,- len: textEnd - paragraphIndex - 1,+ len,line: 0,segmentId,});}- } else {+ dos.push({+ t: TextXActionType.RETAIN,+ len: 1,+ segmentId,+ });+ cursor = pos + 1;+ });++ if (cursor < textEnd) {dos.push({t: TextXActionType.DELETE,- len: textEnd - textStart,+ len: textEnd - cursor,line: 0,segmentId,});}-return dos;}diff --git a/packages/docs/src/commands/commands/core-editing.command.ts b/packages/docs/src/commands/commands/core-editing.command.tsindex 013ecc6baa..0026413ab6 100644--- a/packages/docs/src/commands/commands/core-editing.command.ts+++ b/packages/docs/src/commands/commands/core-editing.command.ts@@ -15,6 +15,7 @@*/import type {+ DocumentDataModel,ICommand,IDocumentBody,IDocumentData,@@ -22,18 +23,20 @@ import type {ITextRange,UpdateDocsAttributeType,} from '@univerjs/core';-import { CommandType, ICommandService, JSONX, TextX, TextXActionType } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType, UniverInstanceType } from '@univerjs/core';import type { ITextRangeWithStyle } from '@univerjs/engine-render';-import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';+import { isIntersecting, shouldDeleteCustomRange } from '../../basics/custom-range';+import { TextSelectionManagerService } from '../../services/text-selection-manager.service';+import { getInsertSelection } from '../../basics/selection';export interface IInsertCommandParams {unitId: string;body: IDocumentBody;range: ITextRange;- textRanges: ITextRangeWithStyle[];+ textRanges?: ITextRangeWithStyle[];segmentId?: string;}@@ -50,15 +53,35 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {handler: async (accessor, params: IInsertCommandParams) => {const commandService = accessor.get(ICommandService);- const { range, segmentId, body, unitId, textRanges } = params;- const { startOffset, collapsed } = range;+ const { range, segmentId, body, unitId, textRanges: propTextRanges } = params;+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);+ const originBody = doc?.getBody();+ const activeRange = textSelectionManagerService.getActiveRange();+ if (activeRange == null) {+ return false;+ }+ if (!originBody) {+ return false;+ }+ const actualRange = getInsertSelection(range, originBody);+ const { startOffset, collapsed } = actualRange;+ const textRanges = [+ {+ startOffset: startOffset + body.dataStream.length,+ endOffset: startOffset + body.dataStream.length,+ style: activeRange.style,+ collapsed,+ },+ ];const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {id: RichTextEditingMutation.id,params: {unitId,actions: [],- textRanges,+ textRanges: propTextRanges ?? textRanges,debounce: true,},};@@ -75,7 +98,13 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {});}} else {- textX.push(...getRetainAndDeleteFromReplace(range, segmentId));+ const { dos, retain } = getRetainAndDeleteFromReplace(actualRange, segmentId, 0, originBody);+ textX.push(...dos);+ doMutation.params.textRanges = [{+ startOffset: startOffset + body.dataStream.length + retain,+ endOffset: startOffset + body.dataStream.length + retain,+ collapsed,+ }];}textX.push({@@ -85,7 +114,6 @@ export const InsertCommand: ICommand<IInsertCommandParams> = {line: 0,segmentId,});-doMutation.params.actions = jsonX.editOp(textX.serialize());const result = commandService.syncExecuteCommand<@@ -106,7 +134,6 @@ export interface IDeleteCommandParams {unitId: string;range: ITextRange;direction: DeleteDirection;- textRanges: ITextRangeWithStyle[];len?: number;segmentId?: string;}@@ -116,22 +143,45 @@ export interface IDeleteCommandParams {*/export const DeleteCommand: ICommand<IDeleteCommandParams> = {id: 'doc.command.delete-text',-type: CommandType.COMMAND,-handler: async (accessor, params: IDeleteCommandParams) => {const commandService = accessor.get(ICommandService);-- const { range, segmentId, unitId, direction, textRanges, len = 1 } = params;-+ const { range, segmentId, unitId, direction, len = 1 } = params;+ const univerInstanceService = accessor.get(IUniverInstanceService);const { startOffset } = range;+ const documentDataModel = univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);+ if (!documentDataModel) {+ return false;+ }+ const body = documentDataModel.getBody();+ if (!body) {+ return false;+ }+ const dataStream = body.dataStream;+ const start = direction === DeleteDirection.LEFT ? startOffset - len : startOffset;+ const end = start + len - 1;+ const relativeCustomRanges = body.customRanges?.filter((customRange) => isIntersecting(customRange.startIndex, customRange.endIndex, start, end));+ const toDeleteRanges = relativeCustomRanges?.filter((customRange) => shouldDeleteCustomRange(start, len, customRange, dataStream));+ const deleteIndexes: number[] = [];+ for (let i = 0; i < len; i++) {+ deleteIndexes.push(start + i);+ }+ toDeleteRanges?.forEach((range) => {+ deleteIndexes.push(range.startIndex, range.endIndex);+ });+ deleteIndexes.sort();+ const deleteStart = deleteIndexes[0];const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {id: RichTextEditingMutation.id,params: {unitId,actions: [],- textRanges,+ textRanges: [{+ startOffset: deleteStart,+ endOffset: deleteStart,+ collapsed: true,+ }],debounce: true,},};@@ -139,21 +189,25 @@ export const DeleteCommand: ICommand<IDeleteCommandParams> = {const textX = new TextX();const jsonX = JSONX.getInstance();- if (startOffset > 0) {+ let cursor = 0;+ for (let i = 0; i < deleteIndexes.length; i++) {+ const deleteIndex = deleteIndexes[i];+ if (deleteIndex - cursor > 0) {+ textX.push({+ t: TextXActionType.RETAIN,+ len: deleteIndex - cursor,+ segmentId,+ });+ }textX.push({- t: TextXActionType.RETAIN,- len: direction === DeleteDirection.LEFT ? startOffset - len : startOffset,+ t: TextXActionType.DELETE,+ len: 1,segmentId,+ line: 0,});+ cursor = deleteIndex + 1;}- textX.push({- t: TextXActionType.DELETE,- len,- line: 0,- segmentId,- });-doMutation.params.actions = jsonX.editOp(textX.serialize());const result = commandService.syncExecuteCommand<diff --git a/packages/docs/src/commands/commands/delete.command.ts b/packages/docs/src/commands/commands/delete.command.tsindex fce46dda91..1f3e57c360 100644--- a/packages/docs/src/commands/commands/delete.command.ts+++ b/packages/docs/src/commands/commands/delete.command.ts@@ -24,12 +24,14 @@ import {TextXActionType,UpdateDocsAttributeType,} from '@univerjs/core';-import { getParagraphByGlyph, hasListGlyph, type IActiveTextRange, isFirstGlyph, isIndentByGlyph, type ITextRangeWithStyle, type TextRange } from '@univerjs/engine-render';+import type { IActiveTextRange, ITextRangeWithStyle, TextRange } from '@univerjs/engine-render';+import { getParagraphByGlyph, hasListGlyph, isFirstGlyph, isIndentByGlyph } from '@univerjs/engine-render';import type { ITextActiveRange } from '../../services/text-selection-manager.service';import { TextSelectionManagerService } from '../../services/text-selection-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';+import { getDeleteSelection, getInsertSelection } from '../../basics/selection';import { getCommandSkeleton } from '../util';import { CutContentCommand } from './clipboard.inner.command';import { DeleteCommand, DeleteDirection, UpdateCommand } from './core-editing.command';@@ -38,7 +40,8 @@ import { DeleteCommand, DeleteDirection, UpdateCommand } from './core-editing.coexport const DeleteLeftCommand: ICommand = {id: 'doc.command.delete-left',type: CommandType.COMMAND,- // eslint-disable-next-line max-lines-per-function++ // eslint-disable-next-line max-lines-per-function, complexityhandler: async (accessor) => {const textSelectionManagerService = accessor.get(TextSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);@@ -47,7 +50,8 @@ export const DeleteLeftCommand: ICommand = {let result = true;const docDataModel = univerInstanceService.getCurrentUniverDocInstance();- if (!docDataModel) {+ const body = docDataModel?.getBody();+ if (!docDataModel || !body) {return false;}@@ -60,8 +64,9 @@ export const DeleteLeftCommand: ICommand = {return false;}- const { startOffset, collapsed, segmentId, style } = activeRange;-+ const actualRange = getDeleteSelection(activeRange, body);+ const { startOffset, collapsed } = actualRange;+ const { segmentId, style } = activeRange;const curGlyph = skeleton.findNodeByCharIndex(startOffset);// is in bullet list?@@ -144,34 +149,26 @@ export const DeleteLeftCommand: ICommand = {if (preGlyph == null) {return true;}-if (preGlyph.content === '\r') {result = await commandService.executeCommand(MergeTwoParagraphCommand.id, {direction: DeleteDirection.LEFT,- range: activeRange,+ range: actualRange,});} else {cursor -= preGlyph.count;-- const textRanges = [- {- startOffset: cursor,- endOffset: cursor,- style,- },- ];-result = await commandService.executeCommand(DeleteCommand.id, {unitId: docDataModel.getUnitId(),- range: activeRange,+ range: actualRange,segmentId,direction: DeleteDirection.LEFT,len: preGlyph.count,- textRanges,});}} else {- const textRanges = getTextRangesWhenDelete(activeRange, ranges);+ const textRanges = getTextRangesWhenDelete({+ ...activeRange,+ ...actualRange,+ }, ranges);// If the selection is not closed, the effect of Delete and// BACKSPACE is the same as CUT, so the CUT command is executed.result = await commandService.executeCommand(CutContentCommand.id, {@@ -202,13 +199,20 @@ export const DeleteRightCommand: ICommand = {const activeRange = textSelectionManagerService.getActiveRange();const ranges = textSelectionManagerService.getSelections();+const skeleton = docSkeletonManagerService?.getSkeleton();if (activeRange == null || skeleton == null || ranges == null) {return false;}- const { startOffset, collapsed, segmentId, style } = activeRange;+ const body = docDataModel?.getBody();+ if (!docDataModel || !body) {+ return false;+ }+ const actualRange = getInsertSelection(activeRange, body);+ const { startOffset, collapsed } = actualRange;+ const { segmentId, style } = activeRange;// No need to delete when the cursor is at the last position of the last paragraph.if (startOffset === docDataModel.getBody()!.dataStream.length - 2 && collapsed) {return true;@@ -218,6 +222,7 @@ export const DeleteRightCommand: ICommand = {if (collapsed === true) {const needDeleteSpan = skeleton.findNodeByCharIndex(startOffset)!;+ // skip custom-range-split-symbolif (needDeleteSpan.content === '\r') {result = await commandService.executeCommand(MergeTwoParagraphCommand.id, {direction: DeleteDirection.RIGHT,@@ -234,7 +239,11 @@ export const DeleteRightCommand: ICommand = {result = await commandService.executeCommand(DeleteCommand.id, {unitId: docDataModel.getUnitId(),- range: activeRange,+ range: {+ startOffset,+ endOffset: startOffset,+ collapsed,+ } as ITextActiveRange,segmentId,direction: DeleteDirection.RIGHT,textRanges,diff --git a/packages/docs/src/commands/commands/ime-input.command.ts b/packages/docs/src/commands/commands/ime-input.command.tsindex f571edfb2f..722ef79f9d 100644--- a/packages/docs/src/commands/commands/ime-input.command.ts+++ b/packages/docs/src/commands/commands/ime-input.command.ts@@ -14,14 +14,15 @@* limitations under the License.*/-import type { ICommand, ICommandInfo } from '@univerjs/core';-import { CommandType, ICommandService, JSONX, TextX, TextXActionType } from '@univerjs/core';+import type { DocumentDataModel, ICommand, ICommandInfo } from '@univerjs/core';+import { CommandType, ICommandService, IUniverInstanceService, JSONX, TextX, TextXActionType } from '@univerjs/core';import type { ITextRangeWithStyle } from '@univerjs/engine-render';import { getRetainAndDeleteFromReplace } from '../../basics/retain-delete-params';import { IMEInputManagerService } from '../../services/ime-input-manager.service';import type { IRichTextEditingMutationParams } from '../mutations/core-editing.mutation';import { RichTextEditingMutation } from '../mutations/core-editing.mutation';+import { getInsertSelection } from '../../basics/selection';export interface IIMEInputCommandParams {unitId: string;@@ -36,15 +37,21 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {type: CommandType.COMMAND,+ // eslint-disable-next-line max-lines-per-functionhandler: async (accessor, params: IIMEInputCommandParams) => {const { unitId, newText, oldTextLen, isCompositionEnd, isCompositionStart } = params;+ // console.log('===ime', params);const commandService = accessor.get(ICommandService);const imeInputManagerService = accessor.get(IMEInputManagerService);const previousActiveRange = imeInputManagerService.getActiveRange();-- if (previousActiveRange == null) {+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const doc = univerInstanceService.getUnit<DocumentDataModel>(unitId);+ const body = doc?.getBody();+ if (!previousActiveRange || !body) {return false;}+ const insertRange = getInsertSelection(previousActiveRange, body);+ Object.assign(previousActiveRange, insertRange);const { startOffset, style, segmentId } = previousActiveRange;const len = newText.length;@@ -70,14 +77,23 @@ export const IMEInputCommand: ICommand<IIMEInputCommandParams> = {const textX = new TextX();const jsonX = JSONX.getInstance();+ let memoryCursor = 0;if (!previousActiveRange.collapsed && isCompositionStart) {- textX.push(...getRetainAndDeleteFromReplace(previousActiveRange, segmentId));+ const { dos, retain, cursor } = getRetainAndDeleteFromReplace(previousActiveRange, segmentId, 0, body);+ textX.push(...dos);+ doMutation.params!.textRanges = [{+ startOffset: startOffset + len + retain,+ endOffset: startOffset + len + retain,+ collapsed: true,+ }];+ memoryCursor = cursor;} else {textX.push({t: TextXActionType.RETAIN,len: startOffset,segmentId,});+ memoryCursor = startOffset;}if (oldTextLen > 0) {diff --git a/packages/docs/src/commands/mutations/core-editing.mutation.ts b/packages/docs/src/commands/mutations/core-editing.mutation.tsindex 87f61db85e..65d1cd4ed4 100644--- a/packages/docs/src/commands/mutations/core-editing.mutation.ts+++ b/packages/docs/src/commands/mutations/core-editing.mutation.ts@@ -95,12 +95,11 @@ export const RichTextEditingMutation: IMutation<IRichTextEditingMutationParams,// Step 1: Update Doc Data Model.const undoActions = JSONX.invertWithDoc(actions, documentDataModel.getSnapshot());documentDataModel.apply(actions);-// Step 2: Update Doc View Model.+ // console.log('===edit end', { actions, undoActions }, Tools.deepClone(documentDataModel.getBody()));const segmentDocumentDataModel = documentDataModel.getSelfOrHeaderFooterModel(segmentId);const segmentViewModel = documentViewModel.getSelfOrHeaderFooterViewModel(segmentId);segmentViewModel.reset(segmentDocumentDataModel);-// Step 3: Update cursor & selection.// Make sure update cursor & selection after doc skeleton is calculated.if (!noNeedSetTextRange && textRanges && trigger != null) {diff --git a/packages/docs/src/controllers/move-cursor.controller.ts b/packages/docs/src/controllers/move-cursor.controller.tsindex 0ad442bf90..469bdcf7df 100644--- a/packages/docs/src/controllers/move-cursor.controller.ts+++ b/packages/docs/src/controllers/move-cursor.controller.ts@@ -194,6 +194,7 @@ export class MoveCursorController extends Disposable {}}+ // eslint-disable-next-line max-lines-per-functionprivate _handleMoveCursor(direction: Direction) {const activeRange = this._textSelectionManagerService.getActiveRange();const allRanges = this._textSelectionManagerService.getSelections();diff --git a/packages/docs/src/controllers/normal-input.controller.ts b/packages/docs/src/controllers/normal-input.controller.tsindex 5397a01ed0..b9fdc6e4b2 100644--- a/packages/docs/src/controllers/normal-input.controller.ts+++ b/packages/docs/src/controllers/normal-input.controller.ts@@ -75,17 +75,7 @@ export class NormalInputController extends Disposable {return;}- const { startOffset, segmentId, style } = activeRange;-- const len = content.length;-- const textRanges = [- {- startOffset: startOffset + len,- endOffset: startOffset + len,- style,- },- ];+ const { segmentId } = activeRange;await this._commandService.executeCommand(InsertCommand.id, {unitId,@@ -93,7 +83,6 @@ export class NormalInputController extends Disposable {dataStream: content,},range: activeRange,- textRanges,segmentId,});});diff --git a/packages/docs/src/doc-plugin.ts b/packages/docs/src/doc-plugin.tsindex cdda5d0e19..6202d2db9e 100644--- a/packages/docs/src/doc-plugin.ts+++ b/packages/docs/src/doc-plugin.ts@@ -137,11 +137,11 @@ export class UniverDocsPlugin extends Plugin {},],[TextSelectionManagerService],-// controllers[NormalInputController],[IMEInputController],[MoveCursorController],+] as Dependency[]).forEach((d) => docInjector.add(d));}diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex e462c79bb0..8faded834c 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -14,6 +14,7 @@* limitations under the License.*/+export { getSelectionText, getDeleteSelection, getInsertSelection } from './basics/selection';export type { IDocObjectParam } from './basics/component-tools';export { getDocObject, neoGetDocObject, getDocObjectById } from './basics/component-tools';export * from './basics/docs-view-key';@@ -64,6 +65,10 @@ export {} from './commands/commands/paragraph-align.command';export { ReplaceContentCommand, CoverContentCommand } from './commands/commands/replace-content.command';export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';+export { addCustomRangeFactory, addCustomRangeBySelectionFactory, deleteCustomRange } from './basics/custom-range-factory';+export { addCustomDecorationBySelectionFactory, addCustomDecorationFactory, deleteCustomDecorationFactory } from './basics/custom-decoration-factory';+export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';+export { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';export {RichTextEditingMutation,diff --git a/packages/docs/src/services/doc-interceptor/doc-interceptor.service.ts b/packages/docs/src/services/doc-interceptor/doc-interceptor.service.tsnew file mode 100644index 0000000000..00c0228bf4--- /dev/null+++ b/packages/docs/src/services/doc-interceptor/doc-interceptor.service.ts@@ -0,0 +1,102 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { DocumentDataModel, ICustomDecorationForInterceptor, ICustomRangeForInterceptor, IInterceptor, Nullable } from '@univerjs/core';+import { composeInterceptors, Disposable, DisposableCollection, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, LifecycleStages, OnLifecycle, remove, toDisposable } from '@univerjs/core';+import type { DocumentViewModel, IRenderContext, IRenderModule } from '@univerjs/engine-render';+import { Inject } from '@wendellhu/redi';+import { DocSkeletonManagerService } from '../doc-skeleton-manager.service';+import { DOC_INTERCEPTOR_POINT } from './interceptor-const';++@OnLifecycle(LifecycleStages.Starting, DocInterceptorService)+export class DocInterceptorService extends Disposable implements IRenderModule {+ private _interceptorsByName: Map<string, Array<IInterceptor<unknown, unknown>>> = new Map();++ constructor(+ private readonly _context: IRenderContext<DocumentDataModel>,+ @Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService+ ) {+ super();++ this.disposeWithMe(this._docSkeletonManagerService.currentViewModel$.subscribe((viewModel) => {+ if (viewModel) {+ const unitId = viewModel.getDataModel().getUnitId();+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY || unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ return;+ }++ this.interceptDocumentViewModel(viewModel);+ }+ }));++ this.disposeWithMe(this.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {+ priority: -1,+ handler: (data, pos, next) => {+ return next(data);+ },+ }));+ }++ intercept<T extends IInterceptor<any, any>>(name: T, interceptor: T) {+ const key = name as unknown as string;+ if (!this._interceptorsByName.has(key)) {+ this._interceptorsByName.set(key, []);+ }+ const interceptors = this._interceptorsByName.get(key)!;+ interceptors.push(interceptor);++ this._interceptorsByName.set(+ key,+ interceptors.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))+ );++ return this.disposeWithMe(toDisposable(() => remove(this._interceptorsByName.get(key)!, interceptor)));+ }++ fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>) {+ const key = name as unknown as string;+ const interceptors = this._interceptorsByName.get(key) as unknown as Array<typeof name>;+ return composeInterceptors<T, C>(interceptors || []);+ }++ interceptDocumentViewModel(viewModel: DocumentViewModel) {+ const disposableCollection = new DisposableCollection();+ disposableCollection.add(viewModel.registerCustomRangeInterceptor({+ getCustomRange: (index: number): Nullable<ICustomRangeForInterceptor> => {+ return this.fetchThroughInterceptors(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE)(+ viewModel.getCustomRangeRaw(index),+ {+ index,+ unitId: viewModel.getDataModel().getUnitId(),+ customRanges: viewModel.getDataModel().getCustomRanges() ?? [],+ }+ );+ },+ getCustomDecoration: (index: number): Nullable<ICustomDecorationForInterceptor> => {+ return this.fetchThroughInterceptors(DOC_INTERCEPTOR_POINT.CUSTOM_DECORATION)(+ viewModel.getCustomDecorationRaw(index),+ {+ index,+ unitId: viewModel.getDataModel().getUnitId(),+ customDecorations: viewModel.getDataModel().getCustomDecorations() ?? [],+ }+ );+ },+ }));++ return disposableCollection;+ }+}diff --git a/packages/docs/src/services/doc-interceptor/interceptor-const.ts b/packages/docs/src/services/doc-interceptor/interceptor-const.tsnew file mode 100644index 0000000000..822a9494fb--- /dev/null+++ b/packages/docs/src/services/doc-interceptor/interceptor-const.ts@@ -0,0 +1,26 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ICustomDecoration, ICustomDecorationForInterceptor, ICustomRange, ICustomRangeForInterceptor } from '@univerjs/core';+import { createInterceptorKey } from '@univerjs/core';++const CUSTOM_RANGE = createInterceptorKey<ICustomRangeForInterceptor, { index: number; unitId: string; customRanges: ICustomRange[] }>('CUSTOM_RANGE');+const CUSTOM_DECORATION = createInterceptorKey<ICustomDecorationForInterceptor, { index: number; unitId: string; customDecorations: ICustomDecoration[] }>('CUSTOM_DECORATION');++export const DOC_INTERCEPTOR_POINT = {+ CUSTOM_RANGE,+ CUSTOM_DECORATION,+};diff --git a/packages/docs/src/services/doc-skeleton-manager.service.ts b/packages/docs/src/services/doc-skeleton-manager.service.tsindex 951e8026dd..79332b1a6b 100644--- a/packages/docs/src/services/doc-skeleton-manager.service.ts+++ b/packages/docs/src/services/doc-skeleton-manager.service.ts@@ -36,6 +36,9 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMoprivate readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();+ private readonly _currentViewModel$ = new BehaviorSubject<Nullable<DocumentViewModel>>(null);+ readonly currentViewModel$ = this._currentViewModel$.asObservable();+constructor(private readonly _context: IRenderContext<DocumentDataModel>,@Inject(LocaleService) private readonly _localeService: LocaleService,@@ -92,6 +95,7 @@ export class DocSkeletonManagerService extends RxDisposable implements IRenderMothis._currentSkeletonBefore$.next(skeleton);this._currentSkeleton$.next(skeleton);+ this._currentViewModel$.next(this._docViewModel);}getSkeleton(): DocumentSkeleton {diff --git a/packages/docs/src/services/doc-view-model-manager.service.ts b/packages/docs/src/services/doc-view-model-manager.service.tsindex d51799ef89..f0b0c02340 100644--- a/packages/docs/src/services/doc-view-model-manager.service.ts+++ b/packages/docs/src/services/doc-view-model-manager.service.ts@@ -18,7 +18,7 @@ import type { DocumentDataModel, Nullable } from '@univerjs/core';import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, IUniverInstanceService, RxDisposable, UniverInstanceType } from '@univerjs/core';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { DocumentViewModel } from '@univerjs/engine-render';-import { BehaviorSubject, takeUntil } from 'rxjs';+import { BehaviorSubject, Subject, takeUntil } from 'rxjs';export interface IDocumentViewModelManagerParam {unitId: string;@@ -37,6 +37,9 @@ export class DocViewModelManagerService extends RxDisposable implements IRenderMprivate readonly _currentDocViewModel$ = new BehaviorSubject<Nullable<IDocumentViewModelManagerParam>>(null);readonly currentDocViewModel$ = this._currentDocViewModel$.asObservable();+ private readonly _docViewModelAdd$ = new Subject<DocumentViewModel>();+ readonly docViewModelAdd$ = this._docViewModelAdd$.asObservable();+constructor(private readonly _context: IRenderContext<DocumentDataModel>,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService@@ -123,6 +126,9 @@ export class DocViewModelManagerService extends RxDisposable implements IRenderM}private _buildDocViewModel(documentDataModel: DocumentDataModel) {- return new DocumentViewModel(documentDataModel);+ const model = new DocumentViewModel(documentDataModel);+ this._docViewModelAdd$.next(model);++ return model;}}diff --git a/packages/engine-render/src/basics/i-document-skeleton-cached.ts b/packages/engine-render/src/basics/i-document-skeleton-cached.tsindex 74aae0ddec..b857f38dde 100644--- a/packages/engine-render/src/basics/i-document-skeleton-cached.ts+++ b/packages/engine-render/src/basics/i-document-skeleton-cached.ts@@ -181,6 +181,7 @@ export interface IDocumentSkeletonGlyph {left: number; // leftcount: number; // count, content length,default 1content: string; // content+ raw: string;adjustability: IAdjustability; // The adjustability of the glyph.isJustifiable: boolean; // Whether this glyph is justifiable for CJK scripts.ts?: ITextStyle; // text stylediff --git a/packages/engine-render/src/components/docs/extensions/line.ts b/packages/engine-render/src/components/docs/extensions/line.tsindex f5c21e642c..f66c28b751 100644--- a/packages/engine-render/src/components/docs/extensions/line.ts+++ b/packages/engine-render/src/components/docs/extensions/line.ts@@ -49,14 +49,18 @@ export class Line extends docExtension {const { sp: strikeoutPosition, spo, sbo, bd } = bBox;const scale = getScale(parentScale);const DELTA = 0.5;- const { ul: underline, st: strikethrough, ol: overline, va: baselineOffset } = textStyle;+ const { ul: underline, st: strikethrough, ol: overline, va: baselineOffset, bbl: bottomBorderLine } = textStyle;if (underline) {const startY = asc + dsc;-this._drawLine(ctx, glyph, underline, startY, scale);}+ if (bottomBorderLine) {+ const startY = asc + dsc + 3;+ this._drawLine(ctx, glyph, bottomBorderLine, startY, scale, 2);+ }+if (strikethrough) {// strikethrough position is the middle of bounding box ascent and descent.let startY = asc + bd - strikeoutPosition - DELTA;@@ -93,7 +97,8 @@ export class Line extends docExtension {glyph: IDocumentSkeletonGlyph,line: ITextDecoration,startY: number,- _scale: number+ _scale: number,+ lineWidth = 1) {let { s: show, cl: colorStyle, t: lineType, c = BooleanNumber.TRUE } = line;@@ -125,6 +130,7 @@ export class Line extends docExtension {const color =(c === BooleanNumber.TRUE ? getColorStyle(glyph.ts?.cl) : getColorStyle(colorStyle)) || COLOR_BLACK_RGB;ctx.strokeStyle = color;+ ctx.lineWidth = lineWidth;this._setLineType(ctx, lineType || TextDecoration.SINGLE);diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.tsindex 74d5d4168d..144bb4930d 100644--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts@@ -111,6 +111,7 @@ export function createSkeletonCustomBlockGlyph(config: IFontCreateConfig, glyphWreturn {content: '',+ raw: content,ts: textStyle,fontStyle,width: glyphWidth,@@ -165,6 +166,7 @@ export function _createSkeletonWordOrLetter(if (skipWidthList.indexOf(content) > -1) {return {content: '',+ raw: content,ts: textStyle,fontStyle,width: 0,@@ -237,6 +239,7 @@ export function _createSkeletonWordOrLetter(isJustifiable: isJustifiable(content),adjustability: baseAdjustability(content, width),count: content.length,+ raw: content,};}@@ -288,6 +291,7 @@ export function createSkeletonBulletGlyph(streamType: DT.LETTER,// Deliberately set to 0 so that there is no need to count when calculating the cursor.count: 0,+ raw: content,};}diff --git a/packages/engine-render/src/components/docs/layout/style/custom-decoration.ts b/packages/engine-render/src/components/docs/layout/style/custom-decoration.tsnew file mode 100644index 0000000000..0e0f4c4954--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/style/custom-decoration.ts@@ -0,0 +1,35 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ICustomDecorationForInterceptor, ITextStyle, Nullable } from '@univerjs/core';+import { BooleanNumber, CustomDecorationType } from '@univerjs/core';++export function getCustomDecorationStyle(customDecoration: ICustomDecorationForInterceptor): Nullable<ITextStyle> {+ if (customDecoration.type === CustomDecorationType.COMMENT) {+ return {+ bbl: {+ s: BooleanNumber.TRUE,+ cl: {+ rgb: '#fcdf7e',+ },+ c: BooleanNumber.FALSE,+ },+ ...customDecoration.active ? { bg: { rgb: '#faedc2' } } : null,+ };+ }++ return null;+}diff --git a/packages/engine-render/src/components/docs/layout/style/custom-range.ts b/packages/engine-render/src/components/docs/layout/style/custom-range.tsnew file mode 100644index 0000000000..3b44e4a860--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/style/custom-range.ts@@ -0,0 +1,35 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { ICustomRangeForInterceptor, ITextStyle, Nullable } from '@univerjs/core';+import { BooleanNumber, CustomRangeType } from '@univerjs/core';++export function getCustomRangeStyle(customRange: ICustomRangeForInterceptor): Nullable<ITextStyle> {+ if (customRange.rangeType === CustomRangeType.COMMENT) {+ return {+ bbl: {+ s: BooleanNumber.TRUE,+ cl: {+ rgb: '#fcdf7e',+ },+ c: BooleanNumber.FALSE,+ },+ ...customRange.active ? { bg: { rgb: '#faedc2' } } : null,+ };+ }++ return null;+}diff --git a/packages/engine-render/src/components/docs/layout/tools.ts b/packages/engine-render/src/components/docs/layout/tools.tsindex 22ba36a59d..3eb8e4cc4d 100644--- a/packages/engine-render/src/components/docs/layout/tools.ts+++ b/packages/engine-render/src/components/docs/layout/tools.ts@@ -61,6 +61,7 @@ import type { DataStreamTreeNode } from '../view-model/data-stream-tree-node';import type { DocumentViewModel } from '../view-model/document-view-model';import type { Hyphen } from './hyphenation/hyphen';import type { LanguageDetector } from './hyphenation/language-detector';+import { getCustomDecorationStyle } from './style/custom-decoration';export function getLastPage(pages: IDocumentSkeletonPage[]) {return pages[pages.length - 1];@@ -760,16 +761,19 @@ export function getFontCreateConfig(const textRun = isRenderStyle === BooleanNumber.FALSE? { ts: {}, st: 0, ed: 0 }: bodyModel.getTextRun(index + startIndex) || { ts: {}, st: 0, ed: 0 };+ const customDecoration = bodyModel.getCustomDecoration(index + startIndex);+ const showCustomDecoration = customDecoration && (customDecoration.show !== false);+ const customDecorationStyle = showCustomDecoration ? getCustomDecorationStyle(customDecoration) : null;+const { st, ed } = textRun;let { ts: textStyle = {} } = textRun;const cache = fontCreateConfigCache.getValue(st, ed);- if (cache) {+ if (cache && !customDecoration) {return cache;}const { snapToGrid = BooleanNumber.TRUE } = paragraphStyle;-- textStyle = { ...documentTextStyle, ...textStyle };+ textStyle = { ...documentTextStyle, ...textStyle, ...customDecorationStyle };const fontStyle = getFontStyleString(textStyle, localeService);@@ -789,7 +793,9 @@ export function getFontCreateConfig(pageWidth,};- fontCreateConfigCache.setValue(st, ed, result);+ if (!showCustomDecoration) {+ fontCreateConfigCache.setValue(st, ed, result);+ }return result;}diff --git a/packages/engine-render/src/components/docs/view-model/document-view-model.ts b/packages/engine-render/src/components/docs/view-model/document-view-model.tsindex 86900ae920..e6b3053824 100644--- a/packages/engine-render/src/components/docs/view-model/document-view-model.ts+++ b/packages/engine-render/src/components/docs/view-model/document-view-model.ts@@ -14,13 +14,20 @@* limitations under the License.*/-import type { IDocumentBody, ITextRun, Nullable } from '@univerjs/core';-import { DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentDataModel } from '@univerjs/core';+import type { ICustomDecorationForInterceptor, ICustomRangeForInterceptor, IDocumentBody, ITextRun, Nullable } from '@univerjs/core';+import { DataStreamTreeNodeType, DataStreamTreeTokenType, DocumentDataModel, toDisposable } from '@univerjs/core';import type { IDisposable } from '@wendellhu/redi';import { DataStreamTreeNode } from './data-stream-tree-node';+export interface ICustomRangeInterceptor {+ getCustomRange: (index: number) => Nullable<ICustomRangeForInterceptor>;+ getCustomDecoration: (index: number) => Nullable<ICustomDecorationForInterceptor>;+}+export class DocumentViewModel implements IDisposable {+ private _interceptor: Nullable<ICustomRangeInterceptor> = null;+children: DataStreamTreeNode[] = [];private _sectionBreakCurrentIndex = 0;@@ -49,6 +56,11 @@ export class DocumentViewModel implements IDisposable {this._buildHeaderFooterViewModel();}+ registerCustomRangeInterceptor(interceptor: ICustomRangeInterceptor): IDisposable {+ this._interceptor = interceptor;+ return toDisposable(() => this._interceptor = null);+ }+dispose(): void {this.children.forEach((child) => {child.dispose();@@ -369,11 +381,12 @@ export class DocumentViewModel implements IDisposable {}}- getCustomRange(index: number) {+ getCustomRangeRaw(index: number) {const customRanges = this.getBody()!.customRanges;if (customRanges == null) {return;}+for (let i = 0, customRangesLen = customRanges.length; i < customRangesLen; i++) {const customRange = customRanges[i];if (index >= customRange.startIndex && index <= customRange.endIndex) {@@ -382,6 +395,36 @@ export class DocumentViewModel implements IDisposable {}}+ getCustomRange(index: number): Nullable<ICustomRangeForInterceptor> {+ if (this._interceptor) {+ return this._interceptor.getCustomRange(index);+ }++ return this.getCustomRangeRaw(index);+ }++ getCustomDecorationRaw(index: number) {+ const customDecorations = this.getBody()!.customDecorations;+ if (customDecorations == null) {+ return;+ }++ for (let i = 0, customDecorationsLen = customDecorations.length; i < customDecorationsLen; i++) {+ const customDecoration = customDecorations[i];+ if (index >= customDecoration.startIndex && index <= customDecoration.endIndex) {+ return customDecoration;+ }+ }+ }++ getCustomDecoration(index: number): Nullable<ICustomDecorationForInterceptor> {+ if (this._interceptor) {+ return this._interceptor.getCustomDecoration(index);+ }++ return this.getCustomDecorationRaw(index);+ }+protected _transformToTree(dataStream: string) {const dataStreamLen = dataStream.length;diff --git a/packages/facade/src/apis/docs/f-document.ts b/packages/facade/src/apis/docs/f-document.tsindex e47f744e3e..d47a2883bd 100644--- a/packages/facade/src/apis/docs/f-document.ts+++ b/packages/facade/src/apis/docs/f-document.ts@@ -78,16 +78,7 @@ export class FDocument {segmentId: '',};- const { startOffset, segmentId } = activeRange;-- const len = text.length;-- const textRanges = [- {- startOffset: startOffset + len,- endOffset: startOffset + len,- },- ];+ const { segmentId } = activeRange;return this._commandService.executeCommand(InsertCommand.id, {unitId,@@ -95,7 +86,6 @@ export class FDocument {dataStream: text,},range: activeRange,- textRanges,segmentId,});}diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsxindex 9d40084d5a..dd667071a4 100644--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx@@ -220,7 +220,7 @@ export const CellLinkEdit = () => {subUnitId: editing.subUnitId,});- const GAP = 5;+ const GAP = 1;await commandService.executeCommand(ScrollToRangeOperation.id, {range: {startRow: Math.max(editing.row - GAP, 0),diff --git a/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts b/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.tsindex ac0ea0ff43..d7f179c22b 100644--- a/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts+++ b/packages/sheets-thread-comment-base/src/controllers/sheets-thread-comment-ref-range.controller.ts@@ -72,6 +72,7 @@ export class SheetsThreadCommentRefRangeController extends Disposable {unitId,subUnitId,comment,+ sync: true,} as IAddCommentMutationParams,}],};@@ -186,6 +187,10 @@ export class SheetsThreadCommentRefRangeController extends Disposable {const { unitId, subUnitId } = option;switch (option.type) {case 'add': {+ if (option.payload.parentId) {+ return;+ }+const comment = {...option.payload,row: option.row,diff --git a/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts b/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.tsindex df32e58467..879ef674a9 100644--- a/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts+++ b/packages/sheets-thread-comment-base/src/models/sheets-thread-comment.model.ts@@ -27,7 +27,7 @@ export type SheetCommentUpdate = CommentUpdate & {};export class SheetsThreadCommentModel extends Disposable {- private _matrixMap: Map<string, Map<string, ObjectMatrix<string>>> = new Map();+ private _matrixMap: Map<string, Map<string, ObjectMatrix<Set<string>>>> = new Map();private _locationMap: Map<string, Map<string, Map<string, { row: number; column: number }>>> = new Map();private _commentUpdate$ = new Subject<SheetCommentUpdate>();@@ -80,6 +80,24 @@ export class SheetsThreadCommentModel extends Disposable {return subUnitMap;}+ private _addCommentToMatrix(matrix: ObjectMatrix<Set<string>>, row: number, column: number, commentId: string) {+ const current = matrix.getValue(row, column) ?? new Set();+ current.add(commentId);+ matrix.setValue(row, column, current);+ }++ private _deleteCommentFromMatrix(matrix: ObjectMatrix<Set<string>>, row: number, column: number, commentId: string) {+ if (row >= 0 && column >= 0) {+ const current = matrix.getValue(row, column);+ if (current && current.has(commentId)) {+ current.delete(commentId);+ if (current.size === 0) {+ matrix.realDeleteValue(row, column);+ }+ }+ }+ }+private _ensure(unitId: string, subUnitId: string) {const matrix = this._ensureCommentMatrix(unitId, subUnitId);const locationMap = this._ensureCommentLocationMap(unitId, subUnitId);@@ -107,9 +125,8 @@ export class SheetsThreadCommentModel extends Disposable {const { row, column } = location;const commentId = comment.id;const { matrix, locationMap } = this._ensure(unitId, subUnitId);-if (!parentId && row >= 0 && column >= 0) {- matrix.setValue(row, column, commentId);+ this._addCommentToMatrix(matrix, row, column, commentId);locationMap.set(commentId, { row, column });}@@ -118,6 +135,7 @@ export class SheetsThreadCommentModel extends Disposable {subUnitId,payload: comment,type: 'add',+ isRoot: !parentId,...location,});}@@ -143,20 +161,15 @@ export class SheetsThreadCommentModel extends Disposable {}case 'delete': {const { isRoot, comment } = update.payload;- const location = singleReferenceToGrid(comment.ref);if (isRoot) {+ const location = singleReferenceToGrid(comment.ref);const { row, column } = location;- if (row >= 0 && column >= 0) {- const current = matrix.getValue(row, column);- if (current === comment.id) {- matrix.realDeleteValue(row, column);- }- }+ this._deleteCommentFromMatrix(matrix, row, column, comment.id);+ this._commentUpdate$.next({+ ...update,+ ...location,+ });}- this._commentUpdate$.next({- ...update,- ...location,- });break;}case 'update': {@@ -180,13 +193,11 @@ export class SheetsThreadCommentModel extends Disposable {return;}const { row, column } = currentLoc;- const currentCommentId = matrix.getValue(row, column);- if (currentCommentId === commentId) {- matrix.realDeleteValue(row, column);- locationMap.delete(commentId);- }+ this._deleteCommentFromMatrix(matrix, row, column, commentId);+ locationMap.delete(commentId);+if (location.row >= 0 && location.column >= 0) {- matrix.setValue(location.row, location.column, commentId);+ this._addCommentToMatrix(matrix, location.row, location.column, commentId);locationMap.set(commentId, { row: location.row, column: location.column });}this._commentUpdate$.next({@@ -195,6 +206,18 @@ export class SheetsThreadCommentModel extends Disposable {});break;}+ case 'resolve': {+ const { unitId, subUnitId, payload } = update;+ const { locationMap } = this._ensure(unitId, subUnitId);+ const location = locationMap.get(payload.commentId);+ if (location) {+ this._commentUpdate$.next({+ ...update,+ ...location,+ });+ }+ break;+ }default:break;@@ -203,8 +226,19 @@ export class SheetsThreadCommentModel extends Disposable {}getByLocation(unitId: string, subUnitId: string, row: number, column: number): string | undefined {+ const comments = this.getAllByLocation(unitId, subUnitId, row, column);+ const activeComments = comments.filter((comment) => !comment.resolved);+ return activeComments[0]?.id;+ }++ getAllByLocation(unitId: string, subUnitId: string, row: number, column: number): IThreadComment[] {const matrix = this._ensureCommentMatrix(unitId, subUnitId);- return matrix.getValue(row, column);+ const current = matrix.getValue(row, column);+ if (!current) {+ return [];+ }++ return Array.from(current).map((id) => this.getComment(unitId, subUnitId, id)).filter(Boolean) as IThreadComment[];}getComment(unitId: string, subUnitId: string, commentId: string) {@@ -212,8 +246,7 @@ export class SheetsThreadCommentModel extends Disposable {}getCommentWithChildren(unitId: string, subUnitId: string, row: number, column: number) {- const matrix = this._ensureCommentMatrix(unitId, subUnitId);- const commentId = matrix.getValue(row, column);+ const commentId = this.getByLocation(unitId, subUnitId, row, column);if (!commentId) {return undefined;}diff --git a/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts b/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.tsindex f0d461176a..d1905f9125 100644--- a/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts+++ b/packages/sheets-thread-comment/src/controllers/render-controllers/render.controller.ts@@ -88,7 +88,7 @@ export class SheetsThreadCommentRenderController extends Disposable {}};- this.disposeWithMe(this._sheetsThreadCommentModel.commentUpdate$.subscribe(() => {+ this.disposeWithMe(this._sheetsThreadCommentModel.commentUpdate$.subscribe((update) => {markSkeletonDirty();}));}diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-copy-paste.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-copy-paste.controller.tsindex 1c65e5cc24..8b61f287d7 100644--- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-copy-paste.controller.ts+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-copy-paste.controller.ts@@ -18,7 +18,7 @@ import type { IMutationInfo, IRange, Nullable } from '@univerjs/core';import { Disposable, LifecycleStages, OnLifecycle, Range } from '@univerjs/core';import { COPY_TYPE, ISheetClipboardService } from '@univerjs/sheets-ui';import { Inject } from '@wendellhu/redi';-import { AddCommentMutation, DeleteCommentMutation, type IThreadComment } from '@univerjs/thread-comment';+import { AddCommentMutation, DeleteCommentMutation, type IThreadComment, IThreadCommentDataSourceService } from '@univerjs/thread-comment';import { serializeRange, singleReferenceToGrid } from '@univerjs/engine-formula';import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment-base';import { SHEETS_THREAD_COMMENT } from '../types/const';@@ -46,7 +46,8 @@ export class SheetsThreadCommentCopyPasteController extends Disposable {constructor(@Inject(ISheetClipboardService) private _sheetClipboardService: ISheetClipboardService,- @Inject(SheetsThreadCommentModel) private _sheetsThreadCommentModel: SheetsThreadCommentModel+ @Inject(SheetsThreadCommentModel) private _sheetsThreadCommentModel: SheetsThreadCommentModel,+ @IThreadCommentDataSourceService private _threadCommentDataSourceService: IThreadCommentDataSourceService) {super();this._initClipboardHook();@@ -79,12 +80,20 @@ export class SheetsThreadCommentCopyPasteController extends Disposable {column: range.startColumn,};if (!(targetUnitId === sourceUnitId && targetSubUnitId === sourceSubUnitId)) {- const roots: { root: IThreadComment; children: IThreadComment[] }[] = [];+ const roots: IThreadComment[] = [];Range.foreach(range, (row, col) => {- const root = this._sheetsThreadCommentModel.getCommentWithChildren(sourceUnitId, sourceSubUnitId, row, col);- if (root) {- roots.push(root);+ const comments = this._sheetsThreadCommentModel.getAllByLocation(sourceUnitId, sourceSubUnitId, row, col);+ if (this._threadCommentDataSourceService.syncUpdateMutationToColla) {+ comments.forEach((comment) => {+ roots.push(comment);+ });+ } else {+ comments.forEach(({ children, ...comment }) => {+ if (!comment.parentId) {+ roots.push(comment);+ }+ });}});@@ -113,6 +122,7 @@ export class SheetsThreadCommentCopyPasteController extends Disposable {unitId: targetUnitId,subUnitId: targetSubUnitId,},+ sync: true,},});sourceUndos.push({@@ -121,6 +131,7 @@ export class SheetsThreadCommentCopyPasteController extends Disposable {unitId: sourceUnitId,subUnitId: sourceSubUnitId,comment: item,+ sync: true,},});targetUndos.unshift({@@ -134,10 +145,7 @@ export class SheetsThreadCommentCopyPasteController extends Disposable {};roots.forEach((root) => {- handleCommentItem(root.root);- root.children.forEach((child) => {- handleCommentItem(child);- });+ handleCommentItem(root);});return {diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.tsindex 16f5c79750..daea6b5269 100644--- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment-remove.controller.ts@@ -20,14 +20,15 @@ import { Inject } from '@wendellhu/redi';import type { IRemoveSheetCommandParams } from '@univerjs/sheets';import { RemoveSheetCommand, SheetInterceptorService } from '@univerjs/sheets';import type { IDeleteCommentMutationParams } from '@univerjs/thread-comment';-import { AddCommentMutation, DeleteCommentMutation, ThreadCommentModel } from '@univerjs/thread-comment';+import { AddCommentMutation, DeleteCommentMutation, IThreadCommentDataSourceService, ThreadCommentModel } from '@univerjs/thread-comment';@OnLifecycle(LifecycleStages.Ready, ThreadCommentRemoveSheetsController)export class ThreadCommentRemoveSheetsController extends Disposable {constructor(@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,- @Inject(ThreadCommentModel) private _threadCommentModel: ThreadCommentModel+ @Inject(ThreadCommentModel) private _threadCommentModel: ThreadCommentModel,+ @IThreadCommentDataSourceService private _threadCommentDataSourceService: IThreadCommentDataSourceService) {super();this._initSheetChange();@@ -50,8 +51,10 @@ export class ThreadCommentRemoveSheetsController extends Disposable {}const { commentMap } = this._threadCommentModel.ensureMap(unitId, subUnitId);- const ids = Array.from(Object.keys(commentMap));- const comments = Array.from(Object.values(commentMap));+ const comments = Array.from(Object.values(commentMap)).filter((comment) => !comment.parentId);+ const ids = comments.map((comment) => comment.id);+ const shouldSync = this._threadCommentDataSourceService.syncUpdateMutationToColla;+const redos = ids.map((id) => ({id: DeleteCommentMutation.id,params: {@@ -61,15 +64,18 @@ export class ThreadCommentRemoveSheetsController extends Disposable {} as IDeleteCommentMutationParams,}));- const undos = comments.map((comment) => ({+ const undos = comments.map(({ children, ...comment }) => ({id: AddCommentMutation.id,params: {unitId,subUnitId,- comment,+ comment: {+ ...comment,+ children: shouldSync ? children : undefined,+ },+ sync: !shouldSync,},}));-return { redos, undos };}return { redos: [], undos: [] };diff --git a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.tsindex d02d008d83..55a6771374 100644--- a/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts+++ b/packages/sheets-thread-comment/src/controllers/sheets-thread-comment.controller.ts@@ -15,7 +15,7 @@*/import type { DependencyOverride, Workbook } from '@univerjs/core';-import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, LocaleService, OnLifecycle, UniverInstanceType } from '@univerjs/core';+import { Disposable, ICommandService, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';import type { MenuConfig } from '@univerjs/ui';import { ComponentManager, IMenuService, IShortcutService } from '@univerjs/ui';import { Inject, Injector } from '@wendellhu/redi';@@ -50,7 +50,6 @@ export class SheetsThreadCommentController extends Disposable {@IMenuService private readonly _menuService: IMenuService,@Inject(Injector) private readonly _injector: Injector,@Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(LocaleService) private readonly _localeService: LocaleService,@ICommandService private readonly _commandService: ICommandService,@Inject(SheetsThreadCommentPopupService) private readonly _sheetsThreadCommentPopupService: SheetsThreadCommentPopupService,@Inject(SheetsThreadCommentModel) private readonly _sheetsThreadCommentModel: SheetsThreadCommentModel,@@ -169,7 +168,7 @@ export class SheetsThreadCommentController extends Disposable {return;}- const GAP = 5;+ const GAP = 1;await this._commandService.executeCommand(ScrollToRangeOperation.id, {range: {startRow: Math.max(location.row - GAP, 0),diff --git a/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx b/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsxindex 13ab1d14db..caf2ab2ff1 100644--- a/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx+++ b/packages/sheets-thread-comment/src/views/sheets-thread-comment-panel/index.tsx@@ -50,20 +50,27 @@ export const SheetsThreadCommentPanel = () => {sheetIndex[sheet.getSheetId()] = i;});- return comments.map((comment) => {- const ref = singleReferenceToGrid(comment.ref);- const p = [sheetIndex[comment.subUnitId] ?? 0, ref.row, ref.column];- return { ...comment, p };- }).sort((pre, aft) => {- if (pre.p[0] === aft.p[0]) {- if (pre.p[1] === aft.p[1]) {- return pre.p[2] - aft.p[2];+ const sort = (comments: IThreadComment[]) => {+ return comments.map((comment) => {+ const ref = singleReferenceToGrid(comment.ref);+ const p = [sheetIndex[comment.subUnitId] ?? 0, ref.row, ref.column];+ return { ...comment, p };+ }).sort((pre, aft) => {+ if (pre.p[0] === aft.p[0]) {+ if (pre.p[1] === aft.p[1]) {+ return pre.p[2] - aft.p[2];+ }+ return pre.p[1] - aft.p[1];}- return pre.p[1] - aft.p[1];- }- return pre.p[0] - aft.p[0];- });+ return pre.p[0] - aft.p[0];+ });+ };++ return [+ ...sort(comments.filter((comment) => !comment.resolved)),+ ...sort(comments.filter((comment) => comment.resolved)),+ ];}, [workbook]);const showShape = useCallback((comment: IThreadComment) => {@@ -98,10 +105,6 @@ export const SheetsThreadCommentPanel = () => {commandService.executeCommand(ShowAddSheetCommentModalOperation.id);};- const handleResolve = () => {- sheetsThreadCommentPopupService.hidePopup();- };-const handleHover = (comment: IThreadComment) => {if (activeCommentId &&@@ -127,6 +130,12 @@ export const SheetsThreadCommentPanel = () => {}};+ const handleResolve = (id: string, resolved: boolean) => {+ if (resolved) {+ sheetsThreadCommentPopupService.hidePopup();+ }+ };+useEffect(() => {if (!activeCommentId) {return;@@ -154,6 +163,10 @@ export const SheetsThreadCommentPanel = () => {sortComments={sortComments}onItemEnter={handleHover}onItemLeave={handleLeave}+ onDeleteComment={() => {+ handleLeave();+ return true;+ }}/>);};diff --git a/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.tsindex ff8694bba7..e845632c41 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/hide-row-col-confirm.command.spec.ts@@ -27,6 +27,7 @@ import {SetRangeValuesMutation,SetRowHiddenCommand,SetRowHiddenMutation,+ SetSelectionsOperation,} from '@univerjs/sheets';import { type IConfirmPartMethodOptions, IConfirmService } from '@univerjs/ui';import type { IDisposable, Injector } from '@wendellhu/redi';@@ -89,6 +90,7 @@ describe('Test hide row col confirm commands', () => {commandService.registerCommand(SetRowHiddenMutation);commandService.registerCommand(SetColHiddenCommand);commandService.registerCommand(SetColHiddenMutation);+ commandService.registerCommand(SetSelectionsOperation);get(LocaleService).load({});});diff --git a/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.tsindex 30ea590077..c400946744 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/remove-row-col-confirm.command.spec.ts@@ -27,6 +27,7 @@ import {RemoveWorksheetMergeMutation,SelectionManagerService,SetRangeValuesMutation,+ SetSelectionsOperation,} from '@univerjs/sheets';import { type IConfirmPartMethodOptions, IConfirmService } from '@univerjs/ui';import type { IDisposable, Injector } from '@wendellhu/redi';@@ -89,6 +90,7 @@ describe('Test remove row col confirm commands', () => {commandService.registerCommand(RemoveColConfirmCommand);commandService.registerCommand(RemoveColCommand);commandService.registerCommand(RemoveColMutation);+ commandService.registerCommand(SetSelectionsOperation);get(LocaleService).load({});});diff --git a/packages/sheets-ui/src/controllers/render-controllers/skeleton.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/skeleton.render-controller.tsnew file mode 100644index 0000000000..c697a2e7a4--- /dev/null+++ b/packages/sheets-ui/src/controllers/render-controllers/skeleton.render-controller.ts@@ -0,0 +1,41 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 { Workbook } from '@univerjs/core';+import { Disposable, LifecycleStages, OnLifecycle } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import type { IRenderContext } from '@univerjs/engine-render';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';++@OnLifecycle(LifecycleStages.Ready, SheetSkeletonRenderController)+export class SheetSkeletonRenderController extends Disposable {+ constructor(+ private readonly _context: IRenderContext<Workbook>,+ @Inject(SheetSkeletonManagerService) private readonly _sheetSkeletonManagerService: SheetSkeletonManagerService+ ) {+ super();++ this._initRemoveSheet();+ }++ private _initRemoveSheet() {+ this.disposeWithMe(this._context.unit.sheetDisposed$.subscribe((sheet) => {+ this._sheetSkeletonManagerService.disposeSkeleton({+ sheetId: sheet.getSheetId(),+ });+ }));+ }+}diff --git a/packages/sheets-ui/src/sheets-ui-plugin.ts b/packages/sheets-ui/src/sheets-ui-plugin.tsindex 6820809b59..4cf882cfd0 100644--- a/packages/sheets-ui/src/sheets-ui-plugin.ts+++ b/packages/sheets-ui/src/sheets-ui-plugin.ts@@ -83,6 +83,7 @@ import { SheetPermissionUserManagerService } from './services/permission/sheet-pimport { WorksheetProtectionRenderService } from './services/permission/worksheet-permission-render.service';import { SheetPrintInterceptorService } from './services/print-interceptor.service';import { MoveRangeController } from './controllers/move-range.controller';+import { SheetSkeletonRenderController } from './controllers/render-controllers/skeleton.render-controller';@DependentOn(UniverSheetsPlugin)export class UniverSheetsUIPlugin extends Plugin {@@ -222,6 +223,7 @@ export class UniverSheetsUIPlugin extends Plugin {SheetPermissionInterceptorFormulaRenderController,SheetPermissionRenderController,+ SheetSkeletonRenderController,]).forEach((m) => {this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, m));});diff --git a/packages/thread-comment-ui/package.json b/packages/thread-comment-ui/package.jsonindex a4642bd42c..5e7a998043 100644--- a/packages/thread-comment-ui/package.json+++ b/packages/thread-comment-ui/package.json@@ -65,6 +65,8 @@"peerDependencies": {"@univerjs/core": "workspace:*","@univerjs/design": "workspace:*",+ "@univerjs/docs": "workspace:*",+ "@univerjs/engine-render": "workspace:*","@univerjs/thread-comment": "workspace:*","@univerjs/ui": "workspace:*","@wendellhu/redi": "0.15.5",@@ -81,6 +83,8 @@"devDependencies": {"@univerjs/core": "workspace:*","@univerjs/design": "workspace:*",+ "@univerjs/docs": "workspace:*",+ "@univerjs/engine-render": "workspace:*","@univerjs/shared": "workspace:*","@univerjs/ui": "workspace:*","@wendellhu/redi": "0.15.5",diff --git a/packages/thread-comment-ui/src/common/utils.ts b/packages/thread-comment-ui/src/common/utils.tsnew file mode 100644index 0000000000..dfcd70d926--- /dev/null+++ b/packages/thread-comment-ui/src/common/utils.ts@@ -0,0 +1,21 @@+/**+ * Copyright 2023-present DreamNum Inc.+ *+ * 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 dayjs from 'dayjs';++export function getDT() {+ return dayjs().format('YYYY/MM/DD HH:mm');+}diff --git a/packages/thread-comment-ui/src/index.ts b/packages/thread-comment-ui/src/index.tsindex 34231eb302..71b5ade716 100644--- a/packages/thread-comment-ui/src/index.ts+++ b/packages/thread-comment-ui/src/index.ts@@ -14,14 +14,15 @@* limitations under the License.*/+export { getDT } from './common/utils';export { UniverThreadCommentUIPlugin } from './plugin';-export { ThreadCommentPanelService } from './services/thread-comment-panel.service';+export { ThreadCommentPanelService, type ActiveCommentInfo } from './services/thread-comment-panel.service';export { ThreadCommentPanel } from './views/thread-comment-panel';export type { IThreadCommentPanelProps } from './views/thread-comment-panel';export { ThreadCommentTree } from './views/thread-comment-tree';export type { IThreadCommentTreeProps } from './views/thread-comment-tree';export { THREAD_COMMENT_PANEL } from './types/const';-export { IThreadCommentMentionDataService } from './services/thread-comment-mention-data.service';+export { IThreadCommentMentionDataService, type IThreadCommentMentionDataSource } from './services/thread-comment-mention-data.service';// #region - all commandsdiff --git a/packages/thread-comment-ui/src/locale/zh-CN.ts b/packages/thread-comment-ui/src/locale/zh-CN.tsindex 1e1f1497ad..2c269e9b5d 100644--- a/packages/thread-comment-ui/src/locale/zh-CN.ts+++ b/packages/thread-comment-ui/src/locale/zh-CN.ts@@ -21,7 +21,7 @@ export default {empty: '暂无评论',filterEmpty: '没有匹配的结果',reset: '重置',- addComment: '新建评论',+ addComment: '添加评论',},editor: {placeholder: '回复',diff --git a/packages/thread-comment-ui/src/services/thread-comment-mention-data.service.ts b/packages/thread-comment-ui/src/services/thread-comment-mention-data.service.tsindex 81efc7350d..1886b14c38 100644--- a/packages/thread-comment-ui/src/services/thread-comment-mention-data.service.ts+++ b/packages/thread-comment-ui/src/services/thread-comment-mention-data.service.ts@@ -14,18 +14,32 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import type { MentionProps } from '@univerjs/design';import type { IThreadCommentMention } from '@univerjs/thread-comment';import { createIdentifier } from '@wendellhu/redi';+export interface IThreadCommentMentionDataSource {+ getMentions(search: string, unitId: string, subUnitId: string): Promise<IThreadCommentMention[]>;+}+export interface IThreadCommentMentionDataService {- getMentions: (search: string) => Promise<IThreadCommentMention[]>;+ dataSource: Nullable<IThreadCommentMentionDataSource>;++ getMentions: (search: string, unitId: string, subUnitId: string) => Promise<IThreadCommentMention[]>;trigger: string;renderSuggestion?: MentionProps['renderSuggestion'];}export class ThreadCommentMentionDataService implements IThreadCommentMentionDataService {- async getMentions(search: string) {+ dataSource: Nullable<IThreadCommentMentionDataSource>;++ renderSuggestion: MentionProps['renderSuggestion'];++ async getMentions(search: string, unitId: string, subUnitId: string) {+ if (this.dataSource) {+ return this.dataSource.getMentions(search, unitId, subUnitId);+ }return [];}diff --git a/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts b/packages/thread-comment-ui/src/services/thread-comment-panel.service.tsindex d397af4938..b2ba1e7884 100644--- a/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts+++ b/packages/thread-comment-ui/src/services/thread-comment-panel.service.ts@@ -14,12 +14,13 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import { Disposable, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { ISidebarService } from '@univerjs/ui';import { Inject } from '@wendellhu/redi';import { BehaviorSubject, filter } from 'rxjs';-type ActiveCommentInfo = { unitId: string; subUnitId: string; commentId: string; trigger?: string } | undefined;+export type ActiveCommentInfo = Nullable<{ unitId: string; subUnitId: string; commentId: string; trigger?: string }>;export class ThreadCommentPanelService extends Disposable {private _panelVisible = false;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.tsxindex 22daf4d463..12b50d826b 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@@ -20,8 +20,11 @@ import { Button, Mention, Mentions } from '@univerjs/design';import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';import { useDependency } from '@wendellhu/redi/react-bindings';import type { IDocumentBody } from '@univerjs/core';-import { LocaleService } from '@univerjs/core';+import { ICommandService, LocaleService } from '@univerjs/core';+import { ITextSelectionRenderManager } from '@univerjs/engine-render';+import { TextSelectionManagerService } from '@univerjs/docs';import { IThreadCommentMentionDataService } from '../../services/thread-comment-mention-data.service';+import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';import styles from './index.module.less';import { parseMentions, transformDocument2TextNodes, transformMention, transformTextNode2Text, transformTextNodes2Document } from './util';@@ -31,6 +34,8 @@ export interface IThreadCommentEditorProps {onSave?: (comment: Pick<IThreadComment, 'attachments' | 'text'>) => void;onCancel?: () => void;autoFocus?: boolean;+ unitId: string;+ subUnitId: string;}export interface IThreadCommentEditorInstance {@@ -50,12 +55,15 @@ const defaultRenderSuggestion: MentionProps['renderSuggestion'] = (mention, sear};export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThreadCommentEditorProps>((props, ref) => {- const { comment, onSave, id, onCancel, autoFocus } = props;+ const { comment, onSave, id, onCancel, autoFocus, unitId, subUnitId } = props;const mentionDataService = useDependency(IThreadCommentMentionDataService);+ const commandService = useDependency(ICommandService);const localeService = useDependency(LocaleService);const [localComment, setLocalComment] = useState({ ...comment });const [editing, setEditing] = useState(false);const inputRef = useRef(null);+ const textSelectionRenderManager = useDependency(ITextSelectionRenderManager);+ const textSelectionManagerService = useDependency(TextSelectionManagerService);useImperativeHandle(ref, () => ({reply(text) {@@ -84,13 +92,18 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThrsetLocalComment?.({ ...comment, text: transformTextNodes2Document(parseMentions(e.target.value)) });}}onFocus={() => {+ const activeRange = textSelectionManagerService.getActiveRange();+ if (activeRange && activeRange.collapsed) {+ textSelectionRenderManager.removeAllTextRanges();+ }+ textSelectionRenderManager.blur();setEditing(true);}}><Mentionkey={mentionDataService.trigger}trigger={mentionDataService.trigger}- data={(query, callback) => mentionDataService.getMentions!(query)+ data={(query, callback) => mentionDataService.getMentions!(query, unitId, subUnitId).then((res) => res.map(transformMention)).then(callback) as any}displayTransform={(id, label) => `@${label} `}renderSuggestion={mentionDataService.renderSuggestion ?? defaultRenderSuggestion}@@ -105,6 +118,7 @@ export const ThreadCommentEditor = forwardRef<IThreadCommentEditorInstance, IThronCancel?.();setEditing(false);setLocalComment({ text: undefined });+ commandService.executeCommand(SetActiveCommentOperation.id);}}>{localeService.t('threadCommentUI.editor.cancel')}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.tsxindex 9282849aec..0a5ab3c721 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,11 +18,13 @@ import React, { useEffect, useMemo, useRef, useState } from 'react';import { useDependency } from '@wendellhu/redi/react-bindings';import type { IThreadComment } from '@univerjs/thread-comment';import { ThreadCommentModel } from '@univerjs/thread-comment';-import { ICommandService, LocaleService, type UniverInstanceType, UserManagerService } from '@univerjs/core';+import type { Nullable } from '@univerjs/core';+import { ICommandService, LocaleService, UniverInstanceType, UserManagerService } from '@univerjs/core';import { useObservable } from '@univerjs/ui';import { Button, Select } from '@univerjs/design';import { IncreaseSingle } from '@univerjs/icons';import type { Observable } from 'rxjs';+import type { IThreadCommentTreeProps } from '../thread-comment-tree';import { ThreadCommentTree } from '../thread-comment-tree';import { ThreadCommentPanelService } from '../../services/thread-comment-panel.service';import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';@@ -34,14 +36,34 @@ export interface IThreadCommentPanelProps {type: UniverInstanceType;onAdd: () => void;getSubUnitName: (subUnitId: string) => string;- onResolve?: (id: string) => void;+ onResolve?: (id: string, resolved: boolean) => void;sortComments?: (comments: IThreadComment[]) => IThreadComment[];onItemLeave?: (comment: IThreadComment) => void;onItemEnter?: (comment: IThreadComment) => void;+ disableAdd?: boolean;+ tempComment?: Nullable<IThreadComment>;+ onAddComment?: IThreadCommentTreeProps['onAddComment'];+ onDeleteComment?: IThreadCommentTreeProps['onDeleteComment'];+ showComments?: string[];}export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {- const { unitId, subUnitId$, type, onAdd, getSubUnitName, onResolve, sortComments, onItemLeave, onItemEnter } = props;+ const {+ unitId,+ subUnitId$,+ type,+ onAdd,+ getSubUnitName,+ onResolve,+ sortComments,+ onItemLeave,+ onItemEnter,+ disableAdd,+ tempComment,+ onAddComment,+ onDeleteComment,+ showComments,+ } = props;const [unit, setUnit] = useState('all');const [status, setStatus] = useState('all');const localeService = useDependency(LocaleService);@@ -53,32 +75,48 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {const update = useObservable(threadCommentModel.commentUpdate$);const commandService = useDependency(ICommandService);const subUnitId = useObservable(subUnitId$);- const currentUser = userService.getCurrentUser();const shouldScroll = useRef(true);const prefix = 'panel';+ const currentUser = useObservable(userService.currentUser$);const comments = useMemo(() => {- if (unit === 'all') {- const filteredComments = unitComments.map((i) => i[1]).flat().filter((i) => !i.parentId);- return sortComments ? sortComments(filteredComments) : filteredComments;+ const allComments =+ (unit === 'all' ? unitComments.map((i) => i[1]).flat() : unitComments.find((i) => i[0] === subUnitId)?.[1] ?? [])+ .filter((i) => !i.parentId);++ const sort = sortComments ?? ((a) => a);+ const res = allComments;++ if (showComments) {+ const map = new Map<string, IThreadComment>();+ res.forEach((comment) => {+ map.set(comment.id, comment);+ });++ return [...showComments, ''].map((id) => map.get(id)).filter(Boolean) as IThreadComment[];} else {- return unitComments.find((i) => i[0] === subUnitId)?.[1] ?? [];+ return sort(res);}- }, [unit, unitComments, subUnitId, sortComments]);+ }, [showComments, unit, unitComments, sortComments, subUnitId]);++ const commentsSorted = useMemo(() => [+ ...comments.filter((comment) => !comment.resolved),+ ...comments.filter((comment) => comment.resolved),+ ], [comments]);const statuedComments = useMemo(() => {if (status === 'resolved') {- return comments.filter((comment) => comment.resolved);+ return commentsSorted.filter((comment) => comment.resolved);}if (status === 'unsolved') {- return comments.filter((comment) => !comment.resolved);+ return commentsSorted.filter((comment) => !comment.resolved);}if (status === 'concern_me') {if (!currentUser?.userID) {- return comments;+ return commentsSorted;}- return comments.map((comment) => threadCommentModel.getCommentWithChildren(comment.unitId, comment.subUnitId, comment.id)).map((comment) => {+ return commentsSorted.map((comment) => threadCommentModel.getCommentWithChildren(comment.unitId, comment.subUnitId, comment.id)).map((comment) => {if (comment?.relativeUsers.has(currentUser.userID)) {return comment.root;}@@ -86,8 +124,12 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {}).filter(Boolean) as IThreadComment[];}- return comments;- }, [comments, currentUser?.userID, status, threadCommentModel]);+ return commentsSorted;+ }, [commentsSorted, currentUser?.userID, status, threadCommentModel]);++ const renderComments = tempComment+ ? [tempComment, ...statuedComments]+ : statuedComments;const isFiltering = status !== 'all' || unit !== 'all';@@ -120,20 +162,24 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {return (<div className={styles.threadCommentPanel}><div className={styles.threadCommentPanelForms}>- <Select- borderless- value={unit}- onChange={(e) => setUnit(e)}- options={[- {- value: 'current',- label: localeService.t('threadCommentUI.filter.sheet.current'),- }, {- value: 'all',- label: localeService.t('threadCommentUI.filter.sheet.all'),- },- ]}- />+ {type === UniverInstanceType.UNIVER_SHEET+ ? (+ <Select+ borderless+ value={unit}+ onChange={(e) => setUnit(e)}+ options={[+ {+ value: 'current',+ label: localeService.t('threadCommentUI.filter.sheet.current'),+ }, {+ value: 'all',+ label: localeService.t('threadCommentUI.filter.sheet.all'),+ },+ ]}+ />+ )+ : null}<Selectborderlessvalue={status}@@ -157,7 +203,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {]}/></div>- {statuedComments?.map((comment) => (+ {renderComments.map((comment) => (<ThreadCommentTreeprefix={prefix}getSubUnitName={getSubUnitName}@@ -165,24 +211,34 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {id={comment.id}unitId={comment.unitId}subUnitId={comment.subUnitId}+ refStr={comment.ref}type={type}showEdit={activeCommentId?.commentId === comment.id}showHighlight={activeCommentId?.commentId === comment.id}onClick={() => {shouldScroll.current = false;- commandService.executeCommand(SetActiveCommentOperation.id, {- unitId: comment.unitId,- subUnitId: comment.subUnitId,- commentId: comment.id,- temp: true,- });+ if (!comment.resolved) {+ commandService.executeCommand(+ SetActiveCommentOperation.id,+ {+ unitId: comment.unitId,+ subUnitId: comment.subUnitId,+ commentId: comment.id,+ temp: false,+ }+ );+ } else {+ commandService.executeCommand(SetActiveCommentOperation.id);+ }}}- onClose={() => onResolve?.(comment.id)}onMouseEnter={() => onItemEnter?.(comment)}onMouseLeave={() => onItemLeave?.(comment)}+ onAddComment={onAddComment}+ onDeleteComment={onDeleteComment}+ onResolve={(resolved: boolean) => onResolve?.(comment.id, resolved)}/>))}- {statuedComments.length+ {renderComments.length? null: (<div className={styles.threadCommentPanelEmpty}>@@ -204,6 +260,7 @@ export const ThreadCommentPanel = (props: IThreadCommentPanelProps) => {className={styles.threadCommentPanelAdd}type="primary"onClick={onAdd}+ disabled={disableAdd}><IncreaseSingle />{localeService.t('threadCommentUI.panel.addComment')}diff --git a/packages/thread-comment-ui/src/views/thread-comment-tree/index.module.less b/packages/thread-comment-ui/src/views/thread-comment-tree/index.module.lessindex 53bc5a571d..78f4dd5696 100644--- a/packages/thread-comment-ui/src/views/thread-comment-tree/index.module.less+++ b/packages/thread-comment-ui/src/views/thread-comment-tree/index.module.less@@ -35,6 +35,8 @@.thread-comment-icon-container {display: flex;flex-direction: row;+ flex-shrink: 0;+ flex-grow: 0;}.thread-comment-icon {@@ -67,6 +69,8 @@display: flex;flex-direction: row;align-items: center;+ flex: 1 1 0;+ overflow: hidden;}.thread-comment-title-highlight {@@ -75,6 +79,15 @@border-radius: 1.5px;background-color: rgba(var(--gold-400));margin-right: 8px;+ flex-shrink: 0;+ flex-grow: 0;+}++.thread-comment-title-position-text {+ flex: 1 1 0;+ white-space: nowrap;+ text-overflow: ellipsis;+ overflow: hidden;}.thread-comment-username {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.tsxindex bbc7f198fc..c1878cf3fb 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@@ -17,16 +17,17 @@import { useDependency } from '@wendellhu/redi/react-bindings';import type { IAddCommentCommandParams, IThreadComment, IUpdateCommentCommandParams } from '@univerjs/thread-comment';import { AddCommentCommand, DeleteCommentCommand, DeleteCommentTreeCommand, ResolveCommentCommand, ThreadCommentModel, UpdateCommentCommand } from '@univerjs/thread-comment';-import React, { useRef, useState } from 'react';+import React, { useEffect, useRef, useState } from 'react';import { DeleteSingle, MoreHorizontalSingle, ReplyToCommentSingle, ResolvedSingle, SolveSingle } from '@univerjs/icons';import { ICommandService, type IUser, LocaleService, Tools, type UniverInstanceType, UserManagerService } from '@univerjs/core';import { useObservable } from '@univerjs/ui';-import dayjs from 'dayjs';import { Dropdown, Menu, MenuItem } from '@univerjs/design';import cs from 'clsx';import type { IThreadCommentEditorInstance } from '../thread-comment-editor';import { ThreadCommentEditor } from '../thread-comment-editor';import { transformDocument2TextNodes, transformTextNodes2Document } from '../thread-comment-editor/util';+import { getDT } from '../../common/utils';+import { SetActiveCommentOperation } from '../../commands/operations/comment.operations';import styles from './index.module.less';export interface IThreadCommentTreeProps {@@ -44,6 +45,9 @@ export interface IThreadCommentTreeProps {autoFocus?: boolean;onMouseEnter?: () => void;onMouseLeave?: () => void;+ onAddComment?: (comment: IThreadComment) => boolean;+ onDeleteComment?: (comment: IThreadComment) => boolean;+ onResolve?: (resolved: boolean) => void;}export interface IThreadCommentItemProps {@@ -57,12 +61,14 @@ export interface IThreadCommentItemProps {onReply: (user: IUser | undefined) => void;isRoot?: boolean;onClose?: () => void;+ onAddComment?: (comment: IThreadComment) => boolean;+ onDeleteComment?: (comment: IThreadComment) => boolean;}const MOCK_ID = '__mock__';const ThreadCommentItem = (props: IThreadCommentItemProps) => {- const { item, unitId, subUnitId, editing, onEditingChange, onReply, resolved, isRoot, onClose } = props;+ const { item, unitId, subUnitId, editing, onEditingChange, onReply, resolved, isRoot, onClose, onDeleteComment } = props;const commandService = useDependency(ICommandService);const localeService = useDependency(LocaleService);const userManagerService = useDependency(UserManagerService);@@ -71,7 +77,12 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {const isCommentBySelf = currentUser?.userID === item.personId;const isMock = item.id === MOCK_ID;const [showReply, setShowReply] = useState(false);+const handleDeleteItem = () => {+ if (onDeleteComment?.(item) === false) {+ return;+ }+commandService.executeCommand(isRoot ? DeleteCommentTreeCommand.id : DeleteCommentCommand.id,{@@ -130,6 +141,8 @@ const ThreadCommentItem = (props: IThreadCommentItemProps) => {comment={item}onCancel={() => onEditingChange?.(false)}autoFocus+ unitId={unitId}+ subUnitId={subUnitId}onSave={({ text, attachments }) => {onEditingChange?.(false);commandService.executeCommand(@@ -184,6 +197,9 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {autoFocus,onMouseEnter,onMouseLeave,+ onAddComment,+ onDeleteComment,+ onResolve,} = props;const threadCommentModel = useDependency(ThreadCommentModel);const [isHover, setIsHover] = useState(false);@@ -195,7 +211,7 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {const resolved = comments?.root.resolved;const currentUser = useObservable(userManagerService.currentUser$);const editorRef = useRef<IThreadCommentEditorInstance>(null);- const renderComments = [+ const renderComments: IThreadComment[] = [...comments ?[comments.root] :// mock empty comment@@ -209,20 +225,39 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {dT: '',unitId,subUnitId,+ threadId: '',}],- ...comments?.children ?? [],+ ...(comments?.children ?? []) as IThreadComment[],];- const handleResolve = () => {+ const handleResolve: React.MouseEventHandler<HTMLDivElement> = (e) => {+ e.stopPropagation();+ if (!resolved) {+ commandService.executeCommand(SetActiveCommentOperation.id);+ } else {+ commandService.executeCommand(SetActiveCommentOperation.id, {+ unitId,+ subUnitId,+ commentId: id,+ });+ }+commandService.executeCommand(ResolveCommentCommand.id, {unitId,subUnitId,commentId: id,resolved: !resolved,});- onClose?.();++ onResolve?.(!resolved);};- const handleDeleteRoot = () => {+ const handleDeleteRoot: React.MouseEventHandler<HTMLDivElement> = (e) => {+ e.stopPropagation();+ commandService.executeCommand(SetActiveCommentOperation.id);+ if (comments?.root && (onDeleteComment?.(comments.root) === false)) {+ return;+ }+commandService.executeCommand(DeleteCommentTreeCommand.id,{@@ -234,6 +269,14 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {onClose?.();};+ useEffect(() => {+ return onMouseLeave?.();+ }, []);++ const subUnitName = getSubUnitName(comments?.root.subUnitId ?? subUnitId);+ const editorVisible = showEdit && !editingId && !resolved;+ const title = `${refStr || comments?.root.ref}${subUnitName ? ' · ' : ''}${subUnitName}`;+return (<divclassName={cs(styles.threadComment, {@@ -254,9 +297,9 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {<div className={styles.threadCommentTitle}><div className={styles.threadCommentTitlePosition}><div className={styles.threadCommentTitleHighlight} />- {refStr || comments?.root.ref}- {' · '}- {getSubUnitName(comments?.root.subUnitId ?? subUnitId)}+ <div className={styles.threadCommentTitlePositionText}>+ {title}+ </div></div>{comments? (@@ -302,41 +345,54 @@ export const ThreadCommentTree = (props: IThreadCommentTreeProps) => {if (!user) {return;}- editorRef.current?.reply(transformTextNodes2Document([{- type: 'mention',- content: {- id: user.userID,- label: user.name,- },- }]));+ requestAnimationFrame(() => {+ editorRef.current?.reply(transformTextNodes2Document([{+ type: 'mention',+ content: {+ id: user.userID,+ label: user.name,+ },+ }]));+ });}}+ onAddComment={onAddComment}+ onDeleteComment={onDeleteComment}/>))}</div>- {showEdit && !editingId && !resolved+ {editorVisible? (<div><ThreadCommentEditorkey={`${autoFocus}`}ref={editorRef}+ unitId={unitId}+ subUnitId={subUnitId}onSave={({ text, attachments }) => {+ const comment: IThreadComment = {+ text,+ attachments,+ dT: getDT(),+ id: Tools.generateRandomId(),+ ref: refStr!,+ personId: currentUser?.userID!,+ parentId: comments?.root.id,+ unitId,+ subUnitId,+ threadId: comments?.root.threadId!,+ };++ if (onAddComment?.(comment) === false) {+ return;+ }+commandService.executeCommand(AddCommentCommand.id,{unitId,subUnitId,- comment: {- text,- attachments,- dT: dayjs().format('YYYY/MM/DD HH:mm'),- id: Tools.generateRandomId(),- ref: refStr,- personId: currentUser?.userID,- parentId: comments?.root.id,- unitId,- subUnitId,- },+ comment,} as IAddCommentCommandParams);}}diff --git a/packages/thread-comment/src/commands/commands/comment.command.ts b/packages/thread-comment/src/commands/commands/comment.command.tsindex 707a0f0500..1463af67bd 100644--- a/packages/thread-comment/src/commands/commands/comment.command.ts+++ b/packages/thread-comment/src/commands/commands/comment.command.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { CommandType, type ICommand, ICommandService, IUndoRedoService, sequenceExecute } from '@univerjs/core';+import { CommandType, type ICommand, ICommandService } from '@univerjs/core';import type { IThreadComment } from '../../types/interfaces/i-thread-comment';import { ThreadCommentModel } from '../../models/thread-comment.model';import { AddCommentMutation, DeleteCommentMutation, type IUpdateCommentPayload, ResolveCommentMutation, UpdateCommentMutation } from '../mutations/comment.mutation';@@ -29,34 +29,48 @@ export interface IAddCommentCommandParams {export const AddCommentCommand: ICommand<IAddCommentCommandParams> = {id: 'thread-comment.command.add-comment',type: CommandType.COMMAND,- async handler(accessor, params) {+ async handler(accessor, params) {if (!params) {return false;}const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);+ // const undoRedoService = accessor.get(IUndoRedoService);const dataSourceService = accessor.get(IThreadCommentDataSourceService);- const { unitId, subUnitId, comment: originComment } = params;+ const { comment: originComment } = params;const comment = await dataSourceService.addComment(originComment);+ const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;+ const isRoot = !originComment.parentId;+const redo = {id: AddCommentMutation.id,- params,- };- const undo = {- id: DeleteCommentMutation.id,params: {- unitId,- subUnitId,- commentId: comment.id,+ ...params,+ comment,},};- undoRedoService.pushUndoRedo({- undoMutations: [undo],- redoMutations: [redo],- unitID: unitId,++ if (isRoot) {+ const res = await commandService.executeCommand(redo.id, redo.params);+ // const undo = {+ // id: DeleteCommentMutation.id,+ // params: {+ // unitId,+ // subUnitId,+ // commentId: comment.id,+ // },+ // };+ // res && undoRedoService.pushUndoRedo({+ // undoMutations: [undo],+ // redoMutations: [redo],+ // unitID: unitId,+ // });++ return res;+ }++ return commandService.executeCommand(redo.id, redo.params, {+ onlyLocal: !syncUpdateMutationToColla,});- commandService.executeCommand(redo.id, redo.params);- return true;},};@@ -75,19 +89,20 @@ export const UpdateCommentCommand: ICommand<IUpdateCommentCommandParams> = {}const { unitId, subUnitId, payload } = params;const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);const threadCommentModel = accessor.get(ThreadCommentModel);const dataSourceService = accessor.get(IThreadCommentDataSourceService);- const currentComment = threadCommentModel.getComment(+ const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;+ const current = threadCommentModel.getComment(unitId,subUnitId,payload.commentId);- if (!currentComment) {+ if (!current) {return false;}+ const { children, ...currentComment } = current;const success = await dataSourceService.updateComment({...currentComment,...payload,@@ -101,87 +116,8 @@ export const UpdateCommentCommand: ICommand<IUpdateCommentCommandParams> = {id: UpdateCommentMutation.id,params,};- const undo = {- id: UpdateCommentMutation.id,- params: {- unitId,- subUnitId,- payload: {- commentId: payload.commentId,- text: currentComment.text,- attachments: currentComment.attachments,- updateT: currentComment.updateT,- updated: currentComment.updated,- },- },- };- undoRedoService.pushUndoRedo({- undoMutations: [undo],- redoMutations: [redo],- unitID: unitId,- });- commandService.executeCommand(redo.id, redo.params);- return true;- },-};--export interface IUpdateCommentRefPayload {- commentId: string;- ref: string;-}--export interface IUpdateCommentRefCommandParams {- unitId: string;- subUnitId: string;- payload: IUpdateCommentRefPayload;-}-export const UpdateCommentRefCommand: ICommand<IUpdateCommentRefCommandParams> = {- id: 'thread-comment.command.update-comment-ref',- type: CommandType.COMMAND,- async handler(accessor, params) {- if (!params) {- return false;- }- const dataSourceService = accessor.get(IThreadCommentDataSourceService);- const threadCommentModel = accessor.get(ThreadCommentModel);- const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);- const { unitId, subUnitId, payload } = params;- const currentComment = threadCommentModel.getComment(unitId, subUnitId, payload.commentId);-- if (!currentComment) {- return false;- }-- const success = await dataSourceService.updateComment({- ...currentComment,- ref: payload.ref,- });- if (!success) {- return false;- }- const redo = {- id: UpdateCommentMutation.id,- params,- };- const undo = {- id: UpdateCommentMutation.id,- params: {- unitId,- subUnitId,- payload: {- commentId: payload.commentId,- ref: currentComment.ref,- },- },- };- undoRedoService.pushUndoRedo({- undoMutations: [undo],- redoMutations: [redo],- unitID: unitId,- });- commandService.executeCommand(redo.id, redo.params);+ commandService.executeCommand(redo.id, redo.params, { onlyLocal: !syncUpdateMutationToColla });return true;},};@@ -196,7 +132,7 @@ export interface IResolveCommentCommandParams {export const ResolveCommentCommand: ICommand<IResolveCommentCommandParams> = {id: 'thread-comment.command.resolve-comment',type: CommandType.COMMAND,- async handler(accessor, params) {+ async handler(accessor, params) {if (!params) {return false;}@@ -204,25 +140,27 @@ export const ResolveCommentCommand: ICommand<IResolveCommentCommandParams> = {const dataSourceService = accessor.get(IThreadCommentDataSourceService);const threadCommentModel = accessor.get(ThreadCommentModel);const currentComment = threadCommentModel.getComment(unitId, subUnitId, commentId);-+ const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;if (!currentComment) {return false;}- const success = await dataSourceService.updateComment({+ const success = await dataSourceService.resolveComment({...currentComment,resolved,});+if (!success) {return false;}+const commandService = accessor.get(ICommandService);- commandService.executeCommand(+ return commandService.executeCommand(ResolveCommentMutation.id,- params+ params,+ { onlyLocal: !syncUpdateMutationToColla });- return true;},};@@ -232,6 +170,9 @@ export interface IDeleteCommentCommandParams {commentId: string;}+/**+ * Delete Reply+ */export const DeleteCommentCommand: ICommand<IDeleteCommentCommandParams> = {id: 'thread-comment.command.delete-comment',type: CommandType.COMMAND,@@ -242,15 +183,15 @@ export const DeleteCommentCommand: ICommand<IDeleteCommentCommandParams> = {const threadCommentModel = accessor.get(ThreadCommentModel);const dataSourceService = accessor.get(IThreadCommentDataSourceService);const commandService = accessor.get(ICommandService);- const undoRedoService = accessor.get(IUndoRedoService);const { unitId, subUnitId, commentId } = params;+ const syncUpdateMutationToColla = dataSourceService.syncUpdateMutationToColla;const comment = threadCommentModel.getComment(unitId, subUnitId, commentId);if (!comment) {return false;}- if (!(await dataSourceService.deleteComment(commentId))) {+ if (!(await dataSourceService.deleteComment(unitId, subUnitId, comment.threadId, commentId))) {return false;}@@ -258,20 +199,8 @@ export const DeleteCommentCommand: ICommand<IDeleteCommentCommandParams> = {id: DeleteCommentMutation.id,params,};- const undo = {- id: AddCommentMutation.id,- params: {- unitId,- subUnitId,- comment,- },- };- undoRedoService.pushUndoRedo({- undoMutations: [undo],- redoMutations: [redo],- unitID: unitId,- });- return commandService.executeCommand(redo.id, redo.params);++ return commandService.executeCommand(redo.id, redo.params, { onlyLocal: !syncUpdateMutationToColla });},};@@ -291,47 +220,21 @@ export const DeleteCommentTreeCommand: ICommand<IDeleteCommentCommandParams> = {const threadCommentModel = accessor.get(ThreadCommentModel);const commandService = accessor.get(ICommandService);const dataSourceService = accessor.get(IThreadCommentDataSourceService);- const undoRedoService = accessor.get(IUndoRedoService);const { unitId, subUnitId, commentId } = params;const commentWithChildren = threadCommentModel.getCommentWithChildren(unitId, subUnitId, commentId);if (!commentWithChildren) {return false;}- const comments = [commentWithChildren.root, ...commentWithChildren.children];- if (!(await dataSourceService.deleteCommentBatch(comments.map((comment) => comment.id)))) {+ if (!(await dataSourceService.deleteComment(unitId, subUnitId, commentWithChildren.root.threadId, commentId))) {return false;}- const redos = comments.map((item) => ({- id: DeleteCommentMutation.id,- params: {- unitId,- subUnitId,- commentId: item.id,- },- }));-- const undos = comments.map((item) => ({- id: AddCommentMutation.id,- params: {- unitId,- subUnitId,- comment: item,- },- }));-- const result = sequenceExecute(redos, commandService);-- if (result.result) {- undoRedoService.pushUndoRedo({- undoMutations: undos,- redoMutations: redos,- unitID: unitId,- });- }-- return result.result;+ return await commandService.executeCommand(DeleteCommentMutation.id, {+ unitId,+ subUnitId,+ commentId: commentWithChildren.root.id,+ });},};diff --git a/packages/thread-comment/src/commands/mutations/comment.mutation.ts b/packages/thread-comment/src/commands/mutations/comment.mutation.tsindex db092c511a..28c4021007 100644--- a/packages/thread-comment/src/commands/mutations/comment.mutation.ts+++ b/packages/thread-comment/src/commands/mutations/comment.mutation.ts@@ -23,18 +23,20 @@ export interface IAddCommentMutationParams {unitId: string;subUnitId: string;comment: IThreadComment;+ sync?: boolean;}export const AddCommentMutation: ICommand<IAddCommentMutationParams> = {id: 'thread-comment.mutation.add-comment',type: CommandType.MUTATION,- handler(accessor, params) {+ handler(accessor, params, options) {if (!params) {return false;}const threadCommentModel = accessor.get(ThreadCommentModel);- const { unitId, subUnitId, comment } = params;- return threadCommentModel.addComment(unitId, subUnitId, comment);+ const { unitId, subUnitId, comment, sync } = params;+ const shouldSync = sync || ((options?.fromChangeset) && !comment.parentId);+ return threadCommentModel.addComment(unitId, subUnitId, comment, shouldSync);},};diff --git a/packages/thread-comment/src/controllers/tc-resource.controller.ts b/packages/thread-comment/src/controllers/tc-resource.controller.tsindex 04c489289a..5c60faf73b 100644--- a/packages/thread-comment/src/controllers/tc-resource.controller.ts+++ b/packages/thread-comment/src/controllers/tc-resource.controller.ts@@ -44,7 +44,7 @@ export class ThreadCommentResourceController extends Disposable {resultMap[key] = v;});- return JSON.stringify(this._threadCommentDataSourceService.saveToSnapshot(resultMap));+ return JSON.stringify(this._threadCommentDataSourceService.saveToSnapshot(resultMap, unitID));}return '';};@@ -62,19 +62,20 @@ export class ThreadCommentResourceController extends Disposable {this.disposeWithMe(this._resourceManagerService.registerPluginResource({pluginName: `SHEET_${TC_PLUGIN_NAME}`,- businesses: [UniverType.UNIVER_SHEET],+ businesses: [UniverType.UNIVER_SHEET, UniverType.UNIVER_DOC],toJson: (unitID) => toJson(unitID),parseJson: (json) => parseJson(json),onUnLoad: (unitID) => {this._threadCommentModel.deleteUnit(unitID);},onLoad: async (unitID, value) => {- const unitComments = await this._threadCommentDataSourceService.loadFormSnapshot(value);- Object.keys(unitComments).forEach((subunitId) => {+ Object.keys(value).forEach((subunitId) => {const commentList = value[subunitId];- commentList.forEach((comment) => {+ commentList.forEach((comment: IThreadComment) => {this._threadCommentModel.addComment(unitID, subunitId, comment);});++ this._threadCommentModel.syncThreadComments(unitID, subunitId, commentList.map((i) => i.threadId));});},})diff --git a/packages/thread-comment/src/index.ts b/packages/thread-comment/src/index.tsindex cac745a090..d9dcec4f2c 100644--- a/packages/thread-comment/src/index.ts+++ b/packages/thread-comment/src/index.ts@@ -17,10 +17,15 @@export { ThreadCommentModel, type CommentUpdate } from './models/thread-comment.model';export { ThreadCommentResourceController } from './controllers/tc-resource.controller';export { TC_PLUGIN_NAME } from './types/const';-export type { IThreadComment, IThreadCommentMention } from './types/interfaces/i-thread-comment';-+export type { IThreadComment, IThreadCommentMention, IBaseComment } from './types/interfaces/i-thread-comment';export { UniverThreadCommentPlugin } from './plugin';-export { IThreadCommentDataSourceService, ThreadCommentDataSourceService } from './services/tc-datasource.service';++export {+ IThreadCommentDataSourceService,+ ThreadCommentDataSourceService,+ type IThreadCommentDataSource,+ type ThreadCommentJSON,+} from './services/tc-datasource.service';// #region - all commands@@ -39,6 +44,7 @@ export type {IUpdateCommentPayload,IUpdateCommentRefMutationParams,} from './commands/mutations/comment.mutation';+export {AddCommentCommand,DeleteCommentCommand,@@ -52,8 +58,6 @@ export type {IResolveCommentCommandParams,IUpdateCommentCommandParams,IDeleteCommentTreeCommandParams,- IUpdateCommentRefCommandParams,- IUpdateCommentRefPayload,} from './commands/commands/comment.command';// #endregiondiff --git a/packages/thread-comment/src/models/thread-comment.model.ts b/packages/thread-comment/src/models/thread-comment.model.tsindex 116015fb71..998715ab91 100644--- a/packages/thread-comment/src/models/thread-comment.model.ts+++ b/packages/thread-comment/src/models/thread-comment.model.ts@@ -15,9 +15,11 @@*/import { BehaviorSubject, map, Subject } from 'rxjs';-import { CustomRangeType } from '@univerjs/core';-import type { IThreadComment } from '../types/interfaces/i-thread-comment';+import { CustomRangeType, ICommandService } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';+import type { IBaseComment, IThreadComment } from '../types/interfaces/i-thread-comment';import type { IUpdateCommentPayload, IUpdateCommentRefPayload } from '../commands/mutations/comment.mutation';+import { IThreadCommentDataSourceService } from '../services/tc-datasource.service';export type CommentUpdate = {unitId: string;@@ -26,6 +28,7 @@ export type CommentUpdate = {} & ({type: 'add';payload: IThreadComment;+ isRoot: boolean;} | {type: 'update';payload: IUpdateCommentPayload;@@ -45,19 +48,28 @@ export type CommentUpdate = {commentId: string;resolved: boolean;};+} | {+ type: 'syncUpdate';+ payload: IThreadComment;});export class ThreadCommentModel {private _commentsMap: Record<string, Record<string, Record<string, IThreadComment>>> = {};- private _commentsTreeMap: Map<string, Map<string, Map<string, string[]>>> = new Map();+ private _commentsTreeMap: Map<string, Map<string, Map<string, IThreadComment>>> = new Map();+ private _threadMap: Map<string, Map<string, IThreadComment>> = new Map();+private _commentUpdate$ = new Subject<CommentUpdate>();- private _commentsTreeMap$ = new BehaviorSubject<Record<string, Record<string, Record<string, string[]>>>>({});private _commentsMap$ = new BehaviorSubject<Record<string, Record<string, Record<string, IThreadComment>>>>({});commentUpdate$ = this._commentUpdate$.asObservable();- commentTreeMap$ = this._commentsTreeMap$.asObservable();commentMap$ = this._commentsMap$.asObservable();+ constructor(+ @Inject(IThreadCommentDataSourceService) private readonly _dataSourceService: IThreadCommentDataSourceService,+ @ICommandService private readonly _commandService: ICommandService+ ) {+ }+private _ensureCommentMap(unitId: string, subUnitId: string) {let unitMap = this._commentsMap[unitId];@@ -92,28 +104,23 @@ export class ThreadCommentModel {return subUnitMap;}+ private _ensureThreadMap(unitId: string) {+ let unitMap = this._threadMap.get(unitId);++ if (!unitMap) {+ unitMap = new Map();+ this._threadMap.set(unitId, unitMap);+ }++ return unitMap;+ }+private _refreshCommentsMap$() {this._commentsMap$.next({...this._commentsMap,});}- private _refreshCommentsTreeMap$() {- const map: Record<string, Record<string, Record<string, string[]>>> = {};- this._commentsTreeMap.forEach((unit, unitId) => {- map[unitId] = {};- const unitRecord = map[unitId];- unit.forEach((subUnit, subUnitId) => {- unitRecord[subUnitId] = {};- const subUnitRecord = unitRecord[subUnitId];- subUnit.forEach((children, key) => {- subUnitRecord[key] = children;- });- });- });- this._commentsTreeMap$.next(map);- }-ensureMap(unitId: string, subUnitId: string) {const commentMap = this._ensureCommentMap(unitId, subUnitId);const commentChildrenMap = this._ensureCommentChildrenMap(unitId, subUnitId);@@ -124,39 +131,100 @@ export class ThreadCommentModel {};}- addComment(unitId: string, subUnitId: string, comment: IThreadComment) {+ private _replaceComment(unitId: string, subUnitId: string, comment: IBaseComment) {const { commentMap, commentChildrenMap } = this.ensureMap(unitId, subUnitId);+ const currentComment = commentMap[comment.id];++ if (currentComment) {+ const newComment = {+ ...comment,+ ref: currentComment.ref,+ };+ commentMap[comment.id] = newComment;+ comment.children?.forEach((child) => {+ commentMap[child.id] = {+ ...child,+ ref: '',+ };+ });+ commentChildrenMap.set(comment.id, newComment);+ this._commentUpdate$.next({+ unitId,+ subUnitId,+ type: 'syncUpdate',+ payload: newComment,+ });- let parentId = comment.parentId;- if (parentId) {- let parent = commentMap[parentId];- // find the top root- while (parent?.parentId) {- parent = commentMap[parent.parentId];- parentId = parent.parentId!;+ if (Boolean(comment.resolved) !== Boolean(currentComment.resolved)) {+ this._commentUpdate$.next({+ unitId,+ subUnitId,+ type: 'resolve',+ payload: {+ commentId: comment.id,+ resolved: Boolean(comment.resolved),+ },+ });}+ }+ }- if (parent) {- let children = commentChildrenMap.get(parentId);- if (!children) {- children = [];- }- children.push(comment.id);- commentChildrenMap.set(parentId, children);+ async syncThreadComments(unitId: string, subUnitId: string, threadIds: string[]) {+ const comments = await this._dataSourceService.listThreadComments(unitId, subUnitId, threadIds);+ if (!comments.length) {+ return;+ }+ const deleteThreads = new Set<string>(threadIds);+ comments.forEach((comment) => {+ this._replaceComment(unitId, subUnitId, comment);+ deleteThreads.delete(comment.threadId);+ });+ deleteThreads.forEach((id) => {+ const thread = this.getThread(unitId, id);+ if (thread) {+ this.deleteComment(thread.unitId, thread.subUnitId, thread.id);}+ });+ this._refreshCommentsMap$();+ }++ addComment(unitId: string, subUnitId: string, origin: IThreadComment, shouldSync?: boolean) {+ const { commentMap, commentChildrenMap } = this.ensureMap(unitId, subUnitId);+ const comment = origin;+ const addCommentItem = (item: IThreadComment) => {+ commentMap[item.id] = item;+ this._commentUpdate$.next({+ unitId,+ subUnitId,+ type: 'add',+ payload: item,+ isRoot: !item.parentId,+ });+ };++ const parentId = comment.parentId;+ if (parentId) {+ const parent = commentMap[parentId];+ parent.children = [+ ...parent.children ?? [],+ comment,+ ];+ addCommentItem(comment);} else {- commentChildrenMap.set(comment.id, []);+ commentChildrenMap.set(comment.id, comment);+ const threadMap = this._ensureThreadMap(unitId);+ threadMap.set(comment.threadId, comment);+ addCommentItem(comment);+ comment.children?.forEach((child) => addCommentItem({+ ...child,+ ref: '',+ }));}- commentMap[comment.id] = comment;- this._commentUpdate$.next({- unitId,- subUnitId,- type: 'add',- payload: comment,- });this._refreshCommentsMap$();- this._refreshCommentsTreeMap$();+ if (shouldSync) {+ this.syncThreadComments(unitId, subUnitId, [comment.threadId]);+ }return true;}@@ -179,7 +247,6 @@ export class ThreadCommentModel {silent,});this._refreshCommentsMap$();- this._refreshCommentsTreeMap$();return true;}@@ -191,7 +258,6 @@ export class ThreadCommentModel {}oldComment.ref = payload.ref;-this._commentUpdate$.next({unitId,subUnitId,@@ -200,7 +266,6 @@ export class ThreadCommentModel {silent,});this._refreshCommentsMap$();- this._refreshCommentsTreeMap$();return true;}@@ -222,7 +287,6 @@ export class ThreadCommentModel {},});this._refreshCommentsMap$();- this._refreshCommentsTreeMap$();return true;}@@ -243,10 +307,13 @@ export class ThreadCommentModel {}const relativeUsers = new Set<string>();- const children = commentChildrenMap.get(commentId) ?? [];- const childrenComments = children?.map((childId) => commentMap[childId]!);+ const root = commentChildrenMap.get(commentId);- [current, ...childrenComments].forEach((comment) => {+ if (!root) {+ return undefined;+ }++ [root, ...root.children ?? []].forEach((comment) => {relativeUsers.add(comment.personId);comment.text.customRanges?.forEach((range) => {if (range.rangeType === CustomRangeType.MENTION) {@@ -257,7 +324,7 @@ export class ThreadCommentModel {return {root: current,- children: childrenComments,+ children: root.children ?? [],relativeUsers,};}@@ -266,19 +333,35 @@ export class ThreadCommentModel {const { commentMap, commentChildrenMap } = this.ensureMap(unitId, subUnitId);const current = commentMap[commentId];if (!current) {- return false;+ return true;}if (current.parentId) {- const children = commentChildrenMap.get(current.parentId);- if (children) {- const index = children.indexOf(commentId);- children.splice(index, 1);+ const root = commentChildrenMap.get(current.parentId);+ if (root && root.children) {+ const index = root.children.findIndex((comment) => comment.id = commentId);+ root.children.splice(index, 1);}delete commentMap[commentId];} else {delete commentMap[commentId];+ const comment = commentChildrenMap.get(commentId);commentChildrenMap.delete(commentId);+ const threadMap = this._ensureThreadMap(unitId);+ threadMap.delete(current.threadId);+ comment?.children?.forEach((child) => {+ delete commentMap[child.id];+ this._commentUpdate$.next({+ unitId,+ subUnitId,+ type: 'delete',+ payload: {+ commentId: child.id,+ isRoot: false,+ comment: child as IThreadComment,+ },+ });+ });}this._commentUpdate$.next({@@ -292,7 +375,6 @@ export class ThreadCommentModel {},});this._refreshCommentsMap$();- this._refreshCommentsTreeMap$();return true;}@@ -323,13 +405,11 @@ export class ThreadCommentModel {return Array.from(commentChildrenMap.keys());}- getRootCommentIds$(unitId: string, subUnitId: string) {- return this._commentsTreeMap$.pipe(map(- (tree) => Object.keys(tree[unitId]?.[subUnitId])- ));- }-getAll() {return this._commentsMap;}++ getThread(unitId: string, threadId: string) {+ return this._ensureThreadMap(unitId).get(threadId);+ }}diff --git a/packages/thread-comment/src/plugin.ts b/packages/thread-comment/src/plugin.tsindex c9689236e0..25faf140e0 100644--- a/packages/thread-comment/src/plugin.ts+++ b/packages/thread-comment/src/plugin.ts@@ -44,9 +44,10 @@ export class UniverThreadCommentPlugin extends Plugin {override onStarting(injector: Injector): void {(mergeOverrideWithDependencies([+ [IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }],[ThreadCommentModel],[ThreadCommentResourceController],- [IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }],+], this._config?.overrides) as Dependency[]).forEach((d) => {injector.add(d);diff --git a/packages/thread-comment/src/services/tc-datasource.service.ts b/packages/thread-comment/src/services/tc-datasource.service.tsindex 387f87c846..5187b052c9 100644--- a/packages/thread-comment/src/services/tc-datasource.service.ts+++ b/packages/thread-comment/src/services/tc-datasource.service.ts@@ -15,44 +15,142 @@*/import { createIdentifier } from '@wendellhu/redi';-import type { IThreadComment } from '../types/interfaces/i-thread-comment';+import type { Nullable } from '@univerjs/core';+import { Disposable } from '@univerjs/core';+import type { IBaseComment, IThreadComment } from '../types/interfaces/i-thread-comment';-export type ThreadCommentJSON = { id: string } & Partial<Omit<IThreadComment, 'id'>>;+export type ThreadCommentJSON = {+ id: string;+ threadId: string;+ ref: string;+} & Partial<Omit<IThreadComment, 'id' | 'threadId' | 'ref'>>;++type Success = boolean;++export interface IThreadCommentDataSource {+ /**+ * handler for add-comment, throw error means fail and stop the process.+ */+ addComment: (comment: IThreadComment) => Promise<IThreadComment>;+ /**+ * handler for update-comment, throw error means fail and stop the process.+ */+ updateComment: (comment: IThreadComment) => Promise<Success>;+ resolveComment: (comment: IThreadComment) => Promise<Success>;+ /**+ * handler for delete-comment, throw error means fail and stop the process.+ */+ deleteComment: (unitId: string, subUnitId: string, threadId: string, commentId: string,) => Promise<Success>;+ /**+ * handler for batch-fetch-comment, throw error means fail and stop the process.+ */+ listComments: (unitId: string, subUnitId: string, threadId: string[]) => Promise<IBaseComment[]>;+ saveCommentToSnapshot: (comment: IThreadComment) => ThreadCommentJSON;+}export interface IThreadCommentDataSourceService {+ dataSource: Nullable<IThreadCommentDataSource>;++ /**+ * should sync update mutations to collaboration-server+ */+ syncUpdateMutationToColla: boolean;++ /**+ * handler for add-comment, throw error means fail and stop the process.+ */addComment: (comment: IThreadComment) => Promise<IThreadComment>;- updateComment: (comment: IThreadComment) => Promise<boolean>;- deleteComment: (commentId: string) => Promise<boolean>;- deleteCommentBatch: (commentIds: string[]) => Promise<boolean>;- loadFormSnapshot: (unitComments: Record<string, ThreadCommentJSON[]>) => Promise<Record<string, IThreadComment[]>>;- saveToSnapshot: (unitComments: Record<string, IThreadComment[]>) => Record<string, ThreadCommentJSON[]>;+ /**+ * handler for update-comment, throw error means fail and stop the process.+ */+ updateComment: (comment: IThreadComment) => Promise<Success>;+ /**+ * handler for resolve-comment, throw error means fail and stop the process.+ */+ resolveComment: (comment: IThreadComment) => Promise<Success>;+ /**+ * handler for delete-comment, throw error means fail and stop the process.+ */+ deleteComment: (unitId: string, subUnitId: string, threadId: string, commentId: string) => Promise<Success>;+ saveToSnapshot: (unitComments: Record<string, IThreadComment[]>, unitId: string) => Record<string, ThreadCommentJSON[]>;+ getThreadComment: (unitId: string, subUnitId: string, threadId: string) => Promise<Nullable<IBaseComment>>;+ listThreadComments: (unitId: string, subUnitId: string, threadId: string[]) => Promise<IBaseComment[]>;}/*** Preserve for import async comment system*/-export class ThreadCommentDataSourceService implements IThreadCommentDataSourceService {+export class ThreadCommentDataSourceService extends Disposable implements IThreadCommentDataSourceService {+ private _dataSource: Nullable<IThreadCommentDataSource> = null;+ syncUpdateMutationToColla = true;++ set dataSource(dataSource: Nullable<IThreadCommentDataSource>) {+ this._dataSource = dataSource;+ }++ get dataSource() {+ return this._dataSource;+ }++ constructor() {+ super();+ }++ async getThreadComment(unitId: string, subUnitId: string, threadId: string): Promise<Nullable<IBaseComment>> {+ if (this._dataSource) {+ const comments = await this._dataSource.listComments(unitId, subUnitId, [threadId]);+ return comments[0];+ }++ return null;+ }+async addComment(comment: IThreadComment) {+ if (this._dataSource) {+ return this._dataSource.addComment(comment);+ }return comment;}- async updateComment(_comment: IThreadComment) {+ async updateComment(comment: IThreadComment) {+ if (this._dataSource) {+ return this._dataSource.updateComment(comment);+ }return true;}- async deleteComment(_commentId: string) {+ async resolveComment(comment: IThreadComment) {+ if (this._dataSource) {+ return this._dataSource.resolveComment(comment);+ }return true;}- async deleteCommentBatch(_commentIds: string[]) {+ async deleteComment(unitId: string, subUnitId: string, threadId: string, commentId: string) {+ if (this._dataSource) {+ return this._dataSource.deleteComment(unitId, subUnitId, threadId, commentId);+ }return true;}- async loadFormSnapshot(unitComments: Record<string, ThreadCommentJSON[]>) {- return unitComments as Record<string, IThreadComment[]>;+ async listThreadComments(unitId: string, subUnitId: string, threadIds: string[]) {+ if (this.dataSource) {+ return this.dataSource.listComments(unitId, subUnitId, threadIds);+ }++ return [];}- saveToSnapshot(unitComments: Record<string, IThreadComment[]>) {+ saveToSnapshot(unitComments: Record<string, IThreadComment[]>, unitId: string) {+ if (this._dataSource) {+ const map: Record<string, ThreadCommentJSON[]> = {};+ Object.keys(unitComments).forEach((subUnitId) => {+ const comments = unitComments[subUnitId];+ map[subUnitId] = comments.map(this.dataSource!.saveCommentToSnapshot);+ });+ return map;+ }+return unitComments;}}diff --git a/packages/thread-comment/src/types/interfaces/i-thread-comment.ts b/packages/thread-comment/src/types/interfaces/i-thread-comment.tsindex da79a1d5a0..129a91c1a4 100644--- a/packages/thread-comment/src/types/interfaces/i-thread-comment.ts+++ b/packages/thread-comment/src/types/interfaces/i-thread-comment.ts@@ -22,18 +22,23 @@ export interface IThreadCommentMention {icon?: string;}-export interface IThreadComment {+export interface IBaseComment {id: string;- ref: string;+ threadId: string;dT: string;updateT?: string;personId: string;- parentId?: string;text: IDocumentBody;attachments?: string[];- resolved?: boolean;updated?: boolean;+ mentions?: string[];+ parentId?: string;+ resolved?: boolean;unitId: string;subUnitId: string;- mentions?: string[];+ children?: IBaseComment[];+}++export interface IThreadComment extends IBaseComment {+ ref: string;}diff --git a/packages/ui/src/views/components/sidebar/Sidebar.tsx b/packages/ui/src/views/components/sidebar/Sidebar.tsxindex 9784a77f41..1d85768f22 100644--- a/packages/ui/src/views/components/sidebar/Sidebar.tsx+++ b/packages/ui/src/views/components/sidebar/Sidebar.tsx@@ -77,7 +77,6 @@ export function Sidebar() {sidebarService.sidebarOptions$.next(options);options?.onClose?.();}-return (<section className={_className} style={{ width }}><section className={styles.sidebarContainer}>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0238ee3274..829ac194b9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -222,6 +222,9 @@ importers:'@univerjs/docs-drawing-ui':specifier: workspace:*version: link:../packages/docs-drawing-ui+ '@univerjs/docs-thread-comment-ui':+ specifier: workspace:*+ version: link:../packages/docs-thread-comment-ui'@univerjs/docs-ui':specifier: workspace:*version: link:../packages/docs-ui@@ -722,6 +725,64 @@ importers:specifier: ^1.6.0version: 1.6.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ packages/docs-thread-comment-ui:+ dependencies:+ '@univerjs/docs':+ specifier: workspace:*+ version: link:../docs+ '@univerjs/docs-ui':+ specifier: workspace:*+ version: link:../docs-ui+ '@univerjs/engine-render':+ specifier: workspace:*+ version: link:../engine-render+ '@univerjs/icons':+ specifier: ^0.1.56+ '@univerjs/thread-comment':+ specifier: workspace:*+ version: link:../thread-comment+ '@univerjs/thread-comment-ui':+ specifier: workspace:*+ version: link:../thread-comment-ui+ devDependencies:+ '@univerjs/core':+ specifier: workspace:*+ version: link:../core+ '@univerjs/design':+ specifier: workspace:*+ version: link:../design+ '@univerjs/engine-formula':+ specifier: workspace:*+ version: link:../engine-formula+ '@univerjs/shared':+ specifier: workspace:*+ version: link:../../common/shared+ '@univerjs/ui':+ specifier: workspace:*+ version: link:../ui+ '@wendellhu/redi':+ specifier: 0.15.4+ version: 0.15.4+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ react:+ specifier: 18.3.1+ version: 18.3.1+ rxjs:+ specifier: ^7.8.1+ version: 7.8.1+ typescript:+ specifier: ^5.4.5+ version: 5.4.5+ vite:+ specifier: ^5.2.12+ vitest:+ specifier: ^1.6.0+ version: 1.6.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+packages/docs-ui:devDependencies:'@types/react':@@ -2215,6 +2276,12 @@ importers:'@univerjs/design':specifier: workspace:*version: link:../design+ '@univerjs/docs':+ specifier: workspace:*+ version: link:../docs+ '@univerjs/engine-render':+ specifier: workspace:*+ version: link:../engine-render'@univerjs/shared':specifier: workspace:*version: link:../../common/shared