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(docs): support inline formula custom ranges (#7360)
Univer9da46c436573
diff --git a/packages/docs-find-replace/src/controllers/__tests__/utils.spec.ts b/packages/docs-find-replace/src/controllers/__tests__/utils.spec.tsindex e9ffc5f4f4..a60ecada63 100644--- a/packages/docs-find-replace/src/controllers/__tests__/utils.spec.ts+++ b/packages/docs-find-replace/src/controllers/__tests__/utils.spec.ts@@ -74,4 +74,31 @@ describe('findDocRanges', () => {{ startOffset: 4, endOffset: 7, replaceable: false },]);});++ it('maps matches in consumer-facing replacement text back to the native entity', () => {+ const body: IDocumentBody = {+ dataStream: 'A\uFFFCC\r\n',+ customRanges: [{+ startIndex: 1,+ endIndex: 1,+ rangeId: 'formula-1',+ rangeType: CustomRangeType.CUSTOM,+ wholeEntity: true,+ }],+ };++ expect(findDocRanges(body, query('42'), false, {+ text: 'A42C\r\n',+ characters: [+ { startOffset: 0, endOffset: 1, replaceable: true },+ { startOffset: 1, endOffset: 2, replaceable: false },+ { startOffset: 1, endOffset: 2, replaceable: false },+ { startOffset: 2, endOffset: 3, replaceable: true },+ { startOffset: 3, endOffset: 4, replaceable: true },+ { startOffset: 4, endOffset: 5, replaceable: true },+ ],+ })).toEqual([+ { startOffset: 1, endOffset: 2, replaceable: false },+ ]);+ });});diff --git a/packages/docs-find-replace/src/controllers/utils.ts b/packages/docs-find-replace/src/controllers/utils.tsindex f5e04b8c7a..2be5b90835 100644--- a/packages/docs-find-replace/src/controllers/utils.ts+++ b/packages/docs-find-replace/src/controllers/utils.ts@@ -15,6 +15,7 @@*/import type { IDocumentBody } from '@univerjs/core';+import type { IResolvedDocText } from '@univerjs/docs';import type { IFindQuery } from '@univerjs/find-replace';import { regexp } from '@univerjs/core';@@ -24,26 +25,51 @@ export interface IDocFindRange {replaceable: boolean;}-export function findDocRanges(body: IDocumentBody, query: IFindQuery, disabled: boolean): IDocFindRange[] {+export function findDocRanges(+ body: IDocumentBody,+ query: IFindQuery,+ disabled: boolean,+ resolved: IResolvedDocText = {+ text: body.dataStream,+ characters: Array.from({ length: body.dataStream.length }, (_value, index) => ({+ startOffset: index,+ endOffset: index + 1,+ replaceable: true,+ })),+ }+): IDocFindRange[] {if (!query.findString) return [];const expression = regexp.createLiteralRegExp(query.findString, query.caseSensitive ? 'gu' : 'giu');const wordRanges = query.matchesTheWholeWord- ? new Set(Array.from(new Intl.Segmenter(undefined, { granularity: 'word' }).segment(body.dataStream))+ ? new Set(Array.from(new Intl.Segmenter(undefined, { granularity: 'word' }).segment(resolved.text)).filter((item) => item.isWordLike).map((item) => `${item.index}:${item.index + item.segment.length}`)): null;- return Array.from(body.dataStream.matchAll(expression))+ return Array.from(resolved.text.matchAll(expression)).filter((match) => {return wordRanges?.has(`${match.index}:${match.index + match[0].length}`) ?? true;})- .map((match) => {- const startOffset = match.index;- const endOffset = startOffset + match[0].length;+ .flatMap((match) => {+ const characters = resolved.characters.slice(+ match.index,+ match.index + match[0].length+ );+ if (!characters.length) {+ return [];+ }+ const startOffset = Math.min(...characters.map((character) => character.startOffset));+ const endOffset = Math.max(...characters.map((character) => character.endOffset));const overlapsWholeEntity = body.customRanges?.some((range) =>range.wholeEntity && range.startIndex < endOffset && range.endIndex + 1 > startOffset) ?? false;- return { startOffset, endOffset, replaceable: !disabled && !overlapsWholeEntity };+ return [{+ startOffset,+ endOffset,+ replaceable: !disabled &&+ !overlapsWholeEntity &&+ characters.every((character) => character.replaceable),+ }];});}diff --git a/packages/docs-find-replace/src/models/__tests__/docs-find.model.spec.ts b/packages/docs-find-replace/src/models/__tests__/docs-find.model.spec.tsindex 61e63d1a84..5737ce725d 100644--- a/packages/docs-find-replace/src/models/__tests__/docs-find.model.spec.ts+++ b/packages/docs-find-replace/src/models/__tests__/docs-find.model.spec.ts@@ -18,7 +18,7 @@ import type { ICommand } from '@univerjs/core';import type { Documents, DocumentSkeleton, ITextRangeWithStyle } from '@univerjs/engine-render';import type { IFindQuery } from '@univerjs/find-replace';import { ICommandService } from '@univerjs/core';-import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DocSelectionManagerService, DocSkeletonManagerService, DocTextResolverService, RichTextEditingMutation } from '@univerjs/docs';import { DocBackScrollRenderController, getTextRangeFromCharIndex } from '@univerjs/docs-ui';import { createCommandTestBed } from '@univerjs/docs-ui/commands/commands/__tests__/create-command-test-bed';import { IRenderManagerService } from '@univerjs/engine-render';@@ -55,7 +55,10 @@ function createModelTestBed(dataStream = 'cat xx cat\r\n') {const scrollToRange = vi.fn();const testBed = createCommandTestBed({ id: 'test-doc', body: { dataStream }, documentStyle: {} },- [[DocBackScrollRenderController, { useValue: { scrollToRange } }]]+ [+ [DocBackScrollRenderController, { useValue: { scrollToRange } }],+ [DocTextResolverService],+ ]);const commandService = testBed.get(ICommandService);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);@@ -154,6 +157,20 @@ describe('DocsFindModel', () => {univer.dispose();});+ it('rescans when a consumer-facing text projection changes', async () => {+ vi.useFakeTimers();+ const { get, model, univer } = createModelTestBed();+ model.start(docsQuery('cat'));+ const update = firstValueFrom(model.matchesUpdate$);++ get(DocTextResolverService).notifyTextChanged('test-doc');+ await vi.advanceTimersByTimeAsync(250);++ expect(await update).toEqual(model.getMatches());+ model.dispose();+ univer.dispose();+ });+it('disposes every TextRange highlight', () => {const { model, skeletonManager, get, univer } = createModelTestBed();vi.mocked(skeletonManager.getSkeleton).mockReturnValue({} as DocumentSkeleton);diff --git a/packages/docs-find-replace/src/models/docs-find.model.ts b/packages/docs-find-replace/src/models/docs-find.model.tsindex 5175047f39..6f92ffe122 100644--- a/packages/docs-find-replace/src/models/docs-find.model.ts+++ b/packages/docs-find-replace/src/models/docs-find.model.ts@@ -27,11 +27,15 @@ import {ThemeService,toDisposable,} from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';+import {+ DocSelectionManagerService,+ DocTextResolverService,+ RichTextEditingMutation,+} from '@univerjs/docs';import { DocBackScrollRenderController, getTextRangeFromCharIndex } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { FindModel } from '@univerjs/find-replace';-import { debounceTime, filter, Subject } from 'rxjs';+import { debounceTime, filter, merge, Subject } from 'rxjs';import { DocsReplaceCommand } from '../commands/commands/docs-replace.command';import { findDocRanges } from '../controllers/utils';@@ -61,15 +65,21 @@ export class DocsFindModel extends FindModel {@Inject(DocSelectionManagerService) private readonly _selectionManager: DocSelectionManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@ICommandService private readonly _commandService: ICommandService,- @Inject(ThemeService) private readonly _themeService: ThemeService+ @Inject(ThemeService) private readonly _themeService: ThemeService,+ @Inject(DocTextResolverService)+ private readonly _textResolverService: DocTextResolverService) {super();this.unitId = _doc.getUnitId();- this.disposeWithMe(toDisposable(fromCallback(this._commandService.onCommandExecuted.bind(this._commandService))+ this.disposeWithMe(toDisposable(merge(+ fromCallback(this._commandService.onCommandExecuted.bind(this._commandService))+ .pipe(filter(([command]) => command.id === RichTextEditingMutation.id &&+ getUnitId(command.params) === this.unitId)),+ this._textResolverService.textChanged$+ .pipe(filter((unitId) => unitId === this.unitId))+ ).pipe(- filter(([command]) => command.id === RichTextEditingMutation.id &&- (command.params as { unitId?: string })?.unitId === this.unitId),debounceTime(220)).subscribe(() => this._scan(true))));@@ -190,7 +200,12 @@ export class DocsFindModel extends FindModel {}const previousStart = this.currentMatch?.range.startOffset;- this._matches = findDocRanges(body, this._query, !!this._doc.getSnapshot().disabled)+ this._matches = findDocRanges(+ body,+ this._query,+ !!this._doc.getSnapshot().disabled,+ this._textResolverService.resolve(this.unitId, body)+ ).map((range) => ({provider: DOCS_FIND_REPLACE_PROVIDER,unitId: this.unitId,@@ -272,3 +287,12 @@ export class DocsFindModel extends FindModel {this._highlights = [];}}++function getUnitId(params: unknown): string | undefined {+ return params != null &&+ typeof params === 'object' &&+ 'unitId' in params &&+ typeof params.unitId === 'string'+ ? params.unitId+ : undefined;+}diff --git a/packages/docs-find-replace/src/services/__tests__/docs-find-replace.provider.spec.ts b/packages/docs-find-replace/src/services/__tests__/docs-find-replace.provider.spec.tsindex 0704944ba4..ecd7d95531 100644--- a/packages/docs-find-replace/src/services/__tests__/docs-find-replace.provider.spec.ts+++ b/packages/docs-find-replace/src/services/__tests__/docs-find-replace.provider.spec.ts@@ -17,7 +17,7 @@import type { UnitModel } from '@univerjs/core';import type { IFindQuery } from '@univerjs/find-replace';import { UniverInstanceType } from '@univerjs/core';-import { DocSkeletonManagerService } from '@univerjs/docs';+import { DocSkeletonManagerService, DocTextResolverService } from '@univerjs/docs';import { createCommandTestBed } from '@univerjs/docs-ui/commands/commands/__tests__/create-command-test-bed';import { IRenderManagerService } from '@univerjs/engine-render';import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';@@ -37,7 +37,10 @@ const query: IFindQuery = {describe('DocsFindReplaceProvider', () => {it('supports Docs and creates one model for the current document', async () => {- const testBed = createCommandTestBed({ id: 'test-doc', body: { dataStream: 'cat\r\n' }, documentStyle: {} });+ const testBed = createCommandTestBed(+ { id: 'test-doc', body: { dataStream: 'cat\r\n' }, documentStyle: {} },+ [[DocTextResolverService]]+ );const skeleton = testBed.get(IRenderManagerService).getRenderUnitById('test-doc')!.with(DocSkeletonManagerService);vi.spyOn(skeleton, 'getSkeleton').mockReturnValue(null as never);testBed.injector.add([DocsFindReplaceProvider]);diff --git a/packages/docs-ui/src/basics/doc-custom-range-chrome.spec.ts b/packages/docs-ui/src/basics/doc-custom-range-chrome.spec.tsnew file mode 100644index 0000000000..7445296fd6--- /dev/null+++ b/packages/docs-ui/src/basics/doc-custom-range-chrome.spec.ts@@ -0,0 +1,104 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { UniverRenderingContext } from '@univerjs/engine-render';+import { ThemeService } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import {+ DOC_CUSTOM_RANGE_CHROME_BACKGROUND_ALPHA,+ DOC_CUSTOM_RANGE_CHROME_RADIUS,+ drawDocCustomRangeChrome,+ resolveDocCustomRangeChromeTheme,+} from './doc-custom-range-chrome';++describe('Doc custom range chrome', () => {+ it('derives a subtle background and border from the current primary theme token', () => {+ const themeService = new ThemeService();+ const currentTheme = themeService.getCurrentTheme();+ themeService.setTheme({+ ...currentTheme,+ primary: {+ ...currentTheme.primary,+ 600: '#123456',+ },+ });++ expect(resolveDocCustomRangeChromeTheme(themeService)).toEqual({+ background: `rgba(18,52,86,${DOC_CUSTOM_RANGE_CHROME_BACKGROUND_ALPHA})`,+ border: '#123456',+ });+ expect(DOC_CUSTOM_RANGE_CHROME_RADIUS).toBe(1);+ themeService.dispose();+ });++ it('draws a filled rounded rectangle before its outline', () => {+ const calls: string[] = [];+ const ctx = {+ beginPath: vi.fn(() => {+ calls.push('beginPath');+ }),+ fill: vi.fn(() => {+ calls.push('fill');+ }),+ fillStyle: '',+ lineWidth: 0,+ restore: vi.fn(() => {+ calls.push('restore');+ }),+ roundRect: vi.fn(() => {+ calls.push('roundRect');+ }),+ save: vi.fn(() => {+ calls.push('save');+ }),+ stroke: vi.fn(() => {+ calls.push('stroke');+ }),+ strokeStyle: '',+ } satisfies Pick<+ UniverRenderingContext,+ | 'beginPath'+ | 'fill'+ | 'fillStyle'+ | 'lineWidth'+ | 'restore'+ | 'roundRect'+ | 'save'+ | 'stroke'+ | 'strokeStyle'+ >;++ drawDocCustomRangeChrome(ctx, {+ bottom: 28,+ left: 10,+ right: 50,+ top: 8,+ }, {+ background: 'rgba(18,52,86,0.07)',+ border: '#123456',+ });++ expect(ctx.roundRect).toHaveBeenCalledWith(10, 8, 40, 20, 1);+ expect(calls).toEqual([+ 'save',+ 'beginPath',+ 'roundRect',+ 'fill',+ 'stroke',+ 'restore',+ ]);+ });+});diff --git a/packages/docs-ui/src/basics/doc-custom-range-chrome.ts b/packages/docs-ui/src/basics/doc-custom-range-chrome.tsnew file mode 100644index 0000000000..6bb49f63d3--- /dev/null+++ b/packages/docs-ui/src/basics/doc-custom-range-chrome.ts@@ -0,0 +1,80 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ThemeService } from '@univerjs/core';+import type { UniverRenderingContext } from '@univerjs/engine-render';+import { ColorKit } from '@univerjs/core';++export const DOC_CUSTOM_RANGE_CHROME_RADIUS = 1;+export const DOC_CUSTOM_RANGE_CHROME_BACKGROUND_ALPHA = 0.07;++export interface IDocCustomRangeChromeRect {+ bottom: number;+ left: number;+ right: number;+ top: number;+}++export interface IDocCustomRangeChromeTheme {+ background: string;+ border: string;+}++export function resolveDocCustomRangeChromeTheme(+ themeService: ThemeService+): IDocCustomRangeChromeTheme {+ const primary = themeService.getColorFromTheme('primary.600');++ return {+ background: new ColorKit(primary)+ .setAlpha(DOC_CUSTOM_RANGE_CHROME_BACKGROUND_ALPHA)+ .toRgbString(),+ border: primary,+ };+}++export function drawDocCustomRangeChrome(+ ctx: Pick<+ UniverRenderingContext,+ | 'beginPath'+ | 'fill'+ | 'fillStyle'+ | 'lineWidth'+ | 'restore'+ | 'roundRect'+ | 'save'+ | 'stroke'+ | 'strokeStyle'+ >,+ rect: IDocCustomRangeChromeRect,+ theme: IDocCustomRangeChromeTheme+): void {+ ctx.save();+ ctx.fillStyle = theme.background;+ ctx.strokeStyle = theme.border;+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.roundRect(+ rect.left,+ rect.top,+ rect.right - rect.left,+ rect.bottom - rect.top,+ DOC_CUSTOM_RANGE_CHROME_RADIUS+ );+ ctx.fill();+ ctx.stroke();+ ctx.restore();+}diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.tsindex 5fc44048b3..8023e9cc17 100644--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts@@ -21,6 +21,7 @@ import type { IInnerCutCommandParams, IInnerPasteCommandParams } from '../clipboimport {BooleanNumber,CustomDecorationType,+ CustomRangeType,DataStreamTreeTokenType,DOC_RANGE_TYPE,EDITOR_ACTIVATED,@@ -394,6 +395,43 @@ describe('test cases in clipboard', () => {expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();});+ it('creates independent Custom Range ids for every pasted selection', async () => {+ const sourceRange = {+ startIndex: 0,+ endIndex: 0,+ rangeId: 'source-range',+ rangeType: CustomRangeType.CUSTOM,+ wholeEntity: true,+ };+ const initialTargetRange = {+ ...sourceRange,+ rangeId: 'initial-target-range',+ };++ await commandService.executeCommand(InnerPasteCommand.id, {+ segmentId: '',+ doc: {+ body: {+ dataStream: 'x',+ customRanges: [initialTargetRange],+ },+ },+ customRangeMappings: [{+ sourceRange,+ targetRange: initialTargetRange,+ }],+ textRanges: [],+ } satisfies IInnerPasteCommandParams);++ const pastedRangeIds = getDocumentSnapshot()?.body?.customRanges?.map((range) => range.rangeId) ?? [];+ expect(pastedRangeIds).toHaveLength(2);+ expect(new Set(pastedRangeIds).size).toBe(2);+ expect(pastedRangeIds).not.toContain(sourceRange.rangeId);+ expect(pastedRangeIds).not.toContain(initialTargetRange.rangeId);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+it('Should insert pasted content at a collapsed cursor without deleting nearby text', async () => {const selectionManager = get(DocSelectionManagerService);selectionManager.__TEST_ONLY_add([{diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.tsindex 509017b6a6..fb9a0f9ec5 100644--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts@@ -14,22 +14,10 @@* limitations under the License.*/-import type {- DocumentDataModel,- IAccessor,- ICommand,- ICustomTable,- IDisposable,- IDocumentData,- IDrawingParam,- IMutationInfo,- ITextRange,- JSONXActions,- Nullable,-} from '@univerjs/core';+import type { DocumentDataModel, IAccessor, ICommand, ICustomTable, IDisposable, IDocumentData, IDrawingParam, IMutationInfo, ITextRange, JSONXActions, Nullable } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';import type { DocumentViewModel, IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';-import type { IDocClipboardPasteBlockRangeMapping, IDocClipboardPasteCustomBlockMapping } from '../../services/clipboard/doc-paste-mutation-adapter.service';+import type { IDocClipboardPasteBlockRangeMapping, IDocClipboardPasteCustomBlockMapping, IDocClipboardPasteCustomRangeMapping } from '../../services/clipboard/doc-paste-mutation-adapter.service';import {BuildTextUtils,CommandType,@@ -65,6 +53,7 @@ export interface IInnerPasteCommandParams {segmentId: string;doc: Partial<IDocumentData>;textRanges: ITextRangeWithStyle[];+ customRangeMappings?: IDocClipboardPasteCustomRangeMapping[];}const UNITS = SHEET_EDITOR_UNITS;@@ -75,7 +64,12 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {// eslint-disable-next-line max-lines-per-function, complexityhandler: async (accessor, params: IInnerPasteCommandParams) => {- const { segmentId, textRanges, doc } = params;+ const {+ customRangeMappings = [],+ segmentId,+ textRanges,+ doc,+ } = params;const commandService = accessor.get(ICommandService);const undoRedoService = accessor.get(IUndoRedoService);const docSelectionManagerService = accessor.get(DocSelectionManagerService);@@ -145,6 +139,15 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {const cloneBody = Tools.deepClone(body);const blockRangeMappings: IDocClipboardPasteBlockRangeMapping[] = [];const customBlockMappings: IDocClipboardPasteCustomBlockMapping[] = [];+ const selectionCustomRangeMappings = customRangeMappings.map(({ sourceRange }) => ({+ sourceRange,+ targetRange: BuildTextUtils.customRange.copyCustomRange(sourceRange),+ }));+ if (selectionCustomRangeMappings.length > 0) {+ cloneBody.customRanges = selectionCustomRangeMappings.map(+ ({ targetRange }) => targetRange+ );+ }if (hasBlockRange) {cloneBody.blockRanges!.forEach((targetBlockRange, index) => {@@ -201,7 +204,14 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {});}- if ((blockRangeMappings.length > 0 || customBlockMappings.length > 0) && pasteAdapterService) {+ if (+ (+ blockRangeMappings.length > 0 ||+ customBlockMappings.length > 0 ||+ selectionCustomRangeMappings.length > 0+ ) &&+ pasteAdapterService+ ) {const mutationInfos = pasteAdapterService.getPasteMutationInfos({unitId,segmentId,@@ -209,6 +219,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {sourceBody: body,targetBody: cloneBody,blockRangeMappings,+ customRangeMappings: selectionCustomRangeMappings,customBlockMappings,});diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex 7440f2b321..07fe40631d 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -23,6 +23,16 @@ export {addCustomDecorationFactory,deleteCustomDecorationFactory,} from './basics/custom-decoration-factory';+export {+ DOC_CUSTOM_RANGE_CHROME_BACKGROUND_ALPHA,+ DOC_CUSTOM_RANGE_CHROME_RADIUS,+ drawDocCustomRangeChrome,+ resolveDocCustomRangeChromeTheme,+} from './basics/doc-custom-range-chrome';+export type {+ IDocCustomRangeChromeRect,+ IDocCustomRangeChromeTheme,+} from './basics/doc-custom-range-chrome';export * from './basics/docs-view-key';export { hasParagraphInTable } from './basics/paragraph';export { AfterSpaceCommand, EnterCommand, TabCommand } from './commands/commands/auto-format.command';@@ -199,7 +209,11 @@ export { menuSchema as DocsUIMenuSchema } from './menu/schema';export { UniverDocsUIPlugin } from './plugin';export * from './services';export { IDocClipboardService } from './services/clipboard/clipboard.service';-export type { IDocClipboardHook } from './services/clipboard/clipboard.service';+export type {+ IDocClipboardCopyContentContext,+ IDocClipboardHook,+ IDocClipboardPasteContext,+} from './services/clipboard/clipboard.service';export {DocClipboardPasteAdapterService,IDocClipboardPasteAdapterService,@@ -208,6 +222,7 @@ export type {IDocClipboardPasteAdapter,IDocClipboardPasteBlockRangeMapping,IDocClipboardPasteCustomBlockMapping,+ IDocClipboardPasteCustomRangeMapping,IDocClipboardPasteMutationInfoParams,IDocClipboardPasteMutationInfos,} from './services/clipboard/doc-paste-mutation-adapter.service';diff --git a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.tsindex 237ce8af94..372894d885 100644--- a/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__tests__/clipboard.service.spec.ts@@ -16,6 +16,7 @@import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';+import type { IDocClipboardPasteAdapter } from '../doc-paste-mutation-adapter.service';import {BooleanNumber,DataStreamTreeTokenType,@@ -33,6 +34,10 @@ import { describe, expect, it, vi } from 'vitest';import { createCommandTestBed } from '../../../commands/commands/__tests__/create-command-test-bed';import { CutContentCommand, InnerPasteCommand } from '../../../commands/commands/clipboard.inner.command';import { DocClipboardService, getTableClipboardBodySlice, IDocClipboardService } from '../clipboard.service';+import {+ DocClipboardPasteAdapterService,+ IDocClipboardPasteAdapterService,+} from '../doc-paste-mutation-adapter.service';import {createInternalClipboardFragment,DOC_INTERNAL_FRAGMENT_MIME,@@ -845,3 +850,135 @@ describe('DocClipboardService table copy helpers', () => {testBed.univer.dispose();});});++describe('DocClipboardService copy text hooks', () => {+ it('uses onCopyContent for plain text while preserving the internal document fragment', async () => {+ const clipboard = new TestClipboardInterfaceService();+ const documentData: IDocumentData = {+ id: 'copy-content-hook-doc',+ body: {+ dataStream: 'A\uFFFCC\r\n',+ paragraphs: [{+ paragraphId: 'para_docs_ui_clipboard_copy_hook',+ startIndex: 3,+ }],+ customRanges: [{+ startIndex: 1,+ endIndex: 1,+ rangeId: 'formula-1',+ rangeType: 0,+ wholeEntity: true,+ }],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useValue: clipboard }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: documentData.id,+ subUnitId: '',+ });+ const service = testBed.get(IDocClipboardService);+ service.addClipboardHook({+ onCopyContent: (start, end, context) => {+ expect([start, end]).toEqual([0, 3]);+ expect(context.unitId).toBe(documentData.id);+ expect(context.segmentId).toBe('');+ expect(context.body.dataStream).toBe(documentData.body?.dataStream);+ return 'A42C';+ },+ });++ expect(await service.copy(SliceBodyType.copy, [{+ startOffset: 0,+ endOffset: 3,+ collapsed: false,+ segmentId: '',+ }])).toBe(true);+ expect(clipboard.writes[0].text).toBe('A42C');+ const internalJson = clipboard.writes[0].custom?.[DOC_INTERNAL_FRAGMENT_MIME];+ expect(parseInternalClipboardFragment(internalJson)?.body?.dataStream)+ .toContain('\uFFFC');++ testBed.univer.dispose();+ });++ it('passes source-to-target Custom Range identity mappings to paste adapters', async () => {+ const clipboard = new TestClipboardInterfaceService();+ const documentData: IDocumentData = {+ id: 'custom-range-mapping-doc',+ body: {+ dataStream: '\uFFFC\r\n',+ paragraphs: [{+ paragraphId: 'para_docs_ui_clipboard_mapping',+ startIndex: 1,+ }],+ customRanges: [{+ startIndex: 0,+ endIndex: 0,+ rangeId: 'source-range',+ rangeType: 0,+ wholeEntity: true,+ }],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useValue: clipboard }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ [IDocClipboardPasteAdapterService, {+ useClass: DocClipboardPasteAdapterService,+ }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const mappings = vi.fn<+ NonNullable<IDocClipboardPasteAdapter['getPasteMutationInfos']>+ >(() => ({+ redoMutations: [],+ undoMutations: [],+ }));+ testBed.get(IDocClipboardPasteAdapterService).registerAdapter({+ getPasteMutationInfos: mappings,+ });+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: documentData.id,+ subUnitId: '',+ });+ const service = testBed.get(IDocClipboardService);++ expect(await service.copy(SliceBodyType.copy, [{+ startOffset: 0,+ endOffset: 1,+ collapsed: false,+ segmentId: '',+ }])).toBe(true);+ selectionManager.__TEST_ONLY_add([{+ startOffset: 1,+ endOffset: 1,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ expect(await service.paste()).toBe(true);++ const firstCall = mappings.mock.calls[0];+ if (!firstCall) {+ throw new Error('Expected the paste adapter to be called.');+ }+ const mapping = firstCall[0].customRangeMappings?.[0];+ if (!mapping) {+ throw new Error('Expected one Custom Range mapping.');+ }+ expect(mapping.sourceRange.rangeId).toBe('source-range');+ expect(mapping.targetRange.rangeId).not.toBe('source-range');++ testBed.univer.dispose();+ });+});diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex fa087bed79..d6fe666527 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -83,11 +83,22 @@ export interface IDocClipboardCopyDocDataContext {sourceDocuments: IDocumentData[];}+export interface IDocClipboardCopyContentContext {+ body: IDocumentBody;+ segmentId?: string;+ unitId: string;+}++export interface IDocClipboardPasteContext {+ documentData: Partial<IDocumentData>;+ targetUnitId: string;+}+export interface IDocClipboardHook {onCopyDocData?(doc: Partial<IDocumentData>, context: IDocClipboardCopyDocDataContext): Partial<IDocumentData>;onCopyProperty?(start: number, end: number): IClipboardPropertyItem;- onCopyContent?(start: number, end: number): string;- onBeforePaste?: (body: IDocumentBody) => IDocumentBody;+ onCopyContent?(start: number, end: number, context: IDocClipboardCopyContentContext): string;+ onBeforePaste?: (body: IDocumentBody, context: IDocClipboardPasteContext) => IDocumentBody;onBeforePasteImage?: (file: File) => Promise<{ source: string; imageSourceType: ImageSourceType } | null>;}@@ -170,7 +181,13 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}async copy(sliceType: SliceBodyType = SliceBodyType.copy, ranges?: ITextRangeWithStyle[]): Promise<boolean> {- const { newSnapshotList = [], needCache = false, snapshot, ranges: allRanges } = this._getDocumentBodyInRanges(sliceType, ranges) ?? {};+ const {+ newSnapshotList = [],+ needCache = false,+ plainTextList,+ snapshot,+ ranges: allRanges,+ } = this._getDocumentBodyInRanges(sliceType, ranges) ?? {};if (newSnapshotList.length === 0 || snapshot == null) {return false;@@ -179,7 +196,11 @@ export class DocClipboardService extends Disposable implements IDocClipboardServtry {const isCopyInHeaderFooter = !!allRanges?.[0]?.segmentId;- await this._setClipboardData(newSnapshotList, !isCopyInHeaderFooter && needCache);+ await this._setClipboardData(+ newSnapshotList,+ !isCopyInHeaderFooter && needCache,+ plainTextList+ );} catch (e) {this._logService.error('[DocClipboardService] copy failed', e);return false;@@ -310,12 +331,19 @@ export class DocClipboardService extends Disposable implements IDocClipboardServthis._clipboardHooks.forEach((hook) => {if (hook.onBeforePaste) {- body = hook.onBeforePaste(body);+ body = hook.onBeforePaste(body, {+ documentData: docData,+ targetUnitId: currentDocument.getUnitId(),+ });}});// copy custom ranges- body.customRanges = body.customRanges?.map(BuildTextUtils.customRange.copyCustomRange);+ const customRangeMappings = body.customRanges?.map((sourceRange) => {+ const targetRange = BuildTextUtils.customRange.copyCustomRange(sourceRange);+ return { sourceRange, targetRange };+ }) ?? [];+ body.customRanges = customRangeMappings.map(({ targetRange }) => targetRange);body.paragraphs?.forEach((copy) => {if (copy.paragraphStyle?.headingId) {@@ -368,6 +396,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ...docData,body,},+ customRangeMappings,segmentId,textRanges,});@@ -377,12 +406,18 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}}- private async _setClipboardData(documentList: IDocumentData[], needCache = true): Promise<void> {+ private async _setClipboardData(+ documentList: IDocumentData[],+ needCache = true,+ plainTextList?: readonly string[]+ ): Promise<void> {const copyId = generateRandomId(6);const text =- (documentList.length > 1- ? documentList.map((doc) => doc.body?.dataStream || '').join('\n')- : documentList[0].body?.dataStream || '')+ (plainTextList+ ? plainTextList.join('\n')+ : documentList.length > 1+ ? documentList.map((doc) => doc.body?.dataStream || '').join('\n')+ : documentList[0].body?.dataStream || '').replaceAll(DataStreamTreeTokenType.TABLE_START, '').replaceAll(DataStreamTreeTokenType.TABLE_END, '').replaceAll(DataStreamTreeTokenType.TABLE_ROW_START, '')@@ -446,6 +481,8 @@ export class DocClipboardService extends Disposable implements IDocClipboardServconst allRanges = ranges ?? this._docSelectionManagerService.getDocRanges();const results: IDocumentData['body'][] = [];+ const plainTextResults: string[] = [];+ const copyContentHook = this._clipboardHooks.find((hook) => hook.onCopyContent)?.onCopyContent;let needCache = true;if (docDataModel == null || allRanges.length === 0) {@@ -475,6 +512,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServconst bodySlice = getTableClipboardBodySlice(body, range as IRectRangeWithStyle);results.push(bodySlice);+ plainTextResults.push(bodySlice.dataStream);continue;}@@ -487,10 +525,23 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}results.push(docBody);+ plainTextResults.push(+ copyContentHook?.(+ deleteRange.startOffset,+ deleteRange.endOffset,+ {+ body,+ segmentId,+ unitId: docDataModel.getUnitId(),+ }+ ) ??+ docBody.dataStream+ );}return {newSnapshotList: results.map((e) => ({ ...snapshot, body: e })),needCache,+ plainTextList: plainTextResults,snapshot,ranges: allRanges,};diff --git a/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts b/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.tsindex 60f7b06d7a..f6af7a2b41 100644--- a/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts+++ b/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts@@ -14,8 +14,11 @@* limitations under the License.*/-import type { IDisposable, IDocumentBlockRange, IDocumentBody, IDocumentData, IDrawingParam, IMutationInfo } from '@univerjs/core';-import { createIdentifier, toDisposable } from '@univerjs/core';+import type { ICustomRange, IDisposable, IDocumentBlockRange, IDocumentBody, IDocumentData, IDrawingParam, IMutationInfo } from '@univerjs/core';+import {+ createIdentifier,+ toDisposable,+} from '@univerjs/core';export interface IDocClipboardPasteCustomBlockMapping {sourceBlockId: string;@@ -29,6 +32,11 @@ export interface IDocClipboardPasteBlockRangeMapping {targetBlockRange: IDocumentBlockRange;}+export interface IDocClipboardPasteCustomRangeMapping {+ sourceRange: ICustomRange;+ targetRange: ICustomRange;+}+export interface IDocClipboardPasteMutationInfoParams {unitId: string;segmentId: string;@@ -36,6 +44,7 @@ export interface IDocClipboardPasteMutationInfoParams {sourceBody: IDocumentBody;targetBody: IDocumentBody;blockRangeMappings: IDocClipboardPasteBlockRangeMapping[];+ customRangeMappings?: IDocClipboardPasteCustomRangeMapping[];customBlockMappings: IDocClipboardPasteCustomBlockMapping[];}diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.tsindex 3680861201..34729cedb6 100644--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts@@ -28,12 +28,14 @@ import { DocSelectionRenderService } from '../doc-selection-render.service';import { TextRange } from '../text-range';const {+ cursorConvertToTextRangeMock,getCanvasOffsetByEngineMock,getRangeListFromCharIndexMock,getRangeListFromSelectionMock,getRectRangeFromCharIndexMock,getTextRangeFromCharIndexMock,} = vi.hoisted(() => ({+ cursorConvertToTextRangeMock: vi.fn(),getCanvasOffsetByEngineMock: vi.fn(),getRangeListFromCharIndexMock: vi.fn(),getRangeListFromSelectionMock: vi.fn(),@@ -54,6 +56,15 @@ vi.mock('../selection-utils', async () => {};});+vi.mock('../text-range', async () => {+ const actual = await vi.importActual<typeof import('../text-range')>('../text-range');++ return {+ ...actual,+ cursorConvertToTextRange: cursorConvertToTextRangeMock,+ };+});+type VoidMock = Mock<() => void>;type BooleanMock = Mock<() => boolean>;type AnchorMock = Mock<() => { left: number; top: number; visible: boolean } | null>;@@ -326,6 +337,7 @@ describe('doc selection render service internals', () => {getRangeListFromSelectionMock.mockReturnValue(null);getRectRangeFromCharIndexMock.mockReturnValue(null);getTextRangeFromCharIndexMock.mockReturnValue(null);+ cursorConvertToTextRangeMock.mockReturnValue(null);vi.spyOn(TextRange.prototype as unknown as Record<'_anchorBlink', () => void>, '_anchorBlink').mockImplementation(() => {});vi.spyOn(TextRange.prototype, 'refresh').mockImplementation(() => {});});@@ -565,6 +577,77 @@ describe('doc selection render service internals', () => {expect(service._rectRangeList).toEqual([rectRange, fallbackRectRange, generalRectRange]);});+ it('uses a range-specific selection style when one is supplied', () => {+ const { mainComponent, scene, service, skeleton } = createService();+ const customStyle = {+ fill: 'rgba(0, 0, 0, 0)',+ stroke: 'rgba(0, 0, 0, 0)',+ strokeActive: 'rgba(0, 0, 0, 0)',+ strokeWidth: 0,+ };+ getRangeListFromCharIndexMock.mockReturnValueOnce({+ textRanges: [createTextRange()],+ rectRanges: [],+ });++ service.addDocRanges([{+ startOffset: 10,+ endOffset: 11,+ style: customStyle,+ }], false, {+ shouldFocus: false,+ });++ expect(getRangeListFromCharIndexMock).toHaveBeenCalledWith(+ 10,+ 11,+ scene,+ mainComponent,+ skeleton,+ customStyle,+ 'segment-1',+ 2+ );+ });++ it('reconstructs a collapsed document range as a cursor instead of an expanded whole-entity selection', () => {+ const { mainComponent, scene, service, skeleton } = createService();+ const cursorRange = createTextRange({ collapsed: true, focusNodePosition: null });+ const customStyle = {+ fill: 'rgba(0, 0, 0, 0)',+ stroke: 'rgba(0, 0, 0, 0)',+ strokeActive: 'rgba(0, 0, 0, 0)',+ strokeWidth: 0,+ };+ cursorConvertToTextRangeMock.mockReturnValueOnce(cursorRange);++ service.addDocRanges([{+ startOffset: 35,+ endOffset: 35,+ collapsed: true,+ style: customStyle,+ }], true, {+ shouldFocus: false,+ });++ expect(cursorConvertToTextRangeMock).toHaveBeenCalledWith(+ scene,+ {+ startOffset: 35,+ endOffset: 35,+ collapsed: true,+ segmentId: 'segment-1',+ segmentPage: 2,+ style: customStyle,+ },+ skeleton,+ mainComponent+ );+ expect(getTextRangeFromCharIndexMock).not.toHaveBeenCalled();+ expect(getRangeListFromCharIndexMock).not.toHaveBeenCalled();+ expect(service._rangeList).toEqual([cursorRange]);+ });+it('sets the cursor manually from the resolved paragraph node and emits selection state', () => {const { service } = createService();const position = { glyph: 3 };diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.tsindex bdd55c47ea..c99aaa985d 100644--- a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts@@ -1705,6 +1705,10 @@ describe('selection utils', () => {direction: 'FORWARD',segmentId: 'body',segmentPage: -1,+ style: {+ fill: 'transparent',+ strokeWidth: 0,+ },isActive: () => true,} as never;expect(serializeTextRange(textRange)).toMatchObject({@@ -1712,6 +1716,10 @@ describe('selection utils', () => {endOffset: 3,isActive: true,segmentId: 'body',+ style: {+ fill: 'transparent',+ strokeWidth: 0,+ },});const rectRange = {diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.tsindex b177d020e8..179c9011ac 100644--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts@@ -50,7 +50,7 @@ import {serializeRectRange,serializeTextRange,} from './selection-utils';-import { TextRange } from './text-range';+import { cursorConvertToTextRange, TextRange } from './text-range';import { getWordBoundaryByIndex } from './word-boundary';export interface IEditorInputConfig {@@ -236,14 +236,18 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoconst document = mainComponent as Documents;const docSkeleton = this._docSkeletonManagerService.getSkeleton();- const generalAddRange = (startOffset: number, endOffset: number) => {+ const generalAddRange = (+ startOffset: number,+ endOffset: number,+ rangeStyle: ITextSelectionStyle+ ) => {const rangeList = getRangeListFromCharIndex(startOffset,endOffset,scene,document,docSkeleton,- style,+ rangeStyle,segmentId,segmentPage);@@ -263,15 +267,32 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMofor (const range of ranges) {const { startOffset, endOffset, rangeType, startNodePosition, endNodePosition } = range as ITextRangeWithStyle;+ const rangeStyle = range.style ?? style;- if (rangeType === DOC_RANGE_TYPE.RECT) {+ if (rangeType !== DOC_RANGE_TYPE.RECT && startOffset === endOffset) {+ const textRange = cursorConvertToTextRange(+ scene,+ {+ ...range,+ segmentId,+ segmentPage,+ style: rangeStyle,+ },+ docSkeleton,+ document+ );++ if (textRange) {+ this._addTextRange(textRange);+ }+ } else if (rangeType === DOC_RANGE_TYPE.RECT) {const rectRange = getRectRangeFromCharIndex(startOffset,endOffset,scene,document,docSkeleton,- style,+ rangeStyle,segmentId,segmentPage);@@ -291,7 +312,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoscene,document,docSkeleton,- style,+ rangeStyle,segmentId,segmentPage,startNodePosition.isBack,@@ -304,7 +325,7 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMoscene,document,docSkeleton,- style,+ rangeStyle,segmentId,segmentPage);@@ -315,10 +336,10 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo}// eslint-disable-next-line unused-imports/no-unused-vars} catch (_e) {- generalAddRange(startOffset, endOffset);+ generalAddRange(startOffset, endOffset, rangeStyle);}} else {- generalAddRange(startOffset, endOffset);+ generalAddRange(startOffset, endOffset, rangeStyle);}}diff --git a/packages/docs-ui/src/services/selection/selection-utils.ts b/packages/docs-ui/src/services/selection/selection-utils.tsindex ebb6fd0c22..967cce5d87 100644--- a/packages/docs-ui/src/services/selection/selection-utils.ts+++ b/packages/docs-ui/src/services/selection/selection-utils.ts@@ -554,7 +554,7 @@ export function getParagraphInfoByGlyph(node: IDocumentSkeletonGlyph) {}export function serializeTextRange(textRange: IDocRange): ITextRangeWithStyle {- const { startOffset, endOffset, collapsed, rangeType, startNodePosition, endNodePosition, direction, segmentId, segmentPage } = textRange;+ const { startOffset, endOffset, collapsed, rangeType, startNodePosition, endNodePosition, direction, segmentId, segmentPage, style } = textRange;const serializedTextRange: ITextRangeWithStyle = {startOffset: startOffset!,endOffset: endOffset!,@@ -565,6 +565,7 @@ export function serializeTextRange(textRange: IDocRange): ITextRangeWithStyle {direction,segmentId,segmentPage,+ style,isActive: textRange.isActive(),};diff --git a/packages/docs/src/index.ts b/packages/docs/src/index.tsindex 36409f9fbc..1ebc2e46f6 100644--- a/packages/docs/src/index.ts+++ b/packages/docs/src/index.ts@@ -72,7 +72,10 @@ export { DocContentInsertService } from './services/doc-content-insert.service';export type { IDocContentInsertRange } from './services/doc-content-insert.service';export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';export { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';-export { DocSelectionManagerService } from './services/doc-selection-manager.service';+export {+ DOC_SELECTION_OPTION_PRESERVE_CARET,+ DocSelectionManagerService,+} from './services/doc-selection-manager.service';export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';export {DocStateChangeManagerService,@@ -80,6 +83,13 @@ export {} from './services/doc-state-change-manager.service';export type { IDocStateChangeInfo, IDocStateChangeParams } from './services/doc-state-emit.service';export { DocStateEmitService } from './services/doc-state-emit.service';+export { DocTextResolverService } from './services/doc-text-resolver.service';+export type {+ IDocTextReplacement,+ IDocTextResolver,+ IResolvedDocText,+ IResolvedDocTextCharacter,+} from './services/doc-text-resolver.service';export {addCustomRangeBySelectionFactory,addCustomRangeFactory,diff --git a/packages/docs/src/plugin.ts b/packages/docs/src/plugin.tsindex dafba1b2f1..ed0628ace9 100644--- a/packages/docs/src/plugin.ts+++ b/packages/docs/src/plugin.ts@@ -41,6 +41,7 @@ import { DocContentInsertService } from './services/doc-content-insert.service';import { DocSelectionManagerService } from './services/doc-selection-manager.service';import { DocStateChangeManagerService } from './services/doc-state-change-manager.service';import { DocStateEmitService } from './services/doc-state-emit.service';+import { DocTextResolverService } from './services/doc-text-resolver.service';export class UniverDocsPlugin extends Plugin {static override pluginName = 'DOCS_PLUGIN';@@ -100,6 +101,7 @@ export class UniverDocsPlugin extends Plugin {[DocStateChangeManagerService],[DocBlockMoveValidatorService],[DocContentInsertService],+ [DocTextResolverService],[DocCustomRangeController],] as Dependency[]).forEach((d) => this._injector.add(d));diff --git a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.tsindex 4f14f85763..d8f8e36733 100644--- a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts+++ b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts@@ -27,6 +27,7 @@ import {IUniverInstanceService,UniverInstanceService,} from '@univerjs/core';+import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';import { describe, expect, it } from 'vitest';import { SetTextSelectionsOperation } from '../../commands/operations/text-selection.operation';import { DocSelectionManagerService } from '../doc-selection-manager.service';@@ -98,6 +99,34 @@ describe('DocSelectionManagerService', () => {sub.unsubscribe();});+ it('preserves selection options when refreshing an existing render selection', () => {+ const service = createService();+ const refreshes: unknown[] = [];+ const sub = service.refreshSelection$.subscribe((value) => refreshes.push(value));+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });+ service.__replaceTextRangesWithNoRefresh({+ textRanges: [{ startOffset: 2, endOffset: 2, collapsed: true }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ isEditing: false,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ options: { preserveCaret: true },+ }, { unitId: 'doc-1', subUnitId: 'doc-1' });++ service.refreshSelection();++ expect(refreshes.at(-1)).toEqual(expect.objectContaining({+ docRanges: [expect.objectContaining({+ startOffset: 2,+ endOffset: 2,+ collapsed: true,+ })],+ options: { preserveCaret: true },+ }));+ sub.unsubscribe();+ });+it('replaces render selections, publishes them, and sorts text and rect ranges together', async () => {const service = createService();const selections: unknown[] = [];diff --git a/packages/docs/src/services/__tests__/doc-text-resolver.service.spec.ts b/packages/docs/src/services/__tests__/doc-text-resolver.service.spec.tsnew file mode 100644index 0000000000..15edf38e30--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-text-resolver.service.spec.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it } from 'vitest';+import { DocTextResolverService } from '../doc-text-resolver.service';++describe('DocTextResolverService', () => {+ it('projects replacement text and maps every visible character to native offsets', () => {+ const service = new DocTextResolverService();+ service.register({+ resolve: () => [{+ startOffset: 1,+ endOffset: 2,+ text: '42',+ }],+ });++ expect(service.resolve('doc-1', { dataStream: 'A\uFFFCC' })).toEqual({+ text: 'A42C',+ characters: [+ { startOffset: 0, endOffset: 1, replaceable: true },+ { startOffset: 1, endOffset: 2, replaceable: false },+ { startOffset: 1, endOffset: 2, replaceable: false },+ { startOffset: 2, endOffset: 3, replaceable: true },+ ],+ });+ });++ it('ignores invalid and overlapping replacements deterministically', () => {+ const service = new DocTextResolverService();+ service.register({+ resolve: () => [+ { startOffset: 1, endOffset: 3, text: 'first' },+ { startOffset: 2, endOffset: 3, text: 'overlap' },+ { startOffset: -1, endOffset: 1, text: 'invalid' },+ ],+ });++ expect(service.resolve('doc-1', { dataStream: 'ABCD' }).text).toBe('AfirstD');+ });+});diff --git a/packages/docs/src/services/doc-selection-manager.service.ts b/packages/docs/src/services/doc-selection-manager.service.tsindex 9e5f71dc06..387311372a 100644--- a/packages/docs/src/services/doc-selection-manager.service.ts+++ b/packages/docs/src/services/doc-selection-manager.service.ts@@ -31,6 +31,12 @@ interface IDocSelectionManagerSearchParam {subUnitId: string;}+/**+ * Keeps a programmatically restored collapsed caret from being promoted back+ * into a neighboring whole-entity selection by feature-specific UI.+ */+export const DOC_SELECTION_OPTION_PRESERVE_CARET = 'preserveCaret';+export interface IRefreshSelectionParam extends IDocSelectionManagerSearchParam {docRanges: ISuccinctDocRangeParam[];isEditing: boolean;@@ -258,7 +264,7 @@ export class DocSelectionManagerService extends RxDisposable {return;}- const { textRanges, rectRanges } = allTextSelectionInfo;+ const { textRanges, rectRanges, options } = allTextSelectionInfo;const docRanges = [...textRanges, ...rectRanges];@@ -269,6 +275,7 @@ export class DocSelectionManagerService extends RxDisposable {subUnitId,docRanges,isEditing: false,+ options,});}diff --git a/packages/docs/src/services/doc-text-resolver.service.ts b/packages/docs/src/services/doc-text-resolver.service.tsnew file mode 100644index 0000000000..be98ea238d--- /dev/null+++ b/packages/docs/src/services/doc-text-resolver.service.ts@@ -0,0 +1,139 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IDisposable, IDocumentBody } from '@univerjs/core';+import { Disposable, toDisposable } from '@univerjs/core';+import { Subject } from 'rxjs';++export interface IDocTextReplacement {+ endOffset: number;+ replaceable?: boolean;+ startOffset: number;+ text: string;+}++export interface IDocTextResolver {+ resolve(unitId: string, body: IDocumentBody): readonly IDocTextReplacement[];+}++export interface IResolvedDocTextCharacter {+ endOffset: number;+ replaceable: boolean;+ startOffset: number;+}++export interface IResolvedDocText {+ characters: readonly IResolvedDocTextCharacter[];+ text: string;+}++/**+ * Builds a consumer-facing text projection while retaining a mapping back to+ * the native document offsets.+ *+ * Consumers such as find/replace can search the projected text and then use+ * `characters` to focus the native object that supplied a matching character.+ * Resolvers must return half-open, non-overlapping replacements.+ */+export class DocTextResolverService extends Disposable {+ private readonly _resolvers = new Set<IDocTextResolver>();+ private readonly _textChanged$ = new Subject<string>();++ readonly textChanged$ = this._textChanged$.asObservable();++ register(resolver: IDocTextResolver): IDisposable {+ this._resolvers.add(resolver);+ return toDisposable(() => this._resolvers.delete(resolver));+ }++ notifyTextChanged(unitId: string): void {+ this._textChanged$.next(unitId);+ }++ resolve(unitId: string, body: IDocumentBody): IResolvedDocText {+ const replacements = this._collectReplacements(unitId, body);+ const characters: IResolvedDocTextCharacter[] = [];+ let text = '';+ let sourceOffset = 0;++ for (const replacement of replacements) {+ const sourceText = body.dataStream.slice(sourceOffset, replacement.startOffset);+ text += sourceText;+ for (let index = sourceOffset; index < replacement.startOffset; index += 1) {+ characters.push({+ startOffset: index,+ endOffset: index + 1,+ replaceable: true,+ });+ }++ text += replacement.text;+ for (let index = 0; index < replacement.text.length; index += 1) {+ characters.push({+ startOffset: replacement.startOffset,+ endOffset: replacement.endOffset,+ replaceable: replacement.replaceable ?? false,+ });+ }+ sourceOffset = replacement.endOffset;+ }++ text += body.dataStream.slice(sourceOffset);+ for (let index = sourceOffset; index < body.dataStream.length; index += 1) {+ characters.push({+ startOffset: index,+ endOffset: index + 1,+ replaceable: true,+ });+ }++ return { characters, text };+ }++ private _collectReplacements(+ unitId: string,+ body: IDocumentBody+ ): IDocTextReplacement[] {+ const candidates = [...this._resolvers]+ .flatMap((resolver) => resolver.resolve(unitId, body))+ .filter((replacement) =>+ Number.isInteger(replacement.startOffset) &&+ Number.isInteger(replacement.endOffset) &&+ replacement.startOffset >= 0 &&+ replacement.endOffset > replacement.startOffset &&+ replacement.endOffset <= body.dataStream.length+ )+ .sort((left, right) =>+ left.startOffset - right.startOffset ||+ right.endOffset - left.endOffset+ );+ const replacements: IDocTextReplacement[] = [];+ let previousEnd = -1;+ for (const candidate of candidates) {+ if (candidate.startOffset < previousEnd) {+ continue;+ }+ replacements.push(candidate);+ previousEnd = candidate.endOffset;+ }+ return replacements;+ }++ override dispose(): void {+ this._textChanged$.complete();+ super.dispose();+ }+}diff --git a/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.tsindex ebe62a9361..40b45f02d4 100644--- a/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts+++ b/packages/engine-formula/src/controllers/__tests__/formula-calculation-trigger.controller.spec.ts@@ -15,9 +15,10 @@*/import * as core from '@univerjs/core';-import { LifecycleStages } from '@univerjs/core';import { BehaviorSubject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import { FormulaCalculationTriggerService } from '../../services/formula-calculation-trigger.service';+import { RegisterOtherFormulaService } from '../../services/register-other-formula.service';import { FormulaCalculationTriggerController } from '../formula-calculation-trigger.controller';describe('FormulaCalculationTriggerController', () => {@@ -26,32 +27,41 @@ describe('FormulaCalculationTriggerController', () => {it('starts immediately in Node.js', () => {vi.spyOn(core, 'isNodeEnv').mockReturnValue(true);const start = vi.fn();- const lifecycle$ = new BehaviorSubject(LifecycleStages.Ready);+ const calculateStarted$ = new BehaviorSubject(false);+ const lifecycle$ = new BehaviorSubject(core.LifecycleStages.Ready);- const controller = new FormulaCalculationTriggerController(- { start } as never,- { lifecycle$ } as never- );+ const injector = new core.Injector([+ [FormulaCalculationTriggerService, { useValue: { start } }],+ [RegisterOtherFormulaService, { useValue: { calculateStarted$ } }],+ [core.LifecycleService, { useValue: { lifecycle$ } }],+ ]);+ const controller = injector.createInstance(FormulaCalculationTriggerController);expect(start).toHaveBeenCalledOnce();+ expect(calculateStarted$.getValue()).toBe(true);controller.dispose();});it('starts after rendering in the browser', () => {vi.spyOn(core, 'isNodeEnv').mockReturnValue(false);const start = vi.fn();- const lifecycle$ = new BehaviorSubject(LifecycleStages.Ready);+ const calculateStarted$ = new BehaviorSubject(false);+ const lifecycle$ = new BehaviorSubject(core.LifecycleStages.Ready);- const controller = new FormulaCalculationTriggerController(- { start } as never,- { lifecycle$ } as never- );+ const injector = new core.Injector([+ [FormulaCalculationTriggerService, { useValue: { start } }],+ [RegisterOtherFormulaService, { useValue: { calculateStarted$ } }],+ [core.LifecycleService, { useValue: { lifecycle$ } }],+ ]);+ const controller = injector.createInstance(FormulaCalculationTriggerController);expect(start).not.toHaveBeenCalled();- lifecycle$.next(LifecycleStages.Rendered);+ expect(calculateStarted$.getValue()).toBe(false);+ lifecycle$.next(core.LifecycleStages.Rendered);expect(start).toHaveBeenCalledOnce();+ expect(calculateStarted$.getValue()).toBe(true);- lifecycle$.next(LifecycleStages.Steady);+ lifecycle$.next(core.LifecycleStages.Steady);expect(start).toHaveBeenCalledOnce();controller.dispose();});diff --git a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.tsindex 5fa454f33f..ff5ff9b6c7 100644--- a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts+++ b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts@@ -27,6 +27,7 @@ import {toDisposable,} from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';+import { OtherFormulaMarkDirty } from '../../commands/mutations/formula.mutation';import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../../services/active-dirty-manager.service';import { FunctionService, IFunctionService } from '../../services/function.service';import { RegisterOtherFormulaService } from '../../services/register-other-formula.service';@@ -39,6 +40,7 @@ type FormulaDataSyncController = Pick<function createController(dataSyncPrimaryController?: FormulaDataSyncController): {controller: FormulaController;+ commandService: ICommandService;registerOtherFormulaService: RegisterOtherFormulaService;} {const injector = new Injector();@@ -50,19 +52,28 @@ function createController(dataSyncPrimaryController?: FormulaDataSyncController)injector.add([LifecycleService]);injector.add([RegisterOtherFormulaService]);const registerOtherFormulaService = injector.get(RegisterOtherFormulaService);+ const commandService = injector.get(ICommandService);return {controller: new FormulaController(- injector.get(ICommandService),+ commandService,injector.get(IFunctionService),injector.get(IConfigService),dataSyncPrimaryController,registerOtherFormulaService),+ commandService,registerOtherFormulaService,};}describe('FormulaController', () => {+ it('registers the generic other-formula dirty mutation', () => {+ const { commandService, controller } = createController();++ expect(commandService.hasCommand(OtherFormulaMarkDirty.id)).toBe(true);+ controller.dispose();+ });+it('registers mutation-only synchronization once per other-formula host', () => {const dispose = vi.fn();const dataSyncPrimaryController = {diff --git a/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts b/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.tsindex 0a86cb3d62..29110e0672 100644--- a/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts+++ b/packages/engine-formula/src/controllers/formula-calculation-trigger.controller.ts@@ -17,22 +17,29 @@import { Disposable, Inject, isNodeEnv, LifecycleService, LifecycleStages } from '@univerjs/core';import { filter, take } from 'rxjs';import { FormulaCalculationTriggerService } from '../services/formula-calculation-trigger.service';+import { RegisterOtherFormulaService } from '../services/register-other-formula.service';export class FormulaCalculationTriggerController extends Disposable {constructor(@Inject(FormulaCalculationTriggerService) formulaCalculationTriggerService: FormulaCalculationTriggerService,+ @Inject(RegisterOtherFormulaService) registerOtherFormulaService: RegisterOtherFormulaService,@Inject(LifecycleService) lifecycleService: LifecycleService) {super();- if (isNodeEnv()) {+ const start = () => {formulaCalculationTriggerService.start();+ registerOtherFormulaService.calculateStarted$.next(true);+ };++ if (isNodeEnv()) {+ start();return;}this.disposeWithMe(lifecycleService.lifecycle$.pipe(filter((stage) => stage >= LifecycleStages.Rendered),take(1)- ).subscribe(() => formulaCalculationTriggerService.start()));+ ).subscribe(start));}}diff --git a/packages/engine-formula/src/controllers/formula.controller.ts b/packages/engine-formula/src/controllers/formula.controller.tsindex 8011cf42d4..5e7a369a5e 100644--- a/packages/engine-formula/src/controllers/formula.controller.ts+++ b/packages/engine-formula/src/controllers/formula.controller.ts@@ -20,6 +20,7 @@ import type { IUniverEngineFormulaConfig } from '../config/config';import type { BaseFunction } from '../functions/base-function';import { Disposable, ICommandService, IConfigService, Inject, Optional } from '@univerjs/core';import { DataSyncPrimaryController } from '@univerjs/rpc';+import { OtherFormulaMarkDirty } from '../commands/mutations/formula.mutation';import { RegisterFunctionMutation } from '../commands/mutations/register-function.mutation';import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';@@ -119,6 +120,7 @@ export class FormulaController extends Disposable {SetFeatureCalculationMutation,RemoveFeatureCalculationMutation,+ OtherFormulaMarkDirty,SetOtherFormulaMutation,RemoveOtherFormulaMutation,SetSuperTableMutation,diff --git a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts b/packages/engine-formula/src/services/__tests__/current-data.service.spec.tsindex 8654d2d7dc..a95afde93a 100644--- a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts@@ -20,7 +20,7 @@ import { FormulaDataModel } from '../../models/formula-data.model';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../current-data.service';import { ISheetRowFilteredService } from '../sheet-row-filtered.service';-function createService() {+function createService(withCurrentWorkbook = true) {const workbookForCurrentType = {getUnitId: vi.fn(() => 'unit-current'),getActiveSheet: vi.fn(() => ({@@ -34,8 +34,13 @@ function createService() {const workbookById = new Map<string, unknown>();const univerInstanceService = {- getCurrentUnitOfType: vi.fn(() => workbookForCurrentType),+ getCurrentUnitOfType: vi.fn(() => withCurrentWorkbook ? workbookForCurrentType : undefined),getUnit: vi.fn((unitId: string) => workbookById.get(unitId)),+ getUnitType: vi.fn((unitId: string) =>+ workbookById.has(unitId)+ ? UniverInstanceType.UNIVER_SHEET+ : UniverInstanceType.UNRECOGNIZED+ ),};const localeService = {getCurrentLocale: vi.fn(() => 'zhCN'),@@ -58,6 +63,7 @@ function createService() {class TestUniverInstanceService {getCurrentUnitOfType = univerInstanceService.getCurrentUnitOfType;getUnit = univerInstanceService.getUnit;+ getUnitType = univerInstanceService.getUnitType;}class TestLocaleService {@@ -219,6 +225,7 @@ describe('FormulaCurrentConfigService', () => {expect(service.getSheetRowColumnCount('unit-size', 'sheet-size')).toEqual({ rowCount: 22, columnCount: 8 });expect(service.getSheetRowColumnCount('unit-size', 'missing')).toEqual({ rowCount: 0, columnCount: 0 });+ expect(service.getSheetRowColumnCount('doc-unit', 'doc-unit')).toEqual({ rowCount: 0, columnCount: 0 });expect(service.getFilteredOutRows('unit-size', 'sheet-size', 1, 5)).toEqual([2, 4]);formulaDataModel.getCalculateData.mockReturnValue({@@ -236,6 +243,15 @@ describe('FormulaCurrentConfigService', () => {expect(service.getUnitData().unitLite.sheetLite.rowData).toEqual({ 1: { h: 30 } });});+ it('returns empty sheet metadata when formula calculation runs without Sheets', () => {+ const { service } = createService(false);++ expect(service.getSheetsInfo()).toEqual({+ sheetOrder: [],+ sheetNameMap: {},+ });+ });+it('should update dirty ranges/register data and cleanup all caches on dispose', () => {const { service } = createService();diff --git a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.tsindex 612b4dfa60..242ae96cef 100644--- a/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/formula-calculation-trigger.service.spec.ts@@ -15,6 +15,7 @@*/import type { ICommandInfo, ICommandService, IExecutionOptions } from '@univerjs/core';+import { CommandType } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {SetFormulaCalculationNotificationMutation,@@ -22,13 +23,15 @@ import {SetFormulaCalculationStopMutation,SetTriggerFormulaCalculationStartMutation,} from '../../commands/mutations/set-formula-calculation.mutation';+import { ActiveDirtyManagerService } from '../active-dirty-manager.service';import { FormulaCalculationTriggerService } from '../formula-calculation-trigger.service';import { FormulaExecutedStateType } from '../runtime.service';function createTestBed(start = true) {let listener: ((command: ICommandInfo, options?: IExecutionOptions) => void) | undefined;const executed: Array<{ id: string; params: unknown; options: unknown }> = [];- const conversions = new Map<string, { commandId: string; shouldTrigger?: () => boolean; getDirtyData: (command: ICommandInfo) => object }>();+ const activeDirtyManagerService = new ActiveDirtyManagerService();+ const conversions = activeDirtyManagerService.getDirtyConversionMap();const commandService = {onCommandExecuted: vi.fn((callback: typeof listener) => {listener = callback;@@ -40,10 +43,7 @@ function createTestBed(start = true) {return true;}),} as unknown as ICommandService;- const activeDirtyManagerService = {- get: (id: string) => conversions.get(id),- };- const service = new FormulaCalculationTriggerService(commandService, activeDirtyManagerService as never);+ const service = new FormulaCalculationTriggerService(commandService, activeDirtyManagerService);if (start) {service.start();}@@ -71,17 +71,16 @@ describe('FormulaCalculationTriggerService', () => {dirtyRanges: [{ unitId: 'sheet-unit', sheetId: 'sheet-1', range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }],}),});- testBed.conversions.set(SetTriggerFormulaCalculationStartMutation.id, {- commandId: SetTriggerFormulaCalculationStartMutation.id,- getDirtyData: () => ({ forceCalculation: true }),- });-testBed.emit({ id: 'sheet-dirty' } as ICommandInfo, { fromChangeset: true });await vi.advanceTimersByTimeAsync(10);expect(testBed.executed).toEqual([]);testBed.service.start();- testBed.emit({ id: SetTriggerFormulaCalculationStartMutation.id } as ICommandInfo);+ testBed.emit({+ id: SetTriggerFormulaCalculationStartMutation.id,+ type: CommandType.MUTATION,+ params: { forceCalculation: true },+ });await vi.advanceTimersByTimeAsync(10);expect(testBed.executed).toHaveLength(1);@@ -236,11 +235,6 @@ describe('FormulaCalculationTriggerService', () => {commandId: 'empty-dirty',getDirtyData: () => ({}),});- testBed.conversions.set(SetTriggerFormulaCalculationStartMutation.id, {- commandId: SetTriggerFormulaCalculationStartMutation.id,- getDirtyData: () => ({}),- });-testBed.emit({ id: 'empty-dirty' } as ICommandInfo);await vi.advanceTimersByTimeAsync(10);expect(testBed.executed).toEqual([]);diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.tsindex fa3e1b26c6..c3510c9bba 100644--- a/packages/engine-formula/src/services/current-data.service.ts+++ b/packages/engine-formula/src/services/current-data.service.ts@@ -317,16 +317,26 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC}getSheetsInfo() {- const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const workbook = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return {+ sheetOrder: [],+ sheetNameMap: {},+ };+ }const { id, sheetOrder } = workbook.getSnapshot();return {sheetOrder,- sheetNameMap: this._sheetIdToNameMap[id] as { [sheetId: string]: string },+ sheetNameMap: this._sheetIdToNameMap[id] ?? {},};}getSheetRowColumnCount(unitId: string, sheetId: string) {+ if (this._univerInstanceService.getUnitType(unitId) !== UniverInstanceType.UNIVER_SHEET) {+ return { rowCount: 0, columnCount: 0 };+ }+const workbook = this._univerInstanceService.getUnit<Workbook>(unitId);const worksheet = workbook?.getSheetBySheetId(sheetId);const snapshot = worksheet?.getSnapshot();diff --git a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts b/packages/engine-formula/src/services/formula-calculation-trigger.service.tsindex e85c970073..f6d4f4aebb 100644--- a/packages/engine-formula/src/services/formula-calculation-trigger.service.ts+++ b/packages/engine-formula/src/services/formula-calculation-trigger.service.ts@@ -53,6 +53,7 @@ export class FormulaCalculationTriggerService extends Disposable {@IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService) {super();+ this._registerGenericDirtyConversions();this._initialize();}@@ -98,6 +99,15 @@ export class FormulaCalculationTriggerService extends Disposable {}));}+ private _registerGenericDirtyConversions(): void {+ this._activeDirtyManagerService.register(SetTriggerFormulaCalculationStartMutation.id, {+ commandId: SetTriggerFormulaCalculationStartMutation.id,+ getDirtyData: (command) => ({+ ...command.params,+ }),+ });+ }+private _scheduleFlush(): void {if (!this._started || (this._waitingCommandQueue.length === 0 && !this._hasPendingCalculation)) {return;diff --git a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.tsindex 5e7991b4bb..5fc17aea92 100644--- a/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts@@ -25,7 +25,6 @@ import {IActiveDirtyManagerService,RemoveDefinedNameMutation,SetDefinedNameMutation,- SetTriggerFormulaCalculationStartMutation,} from '@univerjs/engine-formula';import {InsertSheetMutation,@@ -339,27 +338,6 @@ describe('ActiveDirtyController', () => {},} as IInsertSheetMutationParams;- expect(getDirtyData(testBed, {- id: SetTriggerFormulaCalculationStartMutation.id,- params: {- forceCalculation: true,- dirtyRanges: [],- dirtyNameMap: { test: { sheet1: 'Sheet1' } },- dirtyDefinedNameMap: {},- dirtyUnitFeatureMap: {},- dirtyUnitOtherFormulaMap: {},- clearDependencyTreeCache: {},- },- } as ICommandInfo)).toEqual({- forceCalculation: true,- dirtyRanges: [],- dirtyNameMap: { test: { sheet1: 'Sheet1' } },- dirtyDefinedNameMap: {},- dirtyUnitFeatureMap: {},- dirtyUnitOtherFormulaMap: {},- clearDependencyTreeCache: {},- });-expect(getDirtyData(testBed, {id: RemoveSheetMutation.id,params: {diff --git a/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.tsindex f8d708e4ec..c65274b029 100644--- a/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts@@ -15,7 +15,6 @@*/import { ICommandService } from '@univerjs/core';-import { OtherFormulaMarkDirty } from '@univerjs/engine-formula';import { afterEach, describe, expect, it } from 'vitest';import { InsertFunctionCommand } from '../../commands/commands/insert-function.command';import { QuickSumCommand } from '../../commands/commands/quick-sum.command';@@ -33,13 +32,11 @@ describe('FormulaController', () => {expect(commandService.hasCommand(InsertFunctionCommand.id)).toBe(false);expect(commandService.hasCommand(QuickSumCommand.id)).toBe(false);- expect(commandService.hasCommand(OtherFormulaMarkDirty.id)).toBe(false);testBed.injector.get(FormulaController);expect(commandService.hasCommand(InsertFunctionCommand.id)).toBe(true);expect(commandService.hasCommand(QuickSumCommand.id)).toBe(true);- expect(commandService.hasCommand(OtherFormulaMarkDirty.id)).toBe(true);testBed.univer.dispose();});diff --git a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.tsindex 53f0369383..f387196f44 100644--- a/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts+++ b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts@@ -136,12 +136,21 @@ function createControllerTestBed(initialFormulaComputing = CalculationMode.WHEN_commandService,formulaDataModel: injector.get(FormulaDataModel),activeDirtyManagerService: injector.get(IActiveDirtyManagerService),- registerOtherFormulaService: injector.get(RegisterOtherFormulaService),executedCommands,executedDisposable,};}+async function settleInitialCalculation(testBed: ReturnType<typeof createControllerTestBed>): Promise<void> {+ await vi.advanceTimersByTimeAsync(10);+ if (testBed.executedCommands.some(({ id }) => id === SetFormulaCalculationStartMutation.id)) {+ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ functionsExecutedState: FormulaExecutedStateType.SUCCESS,+ });+ }+ testBed.executedCommands.length = 0;+}+describe('TriggerCalculationController', () => {beforeEach(() => {vi.useFakeTimers();@@ -155,13 +164,7 @@ describe('TriggerCalculationController', () => {it('should trigger initial calculation and enrich calculation params through real command hooks', async () => {const testBed = createControllerTestBed();- await Promise.resolve();-- expect(testBed.registerOtherFormulaService.calculateStarted$.getValue()).toBe(true);-- testBed.executedCommands.length = 0;-- await testBed.commandService.executeCommand(SetFormulaCalculationStartMutation.id, {});+ await vi.advanceTimersByTimeAsync(10);await testBed.commandService.executeCommand(SetFormulaStringBatchCalculationMutation.id, {});expect(testBed.executedCommands.find((command) => command.id === SetFormulaCalculationStartMutation.id)).toMatchObject({@@ -187,10 +190,10 @@ describe('TriggerCalculationController', () => {it('should not enqueue an empty initial calculation in no-calculation mode', async () => {const testBed = createControllerTestBed(CalculationMode.NO_CALCULATION);- await Promise.resolve();+ await vi.advanceTimersByTimeAsync(10);- expect(testBed.registerOtherFormulaService.calculateStarted$.getValue()).toBe(true);expect(testBed.executedCommands.some(({ id }) => id === SetTriggerFormulaCalculationStartMutation.id)).toBe(false);+ expect(testBed.executedCommands.some(({ id }) => id === SetFormulaCalculationStartMutation.id)).toBe(false);testBed.executedDisposable.dispose();testBed.testBed.univer.dispose();@@ -198,6 +201,7 @@ describe('TriggerCalculationController', () => {it('should merge dirty data from real active-dirty registrations and skip style-triggered range updates', async () => {const testBed = createControllerTestBed();+ await settleInitialCalculation(testBed);testBed.activeDirtyManagerService.register('formula.test-dirty-1', {commandId: 'formula.test-dirty-1',@@ -229,8 +233,6 @@ describe('TriggerCalculationController', () => {}),});- testBed.executedCommands.length = 0;-await testBed.commandService.executeCommand('formula.test-dirty-1');await testBed.commandService.executeCommand(SetRangeValuesMutation.id, {unitId: 'test',@@ -266,6 +268,7 @@ describe('TriggerCalculationController', () => {it('should stop and restart calculation through real notification flow', async () => {const testBed = createControllerTestBed();+ await settleInitialCalculation(testBed);testBed.activeDirtyManagerService.register('formula.test-dirty-restart', {commandId: 'formula.test-dirty-restart',@@ -275,8 +278,6 @@ describe('TriggerCalculationController', () => {}),});- testBed.executedCommands.length = 0;-await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {stageInfo: {totalFormulasToCalculate: 1,@@ -312,6 +313,7 @@ describe('TriggerCalculationController', () => {it('should publish progress updates through real notification commands', async () => {const testBed = createControllerTestBed();+ await settleInitialCalculation(testBed);const progressValues: Array<{ done: number; count: number; label?: string }> = [];const subscription = testBed.controller.progress$.subscribe((value) => progressValues.push(value));diff --git a/packages/sheets-formula/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.tsindex 6b335f8b36..9daed98399 100644--- a/packages/sheets-formula/src/controllers/active-dirty.controller.ts+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts@@ -15,7 +15,7 @@*/import type { ICellData, ICommandInfo, IObjectMatrixPrimitiveType, IRange, IUnitRange, Nullable, Workbook } from '@univerjs/core';-import type { IDirtyUnitDefinedNameMap, IDirtyUnitSheetNameMap, IFormulaDirtyData, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';+import type { IDirtyUnitDefinedNameMap, IDirtyUnitSheetNameMap, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';import type {IInsertColMutationParams,IInsertRowMutationParams,@@ -38,7 +38,7 @@ import {ObjectMatrix,UniverInstanceType,} from '@univerjs/core';-import { FormulaDataModel, IActiveDirtyManagerService, RemoveDefinedNameMutation, SetDefinedNameMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';+import { FormulaDataModel, IActiveDirtyManagerService, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';import {ClearSelectionFormatCommand,InsertColMutation,@@ -257,16 +257,6 @@ export class ActiveDirtyController extends Disposable {}private _initialSheet() {- this._activeDirtyManagerService.register(SetTriggerFormulaCalculationStartMutation.id, {- commandId: SetTriggerFormulaCalculationStartMutation.id,- getDirtyData: (command: ICommandInfo) => {- const params = command.params as IFormulaDirtyData;- return {- ...params,- };- },- });-this._activeDirtyManagerService.register(RemoveSheetMutation.id, {commandId: RemoveSheetMutation.id,getDirtyData: (command: ICommandInfo) => {diff --git a/packages/sheets-formula/src/controllers/formula.controller.ts b/packages/sheets-formula/src/controllers/formula.controller.tsindex 1b98fb0ce5..fcb540e321 100644--- a/packages/sheets-formula/src/controllers/formula.controller.ts+++ b/packages/sheets-formula/src/controllers/formula.controller.ts@@ -15,7 +15,6 @@*/import { Disposable, ICommandService } from '@univerjs/core';-import { OtherFormulaMarkDirty } from '@univerjs/engine-formula';import { InsertFunctionCommand } from '../commands/commands/insert-function.command';import { QuickSumCommand } from '../commands/commands/quick-sum.command';@@ -28,7 +27,6 @@ export class FormulaController extends Disposable {[InsertFunctionCommand,QuickSumCommand,- OtherFormulaMarkDirty,].forEach((c) => this._commandService.registerCommand(c));}}diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 2d6f2db964..2e2d81d889 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -15,17 +15,7 @@*/import type { ICommandInfo, IUnitRange, Nullable, Workbook } from '@univerjs/core';-import type {- IDirtyUnitDefinedNameMap,- IDirtyUnitFeatureMap,- IDirtyUnitOtherFormulaMap,- IDirtyUnitSheetNameMap,- IDirtyUnitSuperTableMap,- IExecutionInProgressParams,- IFormulaDirtyData,- ISetFormulaCalculationNotificationMutation,- ISetFormulaCalculationStartMutation,-} from '@univerjs/engine-formula';+import type { IDirtyUnitDefinedNameMap, IDirtyUnitFeatureMap, IDirtyUnitOtherFormulaMap, IDirtyUnitSheetNameMap, IDirtyUnitSuperTableMap, IExecutionInProgressParams, IFormulaDirtyData, ISetFormulaCalculationNotificationMutation, ISetFormulaCalculationStartMutation } from '@univerjs/engine-formula';import type { IUniverSheetsFormulaBaseConfig } from '../config/config';import type { LocaleKey } from '../locale/types';import {@@ -44,7 +34,6 @@ import {FormulaDataModel,FormulaExecutedStateType,FormulaExecuteStageType,- RegisterOtherFormulaService,SetFormulaCalculationNotificationMutation,SetFormulaCalculationStartMutation,SetFormulaCalculationStopMutation,@@ -133,8 +122,7 @@ export class TriggerCalculationController extends Disposable {@ILogService private readonly _logService: ILogService,@IConfigService private readonly _configService: IConfigService,@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,- @Inject(LocaleService) private readonly _localeService: LocaleService,- @Inject(RegisterOtherFormulaService) private readonly _registerOtherFormulaService: RegisterOtherFormulaService+ @Inject(LocaleService) private readonly _localeService: LocaleService) {super();@@ -306,8 +294,6 @@ export class TriggerCalculationController extends Disposable {const params = this._getDirtyDataByCalculationMode(calculationMode);this._commandService.executeCommand(SetTriggerFormulaCalculationStartMutation.id, params, lo);}-- this._registerOtherFormulaService.calculateStarted$.next(true);}private _getDirtyDataByCalculationMode(calculationMode: CalculationMode): IFormulaDirtyData {