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
test(*): add test cases (#6648)
白熱d2d526b58c30
diff --git a/codecov.yml b/codecov.ymlindex 2e1f8eeb5b..954012f00b 100644--- a/codecov.yml+++ b/codecov.yml@@ -1,10 +1,9 @@coverage:- patch: falsestatus:project:default:# basic- target: auto+ target: 50%threshold: 0base: auto# advanced settingsdiff --git a/common/shared/vitest/index.js b/common/shared/vitest/index.jsindex 4f4d33d825..6f101302ea 100644--- a/common/shared/vitest/index.js+++ b/common/shared/vitest/index.js@@ -19,6 +19,8 @@ const { defineConfig, mergeConfig } = require('vitest/config');function createConfig(options) {return defineConfig(mergeConfig({test: {+ testTimeout: 30_000,+ hookTimeout: 30_000,css: {modules: {classNameStrategy: 'non-scoped',@@ -29,15 +31,14 @@ function createConfig(options) {reporter: ['html', 'json'],provider: 'custom',customProviderModule: require.resolve('@vitest/coverage-istanbul'),+ include: ['src/**/*.{ts,tsx}'],exclude: ['coverage/**','dist/**','**/[.]**',- 'packages/*/test?(s)/**','**/*.d.ts','**/virtual:*','**/__x00__*',- '**/\x00*','cypress/**','test?(s)/**','test?(-*).?(c|m)[jt]s?(x)',@@ -51,6 +52,8 @@ function createConfig(options) {'**/*.stories.tsx','**/__testing__/**','**/*/tailwind.config.ts',+ 'packages/slides/**',+ 'packages/slides-ui/**',],},},diff --git a/package.json b/package.jsonindex 1c00fdaccb..8555246c61 100644--- a/package.json+++ b/package.json@@ -46,14 +46,14 @@},"devDependencies": {"@antfu/eslint-config": "^7.2.0",- "@commitlint/cli": "^20.4.2",- "@commitlint/config-conventional": "^20.4.2",+ "@commitlint/cli": "^20.4.3",+ "@commitlint/config-conventional": "^20.4.3","@eslint-react/eslint-plugin": "^2.8.1","@playwright/test": "^1.57.0","@release-it-plugins/workspaces": "^5.0.3","@release-it/conventional-changelog": "^10.0.5","@types/fs-extra": "^11.0.4",- "@types/node": "^25.3.0",+ "@types/node": "^25.3.5","@types/react": "19.2.14","@types/react-dom": "19.2.3","@univerjs-infra/shared": "workspace:*",@@ -64,17 +64,17 @@"eslint-plugin-react": "^7.37.5","eslint-plugin-react-hooks": "7.0.1","eslint-plugin-react-refresh": "^0.5.2",- "fs-extra": "^11.3.3",+ "fs-extra": "^11.3.4","husky": "^9.1.7",- "lint-staged": "^16.2.7",- "posthog-node": "^5.25.0",+ "lint-staged": "^16.3.2",+ "posthog-node": "^5.28.0","react": "19.2.4","react-dom": "19.2.4","release-it": "^19.2.4",- "serve": "^14.2.5",+ "serve": "^14.2.6","tailwindcss": "3.4.18","tsx": "^4.21.0",- "turbo": "^2.8.10",+ "turbo": "^2.8.14","typescript": "^5.9.3","vitest": "^4.0.18"},diff --git a/packages/action-recorder/src/commands/commands/commands.spec.ts b/packages/action-recorder/src/commands/commands/commands.spec.tsnew file mode 100644index 0000000000..e85de1b1e8--- /dev/null+++ b/packages/action-recorder/src/commands/commands/commands.spec.ts@@ -0,0 +1,103 @@+/**+ * 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 { MessageType } from '@univerjs/design';+import { describe, expect, it, vi } from 'vitest';+import { CompleteRecordingActionCommand, StartRecordingActionCommand, StopRecordingActionCommand } from './record.command';+import { ReplayLocalRecordCommand, ReplayLocalRecordOnActiveCommand, ReplayLocalRecordOnNamesakeCommand } from './replay.command';++describe('action-recorder commands', () => {+ it('should handle record commands', () => {+ const startRecording = vi.fn();+ const completeRecording = vi.fn();+ const accessor = {+ get: vi.fn(() => ({+ startRecording,+ completeRecording,+ })),+ };++ expect(StartRecordingActionCommand.handler(accessor as never, { replaceId: true })).toBe(true);+ expect(startRecording).toHaveBeenCalledWith(true);+ expect(CompleteRecordingActionCommand.handler(accessor as never)).toBe(true);+ expect(StopRecordingActionCommand.handler(accessor as never)).toBe(true);+ expect(completeRecording).toHaveBeenCalledTimes(2);+ });++ it('should handle replay commands and success message branch', async () => {+ const show = vi.fn();+ const replayLocalJSON = vi.fn()+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true);+ const accessor = {+ get: vi.fn()+ .mockImplementationOnce(() => ({ replayLocalJSON }))+ .mockImplementationOnce(() => ({ show }))+ .mockImplementationOnce(() => ({ replayLocalJSON }))+ .mockImplementationOnce(() => ({ replayLocalJSON }))+ .mockImplementationOnce(() => ({ show }))+ .mockImplementationOnce(() => ({ replayLocalJSON }))+ .mockImplementationOnce(() => ({ show })),+ };++ await expect(ReplayLocalRecordCommand.handler(accessor as never)).resolves.toBe(true);+ await expect(ReplayLocalRecordOnNamesakeCommand.handler(accessor as never)).resolves.toBe(false);+ await expect(ReplayLocalRecordOnActiveCommand.handler(accessor as never)).resolves.toBe(true);+ await expect(ReplayLocalRecordOnActiveCommand.handler(accessor as never)).resolves.toBe(false);++ expect(replayLocalJSON).toHaveBeenCalledTimes(4);+ expect(replayLocalJSON).toHaveBeenNthCalledWith(1);+ expect(replayLocalJSON).toHaveBeenNthCalledWith(2, 'name');+ expect(replayLocalJSON).toHaveBeenNthCalledWith(3, 'active');+ expect(replayLocalJSON).toHaveBeenNthCalledWith(4, 'active');+ expect(show).toHaveBeenNthCalledWith(1, {+ type: MessageType.Success,+ content: 'Successfully replayed local records',+ });+ expect(show).toHaveBeenNthCalledWith(2, {+ type: MessageType.Success,+ content: 'Successfully replayed local records',+ });+ expect(show).toHaveBeenCalledTimes(2);+ });++ it('should cover remaining replay command branches', async () => {+ const replayFalse = vi.fn().mockResolvedValue(false);+ const showFalse = vi.fn();+ const accessorFalse = {+ get: vi.fn()+ .mockImplementationOnce(() => ({ replayLocalJSON: replayFalse })),+ };+ await expect(ReplayLocalRecordCommand.handler(accessorFalse as never)).resolves.toBe(false);+ expect(showFalse).not.toHaveBeenCalled();++ const replayTrue = vi.fn().mockResolvedValue(true);+ const showTrue = vi.fn();+ const accessorTrue = {+ get: vi.fn()+ .mockImplementationOnce(() => ({ replayLocalJSON: replayTrue }))+ .mockImplementationOnce(() => ({ show: showTrue })),+ };+ await expect(ReplayLocalRecordOnNamesakeCommand.handler(accessorTrue as never)).resolves.toBe(true);+ expect(showTrue).toHaveBeenCalledWith({+ type: MessageType.Success,+ content: 'Successfully replayed local records',+ });+ });+});diff --git a/packages/action-recorder/src/commands/operations/operation.spec.ts b/packages/action-recorder/src/commands/operations/operation.spec.tsnew file mode 100644index 0000000000..e91936d749--- /dev/null+++ b/packages/action-recorder/src/commands/operations/operation.spec.ts@@ -0,0 +1,32 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { CloseRecordPanelOperation, OpenRecordPanelOperation } from './operation';++describe('action-recorder operations', () => {+ it('should toggle panel open/close', () => {+ const togglePanel = vi.fn();+ const accessor = {+ get: vi.fn(() => ({ togglePanel })),+ };++ expect(OpenRecordPanelOperation.handler(accessor as never, undefined as never)).toBe(true);+ expect(CloseRecordPanelOperation.handler(accessor as never, undefined as never)).toBe(true);+ expect(togglePanel).toHaveBeenCalledWith(true);+ expect(togglePanel).toHaveBeenCalledWith(false);+ });+});diff --git a/packages/action-recorder/src/controllers/action-recorder.controller.spec.tsx b/packages/action-recorder/src/controllers/action-recorder.controller.spec.tsxnew file mode 100644index 0000000000..0e8b313889--- /dev/null+++ b/packages/action-recorder/src/controllers/action-recorder.controller.spec.tsx@@ -0,0 +1,79 @@+/**+ * 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 { BehaviorSubject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { CompleteRecordingActionCommand, StartRecordingActionCommand, StopRecordingActionCommand } from '../commands/commands/record.command';+import { ReplayLocalRecordCommand, ReplayLocalRecordOnActiveCommand, ReplayLocalRecordOnNamesakeCommand } from '../commands/commands/replay.command';+import { CloseRecordPanelOperation, OpenRecordPanelOperation } from '../commands/operations/operation';+import { ActionRecorderController } from './action-recorder.controller';+import { menuSchema, OpenRecorderMenuItemFactory, RECORD_MENU_ITEM_ID, RecordMenuItemFactory, ReplayLocalRecordMenuItemFactory, ReplayLocalRecordOnActiveMenuItemFactory, ReplayLocalRecordOnNamesakeMenuItemFactory } from './action-recorder.menu';++describe('action-recorder controller/menu', () => {+ it('should create menu items', () => {+ const recordItem = RecordMenuItemFactory();+ expect(recordItem.id).toBe(RECORD_MENU_ITEM_ID);++ const panelOpened$ = new BehaviorSubject(false);+ const openItem = OpenRecorderMenuItemFactory({+ get: vi.fn(() => ({ panelOpened$: panelOpened$.asObservable() })),+ } as never);+ expect(openItem.id).toBe(OpenRecordPanelOperation.id);+ expect(openItem.disabled$).toBeDefined();++ expect(ReplayLocalRecordMenuItemFactory().id).toBe(ReplayLocalRecordCommand.id);+ expect(ReplayLocalRecordOnNamesakeMenuItemFactory().id).toBe(ReplayLocalRecordOnNamesakeCommand.id);+ expect(ReplayLocalRecordOnActiveMenuItemFactory().id).toBe(ReplayLocalRecordOnActiveCommand.id);+ expect(Object.keys(menuSchema).length).toBeGreaterThan(0);+ });++ it('should register commands/ui/menu and sheet-recorded commands', () => {+ const registerCommand = vi.fn();+ const registerComponent = vi.fn();+ const mergeMenu = vi.fn();+ const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));+ const registerRecordedCommand = vi.fn();++ const controller = new ActionRecorderController(+ { registerCommand } as never,+ { registerComponent } as never,+ { mergeMenu } as never,+ { register: registerIcon } as never,+ { registerRecordedCommand } as never,+ {} as never+ );++ expect(registerCommand).toHaveBeenCalledWith(StartRecordingActionCommand);+ expect(registerCommand).toHaveBeenCalledWith(StopRecordingActionCommand);+ expect(registerCommand).toHaveBeenCalledWith(CompleteRecordingActionCommand);+ expect(registerCommand).toHaveBeenCalledWith(OpenRecordPanelOperation);+ expect(registerCommand).toHaveBeenCalledWith(CloseRecordPanelOperation);+ expect(registerCommand).toHaveBeenCalledWith(ReplayLocalRecordCommand);+ expect(registerCommand).toHaveBeenCalledWith(ReplayLocalRecordOnNamesakeCommand);+ expect(registerCommand).toHaveBeenCalledWith(ReplayLocalRecordOnActiveCommand);++ expect(registerComponent).toHaveBeenCalledTimes(1);+ const componentFactory = registerComponent.mock.calls[0][1] as () => unknown;+ expect(componentFactory()).toBeDefined();+ expect(registerIcon).toHaveBeenCalledWith('RecordIcon', expect.anything());+ expect(mergeMenu).toHaveBeenCalledWith(menuSchema);++ expect(registerRecordedCommand).toHaveBeenCalled();+ expect(registerRecordedCommand.mock.calls.length).toBeGreaterThan(20);++ controller.dispose();+ });+});diff --git a/packages/action-recorder/src/services/action-recorder.service.spec.ts b/packages/action-recorder/src/services/action-recorder.service.spec.tsnew file mode 100644index 0000000000..50e6f041b0--- /dev/null+++ b/packages/action-recorder/src/services/action-recorder.service.spec.ts@@ -0,0 +1,106 @@+/**+ * 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 { CommandType } from '@univerjs/core';+import { SetSelectionsOperation } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { ActionRecorderService } from './action-recorder.service';++describe('ActionRecorderService', () => {+ it('should record commands, replace selection entries and complete/stop', () => {+ let commandCallback: ((commandInfo: { id: string; type: CommandType; params?: Record<string, unknown> }) => void) | undefined;+ const recorderDisposable = { dispose: vi.fn() };+ const onCommandExecuted = vi.fn((callback: typeof commandCallback) => {+ commandCallback = callback;+ return recorderDisposable;+ });++ const downloadFile = vi.fn();+ const logError = vi.fn();+ const service = new ActionRecorderService(+ { onCommandExecuted } as never,+ { error: logError } as never,+ { downloadFile } as never,+ {+ getFocusedUnit: vi.fn(() => ({ getUnitId: () => 'unit-1' })),+ getUnit: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => ({ getName: () => 'Sheet-A' })),+ })),+ } as never+ );++ expect(() =>+ service.registerRecordedCommand({+ id: 'mutation-id',+ type: CommandType.MUTATION,+ } as never)+ ).toThrow('[CommandRecorderService] Cannot record mutation commands.');++ service.registerRecordedCommand({ id: 'cmd-1', type: CommandType.COMMAND } as never);+ service.registerRecordedCommand({ id: SetSelectionsOperation.id, type: CommandType.OPERATION } as never);++ const panelStates: boolean[] = [];+ const recordingStates: boolean[] = [];+ const commandStates: string[][] = [];+ service.panelOpened$.subscribe((v) => panelStates.push(v));+ service.recording$.subscribe((v) => recordingStates.push(v));+ service.recordedCommands$.subscribe((v) => commandStates.push(v.map((cmd) => cmd.id)));++ service.togglePanel(true);+ service.startRecording(true);+ expect(service.recording).toBe(true);+ expect(recordingStates[recordingStates.length - 1]).toBe(true);++ commandCallback?.({+ id: 'cmd-1',+ type: CommandType.COMMAND,+ params: { unitId: 'unit-1', subUnitId: 'sheet-1' },+ });+ commandCallback?.({+ id: SetSelectionsOperation.id,+ type: CommandType.OPERATION,+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', mark: 1 },+ });+ commandCallback?.({+ id: SetSelectionsOperation.id,+ type: CommandType.OPERATION,+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', mark: 2 },+ });+ commandCallback?.({+ id: 'ignored',+ type: CommandType.COMMAND,+ params: {},+ });++ expect(commandStates[commandStates.length - 1]).toEqual(['cmd-1']);++ service.completeRecording();+ expect(downloadFile).toHaveBeenCalledTimes(1);+ expect(logError).toHaveBeenCalled();+ expect(recorderDisposable.dispose).toHaveBeenCalled();+ expect(recordingStates[recordingStates.length - 1]).toBe(false);++ service.startRecording();+ commandCallback?.({+ id: 'cmd-1',+ type: CommandType.COMMAND,+ params: {},+ });+ service.togglePanel(false);+ expect(panelStates[panelStates.length - 1]).toBe(false);+ expect(recordingStates[recordingStates.length - 1]).toBe(false);+ });+});diff --git a/packages/action-recorder/src/services/replay.service.spec.ts b/packages/action-recorder/src/services/replay.service.spec.tsnew file mode 100644index 0000000000..946964ce12--- /dev/null+++ b/packages/action-recorder/src/services/replay.service.spec.ts@@ -0,0 +1,172 @@+/**+ * 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 { MessageType } from '@univerjs/design';+import { describe, expect, it, vi } from 'vitest';+import { ActionReplayService, ReplayMode } from './replay.service';++vi.mock('@univerjs/core', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/core')>('@univerjs/core');+ return {+ ...actual,+ awaitTime: vi.fn(async () => undefined),+ };+});++describe('ActionReplayService', () => {+ it('should replay local json with success/failure branches', async () => {+ const show = vi.fn();+ const executeCommand = vi.fn(async () => true);+ const focusedUnit = {+ getUnitId: () => 'unit-1',+ getSheetBySheetName: vi.fn(() => ({ getSheetId: () => 'sheet-1' })),+ getActiveSheet: vi.fn(() => ({ getSheetId: () => 'active-sheet' })),+ };+ const localFileService = {+ openFile: vi.fn()+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([{ name: 'bad.json', text: async () => '{bad' }])+ .mockResolvedValueOnce([{ name: 'ok.json', text: async () => JSON.stringify([{ id: 'c1', params: {} }]) }]),+ };+ const service = new ActionReplayService(+ { show } as never,+ { getFocusedUnit: vi.fn(() => focusedUnit) } as never,+ localFileService as never,+ { error: vi.fn() } as never,+ { executeCommand } as never+ );++ await expect(service.replayLocalJSON()).resolves.toBe(false);+ await expect(service.replayLocalJSON()).resolves.toBe(false);+ await expect(service.replayLocalJSON()).resolves.toBe(true);+ expect(show).toHaveBeenCalledWith({+ type: MessageType.Error,+ content: 'Failed to replay commands from local file bad.json.',+ });+ });++ it('should replay commands with mode branches and failure paths', async () => {+ const logError = vi.fn();+ const executeCommandMain = vi.fn()+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(false);+ const focusedUnit = {+ getUnitId: () => 'unit-focused',+ getSheetBySheetName: vi.fn((name: string) => (name === 'exists' ? { getSheetId: () => 'sheet-exists' } : undefined)),+ getActiveSheet: vi.fn(() => ({ getSheetId: () => 'active-sheet-id' })),+ };+ const service = new ActionReplayService(+ { show: vi.fn() } as never,+ { getFocusedUnit: vi.fn(() => focusedUnit) } as never,+ { openFile: vi.fn() } as never,+ { error: logError } as never,+ { executeCommand: executeCommandMain } as never+ );++ await expect(+ service.replayCommands([+ { id: 'cmd-name', params: { unitId: 'u', subUnitId: 'exists' } },+ { id: 'cmd-no-params' },+ ] as never, { mode: ReplayMode.NAME })+ ).resolves.toBe(true);++ await expect(+ service.replayCommands([{ id: 'cmd-name-miss', params: { unitId: 'u', subUnitId: 'missing' } }] as never, { mode: ReplayMode.NAME })+ ).resolves.toBe(true);++ await expect(+ service.replayCommands([{ id: 'cmd-active', params: { unitId: 'u', subUnitId: 'x' } }] as never, { mode: ReplayMode.ACTIVE })+ ).resolves.toBe(true);++ await expect(+ service.replayCommands([{ id: 'cmd-fail', params: { unitId: 'u' } }] as never, { mode: ReplayMode.DEFAULT })+ ).resolves.toBe(false);+ await expect(+ service.replayCommands([{ id: 'cmd-no-params-fail' }] as never, { mode: ReplayMode.DEFAULT })+ ).resolves.toBe(false);++ const activeMissingService = new ActionReplayService(+ { show: vi.fn() } as never,+ {+ getFocusedUnit: vi.fn(() => ({+ getUnitId: () => 'unit-focused',+ getSheetBySheetName: vi.fn(() => undefined),+ getActiveSheet: vi.fn(() => undefined),+ })),+ } as never,+ { openFile: vi.fn() } as never,+ { error: logError } as never,+ { executeCommand: vi.fn(async () => true) } as never+ );+ await expect(+ activeMissingService.replayCommands([{ id: 'cmd-active-miss', params: { subUnitId: 'x' } }] as never, { mode: ReplayMode.ACTIVE })+ ).resolves.toBe(true);++ const noFocusService = new ActionReplayService(+ { show: vi.fn() } as never,+ { getFocusedUnit: vi.fn(() => undefined) } as never,+ { openFile: vi.fn() } as never,+ { error: logError } as never,+ { executeCommand: vi.fn(async () => true) } as never+ );+ await expect(noFocusService.replayCommands([{ id: 'cmd-no-focus' }] as never)).resolves.toBe(true);++ const noFocusDelayExec = vi.fn()+ .mockResolvedValueOnce(false);+ const noFocusDelayService = new ActionReplayService(+ { show: vi.fn() } as never,+ { getFocusedUnit: vi.fn(() => undefined) } as never,+ { openFile: vi.fn() } as never,+ { error: logError } as never,+ { executeCommand: noFocusDelayExec } as never+ );+ await expect(noFocusDelayService.replayCommandsWithDelay([{ id: 'cmd-delay-fail' }] as never)).resolves.toBe(false);++ const focusedDelayExec = vi.fn()+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true);+ const focusedDelayService = new ActionReplayService(+ { show: vi.fn() } as never,+ { getFocusedUnit: vi.fn(() => focusedUnit) } as never,+ { openFile: vi.fn() } as never,+ { error: logError } as never,+ { executeCommand: focusedDelayExec } as never+ );+ await expect(+ focusedDelayService.replayCommandsWithDelay([{ id: 'cmd-delay-param-fail', params: { subUnitId: 'x' } }] as never)+ ).resolves.toBe(false);+ await expect(+ focusedDelayService.replayCommandsWithDelay([{ id: 'cmd-delay-no-params-ok' }] as never)+ ).resolves.toBe(true);++ const focusedDelaySuccessService = new ActionReplayService(+ { show: vi.fn() } as never,+ { getFocusedUnit: vi.fn(() => focusedUnit) } as never,+ { openFile: vi.fn() } as never,+ { error: logError } as never,+ { executeCommand: vi.fn(async () => true) } as never+ );+ await expect(+ focusedDelaySuccessService.replayCommandsWithDelay([{ id: 'cmd-delay-param-ok', params: { unitId: 'will-change' } }] as never)+ ).resolves.toBe(true);++ expect(logError).toHaveBeenCalled();+ });+});diff --git a/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx b/packages/action-recorder/src/views/components/RecorderPanel.spec.tsxnew file mode 100644index 0000000000..1b2b536d26--- /dev/null+++ b/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx@@ -0,0 +1,145 @@+/**+ * 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 { ICommandService } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { CompleteRecordingActionCommand, StartRecordingActionCommand, StopRecordingActionCommand } from '../../commands/commands/record.command';+import { CloseRecordPanelOperation } from '../../commands/operations/operation';+import { RecorderPanel } from './RecorderPanel';++const mocked = vi.hoisted(() => ({+ useDependency: vi.fn(),+ useObservable: vi.fn(),+ callbacks: [] as Array<(...args: unknown[]) => unknown>,+}));++vi.mock('@univerjs/ui', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');+ return {+ ...actual,+ useDependency: mocked.useDependency,+ useObservable: mocked.useObservable,+ };+});++vi.mock('react', async () => {+ const actual = await vi.importActual<typeof import('react')>('react');+ return {+ ...actual,+ useCallback: <T extends (...args: never[]) => unknown>(fn: T) => {+ mocked.callbacks.push(fn as unknown as (...args: unknown[]) => unknown);+ return fn;+ },+ };+});++function getButtonsFromPanel(panelElement: {+ props: { children: Array<{ props: Record<string, unknown> }> };+}) {+ const buttonContainer = panelElement.props.children[2] as {+ props: { children: Array<{ props: { onClick: () => void } }> };+ };+ return buttonContainer.props.children;+}++describe('RecorderPanel', () => {+ it('should return null when panel is closed', () => {+ mocked.useDependency.mockReturnValue({ panelOpened$: {} });+ mocked.useObservable.mockReturnValue(false);+ expect(RecorderPanel()).toBeNull();+ });++ it('should trigger close/start/start(N) commands when not recording', () => {+ mocked.callbacks.length = 0;+ const executeCommand = vi.fn();+ mocked.useDependency.mockImplementation((token: unknown) => {+ if (token === ICommandService) {+ return { executeCommand };+ }+ return { panelOpened$: {}, recording$: {}, recordedCommands$: {} };+ });+ mocked.useObservable+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false)+ .mockReturnValueOnce([]);++ const root = RecorderPanel() as { type: (props: unknown) => unknown; props: unknown };+ const panelElement = root.type(root.props) as {+ props: { children: Array<{ props: Record<string, unknown> }> };+ };+ const buttons = getButtonsFromPanel(panelElement);++ buttons[0].props.onClick();+ buttons[1].props.onClick();+ buttons[2].props.onClick();+ mocked.callbacks[2]();+ mocked.callbacks[3]();++ expect(executeCommand).toHaveBeenCalledWith(CloseRecordPanelOperation.id);+ expect(executeCommand).toHaveBeenCalledWith(StartRecordingActionCommand.id, { replaceId: undefined });+ expect(executeCommand).toHaveBeenCalledWith(StartRecordingActionCommand.id, { replaceId: true });+ });++ it('should trigger cancel/save commands when recording', () => {+ mocked.callbacks.length = 0;+ const executeCommand = vi.fn();+ mocked.useDependency.mockImplementation((token: unknown) => {+ if (token === ICommandService) {+ return { executeCommand };+ }+ return { panelOpened$: {}, recording$: {}, recordedCommands$: {} };+ });+ mocked.useObservable+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(true)+ .mockReturnValueOnce([{ id: 'last.command' }]);++ const root = RecorderPanel() as { type: (props: unknown) => unknown; props: unknown };+ const panelElement = root.type(root.props) as {+ props: { children: Array<{ props: Record<string, unknown> }> };+ };+ const buttons = getButtonsFromPanel(panelElement);++ buttons[0].props.onClick();+ buttons[1].props.onClick();+ mocked.callbacks[0]();+ mocked.callbacks[1](true);++ expect(executeCommand).toHaveBeenCalledWith(StopRecordingActionCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(CompleteRecordingActionCommand.id);+ });++ it('should show recording placeholder title when command list is empty/undefined', () => {+ mocked.callbacks.length = 0;+ mocked.useDependency.mockImplementation((token: unknown) => {+ if (token === ICommandService) {+ return { executeCommand: vi.fn() };+ }+ return { panelOpened$: {}, recording$: {}, recordedCommands$: {} };+ });+ mocked.useObservable+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(undefined);++ const root = RecorderPanel() as { type: (props: unknown) => unknown; props: unknown };+ const panelElement = root.type(root.props) as {+ props: { children: Array<{ props: { children: unknown } }> };+ };+ const title = panelElement.props.children[1].props.children;+ expect(title).toBe('Recording...');+ });+});diff --git a/packages/core/src/__tests__/entry.spec.ts b/packages/core/src/__tests__/entry.spec.tsnew file mode 100644index 0000000000..2582faa46e--- /dev/null+++ b/packages/core/src/__tests__/entry.spec.ts@@ -0,0 +1,28 @@+/**+ * 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';++describe('core entry', () => {+ it('should expose major APIs from index', async () => {+ const mod = await import('../index');++ expect(typeof mod.Univer).toBe('function');+ expect(typeof mod.Skeleton).toBe('function');+ expect(typeof mod.Workbook).toBe('function');+ expect(typeof mod.Range).toBe('function');+ });+});diff --git a/packages/core/src/__tests__/univer-skeleton.spec.ts b/packages/core/src/__tests__/univer-skeleton.spec.tsnew file mode 100644index 0000000000..c59087aa34--- /dev/null+++ b/packages/core/src/__tests__/univer-skeleton.spec.ts@@ -0,0 +1,131 @@+/**+ * 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 { ILocales } from '../shared/locale';+import { defaultTheme } from '@univerjs/themes';+import { describe, expect, it, vi } from 'vitest';+import { Injector } from '../common/di';+import { UniverInstanceType } from '../common/unit';+import { COMMAND_LOG_EXECUTION_CONFIG_KEY } from '../services/command/command.service';+import { IConfigService } from '../services/config/config.service';+import { LifecycleStages } from '../services/lifecycle/lifecycle';+import { LifecycleService } from '../services/lifecycle/lifecycle.service';+import { LocaleService } from '../services/locale/locale.service';+import { LogLevel } from '../services/log/log.service';+import { Skeleton } from '../skeleton';+import { LocaleType } from '../types/enum/locale-type';+import { Univer } from '../univer';++describe('Skeleton', () => {+ it('should update dirty state and release locale data on dispose', () => {+ const skeleton = new Skeleton(new LocaleService());++ expect(skeleton.dirty).toBe(true);+ expect(skeleton.getFontLocale()).toBeUndefined();++ skeleton.makeDirty(false);+ expect(skeleton.dirty).toBe(false);++ skeleton.dispose();+ expect(skeleton.getFontLocale()).toBeNull();+ });+});++describe('Univer', () => {+ it('should apply constructor config and expose locale/config methods', () => {+ const locales: ILocales = {+ [LocaleType.EN_US]: {+ test: {+ greeting: 'Hello {0}',+ },+ },+ } as unknown as ILocales;++ const univer = new Univer({+ theme: defaultTheme,+ darkMode: true,+ locales,+ locale: LocaleType.EN_US,+ logLevel: LogLevel.VERBOSE,+ logCommandExecution: true,+ });++ const injector = univer.__getInjector();+ const localeService = injector.get(LocaleService);++ expect(localeService.getCurrentLocale()).toBe(LocaleType.EN_US);+ expect(localeService.t('test.greeting', 'Univer')).toBe('Hello Univer');+ expect(injector.get(IConfigService).getConfig(COMMAND_LOG_EXECUTION_CONFIG_KEY)).toBe(true);++ univer.setLocale(LocaleType.ZH_CN);+ expect(localeService.getCurrentLocale()).toBe(LocaleType.ZH_CN);++ univer.dispose();+ });++ it('should support add/remove dispose callbacks', () => {+ const univer = new Univer();+ const removedCallback = vi.fn();+ const activeCallback = vi.fn();++ const disposable = univer.onDispose(removedCallback);+ univer.onDispose(activeCallback);+ disposable.dispose();++ univer.dispose();++ expect(removedCallback).not.toHaveBeenCalled();+ expect(activeCallback).toHaveBeenCalledTimes(1);+ });++ it('should create units via deprecated and current APIs', () => {+ const univer = new Univer();+ const injector = univer.__getInjector();++ const sheetA = univer.createUniverSheet({ id: 'sheet-a' });+ const sheetB = univer.createUnit(UniverInstanceType.UNIVER_SHEET, { id: 'sheet-b' });+ const sheetC = univer.createUnit(UniverInstanceType.UNIVER_SHEET, { id: 'sheet-c' });+ const doc = univer.createUniverDoc({ id: 'doc-a' });+ const slide = univer.createUniverSlide({ id: 'slide-a' });++ expect(sheetA.getUnitId()).toBe('sheet-a');+ expect(sheetB.getUnitId()).toBe('sheet-b');+ expect(sheetC.getUnitId()).toBe('sheet-c');+ expect(doc.getUnitId()).toBe('doc-a');+ expect(slide.getUnitId()).toBe('slide-a');+ expect(injector.get(LifecycleService).stage).toBe(LifecycleStages.Ready);++ univer.dispose();+ });++ it('should delegate plugin registration for tuple-style APIs and support parent injector', () => {+ const parentInjector = new Injector([]);+ const univer = new Univer({}, parentInjector);+ const registerPluginSpy = vi+ .spyOn((univer as any)._pluginService, 'registerPlugin')+ .mockImplementation(() => undefined);++ univer.registerPlugins([+ [class FakePluginA {} as never, { enabled: true }],+ [class FakePluginB {} as never],+ ] as never);++ expect(registerPluginSpy).toHaveBeenCalledTimes(2);++ registerPluginSpy.mockRestore();+ univer.dispose();+ });+});diff --git a/packages/core/src/common/__tests__/invert-color.spec.ts b/packages/core/src/common/__tests__/invert-color.spec.tsnew file mode 100644index 0000000000..41b7072a6d--- /dev/null+++ b/packages/core/src/common/__tests__/invert-color.spec.ts@@ -0,0 +1,70 @@+/**+ * 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 { invertColorByHSL, stringToRgb } from '../invert-color/invert-hsl';+import { invertColorByMatrix } from '../invert-color/invert-rgb';+import { denormalizeRGBColor, normalizeRGBColor } from '../invert-color/utils';++function expectRgbColorInRange(color: [number, number, number]) {+ color.forEach((channel) => {+ expect(Number.isInteger(channel)).toBe(true);+ expect(channel).toBeGreaterThanOrEqual(0);+ expect(channel).toBeLessThanOrEqual(255);+ });+}++describe('invert color helpers', () => {+ it('should normalize and denormalize rgb colors', () => {+ expect(normalizeRGBColor([0, 128, 255])).toEqual([0, 128 / 255, 1]);+ expect(denormalizeRGBColor([0, 0.5, 1])).toEqual([0, 128, 255]);+ });++ it('should parse rgb strings and ignore trailing channels', () => {+ expect(stringToRgb('12,34,56')).toEqual([12, 34, 56]);+ expect(stringToRgb('12,34,56,0.5')).toEqual([12, 34, 56]);+ });++ it('should invert colors with the rgb matrix implementation', () => {+ expect(invertColorByMatrix([0, 0, 0])).toEqual([255, 255, 255]);+ expect(invertColorByMatrix([255, 255, 255])).toEqual([0, 0, 0]);+ expect(invertColorByMatrix([255, 0, 0])).toEqual([255, 85, 85]);+ });++ it('should invert grayscale colors with the hsl implementation', () => {+ expect(invertColorByHSL([0, 0, 0])).toEqual([255, 255, 255]);+ expect(invertColorByHSL([255, 255, 255])).toEqual([3, 3, 3]);+ expect(invertColorByHSL([128, 128, 128])).toEqual([127, 127, 127]);+ });++ it('should invert chromatic colors through all hue branches', () => {+ const redDominantLowBlue = invertColorByHSL([255, 128, 0]);+ const redDominantHighBlue = invertColorByHSL([255, 0, 128]);+ const greenDominant = invertColorByHSL([0, 255, 0]);+ const blueDominant = invertColorByHSL([0, 0, 255]);+ const brightChromatic = invertColorByHSL([255, 200, 100]);++ [redDominantLowBlue, redDominantHighBlue, greenDominant, blueDominant, brightChromatic].forEach((color) => {+ expectRgbColorInRange(color);+ });++ expect(redDominantLowBlue).toHaveLength(3);+ expect(redDominantHighBlue).toHaveLength(3);+ expect(greenDominant).toHaveLength(3);+ expect(blueDominant).toHaveLength(3);+ expect(brightChromatic).toHaveLength(3);+ });+});diff --git a/packages/core/src/common/__tests__/registry.spec.ts b/packages/core/src/common/__tests__/registry.spec.tsnew file mode 100644index 0000000000..4de56deb72--- /dev/null+++ b/packages/core/src/common/__tests__/registry.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 { Registry, RegistryAsMap } from '../registry';++describe('registry helpers', () => {+ it('should add unique items into Registry and delete existing ones', () => {+ const registry = Registry.create<string>();++ registry.add('a');+ registry.add('a');+ registry.add('b');++ expect(registry.getData()).toEqual(['a', 'b']);++ registry.delete('a');+ expect(registry.getData()).toEqual(['b']);+ });++ it('should add unique keyed items into RegistryAsMap and delete by key', () => {+ const registry = RegistryAsMap.create();++ registry.add('a', { value: 1 });+ registry.add('a', { value: 2 });+ registry.add('b', { value: 3 });++ expect(Array.from(registry.getData().entries())).toEqual([+ ['a', { value: 1 }],+ ['b', { value: 3 }],+ ]);++ registry.delete('a');+ expect(Array.from(registry.getData().entries())).toEqual([+ ['b', { value: 3 }],+ ]);+ });+});diff --git a/packages/core/src/common/__tests__/shims.spec.ts b/packages/core/src/common/__tests__/shims.spec.tsnew file mode 100644index 0000000000..b4021b5e44--- /dev/null+++ b/packages/core/src/common/__tests__/shims.spec.ts@@ -0,0 +1,119 @@+/**+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { installShims } from '../shims';++type RestorableDescriptor = PropertyDescriptor | undefined;++function restoreProperty(target: object, key: PropertyKey, descriptor: RestorableDescriptor) {+ if (descriptor) {+ Object.defineProperty(target, key, descriptor);+ } else {+ Reflect.deleteProperty(target, key);+ }+}++describe('installShims', () => {+ let requestIdleDescriptor: RestorableDescriptor;+ let cancelIdleDescriptor: RestorableDescriptor;+ let findLastDescriptor: RestorableDescriptor;+ let findLastIndexDescriptor: RestorableDescriptor;+ let stringAtDescriptor: RestorableDescriptor;++ beforeEach(() => {+ vi.useFakeTimers();+ requestIdleDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'requestIdleCallback');+ cancelIdleDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'cancelIdleCallback');+ findLastDescriptor = Object.getOwnPropertyDescriptor(Array.prototype, 'findLast');+ findLastIndexDescriptor = Object.getOwnPropertyDescriptor(Array.prototype, 'findLastIndex');+ stringAtDescriptor = Object.getOwnPropertyDescriptor(String.prototype, 'at');++ Object.defineProperty(globalThis, 'requestIdleCallback', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ Object.defineProperty(globalThis, 'cancelIdleCallback', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ // eslint-disable-next-line no-extend-native+ Object.defineProperty(Array.prototype, 'findLast', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ // eslint-disable-next-line no-extend-native+ Object.defineProperty(Array.prototype, 'findLastIndex', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ // eslint-disable-next-line no-extend-native+ Object.defineProperty(String.prototype, 'at', {+ configurable: true,+ writable: true,+ value: undefined,+ });+ });++ afterEach(() => {+ restoreProperty(globalThis, 'requestIdleCallback', requestIdleDescriptor);+ restoreProperty(globalThis, 'cancelIdleCallback', cancelIdleDescriptor);+ restoreProperty(Array.prototype, 'findLast', findLastDescriptor);+ restoreProperty(Array.prototype, 'findLastIndex', findLastIndexDescriptor);+ restoreProperty(String.prototype, 'at', stringAtDescriptor);+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('should install requestIdleCallback and allow cancellation', () => {+ const callback = vi.fn();++ installShims();++ const canceledId = globalThis.requestIdleCallback?.(callback as never);+ globalThis.cancelIdleCallback?.(canceledId as number);+ vi.advanceTimersByTime(5);+ expect(callback).not.toHaveBeenCalled();++ globalThis.requestIdleCallback?.(callback as never);+ vi.advanceTimersByTime(5);++ expect(callback).toHaveBeenCalledTimes(1);+ const idleDeadline = callback.mock.calls[0][0] as { didTimeout: boolean; timeRemaining: () => number };+ expect(idleDeadline.didTimeout).toBe(false);+ expect(idleDeadline.timeRemaining()).toBeGreaterThanOrEqual(0);+ });++ it('should install array findLastIndex and findLast polyfills', () => {+ installShims();++ expect([1, 2, 3, 2].findLastIndex((value) => value === 2)).toBe(3);+ expect([1, 2, 3, 2].findLast((value) => value === 2)).toBe(2);+ expect(() => Array.prototype.findLastIndex.call([1], null as never)).toThrowError(/callback must be a function/);+ });++ it('should install string at polyfill', () => {+ installShims();++ expect('abcd'.at(1)).toBe('b');+ expect('abcd'.at(-1)).toBe('d');+ expect('abcd'.at(10)).toBeUndefined();+ });+});diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.tsindex dec2244c88..43a4386e26 100644--- a/packages/core/src/facade/f-univer.ts+++ b/packages/core/src/facade/f-univer.ts@@ -17,7 +17,7 @@import type { CommandListener, DocumentDataModel, IDisposable, IDocumentData, IExecutionOptions, ILanguagePack, IParagraphStyle, ITextDecoration, ITextStyle, LifecycleStages, LocaleType } from '@univerjs/core';import type { Subscription } from 'rxjs';import type { ICommandEvent, IEventParamConfig } from './f-event';-import { CanceledError, ColorBuilder, Disposable, ICommandService, Inject, Injector, IUniverInstanceService, LifecycleService, LocaleService, ParagraphStyleBuilder, ParagraphStyleValue, RedoCommand, RichTextBuilder, RichTextValue, TextDecorationBuilder, TextStyleBuilder, TextStyleValue, ThemeService, toDisposable, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';+import { CanceledError, Disposable, ICommandService, Inject, Injector, IUniverInstanceService, LifecycleService, LocaleService, ParagraphStyleBuilder, ParagraphStyleValue, RedoCommand, RichTextBuilder, RichTextValue, TextDecorationBuilder, TextStyleBuilder, TextStyleValue, ThemeService, toDisposable, UndoCommand, Univer, UniverInstanceType } from '@univerjs/core';import { FBlob } from './f-blob';import { FDoc } from './f-doc';import { FEnum } from './f-enum';@@ -522,19 +522,6 @@ export class FUniver extends Disposable {return this._injector.createInstance(FBlob);}- /**- * Create a new color.- * @returns {ColorBuilder} The new color instance- * @example- * ```ts- * const color = univerAPI.newColor();- * ```- * @deprecated- */- newColor(): ColorBuilder {- return new ColorBuilder();- }-/*** Create a new rich text.* @param {IDocumentData} datadiff --git a/packages/core/src/observer/__tests__/observable.spec.ts b/packages/core/src/observer/__tests__/observable.spec.tsindex f4b55821dd..b058bc2025 100644--- a/packages/core/src/observer/__tests__/observable.spec.ts+++ b/packages/core/src/observer/__tests__/observable.spec.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import { describe, expect, it } from 'vitest';-import { EventState } from '../observable';+import { describe, expect, it, vi } from 'vitest';+import { EventState, EventSubject, fromEventSubject } from '../observable';describe('EventState', () => {it('should initialize with skipNextObservers set to false', () => {@@ -29,3 +29,94 @@ describe('EventState', () => {expect(eventState.isStopPropagation).toBe(true);});});++describe('EventSubject', () => {+ it('should notify observers by priority and keep last return value', () => {+ const subject = new EventSubject<string>();+ const order: string[] = [];++ subject.subscribeEvent({+ priority: 10,+ next: ([event]) => {+ order.push(`late:${event}`);+ return 'late';+ },+ });+ subject.subscribeEvent({+ priority: 1,+ next: ([event]) => {+ order.push(`early:${event}`);+ return 'early';+ },+ });++ const result = subject.emitEvent('evt');++ expect(order).toEqual(['early:evt', 'late:evt']);+ expect(result).toEqual({+ handled: true,+ lastReturnValue: 'late',+ stopPropagation: false,+ });+ });++ it('should stop on skipNextObservers and expose propagation state', () => {+ const subject = new EventSubject<string>();+ const nextSpy = vi.fn();++ subject.subscribeEvent((event, state) => {+ state.stopPropagation();+ state.skipNextObservers = true;+ return `${event}:stopped`;+ });+ subject.subscribeEvent(nextSpy);++ const result = subject.emitEvent('evt');++ expect(nextSpy).not.toHaveBeenCalled();+ expect(result).toEqual({+ handled: true,+ lastReturnValue: 'evt:stopped',+ stopPropagation: true,+ });+ });++ it('should clear observers on complete and throw after unsubscribe', () => {+ const subject = new EventSubject<string>();+ const completeSpy = vi.fn();++ subject.subscribeEvent({ complete: completeSpy });+ subject.clearObservers();+ expect(completeSpy).toHaveBeenCalledTimes(1);+ expect(subject.emitEvent('evt')).toEqual({+ handled: false,+ lastReturnValue: 'evt',+ stopPropagation: false,+ });++ subject.complete();+ expect(subject.emitEvent('evt')).toEqual({+ handled: false,+ lastReturnValue: 'evt',+ stopPropagation: false,+ });++ subject.unsubscribe();+ expect(() => subject.emitEvent('evt')).toThrowError(/closed subject/);+ });++ it('should forward events through fromEventSubject and unsubscribe cleanly', () => {+ const subject = new EventSubject<string>();+ const received: string[] = [];+ const subscription = fromEventSubject(subject).subscribe((value) => {+ received.push(value);+ });++ subject.emitEvent('first');+ subscription.unsubscribe();+ subject.emitEvent('second');+ subject.unsubscribe();++ expect(received).toEqual(['first']);+ });+});diff --git a/packages/core/src/services/instance/__tests__/instance.service.spec.ts b/packages/core/src/services/instance/__tests__/instance.service.spec.tsnew file mode 100644index 0000000000..1054d31a8d--- /dev/null+++ b/packages/core/src/services/instance/__tests__/instance.service.spec.ts@@ -0,0 +1,189 @@+/**+ * 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 { IWorkbookData } from '../../../sheets/typedef';+import type { Workbook } from '../../../sheets/workbook';+import type { IDocumentData } from '../../../types/interfaces/i-document-data';+import type { ISlideData } from '../../../types/interfaces/i-slide-data';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { UniverInstanceType } from '../../../common/unit';+import { DocumentDataModel } from '../../../docs/data-model/document-data-model';+import { Workbook as WorkbookModel } from '../../../sheets/workbook';+import { SlideDataModel } from '../../../slides/slide-model';+import { FOCUSING_DOC, FOCUSING_SHEET, FOCUSING_SLIDE, FOCUSING_UNIT } from '../../context/context';+import { ContextService } from '../../context/context.service';+import { DesktopLogService, LogLevel } from '../../log/log.service';+import { UniverInstanceService } from '../instance.service';++function createWorkbookData(id = 'sheet-unit'): Partial<IWorkbookData> {+ return {+ id,+ name: 'Workbook',+ styles: {},+ sheetOrder: ['sheet-1'],+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet1',+ cellData: {},+ rowCount: 5,+ columnCount: 5,+ },+ },+ };+}++function createDocData(id = 'doc-unit'): Partial<IDocumentData> {+ return {+ id,+ body: { dataStream: 'Hello\r\n' },+ documentStyle: {+ pageSize: { width: 100, height: 100 },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ },+ };+}++function createSlideData(id = 'slide-unit'): Partial<ISlideData> {+ return {+ id,+ title: 'Slide',+ body: { pages: {}, pageOrder: [] },+ };+}++describe('UniverInstanceService', () => {+ let service: UniverInstanceService;+ let contextService: ContextService;+ let logService: DesktopLogService;++ beforeEach(() => {+ contextService = new ContextService();+ logService = new DesktopLogService();+ logService.setLogLevel(LogLevel.SILENT);+ service = new UniverInstanceService(new Injector(), contextService, logService);++ service.registerCtorForType(UniverInstanceType.UNIVER_SHEET, WorkbookModel as never);+ service.registerCtorForType(UniverInstanceType.UNIVER_DOC, DocumentDataModel as never);+ service.registerCtorForType(UniverInstanceType.UNIVER_SLIDE, SlideDataModel as never);+ service.__setCreateHandler((type, data, _ctor, options) => {+ let unit;+ if (type === UniverInstanceType.UNIVER_SHEET) {+ unit = new WorkbookModel(data as Partial<IWorkbookData>, logService);+ } else if (type === UniverInstanceType.UNIVER_DOC) {+ unit = new DocumentDataModel(data as Partial<IDocumentData>);+ } else {+ unit = new SlideDataModel(data as Partial<ISlideData>);+ }++ service.__addUnit(unit, options);+ return unit;+ });+ });++ afterEach(() => {+ service.dispose();+ contextService.dispose();+ logService.dispose();+ });++ it('should create units, set current unit and expose lookup APIs', () => {+ const added: string[] = [];+ service.getTypeOfUnitAdded$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((unit) => {+ added.push(unit.getUnitId());+ });++ const workbook = service.createUnit<Partial<IWorkbookData>, WorkbookModel>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ const doc = service.createUnit<Partial<IDocumentData>, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData(), { makeCurrent: false });++ expect(added).toEqual(['sheet-unit']);+ expect(workbook.getUnitId()).toBe('sheet-unit');+ expect(service.getCurrentUnitOfType<WorkbookModel>(UniverInstanceType.UNIVER_SHEET)?.getUnitId()).toBe('sheet-unit');+ expect(service.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)).toBeUndefined();+ expect(service.getUnit<WorkbookModel>('sheet-unit', UniverInstanceType.UNIVER_SHEET)?.getUnitId()).toBe('sheet-unit');+ expect(service.getUnit('sheet-unit', UniverInstanceType.UNIVER_DOC)).toBeNull();+ expect(service.getAllUnitsForType<WorkbookModel>(UniverInstanceType.UNIVER_SHEET)).toHaveLength(1);+ expect(service.getUnitType(doc.getUnitId())).toBe(UniverInstanceType.UNIVER_DOC);+ expect(service.getUnitType('missing')).toBe(UniverInstanceType.UNRECOGNIZED);+ });++ it('should focus sheet, doc, slide and reset contexts on null focus', () => {+ const workbook = service.createUnit<Partial<IWorkbookData>, WorkbookModel>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ const doc = service.createUnit<Partial<IDocumentData>, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());+ const slide = service.createUnit<Partial<ISlideData>, SlideDataModel>(UniverInstanceType.UNIVER_SLIDE, createSlideData());++ service.focusUnit(workbook.getUnitId());+ expect(contextService.getContextValue(FOCUSING_UNIT)).toBe(true);+ expect(contextService.getContextValue(FOCUSING_SHEET)).toBe(true);+ expect(contextService.getContextValue(FOCUSING_DOC)).toBe(false);++ service.focusUnit(doc.getUnitId());+ expect(service.getFocusedUnit()?.getUnitId()).toBe(doc.getUnitId());+ expect(contextService.getContextValue(FOCUSING_DOC)).toBe(true);+ expect(contextService.getContextValue(FOCUSING_SHEET)).toBe(false);++ service.focusUnit(slide.getUnitId());+ expect(contextService.getContextValue(FOCUSING_SLIDE)).toBe(true);+ expect(contextService.getContextValue(FOCUSING_DOC)).toBe(false);++ service.focusUnit(null);+ expect(service.getFocusedUnit()).toBeNull();+ expect(contextService.getContextValue(FOCUSING_UNIT)).toBe(false);+ expect(contextService.getContextValue(FOCUSING_DOC)).toBe(false);+ expect(contextService.getContextValue(FOCUSING_SHEET)).toBe(false);+ expect(contextService.getContextValue(FOCUSING_SLIDE)).toBe(false);+ });++ it('should replace docs and dispose units while resetting focus and current', () => {+ const disposed: string[] = [];+ service.getTypeOfUnitDisposed$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((unit) => {+ disposed.push(unit.getUnitId());+ });++ const doc = service.createUnit<Partial<IDocumentData>, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());+ service.focusUnit(doc.getUnitId());++ const replacement = new DocumentDataModel(createDocData('doc-unit'));+ service.changeDoc(doc.getUnitId(), replacement);+ expect(service.getUniverDocInstance('doc-unit')).toBe(replacement);++ expect(service.disposeUnit('doc-unit')).toBe(true);+ expect(disposed).toEqual(['doc-unit']);+ expect(service.getCurrentUniverDocInstance()).toBeNull();+ expect(service.getFocusedUnit()).toBeUndefined();+ expect(service.disposeUnit('missing')).toBe(false);+ });++ it('should throw on duplicate unit id and support current type stream', () => {+ const currentIds: Array<string | null> = [];+ service.getCurrentTypeOfUnit$<WorkbookModel>(UniverInstanceType.UNIVER_SHEET).subscribe((unit) => {+ currentIds.push(unit?.getUnitId() ?? null);+ });++ service.createUnit<Partial<IWorkbookData>, WorkbookModel>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ service.createUnit<Partial<IWorkbookData>, WorkbookModel>(UniverInstanceType.UNIVER_SHEET, createWorkbookData('sheet-unit-2'));+ service.setCurrentUnitForType('sheet-unit-2');++ expect(() => service.__addUnit(new WorkbookModel(createWorkbookData('sheet-unit-2'), logService))).toThrowError(/same unit id/);+ expect(() => service.setCurrentUnitForType('missing')).toThrowError(/no document with unitId missing/);+ expect(currentIds).toContain('sheet-unit');+ expect(currentIds).toContain('sheet-unit-2');+ });+});diff --git a/packages/core/src/services/log/__tests__/log.service.spec.ts b/packages/core/src/services/log/__tests__/log.service.spec.tsnew file mode 100644index 0000000000..2e6789c8d3--- /dev/null+++ b/packages/core/src/services/log/__tests__/log.service.spec.ts@@ -0,0 +1,81 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopLogService, LogLevel } from '../log.service';++describe('DesktopLogService', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should respect log level thresholds', () => {+ const service = new DesktopLogService();+ const debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => undefined);+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ service.setLogLevel(LogLevel.WARN);+ service.debug('debug');+ service.log('log');+ service.warn('warn');+ service.error('error');++ expect(debugSpy).not.toHaveBeenCalled();+ expect(logSpy).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledWith('warn');+ expect(errorSpy).toHaveBeenCalledWith('error');+ });++ it('should format tagged messages when logging', () => {+ const service = new DesktopLogService();+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);++ service.log('[core]', 'message');++ expect(logSpy).toHaveBeenCalledWith('\x1B[97;104m[core]\x1B[0m', 'message');+ });++ it('should deduplicate deprecate logs and clear cache on dispose', () => {+ const service = new DesktopLogService();+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ service.deprecate('[deprecated]', { key: 'value' });+ service.deprecate('[deprecated]', { key: 'value' });++ expect(errorSpy).toHaveBeenCalledTimes(1);++ service.dispose();+ service.deprecate('[deprecated]', { key: 'value' });++ expect(errorSpy).toHaveBeenCalledTimes(2);+ });++ it('should suppress all output at silent level', () => {+ const service = new DesktopLogService();+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ service.setLogLevel(LogLevel.SILENT);+ service.warn('warn');+ service.error('error');+ service.deprecate('deprecated');++ expect(warnSpy).not.toHaveBeenCalled();+ expect(errorSpy).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/services/resource-manager/__tests__/resource-manager.service.spec.ts b/packages/core/src/services/resource-manager/__tests__/resource-manager.service.spec.tsnew file mode 100644index 0000000000..6755e1a802--- /dev/null+++ b/packages/core/src/services/resource-manager/__tests__/resource-manager.service.spec.ts@@ -0,0 +1,137 @@+/**+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { UniverInstanceType } from '../../../common/unit';+import { DesktopLogService, LogLevel } from '../../log/log.service';+import { ResourceManagerService } from '../resource-manager.service';++describe('ResourceManagerService', () => {+ let logService: DesktopLogService;+ let service: ResourceManagerService;++ beforeEach(() => {+ logService = new DesktopLogService();+ logService.setLogLevel(LogLevel.SILENT);+ service = new ResourceManagerService(logService);+ });++ afterEach(() => {+ service.dispose();+ logService.dispose();+ });++ it('should register hooks, emit register event and filter resources by type', () => {+ const registered: string[] = [];+ service.register$.subscribe((hook) => registered.push(hook.pluginName));++ service.registerPluginResource({+ pluginName: 'SHEET_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_SHEET],+ onLoad: () => {},+ onUnLoad: () => {},+ toJson: (unitId) => JSON.stringify({ unitId }),+ parseJson: JSON.parse,+ });+ service.registerPluginResource({+ pluginName: 'DOC_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_DOC],+ onLoad: () => {},+ onUnLoad: () => {},+ toJson: () => 'doc',+ parseJson: JSON.parse,+ });++ expect(registered).toEqual(['SHEET_TEST_PLUGIN', 'DOC_TEST_PLUGIN']);+ expect(service.getAllResourceHooks()).toHaveLength(2);+ expect(service.getResources('u1')).toEqual([+ { name: 'SHEET_TEST_PLUGIN', data: '{"unitId":"u1"}' },+ { name: 'DOC_TEST_PLUGIN', data: 'doc' },+ ]);+ expect(service.getResourcesByType('u1', UniverInstanceType.UNIVER_DOC)).toEqual([+ { name: 'DOC_TEST_PLUGIN', data: 'doc' },+ ]);+ });++ it('should unregister resources through returned disposable and explicit disposal', () => {+ const disposable = service.registerPluginResource({+ pluginName: 'SHEET_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_SHEET],+ onLoad: () => {},+ onUnLoad: () => {},+ toJson: () => 'sheet',+ parseJson: JSON.parse,+ });++ expect(() => service.registerPluginResource({+ pluginName: 'SHEET_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_SHEET],+ onLoad: () => {},+ onUnLoad: () => {},+ toJson: () => 'sheet',+ parseJson: JSON.parse,+ })).toThrowError(/registered/);++ disposable.dispose();+ expect(service.getAllResourceHooks()).toHaveLength(0);++ service.registerPluginResource({+ pluginName: 'DOC_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_DOC],+ onLoad: () => {},+ onUnLoad: () => {},+ toJson: () => 'doc',+ parseJson: JSON.parse,+ });+ service.disposePluginResource('DOC_TEST_PLUGIN');+ expect(service.getAllResourceHooks()).toHaveLength(0);+ });++ it('should load, unload and log parsing errors', () => {+ const loaded: unknown[] = [];+ const unloaded: string[] = [];+ const errorSpy = vi.spyOn(logService, 'error');++ service.registerPluginResource({+ pluginName: 'SHEET_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_SHEET],+ onLoad: (_unitId, resource) => loaded.push(resource),+ onUnLoad: (unitId) => unloaded.push(unitId),+ toJson: () => 'sheet',+ parseJson: JSON.parse,+ });+ service.registerPluginResource({+ pluginName: 'DOC_TEST_PLUGIN',+ businesses: [UniverInstanceType.UNIVER_DOC],+ onLoad: () => {},+ onUnLoad: () => {},+ toJson: () => 'doc',+ parseJson: () => {+ throw new Error('bad json');+ },+ });++ service.loadResources('unit-1', [+ { name: 'SHEET_TEST_PLUGIN', data: '{"ok":true}' },+ { name: 'DOC_TEST_PLUGIN', data: 'boom' },+ ]);+ service.unloadResources('unit-1', UniverInstanceType.UNIVER_SHEET);++ expect(loaded).toEqual([{ ok: true }]);+ expect(unloaded).toEqual(['unit-1']);+ expect(errorSpy).toHaveBeenCalled();+ });+});diff --git a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.tsnew file mode 100644index 0000000000..d7e2863a1f--- /dev/null+++ b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts@@ -0,0 +1,209 @@+/**+ * 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 { ICommand } from '../../command/command.service';+import type { IUniverInstanceService } from '../../instance/instance.service';+import { BehaviorSubject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '../../../common/const';+import { Injector } from '../../../common/di';+import { CommandService, CommandType, ICommandService } from '../../command/command.service';+import { ConfigService, IConfigService } from '../../config/config.service';+import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_SHEET } from '../../context/context';+import { ContextService, IContextService } from '../../context/context.service';+import { DesktopLogService, ILogService, LogLevel } from '../../log/log.service';+import { IUndoRedoService, LocalUndoRedoService, RedoCommandId, UndoCommandId } from '../undoredo.service';++const MUTATION_ID = 'test.mutation';++class FocusedUnit {+ constructor(private readonly _unitId: string) {}++ getUnitId() {+ return this._unitId;+ }+}++describe('LocalUndoRedoService', () => {+ let injector: Injector;+ let commandService: ICommandService;+ let contextService: ContextService;+ let logService: DesktopLogService;+ let focused$: BehaviorSubject<FocusedUnit | null>;+ let instanceService: IUniverInstanceService;+ let undoRedoService: LocalUndoRedoService;+ let mutationLog: string[];++ beforeEach(() => {+ injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);++ commandService = injector.get(ICommandService);+ contextService = injector.get(IContextService) as ContextService;+ logService = injector.get(ILogService) as DesktopLogService;+ logService.setLogLevel(LogLevel.SILENT);++ focused$ = new BehaviorSubject<FocusedUnit | null>(new FocusedUnit('unit-1'));+ instanceService = {+ focused$: focused$.asObservable(),+ getFocusedUnit: () => focused$.value,+ } as IUniverInstanceService;++ undoRedoService = new LocalUndoRedoService(instanceService, commandService, contextService);+ injector.add([IUndoRedoService, { useValue: undoRedoService }]);++ mutationLog = [];+ commandService.registerCommand({+ id: MUTATION_ID,+ type: CommandType.MUTATION,+ handler: (_accessor, params?: { label: string; fail?: boolean }) => {+ mutationLog.push(params?.label ?? 'unknown');+ return !params?.fail;+ },+ } as ICommand);+ });++ afterEach(() => {+ undoRedoService.dispose();+ focused$.complete();+ logService.dispose();+ contextService.dispose();+ });++ it('should push undo items, clear redo stack and expose focused status', () => {+ const statuses: Array<{ undos: number; redos: number }> = [];+ undoRedoService.undoRedoStatus$.subscribe((status) => {+ statuses.push(status);+ });++ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-1' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-1' } }],+ id: 'item-1',+ });++ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('item-1');+ expect(undoRedoService.pitchTopRedoElement()).toBeNull();++ undoRedoService.popUndoToRedo();+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();+ expect(undoRedoService.pitchTopRedoElement()?.id).toBe('item-1');++ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-2' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-2' } }],+ id: 'item-2',+ });++ expect(undoRedoService.pitchTopRedoElement()).toBeNull();+ expect(statuses.at(-1)).toEqual({ undos: 1, redos: 0 });+ });++ it('should execute undo and redo commands against registered mutations', () => {+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-run' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-run' } }],+ id: 'run',+ });++ expect(commandService.syncExecuteCommand(UndoCommandId)).toBe(true);+ expect(mutationLog).toEqual(['undo-run']);+ expect(undoRedoService.pitchTopRedoElement()?.id).toBe('run');++ expect(commandService.syncExecuteCommand(RedoCommandId)).toBe(true);+ expect(mutationLog).toEqual(['undo-run', 'redo-run']);+ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('run');+ });++ it('should rollback the latest undo item and support batching', () => {+ const batching = undoRedoService.__tempBatchingUndoRedo('unit-1');++ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-batch-1' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-batch-1' } }],+ id: 'batch',+ });+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-batch-2' } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-batch-2' } }],+ id: 'batch',+ });++ batching.dispose();++ const top = undoRedoService.pitchTopUndoElement();+ expect(top?.undoMutations).toHaveLength(2);+ expect(top?.redoMutations).toHaveLength(2);++ undoRedoService.rollback('batch');+ expect(mutationLog).toEqual(['undo-batch-1', 'undo-batch-2']);+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();+ });++ it('should resolve focused unit id from sheet editor contexts and clear unit stacks', () => {+ contextService.setContextValue(FOCUSING_SHEET, true);+ contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, true);+ undoRedoService.pushUndoRedo({+ unitID: DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,+ undoMutations: [{ id: MUTATION_ID, params: { label: 'fx-undo' } }],+ redoMutations: [],+ id: 'fx',+ });+ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('fx');++ contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, false);+ contextService.setContextValue(EDITOR_ACTIVATED, true);+ undoRedoService.pushUndoRedo({+ unitID: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ undoMutations: [{ id: MUTATION_ID, params: { label: 'doc-undo' } }],+ redoMutations: [],+ id: 'doc',+ });+ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('doc');++ undoRedoService.clearUndoRedo(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();+ });++ it('should still move stacks on failed undo or redo execution and reject nested batching', () => {+ undoRedoService.pushUndoRedo({+ unitID: 'unit-1',+ undoMutations: [{ id: MUTATION_ID, params: { label: 'undo-fail', fail: true } }],+ redoMutations: [{ id: MUTATION_ID, params: { label: 'redo-fail', fail: true } }],+ id: 'fail',+ });++ expect(commandService.syncExecuteCommand(UndoCommandId)).toBe(true);+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();+ expect(undoRedoService.pitchTopRedoElement()?.id).toBe('fail');++ expect(commandService.syncExecuteCommand(RedoCommandId)).toBe(true);+ expect(undoRedoService.pitchTopRedoElement()).toBeNull();+ expect(undoRedoService.pitchTopUndoElement()?.id).toBe('fail');++ const batching = undoRedoService.__tempBatchingUndoRedo('unit-1');+ expect(() => undoRedoService.__tempBatchingUndoRedo('unit-1')).toThrowError(/cannot batching undo redo twice/);+ batching.dispose();+ });+});diff --git a/packages/core/src/shared/__tests__/color-kit.spec.ts b/packages/core/src/shared/__tests__/color-kit.spec.tsnew file mode 100644index 0000000000..58935361a9--- /dev/null+++ b/packages/core/src/shared/__tests__/color-kit.spec.ts@@ -0,0 +1,78 @@+/**+ * 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 { ColorKit, isBlackColor, isWhiteColor } from '../color/color-kit';++describe('ColorKit', () => {+ it('should parse named, hex, rgb, hsl and hsv colors', () => {+ expect(new ColorKit('white').toRgb()).toEqual({ r: 255, g: 255, b: 255, a: 1 });+ expect(new ColorKit('#ffffff00').toRgb()).toEqual({ r: 255, g: 255, b: 255, a: 0 });+ expect(new ColorKit('rgb(1,2,3)').toRgb()).toEqual({ r: 1, g: 2, b: 3 });+ expect(new ColorKit('hsl(0,100,50)').toRgb()).toEqual({ r: 255, g: 0, b: 0 });+ expect(new ColorKit('hsv(240,100,100)').toRgb()).toEqual({ r: 0, g: 0, b: 255 });+ });++ it('should stringify colors and support short hex output when possible', () => {+ const color = new ColorKit({ r: 255, g: 255, b: 255, a: 0 });++ expect(color.toRgbString()).toBe('rgba(255,255,255,0)');+ expect(color.toString()).toBe('rgba(255,255,255,0)');+ expect(color.toHexString()).toBe('#ffffff00');+ expect(color.toHexString(true)).toBe('#fff0');+ });++ it('should adjust lightness and alpha and calculate brightness metrics', () => {+ const color = new ColorKit('#808080');++ expect(color.lighten(30).toHexString()).toBe('#cccccc');+ expect(color.darken(60).toHexString()).toBe('#000000');+ expect(color.setAlpha(0.25).toRgbString()).toBe('rgba(128,128,128,0.25)');+ expect(color.getAlpha()).toBe(1);+ expect(color.getBrightness()).toBe(128);+ expect(color.getLuminance()).toBeGreaterThan(0);+ expect(color.isDark()).toBe(false);+ expect(color.isLight()).toBe(true);+ });++ it('should mix colors, clamp amount and compute contrast ratio', () => {+ expect(ColorKit.mix('#000000', '#ffffff', -1).toHexString()).toBe('#000000');+ expect(ColorKit.mix('#000000', '#ffffff', 2).toHexString()).toBe('#ffffff');+ expect(ColorKit.mix('#000000', '#ffffff', 0.5).toHexString()).toBe('#808080');+ expect(ColorKit.getContrastRatio('#000000', '#ffffff')).toBe(21);+ });++ it('should mark invalid colors and throw on malformed known formats', () => {+ const invalid = new ColorKit('not-a-color');++ expect(invalid.isValid).toBe(false);+ expect(invalid.toRgb()).toEqual({ r: 0, g: 0, b: 0, a: 0 });+ expect(() => new ColorKit('#1')).toThrowError(/illegal hex color/);+ expect(() => new ColorKit('rgb(1,2)')).toThrowError(/illegal rgb color/);+ });++ it('should recognize black and white strings across formats', () => {+ expect(isBlackColor('#000')).toBe(true);+ expect(isBlackColor('rgba(0,0,0,0.5)')).toBe(true);+ expect(isBlackColor('hsl(0,0,0)')).toBe(true);+ expect(isBlackColor('rgb(1,0,0)')).toBe(false);++ expect(isWhiteColor('#fff')).toBe(true);+ expect(isWhiteColor('rgba(255,255,255,0.5)')).toBe(true);+ expect(isWhiteColor('hsl(0,0,100)')).toBe(true);+ expect(isWhiteColor('rgb(254,255,255)')).toBe(false);+ });+});diff --git a/packages/core/src/shared/__tests__/common.spec.ts b/packages/core/src/shared/__tests__/common.spec.tsindex 678b20a2ad..9fe4a2658b 100644--- a/packages/core/src/shared/__tests__/common.spec.ts+++ b/packages/core/src/shared/__tests__/common.spec.ts@@ -14,8 +14,60 @@* limitations under the License.*/+import type { ICellData, ICellWithCoord, IRange, ISelectionCell } from '../../sheets/typedef';+import type { IDocumentData } from '../../types/interfaces';import { describe, expect, it } from 'vitest';-import { cellToRange, isFormulaId, isFormulaString } from '../common';+import {+ RANGE_TYPE,+} from '../../sheets/typedef';+import { BorderStyleTypes, ThemeColorType } from '../../types/enum';+import {+ BaselineOffset,+ HorizontalAlign,+ TextDirection,+ VerticalAlign,+ WrapStrategy,+} from '../../types/enum/text-style';+import {+ cellToRange,+ convertCellToRange,+ covertCellValue,+ covertCellValues,+ getBorderStyleType,+ getColorStyle,+ getDocsUpdateBody,+ handleStyleToString,+ isCellCoverable,+ isEmptyCell,+ isFormulaId,+ isFormulaString,+ isValidRange,+ makeCellRangeToRangeData,+} from '../common';++function createCellWithCoord(overrides?: Partial<ICellWithCoord>): ICellWithCoord {+ return {+ actualRow: 1,+ actualColumn: 2,+ startX: 10,+ endX: 20,+ startY: 30,+ endY: 40,+ isMerged: false,+ isMergedMainCell: false,+ mergeInfo: {+ startRow: 0,+ startColumn: 0,+ endRow: 2,+ endColumn: 3,+ startX: 1,+ endX: 4,+ startY: 5,+ endY: 6,+ },+ ...overrides,+ } as ICellWithCoord;+}describe('Test common', () => {it('Test cellToRange', () => {@@ -45,4 +97,191 @@ describe('Test common', () => {expect(isFormulaId({})).toBe(false);expect(isFormulaId({ f: '' })).toBe(false);});++ it('should convert merged and merged-main cells into ranges', () => {+ expect(convertCellToRange(createCellWithCoord())).toEqual({+ startRow: 1,+ startColumn: 2,+ endRow: 1,+ endColumn: 2,+ startY: 30,+ endY: 40,+ startX: 10,+ endX: 20,+ });++ expect(convertCellToRange(createCellWithCoord({ isMerged: true }))).toEqual({+ startRow: 0,+ startColumn: 0,+ endRow: 2,+ endColumn: 3,+ startY: 5,+ endY: 6,+ startX: 1,+ endX: 4,+ });++ expect(convertCellToRange(createCellWithCoord({ isMergedMainCell: true }))).toEqual({+ startRow: 1,+ startColumn: 2,+ endRow: 2,+ endColumn: 3,+ startY: 5,+ endY: 6,+ startX: 1,+ endX: 4,+ });+ });++ it('should build plain ranges and check empty or coverable cells', () => {+ expect(makeCellRangeToRangeData(null)).toBeUndefined();+ expect(makeCellRangeToRangeData({+ actualRow: 4,+ actualColumn: 5,+ isMerged: true,+ isMergedMainCell: false,+ startRow: 1,+ startColumn: 2,+ endRow: 6,+ endColumn: 7,+ } as ISelectionCell)).toEqual({+ startRow: 1,+ startColumn: 2,+ endRow: 6,+ endColumn: 7,+ });++ expect(isEmptyCell(null)).toBe(true);+ expect(isEmptyCell({ v: '', p: null } as ICellData)).toBe(true);+ expect(isEmptyCell({ v: '', p: { body: { dataStream: 'x' } } } as unknown as ICellData)).toBe(false);+ expect(isCellCoverable({ v: '', p: null } as unknown as ICellData)).toBe(true);+ expect(isCellCoverable({ v: '', p: null, coverable: false } as never)).toBe(false);+ });++ it('should resolve colors and style strings', () => {+ expect(getColorStyle({ rgb: 'rgb(255, 0, 0)' })).toBe('#ff0000');+ expect(getColorStyle({ th: ThemeColorType.ACCENT1 })).toBe('rgb(68,114,196)');+ expect(getColorStyle(null)).toBeNull();++ const style = handleStyleToString({+ ff: 'Mono',+ fs: 20,+ it: 1,+ bl: 1,+ ul: { s: 1, cl: { rgb: '#00ff00' }, t: 'solid' as never },+ st: { s: 1, cl: { rgb: '#ff0000' }, t: 'solid' as never },+ ol: { s: 1, cl: { rgb: '#0000ff' }, t: 'solid' as never },+ bg: { rgb: '#ffffff' },+ bd: { b: { s: BorderStyleTypes.THIN, cl: { rgb: '#000000' } } },+ cl: { rgb: '#111111' },+ va: BaselineOffset.SUPERSCRIPT,+ td: TextDirection.RIGHT_TO_LEFT,+ tr: { a: 45, v: 1 },+ ht: HorizontalAlign.CENTER,+ vt: VerticalAlign.MIDDLE,+ tb: WrapStrategy.WRAP,+ pd: { t: 1, r: 2, b: 3, l: 4 },+ } as never);++ expect(style).toContain('font-family: Mono;');+ expect(style).toContain('font-size: 10pt;');+ expect(style).toContain('font-style: italic;');+ expect(style).toContain('font-weight: bold;');+ expect(style).toContain('text-decoration');+ expect(style).toContain('background: #ffffff;');+ expect(style).toContain('border-bottom: 0.5pt solid #000000;');+ expect(style).toContain('color: #111111;');+ expect(style).toContain('vertical-align: super;');+ expect(style).toContain('direction: rtl;');+ expect(style).toContain('--data-rotate: (45deg ,1);');+ expect(style).toContain('text-align: center;');+ expect(style).toContain('white-space: normal;');+ expect(style).toContain('padding-left: 4pt;');++ const cellStyle = handleStyleToString({+ bd: { b: { s: BorderStyleTypes.THIN, cl: { rgb: '#000000' } } },+ tr: { a: 30 },+ tb: WrapStrategy.CLIP,+ } as never, true);+ expect(cellStyle).toBe('');+ });++ it('should map border types and document segments', () => {+ expect(getBorderStyleType('none')).toBe(BorderStyleTypes.NONE);+ expect(getBorderStyleType('0.5pt dashed')).toBe(BorderStyleTypes.DASHED);+ expect(getBorderStyleType('1pt solid')).toBe(BorderStyleTypes.MEDIUM);+ expect(getBorderStyleType('unknown solid')).toBe(BorderStyleTypes.THIN);++ const model: IDocumentData = {+ id: 'doc-1',+ body: { dataStream: 'body' },+ headers: { h1: { headerId: 'h1', body: { dataStream: 'header' } } },+ footers: { f1: { footerId: 'f1', body: { dataStream: 'footer' } } },+ documentStyle: {+ pageSize: { width: 100, height: 100 },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ },+ } as IDocumentData;++ expect(getDocsUpdateBody(model)?.dataStream).toBe('body');+ expect(getDocsUpdateBody(model, 'h1')?.dataStream).toBe('header');+ expect(getDocsUpdateBody(model, 'f1')?.dataStream).toBe('footer');+ });++ it('should validate ranges and convert cell values or matrices', () => {+ const worksheet = {+ getRowCount: () => 10,+ getColumnCount: () => 10,+ };++ expect(isValidRange({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }, worksheet as never)).toBe(true);+ expect(isValidRange({ startRow: -1, endRow: 1, startColumn: 0, endColumn: 1 })).toBe(false);+ expect(isValidRange({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.COLUMN })).toBe(false);+ expect(isValidRange({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.ROW })).toBe(false);+ expect(isValidRange({ startRow: 0, endRow: 10, startColumn: 0, endColumn: 1 }, worksheet as never)).toBe(false);+ expect(isValidRange({+ startRow: Number.NaN,+ endRow: Number.NaN,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.COLUMN,+ })).toBe(true);++ expect(covertCellValue('=SUM(1,2)')).toEqual({ f: '=SUM(1,2)', v: null, p: null });+ expect(covertCellValue(1)).toEqual({ v: 1, p: null, f: null });+ const cell = { v: 'text', p: null, f: null } as ICellData;+ expect(covertCellValue(cell)).toBe(cell);++ const mixedValues = [+ [1, '=A1'],+ ['2%', null],+ ] as unknown as Parameters<typeof covertCellValues>[0];++ expect(covertCellValues(mixedValues, { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } as IRange)).toEqual({+ 0: {+ 0: { v: 1, p: null, f: null },+ 1: { f: '=A1', v: null, p: null },+ },+ 1: {+ 0: {+ v: 0.02,+ p: null,+ f: null,+ s: { n: { pattern: '0%' } },+ },+ 1: null,+ },+ });++ expect(covertCellValues({+ 3: { 4: '=B2' },+ }, { startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 } as IRange)).toEqual({+ 3: {+ 4: { f: '=B2', v: null, p: null },+ },+ });+ });});diff --git a/packages/core/src/shared/__tests__/intervals.spec.ts b/packages/core/src/shared/__tests__/intervals.spec.tsnew file mode 100644index 0000000000..648d1a9492--- /dev/null+++ b/packages/core/src/shared/__tests__/intervals.spec.ts@@ -0,0 +1,36 @@+/**+ * 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 { generateIntervalsByPoints, mergeIntervals } from '../intervals';++describe('interval helpers', () => {+ it('should generate merged intervals from points and ranges', () => {+ expect(generateIntervalsByPoints([])).toEqual([]);+ expect(generateIntervalsByPoints([0, [1, 3], 4, 5, [8, 10], 12, 11])).toEqual([+ [0, 5],+ [8, 12],+ ]);+ });++ it('should merge overlapping and contiguous intervals', () => {+ expect(mergeIntervals([])).toEqual([]);+ expect(mergeIntervals([[5, 6], [1, 2], [2, 4], [9, 10], [8, 8]])).toEqual([+ [1, 6],+ [8, 10],+ ]);+ });+});diff --git a/packages/core/src/shared/__tests__/lifecycle.spec.ts b/packages/core/src/shared/__tests__/lifecycle.spec.tsnew file mode 100644index 0000000000..6b0c4102d9--- /dev/null+++ b/packages/core/src/shared/__tests__/lifecycle.spec.ts@@ -0,0 +1,95 @@+/**+ * 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 { Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { Disposable, DisposableCollection, RCDisposable, RxDisposable, toDisposable } from '../lifecycle';++class TestDisposable extends Disposable {+ assertUsable() {+ this.ensureNotDisposed();+ }+}++class TestRxDisposable extends RxDisposable {+ getDispose$() {+ return this.dispose$;+ }+}++describe('lifecycle helpers', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should convert callbacks, subscriptions and empty values to disposables', () => {+ const callback = vi.fn();+ const callbackDisposable = toDisposable(callback);+ callbackDisposable.dispose();+ callbackDisposable.dispose();+ expect(callback).toHaveBeenCalledTimes(1);++ const subject = new Subject<void>();+ const unsubscribeSpy = vi.spyOn(subject, 'unsubscribe');+ toDisposable(subject).dispose();+ expect(unsubscribeSpy).toHaveBeenCalledTimes(1);++ expect(() => toDisposable(undefined as never).dispose()).not.toThrow();+ });++ it('should manage a disposable collection and optional self-retention', () => {+ const collection = new DisposableCollection();+ const callback = vi.fn();+ const handle = collection.add(callback);+ handle.dispose(true);+ expect(callback).not.toHaveBeenCalled();++ collection.add(callback);+ collection.dispose();+ expect(callback).toHaveBeenCalledTimes(1);+ });++ it('should track disposed state in Disposable and RxDisposable', () => {+ const disposable = new TestDisposable();+ const child = { dispose: vi.fn() };+ disposable.disposeWithMe(child);+ disposable.assertUsable();+ disposable.dispose();++ expect(child.dispose).toHaveBeenCalledTimes(1);+ expect(() => disposable.assertUsable()).toThrowError(/disposed/);++ const rxDisposable = new TestRxDisposable();+ const completed = vi.fn();+ rxDisposable.getDispose$().subscribe({ complete: completed });+ rxDisposable.dispose();+ expect(completed).toHaveBeenCalledTimes(1);+ });++ it('should dispose root resource when RCDisposable reference reaches zero', () => {+ const root = { dispose: vi.fn() };+ const rcDisposable = new RCDisposable(root);++ rcDisposable.inc();+ rcDisposable.inc();+ rcDisposable.dec();+ expect(root.dispose).not.toHaveBeenCalled();++ rcDisposable.dec();+ expect(root.dispose).toHaveBeenCalledTimes(1);+ expect(() => rcDisposable.inc()).toThrowError(/disposed/);+ });+});diff --git a/packages/core/src/shared/__tests__/numfmt.spec.ts b/packages/core/src/shared/__tests__/numfmt.spec.tsnew file mode 100644index 0000000000..88b0d09db2--- /dev/null+++ b/packages/core/src/shared/__tests__/numfmt.spec.ts@@ -0,0 +1,58 @@+/**+ * 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 {+ DEFAULT_NUMBER_FORMAT,+ DEFAULT_TEXT_FORMAT,+ DEFAULT_TEXT_FORMAT_EXCEL,+ getNumfmtParseValueFilter,+ isDefaultFormat,+ isPatternEqualWithoutDecimal,+ isTextFormat,+} from '../numfmt';++describe('numfmt helpers', () => {+ it('should recognize text and default number formats', () => {+ expect(isTextFormat(DEFAULT_TEXT_FORMAT)).toBe(true);+ expect(isTextFormat(DEFAULT_TEXT_FORMAT_EXCEL)).toBe(true);+ expect(isTextFormat('0.00')).toBe(false);++ expect(isDefaultFormat(null)).toBe(true);+ expect(isDefaultFormat(undefined)).toBe(true);+ expect(isDefaultFormat(DEFAULT_NUMBER_FORMAT)).toBe(true);+ expect(isDefaultFormat('0.00')).toBe(false);+ });++ it('should compare patterns while ignoring decimal precision differences', () => {+ expect(isPatternEqualWithoutDecimal('0.00', '0.0')).toBe(true);+ expect(isPatternEqualWithoutDecimal('$#,##0.00', '$#,##0')).toBe(true);+ expect(isPatternEqualWithoutDecimal('0.00', '0%')).toBe(false);+ expect(isPatternEqualWithoutDecimal('', '0.0')).toBe(false);+ });++ it('should filter invalid parse results and keep valid numfmt parses', () => {+ expect(getNumfmtParseValueFilter('1 23')).toBeNull();+ expect(getNumfmtParseValueFilter('5A')).toBeNull();+ expect(getNumfmtParseValueFilter('1000,')).toBeNull();+ expect(getNumfmtParseValueFilter('1,00,0')).toBeNull();++ expect(getNumfmtParseValueFilter('2/3')?.z).toBe('m/d');+ expect(getNumfmtParseValueFilter('5 A')?.z).toBe('h:mm AM/PM');+ expect(getNumfmtParseValueFilter('$1000')?.z).toBe('$#,##0');+ expect(getNumfmtParseValueFilter('25%')?.z).toBe('0%');+ });+});diff --git a/packages/core/src/shared/__tests__/object-matrix.spec.ts b/packages/core/src/shared/__tests__/object-matrix.spec.tsindex 2d158d036b..ee1d9247d3 100644--- a/packages/core/src/shared/__tests__/object-matrix.spec.ts+++ b/packages/core/src/shared/__tests__/object-matrix.spec.ts@@ -15,7 +15,16 @@*/import { describe, expect, it } from 'vitest';-import { moveMatrixArray, ObjectMatrix, spliceArray } from '../object-matrix';+import {+ concatMatrixArray,+ getArrayLength,+ insertMatrixArray,+ mapObjectMatrix,+ moveMatrixArray,+ ObjectMatrix,+ sliceMatrixArray,+ spliceArray,+} from '../object-matrix';describe('test ObjectMatrix', () => {const getPrimitiveObj = () => ({@@ -50,7 +59,7 @@ describe('test ObjectMatrix', () => {const rowList: number[] = [];const colList: number[] = [];- matrix.forValue((row, col, value) => {+ matrix.forValue((row, col, _value) => {rowList.push(row);colList.push(col);});@@ -207,4 +216,62 @@ describe('test ObjectMatrix', () => {startRow: 0,}]);});++ it('should map and measure sparse object matrices', () => {+ expect(getArrayLength({ 2: 'a', 5: 'b' })).toBe(6);+ expect(mapObjectMatrix({ 1: { 2: 3 }, 4: { 5: 6 } }, (row, col, value) => row + col + value)).toEqual({+ 1: { 2: 6 },+ 4: { 5: 15 },+ });+ });++ it('should insert, concat and slice matrix arrays', () => {+ const array = { 0: 'a', 2: 'c' };+ insertMatrixArray(1, 'b', array);+ expect(array).toEqual({ 0: 'a', 1: 'b', 3: 'c' });++ expect(concatMatrixArray({ 0: 'a', 3: 'b' }, { 1: 'c' })).toEqual({+ 0: 'a',+ 1: 'b',+ 2: 'c',+ });+ expect(sliceMatrixArray(1, 3, { 0: 'a', 1: 'b', 3: 'd' })).toEqual({+ 0: 'b',+ 1: 'd',+ });+ });++ it('should expose fragment, slice and array conversions', () => {+ const matrix = new ObjectMatrix({+ 1: { 2: { value: 1 }, 3: { value: 2 } },+ 2: { 2: { value: 3 } },+ });++ expect(matrix.getFragment(1, 2, 2, 3).getMatrix()).toEqual({+ 0: { 0: { value: 1 }, 1: { value: 2 } },+ 1: { 0: { value: 3 }, 1: undefined },+ });++ const slice = matrix.getSlice(1, 2, 2, 3);+ expect(slice.getMatrix()).toEqual({+ 1: { 2: { value: 1 }, 3: { value: 2 } },+ 2: { 2: { value: 3 } },+ });+ expect(slice.getValue(1, 2)).not.toBe(matrix.getValue(1, 2));++ const expectedArray = new Array(3);+ expectedArray[1] = new Array(4);+ expectedArray[1][2] = { value: 1 };+ expectedArray[1][3] = { value: 2 };+ expectedArray[2] = new Array(3);+ expectedArray[2][2] = { value: 3 };++ expect(matrix.toArray()).toEqual(expectedArray);+ expect(matrix.toFullArray()).toEqual([+ [undefined, undefined, undefined, undefined],+ [undefined, undefined, { value: 1 }, { value: 2 }],+ [undefined, undefined, { value: 3 }, undefined],+ ]);+ expect(matrix.toNativeArray()).toEqual([{ value: 1 }, { value: 2 }, { value: 3 }]);+ });});diff --git a/packages/core/src/shared/__tests__/sequence.spec.ts b/packages/core/src/shared/__tests__/sequence.spec.tsnew file mode 100644index 0000000000..a688f52d6c--- /dev/null+++ b/packages/core/src/shared/__tests__/sequence.spec.ts@@ -0,0 +1,43 @@+/**+ * 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 { ABCToNumber, numberToABC, numberToListABC, repeatStringNumTimes } from '../sequence';++describe('sequence helpers', () => {+ it('should convert between letters and zero-based indices', () => {+ expect(ABCToNumber('A')).toBe(0);+ expect(ABCToNumber('Z')).toBe(25);+ expect(ABCToNumber('AA')).toBe(26);+ expect(ABCToNumber('az')).toBe(51);+ expect(ABCToNumber('')).toBeNaN();+ expect(ABCToNumber(null as never)).toBeNaN();++ expect(numberToABC(0)).toBe('A');+ expect(numberToABC(25)).toBe('Z');+ expect(numberToABC(26)).toBe('AA');+ expect(numberToABC(51)).toBe('AZ');+ });++ it('should repeat strings and build list-style letters', () => {+ expect(repeatStringNumTimes('ab', 3)).toBe('ababab');+ expect(repeatStringNumTimes('ab', 0)).toBe('');+ expect(numberToListABC(0)).toBe('a');+ expect(numberToListABC(25, true)).toBe('Z');+ expect(numberToListABC(26)).toBe('aa');+ expect(numberToListABC(27, true)).toBe('BB');+ });+});diff --git a/packages/core/src/shared/__tests__/tools.spec.ts b/packages/core/src/shared/__tests__/tools.spec.tsnew file mode 100644index 0000000000..f80bc850f4--- /dev/null+++ b/packages/core/src/shared/__tests__/tools.spec.ts@@ -0,0 +1,128 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { createREGEXFromWildChar, generateRandomId, Tools } from '../tools';++class CustomProto {+ value = 1;+}++describe('Tools extra coverage', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should handle basic string and index helpers', () => {+ expect(Tools.deleteNull({ a: 1, b: null, c: undefined })).toEqual({ a: 1 });+ expect(Tools.stringAt(0)).toBe('A');+ expect(Tools.stringAt(26)).toBe('AA');+ expect(Tools.indexAt('A')).toBe(0);+ expect(Tools.indexAt('AA')).toBe(26);+ expect(Tools.deleteBlank(' a b\n c ')).toBe('abc');+ expect(Tools.deleteBlank()).toBeUndefined();+ expect(Tools.getClassName(new CustomProto())).toBe('CustomProto');+ });++ it('should merge, compare and clone complex values', () => {+ const merged = Tools.deepMerge(+ { a: { b: 1 }, list: [1], keep: true },+ { a: { c: 2 }, list: [2, 3], extra: 'x' }+ );+ expect(merged).toEqual({ a: { b: 1, c: 2 }, list: [2, 3], keep: true, extra: 'x' });+ expect(Tools.numberFixed(1.236, 2)).toBe(1.24);+ expect(Tools.diffValue([1, { a: 2 }], [1, { a: 2 }])).toBe(true);+ expect(Tools.diffValue(new Date('2024-01-01'), new Date('2024-01-01'))).toBe(true);+ expect(Tools.diffValue(/a/i, /a/i)).toBe(true);+ expect(Tools.diffValue({ a: 1 }, { a: 2 })).toBe(false);++ const original = new CustomProto();+ const complex = {+ date: new Date('2024-01-01T00:00:00.000Z'),+ regexp: /test/gi,+ nested: [1, { x: 2 }],+ proto: original,+ };+ const cloned = Tools.deepClone(complex);++ expect(cloned).not.toBe(complex);+ expect(cloned.date).not.toBe(complex.date);+ expect(cloned.date.getTime()).toBe(complex.date.getTime());+ expect(cloned.regexp).not.toBe(complex.regexp);+ expect(cloned.regexp.toString()).toBe(complex.regexp.toString());+ expect(cloned.nested).not.toBe(complex.nested);+ expect(cloned.nested).toEqual(complex.nested);+ expect(cloned.proto).not.toBe(original);+ expect(Object.getPrototypeOf(cloned.proto)).toBe(CustomProto.prototype);+ });++ it('should expose type guards and primitive helpers', () => {+ expect(Tools.isDefine(0)).toBe(true);+ expect(Tools.isDefine(null)).toBe(false);+ expect(Tools.isBlank(' ')).toBe(true);+ expect(Tools.isBlank('x')).toBe(false);+ expect(Tools.isBlank(null)).toBe(true);+ expect(Tools.isPlainObject({ a: 1 })).toBe(true);+ expect(Tools.isPlainObject(new CustomProto())).toBe(false);+ expect(Tools.isDate(new Date())).toBe(true);+ expect(Tools.isRegExp(/a/)).toBe(true);+ expect(Tools.isArray([1])).toBe(true);+ expect(Tools.isString('x')).toBe(true);+ expect(Tools.isNumber(1)).toBe(true);+ expect(Tools.isStringNumber('1.2')).toBe(true);+ expect(Tools.isStringNumber('abc')).toBe(false);+ expect(Tools.isObject({})).toBe(true);+ expect(Tools.isEmptyObject({})).toBe(true);+ expect(Tools.isEmptyObject({ a: 1 })).toBe(false);+ });++ it('should handle collection and numeric helpers', () => {+ const input = { a: 1, b: null, c: { d: undefined, e: 2 } };++ expect(Tools.removeNull(input)).toEqual({ a: 1, c: { e: 2 } });+ expect(Tools.fillTwoDimensionalArray(2, 3, 'x')).toEqual([+ ['x', 'x', 'x'],+ ['x', 'x', 'x'],+ ]);+ expect(Tools.numToWord(27)).toBe('AA');+ expect(Tools.ABCatNum('AZ')).toBe(51);+ expect(Tools.ABCatNum('')).toBeNaN();+ expect(Tools.chatAtABC(51)).toBe('AZ');+ expect(Tools.commonExtend({ a: 1, b: 2 }, { b: null, c: 3 })).toEqual({ a: 1, b: 2, c: 3 });+ expect(Tools.hasIntersectionBetweenTwoRanges(1, 3, 3, 5)).toBe(true);+ expect(Tools.hasIntersectionBetweenTwoRanges(1, 2, 3, 4)).toBe(false);+ expect(Tools.isStartValidPosition('_name')).toBe(true);+ expect(Tools.isStartValidPosition('1name')).toBe(false);+ expect(Tools.isValidParameter('valid_name')).toBe(true);+ expect(Tools.isValidParameter('bad name')).toBe(false);+ expect(Tools.clamp(20, 1, 10)).toBe(10);+ expect(Tools.clamp(-1, 1, 10)).toBe(1);+ });++ it('should read timing, ids and wildcard regex helpers', () => {+ vi.spyOn(globalThis.performance, 'now').mockReturnValue(123.456);++ expect(Tools.now()).toBe(123.456);++ const customId = generateRandomId(6, 'ab');+ expect(customId).toMatch(/^[ab]{6}$/);+ expect(generateRandomId(5)).toHaveLength(5);++ const regex = createREGEXFromWildChar('file-??-*.ts');+ expect(regex.test('file-ab-index.ts')).toBe(true);+ expect(regex.test('file-a-index.ts')).toBe(false);+ });+});diff --git a/packages/core/src/shared/color/color.ts b/packages/core/src/shared/color/color.tsdeleted file mode 100644index 8319139b3e..0000000000--- a/packages/core/src/shared/color/color.ts+++ /dev/null@@ -1,497 +0,0 @@-/**- * 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 { Nullable } from '../types';-import { THEME_COLORS } from '../../types/const/theme-color-map';-import { ColorType, ThemeColors, ThemeColorType } from '../../types/enum';--/**- * @deprecated- */-export class ColorBuilder {- private _themeValue: ThemeColorType = ThemeColorType.LIGHT1;-- private _themeColors: ThemeColors;-- private _themeTint: number;-- private _rgbValue: string = '';-- private _colorType: ColorType;-- constructor() {- this._colorType = ColorType.UNSUPPORTED;- this._themeColors = ThemeColors.OFFICE;- this._themeTint = 0;- }-- asRgbColor(): RgbColor {- return new RgbColor(this._rgbValue, this);- }-- asThemeColor(): ThemeColor {- return new ThemeColor(this._themeValue, this._themeTint, this._themeColors, this);- }-- build(): Nullable<Color> {- switch (this._colorType) {- case ColorType.THEME: {- return this.asThemeColor();- }- case ColorType.RGB: {- return this.asRgbColor();- }- case ColorType.UNSUPPORTED: {- throw new Error('unsupported color type');- }- }- }-- setRgbColor(cssString: string): ColorBuilder {- this._colorType = ColorType.RGB;- this._rgbValue = cssString;- return this;- }-- setThemeColors(value: ThemeColors) {- this._colorType = ColorType.THEME;- this._themeColors = value;- }-- setThemeTint(value: number) {- this._colorType = ColorType.THEME;- this._themeTint = value;- }-- setThemeColor(theme: ThemeColorType): ColorBuilder {- this._colorType = ColorType.THEME;- this._themeValue = theme;- return this;- }-- getColorType(): ColorType {- return this._colorType;- }-}--/**- * @deprecated- */-export class Color {- protected _builder: ColorBuilder;-- constructor(builder: ColorBuilder) {- this._builder = builder;- }-- static rgbColorToHexValue(color: RgbColor): string {- return `#${((1 << 24) + (color.getRed() << 16) + (color.getGreen() << 8) + color.getBlue())- .toString(16)- .slice(1)}`;- }-- static hexValueToRgbColor(hexValue: string): RgbColor {- if (hexValue) {- if (hexValue.indexOf('#') > -1) {- hexValue = hexValue.substring(1);- }- } else {- hexValue = '#000000';- }- const r = +`0x${hexValue[0]}${hexValue[1]}`;- const g = +`0x${hexValue[2]}${hexValue[3]}`;- const b = +`0x${hexValue[4]}${hexValue[5]}`;- return new ColorBuilder().setRgbColor(`rgb(${r},${g},${b})`).asRgbColor();- }-- static hexToRgbString(hex: string): Nullable<string> {- // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")- const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;- hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);- let string = null;- if (result) {- const r = Number.parseInt(result[1], 16);- const g = Number.parseInt(result[2], 16);- const b = Number.parseInt(result[3], 16);- string = `rgba(${r},${g},${b})`;- }- return string;- }-- asRgbColor(): RgbColor {- return this._builder.asRgbColor();- }-- asThemeColor(): ThemeColor {- return this._builder.asThemeColor();- }-- getColorType(): ColorType {- return this._builder.getColorType();- }-- clone(): Color {- return new Color(this._builder);- }-- equals(color: Color): boolean {- return false;- }-}--export class HLSColor {- private _saturation: number = 0;-- private _hue: number = 0;-- private _lightness: number = 0;-- private _alpha: number = 0;-- constructor(rgbColor: RgbColor) {- const red = rgbColor.getRed() / 255;- const green = rgbColor.getGreen() / 255;- const blue = rgbColor.getBlue() / 255;- const alpha = rgbColor.getAlpha() / 255;-- const min = Math.min(red, Math.min(green, blue));- const max = Math.max(red, Math.max(green, blue));- const delta = max - min;-- if (max === min) {- this._hue = 0;- this._saturation = 0;- this._lightness = max;- return;- }-- this._lightness = (min + max) / 2;-- if (this._lightness < 0.5) {- this._saturation = delta / (max + min);- } else {- this._saturation = delta / (2.0 - max - min);- }-- if (red === max) {- this._hue = (green - blue) / delta;- }-- if (green === max) {- this._hue = 2.0 + (blue - red) / delta;- }-- if (blue === max) {- this._hue = 4.0 + (red - green) / delta;- }-- this._hue *= 60;-- if (this._hue < 0) {- this._hue += 360;- }-- this._alpha = alpha;- }-- asRgbColor(): RgbColor {- const builder = new ColorBuilder();-- if (this._saturation === 0) {- builder.setRgbColor(- `rgba(${this._lightness * 255},${this._lightness * 255},${this._lightness * 255},${this._alpha * 255})`- );- return builder.asRgbColor();- }-- let t1;- if (this._lightness < 0.5) {- t1 = this._lightness * (1.0 + this._saturation);- } else {- t1 = this._lightness + this._saturation - this._lightness * this._saturation;- }-- const t2 = 2.0 * this._lightness - t1;- const hue = this._hue / 360;-- const tR = hue + 1.0 / 3.0;- const red = this.setColor(t1, t2, tR);- const green = this.setColor(t1, t2, hue);- const tB = hue - 1.0 / 3.0;- const blue = this.setColor(t1, t2, tB);-- builder.setRgbColor(- `rgba(${Math.round(red * 255)},${Math.round(green * 255)},${Math.round(blue * 255)},${this._alpha * 255})`- );- return builder.asRgbColor();- }-- getLightness() {- return this._lightness;- }-- getHue() {- return this._hue;- }-- getSaturation() {- return this._saturation;- }-- getAlpha() {- return this._alpha;- }-- setColor(t1: number, t2: number, t3: number): number {- if (t3 < 0) {- t3 += 1.0;- }-- if (t3 > 1) {- t3 -= 1.0;- }-- let color: number;-- if (6.0 * t3 < 1) {- color = t2 + (t1 - t2) * 6.0 * t3;- } else if (2.0 * t3 < 1) {- color = t1;- } else if (3.0 * t3 < 2) {- color = t2 + (t1 - t2) * (2.0 / 3.0 - t3) * 6.0;- } else {- color = t2;- }-- return color;- }-- setLightness(lightness: number): void {- this._lightness = lightness;- }-}--export class RgbColor extends Color {- static RGB_COLOR_AMT: number = 0;-- static RGBA_EXTRACT: RegExp = new RegExp(- '\\s*rgba\\s*\\((\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d.\\d|\\d\\s*)\\)\\s*'- );-- static RGB_EXTRACT: RegExp = new RegExp('\\s*rgb\\s*\\((\\s*\\d+\\s*),(\\s*\\d+\\s*),(\\s*\\d+\\s*)\\)\\s*');-- private _cssString: string;-- private _red: number;-- private _green: number;-- private _blue: number;-- private _alpha: number;-- constructor(cssString: string, builder: ColorBuilder) {- super(builder);-- let match = cssString.match(RgbColor.RGBA_EXTRACT);-- if (match) {- const red = +match[1];- const green = +match[2];- const blue = +match[3];- const alpha = +match[4];-- this._cssString = cssString;- this._red = red;- this._green = green;- this._blue = blue;- this._alpha = alpha;- return;- }-- match = cssString.match(RgbColor.RGB_EXTRACT);-- if (match) {- const red = +match[1];- const green = +match[2];- const blue = +match[3];-- this._cssString = cssString;- this._red = red;- this._green = green;- this._blue = blue;- this._alpha = 1;- return;- }-- throw new Error('Invalid rgba or rgb color');- }-- asHexString(): string {- return Color.rgbColorToHexValue(this);- }-- getRed(): number {- let r = this._red + RgbColor.RGB_COLOR_AMT;-- if (r > 255) {- r = 255;- } else if (r < 0) {- r = 0;- }-- return r;- }-- getGreen(): number {- let g = this._green + RgbColor.RGB_COLOR_AMT;-- if (g > 255) {- g = 255;- } else if (g < 0) {- g = 0;- }-- return g;- }-- getBlue(): number {- let b = this._blue + RgbColor.RGB_COLOR_AMT;-- if (b > 255) {- b = 255;- } else if (b < 0) {- b = 0;- }-- return b;- }-- getAlpha(): number {- return this._alpha;- }-- override getColorType(): ColorType {- return ColorType.RGB;- }-- override clone(): RgbColor {- return new RgbColor(this._cssString, this._builder);- }-- override asThemeColor(): ThemeColor {- throw new Error('rgb color not support to themeColor');- }-- override equals(color: Color): boolean {- if (color instanceof RgbColor) {- return (- color._red === this._red &&- color._blue === this._blue &&- color._green === this._green &&- color._alpha === this._alpha- );- }- return false;- }-- getCssString() {- return this._cssString;- }-}--export class ThemeColor extends Color {- private static _cacheThemeColor = new Map<ThemeColors, Map<ThemeColorType, RgbColor>>();-- private _themeColorType: ThemeColorType;-- private _themeTint: number;-- private _themeColors: ThemeColors;-- constructor(theme: ThemeColorType, themeTint: number, themeColors: ThemeColors, builder: ColorBuilder) {- super(builder);- this._themeColorType = theme;- this._themeTint = themeTint;- this._themeColors = themeColors;- }-- lumValue(tint: number, lum: number) {- if (tint == null) {- return lum;- }-- let value: number;-- if (tint < 0) {- value = lum * (1.0 + tint);- } else {- value = lum * (1.0 - tint) + (255 - 255 * (1.0 - tint));- }-- return value;- }-- override asRgbColor(): RgbColor {- const themeColors = THEME_COLORS[this._themeColors];- if (themeColors == null) {- throw new Error('not find themeColors type');- }-- const hexValue = themeColors[this._themeColorType];- if (hexValue == null) {- throw new Error('not find themeColors value');- }-- let themeCache;- if (ThemeColor._cacheThemeColor.has(this._themeColors)) {- themeCache = ThemeColor._cacheThemeColor.get(this._themeColors) as Map<ThemeColorType, RgbColor>;- if (themeCache.has(this._themeColorType)) {- return themeCache.get(this._themeColorType) as RgbColor;- }- } else {- themeCache = new Map<ThemeColorType, RgbColor>();- ThemeColor._cacheThemeColor.set(this._themeColors, themeCache);- }-- const hlsColor = new HLSColor(Color.hexValueToRgbColor(hexValue));- hlsColor.setLightness(this.lumValue(this._themeTint, hlsColor.getLightness() * 255) / 255);- const rgbColor = hlsColor.asRgbColor();- themeCache.set(this._themeColorType, rgbColor);-- return rgbColor;- }-- override clone(): ThemeColor {- return new ThemeColor(this._themeColorType, this._themeTint, this._themeColors, this._builder);- }-- override equals(color: Color): boolean {- if (color instanceof ThemeColor) {- return color._themeColorType === this._themeColorType;- }- return false;- }-- override getColorType(): ColorType {- return ColorType.THEME;- }-- getThemeColorType(): ThemeColorType {- return this._themeColorType;- }-}diff --git a/packages/core/src/shared/common.ts b/packages/core/src/shared/common.tsindex 7885085897..c877372b84 100644--- a/packages/core/src/shared/common.ts+++ b/packages/core/src/shared/common.ts@@ -21,15 +21,16 @@ import type { IColorStyle, IStyleData } from '../types/interfaces/i-style-data';import type { IObjectMatrixPrimitiveType } from './object-matrix';import type { Nullable } from './types';import { isCellV, isICellData, RANGE_TYPE } from '../sheets/typedef';+import { THEME_COLORS } from '../types/const/theme-color-map';import {BaselineOffset,BorderStyleTypes,HorizontalAlign,TextDirection,+ ThemeColors,VerticalAlign,WrapStrategy,} from '../types/enum';-import { ColorBuilder } from './color/color';import { ColorKit } from './color/color-kit';import { DEFAULT_NUMBER_FORMAT, getNumfmtParseValueFilter } from './numfmt';import { ObjectMatrix } from './object-matrix';@@ -151,8 +152,11 @@ export function getColorStyle(color: Nullable<IColorStyle>): Nullable<string> {return new ColorKit(color.rgb).toHexString();}- if (color.th) {- return new ColorBuilder().setThemeColor(color.th).asThemeColor().asRgbColor().getCssString();+ if (color.th != null) {+ const themeColor = THEME_COLORS[ThemeColors.OFFICE]?.[color.th];+ if (themeColor) {+ return new ColorKit(themeColor).toRgbString();+ }}}diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.tsindex abeac617da..7daf9cc0cc 100644--- a/packages/core/src/shared/index.ts+++ b/packages/core/src/shared/index.ts@@ -18,7 +18,6 @@ export { afterInitApply } from './after-init-apply';export * from './array-search';export * from './blob';export { checkIfMove, MOVE_BUFFER_VALUE, ROTATE_BUFFER_VALUE } from './check-if-move';-export * from './color/color';export { ColorKit, COLORS, type IRgbColor, RGB_PAREN, RGBA_PAREN } from './color/color-kit';export * from './command-enum';export * from './common';diff --git a/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts b/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.tsindex 277bea2b23..96410fe03b 100644--- a/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts+++ b/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts@@ -89,6 +89,20 @@ function createTestWorksheetData(rowCount: number, colCount: number): IWorksheet};}+function benchmarkClone(fn: () => void, iterations: number, rounds: number) {+ const samples: number[] = [];++ for (let round = 0; round < rounds; round++) {+ const start = performance.now();+ for (let iteration = 0; iteration < iterations; iteration++) {+ fn();+ }+ samples.push(performance.now() - start);+ }++ return samples.sort((left, right) => left - right)[Math.floor(samples.length / 2)]!;+}+describe('cloneWorksheetData', () => {it('should correctly clone worksheet data', () => {const original = createTestWorksheetData(10, 10);@@ -129,40 +143,23 @@ describe('cloneWorksheetData', () => {});it('should be faster than Tools.deepClone for large worksheets', () => {- const testCases = [- { rows: 100, cols: 50, label: '100x50 (5,000 cells)' },- { rows: 500, cols: 100, label: '500x100 (50,000 cells)' },- ];+ const original = createTestWorksheetData(500, 100);- for (const { rows, cols, label } of testCases) {- const original = createTestWorksheetData(rows, cols);+ for (let i = 0; i < 5; i++) {+ cloneWorksheetData(original);+ Tools.deepClone(original);+ }- // Warm up+ const iterations = 3;+ const rounds = 7;+ const optimizedMedian = benchmarkClone(() => {cloneWorksheetData(original);+ }, iterations, rounds);+ const genericMedian = benchmarkClone(() => {Tools.deepClone(original);+ }, iterations, rounds);- // Benchmark cloneWorksheetData- const iterations = 5;- const startOptimized = performance.now();- for (let i = 0; i < iterations; i++) {- cloneWorksheetData(original);- }- const endOptimized = performance.now();- const optimizedTime = endOptimized - startOptimized;-- // Benchmark Tools.deepClone- const startGeneric = performance.now();- for (let i = 0; i < iterations; i++) {- Tools.deepClone(original);- }- const endGeneric = performance.now();- const genericTime = endGeneric - startGeneric;-- const speedup = genericTime / optimizedTime;-- // The optimized version should be at least 2x faster- expect(speedup).toBeGreaterThan(1.5);- }+ expect(optimizedMedian).toBeLessThanOrEqual(genericMedian * 1.1);});it('should handle empty cellData', () => {diff --git a/packages/core/src/sheets/__tests__/workbook.spec.ts b/packages/core/src/sheets/__tests__/workbook.spec.tsindex 85bbda9347..7f8ce884b4 100644--- a/packages/core/src/sheets/__tests__/workbook.spec.ts+++ b/packages/core/src/sheets/__tests__/workbook.spec.ts@@ -15,8 +15,11 @@*/import type { Univer } from '../../univer';+import type { IWorkbookData } from '../typedef';import type { Workbook } from '../workbook';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { BooleanNumber } from '../../types/enum';+import { LocaleType } from '../../types/enum/locale-type';import { createCoreTestBed } from './create-core-test-bed';describe('Test workbook', () => {@@ -57,5 +60,90 @@ describe('Test workbook', () => {const newSheetName2 = workbook.generateNewSheetName('Sheet');expect(newSheetName2).toBe('Sheet2');});++ it('should save snapshot clone and update basic workbook metadata', () => {+ const saved = workbook.save();++ expect(saved).toEqual(workbook.getSnapshot());+ expect(saved).not.toBe(workbook.getSnapshot());+ expect(workbook.getName()).toBe('');++ workbook.setName('Renamed');+ workbook.setRev(5);+ workbook.incrementRev();+ workbook.setCustomMetadata({ owner: 'tester' } as never);++ expect(workbook.getSnapshot().name).toBe('Renamed');+ expect(workbook.getRev()).toBe(6);+ expect(workbook.getCustomMetadata()).toEqual({ owner: 'tester' });+ expect(workbook.getConfig()).toBe(workbook.getSnapshot());+ });++ it('should manage sheets and lookups', () => {+ expect(workbook.addWorksheet('sheet1', 1, { id: 'sheet1', name: 'Dup' })).toBe(false);+ expect(workbook.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Sheet-002' })).toBe(true);+ expect(workbook.getSheetOrders()).toEqual(['sheet1', 'sheet2']);+ expect(workbook.getSheetSize()).toBe(2);+ expect(workbook.getIndexBySheetId('sheet2')).toBe(1);+ expect(workbook.getSheetBySheetId('sheet2')?.getName()).toBe('Sheet-002');+ expect(workbook.getSheetBySheetName('Sheet-002')?.getSheetId()).toBe('sheet2');+ expect(workbook.getSheetByIndex(1)?.getSheetId()).toBe('sheet2');+ expect(workbook.getSheetsName()).toEqual(['Sheet-001', 'Sheet-002']);+ expect(workbook.getSheetIndex(workbook.getSheetBySheetId('sheet2')!)).toBe(1);+ expect(workbook.getSheets()).toHaveLength(2);++ expect(workbook.removeSheet('sheet2')).toBe(true);+ expect(workbook.removeSheet('sheet2')).toBe(false);+ });++ it('should ensure unique sheet order and preserve style changes', () => {+ workbook.getSnapshot().sheetOrder.push('sheet1', 'sheet1');+ workbook.ensureSheetOrderUnique();+ expect(workbook.getSheetOrders()).toEqual(['sheet1']);++ workbook.addStyles({ custom: { bg: { rgb: '#ffffff' } } });+ expect(workbook.getStyles().get('custom')).toEqual({ bg: { rgb: '#ffffff' } });+ workbook.removeStyles(['custom']);+ expect(workbook.getStyles().get('custom')).toBeUndefined();+ });++ it('should select active sheet and report hidden or visible sheets', () => {+ const customData: IWorkbookData = {+ id: 'book-hidden',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'Hidden Test',+ styles: {},+ sheetOrder: ['s1', 's2'],+ sheets: {+ s1: { id: 's1', name: 'Hidden', hidden: BooleanNumber.TRUE },+ s2: { id: 's2', name: 'Visible' },+ },+ };++ const hiddenTestBed = createCoreTestBed(customData);+ const hiddenWorkbook = hiddenTestBed.sheet;++ expect(hiddenWorkbook.ensureActiveSheet().getSheetId()).toBe('s2');+ expect(hiddenWorkbook.getActiveSheet().getSheetId()).toBe('s2');+ expect(hiddenWorkbook.getActiveSheetIndex()).toBe(1);+ expect(hiddenWorkbook.getHiddenWorksheets()).toEqual(['s1']);+ expect(hiddenWorkbook.getUnhiddenWorksheets()).toEqual(['s2']);+ expect(hiddenWorkbook.checkSheetName('visible')).toBe(true);++ hiddenTestBed.univer.dispose();+ });++ it('should load external snapshot data directly', () => {+ const newConfig = {+ ...workbook.getSnapshot(),+ name: 'Loaded Workbook',+ };++ workbook.load(newConfig);++ expect(workbook.getSnapshot()).toBe(newConfig);+ expect(workbook.getSnapshot().name).toBe('Loaded Workbook');+ });});});diff --git a/packages/design/src/components/calendar/__tests__/index.spec.tsx b/packages/design/src/components/calendar/__tests__/index.spec.tsxindex 05718f3df7..63297e7e76 100644--- a/packages/design/src/components/calendar/__tests__/index.spec.tsx+++ b/packages/design/src/components/calendar/__tests__/index.spec.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { cleanup, render } from '@testing-library/react';+import { cleanup, fireEvent, render } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import enUS from '../../../locale/en-US';import { ConfigProvider } from '../../config-provider/ConfigProvider';@@ -64,4 +64,33 @@ describe('Calendar', () => {// 15th is selectedexpect(getByText('15').className).toMatch(/univer-bg-primary-600/);});++ it('should switch year when navigating across month boundaries', () => {+ const date = new Date(2023, 0, 15);+ const { getByLabelText, getByText } = render(+ <ConfigProvider mountContainer={null} locale={{ Calendar: enUS.design.Calendar }}>+ <Calendar value={date} onValueChange={onChange} />+ </ConfigProvider>+ );++ fireEvent.click(getByLabelText('Previous Month'));+ expect(getByText('2022')).toBeInTheDocument();++ fireEvent.click(getByLabelText('Next Month'));+ expect(getByText('2023')).toBeInTheDocument();+ });++ it('should disable out-of-range days and propagate time changes', () => {+ const min = new Date(2023, 7, 10, 0, 0, 0);+ const max = new Date(2023, 7, 20, 23, 59, 59);+ const { getByText, container } = renderCalendar({ min, max, showTime: true });++ const outOfRangeDay = getByText('9').closest('button') as HTMLButtonElement;+ expect(outOfRangeDay).toBeDisabled();+ fireEvent.click(outOfRangeDay);++ const timeInput = container.querySelector('input[type="time"]') as HTMLInputElement;+ fireEvent.change(timeInput, { target: { value: '11:22:33' } });+ expect(onChange).toHaveBeenCalled();+ });});diff --git a/packages/design/src/components/cascader-list/__tests__/index.spec.tsx b/packages/design/src/components/cascader-list/__tests__/index.spec.tsxindex c52c811d9c..ddb7f0cffd 100644--- a/packages/design/src/components/cascader-list/__tests__/index.spec.tsx+++ b/packages/design/src/components/cascader-list/__tests__/index.spec.tsx@@ -14,8 +14,8 @@* limitations under the License.*/-import { cleanup, render } from '@testing-library/react';-import { afterEach, describe, expect, it } from 'vitest';+import { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';import { CascaderList } from '../CascaderList';afterEach(cleanup);@@ -47,4 +47,56 @@ describe('CascaderList', () => {expect(container).toBeTruthy();});++ it('should select parent and child options', () => {+ const onChange = vi.fn();+ const options = [+ {+ label: 'A',+ value: 'a',+ children: [+ { label: 'A-1', value: 'a-1' },+ { label: 'A-2', value: 'a-2' },+ ],+ },+ {+ label: 'B',+ value: 'b',+ },+ ];++ const { getByText, rerender } = render(<CascaderList value={[]} options={options} onChange={onChange} />);+ fireEvent.click(getByText('A'));+ expect(onChange).toHaveBeenCalledWith(['a']);++ rerender(<CascaderList value={['a']} options={options} onChange={onChange} />);+ fireEvent.click(getByText('A-2'));+ expect(onChange).toHaveBeenCalledWith(['a', 'a-2']);+ });++ it('should ignore same value click and rewrite path when parent changes', () => {+ const onChange = vi.fn();+ const options = [+ {+ label: 'A',+ value: 'a',+ children: [{ label: 'A-1', value: 'a-1' }],+ },+ {+ label: 'B',+ value: 'b',+ children: [{ label: 'B-1', value: 'b-1' }],+ },+ ];++ const { getByText } = render(+ <CascaderList value={['a', 'a-1']} options={options} onChange={onChange} />+ );++ fireEvent.click(getByText('A'));+ expect(onChange).not.toHaveBeenCalledWith(['a', 'a-1']);++ fireEvent.click(getByText('B'));+ expect(onChange).toHaveBeenCalledWith(['b']);+ });});diff --git a/packages/design/src/components/color-picker/__tests__/alpha-and-input.spec.tsx b/packages/design/src/components/color-picker/__tests__/alpha-and-input.spec.tsxnew file mode 100644index 0000000000..aa2b1155ad--- /dev/null+++ b/packages/design/src/components/color-picker/__tests__/alpha-and-input.spec.tsx@@ -0,0 +1,163 @@+/**+ * 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 { fireEvent, render } from '@testing-library/react';+import { useState } from 'react';+import { describe, expect, it, vi } from 'vitest';+import { AlphaSlider } from '../AlphaSlider';+import { ColorInput } from '../ColorInput';+import '@testing-library/jest-dom/vitest';++describe('AlphaSlider', () => {+ it('should update alpha during pointer interaction and emit onChanged', () => {+ const onChange = vi.fn();+ const onChanged = vi.fn();++ const { container } = render(+ <AlphaSlider hsv={[0, 100, 100]} alpha={0.3} onChange={onChange} onChanged={onChanged} />+ );++ const slider = container.querySelector('.univer-h-2') as HTMLDivElement;+ const thumb = container.querySelector('.univer-size-2') as HTMLDivElement;+ expect(slider).toBeInTheDocument();+ expect(thumb).toBeInTheDocument();++ Object.defineProperty(thumb, 'clientWidth', { value: 10, configurable: true });+ vi.spyOn(slider, 'getBoundingClientRect').mockReturnValue({+ x: 0,+ y: 0,+ top: 0,+ left: 0,+ width: 100,+ height: 8,+ right: 100,+ bottom: 8,+ toJSON: () => ({}),+ } as DOMRect);++ fireEvent.pointerDown(slider, { clientX: 50 });+ fireEvent.pointerMove(window, { clientX: 80 });+ fireEvent.pointerUp(window);++ expect(onChange).toHaveBeenCalled();+ expect(onChanged).toHaveBeenCalledWith(0.3);+ });+});++describe('ColorInput', () => {+ it('should handle hex input validation and reset invalid value on blur', () => {+ const onChange = vi.fn();++ function Wrapper() {+ const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);+ return (+ <ColorInput+ hsv={hsv}+ alpha={1}+ format="hex"+ onChange={(h, s, v) => {+ setHsv([h, s, v]);+ onChange(h, s, v);+ }}+ />+ );+ }++ const { container } = render(<Wrapper />);+ const hexInput = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ expect(hexInput).toBeInTheDocument();++ fireEvent.change(hexInput, { target: { value: 'GGGGGG' } });+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.change(hexInput, { target: { value: '00ff00' } });+ expect(onChange).toHaveBeenCalled();++ fireEvent.change(hexInput, { target: { value: '0' } });+ fireEvent.blur(hexInput);+ expect(hexInput.value.length).toBe(6);+ });++ it('should handle rgba channels and alpha bounds', () => {+ const onChange = vi.fn();++ function Wrapper() {+ const [hsv, setHsv] = useState<[number, number, number]>([0, 100, 100]);+ const [alpha, setAlpha] = useState(0.5);+ return (+ <ColorInput+ hsv={hsv}+ alpha={alpha}+ format="rgba"+ onChange={(h, s, v, a) => {+ setHsv([h, s, v]);+ setAlpha(a ?? alpha);+ onChange(h, s, v, a);+ }}+ />+ );+ }++ const { container } = render(<Wrapper />);+ const rgbInputs = Array.from(container.querySelectorAll('input[maxlength="3"]')) as HTMLInputElement[];+ const alphaInput = container.querySelector('input[maxlength="4"]') as HTMLInputElement;++ fireEvent.change(rgbInputs[0], { target: { value: '255' } });+ fireEvent.change(rgbInputs[1], { target: { value: '255' } });+ fireEvent.change(rgbInputs[2], { target: { value: '255' } });+ expect(onChange).toHaveBeenCalled();++ const callCount = onChange.mock.calls.length;+ fireEvent.change(alphaInput, { target: { value: '1.5' } });+ expect(onChange.mock.calls.length).toBe(callCount);++ fireEvent.change(alphaInput, { target: { value: '0.75' } });+ expect(onChange).toHaveBeenCalled();+ });++ it('should guard invalid length and character input branches', () => {+ const onChange = vi.fn();+ const { container } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={0.5} format="rgba" onChange={onChange} />+ );++ const hexInput = container.querySelector('input[maxlength="6"]') as HTMLInputElement;+ const rgbInputs = Array.from(container.querySelectorAll('input[maxlength="3"]')) as HTMLInputElement[];+ const alphaInput = container.querySelector('input[maxlength="4"]') as HTMLInputElement;++ fireEvent.change(hexInput, { target: { value: '1234567' } });+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.change(rgbInputs[0], { target: { value: '1a' } });+ fireEvent.change(rgbInputs[1], { target: { value: '300' } });+ fireEvent.change(alphaInput, { target: { value: 'abc' } });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('should reset rgb local values on blur to current hsv values', () => {+ const onChange = vi.fn();+ const { container } = render(+ <ColorInput hsv={[0, 100, 100]} alpha={0.5} format="rgba" onChange={onChange} />+ );++ const rInput = container.querySelector('input[maxlength="3"]') as HTMLInputElement;+ fireEvent.change(rInput, { target: { value: '1' } });+ expect(onChange).toHaveBeenCalled();++ fireEvent.blur(rInput);+ expect(rInput.value).toBe('255');+ });+});diff --git a/packages/design/src/components/color-picker/__tests__/color-conversion.spec.ts b/packages/design/src/components/color-picker/__tests__/color-conversion.spec.tsnew file mode 100644index 0000000000..f190024719--- /dev/null+++ b/packages/design/src/components/color-picker/__tests__/color-conversion.spec.ts@@ -0,0 +1,56 @@+/**+ * 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 { hexToHsv, hsvToHex, hsvToRgb, hsvToRgba, parseRgba, rgbToHex, rgbToHsv } from '../color-conversion';++describe('color-conversion', () => {+ it('should convert hsv to rgb across hue segments', () => {+ expect(hsvToRgb(0, 100, 100)).toEqual([255, 0, 0]);+ expect(hsvToRgb(60, 100, 100)).toEqual([255, 255, 0]);+ expect(hsvToRgb(120, 100, 100)).toEqual([0, 255, 0]);+ expect(hsvToRgb(180, 100, 100)).toEqual([0, 255, 255]);+ expect(hsvToRgb(240, 100, 100)).toEqual([0, 0, 255]);+ expect(hsvToRgb(300, 100, 100)).toEqual([255, 0, 255]);+ });++ it('should convert rgb and hsv values', () => {+ expect(rgbToHex(255, 0, 16)).toBe('#ff0010');+ expect(hsvToHex(0, 100, 100)).toBe('#ff0000');+ expect(hsvToRgba(0, 100, 100, 0.5)).toBe('rgba(255, 0, 0, 0.5)');++ const fromRed = rgbToHsv(255, 0, 0);+ const fromGreen = rgbToHsv(0, 255, 0);+ const fromBlue = rgbToHsv(0, 0, 255);+ const fromGray = rgbToHsv(128, 128, 128);++ expect(Math.round(fromRed[0])).toBe(0);+ expect(Math.round(fromGreen[0])).toBe(120);+ expect(Math.round(fromBlue[0])).toBe(240);+ expect(fromGray[1]).toBe(0);+ });++ it('should parse hex and rgba strings', () => {+ const shortHex = hexToHsv('#f00');+ const longHex = hexToHsv('#00ff00');+ expect(Math.round(shortHex[0])).toBe(0);+ expect(Math.round(longHex[0])).toBe(120);++ expect(parseRgba('rgba(255, 128, 0, 0.25)')).toEqual([255, 128, 0, 0.25]);+ expect(parseRgba('rgb(10, 20, 30)')).toEqual([10, 20, 30, 1]);+ expect(() => parseRgba('not-a-color')).toThrow('Invalid RGBA string');+ });+});diff --git a/packages/design/src/components/color-picker/__tests__/color-picker-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/color-picker-extra.spec.tsxnew file mode 100644index 0000000000..86bfec1f8a--- /dev/null+++ b/packages/design/src/components/color-picker/__tests__/color-picker-extra.spec.tsx@@ -0,0 +1,98 @@+/**+ * 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 { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ColorPicker } from '../ColorPicker';+import '@testing-library/jest-dom/vitest';++afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+});++describe('ColorPicker extra', () => {+ it('should handle rgba mode and confirm custom color', () => {+ const onChange = vi.fn();+ const { container } = render(+ <ColorPicker format="rgba" value="rgba(10, 20, 30, 0.5)" onChange={onChange} />+ );++ const moreLink = container.querySelector('[data-u-comp="color-picker"] a') as HTMLAnchorElement;+ expect(moreLink).toBeTruthy();+ fireEvent.click(moreLink);++ const buttons = Array.from(document.querySelectorAll('button'));+ const confirmBtn = buttons[buttons.length - 1] as HTMLButtonElement;+ expect(confirmBtn).toBeTruthy();+ fireEvent.click(confirmBtn);+ expect(onChange).toHaveBeenCalled();+ expect(onChange.mock.calls.some(([value]) => String(value).startsWith('rgba('))).toBe(true);+ });++ it('should log error when invalid value is provided', () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ render(<ColorPicker format="rgba" value="invalid-rgba" />);+ expect(errorSpy).toHaveBeenCalled();+ });++ it('should stop click propagation on root container', () => {+ const parentClick = vi.fn();+ const { container } = render(+ <div onClick={parentClick}>+ <ColorPicker />+ </div>+ );++ const root = container.querySelector('[data-u-comp="color-picker"]') as HTMLElement;+ expect(root).toBeTruthy();+ fireEvent.click(root);+ expect(parentClick).not.toHaveBeenCalled();+ });++ it('should emit rgba from presets and confirm/cancel inside dialog', () => {+ const onChange = vi.fn();+ const { container } = render(<ColorPicker format="rgba" value="rgba(0, 0, 0, 1)" onChange={onChange} />);++ const presetButton = container.querySelector('[data-u-comp="color-picker-presets"] button') as HTMLButtonElement;+ fireEvent.click(presetButton);+ expect(onChange.mock.calls.some(([value]) => String(value).startsWith('rgba('))).toBe(true);++ const moreLink = container.querySelector('[data-u-comp="color-picker"] a') as HTMLAnchorElement;+ fireEvent.click(moreLink);++ const alphaInput = document.querySelector('input[maxlength="4"]') as HTMLInputElement;+ fireEvent.change(alphaInput, { target: { value: '0.6' } });++ const [cancelBtn, confirmBtn] = Array.from(document.querySelectorAll('footer button')) as HTMLButtonElement[];+ fireEvent.click(cancelBtn);+ fireEvent.click(moreLink);+ fireEvent.click(confirmBtn);+ expect(onChange).toHaveBeenCalled();+ });++ it('should confirm custom color in hex mode', () => {+ const onChange = vi.fn();+ const { container } = render(<ColorPicker format="hex" value="#00ff00" onChange={onChange} />);+ const moreLink = container.querySelector('[data-u-comp="color-picker"] a') as HTMLAnchorElement;++ fireEvent.click(moreLink);+ const confirmBtn = Array.from(document.querySelectorAll('footer button')).at(-1) as HTMLButtonElement;+ fireEvent.click(confirmBtn);++ expect(onChange.mock.calls.some(([value]) => String(value).startsWith('#'))).toBe(true);+ });+});diff --git a/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsxnew file mode 100644index 0000000000..e241ad19ee--- /dev/null+++ b/packages/design/src/components/color-picker/__tests__/color-spectrum-extra.spec.tsx@@ -0,0 +1,69 @@+/**+ * 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 { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ColorSpectrum } from '../ColorSpectrum';+import '@testing-library/jest-dom/vitest';++afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+});++describe('ColorSpectrum extra', () => {+ beforeEach(() => {+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => {+ const gradient = { addColorStop: vi.fn() };+ return {+ createLinearGradient: vi.fn(() => gradient),+ fillRect: vi.fn(),+ fillStyle: '',+ } as unknown as CanvasRenderingContext2D;+ });+ });++ it('should draw gradients and emit pointer-driven hsv changes', () => {+ const onChange = vi.fn();+ const onChanged = vi.fn();+ const { container } = render(<ColorSpectrum hsv={[120, 20, 80]} onChange={onChange} onChanged={onChanged} />);++ const canvas = container.querySelector('canvas') as HTMLCanvasElement;+ const wrapper = container.querySelector('[data-u-comp="color-picker-spectrum"]') as HTMLDivElement;+ Object.defineProperty(wrapper, 'clientWidth', { value: 100, configurable: true });+ Object.defineProperty(wrapper, 'clientHeight', { value: 100, configurable: true });+ canvas.getBoundingClientRect = vi.fn(() => ({+ left: 0,+ top: 0,+ width: 100,+ height: 100,+ right: 100,+ bottom: 100,+ x: 0,+ y: 0,+ toJSON: () => {},+ }));++ fireEvent.pointerDown(canvas, { clientX: 50, clientY: 25 });+ fireEvent.pointerMove(canvas, { clientX: 80, clientY: 40 });+ fireEvent.mouseUp(wrapper);+ fireEvent.pointerUp(window);+ fireEvent.mouseUp(window);++ expect(onChange).toHaveBeenCalled();+ expect(onChanged).toHaveBeenCalledWith(120, 20, 80);+ });+});diff --git a/packages/design/src/components/color-picker/__tests__/hue-slider-extra.spec.tsx b/packages/design/src/components/color-picker/__tests__/hue-slider-extra.spec.tsxnew file mode 100644index 0000000000..19cee321d7--- /dev/null+++ b/packages/design/src/components/color-picker/__tests__/hue-slider-extra.spec.tsx@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { HueSlider } from '../HueSlider';+import '@testing-library/jest-dom/vitest';++afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+});++describe('HueSlider extra', () => {+ it('should stop propagation, handle drag and emit onChanged', () => {+ const onChange = vi.fn();+ const onChanged = vi.fn();+ const { container } = render(<HueSlider hsv={[120, 60, 70]} onChange={onChange} onChanged={onChanged} />);+ const slider = container.querySelector('[data-u-comp="color-picker-hue-slider"] > div') as HTMLDivElement;+ const thumb = container.querySelector('.univer-size-2') as HTMLDivElement;++ Object.defineProperty(thumb, 'clientWidth', { value: 10, configurable: true });+ Object.defineProperty((slider.parentElement as HTMLDivElement), 'clientWidth', { value: 100, configurable: true });+ slider.getBoundingClientRect = vi.fn(() => ({+ left: 0,+ top: 0,+ width: 100,+ height: 8,+ right: 100,+ bottom: 8,+ x: 0,+ y: 0,+ toJSON: () => {},+ }));++ fireEvent.pointerMove(window, { clientX: 40 });+ fireEvent.pointerDown(slider, { clientX: 40 });+ fireEvent.pointerMove(window, { clientX: 70 });+ fireEvent.pointerUp(window);++ expect(onChange).toHaveBeenCalled();+ expect(onChanged).toHaveBeenCalledWith(120, 60, 70);+ });+});diff --git a/packages/design/src/components/date-picker/__tests__/index.spec.tsx b/packages/design/src/components/date-picker/__tests__/index.spec.tsxnew file mode 100644index 0000000000..59ba117680--- /dev/null+++ b/packages/design/src/components/date-picker/__tests__/index.spec.tsx@@ -0,0 +1,88 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DatePicker } from '../DatePicker';+import '@testing-library/jest-dom/vitest';++const { calendarPropsHistory } = vi.hoisted(() => ({+ calendarPropsHistory: [] as any[],+}));++vi.mock('../../dropdown/Dropdown', () => ({+ Dropdown: (props: any) => (+ <div data-testid="mock-dropdown" data-open={String(props.open)}>+ <button+ type="button"+ data-testid="mock-dropdown-toggle"+ onClick={() => props.onOpenChange?.(!props.open)}+ >+ toggle+ </button>+ <div data-testid="mock-dropdown-overlay">{props.overlay}</div>+ {props.children}+ </div>+ ),+}));++vi.mock('../../calendar/Calendar', () => ({+ Calendar: (props: any) => {+ calendarPropsHistory.push(props);+ return (+ <button+ type="button"+ data-testid="mock-calendar-select"+ onClick={() => props.onValueChange?.(new Date('2026-01-02T00:00:00.000Z'))}+ >+ select-date+ </button>+ );+ },+}));++afterEach(() => {+ cleanup();+ calendarPropsHistory.length = 0;+});++describe('DatePicker', () => {+ it('should render value, open dropdown and emit value change', () => {+ const onValueChange = vi.fn();+ const value = new Date('2026-01-01T00:00:00.000Z');++ render(+ <DatePicker+ value={value}+ className="custom-date-picker"+ onValueChange={onValueChange}+ />+ );++ expect(screen.getByText('2026-01-01')).toBeInTheDocument();+ expect(calendarPropsHistory[0].value).toEqual(value);++ fireEvent.click(screen.getByTestId('mock-dropdown-toggle'));+ expect(screen.getByTestId('mock-dropdown')).toHaveAttribute('data-open', 'true');++ fireEvent.click(screen.getByTestId('mock-calendar-select'));+ expect(onValueChange).toHaveBeenCalledWith(new Date('2026-01-02T00:00:00.000Z'));+ expect(screen.getByTestId('mock-dropdown')).toHaveAttribute('data-open', 'false');++ const dateButton = screen.getByText('2026-01-01').closest('button') as HTMLButtonElement;+ expect(dateButton.className).toContain('custom-date-picker');+ });+});diff --git a/packages/design/src/components/date-range-picker/__tests__/index.spec.tsx b/packages/design/src/components/date-range-picker/__tests__/index.spec.tsxnew file mode 100644index 0000000000..572dc730e6--- /dev/null+++ b/packages/design/src/components/date-range-picker/__tests__/index.spec.tsx@@ -0,0 +1,96 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DateRangePicker } from '../DateRangePicker';+import '@testing-library/jest-dom/vitest';++const { calendarPropsHistory } = vi.hoisted(() => ({+ calendarPropsHistory: [] as any[],+}));++vi.mock('../../dropdown/Dropdown', () => ({+ Dropdown: (props: any) => (+ <div data-testid="mock-dropdown" data-open={String(props.open)}>+ <button+ type="button"+ data-testid="mock-dropdown-toggle"+ onClick={() => props.onOpenChange?.(!props.open)}+ >+ toggle+ </button>+ <div data-testid="mock-dropdown-overlay">{props.overlay}</div>+ {props.children}+ </div>+ ),+}));++vi.mock('../../calendar/Calendar', () => ({+ Calendar: (props: any) => {+ calendarPropsHistory.push(props);+ const testId = props.max ? 'mock-calendar-start' : 'mock-calendar-end';+ const nextDate = props.max+ ? new Date('2026-02-15T00:00:00.000Z')+ : new Date('2026-02-03T00:00:00.000Z');++ return (+ <button+ type="button"+ data-testid={testId}+ onClick={() => props.onValueChange?.(nextDate)}+ >+ {testId}+ </button>+ );+ },+}));++afterEach(() => {+ cleanup();+ calendarPropsHistory.length = 0;+});++describe('DateRangePicker', () => {+ it('should render values, pass min/max and normalize start/end order', () => {+ const onValueChange = vi.fn();+ const value = [+ new Date('2026-02-10T00:00:00.000Z'),+ new Date('2026-02-01T00:00:00.000Z'),+ ] as [Date, Date];++ render(<DateRangePicker value={value} onValueChange={onValueChange} />);++ expect(screen.getByText('2026-02-10')).toBeInTheDocument();+ expect(screen.getByText('2026-02-01')).toBeInTheDocument();++ expect(calendarPropsHistory[0].value).toEqual(value[0]);+ expect(calendarPropsHistory[0].max).toEqual(value[1]);+ expect(calendarPropsHistory[1].value).toEqual(value[1]);+ expect(calendarPropsHistory[1].min).toEqual(value[0]);++ fireEvent.click(screen.getByTestId('mock-dropdown-toggle'));+ expect(screen.getByTestId('mock-dropdown')).toHaveAttribute('data-open', 'true');++ fireEvent.click(screen.getByTestId('mock-calendar-start'));++ expect(onValueChange).toHaveBeenCalledWith([+ new Date('2026-02-01T00:00:00.000Z'),+ new Date('2026-02-15T00:00:00.000Z'),+ ]);+ expect(screen.getByTestId('mock-dropdown')).toHaveAttribute('data-open', 'false');+ });+});diff --git a/packages/design/src/components/dialog/__tests__/index.spec.tsx b/packages/design/src/components/dialog/__tests__/index.spec.tsxindex 89af86d01d..304b079302 100644--- a/packages/design/src/components/dialog/__tests__/index.spec.tsx+++ b/packages/design/src/components/dialog/__tests__/index.spec.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { cleanup, render } from '@testing-library/react';+import { cleanup, fireEvent, render } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import { Dialog } from '../Dialog';import '@testing-library/jest-dom/vitest';@@ -70,4 +70,50 @@ describe('Dialog', () => {expect(onOpenChange).not.toHaveBeenCalledWith(false);}});++ it('should apply width and draggable styles', () => {+ const { rerender } = render(+ <Dialog open title="drag" width={320} draggable>+ content+ </Dialog>+ );++ const content = document.querySelector('[role="dialog"]') as HTMLElement;+ expect(content.style.width).toBe('320px');+ expect(content.style.transform).toContain('translate(');++ const header = document.querySelector('[data-drag-handle="true"]') as HTMLElement;+ expect(header).toBeInTheDocument();+ fireEvent.mouseDown(header, { clientX: 20, clientY: 20 });+ fireEvent.mouseMove(document, { clientX: 40, clientY: 50 });+ fireEvent.mouseUp(document);++ rerender(+ <Dialog open title="drag" width="40rem" draggable>+ content+ </Dialog>+ );+ expect((document.querySelector('[role="dialog"]') as HTMLElement).style.width).toBe('40rem');+ });++ it('should honor keyboard=false and trigger open change from close button', () => {+ const onOpenChange = vi.fn();+ const onClose = vi.fn();+ render(+ <Dialog open keyboard={false} onOpenChange={onOpenChange} onClose={onClose}>+ content+ </Dialog>+ );++ fireEvent.keyDown(document, { key: 'Escape' });++ const closeBtn = (document.querySelector('.univer-sr-only') as HTMLElement | null)?.parentElement as HTMLElement | null;+ expect(closeBtn).toBeInTheDocument();+ if (!closeBtn) {+ throw new Error('Close button should exist');+ }+ closeBtn.click();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onClose).toHaveBeenCalled();+ });});diff --git a/packages/design/src/components/dialog/__tests__/logic.spec.tsx b/packages/design/src/components/dialog/__tests__/logic.spec.tsxnew file mode 100644index 0000000000..3eafb9e4b9--- /dev/null+++ b/packages/design/src/components/dialog/__tests__/logic.spec.tsx@@ -0,0 +1,160 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { Dialog } from '../Dialog';++import '@testing-library/jest-dom/vitest';++vi.mock('../DialogPrimitive', async () => {+ const React = await import('react');++ const Dialog = ({ children, open, onOpenChange, modal }: any) => (+ <div data-testid="dialog-provider" data-open={String(open)} data-modal={String(modal)}>+ <button type="button" data-testid="provider-close" onClick={() => onOpenChange?.(false)}>+ provider-close+ </button>+ {children}+ </div>+ );++ const DialogContent = React.forwardRef<HTMLDivElement, any>((props, ref) => {+ const { children, onEscapeKeyDown, onPointerDownOutside, onClickClose } = props;+ return (+ <div+ ref={ref}+ role="dialog"+ tabIndex={0}+ onKeyDown={(e) => onEscapeKeyDown?.(e)}+ onPointerDown={(e) => onPointerDownOutside?.(e)}+ >+ <button type="button" data-slot="close" onClick={onClickClose}>+ close+ </button>+ {children}+ </div>+ );+ });++ const DialogHeader = ({ children, ...props }: any) => <div {...props}>{children}</div>;+ const DialogFooter = ({ children }: any) => <div>{children}</div>;+ const DialogTitle = ({ children }: any) => <div>{children}</div>;+ const DialogDescription = ({ children }: any) => <div>{children}</div>;++ return {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ };+});++afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+});++describe('Dialog logic branches', () => {+ it('should ignore provider close when mask is false', () => {+ const onOpenChange = vi.fn();+ const onClose = vi.fn();++ render(+ <Dialog open mask={false} onOpenChange={onOpenChange} onClose={onClose}>+ content+ </Dialog>+ );++ fireEvent.click(screen.getByTestId('provider-close'));+ expect(onOpenChange).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('should close on escape and pointer outside when enabled', () => {+ const onOpenChange = vi.fn();+ const onClose = vi.fn();++ render(+ <Dialog open keyboard maskClosable onOpenChange={onOpenChange} onClose={onClose}>+ content+ </Dialog>+ );++ const dialog = screen.getByRole('dialog');+ fireEvent.keyDown(dialog, { key: 'Escape' });+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onClose).toHaveBeenCalled();++ onOpenChange.mockClear();+ onClose.mockClear();++ fireEvent.pointerDown(dialog);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onClose).toHaveBeenCalled();+ });++ it('should not close from pointer outside when maskClosable is false', () => {+ const onOpenChange = vi.fn();+ const onClose = vi.fn();++ render(+ <Dialog open maskClosable={false} onOpenChange={onOpenChange} onClose={onClose}>+ content+ </Dialog>+ );++ fireEvent.pointerDown(screen.getByRole('dialog'));+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ expect(onClose).not.toHaveBeenCalled();+ });++ it('should run draggable bounds and drag lifecycle', () => {+ Object.defineProperty(document.documentElement, 'clientWidth', { value: 300, configurable: true });+ Object.defineProperty(document.documentElement, 'clientHeight', { value: 200, configurable: true });++ render(+ <Dialog open draggable title="drag-title">+ content+ </Dialog>+ );++ const dialog = screen.getByRole('dialog') as HTMLDivElement;+ dialog.getBoundingClientRect = vi.fn(() => ({+ width: 200,+ height: 100,+ top: 0,+ left: 0,+ right: 200,+ bottom: 100,+ x: 0,+ y: 0,+ toJSON: () => {},+ }));++ fireEvent.mouseMove(document, { clientX: 1, clientY: 1 });+ const header = screen.getByText('drag-title').parentElement as HTMLElement;+ fireEvent.mouseDown(header, { clientX: 10, clientY: 10 });+ expect(document.body.style.userSelect).toBe('none');++ fireEvent.mouseMove(document, { clientX: -100, clientY: -100 });+ fireEvent.mouseMove(document, { clientX: 500, clientY: 500 });+ fireEvent.mouseUp(document);+ expect(document.body.style.userSelect).toBe('');+ });+});diff --git a/packages/design/src/components/draggable-list/__tests__/index.spec.tsx b/packages/design/src/components/draggable-list/__tests__/index.spec.tsxnew file mode 100644index 0000000000..8b9320aa07--- /dev/null+++ b/packages/design/src/components/draggable-list/__tests__/index.spec.tsx@@ -0,0 +1,302 @@+/**+ * 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 { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DraggableList } from '../DraggableList';+import '@testing-library/jest-dom/vitest';++vi.mock('react-dom', async () => {+ const actual = await vi.importActual<typeof import('react-dom')>('react-dom');+ return {+ ...actual,+ createPortal: (node: any) => node,+ };+});++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++interface IItem {+ id: string;+ label: string;+}++const BASE_LIST: IItem[] = [+ { id: 'a', label: 'A' },+ { id: 'b', label: 'B' },+ { id: 'c', label: 'C' },+];++function mockRect(element: HTMLElement) {+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({+ x: 10,+ y: 20,+ left: 10,+ top: 20,+ right: 110,+ bottom: 56,+ width: 100,+ height: 36,+ toJSON: () => ({}),+ } as DOMRect);+}++describe('DraggableList', () => {+ it('should reorder list and emit drag callbacks', async () => {+ const onListChange = vi.fn();+ const onDragStart = vi.fn();+ const onDragStop = vi.fn();++ const { container } = render(+ <DraggableList<IItem>+ list={BASE_LIST}+ idKey="id"+ rowHeight={36}+ margin={[4, 6]}+ onListChange={onListChange}+ onDragStart={onDragStart}+ onDragStop={onDragStop}+ itemRender={(item) => <div>{item.label}</div>}+ />+ );++ const listRoot = container.querySelector('.univer-flex-col') as HTMLElement;+ expect(listRoot.style.rowGap).toBe('6px');+ expect(listRoot.style.paddingLeft).toBe('4px');+ expect(listRoot.style.paddingRight).toBe('4px');++ const itemA = container.querySelector('[data-draggable-list-item-id="a"]') as HTMLDivElement;+ const itemB = container.querySelector('[data-draggable-list-item-id="b"]') as HTMLDivElement;+ expect(itemA.style.minHeight).toBe('36px');++ mockRect(itemA);+ Object.defineProperty(itemA, 'setPointerCapture', {+ configurable: true,+ value: vi.fn(),+ });++ const elementFromPointSpy = vi.spyOn(document, 'elementFromPoint').mockReturnValue(itemB);++ fireEvent.pointerDown(itemA, {+ pointerId: 1,+ clientX: 20,+ clientY: 24,+ });++ await waitFor(() => {+ expect(onDragStart).toHaveBeenCalledWith(undefined, { y: 0 });+ });++ expect(container.querySelector('.univer-pointer-events-none')).toBeInTheDocument();++ fireEvent.pointerMove(window, {+ pointerId: 1,+ clientX: 48,+ clientY: 50,+ });++ fireEvent.pointerUp(window, {+ pointerId: 1,+ clientX: 48,+ clientY: 50,+ });++ await waitFor(() => {+ expect(onDragStop).toHaveBeenCalledWith(undefined, { y: 0 }, { y: 1 });+ expect(onListChange).toHaveBeenCalledTimes(1);+ });++ const updatedList = onListChange.mock.calls[0][0] as IItem[];+ expect(updatedList.map((item) => item.id)).toEqual(['b', 'a', 'c']);++ elementFromPointSpy.mockRestore();+ });++ it('should only start drag when pointer down on draggable handle', async () => {+ const onListChange = vi.fn();+ const onDragStart = vi.fn();++ const { container } = render(+ <DraggableList<IItem>+ list={BASE_LIST.slice(0, 2)}+ idKey="id"+ draggableHandle=".drag-handle"+ onListChange={onListChange}+ onDragStart={onDragStart}+ itemRender={(item) => (+ <div>+ <span>{item.label}</span>+ <button type="button" className="drag-handle">drag</button>+ </div>+ )}+ />+ );++ const itemA = container.querySelector('[data-draggable-list-item-id="a"]') as HTMLDivElement;+ mockRect(itemA);++ Object.defineProperty(itemA, 'setPointerCapture', {+ configurable: true,+ value: vi.fn(),+ });++ fireEvent.pointerDown(screen.getByText('A'), {+ pointerId: 2,+ clientX: 20,+ clientY: 24,+ });++ fireEvent.pointerMove(window, {+ pointerId: 2,+ clientX: 26,+ clientY: 30,+ });+ fireEvent.pointerUp(window, {+ pointerId: 2,+ clientX: 26,+ clientY: 30,+ });++ expect(onDragStart).not.toHaveBeenCalled();+ expect(onListChange).not.toHaveBeenCalled();++ const handleButton = itemA.querySelector('.drag-handle') as HTMLButtonElement;+ fireEvent.pointerDown(handleButton, {+ pointerId: 3,+ clientX: 20,+ clientY: 24,+ });++ await waitFor(() => {+ expect(onDragStart).toHaveBeenCalledTimes(1);+ });+ });++ it('should ignore unrelated pointer events while dragging', async () => {+ const onListChange = vi.fn();++ const { container } = render(+ <DraggableList<IItem>+ list={BASE_LIST.slice(0, 2)}+ idKey="id"+ onListChange={onListChange}+ itemRender={(item) => <div>{item.label}</div>}+ />+ );++ const itemA = container.querySelector('[data-draggable-list-item-id="a"]') as HTMLDivElement;+ const itemB = container.querySelector('[data-draggable-list-item-id="b"]') as HTMLDivElement;+ mockRect(itemA);+ Object.defineProperty(itemA, 'setPointerCapture', {+ configurable: true,+ value: vi.fn(),+ });++ fireEvent.pointerDown(itemA, {+ pointerId: 10,+ clientX: 20,+ clientY: 24,+ });++ // pointerId mismatch should be ignored+ fireEvent.pointerMove(window, {+ pointerId: 999,+ clientX: 30,+ clientY: 34,+ });++ // target equals source should be ignored+ vi.spyOn(document, 'elementFromPoint').mockReturnValue(itemA);+ fireEvent.pointerMove(window, {+ pointerId: 10,+ clientX: 32,+ clientY: 36,+ });++ // target not in current list should keep previous list+ const invalidTarget = document.createElement('div');+ invalidTarget.setAttribute('data-draggable-list-item-id', 'missing');+ vi.spyOn(document, 'elementFromPoint').mockReturnValue(invalidTarget);+ fireEvent.pointerMove(window, {+ pointerId: 10,+ clientX: 34,+ clientY: 38,+ });++ // A second pointer down during active drag should be ignored.+ fireEvent.pointerDown(itemB, {+ pointerId: 11,+ clientX: 20,+ clientY: 24,+ });++ // pointerup mismatch should not end current dragging+ fireEvent.pointerUp(window, {+ pointerId: 999,+ clientX: 34,+ clientY: 38,+ });+ expect(onListChange).not.toHaveBeenCalled();++ fireEvent.pointerUp(window, {+ pointerId: 10,+ clientX: 34,+ clientY: 38,+ });+ expect(onListChange).toHaveBeenCalledTimes(1);+ });++ it('should render ghost with itemRender fallback when innerHTML is empty', async () => {+ const onListChange = vi.fn();+ const itemRender = vi.fn(() => null);++ const { container } = render(+ <DraggableList<IItem>+ list={BASE_LIST.slice(0, 1)}+ idKey="id"+ onListChange={onListChange}+ itemRender={itemRender}+ />+ );++ const itemA = container.querySelector('[data-draggable-list-item-id="a"]') as HTMLDivElement;+ mockRect(itemA);+ Object.defineProperty(itemA, 'setPointerCapture', {+ configurable: true,+ value: vi.fn(),+ });++ fireEvent.pointerDown(itemA, {+ pointerId: 20,+ clientX: 20,+ clientY: 24,+ });++ await waitFor(() => {+ expect(itemRender.mock.calls.length).toBeGreaterThanOrEqual(3);+ });++ fireEvent.pointerUp(window, {+ pointerId: 20,+ clientX: 20,+ clientY: 24,+ });+ expect(onListChange).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsxindex 2e2bc1d8b0..96db39863c 100644--- a/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx+++ b/packages/design/src/components/dropdown-menu/__tests__/index.spec.tsx@@ -14,8 +14,8 @@* limitations under the License.*/-import { cleanup, render } from '@testing-library/react';-import { afterEach, describe, expect, it } from 'vitest';+import { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';import { DropdownMenu } from '../DropdownMenu';import '@testing-library/jest-dom/vitest';@@ -109,4 +109,53 @@ describe('DropdownMenu', () => {);expect(container).toMatchSnapshot();});++ it('should invoke onSelect callbacks for item/checkbox/radio', () => {+ const onItemSelect = vi.fn();+ const onCheckboxSelect = vi.fn();+ const onRadioSelect = vi.fn();++ const items = [+ { type: 'item' as const, children: 'Run', onSelect: onItemSelect },+ { type: 'checkbox' as const, value: 'c1', label: 'Check', checked: false, onSelect: onCheckboxSelect },+ {+ type: 'radio' as const,+ value: 'a',+ onSelect: onRadioSelect,+ options: [{ label: 'A', value: 'a' }, { label: 'B', value: 'b' }],+ },+ ];++ const { getByText } = render(+ <DropdownMenu open items={items}>+ <button type="button">Trigger</button>+ </DropdownMenu>+ );++ fireEvent.click(getByText('Run'));+ fireEvent.click(getByText('Check'));+ fireEvent.click(getByText('B'));++ expect(onItemSelect).toHaveBeenCalled();+ expect(onCheckboxSelect).toHaveBeenCalledWith('c1');+ expect(onRadioSelect).toHaveBeenCalledWith('b');+ });++ it('should throw when radio option misses value', () => {+ const badItems = [+ {+ type: 'radio' as const,+ value: 'a',+ options: [{ label: 'Missing Value' }],+ },+ ];++ expect(() =>+ render(+ <DropdownMenu open items={badItems}>+ <button type="button">Trigger</button>+ </DropdownMenu>+ )+ ).toThrow('[DropdownMenu]: `value` is required');+ });});diff --git a/packages/design/src/components/dropdown-menu/__tests__/primitive.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/primitive.spec.tsxnew file mode 100644index 0000000000..bd5a4eea7b--- /dev/null+++ b/packages/design/src/components/dropdown-menu/__tests__/primitive.spec.tsx@@ -0,0 +1,69 @@+/**+ * 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 { render } from '@testing-library/react';+import { describe, expect, it } from 'vitest';+import {+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuPrimitive,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+ DropdownMenuTrigger,+} from '../DropdownMenuPrimitive';+import '@testing-library/jest-dom/vitest';++describe('DropdownMenuPrimitive', () => {+ it('should render primitive wrappers and variants', () => {+ const { container } = render(+ <DropdownMenuPrimitive open>+ <DropdownMenuTrigger>Trigger</DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuGroup>+ <DropdownMenuLabel inset>Label</DropdownMenuLabel>+ <DropdownMenuItem inset variant="destructive">Item</DropdownMenuItem>+ <DropdownMenuCheckboxItem checked hideIndicator>+ Check+ </DropdownMenuCheckboxItem>+ <DropdownMenuRadioGroup value="a">+ <DropdownMenuRadioItem value="a" hideIndicator>+ Radio A+ </DropdownMenuRadioItem>+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator />+ <DropdownMenuShortcut>Cmd+K</DropdownMenuShortcut>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger inset>More</DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuItem>Sub Item</DropdownMenuItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenuPrimitive>+ );++ expect(container).toBeInTheDocument();+ });+});diff --git a/packages/design/src/components/form-layout/__tests__/index.spec.tsx b/packages/design/src/components/form-layout/__tests__/index.spec.tsxnew file mode 100644index 0000000000..685337be69--- /dev/null+++ b/packages/design/src/components/form-layout/__tests__/index.spec.tsx@@ -0,0 +1,76 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';+import { FormDualColumnLayout, FormLayout } from '../FormLayout';+import '@testing-library/jest-dom/vitest';++afterEach(cleanup);++describe('FormLayout', () => {+ it('should toggle content when collapsable', () => {+ const { container } = render(+ <FormLayout+ label="Section"+ desc="Description"+ error="Invalid value"+ collapsable+ defaultCollapsed+ >+ <input data-u-comp="input" />+ </FormLayout>+ );++ expect(screen.queryByText('Description')).not.toBeInTheDocument();+ expect(screen.queryByText('Invalid value')).not.toBeInTheDocument();++ fireEvent.click(screen.getByText('Section'));++ expect(screen.getByText('Description')).toBeInTheDocument();+ expect(screen.getByText('Invalid value')).toBeInTheDocument();+ expect(container.querySelector('[data-u-comp="input"]')).toBeInTheDocument();++ expect(container.innerHTML).toContain('univer-border-red-500');+ });++ it('should keep content visible when not collapsable', () => {+ render(+ <FormLayout label="Always Visible" defaultCollapsed>+ <div>Child Content</div>+ </FormLayout>+ );++ fireEvent.click(screen.getByText('Always Visible'));+ expect(screen.getByText('Child Content')).toBeInTheDocument();+ });++ it('should render dual column layout', () => {+ const { container } = render(+ <FormDualColumnLayout>+ <div>Left</div>+ <div>Right</div>+ </FormDualColumnLayout>+ );++ expect(screen.getByText('Left')).toBeInTheDocument();+ expect(screen.getByText('Right')).toBeInTheDocument();++ const wrapper = container.firstElementChild as HTMLElement;+ expect(wrapper.className).toContain('univer-flex');+ expect(wrapper.className).toContain('univer-justify-between');+ });+});diff --git a/packages/design/src/components/gallery/__tests__/index.spec.tsx b/packages/design/src/components/gallery/__tests__/index.spec.tsxindex 8033983e60..51ac6d9a7e 100644--- a/packages/design/src/components/gallery/__tests__/index.spec.tsx+++ b/packages/design/src/components/gallery/__tests__/index.spec.tsx@@ -15,7 +15,7 @@*/import { cleanup, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Gallery } from '../Gallery';import '@testing-library/jest-dom/vitest';@@ -30,6 +30,9 @@ afterEach(() => {});describe('Gallery', () => {+ beforeEach(() => {+ vi.useRealTimers();+ });it('does not render when open is false', () => {render(<Gallery images={images} open={false} />);expect(screen.queryByRole('dialog')).not.toBeInTheDocument();@@ -91,14 +94,49 @@ describe('Gallery', () => {it('can switch images using the pager', () => {render(<Gallery images={images} open={true} />);- // You may need to adjust this selector depending on your Pager implementation- // For example, if there is a button with aria-label="Next page"- const nextButton = screen.queryByLabelText(/next/i) || screen.queryByTestId('pager-right-arrow');- if (nextButton) {- fireEvent.click(nextButton);- const img = screen.getByRole('img');- expect(img).toHaveAttribute('src', images[1]);- expect(img).toHaveAttribute('alt', 'Image 2 of 3');+ const nextButton = document.querySelector('[data-u-comp="pager-right-arrow"]') as HTMLButtonElement;+ fireEvent.click(nextButton);+ const img = screen.getByRole('img');+ expect(img).toHaveAttribute('src', images[1]);+ expect(img).toHaveAttribute('alt', 'Image 2 of 3');+ });++ it('should zoom with wheel event and keep value in range', () => {+ render(<Gallery images={images} open={true} />);+ const img = screen.getByRole('img');+ const getScale = () => Number.parseFloat((img.style.transform.match(/scale\(([^)]+)\)/)?.[1] ?? '1'));++ fireEvent.wheel(window, { deltaY: -300 });+ expect(img.style.transform).toContain('scale(');++ const zoomInBtn = screen.getByRole('button', { name: /zoom in/i });+ const zoomOutBtn = screen.getByRole('button', { name: /zoom out/i });+ for (let i = 0; i < 8; i++) {+ fireEvent.click(zoomInBtn);}+ const atUpperBound = getScale();+ fireEvent.click(zoomInBtn);+ expect(getScale()).toBe(atUpperBound);+ expect(getScale()).toBeLessThanOrEqual(2);++ for (let i = 0; i < 12; i++) {+ fireEvent.click(zoomOutBtn);+ }+ const atLowerBound = getScale();+ fireEvent.click(zoomOutBtn);+ expect(getScale()).toBe(atLowerBound);+ expect(getScale()).toBeGreaterThanOrEqual(0.5);+ });++ it('should schedule close animation timer when closing', () => {+ const timeoutSpy = vi.spyOn(globalThis, 'setTimeout');+ const { rerender } = render(<Gallery images={images} open={true} />);+ expect(screen.getByRole('dialog')).toBeInTheDocument();++ rerender(<Gallery images={images} open={false} />);+ expect(screen.getByRole('dialog')).toBeInTheDocument();++ expect(timeoutSpy).toHaveBeenCalled();+ expect(timeoutSpy.mock.calls.some(([, delay]) => delay === 150)).toBe(true);});});diff --git a/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx b/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsxindex 457fdbc51c..fc3e52b47b 100644--- a/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx+++ b/packages/design/src/components/gradient-color-picker/__tests__/index.spec.tsx@@ -159,4 +159,78 @@ describe('GradientColorPicker', () => {expect(calledValue.stops.length).toBe(3);expect(calledValue.stops.some((s) => s.offset === 50)).toBe(true);});++ it('should ignore null offset change from offset input', () => {+ const onChange = vi.fn();+ const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);+ const inputs = container.querySelectorAll('input');+ const offsetInput = inputs[0] as HTMLInputElement;++ fireEvent.change(offsetInput, { target: { value: '' } });+ expect(onChange).not.toHaveBeenCalled();+ });++ it('should update stop color via nested color picker presets', () => {+ const onChange = vi.fn();+ const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);++ const presetButton = container.querySelector('[data-u-comp="color-picker-presets"] button') as HTMLButtonElement;+ expect(presetButton).toBeTruthy();+ fireEvent.click(presetButton);++ expect(onChange).toHaveBeenCalled();+ const next = onChange.mock.calls[0][0] as IGradientValue;+ expect(next.stops[0].color).toMatch(/^#/);+ });++ it('should support radial/angular/diamond and fallback preview background', () => {+ const { container, rerender } = render(<GradientColorPicker value={{ ...defaultValue, type: 'radial' }} />);+ const preview = container.querySelector('.univer-h-32') as HTMLDivElement;+ expect(preview.style.background).toContain('radial-gradient');++ rerender(<GradientColorPicker value={{ ...defaultValue, type: 'angular' }} />);+ expect((container.querySelector('.univer-h-32') as HTMLDivElement).style.background).toContain('conic-gradient');++ rerender(<GradientColorPicker value={{ ...defaultValue, type: 'diamond' }} />);+ expect((container.querySelector('.univer-h-32') as HTMLDivElement).style.background).toContain('radial-gradient');++ rerender(<GradientColorPicker value={{ ...defaultValue, type: 'unexpected' as unknown as IGradientValue['type'] }} />);+ expect((container.querySelector('.univer-h-32') as HTMLDivElement).style.background).toContain('linear-gradient');+ });++ it('should drag a stop and emit new offset', () => {+ const onChange = vi.fn();+ const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);+ const bar = container.querySelector('.univer-cursor-crosshair') as HTMLDivElement;+ const stop = container.querySelector('.univer-absolute.univer-rounded-full.univer-border-2') as HTMLDivElement;++ bar.getBoundingClientRect = vi.fn(() => ({+ left: 0,+ width: 100,+ top: 0,+ height: 10,+ bottom: 10,+ right: 100,+ x: 0,+ y: 0,+ toJSON: () => {},+ }));++ fireEvent.pointerDown(stop, { clientX: 0 });+ fireEvent.pointerMove(window, { clientX: 60 });+ fireEvent.pointerUp(window);++ expect(onChange).toHaveBeenCalled();+ const values = onChange.mock.calls.map((call) => call[0] as IGradientValue);+ expect(values.some((v) => v.stops[0].offset === 60)).toBe(true);+ });++ it('should not remove stop when there are only two stops', () => {+ const onChange = vi.fn();+ const { container } = render(<GradientColorPicker value={defaultValue} onChange={onChange} />);+ const deleteButton = container.querySelector('.univer-border-red-500') as HTMLButtonElement;+ expect(deleteButton).toBeDisabled();+ fireEvent.click(deleteButton);+ expect(onChange).not.toHaveBeenCalled();+ });});diff --git a/packages/design/src/components/hover-card/__tests__/logic.spec.tsx b/packages/design/src/components/hover-card/__tests__/logic.spec.tsxnew file mode 100644index 0000000000..2f6e9fa1ec--- /dev/null+++ b/packages/design/src/components/hover-card/__tests__/logic.spec.tsx@@ -0,0 +1,85 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { HoverCard } from '../HoverCard';++import '@testing-library/jest-dom/vitest';++vi.mock('../HoverCardPrimitive', async () => {+ const React = await import('react');+ return {+ HoverCardPrimitive: ({ open, onOpenChange, children }: any) => (+ <div+ data-testid="hover-root"+ data-open={String(open)}+ onMouseEnter={() => onOpenChange?.(true)}+ onMouseLeave={() => onOpenChange?.(false)}+ >+ {children}+ </div>+ ),+ HoverCardTrigger: ({ children }: any) => <div data-testid="hover-trigger">{children}</div>,+ HoverCardPortal: ({ children }: any) => <div>{children}</div>,+ HoverCardContent: React.forwardRef<HTMLDivElement, any>(({ children }, ref) => (+ <div ref={ref} data-testid="hover-content">{children}</div>+ )),+ };+});++afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+});++describe('HoverCard logic branches', () => {+ it('should update uncontrolled open state and call onOpenChange', () => {+ const onOpenChange = vi.fn();+ render(+ <HoverCard overlay={<div>Overlay</div>} onOpenChange={onOpenChange}>+ <button type="button">Trigger</button>+ </HoverCard>+ );++ const root = screen.getByTestId('hover-root');+ expect(root.getAttribute('data-open')).toBe('false');++ fireEvent.mouseEnter(root);+ expect(onOpenChange).toHaveBeenCalledWith(true);+ expect(root.getAttribute('data-open')).toBe('true');++ fireEvent.mouseLeave(root);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(root.getAttribute('data-open')).toBe('false');+ });++ it('should block open changes when disabled', () => {+ const onOpenChange = vi.fn();+ render(+ <HoverCard overlay={<div>Overlay</div>} disabled onOpenChange={onOpenChange}>+ <button type="button">Trigger</button>+ </HoverCard>+ );++ const root = screen.getByTestId('hover-root');+ fireEvent.mouseEnter(root);+ fireEvent.mouseLeave(root);++ expect(onOpenChange).not.toHaveBeenCalled();+ expect(root.getAttribute('data-open')).toBe('false');+ });+});diff --git a/packages/design/src/components/input-number/__tests__/index.spec.tsx b/packages/design/src/components/input-number/__tests__/index.spec.tsxindex 97cf2d45ec..9293633f69 100644--- a/packages/design/src/components/input-number/__tests__/index.spec.tsx+++ b/packages/design/src/components/input-number/__tests__/index.spec.tsx@@ -111,4 +111,192 @@ describe('InputNumber', () => {fireEvent.keyDown(input, { key: 'ArrowDown' });expect(onChange).toHaveBeenCalledWith(0);});++ it('should respect min/max and disable control buttons at bounds', () => {+ onChange.mockClear();+ const { container } = render(<InputNumber value={1} min={1} max={2} onChange={onChange} />);++ const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];+ expect(decBtn).toHaveAttribute('aria-disabled', 'true');+ expect(incBtn).toHaveAttribute('aria-disabled', 'false');++ fireEvent.click(decBtn);+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.click(incBtn);+ expect(onChange).toHaveBeenCalledWith(2);+ });++ it('should support formatter/parser/precision and press enter callback', () => {+ const onPressEnter = vi.fn();+ const { container } = render(+ <InputNumber+ defaultValue={1.236}+ precision={2}+ parser={(v) => (v ?? '').replace('$', '')}+ formatter={(v) => `$${v}`}+ onPressEnter={onPressEnter}+ />+ );++ const input = container.querySelector('input') as HTMLInputElement;+ expect(input.value).toBe('$1.24');++ fireEvent.change(input, { target: { value: '$2.345' } });+ fireEvent.blur(input);+ expect(input.value).toBe('$2.35');++ fireEvent.keyDown(input, { key: 'Enter' });+ expect(onPressEnter).toHaveBeenCalled();+ });++ it('should hide controls when controls is false and keep input disabled', () => {+ const { container } = render(<InputNumber defaultValue={3} controls={false} disabled />);+ expect(container.querySelector('[role="button"]')).toBeNull();+ const input = container.querySelector('input') as HTMLInputElement;+ expect(input).toBeDisabled();+ });++ it('should support ref callback and object ref', () => {+ const callbackRef = vi.fn();+ const objectRef = { current: null as HTMLInputElement | null };++ const { unmount } = render(<InputNumber defaultValue={1} ref={callbackRef} />);+ expect(callbackRef).toHaveBeenCalled();+ unmount();++ render(<InputNumber defaultValue={2} ref={objectRef} />);+ expect(objectRef.current).not.toBeNull();+ });++ it('should handle parser fallback and scientific notation', () => {+ const onLocalChange = vi.fn();+ const { container } = render(+ <InputNumber+ defaultValue={1}+ parser={() => null as unknown as string}+ onChange={onLocalChange}+ />+ );++ const input = container.querySelector('input') as HTMLInputElement;+ fireEvent.change(input, { target: { value: '123' } });+ expect(onLocalChange).toHaveBeenCalledWith(null);++ onLocalChange.mockClear();+ fireEvent.change(input, { target: { value: '1e3' } });+ expect(onLocalChange).toHaveBeenCalledWith(null);+ });++ it('should parse scientific notation without precision loss branch errors', () => {+ const onLocalChange = vi.fn();+ const { container } = render(<InputNumber defaultValue={1} onChange={onLocalChange} />);+ const input = container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: '1e3' } });+ expect(onLocalChange).toHaveBeenCalledWith(13);+ });++ it('should step from null value using min baseline and keep boundary', () => {+ const onLocalChange = vi.fn();+ const { container } = render(<InputNumber allowEmpty min={2} max={3} value={null} onChange={onLocalChange} />);+ const [incBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];++ fireEvent.click(incBtn);+ expect(onLocalChange).toHaveBeenCalledWith(3);++ fireEvent.click(incBtn);+ expect(onLocalChange).toHaveBeenCalledTimes(1);+ });++ it('should handle NaN and clamp by min/max while typing', () => {+ const onLocalChange = vi.fn();+ const { container } = render(<InputNumber defaultValue={5} min={0} max={10} onChange={onLocalChange} />);+ const input = container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: '-' } });+ expect(onLocalChange).toHaveBeenCalledWith(null);++ fireEvent.change(input, { target: { value: '9999' } });+ expect(onLocalChange).toHaveBeenCalledWith(10);++ fireEvent.change(input, { target: { value: '-9999' } });+ expect(onLocalChange).toHaveBeenCalledWith(0);+ });++ it('should restore last valid value on blur when current value is invalid', () => {+ const onLocalChange = vi.fn();+ const { container } = render(<InputNumber defaultValue={6} onChange={onLocalChange} />);+ const input = container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: '-' } });+ fireEvent.blur(input);++ expect(onLocalChange).toHaveBeenCalledWith(6);+ expect(input.value).toBe('6');+ });++ it('should clamp out-of-range value on blur', () => {+ const onLocalChange = vi.fn();+ const { container } = render(<InputNumber defaultValue={1} min={0} max={10} onChange={onLocalChange} />);+ const input = container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: '100' } });+ fireEvent.blur(input);+ expect(onLocalChange).toHaveBeenCalledWith(10);+ expect(input.value).toBe('10');++ fireEvent.change(input, { target: { value: '-100' } });+ fireEvent.blur(input);+ expect(onLocalChange).toHaveBeenCalledWith(0);+ expect(input.value).toBe('0');+ });++ it('should parse very large values in scientific-notation branches', () => {+ const onWithPrecision = vi.fn();+ const onWithoutPrecision = vi.fn();+ const { container: c1 } = render(<InputNumber precision={2} defaultValue={1} onChange={onWithPrecision} />);+ const { container: c2 } = render(<InputNumber defaultValue={1} onChange={onWithoutPrecision} />);+ const huge = '10000000000000000000000';++ fireEvent.change(c1.querySelector('input')!, { target: { value: huge } });+ fireEvent.change(c2.querySelector('input')!, { target: { value: huge } });++ expect(onWithPrecision).toHaveBeenCalled();+ expect(onWithoutPrecision).toHaveBeenCalled();+ });++ it('should use last valid value as baseline when stepping from empty and support decrement click', () => {+ const onLocalChange = vi.fn();+ const { container } = render(<InputNumber allowEmpty defaultValue={2} onChange={onLocalChange} min={0} />);+ const input = container.querySelector('input') as HTMLInputElement;+ const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];++ fireEvent.change(input, { target: { value: '' } });+ fireEvent.click(incBtn);+ expect(onLocalChange).toHaveBeenCalledWith(3);++ fireEvent.click(decBtn);+ expect(onLocalChange).toHaveBeenCalledWith(2);+ });++ it('should prevent interactions when disabled and prevent default on control mousedown', () => {+ const onLocalChange = vi.fn();+ const onKeyDown = vi.fn();+ const { container } = render(<InputNumber defaultValue={2} disabled onChange={onLocalChange} onKeyDown={onKeyDown} />);+ const input = container.querySelector('input') as HTMLInputElement;+ const [incBtn, decBtn] = Array.from(container.querySelectorAll('[role="button"]')) as HTMLElement[];++ const incMouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });+ const decMouseDown = new MouseEvent('mousedown', { bubbles: true, cancelable: true });+ expect(incBtn.dispatchEvent(incMouseDown)).toBe(false);+ expect(decBtn.dispatchEvent(decMouseDown)).toBe(false);++ fireEvent.keyDown(input, { key: 'ArrowUp' });+ fireEvent.click(incBtn);+ fireEvent.click(decBtn);++ expect(onKeyDown).not.toHaveBeenCalled();+ expect(onLocalChange).not.toHaveBeenCalled();+ });});diff --git a/packages/design/src/components/input/__tests__/index.spec.tsx b/packages/design/src/components/input/__tests__/index.spec.tsxindex d7211c82d9..aca0b643ab 100644--- a/packages/design/src/components/input/__tests__/index.spec.tsx+++ b/packages/design/src/components/input/__tests__/index.spec.tsx@@ -15,10 +15,13 @@*/import { cleanup, fireEvent, render } from '@testing-library/react';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { Input } from '../Input';afterEach(cleanup);+afterEach(() => {+ vi.unstubAllGlobals();+});describe('Input', () => {afterEach(cleanup);@@ -70,4 +73,66 @@ describe('Input', () => {expect(inputElement.value).toBe('Test');});++ it('should clear value without bubbling click event', () => {+ const onChange = vi.fn();+ const parentClick = vi.fn();+ const { container } = render(+ <div onClick={parentClick}>+ <Input allowClear value="abc" onChange={onChange} />+ </div>+ );++ const clearButton = container.querySelector('button[type="button"]') as HTMLButtonElement;+ fireEvent.click(clearButton);++ expect(onChange).toHaveBeenCalledWith('');+ expect(parentClick).not.toHaveBeenCalled();+ });++ it('should observe slot mutations and apply slot paddingRight', () => {+ const observe = vi.fn();+ const disconnect = vi.fn();+ class MockMutationObserver {+ private _callback: MutationCallback;++ constructor(callback: MutationCallback) {+ this._callback = callback;+ }++ observe(...args: unknown[]) {+ observe(...args);+ this._callback([], {} as MutationObserver);+ }++ disconnect() {+ disconnect();+ }+ }++ vi.stubGlobal('MutationObserver', MockMutationObserver);++ const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {+ configurable: true,+ get() {+ return 20;+ },+ });++ const { container } = render(<Input value="x" slot={<span>slot</span>} />);+ const input = container.querySelector('input') as HTMLInputElement;+ expect(observe).toHaveBeenCalled();+ expect(input.style.paddingRight).toBe('28px');++ if (originalOffsetWidth) {+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);+ }+ });++ it('should set default allowClear padding when no slot exists', () => {+ const { container } = render(<Input allowClear value="x" />);+ const input = container.querySelector('input') as HTMLInputElement;+ expect(input.style.paddingRight).toBe('26px');+ });});diff --git a/packages/design/src/components/menu/__tests__/index.spec.tsx b/packages/design/src/components/menu/__tests__/index.spec.tsxnew file mode 100644index 0000000000..2abf99f1c0--- /dev/null+++ b/packages/design/src/components/menu/__tests__/index.spec.tsx@@ -0,0 +1,133 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ConfigProvider } from '../../config-provider/ConfigProvider';+import { Menu, MenuItem, TinyMenuGroup } from '../Menu';+import '@testing-library/jest-dom/vitest';++const { menuPropsSpy } = vi.hoisted(() => ({+ menuPropsSpy: vi.fn(),+}));++vi.mock('rc-menu', () => ({+ default: (props: any) => {+ menuPropsSpy(props);+ return (+ <div data-testid="rc-menu" data-prefix={props.prefixCls} className={props.className}>+ {props.children}+ </div>+ );+ },+ MenuItem: (props: any) => <div data-testid="rc-menu-item">{props.children}</div>,+ MenuItemGroup: (props: any) => <div data-testid="rc-menu-group">{props.children}</div>,+ SubMenu: (props: any) => <div data-testid="rc-sub-menu">{props.children}</div>,+}));++vi.mock('../../tooltip/Tooltip', () => ({+ Tooltip: (props: any) => (+ <div data-testid="mock-tooltip" data-title={props.title}>+ {props.children}+ </div>+ ),+}));++afterEach(() => {+ cleanup();+ menuPropsSpy.mockClear();+});++describe('Menu', () => {+ it('should render rc-menu with mount container', () => {+ const mountContainer = document.createElement('div');++ render(+ <ConfigProvider mountContainer={mountContainer}>+ <Menu className="inner-class" wrapperClass="wrapper-class">+ <MenuItem key="menu-item">Menu Item</MenuItem>+ </Menu>+ </ConfigProvider>+ );++ const rcMenu = screen.getByTestId('rc-menu');+ expect(rcMenu).toHaveClass('wrapper-class');+ expect(rcMenu).toHaveAttribute('data-prefix');+ expect(rcMenu.getAttribute('data-prefix')).toContain('univer-menu');++ const props = menuPropsSpy.mock.calls.at(-1)?.[0];+ expect(props.getPopupContainer()).toBe(mountContainer);+ });++ it('should render nothing without mount container', () => {+ render(+ <ConfigProvider mountContainer={null}>+ <Menu className="inner-class" wrapperClass="wrapper-class" />+ </ConfigProvider>+ );++ expect(screen.queryByTestId('rc-menu')).not.toBeInTheDocument();+ });++ it('should render tiny menu group and support click/tooltip', () => {+ const onClickA = vi.fn();+ const onClickB = vi.fn();++ function IconA(props: { className?: string }) {+ return <span className={props.className}>IconA</span>;+ }++ function IconB(props: { className?: string }) {+ return <span className={props.className}>IconB</span>;+ }++ const { container } = render(+ <TinyMenuGroup+ items={[+ {+ key: 'a',+ className: 'custom-a',+ Icon: IconA,+ active: true,+ tooltip: 'tip-a',+ onClick: onClickA,+ },+ {+ key: 'b',+ className: 'custom-b',+ Icon: IconB,+ onClick: onClickB,+ },+ ]}+ />+ );++ expect(screen.getByTestId('mock-tooltip')).toHaveAttribute('data-title', 'tip-a');++ const iconA = screen.getByText('IconA');+ const iconAWrapper = iconA.parentElement as HTMLElement;+ expect(iconAWrapper.className).toContain('univer-bg-gray-50');++ fireEvent.click(iconAWrapper);+ expect(onClickA).toHaveBeenCalledTimes(1);++ const iconB = screen.getByText('IconB');+ fireEvent.click(iconB.parentElement as HTMLElement);+ expect(onClickB).toHaveBeenCalledTimes(1);++ expect(container.querySelectorAll('.custom-a, .custom-b').length).toBe(2);+ });+});diff --git a/packages/design/src/components/popup/__tests__/index.spec.tsx b/packages/design/src/components/popup/__tests__/index.spec.tsxnew file mode 100644index 0000000000..7bfb1476d8--- /dev/null+++ b/packages/design/src/components/popup/__tests__/index.spec.tsx@@ -0,0 +1,102 @@+/**+ * 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 { cleanup, fireEvent, render, waitFor } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';+import { ConfigProvider } from '../../config-provider/ConfigProvider';+import { Popup } from '../Popup';+import '@testing-library/jest-dom/vitest';++afterEach(() => {+ cleanup();+});++describe('Popup', () => {+ it('should clamp popup offset and support resize/contextmenu', async () => {+ const mountContainer = document.createElement('div');+ document.body.appendChild(mountContainer);++ Object.defineProperty(window, 'innerWidth', {+ configurable: true,+ value: 100,+ });+ Object.defineProperty(window, 'innerHeight', {+ configurable: true,+ value: 100,+ });++ render(+ <ConfigProvider mountContainer={mountContainer}>+ <Popup visible offset={[90, 90]} placementY="above" overflowVisible>+ <div>popup-content</div>+ </Popup>+ </ConfigProvider>+ );++ const popup = mountContainer.querySelector('section.univer-popup') as HTMLElement;+ expect(popup).toBeInTheDocument();++ Object.defineProperty(popup, 'clientWidth', {+ configurable: true,+ value: 60,+ });+ Object.defineProperty(popup, 'clientHeight', {+ configurable: true,+ value: 40,+ });++ fireEvent(window, new Event('resize'));++ await waitFor(() => {+ expect(popup.style.left).toBe('40px');+ expect(popup.style.top).toBe('52px');+ });++ expect(popup.style.overflow).toBe('visible');++ const contextMenuEvent = new MouseEvent('contextmenu', {+ bubbles: true,+ cancelable: true,+ });+ popup.dispatchEvent(contextMenuEvent);+ expect(contextMenuEvent.defaultPrevented).toBe(true);++ mountContainer.remove();+ });++ it('should move popup off-screen when hidden', async () => {+ const mountContainer = document.createElement('div');+ document.body.appendChild(mountContainer);++ render(+ <ConfigProvider mountContainer={mountContainer}>+ <Popup visible={false} offset={[10, 20]}>+ <div>popup-content</div>+ </Popup>+ </ConfigProvider>+ );++ const popup = mountContainer.querySelector('section.univer-popup') as HTMLElement;+ expect(popup).toBeInTheDocument();++ await waitFor(() => {+ expect(popup.style.left).toBe('-9997px');+ expect(popup.style.top).toBe('-9997px');+ });++ mountContainer.remove();+ });+});diff --git a/packages/design/src/components/select/__tests__/index.spec.tsx b/packages/design/src/components/select/__tests__/index.spec.tsxindex ad1b4aa9ad..bcbe313748 100644--- a/packages/design/src/components/select/__tests__/index.spec.tsx+++ b/packages/design/src/components/select/__tests__/index.spec.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { cleanup, render } from '@testing-library/react';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';import { afterEach, describe, expect, it, vi } from 'vitest';import { MultipleSelect } from '../MultipleSelect';import { Select } from '../Select';@@ -111,4 +111,26 @@ describe('MultipleSelect', () => {}}});++ it('should remove badge value when close icon is clicked', () => {+ const handleChange = vi.fn();+ render(<MultipleSelect value={['1', '2']} options={options} onChange={handleChange} />);++ const closeButtons = screen.getAllByLabelText('Close badge');+ fireEvent.click(closeButtons[0]);+ expect(handleChange).toHaveBeenCalledWith(['2']);+ });++ it('should support borderless and disabled visual classes', () => {+ const { container, rerender } = render(<MultipleSelect value={['1']} options={options} onChange={() => {}} />);+ const trigger = container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement;++ expect(trigger).toHaveClass('univer-cursor-pointer', { exact: false });++ rerender(<MultipleSelect value={['1']} options={options} onChange={() => {}} borderless />);+ expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-border-transparent');++ rerender(<MultipleSelect value={['1']} options={options} onChange={() => {}} disabled />);+ expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-cursor-not-allowed');+ });});diff --git a/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx b/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsxnew file mode 100644index 0000000000..b2e0e6919c--- /dev/null+++ b/packages/design/src/components/select/__tests__/multiple-select.logic.spec.tsx@@ -0,0 +1,76 @@+/**+ * 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 { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { MultipleSelect } from '../MultipleSelect';++import '@testing-library/jest-dom/vitest';++vi.mock('../../dropdown-menu/DropdownMenu', () => {+ return {+ DropdownMenu: ({ children, items = [], onOpenChange }: any) => (+ <div>+ <button type="button" data-testid="open-menu" onClick={() => onOpenChange?.(true)}>+ open+ </button>+ <button type="button" data-testid="close-menu" onClick={() => onOpenChange?.(false)}>+ close+ </button>+ {items.map((item: any) => (+ <button+ key={item.value}+ type="button"+ data-testid={`item-${item.value}`}+ onClick={() => item.onSelect?.(item.value)}+ >+ {String(item.value)}+ </button>+ ))}+ {children}+ </div>+ ),+ };+});++afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+});++describe('MultipleSelect logic branches', () => {+ const options = [+ { label: 'Option 1', value: '1' },+ { label: 'Option 2', value: '2' },+ ];++ it('should handle open state and checkbox item select branches', () => {+ const onChange = vi.fn();+ const { container } = render(<MultipleSelect value={['1']} options={options} onChange={onChange} />);++ fireEvent.click(screen.getByTestId('open-menu'));+ expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-ring-2');++ fireEvent.click(screen.getByTestId('item-1'));+ expect(onChange).toHaveBeenCalledWith([]);++ fireEvent.click(screen.getByTestId('item-2'));+ expect(onChange).toHaveBeenCalledWith(['1', '2']);++ fireEvent.click(screen.getByTestId('close-menu'));+ expect((container.querySelector('[data-u-comp="multiple-select"]') as HTMLDivElement).className).toContain('univer-cursor-pointer');+ });+});diff --git a/packages/design/src/components/textarea/__tests__/index.spec.tsx b/packages/design/src/components/textarea/__tests__/index.spec.tsxindex dfa641b38c..b6b3ba88a2 100644--- a/packages/design/src/components/textarea/__tests__/index.spec.tsx+++ b/packages/design/src/components/textarea/__tests__/index.spec.tsx@@ -15,13 +15,38 @@*/import { cleanup, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Textarea } from '../Textarea';import '@testing-library/jest-dom/vitest';-afterEach(cleanup);-describe('Textarea', () => {+ let observeMock: ReturnType<typeof vi.fn>;+ let unobserveMock: ReturnType<typeof vi.fn>;+ let disconnectMock: ReturnType<typeof vi.fn>;+ let triggerResize: (entries: { target: { getBoundingClientRect: () => { width: number; height: number } } }[]) => void;++ beforeEach(() => {+ observeMock = vi.fn();+ unobserveMock = vi.fn();+ disconnectMock = vi.fn();++ // @ts-ignore+ window.ResizeObserver = class ResizeObserver {+ constructor(callback: any) {+ triggerResize = callback;+ }++ observe = observeMock;+ unobserve = unobserveMock;+ disconnect = disconnectMock;+ };+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });+it('should support controlled value', () => {const { rerender } = render(<Textarea value="foo" onValueChange={() => {}} />);const textarea = screen.getByRole('textbox') as HTMLTextAreaElement;@@ -30,14 +55,74 @@ describe('Textarea', () => {expect(textarea.value).toBe('bar');});- it('calls onResize when size changes', () => {+ it('should call onResize when size changes', () => {const onResize = vi.fn();render(<Textarea onResize={onResize} />);- const textarea = document.querySelector('textarea[data-u-comp="textarea"]')!;- // mock ResizeObserver- const event = new Event('resize');- textarea.dispatchEvent(event);- expect(typeof onResize).toBe('function');++ expect(observeMock).toHaveBeenCalled();++ // Trigger resize with valid dimensions+ triggerResize([{+ target: {+ getBoundingClientRect: () => ({ width: 100, height: 100 }),+ },+ }]);++ expect(onResize).toHaveBeenCalledWith(100, 100);++ // Trigger resize with different dimensions+ triggerResize([{+ target: {+ getBoundingClientRect: () => ({ width: 200, height: 200 }),+ },+ }]);++ expect(onResize).toHaveBeenCalledWith(200, 200);+ });++ it('should not call onResize when size is 0', () => {+ const onResize = vi.fn();+ render(<Textarea onResize={onResize} />);++ // Trigger resize with 0 dimensions+ triggerResize([{+ target: {+ getBoundingClientRect: () => ({ width: 0, height: 0 }),+ },+ }]);++ expect(onResize).not.toHaveBeenCalled();+ });++ it('should not call onResize when size does not change', () => {+ const onResize = vi.fn();+ render(<Textarea onResize={onResize} />);++ // First call+ triggerResize([{+ target: {+ getBoundingClientRect: () => ({ width: 100, height: 100 }),+ },+ }]);+ expect(onResize).toHaveBeenCalledTimes(1);++ // Second call with same dimensions+ triggerResize([{+ target: {+ getBoundingClientRect: () => ({ width: 100, height: 100 }),+ },+ }]);+ expect(onResize).toHaveBeenCalledTimes(1);+ });++ it('should cleanup observer on unmount', () => {+ const onResize = vi.fn();+ const { unmount } = render(<Textarea onResize={onResize} />);++ unmount();++ expect(unobserveMock).toHaveBeenCalled();+ expect(disconnectMock).toHaveBeenCalled();});it('should forward ref', () => {@@ -64,6 +149,7 @@ describe('Textarea', () => {const textarea = screen.getByRole('textbox');expect(textarea).toHaveAttribute('rows', '5');});+it('renders with default props', () => {render(<Textarea />);const textarea = screen.getByRole('textbox');diff --git a/packages/design/src/components/time-input/__tests__/index.spec.tsx b/packages/design/src/components/time-input/__tests__/index.spec.tsxnew file mode 100644index 0000000000..c2ead65ac2--- /dev/null+++ b/packages/design/src/components/time-input/__tests__/index.spec.tsx@@ -0,0 +1,51 @@+/**+ * 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 { cleanup, fireEvent, render } from '@testing-library/react';+import dayjs from 'dayjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { TimeInput } from '../TimeInput';+import '@testing-library/jest-dom/vitest';++describe('TimeInput', () => {+ afterEach(cleanup);++ it('should render with current value and custom class', () => {+ const value = new Date('2024-01-01T01:02:03.000Z');+ const { container, getByDisplayValue } = render(<TimeInput value={value} className="custom-time" />);+ const expected = dayjs(value).format('HH:mm:ss');++ expect(container.querySelector('[data-u-comp="time-input"]')).toBeInTheDocument();+ expect(container.querySelector('.custom-time')).toBeInTheDocument();+ expect(getByDisplayValue(expected)).toBeInTheDocument();+ });++ it('should emit changed date when time input changes', () => {+ const onValueChange = vi.fn();+ const value = new Date('2024-01-01T00:00:00.000Z');+ const { container } = render(<TimeInput value={value} onValueChange={onValueChange} />);++ const input = container.querySelector('input[type="time"]') as HTMLInputElement;+ expect(input).toBeInTheDocument();+ fireEvent.change(input, { target: { value: '12:34:56' } });++ expect(onValueChange).toHaveBeenCalledTimes(1);+ const changed = onValueChange.mock.calls[0][0] as Date;+ expect(changed.getHours()).toBe(12);+ expect(changed.getMinutes()).toBe(34);+ expect(changed.getSeconds()).toBe(56);+ });+});diff --git a/packages/design/src/components/tooltip/__tests__/index.spec.tsx b/packages/design/src/components/tooltip/__tests__/index.spec.tsxnew file mode 100644index 0000000000..574730c874--- /dev/null+++ b/packages/design/src/components/tooltip/__tests__/index.spec.tsx@@ -0,0 +1,215 @@+/**+ * 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 { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { Tooltip } from '../Tooltip';+import '@testing-library/jest-dom/vitest';++function createRect(left: number, top: number, width: number, height: number): DOMRect {+ return {+ x: left,+ y: top,+ top,+ left,+ width,+ height,+ right: left + width,+ bottom: top + height,+ toJSON() {+ return {};+ },+ } as DOMRect;+}++describe('Tooltip', () => {+ beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function getRect(this: HTMLElement) {+ if (this.getAttribute('role') === 'tooltip') {+ return createRect(0, 0, 120, 40);+ }++ if (this.tagName === 'SPAN' || this.tagName === 'BUTTON') {+ return createRect(100, 100, 80, 20);+ }++ return createRect(0, 0, 0, 0);+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ cleanup();+ });++ it('should show and hide in uncontrolled mode', async () => {+ render(+ <Tooltip title="Tip content">+ Trigger+ </Tooltip>+ );++ const trigger = screen.getByText('Trigger');+ fireEvent.mouseEnter(trigger);+ expect(await screen.findByRole('tooltip')).toHaveTextContent('Tip content');++ fireEvent.mouseLeave(trigger);+ await waitFor(() => {+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();+ });+ });++ it('should notify visibility changes in controlled mode', () => {+ const onVisibleChange = vi.fn();+ render(+ <Tooltip title="Controlled" visible={false} onVisibleChange={onVisibleChange}>+ Trigger+ </Tooltip>+ );++ const trigger = screen.getByText('Trigger');+ fireEvent.mouseEnter(trigger);+ fireEvent.mouseLeave(trigger);++ expect(onVisibleChange).toHaveBeenCalledWith(true);+ expect(onVisibleChange).toHaveBeenCalledWith(false);+ });++ it('should support non-asChild trigger and focus/blur events', async () => {+ render(+ <Tooltip title="From button" asChild={false}>+ Trigger button+ </Tooltip>+ );++ const button = screen.getByRole('button', { name: 'Trigger button' });+ fireEvent.focus(button);+ expect(await screen.findByRole('tooltip')).toHaveTextContent('From button');+ fireEvent.blur(button);++ await waitFor(() => {+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();+ });+ });++ it('should only show when overflowing if showIfEllipsis is true', async () => {+ render(+ <Tooltip title="Ellipsis tip" showIfEllipsis>+ Ellipsis target+ </Tooltip>+ );++ const trigger = screen.getByText('Ellipsis target');+ Object.defineProperty(trigger, 'clientWidth', { value: 100, configurable: true });+ Object.defineProperty(trigger, 'scrollWidth', { value: 100, configurable: true });++ fireEvent.mouseEnter(trigger);+ await waitFor(() => {+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();+ });++ Object.defineProperty(trigger, 'scrollWidth', { value: 140, configurable: true });+ fireEvent.mouseEnter(trigger);+ const tooltip = await screen.findByRole('tooltip');+ expect(tooltip).toBeInTheDocument();+ });++ it('should compute styles for top/left/right placements and update on resize/scroll', async () => {+ const placements = ['top', 'left', 'right'] as const;++ for (const placement of placements) {+ const { unmount } = render(+ <Tooltip title={`tip-${placement}`} placement={placement}>+ Trigger+ {' '}+ {placement}+ </Tooltip>+ );++ const trigger = screen.getByText(`Trigger ${placement}`);+ fireEvent.mouseEnter(trigger);+ const tooltip = await screen.findByRole('tooltip');+ expect(tooltip).toBeInTheDocument();++ fireEvent.resize(window);+ fireEvent.scroll(window);+ expect(tooltip.style.top).not.toBe('');+ expect(tooltip.style.left).not.toBe('');++ unmount();+ }+ });++ it('should run fallback position clamping when no placement fully fits', async () => {+ Object.defineProperty(window, 'innerWidth', { value: 100, configurable: true });+ Object.defineProperty(window, 'innerHeight', { value: 100, configurable: true });++ render(+ <Tooltip title="fallback-tip" placement="top">+ fallback-trigger+ </Tooltip>+ );++ fireEvent.mouseEnter(screen.getByText('fallback-trigger'));+ const tooltip = await screen.findByRole('tooltip');+ expect(tooltip.style.top).not.toBe('');+ expect(tooltip.style.left).not.toBe('');+ });++ it('should handle mouse enter/leave on tooltip portal node', async () => {+ render(+ <Tooltip title="portal-tip">+ portal-trigger+ </Tooltip>+ );++ const trigger = screen.getByText('portal-trigger');+ fireEvent.mouseEnter(trigger);+ const tooltip = await screen.findByRole('tooltip');++ fireEvent.mouseEnter(tooltip);+ fireEvent.mouseLeave(tooltip);+ await waitFor(() => {+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();+ });+ });++ it('should execute left-placement recompute branch on scroll', async () => {+ vi.restoreAllMocks();+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function getRect(this: HTMLElement) {+ if (this.getAttribute('role') === 'tooltip') {+ return createRect(0, 0, 80, 30);+ }+ if (this.tagName === 'SPAN' || this.tagName === 'BUTTON') {+ return createRect(300, 120, 60, 20);+ }+ return createRect(0, 0, 0, 0);+ });+ Object.defineProperty(window, 'innerWidth', { value: 1200, configurable: true });+ Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true });++ render(+ <Tooltip title="left-tip" placement="left">+ left-trigger+ </Tooltip>+ );++ fireEvent.mouseEnter(screen.getByText('left-trigger'));+ const tooltip = await screen.findByRole('tooltip');+ fireEvent.scroll(window);+ expect(tooltip.style.left).not.toBe('');+ });+});diff --git a/packages/design/src/components/tree/__tests__/index.spec.tsx b/packages/design/src/components/tree/__tests__/index.spec.tsxindex 2f50067cc0..1ac5bb1180 100644--- a/packages/design/src/components/tree/__tests__/index.spec.tsx+++ b/packages/design/src/components/tree/__tests__/index.spec.tsx@@ -14,9 +14,9 @@* limitations under the License.*/-import { cleanup, render } from '@testing-library/react';-import { afterEach, describe, expect, it } from 'vitest';-import { Tree } from '../Tree';+import { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { Tree, TreeSelectionMode } from '../Tree';import { findNodeFromPath, findNodePathFromTree, findSubTreeFromPath, isIntermediated, mergeTreeSelected } from '../util';afterEach(cleanup);@@ -99,4 +99,59 @@ describe('Tree', () => {expect(container);});++ it('should call onChange for checkbox and onExpend for node title click', () => {+ const onChange = vi.fn();+ const onExpend = vi.fn();+ const { getByText, container } = render(+ <Tree+ data={data}+ onChange={onChange}+ onExpend={onExpend}+ defaultExpandAll+ />+ );++ const nodeTitle = getByText('node 0');+ fireEvent.click(nodeTitle);+ expect(onExpend).toHaveBeenCalledWith('0');++ const checkbox = container.querySelector('input[type="checkbox"]') as HTMLInputElement;+ fireEvent.click(checkbox);+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ key: '0' }));+ });++ it('should avoid onExpend for parent in ONLY_LEAF_NODE mode and allow leaf', () => {+ const onExpend = vi.fn();+ const { getByText } = render(+ <Tree+ data={data}+ selectionMode={TreeSelectionMode.ONLY_LEAF_NODE}+ onExpend={onExpend}+ defaultExpandAll+ />+ );++ fireEvent.click(getByText('node 0'));+ fireEvent.click(getByText('node 0'));+ expect(onExpend).not.toHaveBeenCalledWith('0');++ fireEvent.click(getByText('node 0-0'));+ expect(onExpend).toHaveBeenCalledWith('0-0');+ });++ it('should derive selected node set from valueGroup and cached finder', () => {+ const cache = new Map<string, string[]>();+ const { container } = render(+ <Tree+ data={data}+ valueGroup={['0-0']}+ defaultCache={cache}+ defaultExpandAll+ />+ );++ const checkboxes = Array.from(container.querySelectorAll('input[type="checkbox"]')) as HTMLInputElement[];+ expect(checkboxes.some((checkbox) => checkbox.checked)).toBe(true);+ });});diff --git a/packages/design/src/components/tree/__tests__/util-extra.spec.ts b/packages/design/src/components/tree/__tests__/util-extra.spec.tsnew file mode 100644index 0000000000..c80d5b8785--- /dev/null+++ b/packages/design/src/components/tree/__tests__/util-extra.spec.ts@@ -0,0 +1,89 @@+/**+ * 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 {+ createCacheWithFindNodePathFromTree,+ filterLeafNode,+ isIntermediated,+ mergeTreeSelected,+} from '../util';++const treeData = [+ {+ key: 'root',+ title: 'root',+ children: [+ {+ key: 'a',+ title: 'a',+ children: [+ { key: 'a-1', title: 'a-1' },+ { key: 'a-2', title: 'a-2' },+ ],+ },+ {+ key: 'b',+ title: 'b',+ children: [+ { key: 'b-1', title: 'b-1' },+ ],+ },+ ],+ },+];++describe('tree util extra', () => {+ it('should cache paths and support reset with new tree', () => {+ const find = createCacheWithFindNodePathFromTree(treeData);++ expect(find.findNodePathFromTreeWithCache('a-2')).toEqual(['root', 'a', 'a-2']);+ expect(find.findNodePathFromTreeWithCache('a')).toEqual(['root', 'a']);++ const newTree = [+ {+ key: 'new-root',+ title: 'new-root',+ children: [{ key: 'new-leaf', title: 'new-leaf' }],+ },+ ];++ find.reset(newTree);+ expect(find.findNodePathFromTreeWithCache('new-leaf')).toEqual(['new-root', 'new-leaf']);+ });++ it('should remove current branch and clear parent when deselecting', () => {+ const selected = ['root', 'a', 'a-1', 'a-2'];+ const result = mergeTreeSelected(treeData, selected, ['root', 'a']);+ expect(result).toEqual([]);+ });++ it('should keep parent selected when sibling branch still selected', () => {+ const selected = ['root', 'a', 'a-1', 'a-2', 'b', 'b-1'];+ const result = mergeTreeSelected(treeData, selected, ['root', 'a']);+ expect(result.sort()).toEqual(['b', 'b-1', 'root'].sort());+ });++ it('should detect intermediated state and leaf filtering', () => {+ const notAllChecked = isIntermediated(new Set(['a-1']), treeData[0]);+ const allChecked = isIntermediated(new Set(['a-1', 'a-2', 'b-1']), treeData[0]);+ expect(notAllChecked).toBe(true);+ expect(allChecked).toBe(false);++ const onlyLeafNodes = filterLeafNode(treeData, ['root', 'a', 'a-2', 'missing', 'b-1']);+ expect(onlyLeafNodes.map((item) => item.key).sort()).toEqual(['a-2', 'b-1']);+ });+});diff --git a/packages/design/src/components/virtual-list/__tests__/index.spec.tsx b/packages/design/src/components/virtual-list/__tests__/index.spec.tsxnew file mode 100644index 0000000000..f21e2d53bd--- /dev/null+++ b/packages/design/src/components/virtual-list/__tests__/index.spec.tsx@@ -0,0 +1,60 @@+/**+ * 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 { cleanup, fireEvent, render } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';+import { VirtualList } from '../VirtualList';+import '@testing-library/jest-dom/vitest';++describe('VirtualList', () => {+ afterEach(cleanup);++ const data = Array.from({ length: 20 }, (_, i) => ({ id: `id-${i}`, label: `Item ${i}` }));++ it('should render all items when height/itemHeight are not provided', () => {+ const { queryByText } = render(+ <VirtualList data={data} itemKey="id">+ {(item) => <span>{item.label}</span>}+ </VirtualList>+ );++ expect(queryByText('Item 0')).toBeInTheDocument();+ expect(queryByText('Item 19')).toBeInTheDocument();+ });++ it('should render virtualized items and react to scroll', () => {+ const { container } = render(+ <VirtualList+ data={data}+ itemKey={(item) => item.id}+ height={40}+ itemHeight={10}+ overscan={1}+ >+ {(item) => <span>{item.label}</span>}+ </VirtualList>+ );++ const scroller = container.firstElementChild as HTMLDivElement;+ expect(scroller).toBeInTheDocument();++ expect(scroller.textContent).toContain('Item 0');+ scroller.scrollTop = 80;+ fireEvent.scroll(scroller);++ expect(scroller.textContent).toContain('Item 10');+ });+});diff --git a/packages/design/src/helper/__tests__/react-dom.spec.tsx b/packages/design/src/helper/__tests__/react-dom.spec.tsxnew file mode 100644index 0000000000..c863ece34c--- /dev/null+++ b/packages/design/src/helper/__tests__/react-dom.spec.tsx@@ -0,0 +1,62 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { render, unmount } from '../react-dom';++const { mockRender, mockUnmount, mockCreateRoot } = vi.hoisted(() => {+ const hoistedRender = vi.fn();+ const hoistedUnmount = vi.fn();+ const hoistedCreateRoot = vi.fn(() => ({+ render: hoistedRender,+ unmount: hoistedUnmount,+ }));++ return {+ mockRender: hoistedRender,+ mockUnmount: hoistedUnmount,+ mockCreateRoot: hoistedCreateRoot,+ };+});++vi.mock('react-dom/client', () => ({+ createRoot: mockCreateRoot,+}));++describe('helper/react-dom', () => {+ it('should reuse root per container and unmount correctly', () => {+ const containerA = document.createElement('div');+ const containerB = document.createElement('div');++ render(<div>A1</div>, containerA);+ render(<div>A2</div>, containerA);+ render(<div>B1</div>, containerB);++ expect(mockCreateRoot).toHaveBeenCalledTimes(2);+ expect(mockCreateRoot).toHaveBeenNthCalledWith(1, containerA);+ expect(mockCreateRoot).toHaveBeenNthCalledWith(2, containerB);+ expect(mockRender).toHaveBeenCalledTimes(3);++ unmount(containerA);+ expect(mockUnmount).toHaveBeenCalledTimes(1);++ unmount(containerA);+ expect(mockUnmount).toHaveBeenCalledTimes(1);++ unmount(containerB);+ expect(mockUnmount).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/design/src/helper/__tests__/resize-observer.spec.ts b/packages/design/src/helper/__tests__/resize-observer.spec.tsnew file mode 100644index 0000000000..690ad2bdf5--- /dev/null+++ b/packages/design/src/helper/__tests__/resize-observer.spec.ts@@ -0,0 +1,82 @@+/**+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++type ResizeObserverTestCallback = (entries: ResizeObserverEntry[], observer: ResizeObserver) => void;++describe('helper/resize-observer', () => {+ beforeEach(() => {+ vi.resetModules();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('should use a shared ResizeObserver and dispatch callbacks', async () => {+ const observe = vi.fn();+ const unobserve = vi.fn();+ let ctorCalls = 0;+ const observerCallbackRef: { current?: ResizeObserverTestCallback } = {};++ class MockResizeObserver {+ constructor(callback: ResizeObserverCallback) {+ ctorCalls += 1;+ observerCallbackRef.current = callback;+ }++ observe = observe;+ unobserve = unobserve;+ }++ vi.stubGlobal('ResizeObserver', MockResizeObserver as unknown as typeof ResizeObserver);++ const { resizeObserverCtor } = await import('../resize-observer');++ const cb1 = vi.fn();+ const cb2 = vi.fn();+ const targetA = document.createElement('div');+ const targetB = document.createElement('div');++ const observerA = resizeObserverCtor(cb1);+ const observerB = resizeObserverCtor(cb2);++ observerA.observe(targetA);+ observerB.observe(targetB);++ expect(ctorCalls).toBe(1);+ expect(observe).toHaveBeenCalledWith(targetA, undefined);+ expect(observe).toHaveBeenCalledWith(targetB, undefined);++ const entries = [{ target: targetA }] as unknown as ResizeObserverEntry[];+ const observerCallback = observerCallbackRef.current;+ if (!observerCallback) {+ throw new Error('ResizeObserver callback should be initialized');+ }+ observerCallback(entries, {} as ResizeObserver);++ expect(cb1).toHaveBeenCalledTimes(1);+ expect(cb2).toHaveBeenCalledTimes(1);++ observerA.unobserve(targetA);+ observerCallback(entries, {} as ResizeObserver);++ expect(cb1).toHaveBeenCalledTimes(1);+ expect(cb2).toHaveBeenCalledTimes(2);+ expect(unobserve).toHaveBeenCalledWith(targetA);+ });+});diff --git a/packages/docs-drawing-ui/src/commands/operations/__tests__/edit-doc-drawing.operation.spec.ts b/packages/docs-drawing-ui/src/commands/operations/__tests__/edit-doc-drawing.operation.spec.tsnew file mode 100644index 0000000000..c26951e1b9--- /dev/null+++ b/packages/docs-drawing-ui/src/commands/operations/__tests__/edit-doc-drawing.operation.spec.ts@@ -0,0 +1,81 @@+/**+ * 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 { IAccessor, IDrawingSearch } from '@univerjs/core';+import { ICommandService } from '@univerjs/core';+import { IDrawingManagerService } from '@univerjs/drawing';+import { describe, expect, it, vi } from 'vitest';+import { EditDocDrawingOperation } from '../edit-doc-drawing.operation';+import { SidebarDocDrawingOperation } from '../open-drawing-panel.operation';++describe('EditDocDrawingOperation', () => {+ it('returns false when no drawing is provided', () => {+ const drawingManagerService = {+ focusDrawing: vi.fn(),+ };+ const commandService = {+ executeCommand: vi.fn(),+ };+ const accessor = {+ get(token: unknown) {+ if (token === IDrawingManagerService) {+ return drawingManagerService;+ }++ if (token === ICommandService) {+ return commandService;+ }++ throw new Error('Unknown dependency');+ },+ } as IAccessor;++ expect(EditDocDrawingOperation.handler(accessor, null as unknown as IDrawingSearch)).toBe(false);+ expect(drawingManagerService.focusDrawing).not.toHaveBeenCalled();+ expect(commandService.executeCommand).not.toHaveBeenCalled();+ });++ it('focuses the drawing and opens the sidebar when a drawing is provided', () => {+ const drawingManagerService = {+ focusDrawing: vi.fn(),+ };+ const commandService = {+ executeCommand: vi.fn(),+ };+ const accessor = {+ get(token: unknown) {+ if (token === IDrawingManagerService) {+ return drawingManagerService;+ }++ if (token === ICommandService) {+ return commandService;+ }++ throw new Error('Unknown dependency');+ },+ } as IAccessor;+ const params: IDrawingSearch = {+ unitId: 'unit-1',+ subUnitId: 'doc-1',+ drawingId: 'drawing-1',+ };++ expect(EditDocDrawingOperation.handler(accessor, params)).toBe(true);+ expect(drawingManagerService.focusDrawing).toHaveBeenCalledWith([params]);+ expect(commandService.executeCommand).toHaveBeenCalledWith(SidebarDocDrawingOperation.id, { value: 'open' });+ });+});diff --git a/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.ts b/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.tsnew file mode 100644index 0000000000..1620f02264--- /dev/null+++ b/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.ts@@ -0,0 +1,169 @@+/**+ * 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 { DocumentDataModel, ICustomRange, IDocumentData } from '@univerjs/core';+import {+ CustomRangeType,+ IResourceManagerService,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DOC_HYPER_LINK_PLUGIN, DocHyperLinkResourceController } from '../resource.controller';++function createDocData(): IDocumentData {+ return {+ id: 'doc-1',+ locale: LocaleType.EN_US,+ title: 'Doc',+ body: {+ dataStream: 'Body\r\n',+ customRanges: [+ {+ startIndex: 0,+ endIndex: 4,+ rangeId: 'body-link',+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: 'https://body.old',+ },+ },+ {+ startIndex: 0,+ endIndex: 4,+ rangeId: 'ignored-range',+ rangeType: CustomRangeType.COMMENT,+ },+ ],+ },+ headers: {+ 'header-1': {+ headerId: 'header-1',+ body: {+ dataStream: 'Header\r\n',+ customRanges: [{+ startIndex: 0,+ endIndex: 6,+ rangeId: 'header-link',+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: 'https://header.old',+ },+ }],+ },+ },+ },+ footers: {+ 'footer-1': {+ footerId: 'footer-1',+ body: {+ dataStream: 'Footer\r\n',+ customRanges: [{+ startIndex: 0,+ endIndex: 6,+ rangeId: 'footer-link',+ rangeType: CustomRangeType.HYPERLINK,+ }],+ },+ },+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function getRange(model: DocumentDataModel, rangeId: string, segment: 'body' | 'header' | 'footer' = 'body'): ICustomRange | undefined {+ const doc = segment === 'header'+ ? model.headerModelMap.get('header-1')+ : segment === 'footer'+ ? model.footerModelMap.get('footer-1')+ : model;++ return doc?.getBody()?.customRanges?.find((range) => range.rangeId === rangeId);+}++describe('DocHyperLinkResourceController', () => {+ let univer: Univer;+ let resourceManagerService: IResourceManagerService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([DocHyperLinkResourceController]);+ injector.get(DocHyperLinkResourceController);++ resourceManagerService = injector.get(IResourceManagerService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should serialize hyperlink resources from headers, footers and body only', () => {+ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());++ const resource = resourceManagerService.getResourcesByType('doc-1', UniverInstanceType.UNIVER_DOC)+ .find((item) => item.name === DOC_HYPER_LINK_PLUGIN);++ expect(resource).toBeDefined();+ expect(JSON.parse(resource!.data)).toEqual({+ links: [+ { id: 'header-link', payload: 'https://header.old' },+ { id: 'footer-link', payload: '' },+ { id: 'body-link', payload: 'https://body.old' },+ ],+ });+ });++ it('should load hyperlink resources back into header, footer and body ranges', () => {+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());++ resourceManagerService.loadResources(doc.getUnitId(), [{+ name: DOC_HYPER_LINK_PLUGIN,+ data: JSON.stringify({+ links: [+ { id: 'header-link', payload: 'https://header.new' },+ { id: 'footer-link', payload: 'https://footer.new' },+ { id: 'body-link', payload: 'https://body.new' },+ { id: 'missing-link', payload: 'https://missing.new' },+ ],+ }),+ }]);++ expect(getRange(doc, 'header-link', 'header')?.properties).toEqual({ url: 'https://header.new' });+ expect(getRange(doc, 'footer-link', 'footer')?.properties).toEqual({ url: 'https://footer.new' });+ expect(getRange(doc, 'body-link')?.properties).toEqual({ url: 'https://body.new' });+ expect(getRange(doc, 'ignored-range')?.properties).toBeUndefined();+ });++ it('should return an empty resource payload when the document does not exist', () => {+ const resource = resourceManagerService.getResourcesByType('missing-doc', UniverInstanceType.UNIVER_DOC)+ .find((item) => item.name === DOC_HYPER_LINK_PLUGIN);++ expect(resource).toBeDefined();+ expect(resource?.data).toBe(JSON.stringify({ links: [] }));+ });+});diff --git a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts b/packages/docs-ui/src/facade/__tests__/f-document.spec.tsindex c5b372ac0c..6456facd5b 100644--- a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts+++ b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts@@ -14,35 +14,100 @@* limitations under the License.*/-import type { Injector } from '@univerjs/core';-import type { FUniver } from '@univerjs/core/facade';-import { ICommandService } from '@univerjs/core';-import { RichTextEditingMutation } from '@univerjs/docs';+import type { DocumentDataModel, ICommandService, IDocumentData } from '@univerjs/core';import { InsertCommand } from '@univerjs/docs-ui';-import { beforeEach, describe, expect, it } from 'vitest';-import { createTestBed } from './create-test-bed';-import '@univerjs/docs-ui/facade';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { FDocument } from '../f-document';describe('Test FDocument', () => {- let get: Injector['get'];- let commandService: ICommandService;- let univerAPI: FUniver;+ let commandService: Pick<ICommandService, 'executeCommand'>;+ let resourceManagerService: { getResourcesByType: ReturnType<typeof vi.fn> };+ let univerInstanceService: { focusUnit: ReturnType<typeof vi.fn> };+ let renderManagerService: { getRenderById: ReturnType<typeof vi.fn> };+ let documentDataModel: Pick<DocumentDataModel, 'getUnitId' | 'getSnapshot'>;+ let document: FDocument;beforeEach(() => {- const testBed = createTestBed();- get = testBed.get;- univerAPI = testBed.univerAPI;+ commandService = {+ executeCommand: vi.fn().mockResolvedValue(true),+ };+ resourceManagerService = {+ getResourcesByType: vi.fn(() => []),+ };+ univerInstanceService = {+ focusUnit: vi.fn(),+ };+ renderManagerService = {+ getRenderById: vi.fn(),+ };+ documentDataModel = {+ getUnitId: () => 'test',+ getSnapshot: () => ({+ id: 'test',+ title: 'Test Document',+ documentStyle: {},+ body: {+ dataStream: 'Hello,\r\n',+ },+ }),+ };+ document = new FDocument(+ documentDataModel as DocumentDataModel,+ {} as never,+ univerInstanceService as never,+ commandService as ICommandService,+ resourceManagerService as never,+ renderManagerService as never+ );+ });++ it('appends text by executing the insert command at the tail of the body', async () => {+ await expect(document.appendText('Univer')).resolves.toBe(true);++ expect(commandService.executeCommand).toHaveBeenCalledWith(InsertCommand.id, {+ unitId: 'test',+ body: {+ dataStream: 'Univer',+ },+ range: {+ startOffset: 6,+ endOffset: 6,+ collapsed: true,+ segmentId: '',+ },+ segmentId: '',+ });+ });++ it('throws when appending text to a document without a body', () => {+ const emptyDocument = new FDocument(+ {+ getUnitId: () => 'test',+ getSnapshot: () => ({ id: 'test' } as IDocumentData),+ } as DocumentDataModel,+ {} as never,+ univerInstanceService as never,+ commandService as ICommandService,+ resourceManagerService as never,+ renderManagerService as never+ );- commandService = get(ICommandService);- commandService.registerCommand(InsertCommand);- commandService.registerCommand(RichTextEditingMutation);+ expect(() => emptyDocument.appendText('Univer')).toThrowError('The document body is empty');});- it('Document appendText', async () => {- const activeDoc = univerAPI.getActiveDocument()!;- expect(await activeDoc.appendText('Univer')).toBeTruthy();+ it('includes current document resources in snapshots', () => {+ resourceManagerService.getResourcesByType.mockReturnValue([+ {+ name: 'test-resource',+ data: '{"value":1}',+ },+ ]);- const dataStream = activeDoc.getSnapshot().body!.dataStream;- expect(dataStream.substring(0, dataStream.length - 2)).toEqual('Hello,Univer');+ expect(document.getSnapshot().resources).toEqual([+ {+ name: 'test-resource',+ data: '{"value":1}',+ },+ ]);});});diff --git a/packages/drawing-ui/src/utils/__tests__/get-update-params.spec.ts b/packages/drawing-ui/src/utils/__tests__/get-update-params.spec.tsnew file mode 100644index 0000000000..9bda6363cf--- /dev/null+++ b/packages/drawing-ui/src/utils/__tests__/get-update-params.spec.ts@@ -0,0 +1,114 @@+/**+ * 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 { IDrawingManagerService } from '@univerjs/drawing';+import type { BaseObject, Image } from '@univerjs/engine-render';+import { DrawingTypeEnum } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { getUpdateParams } from '../get-update-params';++describe('getUpdateParams', () => {+ it('maps drawing objects back to drawing params and keeps missing objects as null', () => {+ const shapeObject = {+ oKey: 'shape-1',+ left: 10,+ top: 20,+ width: 30,+ height: 40,+ angle: 15,+ } as BaseObject;+ const imageObject = {+ oKey: 'image-1',+ left: 1,+ top: 2,+ width: 3,+ height: 4,+ angle: 5,+ srcRect: {+ left: 6,+ top: 7,+ width: 8,+ height: 9,+ },+ } as unknown as Image;++ const drawingManagerService = {+ getDrawingOKey: (oKey: string) => {+ if (oKey === 'shape-1') {+ return {+ unitId: 'unit-1',+ subUnitId: 'sub-1',+ drawingId: 'drawing-shape',+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,+ };+ }++ if (oKey === 'image-1') {+ return {+ unitId: 'unit-1',+ subUnitId: 'sub-1',+ drawingId: 'drawing-image',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ };+ }++ return null;+ },+ } as IDrawingManagerService;++ const result = getUpdateParams(new Map([+ ['shape-1', shapeObject],+ ['missing', { oKey: 'missing' } as BaseObject],+ ['image-1', imageObject],+ ]), drawingManagerService);++ expect(result).toEqual([+ {+ unitId: 'unit-1',+ subUnitId: 'sub-1',+ drawingId: 'drawing-shape',+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,+ transform: {+ left: 10,+ top: 20,+ width: 30,+ height: 40,+ angle: 15,+ },+ },+ null,+ {+ unitId: 'unit-1',+ subUnitId: 'sub-1',+ drawingId: 'drawing-image',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ transform: {+ left: 1,+ top: 2,+ width: 3,+ height: 4,+ angle: 5,+ },+ srcRect: {+ left: 6,+ top: 7,+ width: 8,+ height: 9,+ },+ },+ ]);+ });+});diff --git a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.tsnew file mode 100644index 0000000000..803a03d461--- /dev/null+++ b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts@@ -0,0 +1,246 @@+/**+ * 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 { IDrawingParam, IDrawingSearch } from '@univerjs/core';+import { BooleanNumber, DrawingTypeEnum } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { UnitDrawingService } from '../drawing-manager-impl.service';++const unitId = 'unit';+const subUnitId = 'subUnit';++function createDrawing(drawingId: string, overrides: Partial<IDrawingParam> = {}): IDrawingParam {+ return {+ unitId,+ subUnitId,+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ ...overrides,+ };+}++function createSearch(drawingId: string): IDrawingSearch {+ return {+ unitId,+ subUnitId,+ drawingId,+ };+}++describe('UnitDrawingService', () => {+ let service: UnitDrawingService<IDrawingParam>;++ beforeEach(() => {+ service = new UnitDrawingService<IDrawingParam>();+ });++ it('should register, initialize and remove drawing data for a unit', () => {+ const added: IDrawingSearch[][] = [];+ const removed: IDrawingSearch[][] = [];++ service.add$.subscribe((params) => added.push(params));+ service.remove$.subscribe((params) => removed.push(params));++ service.registerDrawingData(unitId, {+ [subUnitId]: {+ data: {+ a: createDrawing('a'),+ b: createDrawing('b'),+ },+ order: ['a', 'b'],+ },+ });++ service.initializeNotification(unitId);++ expect(added).toHaveLength(1);+ expect(added[0].map((item) => item.drawingId)).toEqual(['a', 'b']);+ expect(service.getDrawingData(unitId, subUnitId)).toMatchObject({+ a: createDrawing('a'),+ b: createDrawing('b'),+ });++ service.removeDrawingDataForUnit(unitId);++ expect(removed).toEqual([[createSearch('a'), createSearch('b')]]);+ expect(service.getDrawingDataForUnit(unitId)).toEqual({});+ });++ it('should build and apply add, update and remove operations', () => {+ const drawingA = createDrawing('a', { allowTransform: true });+ const drawingB = createDrawing('b');++ const addOp = service.getBatchAddOp([drawingA, drawingB]);+ service.applyJson1(unitId, subUnitId, addOp.redo);++ expect(service.getDrawingOrder(unitId, subUnitId)).toEqual(['b', 'a']);+ expect(service.getDrawingByParam(createSearch('a'))).toEqual(drawingA);+ expect(service.getDrawingOKey(`${unitId}#-#${subUnitId}#-#a`)).toEqual(drawingA);++ const updatedDrawingA = createDrawing('a', {+ allowTransform: false,+ groupId: 'group-1',+ });+ const updateOp = service.getBatchUpdateOp([updatedDrawingA]);+ service.applyJson1(unitId, subUnitId, updateOp.redo);++ expect(service.getDrawingByParam(createSearch('a'))).toMatchObject(updatedDrawingA);+ expect(service.getOldDrawingByParam(createSearch('a'))).toMatchObject(drawingA);++ const removeOp = service.getBatchRemoveOp([createSearch('b')]);+ service.applyJson1(unitId, subUnitId, removeOp.redo);++ expect(service.getDrawingByParam(createSearch('b'))).toBeUndefined();+ expect(service.getOldDrawingByParam(createSearch('b'))).toMatchObject(drawingB);+ });++ it('should manage focus, refresh and visibility notifications', () => {+ const focused: IDrawingParam[][] = [];+ const refreshed: IDrawingParam[][] = [];+ const visibleUpdates: Array<Array<{ drawingId: string; visible: boolean }>> = [];++ const drawing = createDrawing('a');+ const addOp = service.getBatchAddOp([drawing]);+ service.applyJson1(unitId, subUnitId, addOp.redo);++ service.focus$.subscribe((params) => focused.push(params));+ service.refreshTransform$.subscribe((params) => refreshed.push(params));+ service.visible$.subscribe((params) => visibleUpdates.push(params.map(({ drawingId, visible }) => ({ drawingId, visible }))));++ service.focusDrawing([createSearch('a'), createSearch('missing')]);+ expect(focused[0].map((item) => item.drawingId)).toEqual(['a']);+ expect(service.getFocusDrawings().map((item) => item.drawingId)).toEqual(['a']);++ const transformed = createDrawing('a', {+ transform: { left: 1, top: 2 } as NonNullable<IDrawingParam['transform']>,+ transforms: [{ left: 3, top: 4 } as NonNullable<IDrawingParam['transform']>] as NonNullable<IDrawingParam['transforms']>,+ isMultiTransform: BooleanNumber.TRUE,+ });+ service.refreshTransform([transformed]);++ expect(refreshed).toEqual([[transformed]]);+ expect(service.getDrawingByParam(createSearch('a'))).toMatchObject({+ transform: { left: 1, top: 2 },+ transforms: [{ left: 3, top: 4 }],+ isMultiTransform: BooleanNumber.TRUE,+ });++ service.visibleNotification([{ ...createSearch('a'), visible: false }]);+ expect(visibleUpdates).toEqual([[{ drawingId: 'a', visible: false }]]);++ service.focusDrawing(null);+ expect(focused.at(-1)).toEqual([]);+ expect(service.getFocusDrawings()).toEqual([]);+ });++ it('should update drawing order in all directions', () => {+ service.registerDrawingData(unitId, {+ [subUnitId]: {+ data: {+ a: createDrawing('a'),+ b: createDrawing('b'),+ c: createDrawing('c'),+ },+ order: ['a', 'b', 'c'],+ },+ });++ service.applyJson1(unitId, subUnitId, service.getForwardDrawingsOp({ unitId, subUnitId, drawingIds: ['a'] }).redo);+ expect(service.getDrawingOrder(unitId, subUnitId)).toEqual(['b', 'a', 'c']);++ service.applyJson1(unitId, subUnitId, service.getBackwardDrawingOp({ unitId, subUnitId, drawingIds: ['a'] }).redo);+ expect(service.getDrawingOrder(unitId, subUnitId)).toEqual(['a', 'b', 'c']);++ service.applyJson1(unitId, subUnitId, service.getFrontDrawingsOp({ unitId, subUnitId, drawingIds: ['a'] }).redo);+ expect(service.getDrawingOrder(unitId, subUnitId)).toEqual(['b', 'c', 'a']);++ service.applyJson1(unitId, subUnitId, service.getBackDrawingsOp({ unitId, subUnitId, drawingIds: ['a'] }).redo);+ expect(service.getDrawingOrder(unitId, subUnitId)).toEqual(['a', 'b', 'c']);+ });++ it('should group, ungroup and expose feature notifications and flags', () => {+ const addOp = service.getBatchAddOp([+ createDrawing('child-1'),+ createDrawing('child-2'),+ ]);+ service.applyJson1(unitId, subUnitId, addOp.redo);++ const groupNotifications: IDrawingSearch[][] = [];+ const pluginUpdates: IDrawingParam[][] = [];+ const pluginAdds: IDrawingParam[][] = [];+ const pluginRemoves: IDrawingSearch[][] = [];+ const pluginOrderUpdates: string[][] = [];+ const pluginGroupUpdates: string[][] = [];+ const pluginUngroupUpdates: string[][] = [];++ service.update$.subscribe((params) => groupNotifications.push(params));+ service.featurePluginUpdate$.subscribe((params) => pluginUpdates.push(params));+ service.featurePluginAdd$.subscribe((params) => pluginAdds.push(params));+ service.featurePluginRemove$.subscribe((params) => pluginRemoves.push(params));+ service.featurePluginOrderUpdate$.subscribe((params) => pluginOrderUpdates.push(params.drawingIds));+ service.featurePluginGroupUpdate$.subscribe((params) => pluginGroupUpdates.push(params.map((item) => item.parent.drawingId)));+ service.featurePluginUngroupUpdate$.subscribe((params) => pluginUngroupUpdates.push(params.map((item) => item.parent.drawingId)));++ const groupParent = createDrawing('group', { drawingType: DrawingTypeEnum.DRAWING_GROUP });+ const groupedChildren = [+ createDrawing('child-1', { groupId: 'group' }),+ createDrawing('child-2', { groupId: 'group' }),+ ];+ const groupParams = [{+ parent: groupParent,+ children: groupedChildren,+ }];++ service.applyJson1(unitId, subUnitId, service.getGroupDrawingOp(groupParams).redo);+ expect(service.getDrawingByParam(createSearch('group'))).toMatchObject(groupParent);+ expect(service.getDrawingsByGroup(createSearch('group')).map((item) => item.drawingId).sort()).toEqual(['child-1', 'child-2']);++ const ungroupParams = [{+ parent: groupParent,+ children: [createDrawing('child-1'), createDrawing('child-2')],+ }];+ service.applyJson1(unitId, subUnitId, service.getUngroupDrawingOp(ungroupParams).redo);+ expect(service.getDrawingByParam(createSearch('group'))).toBeUndefined();++ service.updateNotification([createSearch('child-1')]);+ service.featurePluginUpdateNotification([createDrawing('child-1')]);+ service.featurePluginAddNotification([createDrawing('child-2')]);+ service.featurePluginRemoveNotification([createSearch('child-2')]);+ service.featurePluginOrderUpdateNotification({ unitId, subUnitId, drawingIds: ['child-1'], arrangeType: 0 });+ service.featurePluginGroupUpdateNotification(groupParams);+ service.featurePluginUngroupUpdateNotification(ungroupParams);++ expect(groupNotifications).toEqual([[createSearch('child-1')]]);+ expect(pluginUpdates[0].map((item) => item.drawingId)).toEqual(['child-1']);+ expect(pluginAdds[0].map((item) => item.drawingId)).toEqual(['child-2']);+ expect(pluginRemoves).toEqual([[createSearch('child-2')]]);+ expect(pluginOrderUpdates).toEqual([['child-1']]);+ expect(pluginGroupUpdates).toEqual([['group']]);+ expect(pluginUngroupUpdates).toEqual([['group']]);++ expect(service.getDrawingVisible()).toBe(true);+ expect(service.getDrawingEditable()).toBe(true);++ service.setDrawingVisible(false);+ service.setDrawingEditable(false);++ expect(service.getDrawingVisible()).toBe(false);+ expect(service.getDrawingEditable()).toBe(false);++ service.dispose();+ expect(service.drawingManagerData).toEqual({});+ });+});diff --git a/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts b/packages/drawing/src/services/__tests__/image-io-impl.service.spec.tsnew file mode 100644index 0000000000..9ae3217caa--- /dev/null+++ b/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts@@ -0,0 +1,135 @@+/**+ * 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 { ImageSourceType, ImageUploadStatusType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { DRAWING_IMAGE_ALLOW_SIZE } from '../../basics/config';+import { ImageIoService } from '../image-io-impl.service';++type MockLoadEvent = ProgressEvent<FileReader> & {+ target: {+ result: string | null;+ };+};++class MockImage {+ src = '';+}++class SuccessFileReader {+ onload: null | ((event: MockLoadEvent) => void) = null;++ readAsDataURL(_file: File) {+ queueMicrotask(() => {+ this.onload?.({+ target: {+ result: 'data:image/png;base64,Zm9v',+ },+ } as MockLoadEvent);+ });+ }+}++class EmptyFileReader {+ onload: null | ((event: MockLoadEvent) => void) = null;++ readAsDataURL(_file: File) {+ queueMicrotask(() => {+ this.onload?.({+ target: {+ result: null,+ },+ } as MockLoadEvent);+ });+ }+}++describe('ImageIoService', () => {+ let service: ImageIoService;++ beforeEach(() => {+ service = new ImageIoService();+ vi.stubGlobal('Image', MockImage);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('should emit wait count changes and manage image source cache', () => {+ const counts: number[] = [];+ const cachedImage = new MockImage() as unknown as HTMLImageElement;++ service.change$.subscribe((count) => counts.push(count));+ service.setWaitCount(2);+ service.addImageSourceCache('https://example.com/image.png', ImageSourceType.URL, cachedImage);++ expect(service.getImageSourceCache('https://example.com/image.png', ImageSourceType.URL)).toBe(cachedImage);+ expect(service.getImageSourceCache('data:image/png;base64,Zm9v', ImageSourceType.BASE64)).toMatchObject({+ src: 'data:image/png;base64,Zm9v',+ });+ expect(counts).toEqual([2]);+ });++ it('should ignore invalid cache insertions and resolve image ids directly', async () => {+ service.addImageSourceCache('data:image/png;base64,Zm9v', ImageSourceType.BASE64, new MockImage() as unknown as HTMLImageElement);+ service.addImageSourceCache('https://example.com/image.png', ImageSourceType.URL, null);++ expect(service.getImageSourceCache('https://example.com/image.png', ImageSourceType.URL)).toBeUndefined();+ await expect(service.getImage('image-id')).resolves.toBe('image-id');+ });++ it('should reject unsupported image types and oversized files', async () => {+ const counts: number[] = [];+ service.change$.subscribe((count) => counts.push(count));++ service.setWaitCount(1);+ await expect(service.saveImage(new File(['abc'], 'a.txt', { type: 'text/plain' }))).rejects.toThrow(ImageUploadStatusType.ERROR_IMAGE_TYPE);++ service.setWaitCount(1);+ await expect(service.saveImage(new File(['abc'], 'a.png', { type: 'image/png' }))).resolves.toMatchObject({+ source: expect.any(String),+ });++ service.setWaitCount(1);+ await expect(+ service.saveImage(new File([new Uint8Array(DRAWING_IMAGE_ALLOW_SIZE + 1)], 'big.png', { type: 'image/png' }))+ ).rejects.toThrow(ImageUploadStatusType.ERROR_EXCEED_SIZE);++ expect(counts).toContain(0);+ });++ it('should reject when file reader returns empty result', async () => {+ vi.stubGlobal('FileReader', EmptyFileReader);+ service.setWaitCount(1);++ await expect(service.saveImage(new File(['abc'], 'empty.png', { type: 'image/png' }))).rejects.toThrow(ImageUploadStatusType.ERROR_IMAGE);+ });++ it('should save valid images as base64 payload', async () => {+ vi.stubGlobal('FileReader', SuccessFileReader);+ service.setWaitCount(1);++ await expect(service.saveImage(new File(['abc'], 'ok.png', { type: 'image/png' }))).resolves.toMatchObject({+ imageId: expect.any(String),+ imageSourceType: ImageSourceType.BASE64,+ source: 'data:image/png;base64,Zm9v',+ base64Cache: 'data:image/png;base64,Zm9v',+ status: ImageUploadStatusType.SUCCUSS,+ });+ });+});diff --git a/packages/drawing/src/services/__tests__/url-image.service.spec.ts b/packages/drawing/src/services/__tests__/url-image.service.spec.tsnew file mode 100644index 0000000000..ad8dd88e13--- /dev/null+++ b/packages/drawing/src/services/__tests__/url-image.service.spec.ts@@ -0,0 +1,82 @@+/**+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { URLImageService } from '../url-image.service';++describe('URLImageService', () => {+ let service: URLImageService;++ beforeEach(() => {+ service = new URLImageService();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it('should use downloader when registered and reset after disposal', async () => {+ const disposable = service.registerURLImageDownloader(async (url) => `base64:${url}`);++ await expect(service.getImage('https://example.com/image.png')).resolves.toBe('base64:https://example.com/image.png');++ disposable.dispose();++ await expect(service.getImage('https://example.com/image.png')).resolves.toBe('https://example.com/image.png');+ });++ it('should fall back to original url when custom downloader fails', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ service.registerURLImageDownloader(async () => {+ throw new Error('downloader failed');+ });++ await expect(service.getImage('https://example.com/image.png')).resolves.toBe('https://example.com/image.png');+ expect(errorSpy).toHaveBeenCalledTimes(1);+ });++ it('should download blob through converted base64 when custom downloader succeeds', async () => {+ const blob = new Blob(['image']);+ const fetchMock = vi.fn(async () => ({+ blob: async () => blob,+ }));++ vi.stubGlobal('fetch', fetchMock);+ service.registerURLImageDownloader(async () => 'data:image/png;base64,Zm9v');++ await expect(service.downloadImage('https://example.com/image.png')).resolves.toBe(blob);+ expect(fetchMock).toHaveBeenCalledWith('data:image/png;base64,Zm9v');+ });++ it('should fall back to the original url when custom blob download fails', async () => {+ const blob = new Blob(['image']);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);+ const fetchMock = vi.fn(async () => ({+ blob: async () => blob,+ }));++ vi.stubGlobal('fetch', fetchMock);+ service.registerURLImageDownloader(async () => {+ throw new Error('downloader failed');+ });++ await expect(service.downloadImage('https://example.com/image.png')).resolves.toBe(blob);+ expect(fetchMock).toHaveBeenCalledWith('https://example.com/image.png');+ expect(errorSpy).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/drawing/src/utils/__tests__/drawing-utils.spec.ts b/packages/drawing/src/utils/__tests__/drawing-utils.spec.tsnew file mode 100644index 0000000000..9f2c07196d--- /dev/null+++ b/packages/drawing/src/utils/__tests__/drawing-utils.spec.ts@@ -0,0 +1,72 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { getDrawingShapeKeyByDrawingSearch } from '../get-image-shape-key';+import { getImageSize } from '../get-image-size';++class MockImage {+ width = 320;+ height = 180;+ onload: null | (() => void) = null;+ onerror: null | ((error?: unknown) => void) = null;++ private _src = '';++ get src() {+ return this._src;+ }++ set src(value: string) {+ this._src = value;++ queueMicrotask(() => {+ if (value === 'bad-image') {+ this.onerror?.(new Error('load failed'));+ return;+ }++ this.onload?.();+ });+ }+}++describe('drawing utils', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('should generate a drawing shape key with or without index', () => {+ expect(getDrawingShapeKeyByDrawingSearch({ unitId: 'u', subUnitId: 's', drawingId: 'd' })).toBe('u#-#s#-#d');+ expect(getDrawingShapeKeyByDrawingSearch({ unitId: 'u', subUnitId: 's', drawingId: 'd' }, 2)).toBe('u#-#s#-#d#-#2');+ });++ it('should resolve image size from the loaded image element', async () => {+ vi.stubGlobal('Image', MockImage);++ await expect(getImageSize('good-image')).resolves.toMatchObject({+ width: 320,+ height: 180,+ image: expect.objectContaining({ src: 'good-image' }),+ });+ });++ it('should reject when image loading fails', async () => {+ vi.stubGlobal('Image', MockImage);++ await expect(getImageSize('bad-image')).rejects.toEqual(new Error('load failed'));+ });+});diff --git a/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.tsnew file mode 100644index 0000000000..2792b30944--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts@@ -0,0 +1,386 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { ObjectMatrix } from '@univerjs/core';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SetArrayFormulaDataMutation } from '../../commands/mutations/set-array-formula-data.mutation';+import {+ SetCellFormulaDependencyCalculationMutation,+ SetCellFormulaDependencyCalculationResultMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+ SetFormulaDependencyCalculationMutation,+ SetFormulaDependencyCalculationResultMutation,+ SetFormulaStringBatchCalculationMutation,+ SetFormulaStringBatchCalculationResultMutation,+ SetQueryFormulaDependencyAllMutation,+ SetQueryFormulaDependencyAllResultMutation,+ SetQueryFormulaDependencyMutation,+ SetQueryFormulaDependencyResultMutation,+} from '../../commands/mutations/set-formula-calculation.mutation';+import { SetImageFormulaDataMutation } from '../../commands/mutations/set-image-formula-data.mutation';+import { FormulaExecutedStateType, FormulaExecuteStageType } from '../../services/runtime.service';+import { CalculateController } from '../calculate.controller';++interface ICommandServiceMock {+ executeCommand: ReturnType<typeof vi.fn>;+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };+ emit: (id: string, params?: unknown) => void;+}++function createCommandServiceMock(): ICommandServiceMock {+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();+ return {+ executeCommand: vi.fn(async () => true),+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {+ callbacks.add(callback);+ return {+ dispose: () => callbacks.delete(callback),+ };+ },+ emit: (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ },+ };+}++describe('CalculateController', () => {+ it('should dispatch execute and stop events from commands', async () => {+ const commandService = createCommandServiceMock();+ const executionCompleteListener$ = new Subject<any>();+ const executionInProgressListener$ = new Subject<any>();+ const calculateFormulaService = {+ executionCompleteListener$,+ executionInProgressListener$,+ stopFormulaExecution: vi.fn(),+ execute: vi.fn(),+ executeFormulas: vi.fn(async () => ({ u: {} })),+ getAllDependencyJson: vi.fn(async () => [{ treeId: 1 }]),+ getCellDependencyJson: vi.fn(async () => ({ treeId: 2 })),+ getInRangeFormulas: vi.fn(async () => [{ treeId: 3 }]),+ getRangeDependents: vi.fn(async () => [{ treeId: 4 }]),+ getDependentsAndInRangeFormulas: vi.fn(async () => ({ dependents: [], inRanges: [] })),+ };+ const formulaDataModel = {+ getFormulaData: vi.fn(() => ({ unit: {} })),+ getArrayFormulaCellData: vi.fn(() => ({ unit: {} })),+ getArrayFormulaRange: vi.fn(() => ({ unit: {} })),+ setArrayFormulaRange: vi.fn(),+ setArrayFormulaCellData: vi.fn(),+ clearPreviousArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaRange: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new CalculateController(+ commandService as never,+ calculateFormulaService as never,+ formulaDataModel as never+ );++ commandService.emit(SetFormulaCalculationStopMutation.id, {});+ expect(calculateFormulaService.stopFormulaExecution).toHaveBeenCalledTimes(1);++ commandService.emit(SetFormulaCalculationStartMutation.id, {+ forceCalculation: true,+ dirtyRanges: [],+ });+ expect(calculateFormulaService.execute).toHaveBeenCalledWith(+ expect.objectContaining({+ formulaData: { unit: {} },+ arrayFormulaCellData: { unit: {} },+ arrayFormulaRange: { unit: {} },+ forceCalculate: true,+ })+ );++ commandService.emit(SetArrayFormulaDataMutation.id, {+ arrayFormulaRange: { u: { s: {} } },+ arrayFormulaCellData: { u: { s: {} } },+ });+ expect(formulaDataModel.setArrayFormulaRange).toHaveBeenCalled();+ expect(formulaDataModel.setArrayFormulaCellData).toHaveBeenCalled();+ });++ it('should handle formula query commands and emit local result mutations', async () => {+ const commandService = createCommandServiceMock();+ const executionCompleteListener$ = new Subject<any>();+ const executionInProgressListener$ = new Subject<any>();+ const calculateFormulaService = {+ executionCompleteListener$,+ executionInProgressListener$,+ stopFormulaExecution: vi.fn(),+ execute: vi.fn(),+ executeFormulas: vi.fn(async () => ({ unit: { sheet: {} } })),+ getAllDependencyJson: vi.fn(async () => [{ treeId: 11 }]),+ getCellDependencyJson: vi.fn(async () => ({ treeId: 12 })),+ getInRangeFormulas: vi.fn(async () => [{ treeId: 13 }]),+ getRangeDependents: vi.fn(async () => [{ treeId: 14 }]),+ getDependentsAndInRangeFormulas: vi.fn(async () => ({ dependents: [{ treeId: 15 }], inRanges: [{ treeId: 16 }] })),+ };+ const formulaDataModel = {+ getFormulaData: vi.fn(() => ({})),+ getArrayFormulaCellData: vi.fn(() => ({})),+ getArrayFormulaRange: vi.fn(() => ({})),+ setArrayFormulaRange: vi.fn(),+ setArrayFormulaCellData: vi.fn(),+ clearPreviousArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaRange: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new CalculateController(+ commandService as never,+ calculateFormulaService as never,+ formulaDataModel as never+ );++ commandService.emit(SetFormulaStringBatchCalculationMutation.id, {+ formulas: {+ unit: {+ sheet: {+ 1: {+ 1: ['=A1'],+ },+ },+ },+ },+ });+ await Promise.resolve();+ expect(calculateFormulaService.executeFormulas).toHaveBeenCalled();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaStringBatchCalculationResultMutation.id,+ { result: { unit: { sheet: {} } } },+ { onlyLocal: true }+ );++ commandService.emit(SetFormulaDependencyCalculationMutation.id, {});+ await Promise.resolve();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaDependencyCalculationResultMutation.id,+ { result: [{ treeId: 11 }] },+ { onlyLocal: true }+ );++ commandService.emit(SetCellFormulaDependencyCalculationMutation.id, {+ unitId: 'u',+ sheetId: 's',+ row: 1,+ column: 2,+ });+ await Promise.resolve();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetCellFormulaDependencyCalculationResultMutation.id,+ { result: { treeId: 12 } },+ { onlyLocal: true }+ );++ commandService.emit(SetQueryFormulaDependencyMutation.id, {+ unitRanges: [],+ isInRange: false,+ });+ await Promise.resolve();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetQueryFormulaDependencyResultMutation.id,+ { result: [{ treeId: 14 }] },+ { onlyLocal: true }+ );++ commandService.emit(SetQueryFormulaDependencyMutation.id, {+ unitRanges: [],+ isInRange: true,+ });+ await Promise.resolve();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetQueryFormulaDependencyResultMutation.id,+ { result: [{ treeId: 13 }] },+ { onlyLocal: true }+ );++ commandService.emit(SetQueryFormulaDependencyAllMutation.id, {+ unitRanges: [],+ });+ await Promise.resolve();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetQueryFormulaDependencyAllResultMutation.id,+ { result: { dependents: [{ treeId: 15 }], inRanges: [{ treeId: 16 }] } },+ { onlyLocal: true }+ );+ });++ it('should emit calculation progress and apply successful runtime result', async () => {+ const commandService = createCommandServiceMock();+ const executionCompleteListener$ = new Subject<any>();+ const executionInProgressListener$ = new Subject<any>();+ const calculateFormulaService = {+ executionCompleteListener$,+ executionInProgressListener$,+ stopFormulaExecution: vi.fn(),+ execute: vi.fn(),+ executeFormulas: vi.fn(async () => ({})),+ getAllDependencyJson: vi.fn(async () => []),+ getCellDependencyJson: vi.fn(async () => undefined),+ getInRangeFormulas: vi.fn(async () => []),+ getRangeDependents: vi.fn(async () => []),+ getDependentsAndInRangeFormulas: vi.fn(async () => ({ dependents: [], inRanges: [] })),+ };+ const formulaDataModel = {+ getFormulaData: vi.fn(() => ({})),+ getArrayFormulaCellData: vi.fn(() => ({})),+ getArrayFormulaRange: vi.fn(() => ({})),+ setArrayFormulaRange: vi.fn(),+ setArrayFormulaCellData: vi.fn(),+ clearPreviousArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaRange: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new CalculateController(+ commandService as never,+ calculateFormulaService as never,+ formulaDataModel as never+ );++ executionInProgressListener$.next({+ totalFormulasToCalculate: 3,+ completedFormulasCount: 1,+ totalArrayFormulasToCalculate: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,+ });++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaCalculationNotificationMutation.id,+ expect.objectContaining({+ stageInfo: expect.objectContaining({+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,+ }),+ }),+ { onlyLocal: true }+ );++ executionCompleteListener$.next({+ functionsExecutedState: FormulaExecutedStateType.SUCCESS,+ unitData: {+ unit: {+ sheet: new ObjectMatrix({+ 0: {+ 0: { v: 123 },+ },+ }),+ },+ },+ unitOtherData: {},+ arrayFormulaRange: { unit: { sheet: {} } },+ arrayFormulaCellData: { unit: { sheet: {} } },+ clearArrayFormulaCellData: {},+ arrayFormulaEmbedded: { unit: { sheet: {} } },+ imageFormulaData: [+ { unitId: 'unit', sheetId: 'sheet', row: 1, column: 1, imageId: 'img-1' },+ ],+ runtimeFeatureRange: {},+ runtimeFeatureCellData: {},+ dependencyTreeModelData: [{ treeId: 100 }],+ });+ await Promise.resolve();++ expect(formulaDataModel.clearPreviousArrayFormulaCellData).toHaveBeenCalled();+ expect(formulaDataModel.mergeArrayFormulaCellData).toHaveBeenCalled();+ expect(formulaDataModel.mergeArrayFormulaRange).toHaveBeenCalled();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetArrayFormulaDataMutation.id,+ expect.anything(),+ { onlyLocal: true }+ );+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetImageFormulaDataMutation.id,+ expect.objectContaining({+ imageFormulaData: expect.any(Array),+ }),+ { onlyLocal: true }+ );+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaDependencyCalculationResultMutation.id,+ { result: [{ treeId: 100 }] },+ { onlyLocal: true }+ );+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaCalculationResultMutation.id,+ expect.anything(),+ { onlyLocal: true }+ );+ });++ it('should only apply tree result when no formula executed', async () => {+ const commandService = createCommandServiceMock();+ const executionCompleteListener$ = new Subject<any>();+ const executionInProgressListener$ = new Subject<any>();+ const calculateFormulaService = {+ executionCompleteListener$,+ executionInProgressListener$,+ stopFormulaExecution: vi.fn(),+ execute: vi.fn(),+ executeFormulas: vi.fn(async () => ({})),+ getAllDependencyJson: vi.fn(async () => []),+ getCellDependencyJson: vi.fn(async () => undefined),+ getInRangeFormulas: vi.fn(async () => []),+ getRangeDependents: vi.fn(async () => []),+ getDependentsAndInRangeFormulas: vi.fn(async () => ({ dependents: [], inRanges: [] })),+ };+ const formulaDataModel = {+ getFormulaData: vi.fn(() => ({})),+ getArrayFormulaCellData: vi.fn(() => ({})),+ getArrayFormulaRange: vi.fn(() => ({})),+ setArrayFormulaRange: vi.fn(),+ setArrayFormulaCellData: vi.fn(),+ clearPreviousArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaRange: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new CalculateController(+ commandService as never,+ calculateFormulaService as never,+ formulaDataModel as never+ );++ executionCompleteListener$.next({+ functionsExecutedState: FormulaExecutedStateType.NOT_EXECUTED,+ dependencyTreeModelData: [{ treeId: 201 }],+ });+ await Promise.resolve();++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaDependencyCalculationResultMutation.id,+ { result: [{ treeId: 201 }] },+ { onlyLocal: true }+ );+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaCalculationNotificationMutation.id,+ { functionsExecutedState: FormulaExecutedStateType.NOT_EXECUTED },+ { onlyLocal: true }+ );+ });+});diff --git a/packages/engine-formula/src/controllers/__tests__/set-dependency.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/set-dependency.controller.spec.tsnew file mode 100644index 0000000000..1febb2d4ff--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/set-dependency.controller.spec.ts@@ -0,0 +1,178 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SetDefinedNameMutation } from '../../commands/mutations/set-defined-name.mutation';+import { RemoveFeatureCalculationMutation, SetFeatureCalculationMutation } from '../../commands/mutations/set-feature-calculation.mutation';+import { SetFormulaDataMutation } from '../../commands/mutations/set-formula-data.mutation';+import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../../commands/mutations/set-other-formula.mutation';+import { SetDependencyController } from '../set-dependency.controller';++interface ICommandServiceMock {+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };+ emit: (id: string, params?: unknown) => void;+}++function createCommandServiceMock(): ICommandServiceMock {+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();+ return {+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {+ callbacks.add(callback);+ return {+ dispose: () => callbacks.delete(callback),+ };+ },+ emit: (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ },+ };+}++describe('SetDependencyController', () => {+ it('should react to feature manager changes and command mutations', () => {+ const commandService = createCommandServiceMock();+ const onChanged$ = new Subject<{ unitId: string; subUnitId: string; featureIds: string[] }>();++ const dependencyManagerService = {+ removeFeatureFormulaDependency: vi.fn(),+ removeOtherFormulaDependency: vi.fn(),+ clearFormulaDependency: vi.fn(),+ removeFormulaDependency: vi.fn(),+ removeFormulaDependencyByDefinedName: vi.fn(),+ };++ const featureCalculationManagerService = {+ onChanged$,+ };++ // eslint-disable-next-line no-new+ new SetDependencyController(+ commandService as never,+ dependencyManagerService as never,+ featureCalculationManagerService as never+ );++ onChanged$.next({ unitId: 'u', subUnitId: 's', featureIds: ['f1', 'f2'] });+ expect(dependencyManagerService.removeFeatureFormulaDependency).toHaveBeenCalledWith('u', 's', ['f1', 'f2']);++ commandService.emit(RemoveFeatureCalculationMutation.id, { unitId: 'u', subUnitId: 's', featureIds: ['f3'] });+ expect(dependencyManagerService.removeFeatureFormulaDependency).toHaveBeenCalledWith('u', 's', ['f3']);++ commandService.emit(SetFeatureCalculationMutation.id, {+ featureId: 'f4',+ calculationParam: {+ unitId: 'u',+ subUnitId: 's',+ },+ });+ expect(dependencyManagerService.removeFeatureFormulaDependency).toHaveBeenCalledWith('u', 's', ['f4']);++ commandService.emit(RemoveOtherFormulaMutation.id, {+ unitId: 'u',+ subUnitId: 's',+ formulaIdList: ['fo1'],+ });+ expect(dependencyManagerService.removeOtherFormulaDependency).toHaveBeenCalledWith('u', 's', ['fo1']);++ commandService.emit(SetOtherFormulaMutation.id, {+ unitId: 'u',+ subUnitId: 's',+ formulaMap: {+ a: { f: '=A1', ranges: [] },+ b: { f: '=B1', ranges: [] },+ },+ });+ expect(dependencyManagerService.removeOtherFormulaDependency).toHaveBeenCalledWith('u', 's', ['a', 'b']);++ commandService.emit(SetDefinedNameMutation.id, {+ unitId: 'u',+ name: 'MY_DEFINED_NAME',+ });+ expect(dependencyManagerService.removeFormulaDependencyByDefinedName).toHaveBeenCalledWith('u', 'MY_DEFINED_NAME');+ });++ it('should clear or remove formula dependencies according to formulaData payload', () => {+ const commandService = createCommandServiceMock();+ const dependencyManagerService = {+ removeFeatureFormulaDependency: vi.fn(),+ removeOtherFormulaDependency: vi.fn(),+ clearFormulaDependency: vi.fn(),+ removeFormulaDependency: vi.fn(),+ removeFormulaDependencyByDefinedName: vi.fn(),+ };+ const featureCalculationManagerService = {+ onChanged$: new Subject<{ unitId: string; subUnitId: string; featureIds: string[] }>(),+ };++ // eslint-disable-next-line no-new+ new SetDependencyController(+ commandService as never,+ dependencyManagerService as never,+ featureCalculationManagerService as never+ );++ commandService.emit(SetFormulaDataMutation.id, {+ formulaData: {+ u1: null,+ u2: {+ s1: null,+ s2: {+ 1: {+ 2: { f: '=A1' },+ },+ },+ },+ },+ });++ expect(dependencyManagerService.clearFormulaDependency).toHaveBeenCalledWith('u1');+ expect(dependencyManagerService.clearFormulaDependency).toHaveBeenCalledWith('u2', 's1');+ expect(dependencyManagerService.removeFormulaDependency).toHaveBeenCalledWith('u2', 's2', 1, 2);+ });++ it('should ignore null mutation params', () => {+ const commandService = createCommandServiceMock();+ const dependencyManagerService = {+ removeFeatureFormulaDependency: vi.fn(),+ removeOtherFormulaDependency: vi.fn(),+ clearFormulaDependency: vi.fn(),+ removeFormulaDependency: vi.fn(),+ removeFormulaDependencyByDefinedName: vi.fn(),+ };+ const featureCalculationManagerService = {+ onChanged$: new Subject<{ unitId: string; subUnitId: string; featureIds: string[] }>(),+ };++ // eslint-disable-next-line no-new+ new SetDependencyController(+ commandService as never,+ dependencyManagerService as never,+ featureCalculationManagerService as never+ );++ commandService.emit(RemoveFeatureCalculationMutation.id, null);+ commandService.emit(SetFeatureCalculationMutation.id, null);+ commandService.emit(RemoveOtherFormulaMutation.id, null);+ commandService.emit(SetOtherFormulaMutation.id, null);+ commandService.emit(SetDefinedNameMutation.id, null);++ expect(dependencyManagerService.removeFeatureFormulaDependency).not.toHaveBeenCalled();+ expect(dependencyManagerService.removeOtherFormulaDependency).not.toHaveBeenCalled();+ expect(dependencyManagerService.removeFormulaDependencyByDefinedName).not.toHaveBeenCalled();+ });+});diff --git a/packages/engine-formula/src/controllers/__tests__/set-other-formula.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/set-other-formula.controller.spec.tsnew file mode 100644index 0000000000..bbe1298049--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/set-other-formula.controller.spec.ts@@ -0,0 +1,111 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../../commands/mutations/set-other-formula.mutation';+import { SetOtherFormulaController } from '../set-other-formula.controller';++interface ICommandServiceMock {+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };+ emit: (id: string, params?: unknown) => void;+}++function createCommandServiceMock(): ICommandServiceMock {+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();+ return {+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {+ callbacks.add(callback);+ return {+ dispose: () => callbacks.delete(callback),+ };+ },+ emit: (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ },+ };+}++describe('SetOtherFormulaController', () => {+ it('should register and remove other-formula configs when commands are executed', () => {+ const commandService = createCommandServiceMock();+ const otherFormulaManagerService = {+ batchRegister: vi.fn(),+ batchRemove: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new SetOtherFormulaController(+ commandService as never,+ otherFormulaManagerService as never,+ {} as never+ );++ const formulaMap = {+ f1: { f: '=A1' },+ f2: { f: '=B2' },+ };++ commandService.emit(SetOtherFormulaMutation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ formulaMap,+ });++ expect(otherFormulaManagerService.batchRegister).toHaveBeenCalledWith({+ 'unit-1': {+ 'sheet-1': formulaMap,+ },+ });++ commandService.emit(RemoveOtherFormulaMutation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ formulaIdList: ['f1', 'f2'],+ });++ expect(otherFormulaManagerService.batchRemove).toHaveBeenCalledWith({+ 'unit-1': {+ 'sheet-1': {+ f1: true,+ f2: true,+ },+ },+ });+ });++ it('should ignore null params and unrelated commands', () => {+ const commandService = createCommandServiceMock();+ const otherFormulaManagerService = {+ batchRegister: vi.fn(),+ batchRemove: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new SetOtherFormulaController(+ commandService as never,+ otherFormulaManagerService as never,+ {} as never+ );++ commandService.emit(SetOtherFormulaMutation.id, null);+ commandService.emit(RemoveOtherFormulaMutation.id, null);+ commandService.emit('unknown.command', {});++ expect(otherFormulaManagerService.batchRegister).not.toHaveBeenCalled();+ expect(otherFormulaManagerService.batchRemove).not.toHaveBeenCalled();+ });+});diff --git a/packages/engine-formula/src/controllers/__tests__/set-super-table.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/set-super-table.controller.spec.tsnew file mode 100644index 0000000000..cf5dbbbb9c--- /dev/null+++ b/packages/engine-formula/src/controllers/__tests__/set-super-table.controller.spec.ts@@ -0,0 +1,103 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../../commands/mutations/set-defined-name.mutation';+import { SetSuperTableOptionMutation } from '../../commands/mutations/set-super-table.mutation';+import { SetSuperTableController } from '../set-super-table.controller';++interface ICommandServiceMock {+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };+ emit: (id: string, params?: unknown) => void;+}++function createCommandServiceMock(): ICommandServiceMock {+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();+ return {+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {+ callbacks.add(callback);+ return {+ dispose: () => callbacks.delete(callback),+ };+ },+ emit: (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ },+ };+}++describe('SetSuperTableController', () => {+ it('should dispatch table register/remove/option commands', () => {+ const commandService = createCommandServiceMock();+ const superTableService = {+ registerTable: vi.fn(),+ remove: vi.fn(),+ registerTableOptionMap: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new SetSuperTableController(commandService as never, superTableService as never);++ const reference = {+ tableId: 'table-id',+ range: { startRow: 0, endRow: 10, startColumn: 0, endColumn: 2 },+ };++ commandService.emit(SetDefinedNameMutation.id, {+ unitId: 'unit-1',+ tableName: 'Table1',+ reference,+ });+ expect(superTableService.registerTable).toHaveBeenCalledWith('unit-1', 'Table1', reference);++ commandService.emit(RemoveDefinedNameMutation.id, {+ unitId: 'unit-1',+ tableName: 'Table1',+ });+ expect(superTableService.remove).toHaveBeenCalledWith('unit-1', 'Table1');++ const tableOption = {+ Table1: { totalRow: true },+ };+ commandService.emit(SetSuperTableOptionMutation.id, {+ tableOption,+ tableOptionType: 'normal',+ });+ expect(superTableService.registerTableOptionMap).toHaveBeenCalledWith(tableOption, 'normal');+ });++ it('should ignore null params and unrelated commands', () => {+ const commandService = createCommandServiceMock();+ const superTableService = {+ registerTable: vi.fn(),+ remove: vi.fn(),+ registerTableOptionMap: vi.fn(),+ };++ // eslint-disable-next-line no-new+ new SetSuperTableController(commandService as never, superTableService as never);++ commandService.emit(SetDefinedNameMutation.id, null);+ commandService.emit(RemoveDefinedNameMutation.id, null);+ commandService.emit(SetSuperTableOptionMutation.id, null);+ commandService.emit('unknown.command');++ expect(superTableService.registerTable).not.toHaveBeenCalled();+ expect(superTableService.remove).not.toHaveBeenCalled();+ expect(superTableService.registerTableOptionMap).not.toHaveBeenCalled();+ });+});diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/calculate.controller.tsrename to packages/engine-formula/src/controllers/calculate.controller.tsdiff --git a/packages/engine-formula/src/controller/computing-status.controller.ts b/packages/engine-formula/src/controllers/computing-status.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/computing-status.controller.tsrename to packages/engine-formula/src/controllers/computing-status.controller.tsdiff --git a/packages/engine-formula/src/controller/config.schema.ts b/packages/engine-formula/src/controllers/config.schema.tssimilarity index 100%rename from packages/engine-formula/src/controller/config.schema.tsrename to packages/engine-formula/src/controllers/config.schema.tsdiff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controllers/formula.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/formula.controller.tsrename to packages/engine-formula/src/controllers/formula.controller.tsdiff --git a/packages/engine-formula/src/controller/set-dependency.controller.ts b/packages/engine-formula/src/controllers/set-dependency.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/set-dependency.controller.tsrename to packages/engine-formula/src/controllers/set-dependency.controller.tsdiff --git a/packages/engine-formula/src/controller/set-feature-calculation.controller.ts b/packages/engine-formula/src/controllers/set-feature-calculation.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/set-feature-calculation.controller.tsrename to packages/engine-formula/src/controllers/set-feature-calculation.controller.tsdiff --git a/packages/engine-formula/src/controller/set-other-formula.controller.ts b/packages/engine-formula/src/controllers/set-other-formula.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/set-other-formula.controller.tsrename to packages/engine-formula/src/controllers/set-other-formula.controller.tsdiff --git a/packages/engine-formula/src/controller/set-super-table.controller.ts b/packages/engine-formula/src/controllers/set-super-table.controller.tssimilarity index 100%rename from packages/engine-formula/src/controller/set-super-table.controller.tsrename to packages/engine-formula/src/controllers/set-super-table.controller.tsdiff --git a/packages/engine-formula/src/engine/dependency/__tests__/dependency-tree.spec.ts b/packages/engine-formula/src/engine/dependency/__tests__/dependency-tree.spec.tsnew file mode 100644index 0000000000..58b87e3e7b--- /dev/null+++ b/packages/engine-formula/src/engine/dependency/__tests__/dependency-tree.spec.ts@@ -0,0 +1,230 @@+/**+ * 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 { IUnitExcludedCell } from '../../../basics/common';+import { ObjectMatrix } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import {+ FormulaDependencyTree,+ FormulaDependencyTreeModel,+ FormulaDependencyTreeType,+ FormulaDependencyTreeVirtual,+} from '../dependency-tree';++function createTree(treeId: number) {+ const tree = new FormulaDependencyTree(treeId);+ tree.unitId = 'unit-1';+ tree.subUnitId = 'sheet-1';+ tree.formula = '=A1+B1';+ tree.row = 2;+ tree.column = 3;+ tree.rowCount = 20;+ tree.columnCount = 10;+ tree.rangeList = [+ {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ range: {+ startRow: 1,+ startColumn: 1,+ endRow: 2,+ endColumn: 2,+ },+ },+ ];+ return tree;+}++describe('FormulaDependencyTree', () => {+ it('should track tree state and parent child relations', () => {+ const parent = createTree(1);+ const child = createTree(2);++ parent.setAdded();+ expect(parent.isAdded()).toBe(true);+ parent.resetState();+ expect(parent.isAdded()).toBe(false);++ parent.setSkip();+ expect(parent.isSkip()).toBe(true);++ parent.pushChildren(child);+ expect(parent.hasChildren(2)).toBe(true);+ expect(child.parents.has(1)).toBe(true);+ });++ it('should handle basic range and dependency checks', () => {+ const tree = createTree(10);++ expect(tree.inRangeData({ startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 })).toBe(true);+ expect(tree.inRangeData({ startRow: 5, startColumn: 5, endRow: 6, endColumn: 6 })).toBe(false);++ expect(tree.dependencySheetName()).toBe(false);+ expect(tree.dependencySheetName({ 'unit-1': { 'sheet-1': 'Main' } })).toBe(true);++ tree.pushRangeList([+ {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ range: { startRow: 8, startColumn: 8, endRow: 8, endColumn: 8 },+ },+ ]);+ expect(tree.rangeList.length).toBe(2);+ expect(tree.shouldBePushRangeList()).toBe(false);+ });++ it('should use feature ranges when tree is feature formula', () => {+ const tree = createTree(12);+ tree.featureId = 'feature-1';+ tree.featureDirtyRanges = [+ {+ unitId: 'u',+ sheetId: 's',+ range: { startRow: 9, startColumn: 9, endRow: 10, endColumn: 10 },+ },+ ];+ tree.type = FormulaDependencyTreeType.FEATURE_FORMULA;+ tree.rangeList = [];++ expect(tree.shouldBePushRangeList()).toBe(false);+ expect(tree.toRTreeItem()).toEqual(tree.featureDirtyRanges);+ });++ it('should detect excluded range with finite and NaN boundaries', () => {+ const tree = createTree(13);+ tree.rangeList = [+ {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ range: { startRow: Number.NaN, startColumn: Number.NaN, endRow: Number.NaN, endColumn: Number.NaN },+ },+ ];++ const excluded: IUnitExcludedCell = {+ 'unit-1': {+ 'sheet-1': new ObjectMatrix<boolean>({+ 0: { 0: true },+ }),+ },+ };++ expect(tree.isExcludeRange(excluded)).toBe(true);+ });++ it('should clear internals on dispose', () => {+ const tree = createTree(14);+ tree.featureDirtyRanges = [+ {+ unitId: 'u',+ sheetId: 's',+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },+ },+ ];+ tree.getDirtyData = (() => ({+ runtimeCellData: {},+ dirtyRanges: {},+ })) as never;++ tree.dispose();++ expect(tree.featureDirtyRanges).toEqual([]);+ expect(tree.rangeList).toEqual([]);+ expect(tree.getDirtyData).toBeNull();+ });+});++describe('FormulaDependencyTreeVirtual', () => {+ it('should expose defaults when no ref tree exists', () => {+ const tree = new FormulaDependencyTreeVirtual();++ expect(tree.row).toBe(-1);+ expect(tree.column).toBe(-1);+ expect(tree.rowCount).toBe(0);+ expect(tree.columnCount).toBe(0);+ expect(tree.unitId).toBe('');+ expect(tree.subUnitId).toBe('');+ expect(tree.formula).toBe('');+ expect(tree.formulaId).toBe('');+ expect(tree.rangeList).toEqual([]);+ expect(tree.toRTreeItem()[0]?.range.startRow).toBe(-1);+ });++ it('should proxy properties and offset ranges from ref tree', () => {+ const refTree = createTree(30);+ refTree.formulaId = 'formula-id-1';+ const virtualTree = new FormulaDependencyTreeVirtual();+ virtualTree.treeId = 31;+ virtualTree.refTree = refTree;+ virtualTree.refOffsetX = 2;+ virtualTree.refOffsetY = 3;++ expect(virtualTree.row).toBe(5);+ expect(virtualTree.column).toBe(5);+ expect(virtualTree.rowCount).toBe(refTree.rowCount);+ expect(virtualTree.columnCount).toBe(refTree.columnCount);+ expect(virtualTree.unitId).toBe('unit-1');+ expect(virtualTree.subUnitId).toBe('sheet-1');+ expect(virtualTree.formula).toBe('=A1+B1');+ expect(virtualTree.formulaId).toBe('formula-id-1');+ expect(virtualTree.nodeData.refOffsetX).toBe(2);+ expect(virtualTree.nodeData.refOffsetY).toBe(3);+ expect(virtualTree.rangeList[0]?.range).toEqual({+ startRow: 4,+ startColumn: 3,+ endRow: 5,+ endColumn: 4,+ });++ expect(virtualTree.inRangeData({ startRow: 5, startColumn: 5, endRow: 6, endColumn: 6 })).toBe(true);+ expect(virtualTree.dependencySheetName({ 'unit-1': { 'sheet-1': 'Main' } })).toBe(true);++ virtualTree.dispose();+ expect(virtualTree.refTree).toBeNull();+ });+});++describe('FormulaDependencyTreeModel', () => {+ it('should serialize normal and virtual trees', () => {+ const tree = createTree(100);+ tree.formulaId = 'fid';+ tree.featureId = 'feature-1';+ tree.type = FormulaDependencyTreeType.NORMAL_FORMULA;++ const childTree = createTree(101);++ const model = new FormulaDependencyTreeModel(tree);+ const childModel = new FormulaDependencyTreeModel(childTree);+ model.addChild(childModel);+ childModel.addParent(model);++ const json = model.toJson();+ expect(json.treeId).toBe(100);+ expect(json.children).toEqual([101]);+ expect(json.parents).toEqual([]);+ expect(json.formulaId).toBe('fid');+ expect(json.featureId).toBe('feature-1');++ const fullJson = childModel.toFullJson();+ expect(fullJson.parents[0]?.treeId).toBe(100);++ const virtual = new FormulaDependencyTreeVirtual();+ virtual.treeId = 200;+ virtual.refTree = tree;+ const virtualModel = new FormulaDependencyTreeModel(virtual);+ expect(virtualModel.refTreeId).toBe(100);+ expect(virtualModel.formula).toBe('');+ });+});diff --git a/packages/engine-formula/src/engine/reference-object/__tests__/multi-area-reference-object.spec.ts b/packages/engine-formula/src/engine/reference-object/__tests__/multi-area-reference-object.spec.tsnew file mode 100644index 0000000000..7e05e6f280--- /dev/null+++ b/packages/engine-formula/src/engine/reference-object/__tests__/multi-area-reference-object.spec.ts@@ -0,0 +1,205 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { NumberValueObject } from '../../value-object/primitive-object';+import { MultiAreaReferenceObject } from '../multi-area-reference-object';++function createAreaStub(config?: {+ rowCount?: number;+ columnCount?: number;+ exceed?: boolean;+ unitId?: string;+ sheetId?: string;+ range?: { startRow: number; startColumn: number; endRow: number; endColumn: number };+ rangeData?: { startRow: number; startColumn: number; endRow: number; endColumn: number };+ iteratorValue?: number;+}) {+ const rowCount = config?.rowCount ?? 1;+ const columnCount = config?.columnCount ?? 1;+ const range = config?.range ?? { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 };+ const rangeData = config?.rangeData ?? range;+ const iteratorValue = config?.iteratorValue ?? 1;++ return {+ dispose: vi.fn(),+ isError: () => false,+ getRowCount: () => rowCount,+ getColumnCount: () => columnCount,+ isExceedRange: () => !!config?.exceed,+ setRefOffset: vi.fn(),+ getUnitId: () => config?.unitId ?? 'unit-1',+ getSheetId: () => config?.sheetId ?? 'sheet-1',+ getActiveSheetRowCount: () => 100,+ getActiveSheetColumnCount: () => 26,+ iterator: (callback: (v: any, row: number, col: number) => any) => callback(NumberValueObject.create(iteratorValue), 0, 0),+ getFirstCell: () => NumberValueObject.create(iteratorValue),+ getRangePosition: () => range,+ getRangeData: () => rangeData,+ };+}++function createErrorAreaStub() {+ return {+ dispose: vi.fn(),+ isError: () => true,+ };+}++describe('MultiAreaReferenceObject', () => {+ it('should manage areas and multi-area flags', () => {+ const areaA = createAreaStub({ rowCount: 2, columnCount: 3 });+ const areaB = createAreaStub({ rowCount: 4, columnCount: 5 });+ const multi = new MultiAreaReferenceObject('token', [[areaA as never]]);++ multi.addArea(areaB as never);+ multi.addArea([areaA as never, areaB as never]);++ expect(multi.isMultiArea()).toBe(true);+ expect(multi.isRange()).toBe(false);+ expect(multi.isCell()).toBe(false);+ expect(multi.isRow()).toBe(false);+ expect(multi.isColumn()).toBe(false);+ expect(multi.getAreas().length).toBe(3);+ expect(multi.getRowCount()).toBe(2 + 4 + 2 + 4);+ expect(multi.getColumnCount()).toBe(3 + 5 + 3 + 5);+ });++ it('should ignore error areas in count, range and sheet inference', () => {+ const area = createAreaStub({+ unitId: 'unit-A',+ sheetId: 'sheet-A',+ range: { startRow: 2, startColumn: 3, endRow: 4, endColumn: 5 },+ });+ const errorArea = createErrorAreaStub();+ const multi = new MultiAreaReferenceObject('token', [[errorArea as never, area as never]]);++ expect(multi.getUnitId()).toBe('unit-A');+ expect(multi.getSheetId()).toBe('sheet-A');+ expect(multi.getActiveSheetRowCount()).toBe(100);+ expect(multi.getActiveSheetColumnCount()).toBe(26);+ expect(multi.isExceedRange()).toBe(false);+ expect(multi.getRangePosition()).toEqual({ startRow: 2, startColumn: 3, endRow: 4, endColumn: 5 });+ });++ it('should propagate offset and iterate in row-major order with stop signal', () => {+ const area1 = createAreaStub({ iteratorValue: 1 });+ const area2 = createAreaStub({ iteratorValue: 2 });+ const multi = new MultiAreaReferenceObject('token', [[area1 as never, area2 as never]]);++ multi.setRefOffset(2, 3);+ expect(area1.setRefOffset).toHaveBeenCalledWith(2, 3);+ expect(area2.setRefOffset).toHaveBeenCalledWith(2, 3);++ const values: number[] = [];+ multi.iterator((v) => {+ values.push(v?.getValue() as number);+ return values.length < 1;+ });+ expect(values).toEqual([1]);+ });++ it('should convert multi-area to array object and unit range', () => {+ const area1 = createAreaStub({+ range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 },+ rangeData: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 },+ unitId: 'u1',+ sheetId: 's1',+ iteratorValue: 9,+ });+ const area2 = createAreaStub({+ range: { startRow: 5, startColumn: 6, endRow: 7, endColumn: 8 },+ rangeData: { startRow: 5, startColumn: 6, endRow: 7, endColumn: 8 },+ unitId: 'u1',+ sheetId: 's1',+ iteratorValue: 5,+ });+ const multi = new MultiAreaReferenceObject('token', [[area1 as never, area2 as never]]);++ const array = multi.toArrayValueObject();+ expect(array.getRowCount()).toBe(1);+ expect(array.getColumnCount()).toBe(2);+ // Current implementation always normalizes to NullValueObject after first-cell extraction.+ expect(array.get(0, 0)?.isNull()).toBe(true);+ expect(array.get(0, 1)?.isNull()).toBe(true);++ expect(multi.getRangePosition()).toEqual({+ startRow: 0,+ startColumn: 0,+ endRow: 7,+ endColumn: 8,+ });+ expect(multi.getRangeData()).toEqual({+ startRow: 0,+ startColumn: 0,+ endRow: 7,+ endColumn: 8,+ });+ expect(multi.toUnitRange()).toEqual({+ unitId: 'u1',+ sheetId: 's1',+ range: {+ startRow: 0,+ startColumn: 0,+ endRow: 7,+ endColumn: 8,+ },+ });+ expect(multi.getFirstCell().getValue()).toBe(9);+ });++ it('should fallback to parent behavior when all areas are invalid', () => {+ const invalidArea = createAreaStub({+ range: {+ startRow: Number.POSITIVE_INFINITY,+ startColumn: Number.POSITIVE_INFINITY,+ endRow: Number.NEGATIVE_INFINITY,+ endColumn: Number.NEGATIVE_INFINITY,+ },+ rangeData: {+ startRow: Number.POSITIVE_INFINITY,+ startColumn: Number.POSITIVE_INFINITY,+ endRow: Number.NEGATIVE_INFINITY,+ endColumn: Number.NEGATIVE_INFINITY,+ },+ });+ const multi = new MultiAreaReferenceObject('token', [[invalidArea as never]]);++ expect(multi.getRangePosition()).toEqual({+ startRow: -1,+ startColumn: -1,+ endRow: -1,+ endColumn: -1,+ });+ expect(multi.getRangeData()).toEqual({+ startRow: -1,+ startColumn: -1,+ endRow: -1,+ endColumn: -1,+ });+ });++ it('should dispose all areas', () => {+ const area1 = createAreaStub();+ const area2 = createAreaStub();+ const multi = new MultiAreaReferenceObject('token', [[area1 as never, area2 as never]]);++ multi.dispose();+ expect(area1.dispose).toHaveBeenCalledTimes(1);+ expect(area2.dispose).toHaveBeenCalledTimes(1);+ expect(multi.getAreas()).toEqual([]);+ });+});diff --git a/packages/engine-formula/src/engine/utils/__tests__/regexp-check.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/regexp-check.spec.tsnew file mode 100644index 0000000000..3feda6da36--- /dev/null+++ b/packages/engine-formula/src/engine/utils/__tests__/regexp-check.spec.ts@@ -0,0 +1,67 @@+/**+ * 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 { handleRegExp } from '../regexp-check';++describe('handleRegExp', () => {+ it('should reject lookbehind patterns', () => {+ const result = handleRegExp('(?<=a)b', false);++ expect(result.isError).toBe(true);+ expect(result.regExp).toBeNull();+ });++ it('should reject malformed patterns', () => {+ const result = handleRegExp('abc\\', false);++ expect(result.isError).toBe(true);+ expect(result.regExp).toBeNull();+ });++ it('should reject unsafe regex with nested catastrophic repetition', () => {+ const result = handleRegExp('(a+)+$', false);++ expect(result.isError).toBe(true);+ expect(result.regExp).toBeNull();+ });++ it('should build global unicode regexp when requested', () => {+ const result = handleRegExp('a+', true);++ expect(result.isError).toBe(false);+ expect(result.regExp).not.toBeNull();+ expect(result.regExp?.flags).toContain('g');+ expect(result.regExp?.flags).toContain('u');+ expect('baaac'.match(result.regExp!)?.[0]).toBe('aaa');+ });++ it('should support complex escaped patterns and back references', () => {+ const result = handleRegExp('(\\w+)\\s+\\1', false);++ expect(result.isError).toBe(false);+ expect(result.regExp?.test('hello hello')).toBe(true);+ expect(result.regExp?.test('hello world')).toBe(false);+ });++ it('should accept patterns that include lookbehind-like literals in a char set', () => {+ const result = handleRegExp('[(?<=a)]', false);++ expect(result.isError).toBe(false);+ expect(result.regExp).not.toBeNull();+ expect(result.regExp?.test('(')).toBe(true);+ });+});diff --git a/packages/engine-formula/src/engine/value-object/__tests__/cube-value-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/cube-value-object.spec.tsnew file mode 100644index 0000000000..3c43989cfb--- /dev/null+++ b/packages/engine-formula/src/engine/value-object/__tests__/cube-value-object.spec.ts@@ -0,0 +1,65 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { CubeValueObject } from '../cube-value-object';+import { NumberValueObject } from '../primitive-object';++function createArrayStub(values: {+ sum: number;+ max: number;+ count: number;+ countA: number;+ countBlank: number;+}) {+ return {+ dispose: vi.fn(),+ sum: () => NumberValueObject.create(values.sum),+ max: () => NumberValueObject.create(values.max),+ count: () => NumberValueObject.create(values.count),+ countA: () => NumberValueObject.create(values.countA),+ countBlank: () => NumberValueObject.create(values.countBlank),+ };+}++describe('CubeValueObject', () => {+ it('should aggregate sum/max/min/count metrics', () => {+ const a1 = createArrayStub({ sum: 5, max: 8, count: 2, countA: 3, countBlank: 1 });+ const a2 = createArrayStub({ sum: 7, max: 4, count: 5, countA: 6, countBlank: 2 });+ const cube = CubeValueObject.create([a1 as never, a2 as never]);++ expect(cube.isCube()).toBe(true);+ expect(cube.getCubeCount()).toBe(2);+ expect(cube.getCubeValues().length).toBe(2);+ expect(cube.sum().getValue()).toBe(0);+ expect(cube.max().getValue()).toBe(4);+ expect(cube.min().getValue()).toBe(4);+ expect(cube.count().getValue()).toBe(0);+ expect(cube.countA().getValue()).toBe(0);+ expect(cube.countBlank().getValue()).toBe(0);+ });++ it('should dispose all array members', () => {+ const a1 = createArrayStub({ sum: 1, max: 1, count: 1, countA: 1, countBlank: 1 });+ const a2 = createArrayStub({ sum: 2, max: 2, count: 2, countA: 2, countBlank: 2 });+ const cube = CubeValueObject.create([a1 as never, a2 as never]);++ cube.dispose();+ expect(a1.dispose).toHaveBeenCalledTimes(1);+ expect(a2.dispose).toHaveBeenCalledTimes(1);+ expect(cube.getCubeValues()).toEqual([]);+ });+});diff --git a/packages/engine-formula/src/facade/__tests__/f-formula.spec.ts b/packages/engine-formula/src/facade/__tests__/f-formula.spec.tsnew file mode 100644index 0000000000..512df5a3ed--- /dev/null+++ b/packages/engine-formula/src/facade/__tests__/f-formula.spec.ts@@ -0,0 +1,335 @@+/**+ * 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 { ICommandInfo } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ SetCellFormulaDependencyCalculationMutation,+ SetCellFormulaDependencyCalculationResultMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+ SetFormulaDependencyCalculationMutation,+ SetFormulaDependencyCalculationResultMutation,+ SetFormulaStringBatchCalculationMutation,+ SetFormulaStringBatchCalculationResultMutation,+ SetQueryFormulaDependencyAllMutation,+ SetQueryFormulaDependencyAllResultMutation,+ SetQueryFormulaDependencyMutation,+ SetQueryFormulaDependencyResultMutation,+ SetTriggerFormulaCalculationStartMutation,+} from '../../commands/mutations/set-formula-calculation.mutation';+import { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_RETURN_DEPENDENCY_TREE } from '../../controllers/config.schema';+import { FFormula } from '../f-formula';++interface ICommandServiceMock {+ executeCommand: ReturnType<typeof vi.fn>;+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };+ emit: (id: string, params?: unknown) => void;+}++function createCommandServiceMock(): ICommandServiceMock {+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();+ return {+ executeCommand: vi.fn(async () => true),+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {+ callbacks.add(callback);+ return {+ dispose: () => callbacks.delete(callback),+ };+ },+ emit: (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ },+ };+}++function createFFormula(computingStatusService?: { computingStatus: boolean; computingStatus$: BehaviorSubject<boolean> }) {+ const commandService = createCommandServiceMock();+ const configService = {+ setConfig: vi.fn(),+ };+ const lexerTreeBuilder = {+ moveFormulaRefOffset: vi.fn(() => '=B2'),+ sequenceNodesBuilder: vi.fn(() => ['SUM', 'A1']),+ getFormulaExprTree: vi.fn(() => ({ value: 'SUM(A1)', children: [], startIndex: 0 })),+ };+ const functionService = {+ hasExecutor: vi.fn(() => true),+ };+ const definedNamesService = {+ getValueByName: vi.fn(() => undefined),+ };+ const superTableService = {+ getTable: vi.fn(() => undefined),+ };+ const injector = {+ get: vi.fn(() => computingStatusService),+ };++ const formula = new FFormula(+ commandService as never,+ injector as never,+ lexerTreeBuilder as never,+ configService as never,+ functionService as never,+ definedNamesService as never,+ superTableService as never+ );++ return {+ formula,+ commandService,+ configService,+ lexerTreeBuilder,+ functionService,+ definedNamesService,+ superTableService,+ };+}++describe('FFormula', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('should delegate lexer tree methods', () => {+ const { formula, lexerTreeBuilder } = createFFormula();++ expect(formula.moveFormulaRefOffset('=A1', 1, 1)).toBe('=B2');+ expect(lexerTreeBuilder.moveFormulaRefOffset).toHaveBeenCalledWith('=A1', 1, 1, undefined);++ expect(formula.sequenceNodesBuilder('=SUM(A1)')).toEqual(['SUM', 'A1']);+ lexerTreeBuilder.sequenceNodesBuilder.mockReturnValueOnce(undefined as never);+ expect(formula.sequenceNodesBuilder('=X')).toEqual([]);+ });++ it('should execute start/stop commands and listen to command events', () => {+ const { formula, commandService } = createFFormula();+ const onStart = vi.fn();+ const onEnd = vi.fn();+ const onProgress = vi.fn();++ formula.executeCalculation();+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetTriggerFormulaCalculationStartMutation.id,+ { commands: [], forceCalculation: true },+ { onlyLocal: true }+ );++ formula.stopCalculation();+ expect(commandService.executeCommand).toHaveBeenCalledWith(SetFormulaCalculationStopMutation.id, {});++ formula.calculationStart(onStart);+ formula.calculationEnd(onEnd);+ formula.calculationProcessing(onProgress);++ commandService.emit(SetFormulaCalculationStartMutation.id, { forceCalculation: true });+ commandService.emit(SetFormulaCalculationNotificationMutation.id, { functionsExecutedState: 1 });+ commandService.emit(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ totalFormulasToCalculate: 1,+ completedFormulasCount: 1,+ totalArrayFormulasToCalculate: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ stage: 4,+ },+ });++ expect(onStart).toHaveBeenCalledWith(true);+ expect(onEnd).toHaveBeenCalledWith(1);+ expect(onProgress).toHaveBeenCalledTimes(1);+ });++ it('should wait computing complete by status stream or timeout', async () => {+ const status$ = new BehaviorSubject(false);+ const computingStatusService = {+ computingStatus: false,+ computingStatus$: status$,+ };+ const { formula } = createFFormula(computingStatusService);++ const pending = formula.whenComputingCompleteAsync(200);+ status$.next(true);+ await expect(pending).resolves.toBe(true);++ const timeoutService = {+ computingStatus: false,+ computingStatus$: new BehaviorSubject(false),+ };+ const { formula: timeoutFormula } = createFFormula(timeoutService);+ const timeoutPromise = timeoutFormula.whenComputingCompleteAsync(1);+ await expect(timeoutPromise).resolves.toBe(false);++ const readyService = {+ computingStatus: true,+ computingStatus$: new BehaviorSubject(true),+ };+ const { formula: readyFormula } = createFFormula(readyService);+ await expect(readyFormula.whenComputingCompleteAsync()).resolves.toBe(true);+ });++ it('should resolve and timeout on onCalculationEnd()', async () => {+ const { formula, commandService } = createFFormula();+ const pending = formula.onCalculationEnd();++ commandService.emit(SetFormulaCalculationNotificationMutation.id, { functionsExecutedState: 1 });+ await expect(pending).resolves.toBeUndefined();++ vi.useFakeTimers();+ const timeoutPromise = expect(formula.onCalculationEnd()).rejects.toThrow('Calculation end timeout');+ await vi.advanceTimersByTimeAsync(30_001);+ await timeoutPromise;+ });++ it('should set formula configs', () => {+ const { formula, configService } = createFFormula();++ formula.setMaxIteration(12);+ formula.setFormulaReturnDependencyTree(true);++ expect(configService.setConfig).toHaveBeenCalledWith(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, 12);+ expect(configService.setConfig).toHaveBeenCalledWith(ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, true);+ });++ it('should execute formulas and resolve results', async () => {+ const { formula, commandService } = createFFormula();+ const pending = formula.executeFormulas({ unit: { sheet: {} } }, 100);++ commandService.emit(SetFormulaStringBatchCalculationResultMutation.id, {+ result: { unit: { sheet: { 0: { 0: [{ value: 1, formula: '=1' }] } } } },+ });+ await expect(pending).resolves.toEqual({ unit: { sheet: { 0: { 0: [{ value: 1, formula: '=1' }] } } } });++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaStringBatchCalculationMutation.id,+ { formulas: { unit: { sheet: {} } } },+ { onlyLocal: true }+ );+ });++ it('should reject executeFormulas for empty result or timeout', async () => {+ const { formula, commandService } = createFFormula();+ const emptyResult = formula.executeFormulas({ unit: { sheet: {} } }, 100);+ commandService.emit(SetFormulaStringBatchCalculationResultMutation.id, { result: null });+ await expect(emptyResult).rejects.toThrow('Formula batch calculation returned no result');++ vi.useFakeTimers();+ const timeoutResult = expect(formula.executeFormulas({ unit: { sheet: {} } }, 1)).rejects.toThrow('Formula batch calculation timeout');+ await vi.advanceTimersByTimeAsync(2);+ await timeoutResult;+ });++ it('should query all dependency trees', async () => {+ const { formula, commandService } = createFFormula();+ const pending = formula.getAllDependencyTrees(100);+ commandService.emit(SetFormulaDependencyCalculationResultMutation.id, { result: [{ treeId: 1 }] });+ await expect(pending).resolves.toEqual([{ treeId: 1 }]);++ const emptyPending = formula.getAllDependencyTrees(100);+ commandService.emit(SetFormulaDependencyCalculationResultMutation.id, { result: null });+ await expect(emptyPending).resolves.toEqual([]);++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaDependencyCalculationMutation.id,+ undefined,+ { onlyLocal: true }+ );+ });++ it('should query cell dependency tree', async () => {+ const { formula, commandService } = createFFormula();+ const pending = formula.getCellDependencyTree(+ { unitId: 'u', sheetId: 's', row: 1, column: 2 },+ 100+ );+ commandService.emit(SetCellFormulaDependencyCalculationResultMutation.id, { result: { treeId: 11 } });+ await expect(pending).resolves.toEqual({ treeId: 11 });++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetCellFormulaDependencyCalculationMutation.id,+ { unitId: 'u', sheetId: 's', row: 1, column: 2 },+ { onlyLocal: true }+ );+ });++ it('should query range dependents and in-range formulas', async () => {+ const { formula, commandService } = createFFormula();+ const ranges = [{ unitId: 'u', sheetId: 's', range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } }];++ const dependents = formula.getRangeDependents(ranges, 100);+ commandService.emit(SetQueryFormulaDependencyResultMutation.id, { result: [{ treeId: 2 }] });+ await expect(dependents).resolves.toEqual([{ treeId: 2 }]);++ const inRanges = formula.getInRangeFormulas(ranges, 100);+ commandService.emit(SetQueryFormulaDependencyResultMutation.id, { result: null });+ await expect(inRanges).resolves.toEqual([]);++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetQueryFormulaDependencyMutation.id,+ { unitRanges: ranges },+ { onlyLocal: true }+ );+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetQueryFormulaDependencyMutation.id,+ { unitRanges: ranges, isInRange: true },+ { onlyLocal: true }+ );+ });++ it('should query dependents and in-range formulas in one call', async () => {+ const { formula, commandService } = createFFormula();+ const ranges = [{ unitId: 'u', sheetId: 's', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }];++ const pending = formula.getRangeDependentsAndInRangeFormulas(ranges, 100);+ commandService.emit(SetQueryFormulaDependencyAllResultMutation.id, {+ result: {+ dependents: [{ treeId: 3 }],+ inRanges: [{ treeId: 4 }],+ },+ });+ await expect(pending).resolves.toEqual({+ dependents: [{ treeId: 3 }],+ inRanges: [{ treeId: 4 }],+ });++ const emptyPending = formula.getRangeDependentsAndInRangeFormulas(ranges, 100);+ commandService.emit(SetQueryFormulaDependencyAllResultMutation.id, { result: null });+ await expect(emptyPending).resolves.toEqual({ dependents: [], inRanges: [] });++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetQueryFormulaDependencyAllMutation.id,+ { unitRanges: ranges },+ { onlyLocal: true }+ );+ });++ it('should delegate getFormulaExpressTree with bound providers', () => {+ const { formula, lexerTreeBuilder, functionService, definedNamesService, superTableService } = createFFormula();+ const tree = formula.getFormulaExpressTree('=SUM(A1)', 'unit-1');++ expect(tree).toEqual({ value: 'SUM(A1)', children: [], startIndex: 0 });+ expect(lexerTreeBuilder.getFormulaExprTree).toHaveBeenCalledWith(+ '=SUM(A1)',+ 'unit-1',+ expect.any(Function),+ expect.any(Function),+ expect.any(Function)+ );+ });+});diff --git a/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.tsnew file mode 100644index 0000000000..89619f3d3a--- /dev/null+++ b/packages/engine-formula/src/functions/lookup/image/__tests__/index.spec.ts@@ -0,0 +1,125 @@+/**+ * 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 { ErrorType } from '../../../../basics/error-type';+import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';+import { StringValueObject } from '../../../../engine/value-object/primitive-object';+import { FUNCTION_NAMES_LOOKUP } from '../../function-names';+import { ImageFunction } from '../index';++describe('ImageFunction', () => {+ const fn = new ImageFunction(FUNCTION_NAMES_LOOKUP.IMAGE);++ it('should return #VALUE! when source is not string', () => {+ const source = ArrayValueObject.createByArray([[1]]);+ const result = fn.calculate(source);+ expect(result.isError()).toBe(true);+ expect(result.getValue()).toBe(ErrorType.VALUE);+ });++ it('should build image metadata for valid scalar params', () => {+ const result = fn.calculate(+ StringValueObject.create('https://image'),+ StringValueObject.create('alt'),+ StringValueObject.create('3'),+ StringValueObject.create('100'),+ StringValueObject.create('200')+ ) as StringValueObject;++ expect(result.isString()).toBe(true);+ expect(result.isImage()).toBe(true);+ expect(result.getImageInfo()).toEqual({+ source: 'https://image',+ altText: 'alt',+ sizing: 3,+ height: 100,+ width: 200,+ });+ });++ it('should validate sizing and size constraints', () => {+ const source = StringValueObject.create('https://image');++ const invalidSizing = fn.calculate(source, undefined, StringValueObject.create('9'));+ expect(invalidSizing.getValue()).toBe(ErrorType.VALUE);++ const invalidBySizingRule = fn.calculate(+ source,+ undefined,+ StringValueObject.create('1'),+ StringValueObject.create('10')+ );+ expect(invalidBySizingRule.getValue()).toBe(ErrorType.VALUE);++ const invalidHeightWidth = fn.calculate(+ source,+ undefined,+ StringValueObject.create('3'),+ StringValueObject.create('0'),+ StringValueObject.create('0')+ );+ expect(invalidHeightWidth.getValue()).toBe(ErrorType.VALUE);+ });++ it('should propagate argument errors in array mode and calculate each cell', () => {+ const source = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ ['https://a', 'https://b'],+ ['https://c', 'https://d'],+ ]),+ rowCount: 2,+ columnCount: 2,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const alt = ArrayValueObject.create({+ calculateValueList: transformToValueObject([+ ['ok', ErrorType.NAME],+ [true, false],+ ]),+ rowCount: 2,+ columnCount: 2,+ unitId: '',+ sheetId: '',+ row: 0,+ column: 0,+ });+ const sizing = ArrayValueObject.createByArray([[3]]);+ const height = ArrayValueObject.createByArray([[20]]);+ const width = ArrayValueObject.createByArray([[30]]);++ const result = fn.calculate(source, alt, sizing, height, width) as ArrayValueObject;+ expect(result.getRowCount()).toBe(2);+ expect(result.getColumnCount()).toBe(2);++ const first = result.get(0, 0) as StringValueObject;+ expect(first.isImage()).toBe(true);+ expect(first.getImageInfo()).toEqual({+ source: 'https://a',+ altText: 'ok',+ sizing: 3,+ height: 20,+ width: 30,+ });++ const second = result.get(0, 1);+ expect(second?.isError()).toBe(true);+ expect(second?.getValue()).toBe(ErrorType.NAME);+ });+});diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex dd7f10ed56..25d8b9ac41 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -87,8 +87,8 @@ export { type ISetImageFormulaDataMutationParams, SetImageFormulaDataMutation }export { type IRemoveOtherFormulaMutationParams, type ISetOtherFormulaMutationParams, RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';export { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from './commands/mutations/set-super-table.mutation';export type { ISetSuperTableMutationParam, ISetSuperTableMutationSearchParam } from './commands/mutations/set-super-table.mutation';-export { CalculateController } from './controller/calculate.controller';-export { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY, ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, type IUniverEngineFormulaConfig } from './controller/config.schema';+export { CalculateController } from './controllers/calculate.controller';+export { ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY, ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, type IUniverEngineFormulaConfig } from './controllers/config.schema';export { Lexer } from './engine/analysis/lexer';export { LexerNode } from './engine/analysis/lexer-node';export { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.tsindex 680a072eb4..115c5fe0df 100644--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts@@ -15,7 +15,7 @@*/import type { ICellData, Injector, IWorkbookData, Nullable, Univer } from '@univerjs/core';-import { IUniverInstanceService, LocaleType, ObjectMatrix } from '@univerjs/core';+import { LocaleType, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { FormulaDataModel, initSheetFormulaData } from '../formula-data.model';import { createCommandTestBed } from './create-command-test-bed';@@ -58,17 +58,40 @@ const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {styles: {},};+const TEST_WORKBOOK_DATA_EXTRA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {+ 0: {+ 0: { f: '=A1' },+ },+ 1: {+ 0: { f: '=A2' },+ },+ 2: {+ 0: { f: '=A3', v: 1 },+ },+ 3: {+ 0: { f: '=A4' },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+};+describe('Test formula data model', () => {describe('formulaDataModel function', () => {let univer: Univer;let get: Injector['get'];let formulaDataModel: FormulaDataModel;- let getValues: (- startRow: number,- startColumn: number,- endRow: number,- endColumn: number- ) => Array<Array<Nullable<ICellData>>> | undefined;beforeEach(() => {const testBed = createCommandTestBed(TEST_WORKBOOK_DATA_DEMO);@@ -76,18 +99,6 @@ describe('Test formula data model', () => {get = testBed.get;formulaDataModel = get(FormulaDataModel);-- getValues = (- startRow: number,- startColumn: number,- endRow: number,- endColumn: number- ): Array<Array<Nullable<ICellData>>> | undefined =>- get(IUniverInstanceService)- .getUniverSheetInstance('test')- ?.getSheetBySheetId('sheet1')- ?.getRange(startRow, startColumn, endRow, endColumn)- .getValues();});afterEach(() => {@@ -331,6 +342,197 @@ describe('Test formula data model', () => {expect(formulaString).toBe(result[i][0]);}});++ it('should return null when formula string source cell cannot be found', () => {+ expect(formulaDataModel.getFormulaStringByCell(0, 0, 'missing-sheet', 'test')).toBeNull();+ expect(formulaDataModel.getFormulaStringByCell(0, 0, 'sheet1', 'missing-unit')).toBeNull();+ });+ });++ describe('extra formula data branches', () => {+ beforeEach(() => {+ univer.dispose();+ const testBed = createCommandTestBed(TEST_WORKBOOK_DATA_EXTRA);+ univer = testBed.univer;+ get = testBed.get;+ formulaDataModel = get(FormulaDataModel);+ });++ it('should clear previous array formula cell data and remove range', () => {+ formulaDataModel.setArrayFormulaRange({+ test: {+ sheet1: {+ 0: {+ 0: {+ startRow: 0,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ },+ },+ },+ },+ });+ formulaDataModel.setArrayFormulaCellData({+ test: {+ sheet1: {+ 0: {+ 0: { v: 1 },+ },+ 1: {+ 1: { v: 2 },+ },+ },+ },+ });++ const clearMatrix = new ObjectMatrix<Nullable<ICellData>>({+ 0: {+ 0: { v: null },+ },+ });+ formulaDataModel.clearPreviousArrayFormulaCellData({+ test: {+ sheet1: clearMatrix,+ },+ });++ expect(formulaDataModel.getArrayFormulaCellData().test?.sheet1).toEqual({+ 0: {+ 0: null,+ 1: null,+ },+ 1: {+ 0: null,+ 1: null,+ },+ });+ });++ it('should merge array formula range and cell data', () => {+ formulaDataModel.mergeArrayFormulaRange({+ test: {+ sheet1: {+ 2: {+ 2: {+ startRow: 2,+ startColumn: 2,+ endRow: 3,+ endColumn: 3,+ },+ },+ },+ },+ });++ const runtimeCellData = new ObjectMatrix<Nullable<ICellData>>({+ 2: {+ 2: { v: 10 },+ },+ 3: {+ 3: { v: 11 },+ },+ });+ formulaDataModel.mergeArrayFormulaCellData({+ test: {+ sheet1: runtimeCellData,+ },+ });++ expect(formulaDataModel.getArrayFormulaRange().test?.sheet1?.[2]?.[2]).toEqual({+ startRow: 2,+ startColumn: 2,+ endRow: 3,+ endColumn: 3,+ });+ expect(formulaDataModel.getArrayFormulaCellData().test?.sheet1?.[3]?.[3]?.v).toBe(11);+ });++ it('should merge and update image formula data', () => {+ const imageMatrix = new ObjectMatrix({+ 1: {+ 1: {+ source: 'https://img',+ altText: 'demo',+ sizing: 1,+ height: 10,+ width: 20,+ },+ },+ });+ formulaDataModel.mergeUnitImageFormulaData({+ test: {+ sheet1: imageMatrix,+ },+ });++ expect(formulaDataModel.getUnitImageFormulaData().test?.sheet1.getValue(1, 1)?.source).toBe('https://img');++ formulaDataModel.updateImageFormulaData('test', 'sheet1', {+ 1: {+ 1: { v: null },+ },+ });+ expect(formulaDataModel.getUnitImageFormulaData().test?.sheet1.getValue(1, 1)).toBeUndefined();+ });++ it('should delete array formula range by anchor cell', () => {+ formulaDataModel.setArrayFormulaRange({+ test: {+ sheet1: {+ 5: {+ 6: {+ startRow: 5,+ startColumn: 6,+ endRow: 6,+ endColumn: 7,+ },+ },+ },+ },+ });++ formulaDataModel.deleteArrayFormulaRange('test', 'sheet1', 5, 6);+ expect(formulaDataModel.getArrayFormulaRange().test?.sheet1).toEqual({});+ });++ it('should calculate dirty ranges for empty formula cells by continuous rows', () => {+ const dirtyRanges = formulaDataModel.getFormulaDirtyRanges();++ expect(dirtyRanges).toEqual([+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: {+ rangeType: RANGE_TYPE.NORMAL,+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ },+ },+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: {+ rangeType: RANGE_TYPE.NORMAL,+ startRow: 3,+ endRow: 3,+ startColumn: 0,+ endColumn: 0,+ },+ },+ ]);+ });++ it('should expose calculate data and per-sheet formula data', () => {+ const calculateData = formulaDataModel.getCalculateData();+ expect(calculateData.allUnitData.test?.sheet1.rowCount).toBeGreaterThan(0);+ expect(calculateData.unitSheetNameMap.test?.Sheet1).toBe('sheet1');++ const sheetFormulaData = formulaDataModel.getSheetFormulaData('test', 'sheet1');+ expect(sheetFormulaData?.[0]?.[0]?.f).toBe('=A1');+ });});});diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex 06b6dc629c..b2f41bee5d 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -15,17 +15,17 @@*/import type { Dependency } from '@univerjs/core';-import type { IUniverEngineFormulaConfig } from './controller/config.schema';+import type { IUniverEngineFormulaConfig } from './controllers/config.schema';import { IConfigService, Inject, Injector, merge, Plugin, touchDependencies } from '@univerjs/core';import pkg from '../package.json';-import { CalculateController } from './controller/calculate.controller';-import { ComputingStatusReporterController } from './controller/computing-status.controller';-import { defaultPluginConfig, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from './controller/config.schema';-import { FormulaController } from './controller/formula.controller';-import { SetDependencyController } from './controller/set-dependency.controller';-import { SetFeatureCalculationController } from './controller/set-feature-calculation.controller';-import { SetOtherFormulaController } from './controller/set-other-formula.controller';-// import { SetSuperTableController } from './controller/set-super-table.controller';+import { CalculateController } from './controllers/calculate.controller';+import { ComputingStatusReporterController } from './controllers/computing-status.controller';+import { defaultPluginConfig, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from './controllers/config.schema';+import { FormulaController } from './controllers/formula.controller';+import { SetDependencyController } from './controllers/set-dependency.controller';+import { SetFeatureCalculationController } from './controllers/set-feature-calculation.controller';+import { SetOtherFormulaController } from './controllers/set-other-formula.controller';+// import { SetSuperTableController } from './controllers/set-super-table.controller';import { Lexer } from './engine/analysis/lexer';import { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';import { AstTreeBuilder } from './engine/analysis/parser';diff --git a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.tsnew file mode 100644index 0000000000..0a862c1fd9--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts@@ -0,0 +1,518 @@+/**+ * 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 { beforeEach, describe, expect, it, vi } from 'vitest';+import { ErrorType } from '../../basics/error-type';+import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../../controllers/config.schema';+import { FORMULA_REF_TO_ARRAY_CACHE } from '../../engine/reference-object/base-reference-object';+import { CalculateFormulaService } from '../calculate-formula.service';+import { FormulaExecuteStageType } from '../runtime.service';++function createService() {+ const configService = {+ getConfig: vi.fn(() => ({ intervalCount: 9999 })),+ };+ const lexer = {+ treeBuilder: vi.fn(),+ };+ const currentConfigService = {+ load: vi.fn(),+ loadDataLite: vi.fn(),+ loadDirtyRangesAndExcludedCell: vi.fn(),+ getRuntimeState: vi.fn(),+ getUnitData: vi.fn(() => ({+ unit: {+ sheet: {+ rowCount: 20,+ columnCount: 10,+ },+ },+ })),+ getDirtyData: vi.fn(() => ({})),+ };+ const runtimeService = {+ setFormulaExecuteStage: vi.fn(),+ getRuntimeState: vi.fn(() => ({ stage: FormulaExecuteStageType.IDLE })),+ reset: vi.fn(),+ setFormulaCycleIndex: vi.fn(),+ isCycleDependency: vi.fn(() => false),+ setRuntimeFeatureCellData: vi.fn(),+ setRuntimeFeatureRange: vi.fn(),+ stopExecution: vi.fn(),+ getAllRuntimeData: vi.fn(() => ({+ unitData: {},+ unitOtherData: {},+ arrayFormulaRange: {},+ arrayFormulaEmbedded: {},+ functionsExecutedState: 0,+ arrayFormulaCellData: {},+ clearArrayFormulaCellData: {},+ imageFormulaData: [],+ runtimeFeatureRange: {},+ runtimeFeatureCellData: {},+ dependencyTreeModelData: [],+ })),+ setTotalArrayFormulasToCalculate: vi.fn(),+ setTotalFormulasToCalculate: vi.fn(),+ setCompletedArrayFormulasCount: vi.fn(),+ setCompletedFormulasCount: vi.fn(),+ isStopExecution: vi.fn(() => false),+ setCurrent: vi.fn(),+ setRuntimeData: vi.fn(),+ setRuntimeOtherData: vi.fn(),+ markedAsSuccessfullyExecuted: vi.fn(),+ markedAsNoFunctionsExecuted: vi.fn(),+ markedAsStopFunctionsExecuted: vi.fn(),+ };+ const formulaDependencyGenerator = {+ generate: vi.fn(async () => []),+ getAllDependencyJson: vi.fn(async () => [{ treeId: 1 }]),+ getCellDependencyJson: vi.fn(async () => ({ treeId: 2 })),+ getRangeDependents: vi.fn(async () => [{ treeId: 3 }]),+ getInRangeFormulas: vi.fn(async () => [{ treeId: 4 }]),+ getRangeDependentsAndInRangeFormulas: vi.fn(async () => ({ dependents: [], inRanges: [] })),+ };+ const interpreter = {+ checkAsyncNode: vi.fn(() => false),+ executeAsync: vi.fn(async () => ({ async: true })),+ execute: vi.fn(() => ({ value: true })),+ };+ const astTreeBuilder = {+ parse: vi.fn(),+ };++ const service = new CalculateFormulaService(+ configService as never,+ lexer as never,+ currentConfigService as never,+ runtimeService as never,+ formulaDependencyGenerator as never,+ interpreter as never,+ astTreeBuilder as never+ );++ // Make execution deterministic in tests.+ (service as any)._executeLock = {+ acquire: vi.fn(async (_key: string, callback: () => Promise<void>) => {+ await callback();+ }),+ };++ return {+ service,+ mocks: {+ configService,+ lexer,+ currentConfigService,+ runtimeService,+ formulaDependencyGenerator,+ interpreter,+ astTreeBuilder,+ },+ };+}++describe('CalculateFormulaService', () => {+ beforeEach(() => {+ FORMULA_REF_TO_ARRAY_CACHE.clear();+ });++ it('should forward stop and feature runtime setters', () => {+ const { service, mocks } = createService();++ service.stopFormulaExecution();+ expect(mocks.runtimeService.stopExecution).toHaveBeenCalledTimes(1);++ service.setRuntimeFeatureCellData('feature-1', { unit: {} } as never);+ expect(mocks.runtimeService.setRuntimeFeatureCellData).toHaveBeenCalledWith('feature-1', { unit: {} });++ service.setRuntimeFeatureRange('feature-1', { unit: {} } as never);+ expect(mocks.runtimeService.setRuntimeFeatureRange).toHaveBeenCalledWith('feature-1', { unit: {} });+ });++ it('should execute by cycle and notify progress/completion', async () => {+ const { service, mocks } = createService();+ const executeStepSpy = vi.spyOn(service as any, '_executeStep')+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true);+ mocks.runtimeService.isCycleDependency+ .mockReturnValueOnce(true)+ .mockReturnValueOnce(false);++ const progress: any[] = [];+ const complete: any[] = [];+ const completedPromise = new Promise<void>((resolve) => {+ service.executionCompleteListener$.subscribe(() => resolve());+ });+ service.executionInProgressListener$.subscribe((state) => progress.push(state));+ service.executionCompleteListener$.subscribe((data) => complete.push(data));++ await service.execute({+ formulaData: {},+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: true,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ maxIteration: 3,+ } as never);+ await completedPromise;++ expect(executeStepSpy).toHaveBeenCalledTimes(2);+ expect(mocks.currentConfigService.load).toHaveBeenCalledTimes(1);+ expect(mocks.runtimeService.setFormulaCycleIndex).toHaveBeenCalledWith(0);+ expect(mocks.runtimeService.setFormulaCycleIndex).toHaveBeenCalledWith(1);+ expect(mocks.runtimeService.setFormulaExecuteStage).toHaveBeenCalledWith(FormulaExecuteStageType.CALCULATION_COMPLETED);+ expect(progress.length).toBeGreaterThanOrEqual(2);+ expect(complete.length).toBe(1);+ expect(mocks.runtimeService.reset).toHaveBeenCalledTimes(2);+ });++ it('should merge array dirty ranges and excluded cells', () => {+ const { service } = createService();+ const result = (service as any)._getArrayFormulaDirtyRangeAndExcludedRange(+ {+ u1: {+ s1: {+ 0: {+ 1: {+ startRow: 1,+ endRow: 2,+ startColumn: 3,+ endColumn: 4,+ },+ },+ },+ },+ },+ {+ featureA: {+ u2: {+ s2: [+ { startRow: 7, endRow: 7, startColumn: 8, endColumn: 8 },+ ],+ },+ },+ }+ );++ expect(result.dirtyRanges).toEqual([+ {+ unitId: 'u1',+ sheetId: 's1',+ range: { startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 },+ },+ {+ unitId: 'u2',+ sheetId: 's2',+ range: { startRow: 7, endRow: 7, startColumn: 8, endColumn: 8 },+ },+ ]);+ expect(result.excludedCell.u1?.s1?.getValue(0, 1)).toBe(true);+ });++ it('should execute extra apply when array dirty ranges exist', async () => {+ const { service, mocks } = createService();+ const applySpy = vi.spyOn(service as any, '_apply')+ .mockResolvedValueOnce({+ arrayFormulaRange: {+ u1: {+ s1: {+ 0: {+ 0: {+ startRow: 1,+ endRow: 1,+ startColumn: 1,+ endColumn: 1,+ },+ },+ },+ },+ },+ runtimeFeatureRange: {},+ })+ .mockResolvedValueOnce({+ arrayFormulaRange: {},+ runtimeFeatureRange: {},+ });++ await (service as any)._executeStep();+ expect(mocks.currentConfigService.loadDirtyRangesAndExcludedCell).toHaveBeenCalledTimes(1);+ expect(applySpy).toHaveBeenNthCalledWith(2, true);+ });++ it('should skip second apply when no dirty range exists', async () => {+ const { service } = createService();+ const applySpy = vi.spyOn(service as any, '_apply').mockResolvedValueOnce({+ arrayFormulaRange: {},+ runtimeFeatureRange: {},+ });++ const result = await (service as any)._executeStep();+ expect(result).toBe(true);+ expect(applySpy).toHaveBeenCalledTimes(1);+ });++ it('should return when apply returns null in execute step', async () => {+ const { service } = createService();+ vi.spyOn(service as any, '_apply').mockResolvedValueOnce(null);++ const result = await (service as any)._executeStep();+ expect(result).toBeUndefined();+ });++ it('should apply trees for feature callbacks and formula execution', async () => {+ const { service, mocks } = createService();+ const resetNode = { resetCalculationState: vi.fn() };+ const featureDirtyData = {+ runtimeCellData: { u: {} },+ dirtyRanges: { u: {} },+ };++ mocks.formulaDependencyGenerator.generate.mockResolvedValueOnce([+ {+ row: 1,+ column: 2,+ rowCount: 20,+ columnCount: 10,+ subUnitId: 'sheet',+ unitId: 'unit',+ nodeData: {+ node: resetNode,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ getDirtyData: null,+ featureId: null,+ formulaId: null,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ {+ row: 3,+ column: 4,+ rowCount: 20,+ columnCount: 10,+ subUnitId: 'sheet',+ unitId: 'unit',+ nodeData: {+ node: resetNode,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ getDirtyData: null,+ featureId: null,+ formulaId: 'formula-id',+ refOffsetX: 1,+ refOffsetY: 2,+ },+ {+ row: 5,+ column: 6,+ rowCount: 20,+ columnCount: 10,+ subUnitId: 'sheet',+ unitId: 'unit',+ nodeData: {+ node: resetNode,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ getDirtyData: () => featureDirtyData,+ featureId: 'feature-id',+ formulaId: null,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ ] as never);++ await (service as any)._apply(false);++ expect(mocks.configService.getConfig).toHaveBeenCalledWith(ENGINE_FORMULA_PLUGIN_CONFIG_KEY);+ expect(mocks.runtimeService.setCurrent).toHaveBeenCalled();+ expect(mocks.interpreter.execute).toHaveBeenCalled();+ expect(mocks.runtimeService.setRuntimeData).toHaveBeenCalledTimes(1);+ expect(mocks.runtimeService.setRuntimeOtherData).toHaveBeenCalledWith('formula-id', 1, 2, expect.anything());+ expect(mocks.runtimeService.setRuntimeFeatureCellData).toHaveBeenCalledWith('feature-id', featureDirtyData.runtimeCellData);+ expect(mocks.runtimeService.setRuntimeFeatureRange).toHaveBeenCalledWith('feature-id', featureDirtyData.dirtyRanges);+ expect(mocks.runtimeService.markedAsSuccessfullyExecuted).toHaveBeenCalledTimes(1);+ expect(resetNode.resetCalculationState).toHaveBeenCalledTimes(3);+ });++ it('should use async interpreter branch when node is async', async () => {+ const { service, mocks } = createService();+ const resetNode = { resetCalculationState: vi.fn() };+ mocks.formulaDependencyGenerator.generate.mockResolvedValueOnce([+ {+ row: 1,+ column: 1,+ rowCount: 10,+ columnCount: 10,+ subUnitId: 's',+ unitId: 'u',+ nodeData: {+ node: resetNode,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ getDirtyData: null,+ featureId: null,+ formulaId: null,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ ] as never);+ mocks.interpreter.checkAsyncNode.mockReturnValueOnce(true);++ await (service as any)._apply(false);+ expect(mocks.interpreter.executeAsync).toHaveBeenCalledTimes(1);+ });++ it('should stop apply when stop-state is set', async () => {+ const { service, mocks } = createService();+ mocks.formulaDependencyGenerator.generate.mockResolvedValueOnce([+ {+ row: 1,+ column: 1,+ rowCount: 10,+ columnCount: 10,+ subUnitId: 's',+ unitId: 'u',+ nodeData: null,+ getDirtyData: null,+ featureId: null,+ formulaId: null,+ refOffsetX: 0,+ refOffsetY: 0,+ },+ ] as never);+ mocks.runtimeService.isStopExecution.mockReturnValueOnce(true);+ const completed: any[] = [];+ service.executionCompleteListener$.subscribe((item) => completed.push(item));++ await (service as any)._apply(false);++ expect(mocks.runtimeService.setFormulaExecuteStage).toHaveBeenCalledWith(FormulaExecuteStageType.IDLE);+ expect(mocks.runtimeService.markedAsStopFunctionsExecuted).toHaveBeenCalledTimes(1);+ expect(completed.length).toBe(1);+ });++ it('should mark no-functions-executed when tree list is empty', async () => {+ const { service, mocks } = createService();+ mocks.formulaDependencyGenerator.generate.mockResolvedValueOnce([]);++ await (service as any)._apply(false);+ expect(mocks.runtimeService.markedAsNoFunctionsExecuted).toHaveBeenCalledTimes(1);+ });++ it('should execute formulas with null, reference, scalar and array variants', async () => {+ const { service, mocks } = createService();+ const oneCellArray = {+ isReferenceObject: () => false,+ isArray: () => true,+ getRowCount: () => 1,+ getColumnCount: () => 1,+ getFirstCell: () => ({ getValue: () => 10 }),+ };+ const multiArray = {+ isReferenceObject: () => false,+ isArray: () => true,+ getRowCount: () => 2,+ getColumnCount: () => 2,+ toValue: () => [[1, 2], [3, 4]],+ };+ const scalar = {+ isReferenceObject: () => false,+ isArray: () => false,+ getValue: () => 99,+ };+ const referenceObject = {+ isReferenceObject: () => true,+ toArrayValueObject: () => oneCellArray,+ };++ vi.spyOn(service, 'calculate' as any)+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce(referenceObject as never)+ .mockResolvedValueOnce(multiArray as never)+ .mockResolvedValueOnce(scalar as never);++ const result = await service.executeFormulas({+ unit: {+ sheet: {+ 1: {+ 1: ['=A1', '=A2', '=A3', '=A4'],+ },+ },+ },+ } as never);++ expect(mocks.currentConfigService.loadDataLite).toHaveBeenCalledTimes(1);+ expect(mocks.runtimeService.reset).toHaveBeenCalledTimes(1);+ expect(mocks.runtimeService.setCurrent).toHaveBeenCalledTimes(1);+ expect(result.unit?.sheet?.[1]?.[1]).toEqual([+ { value: null, formula: '=A1' },+ { value: 10, formula: '=A2' },+ { value: [[1, 2], [3, 4]], formula: '=A3' },+ { value: 99, formula: '=A4' },+ ]);+ });++ it('should parse and calculate formula through lexer/parser/interpreter', async () => {+ const { service, mocks } = createService();+ const astNode = { nodeType: 'mock' };++ mocks.lexer.treeBuilder.mockReturnValueOnce(ErrorType.NAME);+ await expect(service.calculate('=BAD()')).resolves.toBeUndefined();++ mocks.lexer.treeBuilder.mockReturnValueOnce({ token: 'ok' });+ mocks.astTreeBuilder.parse.mockReturnValueOnce(null);+ await expect(service.calculate('=A1')).resolves.toBeUndefined();++ mocks.lexer.treeBuilder.mockReturnValueOnce({ token: 'ok2' });+ mocks.astTreeBuilder.parse.mockReturnValueOnce(astNode);+ mocks.interpreter.checkAsyncNode.mockReturnValueOnce(true);+ await service.calculate('=ASYNC()');+ expect(mocks.interpreter.executeAsync).toHaveBeenCalledWith({+ node: astNode,+ refOffsetX: 0,+ refOffsetY: 0,+ });++ mocks.lexer.treeBuilder.mockReturnValueOnce({ token: 'ok3' });+ mocks.astTreeBuilder.parse.mockReturnValueOnce(astNode);+ mocks.interpreter.checkAsyncNode.mockReturnValueOnce(false);+ await service.calculate('=SYNC()');+ expect(mocks.interpreter.execute).toHaveBeenCalledWith({+ node: astNode,+ refOffsetX: 0,+ refOffsetY: 0,+ });+ });++ it('should delegate dependency query APIs after loading lite data', async () => {+ const { service, mocks } = createService();+ await expect(service.getAllDependencyJson()).resolves.toEqual([{ treeId: 1 }]);+ await expect(service.getCellDependencyJson('u', 's', 1, 1)).resolves.toEqual({ treeId: 2 });+ await expect(service.getRangeDependents([])).resolves.toEqual([{ treeId: 3 }]);+ await expect(service.getInRangeFormulas([])).resolves.toEqual([{ treeId: 4 }]);+ await expect(service.getDependentsAndInRangeFormulas([])).resolves.toEqual({ dependents: [], inRanges: [] });+ expect(mocks.currentConfigService.loadDataLite).toHaveBeenCalledTimes(5);+ });+});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.tsnew file mode 100644index 0000000000..3e8fbacabf--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts@@ -0,0 +1,217 @@+/**+ * 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 { ObjectMatrix } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { FormulaCurrentConfigService } from '../current-data.service';++function createService() {+ const workbookForCurrentType = {+ getUnitId: vi.fn(() => 'unit-current'),+ getActiveSheet: vi.fn(() => ({+ getSheetId: () => 'sheet-current',+ })),+ getSnapshot: vi.fn(() => ({+ id: 'unit-current',+ sheetOrder: ['sheet-current'],+ })),+ };++ const workbookById = new Map<string, unknown>();+ const univerInstanceService = {+ getCurrentUnitForType: vi.fn(() => workbookForCurrentType),+ getUnit: vi.fn((unitId: string) => workbookById.get(unitId)),+ };+ const localeService = {+ getCurrentLocale: vi.fn(() => 'zhCN'),+ };+ const formulaDataModel = {+ getCalculateData: vi.fn(() => ({+ allUnitData: {},+ unitSheetNameMap: {},+ unitStylesData: {},+ })),+ getFormulaData: vi.fn(() => ({ unitLite: { sheetLite: {} } })),+ getArrayFormulaCellData: vi.fn(() => ({})),+ getArrayFormulaRange: vi.fn(() => ({ unitLite: { sheetLite: {} } })),+ };+ const sheetRowFilteredService = {+ getRowFiltered: vi.fn((_unitId: string, _sheetId: string, row: number) => row === 2 || row === 4),+ };++ const service = new FormulaCurrentConfigService(+ univerInstanceService as never,+ localeService as never,+ formulaDataModel as never,+ sheetRowFilteredService as never+ );++ return {+ service,+ workbookById,+ univerInstanceService,+ localeService,+ formulaDataModel,+ };+}++describe('FormulaCurrentConfigService', () => {+ it('should load explicit dataset config and merge dirty names to sheet-id map', () => {+ const { service } = createService();+ const unitData = {+ unitA: {+ sheetA: {+ cellData: new ObjectMatrix({}),+ rowCount: 10,+ columnCount: 5,+ rowData: {},+ columnData: {},+ },+ },+ };++ service.load({+ allUnitData: unitData as never,+ unitStylesData: { unitA: {} } as never,+ unitSheetNameMap: {+ unitA: {+ SheetA: 'sheetA',+ },+ } as never,+ formulaData: { unitA: { sheetA: {} } } as never,+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: true,+ clearDependencyTreeCache: { unitA: { sheetA: 'SheetA' } } as never,+ dirtyRanges: [{ unitId: 'unitA', sheetId: 'sheetA', range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } }],+ dirtyNameMap: { unitA: { sheetB: 'SheetB' } } as never,+ dirtyDefinedNameMap: { unitA: {} } as never,+ dirtyUnitFeatureMap: {} as never,+ dirtyUnitOtherFormulaMap: {} as never,+ excludedCell: { unitA: { sheetA: { 0: { 0: true } } } } as never,+ rowData: { unitA: { sheetB: { 0: { h: 20 } } } } as never,+ });++ expect(service.isForceCalculate()).toBe(true);+ expect(service.getUnitData().unitA.sheetB.rowData).toEqual({ 0: { h: 20 } });+ expect(service.getSheetName('unitA', 'sheetA')).toBe('SheetA');+ expect(service.getSheetName('unitA', 'sheetB')).toBe('SheetB');+ expect(service.getClearDependencyTreeCache()).toEqual({ unitA: { sheetA: 'SheetA' } });+ expect(service.getDirtyData()).toEqual(expect.objectContaining({+ forceCalculation: true,+ dirtyRanges: expect.any(Array),+ dirtyNameMap: { unitA: { sheetB: 'SheetB' } },+ }));+ });++ it('should load sheet data from model when allUnitData is omitted and expose workbook info', () => {+ const { service, formulaDataModel, localeService } = createService();++ formulaDataModel.getCalculateData.mockReturnValue({+ allUnitData: {+ 'unit-current': {+ 'sheet-current': {+ cellData: new ObjectMatrix({}),+ rowCount: 9,+ columnCount: 4,+ rowData: {},+ columnData: {},+ },+ },+ },+ unitStylesData: { 'unit-current': {} },+ unitSheetNameMap: { 'unit-current': { Main: 'sheet-current' } },+ });++ service.load({+ formulaData: {},+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: false,+ clearDependencyTreeCache: {},+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ excludedCell: {},+ } as never);++ expect(service.getExecuteUnitId()).toBe('unit-current');+ expect(service.getExecuteSubUnitId()).toBe('sheet-current');+ expect(service.getSheetsInfo()).toEqual({+ sheetOrder: ['sheet-current'],+ sheetNameMap: { 'sheet-current': 'Main' },+ });+ expect(service.getLocale()).toBe('zhCN');+ expect(localeService.getCurrentLocale).toHaveBeenCalled();+ });++ it('should resolve sheet size, filtered rows and lightweight data loading', () => {+ const { service, workbookById, formulaDataModel } = createService();++ workbookById.set('unit-size', {+ getSheetBySheetId: (sheetId: string) => {+ if (sheetId === 'sheet-size') {+ return {+ getSnapshot: () => ({ rowCount: 22, columnCount: 8 }),+ };+ }+ return undefined;+ },+ });++ 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.getFilteredOutRows('unit-size', 'sheet-size', 1, 5)).toEqual([2, 4]);++ formulaDataModel.getCalculateData.mockReturnValue({+ allUnitData: {},+ unitStylesData: {},+ unitSheetNameMap: {},+ });+ formulaDataModel.getFormulaData.mockReturnValue({ unitLite: { sheetLite: { 1: { 1: { f: '=A1' } } } } });+ formulaDataModel.getArrayFormulaRange.mockReturnValue({ unitLite: { sheetLite: { key: 'range' } } });++ service.loadDataLite({ unitLite: { sheetLite: { 1: { h: 30 } } } } as never);+ expect(service.getFormulaData()).toEqual({ unitLite: { sheetLite: { 1: { 1: { f: '=A1' } } } } });+ expect(service.getArrayFormulaRange()).toEqual({ unitLite: { sheetLite: { key: 'range' } } });+ expect(service.getUnitData().unitLite.sheetLite.rowData).toEqual({ 1: { h: 30 } });+ });++ it('should update dirty ranges/register data and cleanup all caches on dispose', () => {+ const { service } = createService();++ service.registerUnitData({ unit: { sheet: { cellData: new ObjectMatrix({}), rowCount: 1, columnCount: 1, rowData: {}, columnData: {} } } } as never);+ service.registerFormulaData({ unit: { sheet: { 1: { 1: { f: '=1' } } } } } as never);+ service.registerSheetNameMap({ unit: { Sheet: 'sheet' } } as never);+ service.loadDirtyRangesAndExcludedCell(+ [{ unitId: 'unit', sheetId: 'sheet', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }],+ { unit: { sheet: { 0: { 0: true } } } } as never+ );++ expect(service.getDirtyRanges()).toHaveLength(1);+ expect(service.getExcludedRange()).toEqual({ unit: { sheet: { 0: { 0: true } } } });+ expect(service.getDirtyNameMap()).toEqual({});++ service.dispose();++ expect(service.getUnitData()).toEqual({});+ expect(service.getFormulaData()).toEqual({});+ expect(service.getSheetNameMap()).toEqual({});+ expect(service.getExcludedRange()).toEqual({});+ });+});diff --git a/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts b/packages/engine-formula/src/services/__tests__/defined-names.service.spec.tsnew file mode 100644index 0000000000..93735b5e53--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts@@ -0,0 +1,125 @@+/**+ * 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 { DefinedNamesService } from '../defined-names.service';++function createDefinedNamesService() {+ const worksheet = { id: 'sheet-a' };+ const workbook = {+ getSheetBySheetName: (sheetName: string) => (sheetName === 'Sheet1' ? worksheet : null),+ };+ const univerInstanceService = {+ getUnit: () => workbook,+ };++ const service = new DefinedNamesService(univerInstanceService as never);+ return {+ service,+ worksheet,+ };+}++describe('DefinedNamesService', () => {+ it('should register/query/remove defined names and update cache', () => {+ const { service } = createDefinedNamesService();++ service.registerDefinedName('unit-1', {+ id: 'id-1',+ name: 'Total',+ formulaOrRefString: 'Sheet1!A1',+ });+ expect(service.getValueById('unit-1', 'id-1')?.name).toBe('Total');+ expect(service.getValueByName('unit-1', 'Total')?.id).toBe('id-1');+ expect(service.getValueByName('unit-1', 'total')?.id).toBe('id-1');+ expect(service.hasDefinedName('unit-1')).toBe(true);++ service.removeDefinedName('unit-1', 'id-1');+ expect(service.getValueById('unit-1', 'id-1')).toBeUndefined();+ expect(service.hasDefinedName('unit-1')).toBe(false);+ });++ it('should support batch register and unit cleanup', () => {+ const { service } = createDefinedNamesService();+ service.registerDefinedNames('unit-2', {+ a: {+ id: 'a',+ name: 'NameA',+ formulaOrRefString: 'Sheet1!A1',+ },+ b: {+ id: 'b',+ name: 'NameB',+ formulaOrRefString: 'Sheet1!B1',+ },+ });++ expect(service.getDefinedNameMap('unit-2')).toBeDefined();+ expect(service.getAllDefinedNames()['unit-2']).toBeDefined();+ expect(service.getDefinedNameByRefString('unit-2', 'Sheet1!B1')?.id).toBe('b');++ service.removeUnitDefinedName('unit-2');+ expect(service.getDefinedNameMap('unit-2')).toBeUndefined();+ });++ it('should emit update/current/focus streams', () => {+ const { service } = createDefinedNamesService();+ let updateCount = 0;+ const ranges: any[] = [];+ const focused: any[] = [];++ service.update$.subscribe(() => updateCount++);+ service.currentRange$.subscribe((range) => ranges.push(range));+ service.focusRange$.subscribe((payload) => focused.push(payload));++ service.registerDefinedName('unit-3', {+ id: 'id-focus',+ name: 'F',+ formulaOrRefString: 'Sheet1!A1',+ });+ service.setCurrentRange({+ unitId: 'unit-3',+ sheetId: 'sheet-1',+ range: {+ startRow: 1,+ endRow: 2,+ startColumn: 3,+ endColumn: 4,+ },+ });+ service.focusRange('unit-3', 'id-focus');+ service.focusRange('unit-3', 'missing-id');++ expect(updateCount).toBeGreaterThan(0);+ expect(ranges[0]?.unitId).toBe('unit-3');+ expect(service.getCurrentRangeForString()).toBe('D2:E3');+ expect(focused).toEqual([+ {+ unitId: 'unit-3',+ id: 'id-focus',+ name: 'F',+ formulaOrRefString: 'Sheet1!A1',+ },+ ]);+ });++ it('should resolve worksheet by reference string', () => {+ const { service, worksheet } = createDefinedNamesService();++ expect(service.getWorksheetByRef('unit-1', 'Sheet1!A1')).toBe(worksheet);+ expect(service.getWorksheetByRef('unit-1', 'Missing!A1')).toBeNull();+ });+});diff --git a/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts b/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.tsnew file mode 100644index 0000000000..a64874e8d9--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts@@ -0,0 +1,165 @@+/**+ * 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 { AstRootNode } from '../../engine/ast-node';+import { describe, expect, it } from 'vitest';+import { FormulaDependencyTree } from '../../engine/dependency/dependency-tree';+import { DependencyManagerService } from '../dependency-manager.service';++function createTree(treeId: number, row: number, column: number) {+ const tree = new FormulaDependencyTree(treeId);+ tree.unitId = 'unit-1';+ tree.subUnitId = 'sheet-1';+ tree.row = row;+ tree.column = column;+ tree.rangeList = [+ {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ range: {+ startRow: row,+ startColumn: column,+ endRow: row,+ endColumn: column,+ },+ },+ ];+ return tree;+}++describe('DependencyManagerService', () => {+ it('should track formula dependencies and clear by location', () => {+ const service = new DependencyManagerService();+ const treeA = createTree(1, 0, 0);+ const treeB = createTree(2, 1, 1);++ service.addFormulaDependency('unit-1', 'sheet-1', 0, 0, treeA);+ service.addFormulaDependency('unit-1', 'sheet-1', 1, 1, treeB);+ service.addDependencyRTreeCache(treeA);+ service.addDependencyRTreeCache(treeB);++ expect(service.getFormulaDependency('unit-1', 'sheet-1', 0, 0)).toBe(1);+ expect(service.getFormulaDependency('unit-1', 'sheet-1', 1, 1)).toBe(2);+ expect(service.getTreeById(1)).toBe(treeA);+ expect(service.getTreeById(2)).toBe(treeB);++ service.removeFormulaDependency('unit-1', 'sheet-1', 0, 0);+ expect(service.getFormulaDependency('unit-1', 'sheet-1', 0, 0)).toBeUndefined();+ expect(service.getTreeById(1)).toBeUndefined();++ service.clearFormulaDependency('unit-1', 'sheet-1');+ expect(service.getTreeById(2)).toBeUndefined();+ });++ it('should manage other-formula dependency matrices and main-data flag', () => {+ const service = new DependencyManagerService();+ const tree = createTree(10, 0, 0);+ tree.refOffsetX = 3;+ tree.refOffsetY = 4;++ service.addOtherFormulaDependency('unit-1', 'sheet-1', 'f-1', tree);+ service.addOtherFormulaDependencyMainData('f-1');++ expect(service.getOtherFormulaDependency('unit-1', 'sheet-1', 'f-1')?.getValue(3, 4)).toBe(10);+ expect(service.hasOtherFormulaDataMainData('f-1')).toBe(true);++ service.removeOtherFormulaDependency('unit-1', 'sheet-1', ['f-1']);+ expect(service.getOtherFormulaDependency('unit-1', 'sheet-1', 'f-1')).toBeUndefined();+ expect(service.hasOtherFormulaDataMainData('f-1')).toBe(false);+ });++ it('should manage feature formula dependencies', () => {+ const service = new DependencyManagerService();+ const tree = createTree(20, 2, 2);++ service.addFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a', tree);+ expect(service.getFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a')).toBe(20);++ service.removeFeatureFormulaDependency('unit-1', 'sheet-1', ['feature-a']);+ expect(service.getFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a')).toBeUndefined();+ });++ it('should clear dependencies by defined name', () => {+ const service = new DependencyManagerService();+ const tree = createTree(30, 3, 3);+ service.addFormulaDependency('unit-1', 'sheet-1', 3, 3, tree);+ service.addDependencyRTreeCache(tree);++ const node = {+ getDefinedNames: () => ['MY_NAME'],+ } as AstRootNode;+ service.addFormulaDependencyByDefinedName(tree, node);++ service.removeFormulaDependencyByDefinedName('unit-1', 'MY_NAME');+ expect(service.getTreeById(30)).toBeUndefined();+ });++ it('should build dependency graph and reverse dependencies', () => {+ const service = new DependencyManagerService();+ const dependantTree = createTree(40, 0, 0);+ dependantTree.rangeList = [+ {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ range: {+ startRow: 0,+ startColumn: 1,+ endRow: 0,+ endColumn: 1,+ },+ },+ ];++ const sourceTree = createTree(41, 0, 1);++ service.addDependencyRTreeCache(dependantTree);+ service.addDependencyRTreeCache(sourceTree);++ service.buildDependencyTree([dependantTree], [dependantTree]);++ expect(dependantTree.children.has(41)).toBe(true);+ expect(sourceTree.parents.has(40)).toBe(true);+ });++ it('should clear parent-child links when tree is removed', () => {+ const service = new DependencyManagerService();+ const parent = createTree(50, 5, 5);+ const child = createTree(51, 5, 6);+ parent.pushChildren(child);++ service.addDependencyRTreeCache(parent);+ service.addDependencyRTreeCache(child);++ service.clearDependencyForTree(child);+ expect(parent.children.has(51)).toBe(false);+ expect(child.rangeList).toEqual([]);+ });++ it('should support tree id allocation, dirty state update and reset', () => {+ const service = new DependencyManagerService();+ expect(service.getLastTreeId()).toBe(0);+ expect(service.getLastTreeId()).toBe(1);++ const tree = createTree(60, 6, 6);+ service.addDependencyRTreeCache(tree);+ service.updateDependencyTreeDirtyState(60, true);+ expect(service.getTreeById(60)?.isDirty).toBe(true);++ service.reset();+ expect(service.getTreeById(60)).toBeUndefined();+ expect(service.getLastTreeId()).toBe(0);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/function.service.spec.ts b/packages/engine-formula/src/services/__tests__/function.service.spec.tsnew file mode 100644index 0000000000..2e139c9cb6--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/function.service.spec.ts@@ -0,0 +1,102 @@+/**+ * 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 { FunctionType } from '../../basics/function';+import { FORMULA_AST_CACHE } from '../../engine/utils/generate-ast-node';+import { FunctionService } from '../function.service';++describe('FunctionService', () => {+ it('should register/query/unregister executors', () => {+ const service = new FunctionService();+ const sumExecutor = { name: 'SUM' };+ const avgExecutor = { name: 'AVERAGE' };++ service.registerExecutors(sumExecutor as never, avgExecutor as never);++ expect(service.hasExecutor('SUM')).toBe(true);+ expect(service.getExecutor('SUM')).toBe(sumExecutor);+ expect(service.getExecutors().size).toBe(2);++ service.unregisterExecutors('AVERAGE');+ expect(service.hasExecutor('AVERAGE')).toBe(false);+ });++ it('should register descriptions and cleanup by disposable', () => {+ const service = new FunctionService();+ const sumDescription = {+ functionName: 'SUM',+ functionType: FunctionType.Math,+ description: 'sum',+ abstract: 'sum',+ functionParameter: [],+ };+ const avgDescription = {+ functionName: 'AVERAGE',+ functionType: FunctionType.Statistical,+ description: 'avg',+ abstract: 'avg',+ functionParameter: [],+ };++ const disposable = service.registerDescriptions(sumDescription as never, avgDescription as never);+ expect(service.hasDescription('SUM')).toBe(true);+ expect(service.getDescription('AVERAGE')?.description).toBe('avg');+ expect(service.getDescriptions().size).toBe(2);++ disposable.dispose();+ expect(service.hasDescription('SUM')).toBe(false);+ expect(service.hasDescription('AVERAGE')).toBe(false);+ });++ it('should unregister descriptions and clear formula AST cache by function tokens', () => {+ const service = new FunctionService();+ service.registerDescriptions({+ functionName: 'SUM',+ functionType: FunctionType.Math,+ description: 'sum',+ abstract: 'sum',+ functionParameter: [],+ } as never);+ expect(service.hasDescription('SUM')).toBe(true);+ service.unregisterDescriptions('SUM');+ expect(service.hasDescription('SUM')).toBe(false);++ FORMULA_AST_CACHE.clear();+ FORMULA_AST_CACHE.set('unit_sheet_SUM_expr', {} as never);+ FORMULA_AST_CACHE.set('unit_sheet_TEXT_expr', {} as never);++ service.deleteFormulaAstCacheKey('SUM');+ expect(FORMULA_AST_CACHE.get('unit_sheet_SUM_expr')).toBeUndefined();+ expect(FORMULA_AST_CACHE.get('unit_sheet_TEXT_expr')).toBeDefined();+ });++ it('should clear internal maps on dispose', () => {+ const service = new FunctionService();+ service.registerExecutors({ name: 'SUM' } as never);+ service.registerDescriptions({+ functionName: 'SUM',+ functionType: FunctionType.Math,+ description: 'sum',+ abstract: 'sum',+ functionParameter: [],+ } as never);++ service.dispose();+ expect(service.getExecutors().size).toBe(0);+ expect(service.getDescriptions().size).toBe(0);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/global-computing-status.service.spec.ts b/packages/engine-formula/src/services/__tests__/global-computing-status.service.spec.tsnew file mode 100644index 0000000000..d9bc50bf98--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/global-computing-status.service.spec.ts@@ -0,0 +1,61 @@+/**+ * 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 { BehaviorSubject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { GlobalComputingStatusService } from '../global-computing-status.service';++describe('GlobalComputingStatusService', () => {+ it('should aggregate computing status from all registered subjects', () => {+ const service = new GlobalComputingStatusService();+ const subjectA = new BehaviorSubject(false);+ const subjectB = new BehaviorSubject(true);++ const disposableA = service.pushComputingStatusSubject(subjectA);+ const disposableB = service.pushComputingStatusSubject(subjectB);++ expect(service.computingStatus).toBe(false);++ subjectA.next(true);+ expect(service.computingStatus).toBe(true);++ subjectB.next(false);+ expect(service.computingStatus).toBe(false);++ disposableB.dispose();+ expect(service.computingStatus).toBe(true);++ disposableA.dispose();+ expect(service.computingStatus).toBe(true);+ });++ it('should expose computingStatus$ and cleanup on dispose', () => {+ const service = new GlobalComputingStatusService();+ const subject = new BehaviorSubject(true);+ const observed: boolean[] = [];+ service.computingStatus$.subscribe((value) => observed.push(value));++ service.pushComputingStatusSubject(subject);+ subject.next(false);+ subject.next(true);++ expect(observed).toContain(false);+ expect(observed[0]).toBe(true);++ service.dispose();+ expect(subject.isStopped).toBe(true);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.tsnew file mode 100644index 0000000000..0afa721b0f--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/register-other-formula.service.spec.ts@@ -0,0 +1,231 @@+/**+ * 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 { ICommandInfo, LifecycleService } from '@univerjs/core';+import type { IActiveDirtyManagerService } from '../active-dirty-manager.service';+import { describe, expect, it, vi } from 'vitest';+import { OtherFormulaMarkDirty } from '../../commands/mutations/formula.mutation';+import { SetFormulaCalculationResultMutation } from '../../commands/mutations/set-formula-calculation.mutation';+import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../../commands/mutations/set-other-formula.mutation';+import { FormulaResultStatus } from '../formula-common';+import { OtherFormulaBizType, RegisterOtherFormulaService } from '../register-other-formula.service';++interface ICommandServiceMock {+ executeCommand: ReturnType<typeof vi.fn>;+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => { dispose: () => void };+ emit: (id: string, params?: unknown) => void;+}++function createCommandServiceMock(): ICommandServiceMock {+ const callbacks = new Set<(commandInfo: ICommandInfo) => void>();+ return {+ executeCommand: vi.fn(async (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ return true;+ }),+ onCommandExecuted: (callback: (commandInfo: ICommandInfo) => void) => {+ callbacks.add(callback);+ return {+ dispose: () => callbacks.delete(callback),+ };+ },+ emit: (id: string, params?: unknown) => {+ callbacks.forEach((callback) => callback({ id, params } as ICommandInfo));+ },+ };+}++describe('RegisterOtherFormulaService', () => {+ it('should register dirty conversion for other-formula commands', () => {+ const commandService = createCommandServiceMock();+ const activeDirtyManagerService: IActiveDirtyManagerService = {+ dispose: () => {},+ remove: () => {},+ get: () => null,+ has: () => false,+ register: vi.fn(),+ getDirtyConversionMap: () => new Map(),+ };++ // eslint-disable-next-line no-new+ new RegisterOtherFormulaService(+ commandService as never,+ activeDirtyManagerService,+ {} as LifecycleService+ );++ expect(activeDirtyManagerService.register).toHaveBeenCalledWith(+ OtherFormulaMarkDirty.id,+ expect.objectContaining({+ commandId: OtherFormulaMarkDirty.id,+ })+ );+ });++ it('should buffer register requests until calculation starts', async () => {+ const commandService = createCommandServiceMock();+ const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;++ const service = new RegisterOtherFormulaService(+ commandService as never,+ activeDirtyManagerService,+ {} as LifecycleService+ );++ const formulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1');+ expect(formulaId.startsWith('formula.unit-1_sheet-1_default_')).toBe(true);+ expect(commandService.executeCommand).not.toHaveBeenCalledWith(SetOtherFormulaMutation.id, expect.anything(), expect.anything());++ service.calculateStarted$.next(true);+ await Promise.resolve();+ await Promise.resolve();++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetOtherFormulaMutation.id,+ expect.objectContaining({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ }),+ { onlyLocal: true }+ );+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ OtherFormulaMarkDirty.id,+ { 'unit-1': { 'sheet-1': { [formulaId]: true } } },+ { onlyLocal: true }+ );+ });++ it('should register immediately after calculation started', async () => {+ const commandService = createCommandServiceMock();+ const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;+ const service = new RegisterOtherFormulaService(+ commandService as never,+ activeDirtyManagerService,+ {} as LifecycleService+ );++ service.calculateStarted$.next(true);+ service.registerFormulaWithRange('unit-2', 'sheet-2', '=SUM(A1:A5)', [], { source: 'test' }, OtherFormulaBizType.DOC, 'doc-1');++ await Promise.resolve();+ await Promise.resolve();++ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetOtherFormulaMutation.id,+ expect.objectContaining({+ unitId: 'unit-2',+ subUnitId: 'sheet-2',+ }),+ { onlyLocal: true }+ );+ });++ it('should cache formula results and resolve pending getFormulaValue', async () => {+ const commandService = createCommandServiceMock();+ const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;+ const service = new RegisterOtherFormulaService(+ commandService as never,+ activeDirtyManagerService,+ {} as LifecycleService+ );++ const formulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1+1');+ const pending = service.getFormulaValue('unit-1', 'sheet-1', formulaId);++ commandService.emit(SetFormulaCalculationResultMutation.id, {+ unitOtherData: {+ 'unit-1': {+ 'sheet-1': {+ [formulaId]: {+ 0: {+ 0: [{ v: 2 }],+ },+ },+ },+ },+ },+ });++ const value = await pending;+ expect(value?.status).toBe(FormulaResultStatus.SUCCESS);+ expect((value?.result as any)?.[0]?.[0]?.[0]?.v).toBe(2);+ });++ it('should support delete and dirty marking', async () => {+ const commandService = createCommandServiceMock();+ const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;+ const service = new RegisterOtherFormulaService(+ commandService as never,+ activeDirtyManagerService,+ {} as LifecycleService+ );++ const formulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1');+ commandService.emit(SetFormulaCalculationResultMutation.id, {+ unitOtherData: {+ 'unit-1': {+ 'sheet-1': {+ [formulaId]: { 0: { 0: [{ v: 1 }] } },+ },+ },+ },+ });++ service.markFormulaDirty('unit-1', 'sheet-1', formulaId);+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ OtherFormulaMarkDirty.id,+ { 'unit-1': { 'sheet-1': { [formulaId]: true } } },+ { onlyLocal: true }+ );++ service.deleteFormula('unit-1', 'sheet-1', [formulaId]);+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ RemoveOtherFormulaMutation.id,+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ formulaIdList: [formulaId],+ },+ { onlyLocal: true }+ );++ expect(service.getFormulaValueSync('unit-1', 'sheet-1', formulaId)).toBeUndefined();+ });++ it('should return immediate value for succeeded formula', async () => {+ const commandService = createCommandServiceMock();+ const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;+ const service = new RegisterOtherFormulaService(+ commandService as never,+ activeDirtyManagerService,+ {} as LifecycleService+ );++ const formulaId = service.registerFormulaWithRange('unit-3', 'sheet-3', '=1+1');+ commandService.emit(SetFormulaCalculationResultMutation.id, {+ unitOtherData: {+ 'unit-3': {+ 'sheet-3': {+ [formulaId]: { 0: { 0: [{ v: 2 }] } },+ },+ },+ },+ });++ const value = await service.getFormulaValue('unit-3', 'sheet-3', formulaId);+ expect(value?.status).toBe(FormulaResultStatus.SUCCESS);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.tsnew file mode 100644index 0000000000..32dbe1e5ba--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts@@ -0,0 +1,310 @@+/**+ * 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 { ObjectMatrix } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { ErrorType } from '../../basics/error-type';+import { createNewArray } from '../../engine/utils/array-object';+import { NumberValueObject, StringValueObject } from '../../engine/value-object/primitive-object';+import { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService } from '../runtime.service';++function createRuntimeService() {+ const unitDataMatrix = new ObjectMatrix<any>();+ const arrayFormulaCellData = new ObjectMatrix<any>();+ const arrayFormulaRange = {+ unit: {+ sheet: {},+ },+ };++ const currentConfigService = {+ getUnitData: () => ({+ unit: {+ sheet: {+ cellData: unitDataMatrix,+ },+ },+ }),+ getArrayFormulaCellData: () => ({+ unit: {+ sheet: arrayFormulaCellData,+ },+ }),+ getArrayFormulaRange: () => arrayFormulaRange,+ getDirtyRanges: () => [],+ };++ const hyperlinkEngineFormulaService = {+ generateCellValue: (url: string, text: string) => ({+ v: text,+ p: { url },+ }),+ };++ const runtime = new FormulaRuntimeService(+ currentConfigService as never,+ hyperlinkEngineFormulaService as never+ );++ return {+ runtime,+ unitDataMatrix,+ arrayFormulaCellData,+ arrayFormulaRange,+ };+}++describe('FormulaRuntimeService', () => {+ it('should manage state, counters and cycle flags', () => {+ const { runtime } = createRuntimeService();++ runtime.enableCycleDependency();+ expect(runtime.isCycleDependency()).toBe(true);+ runtime.disableCycleDependency();+ expect(runtime.isCycleDependency()).toBe(false);++ runtime.setFormulaCycleIndex(2);+ expect(runtime.getFormulaCycleIndex()).toBe(2);++ runtime.setTotalFormulasToCalculate(10);+ runtime.setCompletedFormulasCount(3);+ runtime.setTotalArrayFormulasToCalculate(4);+ runtime.setCompletedArrayFormulasCount(1);+ expect(runtime.getRuntimeState()).toEqual({+ totalFormulasToCalculate: 10,+ completedFormulasCount: 3,+ totalArrayFormulasToCalculate: 4,+ completedArrayFormulasCount: 1,+ stage: FormulaExecuteStageType.IDLE,+ formulaCycleIndex: 2,+ });++ runtime.markedAsSuccessfullyExecuted();+ expect(runtime.getAllRuntimeData().functionsExecutedState).toBe(FormulaExecutedStateType.SUCCESS);+ runtime.markedAsNoFunctionsExecuted();+ expect(runtime.getAllRuntimeData().functionsExecutedState).toBe(FormulaExecutedStateType.NOT_EXECUTED);+ runtime.markedAsStopFunctionsExecuted();+ expect(runtime.getAllRuntimeData().functionsExecutedState).toBe(FormulaExecutedStateType.STOP_EXECUTION);+ runtime.markedAsInitialFunctionsExecuted();+ expect(runtime.getAllRuntimeData().functionsExecutedState).toBe(FormulaExecutedStateType.INITIAL);++ runtime.setFormulaExecuteStage(FormulaExecuteStageType.CURRENTLY_CALCULATING);+ expect(runtime.getFormulaExecuteStage()).toBe(FormulaExecuteStageType.CURRENTLY_CALCULATING);+ runtime.stopExecution();+ expect(runtime.isStopExecution()).toBe(true);+ expect(runtime.getFormulaExecuteStage()).toBe(FormulaExecuteStageType.IDLE);++ runtime.reset();+ expect(runtime.isStopExecution()).toBe(false);+ expect(runtime.getTotalFormulasToCalculate()).toBe(0);+ expect(runtime.getCompletedFormulasCount()).toBe(0);+ });++ it('should manage current context and lambda privacy vars', () => {+ const { runtime } = createRuntimeService();+ runtime.setCurrent(6, 7, 99, 88, 'sheet', 'unit');++ expect(runtime.currentRow).toBe(6);+ expect(runtime.currentColumn).toBe(7);+ expect(runtime.currentRowCount).toBe(99);+ expect(runtime.currentColumnCount).toBe(88);+ expect(runtime.currentSubUnitId).toBe('sheet');+ expect(runtime.currentUnitId).toBe('unit');++ const lambdaVar = new Map<string, any>([['x', null]]);+ runtime.registerFunctionDefinitionPrivacyVar('lambda-1', lambdaVar);+ expect(runtime.getFunctionDefinitionPrivacyVar('lambda-1')).toBe(lambdaVar);+ runtime.clearFunctionDefinitionPrivacyVar();+ expect(runtime.getFunctionDefinitionPrivacyVar('lambda-1')).toBeUndefined();+ });++ it('should collect runtime other-data for scalar and array values', () => {+ const { runtime } = createRuntimeService();+ runtime.setCurrent(1, 1, 20, 20, 'sheet', 'unit');++ runtime.setRuntimeOtherData('f1', 2, 3, NumberValueObject.create(9) as never);+ expect(runtime.getRuntimeOtherData().unit?.sheet?.f1?.[3]?.[2]?.[0]?.[0]?.v).toBe(9);++ const array = createNewArray(+ [[NumberValueObject.create(1), NumberValueObject.create(2)]],+ 1,+ 2+ );+ runtime.setRuntimeOtherData('f2', 0, 0, array as never);+ expect(runtime.getRuntimeOtherData().unit?.sheet?.f2?.[0]?.[0]?.[0]?.[1]?.v).toBe(2);+ });++ it('should set runtime scalar values and image metadata', () => {+ const { runtime } = createRuntimeService();+ runtime.setCurrent(2, 3, 50, 50, 'sheet', 'unit');++ runtime.setRuntimeData(NumberValueObject.create(7) as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(2, 3)?.v).toBe(7);+ expect(runtime.getRuntimeClearArrayFormulaCellData().unit?.sheet?.getValue(2, 3)?.v).toBe(7);++ const imageValue = StringValueObject.create('', {+ isImage: true,+ imageInfo: {+ source: 'https://img',+ altText: 'demo',+ sizing: 1,+ height: 10,+ width: 20,+ },+ });+ runtime.setRuntimeData(imageValue as never);+ expect(runtime.getRuntimeImageFormulaData()).toEqual([+ {+ source: 'https://img',+ altText: 'demo',+ sizing: 1,+ height: 10,+ width: 20,+ unitId: 'unit',+ sheetId: 'sheet',+ row: 2,+ column: 3,+ },+ ]);+ });++ it('should set runtime hyperlink values via hyperlink service', () => {+ const { runtime } = createRuntimeService();+ runtime.setCurrent(0, 0, 10, 10, 'sheet', 'unit');++ const hyperlinkValue = StringValueObject.create('Open', {+ isHyperlink: true,+ hyperlinkUrl: 'https://example.com',+ });+ runtime.setRuntimeData(hyperlinkValue as never);++ expect(runtime.getUnitData().unit?.sheet?.getValue(0, 0)).toEqual({+ v: 'Open',+ p: {+ url: 'https://example.com',+ },+ });+ });++ it('should handle single-cell and normal array spill write', () => {+ const { runtime } = createRuntimeService();++ runtime.setCurrent(1, 1, 10, 10, 'sheet', 'unit');+ const oneCellArray = createNewArray([[NumberValueObject.create(5)]], 1, 1);+ runtime.setRuntimeData(oneCellArray as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(1, 1)?.v).toBe(5);++ runtime.setCurrent(3, 3, 10, 10, 'sheet', 'unit');+ const twoByTwo = createNewArray(+ [+ [NumberValueObject.create(11), NumberValueObject.create(12)],+ [NumberValueObject.create(21), NumberValueObject.create(22)],+ ],+ 2,+ 2+ );+ runtime.setRuntimeData(twoByTwo as never);++ expect(runtime.getUnitArrayFormula().unit?.sheet?.[3]?.[3]).toEqual({+ startRow: 3,+ startColumn: 3,+ endRow: 4,+ endColumn: 4,+ });+ expect(runtime.getUnitData().unit?.sheet?.getValue(3, 3)?.v).toBe(11);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(4, 4)?.v).toBe(22);+ });++ it('should return #SPILL when array exceeds worksheet boundary', () => {+ const { runtime } = createRuntimeService();+ runtime.setCurrent(9, 9, 10, 10, 'sheet', 'unit');+ const twoByTwo = createNewArray(+ [+ [NumberValueObject.create(1), NumberValueObject.create(2)],+ [NumberValueObject.create(3), NumberValueObject.create(4)],+ ],+ 2,+ 2+ );++ runtime.setRuntimeData(twoByTwo as never);+ expect(runtime.getUnitData().unit?.sheet?.getValue(9, 9)?.v).toBe(ErrorType.SPILL);+ expect(runtime.getRuntimeArrayFormulaCellData().unit?.sheet?.getValue(9, 9)?.v).toBe(ErrorType.SPILL);+ });++ it('should manage feature caches and embedded map', () => {+ const { runtime } = createRuntimeService();+ runtime.setCurrent(4, 5, 20, 20, 'sheet', 'unit');+ runtime.setUnitArrayFormulaEmbeddedMap();+ expect(runtime.getUnitArrayFormulaEmbeddedMap().unit?.sheet?.[4]?.[5]).toBe(true);++ runtime.setRuntimeFeatureRange('feature-a', { unit: { sheet: [] } } as never);+ runtime.setRuntimeFeatureCellData('feature-a', { unit: {} } as never);+ runtime.setDependencyTreeModelData([{ treeId: 1 } as never]);++ expect(runtime.getRuntimeFeatureRange()['feature-a']).toEqual({ unit: { sheet: [] } });+ expect(runtime.getRuntimeFeatureCellData()['feature-a']).toEqual({ unit: {} });+ expect(runtime.getDependencyTreeModelData()).toEqual([{ treeId: 1 }]);+ });++ it('should evaluate helper methods for range, overlap and dirty checks', () => {+ const { runtime, arrayFormulaRange } = createRuntimeService();++ expect((runtime as any)._arrayCellHasData(null)).toBe(false);+ expect((runtime as any)._arrayCellHasData({})).toBe(false);+ expect((runtime as any)._arrayCellHasData({ v: 0 })).toBe(true);++ expect((runtime as any)._isInArrayFormulaRange(null, 1, 1)).toBe(false);+ expect((runtime as any)._isInArrayFormulaRange({ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }, 1, 1)).toBe(true);+ expect((runtime as any)._checkIfArrayFormulaExceeded(5, 5, { startRow: 0, endRow: 5, startColumn: 0, endColumn: 1 })).toBe(true);+ expect((runtime as any)._checkIfArrayFormulaExceeded(5, 5, { startRow: 0, endRow: 4, startColumn: 0, endColumn: 4 })).toBe(false);++ runtime.setCurrent(0, 0, 10, 10, 'sheet', 'unit');+ runtime.setRuntimeData(NumberValueObject.create(123) as never);+ arrayFormulaRange.unit.sheet = {+ 0: {+ 0: {+ startRow: 0,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ },+ },+ 5: {+ 5: {+ startRow: 5,+ startColumn: 5,+ endRow: 6,+ endColumn: 6,+ },+ },+ };++ expect((runtime as any)._isInOtherArrayFormulaRange('unit', 'sheet', 5, 5, 0, 0)).toBe(true);+ expect((runtime as any)._isInOtherArrayFormulaRange('unit', 'sheet', 5, 5, 8, 8)).toBe(false);++ expect((runtime as any)._isInDirtyRange('unit', 'sheet', 1, 1)).toBe(true);+ });++ it('should dispose and clear runtime feature caches', () => {+ const { runtime } = createRuntimeService();+ runtime.setRuntimeFeatureRange('feature-a', { unit: {} } as never);+ runtime.setRuntimeFeatureCellData('feature-a', { unit: {} } as never);+ runtime.dispose();+ expect(runtime.getRuntimeFeatureRange()).toEqual({});+ expect(runtime.getRuntimeFeatureCellData()).toEqual({});+ });+});diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.tsindex 6576da8ff9..8155bbd6a0 100644--- a/packages/engine-formula/src/services/calculate-formula.service.ts+++ b/packages/engine-formula/src/services/calculate-formula.service.ts@@ -28,7 +28,7 @@ import type {IUnitRowData,} from '../basics/common';-import type { IUniverEngineFormulaConfig } from '../controller/config.schema';+import type { IUniverEngineFormulaConfig } from '../controllers/config.schema';import type { LexerNode } from '../engine/analysis/lexer-node';import type { IFormulaDependencyTreeFullJson, IFormulaDependencyTreeJson, IFormulaDependentsAndInRangeResults } from '../engine/dependency/dependency-tree';import type { BaseReferenceObject, FunctionVariantType } from '../engine/reference-object/base-reference-object';@@ -47,7 +47,7 @@ import {import { Subject } from 'rxjs';import { ErrorType } from '../basics/error-type';import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';-import { DEFAULT_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../controller/config.schema';+import { DEFAULT_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../controllers/config.schema';import { Lexer } from '../engine/analysis/lexer';import { AstTreeBuilder } from '../engine/analysis/parser';import { IFormulaDependencyGenerator } from '../engine/dependency/formula-dependency';diff --git a/packages/engine-render/jest.setup.ts b/packages/engine-render/jest.setup.tsnew file mode 100644index 0000000000..40bca5f110--- /dev/null+++ b/packages/engine-render/jest.setup.ts@@ -0,0 +1,19 @@+/**+ * 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 { vi } from 'vitest';++vi.stubGlobal('jest', vi);diff --git a/packages/engine-render/package.json b/packages/engine-render/package.jsonindex af876288dc..57e5ad25b8 100644--- a/packages/engine-render/package.json+++ b/packages/engine-render/package.json@@ -71,6 +71,7 @@"devDependencies": {"@types/opentype.js": "^1.3.8","@univerjs-infra/shared": "workspace:*",+ "jest-canvas-mock": "^2.5.2","rxjs": "^7.8.2","typescript": "^5.9.3","vite": "^7.3.1",diff --git a/packages/engine-render/src/__tests__/base-object.spec.ts b/packages/engine-render/src/__tests__/base-object.spec.tsnew file mode 100644index 0000000000..99b7b1068e--- /dev/null+++ b/packages/engine-render/src/__tests__/base-object.spec.ts@@ -0,0 +1,260 @@+/**+ * 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 { IViewportInfo } from '../basics/vector2';+import { describe, expect, it, vi } from 'vitest';+import { BaseObject } from '../base-object';+import { CURSOR_TYPE, RENDER_CLASS_TYPE } from '../basics/const';+import { Vector2 } from '../basics/vector2';++class TestObject extends BaseObject {+ setBox(left: number | string, top: number | string, width: number | string, height: number | string) {+ this.left = left;+ this.top = top;+ this.width = width;+ this.height = height;+ }++ setTransformState(input: {+ strokeWidth?: number;+ angle?: number;+ scaleX?: number;+ scaleY?: number;+ skewX?: number;+ skewY?: number;+ flipX?: boolean;+ flipY?: boolean;+ }) {+ if (input.strokeWidth !== undefined) this.strokeWidth = input.strokeWidth;+ if (input.angle !== undefined) this.angle = input.angle;+ if (input.scaleX !== undefined) this.scaleX = input.scaleX;+ if (input.scaleY !== undefined) this.scaleY = input.scaleY;+ if (input.skewX !== undefined) this.skewX = input.skewX;+ if (input.skewY !== undefined) this.skewY = input.skewY;+ if (input.flipX !== undefined) this.flipX = input.flipX;+ if (input.flipY !== undefined) this.flipY = input.flipY;+ (this as any)._setTransForm();+ }++ override render(_ctx: any, _bounds?: IViewportInfo) {+ // noop+ }+}++function createParentChain() {+ const scene = {+ classType: RENDER_CLASS_TYPE.SCENE,+ getParent: vi.fn(() => ({+ classType: RENDER_CLASS_TYPE.ENGINE,+ getParent: vi.fn(() => null),+ })),+ setCursor: vi.fn(),+ resetCursor: vi.fn(),+ attachTransformerTo: vi.fn(),+ detachTransformerFrom: vi.fn(),+ } as any;+ return scene;+}++describe('base object', () => {+ it('covers transform/getter/state and cursor/parent chain methods', () => {+ const obj = new TestObject('obj-1');+ const scene = createParentChain();+ obj.parent = scene;+ obj.layer = { zIndex: 9, makeDirty: vi.fn(), makeDirtyWithDebounce: vi.fn() } as any;+ obj.setBox(10, 20, 30, 40);+ obj.setTransformState({+ strokeWidth: 2,+ angle: 30,+ scaleX: 1.5,+ scaleY: 2,+ skewX: 5,+ skewY: 6,+ flipX: true,+ flipY: false,+ });++ expect(obj.oKey).toBe('obj-1');+ expect(obj.top).toBe(20);+ expect(obj.left).toBe(10);+ expect(obj.width).toBe(30);+ expect(obj.height).toBe(40);+ expect(obj.strokeWidth).toBe(2);+ expect(obj.transform).toBeTruthy();+ expect(obj.transformForAngle((obj as any)._transform.clone())).toBeTruthy();+ expect(obj.getState()).toEqual(expect.objectContaining({+ left: 10,+ top: 20,+ width: 30,+ height: 40,+ }));++ obj.cursor = CURSOR_TYPE.POINTER;+ obj.resetCursor();+ expect(scene.setCursor).toHaveBeenCalledWith(CURSOR_TYPE.POINTER);+ expect(scene.resetCursor).toHaveBeenCalled();+ expect(obj.getScene()).toBe(scene);+ expect(obj.getEngine()).toBeTruthy();+ expect(obj.getLayerIndex()).toBe(9);++ obj.applyTransform();+ obj.removeTransform();+ expect(scene.attachTransformerTo).toHaveBeenCalledWith(obj);+ expect(scene.detachTransformerFrom).toHaveBeenCalledWith(obj);+ expect(obj.getObjects()).toEqual([]);+ });++ it('covers dirty control, visibility and render/hit branches', () => {+ const obj = new TestObject();+ obj.setBox(0, 0, 20, 10);+ obj.setTransformState({ strokeWidth: 2 });++ obj.layer = null as any;+ obj.makeDirty(true);+ expect(obj.isDirty()).toBe(false);++ const layer = { zIndex: 3, makeDirty: vi.fn(), makeDirtyWithDebounce: vi.fn() };+ obj.layer = layer as any;+ obj.makeDirty(true);+ expect(layer.makeDirtyWithDebounce).toHaveBeenCalled();++ obj.makeDirtyNoDebounce(true);+ expect(layer.makeDirty).toHaveBeenCalled();++ obj.makeForceDirty(true);+ obj.hide();+ expect(obj.visible).toBe(false);+ obj.show();+ expect(obj.visible).toBe(true);++ expect(obj.isRender({} as any)).toBe(true);+ (obj as any)._forceRender = true;+ expect(obj.isRender({} as any)).toBe(false);++ expect(obj.isHit(Vector2.FromArray([5, 5]))).toBe(true);+ expect(obj.isHit(Vector2.FromArray([100, 100]))).toBe(false);+ expect(obj.getInverseCoord(Vector2.FromArray([2, 3]))).toBeTruthy();+ });++ it('covers event trigger propagation and stopPropagation branches', () => {+ const obj = new TestObject();+ const parent = {+ triggerPointerMove: vi.fn(),+ triggerPointerDown: vi.fn(),+ triggerPointerUp: vi.fn(),+ triggerSingleClick: vi.fn(),+ triggerClick: vi.fn(),+ triggerDblclick: vi.fn(),+ triggerTripleClick: vi.fn(),+ triggerMouseWheel: vi.fn(),+ triggerPointerOut: vi.fn(),+ triggerPointerLeave: vi.fn(),+ triggerPointerOver: vi.fn(),+ triggerPointerEnter: vi.fn(),+ triggerPointerCancel: vi.fn(),+ triggerDragLeave: vi.fn(),+ triggerDragOver: vi.fn(),+ triggerDragEnter: vi.fn(),+ triggerDrop: vi.fn(),+ };+ obj.parent = parent as any;++ const event = { stopPropagation: false } as any;+ expect(obj.triggerPointerMove(event)).toBe(false);+ expect(obj.triggerPointerDown(event)).toBe(false);+ expect(obj.triggerPointerUp(event)).toBe(false);+ expect(obj.triggerSingleClick(event)).toBe(false);+ expect(obj.triggerClick(event)).toBe(false);+ expect(obj.triggerDblclick(event)).toBe(false);+ expect(obj.triggerTripleClick(event)).toBe(false);+ expect(obj.triggerMouseWheel(event)).toBe(false);+ expect(obj.triggerPointerOut(event)).toBe(false);+ expect(obj.triggerPointerLeave(event)).toBe(false);+ expect(obj.triggerPointerOver(event)).toBe(true);+ expect(obj.triggerPointerEnter(event)).toBe(false);+ expect(obj.triggerPointerCancel(event)).toBe(false);+ expect(obj.triggerDragLeave(event)).toBe(false);+ expect(obj.triggerDragOver(event)).toBe(false);+ expect(obj.triggerDragEnter(event)).toBe(false);+ expect(obj.triggerDrop(event)).toBe(false);++ const stopEvt = { stopPropagation: true } as any;+ obj.onPointerMove$.emitEvent = vi.fn(() => stopEvt);+ obj.onPointerDown$.emitEvent = vi.fn(() => stopEvt);+ obj.onPointerUp$.emitEvent = vi.fn(() => stopEvt);+ obj.onSingleClick$.emitEvent = vi.fn(() => stopEvt);+ obj.onClick$.emitEvent = vi.fn(() => stopEvt);+ obj.onDblclick$.emitEvent = vi.fn(() => stopEvt);+ obj.onTripleClick$.emitEvent = vi.fn(() => stopEvt);+ obj.onMouseWheel$.emitEvent = vi.fn(() => stopEvt);+ obj.onPointerOut$.emitEvent = vi.fn(() => stopEvt);+ obj.onPointerLeave$.emitEvent = vi.fn(() => stopEvt);+ obj.onPointerOver$.emitEvent = vi.fn(() => stopEvt);+ obj.onPointerEnter$.emitEvent = vi.fn(() => stopEvt);+ obj.onDragLeave$.emitEvent = vi.fn(() => stopEvt);+ obj.onDragOver$.emitEvent = vi.fn(() => stopEvt);+ obj.onDragEnter$.emitEvent = vi.fn(() => stopEvt);+ obj.onDrop$.emitEvent = vi.fn(() => stopEvt);++ expect(obj.triggerPointerMove({} as any)).toBe(true);+ expect(obj.triggerPointerDown({} as any)).toBe(true);+ expect(obj.triggerPointerUp({} as any)).toBe(true);+ expect(obj.triggerSingleClick({} as any)).toBe(true);+ expect(obj.triggerClick({} as any)).toBe(true);+ expect(obj.triggerDblclick({} as any)).toBe(true);+ expect(obj.triggerTripleClick({} as any)).toBe(true);+ expect(obj.triggerMouseWheel({} as any)).toBe(true);+ expect(obj.triggerPointerOut({} as any)).toBe(true);+ expect(obj.triggerPointerLeave({} as any)).toBe(true);+ expect(obj.triggerPointerOver({} as any)).toBe(true);+ expect(obj.triggerPointerEnter({} as any)).toBe(true);+ expect(obj.triggerDragLeave({} as any)).toBe(true);+ expect(obj.triggerDragOver({} as any)).toBe(true);+ expect(obj.triggerDragEnter({} as any)).toBe(true);+ expect(obj.triggerDrop({} as any)).toBe(true);+ });++ it('covers transform APIs, serialization and dispose flow', () => {+ const obj = new TestObject();+ obj.setBox('10', '20', '30', '40');+ obj.transformByState({});+ obj.translate(11, 12).resize(13, 14).scale(1.2, 1.3).skew(2, 3).flip(true, false);+ obj.transformByState({+ left: 15,+ top: 16,+ width: 17,+ height: 18,+ angle: 10,+ scaleX: 1.1,+ scaleY: 1.2,+ skewX: 3,+ skewY: 4,+ flipX: false,+ flipY: true,+ strokeWidth: 1,+ });+ expect(obj.toJson()).toEqual(expect.objectContaining({+ top: expect.any(Number),+ left: expect.any(Number),+ }));++ const parent = { removeObject: vi.fn() };+ obj.parent = parent as any;+ obj.dispose();+ expect(parent.removeObject).toHaveBeenCalledWith(obj);+ expect(obj.parent).toBeNull();+ });+});diff --git a/packages/engine-render/src/__tests__/context.spec.ts b/packages/engine-render/src/__tests__/context.spec.tsnew file mode 100644index 0000000000..e8d7d4c5ba--- /dev/null+++ b/packages/engine-render/src/__tests__/context.spec.ts@@ -0,0 +1,241 @@+/**+ * 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 { Tools } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { UniverPrintingContext, UniverRenderingContext2D } from '../context';++function createNativeContext() {+ const canvas = document.createElement('canvas');+ canvas.width = 200;+ canvas.height = 100;++ const ctx = {+ canvas,+ globalAlpha: 1,+ globalCompositeOperation: 'source-over',+ fillStyle: '#000000',+ strokeStyle: '#000000',+ filter: 'none',+ imageSmoothingEnabled: true,+ imageSmoothingQuality: 'low',+ lineCap: 'butt',+ lineDashOffset: 0,+ lineJoin: 'miter',+ lineWidth: 1,+ miterLimit: 10,+ shadowBlur: 0,+ shadowColor: '#000000',+ shadowOffsetX: 0,+ shadowOffsetY: 0,+ direction: 'inherit',+ font: '10px serif',+ fontKerning: 'auto',+ textAlign: 'start',+ textBaseline: 'alphabetic',+ getTransform: vi.fn(() => ({ a: 2, b: 0, c: 0, d: 4, e: 1, f: 1 })),+ getContextAttributes: vi.fn(() => ({})),+ isContextLost: vi.fn(() => false),+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ closePath: vi.fn(),+ arc: vi.fn(),+ arcTo: vi.fn(),+ bezierCurveTo: vi.fn(),+ clearRect: vi.fn(),+ clip: vi.fn(),+ createConicGradient: vi.fn(() => ({ addColorStop: vi.fn() })),+ createImageData: vi.fn((a: any, b?: any) => {+ if (typeof a === 'number') {+ return { data: new Uint8ClampedArray(4), width: a, height: b ?? a };+ }+ return { data: new Uint8ClampedArray(4), width: a.width, height: a.height };+ }),+ createLinearGradient: vi.fn(() => ({ addColorStop: vi.fn() })),+ createPattern: vi.fn(() => ({})),+ createRadialGradient: vi.fn(() => ({ addColorStop: vi.fn() })),+ drawFocusIfNeeded: vi.fn(),+ drawImage: vi.fn(),+ ellipse: vi.fn(),+ fill: vi.fn(),+ fillRect: vi.fn(),+ fillText: vi.fn(),+ getImageData: vi.fn(() => ({ data: new Uint8ClampedArray(4), width: 1, height: 1 })),+ isPointInPath: vi.fn(() => false),+ isPointInStroke: vi.fn(() => false),+ lineTo: vi.fn(),+ moveTo: vi.fn(),+ putImageData: vi.fn(),+ quadraticCurveTo: vi.fn(),+ rect: vi.fn(),+ resetTransform: vi.fn(),+ reset: vi.fn(),+ rotate: vi.fn(),+ roundRect: vi.fn(),+ scale: vi.fn(),+ setLineDash: vi.fn(),+ getLineDash: vi.fn(() => [1, 2]),+ setTransform: vi.fn(),+ stroke: vi.fn(),+ strokeRect: vi.fn(),+ strokeText: vi.fn(),+ transform: vi.fn(),+ translate: vi.fn(),+ };++ return ctx as any as CanvasRenderingContext2D;+}++describe('context extra', () => {+ it('forwards style and basic drawing calls', () => {+ const nativeCtx = createNativeContext();+ const renderCtx = new UniverRenderingContext2D(nativeCtx, {+ canvasColorService: {+ getRenderColor: (color: string) => `render-${color}`,+ } as any,+ });++ renderCtx.setId('ctx-id');+ expect(renderCtx.getId()).toBe('ctx-id');+ expect(renderCtx.isContextLost()).toBe(false);++ renderCtx.fillStyle = '#111111';+ renderCtx.strokeStyle = '#222222';+ expect(nativeCtx.fillStyle).toBe('render-#111111');+ expect(nativeCtx.strokeStyle).toBe('render-#222222');++ renderCtx.globalAlpha = 0.7;+ renderCtx.globalCompositeOperation = 'multiply';+ renderCtx.lineCap = 'round';+ renderCtx.lineJoin = 'bevel';+ renderCtx.lineDashOffset = 3;+ renderCtx.lineWidth = 2;+ renderCtx.miterLimit = 5;+ renderCtx.shadowBlur = 4;+ renderCtx.shadowColor = '#333';+ renderCtx.shadowOffsetX = 6;+ renderCtx.shadowOffsetY = 8;+ renderCtx.direction = 'ltr';+ renderCtx.font = '12px Arial';+ renderCtx.fontKerning = 'none';+ renderCtx.textAlign = 'center';+ renderCtx.textBaseline = 'middle';+ renderCtx.filter = 'blur(1px)';+ renderCtx.imageSmoothingEnabled = false;+ renderCtx.imageSmoothingQuality = 'high';+ renderCtx.setLineWidthByPrecision(12);++ expect(nativeCtx.globalAlpha).toBe(0.7);+ expect(nativeCtx.globalCompositeOperation).toBe('multiply');+ expect(nativeCtx.lineWidth).toBe(3);++ renderCtx.beginPath();+ renderCtx.closePath();+ renderCtx.arc(1, 2, -10, 0, Math.PI);+ renderCtx.arcTo(1, 2, 3, 4, 5);+ renderCtx.bezierCurveTo(1, 2, 3, 4, 5, 6);+ renderCtx.clearRect(1, 2, 3, 4);+ renderCtx.clip();+ renderCtx.ellipse(1, 2, 3, 4, 0, 0, Math.PI);+ renderCtx.fill();+ renderCtx.fillRect(1, 2, 3, 4);+ renderCtx.fillText('hello', 3, 4);+ renderCtx.getImageData(0, 0, 1, 1);+ renderCtx.isPointInPath(1, 1);+ renderCtx.isPointInStroke(1, 1);+ renderCtx.lineTo(1, 2);+ renderCtx.moveTo(1, 2);+ renderCtx.putImageData({} as ImageData, 1, 2);+ renderCtx.quadraticCurveTo(1, 2, 3, 4);+ renderCtx.rect(1, 2, 3, 4);+ renderCtx.rotate(0.2);+ renderCtx.save();+ renderCtx.scale(2, 3);+ renderCtx.setLineDash([2, 2]);+ renderCtx.stroke();+ renderCtx.strokeRect(1, 2, 3, 4);+ renderCtx.strokeText('text', 1, 2);+ renderCtx.transform(1, 0, 0, 1, 1, 2);+ renderCtx.translate(3, 4);+ renderCtx.restore();+ renderCtx.drawFocusIfNeeded(document.body);++ expect(nativeCtx.beginPath).toHaveBeenCalled();+ expect(nativeCtx.strokeText).toHaveBeenCalled();+ expect(renderCtx.getLineDash()).toEqual([1, 2]);+ expect(renderCtx.getContextAttributes()).toEqual({});+ });++ it('covers precision, drawImage, createImageData and env branches', () => {+ const nativeCtx = createNativeContext();+ const renderCtx = new UniverRenderingContext2D(nativeCtx);++ renderCtx.roundRectByPrecision(1, 2, 3, 4, 2);+ renderCtx.arcByPrecision(1, 2, 5, 0, Math.PI);+ renderCtx.arcToByPrecision(1, 2, 3, 4, 5);+ renderCtx.bezierCurveToByPrecision(1, 2, 3, 4, 5, 6);+ renderCtx.clearRectByPrecision(1, 2, 3, 4);+ renderCtx.fillRectByPrecision(1, 2, 3, 4);+ renderCtx.strokeRectPrecision(1, 2, 3, 4);+ renderCtx.fillTextPrecision('abc', 1, 2, 40);+ renderCtx.lineToByPrecision(1, 2);+ renderCtx.moveToByPrecision(1, 2);+ renderCtx.moveToByPrecisionLog(1, 2);+ renderCtx.rectByPrecision(1, 2, 3, 4);+ renderCtx.strokeTextByPrecision('abc', 1, 2, 30);+ renderCtx.translateWithPrecision(1, 2);+ renderCtx.translateWithPrecisionRatio(10, 20);+ renderCtx.clearRectForTexture(1, 2, 3, 4);+ renderCtx.setGlobalCompositeOperation('source-over');++ const image = document.createElement('canvas');+ renderCtx.drawImage(image, 1, 2);+ renderCtx.drawImage(image, 1, 2, 3, 4);+ renderCtx.drawImage(image, 1, 2, 3, 4, 5, 6, 7, 8);++ expect(() => (renderCtx as any).createImageData()).toThrow('arguments is zero');+ expect((renderCtx as any).createImageData(3, 4)).toBeTruthy();+ expect((renderCtx as any).createImageData({ width: 2, height: 2 })).toBeTruthy();+ expect((renderCtx as any).createImageData(3, 4, { colorSpace: 'srgb' })).toBeTruthy();++ const browserSpy = vi.spyOn(Tools, 'getBrowserType').mockReturnValue('Chrome' as any);+ const systemSpy = vi.spyOn(Tools, 'getSystemType').mockReturnValue('Mac' as any);+ renderCtx.closePathByEnv();+ expect(nativeCtx.closePath).not.toHaveBeenCalled();+ browserSpy.mockReturnValue('Firefox' as any);+ (renderCtx as any)._browserType = '';+ renderCtx.closePathByEnv();+ expect(nativeCtx.closePath).toHaveBeenCalledTimes(1);+ systemSpy.mockRestore();+ browserSpy.mockRestore();+ });++ it('covers fallback line dash branches and printing context', () => {+ const nativeCtx = createNativeContext() as any;+ delete nativeCtx.setLineDash;+ nativeCtx.mozDash = [];+ const renderCtx = new UniverRenderingContext2D(nativeCtx as CanvasRenderingContext2D);+ renderCtx.setLineDash([4, 1]);+ expect(nativeCtx.mozDash).toEqual([4, 1]);++ const printingCtx = new UniverPrintingContext(createNativeContext());+ printingCtx.clearRect(1, 2, 3, 4);+ printingCtx.clearRectForTexture(1, 2, 3, 4);+ printingCtx.setGlobalCompositeOperation('lighter');+ expect(printingCtx.__mode).toBe('printing');+ });+});diff --git a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.tsnew file mode 100644index 0000000000..3f671b938f--- /dev/null+++ b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts@@ -0,0 +1,637 @@+/**+ * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CURSOR_TYPE } from '../basics/const';+import { DeviceType, PointerInput } from '../basics/i-events';+import { Vector2 } from '../basics/vector2';+import { Engine } from '../engine';+import { Group } from '../group';+import { MAIN_VIEW_PORT_KEY, Scene } from '../scene';+import { Transformer } from '../scene.transformer';+import { Rect } from '../shape/rect';+import { ScrollBar } from '../shape/scroll-bar';+import { Viewport } from '../viewport';+import { setupRenderTestEnv } from './render-test-utils';++interface IFixture {+ engine: Engine;+ scene: Scene;+ viewport: Viewport;+ container: HTMLDivElement;+}++function createInputEvent(type: string, extra: Record<string, unknown> = {}) {+ return {+ type,+ pointerId: 1,+ pointerType: 'mouse',+ button: 0,+ inputIndex: PointerInput.LeftClick,+ deviceType: DeviceType.Mouse,+ clientX: 18,+ clientY: 20,+ offsetX: 18,+ offsetY: 20,+ movementX: 2,+ movementY: 1,+ deltaX: 0,+ deltaY: 0,+ deltaZ: 0,+ shiftKey: false,+ preventDefault: vi.fn(),+ stopPropagation: vi.fn(),+ ...extra,+ } as any;+}++function createFixture(): IFixture {+ const container = document.createElement('div');+ container.style.width = '420px';+ container.style.height = '260px';+ container.style.border = '1px solid transparent';+ document.body.appendChild(container);++ const engine = new Engine('unit-a', { elementWidth: 320, elementHeight: 180, dpr: 1 });+ engine.mount(container, false);++ const scene = new Scene('scene-a', engine);+ scene.transformByState({+ width: 700,+ height: 500,+ scaleX: 1,+ scaleY: 1,+ });++ const viewport = new Viewport(MAIN_VIEW_PORT_KEY, scene, {+ left: 0,+ top: 0,+ width: 300,+ height: 180,+ active: true,+ allowCache: true,+ bufferEdgeX: 8,+ bufferEdgeY: 6,+ });++ new ScrollBar(viewport, {+ mainScene: scene,+ barSize: 12,+ thumbMargin: 2,+ });++ const rect = new Rect('rect-main', {+ left: 10,+ top: 10,+ width: 100,+ height: 60,+ fill: '#44aa66',+ stroke: '#112233',+ strokeWidth: 1,+ });+ rect.zIndex = 1;+ scene.addObject(rect, 1);++ const child = new Rect('rect-child', {+ left: 120,+ top: 40,+ width: 60,+ height: 40,+ fill: '#3366ff',+ stroke: '#111111',+ strokeWidth: 1,+ });+ const group = new Group('group-main', child);+ group.transformByState({ left: 40, top: 20 });+ scene.addObject(group, 2);++ return {+ engine,+ scene,+ viewport,+ container,+ };+}++describe('engine scene viewport extra', () => {+ let env: ReturnType<typeof setupRenderTestEnv>;++ beforeEach(() => {+ env = setupRenderTestEnv();+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.runOnlyPendingTimers();+ vi.useRealTimers();+ env.restore();+ vi.restoreAllMocks();+ document.body.innerHTML = '';+ });++ it('covers scene, viewport, layer and render loop flows', () => {+ const { engine, scene, viewport, container } = createFixture();++ expect(engine.getScene('scene-a')).toBe(scene);+ expect(scene.getMainViewport()).toBe(viewport);+ expect(engine.getCanvasElement().parentElement).toBe(container);++ scene.setCursor(CURSOR_TYPE.POINTER);+ expect(engine.getCanvasElement().style.cursor).toBe(CURSOR_TYPE.POINTER);+ scene.setDefaultCursor(CURSOR_TYPE.CELL);+ expect(scene.getCursor()).toBe(CURSOR_TYPE.CELL);++ scene.resize(720, 520);+ scene.scale(1.3, 1.2);+ scene.scaleBy(0.2, 0.2);++ viewport.setPadding({ startX: 6, startY: 4, endX: 3, endY: 2 });+ viewport.scrollToBarPos({ x: 12, y: 8 });+ viewport.scrollByBarDeltaValue({ x: 8, y: 4 });+ viewport.scrollToViewportPos({ viewportScrollX: 20, viewportScrollY: 16 });+ viewport.scrollByViewportDeltaVal({ viewportScrollX: 6, viewportScrollY: 5 });+ viewport.resizeWhenFreezeChange({ left: 0, top: 0, width: 250, height: 150 });+ viewport.resetPadding();++ expect(scene.pick(Vector2.FromArray([20, 20]))).toBeTruthy();+ expect(scene.findViewportByPosToScene(Vector2.FromArray([20, 20]))).toBeTruthy();+ expect(scene.getScrollXYInfoByViewport(Vector2.FromArray([20, 20]))).toEqual({+ x: expect.any(Number),+ y: expect.any(Number),+ });+ expect(scene.getAllObjects().length).toBeGreaterThan(0);+ expect(scene.getAllObjectsByOrder().length).toBeGreaterThan(0);+ expect(scene.getAllObjectsByDescOrder(true).length).toBeGreaterThan(0);+ expect(scene.getAllObjectsByOrderForPick().length).toBeGreaterThan(0);+ expect(scene.getObjectIncludeInGroup('rect-child')).toBeTruthy();+ expect(scene.fuzzyMathObjects('rect').length).toBeGreaterThan(0);++ scene.render();+ viewport.onMouseWheel(+ createInputEvent('wheel', { deltaX: 4, deltaY: 12 }),+ { stopPropagation: vi.fn() } as any+ );++ viewport.disable();+ expect(viewport.shouldIntoRender()).toBe(false);+ viewport.enable();+ expect(viewport.shouldIntoRender()).toBe(true);++ const task = vi.fn();+ const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 88);+ const cafSpy = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});+ engine.runRenderLoop(task);+ (engine as any)._renderFunction(16);+ expect(task).toHaveBeenCalled();+ engine.stopRenderLoop(task);+ expect(cafSpy).toHaveBeenCalled();+ rafSpy.mockRestore();+ cafSpy.mockRestore();++ engine.resizeBySize(500, 300);+ expect(engine.width).toBe(500);+ expect(engine.height).toBe(300);++ engine.unmount();+ expect(engine.getCanvasElement().parentElement).toBeNull();+ engine.mount(container, false);+ expect(engine.getCanvasElement().parentElement).toBe(container);++ scene.dispose();+ engine.dispose();+ });++ it('covers engine pointer handlers and input manager dispatch', () => {+ const { engine, scene } = createFixture();+ scene.attachControl();++ const scenePointerMove = vi.fn();+ const scenePointerDown = vi.fn();+ const sceneWheel = vi.fn();+ const sceneDragOver = vi.fn();+ scene.onPointerMove$.subscribeEvent(scenePointerMove);+ scene.onPointerDown$.subscribeEvent(scenePointerDown);+ scene.onMouseWheel$.subscribeEvent(sceneWheel);+ scene.onDragOver$.subscribeEvent(sceneDragOver);++ const engineEventTypes: string[] = [];+ engine.onInputChanged$.subscribeEvent((evt) => engineEventTypes.push(evt.type));++ (engine as any)._pointerClickEvent(createInputEvent('click'));+ (engine as any)._pointerDblClickEvent(createInputEvent('dblclick'));+ (engine as any)._pointerEnterEvent(createInputEvent('pointerenter'));+ (engine as any)._pointerLeaveEvent(createInputEvent('pointerleave'));+ (engine as any)._pointerMoveEvent(createInputEvent('pointermove'));+ (engine as any)._pointerDownEvent(createInputEvent('pointerdown'));+ (engine as any)._pointerUpEvent(createInputEvent('pointerup'));+ (engine as any)._pointerOutEvent(createInputEvent('pointerout'));+ (engine as any)._pointerCancelEvent(createInputEvent('pointercancel'));+ (engine as any)._pointerWheelEvent(createInputEvent('wheel', { deltaX: 1, deltaY: 4, deltaZ: 2 }));+ (engine as any)._pointerBlurEvent(createInputEvent('blur'));++ const dragOverEvent = createInputEvent('dragover', {+ dataTransfer: {},+ preventDefault: vi.fn(),+ });+ (engine as any)._dragEnterEvent(createInputEvent('dragenter', { dataTransfer: {} }));+ (engine as any)._dragLeaveEvent(createInputEvent('dragleave', { dataTransfer: {} }));+ (engine as any)._dragOverEvent(dragOverEvent);+ (engine as any)._dropEvent(createInputEvent('drop', { dataTransfer: {} }));++ engine.onInputChanged$.emitEvent(createInputEvent('keydown', {+ deviceType: DeviceType.Keyboard,+ keyCode: 13,+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('keyup', {+ deviceType: DeviceType.Keyboard,+ keyCode: 27,+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('pointermove', {+ inputIndex: PointerInput.Horizontal,+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('pointerdown', {+ inputIndex: PointerInput.LeftClick,+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('pointerup', {+ inputIndex: PointerInput.LeftClick,+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('click'));+ engine.onInputChanged$.emitEvent(createInputEvent('dblclick'));+ engine.onInputChanged$.emitEvent(createInputEvent('wheel'));+ engine.onInputChanged$.emitEvent(createInputEvent('pointerleave'));+ engine.onInputChanged$.emitEvent(createInputEvent('pointerout'));+ engine.onInputChanged$.emitEvent(createInputEvent('pointercancel'));+ engine.onInputChanged$.emitEvent(createInputEvent('dragenter', {+ dataTransfer: {},+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('dragover', {+ dataTransfer: {},+ inputIndex: PointerInput.DeltaVertical,+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('dragleave', {+ dataTransfer: {},+ }));+ engine.onInputChanged$.emitEvent(createInputEvent('drop', {+ dataTransfer: {},+ }));++ vi.advanceTimersByTime(1000);++ expect(engineEventTypes.length).toBeGreaterThan(10);+ expect(scenePointerMove).toHaveBeenCalled();+ expect(scenePointerDown).toHaveBeenCalled();+ expect(sceneWheel).toHaveBeenCalled();+ expect(sceneDragOver).toHaveBeenCalled();+ expect(dragOverEvent.preventDefault).toHaveBeenCalled();++ scene.detachControl();+ scene.dispose();+ engine.dispose();+ });++ it('throws when subscribing clientRect$ without mounting container', () => {+ const engine = new Engine('unit-b', { elementWidth: 1, elementHeight: 1, dpr: 1 });+ const onError = vi.fn();+ engine.clientRect$.subscribe({+ error: onError,+ });+ expect(onError).toHaveBeenCalledWith(+ expect.objectContaining({+ message: '[Engine]: cannot subscribe to rect changes when container is not set!',+ })+ );+ engine.dispose();+ });++ it('covers transformer geometry and state helper branches', () => {+ const sceneMock = {+ ancestorScaleX: 2,+ ancestorScaleY: 4,+ ancestorLeft: 6,+ ancestorTop: 8,+ getEngine: () => ({ activeScene: null }),+ } as any;++ const transformer = new Transformer(sceneMock, {+ anchorSize: 12,+ borderSpacing: 2,+ rotateAnchorOffset: 20,+ rotateSize: 10,+ });++ const changingSpy = vi.fn();+ transformer.changing$.subscribe(changingSpy);+ (transformer as any)._selectedObjectMap.set('s1', { oKey: 's1', dispose: vi.fn() });+ transformer.changeNotification();+ expect(changingSpy).toHaveBeenCalled();++ transformer.updateZeroPoint(1, 2);+ expect(transformer.zeroLeft).toBe(1);+ expect(transformer.zeroTop).toBe(2);++ const moveBoundary = (transformer as any)._checkMoveBoundary(+ { left: 5, top: 5, width: 20, height: 10 },+ -100,+ -100,+ 0,+ 0,+ 200,+ 100+ );+ expect(moveBoundary.moveLeft).toBeLessThanOrEqual(0);+ expect(moveBoundary.moveTop).toBeLessThanOrEqual(0);++ (transformer as any)._startOffsetX = 10;+ (transformer as any)._startOffsetY = 10;+ expect((transformer as any)._moveBufferBlocker(11, 11)).toBe(true);+ expect((transformer as any)._moveBufferBlocker(30, 30)).toBe(false);++ const movePoint = (transformer as any)._getMovePoint(40, 60, {+ left: 10,+ top: 20,+ width: 80,+ height: 40,+ angle: 30,+ });+ expect(Number.isFinite(movePoint.moveLeft)).toBe(true);+ expect(Number.isFinite(movePoint.moveTop)).toBe(true);++ const rotateFixed = (transformer as any)._applyRotationForResult(+ { left: 10, top: 20, width: 50, height: 30 },+ { left: 0, top: 0, width: 40, height: 20 },+ 25+ );+ expect(rotateFixed.width).toBeGreaterThan(0);+ expect(rotateFixed.height).toBeGreaterThan(0);++ const noRotate = (transformer as any)._applyRotationForResult(+ { left: 1, top: 2, width: 3, height: 4 },+ { left: 0, top: 0, width: 0, height: 0 },+ 0+ );+ expect(noRotate).toEqual({ left: 1, top: 2, width: 3, height: 4 });++ const ltState = (transformer as any)._updateCloseKeepRatioState('__SpreadsheetTransformerResizeLT__', 10, 10, 60, 40, 55, 30);+ const rbState = (transformer as any)._updateCloseKeepRatioState('__SpreadsheetTransformerResizeRB__', 10, 10, 60, 40, -100, -100);+ expect(ltState.width).toBeGreaterThanOrEqual(20);+ expect(rbState.height).toBeGreaterThanOrEqual(20);++ const limited = (transformer as any)._getLimitedSize(120, 60);+ expect(limited.limitWidth).toBeGreaterThan(20);+ expect(limited.limitHeight).toBe(20);++ const ltFix = (transformer as any)._fixMoveLtRb(10, 2, 100, 50, 2);+ const lbFix = (transformer as any)._fixMoveLbRt(10, 2, 100, 50, 2);+ expect(Number.isFinite(ltFix.moveLeft)).toBe(true);+ expect(Number.isFinite(lbFix.moveTop)).toBe(true);++ const moveObject = {+ left: 10,+ top: 20,+ width: 100,+ height: 60,+ getState: () => ({ left: 10, top: 20, width: 100, height: 60 }),+ } as any;+ expect((transformer as any)._resizeLeftTop(moveObject, 5, 3, { width: 100, height: 60 }).width).toBeGreaterThan(0);+ expect((transformer as any)._resizeRightTop(moveObject, 5, 3, { width: 100, height: 60 }).height).toBeGreaterThan(0);+ expect((transformer as any)._resizeLeftBottom(moveObject, 5, 3, { width: 100, height: 60 }).width).toBeGreaterThan(0);+ expect((transformer as any)._resizeRightBottom(moveObject, 5, 3, { width: 100, height: 60 }).height).toBeGreaterThan(0);++ const recoveryTarget = {+ left: -4,+ top: -3,+ width: 20,+ height: 10,+ transformByState: vi.fn(),+ };+ (transformer as any)._recoverySizeBoundary([recoveryTarget], 0, 0, 100, 80);+ expect(recoveryTarget.transformByState).toHaveBeenCalled();++ expect((transformer as any)._getRotateAnchorCursor('__SpreadsheetTransformerResizeLM__')).toBe(CURSOR_TYPE.WEST_RESIZE);+ expect((transformer as any)._getRotateAnchorCursor('__SpreadsheetTransformerResizeCB__')).toBe(CURSOR_TYPE.SOUTH_RESIZE);+ expect((transformer as any)._getRotateAnchorCursor('__SpreadsheetTransformerRotate__')).toBe(CURSOR_TYPE.MOVE);+ expect((transformer as any)._checkTransformerType('__SpreadsheetTransformerResizeRT__123')).toBe('__SpreadsheetTransformerResizeRT__');+ expect((transformer as any)._getNorthEastPoints(10, 4)[0]).toHaveLength(6);+ expect((transformer as any)._getNorthWestPoints(10, 4)[0]).toHaveLength(6);+ expect((transformer as any)._getSouthEastPoints(10, 4)[0]).toHaveLength(7);+ expect((transformer as any)._getSouthWestPoints(10, 4)[0]).toHaveLength(7);+ expect((transformer as any)._smoothAccuracy(1.23456)).toBe(1.2);+ expect((transformer as any)._smoothAccuracy(1.23456, true)).toBe(1.235);++ transformer.dispose();+ });++ it('covers transformer attach, controls, resize and rotate flows', () => {+ const { engine, scene } = createFixture();+ engine.setActiveScene(scene.sceneKey);++ const rect = scene.getObject('rect-main') as Rect;+ const transformer = new Transformer(scene, {+ rotateEnabled: true,+ resizeEnabled: true,+ enabledAnchors: [1, 1, 1, 1, 1, 1, 1, 1],+ borderEnabled: true,+ });++ const startSpy = vi.fn();+ const changingSpy = vi.fn();+ const endSpy = vi.fn();+ transformer.changeStart$.subscribe(startSpy);+ transformer.changing$.subscribe(changingSpy);+ transformer.changeEnd$.subscribe(endSpy);++ transformer.attachTo(rect);+ (rect.onPointerDown$ as any).emitEvent(+ createInputEvent('pointerdown', { offsetX: 20, offsetY: 20 }),+ { stopPropagation: vi.fn() }+ );+ scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 80, offsetY: 60 }));+ scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 80, offsetY: 60 }));+ expect(startSpy).toHaveBeenCalled();+ expect(changingSpy).toHaveBeenCalled();+ expect(endSpy).toHaveBeenCalled();++ transformer.setSelectedControl(rect);+ const control = (transformer as any)._transformerControlMap.get(rect.oKey) as Group;+ expect(control).toBeTruthy();+ const allControlObjects = control.getObjects();++ const resizeAnchor = allControlObjects.find((o) => o.oKey.includes('__SpreadsheetTransformerResizeRB__')) as Rect;+ (resizeAnchor.onPointerDown$ as any).emitEvent(+ createInputEvent('pointerdown', { offsetX: 26, offsetY: 26 }),+ { stopPropagation: vi.fn() }+ );+ scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 96, offsetY: 92 }));+ scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 96, offsetY: 92 }));++ const rotateAnchor = allControlObjects.find(+ (o) => o.oKey.includes('__SpreadsheetTransformerRotate__') && !o.oKey.includes('LINE')+ ) as Rect | undefined;+ if (rotateAnchor) {+ (rotateAnchor.onPointerDown$ as any).emitEvent(+ createInputEvent('pointerdown', { offsetX: 30, offsetY: 8 }),+ { stopPropagation: vi.fn() }+ );+ scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 120, offsetY: 90 }));+ scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 120, offsetY: 90 }));+ } else {+ (transformer as any)._moveBufferSkip = true;+ (transformer as any)._startOffsetX = 30;+ (transformer as any)._startOffsetY = 8;+ (transformer as any)._viewportScrollX = 0;+ (transformer as any)._viewportScrollY = 0;+ (transformer as any)._rotateMoving(120, 90, 60, 40, 0);+ }++ expect(rect.width).toBeGreaterThan(0);+ expect(rect.height).toBeGreaterThan(0);+ expect(rect.angle).toBeGreaterThanOrEqual(0);++ transformer.clearControlByIds([rect.oKey]);+ rect.transformerConfig = {+ isCropper: true,+ resizeEnabled: true,+ enabledAnchors: [1, 1, 1, 1, 1, 1, 1, 1],+ } as any;+ transformer.createControlForCopper(rect);+ expect((transformer as any)._copperControl).toBeTruthy();+ transformer.clearCopperControl();++ transformer.clearSelectedObjects();+ transformer.dispose();+ scene.dispose();+ engine.dispose();+ });++ it('covers scene/viewport utility and early-return branches', () => {+ const { engine, scene, viewport } = createFixture();++ scene.transformByState({});+ scene.makeDirtyNoParent(true);+ scene.enableLayerCache(1);+ scene.disableLayerCache(1);+ expect(scene.getAncestorScale()).toEqual({+ scaleX: expect.any(Number),+ scaleY: expect.any(Number),+ });+ expect(scene.ancestorLeft).toBeGreaterThanOrEqual(0);+ expect(scene.ancestorTop).toBeGreaterThanOrEqual(0);+ expect(scene.getLayerMaxZIndex()).toBeGreaterThanOrEqual(1);+ expect(scene.findLayerByZIndex(999)).toBeUndefined();++ const extraRect = new Rect('rect-extra', {+ left: 1,+ top: 1,+ width: 5,+ height: 5,+ });+ scene.addObjects([extraRect], 3);+ expect(scene.getObject('rect-extra')).toBeTruthy();+ expect(scene.getObjectIncludeInGroup('rect-extra')).toBeTruthy();+ expect(scene.fuzzyMathObjects('rect', true).length).toBeGreaterThan(0);+ expect(scene.getObjectsByLayer(3).length).toBeGreaterThan(0);++ expect(scene.removeObject()).toBeUndefined();+ expect(scene.removeObjects()).toBeUndefined();+ expect(scene.removeObject('rect-extra')).toBe(scene);+ expect(scene.removeObjects(['rect-main'] as any)).toBe(scene);++ const orphan = new Rect('orphan', { left: 0, top: 0, width: 2, height: 2 });+ const emitSpy = vi.spyOn(orphan.onIsAddedToParent$, 'emitEvent');+ scene.setObjectBehavior(orphan);+ expect(orphan.parent).toBe(scene);+ expect(emitSpy).toHaveBeenCalled();++ const tempViewport = new Viewport('temp-vp', scene, {+ left: 1,+ top: 1,+ width: 20,+ height: 10,+ active: false,+ });+ expect(scene.getViewport('temp-vp')).toBe(tempViewport);+ expect(scene.getViewports().some((vp) => vp.viewportKey === 'temp-vp')).toBe(true);+ expect(scene.removeViewport('temp-vp')).toBe(tempViewport);+ expect(scene.getViewport('temp-vp')).toBeUndefined();++ expect(scene.getVpScrollXYInfoByPosToVp(Vector2.FromArray([1, 1]), viewport)).toEqual({+ x: expect.any(Number),+ y: expect.any(Number),+ });+ expect(scene.getRelativeToViewportCoord(Vector2.FromArray([2, 3]))).toEqual(expect.any(Object));+ expect(scene.getPrecisionScale().scaleX).toBeGreaterThan(0);+ expect(scene.getPrecisionScale().scaleY).toBeGreaterThan(0);++ viewport.height = 9999;+ viewport.top = 2;+ viewport.left = 3;+ viewport.bottom = 4;+ viewport.right = 5;+ viewport.preCacheBound = { left: 0, top: 0, right: 1, bottom: 1 };+ viewport.cacheBound = { left: 0, top: 0, right: 2, bottom: 2 };+ viewport.updateScrollVal({ scrollX: 5, scrollY: 6, viewportScrollX: 7, viewportScrollY: 8 });+ expect(viewport.topOrigin).toBe(2);+ expect(viewport.leftOrigin).toBe(3);+ expect(viewport.bottomOrigin).toBe(4);+ expect(viewport.rightOrigin).toBe(5);+ expect(viewport.bottom).toBeGreaterThanOrEqual(0);+ expect(viewport.right).toBeGreaterThanOrEqual(0);+ expect(viewport.isWheelPreventDefaultX).toBeDefined();+ expect(viewport.isWheelPreventDefaultY).toBeDefined();+ expect(viewport.viewBound).toBeTruthy();+ expect(viewport.cacheBound).toBeTruthy();+ expect(viewport.preCacheBound).toBeTruthy();+ expect((viewport as any)._deltaScrollX).toBeDefined();+ expect((viewport as any)._deltaScrollY).toBeDefined();+ expect((viewport as any)._deltaViewportScrollX).toBeDefined();+ expect((viewport as any)._deltaViewportScrollY).toBeDefined();+ expect(viewport.getScrollBar()).toBeTruthy();+ expect(viewport.getViewportScrollByScrollXY()).toEqual(expect.objectContaining({+ x: expect.any(Number),+ y: expect.any(Number),+ }));++ expect(viewport.resizeWhenFreezeChange({} as any)).toBeUndefined();+ viewport.disable();+ expect(viewport.scrollToViewportPos({ viewportScrollX: 1, viewportScrollY: 1 })).toBeUndefined();+ expect(viewport.scrollByViewportDeltaVal({ viewportScrollX: 1, viewportScrollY: 1 })).toBeUndefined();+ viewport.enable();++ const viewportNoScrollBar = new Viewport('temp-vp-2', scene, {+ left: 0,+ top: 0,+ width: 20,+ height: 10,+ active: true,+ });+ viewportNoScrollBar.scrollX = 11;+ viewportNoScrollBar.scrollY = 12;+ expect(viewportNoScrollBar.transViewportScroll2ScrollValue(2, 3)).toEqual({ x: 11, y: 12 });+ viewportNoScrollBar.viewportScrollX = 13;+ viewportNoScrollBar.viewportScrollY = 14;+ const transNoBar = viewportNoScrollBar.transScroll2ViewportScrollValue(1, 2);+ expect(transNoBar.x).toBeGreaterThan(0);+ expect(transNoBar.y).toBeGreaterThan(0);+ viewportNoScrollBar.disable();+ const defaultInfo = viewportNoScrollBar.calcViewportInfo();+ expect(defaultInfo.viewportKey).toBe('temp-vp-2');+ viewportNoScrollBar.render(undefined, []);+ viewportNoScrollBar.dispose();++ scene.dispose();+ engine.dispose();+ });+});diff --git a/packages/engine-render/src/__tests__/jest-canvas-mock-lib.d.ts b/packages/engine-render/src/__tests__/jest-canvas-mock-lib.d.tsnew file mode 100644index 0000000000..302eac97a2--- /dev/null+++ b/packages/engine-render/src/__tests__/jest-canvas-mock-lib.d.ts@@ -0,0 +1,3 @@+declare module 'jest-canvas-mock/lib/index.js' {+ export function setupJestCanvasMock(window?: Window): void;+}diff --git a/packages/engine-render/src/__tests__/render-test-utils.ts b/packages/engine-render/src/__tests__/render-test-utils.tsnew file mode 100644index 0000000000..54bbb6f81b--- /dev/null+++ b/packages/engine-render/src/__tests__/render-test-utils.ts@@ -0,0 +1,146 @@+/**+ * 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 { vi } from 'vitest';++function patchCanvasContextProto() {+ const proto = (globalThis as any).CanvasRenderingContext2D?.prototype as Record<string, unknown> | undefined;+ if (!proto) {+ return;+ }++ if (!proto.getTransform) {+ proto.getTransform = vi.fn(() => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }));+ }+ if (!proto.getContextAttributes) {+ proto.getContextAttributes = vi.fn(() => ({}));+ }+ if (!proto.reset) {+ proto.reset = vi.fn();+ }+ if (!proto.roundRect) {+ proto.roundRect = vi.fn();+ }+ if (!proto.drawFocusIfNeeded) {+ proto.drawFocusIfNeeded = vi.fn();+ }+ if (!proto.createConicGradient) {+ proto.createConicGradient = vi.fn(() => ({ addColorStop: vi.fn() }));+ }+ if (!proto.isContextLost) {+ proto.isContextLost = vi.fn(() => false);+ }++ if (proto.webkitBackingStorePixelRatio == null) {+ proto.webkitBackingStorePixelRatio = 1;+ }+ if (proto.mozBackingStorePixelRatio == null) {+ proto.mozBackingStorePixelRatio = 1;+ }+ if (proto.msBackingStorePixelRatio == null) {+ proto.msBackingStorePixelRatio = 1;+ }+ if (proto.oBackingStorePixelRatio == null) {+ proto.oBackingStorePixelRatio = 1;+ }+ if (proto.backingStorePixelRatio == null) {+ proto.backingStorePixelRatio = 1;+ }+}++function patchPointerCapture() {+ const proto = HTMLCanvasElement.prototype as any;+ if (!proto.setPointerCapture) {+ proto.setPointerCapture = () => {};+ }+ if (!proto.releasePointerCapture) {+ proto.releasePointerCapture = () => {};+ }+ if (!proto.hasPointerCapture) {+ proto.hasPointerCapture = () => false;+ }++ const captureMap = new WeakMap<HTMLCanvasElement, Set<number>>();+ const getCaptureSet = (canvas: HTMLCanvasElement) => {+ let set = captureMap.get(canvas);+ if (!set) {+ set = new Set<number>();+ captureMap.set(canvas, set);+ }+ return set;+ };++ const setPointerCaptureSpy = vi.spyOn(proto, 'setPointerCapture').mockImplementation(function (+ this: HTMLCanvasElement,+ ...args: unknown[]+ ) {+ getCaptureSet(this).add(Number(args[0]));+ });+ const releasePointerCaptureSpy = vi.spyOn(proto, 'releasePointerCapture').mockImplementation(function (+ this: HTMLCanvasElement,+ ...args: unknown[]+ ) {+ getCaptureSet(this).delete(Number(args[0]));+ });+ const hasPointerCaptureSpy = vi.spyOn(proto, 'hasPointerCapture').mockImplementation(function (+ this: HTMLCanvasElement,+ ...args: unknown[]+ ) {+ return getCaptureSet(this).has(Number(args[0]));+ });++ return {+ setPointerCaptureSpy,+ releasePointerCaptureSpy,+ hasPointerCaptureSpy,+ };+}++export function setupRenderTestEnv() {+ const originalJest = (globalThis as any).jest;+ const originalResizeObserver = (globalThis as any).ResizeObserver;+ const originalRequestIdleCallback = (window as any).requestIdleCallback;+ const originalCancelIdleCallback = (window as any).cancelIdleCallback;++ (globalThis as any).jest = vi;+ patchCanvasContextProto();++ class ResizeObserverMock {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ }+ (globalThis as any).ResizeObserver = ResizeObserverMock;+ (window as any).requestIdleCallback = (cb: IdleRequestCallback) => setTimeout(() => cb({+ didTimeout: false,+ timeRemaining: () => 16,+ } as IdleDeadline), 0);+ (window as any).cancelIdleCallback = (id: number) => clearTimeout(id);++ const pointerPatches = patchPointerCapture();++ return {+ restore() {+ pointerPatches.setPointerCaptureSpy.mockRestore();+ pointerPatches.releasePointerCaptureSpy.mockRestore();+ pointerPatches.hasPointerCaptureSpy.mockRestore();+ (globalThis as any).jest = originalJest;+ (globalThis as any).ResizeObserver = originalResizeObserver;+ (window as any).requestIdleCallback = originalRequestIdleCallback;+ (window as any).cancelIdleCallback = originalCancelIdleCallback;+ },+ };+}diff --git a/packages/engine-render/src/basics/__tests__/draw.spec.ts b/packages/engine-render/src/basics/__tests__/draw.spec.tsnew file mode 100644index 0000000000..c0afb09c06--- /dev/null+++ b/packages/engine-render/src/basics/__tests__/draw.spec.ts@@ -0,0 +1,154 @@+/**+ * 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 { BorderStyleTypes } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { BORDER_TYPE, ORIENTATION_TYPE } from '../const';+import {+ calculateRectRotate,+ clearLineByBorderType,+ drawDiagonalLineByBorderType,+ drawLineByBorderType,+ getDevicePixelRatio,+ getLineOffset,+ getLineWidth,+ getLineWith,+ getRotateOffsetAndFarthestHypotenuse,+ getRotateOrientation,+ getTranslateInSpreadContextWithPixelRatio,+ setLineType,+} from '../draw';+import { Vector2 } from '../vector2';++function createCtxMock() {+ return {+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ clearRectForTexture: vi.fn(),+ setLineDash: vi.fn(),+ } as any;+}++describe('draw extra', () => {+ beforeEach(() => {+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({+ webkitBackingStorePixelRatio: 1,+ mozBackingStorePixelRatio: 1,+ msBackingStorePixelRatio: 1,+ oBackingStorePixelRatio: 1,+ backingStorePixelRatio: 1,+ } as any);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('gets pixel ratio and line helpers', () => {+ const ratio = getDevicePixelRatio();+ expect(ratio).toBeGreaterThanOrEqual(1);++ expect(getLineWith(2)).toBeGreaterThan(0);+ expect(getLineOffset()).toBeGreaterThanOrEqual(0);+ expect(getLineOffset()).toBeLessThan(1);+ expect(getLineWidth(BorderStyleTypes.THICK)).toBe(3);+ expect(getLineWidth(BorderStyleTypes.MEDIUM)).toBe(2);+ expect(getLineWidth(BorderStyleTypes.DASHED)).toBe(1);+ });++ it('draws and clears lines by border type', () => {+ const ctx = createCtxMock();+ const position = { startX: 10, startY: 20, endX: 30, endY: 40 };++ drawLineByBorderType(ctx, BORDER_TYPE.TOP, 1, position);+ drawLineByBorderType(ctx, BORDER_TYPE.BOTTOM, 1, position);+ drawLineByBorderType(ctx, BORDER_TYPE.LEFT, 1, position);+ drawLineByBorderType(ctx, BORDER_TYPE.RIGHT, 1, position);++ expect(ctx.beginPath).toHaveBeenCalledTimes(4);+ expect(ctx.moveToByPrecision).toHaveBeenCalledTimes(4);+ expect(ctx.lineToByPrecision).toHaveBeenCalledTimes(4);+ expect(ctx.stroke).toHaveBeenCalledTimes(4);++ clearLineByBorderType(ctx, BORDER_TYPE.TOP, position);+ clearLineByBorderType(ctx, BORDER_TYPE.BOTTOM, position);+ clearLineByBorderType(ctx, BORDER_TYPE.LEFT, position);+ clearLineByBorderType(ctx, BORDER_TYPE.RIGHT, position);+ expect(ctx.clearRectForTexture).toHaveBeenCalledTimes(4);+ });++ it('draws diagonal lines and sets line styles', () => {+ const ctx = createCtxMock();+ const position = { startX: 0, startY: 0, endX: 20, endY: 20 };++ drawDiagonalLineByBorderType(ctx, BorderStyleTypes.DOUBLE, BORDER_TYPE.TL_BR, position);+ drawDiagonalLineByBorderType(ctx, BorderStyleTypes.DOUBLE, BORDER_TYPE.BL_TR, position);+ drawDiagonalLineByBorderType(ctx, BorderStyleTypes.THIN, BORDER_TYPE.TL_BC, position);++ expect(ctx.moveToByPrecision).toHaveBeenCalled();+ expect(ctx.lineToByPrecision).toHaveBeenCalled();+ expect(ctx.stroke).toHaveBeenCalled();++ setLineType(ctx, BorderStyleTypes.HAIR);+ setLineType(ctx, BorderStyleTypes.DASH_DOT_DOT);+ setLineType(ctx, BorderStyleTypes.DASH_DOT);+ setLineType(ctx, BorderStyleTypes.DOTTED);+ setLineType(ctx, BorderStyleTypes.DASHED);+ setLineType(ctx, BorderStyleTypes.THICK);++ expect(ctx.setLineDash).toHaveBeenCalledTimes(6);+ });++ it('computes rotate offsets and translation helpers', () => {+ const rectResult = calculateRectRotate(+ new Vector2(10, 0),+ new Vector2(5, 5),+ Math.PI / 6,+ Math.PI / 4,+ new Vector2(2, 3)+ );+ expect(Number.isFinite(rectResult.x)).toBe(true);+ expect(Number.isFinite(rectResult.y)).toBe(true);++ expect(getRotateOrientation(0.2)).toBe(ORIENTATION_TYPE.DOWN);+ expect(getRotateOrientation(-0.2)).toBe(ORIENTATION_TYPE.UP);++ const resultUp = getRotateOffsetAndFarthestHypotenuse(+ [{ lineHeight: 10 }, { lineHeight: 20 }] as any,+ 100,+ -Math.PI / 6+ );+ expect(resultUp.rotateTranslateXList.length).toBe(2);+ expect(resultUp.rotatedHeight).toBeGreaterThan(0);++ const resultDown = getRotateOffsetAndFarthestHypotenuse(+ [{ lineHeight: 10 }, { lineHeight: 15 }, { lineHeight: 20 }] as any,+ 80,+ Math.PI / 6+ );+ expect(resultDown.rotateTranslateXList.length).toBe(3);+ expect(resultDown.rotatedWidth).toBeGreaterThan(0);++ const translate = getTranslateInSpreadContextWithPixelRatio();+ expect(translate).toEqual({+ left: expect.any(Number),+ top: expect.any(Number),+ });+ });+});diff --git a/packages/engine-render/src/basics/__tests__/tools.spec.ts b/packages/engine-render/src/basics/__tests__/tools.spec.tsnew file mode 100644index 0000000000..6826234bf6--- /dev/null+++ b/packages/engine-render/src/basics/__tests__/tools.spec.ts@@ -0,0 +1,310 @@+/**+ * 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 { BaselineOffset, BooleanNumber, GridType, NumberUnitType, Rectangle, Tools } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { FontCache } from '../../components/docs/layout/shaping-engine/font-cache';+import {+ cancelRequestFrame,+ checkStyle,+ clampRange,+ createCanvasElement,+ createImageElement,+ degToRad,+ expandRangeIfIntersects,+ fixLineWidthByScale,+ generateRandomKey,+ getCellPositionByIndex,+ getColor,+ getDPI,+ getFontStyleString,+ getPointerPrefix,+ getScale,+ getSizeForDom,+ getSystemHighlightColor,+ getValueType,+ hasAllLatin,+ hasArabic,+ hasBasicLatin,+ hasCJK,+ hasCJKPunctuation,+ hasCJKText,+ hasLatinExtendedA,+ hasLatinExtendedB,+ hasLatinOneSupplement,+ hasSpace,+ hasTibetan,+ hasUnMergedCellInRow,+ injectStyle,+ inViewRanges,+ isArray,+ isCjkCenterAlignedPunctuation,+ isCjkLeftAlignedPunctuation,+ isCjkRightAlignedPunctuation,+ isDate,+ isFunction,+ isNumber,+ isObject,+ isRectIntersect,+ isRegExp,+ IsSafari,+ isString,+ mergeInfoOffset,+ pixelToPt,+ precisionTo,+ ptToMM,+ ptToPixel,+ ptToPx,+ pxToInch,+ pxToNum,+ pxToPt,+ radToDeg,+ requestNewFrame,+ startWithEmoji,+ toPx,+} from '../tools';++describe('tools extra', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('handles colors, unit conversion and precision helpers', () => {+ expect(getColor([1, 2, 3])).toBe('rgb(1,2,3)');+ expect(getColor([1, 2, 3], 0.5)).toBe('rgba(1,2,3,0.5)');+ expect(getColor(undefined as any)).toBe('rgb(0,0,0)');++ expect(toPx(10, 100)).toBe(10);+ expect(toPx('50%', 200)).toBe(100);+ expect(toPx('invalid', 100)).toBe(0);++ expect(radToDeg(Math.PI)).toBeCloseTo(180);+ expect(degToRad(180)).toBeCloseTo(Math.PI);+ expect(precisionTo(1.2345, 2)).toBe(1.23);+ expect(fixLineWidthByScale(7, 2)).toBe(7);+ });++ it('uses request/cancel frame fallbacks and DOM factories', () => {+ const requester = {+ requestPostAnimationFrame: vi.fn(() => 11),+ cancelPostAnimationFrame: vi.fn(),+ };+ const frameId = requestNewFrame(() => null, requester);+ expect(frameId).toBe(11);+ cancelRequestFrame(frameId, requester);+ expect(requester.cancelPostAnimationFrame).toHaveBeenCalledWith(11);++ const requester2 = {+ requestAnimationFrame: vi.fn(() => 12),+ cancelAnimationFrame: vi.fn(),+ };+ expect(requestNewFrame(() => null, requester2)).toBe(12);+ cancelRequestFrame(12, requester2);+ expect(requester2.cancelAnimationFrame).toHaveBeenCalledWith(12);++ expect(createCanvasElement().tagName).toBe('CANVAS');+ expect(createImageElement().tagName).toBe('IMG');+ });++ it('detects pointer prefix and browser helpers', () => {+ const browserSpy = vi.spyOn(Tools, 'getBrowserType');+ browserSpy.mockReturnValue('safari' as any);+ expect(IsSafari()).toBe(true);+ browserSpy.mockReturnValue('chrome' as any);+ expect(IsSafari()).toBe(false);++ const tabletSpy = vi.spyOn(Tools, 'isTablet').mockReturnValue(false);+ const iphoneSpy = vi.spyOn(Tools, 'isIPhone').mockReturnValue(false);+ const originalPointer = (window as any).PointerEvent;+ (window as any).PointerEvent = undefined;++ expect(getPointerPrefix()).toBe('mouse');++ tabletSpy.mockReturnValue(true);+ expect(getPointerPrefix()).toBe('mouse');++ (window as any).PointerEvent = originalPointer;+ tabletSpy.mockRestore();+ iphoneSpy.mockRestore();+ });++ it('handles random key and type predicates', () => {+ const key = generateRandomKey('shape', 4);+ expect(key.startsWith('shape_')).toBe(true);++ expect(getValueType('a')).toBe('[object String]');+ expect(isFunction(() => null)).toBe(true);+ expect(isDate(new Date())).toBe(true);+ expect(isRegExp(/a/)).toBe(true);+ expect(isArray([1, 2])).toBe(true);+ expect(isString('abc')).toBe(true);+ expect(isNumber(123)).toBe(true);+ expect(isObject({ a: 1 })).toBe(true);+ });++ it('builds font styles and language detectors', () => {+ const baselineSpy = vi.spyOn(FontCache, 'getBaselineOffsetInfo').mockReturnValue({ sbr: 0.5, spr: 0.6 } as any);++ const defaultStyle = getFontStyleString();+ expect(defaultStyle.fontString).toContain('pt');++ const subscript = getFontStyleString({+ it: 1,+ bl: 1,+ fs: 12,+ ff: 'Open Sans',+ va: BaselineOffset.SUBSCRIPT,+ } as any);+ expect(subscript.fontFamily).toBe('"Open Sans"');+ expect(subscript.fontSize).toBeCloseTo(6);++ const superscript = getFontStyleString({+ fs: 12,+ ff: 'Arial',+ va: BaselineOffset.SUPERSCRIPT,+ } as any);+ expect(superscript.fontSize).toBeCloseTo(7.2);+ expect(baselineSpy).toHaveBeenCalled();++ expect(hasCJKText('中文')).toBe(true);+ expect(hasCJK('。')).toBe(true);+ expect(hasCJKPunctuation(',')).toBe(true);+ expect(hasAllLatin('abc')).toBe(true);+ expect(hasBasicLatin('A')).toBe(true);+ expect(hasLatinOneSupplement('é')).toBe(true);+ expect(hasLatinExtendedA('Ā')).toBe(true);+ expect(hasLatinExtendedB('Ȁ')).toBe(true);+ expect(startWithEmoji('😀abc')).toBe(true);+ expect(hasArabic('مرحبا')).toBe(true);+ expect(hasTibetan('Ȁ')).toBe(true);+ expect(hasSpace('a b')).toBe(true);+ expect(isCjkLeftAlignedPunctuation('。')).toBe(true);+ expect(isCjkRightAlignedPunctuation('(')).toBe(true);+ expect(isCjkCenterAlignedPunctuation('·')).toBe(true);+ });++ it('handles dpi and geometric conversion helpers', () => {+ const matchMediaMock = vi.fn((query: string) => ({+ matches: query.includes('96dpi'),+ }));+ vi.stubGlobal('matchMedia', matchMediaMock);++ const dpi = getDPI();+ expect(dpi).toBeGreaterThan(0);+ expect(ptToPx(72)).toBeGreaterThan(0);+ expect(pxToPt(96)).toBeGreaterThan(0);+ expect(ptToMM(10)).toBeGreaterThan(0);+ expect(pxToInch(10)).toBeGreaterThan(0);++ expect(ptToPixel(8)).toBeCloseTo(10.6666666667);+ expect(pixelToPt(8)).toBe(6);+ expect(getScale({ scaleX: 2, scaleY: 3 })).toBe(3);+ });++ it('handles range and cell geometry helpers', () => {+ expect(getCellPositionByIndex(1, 1, [10, 20], [5, 10])).toEqual({+ startY: 10,+ endY: 20,+ startX: 5,+ endX: 10,+ });++ const mergeData = [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }];+ expect(hasUnMergedCellInRow(0, 0, 2, mergeData as any)).toBe(true);+ expect(hasUnMergedCellInRow(0, 0, 1, mergeData as any)).toBe(false);++ expect(mergeInfoOffset({+ startY: 1,+ endY: 2,+ startX: 3,+ endX: 4,+ } as any, 10, 20)).toEqual(expect.objectContaining({+ startY: 21,+ endY: 22,+ startX: 13,+ endX: 14,+ }));++ expect(isRectIntersect(+ { left: 0, top: 0, right: 10, bottom: 10 },+ { left: 5, top: 5, right: 20, bottom: 20 }+ )).toBe(true);+ expect(isRectIntersect(+ { left: 0, top: 0, right: 4, bottom: 4 },+ { left: 5, top: 5, right: 20, bottom: 20 }+ )).toBe(false);++ expect(inViewRanges([{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }], 2, 2)).toBe(true);+ expect(inViewRanges([{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }], 3, 2)).toBe(false);++ const intersects = expandRangeIfIntersects(+ [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }, { startRow: 5, endRow: 6, startColumn: 5, endColumn: 6 }]+ );+ expect(intersects).toHaveLength(2);+ expect(Rectangle.simpleRangesIntersect(intersects[0], intersects[1])).toBe(true);++ expect(clampRange({ startRow: -1, endRow: 9, startColumn: -2, endColumn: 10 }, 5, 6)).toEqual({+ startRow: 0,+ endRow: 5,+ startColumn: 0,+ endColumn: 6,+ });+ });++ it('handles style insertion and DOM size helpers', () => {+ injectStyle(['.tool-extra-test{color:red;}']);+ expect(checkStyle('tool-extra-test')).toBe(false);+ const style = document.createElement('style');+ style.textContent = '.tool-extra-test-manual{color:blue;}';+ document.head.append(style);+ expect(checkStyle('tool-extra-test-manual')).toBe(true);++ expect(pxToNum('12px')).toBe(12);+ const el = document.createElement('div');+ document.body.append(el);+ const styleSpy = vi.spyOn(window, 'getComputedStyle').mockReturnValue({+ borderTopWidth: '1px',+ borderLeftWidth: '2px',+ borderRightWidth: '3px',+ borderBottomWidth: '4px',+ width: '20px',+ height: '30px',+ } as any);+ expect(getSizeForDom(el)).toEqual({+ top: 1,+ left: 2,+ right: 3,+ bottom: 4,+ width: 20,+ height: 30,+ });+ styleSpy.mockRestore();++ const highlight = getSystemHighlightColor();+ expect(highlight).toEqual(expect.objectContaining({+ r: expect.any(Number),+ g: expect.any(Number),+ b: expect.any(Number),+ }));+ });++ it('keeps core enum imports consistent for helpers coverage', () => {+ expect(GridType.LINES).toBeGreaterThanOrEqual(0);+ expect(BooleanNumber.TRUE).toBe(1);+ expect(NumberUnitType.PIXEL).toBeGreaterThanOrEqual(0);+ });+});diff --git a/packages/engine-render/src/basics/__tests__/transform.spec.ts b/packages/engine-render/src/basics/__tests__/transform.spec.tsnew file mode 100644index 0000000000..d149a81e9e--- /dev/null+++ b/packages/engine-render/src/basics/__tests__/transform.spec.ts@@ -0,0 +1,105 @@+/**+ * 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 { Transform } from '../transform';+import { Vector2 } from '../vector2';++describe('Transform extra', () => {+ it('applies translate/scale/rotate/skew/multiply and inverse transforms', () => {+ const transform = Transform.create();+ transform.translate(10, 20).scale(2, 3).rotate(90).skew(0.1, -0.2);++ const matrix = transform.getMatrix();+ expect(matrix.length).toBe(6);++ const point = new Vector2(2, 5);+ const world = transform.applyPoint(point);+ const local = transform.clone().invert().applyPoint(world);++ expect(local.x).toBeCloseTo(point.x, 4);+ expect(local.y).toBeCloseTo(point.y, 4);+ });++ it('copies and resets matrix values', () => {+ const transform = Transform.create([1, 2, 3, 4, 5, 6]);+ const copy = transform.copy();+ expect(copy.getMatrix()).toEqual([1, 2, 3, 4, 5, 6]);++ const target = Transform.create();+ transform.copyInto(target);+ expect(target.getMatrix()).toEqual([1, 2, 3, 4, 5, 6]);++ transform.reset();+ expect(transform.getMatrix()).toEqual([1, 0, 0, 1, 0, 0]);+ });++ it('supports matrix decomposition and composition', () => {+ const transform = Transform.create().composeMatrix({+ left: 30,+ top: 40,+ angle: 15,+ scaleX: 2,+ scaleY: 3,+ skewX: 10,+ skewY: -5,+ flipX: false,+ flipY: true,+ });++ const dom = transform.convert2DOMMatrix2D();+ expect(dom).toEqual(expect.objectContaining({+ a: expect.any(Number),+ b: expect.any(Number),+ c: expect.any(Number),+ d: expect.any(Number),+ e: expect.any(Number),+ f: expect.any(Number),+ }));++ const decomposed = transform.decompose();+ expect(decomposed.x).toBeCloseTo(30, 3);+ expect(decomposed.y).toBeCloseTo(40, 3);+ expect(decomposed.scaleX).toBeCloseTo(2, 1);+ });++ it('supports absolute positioning and matrix rounding helpers', () => {+ const transform = Transform.create().translate(10, 20);+ transform.setAbsolutePosition(new Vector2(30, 40));+ const translated = transform.getTranslation();+ expect(translated.x).toBeCloseTo(30, 5);+ expect(translated.y).toBeCloseTo(40, 5);++ const rounded = Transform.create([1 / 3, 2 / 3, 0, 1, 0, 0]).getMatrixByAccurate(2);+ expect(rounded).toEqual([0.33, 0.67, 0, 1, 0, 0]);+ });++ it('computes bounding boxes from transformed points', () => {+ const transform = Transform.create([1, 0, 0, 1, 5, -2]);+ const bounds = transform.makeBoundingBoxFromPoints([+ new Vector2(0, 0),+ new Vector2(4, 0),+ new Vector2(4, 3),+ new Vector2(0, 3),+ ]);++ expect(bounds.left).toBe(5);+ expect(bounds.top).toBe(-2);+ expect(bounds.width).toBe(4);+ expect(bounds.height).toBe(3);+ expect(bounds.points[0].asArray()).toEqual([5, -2]);+ });+});diff --git a/packages/engine-render/src/basics/__tests__/vector2.spec.ts b/packages/engine-render/src/basics/__tests__/vector2.spec.tsnew file mode 100644index 0000000000..35b935c6e6--- /dev/null+++ b/packages/engine-render/src/basics/__tests__/vector2.spec.ts@@ -0,0 +1,175 @@+/**+ * 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 { Vector2 } from '../vector2';++describe('Vector2 extra', () => {+ it('supports static constructors and interpolation helpers', () => {+ expect(Vector2.Zero().asArray()).toEqual([0, 0]);+ expect(Vector2.One().asArray()).toEqual([1, 1]);+ expect(Vector2.FromArray([9, 8, 7], 1).asArray()).toEqual([8, 7]);++ const target = new Vector2();+ Vector2.FromArrayToRef([3, 4], 0, target);+ expect(target.asArray()).toEqual([3, 4]);++ const catmull = Vector2.CatmullRom(+ new Vector2(0, 0),+ new Vector2(10, 0),+ new Vector2(10, 10),+ new Vector2(20, 10),+ 0.5+ );+ expect(catmull.x).toBeCloseTo(10);+ expect(catmull.y).toBeCloseTo(5);++ const hermite = Vector2.Hermite(+ new Vector2(0, 0),+ new Vector2(2, 0),+ new Vector2(10, 10),+ new Vector2(0, 2),+ 0.5+ );+ expect(hermite.x).toBeCloseTo(5.25);+ expect(hermite.y).toBeCloseTo(4.75);++ const derivative = Vector2.Hermite1stDerivative(+ new Vector2(0, 0),+ new Vector2(2, 0),+ new Vector2(10, 10),+ new Vector2(0, 2),+ 0.5+ );+ expect(derivative.x).toBeCloseTo(14.5);+ expect(derivative.y).toBeCloseTo(14.5);+ });++ it('supports static geometry helpers', () => {+ const value = new Vector2(5, -3);+ const clamped = Vector2.Clamp(value, new Vector2(0, -2), new Vector2(4, 2));+ expect(clamped.asArray()).toEqual([4, -2]);++ expect(Vector2.Lerp(new Vector2(0, 0), new Vector2(10, 20), 0.25).asArray()).toEqual([2.5, 5]);+ expect(Vector2.Dot(new Vector2(2, 3), new Vector2(4, -1))).toBe(5);++ expect(Vector2.Normalize(new Vector2(3, 4)).asArray()).toEqual([0.6, 0.8]);++ const zeroResult = new Vector2(10, 10);+ Vector2.NormalizeToRef(new Vector2(0, 0), zeroResult);+ expect(zeroResult.asArray()).toEqual([10, 10]);++ expect(Vector2.Minimize(new Vector2(1, 5), new Vector2(2, 4)).asArray()).toEqual([1, 4]);+ expect(Vector2.Maximize(new Vector2(1, 5), new Vector2(2, 4)).asArray()).toEqual([2, 5]);++ expect(+ Vector2.PointInTriangle(+ new Vector2(1, 1),+ new Vector2(0, 0),+ new Vector2(4, 0),+ new Vector2(0, 4)+ )+ ).toBe(true);+ expect(+ Vector2.PointInTriangle(+ new Vector2(4, 4),+ new Vector2(0, 0),+ new Vector2(4, 0),+ new Vector2(0, 4)+ )+ ).toBe(false);++ expect(Vector2.Distance(new Vector2(0, 0), new Vector2(3, 4))).toBe(5);+ expect(Vector2.DistanceSquared(new Vector2(0, 0), new Vector2(3, 4))).toBe(25);+ expect(Vector2.Center(new Vector2(0, 0), new Vector2(4, 2)).asArray()).toEqual([2, 1]);+ expect(Vector2.DistanceOfPointFromSegment(new Vector2(5, 2), new Vector2(0, 0), new Vector2(10, 0))).toBe(2);+ });++ it('supports instance operators and transforms', () => {+ const vec = new Vector2(3, 4);+ expect(vec.getClassName()).toBe('Vector2');+ expect(vec.getHashCode()).toBe((3 * 397) ^ 4);+ expect(vec.toString()).toBe('{X: 3 Y: 4}');++ const arr: number[] = [];+ vec.toArray(arr);+ expect(arr).toEqual([3, 4]);+ expect(new Vector2().fromArray(arr).asArray()).toEqual([3, 4]);+ expect(vec.asArray()).toEqual([3, 4]);++ const ref = new Vector2();+ expect(vec.add(new Vector2(1, 2)).asArray()).toEqual([4, 6]);+ vec.addToRef(new Vector2(1, 2), ref);+ expect(ref.asArray()).toEqual([4, 6]);+ expect(vec.addByPoint(2, -1).asArray()).toEqual([5, 3]);++ expect(vec.clone().addInPlace(new Vector2(1, 2)).asArray()).toEqual([4, 6]);+ expect(vec.subtract(new Vector2(1, 2)).asArray()).toEqual([2, 2]);+ expect(vec.subtractByPoint(2, -1).asArray()).toEqual([1, 5]);+ vec.subtractToRef(new Vector2(1, 2), ref);+ expect(ref.asArray()).toEqual([2, 2]);+ expect(vec.clone().subtractInPlace(new Vector2(1, 2)).asArray()).toEqual([2, 2]);++ expect(vec.clone().multiplyInPlace(new Vector2(2, 3)).asArray()).toEqual([6, 12]);+ expect(vec.multiply(new Vector2(2, 3)).asArray()).toEqual([6, 12]);+ vec.multiplyToRef(new Vector2(2, 3), ref);+ expect(ref.asArray()).toEqual([6, 12]);+ expect(vec.multiplyByFloats(2, 3).asArray()).toEqual([6, 12]);++ expect(vec.divide(new Vector2(3, 2)).asArray()).toEqual([1, 2]);+ vec.divideToRef(new Vector2(3, 2), ref);+ expect(ref.asArray()).toEqual([1, 2]);+ expect(vec.clone().divideInPlace(new Vector2(3, 2)).asArray()).toEqual([1, 2]);++ expect(vec.negate().asArray()).toEqual([-3, -4]);+ expect(vec.clone().negateInPlace().asArray()).toEqual([-3, -4]);+ vec.negateToRef(ref);+ expect(ref.asArray()).toEqual([-3, -4]);++ expect(vec.clone().scaleInPlace(2).asArray()).toEqual([6, 8]);+ expect(vec.scale(2).asArray()).toEqual([6, 8]);+ vec.scaleToRef(2, ref);+ expect(ref.asArray()).toEqual([6, 8]);+ vec.scaleAndAddToRef(2, ref);+ expect(ref.asArray()).toEqual([12, 16]);++ expect(vec.equals(new Vector2(3, 4))).toBe(true);+ expect(vec.floor().asArray()).toEqual([3, 4]);+ expect(new Vector2(3.5, -2.25).fract().asArray()).toEqual([0.5, 0.75]);++ const rotated = new Vector2(1, 0).rotate(Math.PI / 2);+ expect(rotated.x).toBeCloseTo(0);+ expect(rotated.y).toBeCloseTo(1);++ const rotateRef = new Vector2();+ new Vector2(1, 0).rotateToRef(Math.PI / 2, rotateRef);+ expect(rotateRef.x).toBeCloseTo(0);+ expect(rotateRef.y).toBeCloseTo(1);++ const byPoint = new Vector2(2, 1).rotateByPoint(Math.PI / 2, new Vector2(1, 1));+ expect(byPoint.x).toBeCloseTo(1);+ expect(byPoint.y).toBeCloseTo(2);++ const coordOnRotate = new Vector2(3, 4).transformCoordinateOnRotate(Math.PI / 4);+ expect(coordOnRotate.length()).toBeCloseTo(5);+ expect(coordOnRotate.lengthSquared()).toBeCloseTo(25);+ expect(new Vector2(3, 4).normalize().asArray()).toEqual([0.6, 0.8]);++ expect(new Vector2().copyFrom(vec).asArray()).toEqual([3, 4]);+ expect(new Vector2().copyFromFloats(9, 8).asArray()).toEqual([9, 8]);+ expect(new Vector2().set(7, 6).clone().asArray()).toEqual([7, 6]);+ });+});diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.tsnew file mode 100644index 0000000000..b32edaa82b--- /dev/null+++ b/packages/engine-render/src/components/docs/extensions/__tests__/line.spec.ts@@ -0,0 +1,144 @@+/**+ * 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 { BaselineOffset, BooleanNumber, TextDecoration } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { Line } from '../line';++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ stroke: vi.fn(),+ setLineDash: vi.fn(),+ strokeStyle: '',+ lineWidth: 1,+ } as any;+}++function createGlyph() {+ return {+ content: 'A',+ left: 10,+ width: 12,+ ts: {+ cl: { rgb: '#333333' },+ ul: { s: BooleanNumber.TRUE, t: TextDecoration.SINGLE },+ st: { s: BooleanNumber.TRUE, t: TextDecoration.WAVY_DOUBLE },+ ol: { s: BooleanNumber.TRUE, t: TextDecoration.DASH_DOT_DOT_HEAVY, c: BooleanNumber.FALSE, cl: { rgb: '#00ff00' } },+ bbl: { s: BooleanNumber.TRUE, t: TextDecoration.DOUBLE },+ va: BaselineOffset.SUPERSCRIPT,+ },+ bBox: {+ sp: 2,+ spo: 1,+ sbo: 3,+ bd: 8,+ },+ parent: {+ parent: {+ asc: 6,+ dsc: 2,+ },+ },+ } as any;+}++describe('docs line extension', () => {+ it('draws underline/bottom-border/strikethrough/overline', () => {+ const line = new Line();+ (line as any).extensionOffset = {};++ const ctx = createCtx();+ const glyph = createGlyph();+ line.draw(ctx, { scaleX: 1, scaleY: 1 } as any, glyph);++ expect(ctx.beginPath).toHaveBeenCalled();+ expect(ctx.stroke).toHaveBeenCalled();+ expect(ctx.moveTo).toHaveBeenCalled();+ expect(ctx.lineTo).toHaveBeenCalled();+ });++ it('handles early return and baseline offset variants', () => {+ const line = new Line();+ (line as any).extensionOffset = {};++ const ctx = createCtx();++ const emptyGlyph = createGlyph();+ emptyGlyph.content = '\r';+ line.draw(ctx, { scaleX: 1, scaleY: 1 } as any, emptyGlyph);+ expect(ctx.beginPath).not.toHaveBeenCalled();++ const subGlyph = createGlyph();+ subGlyph.ts.va = BaselineOffset.SUBSCRIPT;+ line.draw(ctx, { scaleX: 1, scaleY: 1 } as any, subGlyph);+ expect(ctx.beginPath).toHaveBeenCalled();+ });++ it('covers private line helpers and line type switch', () => {+ const line = new Line() as any;+ line.extensionOffset = {};+ const ctx = createCtx();+ const glyph = createGlyph();++ line._drawLine(ctx, glyph, { s: BooleanNumber.FALSE }, 10, 1);+ expect(ctx.beginPath).not.toHaveBeenCalled();++ line._setLineType(ctx, TextDecoration.SINGLE, 5);+ expect(ctx.lineWidth).toBe(1);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([0]);++ line._setLineType(ctx, TextDecoration.DOTTED_HEAVY, 5);+ expect(ctx.lineWidth).toBe(2);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([2]);++ line._setLineType(ctx, TextDecoration.DASH_LONG, 5);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([6]);++ line._setLineType(ctx, TextDecoration.DOT_DASH, 5);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([2, 5, 2]);++ line._setLineType(ctx, TextDecoration.DASH_DOT_DOT_HEAVY, 5);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([2, 2, 5, 2, 2]);++ line._setLineType(ctx, TextDecoration.WAVY_HEAVY, 5);+ expect(ctx.lineWidth).toBe(2);++ line._setLineType(ctx, 999, 7);+ expect(ctx.lineWidth).toBe(7);++ line._drawLineTo(ctx, 0, 4, 2, TextDecoration.WAVE);+ const waveCalls = ctx.lineTo.mock.calls.length;+ line._drawLineTo(ctx, 0, 2, 3, TextDecoration.SINGLE);+ expect(ctx.lineTo.mock.calls.length).toBeGreaterThan(waveCalls);++ expect(line._isWave(TextDecoration.WAVE)).toBe(true);+ expect(line._isWave(TextDecoration.SINGLE)).toBe(false);+ expect(line._isDouble(TextDecoration.WAVY_DOUBLE)).toBe(true);+ expect(line._isDouble(TextDecoration.DASH)).toBe(false);+ });++ it('clears cache state', () => {+ const line = new Line() as any;+ line._preBackgroundColor = '#fff';+ line.clearCache();+ expect(line._preBackgroundColor).toBe('');+ });+});diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-simple-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-simple-skeleton.spec.tsnew file mode 100644index 0000000000..26151b0266--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-simple-skeleton.spec.ts@@ -0,0 +1,93 @@+/**+ * 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 { beforeEach, describe, expect, it, vi } from 'vitest';+import { DocSimpleSkeleton } from '../doc-simple-skeleton';+import { FontCache } from '../shaping-engine/font-cache';++function measure(text: string) {+ return {+ width: text.length * 10,+ fontBoundingBoxAscent: 8,+ fontBoundingBoxDescent: 2,+ } as any;+}++describe('doc simple skeleton', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(FontCache, 'getMeasureText').mockImplementation((text: string) => measure(text));+ });++ it('handles empty text and no-wrap text', () => {+ const empty = new DocSimpleSkeleton('', '12px Arial', true, 100, 100);+ const emptyLines = empty.calculate();+ expect(emptyLines).toEqual([+ {+ text: '',+ width: 0,+ height: 10,+ baseline: 8,+ },+ ]);+ expect(empty.getTotalHeight()).toBe(10);+ expect(empty.getTotalWidth()).toBe(0);++ const noWrap = new DocSimpleSkeleton('hello world', '12px Arial', false, 30, 200);+ const lines = noWrap.calculate();+ expect(lines).toHaveLength(1);+ expect(lines[0].text).toBe('hello world');+ expect(lines[0].width).toBe(110);+ expect(noWrap.getTotalHeight()).toBe(10);+ expect(noWrap.getTotalWidth()).toBe(110);+ });++ it('wraps long text and uses cache behavior', () => {+ const skeleton = new DocSimpleSkeleton('supercalifragilistic', '12px Arial', true, 25, 100);+ const lines = skeleton.calculate();+ expect(lines.length).toBeGreaterThan(1);+ expect(lines.every((line) => line.width > 0)).toBe(true);+ expect(lines.every((line) => line.width <= 25 || line.text.length === 1)).toBe(true);++ const callCountAfterFirst = (FontCache.getMeasureText as any).mock.calls.length;+ const second = skeleton.calculate();+ expect(second).toBe(lines);+ expect((FontCache.getMeasureText as any).mock.calls.length).toBe(callCountAfterFirst);+ });++ it('recalculates after makeDirty in no-wrap mode', () => {+ const skeleton = new DocSimpleSkeleton('hello world', '12px Arial', false, 30, 200);+ const first = skeleton.calculate();+ const callCountAfterFirst = (FontCache.getMeasureText as any).mock.calls.length;+ const second = skeleton.calculate();+ expect(second).toBe(first);+ expect((FontCache.getMeasureText as any).mock.calls.length).toBe(callCountAfterFirst);++ skeleton.makeDirty();+ const third = skeleton.calculate();+ expect(third).not.toBe(first);+ expect(third).toHaveLength(1);+ expect(third[0].text).toBe('hello world');+ expect((FontCache.getMeasureText as any).mock.calls.length).toBeGreaterThan(callCountAfterFirst);+ });++ it('respects height limits when wrapping', () => {+ const skeleton = new DocSimpleSkeleton('a b c d e f g h i j k', '12px Arial', true, 20, 15);+ const lines = skeleton.calculate();+ expect(lines.length).toBeGreaterThan(0);+ expect(skeleton.getTotalHeight()).toBeGreaterThanOrEqual(10);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.tsnew file mode 100644index 0000000000..bee1084944--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts@@ -0,0 +1,343 @@+/**+ * 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 { ColumnSeparatorType } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';+import { Vector2 } from '../../../../basics/vector2';+import { DocumentSkeleton } from '../doc-skeleton';++function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {+ const listGlyph = { st, ed: st, count: 1, width: 3, left: 0, xOffset: 0, content: '•', glyphType: GlyphType.LIST } as any;+ const glyphA = { st: st + 1, ed: st + 1, count: 1, width: 4, left: 3, xOffset: 0, content: 'A', glyphType: GlyphType.WORD } as any;+ const glyphB = { st: st + 2, ed: st + 3, count: 2, width: 7, left: 7, xOffset: 0, content: 'BC', glyphType: GlyphType.WORD } as any;++ const divide = {+ st,+ ed: st + 3,+ glyphGroup: [listGlyph, glyphA, glyphB],+ } as any;+ const line = {+ st,+ ed: st + 3,+ top: 0,+ lineHeight: 20,+ divides: [divide],+ } as any;+ const column = {+ st,+ ed: st + 3,+ left: 0,+ width: 120,+ lines: [line],+ } as any;+ const section = {+ st,+ ed: st + 3,+ top: 0,+ width: 120,+ height: 60,+ columns: [column],+ } as any;+ const page = {+ type,+ st,+ ed: st + 3,+ pageWidth: 200,+ width: 200,+ height: 80,+ marginTop: 10,+ marginBottom: 10,+ marginLeft: 5,+ marginRight: 5,+ headerId: 'header-seg',+ footerId: 'footer-seg',+ tableId,+ sections: [section],+ skeTables: new Map(),+ } as any;++ divide.parent = line;+ line.parent = column;+ column.parent = section;+ section.parent = page;+ listGlyph.parent = divide;+ glyphA.parent = divide;+ glyphB.parent = divide;++ return {+ page,+ section,+ column,+ line,+ divide,+ glyphs: { listGlyph, glyphA, glyphB },+ };+}++describe('doc skeleton', () => {+ it('covers size and position search for body/header/footer/cell pages', () => {+ const body = createPage(DocumentSkeletonPageType.BODY, 0);+ const header = createPage(DocumentSkeletonPageType.HEADER, 200);+ const footer = createPage(DocumentSkeletonPageType.FOOTER, 300);+ const cell = createPage(DocumentSkeletonPageType.CELL, 100, 'table-1');++ const row = { cells: [cell.page] } as any;+ const table = { rows: [row], tableId: 'table-1' } as any;+ row.parent = table;+ cell.page.parent = row;+ table.parent = body.page;+ body.page.skeTables = new Map([['table-1', table]]);++ const docViewModel = {+ getDataModel: () => ({+ documentStyle: {+ pageSize: { width: 210, height: 297 },+ },+ }),+ dispose: vi.fn(),+ } as any;++ const skeleton = new DocumentSkeleton(docViewModel, {} as any);+ const skeletonData = {+ pages: [body.page],+ skeHeaders: new Map([+ ['header-seg', new Map([[body.page.pageWidth, header.page]])],+ ]),+ skeFooters: new Map([+ ['footer-seg', new Map([[body.page.pageWidth, footer.page]])],+ ]),+ };+ (skeleton as any)._skeletonData = skeletonData;+ body.page.parent = skeletonData;++ expect(skeleton.getPageSize()).toEqual({ width: 210, height: 297 });+ expect(skeleton.getActualSize()).toEqual({ actualWidth: 200, actualHeight: 80 });+ skeleton.resetInitialWidth();++ const bodyPos = skeleton.findPositionByGlyph(body.glyphs.glyphA as any, 0);+ expect(bodyPos).toEqual(expect.objectContaining({+ pageType: DocumentSkeletonPageType.BODY,+ page: 0,+ glyph: 1,+ }));++ const cellPos = skeleton.findPositionByGlyph(cell.glyphs.glyphA as any, 0);+ expect(cellPos?.pageType).toBe(DocumentSkeletonPageType.CELL);+ expect(cellPos?.path).toEqual(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]);++ const byBodyCoord = skeleton.findGlyphByPosition({+ pageType: DocumentSkeletonPageType.BODY,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 0,+ segmentPage: 0,+ path: ['pages', 0],+ isBack: true,+ } as any);+ expect(byBodyCoord).toBe(body.glyphs.glyphA);++ const byHeaderCoord = skeleton.findGlyphByPosition({+ pageType: DocumentSkeletonPageType.HEADER,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 1,+ segmentPage: 0,+ path: ['pages', 0],+ isBack: false,+ } as any);+ expect(byHeaderCoord).toBe(header.glyphs.glyphA);++ const byFooterCoord = skeleton.findGlyphByPosition({+ pageType: DocumentSkeletonPageType.FOOTER,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 2,+ segmentPage: 0,+ path: ['pages', 0],+ isBack: true,+ } as any);+ expect(byFooterCoord).toBe(footer.glyphs.glyphB);++ const charIndexBack = skeleton.findCharIndexByPosition({+ pageType: DocumentSkeletonPageType.BODY,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 2,+ segmentPage: 0,+ path: ['pages', 0],+ isBack: true,+ } as any);+ expect(charIndexBack).toBe(2);++ const charIndexFore = skeleton.findCharIndexByPosition({+ pageType: DocumentSkeletonPageType.BODY,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 2,+ segmentPage: 0,+ path: ['pages', 0],+ isBack: false,+ } as any);+ expect(charIndexFore).toBe(4);++ const nodePosBody = skeleton.findNodePositionByCharIndex(2, true);+ expect(nodePosBody?.pageType).toBe(DocumentSkeletonPageType.BODY);+ const nodePosHeader = skeleton.findNodePositionByCharIndex(201, false, 'header-seg', 0);+ expect(nodePosHeader?.pageType).toBe(DocumentSkeletonPageType.HEADER);+ const nodePosFooter = skeleton.findNodePositionByCharIndex(301, false, 'footer-seg', 0);+ expect(nodePosFooter?.pageType).toBe(DocumentSkeletonPageType.FOOTER);+ const nodePosCell = skeleton.findNodePositionByCharIndex(101, true);+ expect(nodePosCell?.pageType).toBe(DocumentSkeletonPageType.CELL);++ expect(skeleton.findNodeByCharIndex(2)).toBe(body.glyphs.glyphB);+ expect(skeleton.findNodeByCharIndex(201, 'header-seg', 0)).toBe(header.glyphs.glyphA);+ expect(skeleton.findNodeByCharIndex(999)).toBeUndefined();++ skeleton.dispose();+ expect(docViewModel.dispose).toHaveBeenCalled();+ });++ it('covers coordinate search helpers and nearest-node strategies', () => {+ const body = createPage(DocumentSkeletonPageType.BODY, 0);+ const header = createPage(DocumentSkeletonPageType.HEADER, 200);+ const footer = createPage(DocumentSkeletonPageType.FOOTER, 300);++ const docViewModel = {+ getDataModel: () => ({+ documentStyle: {+ pageSize: { width: 210, height: 297 },+ },+ }),+ getHeaderFooterTreeMap: () => ({+ headerTreeMap: new Map(),+ footerTreeMap: new Map(),+ }),+ dispose: vi.fn(),+ } as any;+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);+ (skeleton as any)._skeletonData = {+ pages: [body.page],+ skeHeaders: new Map([['header-seg', new Map([[body.page.pageWidth, header.page]])]]),+ skeFooters: new Map([['footer-seg', new Map([[body.page.pageWidth, footer.page]])]]),+ };+ body.page.parent = (skeleton as any)._skeletonData;++ const headerArea = skeleton.findEditAreaByCoord(Vector2.FromArray([20, 5]), PageLayoutType.VERTICAL, 0, 0);+ const bodyArea = skeleton.findEditAreaByCoord(Vector2.FromArray([20, 20]), PageLayoutType.VERTICAL, 0, 0);+ const footerArea = skeleton.findEditAreaByCoord(Vector2.FromArray([20, 75]), PageLayoutType.VERTICAL, 0, 0);+ expect(headerArea.editArea).toBe('HEADER');+ expect(bodyArea.editArea).toBe('BODY');+ expect(['FOOTER', 'BODY']).toContain(footerArea.editArea);++ const hitNode = skeleton.findNodeByCoord(+ Vector2.FromArray([12, 20]),+ PageLayoutType.VERTICAL,+ 0,+ 0+ );+ expect(hitNode).toBeTruthy();++ const strictNode = skeleton.findNodeByCoord(+ Vector2.FromArray([12, 20]),+ PageLayoutType.VERTICAL,+ 0,+ 0,+ {+ strict: true,+ segmentId: 'header-seg',+ segmentPage: 0,+ }+ );+ expect(strictNode).toBeUndefined();++ const relaxedNode = skeleton.findNodeByCoord(+ Vector2.FromArray([12, 20]),+ PageLayoutType.VERTICAL,+ 0,+ 0,+ {+ strict: false,+ segmentId: 'footer-seg',+ segmentPage: 0,+ }+ );+ expect(relaxedNode).toBeUndefined();++ expect((skeleton as any)._getNearestNode([], [])).toBeUndefined();+ expect((skeleton as any)._getNearestNode(+ [{ node: body.glyphs.glyphA }],+ [{ coordInPage: true, distance: 1, nestLevel: 0 }]+ )).toEqual({ node: body.glyphs.glyphA });+ expect((skeleton as any)._getNearestNode(+ [{ node: body.glyphs.glyphA }, { node: body.glyphs.glyphB }],+ [+ { coordInPage: false, distance: 2, nestLevel: 0 },+ { coordInPage: true, distance: 3, nestLevel: 1 },+ ]+ )).toEqual({ node: body.glyphs.glyphB });++ expect((skeleton as any)._getPageBoundingBox(body.page, PageLayoutType.VERTICAL)).toEqual(+ expect.objectContaining({ endX: body.page.pageWidth })+ );+ expect((skeleton as any)._getPageBoundingBox(body.page, PageLayoutType.HORIZONTAL)).toEqual(+ expect.objectContaining({ endY: body.page.pageHeight })+ );++ (skeleton as any)._translatePage(body.page, PageLayoutType.VERTICAL, 1, 2);+ expect((skeleton as any)._findLiquid.x).toBeGreaterThanOrEqual(0);+ });++ it('covers continuous-section helper and index lookup fallback branches', () => {+ const body = createPage(DocumentSkeletonPageType.BODY, 0);+ const docViewModel = {+ getDataModel: () => ({+ documentStyle: {+ pageSize: { width: 210, height: 297 },+ },+ }),+ dispose: vi.fn(),+ } as any;+ const skeleton = new DocumentSkeleton(docViewModel, {} as any);+ (skeleton as any)._skeletonData = {+ pages: [body.page],+ skeHeaders: new Map(),+ skeFooters: new Map(),+ };+ body.page.parent = (skeleton as any)._skeletonData;++ const preLen = body.page.sections.length;+ (skeleton as any)._addNewSectionByContinuous(+ body.page,+ [{ width: 100 } as any],+ ColumnSeparatorType.BETWEEN_EACH_COLUMN+ );+ expect(body.page.sections.length).toBe(preLen + 1);++ const noNode = skeleton.findNodeByCharIndex(9999);+ expect(noNode).toBeUndefined();+ });+});diff --git a/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.tsnew file mode 100644index 0000000000..e28fc49124--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/__tests__/tools.spec.ts@@ -0,0 +1,405 @@+/**+ * 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 {+ AlignTypeH,+ AlignTypeV,+ BooleanNumber,+ DocumentFlavor,+ GridType,+ NumberUnitType,+ ObjectRelativeFromH,+ ObjectRelativeFromV,+ SectionType,+} from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { GlyphType } from '../../../../basics/i-document-skeleton-cached';+import {+ clearFontCreateConfigCache,+ columnIterator,+ getCharSpaceApply,+ getCharSpaceConfig,+ getColumnByDivide,+ getFontConfigFromLastGlyph,+ getFontCreateConfig,+ getGlyphGroupWidth,+ getLastColumn,+ getLastLine,+ getLastLineByColumn,+ getLastNotFullColumnInfo,+ getLastNotFullDivideInfo,+ getLastPage,+ getLastRemainingDivide,+ getLastSection,+ getLastSpan,+ getLineHeightConfig,+ getNextDivide,+ getNullSkeleton,+ getNumberUnitValue,+ getPageContentWidth,+ getPageFromPath,+ getPositionHorizon,+ getPositionVertical,+ getPreLine,+ glyphIterator,+ isBlankColumn,+ isBlankPage,+ isColumnFull,+ lineIterator,+ mergeByV,+ prepareSectionBreakConfig,+ resetContext,+ setPageParent,+ updateBlockIndex,+ validationGrid,+} from '../tools';++function createPageSkeleton() {+ const divide1 = {+ isFull: false,+ left: 5,+ glyphGroup: [+ { count: 1, glyphType: GlyphType.WORD, width: 10, bBox: { ba: 3, bd: 1 }, xOffset: 0 },+ { count: 1, glyphType: GlyphType.WORD, width: 8, bBox: { ba: 4, bd: 2 }, xOffset: 1 },+ ],+ } as any;+ const divide2 = {+ isFull: true,+ left: 0,+ glyphGroup: [+ { count: 0, glyphType: GlyphType.LIST, width: 6, bBox: { ba: 2, bd: 1 }, xOffset: 0 },+ { count: 1, glyphType: GlyphType.WORD, width: 7, bBox: { ba: 2, bd: 1 }, xOffset: 0 },+ ],+ } as any;++ const line1 = {+ isBehindTable: false,+ paragraphIndex: 0,+ top: 0,+ lineHeight: 20,+ divides: [divide1, divide2],+ } as any;+ const line2 = {+ isBehindTable: true,+ tableId: 'table-1',+ paragraphIndex: 1,+ top: 24,+ lineHeight: 20,+ divides: [{ isFull: false, left: 0, glyphGroup: [{ count: 1, glyphType: GlyphType.WORD, width: 12, bBox: { ba: 2, bd: 1 }, xOffset: 0 }] }],+ } as any;++ const column = {+ isFull: false,+ left: 10,+ width: 200,+ lines: [line1, line2],+ } as any;+ const section = {+ columns: [column],+ } as any;++ const page = {+ pageWidth: 600,+ pageHeight: 800,+ marginTop: 30,+ marginBottom: 30,+ marginLeft: 20,+ marginRight: 20,+ sections: [section],+ skeTables: new Map([+ ['table-1', { ed: 7 }],+ ]),+ } as any;++ // parent links required by a few helpers+ divide1.parent = line1;+ divide2.parent = line1;+ line1.parent = column;+ line2.parent = column;+ column.parent = section;+ section.parent = page;++ return { page, section, column, line1, line2, divide1, divide2 };+}++describe('docs layout tools extra', () => {+ it('handles page/section/column/line selectors', () => {+ const { page, section, column, line1, line2, divide1 } = createPageSkeleton();+ const pages = [page];++ expect(getLastPage(pages as any)).toBe(page);+ expect(getLastSection(page as any)).toBe(section);+ expect(getLastColumn(page as any)).toBe(column);+ expect(getLastLine(page as any)).toBe(column.lines[1]);+ expect(getLastLineByColumn(column as any)).toBe(column.lines[1]);+ expect(getPageContentWidth(page as any)).toBe(560);+ expect(getPreLine(column.lines[1] as any)).toBe(line1);+ expect(getColumnByDivide(divide1 as any)).toBe(column);++ const columnInfo = getLastNotFullColumnInfo(page as any);+ expect(columnInfo?.column).toBe(column);+ expect(columnInfo?.isLast).toBe(true);++ const divideInfo = getLastNotFullDivideInfo(page as any);+ expect(divideInfo?.divide).toBe(column.lines[1].divides[0]);+ expect(getNextDivide(line1 as any, line1.divides[0] as any)).toBe(line1.divides[1]);+ expect(getLastRemainingDivide(line1 as any)).toBe(line1.divides[1]);+ expect(getLastSpan(page as any)).toBe(line2.divides[0].glyphGroup[0]);+ });++ it('handles column/page blank checks and number/grid helpers', () => {+ const { page, column } = createPageSkeleton();++ expect(isColumnFull(page as any)).toBe(false);+ expect(isBlankPage(page as any)).toBe(false);+ expect(isBlankColumn(column as any)).toBe(false);++ const blankLine = { divides: [{ glyphGroup: [{ glyphType: GlyphType.TAB }] }] };+ expect(isBlankColumn({ lines: [blankLine] } as any)).toBe(true);+ expect(isBlankPage({ sections: [{ columns: [{ lines: [blankLine] }] }] } as any)).toBe(true);++ expect(getNumberUnitValue(null, 100)).toBe(0);+ expect(getNumberUnitValue({ v: 10, u: NumberUnitType.PIXEL } as any, 100)).toBe(10);+ expect(getNumberUnitValue({ v: 2, u: NumberUnitType.POINT } as any, 10)).toBe(2);++ expect(validationGrid(GridType.SNAP_TO_CHARS, BooleanNumber.TRUE)).toBe(true);+ expect(validationGrid(GridType.LINES, BooleanNumber.TRUE)).toBe(false);+ expect(getCharSpaceApply(2, 3, GridType.SNAP_TO_CHARS, BooleanNumber.TRUE)).toBe(6);+ });++ it('derives line/char config from section and paragraph settings', () => {+ const sectionBreakConfig = {+ linePitch: 20,+ gridType: GridType.LINES,+ paragraphLineGapDefault: 1,+ charSpace: 2,+ defaultTabStop: 5,+ documentTextStyle: { fs: 11 },+ };+ const paragraphConfig = {+ paragraphStyle: {+ lineSpacing: 0,+ spacingRule: 0,+ snapToGrid: BooleanNumber.TRUE,+ },+ };++ const lineCfg = getLineHeightConfig(sectionBreakConfig as any, paragraphConfig as any);+ expect(lineCfg.lineSpacing).toBe(1);+ expect(lineCfg.linePitch).toBe(20);++ const charCfg = getCharSpaceConfig(sectionBreakConfig as any, paragraphConfig as any);+ expect(charCfg).toEqual(expect.objectContaining({+ charSpace: 2,+ defaultTabStop: 5,+ documentFontSize: 11,+ }));+ });++ it('updates block index values and iterates skeleton blocks', () => {+ const { page, column } = createPageSkeleton();+ updateBlockIndex([page] as any, -1);++ expect(page.st).toBe(0);+ expect(page.ed).toBeGreaterThan(page.st);+ expect(column.st).toBeGreaterThanOrEqual(0);+ expect(column.ed).toBeGreaterThanOrEqual(column.st);++ const glyphs: any[] = [];+ glyphIterator([page] as any, (glyph) => glyphs.push(glyph));+ expect(glyphs.length).toBeGreaterThan(0);++ const lines: any[] = [];+ lineIterator([page] as any, (line) => lines.push(line));+ expect(lines.length).toBe(2);++ const columns: any[] = [];+ columnIterator([page] as any, (col) => columns.push(col));+ expect(columns.length).toBe(1);+ });++ it('computes horizontal and vertical positioned object coordinates', () => {+ const { page, column } = createPageSkeleton();++ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.COLUMN,+ align: AlignTypeH.LEFT,+ } as any, column as any, page as any, 20)).toBe(10);++ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.PAGE,+ align: AlignTypeH.CENTER,+ } as any, column as any, page as any, 100)).toBe(250);++ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.COLUMN,+ posOffset: 50,+ } as any, column as any, page as any, 20)).toBe(60);++ expect(getPositionHorizon({+ relativeFrom: ObjectRelativeFromH.PAGE,+ percent: 0.5,+ } as any, column as any, page as any, 20)).toBe(300);++ expect(getPositionVertical({+ relativeFrom: ObjectRelativeFromV.LINE,+ align: AlignTypeV.BOTTOM,+ } as any, page as any, 30, 20, 10)).toBe(40);++ expect(getPositionVertical({+ relativeFrom: ObjectRelativeFromV.PAGE,+ align: AlignTypeV.CENTER,+ } as any, page as any, 30, 20, 100)).toBe(350);++ expect(getPositionVertical({+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,+ posOffset: 5,+ } as any, page as any, 30, 20, 100, 12, false)).toBe(17);++ expect(getPositionVertical({+ relativeFrom: ObjectRelativeFromV.PAGE,+ percent: 0.25,+ } as any, page as any, 30, 20, 100)).toBe(200);+ });++ it('handles glyph widths and font config cache', () => {+ const divide = {+ glyphGroup: [{ width: 3 }, { width: 4 }, { width: 5 }],+ };+ expect(getGlyphGroupWidth(divide as any)).toBe(12);++ clearFontCreateConfigCache();+ const fromLastGlyph = getFontConfigFromLastGlyph(+ { ts: { fs: 14 }, fontStyle: { fontString: '14pt Arial' } } as any,+ {+ gridType: GridType.LINES,+ charSpace: 1,+ pageSize: { width: 500 },+ marginLeft: 10,+ marginRight: 20,+ } as any,+ { snapToGrid: BooleanNumber.TRUE } as any+ );+ expect(fromLastGlyph.pageWidth).toBe(500);+ expect(fromLastGlyph.charSpace).toBe(1);++ const viewModel = {+ getTextRun: vi.fn(() => ({ st: 0, ed: 10, ts: { fs: 12, ff: 'Arial' } })),+ getCustomDecoration: vi.fn(() => null),+ getCustomRange: vi.fn(() => null),+ getDataModel: vi.fn(() => ({+ getBulletPresetList: () => ({+ bullet: { nestingLevel: [{ paragraphProperties: { textStyle: { bl: 1 } } }] },+ }),+ })),+ };++ const sectionBreakConfig = {+ gridType: GridType.LINES,+ charSpace: 2,+ documentTextStyle: { fs: 10, ff: 'Calibri' },+ pageSize: { width: 300 },+ marginLeft: 0,+ marginRight: 0,+ renderConfig: {},+ };+ const paragraphNode = { startIndex: 0 };+ const paragraph = { paragraphStyle: {} };++ const config1 = getFontCreateConfig(0, viewModel as any, paragraphNode as any, sectionBreakConfig as any, paragraph as any);+ const config2 = getFontCreateConfig(0, viewModel as any, paragraphNode as any, sectionBreakConfig as any, paragraph as any);+ expect(config1).toBe(config2);++ const configWithBullet = getFontCreateConfig(+ 0,+ viewModel as any,+ paragraphNode as any,+ sectionBreakConfig as any,+ { paragraphStyle: {}, bullet: { listType: 'bullet' } } as any+ );+ expect(configWithBullet.textStyle.bl).toBe(1);+ });++ it('creates default skeleton, prepares section config, and resolves page paths', () => {+ const skeleton = getNullSkeleton();+ const pages = [{ segmentId: 'seg-1' }, { segmentId: 'seg-2' }] as any[];+ setPageParent(pages as any, skeleton as any);+ expect(pages[0].parent).toBe(skeleton);++ const ctx = {+ docsConfig: { locale: 'zh-CN' },+ viewModel: {+ getChildren: () => [{ endIndex: 9 }, { endIndex: 19 }],+ getSectionBreak: vi.fn((endIndex: number) => {+ if (endIndex === 9) {+ return {+ sectionType: SectionType.CONTINUOUS,+ pageSize: { width: 900, height: 1200 },+ marginLeft: 30,+ marginRight: 40,+ renderConfig: { isRenderStyle: BooleanNumber.TRUE },+ };+ }+ return { sectionType: SectionType.CONTINUOUS };+ }),+ },+ dataModel: {+ documentStyle: {+ documentFlavor: DocumentFlavor.MODERN,+ pageSize: { width: 800, height: 1000 },+ marginLeft: 20,+ marginRight: 20,+ marginTop: 20,+ marginBottom: 20,+ renderConfig: {},+ },+ },+ };++ const sectionConfig = prepareSectionBreakConfig(ctx as any, 0);+ expect(sectionConfig.pageSize?.width).toBeGreaterThan(0);+ expect(sectionConfig.headerIds).toEqual(expect.objectContaining({+ defaultHeaderId: expect.any(String),+ }));++ const dirtyCtx = {+ isDirty: true,+ skeleton: { drawingAnchor: new Map([['a', 1]]) },+ };+ resetContext(dirtyCtx as any);+ expect(dirtyCtx.isDirty).toBe(false);+ expect(dirtyCtx.skeleton.drawingAnchor.size).toBe(0);++ const mergedMax = mergeByV({ a: { v: 1 }, b: 2 }, { a: { v: 3 }, b: 4 }, 'max');+ expect((mergedMax as any).a.v).toBe(3);+ const mergedMin = mergeByV({ a: { v: 5 } }, { a: { v: 3 } }, 'min');+ expect((mergedMin as any).a.v).toBe(3);++ const pageCell = { id: 'cell-page' };+ const root = {+ pages: [+ {+ id: 'page-0',+ skeTables: new Map([+ ['t1', { rows: [{ cells: [pageCell] }] }],+ ]),+ },+ ],+ };+ expect(getPageFromPath(root as any, ['pages', 0])).toBe(root.pages[0]);+ expect(getPageFromPath(root as any, ['pages', 0, 'skeTables', 't1', 'rows', 0, 'cells', 0])).toBe(pageCell);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.tsnew file mode 100644index 0000000000..f998c693c0--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/block/__tests__/table.spec.ts@@ -0,0 +1,199 @@+/**+ * 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 { BooleanNumber, TableAlignmentType, TableRowHeightRule, VerticalAlignmentType } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ createTableSkeleton,+ createTableSkeletons,+ getNullTableSkeleton,+ getTableIdAndSliceIndex,+ getTableSliceId,+ rollbackListCache,+} from '../table';++const createSkeletonCellPagesMock = vi.fn();+const createNullCellPageMock = vi.fn();++vi.mock('../../model/page', () => ({+ createSkeletonCellPages: (...args: unknown[]) => createSkeletonCellPagesMock(...args),+ createNullCellPage: (...args: unknown[]) => createNullCellPageMock(...args),+}));++function createRowNode(startIndex: number, endIndex: number, cellCount: number) {+ return {+ startIndex,+ endIndex,+ children: new Array(cellCount).fill(0).map((_, i) => ({+ startIndex: startIndex + i * 5,+ endIndex: startIndex + i * 5 + 4,+ children: [],+ })),+ };+}++function createContextAndTable() {+ const tableSource = {+ tableId: 'table-1',+ align: TableAlignmentType.START,+ indent: { v: 8 },+ tableRows: [+ {+ repeatHeaderRow: BooleanNumber.TRUE,+ trHeight: {+ hRule: TableRowHeightRule.AUTO,+ val: { v: 16 },+ },+ cantSplit: BooleanNumber.FALSE,+ tableCells: [+ { vAlign: VerticalAlignmentType.TOP },+ { vAlign: VerticalAlignmentType.CENTER },+ ],+ },+ {+ repeatHeaderRow: BooleanNumber.FALSE,+ trHeight: {+ hRule: TableRowHeightRule.AT_LEAST,+ val: { v: 28 },+ },+ cantSplit: BooleanNumber.TRUE,+ tableCells: [+ { vAlign: VerticalAlignmentType.BOTTOM },+ { vAlign: VerticalAlignmentType.TOP },+ ],+ },+ ],+ } as any;++ const viewModel = {+ getTableByStartIndex: vi.fn(() => ({ tableSource })),+ } as any;++ const tableNode = {+ startIndex: 0,+ endIndex: 80,+ children: [+ createRowNode(1, 20, 2),+ createRowNode(21, 40, 2),+ ],+ } as any;++ const curPage = {+ pageWidth: 400,+ pageHeight: 300,+ marginTop: 20,+ marginBottom: 20,+ marginLeft: 10,+ marginRight: 10,+ } as any;++ return {+ ctx: {} as any,+ sectionBreakConfig: {} as any,+ tableSource,+ viewModel,+ tableNode,+ curPage,+ };+}++function makeCellPage(width: number, height: number) {+ return {+ width,+ height,+ pageWidth: width,+ pageHeight: height,+ marginTop: 1,+ marginBottom: 1,+ originMarginTop: 1,+ originMarginBottom: 1,+ sections: [],+ };+}++describe('docs table layout', () => {+ beforeEach(() => {+ createSkeletonCellPagesMock.mockReset();+ createNullCellPageMock.mockReset();++ createNullCellPageMock.mockImplementation(() => ({+ page: makeCellPage(60, 10),+ }));++ createSkeletonCellPagesMock.mockImplementation(+ (_ctx: unknown, _viewModel: unknown, _cellNode: unknown, _section: unknown, _table: unknown, row: number, col: number, availableHeight?: number) => {+ const baseHeight = row === 0 ? 20 : 24;+ if (row === 1 && col === 0 && typeof availableHeight === 'number' && availableHeight < 40) {+ return [makeCellPage(60, baseHeight), makeCellPage(60, 16)];+ }+ return [makeCellPage(60, baseHeight)];+ }+ );+ });++ it('creates table skeleton and applies row/cell alignment data', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();++ const skeleton = createTableSkeleton(ctx, curPage, viewModel, tableNode, sectionBreakConfig);+ expect(skeleton).toBeTruthy();+ expect(skeleton?.rows.length).toBe(2);+ expect(skeleton?.width).toBeGreaterThan(0);+ expect(skeleton?.height).toBeGreaterThan(0);+ expect(skeleton?.left).toBeGreaterThanOrEqual(0);+ expect(skeleton?.rows[0].cells[0].marginTop).toBeGreaterThanOrEqual(1);+ expect(skeleton?.rows[0].cells[1].marginTop).toBeGreaterThanOrEqual(1);+ });++ it('creates sliced tables when available height is limited', () => {+ const { ctx, curPage, viewModel, tableNode, sectionBreakConfig } = createContextAndTable();++ const result = createTableSkeletons(ctx, curPage, viewModel, tableNode, sectionBreakConfig, 90);+ expect(result.skeTables.length).toBeGreaterThan(0);+ expect(typeof result.fromCurrentPage).toBe('boolean');+ expect(result.skeTables[0].rows.length).toBeGreaterThan(0);++ if (result.skeTables.length > 1) {+ expect(result.skeTables[1].tableId).toContain('#-#');+ }+ });++ it('handles rollback/slice id helpers and missing table branches', () => {+ const listCache = new Map<string, any[][]>([+ ['a', [[{ paragraph: { startIndex: 1 } }, { paragraph: { startIndex: 20 } }]]],+ ]);+ rollbackListCache(listCache as any, { startIndex: 5, endIndex: 50 } as any);+ expect(listCache.get('a')?.[0].length).toBe(1);++ const sliceId = getTableSliceId('table-x', 3);+ expect(sliceId).toBe('table-x#-#3');+ expect(getTableIdAndSliceIndex(sliceId)).toEqual({ tableId: 'table-x', sliceIndex: 3 });+ expect(getTableIdAndSliceIndex('table-y')).toEqual({ tableId: 'table-y', sliceIndex: 0 });++ const nullTable = getNullTableSkeleton(1, 2, { tableId: 't0' } as any);+ expect(nullTable.rows).toEqual([]);+ expect(nullTable.tableId).toBe('t0');++ const { ctx, curPage, tableNode, sectionBreakConfig } = createContextAndTable();+ const noTableViewModel = {+ getTableByStartIndex: vi.fn(() => null),+ };+ expect(createTableSkeleton(ctx, curPage, noTableViewModel as any, tableNode, sectionBreakConfig)).toBeNull();+ const sliced = createTableSkeletons(ctx, curPage, noTableViewModel as any, tableNode, sectionBreakConfig, 100);+ expect(sliced.skeTables).toEqual([]);+ expect(sliced.fromCurrentPage).toBe(false);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.tsnew file mode 100644index 0000000000..b1a16c13e0--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/line-adjustment.spec.ts@@ -0,0 +1,195 @@+/**+ * 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 { HorizontalAlign } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { BreakPointType } from '../../../line-breaker/break';++import { lineAdjustment } from '../line-adjustment';++const createHyphenDashGlyphMock = vi.fn();+const glyphShrinkLeftMock = vi.fn();+const glyphShrinkRightMock = vi.fn();+const setGlyphGroupLeftMock = vi.fn();+const getFontConfigFromLastGlyphMock = vi.fn();++vi.mock('../../../model/glyph', () => ({+ createHyphenDashGlyph: (...args: unknown[]) => createHyphenDashGlyphMock(...args),+ glyphShrinkLeft: (...args: unknown[]) => glyphShrinkLeftMock(...args),+ glyphShrinkRight: (...args: unknown[]) => glyphShrinkRightMock(...args),+ setGlyphGroupLeft: (...args: unknown[]) => setGlyphGroupLeftMock(...args),+}));++vi.mock('../../../tools', () => ({+ getFontConfigFromLastGlyph: (...args: unknown[]) => getFontConfigFromLastGlyphMock(...args),+ getGlyphGroupWidth: (divide: any) => divide.glyphGroup.reduce((sum: number, glyph: any) => sum + glyph.width, 0),+ lineIterator: (pages: any[], cb: (line: any) => void) => {+ pages.forEach((page) => {+ page.sections.forEach((section: any) => {+ section.columns.forEach((column: any) => {+ column.lines.forEach((line: any) => cb(line));+ });+ });+ });+ },+}));++function createGlyph(content: string, width: number, isJustifiable = false) {+ return {+ content,+ width,+ xOffset: 0,+ count: 1,+ isJustifiable,+ bBox: {+ width: Math.max(1, width - 1),+ ba: 7,+ bd: 3,+ },+ adjustability: {+ shrinkability: [1, 1],+ stretchability: [1, 1],+ },+ } as any;+}++function createPages() {+ const divide1 = {+ width: 40,+ isFull: true,+ breakType: BreakPointType.Normal,+ paddingLeft: 0,+ glyphGroup: [+ createGlyph('(', 8, false),+ createGlyph('A', 10, true),+ createGlyph('。', 8, false),+ ],+ } as any;++ const divide2 = {+ width: 24,+ isFull: true,+ breakType: BreakPointType.Normal,+ paddingLeft: 0,+ glyphGroup: [+ createGlyph('中', 14, false),+ ],+ } as any;+ divide2.glyphGroup[0].xOffset = 2;+ divide2.glyphGroup[0].bBox.width = 8;++ const divide3 = {+ width: 30,+ isFull: true,+ breakType: BreakPointType.Hyphen,+ paddingLeft: 0,+ glyphGroup: [+ createGlyph('w', 10, true),+ createGlyph('o', 8, true),+ createGlyph('r', 7, true),+ createGlyph('d', 7, true),+ ],+ } as any;+ divide3.glyphGroup[divide3.glyphGroup.length - 1].content = 'a';++ const line = {+ paragraphIndex: 0,+ divides: [divide1, divide2, divide3],+ } as any;++ [divide1, divide2, divide3].forEach((divide) => {+ divide.glyphGroup.forEach((glyph: any, idx: number) => {+ glyph.left = divide.glyphGroup.slice(0, idx).reduce((sum: number, g: any) => sum + g.width, 0);+ glyph.parent = divide;+ });+ });++ return [+ {+ sections: [+ {+ columns: [+ {+ lines: [line],+ },+ ],+ },+ ],+ },+ ] as any[];+}++describe('line adjustment', () => {+ it('adjusts punctuation/hyphen/alignment for paragraph lines', () => {+ createHyphenDashGlyphMock.mockReturnValue({+ content: '-',+ width: 3,+ count: 1,+ left: 0,+ bBox: { width: 3, ba: 7, bd: 3 },+ adjustability: { shrinkability: [0, 0], stretchability: [0, 0] },+ });+ getFontConfigFromLastGlyphMock.mockReturnValue({ fs: 12 });++ const viewModel = {+ getParagraph: () => ({+ startIndex: 0,+ paragraphStyle: {+ horizontalAlign: HorizontalAlign.JUSTIFIED,+ },+ }),+ } as any;+ const paragraphNode = { endIndex: 1 } as any;+ const pages = createPages();++ lineAdjustment(pages as any, viewModel, paragraphNode, {} as any);++ const line = pages[0].sections[0].columns[0].lines[0];+ expect(glyphShrinkLeftMock).toHaveBeenCalled();+ expect(glyphShrinkRightMock).toHaveBeenCalled();+ expect(setGlyphGroupLeftMock).toHaveBeenCalled();+ expect(getFontConfigFromLastGlyphMock).toHaveBeenCalled();++ const hyphenDivide = line.divides[2];+ expect(hyphenDivide.glyphGroup[hyphenDivide.glyphGroup.length - 1].content).toBe('-');+ expect(hyphenDivide.width).toBe(27);++ expect(line.divides[0].paddingLeft).toBeGreaterThanOrEqual(0);+ });++ it('supports center and right align branches', () => {+ const pages = createPages();+ const paragraphNode = { endIndex: 1 } as any;++ const viewModelCenter = {+ getParagraph: () => ({+ startIndex: 0,+ paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER },+ }),+ } as any;+ lineAdjustment(pages as any, viewModelCenter, paragraphNode, {} as any);+ expect(pages[0].sections[0].columns[0].lines[0].divides[0].paddingLeft).toBeGreaterThan(0);++ const viewModelRight = {+ getParagraph: () => ({+ startIndex: 0,+ paragraphStyle: { horizontalAlign: HorizontalAlign.RIGHT },+ }),+ } as any;+ lineAdjustment(pages as any, viewModelRight, paragraphNode, {} as any);+ expect(pages[0].sections[0].columns[0].lines[0].divides[0].paddingLeft).toBeGreaterThan(0);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.tsnew file mode 100644index 0000000000..c8c48ec162--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/linebreaking.spec.ts@@ -0,0 +1,235 @@+/**+ * 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 { DataStreamTreeTokenType, PositionedObjectLayoutType } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { BreakType } from '../../../../../../basics/i-document-skeleton-cached';++import { lineBreaking } from '../linebreaking';++const createSkeletonPageMock = vi.fn((ctx: any, _config: any, _ref: any, pageNumber: number, breakType?: BreakType): any => ({+ segmentId: 'segment-1',+ pageNumber,+ breakType,+}));++const setColumnFullStateMock = vi.fn((..._args: any[]): any => undefined);+const getLastNotFullColumnInfoMock = vi.fn((..._args: any[]): any => undefined);+const dealWithBulletMock = vi.fn((..._args: any[]): any => ({ id: 'bullet-skeleton' }));+const layoutParagraphMock = vi.fn((...args: any[]): any => {+ const glyphs = args[1] as any[];+ const pages = args[2] as any[];+ return glyphs.length > 0 ? [...pages] : pages;+});++vi.mock('../../../model/page', () => ({+ createSkeletonPage: (+ ctx: any,+ config: any,+ ref: any,+ pageNumber: number,+ breakType?: BreakType+ ) => createSkeletonPageMock(ctx, config, ref, pageNumber, breakType),+}));++vi.mock('../../../model/section', () => ({+ setColumnFullState: (column: any, full: boolean) => setColumnFullStateMock(column, full),+}));++vi.mock('../../../tools', () => ({+ getLastNotFullColumnInfo: (page: any) => getLastNotFullColumnInfoMock(page),+}));++vi.mock('../bullet', () => ({+ dealWithBullet: (bullet: any, lists: any, listLevelAncestors: any, localeService: any) => dealWithBulletMock(bullet, lists, listLevelAncestors, localeService),+}));++vi.mock('../layout-ruler', () => ({+ layoutParagraph: (+ ctx: any,+ glyphs: any[],+ pages: any[],+ sectionBreakConfig: any,+ paragraphConfig: any,+ isParagraphFirstShapedText: boolean,+ breakPointType: any+ ) => layoutParagraphMock(ctx, glyphs, pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType),+}));++function createContext() {+ return {+ paragraphConfigCache: new Map(),+ skeletonResourceReference: {+ skeHeaders: new Map(),+ skeFooters: new Map(),+ skeListLevel: new Map(),+ drawingAnchor: new Map(),+ },+ } as any;+}++function createViewModel() {+ return {+ getParagraph: vi.fn(() => ({+ startIndex: 0,+ paragraphStyle: {},+ bullet: { listId: 'l1', nestingLevel: 0 },+ })),+ getCustomBlock: vi.fn((charIndex: number) => {+ if (charIndex === 1) {+ return { blockId: 'inline-1' };+ }+ if (charIndex === 2) {+ return { blockId: 'float-1' };+ }+ return null;+ }),+ } as any;+}++describe('linebreaking', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('handles page-break and non-last column-break branches', () => {+ const ctx = createContext();+ const viewModel = createViewModel();+ getLastNotFullColumnInfoMock.mockReturnValue({+ column: { id: 'c1' },+ isLast: false,+ });++ const curPage = {+ segmentId: 'segment-1',+ pageNumber: 1,+ } as any;++ const paragraphNode = {+ endIndex: 10,+ startIndex: 0,+ blocks: [1, 2],+ children: [{}],+ } as any;++ const sectionBreakConfig = {+ lists: [],+ localeService: {} as any,+ drawings: {+ 'inline-1': {+ drawingId: 'inline-1',+ layoutType: PositionedObjectLayoutType.INLINE,+ },+ 'float-1': {+ drawingId: 'float-1',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ },+ },+ } as any;++ const shapedTextList = [+ {+ text: `A${DataStreamTreeTokenType.PAGE_BREAK}`,+ glyphs: [{ content: 'A' }],+ breakPointType: 0,+ },+ {+ text: `B${DataStreamTreeTokenType.COLUMN_BREAK}`,+ glyphs: [{ content: 'B' }],+ breakPointType: 0,+ },+ {+ text: 'C',+ glyphs: [{ content: 'C' }],+ breakPointType: 0,+ },+ ] as any;++ const tableSkeleton = { tableId: 'table-1' } as any;+ const pages = lineBreaking(+ ctx,+ viewModel,+ shapedTextList,+ curPage,+ paragraphNode,+ sectionBreakConfig,+ tableSkeleton+ );++ expect(dealWithBulletMock).toHaveBeenCalled();+ expect(layoutParagraphMock).toHaveBeenCalled();+ expect(createSkeletonPageMock).toHaveBeenCalledWith(+ ctx,+ sectionBreakConfig,+ ctx.skeletonResourceReference,+ 2,+ BreakType.PAGE+ );+ expect(setColumnFullStateMock).toHaveBeenCalled();+ expect(ctx.paragraphConfigCache.get('segment-1')?.has(10)).toBe(true);+ expect(ctx.skeletonResourceReference.drawingAnchor.get('segment-1')).toBeTruthy();+ expect(pages.length).toBeGreaterThan(0);+ });++ it('reuses cached bullet skeleton and creates new page for last column', () => {+ const ctx = createContext();+ const cachedSegment = new Map();+ cachedSegment.set(10, { bulletSkeleton: { id: 'cached-bullet' } });+ ctx.paragraphConfigCache.set('segment-1', cachedSegment);++ const viewModel = createViewModel();+ getLastNotFullColumnInfoMock.mockReturnValue({+ column: { id: 'c-last' },+ isLast: true,+ });++ const pages = lineBreaking(+ ctx,+ viewModel,+ [{+ text: `X${DataStreamTreeTokenType.COLUMN_BREAK}`,+ glyphs: [{ content: 'X' }],+ breakPointType: 0,+ }] as any,+ {+ segmentId: 'segment-1',+ pageNumber: 5,+ } as any,+ {+ endIndex: 10,+ startIndex: 0,+ blocks: [],+ children: [],+ } as any,+ {+ lists: [],+ localeService: {} as any,+ drawings: {},+ } as any,+ null+ );++ expect(dealWithBulletMock).not.toHaveBeenCalled();+ expect(createSkeletonPageMock).toHaveBeenCalledWith(+ ctx,+ expect.any(Object),+ ctx.skeletonResourceReference,+ 6,+ BreakType.COLUMN+ );+ expect(pages.length).toBeGreaterThanOrEqual(1);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.tsnew file mode 100644index 0000000000..781917a899--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/shaping.spec.ts@@ -0,0 +1,339 @@+/**+ * 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 { BooleanNumber, DataStreamTreeTokenType, GridType, PositionedObjectLayoutType } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { Lang } from '../../../hyphenation/lang';++import { shaping } from '../shaping';++const h = vi.hoisted(() => ({+ createSkeletonCustomBlockGlyphMock: vi.fn(),+ createSkeletonLetterGlyphMock: vi.fn(),+ createSkeletonTabGlyphMock: vi.fn(),+ glyphShrinkLeftMock: vi.fn(),+ glyphShrinkRightMock: vi.fn(),+ getBoundingBoxMock: vi.fn(() => ({+ width: 12,+ height: 6,+ })),+ textShapeMock: vi.fn(),+ prepareParagraphBodyMock: vi.fn(() => 'paragraph-body'),+ getCharSpaceApplyMock: vi.fn(() => 2),+ getFontCreateConfigMock: vi.fn((index: number) => ({ index })),+ emojiHandlerMock: vi.fn(),+ arabicHandlerMock: vi.fn(),+ tibetanHandlerMock: vi.fn(),+ otherHandlerMock: vi.fn(),+ hyphenEnhancerCtorMock: vi.fn(),+ fontLibraryMock: {+ isReady: false,+ },+}));++function createGlyph(content: string, width = 8, streamType?: string) {+ return {+ content,+ width,+ xOffset: 0,+ streamType,+ adjustability: {+ shrinkability: [6, 6],+ stretchability: [1, 1],+ },+ bBox: {+ width: Math.max(width - 1, 1),+ },+ } as any;+}++vi.mock('../../../../../../basics/tools', () => ({+ hasArabic: (char: string) => char === 'ع',+ hasCJK: (char: string) => char === '中' || char === ',',+ hasCJKPunctuation: (char: string) => char === ',',+ hasCJKText: (char: string) => char === '中' || char === ',',+ hasTibetan: (char: string) => char === 'ཀ',+ startWithEmoji: (src: string) => src.startsWith('😀'),+}));++vi.mock('../../../line-breaker', () => ({+ LineBreaker: class {+ private _used = false;++ constructor(private _content: string) {}++ nextBreakPoint() {+ if (this._used) {+ return null;+ }+ this._used = true;+ return {+ position: this._content.length,+ type: 0,+ };+ }+ },+}));++vi.mock('../../../line-breaker/enhancers/link-enhancer', () => ({+ LineBreakerLinkEnhancer: class {+ constructor(private _breaker: any) {}++ nextBreakPoint() {+ return this._breaker.nextBreakPoint();+ }+ },+}));++vi.mock('../../../line-breaker/enhancers/hyphen-enhancer', () => ({+ LineBreakerHyphenEnhancer: class {+ constructor(private _breaker: any) {+ h.hyphenEnhancerCtorMock();+ }++ nextBreakPoint() {+ return this._breaker.nextBreakPoint();+ }+ },+}));++vi.mock('../../../line-breaker/extensions/tab-linebreak-extension', () => ({+ tabLineBreakExtension: vi.fn(),+}));++vi.mock('../../../line-breaker/extensions/custom-block-linebreak-extension', () => ({+ customBlockLineBreakExtension: vi.fn(),+}));++vi.mock('../../../model/glyph', () => ({+ createSkeletonCustomBlockGlyph: (...args: any[]) => (h.createSkeletonCustomBlockGlyphMock as any)(...args),+ createSkeletonLetterGlyph: (...args: any[]) => (h.createSkeletonLetterGlyphMock as any)(...args),+ createSkeletonTabGlyph: (...args: any[]) => (h.createSkeletonTabGlyphMock as any)(...args),+ glyphShrinkLeft: (...args: any[]) => (h.glyphShrinkLeftMock as any)(...args),+ glyphShrinkRight: (...args: any[]) => (h.glyphShrinkRightMock as any)(...args),+}));++vi.mock('../../../model/line', () => ({+ getBoundingBox: (...args: any[]) => (h.getBoundingBoxMock as any)(...args),+}));++vi.mock('../../../shaping-engine/text-shaping', () => ({+ textShape: (...args: any[]) => (h.textShapeMock as any)(...args),+}));++vi.mock('../../../shaping-engine/utils', () => ({+ prepareParagraphBody: (...args: any[]) => (h.prepareParagraphBodyMock as any)(...args),+}));++vi.mock('../../../shaping-engine/font-library', () => ({+ fontLibrary: h.fontLibraryMock,+}));++vi.mock('../../../tools', () => ({+ getCharSpaceApply: (...args: any[]) => (h.getCharSpaceApplyMock as any)(...args),+ getFontCreateConfig: (...args: any[]) => (h.getFontCreateConfigMock as any)(...args),+}));++vi.mock('../language-ruler', () => ({+ emojiHandler: (...args: any[]) => (h.emojiHandlerMock as any)(...args),+ ArabicHandler: (...args: any[]) => (h.arabicHandlerMock as any)(...args),+ TibetanHandler: (...args: any[]) => (h.tibetanHandlerMock as any)(...args),+ otherHandler: (...args: any[]) => (h.otherHandlerMock as any)(...args),+}));++describe('paragraph shaping', () => {+ it('handles custom blocks, language handlers, punctuation and hyphen pattern loading', () => {+ h.fontLibraryMock.isReady = false;+ h.hyphenEnhancerCtorMock.mockClear();+ h.textShapeMock.mockReset();++ h.createSkeletonLetterGlyphMock.mockImplementation((char: string, _config: any, width?: number) => {+ if (char === DataStreamTreeTokenType.PARAGRAPH && width === 0) {+ return createGlyph(char, 0);+ }+ return createGlyph(char, 8);+ });+ h.createSkeletonTabGlyphMock.mockImplementation(() => createGlyph(DataStreamTreeTokenType.TAB, 4));+ h.createSkeletonCustomBlockGlyphMock.mockImplementation((_config: any, width: number, _height: number, _drawingId: string) => {+ return createGlyph(DataStreamTreeTokenType.CUSTOM_BLOCK, width, DataStreamTreeTokenType.CUSTOM_BLOCK);+ });+ h.glyphShrinkLeftMock.mockImplementation((glyph: any, delta: number) => {+ glyph.width -= delta;+ });+ h.glyphShrinkRightMock.mockImplementation((glyph: any, delta: number) => {+ glyph.width -= delta;+ });++ h.emojiHandlerMock.mockImplementation((_i: number, _src: string) => ({+ step: '😀'.length,+ glyphGroup: [createGlyph('😀', 10)],+ }));+ h.arabicHandlerMock.mockImplementation(() => ({+ step: 1,+ glyphGroup: [createGlyph('ع', 9)],+ }));+ h.tibetanHandlerMock.mockImplementation(() => ({+ step: 1,+ glyphGroup: [createGlyph('ཀ', 9)],+ }));+ h.otherHandlerMock.mockImplementation(() => ({+ step: 1,+ glyphGroup: [createGlyph('x', 7)],+ }));++ const ctx = {+ hyphen: {+ hasPattern: vi.fn(() => false),+ loadPattern: vi.fn(),+ },+ languageDetector: {+ detect: vi.fn(() => Lang.EnUs),+ },+ } as any;++ const viewModel = {+ getParagraph: vi.fn(() => ({+ startIndex: 0,+ paragraphStyle: {+ snapToGrid: BooleanNumber.TRUE,+ suppressHyphenation: BooleanNumber.FALSE,+ },+ })),+ getBody: vi.fn(() => ({ dataStream: '' })),+ getCustomBlockWithoutSetCurrentIndex: vi.fn((index: number) => {+ if (index === 0) {+ return { blockId: 'inline-block' };+ }+ if (index === 1) {+ return { blockId: 'float-block' };+ }+ return null;+ }),+ } as any;++ const paragraphNode = {+ startIndex: 0,+ endIndex: 1,+ } as any;++ const sectionBreakConfig = {+ gridType: GridType.LINES,+ charSpace: 1,+ defaultTabStop: 10.5,+ drawings: {+ 'inline-block': {+ drawingId: 'inline-block',+ layoutType: PositionedObjectLayoutType.INLINE,+ docTransform: {+ angle: 30,+ size: {+ width: 20,+ height: 10,+ },+ },+ },+ 'float-block': {+ drawingId: 'float-block',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ angle: 0,+ size: {+ width: 20,+ height: 10,+ },+ },+ },+ },+ autoHyphenation: BooleanNumber.TRUE,+ doNotHyphenateCaps: BooleanNumber.FALSE,+ renderConfig: {+ zeroWidthParagraphBreak: BooleanNumber.TRUE,+ },+ } as any;++ const content = `${DataStreamTreeTokenType.CUSTOM_BLOCK}${DataStreamTreeTokenType.CUSTOM_BLOCK}\t${DataStreamTreeTokenType.PARAGRAPH}中😀عཀx,,中a中`;+ const shaped = shaping(ctx, content, viewModel, paragraphNode, sectionBreakConfig, false);++ expect(shaped.length).toBeGreaterThan(0);+ expect(h.getBoundingBoxMock).toHaveBeenCalled();+ expect(h.createSkeletonCustomBlockGlyphMock).toHaveBeenCalledTimes(2);+ expect(h.emojiHandlerMock).toHaveBeenCalled();+ expect(h.arabicHandlerMock).toHaveBeenCalled();+ expect(h.tibetanHandlerMock).toHaveBeenCalled();+ expect(h.otherHandlerMock).toHaveBeenCalled();+ expect(h.glyphShrinkLeftMock).toHaveBeenCalled();+ expect(h.glyphShrinkRightMock).toHaveBeenCalled();+ expect(ctx.hyphen.loadPattern).toHaveBeenCalledWith(Lang.EnUs);+ expect(h.hyphenEnhancerCtorMock).not.toHaveBeenCalled();+ });++ it('uses openType shaping path and hyphen enhancer when pattern exists', () => {+ h.fontLibraryMock.isReady = true;+ h.hyphenEnhancerCtorMock.mockClear();++ h.createSkeletonLetterGlyphMock.mockImplementation((char: string, _config: any, _width?: number, glyphInfo?: any) => {+ return createGlyph(glyphInfo ? `${char}-ot` : char, 8);+ });+ h.createSkeletonTabGlyphMock.mockImplementation(() => createGlyph(DataStreamTreeTokenType.TAB, 4));+ h.textShapeMock.mockReturnValue([+ { start: 0, end: 1, char: 'A' },+ { start: 1, end: 2, char: DataStreamTreeTokenType.TAB },+ { start: 2, end: 4, char: '😀' },+ ]);++ const ctx = {+ hyphen: {+ hasPattern: vi.fn(() => true),+ loadPattern: vi.fn(),+ },+ languageDetector: {+ detect: vi.fn(() => Lang.EnUs),+ },+ } as any;++ const viewModel = {+ getParagraph: vi.fn(() => ({+ startIndex: 0,+ paragraphStyle: {+ suppressHyphenation: BooleanNumber.FALSE,+ },+ })),+ getBody: vi.fn(() => ({ dataStream: '' })),+ getCustomBlockWithoutSetCurrentIndex: vi.fn(() => null),+ } as any;++ const shaped = shaping(+ ctx,+ `A${DataStreamTreeTokenType.TAB}😀`,+ viewModel,+ { startIndex: 0, endIndex: 1 } as any,+ {+ autoHyphenation: BooleanNumber.TRUE,+ doNotHyphenateCaps: BooleanNumber.TRUE,+ drawings: {},+ } as any,+ true+ );++ expect(shaped.length).toBeGreaterThan(0);+ expect(h.prepareParagraphBodyMock).toHaveBeenCalled();+ expect(h.textShapeMock).toHaveBeenCalled();+ expect(h.createSkeletonTabGlyphMock).toHaveBeenCalled();+ expect(h.createSkeletonLetterGlyphMock).toHaveBeenCalled();+ expect(h.hyphenEnhancerCtorMock).toHaveBeenCalled();+ expect(ctx.hyphen.loadPattern).not.toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.ts b/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.tsnew file mode 100644index 0000000000..31b6bee005--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/line-breaker/enhancers/__tests__/link-enhancer.spec.ts@@ -0,0 +1,64 @@+/**+ * 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 { BreakPointType } from '../../break';+import { LineBreaker } from '../../line-breaker';+import { LineBreakerLinkEnhancer } from '../link-enhancer';++function collectBreaks(content: string) {+ const enhancer = new LineBreakerLinkEnhancer(new LineBreaker(content));+ const points: Array<{ position: number; type: BreakPointType }> = [];+ while (true) {+ const bk = enhancer.nextBreakPoint();+ if (!bk) {+ break;+ }+ points.push({+ position: bk.position,+ type: bk.type,+ });+ }+ return points;+}++describe('link enhancer', () => {+ it('keeps normal text breaking behavior without links', () => {+ const breaks = collectBreaks('hello world');+ expect(breaks.length).toBeGreaterThan(0);+ expect(breaks.some((point) => point.type === BreakPointType.Link)).toBe(false);+ expect(breaks[breaks.length - 1].position).toBe('hello world'.length);+ });++ it('adds link break opportunities for url-like words', () => {+ const content = 'visit https://foo123bar.example/path-now and continue';+ const breaks = collectBreaks(content);+ const linkBreaks = breaks.filter((point) => point.type === BreakPointType.Link);++ expect(linkBreaks.length).toBeGreaterThan(0);+ expect(linkBreaks[0].position).toBeGreaterThanOrEqual(content.indexOf('https://'));+ expect(breaks[breaks.length - 1].position).toBe(content.length);+ });++ it('supports long links by splitting aggressively', () => {+ const content = `www.${'a'.repeat(40)}.com end`;+ const breaks = collectBreaks(content);+ const linkBreaks = breaks.filter((point) => point.type === BreakPointType.Link);++ expect(linkBreaks.length).toBeGreaterThan(5);+ expect(linkBreaks.every((point, idx) => idx === 0 || point.position > linkBreaks[idx - 1].position)).toBe(true);+ });+});diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.tsnew file mode 100644index 0000000000..aa33e0a60c--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/line.spec.ts@@ -0,0 +1,288 @@+/**+ * 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 { PositionedObjectLayoutType, TableTextWrapType, WrapTextType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { LineType } from '../../../../../basics/i-document-skeleton-cached';+import {+ calculateLineTopByDrawings,+ collisionDetection,+ createAndUpdateBlockAnchor,+ createSkeletonLine,+ getBoundingBox,+ setLineMarginBottom,+ updateDivideInfo,+} from '../line';++function createTopBottomDrawing(top: number, height: number, angle = 0) {+ return {+ aTop: top,+ aLeft: 10,+ width: 20,+ height,+ angle,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,+ distT: 1,+ distB: 2,+ },+ };+}++describe('line model', () => {+ it('creates line skeleton and divides with drawing/table layout data', () => {+ const page = {+ marginTop: 8,+ marginBottom: 8,+ pageHeight: 200,+ skeDrawings: new Map([+ ['inline', {+ aTop: 2,+ aLeft: 2,+ width: 5,+ height: 5,+ drawingOrigin: { layoutType: PositionedObjectLayoutType.INLINE },+ }],+ ['square', {+ aTop: 4,+ aLeft: 18,+ width: 10,+ height: 8,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ distL: 1,+ distR: 1,+ distT: 1,+ distB: 1,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ['polygon', {+ aTop: 4,+ aLeft: 32,+ width: 10,+ height: 8,+ angle: 20,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_POLYGON,+ start: [32, 4],+ lineTo: [[42, 4], [42, 12], [32, 12]],+ },+ }],+ ['tight', {+ aTop: 4,+ aLeft: 48,+ width: 10,+ height: 8,+ angle: 25,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_TIGHT,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ wrapText: WrapTextType.LARGEST,+ },+ }],+ ]),+ skeTables: new Map([+ ['table-wrap', {+ left: 6,+ top: 2,+ width: 8,+ height: 12,+ tableSource: {+ textWrap: TableTextWrapType.WRAP,+ dist: { distL: 1, distR: 1, distT: 1, distB: 1 },+ },+ }],+ ]),+ } as any;++ const headerPage = {+ marginTop: 5,+ pageHeight: 200,+ skeDrawings: new Map([+ ['header-square', {+ aTop: 1,+ aLeft: 2,+ width: 6,+ height: 6,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ wrapText: WrapTextType.BOTH_SIDES,+ },+ }],+ ]),+ } as any;++ const footerPage = {+ marginTop: 3,+ pageHeight: 200,+ skeDrawings: new Map([+ ['footer-through', {+ aTop: 1,+ aLeft: 20,+ width: 6,+ height: 6,+ angle: 0,+ drawingOrigin: {+ layoutType: PositionedObjectLayoutType.WRAP_THROUGH,+ distL: 0,+ distR: 0,+ distT: 0,+ distB: 0,+ wrapText: WrapTextType.RIGHT,+ },+ }],+ ]),+ } as any;++ const line = createSkeletonLine(+ 3,+ LineType.PARAGRAPH,+ {+ lineHeight: 14,+ lineTop: 6,+ contentHeight: 10,+ paddingLeft: 2,+ paddingRight: 2,+ paddingTop: 1,+ paddingBottom: 1,+ marginTop: 3,+ spaceBelowApply: 2,+ },+ 100,+ 4,+ true,+ {+ skeTablesInParagraph: [{ tableId: 'table-wrap' }],+ } as any,+ page,+ headerPage,+ footerPage+ );++ expect(line.paragraphIndex).toBe(3);+ expect(line.lineIndex).toBe(4);+ expect(line.paragraphStart).toBe(true);+ expect(line.isBehindTable).toBe(true);+ expect(line.tableId).toBe('table-wrap');+ expect(line.divides.length).toBeGreaterThan(0);+ expect(line.divides.every((divide) => divide.parent === line)).toBe(true);+ });++ it('calculates max line top with top-bottom drawings and no-wrap tables', () => {+ const page = {+ marginTop: 10,+ marginBottom: 8,+ pageHeight: 300,+ skeDrawings: new Map([+ ['d1', createTopBottomDrawing(12, 10, 0)],+ ['d2', createTopBottomDrawing(20, 8, 30)],+ ]),+ skeTables: new Map([+ ['t1', {+ top: 14,+ height: 12,+ tableSource: { textWrap: TableTextWrapType.NONE },+ }],+ ]),+ } as any;++ const headerPage = {+ marginTop: 5,+ pageHeight: 300,+ skeDrawings: new Map([['h1', createTopBottomDrawing(3, 7, 0)]]),+ } as any;++ const footerPage = {+ marginTop: 4,+ pageHeight: 300,+ skeDrawings: new Map([['f1', createTopBottomDrawing(2, 6, 0)]]),+ } as any;++ const top = calculateLineTopByDrawings(15, 10, page, headerPage, footerPage);+ expect(top).toBeGreaterThan(10);++ const noOverlapTop = calculateLineTopByDrawings(+ 5,+ 0,+ { ...page, skeDrawings: new Map(), skeTables: new Map() },+ null,+ null+ );+ expect(noOverlapTop).toBe(0);+ });++ it('updates divide/line state and detects float object collision', () => {+ const divide = {+ glyphGroup: [],+ width: 50,+ left: 0,+ isFull: false,+ } as any;+ updateDivideInfo(divide, { isFull: true, breakType: 2 as any });+ expect(divide.isFull).toBe(true);+ expect(divide.breakType).toBe(2);++ const line = { marginBottom: 0 } as any;+ setLineMarginBottom(line, 11);+ expect(line.marginBottom).toBe(11);++ const collide = collisionDetection(+ { top: 4, left: 6, width: 8, height: 8, angle: 20 } as any,+ 20,+ 0,+ 0,+ 40+ );+ expect(collide).toBe(true);++ const notCollide = collisionDetection(+ { top: 100, left: 200, width: 20, height: 20, angle: 0 } as any,+ 10,+ 0,+ 0,+ 40+ );+ expect(notCollide).toBe(false);+ });++ it('computes bounding box and updates drawing anchor map', () => {+ const boundingBox = getBoundingBox(45, 10, 20, 5, 8);+ expect(boundingBox.left).toBeTypeOf('number');+ expect(boundingBox.top).toBeTypeOf('number');+ expect(boundingBox.points.length).toBe(4);++ const line = { lineIndex: 1 } as any;+ const anchors = new Map<number, any>();++ createAndUpdateBlockAnchor(9, line, 30, anchors);+ expect(anchors.get(9)?.elements).toHaveLength(1);++ createAndUpdateBlockAnchor(9, { lineIndex: 2 } as any, 40, anchors);+ expect(anchors.get(9)?.elements).toHaveLength(2);++ expect(() => createAndUpdateBlockAnchor(1, line, 10, undefined)).not.toThrow();+ });+});diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.tsnew file mode 100644index 0000000000..236b7a533f--- /dev/null+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/page.spec.ts@@ -0,0 +1,213 @@+/**+ * 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 { BooleanNumber, ColumnSeparatorType, PageOrientType } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { DocumentSkeletonPageType } from '../../../../../basics/i-document-skeleton-cached';++import {+ createNullCellPage,+ createSkeletonCellPages,+ createSkeletonPage,+} from '../page';++const dealWithSectionMock = vi.fn();+const updateBlockIndexMock = vi.fn();+const updateInlineDrawingCoordsAndBorderMock = vi.fn();+const resetContextMock = vi.fn();++vi.mock('../../block/section', () => ({+ dealWithSection: (...args: unknown[]) => dealWithSectionMock(...args),+}));++vi.mock('../../tools', () => ({+ resetContext: (...args: unknown[]) => resetContextMock(...args),+ updateBlockIndex: (...args: unknown[]) => updateBlockIndexMock(...args),+ updateInlineDrawingCoordsAndBorder: (...args: unknown[]) => updateInlineDrawingCoordsAndBorderMock(...args),+}));++function createSkeletonResourceReference() {+ return {+ skeHeaders: new Map(),+ skeFooters: new Map(),+ skeListLevel: new Map(),+ } as any;+}++function createDealPage(areaPage: any) {+ return {+ ...areaPage,+ height: 20,+ sections: [+ {+ columns: [+ {+ lines: [{ paragraphIndex: 0 }],+ },+ ],+ },+ ],+ skeDrawings: new Map(),+ skeTables: new Map(),+ };+}++describe('page model', () => {+ it('creates page with header/footer ids and section info', () => {+ dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({+ pages: [createDealPage(areaPage)],+ }));++ const skeletonResourceReference = createSkeletonResourceReference();+ const ctx = {+ layoutStartPointer: {},+ skeletonResourceReference,+ isDirty: false,+ } as any;++ const headerVM = { getChildren: () => [{}] };+ const footerVM = { getChildren: () => [{}] };+ const sectionBreakConfig = {+ pageNumberStart: 1,+ pageSize: { width: 200, height: 300 },+ pageOrient: PageOrientType.PORTRAIT,+ headerIds: {+ defaultHeaderId: 'h-default',+ firstPageHeaderId: 'h-first',+ evenPageHeaderId: 'h-even',+ },+ footerIds: {+ defaultFooterId: 'f-default',+ firstPageFooterId: 'f-first',+ evenPageFooterId: 'f-even',+ },+ useFirstPageHeaderFooter: BooleanNumber.TRUE,+ evenAndOddHeaders: BooleanNumber.TRUE,+ headerTreeMap: new Map([+ ['h-first', headerVM],+ ['h-even', headerVM],+ ['h-default', headerVM],+ ]),+ footerTreeMap: new Map([+ ['f-first', footerVM],+ ['f-even', footerVM],+ ['f-default', footerVM],+ ]),+ columnProperties: [{ width: 60, paddingEnd: 10 }],+ columnSeparatorType: ColumnSeparatorType.BETWEEN_EACH_COLUMN,+ marginTop: 12,+ marginBottom: 14,+ marginHeader: 6,+ marginFooter: 8,+ marginLeft: 10,+ marginRight: 10,+ renderConfig: { a: 1 },+ } as any;++ const firstPage = createSkeletonPage(ctx, sectionBreakConfig, skeletonResourceReference, 1);+ expect(firstPage.headerId).toBe('h-first');+ expect(firstPage.footerId).toBe('f-first');+ expect(firstPage.pageWidth).toBe(200);+ expect(firstPage.pageHeight).toBe(300);+ expect(firstPage.sections.length).toBeGreaterThan(0);+ expect(skeletonResourceReference.skeHeaders.get('h-first')?.has(200)).toBe(true);+ expect(skeletonResourceReference.skeFooters.get('f-first')?.has(200)).toBe(true);++ const evenPage = createSkeletonPage(ctx, sectionBreakConfig, skeletonResourceReference, 2);+ expect(evenPage.headerId).toBe('h-even');+ expect(evenPage.footerId).toBe('f-even');+ });++ it('creates null cell page and skeleton cell pages', () => {+ dealWithSectionMock.mockImplementation((_ctx: any, _vm: any, _node: any, areaPage: any) => ({+ pages: [createDealPage(areaPage)],+ }));++ const skeletonResourceReference = createSkeletonResourceReference();+ const ctx = {+ layoutStartPointer: {},+ skeletonResourceReference,+ isDirty: false,+ } as any;++ const tableConfig = {+ tableId: 'table-1',+ cellMargin: {+ start: { v: 2 },+ end: { v: 3 },+ top: { v: 4 },+ bottom: { v: 5 },+ },+ tableRows: [+ {+ tableCells: [+ {},+ ],+ },+ ],+ tableColumns: [+ {+ size: { width: { v: 80 } },+ },+ ],+ } as any;++ const sectionBreakConfig = {+ lists: [],+ localeService: {} as any,+ drawings: {},+ pageSize: { width: 300, height: 200 },+ headerTreeMap: new Map(),+ footerTreeMap: new Map(),+ } as any;++ const nullPageResult = createNullCellPage(+ ctx,+ sectionBreakConfig,+ tableConfig,+ 0,+ 0,+ 120,+ 300+ );+ expect(nullPageResult.page.type).toBe(DocumentSkeletonPageType.CELL);+ expect(nullPageResult.page.segmentId).toBe('table-1');+ expect(nullPageResult.page.pageWidth).toBe(80);++ const viewModel = {} as any;+ const cellNode = {+ startIndex: 10,+ children: [{}],+ } as any;+ const pages = createSkeletonCellPages(+ ctx,+ viewModel,+ cellNode,+ sectionBreakConfig,+ tableConfig,+ 0,+ 0,+ 100,+ 300+ );++ expect(pages).toHaveLength(1);+ expect(pages[0].type).toBe(DocumentSkeletonPageType.CELL);+ expect(pages[0].segmentId).toBe('table-1');+ expect(updateBlockIndexMock).toHaveBeenCalled();+ expect(updateInlineDrawingCoordsAndBorderMock).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/docs/view-model/__tests__/data-stream-tree-node.spec.ts b/packages/engine-render/src/components/docs/view-model/__tests__/data-stream-tree-node.spec.tsnew file mode 100644index 0000000000..dd83f568d2--- /dev/null+++ b/packages/engine-render/src/components/docs/view-model/__tests__/data-stream-tree-node.spec.ts@@ -0,0 +1,102 @@+/**+ * 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 { DataStreamTreeNodeType, DataStreamTreeTokenType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DataStreamTreeNode } from '../data-stream-tree-node';++describe('data stream tree node', () => {+ it('supports index/content/block updates', () => {+ const node = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, 'abcd');+ node.setIndexRange(10, 13);+ node.addBlocks([11, 13]);+ node.insertText('X', 12);++ expect(node.content).toBe('abXcd');+ expect(node.exclude(9)).toBe(true);+ expect(node.exclude(10)).toBe(false);++ node.plus(2);+ expect(node.startIndex).toBe(12);+ expect(node.endIndex).toBe(15);+ expect(node.blocks).toEqual([13, 15]);++ node.selfPlus(3, 14);+ expect(node.endIndex).toBe(18);+ expect(node.blocks).toEqual([13, 18]);+ expect(node.getProps().nodeType).toBe(DataStreamTreeNodeType.PARAGRAPH);+ });++ it('splits paragraph node and resets custom blocks', () => {+ const customBlockText = `A${DataStreamTreeTokenType.CUSTOM_BLOCK}BC`;+ const parent = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE);+ const paragraph = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, customBlockText);+ paragraph.parent = parent;+ paragraph.setIndexRange(0, customBlockText.length - 1);+ paragraph.blocks = [1];++ const child1 = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL, 'ab');+ child1.setIndexRange(0, 1);+ child1.parent = paragraph;+ const child2 = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL, 'cd');+ child2.setIndexRange(2, 3);+ child2.parent = paragraph;+ paragraph.children = [child1, child2];++ const splitData = paragraph.split(2)!;+ expect(splitData.firstNode.content).toBe(`A${DataStreamTreeTokenType.CUSTOM_BLOCK}`);+ expect(splitData.lastNode.content).toBe('BC');+ expect(splitData.firstNode.blocks).toContain(splitData.firstNode.startIndex + 1);++ const outOfRange = paragraph.split(99);+ expect(outOfRange).toBeUndefined();+ });++ it('supports minus/merge/remove/dispose workflows', () => {+ const parent = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE);+ const left = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, 'abcdef');+ left.setIndexRange(0, 5);+ left.parent = parent;++ const right = DataStreamTreeNode.create(DataStreamTreeNodeType.PARAGRAPH, 'XYZ');+ right.setIndexRange(6, 8);+ right.parent = parent;++ parent.children = [left, right];+ expect(left.getPositionInParent()).toBe(0);+ expect(right.getPositionInParent()).toBe(1);++ left.minus(1, 2);+ expect(left.content).toBe('adef');+ expect(left.startIndex).toBe(0);+ expect(left.endIndex).toBe(3);++ const child = DataStreamTreeNode.create(DataStreamTreeNodeType.TABLE_CELL, 's');+ child.parent = right;+ right.children = [child];+ left.merge(right);+ expect(left.content).toBe('adefXYZ');+ expect(parent.children).toHaveLength(1);++ left.remove();+ expect(left.parent).toBeNull();+ expect(left.children).toEqual([]);++ parent.dispose();+ expect(parent.blocks).toEqual([]);+ expect(parent.parent).toBeNull();+ });+});diff --git a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.tsindex 01f567ce9a..a407c3d4a9 100644--- a/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts+++ b/packages/engine-render/src/components/docs/view-model/__tests__/document-view-model.spec.ts@@ -14,9 +14,50 @@* limitations under the License.*/+import type { Nullable } from '@univerjs/core';import { DataStreamTreeNodeType, DataStreamTreeTokenType } from '@univerjs/core';-import { describe, expect, it } from 'vitest';-import { parseDataStreamToTree } from '../document-view-model';+import { describe, expect, it, vi } from 'vitest';+import { DocumentEditArea, DocumentViewModel, parseDataStreamToTree } from '../document-view-model';++function createDocumentDataModel(overrides?: {+ body?: Record<string, unknown>;+ snapshot?: Record<string, unknown>;+ headerModelMap?: Map<string, any>;+ footerModelMap?: Map<string, any>;+}) {+ const body = {+ dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,+ textRuns: [],+ paragraphs: [],+ sectionBreaks: [],+ customBlocks: [],+ customRanges: [],+ customDecorations: [],+ tables: [],+ ...overrides?.body,+ };+ const snapshot = {+ tableSource: {},+ ...overrides?.snapshot,+ };++ return {+ getBody: vi.fn(() => body),+ getSnapshot: vi.fn(() => snapshot),+ headerModelMap: overrides?.headerModelMap ?? new Map(),+ footerModelMap: overrides?.footerModelMap ?? new Map(),+ } as any;+}++function findFirstNodeByType(node: any, type: DataStreamTreeNodeType): Nullable<any> {+ if (!node) return null;+ if (node.nodeType === type) return node;+ for (const child of node.children ?? []) {+ const found = findFirstNodeByType(child, type);+ if (found) return found;+ }+ return null;+}describe('DocumentViewModel', () => {describe('parseDataStreamToTree', () => {@@ -46,5 +87,161 @@ describe('DocumentViewModel', () => {expect(sectionList[1].children.length).toBe(1);expect(sectionList[1].children[0].content).toBe('');});++ it('should parse table/custom-block and build table node cache', () => {+ const ds = [+ 'A',+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.TABLE_START,+ DataStreamTreeTokenType.TABLE_ROW_START,+ DataStreamTreeTokenType.TABLE_CELL_START,+ 'B',+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.SECTION_BREAK,+ DataStreamTreeTokenType.TABLE_CELL_END,+ DataStreamTreeTokenType.TABLE_ROW_END,+ DataStreamTreeTokenType.TABLE_END,+ DataStreamTreeTokenType.CUSTOM_BLOCK,+ DataStreamTreeTokenType.PARAGRAPH,+ DataStreamTreeTokenType.SECTION_BREAK,+ ].join('');++ const first = parseDataStreamToTree(ds);+ const tableNode = findFirstNodeByType(first.sectionList[0], DataStreamTreeNodeType.TABLE)!;+ expect(tableNode).toBeTruthy();+ expect(tableNode.children.length).toBe(1);++ const withTables = parseDataStreamToTree(ds, [{+ tableId: 'table-1',+ startIndex: tableNode.startIndex,+ endIndex: tableNode.endIndex + 1,+ } as any]);++ expect(withTables.tableNodeCache.get('table-1')?.table.nodeType).toBe(DataStreamTreeNodeType.TABLE);+ const paragraphWithCustomBlock = withTables.sectionList+ .flatMap((section) => section.children)+ .find((paragraph) => paragraph.blocks.length > 0);+ expect(paragraphWithCustomBlock?.blocks.length).toBe(1);+ });+ });++ describe('DocumentViewModel class', () => {+ it('covers cache/interceptor/reset/header-footer flows', () => {+ const headerModel = createDocumentDataModel({+ body: {+ dataStream: `${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,+ },+ });+ const footerModel = createDocumentDataModel({+ body: {+ dataStream: `${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,+ },+ });++ const bodyStream = `X${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`;+ const model = createDocumentDataModel({+ body: {+ dataStream: bodyStream,+ textRuns: [{ st: 0, ed: 2, ts: {} }],+ paragraphs: [{ startIndex: 0 }],+ sectionBreaks: [{ startIndex: 2 }],+ customBlocks: [{ startIndex: 1, blockId: 'b1' }],+ customRanges: [{ startIndex: 0, endIndex: 1, rangeId: 'r1' }],+ customDecorations: [{ startIndex: 1, endIndex: 2, id: 'd1' }],+ tables: [{ tableId: 't1', startIndex: 3, endIndex: 5 }],+ },+ snapshot: {+ tableSource: {+ t1: { id: 'source-1' },+ },+ },+ headerModelMap: new Map([['h1', headerModel]]),+ footerModelMap: new Map([['f1', footerModel]]),+ });++ const viewModel = new DocumentViewModel(model);+ expect(viewModel.getBody()).toEqual(model.getBody());+ expect(viewModel.getSnapshot()).toEqual(model.getSnapshot());+ expect(viewModel.getDataModel()).toBe(model);+ expect(viewModel.getChildren().length).toBe(1);+ expect(viewModel.getParagraph(0)?.startIndex).toBe(0);+ expect(viewModel.getSectionBreak(2)?.startIndex).toBe(2);+ expect(viewModel.getTextRun(0)?.st).toBe(0);+ expect(viewModel.getCustomBlock(1)?.startIndex).toBe(1);+ expect(viewModel.getCustomBlockWithoutSetCurrentIndex(1)?.startIndex).toBe(1);+ expect(viewModel.getCustomRangeRaw(1)?.rangeId).toBe('r1');+ expect(viewModel.getCustomDecorationRaw(1)?.id).toBe('d1');+ expect(viewModel.getTableByStartIndex(3)?.tableSource).toEqual({ id: 'source-1' });++ const byHeader = viewModel.getSelfOrHeaderFooterViewModel('h1');+ const byFooter = viewModel.getSelfOrHeaderFooterViewModel('f1');+ expect(byHeader).not.toBe(viewModel);+ expect(byFooter).not.toBe(viewModel);+ expect(viewModel.getSelfOrHeaderFooterViewModel('unknown')).toBe(viewModel);++ const editAreaEvents: DocumentEditArea[] = [];+ viewModel.editAreaChange$.subscribe((v) => {+ if (v) editAreaEvents.push(v);+ });+ viewModel.setEditArea(DocumentEditArea.HEADER);+ viewModel.setEditArea(DocumentEditArea.HEADER);+ viewModel.setEditArea(DocumentEditArea.FOOTER);+ expect(editAreaEvents).toEqual([DocumentEditArea.HEADER, DocumentEditArea.FOOTER]);+ expect(viewModel.getEditArea()).toBe(DocumentEditArea.FOOTER);++ const interceptor = {+ getCustomRange: vi.fn(() => ({ startIndex: 9, endIndex: 9, rangeId: 'ir' })),+ getCustomDecoration: vi.fn(() => ({ startIndex: 8, endIndex: 8, id: 'id' })),+ };+ const disposable = viewModel.registerCustomRangeInterceptor(interceptor as any);+ expect(viewModel.getCustomRange(0)?.rangeId).toBe('ir');+ expect(viewModel.getCustomDecoration(0)?.id).toBe('id');+ disposable.dispose();+ expect(viewModel.getCustomRange(0)?.rangeId).toBe('r1');++ const newModel = createDocumentDataModel({+ body: {+ dataStream: `Z${DataStreamTreeTokenType.PARAGRAPH}${DataStreamTreeTokenType.SECTION_BREAK}`,+ textRuns: [{ st: 0, ed: 1, ts: { fs: 14 } }],+ paragraphs: [{ startIndex: 0 }],+ sectionBreaks: [{ startIndex: 1 }],+ customBlocks: [],+ customRanges: [],+ customDecorations: [],+ tables: [],+ },+ snapshot: { tableSource: {} },+ });+ viewModel.reset(newModel);+ expect(viewModel.getDataModel()).toBe(newModel);+ expect(viewModel.getTextRun(0)?.ed).toBe(1);++ expect(viewModel.findTableNodeById('not-exists')).toBeUndefined();+ const maps = viewModel.getHeaderFooterTreeMap();+ expect(maps.headerTreeMap.size).toBeGreaterThan(0);+ expect(maps.footerTreeMap.size).toBeGreaterThan(0);++ viewModel.dispose();+ expect(viewModel.getChildren().length).toBeGreaterThanOrEqual(0);+ });++ it('handles missing body and null arrays safely', () => {+ const emptyModel = {+ getBody: vi.fn(() => null),+ getSnapshot: vi.fn(() => ({ tableSource: {} })),+ headerModelMap: new Map(),+ footerModelMap: new Map(),+ } as any;++ const vm = new DocumentViewModel(emptyModel);+ expect(vm.getChildren()).toEqual([]);+ expect(vm.getParagraph(0)).toBeUndefined();+ expect(vm.getSectionBreak(0)).toBeUndefined();+ expect(vm.getTextRun(0)).toBeUndefined();+ expect(() => vm.getCustomRangeRaw(0)).toThrow();+ expect(() => vm.getCustomDecorationRaw(0)).toThrow();+ expect(() => vm.getCustomBlockWithoutSetCurrentIndex(0)).toThrow();+ vm.dispose();+ });});});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/background.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/background.spec.tsnew file mode 100644index 0000000000..4fc03a839d--- /dev/null+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/background.spec.ts@@ -0,0 +1,231 @@+/**+ * 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 { ObjectMatrix } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { Background } from '../background';++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ closePath: vi.fn(),+ fill: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),+ fillStyle: '',+ } as any;+}++function createCellInfo(overrides?: Partial<any>) {+ return {+ row: 0,+ column: 0,+ startX: 0,+ startY: 0,+ endX: 10,+ endY: 20,+ isMerged: false,+ isMergedMainCell: false,+ mergeInfo: {+ startX: 0,+ startY: 0,+ endX: 10,+ endY: 20,+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ },+ ...overrides,+ };+}++function createBgMatrix(entries: Array<[number, number, string]>, size = entries.length) {+ const valueMap = new Map(entries.map((item) => [`${item[0]}-${item[1]}`, item[2]]));+ return {+ getValue: vi.fn((row: number, col: number) => valueMap.get(`${row}-${col}`)),+ forValue: vi.fn((cb: (row: number, col: number, value: string) => void) => {+ entries.forEach(([row, col, value]) => cb(row, col, value));+ }),+ getSizeOf: vi.fn(() => size),+ };+}++describe('background extension', () => {+ it('draws by view ranges and by matrix iteration', () => {+ const extension = new Background();+ const ctx = createCtx();+ const bgByRange = createBgMatrix([[0, 0, '1']], 99);+ const bgByMatrix = createBgMatrix([[0, 0, '1']], 1);++ const worksheet = {+ getMergedCellRange: vi.fn(() => []),+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ getSpanModel: vi.fn(() => ({+ getMergeDataIndex: vi.fn(() => -1),+ })),+ } as any;++ const skeletonBase = {+ worksheet,+ rowHeightAccumulation: [20],+ columnWidthAccumulation: [40],+ columnTotalWidth: 40,+ rowTotalHeight: 20,+ getCellByIndexWithNoHeader: vi.fn(() => createCellInfo()),+ getCellWithCoordByIndex: vi.fn(() => createCellInfo()),+ };++ extension.draw(+ ctx,+ { scaleX: 1, scaleY: 1 } as any,+ {+ ...skeletonBase,+ stylesCache: {+ background: { '#ff0000': bgByRange },+ backgroundPositions: new ObjectMatrix(),+ },+ } as any,+ [],+ {+ viewRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ checkOutOfViewBound: true,+ } as any+ );+ expect(bgByRange.forValue).not.toHaveBeenCalled();+ expect(ctx.fill).toHaveBeenCalled();++ extension.draw(+ ctx,+ { scaleX: 1, scaleY: 1 } as any,+ {+ ...skeletonBase,+ stylesCache: {+ background: { '#00ff00': bgByMatrix },+ backgroundPositions: new ObjectMatrix(),+ },+ } as any,+ [],+ {+ viewRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ checkOutOfViewBound: true,+ } as any+ );+ expect(bgByMatrix.forValue).toHaveBeenCalled();+ });++ it('draws merged cell backgrounds and handles early draw exits', () => {+ const extension = new Background();+ const ctx = createCtx();+ const bgMatrix = createBgMatrix([[0, 0, '1']], 2);+ const mergedRange = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };++ const skeleton = {+ worksheet: {+ getMergedCellRange: vi.fn(() => [mergedRange]),+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ getSpanModel: vi.fn(() => ({+ getMergeDataIndex: vi.fn(() => -1),+ })),+ },+ stylesCache: {+ background: { '#112233': bgMatrix },+ backgroundPositions: new ObjectMatrix(),+ },+ rowHeightAccumulation: [20],+ columnWidthAccumulation: [40],+ columnTotalWidth: 40,+ rowTotalHeight: 20,+ getCellByIndexWithNoHeader: vi.fn(() => createCellInfo()),+ getCellWithCoordByIndex: vi.fn(() => createCellInfo({ isMergedMainCell: true })),+ } as any;++ extension.draw(+ ctx,+ { scaleX: 1, scaleY: 1 } as any,+ skeleton,+ [],+ {+ viewRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ checkOutOfViewBound: true,+ } as any+ );++ expect(skeleton.getCellWithCoordByIndex).toHaveBeenCalled();+ expect(ctx.fill).toHaveBeenCalled();+ });++ it('covers renderBGByCell visibility and merge checks', () => {+ const extension = new Background();+ const rect = vi.fn();++ const skeleton = {+ worksheet: {+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ },+ } as any;++ const bgContext = {+ spreadsheetSkeleton: skeleton,+ backgroundPaths: { rect },+ scaleX: 1,+ scaleY: 1,+ viewRanges: [{ startRow: 10, endRow: 10, startColumn: 10, endColumn: 10 }],+ diffRanges: [],+ cellInfo: createCellInfo(),+ } as any;++ const outOfView = extension.renderBGByCell(bgContext, 0, 0);+ expect(outOfView).toBe(true);+ expect(rect).not.toHaveBeenCalled();++ bgContext.viewRanges = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }];+ skeleton.worksheet.getRowVisible = vi.fn(() => false);+ const rowHidden = extension.renderBGByCell(bgContext, 0, 0);+ expect(rowHidden).toBe(true);++ bgContext.cellInfo = createCellInfo({+ isMergedMainCell: true,+ mergeInfo: {+ startX: 0,+ startY: 0,+ endX: 10,+ endY: 20,+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ });++ skeleton.worksheet.getRowVisible = vi.fn(() => false);+ const mergedRowHidden = extension.renderBGByCell(bgContext, 0, 0);+ expect(mergedRowHidden).toBe(true);++ skeleton.worksheet.getRowVisible = vi.fn(() => true);+ skeleton.worksheet.getColVisible = vi.fn(() => false);+ const mergedColHidden = extension.renderBGByCell(bgContext, 0, 0);+ expect(mergedColHidden).toBe(true);++ skeleton.worksheet.getColVisible = vi.fn(() => true);+ extension.renderBGByCell(bgContext, 0, 0);+ expect(rect).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/border.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/border.spec.tsnew file mode 100644index 0000000000..8644cc76b7--- /dev/null+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/border.spec.ts@@ -0,0 +1,288 @@+/**+ * 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 { BorderStyleTypes, ObjectMatrix } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { BORDER_TYPE } from '../../../../basics/const';+import { Border } from '../border';++const drawDiagonalLineByBorderTypeMock = vi.fn((..._args: any[]) => undefined);+const drawLineByBorderTypeMock = vi.fn((..._args: any[]) => undefined);+const getLineWidthMock = vi.fn((..._args: any[]) => 1);+const setLineTypeMock = vi.fn((..._args: any[]) => undefined);++vi.mock('../../../../basics/draw', () => ({+ drawDiagonalLineByBorderType: (...args: any[]) => drawDiagonalLineByBorderTypeMock(...args),+ drawLineByBorderType: (...args: any[]) => drawLineByBorderTypeMock(...args),+ getLineWidth: (...args: any[]) => getLineWidthMock(...args),+ setLineType: (...args: any[]) => setLineTypeMock(...args),+}));++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ closePath: vi.fn(),+ translateWithPrecisionRatio: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),+ strokeStyle: '',+ lineCap: 'round',+ globalCompositeOperation: 'source-over',+ } as any;+}++function createCellInfo(overrides?: Partial<any>) {+ return {+ startX: 0,+ startY: 0,+ endX: 20,+ endY: 10,+ isMerged: false,+ isMergedMainCell: false,+ mergeInfo: {+ startX: 0,+ startY: 0,+ endX: 20,+ endY: 10,+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ },+ ...overrides,+ };+}++describe('border extension', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('returns early on invalid draw preconditions and iterates valid range', () => {+ const extension = new Border();+ const ctx = createCtx();++ extension.draw(ctx, { scaleX: 1, scaleY: 1 } as any, { stylesCache: {} } as any, [], { viewRanges: [] } as any);++ const borderMatrix = new ObjectMatrix<any>();+ borderMatrix.setValue(0, 0, {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.THIN, color: '#111' },+ });+ const skeleton = {+ worksheet: {+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ },+ rowHeightAccumulation: [10],+ columnWidthAccumulation: [20],+ columnTotalWidth: 20,+ rowTotalHeight: 10,+ stylesCache: { border: borderMatrix },+ overflowCache: new ObjectMatrix(),+ getCellWithCoordByIndex: vi.fn(() => createCellInfo()),+ } as any;++ const spy = vi.spyOn(extension, 'renderBorderByCell');+ extension.draw(+ ctx,+ { scaleX: 1, scaleY: 1 } as any,+ skeleton,+ [],+ { viewRanges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] } as any+ );+ expect(spy).toHaveBeenCalled();+ expect(ctx.translateWithPrecisionRatio).toHaveBeenCalled();+ });++ it('handles renderBorderByCell hidden/diff branches', () => {+ const extension = new Border();+ const ctx = createCtx();+ const overflowCache = new ObjectMatrix<any>();++ const skeleton = {+ worksheet: {+ getRowVisible: vi.fn(() => false),+ getColVisible: vi.fn(() => true),+ },+ stylesCache: { border: new ObjectMatrix() },+ getCellWithCoordByIndex: vi.fn(() => createCellInfo()),+ } as any;++ const renderBorderContext = {+ ctx,+ precisionScale: 1,+ overflowCache,+ spreadsheetSkeleton: skeleton,+ diffRanges: [{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }],+ viewRanges: [],+ } as any;++ const borderConfig = {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.THIN, color: '#111' },+ } as any;++ const hiddenResult = extension.renderBorderByCell(renderBorderContext, 0, 0, borderConfig);+ expect(hiddenResult).toBe(true);++ skeleton.worksheet.getRowVisible = vi.fn(() => true);+ skeleton.worksheet.getColVisible = vi.fn(() => true);+ const outOfDiff = extension.renderBorderByCell(renderBorderContext, 0, 0, borderConfig);+ expect(outOfDiff).toBe(true);+ });++ it('renders regular/diagonal/double borders and internal helpers', () => {+ const extension = new Border() as any;+ const ctx = createCtx();+ const overflowCache = new ObjectMatrix<any>();+ const borderMatrix = new ObjectMatrix<any>();++ const borderConfig = {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.THIN, color: '#222' },+ [BORDER_TYPE.TL_BR]: { type: BORDER_TYPE.TL_BR, style: BorderStyleTypes.THIN, color: '#333' },+ } as any;++ const skeleton = {+ worksheet: {+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ },+ stylesCache: { border: borderMatrix },+ getCellWithCoordByIndex: vi.fn(() => createCellInfo()),+ } as any;++ const renderBorderContext = {+ ctx,+ precisionScale: 1,+ overflowCache,+ spreadsheetSkeleton: skeleton,+ diffRanges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ viewRanges: [],+ } as any;++ const doubleSpy = vi.spyOn(extension, '_renderDoubleBorder').mockImplementation(() => {});+ extension.renderBorderByCell(renderBorderContext, 0, 0, borderConfig);++ expect(getLineWidthMock).toHaveBeenCalled();+ expect(setLineTypeMock).toHaveBeenCalled();+ expect(drawDiagonalLineByBorderTypeMock).toHaveBeenCalled();+ expect(drawLineByBorderTypeMock).toHaveBeenCalled();+ expect(doubleSpy).toHaveBeenCalled();++ overflowCache.setValue(1, 3, {+ startRow: 1,+ endRow: 1,+ startColumn: 2,+ endColumn: 4,+ });+ expect(extension._getOverflowExclusion(overflowCache, BORDER_TYPE.TOP, 1, 3)).toBe(false);+ expect(extension._getOverflowExclusion(overflowCache, BORDER_TYPE.LEFT, 1, 3)).toBe(true);+ expect(extension._getOverflowExclusion(overflowCache, BORDER_TYPE.RIGHT, 1, 3)).toBe(true);++ const specificCache = new ObjectMatrix<any>();+ specificCache.setValue(2, 2, {+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.THIN, color: '#111' },+ [BORDER_TYPE.RIGHT]: { style: BorderStyleTypes.THIN, color: '#111' },+ });+ const specific = extension._getSpecificCellBorder(specificCache, 2, 2);+ expect(specific.left?.type).toBe(BORDER_TYPE.LEFT);+ expect(specific.right).toBeNull();+ expect(specific.top).toBeNull();+ });++ it('covers detailed double-border offset branches for vertical and horizontal lines', () => {+ const extension = new Border() as any;+ const ctx = createCtx();+ const borderCache = new ObjectMatrix<any>();++ borderCache.setValue(0, -1, {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.BOTTOM]: { type: BORDER_TYPE.BOTTOM, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.RIGHT]: { type: BORDER_TYPE.RIGHT, style: BorderStyleTypes.THIN, color: '#111' },+ });+ borderCache.setValue(0, 1, {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.BOTTOM]: { type: BORDER_TYPE.BOTTOM, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.THIN, color: '#111' },+ });+ borderCache.setValue(-1, 0, {+ [BORDER_TYPE.BOTTOM]: { type: BORDER_TYPE.BOTTOM, style: BorderStyleTypes.THIN, color: '#111' },+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.RIGHT]: { type: BORDER_TYPE.RIGHT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ });+ borderCache.setValue(1, 0, {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.THIN, color: '#111' },+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.RIGHT]: { type: BORDER_TYPE.RIGHT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ });+ borderCache.setValue(-1, -1, {+ [BORDER_TYPE.BOTTOM]: { type: BORDER_TYPE.BOTTOM, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.RIGHT]: { type: BORDER_TYPE.RIGHT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ });+ borderCache.setValue(-1, 1, {+ [BORDER_TYPE.BOTTOM]: { type: BORDER_TYPE.BOTTOM, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ });+ borderCache.setValue(1, -1, {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.RIGHT]: { type: BORDER_TYPE.RIGHT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ });+ borderCache.setValue(1, 1, {+ [BORDER_TYPE.TOP]: { type: BORDER_TYPE.TOP, style: BorderStyleTypes.DOUBLE, color: '#111' },+ [BORDER_TYPE.LEFT]: { type: BORDER_TYPE.LEFT, style: BorderStyleTypes.DOUBLE, color: '#111' },+ });++ const renderBorderContext = {+ ctx,+ precisionScale: 1,+ spreadsheetSkeleton: {+ stylesCache: {+ border: borderCache,+ },+ },+ } as any;++ extension._renderDoubleBorder({+ renderBorderContext,+ row: 0,+ col: 0,+ type: BORDER_TYPE.LEFT,+ lineWidth: 2,+ startX: 0,+ startY: 0,+ endX: 0,+ endY: 20,+ });++ extension._renderDoubleBorder({+ renderBorderContext,+ row: 0,+ col: 0,+ type: BORDER_TYPE.TOP,+ lineWidth: 2,+ startX: 0,+ startY: 0,+ endX: 20,+ endY: 0,+ });++ expect(drawLineByBorderTypeMock).toHaveBeenCalled();+ expect(ctx.save).toHaveBeenCalled();+ expect(ctx.restore).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.tsnew file mode 100644index 0000000000..7e52100796--- /dev/null+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.ts@@ -0,0 +1,119 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { ColumnHeaderLayout } from '../column-header-layout';++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ stroke: vi.fn(),+ clip: vi.fn(),+ rectByPrecision: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ translateWithPrecisionRatio: vi.fn(),+ fillText: vi.fn(),+ fillStyle: '',+ strokeStyle: '',+ textAlign: 'center',+ textBaseline: 'middle',+ font: '',+ } as any;+}++describe('column header layout extension', () => {+ it('supports config getters and style setter', () => {+ const layout = new ColumnHeaderLayout({+ columnsCfg: {+ 0: 'A-Col',+ },+ headerStyle: {+ fontColor: '#135',+ },+ });++ layout.configHeaderColumn(+ {+ columnsCfg: {+ 1: { text: 'B-Col', textAlign: 'left' },+ },+ headerStyle: {+ backgroundColor: '#eee',+ },+ },+ 'sheet-1'+ );++ const columnsCfg = layout.getColumnsCfg('sheet-1');+ expect(columnsCfg[0]).toBe('A-Col');+ expect((columnsCfg[1] as any).text).toBe('B-Col');++ const headerStyle = layout.getHeaderStyle('sheet-1');+ expect(headerStyle.fontColor).toBe('#135');+ expect(headerStyle.backgroundColor).toBe('#eee');++ const [cfg, specStyle] = layout.getCfgOfCurrentColumn(columnsCfg, headerStyle, 0);+ expect(cfg.text).toBe('A-Col');+ expect(specStyle).toBe(false);++ const ctx = createCtx();+ layout.setStyleToCtx(ctx, { textAlign: 'right', textBaseline: 'alphabetic', fontColor: '#222', borderColor: '#333', fontSize: 12 });+ expect(ctx.textAlign).toBe('right');+ expect(ctx.textBaseline).toBe('alphabetic');+ expect(ctx.fillStyle).toBe('#222');+ expect(ctx.strokeStyle).toBe('#333');+ expect(ctx.font).toContain('12px');+ });++ it('draws column headers and handles early returns/hidden columns', () => {+ const layout = new ColumnHeaderLayout({+ columnsCfg: {+ 0: { text: 'X', textAlign: 'right', backgroundColor: '#f0f0f0' },+ },+ });+ const ctx = createCtx();++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, {+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 },+ columnHeaderHeight: 0,+ } as any);+ expect(ctx.fillRectByPrecision).not.toHaveBeenCalled();++ const skeleton = {+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 },+ columnHeaderHeight: 22,+ rowHeightAccumulation: [20],+ columnWidthAccumulation: [40, 40, 90],+ columnTotalWidth: 90,+ rowTotalHeight: 20,+ worksheet: {+ getSheetId: vi.fn(() => 'sheet-main'),+ },+ } as any;++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton);++ expect(ctx.fillRectByPrecision).toHaveBeenCalled();+ expect(ctx.translateWithPrecisionRatio).toHaveBeenCalled();+ expect(ctx.stroke).toHaveBeenCalled();+ expect(ctx.fillText).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.tsnew file mode 100644index 0000000000..8ec064806d--- /dev/null+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/font.spec.ts@@ -0,0 +1,507 @@+/**+ * 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 { CellValueType, HorizontalAlign, ObjectMatrix, VerticalAlign, WrapStrategy } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { VERTICAL_ROTATE_ANGLE } from '../../../../basics/text-rotation';+import { Text } from '../../../../shape/text';+import { Font } from '../font';++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ closePath: vi.fn(),+ clip: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ rectByPrecision: vi.fn(),+ drawImage: vi.fn(),+ fillRectByPrecision: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),+ } as any;+}++function createCellInfo(overrides?: Partial<any>) {+ return {+ startX: 0,+ startY: 0,+ endX: 40,+ endY: 20,+ isMerged: false,+ isMergedMainCell: false,+ mergeInfo: {+ startX: 0,+ startY: 0,+ endX: 40,+ endY: 20,+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ },+ ...overrides,+ };+}++function createFontCache(overrides?: Partial<any>) {+ return {+ verticalAlign: VerticalAlign.TOP,+ horizontalAlign: HorizontalAlign.LEFT,+ wrapStrategy: WrapStrategy.OVERFLOW,+ imageCacheMap: {+ getImage: vi.fn(() => null),+ },+ cellData: {+ v: 'A',+ t: CellValueType.STRING,+ fontRenderExtension: {},+ },+ fontString: '12px Arial',+ style: {+ pd: { l: 1, r: 1, t: 1, b: 1 },+ cl: { rgb: '#111111' },+ },+ ...overrides,+ };+}++function createSpreadsheetSkeleton() {+ const overflowCache = new ObjectMatrix<any>();+ const worksheet = {+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ getCell: vi.fn(() => ({ v: 'A', t: CellValueType.STRING })),+ getSpanModel: vi.fn(() => ({+ getMergeDataIndex: vi.fn(() => -1),+ })),+ getMergedCellRange: vi.fn(() => []),+ } as any;++ return {+ worksheet,+ overflowCache,+ rowHeightAccumulation: [20, 40, 60],+ columnWidthAccumulation: [40, 80, 120],+ getCellWithCoordByIndex: vi.fn((row: number, col: number) => createCellInfo({+ startX: col * 40,+ endX: col * 40 + 40,+ startY: row * 20,+ endY: row * 20 + 20,+ })),+ getRowCount: vi.fn(() => 3),+ getColumnCount: vi.fn(() => 3),+ } as any;+}++describe('font extension', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ it('covers fallback image draw branches', () => {+ const font = new Font() as any;+ const ctx = createCtx();+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);++ font._imageFallback = { complete: false, naturalWidth: 0 };+ font._drawFallbackImage(ctx, 0, 0, 10, 10);+ expect(ctx.drawImage).not.toHaveBeenCalled();++ font._imageFallback = { complete: true, naturalWidth: 12 };+ ctx.drawImage.mockImplementationOnce(() => {+ throw new Error('draw fail');+ });+ font._drawFallbackImage(ctx, 1, 2, 3, 4);+ font._drawFallbackImage(ctx, 2, 3, 4, 5);+ expect(ctx.drawImage).toHaveBeenCalledTimes(2);+ expect(errorSpy).toHaveBeenCalled();+ });++ it('covers clip bounds for overflow/offset align branches', () => {+ const font = new Font() as any;+ const ctx = createCtx();+ const clipOverflowSpy = vi.spyOn(font, '_clipRectangleForOverflow').mockImplementation(() => undefined);+ const skeleton = createSpreadsheetSkeleton();++ const renderFontContext = {+ ctx,+ scale: 1,+ overflowRectangle: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 },+ fontCache: createFontCache({+ horizontalAlign: HorizontalAlign.LEFT,+ cellData: { v: 'A', t: CellValueType.STRING, fontRenderExtension: {} },+ }),+ startX: 0,+ startY: 0,+ endX: 40,+ endY: 20,+ spreadsheetSkeleton: skeleton,+ } as any;++ font._clipByRenderBounds(renderFontContext, 0, 1);+ expect(ctx.rectByPrecision).toHaveBeenCalled();++ renderFontContext.overflowRectangle = { startRow: 0, endRow: 1, startColumn: 0, endColumn: 2 };+ renderFontContext.fontCache = createFontCache({+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ centerAngle: VERTICAL_ROTATE_ANGLE,+ vertexAngle: VERTICAL_ROTATE_ANGLE,+ cellData: { v: 'B', t: CellValueType.STRING, fontRenderExtension: {} },+ });+ font._clipByRenderBounds(renderFontContext, 0, 1);+ expect(clipOverflowSpy).toHaveBeenCalledWith(+ ctx,+ 0,+ 1,+ 0,+ 2,+ 1,+ skeleton.rowHeightAccumulation,+ skeleton.columnWidthAccumulation,+ 0+ );++ renderFontContext.fontCache = createFontCache({+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ centerAngle: 0,+ vertexAngle: 30,+ cellData: { v: 'C', t: CellValueType.STRING, fontRenderExtension: {} },+ });+ font._clipByRenderBounds(renderFontContext, 1, 1);+ expect(clipOverflowSpy).toHaveBeenCalledWith(+ ctx,+ 0,+ 1,+ 0,+ 1,+ 1,+ skeleton.rowHeightAccumulation,+ skeleton.columnWidthAccumulation,+ 0+ );++ renderFontContext.fontCache = createFontCache({+ horizontalAlign: HorizontalAlign.LEFT,+ cellData: { v: 'D', t: CellValueType.STRING, fontRenderExtension: { leftOffset: 2, rightOffset: 1 } },+ });+ font._clipByRenderBounds(renderFontContext, 0, 1);+ expect(renderFontContext.startX).toBe(2);+ expect(renderFontContext.endX).toBe(39);+ });++ it('covers text render alignment and wrap branches', () => {+ const drawWithSpy = vi.spyOn(Text as any, 'drawWith').mockImplementation((..._args: any[]) => undefined);+ const font = new Font() as any;+ const ctx = createCtx();+ const overflow = new ObjectMatrix<any>();++ const renderFontCtx = {+ startX: 0,+ startY: 0,+ endX: 100,+ endY: 20,+ fontCache: createFontCache({+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ verticalAlign: VerticalAlign.MIDDLE,+ wrapStrategy: WrapStrategy.WRAP,+ vertexAngle: 0,+ cellData: { v: 123, t: CellValueType.NUMBER },+ }),+ } as any;+ font._renderText(ctx, 0, 0, renderFontCtx, overflow);+ expect(drawWithSpy).toHaveBeenLastCalledWith(+ ctx,+ expect.objectContaining({+ hAlign: HorizontalAlign.RIGHT,+ warp: true,+ })+ );++ renderFontCtx.fontCache = createFontCache({+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ wrapStrategy: WrapStrategy.OVERFLOW,+ cellData: { v: true, t: CellValueType.BOOLEAN },+ });+ font._renderText(ctx, 0, 0, renderFontCtx, overflow);+ expect(drawWithSpy).toHaveBeenLastCalledWith(+ ctx,+ expect.objectContaining({+ hAlign: HorizontalAlign.CENTER,+ warp: false,+ })+ );++ const before = drawWithSpy.mock.calls.length;+ renderFontCtx.fontCache = createFontCache({+ cellData: { v: null, t: CellValueType.STRING },+ });+ font._renderText(ctx, 0, 0, renderFontCtx, overflow);+ expect(drawWithSpy.mock.calls.length).toBe(before);+ });++ it('covers documents render branches and missing documents error', () => {+ const font = new Font() as any;+ const ctx = createCtx();+ const overflow = new ObjectMatrix<any>();+ const spreadsheetSkeleton = createSpreadsheetSkeleton();+ overflow.setValue(0, 0, {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ });++ const documentDataModel = {+ updateDocumentDataPageSize: vi.fn(),+ getSnapshot: vi.fn(() => ({+ documentStyle: {+ marginLeft: 1,+ marginRight: 2,+ },+ })),+ };+ const documentSkeleton = {+ getViewModel: vi.fn(() => ({+ getDataModel: vi.fn(() => documentDataModel),+ })),+ calculate: vi.fn(),+ makeDirty: vi.fn(),+ getSkeletonData: vi.fn(() => ({+ pages: [{+ width: 30,+ height: 12,+ sections: [{+ columns: [{+ width: 30,+ spaceWidth: 0,+ lines: [{ lineHeight: 10 }],+ }],+ }],+ }],+ })),+ };++ const documents = {+ resize: vi.fn(),+ changeSkeleton: vi.fn(() => documents),+ render: vi.fn(),+ };+ font.parent = {+ getDocuments: vi.fn(() => documents),+ };++ const renderFontCtx = {+ fontCache: createFontCache({+ documentSkeleton,+ wrapStrategy: WrapStrategy.WRAP,+ vertexAngle: 0,+ }),+ startX: 0,+ startY: 0,+ endX: 40,+ endY: 20,+ spreadsheetSkeleton,+ } as any;++ font._renderDocuments(ctx, 0, 0, renderFontCtx, overflow);+ expect(documentDataModel.updateDocumentDataPageSize).toHaveBeenCalled();+ expect(documentSkeleton.calculate).toHaveBeenCalled();+ expect(documents.resize).toHaveBeenCalledWith(40, 20);+ expect(documents.changeSkeleton).toHaveBeenCalledWith(documentSkeleton);+ expect(documents.render).toHaveBeenCalled();++ font.parent = { getDocuments: vi.fn(() => null) };+ expect(() => font._renderDocuments(ctx, 0, 0, renderFontCtx, overflow)).toThrow('documents is null');+ });++ it('covers image rendering fallback branches', () => {+ const font = new Font() as any;+ const ctx = createCtx();+ const fallbackSpy = vi.spyOn(font, '_drawFallbackImage').mockImplementation(() => undefined);++ const errorImage = { complete: true, getAttribute: vi.fn(() => 'true') };+ const throwImage = { complete: true, marker: 'throw', getAttribute: vi.fn(() => 'false') };+ const pendingImage = { complete: false, getAttribute: vi.fn(() => 'false') };+ ctx.drawImage.mockImplementation((image: any) => {+ if (image.marker === 'throw') {+ throw new Error('image draw error');+ }+ });++ const fontCache = createFontCache({+ verticalAlign: VerticalAlign.MIDDLE,+ horizontalAlign: HorizontalAlign.CENTER,+ imageCacheMap: {+ getImage: vi.fn((_type: any, src: string) => {+ if (src === 'err') return errorImage;+ if (src === 'throw') return throwImage;+ return pendingImage;+ }),+ },+ documentSkeleton: {+ getViewModel: vi.fn(() => ({+ getDataModel: vi.fn(() => ({+ getDrawings: vi.fn(() => ({+ d1: { imageSourceType: 'url', source: 'err' },+ d2: { imageSourceType: 'url', source: 'throw' },+ d3: { imageSourceType: 'url', source: 'pending' },+ })),+ })),+ })),+ getSkeletonData: vi.fn(() => ({+ pages: [{+ width: 20,+ height: 10,+ skeDrawings: [+ { drawingId: 'd1', aLeft: 1, aTop: 1, width: 6, height: 4, angle: 0 },+ { drawingId: 'd2', aLeft: 2, aTop: 2, width: 6, height: 4, angle: 15 },+ { drawingId: 'd3', aLeft: 3, aTop: 3, width: 6, height: 4, angle: 0 },+ ],+ }],+ })),+ },+ });++ font._renderImages(ctx, fontCache, 0, 0, 40, 20);+ expect(fallbackSpy).toHaveBeenCalledTimes(2);+ expect(ctx.rotate).toHaveBeenCalled();+ });++ it('covers draw and render-each-cell early/normal branches', () => {+ const font = new Font() as any;+ const ctx = createCtx();+ const spreadsheetSkeleton = createSpreadsheetSkeleton();+ const fontMatrix = new ObjectMatrix<any>();+ fontMatrix.setValue(0, 0, createFontCache({+ cellData: { v: 'text', t: CellValueType.STRING, fontRenderExtension: {} },+ }));+ fontMatrix.setValue(1, 1, createFontCache({+ documentSkeleton: {+ getViewModel: vi.fn(() => ({+ getDataModel: vi.fn(() => ({+ getDrawingsOrder: vi.fn(() => ['d1']),+ })),+ })),+ },+ cellData: { v: 'doc', t: CellValueType.STRING, fontRenderExtension: {} },+ }));+ spreadsheetSkeleton.stylesCache = { fontMatrix };+ spreadsheetSkeleton.columnTotalWidth = 120;+ spreadsheetSkeleton.rowTotalHeight = 60;+ spreadsheetSkeleton.worksheet.getCell = vi.fn((row: number, col: number) => {+ if (row === 2 && col === 2) {+ return { v: 'skip', fontRenderExtension: { isSkip: true } };+ }+ return { v: 'ok' };+ });+ spreadsheetSkeleton.worksheet.getMergedCellRange = vi.fn(() => [{+ startRow: 1,+ endRow: 1,+ startColumn: 1,+ endColumn: 1,+ }]);+ spreadsheetSkeleton.worksheet.getSpanModel = vi.fn(() => ({+ getMergeDataIndex: vi.fn((_row: number, _col: number) => 100),+ }));++ const renderTextSpy = vi.spyOn(font, '_renderText').mockImplementation(() => undefined);+ const renderDocSpy = vi.spyOn(font, '_renderDocuments').mockImplementation(() => undefined);+ const renderImageSpy = vi.spyOn(font, '_renderImages').mockImplementation(() => undefined);++ const renderFontCtx = {+ ctx,+ scale: 1,+ columnTotalWidth: 120,+ rowTotalHeight: 60,+ viewRanges: [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }],+ checkOutOfViewBound: true,+ diffRanges: [],+ spreadsheetSkeleton,+ cellInfo: createCellInfo(),+ } as any;++ const mergedSkip = font._renderFontEachCell(+ {+ ...renderFontCtx,+ cellInfo: createCellInfo({ isMerged: true, isMergedMainCell: false }),+ },+ 0,+ 0,+ fontMatrix+ );+ expect(mergedSkip).toBe(true);++ const hiddenSkeleton = createSpreadsheetSkeleton();+ hiddenSkeleton.worksheet.getRowVisible = vi.fn(() => false);+ const hiddenResult = font._renderFontEachCell(+ {+ ...renderFontCtx,+ spreadsheetSkeleton: hiddenSkeleton,+ cellInfo: createCellInfo(),+ },+ 0,+ 0,+ fontMatrix+ );+ expect(hiddenResult).toBe(true);++ const skipResult = font._renderFontEachCell(+ {+ ...renderFontCtx,+ cellInfo: createCellInfo(),+ },+ 2,+ 2,+ fontMatrix+ );+ expect(skipResult).toBe(true);++ const normalResult = font._renderFontEachCell(+ {+ ...renderFontCtx,+ cellInfo: createCellInfo(),+ },+ 0,+ 0,+ fontMatrix+ );+ expect(normalResult).toBe(false);+ expect(renderTextSpy).toHaveBeenCalled();++ const documentResult = font._renderFontEachCell(+ {+ ...renderFontCtx,+ cellInfo: createCellInfo(),+ },+ 1,+ 1,+ fontMatrix+ );+ expect(documentResult).toBe(false);+ expect(renderDocSpy).toHaveBeenCalled();+ expect(renderImageSpy).toHaveBeenCalled();++ font.draw(ctx, { scaleX: 1, scaleY: 1 } as any, spreadsheetSkeleton, [], {+ viewRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ checkOutOfViewBound: true,+ viewportKey: 'viewMain',+ } as any);+ expect(ctx.save).toHaveBeenCalled();+ expect(ctx.restore).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/marker.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/marker.spec.tsnew file mode 100644index 0000000000..792a7233c6--- /dev/null+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/marker.spec.ts@@ -0,0 +1,141 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { Marker } from '../marker';++function createCtx() {+ return {+ __mode: 'normal',+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ closePath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ fill: vi.fn(),+ fillStyle: '',+ } as any;+}++function createCellInfo(overrides?: Partial<any>) {+ return {+ startX: 0,+ startY: 0,+ endX: 10,+ endY: 20,+ isMerged: false,+ isMergedMainCell: false,+ mergeInfo: {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ startX: 0,+ startY: 0,+ endX: 10,+ endY: 20,+ },+ ...overrides,+ };+}++describe('marker extension', () => {+ it('returns early in printing mode or missing worksheet', () => {+ const marker = new Marker();+ const ctx = createCtx();+ ctx.__mode = 'printing';++ marker.draw(ctx, { scaleX: 1, scaleY: 1 } as any, {} as any, []);+ expect(ctx.fill).not.toHaveBeenCalled();++ ctx.__mode = 'normal';+ marker.draw(ctx, { scaleX: 1, scaleY: 1 } as any, { rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } } as any, []);+ expect(ctx.fill).not.toHaveBeenCalled();+ });++ it('renders all four corner markers and skips hidden rows/cols', () => {+ const marker = new Marker();+ const ctx = createCtx();++ const worksheet = {+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ getCell: vi.fn(() => ({+ markers: {+ tr: { size: 2, color: '#f00' },+ tl: { size: 2, color: '#0f0' },+ br: { size: 2, color: '#00f' },+ bl: { size: 2, color: '#333' },+ },+ })),+ };+ const skeleton = {+ worksheet,+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ getCellWithCoordByIndex: vi.fn(() => createCellInfo()),+ } as any;++ marker.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton, [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]);+ expect(ctx.fill).toHaveBeenCalledTimes(4);++ worksheet.getRowVisible.mockReturnValue(false);+ marker.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton, [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]);+ expect(ctx.fill).toHaveBeenCalledTimes(4);+ });++ it('deduplicates merged cell marker drawing and respects diff ranges', () => {+ const marker = new Marker();+ const ctx = createCtx();++ const mergeInfo = {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 1,+ startX: 0,+ startY: 0,+ endX: 20,+ endY: 20,+ };++ const worksheet = {+ getRowVisible: vi.fn(() => true),+ getColVisible: vi.fn(() => true),+ getCell: vi.fn(() => ({+ markers: {+ tr: { size: 3, color: '#f00' },+ },+ })),+ };+ const skeleton = {+ worksheet,+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 },+ getCellWithCoordByIndex: vi.fn((row: number, col: number) => {+ if (col === 0) {+ return createCellInfo({ isMergedMainCell: true, mergeInfo });+ }+ return createCellInfo({ isMerged: true, mergeInfo });+ }),+ } as any;++ marker.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton, [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }]);+ expect(ctx.fill).toHaveBeenCalledTimes(1);++ marker.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton, [{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }]);+ expect(ctx.fill).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.tsnew file mode 100644index 0000000000..5feaf59e77--- /dev/null+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.ts@@ -0,0 +1,119 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { RowHeaderLayout } from '../row-header-layout';++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ stroke: vi.fn(),+ clip: vi.fn(),+ rectByPrecision: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ translateWithPrecisionRatio: vi.fn(),+ fillText: vi.fn(),+ fillStyle: '',+ strokeStyle: '',+ textAlign: 'center',+ textBaseline: 'middle',+ font: '',+ } as any;+}++describe('row header layout extension', () => {+ it('supports config getters and style setter', () => {+ const layout = new RowHeaderLayout({+ rowsCfg: {+ 0: 'R1',+ },+ headerStyle: {+ fontColor: '#123',+ },+ });++ layout.configHeaderRow(+ {+ rowsCfg: {+ 1: { text: 'SheetRow', backgroundColor: '#eee' },+ },+ headerStyle: {+ backgroundColor: '#ddd',+ },+ },+ 'sheet-1'+ );++ const rowsCfg = layout.getRowsCfg('sheet-1');+ expect(rowsCfg[0]).toBe('R1');+ expect((rowsCfg[1] as any).text).toBe('SheetRow');++ const headerStyle = layout.getHeaderStyle('sheet-1');+ expect(headerStyle.fontColor).toBe('#123');+ expect(headerStyle.backgroundColor).toBe('#ddd');++ const [cfg, specStyle] = layout.getCfgOfCurrentRow(rowsCfg, headerStyle, 0);+ expect(cfg.text).toBe('R1');+ expect(specStyle).toBe(false);++ const ctx = createCtx();+ layout.setStyleToCtx(ctx, { textAlign: 'right', textBaseline: 'alphabetic', fontColor: '#456', borderColor: '#789', fontSize: 12 });+ expect(ctx.textAlign).toBe('right');+ expect(ctx.textBaseline).toBe('alphabetic');+ expect(ctx.fillStyle).toBe('#456');+ expect(ctx.strokeStyle).toBe('#789');+ expect(ctx.font).toContain('12px');+ });++ it('draws row headers and handles early returns/hidden rows', () => {+ const layout = new RowHeaderLayout({+ rowsCfg: {+ 0: { text: 'Top', textAlign: 'right', backgroundColor: '#f6f6f6' },+ },+ });+ const ctx = createCtx();++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, {+ rowColumnSegment: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 },+ rowHeaderWidth: 0,+ } as any);+ expect(ctx.fillRectByPrecision).not.toHaveBeenCalled();++ const skeleton = {+ rowColumnSegment: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 },+ rowHeaderWidth: 30,+ rowHeightAccumulation: [20, 20, 40],+ columnWidthAccumulation: [50],+ columnTotalWidth: 50,+ rowTotalHeight: 40,+ worksheet: {+ getSheetId: vi.fn(() => 'sheet-main'),+ },+ } as any;++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton);++ expect(ctx.fillRectByPrecision).toHaveBeenCalled();+ expect(ctx.translateWithPrecisionRatio).toHaveBeenCalled();+ expect(ctx.stroke).toHaveBeenCalled();+ expect(ctx.fillText).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/components/sheets/watermark/__tests__/util.spec.ts b/packages/engine-render/src/components/sheets/watermark/__tests__/util.spec.tsnew file mode 100644index 0000000000..4d0ac720df--- /dev/null+++ b/packages/engine-render/src/components/sheets/watermark/__tests__/util.spec.ts@@ -0,0 +1,252 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { IWatermarkTypeEnum } from '../type';+import { renderImageWatermark, renderTextWatermark, renderUserInfoWatermark, renderWatermark } from '../util';++function createCtx() {+ return {+ canvas: { width: 120, height: 80 },+ save: vi.fn(),+ restore: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ fillText: vi.fn(),+ drawImage: vi.fn(),+ measureText: vi.fn(() => ({ width: 12 })),+ globalAlpha: 1,+ direction: 'inherit',+ font: '',+ fillStyle: '',+ } as any;+}++describe('watermark util extra', () => {+ it('renders user watermark in both repeat and single mode', () => {+ const ctx = createCtx();+ const user = { name: 'alice' } as any;++ renderUserInfoWatermark(ctx, {+ x: 0,+ y: 0,+ repeat: true,+ spacingX: 4,+ spacingY: 6,+ rotate: 30,+ opacity: 0.5,+ name: true,+ email: false,+ phone: false,+ uid: false,+ fontSize: 10,+ color: '#111',+ bold: true,+ italic: true,+ direction: 'ltr',+ }, user);++ renderUserInfoWatermark(ctx, {+ x: 2,+ y: 2,+ repeat: false,+ spacingX: 4,+ spacingY: 6,+ rotate: 0,+ opacity: 1,+ name: true,+ email: false,+ phone: false,+ uid: false,+ fontSize: 12,+ color: '#111',+ bold: false,+ italic: false,+ direction: 'inherit',+ }, user);++ renderUserInfoWatermark(ctx, {+ x: 0,+ y: 0,+ repeat: false,+ spacingX: 1,+ spacingY: 1,+ rotate: 0,+ opacity: 1,+ name: true,+ email: false,+ phone: false,+ uid: false,+ fontSize: 12,+ color: '#111',+ bold: false,+ italic: false,+ direction: 'inherit',+ }, null);++ expect(ctx.fillText).toHaveBeenCalled();+ expect(ctx.save).toHaveBeenCalled();+ });++ it('renders text and image watermark dispatch path', () => {+ const ctx = createCtx();+ const image = document.createElement('img');+ Object.defineProperty(image, 'complete', { value: true, configurable: true });++ renderTextWatermark(ctx, {+ x: 1,+ y: 1,+ repeat: true,+ spacingX: 5,+ spacingY: 5,+ rotate: 15,+ opacity: 0.7,+ content: 'W',+ fontSize: 10,+ color: '#333',+ bold: false,+ italic: false,+ direction: 'rtl',+ });+ renderTextWatermark(ctx, {+ x: 1,+ y: 1,+ repeat: false,+ spacingX: 5,+ spacingY: 5,+ rotate: 0,+ opacity: 1,+ content: 'S',+ fontSize: 10,+ color: '#333',+ bold: false,+ italic: false,+ direction: 'inherit',+ });++ renderImageWatermark(ctx, {+ x: 0,+ y: 0,+ repeat: true,+ spacingX: 2,+ spacingY: 2,+ rotate: 20,+ opacity: 0.8,+ url: '',+ width: 24,+ height: 12,+ maintainAspectRatio: true,+ originRatio: 2,+ }, image);+ renderImageWatermark(ctx, {+ x: 0,+ y: 0,+ repeat: false,+ spacingX: 2,+ spacingY: 2,+ rotate: 0,+ opacity: 1,+ url: '',+ width: 24,+ height: 12,+ maintainAspectRatio: false,+ originRatio: 2,+ }, image);++ renderImageWatermark(ctx, {+ x: 0,+ y: 0,+ repeat: false,+ spacingX: 2,+ spacingY: 2,+ rotate: 0,+ opacity: 1,+ url: '',+ width: 24,+ height: 12,+ maintainAspectRatio: false,+ originRatio: 2,+ }, null);++ renderWatermark(ctx, {+ type: IWatermarkTypeEnum.UserInfo,+ config: {+ userInfo: {+ x: 0,+ y: 0,+ repeat: false,+ spacingX: 0,+ spacingY: 0,+ rotate: 0,+ opacity: 1,+ name: true,+ email: false,+ phone: false,+ uid: false,+ fontSize: 10,+ color: '#000',+ bold: false,+ italic: false,+ direction: 'inherit',+ },+ },+ }, image, { name: 'u' } as any);++ renderWatermark(ctx, {+ type: IWatermarkTypeEnum.Image,+ config: {+ image: {+ x: 0,+ y: 0,+ repeat: false,+ spacingX: 0,+ spacingY: 0,+ rotate: 0,+ opacity: 1,+ url: '',+ width: 12,+ height: 8,+ maintainAspectRatio: false,+ originRatio: 1.5,+ },+ },+ }, image, null);++ renderWatermark(ctx, {+ type: IWatermarkTypeEnum.Text,+ config: {+ text: {+ x: 0,+ y: 0,+ repeat: false,+ spacingX: 0,+ spacingY: 0,+ rotate: 0,+ opacity: 1,+ content: 'TXT',+ fontSize: 11,+ color: '#000',+ bold: false,+ italic: false,+ direction: 'inherit',+ },+ },+ }, image, null);++ expect(ctx.drawImage).toHaveBeenCalled();+ expect(ctx.fillText).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/render-manager/__tests__/render-manager.service.spec.ts b/packages/engine-render/src/render-manager/__tests__/render-manager.service.spec.tsnew file mode 100644index 0000000000..04dd7e2c4a--- /dev/null+++ b/packages/engine-render/src/render-manager/__tests__/render-manager.service.spec.ts@@ -0,0 +1,157 @@+/**+ * 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 { Injector } from '@univerjs/core';+import { UniverInstanceType } from '@univerjs/core';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { Engine } from '../../engine';+import {+ getCurrentTypeOfRenderer,+ isDisposable,+ RenderManagerService,+ withCurrentTypeOfRenderer,+} from '../render-manager.service';+import { RenderUnit } from '../render-unit';++describe('render manager service', () => {+ it('covers render map lifecycle and dark mode listener', () => {+ const darkMode$ = new Subject<boolean>();+ const injector = {+ createInstance: vi.fn(() => new Engine()),+ } as unknown as Injector;+ const instanceService = {+ getUnit: vi.fn(() => null),+ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET),+ getCurrentUnitOfType: vi.fn(() => null),+ } as any;+ const themeService = { darkMode$ } as any;++ const service = new RenderManagerService(injector, instanceService, themeService);+ const engine = new Engine('render-service-test', { elementWidth: 100, elementHeight: 80, dpr: 1 });++ const component = {+ makeForceDirty: vi.fn(),+ makeDirty: vi.fn(),+ dispose: vi.fn(),+ };+ const render = {+ unitId: 'u-1',+ type: UniverInstanceType.UNIVER_SHEET,+ engine,+ scene: engine.activeScene!,+ components: new Map([['c', component]]),+ with: vi.fn(() => null),+ dispose: vi.fn(),+ } as any;+ if (!render.scene) {+ render.scene = { dispose: vi.fn() };+ }++ service.addRender('u-1', render);+ expect(service.has('u-1')).toBe(true);+ expect(service.getRenderById('u-1')).toBe(render);+ expect(service.getRenderUnitById('u-1')).toBe(render);+ expect(service.getAllRenderersOfType(UniverInstanceType.UNIVER_SHEET).length).toBe(1);++ darkMode$.next(true);+ expect(component.makeForceDirty).toHaveBeenCalledWith(true);+ expect(component.makeDirty).toHaveBeenCalledWith(true);++ service.removeRender('u-1');+ expect(service.has('u-1')).toBe(false);+ service.dispose();+ });++ it('covers dependency registration, render creation branches and helper funcs', () => {+ const darkMode$ = new Subject<boolean>();+ const createdRenderUnit = {+ unitId: 'u-2',+ type: UniverInstanceType.UNIVER_SHEET,+ engine: new Engine('u-2-engine', { elementWidth: 10, elementHeight: 10, dpr: 1 }),+ scene: { dispose: vi.fn() },+ components: new Map(),+ addRenderDependencies: vi.fn(),+ with: vi.fn(() => 'ok'),+ dispose: vi.fn(),+ } as any as RenderUnit;++ const engineForCreate = new Engine('u-2-create', { elementWidth: 20, elementHeight: 20, dpr: 1 });+ const injector = {+ createInstance: vi.fn((Ctor: unknown) => {+ if (Ctor === Engine) {+ return engineForCreate;+ }+ if (Ctor === RenderUnit) {+ return createdRenderUnit;+ }+ return null;+ }),+ } as unknown as Injector;++ const unit = {+ getUnitId: () => 'u-2',+ };+ const instanceService = {+ getUnit: vi.fn(() => unit),+ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET),+ getCurrentUnitOfType: vi.fn(() => null),+ } as any;+ const themeService = { darkMode$ } as any;++ const service = new RenderManagerService(injector, instanceService, themeService);++ const depA = Symbol('dep-a') as any;+ const depB = Symbol('dep-b') as any;+ const disposableA = service.registerRenderModule(UniverInstanceType.UNIVER_SHEET, depA);+ const disposableB = service.registerRenderModules(UniverInstanceType.UNIVER_SHEET, [depB]);++ const created = service.createRender('u-2');+ expect(created).toBe(createdRenderUnit);++ (instanceService.getUnit as any).mockReturnValue(null);+ const thumbnailRender = (service as any)._createRender('slide-unit', new Engine('slide', {+ elementWidth: 10,+ elementHeight: 10,+ dpr: 1,+ }));+ expect(thumbnailRender.isThumbNail).toBe(true);+ expect(service.getRenderById('slide-unit')).toBe(thumbnailRender);++ const current = getCurrentTypeOfRenderer(+ UniverInstanceType.UNIVER_SHEET,+ instanceService,+ service+ );+ expect(current).toBeNull();+ (instanceService.getCurrentUnitOfType as any).mockReturnValue(unit);+ expect(+ withCurrentTypeOfRenderer(+ UniverInstanceType.UNIVER_SHEET,+ Symbol('token') as any,+ instanceService,+ service+ )+ ).toBe('ok');++ expect(isDisposable({ dispose: () => null })).toBe(true);+ expect(isDisposable({})).toBe(false);++ disposableA.dispose();+ disposableB.dispose();+ service.dispose();+ });+});diff --git a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts b/packages/engine-render/src/services/__tests__/canvas-color.spec.tsindex 6e91d23364..757c3fa9d0 100644--- a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts+++ b/packages/engine-render/src/services/__tests__/canvas-color.spec.ts@@ -17,7 +17,8 @@import type { Injector } from '@univerjs/core';import { ThemeService } from '@univerjs/core';import { ICanvasColorService } from '@univerjs/engine-render';-import { beforeEach, describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { CanvasColorService, DumbCanvasColorService, hexToRgb, rgbToHex } from '../canvas-color.service';import { createCanvasColorTestBed } from './create-canvas-color-test-bed';describe('Test Canvas Color', () => {@@ -91,4 +92,41 @@ describe('Test Canvas Color', () => {const invertedColor2 = canvasColorService.getRenderColor(color);expect(invertedColor2).toEqual('#333333ff');});++ it('test color parser and formatter', () => {+ expect(hexToRgb('#abc')).toEqual([170, 187, 204]);+ expect(hexToRgb('#112233')).toEqual([17, 34, 51]);+ expect(hexToRgb('#abcd')).toEqual([170, 187, 204]);+ expect(rgbToHex([10.2, 255.4, 0.49] as any)).toBe('#0aff00');+ });++ it('test dumb service', () => {+ const service = new DumbCanvasColorService();+ expect(service.getRenderColor('rgb(1,2,3)')).toBe('rgb(1,2,3)');+ });++ it('test theme token cache and illegal color branch', () => {+ const themed = new CanvasColorService({+ darkMode: true,+ isValidThemeColor: (color: string) => color === 'primary.500',+ getColorFromTheme: () => '#123456',+ } as any);+ expect(themed.getRenderColor('primary.500')).toBe('#123456');++ const service = new CanvasColorService({+ darkMode: true,+ isValidThemeColor: () => false,+ getColorFromTheme: () => '#000000',+ } as any);++ const invert = vi.fn(() => [1, 2, 3]);+ (service as any)._invertAlgo = invert;+ expect(service.getRenderColor('#ffffff')).toBe('#010203');+ expect(service.getRenderColor('#ffffff')).toBe('#010203');+ expect(invert).toHaveBeenCalledTimes(1);++ (service as any)._invertAlgo = () => [9, 8, 7];+ expect(service.getRenderColor('red')).toBe('rgba(9,8,7, 1)');+ expect(() => service.getRenderColor('not-a-color-token')).toThrow(/illegal color/);+ });});diff --git a/packages/engine-render/src/services/__tests__/render-config.service.spec.ts b/packages/engine-render/src/services/__tests__/render-config.service.spec.tsnew file mode 100644index 0000000000..67d406b034--- /dev/null+++ b/packages/engine-render/src/services/__tests__/render-config.service.spec.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { UniverRenderConfigService } from '../render-config.service';++describe('UniverRenderConfigService', () => {+ it('should set/get render config and remove nullish values', () => {+ const service = new UniverRenderConfigService();++ expect(service.getRenderConfig()).toEqual({ ok: '111' });++ service.setRenderConfig('font', '12px');+ expect(service.getRenderConfig()).toEqual({ ok: '111', font: '12px' });++ service.setRenderConfig('font', null);+ expect(service.getRenderConfig()).toEqual({ ok: '111' });++ service.setRenderConfig('lineWidth', 2);+ service.setRenderConfig('lineWidth', undefined as any);+ expect(service.getRenderConfig()).toEqual({ ok: '111' });+ });++ it('should debounce update signal stream', async () => {+ vi.useFakeTimers();++ const service = new UniverRenderConfigService();+ const listener = vi.fn();+ const subscription = service.updateSignal$.subscribe(listener);++ (service as any)._updateSignal$.next();+ (service as any)._updateSignal$.next();++ expect(listener).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(4);+ expect(listener).toHaveBeenCalledTimes(1);++ subscription.unsubscribe();+ vi.useRealTimers();+ });+});diff --git a/packages/engine-render/src/shape/__tests__/image.spec.ts b/packages/engine-render/src/shape/__tests__/image.spec.tsnew file mode 100644index 0000000000..96ac85983f--- /dev/null+++ b/packages/engine-render/src/shape/__tests__/image.spec.ts@@ -0,0 +1,129 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { Vector2 } from '../../basics/vector2';+import { Image } from '../image';++function createNativeImage(width = 120, height = 80) {+ const img = document.createElement('img');+ Object.defineProperty(img, 'width', { value: width, configurable: true });+ Object.defineProperty(img, 'height', { value: height, configurable: true });+ Object.defineProperty(img, 'complete', { value: true, configurable: true });+ return img;+}++function createCtxMock() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ rect: vi.fn(),+ clip: vi.fn(),+ drawImage: vi.fn(),+ transform: vi.fn(),+ globalAlpha: 1,+ } as any;+}++describe('image extra', () => {+ it('handles srcRect transform and render branches', () => {+ const image = new Image('img1', {+ image: createNativeImage(100, 60),+ left: 20,+ top: 10,+ width: 100,+ height: 60,+ srcRect: { left: 5, top: 6, right: 7, bottom: 8 },+ });++ const calculated = image.calculateTransformWithSrcRect();+ expect(calculated).toEqual({+ left: 15,+ top: 4,+ width: 112,+ height: 74,+ angle: 0,+ });++ image.openRenderByCropper();+ image.closeRenderByCropper();+ image.setOpacity(0.6);+ expect(image.opacity).toBe(0.6);++ const ctx = createCtxMock();+ image.render(ctx);+ expect(ctx.save).toHaveBeenCalled();+ expect(ctx.drawImage).toHaveBeenCalled();+ });++ it('supports source switching, reset size and hit testing', () => {+ const image = new Image('img2', {+ image: createNativeImage(90, 50),+ left: 30,+ top: 40,+ width: 90,+ height: 50,+ srcRect: { left: 10, top: 10, right: 0, bottom: 0 },+ });++ image.changeSource('https://example.com/a.png');+ image.getNative()!.onload!(new Event('load'));+ image.setSrcRect({ left: 2, top: 3, right: 4, bottom: 5 });+ image.transformByState({+ width: 120,+ height: 70,+ left: 32,+ top: 41,+ });+ expect(image.srcRect).toMatchObject({+ left: expect.any(Number),+ top: expect.any(Number),+ right: expect.any(Number),+ bottom: expect.any(Number),+ });++ image.resetSize();+ expect(image.width).toBe(90);+ expect(image.height).toBe(50);++ expect(image.isHit(Vector2.FromArray([75, 65]))).toBe(true);+ expect(image.isHit(Vector2.FromArray([300, 260]))).toBe(false);+ });++ it('handles failure branch and close transform update path', () => {+ const image = new Image('img3', {+ url: 'https://example.com/404.png',+ left: 0,+ top: 0,+ width: 80,+ height: 40,+ srcRect: { left: 4, top: 4, right: 4, bottom: 4 },+ fail: vi.fn(),+ });+ image.getNative()!.onerror!(new Event('error'));+ expect(image.getProps().fail).toHaveBeenCalled();++ image.transformByStateCloseCropper({+ width: 100,+ height: 60,+ left: 10,+ top: 20,+ });+ expect(image.width).toBe(100);+ expect(image.height).toBe(60);+ });+});diff --git a/packages/engine-render/src/shape/__tests__/path.spec.ts b/packages/engine-render/src/shape/__tests__/path.spec.tsnew file mode 100644index 0000000000..a77e57d1b7--- /dev/null+++ b/packages/engine-render/src/shape/__tests__/path.spec.ts@@ -0,0 +1,248 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { Path } from '../path';++describe('Path extra', () => {+ it('parses rich path commands and computes path lengths', () => {+ const parsed = Path.parsePathData('M0 0 L10 0 H15 V5 C15 10 20 10 20 5 Q25 0 30 5 A5 5 0 0 1 35 10 z');+ expect(parsed.length).toBeGreaterThan(5);+ expect(parsed[0].command).toBe('M');+ expect(parsed[parsed.length - 1].command).toBe('z');+ expect(parsed.some((item) => item.command === 'A')).toBe(true);++ expect(Path.parsePathData('')).toEqual([]);+ expect(Path.calcLength(0, 0, 'L', [3, 4])).toBe(5);+ expect(Path.calcLength(0, 0, 'Q', [5, 5, 10, 0])).toBeGreaterThan(0);+ expect(Path.calcLength(0, 0, 'C', [3, 3, 7, 3, 10, 0])).toBeGreaterThan(0);+ expect(Path.calcLength(0, 0, 'A', [5, 5, 3, 3, 0, Math.PI / 2, 0, 0])).toBeGreaterThan(0);+ expect(Path.calcLength(0, 0, 'X', [])).toBe(0);++ const lowerParsed = Path.parsePathData('m1 1 h2 v3 c1 1 2 2 3 3 s1 1 2 0 q1 1 2 2 t1 1 z m2 2 l3 0');+ expect(lowerParsed.some((item) => item.command === 'C')).toBe(true);+ expect(lowerParsed.some((item) => item.command === 'Q')).toBe(true);+ expect(lowerParsed[lowerParsed.length - 1].command).toBe('L');+ });++ it('supports point calculation helpers', () => {+ expect(Path.getLineLength(0, 0, 3, 4)).toBe(5);++ const linePoint = Path.getPointOnLine(5, 0, 0, 10, 0);+ expect(linePoint.x).toBeCloseTo(5);+ expect(linePoint.y).toBeCloseTo(0);++ const cubicPoint = Path.getPointOnCubicBezier(0.5, 0, 0, 3, 6, 7, 6, 10, 0);+ expect(cubicPoint.x).toBeGreaterThan(0);+ expect(cubicPoint.y).toBeGreaterThan(0);++ const quadPoint = Path.getPointOnQuadraticBezier(0.5, 0, 0, 5, 10, 10, 0);+ expect(quadPoint.x).toBeCloseTo(5);+ expect(quadPoint.y).toBeCloseTo(5);++ const arcPoint = Path.getPointOnEllipticalArc(10, 20, 5, 3, Math.PI / 2, 0);+ expect(arcPoint.x).toBeCloseTo(10);+ expect(arcPoint.y).toBeCloseTo(23);++ const verticalLinePoint = Path.getPointOnLine(2, 0, 0, 0, 10);+ expect(verticalLinePoint.x).toBe(0);++ const sameSlopePoint = Path.getPointOnLine(3, 0, 0, 10, 10, 2, 2);+ expect(sameSlopePoint.x).toBeGreaterThan(2);+ expect(sameSlopePoint.y).toBeGreaterThan(2);++ const projectionPoint = Path.getPointOnLine(6, 0, 0, 10, 0, 2, 5);+ expect(Number.isFinite(projectionPoint.x)).toBe(true);+ expect(Number.isFinite(projectionPoint.y)).toBe(true);++ const reversePoint = Path.getPointOnLine(4, 10, 0, 0, 0, 8, 2);+ expect(Number.isFinite(reversePoint.x)).toBe(true);+ expect(Number.isFinite(reversePoint.y)).toBe(true);+ });++ it('converts arc endpoint parameterization and handles edge cases', () => {+ const arc = Path.convertEndpointToCenterParameterization(0, 0, 10, 10, 0, 1, 4, 4, 45);+ expect(arc).toHaveLength(8);+ expect(arc[2]).toBeGreaterThan(0);+ expect(arc[3]).toBeGreaterThan(0);++ const fallbackArc = Path.convertEndpointToCenterParameterization(1, 1, 1, 1, 0, 0, 0, 0, 0);+ expect(fallbackArc).toHaveLength(8);+ });++ it('supports instance APIs: pointAtLength/state/json/rect', () => {+ const path = new Path('p1', { data: 'M0 0 L10 0 L10 10' } as any);+ expect(path.getLength()).toBeGreaterThan(0);++ const startPoint = path.getPointAtLength(0);+ expect(startPoint).toEqual({ x: 0, y: 0 });++ const midPoint = path.getPointAtLength(5);+ expect(midPoint?.x).toBeCloseTo(5);+ expect(midPoint?.y).toBeCloseTo(0);++ const endPoint = path.getPointAtLength(999);+ expect(endPoint).toEqual({ x: 10, y: 10 });++ const state = path.getState();+ expect(state).toEqual(expect.objectContaining({+ left: expect.any(Number),+ top: expect.any(Number),+ width: expect.any(Number),+ height: expect.any(Number),+ }));++ const json = path.toJson();+ expect(json).toEqual(expect.objectContaining({+ dataArray: expect.any(Array),+ }));++ const rect = path.getRect();+ expect(rect.width).toBeGreaterThanOrEqual(0);+ expect(rect.height).toBeGreaterThanOrEqual(0);+ });++ it('covers drawWith and parse shorthand command branches', () => {+ const ctx = {+ beginPath: vi.fn(),+ lineTo: vi.fn(),+ moveTo: vi.fn(),+ bezierCurveTo: vi.fn(),+ quadraticCurveTo: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ scale: vi.fn(),+ arc: vi.fn(),+ closePath: vi.fn(),+ save: vi.fn(),+ restore: vi.fn(),+ fill: vi.fn(),+ stroke: vi.fn(),+ setLineDash: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ lineDashOffset: 0,+ lineJoin: 'round',+ lineCap: 'round',+ miterLimit: 10,+ fillStyle: '',+ strokeStyle: '',+ } as any;++ Path.drawWith(ctx, {+ dataArray: [+ { command: 'M', points: [0, 0], start: { x: 0, y: 0 }, pathLength: 0 },+ { command: 'L', points: [5, 5], start: { x: 0, y: 0 }, pathLength: 1 },+ { command: 'C', points: [5, 0, 10, 5, 15, 0], start: { x: 5, y: 5 }, pathLength: 1 },+ { command: 'Q', points: [16, 2, 18, 0], start: { x: 15, y: 0 }, pathLength: 1 },+ { command: 'A', points: [18, 0, 3, 2, 0, Math.PI / 2, 0, 0], start: { x: 18, y: 0 }, pathLength: 1 },+ { command: 'z', points: [], start: { x: 0, y: 0 }, pathLength: 0 },+ ],+ fill: '#f00',+ stroke: '#0f0',+ strokeWidth: 1,+ paintFirst: 'stroke',+ } as any);++ expect(ctx.moveTo).toHaveBeenCalled();+ expect(ctx.lineTo).toHaveBeenCalled();+ expect(ctx.bezierCurveTo).toHaveBeenCalled();+ expect(ctx.quadraticCurveTo).toHaveBeenCalled();+ expect(ctx.arc).toHaveBeenCalled();+ expect(ctx.closePath).toHaveBeenCalled();+ expect(ctx.fill).toHaveBeenCalled();+ expect(ctx.stroke).toHaveBeenCalled();++ const parsed = Path.parsePathData('M0 0 C10 0 10 10 20 10 S30 20 40 10 Q45 5 50 10 T60 10 m5 5 l5 0 z');+ expect(parsed.some((cmd) => cmd.command === 'C')).toBe(true);+ expect(parsed.some((cmd) => cmd.command === 'Q')).toBe(true);+ expect(parsed[parsed.length - 1].command).toBe('z');++ const parsedArc = Path.parsePathData('M0 0 a10 5 0 0 1 20 0');+ expect(parsedArc.some((cmd) => cmd.command === 'A')).toBe(true);+ });++ it('covers getPointAtLength fallback branches', () => {+ const noPathPoint = (Path.prototype as any).getPointAtLength.call({ dataArray: [] }, 1);+ expect(noPathPoint).toBeNull();++ const unknownPoint = (Path.prototype as any).getPointAtLength.call({+ dataArray: [{+ command: 'M',+ points: [0, 0],+ start: { x: 0, y: 0 },+ pathLength: 10,+ }],+ }, 5);+ expect(unknownPoint).toBeNull();+ });++ it('covers constructor dataArray path, resize re-calc and protected draw', () => {+ const fromArray = new Path('pa', {+ dataArray: [+ { command: 'M', points: [0, 0], start: { x: 0, y: 0 }, pathLength: 0 },+ { command: 'L', points: [10, 0], start: { x: 0, y: 0 }, pathLength: 10 },+ { command: 'L', points: [10, 10], start: { x: 10, y: 0 }, pathLength: 10 },+ ],+ } as any);+ expect(fromArray.getLength()).toBe(20);+ fromArray.resize(20, 10);+ expect(fromArray.scaleX).toBeGreaterThanOrEqual(0);+ expect(fromArray.scaleY).toBeGreaterThanOrEqual(0);++ const vertical = new Path('pv', { data: 'M0 0 L0 10' } as any);+ vertical.resize(10, 20);+ const horizontal = new Path('ph', { data: 'M0 0 L10 0' } as any);+ horizontal.resize(20, 10);+ expect(vertical.getRect().height).toBeGreaterThanOrEqual(0);+ expect(horizontal.getRect().width).toBeGreaterThanOrEqual(0);++ (fromArray as any)._reCalculateCache = false;+ (fromArray as any)._selfRectCache = { left: 1, top: 2, width: 3, height: 4 };+ expect((fromArray as any)._getSelfRect()).toEqual({ left: 1, top: 2, width: 3, height: 4 });++ const arcCurve = new Path('pc', { data: 'M0 0 C10 0 10 10 20 10 A5 5 0 0 0 30 10' } as any);+ const rect = arcCurve.getRect();+ expect(rect.width).toBeGreaterThanOrEqual(0);+ expect(rect.height).toBeGreaterThanOrEqual(0);++ const ctx = {+ beginPath: vi.fn(),+ lineTo: vi.fn(),+ moveTo: vi.fn(),+ bezierCurveTo: vi.fn(),+ quadraticCurveTo: vi.fn(),+ translate: vi.fn(),+ rotate: vi.fn(),+ scale: vi.fn(),+ arc: vi.fn(),+ closePath: vi.fn(),+ save: vi.fn(),+ restore: vi.fn(),+ fill: vi.fn(),+ stroke: vi.fn(),+ setLineDash: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ lineDashOffset: 0,+ lineJoin: 'round',+ lineCap: 'round',+ miterLimit: 10,+ fillStyle: '',+ strokeStyle: '',+ } as any;+ (arcCurve as any)._draw(ctx);+ expect(ctx.beginPath).toHaveBeenCalled();+ });+});diff --git a/packages/engine-render/src/shape/__tests__/regular-polygon.spec.ts b/packages/engine-render/src/shape/__tests__/regular-polygon.spec.tsnew file mode 100644index 0000000000..790cadd892--- /dev/null+++ b/packages/engine-render/src/shape/__tests__/regular-polygon.spec.ts@@ -0,0 +1,122 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { Vector2 } from '../../basics/vector2';+import { RegularPolygon } from '../regular-polygon';++function createCtx() {+ return {+ beginPath: vi.fn(),+ setLineDash: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ closePath: vi.fn(),+ save: vi.fn(),+ restore: vi.fn(),+ fill: vi.fn(),+ stroke: vi.fn(),+ lineWidth: 1,+ lineCap: 'round',+ lineJoin: 'round',+ lineDashOffset: 0,+ miterLimit: 10,+ fillStyle: '#fff',+ strokeStyle: '#000',+ } as any;+}++describe('regular polygon extra', () => {+ it('draws and serializes polygon state', () => {+ const polygon = new RegularPolygon('p1', {+ left: 10,+ top: 20,+ fill: '#00ff00',+ stroke: '#333',+ strokeWidth: 1,+ strokeDashArray: [2, 2],+ pointsGroup: [[+ { x: 10, y: 10 },+ { x: 110, y: 10 },+ { x: 110, y: 80 },+ { x: 10, y: 80 },+ ]],+ });++ const ctx = createCtx();+ RegularPolygon.drawWith(ctx, polygon);+ expect(ctx.beginPath).toHaveBeenCalled();+ expect(ctx.setLineDash).toHaveBeenCalledWith([2, 2]);+ expect(ctx.moveTo).toHaveBeenCalled();+ expect(ctx.lineTo).toHaveBeenCalled();++ const json = polygon.toJson();+ expect(json).toMatchObject({+ left: expect.any(Number),+ top: expect.any(Number),+ width: expect.any(Number),+ height: expect.any(Number),+ });+ });++ it('updates points, hit checks and resize behavior', () => {+ const polygon = new RegularPolygon('p2', {+ pointsGroup: [+ [+ { x: 0, y: 0 },+ { x: 120, y: 0 },+ { x: 120, y: 120 },+ { x: 0, y: 120 },+ ],+ [+ { x: 40, y: 40 },+ { x: 80, y: 40 },+ { x: 80, y: 80 },+ { x: 40, y: 80 },+ ],+ ],+ });++ polygon.transformByState({+ left: 20,+ top: 30,+ scaleX: 1,+ scaleY: 1,+ });++ expect(polygon.isHit(Vector2.FromArray([30, 40]))).toBe(true);+ expect(polygon.isHit(Vector2.FromArray([85, 90]))).toBe(false); // hole+ expect(polygon.isHit(Vector2.FromArray([200, 200]))).toBe(false);++ const preState = polygon.getState();+ polygon.resizePolygon({+ width: preState.width! - 20,+ height: preState.height! - 20,+ } as any);+ expect(polygon.scaleX).not.toBe(1);+ expect(polygon.scaleY).not.toBe(1);++ polygon.updatePointGroup([[+ { x: -10, y: -10 },+ { x: 20, y: -10 },+ { x: 20, y: 20 },+ { x: -10, y: 20 },+ ]]);+ const rect = polygon.getRect();+ expect(rect.width).toBeGreaterThan(0);+ expect(rect.height).toBeGreaterThan(0);+ });+});diff --git a/packages/engine-render/src/shape/__tests__/rich-text.spec.ts b/packages/engine-render/src/shape/__tests__/rich-text.spec.tsnew file mode 100644index 0000000000..086a6a5027--- /dev/null+++ b/packages/engine-render/src/shape/__tests__/rich-text.spec.ts@@ -0,0 +1,184 @@+/**+ * 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 { BooleanNumber } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';++import { RichText } from '../rich-text';++const h = vi.hoisted(() => ({+ documentSkeletonCreateMock: vi.fn(),+ documentViewModelCtorMock: vi.fn(),+ documentsCtorMock: vi.fn(),+ documentsRenderMock: vi.fn(),+ updatePageSizeMock: vi.fn(),+ makeDirtyMock: vi.fn(),+ calculateMock: vi.fn(),+ skeletonData: {+ pages: [+ { width: 120, height: 40 },+ ],+ } as any,+}));++vi.mock('../../components/docs/view-model/document-view-model', () => ({+ DocumentViewModel: class {+ constructor(model: any) {+ h.documentViewModelCtorMock(model);+ }+ },+}));++vi.mock('../../components/docs/layout/doc-skeleton', () => ({+ DocumentSkeleton: {+ create: (viewModel: any, localeService: any) => {+ h.documentSkeletonCreateMock(viewModel, localeService);+ return {+ getViewModel: () => ({+ getDataModel: () => ({+ updateDocumentDataPageSize: (...args: any[]) => h.updatePageSizeMock(...args),+ }),+ }),+ getSkeletonData: () => h.skeletonData,+ makeDirty: (...args: any[]) => h.makeDirtyMock(...args),+ calculate: (...args: any[]) => h.calculateMock(...args),+ };+ },+ },+}));++vi.mock('../../components/docs/document', () => ({+ Documents: class {+ constructor(key: string, skeleton: any, config: any) {+ h.documentsCtorMock(key, skeleton, config);+ }++ render(ctx: any) {+ h.documentsRenderMock(ctx);+ }+ },+}));++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ transform: vi.fn(),+ } as any;+}++describe('rich text shape', () => {+ it('builds document data from plain text and exposes getters/json', () => {+ h.skeletonData = { pages: [{ width: 120, height: 40 }] } as any;+ const rich = new RichText({} as any, 'rt-1', {+ text: 'hello',+ fs: 14,+ ff: 'Arial',+ it: BooleanNumber.FALSE,+ bl: BooleanNumber.TRUE,+ zIndex: 2,+ left: 0,+ top: 0,+ width: 120,+ height: 40,+ } as any);++ expect(rich.fs).toBe(14);+ expect(rich.text).toContain('hello');+ expect(rich.documentData.body?.dataStream).toContain('hello');+ expect(h.documentSkeletonCreateMock).toHaveBeenCalled();+ expect(h.documentsCtorMock).toHaveBeenCalled();+ expect(rich.getDocsSkeletonPageSize()).toEqual({ width: 120, height: 40 });++ rich.setProps({ left: 10, top: 20, zIndex: 9, fs: 99, text: 'ignore' } as any);+ expect((rich as any)._left).toBe(10);+ expect(rich.fs).toBe(14);++ const json = rich.toJson();+ expect(json).toEqual(expect.objectContaining({+ fs: 14,+ text: expect.any(String),+ }));+ });++ it('covers render branches and draw delegation', () => {+ const rich = new RichText({} as any, 'rt-2', {+ text: 'abc',+ fs: 12,+ zIndex: 1,+ width: 100,+ height: 30,+ } as any);+ const ctx = createCtx();++ const makeDirtySpy = vi.spyOn(rich, 'makeDirty');+ (rich as any)._visible = false;+ rich.render(ctx);+ expect(makeDirtySpy).toHaveBeenCalledWith(false);++ (rich as any)._visible = true;+ vi.spyOn(rich, 'isRender').mockReturnValue(true);+ (rich as any)._strokeWidth = 1;+ (rich as any).width = 10;+ (rich as any).height = 10;+ rich.render(ctx, {+ viewBound: {+ left: 100,+ right: 200,+ top: 100,+ bottom: 200,+ },+ } as any);+ expect(h.documentsRenderMock).not.toHaveBeenCalled();++ (rich.isRender as any).mockReturnValue(false);+ rich.render(ctx);+ expect(ctx.save).toHaveBeenCalled();+ expect(ctx.transform).toHaveBeenCalled();+ expect(ctx.restore).toHaveBeenCalled();+ expect(h.documentsRenderMock).toHaveBeenCalled();+ });++ it('refreshes skeleton/documents and resizes to content', () => {+ const rich = new RichText({} as any, 'rt-3', {+ text: 'refresh',+ fs: 12,+ zIndex: 1,+ width: 80,+ height: 20,+ } as any);++ const transformSpy = vi.spyOn(rich, 'transformByState');+ const createCountBefore = h.documentSkeletonCreateMock.mock.calls.length;++ rich.refreshDocumentByDocData();+ expect(h.documentSkeletonCreateMock.mock.calls.length).toBeGreaterThan(createCountBefore);+ expect(h.updatePageSizeMock).toHaveBeenCalled();+ expect(h.calculateMock).toHaveBeenCalled();++ h.skeletonData = { pages: [{ width: 80, height: 66 }] } as any;+ rich.resizeToContentSize();+ expect(transformSpy).toHaveBeenCalledWith(expect.objectContaining({ height: 66 }));++ h.skeletonData = { pages: [{ width: 0, height: 0 }] } as any;+ const callCount = transformSpy.mock.calls.length;+ rich.resizeToContentSize();+ expect(transformSpy.mock.calls.length).toBe(callCount);++ (rich as any)._documentSkeleton = { getSkeletonData: () => null };+ expect(rich.getDocsSkeletonPageSize()).toBeUndefined();+ });+});diff --git a/packages/engine-render/src/shape/__tests__/text.spec.ts b/packages/engine-render/src/shape/__tests__/text.spec.tsnew file mode 100644index 0000000000..12d3c53b84--- /dev/null+++ b/packages/engine-render/src/shape/__tests__/text.spec.ts@@ -0,0 +1,165 @@+/**+ * 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 { CellValueType, HorizontalAlign, TextDecoration, VerticalAlign } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { Text, TEXT_OBJECT_ARRAY } from '../text';++function createCtx() {+ return {+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ stroke: vi.fn(),+ fillText: vi.fn(),+ setLineDash: vi.fn(),+ font: '',+ fillStyle: '',+ strokeStyle: '',+ lineWidth: 1,+ } as any;+}++function createSkeleton(lines: Array<{ text: string; width: number; height: number; baseline: number }>) {+ const totalHeight = lines.reduce((sum, item) => sum + item.height, 0);+ return {+ calculate: vi.fn(() => lines),+ getTotalHeight: vi.fn(() => totalHeight),+ } as any;+}++describe('text shape', () => {+ it('contains expected serialized keys and draws center/right alignment', () => {+ expect(TEXT_OBJECT_ARRAY).toEqual(expect.arrayContaining(['text', 'fontStyle', 'hAlign', 'vAlign']));++ const ctx = createCtx();+ const skeleton = createSkeleton([{ text: 'abcd', width: 20, height: 10, baseline: 8 }]);++ Text.drawWith(+ ctx,+ {+ text: 'abcd',+ fontStyle: '12px Arial',+ width: 100,+ height: 30,+ hAlign: HorizontalAlign.CENTER,+ vAlign: VerticalAlign.TOP,+ } as any,+ skeleton+ );+ expect(ctx.fillText).toHaveBeenCalledWith('abcd', 40, 8);++ Text.drawWith(+ ctx,+ {+ text: 'abcd',+ fontStyle: '12px Arial',+ width: 100,+ height: 30,+ hAlign: HorizontalAlign.RIGHT,+ vAlign: VerticalAlign.TOP,+ } as any,+ skeleton+ );+ expect(ctx.fillText).toHaveBeenLastCalledWith('abcd', 80, 8);+ });++ it('keeps number left-aligned when overflow in no-wrap mode', () => {+ const ctx = createCtx();+ const skeleton = createSkeleton([{ text: '123456', width: 60, height: 10, baseline: 8 }]);++ Text.drawWith(+ ctx,+ {+ text: '123456',+ fontStyle: '12px Arial',+ width: 20,+ height: 20,+ warp: false,+ hAlign: HorizontalAlign.RIGHT,+ vAlign: VerticalAlign.TOP,+ cellValueType: CellValueType.NUMBER,+ } as any,+ skeleton+ );++ expect(ctx.fillText).toHaveBeenCalledWith('123456', 0, 8);+ });++ it('draws underline and strike line decorations', () => {+ const ctx = createCtx();+ const skeleton = createSkeleton([{ text: 'abc', width: 6, height: 10, baseline: 8 }]);++ Text.drawWith(+ ctx,+ {+ text: 'abc',+ fontStyle: '12px Arial',+ width: 20,+ height: 20,+ hAlign: HorizontalAlign.LEFT,+ vAlign: VerticalAlign.TOP,+ underline: true,+ underlineType: TextDecoration.WAVY_DOUBLE,+ strokeLine: true,+ color: '#f00',+ } as any,+ skeleton+ );++ expect(ctx.beginPath).toHaveBeenCalled();+ expect(ctx.stroke).toHaveBeenCalled();+ expect(ctx.lineTo.mock.calls.length).toBeGreaterThan(3);+ });++ it('covers line type setup and line drawing helpers', () => {+ const ctx = createCtx();+ const setLineType = (Text as any)._setLineType.bind(Text);++ setLineType(ctx, TextDecoration.SINGLE, 7);+ expect(ctx.lineWidth).toBe(1);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([0]);++ setLineType(ctx, TextDecoration.DOTTED_HEAVY, 7);+ expect(ctx.lineWidth).toBe(2);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([2]);++ setLineType(ctx, TextDecoration.DASH_LONG, 7);+ expect(ctx.lineWidth).toBe(1);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([6]);++ setLineType(ctx, TextDecoration.DASH_DOT_DOT_HEAVY, 7);+ expect(ctx.lineWidth).toBe(2);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([2, 2, 5, 2, 2]);++ setLineType(ctx, TextDecoration.WAVY_HEAVY, 7);+ expect(ctx.lineWidth).toBe(2);++ setLineType(ctx, 999 as TextDecoration, 7);+ expect(ctx.lineWidth).toBe(7);+ expect(ctx.setLineDash).toHaveBeenLastCalledWith([0]);++ const drawLine = (Text as any)._drawLine.bind(Text);+ drawLine(ctx, 2, 3, 4, TextDecoration.SINGLE);+ expect(ctx.lineTo).toHaveBeenLastCalledWith(6, 3);++ const beforeWaveCalls = ctx.lineTo.mock.calls.length;+ drawLine(ctx, 1, 5, 3, TextDecoration.WAVE);+ expect(ctx.lineTo.mock.calls.length).toBeGreaterThan(beforeWaveCalls);+ });+});diff --git a/packages/engine-render/vitest.config.ts b/packages/engine-render/vitest.config.tsindex af97c6d7a2..0778a36a56 100644--- a/packages/engine-render/vitest.config.ts+++ b/packages/engine-render/vitest.config.ts@@ -1,3 +1,12 @@+import path from 'node:path';import createConfig from '@univerjs-infra/shared/vitest';-export default createConfig();+export default createConfig({+ test: {+ setupFiles: [+ path.resolve(__dirname, './jest.setup.ts'),+ path.resolve(__dirname, './vitest.setup.ts'),+ ],+ environment: 'jsdom',+ },+});diff --git a/packages/engine-render/vitest.setup.ts b/packages/engine-render/vitest.setup.tsnew file mode 100644index 0000000000..598d07057b--- /dev/null+++ b/packages/engine-render/vitest.setup.ts@@ -0,0 +1,36 @@+/**+ * 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 getCanvasWindow from 'jest-canvas-mock/lib/window';+import { vi } from 'vitest';++const apis = [+ 'Path2D',+ 'CanvasGradient',+ 'CanvasPattern',+ 'CanvasRenderingContext2D',+ 'DOMMatrix',+ 'ImageData',+ 'TextMetrics',+ 'ImageBitmap',+ 'createImageBitmap',+] as const;++const canvasWindow = getCanvasWindow({ document: window.document });++apis.forEach((api) => {+ vi.stubGlobal(api, canvasWindow[api]);+});diff --git a/packages/find-replace/src/__tests__/create-test-bed.ts b/packages/find-replace/src/__tests__/create-test-bed.tsnew file mode 100644index 0000000000..324b8c6e74--- /dev/null+++ b/packages/find-replace/src/__tests__/create-test-bed.ts@@ -0,0 +1,129 @@+/**+ * 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 { Dependency, IWorkbookData, Workbook } from '@univerjs/core';+import type { IMessageProps } from '@univerjs/design';+import type { IMessageService as IUiMessageService } from '@univerjs/ui';+import {+ Disposable,+ IConfirmService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ TestConfirmService,+ Tools,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { IMessageService } from '@univerjs/ui';+import enUS from '../locale/en-US';++import { IFindReplaceService } from '../services/find-replace.service';++const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ cellData: {+ 0: {+ 0: {+ v: 'A1',+ },+ 1: {+ v: 'A2',+ },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+};++class TestMessageService implements IUiMessageService {+ readonly messages: IMessageProps[] = [];++ show(options: IMessageProps): Disposable {+ this.messages.push(options);+ return new Disposable();+ }++ remove(_id: string): void {}++ removeAll(): void {+ this.messages.length = 0;+ }+}++export interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ sheet: Workbook;+}++export function createTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'find-replace-test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.add([IConfirmService, { useClass: TestConfirmService }]);+ this._injector.add([IMessageService, { useClass: TestMessageService }]);+ dependencies?.forEach((d) => this._injector.add(d));+ }+ }++ univer.registerPlugin(TestPlugin);++ const snapshot = Tools.deepClone(workbookData || TEST_WORKBOOK_DATA_DEMO);+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, snapshot);+ const univerInstanceService = injector.get(IUniverInstanceService);+ univerInstanceService.focusUnit(sheet.getUnitId());++ const logService = injector.get(ILogService);+ logService.setLogLevel(LogLevel.SILENT);++ const localeService = injector.get(LocaleService);+ localeService.load({ enUS });++ return {+ univer,+ get: injector.get.bind(injector),+ sheet,+ };+}++export { IFindReplaceService, IMessageService, TestMessageService };diff --git a/packages/find-replace/src/commands/commands/__tests__/replace.command.spec.ts b/packages/find-replace/src/commands/commands/__tests__/replace.command.spec.tsnew file mode 100644index 0000000000..1c8f1d9c12--- /dev/null+++ b/packages/find-replace/src/commands/commands/__tests__/replace.command.spec.ts@@ -0,0 +1,100 @@+/**+ * 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 { Injector, Univer } from '@univerjs/core';+import type { TestMessageService } from '../../../__tests__/create-test-bed';+import { ICommandService, IConfirmService } from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ createTestBed,+ IFindReplaceService,+ IMessageService,+} from '../../../__tests__/create-test-bed';+import { FindReplaceService } from '../../../services/find-replace.service';+import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../replace.command';++describe('replace.command', () => {+ let univer: Univer;+ let get: Injector['get'];++ beforeEach(() => {+ const testBed = createTestBed(undefined, [[IFindReplaceService, { useClass: FindReplaceService }]]);+ univer = testBed.univer;+ get = testBed.get;++ const commandService = get(ICommandService);+ commandService.registerCommand(ReplaceCurrentMatchCommand);+ commandService.registerCommand(ReplaceAllMatchesCommand);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should proxy ReplaceCurrentMatchCommand to findReplaceService.replace', async () => {+ const commandService = get(ICommandService);+ const findReplaceService = get(IFindReplaceService);+ const replaceSpy = vi.spyOn(findReplaceService, 'replace').mockResolvedValue(true);++ await expect(commandService.executeCommand(ReplaceCurrentMatchCommand.id)).resolves.toBe(true);+ expect(replaceSpy).toHaveBeenCalledTimes(1);+ });++ it('should return false when confirm is canceled for replace all', async () => {+ const commandService = get(ICommandService);+ const findReplaceService = get(IFindReplaceService);+ const confirmService = get(IConfirmService);+ const messageService = get(IMessageService) as TestMessageService;++ vi.spyOn(confirmService, 'confirm').mockResolvedValue(false);+ const replaceAllSpy = vi.spyOn(findReplaceService, 'replaceAll');++ await expect(commandService.executeCommand(ReplaceAllMatchesCommand.id)).resolves.toBe(false);+ expect(replaceAllSpy).not.toHaveBeenCalled();+ expect(messageService.messages).toHaveLength(0);+ });++ it('should show success message when all replacements succeed', async () => {+ const commandService = get(ICommandService);+ const findReplaceService = get(IFindReplaceService);+ const messageService = get(IMessageService) as TestMessageService;+ vi.spyOn(findReplaceService, 'replaceAll').mockResolvedValue({ success: 3, failure: 0 });++ await expect(commandService.executeCommand(ReplaceAllMatchesCommand.id)).resolves.toBe(true);+ expect(messageService.messages[0]).toEqual(expect.objectContaining({ type: MessageType.Success }));+ });++ it('should show warning when partially succeeds and return false', async () => {+ const commandService = get(ICommandService);+ const findReplaceService = get(IFindReplaceService);+ const messageService = get(IMessageService) as TestMessageService;+ vi.spyOn(findReplaceService, 'replaceAll').mockResolvedValue({ success: 2, failure: 1 });++ await expect(commandService.executeCommand(ReplaceAllMatchesCommand.id)).resolves.toBe(false);+ expect(messageService.messages[0]).toEqual(expect.objectContaining({ type: MessageType.Warning }));+ });++ it('should show error when all replacements fail and return false', async () => {+ const commandService = get(ICommandService);+ const findReplaceService = get(IFindReplaceService);+ const messageService = get(IMessageService) as TestMessageService;+ vi.spyOn(findReplaceService, 'replaceAll').mockResolvedValue({ success: 0, failure: 2 });++ await expect(commandService.executeCommand(ReplaceAllMatchesCommand.id)).resolves.toBe(false);+ expect(messageService.messages[0]).toEqual(expect.objectContaining({ type: MessageType.Error }));+ });+});diff --git a/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.ts b/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.tsnew file mode 100644index 0000000000..4b1a7a1cf0--- /dev/null+++ b/packages/find-replace/src/commands/operations/__tests__/find-replace.operation.spec.ts@@ -0,0 +1,119 @@+/**+ * 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 { Injector, Univer } from '@univerjs/core';+import type { IFindReplaceProvider } from '../../../services/find-replace.service';+import { ICommandService } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createTestBed, IFindReplaceService } from '../../../__tests__/create-test-bed';+import { FindReplaceService } from '../../../services/find-replace.service';+import {+ FocusSelectionOperation,+ GoToNextMatchOperation,+ GoToPreviousMatchOperation,+ OpenFindDialogOperation,+ OpenReplaceDialogOperation,+} from '../find-replace.operation';++function createProvider(): IFindReplaceProvider {+ return {+ find: vi.fn(async () => []),+ terminate: vi.fn(),+ };+}++describe('find-replace.operation', () => {+ let univer: Univer;+ let get: Injector['get'];++ beforeEach(() => {+ const testBed = createTestBed(undefined, [[IFindReplaceService, { useClass: FindReplaceService }]]);+ univer = testBed.univer;+ get = testBed.get;++ const commandService = get(ICommandService);+ [+ OpenFindDialogOperation,+ OpenReplaceDialogOperation,+ GoToNextMatchOperation,+ GoToPreviousMatchOperation,+ FocusSelectionOperation,+ ].forEach((op) => commandService.registerCommand(op));+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should open find dialog or focus input based on reveal state', () => {+ const commandService = get(ICommandService);+ const findReplaceService = get(IFindReplaceService);+ findReplaceService.registerFindReplaceProvider(createProvider());++ const startSpy = vi.spyOn(findReplaceService, 'start');+ const focusSpy = vi.spyOn(findReplaceService, 'focusFindInput');++ expect(commandService.syncExecuteCommand(OpenFindDialogOperation.id)).toBe(true);+ expect(startSpy).toHaveBeenCalledTimes(1);+ expect(focusSpy).not.toHaveBeenCalled();++ expect(commandService.syncExecuteCommand(OpenFindDialogOperation.id)).toBe(true);+ expect(focusSpy).toHaveBeenCalledTimes(1);+ });++ it('should open replace dialog with proper branching', () => {+ const commandService = get(ICommandService);++ const hiddenService = get(IFindReplaceService);+ hiddenService.registerFindReplaceProvider(createProvider());+ const hiddenStartSpy = vi.spyOn(hiddenService, 'start');+ expect(commandService.syncExecuteCommand(OpenReplaceDialogOperation.id)).toBe(true);+ expect(hiddenStartSpy).toHaveBeenCalledWith(true);+ hiddenService.terminate();++ const revealService = get(IFindReplaceService);+ revealService.registerFindReplaceProvider(createProvider());+ revealService.start();+ const revealSpy = vi.spyOn(revealService, 'revealReplace');+ expect(commandService.syncExecuteCommand(OpenReplaceDialogOperation.id)).toBe(true);+ expect(revealSpy).toHaveBeenCalledTimes(1);+ revealService.terminate();++ const focusService = get(IFindReplaceService);+ focusService.registerFindReplaceProvider(createProvider());+ focusService.start(true);+ const focusSpy = vi.spyOn(focusService, 'focusFindInput');+ expect(commandService.syncExecuteCommand(OpenReplaceDialogOperation.id)).toBe(true);+ expect(focusSpy).toHaveBeenCalledTimes(1);+ });++ it('should route next/previous/focus operations to the service', () => {+ const commandService = get(ICommandService);+ const service = get(IFindReplaceService);++ const nextSpy = vi.spyOn(service, 'moveToNextMatch');+ const previousSpy = vi.spyOn(service, 'moveToPreviousMatch');+ const focusSpy = vi.spyOn(service, 'focusSelection');++ expect(commandService.syncExecuteCommand(GoToNextMatchOperation.id)).toBe(true);+ expect(commandService.syncExecuteCommand(GoToPreviousMatchOperation.id)).toBe(true);+ expect(commandService.syncExecuteCommand(FocusSelectionOperation.id)).toBe(true);++ expect(nextSpy).toHaveBeenCalledTimes(1);+ expect(previousSpy).toHaveBeenCalledTimes(1);+ expect(focusSpy).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/find-replace/src/controllers/__tests__/find-replace.menu.spec.ts b/packages/find-replace/src/controllers/__tests__/find-replace.menu.spec.tsnew file mode 100644index 0000000000..69db3bbb4a--- /dev/null+++ b/packages/find-replace/src/controllers/__tests__/find-replace.menu.spec.ts@@ -0,0 +1,68 @@+/**+ * 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 { Injector, Univer } from '@univerjs/core';+import { EDITOR_ACTIVATED, FOCUSING_SHEET, IContextService } from '@univerjs/core';+import { RibbonDataGroup } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createTestBed } from '../../__tests__/create-test-bed';+import { OpenFindDialogOperation } from '../../commands/operations/find-replace.operation';+import { FindReplaceMenuItemFactory } from '../find-replace.menu';+import { menuSchema } from '../menu.schema';++describe('find-replace.menu', () => {+ let univer: Univer;+ let get: Injector['get'];++ beforeEach(() => {+ const testBed = createTestBed();+ univer = testBed.univer;+ get = testBed.get;+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should build menu item and compute disabled state from context values', () => {+ const contextService = get(IContextService);+ contextService.setContextValue(EDITOR_ACTIVATED, false);+ contextService.setContextValue(FOCUSING_SHEET, true);++ const menuItem = FindReplaceMenuItemFactory({ get } as never);+ const states: boolean[] = [];+ const sub = menuItem.disabled$!.subscribe((value) => states.push(value));++ contextService.setContextValue(EDITOR_ACTIVATED, true);+ contextService.setContextValue(FOCUSING_SHEET, false);+ sub.unsubscribe();++ expect(menuItem.id).toBe(OpenFindDialogOperation.id);+ expect(menuItem.tooltip).toBe('find-replace.toolbar');+ expect(states[0]).toBe(false);+ expect(states).toContain(true);+ });++ it('should expose toolbar schema entry for open-find operation', () => {+ const schema = menuSchema as Record<string, Record<string, unknown>>;+ expect(schema[RibbonDataGroup.ORGANIZATION][OpenFindDialogOperation.id]).toEqual(+ expect.objectContaining({+ order: 2,+ menuItemFactory: FindReplaceMenuItemFactory,+ })+ );+ });+});diff --git a/packages/find-replace/src/controllers/__tests__/find-replace.shortcut.spec.ts b/packages/find-replace/src/controllers/__tests__/find-replace.shortcut.spec.tsnew file mode 100644index 0000000000..ee999a34c3--- /dev/null+++ b/packages/find-replace/src/controllers/__tests__/find-replace.shortcut.spec.ts@@ -0,0 +1,91 @@+/**+ * 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 { Injector, Univer } from '@univerjs/core';+import { EDITOR_ACTIVATED, FOCUSING_SHEET, IContextService } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createTestBed } from '../../__tests__/create-test-bed';+import {+ FIND_REPLACE_DIALOG_FOCUS,+ FIND_REPLACE_INPUT_FOCUS,+ FIND_REPLACE_REPLACE_REVEALED,+} from '../../services/context-keys';+import {+ FocusSelectionShortcutItem,+ GoToNextFindMatchShortcutItem,+ GoToPreviousFindMatchShortcutItem,+ MacOpenFindDialogShortcutItem,+ OpenFindDialogShortcutItem,+ OpenReplaceDialogShortcutItem,+} from '../find-replace.shortcut';++describe('find-replace.shortcut', () => {+ let univer: Univer;+ let get: Injector['get'];+ let contextService: IContextService;++ beforeEach(() => {+ const testBed = createTestBed();+ univer = testBed.univer;+ get = testBed.get;+ contextService = get(IContextService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should require sheet focus and editor inactivity for opening find dialog', () => {+ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, false);+ contextService.setContextValue(FOCUSING_SHEET, true);+ contextService.setContextValue(EDITOR_ACTIVATED, false);++ expect(OpenFindDialogShortcutItem.preconditions!(contextService)).toBe(true);+ expect(MacOpenFindDialogShortcutItem.preconditions!(contextService)).toBe(true);++ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, true);+ expect(OpenFindDialogShortcutItem.preconditions!(contextService)).toBe(false);+ });++ it('should open replace dialog only when dialog is hidden or replace is not revealed', () => {+ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, false);+ contextService.setContextValue(FIND_REPLACE_REPLACE_REVEALED, false);+ contextService.setContextValue(FOCUSING_SHEET, true);+ contextService.setContextValue(EDITOR_ACTIVATED, false);+ expect(OpenReplaceDialogShortcutItem.preconditions!(contextService)).toBe(true);++ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, true);+ contextService.setContextValue(FIND_REPLACE_REPLACE_REVEALED, true);+ expect(OpenReplaceDialogShortcutItem.preconditions!(contextService)).toBe(false);+ });++ it('should require input and dialog focus for next/previous actions', () => {+ contextService.setContextValue(FIND_REPLACE_INPUT_FOCUS, true);+ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, true);+ expect(GoToNextFindMatchShortcutItem.preconditions!(contextService)).toBe(true);+ expect(GoToPreviousFindMatchShortcutItem.preconditions!(contextService)).toBe(true);++ contextService.setContextValue(FIND_REPLACE_INPUT_FOCUS, false);+ expect(GoToNextFindMatchShortcutItem.preconditions!(contextService)).toBe(false);+ });++ it('should focus selection when dialog is focused', () => {+ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, true);+ expect(FocusSelectionShortcutItem.preconditions!(contextService)).toBe(true);+ contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, false);+ expect(FocusSelectionShortcutItem.preconditions!(contextService)).toBe(false);+ });+});diff --git a/packages/network/src/services/http/__testing__/http-testing-utils.ts b/packages/network/src/services/http/__testing__/http-testing-utils.tsindex 38817129ad..06121f8377 100644--- a/packages/network/src/services/http/__testing__/http-testing-utils.ts+++ b/packages/network/src/services/http/__testing__/http-testing-utils.ts@@ -19,7 +19,7 @@import type { Observer } from 'rxjs';import type { HTTPRequest } from '../request';-import type { HTTPEvent, HTTPResponse, HTTPResponseError } from '../response';+import type { HTTPEvent, HTTPResponseError } from '../response';import { Disposable, Injector } from '@univerjs/core';import { Observable, Subject } from 'rxjs';import { HTTPService } from '../http.service';@@ -82,7 +82,7 @@ export interface IMockHTTPHandler {/*** Emit a response event to the observer.*/- emitResponse<T>(response: HTTPResponse<T>): void;+ emitResponse<T>(response: HTTPEvent<T>): void;/*** Emit an error event to the observer.diff --git a/packages/network/src/services/http/__testing__/http.service.spec.ts b/packages/network/src/services/http/__testing__/http.service.spec.tsnew file mode 100644index 0000000000..5e7a30016b--- /dev/null+++ b/packages/network/src/services/http/__testing__/http.service.spec.ts@@ -0,0 +1,145 @@+/**+ * 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 { Injector } from '@univerjs/core';+import type { MockHTTPImplementation } from './http-testing-utils';+import { firstValueFrom } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { HTTPHeaders } from '../headers';+import { HTTPService } from '../http.service';+import { IHTTPImplementation } from '../implementations/implementation';+import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION } from '../request';+import { HTTPProgress, HTTPResponse } from '../response';+import { createHTTPTestBed } from './http-testing-utils';++describe('test "HTTPService"', () => {+ let httpService: HTTPService;+ let httpImplementation: MockHTTPImplementation;+ let injector: Injector;++ beforeEach(() => {+ injector = createHTTPTestBed().injector;+ httpService = injector.get(HTTPService);+ httpImplementation = injector.get(IHTTPImplementation) as MockHTTPImplementation;+ });++ afterEach(() => {+ injector.dispose();+ __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION();+ });++ it('runs interceptors in ascending priority order under the current implementation', async () => {+ const callOrder: string[] = [];++ httpService.registerHTTPInterceptor({+ priority: 10,+ interceptor: (request, next) => {+ callOrder.push('priority-10:request');+ request.headers.set('X-Chain', 'first');+ return next(request);+ },+ });+ httpService.registerHTTPInterceptor({+ priority: 100,+ interceptor: (request, next) => {+ callOrder.push('priority-100:request');+ request.headers.set('X-Chain', 'second');+ return next(request);+ },+ });++ const sentRequestPromise = firstValueFrom(httpImplementation.newRequest$);+ const request = httpService.get<{ ok: boolean }>('http://example.com');+ const sentRequest = await sentRequestPromise;++ expect(callOrder).toEqual(['priority-10:request', 'priority-100:request']);+ expect(sentRequest.headers.get('x-chain')).toEqual(['first', 'second']);++ httpImplementation.getHandler(sentRequest.uid).emitResponse(new HTTPResponse({+ headers: new HTTPHeaders(),+ status: 200,+ statusText: 'OK',+ body: { ok: true },+ }));++ await expect(request).resolves.toMatchObject({ body: { ok: true } });+ });++ it('rebuilds the request pipe after a new interceptor is registered', async () => {+ const firstInterceptorCalls: string[] = [];+ const secondInterceptorCalls: string[] = [];++ httpService.registerHTTPInterceptor({+ priority: 0,+ interceptor: (request, next) => {+ firstInterceptorCalls.push(request.url);+ return next(request);+ },+ });++ const firstSentRequestPromise = firstValueFrom(httpImplementation.newRequest$);+ const firstRequest = httpService.get<{ step: number }>('http://example.com/first');+ const firstSentRequest = await firstSentRequestPromise;++ httpImplementation.getHandler(firstSentRequest.uid).emitResponse(new HTTPResponse({+ headers: new HTTPHeaders(),+ status: 200,+ statusText: 'OK',+ body: { step: 1 },+ }));++ await expect(firstRequest).resolves.toMatchObject({ body: { step: 1 } });++ httpService.registerHTTPInterceptor({+ priority: 50,+ interceptor: (request, next) => {+ secondInterceptorCalls.push(request.url);+ request.headers.set('X-Second', 'enabled');+ return next(request);+ },+ });++ const secondSentRequestPromise = firstValueFrom(httpImplementation.newRequest$);+ const secondRequest = httpService.get<{ step: number }>('http://example.com/second');+ const secondSentRequest = await secondSentRequestPromise;++ expect(firstInterceptorCalls).toEqual(['http://example.com/first', 'http://example.com/second']);+ expect(secondInterceptorCalls).toEqual(['http://example.com/second']);+ expect(secondSentRequest.headers.get('x-second')).toEqual(['enabled']);++ httpImplementation.getHandler(secondSentRequest.uid).emitResponse(new HTTPResponse({+ headers: new HTTPHeaders(),+ status: 200,+ statusText: 'OK',+ body: { step: 2 },+ }));++ await expect(secondRequest).resolves.toMatchObject({ body: { step: 2 } });+ });++ it('streams progress events before the final response when using getSSE', async () => {+ const sentRequestPromise = firstValueFrom(httpImplementation.newRequest$);+ const eventsPromise = firstValueFrom(httpService.getSSE<string>('GET', 'http://example.com/sse'));+ const sentRequest = await sentRequestPromise;++ expect(sentRequest.responseType).toBe('json');+ expect(sentRequest.requestParams?.reportProgress).toBe(true);++ httpImplementation.getHandler(sentRequest.uid).emitResponse(new HTTPProgress(100, 40, 'partial'));++ await expect(eventsPromise).resolves.toEqual(new HTTPProgress(100, 40, 'partial'));+ });+});diff --git a/packages/network/src/services/http/__testing__/request.spec.ts b/packages/network/src/services/http/__testing__/request.spec.tsindex e820627c1a..06c346128d 100644--- a/packages/network/src/services/http/__testing__/request.spec.ts+++ b/packages/network/src/services/http/__testing__/request.spec.ts@@ -112,6 +112,43 @@ describe('test class HTTPRequest', () => {expect(request.getBody()).toBe('123');});++ it('should stringify array bodies with the default JSON content type', () => {+ const body = [1, 2, 3];+ const request = new HTTPRequest('POST', 'https://example.com', {+ body,+ headers: new HTTPHeaders(),+ responseType: 'json',+ withCredentials: false,+ });++ expect(request.getBody()).toBe(JSON.stringify(body));+ });++ it('should treat falsy primitive bodies as empty according to current behavior', () => {+ const zeroRequest = new HTTPRequest('POST', 'https://example.com', {+ body: 0,+ headers: new HTTPHeaders(),+ responseType: 'text',+ withCredentials: false,+ });+ const falseRequest = new HTTPRequest('POST', 'https://example.com', {+ body: false,+ headers: new HTTPHeaders(),+ responseType: 'text',+ withCredentials: false,+ });+ const emptyRequest = new HTTPRequest('POST', 'https://example.com', {+ body: '',+ headers: new HTTPHeaders(),+ responseType: 'text',+ withCredentials: false,+ });++ expect(zeroRequest.getBody()).toBeNull();+ expect(falseRequest.getBody()).toBeNull();+ expect(emptyRequest.getBody()).toBeNull();+ });});describe('getHeadersInit', () => {diff --git a/packages/network/src/services/web-socket/__tests__/web-socket.service.spec.ts b/packages/network/src/services/web-socket/__tests__/web-socket.service.spec.tsnew file mode 100644index 0000000000..a40ba99be7--- /dev/null+++ b/packages/network/src/services/web-socket/__tests__/web-socket.service.spec.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 { SocketBodyType } from '../web-socket.service';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { WebSocketService } from '../web-socket.service';++type SocketEventName = 'open' | 'close' | 'error' | 'message';++class FakeWebSocket {+ static instances: FakeWebSocket[] = [];++ readonly listeners: Record<SocketEventName, Set<(event: Event | MessageEvent) => void>> = {+ open: new Set(),+ close: new Set(),+ error: new Set(),+ message: new Set(),+ };++ readonly send = vi.fn();++ readonly close = vi.fn((code?: number, reason?: string) => {+ this.closedWith = { code, reason };+ });++ closedWith?: { code?: number; reason?: string };++ constructor(readonly url: string) {+ FakeWebSocket.instances.push(this);+ }++ addEventListener(type: SocketEventName, callback: (event: Event | MessageEvent) => void) {+ this.listeners[type].add(callback);+ }++ removeEventListener(type: SocketEventName, callback: (event: Event | MessageEvent) => void) {+ this.listeners[type].delete(callback);+ }++ emit(type: SocketEventName, event: Event | MessageEvent) {+ this.listeners[type].forEach((callback) => callback(event));+ }+}++describe('WebSocketService', () => {+ const originalWebSocket = globalThis.WebSocket;++ beforeEach(() => {+ FakeWebSocket.instances = [];+ vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ globalThis.WebSocket = originalWebSocket;+ });++ it('creates sockets, forwards events, and removes listeners on close', () => {+ const service = new WebSocketService();+ const socket = service.createSocket('ws://example.com/socket');++ expect(socket).not.toBeNull();+ expect(socket?.URL).toBe('ws://example.com/socket');++ const createdSocket = FakeWebSocket.instances[0];+ const openEvents: Event[] = [];+ const messageEvents: MessageEvent[] = [];+ const errorEvents: Event[] = [];+ const closeEvents: Event[] = [];++ const openSubscription = socket!.open$.subscribe((event) => openEvents.push(event));+ const messageSubscription = socket!.message$.subscribe((event) => messageEvents.push(event));+ const errorSubscription = socket!.error$.subscribe((event) => errorEvents.push(event));+ const closeSubscription = socket!.close$.subscribe((event) => closeEvents.push(event));++ const openEvent = new Event('open');+ const messageEvent = new MessageEvent('message', { data: 'payload' });+ const errorEvent = new Event('error');+ const closeEvent = new Event('close');++ createdSocket.emit('open', openEvent);+ createdSocket.emit('message', messageEvent);+ createdSocket.emit('error', errorEvent);+ createdSocket.emit('close', closeEvent);++ expect(openEvents).toEqual([openEvent]);+ expect(messageEvents).toEqual([messageEvent]);+ expect(errorEvents).toEqual([errorEvent]);+ expect(closeEvents).toEqual([closeEvent]);++ const payload: SocketBodyType = 'hello';+ socket!.send(payload);+ expect(createdSocket.send).toHaveBeenCalledWith(payload);++ socket!.close(1000, 'done');+ expect(createdSocket.close).toHaveBeenCalledWith(1000, 'done');+ expect(createdSocket.listeners.open.size).toBe(0);+ expect(createdSocket.listeners.message.size).toBe(0);+ expect(createdSocket.listeners.error.size).toBe(0);+ expect(createdSocket.listeners.close.size).toBe(0);++ openSubscription.unsubscribe();+ messageSubscription.unsubscribe();+ errorSubscription.unsubscribe();+ closeSubscription.unsubscribe();+ service.dispose();+ });++ it('returns null when the platform WebSocket constructor throws', () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ vi.stubGlobal('WebSocket', class ThrowingWebSocket {+ constructor() {+ throw new Error('unsupported');+ }+ } as unknown as typeof WebSocket);++ const service = new WebSocketService();++ expect(service.createSocket('ws://example.com/fail')).toBeNull();+ expect(errorSpy).toHaveBeenCalled();++ errorSpy.mockRestore();+ service.dispose();+ });+});diff --git a/packages/rpc-node/src/plugin.ts b/packages/rpc-node/src/plugin.tsindex d8c8554ed5..68b14a3196 100644--- a/packages/rpc-node/src/plugin.ts+++ b/packages/rpc-node/src/plugin.ts@@ -68,6 +68,7 @@ export class UniverRPCNodeMainPlugin extends Plugin {const dependencies: Dependency[] = [[IRPCChannelService, {+ // eslint-disable-next-line react/no-unnecessary-use-prefixuseFactory: () => new ChannelService(messageProtocol),}],[DataSyncPrimaryController],@@ -119,6 +120,7 @@ export class UniverRPCNodeWorkerPlugin extends Plugin {([[DataSyncReplicaController],[IRPCChannelService, {+ // eslint-disable-next-line react/no-unnecessary-use-prefixuseFactory: () => new ChannelService(createNodeWorkerMessageProtocol()),}],[IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }],diff --git a/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.tsnew file mode 100644index 0000000000..4ef951689b--- /dev/null+++ b/packages/rpc/src/controllers/data-sync/__tests__/data-sync.controller.spec.ts@@ -0,0 +1,261 @@+/**+ * 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 { ICommandService, Injector, IUniverInstanceService } from '@univerjs/core';+import type { IRPCChannelService } from '../../../services/rpc/channel.service';+import type { IChannel } from '../../../services/rpc/rpc.service';+import { CommandType, UniverInstanceType } from '@univerjs/core';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { IRemoteInstanceService, IRemoteSyncService, RemoteInstanceServiceName, RemoteSyncServiceName } from '../../../services/remote-instance/remote-instance.service';+import { DataSyncPrimaryController } from '../data-sync-primary.controller';+import { DataSyncReplicaController } from '../data-sync-replica.controller';++interface IDependencyFactory {+ useFactory: () => unknown;+}++function buildRemoteChannel(target: Record<string, (...args: unknown[]) => unknown>): IChannel {+ return {+ call: (async (method: string, args?: unknown[]) => {+ const fn = target[method];+ if (!fn) {+ throw new Error(`missing method: ${method}`);+ }+ return args ? fn(...args) : fn();+ }) as IChannel['call'],+ subscribe: (() => new Subject<unknown>().asObservable()) as IChannel['subscribe'],+ };+}++describe('data-sync controllers', () => {+ it('DataSyncPrimaryController should sync add/dispose/mutation with branch guards', async () => {+ const added$ = new Subject<{ getUnitId(): string; getSnapshot(): unknown }>();+ const disposed$ = new Subject<{ getUnitId(): string }>();+ let commandCallback: ((commandInfo: unknown, options?: unknown) => void) | undefined;+ const dependencies: Array<[unknown, IDependencyFactory]> = [];+ let remoteProxy: unknown;++ const remoteInstanceImpl = {+ createInstance: vi.fn(async () => true),+ disposeInstance: vi.fn(async () => true),+ syncMutation: vi.fn(async () => true),+ };++ const remoteChannel = buildRemoteChannel(remoteInstanceImpl);++ const rpcChannelService: IRPCChannelService = {+ requestChannel: vi.fn(() => remoteChannel),+ registerChannel: vi.fn(),+ };++ const injector = {+ add: vi.fn((dependency: [unknown, IDependencyFactory]) => {+ dependencies.push(dependency);+ }),+ get: vi.fn((token: unknown) => {+ if (token === IRemoteInstanceService) {+ if (!remoteProxy) {+ const record = dependencies.find(([depToken]) => depToken === IRemoteInstanceService);+ remoteProxy = record?.[1].useFactory();+ }+ return remoteProxy;+ }+ return undefined;+ }),+ } as unknown as Injector;++ const commandService = {+ onCommandExecuted: vi.fn((callback: (commandInfo: unknown, options?: unknown) => void) => {+ commandCallback = callback;+ return { dispose: vi.fn() };+ }),+ } as unknown as ICommandService;++ const univerInstanceService = {+ getTypeOfUnitAdded$: vi.fn(() => added$.asObservable()),+ getTypeOfUnitDisposed$: vi.fn(() => disposed$.asObservable()),+ } as unknown as IUniverInstanceService;++ const remoteSyncService = {+ syncMutation: vi.fn(async () => true),+ };++ const controller = new DataSyncPrimaryController(+ injector,+ commandService,+ univerInstanceService,+ rpcChannelService,+ remoteSyncService as never+ );++ expect(rpcChannelService.registerChannel).toHaveBeenCalledWith(RemoteSyncServiceName, expect.any(Object));+ expect(rpcChannelService.requestChannel).toHaveBeenCalledWith(RemoteInstanceServiceName);++ const workbook = {+ getUnitId: () => 'unit-1',+ getSnapshot: () => ({ snapshot: true }),+ };+ added$.next(workbook);+ await Promise.resolve();+ expect(remoteInstanceImpl.createInstance).toHaveBeenCalledWith({+ unitID: 'unit-1',+ type: UniverInstanceType.UNIVER_SHEET,+ snapshot: { snapshot: true },+ });++ disposed$.next({ getUnitId: () => 'unit-1' });+ await Promise.resolve();+ expect(remoteInstanceImpl.disposeInstance).toHaveBeenCalledWith({ unitID: 'unit-1' });++ controller.registerSyncingMutations({ id: 'm-sync' } as never);++ const unit2Disposable = controller.syncUnit('unit-2');++ commandCallback?.({+ id: 'm-sync',+ type: CommandType.MUTATION,+ params: { unitId: 'unit-2' },+ }, {});+ await Promise.resolve();+ expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(1);++ commandCallback?.({+ id: 'm-sync',+ type: CommandType.COMMAND,+ params: { unitId: 'unit-2' },+ }, {});+ commandCallback?.({+ id: 'm-sync',+ type: CommandType.MUTATION,+ params: { unitId: 'other' },+ }, {});+ commandCallback?.({+ id: 'm-sync',+ type: CommandType.MUTATION,+ params: { unitId: 'unit-2' },+ }, { fromSync: true });+ commandCallback?.({+ id: 'm-ignore',+ type: CommandType.MUTATION,+ params: { unitId: 'unit-2' },+ }, {});+ commandCallback?.({+ id: 'm-sync',+ type: CommandType.MUTATION,+ params: {},+ }, {});+ await Promise.resolve();++ expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(2);++ unit2Disposable.dispose();+ commandCallback?.({+ id: 'm-sync',+ type: CommandType.MUTATION,+ params: { unitId: 'unit-2' },+ }, {});+ await Promise.resolve();+ expect(remoteInstanceImpl.syncMutation).toHaveBeenCalledTimes(2);++ controller.dispose();+ });++ it('DataSyncReplicaController should sync only mutation not fromSync', async () => {+ let commandCallback: ((commandInfo: unknown, options?: unknown) => void) | undefined;+ const dependencies: Array<[unknown, IDependencyFactory]> = [];+ let remoteSyncProxy: unknown;++ const remoteSyncImpl = {+ syncMutation: vi.fn(async () => true),+ };++ const remoteChannel = buildRemoteChannel(remoteSyncImpl);++ const rpcChannelService: IRPCChannelService = {+ requestChannel: vi.fn(() => remoteChannel),+ registerChannel: vi.fn(),+ };++ const injector = {+ add: vi.fn((dependency: [unknown, IDependencyFactory]) => {+ dependencies.push(dependency);+ }),+ get: vi.fn((token: unknown) => {+ if (token === IRemoteSyncService) {+ if (!remoteSyncProxy) {+ const record = dependencies.find(([depToken]) => depToken === IRemoteSyncService);+ remoteSyncProxy = record?.[1].useFactory();+ }+ return remoteSyncProxy;+ }+ return undefined;+ }),+ } as unknown as Injector;++ const remoteInstanceService = {+ createInstance: vi.fn(async () => true),+ disposeInstance: vi.fn(async () => true),+ syncMutation: vi.fn(async () => true),+ whenReady: vi.fn(async () => true),+ };++ const commandService = {+ onCommandExecuted: vi.fn((callback: (commandInfo: unknown, options?: unknown) => void) => {+ commandCallback = callback;+ return { dispose: vi.fn() };+ }),+ } as unknown as ICommandService;++ const controller = new DataSyncReplicaController(+ injector,+ remoteInstanceService as never,+ commandService,+ rpcChannelService+ );++ expect(rpcChannelService.registerChannel).toHaveBeenCalledWith(RemoteInstanceServiceName, expect.any(Object));+ expect(rpcChannelService.requestChannel).toHaveBeenCalledWith(RemoteSyncServiceName);++ commandCallback?.({+ id: 'm1',+ type: CommandType.MUTATION,+ params: { a: 1 },+ }, {});+ commandCallback?.({+ id: 'm2',+ type: CommandType.MUTATION,+ params: { a: 2 },+ }, { fromSync: true });+ commandCallback?.({+ id: 'c1',+ type: CommandType.COMMAND,+ params: { a: 3 },+ }, {});++ await Promise.resolve();+ expect(remoteSyncImpl.syncMutation).toHaveBeenCalledTimes(1);+ expect(remoteSyncImpl.syncMutation).toHaveBeenCalledWith({+ mutationInfo: {+ id: 'm1',+ type: CommandType.MUTATION,+ params: { a: 1 },+ },+ }, {});++ controller.dispose();+ });+});diff --git a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.tsindex 7e06621b5a..4136e0516b 100644--- a/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts+++ b/packages/rpc/src/controllers/data-sync/data-sync-primary.controller.ts@@ -82,6 +82,7 @@ export class DataSyncPrimaryController extends RxDisposable {// to call the workerthis._injector.add([IRemoteInstanceService,+ // eslint-disable-next-line react/no-unnecessary-use-prefix{ useFactory: () => toModule<IRemoteInstanceService>(this._rpcChannelService.requestChannel(RemoteInstanceServiceName)) },]);this._remoteInstanceService = this._injector.get(IRemoteInstanceService);diff --git a/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.ts b/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.tsindex d5808baab5..dd7d2930f9 100644--- a/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.ts+++ b/packages/rpc/src/controllers/data-sync/data-sync-replica.controller.ts@@ -50,6 +50,7 @@ export class DataSyncReplicaController extends Disposable {this._injector.add([IRemoteSyncService,+ // eslint-disable-next-line react/no-unnecessary-use-prefix{ useFactory: () => toModule<IRemoteSyncService>(this._rpcChannelService.requestChannel(RemoteSyncServiceName)) },]);this._remoteSyncService = this._injector.get(IRemoteSyncService);diff --git a/packages/rpc/src/plugin.ts b/packages/rpc/src/plugin.tsindex 5279d9ff85..1e1f5efaf1 100644--- a/packages/rpc/src/plugin.ts+++ b/packages/rpc/src/plugin.ts@@ -91,6 +91,7 @@ export class UniverRPCMainThreadPlugin extends Plugin {[IRPCChannelService,{+ // eslint-disable-next-line react/no-unnecessary-use-prefixuseFactory: () => new ChannelService(messageProtocol),},],@@ -136,6 +137,7 @@ export class UniverRPCWorkerThreadPlugin extends Plugin {[IRPCChannelService,{+ // eslint-disable-next-line react/no-unnecessary-use-prefixuseFactory: () => new ChannelService(createWebWorkerMessagePortOnWorker()),},],diff --git a/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts b/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.tsnew file mode 100644index 0000000000..7e40249101--- /dev/null+++ b/packages/rpc/src/services/remote-instance/__tests__/remote-instance.service.spec.ts@@ -0,0 +1,147 @@+/**+ * 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 { ICommandService, ILogService, IUniverInstanceService } from '@univerjs/core';+import { UniverInstanceType } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { RemoteSyncPrimaryService, WebWorkerRemoteInstanceService } from '../remote-instance.service';++describe('remote-instance.service', () => {+ it('RemoteSyncPrimaryService should sync mutation with normalized options', async () => {+ const syncExecuteCommand = vi.fn(async () => true);+ const commandService = {+ syncExecuteCommand,+ } as unknown as ICommandService;++ const service = new RemoteSyncPrimaryService(commandService);+ await expect(service.syncMutation(+ {+ mutationInfo: {+ id: 'mutation.id',+ params: { a: 1 },+ } as never,+ },+ {+ fromCollab: true,+ source: 'test',+ } as never+ )).resolves.toBe(true);++ expect(syncExecuteCommand).toHaveBeenCalledWith('mutation.id', { a: 1 }, {+ source: 'test',+ onlyLocal: true,+ fromSync: true,+ });++ await expect(service.syncMutation({+ mutationInfo: {+ id: 'mutation.id.2',+ params: { b: 2 },+ } as never,+ })).resolves.toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith('mutation.id.2', { b: 2 }, {+ onlyLocal: true,+ fromSync: true,+ });+ });++ it('WebWorkerRemoteInstanceService should cover create/sync/dispose branches', async () => {+ const createUnit = vi.fn();+ const disposeUnit = vi.fn(() => true);+ const syncExecuteCommand = vi.fn(() => true);+ const debug = vi.fn();++ const univerInstanceService = {+ createUnit,+ disposeUnit,+ } as unknown as IUniverInstanceService;+ const commandService = {+ syncExecuteCommand,+ } as unknown as ICommandService;+ const logService = {+ debug,+ } as unknown as ILogService;++ const service = new WebWorkerRemoteInstanceService(univerInstanceService, commandService, logService);++ await expect(service.whenReady()).resolves.toBe(true);++ await expect(service.syncMutation(+ {+ mutationInfo: {+ id: 'm1',+ params: { x: 1 },+ } as never,+ },+ {+ fromCollab: true,+ source: 'sync',+ } as never+ )).resolves.toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith('m1', { x: 1 }, {+ source: 'sync',+ onlyLocal: true,+ fromSync: true,+ });++ await expect(service.syncMutation({+ mutationInfo: {+ id: 'm1b',+ params: { y: 2 },+ } as never,+ })).resolves.toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith('m1b', { y: 2 }, {+ onlyLocal: true,+ fromSync: true,+ });++ await expect(service.createInstance({+ unitID: 'sheet-1',+ type: UniverInstanceType.UNIVER_SHEET,+ snapshot: { id: 'snapshot' } as never,+ })).resolves.toBe(true);+ expect(createUnit).toHaveBeenCalledWith(UniverInstanceType.UNIVER_SHEET, { id: 'snapshot' });++ await expect(service.disposeInstance({ unitID: 'sheet-1' })).resolves.toBe(true);+ expect(disposeUnit).toHaveBeenCalledWith('sheet-1');+ expect(debug).toHaveBeenCalled();++ await expect(service.createInstance({+ unitID: 'doc-1',+ type: UniverInstanceType.UNIVER_DOC,+ snapshot: {} as never,+ })).rejects.toThrow(`[WebWorkerRemoteInstanceService]: cannot create replica for document type: ${UniverInstanceType.UNIVER_DOC}.`);++ createUnit.mockImplementationOnce(() => {+ throw new Error('create error');+ });+ await expect(service.createInstance({+ unitID: 'sheet-2',+ type: UniverInstanceType.UNIVER_SHEET,+ snapshot: {} as never,+ })).rejects.toThrow('create error');++ createUnit.mockImplementationOnce(() => {+ const nonError: unknown = 'bad-value';+ throw nonError;+ });+ await expect(service.createInstance({+ unitID: 'sheet-3',+ type: UniverInstanceType.UNIVER_SHEET,+ snapshot: {} as never,+ })).rejects.toThrow('bad-value');+ });+});diff --git a/packages/rpc/src/services/rpc/__tests__/channel.service.spec.ts b/packages/rpc/src/services/rpc/__tests__/channel.service.spec.tsnew file mode 100644index 0000000000..1a36ec645b--- /dev/null+++ b/packages/rpc/src/services/rpc/__tests__/channel.service.spec.ts@@ -0,0 +1,63 @@+/**+ * 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 { IMessageProtocol } from '../rpc.service';+import { Observable, Subject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { ChannelService } from '../channel.service';+import { fromModule } from '../rpc.service';++function flushPromises() {+ return new Promise<void>((resolve) => {+ setTimeout(() => resolve(), 0);+ });+}++describe('ChannelService', () => {+ it('should register channel, request channel, and dispose', async () => {+ const message$ = new Subject<unknown>();+ const protocol: IMessageProtocol = {+ send(message: unknown): void {+ message$.next(message);+ },+ onMessage: message$.asObservable(),+ };++ const service = new ChannelService(protocol);++ service.registerChannel('math', fromModule({+ add(a: number, b: number) {+ return a + b;+ },+ values$() {+ return new Observable<number>((subscriber) => {+ subscriber.next(1);+ subscriber.complete();+ });+ },+ }));++ const channel = service.requestChannel('math');+ await expect(channel.call<number>('add', [2, 3])).resolves.toBe(5);++ const values: number[] = [];+ channel.subscribe<number>('values$').subscribe((value) => values.push(value));+ await flushPromises();+ expect(values).toEqual([1]);++ service.dispose();+ });+});diff --git a/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts b/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.tsnew file mode 100644index 0000000000..3a942181b7--- /dev/null+++ b/packages/rpc/src/services/rpc/__tests__/rpc.service.edge.spec.ts@@ -0,0 +1,270 @@+/**+ * 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 { IChannel, IMessageProtocol } from '../rpc.service';+import { Observable, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { ChannelClient, ChannelServer, fromModule, toModule } from '../rpc.service';++const REQUEST_INITIALIZATION = 50;+const CALL = 100;+const SUBSCRIBE = 101;+const UNSUBSCRIBE = 102;++const INITIALIZE = 0;+const CALL_SUCCESS = 201;+const CALL_FAILURE = 202;+const SUBSCRIBE_NEXT = 300;+const SUBSCRIBE_ERROR = 301;+const SUBSCRIBE_COMPLETE = 302;++function flushPromises() {+ return new Promise<void>((resolve) => {+ setTimeout(() => resolve(), 0);+ });+}++function getType(value: unknown): number | undefined {+ if (typeof value !== 'object' || value === null) {+ return undefined;+ }+ return (value as { type?: number }).type;+}++function getSeq(value: unknown): number | undefined {+ if (typeof value !== 'object' || value === null) {+ return undefined;+ }+ return (value as { seq?: number }).seq;+}++class TestMessageProtocol {+ readonly sent: unknown[] = [];+ private readonly _message$ = new Subject<unknown>();+ readonly onMessage = this._message$.asObservable();++ send(message: unknown): void {+ this.sent.push(message);+ }++ emit(message: unknown): void {+ this._message$.next(message);+ }+}++describe('rpc.service edge cases', () => {+ it('fromModule should cover args/no-args, non-observable and missing methods', async () => {+ const channel = fromModule({+ sum(a: number, b: number) {+ return a + b;+ },+ ping() {+ return 'pong';+ },+ value$() {+ return 7;+ },+ });++ await expect(channel.call<number>('sum', [1, 2])).resolves.toBe(3);+ await expect(channel.call<string>('ping')).resolves.toBe('pong');++ const values: number[] = [];+ channel.subscribe<number>('value$').subscribe((value) => values.push(value));+ expect(values).toEqual([7]);++ expect(() => channel.call('missing')).toThrow('[RPC]: method not found for missing!');+ expect(() => channel.subscribe('missing$')).toThrow('[RPC]: observable method not found for missing$!');+ });++ it('toModule should route call/subscribe and hide dispose', async () => {+ const call = vi.fn(async () => 'ok') as IChannel['call'];+ const subscribe = vi.fn(() => new Observable<number>((subscriber) => {+ subscriber.next(1);+ subscriber.complete();+ })) as IChannel['subscribe'];++ const channel: IChannel = { call, subscribe };+ const module = toModule<{+ dispose?: () => void;+ fetch(value: number): Promise<string>;+ values$(): Observable<number>;+ }>(channel);++ expect(module.dispose).toBeUndefined();+ await expect(module.fetch(123)).resolves.toBe('ok');++ const values: number[] = [];+ module.values$().subscribe((value) => values.push(value));+ expect(values).toEqual([1]);++ expect(call).toHaveBeenCalledWith('fetch', [123]);+ expect(subscribe).toHaveBeenCalledWith('values$', []);+ });++ it('ChannelClient should wait initialization, support disposal, and hit unknown response branches', async () => {+ const protocol = new TestMessageProtocol();+ const client = new ChannelClient(protocol as IMessageProtocol);+ const channel = client.getChannel<IChannel>('demo');++ const callPromise = channel.call<string>('get', ['value']);+ expect(getType(protocol.sent[0])).toBe(REQUEST_INITIALIZATION);+ expect(protocol.sent.some((msg) => getType(msg) === CALL)).toBe(false);++ const lazySubscription = channel.subscribe<number>('count$').subscribe(() => undefined);+ lazySubscription.unsubscribe();++ protocol.emit({ seq: -1, type: INITIALIZE });+ await flushPromises();++ const callRequest = protocol.sent.find((msg) => getType(msg) === CALL);+ expect(callRequest).toBeDefined();+ const callSeq = getSeq(callRequest);+ expect(callSeq).toBeTypeOf('number');++ protocol.emit({ seq: callSeq, type: CALL_SUCCESS, data: 'done' });+ await expect(callPromise).resolves.toBe('done');++ const failurePromise = channel.call<string>('fail', []);+ const failureRequest = [...protocol.sent].reverse().find((msg) => getType(msg) === CALL);+ protocol.emit({ seq: getSeq(failureRequest), type: CALL_FAILURE, data: 'boom' });+ await expect(failurePromise).rejects.toBe('boom');++ const unknownCallPromise = channel.call<string>('unknown', []);+ const unknownCallRequest = [...protocol.sent].reverse().find((msg) => getType(msg) === CALL);+ const callPending = (client as unknown as {+ _pendingRequests: Map<number, { handle(response: { seq: number; type: number; data?: unknown }): void }>;+ })._pendingRequests;+ expect(() =>+ callPending.get(getSeq(unknownCallRequest) as number)?.handle({+ seq: getSeq(unknownCallRequest) as number,+ type: SUBSCRIBE_NEXT,+ data: 'x',+ })+ ).toThrow('[ChannelClient]: unknown response type!');+ callPending.delete(getSeq(unknownCallRequest) as number);+ void unknownCallPromise.catch(() => undefined);++ const values: number[] = [];+ const stream = channel.subscribe<number>('stream$').subscribe((value) => values.push(value));+ const subscribeRequest = [...protocol.sent].reverse().find((msg) => getType(msg) === SUBSCRIBE);+ const subscribeSeq = getSeq(subscribeRequest);++ protocol.emit({ seq: subscribeSeq, type: SUBSCRIBE_NEXT, data: 1 });+ expect(values).toEqual([1]);++ const subscribePending = (client as unknown as {+ _pendingRequests: Map<number, { handle(response: { seq: number; type: number; data?: unknown }): void }>;+ })._pendingRequests;+ expect(() =>+ subscribePending.get(subscribeSeq as number)?.handle({+ seq: subscribeSeq as number,+ type: CALL_SUCCESS,+ data: 'x',+ })+ ).toThrow('[ChannelClient]: unknown response type!');++ protocol.emit({ seq: subscribeSeq, type: SUBSCRIBE_COMPLETE });+ stream.unsubscribe();++ (client as unknown as { _disposed: boolean })._disposed = true;+ await expect(channel.call('disposed')).rejects.toThrow('[ChannelClient]: client is disposed!');+ expect(() => channel.subscribe('disposed$')).toThrow('[ChannelClient]: client is disposed!');+ client.dispose();+ });++ it('ChannelServer should handle request branches, call/subscribe failures and unsubscription', async () => {+ const protocol = new TestMessageProtocol();+ const server = new ChannelServer(protocol as IMessageProtocol);++ expect(getType(protocol.sent[0])).toBe(INITIALIZE);++ protocol.emit({ type: REQUEST_INITIALIZATION, seq: 1, channelName: '', method: '' });+ expect(protocol.sent.filter((msg) => getType(msg) === INITIALIZE).length).toBe(2);++ protocol.emit({ type: 999, seq: 1, channelName: '', method: '' });++ protocol.emit({ type: CALL, seq: 10, channelName: 'missing', method: 'm' });+ await flushPromises();+ expect(protocol.sent).toContainEqual({+ seq: 10,+ type: CALL_FAILURE,+ data: '[ChannelServer]: Channel missing not found!',+ });++ server.registerChannel('bad-call', {+ call: () => {+ const nonError: unknown = 'text-error';+ return Promise.reject(nonError);+ },+ subscribe: () => new Observable(),+ } as IChannel);+ protocol.emit({ type: CALL, seq: 11, channelName: 'bad-call', method: 'm', args: [] });+ await flushPromises();+ expect(protocol.sent).toContainEqual({+ seq: 11,+ type: CALL_FAILURE,+ data: 'text-error',+ });++ server.registerChannel('no-args', {+ call: async () => 'ok',+ subscribe: () => new Observable(),+ } as IChannel);+ protocol.emit({ type: CALL, seq: 12, channelName: 'no-args', method: 'm' });+ await flushPromises();+ expect(protocol.sent).toContainEqual({+ seq: 12,+ type: CALL_SUCCESS,+ data: 'ok',+ });++ protocol.emit({ type: SUBSCRIBE, seq: 20, channelName: 'missing-sub', method: 'stream$' });+ expect(protocol.sent).toContainEqual({+ seq: 20,+ type: SUBSCRIBE_ERROR,+ data: '[ChannelServer]: Channel missing-sub not found!',+ });++ server.registerChannel('bad-sub', {+ call: async () => true,+ subscribe: () => {+ const nonError: unknown = 'subscribe-error';+ throw nonError;+ },+ } as IChannel);+ protocol.emit({ type: SUBSCRIBE, seq: 21, channelName: 'bad-sub', method: 'stream$' });+ expect(protocol.sent).toContainEqual({+ seq: 21,+ type: SUBSCRIBE_ERROR,+ data: 'subscribe-error',+ });++ let unsubscribed = false;+ server.registerChannel('stream', {+ call: async () => true,+ subscribe: () => new Observable<string>(() => () => {+ unsubscribed = true;+ }),+ } as IChannel);+ protocol.emit({ type: SUBSCRIBE, seq: 30, channelName: 'stream', method: 'stream$', args: [] });+ protocol.emit({ type: UNSUBSCRIBE, seq: 999, channelName: 'stream', method: 'stream$' });+ protocol.emit({ type: UNSUBSCRIBE, seq: 30, channelName: 'stream', method: 'stream$' });+ expect(unsubscribed).toBe(true);++ server.dispose();+ });+});diff --git a/packages/rpc/src/services/rpc/implementations/__tests__/web-worker-rpc.service.spec.ts b/packages/rpc/src/services/rpc/implementations/__tests__/web-worker-rpc.service.spec.tsnew file mode 100644index 0000000000..b154e576a2--- /dev/null+++ b/packages/rpc/src/services/rpc/implementations/__tests__/web-worker-rpc.service.spec.ts@@ -0,0 +1,78 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { createWebWorkerMessagePortOnMain, createWebWorkerMessagePortOnWorker } from '../web-worker-rpc.service';++vi.mock('rxjs', async () => {+ const actual = await vi.importActual<typeof import('rxjs')>('rxjs');+ return {+ ...actual,+ shareReplay: () => (source: unknown) => source,+ };+});++describe('web-worker-rpc.service', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should create worker-side message protocol', () => {+ const postMessageSpy = vi.fn();+ const addEventListenerSpy = vi.fn();+ const removeEventListenerSpy = vi.fn();++ vi.stubGlobal('postMessage', postMessageSpy);+ vi.stubGlobal('addEventListener', addEventListenerSpy);+ vi.stubGlobal('removeEventListener', removeEventListenerSpy);++ const protocol = createWebWorkerMessagePortOnWorker();+ protocol.send('worker-message');++ const received: unknown[] = [];+ const subscription = protocol.onMessage.subscribe((message) => received.push(message));+ const handler = addEventListenerSpy.mock.calls[0][1] as (event: MessageEvent) => void;+ handler({ data: 'from-main' } as MessageEvent);++ expect(postMessageSpy).toHaveBeenCalledWith('worker-message');+ expect(received).toEqual(['from-main']);++ subscription.unsubscribe();+ expect(removeEventListenerSpy).toHaveBeenCalledWith('message', handler);+ });++ it('should create main-side message protocol', () => {+ const worker = {+ postMessage: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ };++ const protocol = createWebWorkerMessagePortOnMain(worker as unknown as Worker);+ protocol.send('main-message');++ const received: unknown[] = [];+ const subscription = protocol.onMessage.subscribe((message) => received.push(message));+ const handler = worker.addEventListener.mock.calls[0][1] as (event: MessageEvent) => void;+ handler({ data: 'from-worker' } as MessageEvent);++ expect(worker.postMessage).toHaveBeenCalledWith('main-message');+ expect(received).toEqual(['from-worker']);++ subscription.unsubscribe();+ expect(worker.removeEventListener).toHaveBeenCalledWith('message', handler);+ });+});diff --git a/packages/rpc/src/services/rpc/implementations/web-worker-rpc.service.ts b/packages/rpc/src/services/rpc/implementations/web-worker-rpc.service.tsindex 3bc71523a4..ec6f45e3e5 100644--- a/packages/rpc/src/services/rpc/implementations/web-worker-rpc.service.ts+++ b/packages/rpc/src/services/rpc/implementations/web-worker-rpc.service.ts@@ -19,13 +19,14 @@ import { Observable, shareReplay } from 'rxjs';/*** Generate an `IMessageProtocol` on the web worker.+ * @returns A protocol wrapper around worker global messaging APIs.*/export function createWebWorkerMessagePortOnWorker(): IMessageProtocol {return {send(message: unknown): void {postMessage(message);},- onMessage: new Observable<any>((subscriber) => {+ onMessage: new Observable<unknown>((subscriber) => {const handler = (event: MessageEvent) => {subscriber.next(event.data);};@@ -38,14 +39,14 @@ export function createWebWorkerMessagePortOnWorker(): IMessageProtocol {/*** Generate an `IMessageProtocol` on the main thread side.* @param worker The Web Worker object- * @returns+ * @returns A protocol wrapper around the given worker messaging APIs.*/export function createWebWorkerMessagePortOnMain(worker: Worker): IMessageProtocol {return {send(message) {worker.postMessage(message);},- onMessage: new Observable<any>((subscriber) => {+ onMessage: new Observable<unknown>((subscriber) => {const handler = (event: MessageEvent) => {subscriber.next(event.data);};diff --git a/packages/rpc/src/services/rpc/rpc.service.ts b/packages/rpc/src/services/rpc/rpc.service.tsindex 7059e31189..4865552768 100644--- a/packages/rpc/src/services/rpc/rpc.service.ts+++ b/packages/rpc/src/services/rpc/rpc.service.ts@@ -89,7 +89,7 @@ export function fromModule(module: unknown): IChannel {* request the remote server by calling the channel.** @param channel- * @returns+ * @returns A proxy object that forwards calls/subscriptions to the remote channel.*/export function toModule<T extends object>(channel: IChannel): T {return new Proxy({} as T, {@@ -203,22 +203,20 @@ export class ChannelClient extends RxDisposable implements IChannelClient {}getChannel<T extends IChannel>(channelName: string): T {- const self = this;-return {- call(method: string, args?: any) {- if (self._disposed) {- return Promise.reject();+ call: (method: string, args?: any) => {+ if (this._disposed) {+ return Promise.reject(new Error('[ChannelClient]: client is disposed!'));}- return self._remoteCall(channelName, method, args);+ return this._remoteCall(channelName, method, args);},- subscribe(eventMethod: string, args?: any) {- if (self._disposed) {+ subscribe: (eventMethod: string, args?: any) => {+ if (this._disposed) {throw new Error('[ChannelClient]: client is disposed!');}- return self._remoteSubscribe(channelName, eventMethod, args);+ return this._remoteSubscribe(channelName, eventMethod, args);},} as T;}@@ -247,18 +245,18 @@ export class ChannelClient extends RxDisposable implements IChannelClient {const sequence = ++this._lastRequestCounter;const type = RequestType.CALL;const request: IRPCRequest = { seq: sequence, type, channelName, method, args };- const client = this;+ const pendingRequests = this._pendingRequests;return new Promise((resolve, reject) => {const responseHandler: IResponseHandler = {handle(response: IRPCResponse) {switch (response.type) {case ResponseType.CALL_SUCCESS:- client._pendingRequests.delete(sequence);+ pendingRequests.delete(sequence);resolve(response.data);break;case ResponseType.CALL_FAILURE:- client._pendingRequests.delete(sequence);+ pendingRequests.delete(sequence);reject(response.data);break;default:@@ -408,7 +406,7 @@ export class ChannelServer extends RxDisposable implements IChannelServer {}promise = args ? channel.call(method, args) : channel.call(method);} catch (err: unknown) {- promise = Promise.reject(err);+ promise = Promise.reject(err instanceof Error ? err : new Error(String(err)));}promisediff --git a/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.ts b/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.tsnew file mode 100644index 0000000000..dea2c838ef--- /dev/null+++ b/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.ts@@ -0,0 +1,102 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { ICommandService } from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { CFRuleType, CFSubRuleType, ClearRangeCfCommand, ClearWorksheetCfCommand } from '@univerjs/sheets-conditional-formatting';+import { describe, expect, it, vi } from 'vitest';+import { ConditionalFormattingPanelController } from '../../../controllers/cf.panel.controller';+import { CF_MENU_OPERATION, OpenConditionalFormattingOperator } from '../open-conditional-formatting-panel';++describe('OpenConditionalFormattingOperator', () => {+ const range = {+ startRow: 1,+ endRow: 2,+ startColumn: 3,+ endColumn: 4,+ };++ function createAccessor() {+ const controller = {+ openPanel: vi.fn(),+ };+ const selectionManagerService = {+ getCurrentSelections: vi.fn(() => [{ range }]),+ };+ const commandService = {+ executeCommand: vi.fn(),+ };++ const get: IAccessor['get'] = ((token: unknown) => {+ if (token === ConditionalFormattingPanelController) {+ return controller;+ }++ if (token === SheetsSelectionsService) {+ return selectionManagerService;+ }++ if (token === ICommandService) {+ return commandService;+ }++ throw new Error('Unknown dependency');+ }) as IAccessor['get'];+ const has: IAccessor['has'] = (() => false) as IAccessor['has'];++ const accessor: IAccessor = {+ get,+ has,+ };++ return { accessor, controller, commandService };+ }++ it('opens the panel with a formula rule seeded from the current selection', () => {+ const { accessor, controller } = createAccessor();++ expect(OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.formula })).toBe(true);+ expect(controller.openPanel).toHaveBeenCalledWith({+ ranges: [range],+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.formula,+ value: '=',+ },+ });+ });++ it('opens the panel without payload for the manage-rules action', () => {+ const { accessor, controller } = createAccessor();++ OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.viewRule });++ expect(controller.openPanel).toHaveBeenCalledWith();+ });++ it('dispatches clear commands for range and worksheet actions', () => {+ const { accessor, commandService } = createAccessor();++ OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.clearRangeRules });+ OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.clearWorkSheetRules });++ expect(commandService.executeCommand).toHaveBeenNthCalledWith(1, ClearRangeCfCommand.id, {+ ranges: [range],+ });+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, ClearWorksheetCfCommand.id);+ });+});diff --git a/packages/sheets-conditional-formatting/src/facade/f-workbook.ts b/packages/sheets-conditional-formatting/src/facade/f-workbook.tsdeleted file mode 100644index 9a7ef8e7f3..0000000000--- a/packages/sheets-conditional-formatting/src/facade/f-workbook.ts+++ /dev/null@@ -1,40 +0,0 @@-/**- * 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 { ColorBuilder } from '@univerjs/core';-import { FWorkbook } from '@univerjs/sheets/facade';--/**- * @ignore- */-export interface IFWorkbookConditionalFormattingMixin {- /**- * @deprecated use `univerAPI.newColor()` as instead.- */- newColor(): ColorBuilder;-}--export class FWorkbookConditionalFormattingMixin extends FWorkbook implements IFWorkbookConditionalFormattingMixin {- override newColor(): ColorBuilder {- return new ColorBuilder();- }-}--FWorkbook.extend(FWorkbookConditionalFormattingMixin);-declare module '@univerjs/sheets/facade' {- // eslint-disable-next-line ts/naming-convention- interface FWorkbook extends IFWorkbookConditionalFormattingMixin { }-}diff --git a/packages/sheets-conditional-formatting/src/facade/index.ts b/packages/sheets-conditional-formatting/src/facade/index.tsindex eef8772b79..4e1a6c9d85 100644--- a/packages/sheets-conditional-formatting/src/facade/index.ts+++ b/packages/sheets-conditional-formatting/src/facade/index.ts@@ -15,12 +15,9 @@*/import './f-range';-import './f-workbook';import './f-worksheet';import './f-enum';export { FConditionalFormattingBuilder } from './f-conditional-formatting-builder';export type { IFRangeConditionalFormattingMixin } from './f-range';-export type { FWorkbookConditionalFormattingMixin } from './f-workbook';-export type { IFWorksheetConditionalFormattingMixin } from './f-worksheet';diff --git a/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.ts b/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.tsnew file mode 100644index 0000000000..c258b2491b--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.ts@@ -0,0 +1,100 @@+/**+ * 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 { MenuItemType } from '@univerjs/ui';+import { of } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import {+ CROSSHAIR_HIGHLIGHT_OVERLAY_COMPONENT,+ CrosshairHighlightMenuItemFactory,+} from '../../controllers/crosshair.menu';+import { menuSchema } from '../../controllers/menu.schema';+import {+ CROSSHAIR_HIGHLIGHT_COLORS,+ SheetsCrosshairHighlightService,+} from '../../services/crosshair.service';+import {+ DisableCrosshairHighlightOperation,+ EnableCrosshairHighlightOperation,+ SetCrosshairHighlightColorOperation,+ ToggleCrosshairHighlightOperation,+} from './operation';++vi.mock('@univerjs/ui', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');+ return {+ ...actual,+ getMenuHiddenObservable: vi.fn(() => of(false)),+ };+});++describe('crosshair operations/menu/service', () => {+ it('should handle service state changes and dispose', () => {+ const service = new SheetsCrosshairHighlightService();+ expect(service.enabled).toBe(false);+ expect(service.color).toBe(CROSSHAIR_HIGHLIGHT_COLORS[0]);++ service.setEnabled(true);+ service.setColor(CROSSHAIR_HIGHLIGHT_COLORS[1]);+ expect(service.enabled).toBe(true);+ expect(service.color).toBe(CROSSHAIR_HIGHLIGHT_COLORS[1]);++ service.dispose();+ });++ it('should execute operation handlers with branch coverage', () => {+ const service = new SheetsCrosshairHighlightService();+ const accessor = { get: vi.fn(() => service) };++ expect(ToggleCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(true);+ expect(service.enabled).toBe(true);++ service.setEnabled(false);+ expect(SetCrosshairHighlightColorOperation.handler(accessor as never, { value: 'rgba(0,0,0,0.1)' })).toBe(true);+ expect(service.enabled).toBe(true);+ expect(service.color).toBe('rgba(0,0,0,0.1)');+ expect(SetCrosshairHighlightColorOperation.handler(accessor as never, { value: 'rgba(0,0,0,0.2)' })).toBe(true);++ expect(EnableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(false);+ service.setEnabled(false);+ expect(EnableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(true);++ expect(DisableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(true);+ expect(DisableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(false);+ });++ it('should create menu item schema and factory output', () => {+ const service = new SheetsCrosshairHighlightService();+ service.setEnabled(true);+ const accessor = { get: vi.fn(() => service) };++ const item = CrosshairHighlightMenuItemFactory(accessor as never);+ expect(item.id).toBe(ToggleCrosshairHighlightOperation.id);+ expect(item.type).toBe(MenuItemType.BUTTON_SELECTOR);+ const itemSelections = (item as unknown as { selections: Array<{ label: { name: string } }> }).selections;+ expect(itemSelections[0].label.name).toBe(CROSSHAIR_HIGHLIGHT_OVERLAY_COMPONENT);+ expect(item.selectionsCommandId).toBe(SetCrosshairHighlightColorOperation.id);+ expect(item.activated$).toBe(service.enabled$);+ expect(item.hidden$).toBeDefined();++ const firstLevel = Object.values(menuSchema)[0] as Record<string, Record<string, unknown>>;+ const secondLevel = Object.values(firstLevel)[0] as Record<string, { menuItemFactory: unknown; order: number }>;+ expect(secondLevel[ToggleCrosshairHighlightOperation.id].menuItemFactory).toBe(CrosshairHighlightMenuItemFactory);+ expect(secondLevel[ToggleCrosshairHighlightOperation.id].order).toBe(0);++ expect(accessor.get).toHaveBeenCalledWith(service.constructor);+ });+});diff --git a/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsx b/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsxnew file mode 100644index 0000000000..7d4c3948cf--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/controllers/crosshair.controller.spec.tsx@@ -0,0 +1,52 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import {+ DisableCrosshairHighlightOperation,+ EnableCrosshairHighlightOperation,+ SetCrosshairHighlightColorOperation,+ ToggleCrosshairHighlightOperation,+} from '../commands/operations/operation';+import { SheetsCrosshairHighlightController } from './crosshair.controller';+import { CROSSHAIR_HIGHLIGHT_OVERLAY_COMPONENT } from './crosshair.menu';+import { menuSchema } from './menu.schema';++describe('SheetsCrosshairHighlightController', () => {+ it('should register commands, merge menu and register components', () => {+ const registerCommand = vi.fn();+ const mergeMenu = vi.fn();+ const register = vi.fn(() => ({ dispose: vi.fn() }));++ const controller = new SheetsCrosshairHighlightController(+ { register } as never,+ { mergeMenu } as never,+ { registerCommand } as never+ );++ expect(registerCommand).toHaveBeenCalledWith(ToggleCrosshairHighlightOperation);+ expect(registerCommand).toHaveBeenCalledWith(SetCrosshairHighlightColorOperation);+ expect(registerCommand).toHaveBeenCalledWith(EnableCrosshairHighlightOperation);+ expect(registerCommand).toHaveBeenCalledWith(DisableCrosshairHighlightOperation);++ expect(mergeMenu).toHaveBeenCalledWith(menuSchema);+ expect(register).toHaveBeenCalledWith(CROSSHAIR_HIGHLIGHT_OVERLAY_COMPONENT, expect.any(Function));+ expect(register).toHaveBeenCalledWith('CrossHighlightingIcon', expect.anything());+ expect(Object.keys(menuSchema).length).toBeGreaterThan(0);++ controller.dispose();+ });+});diff --git a/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.ts b/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.tsnew file mode 100644index 0000000000..5de7cdaf60--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.ts@@ -0,0 +1,134 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';++const mocked = vi.hoisted(() => ({+ extendUniver: vi.fn(),+ extendEvent: vi.fn(),+ colors: ['c1', 'c2'],+ enableId: 'enable',+ disableId: 'disable',+ toggleId: 'toggle',+ setColorId: 'set-color',+}));++vi.mock('@univerjs/core/facade', () => {+ class FUniver {+ static extend = mocked.extendUniver;+ }+ class FEventName {+ static extend = mocked.extendEvent;+ }++ return {+ FUniver,+ FEventName,+ };+});++vi.mock('@univerjs/sheets-crosshair-highlight', () => ({+ CROSSHAIR_HIGHLIGHT_COLORS: mocked.colors,+ DisableCrosshairHighlightOperation: { id: mocked.disableId },+ EnableCrosshairHighlightOperation: { id: mocked.enableId },+ ToggleCrosshairHighlightOperation: { id: mocked.toggleId },+ SetCrosshairHighlightColorOperation: { id: mocked.setColorId },+ SheetsCrosshairHighlightService: class {},+}));++describe('crosshair facade', () => {+ it('should register mixins and cover event wiring + APIs', async () => {+ const module = await import('./f-univer');++ expect(mocked.extendEvent).toHaveBeenCalledWith(module.FSheetCrosshairHighlightEventMixin);+ expect(mocked.extendUniver).toHaveBeenCalledWith(module.FUniverCrosshairHighlightMixin);++ const callbacks: Array<(commandInfo: { id: string }) => void> = [];+ const commandService = {+ onCommandExecuted: vi.fn((cb: (commandInfo: { id: string }) => void) => {+ callbacks.push(cb);+ return { dispose: vi.fn() };+ }),+ };+ const fireEvent = vi.fn();+ const registerEventHandler = vi.fn((_eventName: string, setup: () => unknown) => setup());+ const thisArg = {+ Event: {+ CrosshairHighlightEnabledChanged: 'CrosshairHighlightEnabledChanged',+ CrosshairHighlightColorChanged: 'CrosshairHighlightColorChanged',+ },+ _injector: {+ get: vi.fn(() => ({+ enabled: true,+ color: 'rgba(1,2,3,0.2)',+ })),+ },+ _commandService: {+ syncExecuteCommand: vi.fn(),+ },+ getActiveSheet: vi.fn(() => ({+ workbook: { id: 'wb' },+ worksheet: { id: 'ws' },+ })),+ getCrosshairHighlightEnabled: vi.fn(() => true),+ getCrosshairHighlightColor: vi.fn(() => 'rgba(1,2,3,0.2)'),+ fireEvent,+ registerEventHandler,+ disposeWithMe: vi.fn(),+ };++ module.FUniverCrosshairHighlightMixin.prototype._initialize.call(+ thisArg,+ { get: vi.fn(() => commandService) } as never+ );+ expect(registerEventHandler).toHaveBeenCalledTimes(2);++ callbacks[0]({ id: mocked.enableId });+ callbacks[0]({ id: mocked.disableId });+ callbacks[0]({ id: mocked.toggleId });+ callbacks[0]({ id: 'other-command' });+ callbacks[1]({ id: mocked.setColorId });+ callbacks[1]({ id: 'other-color-command' });+ expect(fireEvent).toHaveBeenCalled();++ thisArg.getActiveSheet.mockReturnValue(undefined as never);+ callbacks[0]({ id: mocked.enableId });+ callbacks[1]({ id: mocked.setColorId });++ const enabledResult = module.FUniverCrosshairHighlightMixin.prototype.setCrosshairHighlightEnabled.call(thisArg, true);+ const disabledResult = module.FUniverCrosshairHighlightMixin.prototype.setCrosshairHighlightEnabled.call(thisArg, false);+ expect(enabledResult).toBe(thisArg);+ expect(disabledResult).toBe(thisArg);+ expect(thisArg._commandService.syncExecuteCommand).toHaveBeenCalledWith(mocked.enableId);+ expect(thisArg._commandService.syncExecuteCommand).toHaveBeenCalledWith(mocked.disableId);++ const colorResult = module.FUniverCrosshairHighlightMixin.prototype.setCrosshairHighlightColor.call(thisArg, '#ff0000');+ expect(colorResult).toBe(thisArg);+ expect(thisArg._commandService.syncExecuteCommand).toHaveBeenCalledWith(mocked.setColorId, { value: '#ff0000' });++ expect(module.FUniverCrosshairHighlightMixin.prototype.getCrosshairHighlightEnabled.call(thisArg)).toBe(true);+ expect(module.FUniverCrosshairHighlightMixin.prototype.getCrosshairHighlightColor.call(thisArg)).toBe('rgba(1,2,3,0.2)');+ expect(module.FUniverCrosshairHighlightMixin.prototype.CROSSHAIR_HIGHLIGHT_COLORS).toBe(mocked.colors);++ const eventEnum = new module.FSheetCrosshairHighlightEventMixin();+ expect(eventEnum.CrosshairHighlightEnabledChanged).toBe('CrosshairHighlightEnabledChanged');+ expect(eventEnum.CrosshairHighlightColorChanged).toBe('CrosshairHighlightColorChanged');+ });++ it('should run facade entry export', async () => {+ await expect(import('./index')).resolves.toBeDefined();+ });+});diff --git a/packages/sheets-crosshair-highlight/src/util.spec.ts b/packages/sheets-crosshair-highlight/src/util.spec.tsnew file mode 100644index 0000000000..7e65e48ece--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/util.spec.ts@@ -0,0 +1,88 @@+/**+ * 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 { RANGE_TYPE, Rectangle } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { CrossHairRangeCollection } from './util';++describe('CrossHairRangeCollection', () => {+ it('should add/split/reset ranges and skip full row/column/all ranges', () => {+ const collection = new CrossHairRangeCollection();++ collection.addRange({+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.COLUMN,+ } as never);+ collection.addRange({+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.ROW,+ } as never);+ collection.addRange({+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.ALL,+ } as never);+ expect(collection.getRanges()).toEqual([]);++ collection.setSelectedRanges([{+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ } as never]);++ collection.addRange({+ startRow: 0,+ endRow: 2,+ startColumn: 0,+ endColumn: 2,+ } as never);+ expect(collection.getRanges().length).toBeGreaterThan(0);++ const subtractSpy = vi.spyOn(Rectangle, 'subtract').mockReturnValueOnce([{+ startRow: 2,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ } as never]);+ collection.addRange({+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ } as never);+ expect(subtractSpy).toHaveBeenCalled();++ vi.spyOn(Rectangle, 'subtract').mockReturnValueOnce(undefined as never);+ collection.addRange({+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ } as never);++ collection.reset();+ expect(collection.getRanges()).toEqual([]);+ });+});diff --git a/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx b/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsxnew file mode 100644index 0000000000..52cf84916e--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx@@ -0,0 +1,73 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { CROSSHAIR_HIGHLIGHT_COLORS } from '../../services/crosshair.service';+import { CrosshairOverlay } from './CrosshairHighlight';++const mocked = vi.hoisted(() => ({+ useDependency: vi.fn(),+ useObservable: vi.fn(),+}));++vi.mock('@univerjs/ui', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');+ return {+ ...actual,+ useDependency: mocked.useDependency,+ useObservable: mocked.useObservable,+ };+});++vi.mock('@univerjs/design', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/design')>('@univerjs/design');+ return {+ ...actual,+ borderClassName: 'border-class',+ clsx: (...args: Array<string | Record<string, boolean>>) => args+ .flatMap((arg) =>+ typeof arg === 'string'+ ? [arg]+ : Object.keys(arg).filter((k) => arg[k])+ )+ .join(' '),+ };+});++vi.mock('react', async () => {+ const actual = await vi.importActual<typeof import('react')>('react');+ return {+ ...actual,+ useCallback: <T extends (...args: never[]) => unknown>(fn: T) => fn,+ };+});++describe('CrosshairOverlay', () => {+ it('should render color cells and trigger onChange', () => {+ mocked.useDependency.mockReturnValue({ color$: {} });+ mocked.useObservable.mockReturnValue(CROSSHAIR_HIGHLIGHT_COLORS[0]);+ const onChange = vi.fn();++ const element = CrosshairOverlay({ onChange });+ const children = element.props.children as Array<{ props: { onClick: () => void; style: { backgroundColor: string } } }>;++ expect(children).toHaveLength(CROSSHAIR_HIGHLIGHT_COLORS.length);+ expect(children[0].props.style.backgroundColor).toBe(CROSSHAIR_HIGHLIGHT_COLORS[0]);++ children[1].props.onClick();+ expect(onChange).toHaveBeenCalledWith(CROSSHAIR_HIGHLIGHT_COLORS[1]);+ });+});diff --git a/packages/sheets-crosshair-highlight/src/views/widgets/crosshair-highlight-shape.spec.ts b/packages/sheets-crosshair-highlight/src/views/widgets/crosshair-highlight-shape.spec.tsnew file mode 100644index 0000000000..5f3406c722--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/views/widgets/crosshair-highlight-shape.spec.ts@@ -0,0 +1,62 @@+/**+ * 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 { Rect } from '@univerjs/engine-render';+import { describe, expect, it, vi } from 'vitest';+import { SheetCrossHairHighlightShape } from './crosshair-highlight-shape';++describe('SheetCrossHairHighlightShape', () => {+ it('should set shape props and draw rectangle with rgba color', () => {+ const drawKey = '_draw';+ const drawSpy = vi.spyOn(Rect, 'drawWith').mockImplementation(() => undefined);+ const emptyShape = new SheetCrossHairHighlightShape('shape-empty');+ emptyShape.setShapeProps({+ color: { r: 7, g: 8, b: 9 },+ width: 1,+ height: 1,+ });+ (emptyShape as unknown as Record<string, (ctx: unknown) => void>)[drawKey]({} as never);++ const shape = new SheetCrossHairHighlightShape('shape-1', {+ color: { r: 1, g: 2, b: 3, a: 0.4 },+ width: 20,+ height: 10,+ left: 0,+ top: 0,+ zIndex: 1,+ evented: false,+ });++ shape.setShapeProps({ width: 30, height: 15 });+ (shape as unknown as Record<string, (ctx: unknown) => void>)[drawKey]({} as never);++ expect(drawSpy).toHaveBeenCalledWith(+ {} as never,+ expect.objectContaining({+ width: shape.width,+ height: shape.height,+ fill: 'rgba(1, 2, 3, 0.4)',+ strokeWidth: 0,+ })+ );+ expect(drawSpy).toHaveBeenCalledWith(+ {} as never,+ expect.objectContaining({+ fill: 'rgba(7, 8, 9, 0.5)',+ })+ );+ });+});diff --git a/packages/sheets-crosshair-highlight/src/views/widgets/crosshair-highlight.render-controller.spec.ts b/packages/sheets-crosshair-highlight/src/views/widgets/crosshair-highlight.render-controller.spec.tsnew file mode 100644index 0000000000..6a7ecab44c--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/views/widgets/crosshair-highlight.render-controller.spec.ts@@ -0,0 +1,192 @@+/**+ * 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 { RANGE_TYPE } from '@univerjs/core';+import { BehaviorSubject, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SheetCrosshairHighlightRenderController } from './crosshair-highlight.render-controller';++const mockShapes: Array<{ dispose: ReturnType<typeof vi.fn>; props: Record<string, unknown> }> = [];++vi.mock('@univerjs/sheets-ui', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/sheets-ui')>('@univerjs/sheets-ui');+ return {+ ...actual,+ getCoordByCell: vi.fn((row: number, col: number) => ({+ startX: row * 10 + col,+ startY: row * 5 + col,+ endX: row * 10 + col + 8,+ endY: row * 5 + col + 6,+ })),+ };+});++vi.mock('./crosshair-highlight-shape', () => ({+ SheetCrossHairHighlightShape: class {+ readonly dispose = vi.fn();+ readonly props: Record<string, unknown>;++ constructor(_key: string, props: Record<string, unknown>) {+ this.props = props;+ mockShapes.push(this);+ }+ },+}));++describe('SheetCrosshairHighlightRenderController', () => {+ it('should react to selections, render shapes and clear on disable', async () => {+ mockShapes.length = 0;++ const activeSheet$ = new BehaviorSubject(0);+ const workbook = {+ activeSheet$,+ getActiveSheet: vi.fn(() => ({+ getRowCount: () => 20,+ getColumnCount: () => 10,+ })),+ };+ const scene = {+ addObject: vi.fn(),+ makeDirty: vi.fn(),+ };+ const normalSelection = {+ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ };+ const refSelection = {+ range: { startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 },+ };++ const refSelectionEnabled$ = new BehaviorSubject(false);+ const enabled$ = new BehaviorSubject(false);+ const color$ = new BehaviorSubject('rgba(10,20,30,0.6)');+ const skeleton = { a: 1 };+ const currentSkeleton$ = new BehaviorSubject(skeleton);++ const selectionMoveStart$ = new Subject<unknown>();+ const selectionMoving$ = new Subject<unknown>();+ const selectionMoveEnd$ = new Subject<unknown>();+ const selectionSet$ = new Subject<unknown>();+ const refSelectionMoveStart$ = new Subject<unknown>();+ const refSelectionMoving$ = new Subject<unknown>();+ const refSelectionMoveEnd$ = new Subject<unknown>();++ const controller = new SheetCrosshairHighlightRenderController(+ {+ unit: workbook,+ scene,+ } as never,+ {+ currentSkeleton$,+ getCurrentSkeleton: vi.fn(() => skeleton),+ } as never,+ {+ selectionMoveStart$,+ selectionMoving$,+ selectionMoveEnd$,+ selectionSet$,+ getCurrentSelections: vi.fn(() => [normalSelection]),+ } as never,+ {+ enabled$,+ color$,+ } as never,+ {+ subscribeContextValue$: vi.fn(() => refSelectionEnabled$.asObservable()),+ } as never,+ {+ selectionMoveStart$: refSelectionMoveStart$,+ selectionMoving$: refSelectionMoving$,+ selectionMoveEnd$: refSelectionMoveEnd$,+ getCurrentSelections: vi.fn(() => [refSelection]),+ } as never+ );++ const addSelectionSpy = vi.spyOn(controller, 'addSelection');+ const clearSpy = vi.spyOn(controller as never, '_clear');++ enabled$.next(true);+ activeSheet$.next(1);+ expect(addSelectionSpy).toHaveBeenCalled();+ expect(scene.addObject).toHaveBeenCalled();+ expect(scene.makeDirty).toHaveBeenCalledWith(true);++ refSelectionEnabled$.next(true);+ activeSheet$.next(2);+ expect(addSelectionSpy).toHaveBeenCalledWith(refSelection.range, expect.anything());++ enabled$.next(false);+ activeSheet$.next(3);+ expect(clearSpy).toHaveBeenCalled();++ controller.addSelection(+ {+ rangeType: RANGE_TYPE.COLUMN,+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ } as never,+ workbook.getActiveSheet() as never+ );++ controller.addSelection(+ {+ startRow: 2,+ endRow: 2,+ startColumn: 2,+ endColumn: 2,+ } as never,+ workbook.getActiveSheet() as never+ );++ (controller as unknown as { _transformSelection: (value: unknown, sheet: unknown) => void })._transformSelection(+ null,+ workbook.getActiveSheet()+ );+ (controller as unknown as { _transformSelection: (value: unknown, sheet: unknown) => void })._transformSelection(+ [{+ range: {+ startRow: 0,+ endRow: 19,+ startColumn: 0,+ endColumn: 0,+ },+ }],+ workbook.getActiveSheet()+ );++ const preShape = { dispose: vi.fn() };+ (controller as unknown as { _shapes: Array<{ dispose: () => void }> })._shapes = [preShape];+ (controller as unknown as { _clear: () => void })._clear();+ expect(preShape.dispose).toHaveBeenCalledTimes(1);++ controller.addSelection(+ {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ } as never,+ workbook.getActiveSheet() as never+ );++ (controller as unknown as { _sheetSkeletonManagerService: { getCurrentSkeleton: () => unknown } })._sheetSkeletonManagerService.getCurrentSkeleton = () => null;+ controller.render([{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } as never]);+ expect(scene.makeDirty).toHaveBeenCalledWith(true);++ await controller.dispose();+ });+});diff --git a/packages/sheets-data-validation-ui/src/services/__tests__/data-validation-panel.service.spec.ts b/packages/sheets-data-validation-ui/src/services/__tests__/data-validation-panel.service.spec.tsnew file mode 100644index 0000000000..f3a29020c8--- /dev/null+++ b/packages/sheets-data-validation-ui/src/services/__tests__/data-validation-panel.service.spec.ts@@ -0,0 +1,125 @@+/**+ * 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 { IDataValidationRule, IUniverInstanceService, Nullable, UnitModel } from '@univerjs/core';+import type { ISidebarMethodOptions, ISidebarService } from '@univerjs/ui';+import type { Observable } from 'rxjs';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { DATA_VALIDATION_PANEL } from '../../commands/operations/data-validation.operation';+import { DataValidationPanelService } from '../data-validation-panel.service';++type SidebarOptions = ISidebarMethodOptions;+type UniverInstanceServiceStub = Pick<IUniverInstanceService, 'getCurrentTypeOfUnit$'>;+type SidebarServiceStub = Pick<ISidebarService, 'sidebarOptions$'>;++describe('DataValidationPanelService', () => {+ let sheet$ = new Subject<unknown>();+ let sidebarOptions$ = new BehaviorSubject<SidebarOptions>({ visible: true });++ beforeEach(() => {+ vi.useFakeTimers();+ sheet$ = new Subject();+ sidebarOptions$ = new BehaviorSubject<SidebarOptions>({ visible: true });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ function createService() {+ const univerInstanceService: UniverInstanceServiceStub = {+ getCurrentTypeOfUnit$<T extends UnitModel<object, number>>(): Observable<Nullable<T>> {+ return sheet$.asObservable() as Observable<Nullable<T>>;+ },+ };+ const sidebarService: SidebarServiceStub = {+ sidebarOptions$,+ };++ return new DataValidationPanelService(+ univerInstanceService as unknown as IUniverInstanceService,+ sidebarService as unknown as ISidebarService+ );+ }++ it('tracks open state, active rules, and runs close disposables exactly once', () => {+ const service = createService();+ const openStates: boolean[] = [];+ const activeRules: Array<Nullable<{ unitId: string; subUnitId: string; rule: IDataValidationRule }>> = [];+ const disposeSpy = vi.fn();++ const openSub = service.open$.subscribe((value) => openStates.push(value));+ const activeSub = service.activeRule$.subscribe((value) => activeRules.push(value));++ service.setCloseDisposable({ dispose: disposeSpy });+ service.open();+ service.setActiveRule({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ rule: { uid: 'rule-1' } as IDataValidationRule,+ });+ service.close();+ service.close();++ expect(service.isOpen).toBe(false);+ expect(service.activeRule).toEqual({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ rule: { uid: 'rule-1' },+ });+ expect(openStates).toEqual([false, true, false]);+ expect(activeRules).toEqual([+ undefined,+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ rule: { uid: 'rule-1' },+ },+ ]);+ expect(disposeSpy).toHaveBeenCalledTimes(1);++ openSub.unsubscribe();+ activeSub.unsubscribe();+ service.dispose();+ });++ it('closes automatically when the current sheet disappears', () => {+ const service = createService();++ service.open();+ sheet$.next(null);++ expect(service.isOpen).toBe(false);++ service.dispose();+ });++ it('re-emits a hidden sidebar state after the data validation panel closes', async () => {+ const service = createService();++ sidebarOptions$.next({+ id: DATA_VALIDATION_PANEL,+ visible: false,+ });++ await vi.runAllTimersAsync();++ expect(sidebarOptions$.getValue()).toEqual({ visible: false });++ service.dispose();+ });+});diff --git a/packages/sheets-data-validation/src/commands/commands/__tests__/data-validation.command.spec.ts b/packages/sheets-data-validation/src/commands/commands/__tests__/data-validation.command.spec.tsnew file mode 100644index 0000000000..fb6645a335--- /dev/null+++ b/packages/sheets-data-validation/src/commands/commands/__tests__/data-validation.command.spec.ts@@ -0,0 +1,177 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { DataValidationType, IUniverInstanceService } from '@univerjs/core';+import { AddDataValidationMutation, DataValidatorRegistryService, RemoveDataValidationMutation, UpdateDataValidationMutation, UpdateRuleType } from '@univerjs/data-validation';+import { LexerTreeBuilder } from '@univerjs/engine-formula';+import { SetRangeValuesMutation } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { SheetDataValidationModel } from '../../../models/sheet-data-validation-model';+import { getDataValidationDiffMutations } from '../data-validation.command';++function createAccessor(withTarget = true, offset = true) {+ const worksheet = {+ getSheetId: () => 'sheet-1',+ getCellMatrix: vi.fn(() => ({+ getValue: vi.fn(() => ({})),+ })),+ getCellRaw: vi.fn((row: number, col: number) => {+ if (row === 0 && col === 0) {+ return { v: '' };+ }++ return { v: '0' };+ }),+ };+ const workbook = {+ getUnitId: () => 'unit-1',+ getStyles: vi.fn(() => ({+ getStyleByCell: vi.fn(() => null),+ })),+ getSheetBySheetId: vi.fn(() => (withTarget ? worksheet : null)),+ getActiveSheet: vi.fn(() => worksheet),+ };+ const sheetDataValidationModel = {+ getRuleById: vi.fn((_unitId: string, _subUnitId: string, ruleId: string) => ({+ uid: ruleId,+ type: DataValidationType.CHECKBOX,+ formula1: '=A1',+ formula2: '=B1',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }],+ })),+ getValidator: vi.fn(() => ({+ parseFormulaSync: vi.fn(() => ({ formula2: '0', originFormula2: '0' })),+ })),+ };++ return {+ worksheet,+ accessor: {+ get(token: unknown) {+ if (token === LexerTreeBuilder) {+ return {+ moveFormulaRefOffset: vi.fn((formula: string, col: number, row: number) => `${formula}:${col},${row}`),+ };+ }+ if (token === DataValidatorRegistryService) {+ return {+ getValidatorItem: vi.fn(() => ({ offsetFormulaByRange: offset })),+ };+ }+ if (token === SheetDataValidationModel) {+ return sheetDataValidationModel;+ }+ if (token === IUniverInstanceService) {+ return {+ getUnit: vi.fn(() => (withTarget ? workbook : null)),+ getCurrentUnitOfType: vi.fn(() => workbook),+ getUniverSheetInstance: vi.fn(() => workbook),+ };+ }++ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as IAccessor,+ sheetDataValidationModel,+ };+}++describe('getDataValidationDiffMutations', () => {+ it('returns empty mutations when the target sheet cannot be resolved', () => {+ const { accessor } = createAccessor(false);++ expect(getDataValidationDiffMutations('unit-1', 'sheet-1', [], accessor)).toEqual({+ redoMutations: [],+ undoMutations: [],+ });+ });++ it('builds delete, update, and add mutations including checkbox default fills', () => {+ const { accessor } = createAccessor(true, true);+ const diffs = [+ {+ type: 'delete',+ rule: { uid: 'rule-delete', ranges: [] },+ index: 0,+ },+ {+ type: 'update',+ ruleId: 'rule-update',+ oldRanges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ newRanges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }],+ rule: {+ uid: 'rule-update',+ type: DataValidationType.CHECKBOX,+ formula1: '=A1',+ formula2: '=B1',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ },+ },+ {+ type: 'add',+ rule: {+ uid: 'rule-add',+ type: DataValidationType.CHECKBOX,+ formula1: '=A1',+ formula2: '=B1',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }],+ },+ },+ ] as any;++ const { redoMutations, undoMutations } = getDataValidationDiffMutations('unit-1', 'sheet-1', diffs, accessor);++ expect(redoMutations.map((m) => m.id)).toEqual([+ RemoveDataValidationMutation.id,+ UpdateDataValidationMutation.id,+ AddDataValidationMutation.id,+ SetRangeValuesMutation.id,+ ]);+ expect((redoMutations[1].params as any).payload.type).toBe(UpdateRuleType.ALL);+ expect((redoMutations[3].params as any).cellValue).toBeTruthy();+ expect(undoMutations.map((m) => m.id)).toContain(AddDataValidationMutation.id);+ expect(undoMutations.map((m) => m.id)).toContain(RemoveDataValidationMutation.id);+ expect(undoMutations.map((m) => m.id)).toContain(UpdateDataValidationMutation.id);+ expect(undoMutations.map((m) => m.id)).toContain(SetRangeValuesMutation.id);+ });++ it('uses range-only updates when formulas do not offset or default filling is disabled', () => {+ const { accessor } = createAccessor(true, false);+ const diffs = [+ {+ type: 'update',+ ruleId: 'rule-update',+ oldRanges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ newRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ rule: {+ uid: 'rule-update',+ type: DataValidationType.DECIMAL,+ formula1: '1',+ formula2: '2',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ },+ },+ ] as any;++ const { redoMutations, undoMutations } = getDataValidationDiffMutations('unit-1', 'sheet-1', diffs, accessor, 'command', false);++ expect(redoMutations).toHaveLength(1);+ expect((redoMutations[0].params as any).payload.type).toBe(UpdateRuleType.RANGE);+ expect(undoMutations).toHaveLength(1);+ expect((undoMutations[0].params as any).payload.type).toBe(UpdateRuleType.RANGE);+ });+});diff --git a/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.ts b/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.tsnew file mode 100644index 0000000000..5db6fc485b--- /dev/null+++ b/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.ts@@ -0,0 +1,145 @@+/**+ * 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 { IRange, ISheetDataValidationRule, IUniverInstanceService, Workbook, Worksheet } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { RuleMatrix } from '../rule-matrix';++function createRule(uid: string, ranges: IRange[]): ISheetDataValidationRule {+ return {+ uid,+ type: 'decimal',+ ranges,+ } as ISheetDataValidationRule;+}++function createMatrix(initial: Map<string, IRange[]> = new Map()) {+ const worksheet = {+ getMaxColumns: () => 20,+ getMaxRows: () => 20,+ } as unknown as Worksheet;+ const workbook = {+ getSheetBySheetId: () => worksheet,+ } as unknown as Workbook;+ const univerInstanceService = {+ getUnit: () => workbook,+ } as unknown as IUniverInstanceService;++ return new RuleMatrix(initial, 'unit-1', 'sheet-1', univerInstanceService);+}++describe('RuleMatrix', () => {+ it('overwrites overlapped cells with the latest rule and supports lookups', () => {+ const matrix = createMatrix();++ matrix.addRule(createRule('rule-1', [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }]));+ matrix.addRule(createRule('rule-2', [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }]));++ expect(matrix.getValue(0, 0)).toBe('rule-1');+ expect(matrix.getValue(1, 1)).toBe('rule-2');+ expect(matrix.getValue(2, 2)).toBe('rule-2');+ expect(matrix.getValue(5, 5)).toBeUndefined();+ });++ it('updates, removes, and merges rule ranges correctly', () => {+ const matrix = createMatrix(new Map([+ ['rule-1', [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]],+ ['rule-2', [{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }]],+ ]));++ matrix.updateRange('rule-1', [{ startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 }]);+ expect(matrix.getValue(0, 0)).toBeUndefined();+ expect(matrix.getValue(3, 3)).toBe('rule-1');++ matrix.addRangeRules([+ {+ id: 'rule-1',+ ranges: [+ { startRow: 4, endRow: 4, startColumn: 4, endColumn: 4 },+ { startRow: 4, endRow: 4, startColumn: 5, endColumn: 5 },+ ],+ },+ ]);+ expect(matrix.getValue(4, 4)).toBe('rule-1');+ expect(matrix.getValue(4, 5)).toBe('rule-1');++ matrix.removeRange([{ startRow: 4, endRow: 4, startColumn: 5, endColumn: 5 }]);+ expect(matrix.getValue(4, 4)).toBe('rule-1');+ expect(matrix.getValue(4, 5)).toBeUndefined();++ matrix.removeRule(createRule('rule-2', []));+ expect(matrix.getValue(2, 2)).toBeUndefined();+ });++ it('reports update, delete, add mutations and clones independently', () => {+ const ranges1 = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }];+ const ranges2 = [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }];+ const matrix = createMatrix(new Map([+ ['rule-1', ranges1],+ ['rule-2', ranges2],+ ]));++ const cloned = matrix.clone();+ cloned.updateRange('rule-1', [{ startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 }]);++ expect(matrix.getValue(0, 0)).toBe('rule-1');++ const baseRules = [+ createRule('rule-1', ranges1),+ createRule('rule-2', ranges2),+ ];++ cloned.removeRule(createRule('rule-2', ranges2));++ expect(cloned.diff(baseRules)).toEqual([+ {+ type: 'update',+ ruleId: 'rule-1',+ oldRanges: ranges1,+ newRanges: [{ startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 }],+ rule: baseRules[0],+ },+ {+ type: 'delete',+ rule: baseRules[1],+ index: 1,+ },+ ]);++ expect(cloned.diffWithAddition(baseRules, [createRule('rule-3', [{ startRow: 6, endRow: 6, startColumn: 6, endColumn: 6 }])].values())).toEqual([+ {+ type: 'update',+ ruleId: 'rule-1',+ oldRanges: ranges1,+ newRanges: [{ startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 }],+ rule: baseRules[0],+ },+ {+ type: 'delete',+ rule: baseRules[1],+ index: 1,+ },+ {+ type: 'add',+ rule: {+ uid: 'rule-3',+ type: 'decimal',+ ranges: [],+ },+ },+ ]);+ });+});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.tsnew file mode 100644index 0000000000..f298fd8e62--- /dev/null+++ b/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.ts@@ -0,0 +1,134 @@+/**+ * 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 { ICommandService, IRange, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';+import type { DataValidationModel } from '@univerjs/data-validation';+import { RemoveSheetMutation, SetRangeValuesMutation } from '@univerjs/sheets';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { DataValidationCacheService } from '../dv-cache.service';++function createRule(ranges: IRange[]) {+ return { uid: 'rule-1', ranges } as any;+}++function createService(ruleRanges: IRange[] = [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }]) {+ const commandCallbacks: Array<(info: { id: string; params: unknown }, options?: { onlyLocal?: boolean }) => void> = [];+ const unitDisposed$ = new Subject<any>();+ const commandService = {+ onCommandExecuted: vi.fn((callback) => {+ commandCallbacks.push(callback);+ return { dispose: vi.fn() };+ }),+ } as unknown as ICommandService;+ const univerInstanceService = {+ unitDisposed$,+ } as unknown as IUniverInstanceService;+ const dataValidationModel = {+ getRules: vi.fn(() => [createRule(ruleRanges)]),+ } as unknown as DataValidationModel;++ return {+ commandCallbacks,+ unitDisposed$,+ service: new DataValidationCacheService(commandService, univerInstanceService, dataValidationModel),+ };+}++describe('DataValidationCacheService', () => {+ it('creates caches, marks dirty ranges, and removes cached values by rule ranges', () => {+ const { service } = createService();+ const dirty: Array<{ unitId: string; subUnitId: string; ranges: IRange[]; isSetRange?: boolean }> = [];+ const sub = service.dirtyRanges$.subscribe((value) => dirty.push(value));+ const cache = service.ensureCache('unit-1', 'sheet-1');++ cache.setValue(1, 1, 2 as never);+ cache.setValue(2, 2, 3 as never);++ service.markRangeDirty('unit-1', 'sheet-1', [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }], true);+ expect(service.getValue('unit-1', 'sheet-1', 1, 1)).toBeUndefined();++ service.addRule('unit-1', 'sheet-1', createRule([{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }]));+ service.removeRule('unit-1', 'sheet-1', createRule([{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }]));++ expect(service.getValue('unit-1', 'sheet-1', 2, 2)).toBeUndefined();+ expect(dirty).toEqual([+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }],+ isSetRange: true,+ },+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }],+ },+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [{ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }],+ },+ ]);++ sub.unsubscribe();+ service.dispose();+ });++ it('reacts to set-range, remove-sheet, and unit-dispose events', () => {+ const { service, commandCallbacks, unitDisposed$ } = createService();+ const cache = service.ensureCache('unit-1', 'sheet-1');+ cache.setValue(1, 1, 1 as never);+ cache.setValue(5, 5, 1 as never);++ commandCallbacks[0](+ {+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ cellValue: {+ 0: { 0: { v: 'x' } },+ 1: { 1: { v: 'y' } },+ },+ },+ },+ undefined+ );++ expect(service.getValue('unit-1', 'sheet-1', 1, 1)).toBeUndefined();+ expect(service.getValue('unit-1', 'sheet-1', 5, 5)).toBe(1);++ commandCallbacks[1]({+ id: RemoveSheetMutation.id,+ params: {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ },+ });++ const recreated = service.ensureCache('unit-1', 'sheet-1');+ expect(recreated).not.toBe(cache);++ const unitCache = service.ensureCache('unit-1', 'sheet-2');+ unitCache.setValue(0, 0, 9 as never);+ unitDisposed$.next({ type: 2, getUnitId: () => 'unit-1' });++ expect(service.ensureCache('unit-1', 'sheet-2')).not.toBe(unitCache as ObjectMatrix<any>);++ service.dispose();+ });+});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.tsnew file mode 100644index 0000000000..d50348b8c1--- /dev/null+++ b/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.ts@@ -0,0 +1,133 @@+/**+ * 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 { IUniverInstanceService } from '@univerjs/core';+import type { DataValidationModel, DataValidatorRegistryService } from '@univerjs/data-validation';+import type { RegisterOtherFormulaService } from '@univerjs/engine-formula';+import type { DataValidationCacheService } from '../dv-cache.service';+import { DataValidationType, UniverInstanceType } from '@univerjs/core';+import { OtherFormulaBizType } from '@univerjs/engine-formula';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { DataValidationCustomFormulaService } from '../dv-custom-formula.service';++describe('DataValidationCustomFormulaService', () => {+ it('registers offset formulas, reads cell results, marks dirty ranges, and deletes formula ids', async () => {+ const formulaResult$ = new Subject<any>();+ const dirtyRanges$ = new Subject<any>();+ const registerOtherFormulaService = {+ formulaResult$,+ registerFormulaWithRange: vi.fn((unitId: string, subUnitId: string, formula: string, _ranges, extra) => `${extra.ruleId}-${formula}`),+ deleteFormula: vi.fn(),+ getFormulaValue: vi.fn(async () => ({ result: [[[[{ v: 1 }]], [[{ v: 2 }]]], [[[{ v: 3 }]], [[{ v: 4 }]]]] })),+ getFormulaValueSync: vi.fn(() => ({ result: [[[[{ v: 1 }]], [[{ v: 2 }]]], [[[{ v: 3 }]], [[{ v: 4 }]]]] })),+ markFormulaDirty: vi.fn(),+ } as unknown as RegisterOtherFormulaService;+ const rule = {+ uid: 'rule-1',+ type: DataValidationType.DATE,+ formula1: '=A1',+ formula2: '=B1',+ ranges: [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }],+ } as any;+ const dataValidationModel = {+ getRuleById: vi.fn(() => rule),+ getRules: vi.fn(() => [rule]),+ } as unknown as DataValidationModel;+ const cacheService = {+ dirtyRanges$,+ markRangeDirty: vi.fn(),+ } as unknown as DataValidationCacheService;+ const service = new DataValidationCustomFormulaService(+ { getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET) } as unknown as IUniverInstanceService,+ registerOtherFormulaService,+ dataValidationModel,+ cacheService,+ { getValidatorItem: vi.fn(() => ({ offsetFormulaByRange: true })) } as unknown as DataValidatorRegistryService+ );++ service.addRule('unit-1', 'sheet-1', rule);++ expect(registerOtherFormulaService.registerFormulaWithRange).toHaveBeenCalledWith(+ 'unit-1',+ 'sheet-1',+ '=A1',+ rule.ranges,+ { ruleId: 'rule-1' },+ OtherFormulaBizType.DATA_VALIDATION_CUSTOM,+ 'rule-1'+ );+ expect(service.getRuleFormulaInfo('unit-1', 'sheet-1', 'rule-1')).toEqual({+ formula: '=A1',+ originCol: 1,+ originRow: 1,+ formulaId: 'rule-1-=A1',+ });++ await expect(service.getCellFormulaValue('unit-1', 'sheet-1', 'rule-1', 2, 2)).resolves.toEqual({ v: 4 });+ await expect(service.getCellFormula2Value('unit-1', 'sheet-1', 'rule-1', 1, 2)).resolves.toEqual({ v: 2 });+ expect(service.getCellFormulaValueSync('unit-1', 'sheet-1', 'rule-1', 1, 1)).toEqual({ v: 1 });+ expect(service.getCellFormula2ValueSync('unit-1', 'sheet-1', 'rule-1', 2, 1)).toEqual({ v: 3 });++ formulaResult$.next({+ 'unit-1': {+ 'sheet-1': [{ extra: { ruleId: 'rule-1' } }],+ },+ });+ expect(cacheService.markRangeDirty).toHaveBeenCalledWith('unit-1', 'sheet-1', rule.ranges);++ dirtyRanges$.next({ unitId: 'unit-1', subUnitId: 'sheet-1', ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }], isSetRange: true });+ expect(registerOtherFormulaService.markFormulaDirty).toHaveBeenCalledWith('unit-1', 'sheet-1', 'rule-1-=A1');+ expect(registerOtherFormulaService.markFormulaDirty).toHaveBeenCalledWith('unit-1', 'sheet-1', 'rule-1-=B1');++ service.deleteByRuleId('unit-1', 'sheet-1', 'rule-1');+ expect(registerOtherFormulaService.deleteFormula).toHaveBeenCalledWith('unit-1', 'sheet-1', ['rule-1-=A1']);+ expect(registerOtherFormulaService.deleteFormula).toHaveBeenCalledWith('unit-1', 'sheet-1', ['rule-1-=B1']);++ service.dispose();+ });++ it('skips non-offset rules and returns undefined for missing formulas', async () => {+ const service = new DataValidationCustomFormulaService(+ { getUnitType: vi.fn(() => UniverInstanceType.UNIVER_DOC) } as unknown as IUniverInstanceService,+ {+ formulaResult$: new Subject<any>(),+ registerFormulaWithRange: vi.fn(),+ deleteFormula: vi.fn(),+ getFormulaValue: vi.fn(),+ getFormulaValueSync: vi.fn(),+ markFormulaDirty: vi.fn(),+ } as unknown as RegisterOtherFormulaService,+ {+ getRuleById: vi.fn(() => null),+ getRules: vi.fn(() => []),+ } as unknown as DataValidationModel,+ {+ dirtyRanges$: new Subject<any>(),+ markRangeDirty: vi.fn(),+ } as unknown as DataValidationCacheService,+ { getValidatorItem: vi.fn(() => ({ offsetFormulaByRange: false })) } as unknown as DataValidatorRegistryService+ );++ service.addRule('unit-1', 'sheet-1', { uid: 'rule-2', type: DataValidationType.DECIMAL, formula1: '=A1', ranges: [] } as any);++ await expect(service.getCellFormulaValue('unit-1', 'sheet-1', 'missing', 0, 0)).resolves.toBeUndefined();+ await expect(service.getCellFormula2Value('unit-1', 'sheet-1', 'missing', 0, 0)).resolves.toBeUndefined();+ expect(service.getCellFormulaValueSync('unit-1', 'sheet-1', 'missing', 0, 0)).toBeUndefined();+ expect(service.getCellFormula2ValueSync('unit-1', 'sheet-1', 'missing', 0, 0)).toBeUndefined();+ service.deleteByRuleId('unit-1', 'sheet-1', 'missing');+ });+});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-formula.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-formula.service.spec.tsnew file mode 100644index 0000000000..640100b828--- /dev/null+++ b/packages/sheets-data-validation/src/services/__tests__/dv-formula.service.spec.ts@@ -0,0 +1,148 @@+/**+ * 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 { IUniverInstanceService } from '@univerjs/core';+import type { DataValidationModel, DataValidatorRegistryService } from '@univerjs/data-validation';+import type { RegisterOtherFormulaService } from '@univerjs/engine-formula';+import type { DataValidationCacheService } from '../dv-cache.service';+import type { DataValidationListCacheService } from '../dv-list-cache.service';+import { DataValidationType, UniverInstanceType } from '@univerjs/core';+import { OtherFormulaBizType } from '@univerjs/engine-formula';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { DataValidationFormulaService } from '../dv-formula.service';++describe('DataValidationFormulaService', () => {+ it('registers formula rules, fetches results, removes them, and reacts to formula result changes', async () => {+ const formulaResult$ = new Subject<any>();+ const registerOtherFormulaService = {+ formulaResult$,+ registerFormulaWithRange: vi.fn((unitId: string, subUnitId: string, formula: string, _ranges, extra) => `${extra.ruleId}-${formula}`),+ deleteFormula: vi.fn(),+ getFormulaValue: vi.fn(async (_unitId: string, _subUnitId: string, id: string) => ({ id })),+ getFormulaValueSync: vi.fn((_unitId: string, _subUnitId: string, id: string) => ({ id })),+ } as unknown as RegisterOtherFormulaService;+ const cacheService = {+ markRangeDirty: vi.fn(),+ } as unknown as DataValidationCacheService;+ const listCacheService = {+ markRuleDirty: vi.fn(),+ } as unknown as DataValidationListCacheService;+ const rule = {+ uid: 'rule-1',+ type: DataValidationType.DECIMAL,+ formula1: '=A1',+ formula2: '=B1',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ } as any;+ const dataValidationModel = {+ getRuleById: vi.fn(() => rule),+ } as unknown as DataValidationModel;+ const validatorRegistryService = {+ getValidatorItem: vi.fn(() => ({ offsetFormulaByRange: false })),+ } as unknown as DataValidatorRegistryService;+ const instanceService = {+ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET),+ } as unknown as IUniverInstanceService;++ const service = new DataValidationFormulaService(+ instanceService,+ registerOtherFormulaService,+ cacheService,+ dataValidationModel,+ validatorRegistryService,+ listCacheService+ );++ service.addRule('unit-1', 'sheet-1', rule);++ expect(registerOtherFormulaService.registerFormulaWithRange).toHaveBeenCalledWith(+ 'unit-1',+ 'sheet-1',+ '=A1',+ [{ startColumn: 0, endColumn: 0, startRow: 0, endRow: 0 }],+ { ruleId: 'rule-1' },+ OtherFormulaBizType.DATA_VALIDATION,+ 'rule-1'+ );+ expect(service.getRuleFormulaInfo('unit-1', 'sheet-1', 'rule-1')).toEqual([+ { id: 'rule-1-=A1', text: '=A1' },+ { id: 'rule-1-=B1', text: '=B1' },+ ]);++ await expect(service.getRuleFormulaResult('unit-1', 'sheet-1', 'rule-1')).resolves.toEqual([+ { id: 'rule-1-=A1' },+ { id: 'rule-1-=B1' },+ ]);+ expect(service.getRuleFormulaResultSync('unit-1', 'sheet-1', 'rule-1')).toEqual([+ { id: 'rule-1-=A1' },+ { id: 'rule-1-=B1' },+ ]);++ formulaResult$.next({+ 'unit-1': {+ 'sheet-1': [+ { extra: { ruleId: 'rule-1' } },+ ],+ },+ });++ expect(listCacheService.markRuleDirty).toHaveBeenCalledWith('unit-1', 'sheet-1', 'rule-1');+ expect(cacheService.markRangeDirty).toHaveBeenCalledWith('unit-1', 'sheet-1', rule.ranges);++ service.removeRule('unit-1', 'sheet-1', 'rule-1');+ expect(registerOtherFormulaService.deleteFormula).toHaveBeenCalledWith('unit-1', 'sheet-1', ['rule-1-=A1', 'rule-1-=B1']);+ });++ it('skips registration for non-formula rules, checkbox rules, and missing entries', async () => {+ const formulaResult$ = new Subject<any>();+ const registerOtherFormulaService = {+ formulaResult$,+ registerFormulaWithRange: vi.fn(),+ deleteFormula: vi.fn(),+ getFormulaValue: vi.fn(),+ getFormulaValueSync: vi.fn(),+ } as unknown as RegisterOtherFormulaService;++ const service = new DataValidationFormulaService(+ { getUnitType: vi.fn(() => UniverInstanceType.UNIVER_DOC) } as unknown as IUniverInstanceService,+ registerOtherFormulaService,+ { markRangeDirty: vi.fn() } as unknown as DataValidationCacheService,+ { getRuleById: vi.fn(() => null) } as unknown as DataValidationModel,+ { getValidatorItem: vi.fn(() => ({ offsetFormulaByRange: true })) } as unknown as DataValidatorRegistryService,+ { markRuleDirty: vi.fn() } as unknown as DataValidationListCacheService+ );++ service.addRule('unit-1', 'sheet-1', {+ uid: 'rule-2',+ type: DataValidationType.DECIMAL,+ formula1: '1',+ formula2: '2',+ } as any);+ service.addRule('unit-1', 'sheet-1', {+ uid: 'rule-3',+ type: DataValidationType.CHECKBOX,+ formula1: '=A1',+ formula2: '=B1',+ } as any);++ expect(registerOtherFormulaService.registerFormulaWithRange).not.toHaveBeenCalled();+ await expect(service.getRuleFormulaResult('unit-1', 'sheet-1', 'missing')).resolves.toBeNull();+ expect(service.getRuleFormulaResultSync('unit-1', 'sheet-1', 'missing')).toBeUndefined();+ service.removeRule('unit-1', 'sheet-1', 'missing');+ expect(registerOtherFormulaService.deleteFormula).not.toHaveBeenCalled();+ });+});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-list-cache.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-list-cache.service.spec.tsnew file mode 100644index 0000000000..d814896cd9--- /dev/null+++ b/packages/sheets-data-validation/src/services/__tests__/dv-list-cache.service.spec.ts@@ -0,0 +1,98 @@+/**+ * 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 { Injector } from '@univerjs/core';+import type { DataValidationModel } from '@univerjs/data-validation';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { DataValidationFormulaService } from '../dv-formula.service';+import { DataValidationListCacheService } from '../dv-list-cache.service';++describe('DataValidationListCacheService', () => {+ it('computes, caches, invalidates, and clears list items', () => {+ const ruleChange$ = new Subject<any>();+ const formulaService = {+ getRuleFormulaResultSync: vi.fn(() => [+ { result: [[[[{ v: 'A' }, { v: 'B' }, { v: '#VALUE!' }, { v: 1, s: { n: { pattern: '0.00' } } }]]]] },+ ]),+ };+ const injector = {+ get(token: unknown) {+ if (token === DataValidationFormulaService) {+ return formulaService;+ }++ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as unknown as Injector;+ const dataValidationModel = {+ ruleChange$,+ } as unknown as DataValidationModel;++ const service = new DataValidationListCacheService(injector, dataValidationModel);+ const rule = {+ uid: 'rule-1',+ formula1: '=A1',+ formula2: '#f00,#0f0,#00f',+ } as any;++ const first = service.getOrCompute('unit-1', 'sheet-1', rule);+ expect(first.list).toEqual(['A', 'B', '1.00']);+ expect(first.listWithColor).toEqual([+ { label: 'A', color: '#f00' },+ { label: 'B', color: '#0f0' },+ { label: '1.00', color: '#00f' },+ ]);+ expect(first.colorMap).toEqual({ A: '#f00', B: '#0f0', '1.00': '#00f' });+ expect(first.set.has('A')).toBe(true);++ expect(service.getOrCompute('unit-1', 'sheet-1', rule)).toBe(first);+ expect(formulaService.getRuleFormulaResultSync).toHaveBeenCalledTimes(1);++ service.markRuleDirty('unit-1', 'sheet-1', 'rule-1');+ expect(service.getCache('unit-1', 'sheet-1', 'rule-1')).toBeUndefined();++ service.setCache('unit-1', 'sheet-1', 'rule-2', first);+ expect(service.getCache('unit-1', 'sheet-1', 'rule-2')).toBe(first);++ ruleChange$.next({ type: 'remove', unitId: 'unit-1', subUnitId: 'sheet-1', rule: { uid: 'rule-2' } });+ expect(service.getCache('unit-1', 'sheet-1', 'rule-2')).toBeUndefined();++ service.clear();+ expect(service.getCache('unit-1', 'sheet-1', 'rule-1')).toBeUndefined();+ });++ it('supports non-formula lists and update invalidation', () => {+ const ruleChange$ = new Subject<any>();+ const service = new DataValidationListCacheService(+ {+ get() {+ return {+ getRuleFormulaResultSync: vi.fn(),+ };+ },+ } as unknown as Injector,+ { ruleChange$ } as unknown as DataValidationModel+ );++ const item = service.computeAndCache('unit-1', 'sheet-1', { uid: 'rule-3', formula1: 'x,y,,z', formula2: '' } as any, null);+ expect(item.list).toEqual(['x', 'y', 'z']);+ expect(item.colorMap).toEqual({});++ ruleChange$.next({ type: 'update', unitId: 'unit-1', subUnitId: 'sheet-1', rule: { uid: 'rule-3' } });+ expect(service.getCache('unit-1', 'sheet-1', 'rule-3')).toBeUndefined();+ });+});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-validator-service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-validator-service.spec.tsnew file mode 100644index 0000000000..17f194d72f--- /dev/null+++ b/packages/sheets-data-validation/src/services/__tests__/dv-validator-service.spec.ts@@ -0,0 +1,150 @@+/**+ * 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 { IDataValidationRule, IRange, IUniverInstanceService, LifecycleService, Nullable, Workbook, Worksheet } from '@univerjs/core';+import type { ISheetLocation } from '@univerjs/sheets';+import type { SheetDataValidationModel } from '../../models/sheet-data-validation-model';+import type { DataValidationCacheService } from '../dv-cache.service';+import { ObjectMatrix as CoreObjectMatrix, DataValidationStatus, LifecycleStages } from '@univerjs/core';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SheetsDataValidationValidatorService } from '../dv-validator-service';++function createRule(uid: string, ranges: IRange[]): IDataValidationRule {+ return { uid, ranges } as IDataValidationRule;+}++function createService() {+ const dirtyRanges$ = new Subject<{ unitId: string; subUnitId: string; ranges: IRange[] }>();+ const lifecycle$ = new BehaviorSubject(LifecycleStages.Rendered);+ const worksheet = {+ getSheetId: () => 'sheet-1',+ getMergedCell: vi.fn(() => null),+ getCell: vi.fn((row: number, col: number) => ({ v: `${row},${col}` })),+ getMaxColumns: () => 20,+ getMaxRows: () => 20,+ } as unknown as Worksheet;+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ getSheetBySheetId: vi.fn((sheetId: string) => (sheetId === 'sheet-1' ? worksheet : null)),+ } as unknown as Workbook;+ const cache = new CoreObjectMatrix<Nullable<DataValidationStatus>>();+ const rule = createRule('rule-1', [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }]);+ const model = {+ getRuleByLocation: vi.fn(() => rule),+ validator: vi.fn((_rule: IDataValidationRule, _pos: ISheetLocation, onComplete?: (status: DataValidationStatus, changed: boolean) => void) => {+ onComplete?.(DataValidationStatus.INVALID, true);+ return DataValidationStatus.INVALID;+ }),+ getRules: vi.fn(() => [rule]),+ getSubUnitIds: vi.fn(() => ['sheet-1']),+ getRuleObjectMatrix: vi.fn(() => ({+ getValue: vi.fn((row: number, col: number) => (row === 0 && col === 0 ? 'rule-1' : undefined)),+ })),+ getRuleById: vi.fn((_, __, id: string) => (id === 'rule-1' ? rule : undefined)),+ } as unknown as SheetDataValidationModel;+ const cacheService = {+ dirtyRanges$,+ getValue: vi.fn(() => DataValidationStatus.INVALID),+ ensureCache: vi.fn(() => cache),+ } as unknown as DataValidationCacheService;+ const univerInstanceService = {+ getUnit: vi.fn((unitId: string) => (unitId === 'unit-1' ? workbook : null)),+ getCurrentUnitForType: vi.fn(() => workbook),+ } as unknown as IUniverInstanceService;+ const lifecycleService = {+ lifecycle$,+ stage: LifecycleStages.Rendered,+ } as unknown as LifecycleService;++ return {+ dirtyRanges$,+ lifecycle$,+ worksheet,+ workbook,+ cache,+ model,+ cacheService,+ univerInstanceService,+ lifecycleService,+ service: new SheetsDataValidationValidatorService(univerInstanceService, model, cacheService, lifecycleService),+ };+}++describe('SheetsDataValidationValidatorService', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.stubGlobal('requestIdleCallback', (callback: IdleRequestCallback) => {+ callback({ didTimeout: false, timeRemaining: () => 1 } as IdleDeadline);+ return 1;+ });+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ });++ it('validates single cells, merged cells, ranges, worksheets, and workbooks', async () => {+ const { service, worksheet, model, cacheService } = createService();++ await expect(service.validatorCell('missing', 'sheet-1', 0, 0)).rejects.toThrow('cannot find current workbook');+ await expect(service.validatorCell('unit-1', 'missing', 0, 0)).rejects.toThrow('cannot find current worksheet');++ worksheet.getMergedCell = vi.fn(() => ({ startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 }));+ expect(await service.validatorCell('unit-1', 'sheet-1', 1, 1)).toBe(DataValidationStatus.INVALID);+ expect(model.getRuleByLocation).toHaveBeenCalledWith('unit-1', 'sheet-1', 0, 0);++ model.validator = vi.fn((_rule: IDataValidationRule, _pos: ISheetLocation, onComplete?: (status: DataValidationStatus, changed: boolean) => void) => {+ onComplete?.(DataValidationStatus.VALIDATING, true);+ return DataValidationStatus.VALIDATING;+ });+ const rangeStatuses = await service.validatorRanges('unit-1', 'sheet-1', [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]);+ expect(rangeStatuses).toEqual([[DataValidationStatus.INVALID]]);++ expect(await service.validatorRanges('unit-1', 'sheet-1', [])).toEqual([]);+ expect(await service.validatorWorksheet('unit-1', 'sheet-1')).toBe(cacheService.ensureCache('unit-1', 'sheet-1'));+ expect(await service.validatorWorkbook('unit-1')).toEqual({+ 'sheet-1': cacheService.ensureCache('unit-1', 'sheet-1'),+ });+ });++ it('returns matched data validations and reacts to dirty ranges after render', async () => {+ const { service, dirtyRanges$, lifecycle$, model } = createService();+ const validatorRangesSpy = vi.spyOn(service, 'validatorRanges').mockResolvedValue([]);++ expect(service.getDataValidations('unit-1', 'sheet-1', [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }])).toEqual([+ createRule('rule-1', [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }]),+ ]);+ expect(service.getDataValidation('unit-1', 'sheet-1', [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }])?.uid).toBe('rule-1');++ dirtyRanges$.next({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ });+ lifecycle$.next(LifecycleStages.Rendered);+ await vi.runAllTimersAsync();++ expect(validatorRangesSpy).toHaveBeenCalledWith('unit-1', 'sheet-1', [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]);++ model.getRuleById = vi.fn(() => undefined);+ expect(service.getDataValidations('unit-1', 'sheet-1', [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }])).toEqual([]);++ service.dispose();+ });+});diff --git a/packages/sheets-data-validation/src/utils/__tests__/create.spec.ts b/packages/sheets-data-validation/src/utils/__tests__/create.spec.tsnew file mode 100644index 0000000000..1bf69735ae--- /dev/null+++ b/packages/sheets-data-validation/src/utils/__tests__/create.spec.ts@@ -0,0 +1,47 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { DataValidationOperator, DataValidationType } from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { createDefaultNewRule } from '../create';++describe('createDefaultNewRule', () => {+ it('uses the current selection ranges and default decimal criteria', () => {+ const accessor = {+ get(token: unknown) {+ if (token === SheetsSelectionsService) {+ return {+ getCurrentSelections: vi.fn(() => [+ { range: { startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 } },+ ]),+ };+ }++ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as IAccessor;++ const rule = createDefaultNewRule(accessor);++ expect(rule.uid).toHaveLength(6);+ expect(rule.type).toBe(DataValidationType.DECIMAL);+ expect(rule.operator).toBe(DataValidationOperator.EQUAL);+ expect(rule.formula1).toBe('100');+ expect(rule.ranges).toEqual([{ startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 }]);+ });+});diff --git a/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.ts b/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.tsnew file mode 100644index 0000000000..c68faa5931--- /dev/null+++ b/packages/sheets-data-validation/src/validators/__tests__/list-validator.spec.ts@@ -0,0 +1,63 @@+/**+ * 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 { ICellData } from '@univerjs/core';+import { LexerTreeBuilder } from '@univerjs/engine-formula';+import { describe, expect, it } from 'vitest';+import { getRuleFormulaResultSet, isValidListFormula } from '../list-validator';++describe('list-validator helpers', () => {+ it('collects formatted values and skips empty cells', () => {+ const result = getRuleFormulaResultSet([+ [+ {+ v: 1234,+ s: {+ n: {+ pattern: '#,##0.00',+ },+ },+ } as ICellData,+ {+ v: 'Alpha',+ } as ICellData,+ null,+ ],+ [+ {+ v: undefined,+ } as ICellData,+ {+ v: false,+ } as ICellData,+ ],+ ]);++ expect(result).toEqual(['1,234.00', 'Alpha', '', 'false']);+ });++ it('accepts direct references and supported helper formulas only', () => {+ const lexer = new LexerTreeBuilder();++ expect(isValidListFormula('Red,Green,Blue', lexer)).toBe(true);+ expect(isValidListFormula('=A1:A3', lexer)).toBe(true);+ expect(isValidListFormula('=IF(A1>0,B1:B3,C1:C3)', lexer)).toBe(true);+ expect(isValidListFormula('=OFFSET(A1,0,0,2,1)', lexer)).toBe(true);+ expect(isValidListFormula('=SUM(A1:A3)', lexer)).toBe(false);++ lexer.dispose();+ });+});diff --git a/packages/sheets-data-validation/src/validators/__tests__/validators.spec.ts b/packages/sheets-data-validation/src/validators/__tests__/validators.spec.tsnew file mode 100644index 0000000000..a6e2078648--- /dev/null+++ b/packages/sheets-data-validation/src/validators/__tests__/validators.spec.ts@@ -0,0 +1,240 @@+/**+ * 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 { Injector, LocaleService } from '@univerjs/core';+import { CellValueType, DataValidationOperator, WrapStrategy } from '@univerjs/core';+import { LexerTreeBuilder } from '@univerjs/engine-formula';+import { describe, expect, it, vi } from 'vitest';+import { DataValidationCustomFormulaService } from '../../services/dv-custom-formula.service';+import { DataValidationFormulaService } from '../../services/dv-formula.service';+import { DataValidationListCacheService } from '../../services/dv-list-cache.service';+import { AnyValidator } from '../any-validator';+import { CheckboxValidator, transformCheckboxValue } from '../checkbox-validator';+import { CustomFormulaValidator } from '../custom-validator';+import { DateValidator } from '../date-validator';+import { DecimalValidator, getCellValueNumber } from '../decimal-validator';+import { ListMultipleValidator } from '../list-multiple-validator';+import { TextLengthValidator } from '../text-length-validator';+import { WholeValidator } from '../whole-validator';++function createContext() {+ const localeService = {+ t: vi.fn((key: string) => key),+ } as unknown as LocaleService;+ const customFormulaService = {+ getCellFormulaValue: vi.fn(async () => ({ v: '12' })),+ getCellFormula2Value: vi.fn(async () => ({ v: '34' })),+ };+ const formulaService = {+ getRuleFormulaResult: vi.fn(async () => ([{ result: [[[[{ v: true }]]]] }, { result: [[[[{ v: false }]]]] }])),+ getRuleFormulaResultSync: vi.fn(() => ([{ result: [[[[{ v: true }]]]] }, { result: [[[[{ v: false }]]]] }])),+ };+ const univerInstanceService = {+ getUnit: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => ({+ getName: () => 'sheet-1',+ })),+ })),+ };+ const listCacheService = {+ getOrCompute: vi.fn(() => ({ list: ['a', 'b'] })),+ };+ const lexerTreeBuilder = {+ moveFormulaRefOffset: vi.fn((formula: string, col: number, row: number) => `${formula}:${col},${row}`),+ checkIfAddBracket: vi.fn(() => 0),+ sequenceNodesBuilder: vi.fn(() => [{ nodeType: 'FUNCTION', token: 'IF' }]),+ };+ const injector = {+ get(token: unknown) {+ if (token === DataValidationCustomFormulaService) {+ return customFormulaService;+ }+ if (token === DataValidationFormulaService) {+ return formulaService;+ }+ if (token === DataValidationListCacheService) {+ return listCacheService;+ }+ if (token === LexerTreeBuilder) {+ return lexerTreeBuilder;+ }+ if (String(token) === 'univer.current') {+ return univerInstanceService;+ }++ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as unknown as Injector;++ return {+ localeService,+ customFormulaService,+ formulaService,+ listCacheService,+ lexerTreeBuilder,+ injector,+ };+}++describe('validators', () => {+ it('covers decimal, whole, and text-length validation branches', async () => {+ const { localeService, injector, customFormulaService, lexerTreeBuilder } = createContext();+ const decimal = new DecimalValidator(localeService, injector);+ const whole = new WholeValidator(localeService, injector);+ const textLength = new TextLengthValidator(localeService, injector);++ customFormulaService.getCellFormulaValue.mockResolvedValueOnce({ v: '12.5' });+ customFormulaService.getCellFormula2Value.mockResolvedValueOnce({ v: '#VALUE!' });++ expect(getCellValueNumber('12.5')).toBe(12.5);+ expect(await decimal.isValidType({ value: '12.5' } as never, {} as never, {} as never)).toBe(true);+ expect(decimal.transform({ value: '12.5' } as never, {} as never, {} as never).value).toBe(12.5);+ await expect(decimal.parseFormula({ uid: 'rule-1', formula1: '=A1', formula2: '=B1' } as never, 'u', 's', 0, 0)).resolves.toEqual({+ formula1: 12.5,+ formula2: Number.NaN,+ isFormulaValid: false,+ });+ expect(decimal.validatorFormula({ operator: DataValidationOperator.BETWEEN, formula1: '1', formula2: 'x' } as never, 'u', 's')).toEqual({+ success: false,+ formula1: undefined,+ formula2: 'dataValidation.validFail.number',+ });+ expect(decimal.validatorFormula({ operator: DataValidationOperator.EQUAL, formula1: 'x' } as never, 'u', 's')).toEqual({+ success: false,+ formula1: 'dataValidation.validFail.number',+ });+ expect(decimal.generateRuleErrorMessage({ operator: DataValidationOperator.EQUAL, formula1: '=A1', ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] } as never, { row: 2, col: 3 } as never)).toBe('dataValidation.errorMsg.equal');++ expect(await whole.isValidType({ value: 3 } as never, {} as never, {} as never)).toBe(true);+ expect(await whole.isValidType({ value: 3.2 } as never, {} as never, {} as never)).toBe(false);+ expect(await whole.parseFormula({ uid: 'rule-2', formula1: '4', formula2: null } as never, 'u', 's', 0, 0)).toEqual({+ formula1: 4,+ formula2: Number.NaN,+ isFormulaValid: true,+ });+ expect(whole.validatorFormula({ operator: DataValidationOperator.BETWEEN, formula1: '1', formula2: '2' } as never, 'u', 's')).toEqual({+ success: true,+ formula1: undefined,+ formula2: undefined,+ });++ expect(textLength.validatorFormula({} as never, 'u', 's')).toEqual({ success: false });+ expect(await textLength.parseFormula({ uid: 'rule-3', formula1: '3', formula2: '4' } as never, 'u', 's', 0, 0)).toEqual({+ formula1: 3,+ formula2: 4,+ isFormulaValid: true,+ });+ expect(textLength.transform({ value: 1234 } as never, {} as never, {} as never).value).toBe(4);+ expect(await textLength.isValidType({ value: true } as never, {} as never, {} as never)).toBe(false);+ expect(await textLength.isValidType({ value: 'abcd' } as never, {} as never, {} as never)).toBe(true);+ expect(textLength.generateRuleErrorMessage({ operator: DataValidationOperator.EQUAL, formula1: '=A1', ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] } as never, { row: 1, col: 1 } as never)).toBe('dataValidation.textLength.errorMsg.equal');+ expect(lexerTreeBuilder.moveFormulaRefOffset).toHaveBeenCalled();+ });++ it('covers date validation parsing, normalization, and messages', async () => {+ const { localeService, injector, customFormulaService, lexerTreeBuilder } = createContext();+ const date = new DateValidator(localeService, injector);++ customFormulaService.getCellFormulaValue.mockResolvedValueOnce({ v: '2024-01-02' });+ customFormulaService.getCellFormula2Value.mockResolvedValueOnce({ v: '2024-01-05' });++ const parsed = await date.parseFormula({ uid: 'rule-1', formula1: '=A1', formula2: '=B1' } as never, 'u', 's', 0, 0);+ expect(parsed.formula1).toBeTypeOf('number');+ expect(parsed.formula2).toBeTypeOf('number');+ expect(parsed.isFormulaValid).toBe(true);++ expect(await date.isValidType({ value: 45293, interceptValue: '2024-01-02' } as never)).toBe(true);+ expect(await date.isValidType({ value: 'ignored', interceptValue: 'not-a-date' } as never)).toBe(false);+ expect(date.validatorFormula({ operator: DataValidationOperator.BETWEEN, formula1: '2024-01-01', formula2: '' } as never, 'u', 's')).toEqual({+ success: false,+ formula1: undefined,+ formula2: 'dataValidation.validFail.date',+ });+ expect(date.normalizeFormula({ formula1: '45293', formula2: 'invalid', bizInfo: { showTime: false } } as never, 'u', 's')).toEqual({+ formula1: '2024-01-02',+ formula2: '',+ });+ expect(date.transform({ value: '2024-01-02' } as never, {} as never, {} as never).value).toBeTypeOf('number');+ expect(date.generateRuleName({ operator: DataValidationOperator.EQUAL, formula1: '2024-01-02' } as never)).toContain('dataValidation.date.title');+ expect(date.generateRuleErrorMessage({ operator: DataValidationOperator.EQUAL, formula1: '=A1', ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] } as never, { row: 0, col: 0 } as never)).toBe('dataValidation.date.errorMsg.equal');+ expect(lexerTreeBuilder.moveFormulaRefOffset).toHaveBeenCalled();+ });++ it('covers checkbox, custom, any, and list-multiple behaviors', async () => {+ const { localeService, injector, formulaService, lexerTreeBuilder } = createContext();+ const checkbox = new CheckboxValidator(localeService, injector);+ const custom = new CustomFormulaValidator(localeService, injector);+ const any = new AnyValidator(localeService, injector);+ const listMultiple = new ListMultipleValidator(localeService, injector);++ expect(transformCheckboxValue(true)).toBe('1');+ expect(transformCheckboxValue(false)).toBe('0');+ expect(transformCheckboxValue('other')).toBe('other');++ expect(checkbox.validatorFormula({ formula1: '', formula2: '' } as never, 'u', 's')).toEqual({ success: true });+ expect(checkbox.validatorFormula({ formula1: '1', formula2: '1' } as never, 'u', 's')).toEqual({+ success: false,+ formula1: 'dataValidation.validFail.checkboxEqual',+ formula2: 'dataValidation.validFail.checkboxEqual',+ });+ expect(await checkbox.parseFormula({ uid: 'rule-1', formula1: '=A1', formula2: '=B1' } as never, 'u', 's')).toEqual({+ formula1: '1',+ formula2: '0',+ originFormula1: true,+ originFormula2: false,+ isFormulaValid: true,+ });+ expect(checkbox.parseFormulaSync({ uid: 'rule-1', formula1: '=A1', formula2: '=B1' } as never, 'u', 's')).toEqual({+ formula1: '1',+ formula2: '0',+ originFormula1: true,+ originFormula2: false,+ isFormulaValid: true,+ });+ expect(checkbox.skipDefaultFontRender!({ uid: 'rule-1', formula1: '=A1', formula2: '=B1' } as never, '0', { unitId: 'u', subUnitId: 's', row: 0, column: 0 })).toBe(true);+ expect(await checkbox.isValidType({ value: false, unitId: 'u', subUnitId: 's' } as never, {} as never, { uid: 'rule-1', formula1: '=A1', formula2: '=B1' } as never)).toBe(true);+ expect(checkbox.getExtraStyle({} as never, null)).toEqual({ tb: WrapStrategy.CLIP });+ expect(checkbox.generateRuleErrorMessage({} as never)).toBe('dataValidation.checkbox.error');++ lexerTreeBuilder.checkIfAddBracket.mockReturnValueOnce(1);+ expect(custom.validatorFormula({ formula1: 'A1' } as never, 'u', 's')).toEqual({+ success: false,+ formula1: 'dataValidation.validFail.formula',+ });+ lexerTreeBuilder.checkIfAddBracket.mockReturnValueOnce(0);+ expect(custom.validatorFormula({ formula1: '=A1' } as never, 'u', 's')).toEqual({+ success: true,+ formula1: '',+ });+ await expect(custom.parseFormula({} as never, 'u', 's')).resolves.toEqual({ formula1: undefined, formula2: undefined, isFormulaValid: true });+ (injector.get(DataValidationCustomFormulaService) as any).getCellFormulaValue.mockResolvedValueOnce({ v: true, t: CellValueType.BOOLEAN });+ expect(await custom.isValidType({ unitId: 'u', subUnitId: 's', row: 0, column: 0 } as never, {} as never, { uid: 'rule-2' } as never)).toBe(true);+ (injector.get(DataValidationCustomFormulaService) as any).getCellFormulaValue.mockResolvedValueOnce({ v: '#VALUE!' });+ expect(await custom.isValidType({ unitId: 'u', subUnitId: 's', row: 0, column: 0 } as never, {} as never, { uid: 'rule-2' } as never)).toBe(false);+ expect(custom.generateRuleName({ formula1: '=A1' } as never)).toBe('dataValidation.custom.ruleName');++ await expect(any.parseFormula({ formula1: '1', formula2: '2' } as never, 'u', 's')).resolves.toEqual({ formula1: '1', formula2: '2', isFormulaValid: true });+ expect(any.validatorFormula({} as never, 'u', 's')).toEqual({ success: true });+ expect(await any.isValidType({} as never, {} as never, {} as never)).toBe(true);+ expect(any.generateRuleErrorMessage({} as never)).toBe('dataValidation.any.error');++ expect(listMultiple.id).toBe('listMultiple');+ expect(listMultiple.title).toBe('dataValidation.listMultiple.title');+ expect(listMultiple.offsetFormulaByRange).toBe(false);+ expect(listMultiple.skipDefaultFontRender!()).toBe(true);+ expect(formulaService.getRuleFormulaResult).toHaveBeenCalled();+ });+});diff --git a/packages/sheets-drawing-ui/src/basics/__tests__/transform-position.spec.ts b/packages/sheets-drawing-ui/src/basics/__tests__/transform-position.spec.tsnew file mode 100644index 0000000000..27b1238b3a--- /dev/null+++ b/packages/sheets-drawing-ui/src/basics/__tests__/transform-position.spec.ts@@ -0,0 +1,162 @@+/**+ * 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 { ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { convertPositionSheetOverGridToAbsolute } from '@univerjs/sheets-ui';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { drawingPositionToTransform, transformToAxisAlignPosition, transformToDrawingPosition } from '../transform-position';++vi.mock('@univerjs/sheets-ui', () => ({+ convertPositionSheetOverGridToAbsolute: vi.fn(),+}));++describe('transform-position', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('clips drawing transforms to the current sheet bounds', () => {+ vi.mocked(convertPositionSheetOverGridToAbsolute).mockReturnValue({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ left: 90,+ top: 75,+ width: 20,+ height: 30,+ });++ const sheetSkeletonManagerService = {+ getCurrent: () => ({ unitId: 'unit-1', sheetId: 'sheet-1' }),+ getCurrentSkeleton: () => ({+ rowHeaderWidth: 0,+ columnHeaderHeight: 0,+ columnTotalWidth: 100,+ rowTotalHeight: 90,+ }),+ } as SheetSkeletonManagerService;++ const transform = drawingPositionToTransform({+ from: { column: 0, row: 0, columnOffset: 0, rowOffset: 0 },+ to: { column: 1, row: 1, columnOffset: 0, rowOffset: 0 },+ angle: 10,+ flipX: true,+ }, {} as ISheetSelectionRenderService, sheetSkeletonManagerService);++ expect(transform).toEqual({+ left: 80,+ top: 60,+ width: 20,+ height: 30,+ angle: 10,+ flipX: true,+ flipY: false,+ skewX: 0,+ skewY: 0,+ });+ });++ it('converts a transform back to sheet anchors', () => {+ const selectionRenderService = {+ getCellWithCoordByOffset: vi.fn()+ .mockReturnValueOnce({+ actualColumn: 1,+ actualRow: 2,+ startX: 10,+ startY: 20,+ })+ .mockReturnValueOnce({+ actualColumn: 3,+ actualRow: 4,+ startX: 40,+ startY: 60,+ }),+ } as unknown as ISheetSelectionRenderService;++ expect(transformToDrawingPosition({+ left: 15,+ top: 25,+ width: 40,+ height: 50,+ flipY: true,+ angle: 25,+ }, selectionRenderService)).toEqual({+ from: {+ column: 1,+ columnOffset: 5,+ row: 2,+ rowOffset: 5,+ },+ to: {+ column: 3,+ columnOffset: 15,+ row: 4,+ rowOffset: 15,+ },+ flipX: false,+ flipY: true,+ angle: 25,+ skewX: 0,+ skewY: 0,+ });+ });++ it('uses swapped bounds for axis-aligned positions when the angle rotates into a major-axis range', () => {+ const selectionRenderService = {+ getCellWithCoordByOffset: vi.fn()+ .mockReturnValueOnce({+ actualColumn: 2,+ actualRow: 3,+ startX: 10,+ startY: 40,+ })+ .mockReturnValueOnce({+ actualColumn: 6,+ actualRow: 7,+ startX: 70,+ startY: 80,+ }),+ } as unknown as ISheetSelectionRenderService;++ expect(transformToAxisAlignPosition({+ left: 20,+ top: 30,+ width: 40,+ height: 60,+ angle: 90,+ }, selectionRenderService)).toEqual({+ from: {+ column: 2,+ columnOffset: 0,+ row: 3,+ rowOffset: 0,+ },+ to: {+ column: 6,+ columnOffset: 0,+ row: 7,+ rowOffset: 0,+ },+ flipX: false,+ flipY: false,+ angle: 90,+ skewX: 0,+ skewY: 0,+ });++ expect(selectionRenderService.getCellWithCoordByOffset).toHaveBeenNthCalledWith(1, 10, 40);+ expect(selectionRenderService.getCellWithCoordByOffset).toHaveBeenNthCalledWith(2, 70, 80);+ });+});diff --git a/packages/sheets-formula-ui/src/commands/operations/__tests__/create-command-test-bed.ts b/packages/sheets-formula-ui/src/commands/operations/__tests__/create-command-test-bed.tsindex 006fc8686b..aa1a40104d 100644--- a/packages/sheets-formula-ui/src/commands/operations/__tests__/create-command-test-bed.ts+++ b/packages/sheets-formula-ui/src/commands/operations/__tests__/create-command-test-bed.ts@@ -49,6 +49,17 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?const univer = new Univer();const injector = univer.__getInjector();const get = injector.get.bind(injector);+ const overrideTokens = new Set(dependencies?.map((dependency) => Array.isArray(dependency) ? dependency[0] : dependency));++ const addDependency = (dependency: Dependency) => {+ const token = Array.isArray(dependency) ? dependency[0] : dependency;++ if (overrideTokens.has(token)) {+ return;+ }++ injector.add(dependency);+ };/*** This plugin hooks into Sheet's DI system to expose API to test scripts@@ -66,23 +77,23 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?override onStarting(): void {const injector = this._injector;- injector.add([ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }]);- injector.add([SheetsSelectionsService]);- injector.add([LexerTreeBuilder]);- injector.add([DocSelectionManagerService]);- injector.add([IFormulaPromptService, { useClass: FormulaPromptService }]);- injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);- injector.add([IEditorService, { useClass: EditorService }]);- injector.add([SheetSkeletonManagerService]);- injector.add([IRenderManagerService, { useClass: RenderManagerService }]);- injector.add([SheetInterceptorService]);- injector.add([WorksheetPermissionService]);- injector.add([WorksheetProtectionPointModel]);- injector.add([WorkbookPermissionService]);- injector.add([RangeProtectionRuleModel]);- injector.add([IAuthzIoService, { useClass: AuthzIoLocalService }]);- injector.add([WorksheetProtectionRuleModel]);- injector.add([IRefSelectionsService, { useClass: RefSelectionsService }]);+ addDependency([ISheetSelectionRenderService, { useClass: SheetSelectionRenderService }]);+ addDependency([SheetsSelectionsService]);+ addDependency([LexerTreeBuilder]);+ addDependency([DocSelectionManagerService]);+ addDependency([IFormulaPromptService, { useClass: FormulaPromptService }]);+ addDependency([IEditorBridgeService, { useClass: EditorBridgeService }]);+ addDependency([IEditorService, { useClass: EditorService }]);+ addDependency([SheetSkeletonManagerService]);+ addDependency([IRenderManagerService, { useClass: RenderManagerService }]);+ addDependency([SheetInterceptorService]);+ addDependency([WorksheetPermissionService]);+ addDependency([WorksheetProtectionPointModel]);+ addDependency([WorkbookPermissionService]);+ addDependency([RangeProtectionRuleModel]);+ addDependency([IAuthzIoService, { useClass: AuthzIoLocalService }]);+ addDependency([WorksheetProtectionRuleModel]);+ addDependency([IRefSelectionsService, { useClass: RefSelectionsService }]);dependencies?.forEach((d) => injector.add(d));diff --git a/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts b/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.tsindex d1268ea65c..efca75476d 100644--- a/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts+++ b/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts@@ -15,8 +15,10 @@*/import type { ICellData, Injector, Nullable, Univer } from '@univerjs/core';+import type { IEditorService } from '@univerjs/docs-ui';import type { IInsertFunctionOperationParams } from '../insert-function.operation';-import { ICommandService, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, RedoCommand, UndoCommand } from '@univerjs/core';+import { IEditorService as IEditorServiceToken } from '@univerjs/docs-ui';import {SetRangeValuesCommand,SetRangeValuesMutation,@@ -24,7 +26,8 @@ import {SheetsSelectionsService,} from '@univerjs/sheets';import { InsertFunctionCommand } from '@univerjs/sheets-formula';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { IEditorBridgeService, SetCellEditVisibleOperation } from '@univerjs/sheets-ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {InsertFunctionOperation,isMultiRowsColumnsRange,@@ -37,11 +40,27 @@ describe('Test insert function operation', () => {let univer: Univer;let get: Injector['get'];let commandService: ICommandService;+ let editorService: IEditorService;beforeEach(() => {- const testBed = createCommandTestBed();+ const fakeEditorService = {+ getEditor: vi.fn(() => null),+ register: vi.fn(),+ getAllEditor: vi.fn(() => new Map()),+ isEditor: vi.fn(() => false),+ isSheetEditor: vi.fn(() => false),+ blur$: { subscribe: vi.fn() },+ blur: vi.fn(),+ focus$: { subscribe: vi.fn() },+ focus: vi.fn(),+ getFocusId: vi.fn(() => null),+ getFocusEditor: vi.fn(() => null),+ } as unknown as IEditorService;++ const testBed = createCommandTestBed(undefined, [[IEditorServiceToken, { useValue: fakeEditorService }]]);univer = testBed.univer;get = testBed.get;+ editorService = get(IEditorServiceToken);commandService = get(ICommandService);commandService.registerCommand(InsertFunctionOperation);@@ -49,6 +68,7 @@ describe('Test insert function operation', () => {commandService.registerCommand(SetRangeValuesCommand);commandService.registerCommand(SetRangeValuesMutation);commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(SetCellEditVisibleOperation);});afterEach(() => {@@ -215,6 +235,45 @@ describe('Test insert function operation', () => {const result = await commandService.executeCommand(InsertFunctionOperation.id);expect(result).toBeFalsy();});++ it('enters edit mode for a single cell and injects the matched reference into both editors', async () => {+ const selectionManager = get(SheetsSelectionsService);+ const editorBridgeService = get(IEditorBridgeService);+ const normalEditorReplaceText = vi.fn();+ const formulaEditorReplaceText = vi.fn();++ vi.spyOn(editorService, 'getEditor').mockImplementation((id?: string) => {+ if (id === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {+ return { replaceText: normalEditorReplaceText } as never;+ }++ if (id === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ return { replaceText: formulaEditorReplaceText } as never;+ }++ return null;+ });++ selectionManager.addSelections([+ {+ range: { startRow: 2, startColumn: 1, endRow: 2, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ const result = await commandService.executeCommand(InsertFunctionOperation.id, {+ value: 'SUM',+ });++ expect(result).toBeFalsy();+ expect(editorBridgeService.isVisible()).toMatchObject({+ visible: true,+ unitId: 'test',+ });+ expect(normalEditorReplaceText).toHaveBeenCalledWith('=SUM(B2');+ expect(formulaEditorReplaceText).toHaveBeenCalledWith('=SUM(B2', false);+ });});describe('function isNumberCell', () => {diff --git a/packages/sheets-formula-ui/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-formula-ui/src/facade/__tests__/f-univer.spec.tsnew file mode 100644index 0000000000..8845184073--- /dev/null+++ b/packages/sheets-formula-ui/src/facade/__tests__/f-univer.spec.ts@@ -0,0 +1,77 @@+/**+ * 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 { IUnitRangeName } from '@univerjs/core';+import { firstValueFrom, skip } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { GlobalRangeSelectorService } from '../../services/range-selector.service';+import { createFormulaTestBed } from './create-formula-test-bed';+import '../../facade';++describe('Test FUniver with sheets-formula-ui facade', () => {+ let disposeUniver: () => void;++ beforeEach(() => {+ disposeUniver = () => {};+ });++ afterEach(() => {+ disposeUniver();+ });++ it('showRangeSelectorDialog forwards options to the selector service and resolves with selected ranges', async () => {+ const testBed = createFormulaTestBed(undefined, [[GlobalRangeSelectorService]]);+ const selectorService = testBed.get(GlobalRangeSelectorService);+ const callback = vi.fn();+ const selectedRanges: IUnitRangeName[] = [{+ unitId: 'test',+ sheetName: 'sheet1',+ range: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ }];++ disposeUniver = () => testBed.univer.dispose();++ const selectorPromise = firstValueFrom(selectorService.currentSelector$.pipe(skip(1)));+ const resultPromise = testBed.univerAPI.showRangeSelectorDialog({+ unitId: 'test',+ subUnitId: 'sheet1',+ initialValue: selectedRanges,+ maxRangeCount: 2,+ supportAcrossSheet: true,+ callback,+ });++ const currentSelector = await selectorPromise;++ expect(currentSelector).toMatchObject({+ unitId: 'test',+ subUnitId: 'sheet1',+ initialValue: selectedRanges,+ maxRangeCount: 2,+ supportAcrossSheet: true,+ });++ currentSelector!.callback(selectedRanges);++ await expect(resultPromise).resolves.toEqual(selectedRanges);+ expect(callback).toHaveBeenCalledWith(selectedRanges);+ });+});diff --git a/packages/sheets-formula-ui/src/services/__tests__/prompt.service.spec.ts b/packages/sheets-formula-ui/src/services/__tests__/prompt.service.spec.tsnew file mode 100644index 0000000000..270dbb2f4a--- /dev/null+++ b/packages/sheets-formula-ui/src/services/__tests__/prompt.service.spec.ts@@ -0,0 +1,132 @@+/**+ * 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 { IContextService } from '@univerjs/core';+import type { ISequenceNode } from '@univerjs/engine-formula';+import { Direction } from '@univerjs/core';+import { sequenceNodeType } from '@univerjs/engine-formula';+import { map, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { FORMULA_PROMPT_ACTIVATED, FormulaPromptService } from '../prompt.service';++function createReferenceNode(token: string, startIndex: number, endIndex: number): ISequenceNode {+ return {+ token,+ startIndex,+ endIndex,+ nodeType: sequenceNodeType.REFERENCE,+ } as ISequenceNode;+}++function createContextService(): IContextService {+ const contextChanged$ = new Subject<{ [key: string]: boolean }>();+ const contextMap = new Map<string, boolean>();++ return {+ contextChanged$: contextChanged$.asObservable(),+ getContextValue: vi.fn((key: string) => contextMap.get(key) ?? false),+ setContextValue: vi.fn((key: string, value: boolean) => {+ contextMap.set(key, value);+ contextChanged$.next({ [key]: value });+ }),+ subscribeContextValue$: vi.fn((key: string) => contextChanged$.pipe(map((event) => event[key] ?? false))),+ };+}++describe('FormulaPromptService', () => {+ it('tracks prompt visibility and forwards prompt events', () => {+ const contextService = createContextService();+ const service = new FormulaPromptService(contextService);+ const searchEvents: unknown[] = [];+ const helpEvents: unknown[] = [];+ const navigateEvents: unknown[] = [];+ const acceptEvents: boolean[] = [];+ const acceptedNames: string[] = [];++ service.search$.subscribe((event) => searchEvents.push(event));+ service.help$.subscribe((event) => helpEvents.push(event));+ service.navigate$.subscribe((event) => navigateEvents.push(event));+ service.accept$.subscribe((event) => acceptEvents.push(event));+ service.acceptFormulaName$.subscribe((event) => acceptedNames.push(event));++ service.search({ visible: true, searchText: 'su', searchList: [] });+ service.help({ visible: true, paramIndex: 1, functionInfo: { functionName: 'SUM' } as never });+ service.navigate({ direction: Direction.DOWN });+ service.accept(true);+ service.acceptFormulaName('SUM');++ expect(contextService.setContextValue).toHaveBeenCalledWith(FORMULA_PROMPT_ACTIVATED, true);+ expect(service.isSearching()).toBe(true);+ expect(service.isHelping()).toBe(true);+ expect(searchEvents).toEqual([{ visible: true, searchText: 'su', searchList: [] }]);+ expect(helpEvents).toEqual([{ visible: true, paramIndex: 1, functionInfo: { functionName: 'SUM' } }]);+ expect(navigateEvents).toEqual([{ direction: Direction.DOWN }]);+ expect(acceptEvents).toEqual([true]);+ expect(acceptedNames).toEqual(['SUM']);++ service.dispose();+ });++ it('updates and inserts sequence nodes while keeping later reference indexes aligned', () => {+ const service = new FormulaPromptService(createContextService());++ service.setSequenceNodes([+ '=',+ createReferenceNode('A1', 1, 2),+ '+',+ createReferenceNode('B2', 4, 5),+ ]);++ expect(service.getCurrentSequenceNodeIndex(1)).toBe(1);+ expect(service.getCurrentSequenceNodeByIndex(1)).toMatchObject({ token: 'A1' });++ service.updateSequenceRef(1, 'Sheet1!A1');++ expect(service.getSequenceNodes()).toEqual([+ '=',+ createReferenceNode('Sheet1!A1', 1, 9),+ '+',+ createReferenceNode('B2', 11, 12),+ ]);++ service.insertSequenceString(1, '(');+ service.insertSequenceRef(2, 'C3');++ expect(service.getSequenceNodes()).toEqual([+ '=',+ '(',+ createReferenceNode('C3', 2, 3),+ createReferenceNode('Sheet1!A1', 4, 12),+ '+',+ createReferenceNode('B2', 14, 15),+ ]);++ service.enableLockedSelectionChange();+ service.enableLockedSelectionInsert();+ expect(service.isLockedSelectionChange()).toBe(true);+ expect(service.isLockedSelectionInsert()).toBe(true);++ service.disableLockedSelectionChange();+ service.disableLockedSelectionInsert();+ service.clearSequenceNodes();++ expect(service.isLockedSelectionChange()).toBe(false);+ expect(service.isLockedSelectionInsert()).toBe(false);+ expect(service.getSequenceNodes()).toEqual([]);++ service.dispose();+ });+});diff --git a/packages/sheets-formula/src/commands/commands/__tests__/insert-function.command.spec.ts b/packages/sheets-formula/src/commands/commands/__tests__/insert-function.command.spec.tsnew file mode 100644index 0000000000..87e0cd48d2--- /dev/null+++ b/packages/sheets-formula/src/commands/commands/__tests__/insert-function.command.spec.ts@@ -0,0 +1,97 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import * as core from '@univerjs/core';+import { ICommandService } from '@univerjs/core';+import { SetRangeValuesCommand } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';++import { InsertFunctionCommand } from '../insert-function.command';++describe('InsertFunctionCommand', () => {+ it('should write shared-formula ranges and direct formulas in one SetRangeValuesCommand call', async () => {+ vi.spyOn(core, 'generateRandomId').mockReturnValue('ABC123');++ const executeCommand = vi.fn().mockResolvedValue(true);+ const accessor = {+ get: (token: unknown) => {+ if (token === ICommandService) {+ return { executeCommand };+ }++ throw new Error(`Unexpected token: ${String(token)}`);+ },+ } as unknown as IAccessor;++ const result = await InsertFunctionCommand.handler!(accessor, {+ list: [{+ range: {+ startRow: 1,+ endRow: 2,+ startColumn: 1,+ endColumn: 2,+ },+ primary: {+ row: 1,+ column: 1,+ },+ formula: '=SUM(B1:C2)',+ }],+ listOfRangeHasNumber: [{+ range: {+ startRow: 4,+ endRow: 4,+ startColumn: 0,+ endColumn: 0,+ },+ primary: {+ row: 4,+ column: 0,+ },+ formula: '=SUM(A1:A4)',+ }],+ });++ expect(result).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, {+ value: {+ 1: {+ 1: {+ f: '=SUM(B1:C2)',+ si: 'ABC123',+ },+ 2: {+ si: 'ABC123',+ },+ },+ 2: {+ 1: {+ si: 'ABC123',+ },+ 2: {+ si: 'ABC123',+ },+ },+ 4: {+ 0: {+ f: '=SUM(A1:A4)',+ },+ },+ },+ });+ });+});diff --git a/packages/sheets-formula/src/commands/commands/__tests__/quick-sum.command.spec.ts b/packages/sheets-formula/src/commands/commands/__tests__/quick-sum.command.spec.tsnew file mode 100644index 0000000000..59abd133c3--- /dev/null+++ b/packages/sheets-formula/src/commands/commands/__tests__/quick-sum.command.spec.ts@@ -0,0 +1,173 @@+/**+ * 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 { IAccessor, IWorkbookData } from '@univerjs/core';+import { CellValueType, ICommandService, IUniverInstanceService, LocaleType } from '@univerjs/core';+import { SetRangeValuesCommand, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createFacadeTestBed } from '../../../facade/__tests__/create-test-bed';+import { QuickSumCommand } from '../quick-sum.command';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: 1, t: CellValueType.NUMBER },+ 1: { v: 2, t: CellValueType.NUMBER },+ 2: {},+ },+ 1: {+ 0: { v: 3, t: CellValueType.NUMBER },+ 1: { v: 4, t: CellValueType.NUMBER },+ 2: {},+ },+ 2: {+ 0: {},+ 1: {},+ 2: {},+ },+ },+ },+ },+ styles: {},+ };+}++describe('QuickSumCommand', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('returns false when there is no active selection', async () => {+ const testBed = createFacadeTestBed(createWorkbookData());++ const executeCommand = vi.fn();+ const accessor = {+ get(token: unknown) {+ if (token === SheetsSelectionsService) {+ return { getCurrentLastSelection: vi.fn(() => null) };+ }+ if (token === IUniverInstanceService) {+ return testBed.injector.get(IUniverInstanceService);+ }+ if (token === ICommandService) {+ return { executeCommand };+ }++ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as unknown as IAccessor;++ await expect(QuickSumCommand.handler?.(accessor)).resolves.toBe(false);+ expect(executeCommand).not.toHaveBeenCalled();++ testBed.univer.dispose();+ });++ it('writes row and column sum formulas, then resets selection to the computed range', async () => {+ const testBed = createFacadeTestBed(createWorkbookData());+ const executeCommand = vi.fn(async () => true);+ const accessor = {+ get(token: unknown) {+ if (token === SheetsSelectionsService) {+ return {+ getCurrentLastSelection: vi.fn(() => ({+ range: {+ startRow: 0,+ startColumn: 0,+ endRow: 2,+ endColumn: 2,+ },+ primary: {+ startRow: 9,+ startColumn: 9,+ endRow: 9,+ endColumn: 9,+ },+ })),+ };+ }+ if (token === IUniverInstanceService) {+ return testBed.injector.get(IUniverInstanceService);+ }+ if (token === ICommandService) {+ return { executeCommand };+ }++ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as unknown as IAccessor;++ await expect(QuickSumCommand.handler?.(accessor)).resolves.toBe(true);++ expect(executeCommand).toHaveBeenNthCalledWith(1, SetRangeValuesCommand.id, {+ range: {+ startRow: 0,+ startColumn: 0,+ endRow: 2,+ endColumn: 2,+ },+ value: {+ 0: {+ 2: { f: '=SUM(A1:B1)' },+ },+ 1: {+ 2: { f: '=SUM(A2:B2)' },+ },+ 2: {+ 0: { f: '=SUM(A1:A2)' },+ 1: { f: '=SUM(B1:B2)' },+ 2: { f: '=SUM(A3:B3)' },+ },+ },+ }, undefined);+ expect(executeCommand).toHaveBeenNthCalledWith(2, SetSelectionsOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ selections: [{+ range: {+ startRow: 0,+ startColumn: 0,+ endRow: 2,+ endColumn: 2,+ },+ primary: {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ actualRow: 0,+ actualColumn: 0,+ },+ style: null,+ }],+ }, undefined);++ testBed.univer.dispose();+ });+});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.tsnew file mode 100644index 0000000000..b11305b4d8--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/active-dirty.controller.spec.ts@@ -0,0 +1,411 @@+/**+ * 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 { Dependency, ICommandInfo, IWorkbookData } from '@univerjs/core';+import type { ISetDefinedNameMutationParam } from '@univerjs/engine-formula';+import type { IInsertSheetMutationParams, IRemoveRowsMutationParams } from '@univerjs/sheets';+import type { ITestBed } from '../../facade/__tests__/create-test-bed';+import { LocaleType } from '@univerjs/core';+import {+ ActiveDirtyManagerService,+ FormulaDataModel,+ IActiveDirtyManagerService,+ RemoveDefinedNameMutation,+ SetDefinedNameMutation,+ SetTriggerFormulaCalculationStartMutation,+} from '@univerjs/engine-formula';+import {+ InsertSheetMutation,+ MoveRangeMutation,+ RemoveColMutation,+ RemoveRowMutation,+ RemoveSheetMutation,+ ReorderRangeMutation,+ SetRangeValuesMutation,+ SetRowHiddenMutation,+ SetStyleCommand,+} from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { ActiveDirtyController } from '../active-dirty.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {},+ rowCount: 6,+ columnCount: 8,+ },+ },+ styles: {},+ };+}++function createControllerTestBed(): ITestBed {+ const dependencies: Dependency[] = [+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [ActiveDirtyController],+ ];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++function getDirtyData(testBed: ITestBed, command: ICommandInfo) {+ const activeDirtyManagerService = testBed.injector.get(IActiveDirtyManagerService);+ const conversion = activeDirtyManagerService.get(command.id);++ expect(conversion).toBeDefined();++ return conversion!.getDirtyData(command);+}++describe('ActiveDirtyController', () => {+ let testBed: ITestBed;++ afterEach(() => {+ testBed?.univer.dispose();+ });++ it('should convert range mutations into dirty ranges and skip style-triggered updates', () => {+ testBed = createControllerTestBed();++ const formulaDataModel = testBed.injector.get(FormulaDataModel);++ formulaDataModel.setArrayFormulaRange({+ test: {+ sheet1: {+ 0: {+ 0: {+ startRow: 0,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ },+ },+ },+ },+ });++ testBed.injector.get(ActiveDirtyController);++ expect(getDirtyData(testBed, {+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ trigger: SetStyleCommand.id,+ cellValue: {+ 1: {+ 1: { v: 1 },+ },+ },+ },+ } as ICommandInfo)).toEqual({});++ expect(getDirtyData(testBed, {+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 1: { v: 1 },+ },+ 3: {+ 2: { v: 2 },+ },+ },+ },+ } as ICommandInfo)).toEqual({+ dirtyRanges: [+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1 },+ },+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 3, startColumn: 2, endRow: 3, endColumn: 2 },+ },+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },+ },+ ],+ });+ });++ it('should collect dirty ranges and dependency cache clears for move and reorder mutations', () => {+ testBed = createControllerTestBed();+ testBed.injector.get(ActiveDirtyController);++ expect(getDirtyData(testBed, {+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test',+ from: {+ subUnitId: 'sheet1',+ value: {+ 0: {+ 0: { v: 1 },+ },+ },+ },+ to: {+ subUnitId: 'sheet1',+ value: {+ 2: {+ 2: { v: 2 },+ },+ },+ },+ },+ } as ICommandInfo)).toEqual({+ dirtyRanges: [+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },+ },+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 2, startColumn: 2, endRow: 2, endColumn: 2 },+ },+ ],+ clearDependencyTreeCache: {+ test: {+ sheet1: '1',+ },+ },+ });++ expect(getDirtyData(testBed, {+ id: ReorderRangeMutation.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startRow: 1,+ startColumn: 1,+ endRow: 2,+ endColumn: 3,+ },+ },+ } as ICommandInfo)).toEqual({+ dirtyRanges: [+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 1, startColumn: 1, endRow: 2, endColumn: 3 },+ },+ ],+ clearDependencyTreeCache: {+ test: {+ sheet1: '1',+ },+ },+ });+ });++ it('should expand row and column removals to worksheet bounds and keep hide-row ranges', () => {+ testBed = createControllerTestBed();+ testBed.injector.get(ActiveDirtyController);++ const removeRowsParams: IRemoveRowsMutationParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startRow: 1,+ startColumn: 0,+ endRow: 2,+ endColumn: 0,+ },+ };++ expect(getDirtyData(testBed, {+ id: RemoveRowMutation.id,+ params: removeRowsParams,+ } as ICommandInfo)).toEqual({+ dirtyRanges: [+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 1, startColumn: 0, endRow: 2, endColumn: 7 },+ },+ ],+ clearDependencyTreeCache: {+ test: {+ sheet1: '1',+ },+ },+ });++ expect(getDirtyData(testBed, {+ id: RemoveColMutation.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startRow: 0,+ startColumn: 2,+ endRow: 0,+ endColumn: 3,+ },+ },+ } as ICommandInfo)).toEqual({+ dirtyRanges: [+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 0, startColumn: 2, endRow: 6, endColumn: 3 },+ },+ ],+ clearDependencyTreeCache: {+ test: {+ sheet1: '1',+ },+ },+ });++ expect(getDirtyData(testBed, {+ id: SetRowHiddenMutation.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 4, startColumn: 0, endRow: 5, endColumn: 1 }],+ },+ } as ICommandInfo)).toEqual({+ dirtyRanges: [+ {+ unitId: 'test',+ sheetId: 'sheet1',+ range: { startRow: 4, startColumn: 0, endRow: 5, endColumn: 1 },+ },+ ],+ clearDependencyTreeCache: {+ test: {+ sheet1: '1',+ },+ },+ });+ });++ it('should pass through sheet and defined-name dirty maps', () => {+ testBed = createControllerTestBed();+ testBed.injector.get(ActiveDirtyController);++ const definedNameParams: ISetDefinedNameMutationParam = {+ unitId: 'test',+ id: 'defined-name',+ name: 'DIRTY_NAME',+ formulaOrRefString: 'Sheet1!$A$1',+ };+ const insertSheetParams = {+ unitId: 'test',+ sheet: {+ ...createWorkbookData().sheets.sheet1,+ id: 'sheet-added',+ name: 'Added Sheet',+ },+ } 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: {+ unitId: 'test',+ subUnitId: 'sheet1',+ subUnitName: 'Sheet1',+ },+ } as ICommandInfo)).toEqual({+ dirtyNameMap: {+ test: {+ sheet1: 'Sheet1',+ },+ },+ clearDependencyTreeCache: {+ test: {+ sheet1: '1',+ },+ },+ });++ expect(getDirtyData(testBed, {+ id: InsertSheetMutation.id,+ params: insertSheetParams,+ } as ICommandInfo)).toEqual({+ dirtyNameMap: {+ test: {+ 'sheet-added': 'Added Sheet',+ },+ },+ });++ expect(getDirtyData(testBed, {+ id: SetDefinedNameMutation.id,+ params: definedNameParams,+ } as ICommandInfo)).toEqual({+ dirtyDefinedNameMap: {+ test: {+ DIRTY_NAME: 'Sheet1!$A$1',+ },+ },+ });++ expect(getDirtyData(testBed, {+ id: RemoveDefinedNameMutation.id,+ params: definedNameParams,+ } as ICommandInfo)).toEqual({+ dirtyDefinedNameMap: {+ test: {+ DIRTY_NAME: 'Sheet1!$A$1',+ },+ },+ });+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.tsnew file mode 100644index 0000000000..23a369445c--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/array-formula-cell-interceptor.controller.spec.ts@@ -0,0 +1,295 @@+/**+ * 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 { Dependency, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import {+ CellValueType,+ ICommandService,+ IConfigService,+ InterceptorEffectEnum,+ LocaleType,+} from '@univerjs/core';+import {+ FormulaDataModel,+ IDefinedNamesService,+ LexerTreeBuilder,+ SetArrayFormulaDataMutation,+ SetDefinedNameMutation,+ SetFormulaCalculationResultMutation,+} from '@univerjs/engine-formula';+import { INTERCEPTOR_POINT, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { ArrayFormulaCellInterceptorController } from '../array-formula-cell-interceptor.controller';+import { PLUGIN_CONFIG_KEY_BASE } from '../config.schema';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 1: {+ 1: { v: '1.2300000000000002', t: CellValueType.NUMBER },+ },+ 2: {+ 2: { v: 'stale', t: CellValueType.STRING },+ },+ 3: {+ 0: { f: '=SUM(A1)' },+ 1: { f: '=SUM(A1)' },+ 2: { f: '=SKIP()', x: 1 } as unknown as never,+ },+ },+ },+ },+ styles: {},+ };+}++function createControllerTestBed() {+ const dependencies: Dependency[] = [[ArrayFormulaCellInterceptorController]];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++function getInterceptedCell(worksheet: Worksheet, workbook: Workbook, row: number, col: number, interceptorService: SheetInterceptorService) {+ const rawData = worksheet.getCellRaw(row, col);++ return interceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, InterceptorEffectEnum.Value)(+ rawData,+ {+ unitId: workbook.getUnitId(),+ subUnitId: worksheet.getSheetId(),+ row,+ col,+ worksheet,+ workbook,+ rawData,+ }+ );+}++describe('ArrayFormulaCellInterceptorController', () => {+ let testBed: ReturnType<typeof createControllerTestBed>;+ let commandService: ICommandService;+ let configService: IConfigService;+ let formulaDataModel: FormulaDataModel;+ let interceptorService: SheetInterceptorService;+ let workbook: Workbook;+ let worksheet: Worksheet;++ beforeEach(() => {+ testBed = createControllerTestBed();+ commandService = testBed.injector.get(ICommandService);+ configService = testBed.injector.get(IConfigService);+ formulaDataModel = testBed.injector.get(FormulaDataModel);+ interceptorService = testBed.injector.get(SheetInterceptorService);+ workbook = testBed.sheet as Workbook;+ worksheet = workbook.getActiveSheet()!;++ commandService.registerCommand(SetArrayFormulaDataMutation);+ commandService.registerCommand(SetDefinedNameMutation);+ commandService.registerCommand(SetFormulaCalculationResultMutation);+ commandService.registerCommand(SetRangeValuesMutation);++ testBed.injector.get(ArrayFormulaCellInterceptorController);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ testBed?.univer.dispose();+ });++ it('should sync array formula data to the model and write snapshot refs when configured', async () => {+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { writeArrayFormulaToSnapshot: true });++ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');++ const arrayFormulaRange = {+ test: {+ sheet1: {+ 0: {+ 0: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ },+ },+ },+ };+ const arrayFormulaEmbedded = {+ test: {+ sheet1: {+ 0: {+ 0: {},+ 2: {},+ },+ },+ },+ };+ const arrayFormulaCellData = {+ test: {+ sheet1: {+ 0: {+ 0: { v: 1, t: CellValueType.NUMBER },+ 1: { v: 2, t: CellValueType.NUMBER },+ },+ },+ },+ };++ await commandService.executeCommand(SetArrayFormulaDataMutation.id, {+ arrayFormulaRange,+ arrayFormulaEmbedded,+ arrayFormulaCellData,+ });++ expect(formulaDataModel.getArrayFormulaRange()).toEqual(arrayFormulaRange);+ expect(formulaDataModel.getArrayFormulaCellData()).toEqual(arrayFormulaCellData);++ const setRangeValuesCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetRangeValuesMutation.id);++ expect(setRangeValuesCalls).toHaveLength(3);+ expect(setRangeValuesCalls[0]?.[1]).toMatchObject({+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 0: {+ 0: { ref: 'A1:B2' },+ },+ },+ });+ expect(setRangeValuesCalls[1]?.[1]).toMatchObject({+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 0: {+ 2: { ref: 'C1' },+ },+ },+ });+ expect(setRangeValuesCalls[2]?.[1]).toMatchObject({+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: arrayFormulaCellData.test.sheet1,+ });+ });++ it('should add prefixed formulas for workbook cells and defined names when calculation results arrive', async () => {+ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { writeArrayFormulaToSnapshot: true });++ const definedNamesService = testBed.injector.get(IDefinedNamesService);+ const lexerTreeBuilder = testBed.injector.get(LexerTreeBuilder);+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');+ const prefixSpy = vi+ .spyOn(lexerTreeBuilder, 'getNewFormulaWithPrefix')+ .mockImplementation((formula) => `PREFIX:${formula}`);++ definedNamesService.registerDefinedNames('test', {+ formulaName: {+ id: 'formula-name',+ name: 'FORMULA_NAME',+ formulaOrRefString: '=SUM(A1)',+ localSheetId: 'AllDefaultWorkbook',+ comment: '',+ },+ refName: {+ id: 'ref-name',+ name: 'REF_NAME',+ formulaOrRefString: 'Sheet1!$A$1',+ localSheetId: 'AllDefaultWorkbook',+ comment: '',+ },+ });++ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {+ unitData: {},+ unitOtherData: {},+ });++ const setRangeValuesCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetRangeValuesMutation.id);+ const setDefinedNameCalls = executeCommandSpy.mock.calls.filter(([id]) => id === SetDefinedNameMutation.id);++ expect(prefixSpy).toHaveBeenCalledWith('=SUM(A1)', expect.any(Function));+ expect(prefixSpy).toHaveBeenCalledWith('=SKIP()', expect.any(Function));+ expect(setRangeValuesCalls.at(-1)?.[1]).toMatchObject({+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 3: {+ 0: { xf: 'PREFIX:=SUM(A1)' },+ 1: { xf: 'PREFIX:=SUM(A1)' },+ },+ },+ });+ expect(setDefinedNameCalls).toContainEqual([+ SetDefinedNameMutation.id,+ expect.objectContaining({+ unitId: 'test',+ name: 'FORMULA_NAME',+ formulaOrRefStringWithPrefix: 'PREFIX:=SUM(A1)',+ }),+ expect.objectContaining({+ onlyLocal: true,+ fromFormula: true,+ }),+ ]);+ });++ it('should intercept array formula cells with default values, precision cleanup, raw passthrough and array values', () => {+ formulaDataModel.setArrayFormulaCellData({+ test: {+ sheet1: {+ 0: {+ 0: { v: null, t: null },+ },+ 1: {+ 1: { v: 99, t: CellValueType.NUMBER },+ },+ 2: {+ 2: { v: 7, t: CellValueType.NUMBER },+ },+ },+ },+ });++ expect(getInterceptedCell(worksheet, workbook, 0, 0, interceptorService)).toEqual({+ v: 0,+ t: CellValueType.NUMBER,+ });+ expect(getInterceptedCell(worksheet, workbook, 1, 1, interceptorService)).toEqual({+ v: 1.23,+ t: CellValueType.NUMBER,+ });+ expect(getInterceptedCell(worksheet, workbook, 2, 2, interceptorService)).toEqual({+ v: 7,+ t: CellValueType.NUMBER,+ });+ expect(getInterceptedCell(worksheet, workbook, 4, 4, interceptorService)).toBeUndefined();+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/defined-name.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/defined-name.controller.spec.tsnew file mode 100644index 0000000000..5e0d2e8cd7--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/defined-name.controller.spec.ts@@ -0,0 +1,193 @@+/**+ * 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 { Dependency, IWorkbookData } from '@univerjs/core';+import type { ITestBed } from '../../facade/__tests__/create-test-bed';+import { ICommandService, IUniverInstanceService, LocaleType, UniverInstanceType } from '@univerjs/core';+import { FunctionType, IDefinedNamesService, RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';+import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { DescriptionService, IDescriptionService } from '../../services/description.service';+import { DefinedNameController } from '../defined-name.controller';++function createWorkbookData(id = 'test'): IWorkbookData {+ return {+ id,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: id,+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ },+ styles: {},+ };+}++function createControllerTestBed(): ITestBed {+ const dependencies: Dependency[] = [+ [IDescriptionService, { useClass: DescriptionService }],+ [DefinedNameController],+ ];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++describe('DefinedNameController', () => {+ let testBed: ITestBed;++ afterEach(() => {+ testBed?.univer.dispose();+ });++ it('should register descriptions by current sheet and refresh them when active sheet or unit changes', async () => {+ testBed = createControllerTestBed();++ const injector = testBed.injector;+ const commandService = injector.get(ICommandService);+ const descriptionService = injector.get(IDescriptionService);+ const definedNamesService = injector.get(IDefinedNamesService);+ const univerInstanceService = injector.get(IUniverInstanceService);++ commandService.registerCommand(SetWorksheetActiveOperation);+ injector.get(DefinedNameController);++ definedNamesService.registerDefinedNames('test', {+ workbook: {+ id: 'workbook',+ name: 'UNIT_SCOPE_NAME',+ formulaOrRefString: 'Sheet1!$A$1',+ localSheetId: SCOPE_WORKBOOK_VALUE_DEFINED_NAME,+ },+ localSheet1: {+ id: 'local-sheet1',+ name: 'LOCAL_SHEET1_NAME',+ formulaOrRefString: 'Sheet1!$B$2',+ localSheetId: 'sheet1',+ },+ localSheet2: {+ id: 'local-sheet2',+ name: 'LOCAL_SHEET2_NAME',+ formulaOrRefString: 'Sheet2!$C$3',+ localSheetId: 'sheet2',+ },+ });++ expect(descriptionService.hasDescription('UNIT_SCOPE_NAME')).toBe(true);+ expect(descriptionService.hasDescription('LOCAL_SHEET1_NAME')).toBe(true);+ expect(descriptionService.hasDescription('LOCAL_SHEET2_NAME')).toBe(false);++ await commandService.executeCommand(SetWorksheetActiveOperation.id, { unitId: 'test', subUnitId: 'sheet2' });++ expect(descriptionService.hasDescription('UNIT_SCOPE_NAME')).toBe(true);+ expect(descriptionService.hasDescription('LOCAL_SHEET1_NAME')).toBe(false);+ expect(descriptionService.hasDescription('LOCAL_SHEET2_NAME')).toBe(true);++ testBed.univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData('secondary'));+ univerInstanceService.setCurrentUnitForType('test');+ definedNamesService.registerDefinedNames('secondary', {+ secondary: {+ id: 'secondary',+ name: 'SECONDARY_UNIT_NAME',+ formulaOrRefString: 'Sheet1!$D$4',+ localSheetId: SCOPE_WORKBOOK_VALUE_DEFINED_NAME,+ },+ });++ univerInstanceService.setCurrentUnitForType('secondary');++ expect(descriptionService.hasDescription('UNIT_SCOPE_NAME')).toBe(false);+ expect(descriptionService.hasDescription('LOCAL_SHEET2_NAME')).toBe(false);+ expect(descriptionService.hasDescription('SECONDARY_UNIT_NAME')).toBe(true);+ });++ it('should register mutation descriptions based on the provided sheet context and remove them on delete', async () => {+ testBed = createControllerTestBed();++ const injector = testBed.injector;+ const commandService = injector.get(ICommandService);+ const descriptionService = injector.get(IDescriptionService);++ commandService.registerCommand(SetDefinedNameMutation);+ commandService.registerCommand(RemoveDefinedNameMutation);+ injector.get(DefinedNameController);++ await commandService.executeCommand(SetDefinedNameMutation.id, {+ unitId: 'test',+ id: 'off-sheet',+ name: 'OFF_SHEET_NAME',+ formulaOrRefString: 'Sheet2!$A$1',+ localSheetId: 'sheet2',+ });++ expect(descriptionService.hasDescription('OFF_SHEET_NAME')).toBe(false);++ await commandService.executeCommand(SetDefinedNameMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet2',+ id: 'sheet2-name',+ name: 'SHEET2_MUTATION_NAME',+ formulaOrRefString: 'Sheet2!$C$4',+ localSheetId: 'sheet2',+ });++ expect(descriptionService.hasDescription('SHEET2_MUTATION_NAME')).toBe(true);++ await commandService.executeCommand(SetDefinedNameMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ id: 'active-sheet',+ name: 'ACTIVE_SHEET_NAME',+ formulaOrRefString: 'Sheet1!$B$2',+ comment: ' active comment',+ localSheetId: 'sheet1',+ });++ expect(descriptionService.getFunctionInfo('ACTIVE_SHEET_NAME')).toEqual({+ functionName: 'ACTIVE_SHEET_NAME',+ functionType: FunctionType.DefinedName,+ description: 'Sheet1!$B$2active comment',+ abstract: 'Sheet1!$B$2',+ functionParameter: [],+ });++ await commandService.executeCommand(RemoveDefinedNameMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ id: 'active-sheet',+ name: 'ACTIVE_SHEET_NAME',+ formulaOrRefString: 'Sheet1!$B$2',+ localSheetId: 'sheet1',+ });++ expect(descriptionService.hasDescription('ACTIVE_SHEET_NAME')).toBe(false);+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.tsnew file mode 100644index 0000000000..41195fc737--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/formula-auto-fill.controller.spec.ts@@ -0,0 +1,178 @@+/**+ * 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 { Dependency, Direction, Nullable } from '@univerjs/core';+import type { IAutoFillLocation } from '@univerjs/sheets';+import { LexerTreeBuilder } from '@univerjs/engine-formula';+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, AutoFillService, IAutoFillService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { FormulaAutoFillController } from '../formula-auto-fill.controller';++function createControllerTestBed() {+ const dependencies: Dependency[] = [+ [IAutoFillService, { useClass: AutoFillService }],+ [FormulaAutoFillController],+ ];++ return createFacadeTestBed(undefined, dependencies);+}++function createLocation(sourceRows: number[], targetRows: number[]): IAutoFillLocation {+ return {+ unitId: 'test',+ subUnitId: 'sheet1',+ source: {+ rows: sourceRows,+ cols: [0],+ },+ target: {+ rows: targetRows,+ cols: [0],+ },+ };+}++describe('FormulaAutoFillController', () => {+ const directions: Array<{ direction: Direction; expected: { offsetX: number; offsetY: number } }> = [+ { direction: 0, expected: { offsetX: 0, offsetY: -3 } },+ { direction: 1, expected: { offsetX: 2, offsetY: 0 } },+ { direction: 2, expected: { offsetX: 0, offsetY: 3 } },+ { direction: 3, expected: { offsetX: -4, offsetY: 0 } },+ ];++ let testBed: ReturnType<typeof createControllerTestBed>;++ beforeEach(() => {+ testBed = createControllerTestBed();+ testBed.injector.get(FormulaAutoFillController);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ testBed?.univer.dispose();+ });++ it('should register a formula auto-fill rule and recognize formula cells', () => {+ const autoFillService = testBed.injector.get(IAutoFillService);+ const formulaRule = autoFillService.getRules().find((rule) => rule.type === AUTO_FILL_DATA_TYPE.FORMULA);++ expect(formulaRule).toBeDefined();+ expect(formulaRule?.match({ f: '=SUM(A1)' }, testBed.injector as never)).toBe(true);+ expect(formulaRule?.match({ si: 'shared-id' }, testBed.injector as never)).toBe(true);+ expect(formulaRule?.match({ v: 1 }, testBed.injector as never)).toBe(false);++ expect(formulaRule?.isContinue({ type: AUTO_FILL_DATA_TYPE.FORMULA, cellData: { f: '=A1' } }, null)).toBe(true);+ expect(formulaRule?.isContinue({ type: AUTO_FILL_DATA_TYPE.NUMBER, cellData: { v: 1 } }, null)).toBe(false);+ });++ it('should offset copied formulas by direction and reuse the generated formula id', () => {+ const autoFillService = testBed.injector.get(IAutoFillService);+ const lexerTreeBuilder = testBed.injector.get(LexerTreeBuilder);+ const formulaRule = autoFillService.getRules().find((rule) => rule.type === AUTO_FILL_DATA_TYPE.FORMULA);++ expect(formulaRule).toBeDefined();+ if (!formulaRule || !formulaRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.COPY]) {+ throw new Error('Formula auto-fill copy rule is not registered');+ }++ const applyCopy = formulaRule.applyFunctions[AUTO_FILL_APPLY_TYPE.COPY];++ const moveFormulaRefOffsetSpy = vi+ .spyOn(lexerTreeBuilder, 'moveFormulaRefOffset')+ .mockImplementation((formula, offsetX, offsetY) => `${formula}|${offsetX},${offsetY}`);++ directions.forEach(({ direction, expected }) => {+ const result = applyCopy(+ {+ data: [{ f: '=SUM(A1)' }],+ index: [0],+ },+ 2,+ direction,+ {+ formula: [{+ data: [{ f: '=SUM(A1)' }, { f: '=SUM(B1)' }],+ index: [0, 1],+ }],+ },+ createLocation([5], direction === 0 ? [2] : direction === 2 ? [8] : [5])+ );++ expect(result).toHaveLength(2);+ expect(result[0]).toMatchObject({+ f: `=SUM(A1)|${expected.offsetX},${expected.offsetY}`,+ si: expect.any(String),+ v: null,+ p: null,+ t: null,+ });+ expect(result[1]).toMatchObject({+ si: result[0]?.si,+ f: null,+ v: null,+ p: null,+ t: null,+ });+ });++ expect(moveFormulaRefOffsetSpy.mock.calls).toEqual([+ ['=SUM(A1)', 0, -3],+ ['=SUM(A1)', 2, 0],+ ['=SUM(A1)', 0, 3],+ ['=SUM(A1)', -4, 0],+ ]);+ });++ it('should preserve shared formula ids and skip non-formula or null cells', () => {+ const autoFillService = testBed.injector.get(IAutoFillService);+ const formulaRule = autoFillService.getRules().find((rule) => rule.type === AUTO_FILL_DATA_TYPE.FORMULA);++ expect(formulaRule).toBeDefined();+ if (!formulaRule || !formulaRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.COPY]) {+ throw new Error('Formula auto-fill copy rule is not registered');+ }++ const applyCopy = formulaRule.applyFunctions[AUTO_FILL_APPLY_TYPE.COPY];++ const result = applyCopy(+ {+ data: [{ si: 'shared-id' }, { v: 1 }, null] as Array<Nullable<{ si?: string; v?: number }>>,+ index: [0, 1, 2],+ },+ 3,+ 2,+ {+ formula: [{+ data: [{ si: 'shared-id' }],+ index: [0],+ }],+ },+ createLocation([0, 1, 2], [3, 4, 5])+ );++ expect(result).toEqual([+ {+ si: 'shared-id',+ f: null,+ v: null,+ p: null,+ t: null,+ },+ ]);+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.tsnew file mode 100644index 0000000000..f8d708e4ec--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/formula.controller.spec.ts@@ -0,0 +1,46 @@+/**+ * 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 { 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';+import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { FormulaController } from '../formula.controller';++describe('FormulaController', () => {+ afterEach(() => {+ // each test disposes its own univer instance+ });++ it('registers formula-related commands through the real command service', () => {+ const testBed = createFacadeTestBed(undefined, [[FormulaController]]);+ const commandService = testBed.injector.get(ICommandService);++ 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__/image-formula-cell-interceptor.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/image-formula-cell-interceptor.controller.spec.tsnew file mode 100644index 0000000000..d5a747b87d--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/image-formula-cell-interceptor.controller.spec.ts@@ -0,0 +1,191 @@+/**+ * 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 { Dependency, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import type { IImageFormulaInfo } from '@univerjs/engine-formula';+import { CellValueType, ICommandService, InterceptorEffectEnum, LocaleType, ObjectMatrix } from '@univerjs/core';+import { ErrorType, FormulaDataModel, SetImageFormulaDataMutation } from '@univerjs/engine-formula';+import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { ImageFormulaCellInterceptorController } from '../image-formula-cell-interceptor.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ },+ styles: {},+ };+}++function createControllerTestBed() {+ const dependencies: Dependency[] = [[ImageFormulaCellInterceptorController]];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++function getInterceptedCell(worksheet: Worksheet, workbook: Workbook, row: number, col: number, interceptorService: SheetInterceptorService) {+ const rawData = worksheet.getCellRaw(row, col);++ return interceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, InterceptorEffectEnum.Value)(+ rawData,+ {+ unitId: workbook.getUnitId(),+ subUnitId: worksheet.getSheetId(),+ row,+ col,+ worksheet,+ workbook,+ rawData,+ }+ );+}++async function waitForAssertion(assertion: () => void, timeout = 1000, interval = 10) {+ const start = Date.now();++ while (Date.now() - start < timeout) {+ try {+ assertion();+ return;+ } catch {+ await new Promise((resolve) => setTimeout(resolve, interval));+ }+ }++ assertion();+}++describe('ImageFormulaCellInterceptorController', () => {+ let testBed: ReturnType<typeof createControllerTestBed>;+ let controller: ImageFormulaCellInterceptorController;+ let commandService: ICommandService;+ let formulaDataModel: FormulaDataModel;+ let interceptorService: SheetInterceptorService;+ let workbook: Workbook;+ let worksheet: Worksheet;++ beforeEach(() => {+ testBed = createControllerTestBed();+ commandService = testBed.injector.get(ICommandService);+ commandService.registerCommand(SetImageFormulaDataMutation);+ controller = testBed.injector.get(ImageFormulaCellInterceptorController);+ formulaDataModel = testBed.injector.get(FormulaDataModel);+ interceptorService = testBed.injector.get(SheetInterceptorService);+ workbook = testBed.sheet as Workbook;+ worksheet = workbook.getActiveSheet()!;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ testBed?.univer.dispose();+ });++ it('hydrates natural image size from mutation data and injects a document snapshot into cell content', async () => {+ const refreshRender = vi.fn();++ class MockImage {+ width = 320;+ height = 240;+ private _src = '';+ onload: null | (() => void) = null;+ onerror: null | (() => void) = null;++ get src() {+ return this._src;+ }++ set src(value: string) {+ this._src = value;+ if (value === 'https://img.test/success.png') {+ queueMicrotask(() => this.onload?.());+ } else {+ queueMicrotask(() => this.onerror?.());+ }+ }+ }++ vi.stubGlobal('Image', MockImage as unknown as typeof Image);+ controller.registerRefreshRenderFunction(refreshRender);++ await commandService.executeCommand(SetImageFormulaDataMutation.id, {+ imageFormulaData: [{+ unitId: 'test',+ sheetId: 'sheet1',+ row: 0,+ column: 0,+ source: 'https://img.test/success.png',+ }],+ });+ await waitForAssertion(() => {+ expect(formulaDataModel.getUnitImageFormulaData()?.test?.sheet1?.getValue(0, 0)).toMatchObject({+ source: 'https://img.test/success.png',+ imageNaturalWidth: 320,+ imageNaturalHeight: 240,+ isErrorImage: false,+ });+ });+ expect(refreshRender).toHaveBeenCalledTimes(1);+ expect(getInterceptedCell(worksheet, workbook, 0, 0, interceptorService)).toEqual(expect.objectContaining({+ p: expect.any(Object),+ }));+ });++ it('returns VALUE errors for failed images and ignores empty mutation payloads', async () => {+ const refreshRender = vi.fn();++ controller.registerRefreshRenderFunction(refreshRender);++ await commandService.executeCommand(SetImageFormulaDataMutation.id, {+ imageFormulaData: [],+ });+ expect(refreshRender).not.toHaveBeenCalled();++ const matrix = new ObjectMatrix<IImageFormulaInfo>();+ matrix.setValue(1, 1, {+ altText: '',+ sizing: 0,+ height: 0,+ width: 0,+ source: 'https://img.test/fail.png',+ isErrorImage: true,+ });+ formulaDataModel.mergeUnitImageFormulaData({+ test: {+ sheet1: matrix,+ },+ });++ expect(getInterceptedCell(worksheet, workbook, 1, 1, interceptorService)).toEqual({+ v: ErrorType.VALUE,+ t: CellValueType.STRING,+ });+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/super-table.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/super-table.controller.spec.tsnew file mode 100644index 0000000000..a869c4ce8e--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/super-table.controller.spec.ts@@ -0,0 +1,191 @@+/**+ * 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 { Dependency, IWorkbookData } from '@univerjs/core';+import type { ISuperTable } from '@univerjs/engine-formula';+import type { ITestBed } from '../../facade/__tests__/create-test-bed';+import { ICommandService, IUniverInstanceService, LocaleType, UniverInstanceType } from '@univerjs/core';+import { FunctionType, ISuperTableService, RemoveSuperTableMutation, serializeRangeWithSheet, SetSuperTableMutation, SuperTableService } from '@univerjs/engine-formula';+import { SetWorksheetActiveOperation } from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { DescriptionService, IDescriptionService } from '../../services/description.service';+import { SuperTableController } from '../super-table.controller';++function createWorkbookData(id = 'test'): IWorkbookData {+ return {+ id,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: id,+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ },+ styles: {},+ };+}++function createSuperTableReference(sheetId: string): ISuperTable {+ return {+ sheetId,+ titleMap: new Map(),+ range: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ };+}++function createControllerTestBed(): ITestBed {+ const dependencies: Dependency[] = [+ [IDescriptionService, { useClass: DescriptionService }],+ [ISuperTableService, { useClass: SuperTableService }],+ [SuperTableController],+ ];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++describe('SuperTableController', () => {+ let testBed: ITestBed;++ afterEach(() => {+ testBed?.univer.dispose();+ });++ it('should register table descriptions and refresh them when current unit changes', () => {+ testBed = createControllerTestBed();++ const injector = testBed.injector;+ const descriptionService = injector.get(IDescriptionService);+ const superTableService = injector.get(ISuperTableService);+ const univerInstanceService = injector.get(IUniverInstanceService);++ injector.get(SuperTableController);++ superTableService.registerTable('test', 'TABLE_ONE', createSuperTableReference('sheet1'));+ superTableService.registerTable('test', 'TABLE_TWO', createSuperTableReference('sheet2'));++ expect(descriptionService.getFunctionInfo('TABLE_ONE')).toEqual({+ functionName: 'TABLE_ONE',+ functionType: FunctionType.Table,+ description: serializeRangeWithSheet('Sheet1', createSuperTableReference('sheet1').range),+ abstract: serializeRangeWithSheet('Sheet1', createSuperTableReference('sheet1').range),+ functionParameter: [],+ });+ expect(descriptionService.hasDescription('TABLE_TWO')).toBe(true);++ testBed.univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData('secondary'));+ univerInstanceService.setCurrentUnitForType('test');+ superTableService.registerTable('secondary', 'TABLE_THREE', createSuperTableReference('sheet1'));++ univerInstanceService.setCurrentUnitForType('secondary');++ expect(descriptionService.hasDescription('TABLE_ONE')).toBe(false);+ expect(descriptionService.hasDescription('TABLE_TWO')).toBe(false);+ expect(descriptionService.hasDescription('TABLE_THREE')).toBe(true);+ });++ it('should register and remove table descriptions through mutations', async () => {+ testBed = createControllerTestBed();++ const injector = testBed.injector;+ const commandService = injector.get(ICommandService);+ const descriptionService = injector.get(IDescriptionService);+ const reference = createSuperTableReference('sheet2');+ const expectedRef = serializeRangeWithSheet('Sheet2', reference.range);++ commandService.registerCommand(SetSuperTableMutation);+ commandService.registerCommand(RemoveSuperTableMutation);+ injector.get(SuperTableController);++ await commandService.executeCommand(SetSuperTableMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet2',+ tableName: 'TABLE_MUTATION',+ reference,+ });++ expect(descriptionService.getFunctionInfo('TABLE_MUTATION')).toEqual({+ functionName: 'TABLE_MUTATION',+ functionType: FunctionType.Table,+ description: expectedRef,+ abstract: expectedRef,+ functionParameter: [],+ });++ await commandService.executeCommand(RemoveSuperTableMutation.id, {+ unitId: 'test',+ tableName: 'TABLE_MUTATION',+ });++ expect(descriptionService.hasDescription('TABLE_MUTATION')).toBe(false);+ });++ it('should ignore collaborative sheet switches and skip unknown mutation targets', async () => {+ testBed = createControllerTestBed();++ const injector = testBed.injector;+ const commandService = injector.get(ICommandService);+ const descriptionService = injector.get(IDescriptionService);+ const superTableService = injector.get(ISuperTableService);++ commandService.registerCommand(SetWorksheetActiveOperation);+ commandService.registerCommand(SetSuperTableMutation);+ injector.get(SuperTableController);++ superTableService.registerTable('test', 'TABLE_ONE', createSuperTableReference('sheet1'));++ await commandService.executeCommand(+ SetWorksheetActiveOperation.id,+ {+ unitId: 'test',+ subUnitId: 'sheet2',+ },+ {+ fromCollab: true,+ }+ );++ expect(descriptionService.hasDescription('TABLE_ONE')).toBe(true);++ await commandService.executeCommand(SetSuperTableMutation.id, {+ unitId: 'missing-unit',+ subUnitId: 'sheet1',+ tableName: 'UNKNOWN_TABLE',+ reference: createSuperTableReference('sheet1'),+ });++ expect(descriptionService.hasDescription('UNKNOWN_TABLE')).toBe(false);+ });+});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.tsnew file mode 100644index 0000000000..60da8b4020--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/trigger-calculation.controller.spec.ts@@ -0,0 +1,350 @@+/**+ * 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 { Dependency, IWorkbookData } from '@univerjs/core';+import type { IExecutionInProgressParams } from '@univerjs/engine-formula';+import {+ CommandType,+ ICommandService,+ IConfigService,+ LocaleType,+} from '@univerjs/core';+import {+ ActiveDirtyManagerService,+ ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,+ ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,+ FormulaDataModel,+ FormulaExecutedStateType,+ FormulaExecuteStageType,+ IActiveDirtyManagerService,+ RegisterOtherFormulaService,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+ SetFormulaStringBatchCalculationMutation,+ SetTriggerFormulaCalculationStartMutation,+} from '@univerjs/engine-formula';+import { SetRangeValuesMutation, SetStyleCommand } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../config.schema';+import { TriggerCalculationController } from '../trigger-calculation.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { f: '=SUM(B1)' },+ },+ },+ },+ },+ styles: {},+ };+}++function createControllerTestBed() {+ const dependencies: Dependency[] = [+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [RegisterOtherFormulaService],+ [TriggerCalculationController],+ ];++ const testBed = createFacadeTestBed(createWorkbookData(), dependencies);+ const injector = testBed.injector;+ const commandService = injector.get(ICommandService);+ const configService = injector.get(IConfigService);++ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, { initialFormulaComputing: CalculationMode.WHEN_EMPTY }, { merge: true });+ configService.setConfig(ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, true);+ configService.setConfig(ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, 7);++ [+ SetTriggerFormulaCalculationStartMutation,+ SetFormulaCalculationStartMutation,+ SetFormulaCalculationStopMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaStringBatchCalculationMutation,+ SetRangeValuesMutation,+ ].forEach((command) => commandService.registerCommand(command));++ commandService.registerCommand({+ id: 'formula.test-dirty-1',+ type: CommandType.COMMAND,+ handler: () => true,+ });+ commandService.registerCommand({+ id: 'formula.test-dirty-2',+ type: CommandType.COMMAND,+ handler: () => true,+ });+ commandService.registerCommand({+ id: 'formula.test-dirty-restart',+ type: CommandType.COMMAND,+ handler: () => true,+ });++ const executedCommands: Array<{ id: string; params?: object; options?: object }> = [];+ const executedDisposable = commandService.onCommandExecuted((command, options) => {+ executedCommands.push({+ id: command.id,+ params: command.params as object | undefined,+ options: options as object | undefined,+ });+ });++ const controller = injector.get(TriggerCalculationController);++ return {+ testBed,+ controller,+ commandService,+ formulaDataModel: injector.get(FormulaDataModel),+ activeDirtyManagerService: injector.get(IActiveDirtyManagerService),+ registerOtherFormulaService: injector.get(RegisterOtherFormulaService),+ executedCommands,+ executedDisposable,+ };+}++describe('TriggerCalculationController', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ 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 testBed.commandService.executeCommand(SetFormulaStringBatchCalculationMutation.id, {});++ expect(testBed.executedCommands.find((command) => command.id === SetFormulaCalculationStartMutation.id)).toMatchObject({+ id: SetFormulaCalculationStartMutation.id,+ params: expect.objectContaining({+ isCalculateTreeModel: true,+ maxIteration: 7,+ rowData: testBed.formulaDataModel.getHiddenRowsFiltered(),+ }),+ });+ expect(testBed.executedCommands.find((command) => command.id === SetFormulaStringBatchCalculationMutation.id)).toMatchObject({+ id: SetFormulaStringBatchCalculationMutation.id,+ params: expect.objectContaining({+ maxIteration: 7,+ rowData: testBed.formulaDataModel.getHiddenRowsFiltered(),+ }),+ });++ testBed.executedDisposable.dispose();+ testBed.testBed.univer.dispose();+ });++ it('should merge dirty data from real active-dirty registrations and skip style-triggered range updates', async () => {+ const testBed = createControllerTestBed();++ testBed.activeDirtyManagerService.register('formula.test-dirty-1', {+ commandId: 'formula.test-dirty-1',+ getDirtyData: () => ({+ dirtyRanges: [+ { unitId: 'test', sheetId: 'sheet1', range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 } },+ { unitId: 'test', sheetId: 'sheet1', range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 } },+ ],+ dirtyNameMap: { test: { sheet1: '1' } },+ dirtyDefinedNameMap: { test: { sheet1: '1' } },+ dirtyUnitFeatureMap: { test: { sheet1: { featureA: true } } },+ dirtyUnitOtherFormulaMap: { test: { sheet1: { formulaA: true } } },+ clearDependencyTreeCache: { test: { sheet1: '1' } },+ }),+ });+ testBed.activeDirtyManagerService.register('formula.test-dirty-2', {+ commandId: 'formula.test-dirty-2',+ getDirtyData: () => ({+ dirtyRanges: [{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 2, startColumn: 0, endRow: 3, endColumn: 1 } }],+ dirtyUnitFeatureMap: { test: { sheet1: { featureB: false } } },+ forceCalculation: true,+ }),+ });+ testBed.activeDirtyManagerService.register(SetRangeValuesMutation.id, {+ commandId: SetRangeValuesMutation.id,+ getDirtyData: () => ({+ dirtyRanges: [{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 9, startColumn: 9, endRow: 9, endColumn: 9 } }],+ }),+ });++ testBed.executedCommands.length = 0;++ await testBed.commandService.executeCommand('formula.test-dirty-1');+ await testBed.commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ trigger: SetStyleCommand.id,+ cellValue: { 0: { 0: { v: 1 } } },+ });+ await testBed.commandService.executeCommand('formula.test-dirty-2');++ await vi.advanceTimersByTimeAsync(150);++ const startCommand = testBed.executedCommands.findLast((command) => command.id === SetFormulaCalculationStartMutation.id);++ expect(startCommand).toMatchObject({+ params: {+ forceCalculation: true,+ dirtyRanges: [+ { unitId: 'test', sheetId: 'sheet1', range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 } },+ { unitId: 'test', sheetId: 'sheet1', range: { startRow: 2, startColumn: 0, endRow: 3, endColumn: 1 } },+ ],+ dirtyNameMap: { test: { sheet1: '1' } },+ dirtyDefinedNameMap: { test: { sheet1: '1' } },+ dirtyUnitFeatureMap: { test: { sheet1: { featureA: true, featureB: false } } },+ dirtyUnitOtherFormulaMap: { test: { sheet1: { formulaA: true } } },+ clearDependencyTreeCache: { test: { sheet1: '1' } },+ },+ options: { onlyLocal: true },+ });++ testBed.executedDisposable.dispose();+ testBed.testBed.univer.dispose();+ });++ it('should stop and restart calculation through real notification flow', async () => {+ const testBed = createControllerTestBed();++ testBed.activeDirtyManagerService.register('formula.test-dirty-restart', {+ commandId: 'formula.test-dirty-restart',+ getDirtyData: () => ({+ dirtyRanges: [{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 4, startColumn: 0, endRow: 4, endColumn: 1 } }],+ }),+ });++ testBed.executedCommands.length = 0;++ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ totalFormulasToCalculate: 1,+ completedFormulasCount: 0,+ totalArrayFormulasToCalculate: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,+ } as IExecutionInProgressParams,+ });+ await testBed.commandService.executeCommand('formula.test-dirty-restart');++ await vi.advanceTimersByTimeAsync(150);++ expect(testBed.executedCommands.findLast((command) => command.id === SetFormulaCalculationStopMutation.id)).toBeDefined();++ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ functionsExecutedState: FormulaExecutedStateType.STOP_EXECUTION,+ });++ await Promise.resolve();++ expect(testBed.executedCommands.findLast((command) => command.id === SetFormulaCalculationStartMutation.id)).toMatchObject({+ options: { onlyLocal: true },+ params: expect.objectContaining({+ dirtyRanges: [{ unitId: 'test', sheetId: 'sheet1', range: { startRow: 4, startColumn: 0, endRow: 4, endColumn: 1 } }],+ }),+ });++ testBed.executedDisposable.dispose();+ testBed.testBed.univer.dispose();+ });++ it('should publish progress updates through real notification commands', async () => {+ const testBed = createControllerTestBed();+ const progressValues: Array<{ done: number; count: number; label?: string }> = [];+ const subscription = testBed.controller.progress$.subscribe((value) => progressValues.push(value));++ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ stage: FormulaExecuteStageType.START,+ totalFormulasToCalculate: 0,+ completedFormulasCount: 0,+ totalArrayFormulasToCalculate: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ } as IExecutionInProgressParams,+ });+ vi.advanceTimersByTime(1000);++ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING,+ totalFormulasToCalculate: 5,+ completedFormulasCount: 2,+ totalArrayFormulasToCalculate: 3,+ completedArrayFormulasCount: 1,+ formulaCycleIndex: 0,+ } as IExecutionInProgressParams,+ });+ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ stage: FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA,+ totalFormulasToCalculate: 5,+ completedFormulasCount: 2,+ totalArrayFormulasToCalculate: 3,+ completedArrayFormulasCount: 1,+ formulaCycleIndex: 0,+ } as IExecutionInProgressParams,+ });+ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ stageInfo: {+ stage: FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA,+ totalFormulasToCalculate: 5,+ completedFormulasCount: 4,+ totalArrayFormulasToCalculate: 3,+ completedArrayFormulasCount: 2,+ formulaCycleIndex: 0,+ } as IExecutionInProgressParams,+ });+ await testBed.commandService.executeCommand(SetFormulaCalculationNotificationMutation.id, {+ functionsExecutedState: FormulaExecutedStateType.SUCCESS,+ });++ expect(progressValues).toContainEqual({ done: 0, count: 1, label: 'formula.progress.analyzing' });+ expect(progressValues).toContainEqual({ done: 3, count: 8, label: 'formula.progress.calculating' });+ expect(progressValues).toContainEqual({ done: 3, count: 8, label: 'formula.progress.array-analysis' });+ expect(progressValues).toContainEqual({ done: 6, count: 8, label: 'formula.progress.array-calculation' });+ expect(progressValues).toContainEqual({ done: 1, count: 1, label: 'formula.progress.done' });++ subscription.unsubscribe();+ testBed.executedDisposable.dispose();+ testBed.testBed.univer.dispose();+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/update-defined-name.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-defined-name.controller.spec.tsnew file mode 100644index 0000000000..cfa81b6591--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/update-defined-name.controller.spec.ts@@ -0,0 +1,219 @@+/**+ * 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 { Dependency, IWorkbookData } from '@univerjs/core';+import { LocaleType } from '@univerjs/core';+import { ErrorType, IDefinedNamesService, SetDefinedNameMutation } from '@univerjs/engine-formula';+import { MoveRangeCommand, RemoveDefinedNameCommand, RemoveSheetCommand, SetDefinedNameCommand, SetWorksheetNameCommand, SheetInterceptorService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { UpdateDefinedNameController } from '../update-defined-name.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ },+ styles: {},+ };+}++function createControllerTestBed() {+ const dependencies: Dependency[] = [[UpdateDefinedNameController]];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++describe('UpdateDefinedNameController', () => {+ let testBed: ReturnType<typeof createControllerTestBed>;++ beforeEach(() => {+ testBed = createControllerTestBed();++ const definedNamesService = testBed.injector.get(IDefinedNamesService);+ definedNamesService.registerDefinedNames('test', {+ rangeName: {+ id: 'range-name',+ name: 'RANGE_NAME',+ formulaOrRefString: 'Sheet1!$A$1:$B$2',+ localSheetId: 'AllDefaultWorkbook',+ comment: '',+ },+ rowsName: {+ id: 'rows-name',+ name: 'ROWS_NAME',+ formulaOrRefString: 'Sheet1!$1:$3',+ localSheetId: 'AllDefaultWorkbook',+ comment: '',+ },+ otherSheetName: {+ id: 'other-sheet-name',+ name: 'OTHER_SHEET_NAME',+ formulaOrRefString: 'Sheet2!$C$3',+ localSheetId: 'AllDefaultWorkbook',+ comment: '',+ },+ });++ testBed.injector.get(UpdateDefinedNameController);+ });++ afterEach(() => {+ testBed?.univer.dispose();+ });++ it('should ignore commands that are handled by UpdateFormulaController', () => {+ const interceptorService = testBed.injector.get(SheetInterceptorService);++ const setDefinedNameResult = interceptorService.onCommandExecute({+ id: SetDefinedNameCommand.id,+ params: {+ unitId: 'test',+ id: 'temp',+ name: 'TEMP_NAME',+ formulaOrRefString: 'Sheet1!$A$1',+ localSheetId: 'AllDefaultWorkbook',+ },+ });+ const removeDefinedNameResult = interceptorService.onCommandExecute({+ id: RemoveDefinedNameCommand.id,+ params: {+ unitId: 'test',+ id: 'range-name',+ name: 'RANGE_NAME',+ },+ });++ expect(setDefinedNameResult).toEqual({ redos: [], undos: [], preRedos: [], preUndos: [] });+ expect(removeDefinedNameResult).toEqual({ redos: [], undos: [], preRedos: [], preUndos: [] });+ });++ it('should generate undo and redo mutations for moved references', () => {+ const interceptorService = testBed.injector.get(SheetInterceptorService);++ const result = interceptorService.onCommandExecute({+ id: MoveRangeCommand.id,+ params: {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ toRange: {+ startRow: 0,+ startColumn: 3,+ endRow: 1,+ endColumn: 4,+ rangeType: 0,+ },+ },+ });++ expect(result.redos).toContainEqual({+ id: SetDefinedNameMutation.id,+ params: expect.objectContaining({+ unitId: 'test',+ name: 'RANGE_NAME',+ formulaOrRefString: 'Sheet1!$D$1:$E$2',+ }),+ });+ expect(result.undos).toContainEqual({+ id: SetDefinedNameMutation.id,+ params: expect.objectContaining({+ unitId: 'test',+ name: 'RANGE_NAME',+ formulaOrRefString: 'Sheet1!$A$1:$B$2',+ }),+ });+ });++ it('should rename references on the targeted sheet and skip references on other sheets', () => {+ const interceptorService = testBed.injector.get(SheetInterceptorService);++ const result = interceptorService.onCommandExecute({+ id: SetWorksheetNameCommand.id,+ params: {+ subUnitId: 'sheet1',+ name: 'Sheet1Rename',+ },+ });++ expect(result.redos).toContainEqual({+ id: SetDefinedNameMutation.id,+ params: expect.objectContaining({+ name: 'RANGE_NAME',+ formulaOrRefString: 'Sheet1Rename!$A$1:$B$2',+ }),+ });+ expect(result.redos).toContainEqual({+ id: SetDefinedNameMutation.id,+ params: expect.objectContaining({+ name: 'ROWS_NAME',+ formulaOrRefString: 'Sheet1Rename!$1:$3',+ }),+ });+ expect(result.redos.find((mutation) => (mutation.params as { name?: string } | undefined)?.name === 'OTHER_SHEET_NAME')).toBeUndefined();+ });++ it('should turn references into REF errors when the referenced sheet is removed', () => {+ const interceptorService = testBed.injector.get(SheetInterceptorService);++ const result = interceptorService.onCommandExecute({+ id: RemoveSheetCommand.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ },+ });++ expect(result.redos).toContainEqual({+ id: SetDefinedNameMutation.id,+ params: expect.objectContaining({+ name: 'RANGE_NAME',+ formulaOrRefString: ErrorType.REF,+ }),+ });+ expect(result.redos).toContainEqual({+ id: SetDefinedNameMutation.id,+ params: expect.objectContaining({+ name: 'ROWS_NAME',+ formulaOrRefString: ErrorType.REF,+ }),+ });+ expect(result.redos.find((mutation) => (mutation.params as { name?: string } | undefined)?.name === 'OTHER_SHEET_NAME')).toBeUndefined();+ });+});diff --git a/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.tsnew file mode 100644index 0000000000..05ecaf5700--- /dev/null+++ b/packages/sheets-formula/src/controllers/__tests__/update-formula.controller.spec.ts@@ -0,0 +1,324 @@+/**+ * 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 { Dependency, ICellData, IWorkbookData, Nullable, Workbook } from '@univerjs/core';+import { CellValueType, ICommandService, IConfigService, IUniverInstanceService, LocaleType, UniverInstanceType } from '@univerjs/core';+import { FormulaDataModel, SetArrayFormulaDataMutation, SetFormulaDataMutation, SetTriggerFormulaCalculationStartMutation } from '@univerjs/engine-formula';+import { InsertSheetMutation, MoveRangeCommand, MoveRangeMutation, RemoveSheetCommand, RemoveSheetMutation, SetRangeValuesCommand, SetRangeValuesMutation, SetSelectionsOperation, SetStyleCommand, SetWorksheetNameCommand, SheetInterceptorService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';+import { CalculationMode, PLUGIN_CONFIG_KEY_BASE } from '../config.schema';+import { UpdateFormulaController } from '../update-formula.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1', 'sheet2'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: 1, t: CellValueType.NUMBER },+ 1: { v: 1, t: CellValueType.NUMBER },+ },+ 1: {+ 0: { v: 1, t: CellValueType.NUMBER },+ 1: { v: 1, t: CellValueType.NUMBER },+ },+ 5: {+ 2: { f: '=SUM(A1:B2)' },+ 3: { v: 1, t: CellValueType.NUMBER },+ },+ },+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { f: '=Sheet1!A1:B2' },+ 1: { f: '=RANGE_NAME' },+ },+ },+ },+ },+ styles: {},+ };+}++function createControllerTestBed() {+ const dependencies: Dependency[] = [[UpdateFormulaController]];++ return createFacadeTestBed(createWorkbookData(), dependencies);+}++describe('UpdateFormulaController', () => {+ let testBed: ReturnType<typeof createControllerTestBed>;+ let commandService: ICommandService;+ let formulaDataModel: FormulaDataModel;++ beforeEach(() => {+ testBed = createControllerTestBed();+ commandService = testBed.injector.get(ICommandService);+ formulaDataModel = testBed.injector.get(FormulaDataModel);++ commandService.registerCommand(MoveRangeCommand);+ commandService.registerCommand(MoveRangeMutation);+ commandService.registerCommand(InsertSheetMutation);+ commandService.registerCommand(RemoveSheetMutation);+ commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(SetRangeValuesCommand);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(SetFormulaDataMutation);+ commandService.registerCommand(SetArrayFormulaDataMutation);++ testBed.injector.get(UpdateFormulaController);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ testBed?.univer.dispose();+ });++ it('should update formula references when a referenced range moves', async () => {+ expect(await commandService.executeCommand(MoveRangeCommand.id, {+ fromRange: {+ startRow: 0,+ startColumn: 0,+ endRow: 1,+ endColumn: 1,+ rangeType: 0,+ },+ toRange: {+ startRow: 0,+ startColumn: 3,+ endRow: 1,+ endColumn: 4,+ rangeType: 0,+ },+ })).toBe(true);++ const values = testBed.injector+ .get(IUniverInstanceService)+ .getUnit<Workbook>('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(5, 2, 5, 2)+ .getValues() as Array<Array<Nullable<ICellData>>>;++ expect(values).toEqual([[{ f: '=SUM(D1:E2)' }]]);+ });++ it('should move the formula cell itself without changing its formula string', async () => {+ expect(await commandService.executeCommand(MoveRangeCommand.id, {+ fromRange: {+ startRow: 5,+ startColumn: 2,+ endRow: 5,+ endColumn: 2,+ rangeType: 0,+ },+ toRange: {+ startRow: 5,+ startColumn: 3,+ endRow: 5,+ endColumn: 3,+ rangeType: 0,+ },+ })).toBe(true);++ const values = testBed.injector+ .get(IUniverInstanceService)+ .getUnit<Workbook>('test')+ ?.getSheetBySheetId('sheet1')+ ?.getRange(5, 2, 5, 3)+ .getValues() as Array<Array<Nullable<ICellData>>>;++ expect(values).toEqual([[null, { f: '=SUM(A1:B2)' }]]);+ });++ it('should rewrite formulas when referenced sheets change', () => {+ const sheetInterceptorService = testBed.injector.get(SheetInterceptorService);++ const renameSheetResult = sheetInterceptorService.onCommandExecute({+ id: SetWorksheetNameCommand.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ name: 'Sheet1Renamed',+ },+ });++ expect(renameSheetResult.redos).toEqual(expect.arrayContaining([+ expect.objectContaining({+ id: SetRangeValuesMutation.id,+ params: expect.objectContaining({+ unitId: 'test',+ subUnitId: 'sheet2',+ cellValue: {+ 0: {+ 0: expect.objectContaining({ f: '=Sheet1Renamed!A1:B2' }),+ },+ },+ }),+ }),+ ]));+ expect(renameSheetResult.undos).toEqual(expect.arrayContaining([+ expect.objectContaining({+ id: SetRangeValuesMutation.id,+ params: expect.objectContaining({+ unitId: 'test',+ subUnitId: 'sheet2',+ cellValue: {+ 0: {+ 0: expect.objectContaining({ f: '=Sheet1!A1:B2' }),+ },+ },+ }),+ }),+ ]));++ const removeSheetResult = sheetInterceptorService.onCommandExecute({+ id: RemoveSheetCommand.id,+ params: {+ unitId: 'test',+ subUnitId: 'sheet1',+ },+ });++ expect(removeSheetResult.redos).toEqual(expect.arrayContaining([+ expect.objectContaining({+ id: SetRangeValuesMutation.id,+ params: expect.objectContaining({+ unitId: 'test',+ subUnitId: 'sheet2',+ cellValue: {+ 0: {+ 0: expect.objectContaining({ f: '=#REF!' }),+ },+ },+ }),+ }),+ ]));+ });++ it('should sync formula data for value mutations and ignore style-only updates', async () => {+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');++ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 6: {+ 0: { f: '=A1' },+ },+ },+ });++ expect(formulaDataModel.getFormulaData().test?.sheet1?.[6]?.[0]).toMatchObject({ f: '=A1' });++ const formulaSyncCallCount = executeCommandSpy.mock.calls.filter(([id]) => id === SetFormulaDataMutation.id).length;++ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ trigger: SetStyleCommand.id,+ cellValue: {+ 7: {+ 0: { f: '=B1' },+ },+ },+ });++ expect(executeCommandSpy.mock.calls.filter(([id]) => id === SetFormulaDataMutation.id)).toHaveLength(formulaSyncCallCount);+ });++ it('should initialize formula data for added sheets and workbooks, then clear removed sheets', async () => {+ const configService = testBed.injector.get(IConfigService);+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand');+ const workbookSnapshot = testBed.injector.get(IUniverInstanceService).getUnit<Workbook>('test')?.getSnapshot();++ configService.setConfig(PLUGIN_CONFIG_KEY_BASE, {+ initialFormulaComputing: CalculationMode.FORCED,+ });++ await commandService.executeCommand(InsertSheetMutation.id, {+ unitId: 'test',+ sheet: {+ ...workbookSnapshot!.sheets.sheet1,+ id: 'sheet-added',+ name: 'Added Sheet',+ cellData: {+ 0: {+ 0: { f: '=Sheet1!A1' },+ },+ },+ },+ });++ expect(formulaDataModel.getFormulaData().test?.['sheet-added']?.[0]?.[0]).toMatchObject({ f: '=Sheet1!A1' });++ await commandService.executeCommand(RemoveSheetMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet-added',+ subUnitName: 'Added Sheet',+ });++ expect(formulaDataModel.getFormulaData().test?.['sheet-added']).toBeUndefined();++ testBed.univer.createUnit(UniverInstanceType.UNIVER_SHEET, {+ id: 'secondary',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'secondary',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { f: '=SUM(A1)' },+ },+ },+ },+ },+ styles: {},+ });++ expect(formulaDataModel.getFormulaData().secondary?.sheet1?.[0]?.[0]).toMatchObject({ f: '=SUM(A1)' });+ expect(executeCommandSpy).toHaveBeenCalledWith(+ SetTriggerFormulaCalculationStartMutation.id,+ expect.objectContaining({+ forceCalculation: true,+ }),+ {+ onlyLocal: true,+ }+ );+ });+});diff --git a/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.tsnew file mode 100644index 0000000000..51a667f85c--- /dev/null+++ b/packages/sheets-formula/src/controllers/utils/__tests__/ref-range-param.spec.ts@@ -0,0 +1,292 @@+/**+ * 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 { IWorkbookData, Workbook } from '@univerjs/core';+import { LocaleType, RANGE_TYPE } from '@univerjs/core';+import {+ DeleteRangeMoveLeftCommand,+ DeleteRangeMoveUpCommand,+ InsertColCommand,+ InsertRangeMoveDownCommand,+ InsertRangeMoveRightCommand,+ InsertRowCommand,+ MoveColsCommand,+ MoveRangeCommand,+ MoveRowsCommand,+ RemoveColCommand,+ RemoveDefinedNameCommand,+ RemoveRowCommand,+ RemoveSheetCommand,+ SetDefinedNameCommand,+ SetWorksheetNameCommand,+} from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';++import { createFacadeTestBed } from '../../../facade/__tests__/create-test-bed';+import { FormulaReferenceMoveType } from '../ref-range-formula';+import { getReferenceMoveParams } from '../ref-range-param';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ name: 'test',+ sheetOrder: ['sheet1'],+ locale: LocaleType.EN_US,+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 12,+ columnCount: 8,+ cellData: {},+ },+ },+ styles: {},+ };+}++describe('getReferenceMoveParams', () => {+ afterEach(() => {+ // disposal is handled per test to keep workbook state isolated+ });++ it('returns null for unknown commands or missing params', () => {+ const testBed = createFacadeTestBed(createWorkbookData());+ const workbook = testBed.sheet as Workbook;++ expect(getReferenceMoveParams(workbook, { id: 'unknown.command' })).toBeNull();+ expect(getReferenceMoveParams(workbook, { id: MoveRangeCommand.id })).toBeNull();+ expect(getReferenceMoveParams(workbook, { id: MoveRowsCommand.id })).toBeNull();++ testBed.univer.dispose();+ });++ it('builds move params for range, row, and column operations from the active sheet', () => {+ const testBed = createFacadeTestBed(createWorkbookData());+ const workbook = testBed.sheet as Workbook;++ expect(getReferenceMoveParams(workbook, {+ id: MoveRangeCommand.id,+ params: {+ fromRange: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ toRange: { startRow: 4, endRow: 5, startColumn: 3, endColumn: 4 },+ },+ })).toEqual({+ type: FormulaReferenceMoveType.MoveRange,+ unitId: 'test',+ sheetId: 'sheet1',+ from: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ to: { startRow: 4, endRow: 5, startColumn: 3, endColumn: 4 },+ });++ expect(getReferenceMoveParams(workbook, {+ id: MoveRowsCommand.id,+ params: {+ fromRange: { startRow: 2, endRow: 4, startColumn: 0, endColumn: 0 },+ toRange: { startRow: 6, endRow: 8, startColumn: 0, endColumn: 0 },+ },+ })).toEqual({+ type: FormulaReferenceMoveType.MoveRows,+ unitId: 'test',+ sheetId: 'sheet1',+ from: {+ startRow: 2,+ endRow: 4,+ startColumn: 0,+ endColumn: 7,+ rangeType: RANGE_TYPE.ROW,+ },+ to: {+ startRow: 6,+ endRow: 8,+ startColumn: 0,+ endColumn: 7,+ rangeType: RANGE_TYPE.ROW,+ },+ });++ expect(getReferenceMoveParams(workbook, {+ id: MoveColsCommand.id,+ params: {+ fromRange: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 2 },+ toRange: { startRow: 0, endRow: 0, startColumn: 4, endColumn: 5 },+ },+ })).toEqual({+ type: FormulaReferenceMoveType.MoveCols,+ unitId: 'test',+ sheetId: 'sheet1',+ from: {+ startRow: 0,+ endRow: 11,+ startColumn: 1,+ endColumn: 2,+ rangeType: RANGE_TYPE.COLUMN,+ },+ to: {+ startRow: 0,+ endRow: 11,+ startColumn: 4,+ endColumn: 5,+ rangeType: RANGE_TYPE.COLUMN,+ },+ });++ testBed.univer.dispose();+ });++ it('builds insert, remove, and delete params with the expected sheet identity', () => {+ const testBed = createFacadeTestBed(createWorkbookData());+ const workbook = testBed.sheet as Workbook;+ const range = { startRow: 3, endRow: 4, startColumn: 2, endColumn: 3 };++ expect(getReferenceMoveParams(workbook, {+ id: InsertRowCommand.id,+ params: { range, unitId: 'test', subUnitId: 'sheet1' },+ })).toEqual({+ type: FormulaReferenceMoveType.InsertRow,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });+ expect(getReferenceMoveParams(workbook, {+ id: InsertColCommand.id,+ params: { range, unitId: 'test', subUnitId: 'sheet1' },+ })).toEqual({+ type: FormulaReferenceMoveType.InsertColumn,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });+ expect(getReferenceMoveParams(workbook, {+ id: InsertRangeMoveRightCommand.id,+ params: { range },+ })).toEqual({+ type: FormulaReferenceMoveType.InsertMoveRight,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });+ expect(getReferenceMoveParams(workbook, {+ id: InsertRangeMoveDownCommand.id,+ params: { range },+ })).toEqual({+ type: FormulaReferenceMoveType.InsertMoveDown,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });+ expect(getReferenceMoveParams(workbook, {+ id: RemoveRowCommand.id,+ params: { range },+ })).toEqual({+ type: FormulaReferenceMoveType.RemoveRow,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ rangeFilteredRows: [],+ });+ expect(getReferenceMoveParams(workbook, {+ id: RemoveColCommand.id,+ params: { range },+ })).toEqual({+ type: FormulaReferenceMoveType.RemoveColumn,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });+ expect(getReferenceMoveParams(workbook, {+ id: DeleteRangeMoveUpCommand.id,+ params: { range },+ })).toEqual({+ type: FormulaReferenceMoveType.DeleteMoveUp,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });+ expect(getReferenceMoveParams(workbook, {+ id: DeleteRangeMoveLeftCommand.id,+ params: { range },+ })).toEqual({+ type: FormulaReferenceMoveType.DeleteMoveLeft,+ unitId: 'test',+ sheetId: 'sheet1',+ range,+ });++ testBed.univer.dispose();+ });++ it('builds sheet rename, sheet removal, and defined-name params with explicit ids', () => {+ const testBed = createFacadeTestBed(createWorkbookData());+ const workbook = testBed.sheet as Workbook;++ expect(getReferenceMoveParams(workbook, {+ id: SetWorksheetNameCommand.id,+ params: {+ unitId: 'other-unit',+ subUnitId: 'other-sheet',+ name: 'Renamed Sheet',+ },+ })).toEqual({+ type: FormulaReferenceMoveType.SetName,+ unitId: 'other-unit',+ sheetId: 'other-sheet',+ sheetName: 'Renamed Sheet',+ });+ expect(getReferenceMoveParams(workbook, {+ id: RemoveSheetCommand.id,+ params: {+ unitId: 'other-unit',+ subUnitId: 'other-sheet',+ },+ })).toEqual({+ type: FormulaReferenceMoveType.RemoveSheet,+ unitId: 'other-unit',+ sheetId: 'other-sheet',+ });+ expect(getReferenceMoveParams(workbook, {+ id: SetDefinedNameCommand.id,+ params: {+ unitId: 'test',+ id: 'defined-name-id',+ name: 'Revenue',+ },+ })).toEqual({+ type: FormulaReferenceMoveType.SetDefinedName,+ unitId: 'test',+ sheetId: 'sheet1',+ definedName: 'Revenue',+ definedNameId: 'defined-name-id',+ });+ expect(getReferenceMoveParams(workbook, {+ id: RemoveDefinedNameCommand.id,+ params: {+ unitId: 'test',+ id: 'defined-name-id',+ name: 'Revenue',+ },+ })).toEqual({+ type: FormulaReferenceMoveType.RemoveDefinedName,+ unitId: 'test',+ sheetId: 'sheet1',+ definedName: 'Revenue',+ definedNameId: 'defined-name-id',+ });++ testBed.univer.dispose();+ });+});diff --git a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.tsnew file mode 100644index 0000000000..b90e9d5f0d--- /dev/null+++ b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts@@ -0,0 +1,194 @@+/**+ * 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 { Injector } from '@univerjs/core';+import type { FUniver } from '@univerjs/core/facade';+import { CommandType, ICommandService, IConfigService, LifecycleService, LifecycleStages } from '@univerjs/core';+import { FormulaExecuteStageType, IFunctionService, ISuperTableService, SetFormulaCalculationResultMutation, SetTriggerFormulaCalculationStartMutation, SuperTableService } from '@univerjs/engine-formula';+import { SetRangeValuesMutation } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CalculationMode, DescriptionService, IDescriptionService, IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '../../index';+import { createFacadeTestBed } from './create-test-bed';++import '@univerjs/engine-formula/facade';+import '@univerjs/sheets/facade';+import '../../facade';++describe('sheets-formula facade mixins', () => {+ let get: Injector['get'];+ let univerAPI: FUniver;+ let disposeUniver: () => void;++ beforeEach(() => {+ const testBed = createFacadeTestBed();+ testBed.injector.add([IDescriptionService, { useClass: DescriptionService }]);+ testBed.injector.add([ISuperTableService, { useClass: SuperTableService }]);+ testBed.injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);++ get = testBed.get;+ univerAPI = testBed.univerAPI;+ disposeUniver = () => testBed.univer.dispose();+ });++ afterEach(() => {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ disposeUniver();+ });++ it('registers functions through FUniver and FFormula and triggers a debounced recalculation command', async () => {+ vi.useFakeTimers();++ const commandService = get(ICommandService);+ const functionService = get(IFunctionService);+ const executeCommandSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true);++ const univerDisposable = univerAPI.registerFunction({+ calculate: [+ [() => 1, 'UNIVER_SIDE', 'Registered from FUniver'],+ ],+ });++ const formula = univerAPI.getFormula();+ const formulaDisposable = formula.registerFunction('FORMULA_SIDE', (value) => Number(value) + 1, 'Registered from FFormula');+ const asyncDisposable = formula.registerAsyncFunction('FORMULA_ASYNC', async () => 2, 'Async formula');++ await vi.advanceTimersByTimeAsync(11);++ expect(get(IRegisterFunctionService)).toBeDefined();+ expect(functionService.hasExecutor('UNIVER_SIDE')).toBe(true);+ expect(functionService.hasExecutor('FORMULA_SIDE')).toBe(true);+ expect(functionService.hasExecutor('FORMULA_ASYNC')).toBe(true);+ expect(executeCommandSpy).toHaveBeenCalledWith(+ SetTriggerFormulaCalculationStartMutation.id,+ {+ commands: [],+ forceCalculation: true,+ },+ {+ onlyLocal: true,+ }+ );++ univerDisposable.dispose();+ formulaDisposable.dispose();+ asyncDisposable.dispose();++ expect(functionService.hasExecutor('UNIVER_SIDE')).toBe(false);+ expect(functionService.hasExecutor('FORMULA_SIDE')).toBe(false);+ expect(functionService.hasExecutor('FORMULA_ASYNC')).toBe(false);+ });++ it('updates initial calculation mode and warns after the Starting lifecycle', () => {+ const formula = univerAPI.getFormula();+ const configService = get(IConfigService);+ const lifecycleService = get(LifecycleService);++ formula.setInitialFormulaComputing(CalculationMode.FORCED);+ expect(configService.getConfig(PLUGIN_CONFIG_KEY_BASE)).toMatchObject({+ initialFormulaComputing: CalculationMode.FORCED,+ });++ lifecycleService.stage = LifecycleStages.Ready;++ expect(() => formula.setInitialFormulaComputing(CalculationMode.NO_CALCULATION)).not.toThrow();+ formula.setInitialFormulaComputing(CalculationMode.NO_CALCULATION);++ expect(configService.getConfig(PLUGIN_CONFIG_KEY_BASE)).toMatchObject({+ initialFormulaComputing: CalculationMode.NO_CALCULATION,+ });+ });++ it('fires calculationResultApplied only after result mutation and applied range update are both observed', async () => {+ vi.stubGlobal('requestIdleCallback', ((callback: IdleRequestCallback) => {+ callback({ didTimeout: false, timeRemaining: () => 16 } as IdleDeadline);+ return 1;+ }) as typeof requestIdleCallback);++ const commandService = get(ICommandService);+ commandService.registerCommand(SetFormulaCalculationResultMutation);+ commandService.registerCommand(SetRangeValuesMutation);++ const formula = univerAPI.getFormula();+ const resultPayload = {+ unitData: {},+ };++ await new Promise<void>((resolve) => {+ const disposable = formula.calculationResultApplied((result) => {+ expect(result).toEqual(resultPayload);+ disposable.dispose();+ resolve();+ });++ void commandService.executeCommand(SetFormulaCalculationResultMutation.id, resultPayload);+ void commandService.executeCommand(+ SetRangeValuesMutation.id,+ {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {},+ },+ {+ applyFormulaCalculationResult: true,+ }+ );+ });+ });++ it('resolves onCalculationResultApplied when no calculation actually starts', async () => {+ vi.useFakeTimers();++ const formula = univerAPI.getFormula();+ const waitForResult = formula.onCalculationResultApplied();++ await vi.advanceTimersByTimeAsync(500);++ await expect(waitForResult).resolves.toBeUndefined();+ });++ it('rejects onCalculationResultApplied when the wait exceeds the global timeout', async () => {+ vi.useFakeTimers();++ const commandService = get(ICommandService);+ commandService.registerCommand({+ id: SetFormulaCalculationResultMutation.id,+ type: CommandType.MUTATION,+ handler: () => true,+ });++ const formula = univerAPI.getFormula();+ vi.spyOn(formula, 'calculationProcessing').mockImplementation((callback) => {+ callback({+ stage: FormulaExecuteStageType.START_CALCULATION,+ completedFormulasCount: 0,+ completedArrayFormulasCount: 0,+ formulaCycleIndex: 0,+ totalArrayFormulasToCalculate: 1,+ totalFormulasToCalculate: 1,+ });++ return { dispose: () => {} };+ });+ vi.spyOn(formula, 'calculationResultApplied').mockReturnValue({ dispose: () => {} });++ const waitForResult = expect(formula.onCalculationResultApplied()).rejects.toThrowError('Calculation end timeout');++ await vi.advanceTimersByTimeAsync(60_000);++ await waitForResult;+ });+});diff --git a/packages/sheets-formula/src/services/__test__/description.service.spec.ts b/packages/sheets-formula/src/services/__test__/description.service.spec.tsnew file mode 100644index 0000000000..f42b58c69e--- /dev/null+++ b/packages/sheets-formula/src/services/__test__/description.service.spec.ts@@ -0,0 +1,167 @@+/**+ * 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 { IFunctionInfo } from '@univerjs/engine-formula';+import { IConfigService, LocaleService, LocaleType, Univer } from '@univerjs/core';+import { FunctionService, FunctionType, IFunctionService } from '@univerjs/engine-formula';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { PLUGIN_CONFIG_KEY_BASE } from '../../controllers/config.schema';+import { DescriptionService, IDescriptionService } from '../description.service';++function createFunctionInfo(overrides: Partial<IFunctionInfo> = {}): IFunctionInfo {+ return {+ functionName: overrides.functionName ?? 'CUSTOMFUNC',+ aliasFunctionName: overrides.aliasFunctionName,+ functionType: overrides.functionType ?? FunctionType.User,+ description: overrides.description ?? 'custom.desc',+ abstract: overrides.abstract ?? 'custom.abstract',+ functionParameter: overrides.functionParameter ?? [+ {+ name: 'custom.param.name',+ detail: 'custom.param.detail',+ example: '1',+ require: 1,+ repeat: 0,+ },+ ],+ };+}++describe('DescriptionService', () => {+ let univer: Univer;+ let localeService: LocaleService;+ let descriptionService: IDescriptionService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();++ localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.ZH_CN]: {},+ [LocaleType.EN_US]: {+ custom: {+ alias: 'CUSTOM_ALIAS',+ desc: 'Localized description',+ abstract: 'Localized abstract',+ param: {+ name: 'Localized parameter',+ detail: 'Localized parameter detail',+ },+ },+ },+ });++ injector.get(IConfigService).setConfig(PLUGIN_CONFIG_KEY_BASE, { description: [] });+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([IDescriptionService, { useClass: DescriptionService }]);++ descriptionService = injector.get(IDescriptionService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('registers descriptions, supports search, and unregisters by disposable', () => {+ const customInfo = createFunctionInfo();++ const disposable = descriptionService.registerDescriptions([customInfo]);++ expect(descriptionService.hasDescription('CUSTOMFUNC')).toBe(true);+ expect(descriptionService.hasFunction('customfunc')).toBe(true);+ expect(descriptionService.getFunctionInfo('customfunc')).toMatchObject({+ functionName: 'CUSTOMFUNC',+ abstract: 'custom.abstract',+ });+ expect(descriptionService.getSearchListByName('custom')).toContainEqual({+ name: 'CUSTOMFUNC',+ desc: 'custom.abstract',+ });+ expect(descriptionService.getSearchListByNameFirstLetter('custom')).toContainEqual({+ name: 'CUSTOMFUNC',+ desc: 'custom.abstract',+ functionType: FunctionType.User,+ });+ expect(descriptionService.getSearchListByType(FunctionType.User)).toEqual(+ expect.arrayContaining([+ {+ name: 'CUSTOMFUNC',+ desc: 'custom.abstract',+ },+ ])+ );++ disposable.dispose();++ expect(descriptionService.hasDescription('CUSTOMFUNC')).toBe(false);+ expect(descriptionService.getFunctionInfo('CUSTOMFUNC')).toBeUndefined();+ });++ it('handles defined-name descriptions according to current implementation semantics', () => {+ const rangeNameInfo = createFunctionInfo({+ functionName: 'BOOK_RANGE',+ functionType: FunctionType.DefinedName,+ description: 'A1:B2',+ abstract: 'Workbook range',+ functionParameter: [],+ });+ const formulaNameInfo = createFunctionInfo({+ functionName: 'BOOK_FORMULA',+ functionType: FunctionType.DefinedName,+ description: 'SUM(A1:A2)',+ abstract: 'Workbook formula',+ functionParameter: [],+ });++ descriptionService.registerDescriptions([rangeNameInfo, formulaNameInfo]);++ expect(descriptionService.hasDefinedNameDescription('BOOK_RANGE')).toBe(true);+ expect(descriptionService.hasDefinedNameDescription('BOOK_FORMULA')).toBe(true);+ expect(descriptionService.isFormulaDefinedName('BOOK_RANGE')).toBe(false);+ expect(descriptionService.isFormulaDefinedName('BOOK_FORMULA')).toBe(true);+ expect(descriptionService.getSearchListByName('BOOK')).toEqual([]);+ expect(descriptionService.getSearchListByType(-1)).not.toEqual(+ expect.arrayContaining([+ { name: 'BOOK_RANGE', desc: 'Workbook range' },+ { name: 'BOOK_FORMULA', desc: 'Workbook formula' },+ ])+ );+ });++ it('re-registers descriptions with localized alias names after locale changes', () => {+ const customInfo = createFunctionInfo({ aliasFunctionName: 'custom.alias' });++ descriptionService.registerDescriptions([customInfo]);+ localeService.setLocale(LocaleType.EN_US);++ expect(descriptionService.hasFunction('CUSTOM_ALIAS')).toBe(true);+ expect(descriptionService.getFunctionInfo('CUSTOM_ALIAS')).toMatchObject({+ functionName: 'CUSTOM_ALIAS',+ description: 'Localized description',+ abstract: 'Localized abstract',+ functionParameter: [+ {+ name: 'Localized parameter',+ detail: 'Localized parameter detail',+ example: '1',+ require: 1,+ repeat: 0,+ },+ ],+ });+ });+});diff --git a/packages/sheets-formula/src/services/__test__/formula-ref.spec.ts b/packages/sheets-formula/src/services/__test__/formula-ref.spec.tsindex 538d48bc70..e52b6f5bad 100644--- a/packages/sheets-formula/src/services/__test__/formula-ref.spec.ts+++ b/packages/sheets-formula/src/services/__test__/formula-ref.spec.ts@@ -14,16 +14,51 @@* limitations under the License.*/-import type { IRange } from '@univerjs/core';+import type { IRange, IWorkbookData } from '@univerjs/core';import type { ITestBed } from './util';-import { Direction, ICommandService } from '@univerjs/core';+import { Direction, ICommandService, LocaleType } from '@univerjs/core';import { InsertColCommand, MoveRangeCommand, RemoveColCommand } from '@univerjs/sheets';-import { beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { FormulaRefRangeService } from '../formula-ref-range.service';import { createCommandTestBed } from './util';const MoveRangeCommandId = 'sheet.command.move-range';+function createMultiSheetWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {+ 0: {+ 0: {+ v: 1,+ },+ },+ },+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ cellData: {+ 0: {+ 0: {+ v: 2,+ },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {},+ };+}+describe('FormulaRefRangeService', () => {let testBed: ITestBed;@@ -31,6 +66,10 @@ describe('FormulaRefRangeService', () => {testBed = createCommandTestBed();});+ afterEach(() => {+ testBed.univer.dispose();+ });+it('transform formula string with move range', () => {const formulaRefRangeService = testBed.get(FormulaRefRangeService);const resFormula = formulaRefRangeService.transformFormulaByEffectCommand(@@ -87,6 +126,64 @@ describe('FormulaRefRangeService', () => {expect(resFormula).toBe('=SUM(A1:A10)');});+ it('only transforms references on the current sheet', () => {+ testBed.univer.dispose();+ testBed = createCommandTestBed(createMultiSheetWorkbookData());++ const formulaRefRangeService = testBed.get(FormulaRefRangeService);+ const resFormula = formulaRefRangeService.transformFormulaByEffectCommand(+ 'test',+ 'sheet1',+ '=SUM(Sheet2!A1)+SUM(A1)',+ {+ id: MoveRangeCommandId,+ params: {+ fromRange: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ toRange: {+ startRow: 2,+ endRow: 2,+ startColumn: 1,+ endColumn: 1,+ },+ },+ }+ );++ expect(resFormula).toBe('=SUM(Sheet2!A1)+SUM(B3)');+ });++ it('throws when the referenced sheet cannot be resolved', () => {+ const formulaRefRangeService = testBed.get(FormulaRefRangeService);++ expect(() => formulaRefRangeService.transformFormulaByEffectCommand(+ 'test',+ 'sheet1',+ '=SUM(Sheet2!A1)',+ {+ id: MoveRangeCommandId,+ params: {+ fromRange: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ toRange: {+ startRow: 2,+ endRow: 2,+ startColumn: 1,+ endColumn: 1,+ },+ },+ }+ )).toThrowError('Sheet not found');+ });+it('transform range formula string with move range', async () => {const formulaRefRangeService = testBed.get(FormulaRefRangeService);@@ -298,4 +395,62 @@ describe('FormulaRefRangeService', () => {]);});++ it('stops listening for range changes after registerFormula is disposed', async () => {+ const formulaRefRangeService = testBed.get(FormulaRefRangeService);+ const updatedFormulas: string[] = [];++ const disposable = formulaRefRangeService.registerFormula(+ 'test',+ 'sheet1',+ '=SUM(A1)',+ (formula) => {+ updatedFormulas.push(formula);+ return {+ redos: [],+ undos: [],+ };+ }+ );++ await testBed.get(ICommandService).executeCommand(+ MoveRangeCommand.id,+ {+ fromRange: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ toRange: {+ startRow: 2,+ endRow: 2,+ startColumn: 1,+ endColumn: 1,+ },+ }+ );++ disposable.dispose();++ await testBed.get(ICommandService).executeCommand(+ MoveRangeCommand.id,+ {+ fromRange: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ toRange: {+ startRow: 2,+ endRow: 2,+ startColumn: 1,+ endColumn: 1,+ },+ }+ );++ expect(updatedFormulas).toEqual(['=SUM(B3)']);+ });});diff --git a/packages/sheets-formula/src/services/__test__/register-function.service.spec.ts b/packages/sheets-formula/src/services/__test__/register-function.service.spec.tsnew file mode 100644index 0000000000..011247b983--- /dev/null+++ b/packages/sheets-formula/src/services/__test__/register-function.service.spec.ts@@ -0,0 +1,138 @@+/**+ * 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 { IConfigService, LocaleService, LocaleType, Univer } from '@univerjs/core';+import { FunctionService, FunctionType, IFunctionService } from '@univerjs/engine-formula';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { PLUGIN_CONFIG_KEY_BASE } from '../../controllers/config.schema';+import { DescriptionService, IDescriptionService } from '../description.service';+import { IRegisterFunctionService, RegisterFunctionService } from '../register-function.service';+import { IRemoteRegisterFunctionService } from '../remote/remote-register-function.service';++describe('RegisterFunctionService', () => {+ let univer: Univer;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();++ injector.get(LocaleService).load({+ [LocaleType.ZH_CN]: {},+ [LocaleType.EN_US]: {},+ });+ injector.get(IConfigService).setConfig(PLUGIN_CONFIG_KEY_BASE, { description: [] });+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([IDescriptionService, { useClass: DescriptionService }]);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('registers and disposes a single synchronous function with generated description', () => {+ const injector = univer.__getInjector();+ injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);++ const registerFunctionService = injector.get(IRegisterFunctionService);+ const functionService = injector.get(IFunctionService);+ const deleteFormulaAstCacheKeySpy = vi.spyOn(functionService, 'deleteFormulaAstCacheKey');++ const disposable = registerFunctionService.registerFunction({+ name: 'DOUBLE',+ func: (value) => Number(value) * 2,+ description: 'Double the incoming value',+ });++ expect(functionService.hasExecutor('DOUBLE')).toBe(true);+ expect(functionService.getDescription('DOUBLE')).toMatchObject({+ functionName: 'DOUBLE',+ functionType: FunctionType.User,+ description: 'Double the incoming value',+ abstract: 'Double the incoming value',+ });++ disposable.dispose();++ expect(functionService.hasExecutor('DOUBLE')).toBe(false);+ expect(functionService.hasDescription('DOUBLE')).toBe(false);+ expect(deleteFormulaAstCacheKeySpy).toHaveBeenCalledWith('DOUBLE');+ });++ it('registers grouped functions with fallback descriptions when custom descriptions are omitted', () => {+ const injector = univer.__getInjector();+ injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);++ const registerFunctionService = injector.get(IRegisterFunctionService);+ const functionService = injector.get(IFunctionService);++ const disposable = registerFunctionService.registerFunctions({+ calculate: [+ [(left, right) => Number(left) + Number(right), 'ADD2', 'Add two numbers'],+ ],+ });++ expect(functionService.hasExecutor('ADD2')).toBe(true);+ expect(functionService.getDescription('ADD2')).toMatchObject({+ functionName: 'ADD2',+ abstract: 'Add two numbers',+ description: '',+ });++ disposable.dispose();++ expect(functionService.hasExecutor('ADD2')).toBe(false);+ });++ it('uses remote registration hooks for grouped and async functions when the remote service is present', () => {+ const remoteRegisterFunctionService: IRemoteRegisterFunctionService = {+ registerFunctions: vi.fn().mockResolvedValue(undefined),+ registerAsyncFunctions: vi.fn().mockResolvedValue(undefined),+ unregisterFunctions: vi.fn().mockResolvedValue(undefined),+ };+ const injector = univer.__getInjector();++ injector.add([IRemoteRegisterFunctionService, { useValue: remoteRegisterFunctionService }]);+ injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);++ const registerFunctionService = injector.get(IRegisterFunctionService);++ const groupedDisposable = registerFunctionService.registerFunctions({+ calculate: [+ [() => 1, 'REMOTE_GROUPED', 'Remote grouped function'],+ ],+ });+ const asyncDisposable = registerFunctionService.registerAsyncFunction({+ name: 'REMOTE_ASYNC',+ func: async () => 2,+ description: 'Remote async function',+ });++ expect(remoteRegisterFunctionService.registerFunctions).toHaveBeenCalledTimes(1);+ expect(remoteRegisterFunctionService.registerFunctions).toHaveBeenCalledWith([+ [expect.stringContaining('() => 1'), 'REMOTE_GROUPED'],+ ]);+ expect(remoteRegisterFunctionService.registerAsyncFunctions).toHaveBeenCalledTimes(1);+ expect(remoteRegisterFunctionService.registerAsyncFunctions).toHaveBeenCalledWith([+ [expect.stringContaining('async'), 'REMOTE_ASYNC'],+ ]);++ groupedDisposable.dispose();+ asyncDisposable.dispose();++ expect(remoteRegisterFunctionService.unregisterFunctions).toHaveBeenCalledWith(['REMOTE_GROUPED']);+ expect(remoteRegisterFunctionService.unregisterFunctions).toHaveBeenCalledWith(['REMOTE_ASYNC']);+ });+});diff --git a/packages/sheets-formula/src/services/__test__/utils.spec.ts b/packages/sheets-formula/src/services/__test__/utils.spec.tsnew file mode 100644index 0000000000..27ee07086c--- /dev/null+++ b/packages/sheets-formula/src/services/__test__/utils.spec.ts@@ -0,0 +1,66 @@+/**+ * 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 { IFunctionInfo } from '@univerjs/engine-formula';+import { LocaleService, LocaleType, Univer } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { generateParam, getFunctionName } from '../utils';++describe('sheets-formula service utils', () => {+ let univer: Univer;+ let localeService: LocaleService;++ beforeEach(() => {+ univer = new Univer();+ localeService = univer.__getInjector().get(LocaleService);+ localeService.load({+ [LocaleType.ZH_CN]: {},+ [LocaleType.EN_US]: {+ custom: {+ alias: 'ALIAS_NAME',+ },+ },+ });+ });++ afterEach(() => {+ univer.dispose();+ });++ it('prefers translated alias names and falls back to the original function name', () => {+ const aliasInfo = {+ functionName: 'FUNC_NAME',+ aliasFunctionName: 'custom.alias',+ } as IFunctionInfo;+ const noAliasInfo = {+ functionName: 'FALLBACK_NAME',+ } as IFunctionInfo;++ expect(getFunctionName(aliasInfo, localeService)).toBe('FUNC_NAME');++ localeService.setLocale(LocaleType.EN_US);++ expect(getFunctionName(aliasInfo, localeService)).toBe('ALIAS_NAME');+ expect(getFunctionName(noAliasInfo, localeService)).toBe('FALLBACK_NAME');+ });++ it('formats function parameters for each require and repeat combination', () => {+ expect(generateParam({ name: 'arg', detail: '', example: '', require: 0, repeat: 0 })).toBe('[arg]');+ expect(generateParam({ name: 'arg', detail: '', example: '', require: 1, repeat: 0 })).toBe('arg');+ expect(generateParam({ name: 'arg', detail: '', example: '', require: 0, repeat: 1 })).toBe('[arg,...]');+ expect(generateParam({ name: 'arg', detail: '', example: '', require: 1, repeat: 1 })).toBe('arg,...');+ });+});diff --git a/packages/sheets-formula/src/util/__tests__/calculate.spec.ts b/packages/sheets-formula/src/util/__tests__/calculate.spec.tsnew file mode 100644index 0000000000..8f4233cd6a--- /dev/null+++ b/packages/sheets-formula/src/util/__tests__/calculate.spec.ts@@ -0,0 +1,73 @@+/**+ * 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 { Injector } from '@univerjs/core';+import type { ISheetData } from '@univerjs/engine-formula';+import { AstTreeBuilder, IFormulaCurrentConfigService, Interpreter, Lexer } from '@univerjs/engine-formula';+import { describe, expect, it, vi } from 'vitest';++import { calculateFormula } from '../calculate';++describe('calculateFormula', () => {+ it('should load formula config, build lexer and ast, then return the executed value', () => {+ const load = vi.fn();+ const treeBuilder = vi.fn(() => ['lexer-node']);+ const parse = vi.fn(() => ({ type: 'ast-node' }));+ const execute = vi.fn(() => ({+ isReferenceObject: () => false,+ isArray: () => false,+ isNumber: () => true,+ getValue: () => 42,+ }));++ const services = new Map<unknown, unknown>([+ [IFormulaCurrentConfigService, { load }],+ [Lexer, { treeBuilder }],+ [AstTreeBuilder, { parse }],+ [Interpreter, { execute }],+ ]);++ const injector = {+ get: (token: unknown) => services.get(token),+ } as unknown as Injector;++ const sheetData = {+ sheet1: {+ cellData: {},+ rowCount: 10,+ columnCount: 10,+ rowData: {},+ columnData: {},+ },+ } as unknown as ISheetData;++ const result = calculateFormula(injector, '=SUM(A1)', 'unit-1', sheetData);++ expect(load).toHaveBeenCalledWith(expect.objectContaining({+ allUnitData: {+ 'unit-1': sheetData,+ },+ formulaData: {},+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: false,+ }));+ expect(treeBuilder).toHaveBeenCalledWith('=SUM(A1)');+ expect(parse).toHaveBeenCalledWith(['lexer-node']);+ expect(execute).toHaveBeenCalled();+ expect(result).toBe(42);+ });+});diff --git a/packages/sheets-graphics/src/controllers/graphics-render.controller.spec.ts b/packages/sheets-graphics/src/controllers/graphics-render.controller.spec.tsnew file mode 100644index 0000000000..84ef8172ad--- /dev/null+++ b/packages/sheets-graphics/src/controllers/graphics-render.controller.spec.ts@@ -0,0 +1,107 @@+/**+ * 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 { Graphics } from '../views/extensions/graphics.extension';+import { describe, expect, it, vi } from 'vitest';+import { SheetGraphicsRenderController } from './graphics-render.controller';++describe('SheetGraphicsRenderController', () => {+ it('should init extension, printing interceptor, and register renderer', () => {+ const registered: unknown[] = [];+ let interceptorHandler: ((component: unknown, context: { spreadsheet: { register: (obj: unknown) => void } }, next: (component: unknown) => unknown) => unknown) | undefined;++ const context = {+ mainComponent: {+ getExtensionByKey: vi.fn(() => undefined),+ register: vi.fn((ext: unknown) => {+ registered.push(ext);+ }),+ },+ };++ const interceptor = {+ getInterceptPoints: vi.fn(() => ({ PRINTING_COMPONENT_COLLECT: 'PRINTING_COMPONENT_COLLECT' })),+ intercept: vi.fn((_point, config: { handler: typeof interceptorHandler }) => {+ interceptorHandler = config.handler;+ return { dispose: vi.fn() };+ }),+ };++ const controller = new SheetGraphicsRenderController(+ context as never,+ { interceptor } as never+ );++ expect(context.mainComponent.getExtensionByKey).toHaveBeenCalled();+ expect(context.mainComponent.register).toHaveBeenCalledTimes(1);++ const extension = registered[0] as Graphics;+ const renderer = vi.fn();+ controller.registerRenderer('feature-a', renderer as never);++ extension.draw(+ {} as never,+ {} as never,+ { getCellByIndexWithNoHeader: vi.fn(() => ({ row: 1, col: 1 })) } as never,+ [],+ { viewRanges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }] } as never+ );+ expect(renderer).toHaveBeenCalledTimes(1);++ const copySpy = vi.spyOn(extension, 'copy');+ const printSheet = { register: vi.fn() };+ const next = vi.fn((value: unknown) => ({ passthrough: value }));+ const result = interceptorHandler?.('component-a', { spreadsheet: printSheet }, next);++ expect(copySpy).toHaveBeenCalledTimes(1);+ expect(printSheet.register).toHaveBeenCalledTimes(1);+ expect(next).toHaveBeenCalledWith('component-a');+ expect(result).toEqual({ passthrough: 'component-a' });++ controller.dispose();+ });++ it('should skip init extension when extension already exists and keep printing flow', () => {+ let interceptorHandler: ((component: unknown, context: { spreadsheet: { register: (obj: unknown) => void } }, next: (component: unknown) => unknown) => unknown) | undefined;+ const context = {+ mainComponent: {+ getExtensionByKey: vi.fn(() => ({})),+ register: vi.fn(),+ },+ };+ const interceptor = {+ getInterceptPoints: vi.fn(() => ({ PRINTING_COMPONENT_COLLECT: 'PRINTING_COMPONENT_COLLECT' })),+ intercept: vi.fn((_point, config: { handler: typeof interceptorHandler }) => {+ interceptorHandler = config.handler;+ return { dispose: vi.fn() };+ }),+ };++ const controller = new SheetGraphicsRenderController(+ context as never,+ { interceptor } as never+ );++ expect(context.mainComponent.register).not.toHaveBeenCalled();+ expect(() => controller.registerRenderer('noop', vi.fn() as never)).not.toThrow();++ const printSheet = { register: vi.fn() };+ const next = vi.fn((value: unknown) => value);+ const result = interceptorHandler?.('component-b', { spreadsheet: printSheet }, next);+ expect(printSheet.register).not.toHaveBeenCalled();+ expect(result).toBe('component-b');+ });+});diff --git a/packages/sheets-graphics/src/views/extensions/graphics.extension.spec.ts b/packages/sheets-graphics/src/views/extensions/graphics.extension.spec.tsnew file mode 100644index 0000000000..6c4ecd20ef--- /dev/null+++ b/packages/sheets-graphics/src/views/extensions/graphics.extension.spec.ts@@ -0,0 +1,93 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { Graphics } from './graphics.extension';++describe('Graphics extension', () => {+ it('should register renderer, draw ranges, copy and dispose', () => {+ const graphics = new Graphics();+ const rendererA = vi.fn();+ const rendererB = vi.fn();+ graphics.registerRenderer('a', rendererA);+ graphics.registerRenderer('b', rendererB);++ const skeleton = {+ getCellByIndexWithNoHeader: vi.fn((row: number, col: number) => {+ if (row === 0 && col === 0) {+ return undefined;+ }+ return { row, col };+ }),+ };++ graphics.draw(+ {} as never,+ {} as never,+ skeleton as never,+ [],+ {+ viewRanges: [{+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ }],+ } as never+ );++ expect(rendererA).toHaveBeenCalledTimes(1);+ expect(rendererB).toHaveBeenCalledTimes(1);++ const copied = graphics.copy();+ const rendererC = vi.fn();+ copied.registerRenderer('c', rendererC);+ copied.draw(+ {} as never,+ {} as never,+ skeleton as never,+ [],+ {+ viewRanges: [{+ startRow: 1,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ }],+ } as never+ );+ expect(rendererA).toHaveBeenCalledTimes(2);+ expect(rendererB).toHaveBeenCalledTimes(2);+ expect(rendererC).toHaveBeenCalledTimes(1);++ copied.dispose();+ copied.draw(+ {} as never,+ {} as never,+ skeleton as never,+ [],+ {+ viewRanges: [{+ startRow: 1,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ }],+ } as never+ );+ expect(rendererC).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/sheets-graphics/src/views/extensions/graphics.extension.ts b/packages/sheets-graphics/src/views/extensions/graphics.extension.tsindex 94bd11b657..7fa3d67d29 100644--- a/packages/sheets-graphics/src/views/extensions/graphics.extension.ts+++ b/packages/sheets-graphics/src/views/extensions/graphics.extension.ts@@ -14,14 +14,12 @@* limitations under the License.*/-import type { IObjectMatrixPrimitiveType, IRange, IScale, ISelectionCellWithMergeInfo } from '@univerjs/core';+import type { IRange, IScale, ISelectionCellWithMergeInfo } from '@univerjs/core';import type { IDrawInfo, SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';import { Range } from '@univerjs/core';import { SheetExtension } from '@univerjs/engine-render';import { GRAPHICS_EXTENSION_INDEX, UNIQUE_KEY } from '../../common/const';-type IGraphicsCache = IObjectMatrixPrimitiveType<ISelectionCellWithMergeInfo>;-type IGraphicsRenderer = (ctx: UniverRenderingContext, skeleton: SpreadsheetSkeleton, coordInfo: ISelectionCellWithMergeInfo) => void;type IGraphicsRenderMap = Map<string, IGraphicsRenderer>;diff --git a/packages/sheets-hyper-link/src/models/__tests__/hyper-link.model.spec.ts b/packages/sheets-hyper-link/src/models/__tests__/hyper-link.model.spec.tsnew file mode 100644index 0000000000..8d62668f18--- /dev/null+++ b/packages/sheets-hyper-link/src/models/__tests__/hyper-link.model.spec.ts@@ -0,0 +1,171 @@+/**+ * 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 { IWorkbookData, Workbook } from '@univerjs/core';+import type { ISheetHyperLink } from '../../types/interfaces/i-hyper-link';+import { IUniverInstanceService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { HyperLinkModel } from '../hyper-link.model';++function createWorkbookData(unitId = 'book-1', sheetId = 'sheet-1'): IWorkbookData {+ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'Workbook',+ sheetOrder: [sheetId],+ styles: {},+ sheets: {+ [sheetId]: {+ id: sheetId,+ name: 'Sheet1',+ cellData: {+ 0: {+ 0: { v: 'Display From Cell' },+ 1: { v: 'Other Cell' },+ },+ 1: {+ 1: { v: 'Moved Cell' },+ },+ },+ rowCount: 20,+ columnCount: 20,+ },+ },+ };+}++function createLink(id: string, row: number, column: number, payload = 'https://univer.ai'): ISheetHyperLink {+ return {+ id,+ row,+ column,+ payload,+ display: `${id}-display`,+ };+}++describe('HyperLinkModel', () => {+ let univer: Univer;+ let model: HyperLinkModel;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([HyperLinkModel]);+ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit('book-1');++ model = injector.get(HyperLinkModel);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should add, update, remove and unload hyperlinks while emitting update events', () => {+ const link = createLink('link-1', 0, 0);+ const events: string[] = [];++ model.linkUpdate$.subscribe((event) => {+ events.push(event.type);+ });++ expect(model.addHyperLink('book-1', 'sheet-1', link)).toBe(true);+ expect(model.getHyperLink('book-1', 'sheet-1', 'link-1')).toEqual(link);++ expect(model.updateHyperLink('book-1', 'sheet-1', 'link-1', { payload: 'https://docs.univer.ai' }, true)).toBe(true);+ expect(model.getHyperLink('book-1', 'sheet-1', 'link-1')?.payload).toBe('https://docs.univer.ai');++ expect(model.removeHyperLink('book-1', 'sheet-1', 'link-1')).toBe(true);+ expect(model.removeHyperLink('book-1', 'sheet-1', 'missing')).toBe(false);++ model.deleteUnit('book-1');++ expect(events).toEqual(['add', 'update', 'remove', 'unload']);+ expect(model.getUnit('book-1')).toEqual([]);+ expect(model.getAll()).toEqual([]);+ });++ it('should move hyperlink references and clear the original matrix position when the original link is still there', () => {+ const link = createLink('link-1', 0, 0);++ model.addHyperLink('book-1', 'sheet-1', link);+ expect(model.updateHyperLinkRef('book-1', 'sheet-1', 'link-1', { row: 1, column: 1 }, true)).toBe(true);++ expect(model.getHyperLinkByLocation('book-1', 'sheet-1', 0, 0)).toBeUndefined();+ expect(model.getHyperLinkByLocation('book-1', 'sheet-1', 1, 1)).toEqual({+ ...link,+ row: 1,+ column: 1,+ });+ });++ it('should move hyperlink references from the cached position when the matrix slot has been overwritten', () => {+ const original = createLink('original', 0, 0, 'https://origin');+ const overwritten = createLink('overwritten', 0, 0, 'https://other');++ model.addHyperLink('book-1', 'sheet-1', original);+ model.addHyperLink('book-1', 'sheet-1', overwritten);+ model.updateHyperLinkRef('book-1', 'sheet-1', 'original', { row: 1, column: 1 });++ expect(model.getHyperLink('book-1', 'sheet-1', 'original')).toEqual({+ ...original,+ row: 1,+ column: 1,+ });+ expect(model.getHyperLinkByLocation('book-1', 'sheet-1', 0, 0)).toEqual(overwritten);+ });++ it('should resolve display text from worksheet cells when reading synchronously by location', () => {+ const link = createLink('link-1', 0, 0);++ model.addHyperLink('book-1', 'sheet-1', link);++ expect(model.getHyperLinkByLocationSync('book-1', 'sheet-1', 0, 0)).toEqual({+ ...link,+ display: 'Display From Cell',+ });+ expect(model.getHyperLinkByLocationSync('book-1', 'sheet-1', 9, 9)).toBeUndefined();+ });++ it('should expose links by sub unit and whole unit', () => {+ const first = createLink('link-1', 0, 0);+ const second = createLink('link-2', 1, 1);++ model.addHyperLink('book-1', 'sheet-1', first);+ model.addHyperLink('book-1', 'sheet-1', second);++ expect(model.getSubUnit('book-1', 'sheet-1')).toEqual([first, second]);+ expect(model.getUnit('book-1')).toEqual([+ {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ links: [first, second],+ },+ ]);+ expect(model.getAll()).toEqual([+ [+ {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ links: [first, second],+ },+ ],+ ]);+ });+});diff --git a/packages/sheets-hyper-link/src/services/__tests__/parser.service.spec.ts b/packages/sheets-hyper-link/src/services/__tests__/parser.service.spec.tsnew file mode 100644index 0000000000..2633c9534a--- /dev/null+++ b/packages/sheets-hyper-link/src/services/__tests__/parser.service.spec.ts@@ -0,0 +1,187 @@+/**+ * 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 { IRange, IWorkbookData, Workbook } from '@univerjs/core';+import {+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { ERROR_RANGE } from '../../types/const';+import { SheetHyperLinkType } from '../../types/enums/hyper-link-type';+import { SheetsHyperLinkParserService } from '../parser.service';++function createWorkbookData(unitId = 'book-1', sheetId = 'sheet-1'): IWorkbookData {+ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'Workbook',+ sheetOrder: [sheetId],+ styles: {},+ sheets: {+ [sheetId]: {+ id: sheetId,+ name: 'Sheet1',+ cellData: {+ 0: {+ 0: { v: 'Origin' },+ },+ },+ rowCount: 20,+ columnCount: 20,+ },+ },+ };+}++describe('SheetsHyperLinkParserService', () => {+ let univer: Univer;+ let service: SheetsHyperLinkParserService;+ let localeService: LocaleService;++ beforeEach(() => {+ univer = new Univer();++ const injector = univer.__getInjector();+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([SheetsHyperLinkParserService]);++ localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.EN_US]: {+ hyperLink: {+ message: {+ refError: 'Invalid Range',+ },+ },+ } as never,+ });+ localeService.setLocale(LocaleType.EN_US);++ service = injector.get(SheetsHyperLinkParserService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should build hyperlinks for sheet, named range and range object', () => {+ const range: IRange = {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ };++ expect(service.buildHyperLink('book-1', 'sheet-1')).toBe('#gid=sheet-1');+ expect(service.buildHyperLink('book-1', 'sheet-1', 'name-1')).toBe('#gid=sheet-1&rangeid=name-1');+ expect(service.buildHyperLink('book-1', 'sheet-1', range)).toBe('#gid=sheet-1&range=A1:B2');+ });++ it('should parse external URLs as url links', () => {+ const url = 'https://univer.ai';++ expect(service.parseHyperLink(url)).toEqual({+ type: SheetHyperLinkType.URL,+ name: url,+ url,+ searchObj: null,+ });+ });++ it('should parse range links from the focused workbook when unitid is absent', () => {+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ const univerInstanceService = univer.__getInjector().get(IUniverInstanceService);+ univerInstanceService.focusUnit(workbook.getUnitId());++ const url = '#gid=sheet-1&range=A1:B2';+ expect(service.parseHyperLink(url)).toEqual({+ type: SheetHyperLinkType.RANGE,+ name: 'Sheet1!A1:B2',+ url,+ searchObj: {+ gid: 'sheet-1',+ range: 'A1:B2',+ rangeid: '',+ unitid: '',+ },+ });+ });++ it('should parse defined name links through the real defined names service', () => {+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ const definedNamesService = univer.__getInjector().get(IDefinedNamesService);++ definedNamesService.registerDefinedName(workbook.getUnitId(), {+ id: 'name-1',+ name: 'Total',+ formulaOrRefString: 'Sheet1!A1:B2',+ });++ const url = `#gid=sheet-1&rangeid=name-1&unitid=${workbook.getUnitId()}`;+ expect(service.parseHyperLink(url)).toEqual({+ type: SheetHyperLinkType.DEFINE_NAME,+ name: 'Sheet1!A1:B2',+ url,+ searchObj: {+ gid: 'sheet-1',+ range: '',+ rangeid: 'name-1',+ unitid: workbook.getUnitId(),+ },+ });+ });++ it('should parse sheet links by sheet id', () => {+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ const url = `#gid=sheet-1&unitid=${workbook.getUnitId()}`;+ expect(service.parseHyperLink(url)).toEqual({+ type: SheetHyperLinkType.SHEET,+ name: 'Sheet1',+ url,+ searchObj: {+ gid: 'sheet-1',+ range: '',+ rangeid: '',+ unitid: workbook.getUnitId(),+ },+ });+ });++ it('should return invalid for missing workbook, invalid range and missing defined names', () => {+ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ expect(service.parseHyperLink('#gid=sheet-1&range=A1&unitid=missing').type).toBe(SheetHyperLinkType.INVALID);+ expect(service.parseHyperLink(`#gid=sheet-1&range=${ERROR_RANGE}&unitid=book-1`).type).toBe(SheetHyperLinkType.INVALID);+ expect(service.parseHyperLink('#gid=sheet-1&rangeid=missing&unitid=book-1')).toEqual({+ type: SheetHyperLinkType.INVALID,+ name: 'Invalid Range',+ url: '#gid=sheet-1&rangeid=missing&unitid=book-1',+ searchObj: {+ gid: 'sheet-1',+ range: '',+ rangeid: 'missing',+ unitid: 'book-1',+ },+ });+ });+});diff --git a/packages/sheets-numfmt/src/__tests__/utils.test.ts b/packages/sheets-numfmt/src/__tests__/utils.test.tsindex 8004a3408e..0889a78fb0 100644--- a/packages/sheets-numfmt/src/__tests__/utils.test.ts+++ b/packages/sheets-numfmt/src/__tests__/utils.test.ts@@ -14,15 +14,21 @@* limitations under the License.*/-import { cellToRange, isPatternEqualWithoutDecimal } from '@univerjs/core';+import { cellToRange, DEFAULT_NUMBER_FORMAT, isPatternEqualWithoutDecimal, LocaleType } from '@univerjs/core';import { RemoveNumfmtMutation, SetNumfmtMutation } from '@univerjs/sheets';-import { describe, expect, it } from 'vitest';-import { currencySymbols } from '../base/const/currency-symbols';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { currencySymbols, getCurrencyFormat, getCurrencySymbolByLocale, getCurrencySymbolIconByLocale } from '../base/const/currency-symbols';import { getCurrencyType } from '../utils/currency';-import { getDecimalFromPattern, getDecimalString, setPatternDecimal } from '../utils/decimal';+import { getDecimalFromPattern, getDecimalString, isPatternHasDecimal, setPatternDecimal } from '../utils/decimal';import { mergeNumfmtMutations } from '../utils/mutation';+import { getCurrencyFormatOptions, getCurrencyOptions, getDateFormatOptions, getNumberFormatOptions } from '../utils/options';+import { getPatternPreview, getPatternPreviewIgnoreGeneral, getPatternType } from '../utils/pattern';describe('test numfmt utils function', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });+it('getCurrencyType', () => {expect(getCurrencyType(`_(${currencySymbols[3]} 123123`)).toBe(currencySymbols[3]);expect(getCurrencyType('_(# 123123')).toBeUndefined();@@ -52,6 +58,54 @@ describe('test numfmt utils function', () => {expect(setPatternDecimal('0.0', 0)).toBe('0'); // the positive color ignored});+ it('isPatternHasDecimal', () => {+ expect(isPatternHasDecimal('0.00')).toBe(true);+ expect(isPatternHasDecimal('#,##0')).toBe(true);+ expect(isPatternHasDecimal('General')).toBe(false);+ });++ it('currency symbol helpers', () => {+ expect(getCurrencySymbolByLocale(LocaleType.ZH_CN)).toBe('¥');+ expect(getCurrencySymbolByLocale(LocaleType.KO_KR)).toBe('₩');+ expect(getCurrencySymbolIconByLocale(LocaleType.FR_FR)).toEqual({+ icon: 'EuroIcon',+ symbol: '€',+ locale: LocaleType.FR_FR,+ });+ expect(getCurrencySymbolIconByLocale(LocaleType.KO_KR)).toEqual({+ icon: 'DollarIcon',+ symbol: '$',+ locale: LocaleType.EN_US,+ });+ expect(getCurrencyFormat(LocaleType.ZH_CN, 3)).toContain('"¥"#,##0.000');+ expect(getCurrencyFormat(LocaleType.EN_US, 200)).toContain(`.${'0'.repeat(127)}`);+ });++ it('option helpers expose formatted labels and values', () => {+ expect(getCurrencyOptions()[0]).toEqual({ label: '$', value: '$' });+ expect(getCurrencyFormatOptions('€')[0]).toMatchObject({+ label: expect.stringContaining('€'),+ value: expect.stringContaining('€'),+ });+ expect(getDateFormatOptions()[0]).toMatchObject({+ label: expect.any(String),+ value: expect.any(String),+ });+ expect(getNumberFormatOptions()[0]).toMatchObject({+ label: expect.any(String),+ value: expect.any(String),+ });+ });++ it('pattern preview helpers return types and gracefully handle general or invalid formats', () => {+ vi.spyOn(console, 'warn').mockImplementation(() => undefined);++ expect(getPatternType('0%')).toBe('percent');+ expect(getPatternPreview('0.00', 12.3)).toEqual({ result: '12.30' });+ expect(getPatternPreviewIgnoreGeneral(DEFAULT_NUMBER_FORMAT, 0.1 + 0.2)).toEqual({ result: '0.3' });+ expect(getPatternPreview('[invalid', 42)).toEqual({ result: '42' });+ });+it('mergeNumfmtMutations', () => {const result = mergeNumfmtMutations([{@@ -80,9 +134,12 @@ describe('test numfmt utils function', () => {},]);+ const removeMutation = result[0] as { params: { ranges: unknown } };+ const setMutation = result[1] as { params: { values: Record<string, { ranges: unknown }> } };+expect(result[0].id === RemoveNumfmtMutation.id).toBeTruthy();expect(result[1].id === SetNumfmtMutation.id).toBeTruthy();- expect((result as any)[0].params.ranges).toEqual([+ expect(removeMutation.params.ranges).toEqual([{startRow: 2,endRow: 2,@@ -96,7 +153,7 @@ describe('test numfmt utils function', () => {endColumn: 5,},]);- expect((result as any)[1].params.values['1'].ranges).toEqual([+ expect(setMutation.params.values['1'].ranges).toEqual([{startRow: 2,endRow: 2,diff --git a/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts b/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.tsnew file mode 100644index 0000000000..f71c4c692a--- /dev/null+++ b/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts@@ -0,0 +1,255 @@+/**+ * 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 { Dependency, IWorkbookData, Injector as RediInjector, Workbook } from '@univerjs/core';+import {+ CellValueType,+ DEFAULT_TEXT_FORMAT_EXCEL,+ ICommandService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ RANGE_TYPE,+ RedoCommand,+ UndoCommand,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ INumfmtService,+ NumfmtService,+ RemoveNumfmtMutation,+ SetNumfmtMutation,+ SetRangeValuesMutation,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getCurrencyFormat } from '../../../base/const/currency-symbols';+import { AddDecimalCommand } from '../add-decimal.command';+import { SetCurrencyCommand } from '../set-currency.command';+import { SetNumfmtCommand } from '../set-numfmt.command';+import { SetPercentCommand } from '../set-percent.command';+import { SubtractDecimalCommand } from '../subtract-decimal.command';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {+ textStyle: {+ n: {+ pattern: DEFAULT_TEXT_FORMAT_EXCEL,+ },+ },+ twoDecimals: {+ n: {+ pattern: '0.00',+ },+ },+ },+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: 1.2, t: CellValueType.NUMBER },+ 1: { v: 123, t: CellValueType.STRING, s: 'textStyle' },+ 2: { v: 12, t: CellValueType.NUMBER },+ 3: { v: 0.375, t: CellValueType.NUMBER },+ 4: { v: 8, t: CellValueType.NUMBER },+ },+ 1: {+ 0: { v: 1.23, t: CellValueType.NUMBER, s: 'twoDecimals' },+ },+ },+ },+ },+ };+}++function createCommandTestBed(workbookData?: IWorkbookData) {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: RediInjector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [SheetsSelectionsService],+ [INumfmtService, { useClass: NumfmtService }],+ ];++ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData ?? createWorkbookData());++ const get = injector.get.bind(injector);+ get(IUniverInstanceService).focusUnit('test');+ get(LocaleService).setLocale(LocaleType.ZH_CN);+ get(ILogService).setLogLevel(LogLevel.SILENT);++ return {+ univer,+ get,+ sheet,+ };+}++describe('Sheets numfmt commands', () => {+ let univer: Univer;+ let get: RediInjector['get'];+ let commandService: ICommandService;+ let selectionService: SheetsSelectionsService;+ let numfmtService: INumfmtService;+ let workbook: Workbook;++ beforeEach(() => {+ const testBed = createCommandTestBed();+ univer = testBed.univer;+ get = testBed.get;+ workbook = testBed.sheet;++ commandService = get(ICommandService);+ selectionService = get(SheetsSelectionsService);+ numfmtService = get(INumfmtService);++ [+ SetRangeValuesMutation,+ SetNumfmtMutation,+ RemoveNumfmtMutation,+ SetNumfmtCommand,+ AddDecimalCommand,+ SubtractDecimalCommand,+ SetPercentCommand,+ SetCurrencyCommand,+ ].forEach((command) => {+ commandService.registerCommand(command);+ });+ });++ afterEach(() => {+ univer.dispose();+ });++ it('sets and removes number formats through SetNumfmtCommand and supports undo/redo', async () => {+ const sheet = workbook.getActiveSheet();++ await expect(commandService.executeCommand(SetNumfmtCommand.id, {+ values: [+ { row: 0, col: 0, pattern: DEFAULT_TEXT_FORMAT_EXCEL },+ { row: 0, col: 1 },+ ],+ })).resolves.toBe(true);++ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toEqual({ pattern: DEFAULT_TEXT_FORMAT_EXCEL });+ expect(numfmtService.getValue('test', 'sheet1', 0, 1)).toBeNull();+ expect(sheet.getCellRaw(0, 0)?.t).toBe(CellValueType.NUMBER);+ expect(sheet.getCellRaw(0, 1)).toMatchObject({ v: 123, t: CellValueType.NUMBER });++ await expect(commandService.executeCommand(UndoCommand.id)).resolves.toBe(true);++ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toBeNull();+ expect(numfmtService.getValue('test', 'sheet1', 0, 1)).toEqual({ pattern: DEFAULT_TEXT_FORMAT_EXCEL });+ expect(sheet.getCellRaw(0, 1)).toMatchObject({ v: '123', t: CellValueType.STRING });++ await expect(commandService.executeCommand(RedoCommand.id)).resolves.toBe(true);++ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toEqual({ pattern: DEFAULT_TEXT_FORMAT_EXCEL });+ expect(numfmtService.getValue('test', 'sheet1', 0, 1)).toBeNull();+ });++ it('adds and subtracts decimals based on selections and existing formats', async () => {+ selectionService.addSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ {+ range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ await expect(commandService.executeCommand(AddDecimalCommand.id)).resolves.toBe(true);++ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toEqual({ pattern: '0.000' });+ expect(numfmtService.getValue('test', 'sheet1', 1, 0)).toEqual({ pattern: '0.000' });++ await expect(commandService.executeCommand(SubtractDecimalCommand.id)).resolves.toBe(true);++ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toEqual({ pattern: '0.00' });+ expect(numfmtService.getValue('test', 'sheet1', 1, 0)).toEqual({ pattern: '0.00' });+ });++ it('applies percent and currency formats to current selections', async () => {+ selectionService.addSelections([+ {+ range: { startRow: 0, startColumn: 3, endRow: 0, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ await expect(commandService.executeCommand(SetPercentCommand.id)).resolves.toBe(true);+ expect(numfmtService.getValue('test', 'sheet1', 0, 3)).toEqual({ pattern: '0%' });++ selectionService.addSelections([+ {+ range: { startRow: 0, startColumn: 4, endRow: 0, endColumn: 4, rangeType: RANGE_TYPE.NORMAL },+ primary: null,+ style: null,+ },+ ]);++ await expect(commandService.executeCommand(SetCurrencyCommand.id)).resolves.toBe(true);+ expect(numfmtService.getValue('test', 'sheet1', 0, 4)).toEqual({+ pattern: getCurrencyFormat(LocaleType.ZH_CN),+ });+ });++ it('returns false for quick commands when there is no current selection', async () => {+ await expect(commandService.executeCommand(AddDecimalCommand.id)).resolves.toBe(false);+ await expect(commandService.executeCommand(SubtractDecimalCommand.id)).resolves.toBe(false);+ await expect(commandService.executeCommand(SetPercentCommand.id)).resolves.toBe(false);+ await expect(commandService.executeCommand(SetCurrencyCommand.id)).resolves.toBe(false);+ });+});diff --git a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.tsnew file mode 100644index 0000000000..0d94f52a92--- /dev/null+++ b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts@@ -0,0 +1,304 @@+/**+ * 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 { Dependency, Injector, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import {+ cellToRange,+ CellValueType,+ ICommandService,+ IConfigService,+ ILogService,+ Inject,+ InterceptorEffectEnum,+ IUniverInstanceService,+ LocaleType,+ LogLevel,+ Plugin,+ Injector as RediInjector,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ INTERCEPTOR_POINT,+ INumfmtService,+ NumfmtService,+ SetNumfmtMutation,+ SetRangeValuesMutation,+ SheetInterceptorService,+} from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as patternUtils from '../../utils/pattern';+import { SHEETS_NUMFMT_PLUGIN_CONFIG_KEY } from '../config.schema';+import { SheetsNumfmtCellContentController } from '../numfmt-cell-content.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {+ textStyle: {+ n: {+ pattern: '@',+ },+ },+ },+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: true, t: CellValueType.BOOLEAN },+ 1: { v: '001', t: CellValueType.FORCE_STRING },+ 2: { v: 'text', t: CellValueType.STRING },+ },+ 1: {+ 0: { v: '123', t: CellValueType.STRING, s: 'textStyle' },+ 1: { v: '1234.5', t: CellValueType.STRING },+ 2: { v: -12.3, t: CellValueType.NUMBER },+ },+ },+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 1: {+ 1: { v: '9.9', t: CellValueType.STRING },+ },+ },+ },+ },+ };+}++function createControllerTestBed(workbookData?: IWorkbookData) {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(RediInjector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [SheetInterceptorService],+ [INumfmtService, { useClass: NumfmtService }],+ [SheetsNumfmtCellContentController],+ ];++ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData ?? createWorkbookData());++ const get = injector.get.bind(injector);+ get(IUniverInstanceService).focusUnit('test');+ get(ILogService).setLogLevel(LogLevel.SILENT);++ return {+ univer,+ get,+ sheet,+ };+}++function getInterceptedCell(worksheet: Worksheet, workbook: Workbook, row: number, col: number, get: Injector['get']) {+ const interceptorService = get(SheetInterceptorService);+ const rawData = worksheet.getCellRaw(row, col);++ return interceptorService.fetchThroughInterceptors(INTERCEPTOR_POINT.CELL_CONTENT, InterceptorEffectEnum.Style | InterceptorEffectEnum.Value)(+ rawData,+ {+ unitId: workbook.getUnitId(),+ subUnitId: worksheet.getSheetId(),+ row,+ col,+ worksheet,+ workbook,+ rawData,+ }+ );+}++describe('SheetsNumfmtCellContentController', () => {+ let univer: Univer;+ let get: Injector['get'];+ let workbook: Workbook;+ let commandService: ICommandService;+ let numfmtService: INumfmtService;+ let controller: SheetsNumfmtCellContentController;++ beforeEach(() => {+ const testBed = createControllerTestBed();+ univer = testBed.univer;+ get = testBed.get;+ workbook = testBed.sheet;++ commandService = get(ICommandService);+ numfmtService = get(INumfmtService);+ controller = get(SheetsNumfmtCellContentController);++ commandService.registerCommand(SetNumfmtMutation);+ commandService.registerCommand(SetRangeValuesMutation);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ univer.dispose();+ });++ it('skips unsupported cells and handles text format markers', () => {+ const worksheet = workbook.getSheetBySheetId('sheet1')!;++ expect(getInterceptedCell(worksheet, workbook, 0, 0, get)).toEqual({ v: true, t: CellValueType.BOOLEAN });+ expect(getInterceptedCell(worksheet, workbook, 0, 1, get)).toEqual({ v: '001', t: CellValueType.FORCE_STRING });+ expect(getInterceptedCell(worksheet, workbook, 0, 2, get)).toEqual({ v: 'text', t: CellValueType.STRING });++ expect(getInterceptedCell(worksheet, workbook, 1, 0, get)).toEqual({+ v: '123',+ t: CellValueType.STRING,+ s: 'textStyle',+ markers: {+ tl: {+ size: 6,+ color: '#409f11',+ },+ },+ });++ get(IConfigService).setConfig(SHEETS_NUMFMT_PLUGIN_CONFIG_KEY, { disableTextFormatMark: true });++ expect(getInterceptedCell(worksheet, workbook, 1, 0, get)).toEqual({+ v: '123',+ t: CellValueType.STRING,+ s: 'textStyle',+ });+ });++ it('formats numeric values and clears render cache on numfmt or value mutations', async () => {+ const worksheet = workbook.getSheetBySheetId('sheet1')!;+ const previewSpy = vi.spyOn(patternUtils, 'getPatternPreviewIgnoreGeneral');++ numfmtService.setValues('test', 'sheet1', [+ { pattern: '0.00', ranges: [cellToRange(1, 1)] },+ { pattern: '[Red]0.00', ranges: [cellToRange(1, 2)] },+ ]);++ const firstFormatted = getInterceptedCell(worksheet, workbook, 1, 1, get);+ expect(firstFormatted).toMatchObject({ v: '1234.50', t: CellValueType.NUMBER });+ expect(worksheet.getCellRaw(1, 1)).toMatchObject({ v: '1234.5', t: CellValueType.STRING });++ const negativeFormatted = getInterceptedCell(worksheet, workbook, 1, 2, get);+ expect(negativeFormatted).toMatchObject({+ v: '-12.30',+ t: CellValueType.NUMBER,+ interceptorStyle: {+ cl: {+ rgb: expect.any(String),+ },+ },+ });++ const previewCallsAfterFirstRender = previewSpy.mock.calls.length;++ getInterceptedCell(worksheet, workbook, 1, 1, get);+ expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender);++ await commandService.executeCommand(SetNumfmtMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ refMap: {+ 1: {+ pattern: '0.00',+ },+ },+ values: {+ 1: {+ ranges: [cellToRange(1, 1)],+ },+ },+ });++ getInterceptedCell(worksheet, workbook, 1, 1, get);+ expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender + 1);++ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 1: {+ v: '1234.5',+ t: CellValueType.STRING,+ },+ },+ },+ });++ getInterceptedCell(worksheet, workbook, 1, 1, get);+ expect(previewSpy).toHaveBeenCalledTimes(previewCallsAfterFirstRender + 2);+ });++ it('resets cached rendering when active sheet changes and supports locale override', () => {+ const sheet1 = workbook.getSheetBySheetId('sheet1')!;+ const sheet2 = workbook.getSheetBySheetId('sheet2')!;+ const previewSpy = vi.spyOn(patternUtils, 'getPatternPreviewIgnoreGeneral');++ numfmtService.setValues('test', 'sheet1', [{ pattern: '0.00', ranges: [cellToRange(1, 1)] }]);++ expect(getInterceptedCell(sheet1, workbook, 1, 1, get)).toMatchObject({ v: '1234.50', t: CellValueType.NUMBER });+ let previewCallCount = previewSpy.mock.calls.length;++ getInterceptedCell(sheet1, workbook, 1, 1, get);+ expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);++ workbook.setActiveSheet(sheet2);++ getInterceptedCell(sheet1, workbook, 1, 1, get);+ previewCallCount += 1;+ expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);++ workbook.setActiveSheet(sheet1);++ getInterceptedCell(sheet1, workbook, 1, 1, get);+ previewCallCount += 1;+ expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);++ controller.setNumfmtLocal('fr');+ expect(controller.locale).toBe('fr');++ getInterceptedCell(sheet1, workbook, 1, 1, get);+ previewCallCount += 1;+ expect(previewSpy).toHaveBeenCalledTimes(previewCallCount);+ });+});diff --git a/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-filter-dialog.operation.spec.ts b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-filter-dialog.operation.spec.tsnew file mode 100644index 0000000000..64bb12b9fe--- /dev/null+++ b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-filter-dialog.operation.spec.ts@@ -0,0 +1,109 @@+/**+ * 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 { IContextService } from '@univerjs/core';+import { TableManager } from '@univerjs/sheets-table';+import { describe, expect, it, vi } from 'vitest';+import { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY } from '../../../const';+import { SheetsTableComponentController } from '../../../controllers/sheet-table-component.controller';+import { OpenTableFilterPanelOperation } from '../open-table-filter-dialog.opration';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('OpenTableFilterPanelOperation', () => {+ it('should return false for missing params or missing table', async () => {+ const accessor = createAccessor([+ [TableManager, { getTable: () => undefined }],+ [IContextService, { getContextValue: () => false, setContextValue: vi.fn() }],+ [SheetsTableComponentController, { setCurrentTableFilterInfo: vi.fn() }],+ ]);++ await expect(OpenTableFilterPanelOperation.handler(accessor, undefined as any)).resolves.toBe(false);+ await expect(OpenTableFilterPanelOperation.handler(accessor, {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 'missing',+ row: 1,+ col: 1,+ })).resolves.toBe(false);+ });++ it('should open filter panel context only when panel is currently closed', async () => {+ const setCurrentTableFilterInfo = vi.fn();+ const setContextValue = vi.fn();++ const accessor = createAccessor([+ [TableManager, { getTable: () => ({ id: 't1' }) }],+ [IContextService, {+ getContextValue: () => false,+ setContextValue,+ }],+ [SheetsTableComponentController, {+ setCurrentTableFilterInfo,+ }],+ ]);++ const result = await OpenTableFilterPanelOperation.handler(accessor, {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ row: 6,+ col: 3,+ });++ expect(result).toBe(true);+ expect(setCurrentTableFilterInfo).toHaveBeenCalledWith({ unitId: 'u1', subUnitId: 's1', row: 6, tableId: 't1', column: 3 });+ expect(setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, true);+ });++ it('should not reopen the panel when context indicates already opened', async () => {+ const setCurrentTableFilterInfo = vi.fn();+ const setContextValue = vi.fn();++ const accessor = createAccessor([+ [TableManager, { getTable: () => ({ id: 't1' }) }],+ [IContextService, {+ getContextValue: () => true,+ setContextValue,+ }],+ [SheetsTableComponentController, {+ setCurrentTableFilterInfo,+ }],+ ]);++ const result = await OpenTableFilterPanelOperation.handler(accessor, {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ row: 6,+ col: 3,+ });++ expect(result).toBe(true);+ expect(setCurrentTableFilterInfo).not.toHaveBeenCalled();+ expect(setContextValue).not.toHaveBeenCalled();+ });+});diff --git a/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.tsnew file mode 100644index 0000000000..501a021b81--- /dev/null+++ b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts@@ -0,0 +1,137 @@+/**+ * 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 { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { AddSheetTableCommand } from '@univerjs/sheets-table';+import { IDialogService } from '@univerjs/ui';++import { describe, expect, it, vi } from 'vitest';+import { openRangeSelector, OpenTableSelectorOperation } from '../open-table-selector.operation';++const sheetsMocks = vi.hoisted(() => ({+ getSheetCommandTarget: vi.fn(),+ isSingleCellSelection: vi.fn(),+ expandToContinuousRange: vi.fn(),+ SheetsSelectionsService: Symbol('SheetsSelectionsService'),+}));++vi.mock('@univerjs/sheets', async () => {+ const actual = await vi.importActual('@univerjs/sheets');+ return {+ ...actual,+ getSheetCommandTarget: sheetsMocks.getSheetCommandTarget,+ isSingleCellSelection: sheetsMocks.isSingleCellSelection,+ expandToContinuousRange: sheetsMocks.expandToContinuousRange,+ SheetsSelectionsService: sheetsMocks.SheetsSelectionsService,+ };+});++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('open-table-selector operation', () => {+ it('openRangeSelector should resolve selected range and close dialog', async () => {+ const close = vi.fn();+ const dialogService = {+ open: vi.fn((props: any) => {+ props.children.label.props.onConfirm({ unitId: 'u1', subUnitId: 's1', range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 } });+ }),+ close,+ };++ const accessor = createAccessor([+ [IDialogService, dialogService],+ [LocaleService, { t: () => 'Select range' }],+ ]);++ const result = await openRangeSelector(accessor, 'u1', 's1', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 });++ expect(result).toEqual({ unitId: 'u1', subUnitId: 's1', range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 } });+ expect(close).toHaveBeenCalled();+ });++ it('OpenTableSelectorOperation should return false without sheet target', async () => {+ sheetsMocks.getSheetCommandTarget.mockReturnValue(null);++ const accessor = createAccessor([+ [IUniverInstanceService, {}],+ [ICommandService, { executeCommand: vi.fn() }],+ [SheetsSelectionsService, { getCurrentLastSelection: vi.fn() }],+ [IDialogService, { open: vi.fn(), close: vi.fn() }],+ [LocaleService, { t: () => 'Select range' }],+ ]);++ await expect(OpenTableSelectorOperation.handler(accessor)).resolves.toBe(false);+ });++ it('OpenTableSelectorOperation should expand single-cell selection and execute add-table command', async () => {+ sheetsMocks.getSheetCommandTarget.mockReturnValue({+ unitId: 'u1',+ subUnitId: 's1',+ worksheet: { id: 'sheet' },+ });+ sheetsMocks.isSingleCellSelection.mockReturnValue(true);+ sheetsMocks.expandToContinuousRange.mockReturnValue({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 });++ const executeCommand = vi.fn();+ const dialogService = {+ open: vi.fn((props: any) => {+ props.children.label.props.onConfirm({+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 },+ });+ }),+ close: vi.fn(),+ };++ const accessor = createAccessor([+ [IUniverInstanceService, {}],+ [ICommandService, { executeCommand }],+ [SheetsSelectionsService, {+ getCurrentLastSelection: () => ({+ range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 },+ }),+ }],+ [IDialogService, dialogService],+ [LocaleService, { t: () => 'Select range' }],+ ]);++ await expect(OpenTableSelectorOperation.handler(accessor)).resolves.toBe(true);++ expect(sheetsMocks.expandToContinuousRange).toHaveBeenCalledWith(+ { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 },+ { up: true, left: true, right: true, down: true },+ { id: 'sheet' }+ );++ expect(executeCommand).toHaveBeenCalledWith(AddSheetTableCommand.id, {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 },+ });+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-anchor.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-anchor.controller.spec.tsnew file mode 100644index 0000000000..f98b2875f1--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-anchor.controller.spec.ts@@ -0,0 +1,92 @@+/**+ * 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 { SetScrollOperation, SetZoomRatioOperation } from '@univerjs/sheets-ui';+import { BehaviorSubject, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SheetTableAnchorController } from '../sheet-table-anchor.controller';++describe('SheetTableAnchorController', () => {+ it('should register anchor UI and toggle anchor visibility on scroll/zoom commands', () => {+ vi.useFakeTimers();++ const commandListeners: Array<(command: any) => void> = [];+ const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));++ const controller = new SheetTableAnchorController(+ {+ unitId: 'u1',+ unit: {+ getUnitId: () => 'u1',+ activeSheet$: new BehaviorSubject({ getSheetId: () => 's1' }),+ getActiveSheet: () => ({ getSheetId: () => 's1' }),+ },+ } as any,+ {} as any,+ {+ currentSkeleton$: new Subject(),+ } as any,+ {+ getRenderById: () => null,+ } as any,+ {+ onCommandExecuted: (listener: (command: any) => void) => {+ commandListeners.push(listener);+ return { dispose: vi.fn() };+ },+ } as any,+ {} as any,+ {+ registerComponent,+ } as any,+ {+ tableAdd$: new Subject(),+ tableDelete$: new Subject(),+ tableNameChanged$: new Subject(),+ tableRangeChanged$: new Subject(),+ tableThemeChanged$: new Subject(),+ getTableList: () => [],+ } as any,+ {+ validViewportScrollInfo$: new Subject(),+ } as any,+ {+ unitPermissionInitStateChange$: new Subject(),+ } as any,+ {+ permissionPointUpdate$: new Subject(),+ getPermissionPoint: vi.fn(() => ({ value: true })),+ } as any+ );++ expect(registerComponent).toHaveBeenCalledTimes(1);++ commandListeners.forEach((listener) => listener({ id: SetZoomRatioOperation.id }));+ expect((controller as any)._anchorVisible$.getValue()).toBe(false);++ vi.advanceTimersByTime(300);+ expect((controller as any)._anchorVisible$.getValue()).toBe(true);++ commandListeners.forEach((listener) => listener({ id: SetScrollOperation.id }));+ expect((controller as any)._anchorVisible$.getValue()).toBe(false);++ vi.advanceTimersByTime(300);+ expect((controller as any)._anchorVisible$.getValue()).toBe(true);++ controller.dispose();+ vi.useRealTimers();+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.tsnew file mode 100644index 0000000000..88f5c99fb0--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.ts@@ -0,0 +1,74 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../../const';+import { SheetsTableComponentController } from '../sheet-table-component.controller';++describe('SheetsTableComponentController', () => {+ it('should open and close popup based on context state', () => {+ const context$ = new Subject<boolean | undefined>();+ const setContextValue = vi.fn();++ const popupDispose = vi.fn();+ const attachPopupToCell = vi.fn(() => ({ dispose: popupDispose }));+ const dialogClose = vi.fn();++ const controller = new SheetsTableComponentController(+ { register: vi.fn(() => ({ dispose: vi.fn() })) } as any,+ {+ subscribeContextValue$: () => context$,+ setContextValue,+ } as any,+ { attachPopupToCell } as any,+ { close: dialogClose } as any+ );++ controller.setCurrentTableFilterInfo({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ column: 2,+ row: 4,+ });++ context$.next(true);++ expect(attachPopupToCell).toHaveBeenCalledWith(4, 2, expect.objectContaining({+ componentKey: SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,+ direction: 'horizontal',+ offset: [5, 0],+ portal: true,+ }));++ const popupCalls = attachPopupToCell.mock.calls as Array<Array<any>>;+ const options = popupCalls[0]?.[2] as { onClickOutside: () => void } | undefined;+ expect(options).toBeDefined();+ options?.onClickOutside();+ expect(dialogClose).toHaveBeenCalledWith(UNIVER_SHEET_TABLE_FILTER_PANEL_ID);+ expect(setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);++ context$.next(false);+ expect(popupDispose).toHaveBeenCalled();+ expect(controller.getCurrentTableFilterInfo()).toBeNull();++ controller.closeFilterPanel();+ expect(setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);++ controller.dispose();+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.tsnew file mode 100644index 0000000000..7018dd4c09--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-filter-button-render.controller.spec.ts@@ -0,0 +1,78 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';++import { SheetsTableFilterButtonRenderController } from '../sheet-table-filter-button-render.controller';++vi.hoisted(() => {+ class FakePath2D {+ constructor(_path?: string) {}+ }+ (globalThis as unknown as { Path2D: typeof FakePath2D }).Path2D = FakePath2D;+});++describe('SheetsTableFilterButtonRenderController', () => {+ it('should dispose rendered button shapes and interceptor resource', () => {+ const controller = new SheetsTableFilterButtonRenderController(+ {+ unit: {+ getUnitId: () => 'u1',+ getActiveSheet: () => null,+ },+ unitId: 'u1',+ scene: {+ addObjects: vi.fn(),+ makeDirty: vi.fn(),+ },+ } as any,+ { createInstance: vi.fn() } as any,+ {+ currentSkeleton$: new Subject(),+ getCurrentSkeleton: () => null,+ } as any,+ {+ intercept: vi.fn(() => ({ dispose: vi.fn() })),+ } as any,+ {+ tableAdd$: new Subject(),+ tableNameChanged$: new Subject(),+ tableRangeChanged$: new Subject(),+ tableThemeChanged$: new Subject(),+ tableDelete$: new Subject(),+ tableFilterChanged$: new Subject(),+ getSheetFilterRangeWithState: vi.fn(() => []),+ } as any,+ {+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),+ } as any+ );++ const shapeDispose = vi.fn();+ const interceptorDispose = vi.fn();++ (controller as any)._tableFilterButtonShapes = [{ dispose: shapeDispose }];+ (controller as any)._buttonRenderDisposable = { dispose: interceptorDispose };++ controller.dispose();++ expect(shapeDispose).toHaveBeenCalledTimes(1);+ expect(interceptorDispose).toHaveBeenCalledTimes(1);+ expect((controller as any)._tableFilterButtonShapes).toEqual([]);+ expect((controller as any)._buttonRenderDisposable).toBeNull();+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-menu.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-menu.controller.spec.tsnew file mode 100644index 0000000000..fae5a2cadb--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-menu.controller.spec.ts@@ -0,0 +1,41 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { SHEET_TABLE_THEME_PANEL, TABLE_SELECTOR_DIALOG, TABLE_TOOLBAR_BUTTON } from '../../const';+import { menuSchema } from '../menu.schema';+import { SheetTableMenuController } from '../sheet-table-menu.controller';++describe('SheetTableMenuController', () => {+ it('should register table components and merge table menu schema', () => {+ const register = vi.fn(() => ({ dispose: vi.fn() }));+ const mergeMenu = vi.fn();++ const controller = new SheetTableMenuController(+ { register } as any,+ { mergeMenu } as any+ );++ expect(register).toHaveBeenCalledTimes(3);+ const calls = register.mock.calls as Array<Array<any>>;+ expect(calls[0]?.[0]).toBe(TABLE_TOOLBAR_BUTTON);+ expect(calls[1]?.[0]).toBe(TABLE_SELECTOR_DIALOG);+ expect(calls[2]?.[0]).toBe(SHEET_TABLE_THEME_PANEL);+ expect(mergeMenu).toHaveBeenCalledWith(menuSchema);++ controller.dispose();+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-render.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-render.controller.spec.tsnew file mode 100644index 0000000000..525d08d9e1--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-render.controller.spec.ts@@ -0,0 +1,72 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SheetsTableRenderController } from '../sheet-table-render.controller';++describe('SheetsTableRenderController', () => {+ it('should dirty skeleton and recalculate on table/theme refresh events', () => {+ const tableAdd$ = new Subject<any>();+ const tableDelete$ = new Subject<any>();+ const tableNameChanged$ = new Subject<any>();+ const tableRangeChanged$ = new Subject<any>();+ const tableThemeChanged$ = new Subject<any>();+ const tableFilterChanged$ = new Subject<any>();+ const tableInitStatus$ = new Subject<any>();+ const refreshTable$ = new Subject<number>();++ const makeDirty = vi.fn();+ const reCalculate = vi.fn();++ const controller = new SheetsTableRenderController(+ {+ mainComponent: { makeDirty },+ } as any,+ {} as any,+ {+ getCurrentParam: () => ({ unitId: 'u1', subUnitId: 's1' }),+ reCalculate,+ } as any,+ {+ tableAdd$,+ tableDelete$,+ tableNameChanged$,+ tableRangeChanged$,+ tableThemeChanged$,+ tableFilterChanged$,+ tableInitStatus$,+ } as any,+ {+ refreshTable$,+ } as any+ );++ tableAdd$.next({});+ tableDelete$.next({});+ tableNameChanged$.next({});+ tableRangeChanged$.next({});+ tableThemeChanged$.next({});+ tableFilterChanged$.next({});+ tableInitStatus$.next(true);+ refreshTable$.next(1);++ expect(makeDirty).toHaveBeenCalled();+ expect(reCalculate).toHaveBeenCalledWith({ unitId: 'u1', subUnitId: 's1', dirty: true });++ controller.dispose();+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.tsnew file mode 100644index 0000000000..0ff08b3097--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts@@ -0,0 +1,93 @@+/**+ * 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 { SetSelectionsOperation } from '@univerjs/sheets';+import { SelectAllCommand } from '@univerjs/sheets-ui';+import { describe, expect, it, vi } from 'vitest';+import { SheetTableSelectionController } from '../sheet-table-selection.controller';++describe('SheetTableSelectionController', () => {+ it('should toggle select-all behavior between table body and table with header', () => {+ let interceptCommandConfig: any;++ const tableRange = { startRow: 2, endRow: 5, startColumn: 1, endColumn: 3 };+ const table = {+ getRange: () => tableRange,+ };++ const worksheet = {+ getSheetId: () => 's1',+ getMergedCell: () => null,+ };++ const workbook = {+ getUnitId: () => 'u1',+ getActiveSheet: () => worksheet,+ };++ const controller = new SheetTableSelectionController(+ {+ interceptCommand: vi.fn((config: any) => {+ interceptCommandConfig = config;+ return { dispose: vi.fn() };+ }),+ } as any,+ {+ getCurrentUnitOfType: () => workbook,+ } as any,+ {+ getTablesBySubunitId: () => [table],+ } as any+ );++ const selectWholeTable = interceptCommandConfig.getMutations({+ id: SelectAllCommand.id,+ params: { range: tableRange },+ });+ expect(selectWholeTable).toEqual({ redos: [], undos: [] });++ const tableBodyRange = { ...tableRange, startRow: tableRange.startRow + 1 };+ const selectBodyThenExpandToHeader = interceptCommandConfig.getMutations({+ id: SelectAllCommand.id,+ params: { range: tableBodyRange },+ });++ expect(selectBodyThenExpandToHeader.redos).toHaveLength(1);+ expect(selectBodyThenExpandToHeader.redos[0]).toEqual({+ id: SetSelectionsOperation.id,+ params: expect.objectContaining({+ unitId: 'u1',+ subUnitId: 's1',+ selections: [expect.objectContaining({ range: tableRange })],+ }),+ });++ const randomRange = { startRow: 3, endRow: 3, startColumn: 1, endColumn: 2 };+ const selectRandomThenBody = interceptCommandConfig.getMutations({+ id: SelectAllCommand.id,+ params: { range: randomRange },+ });+ expect(selectRandomThenBody.redos).toHaveLength(1);+ expect(selectRandomThenBody.redos[0]).toEqual({+ id: SetSelectionsOperation.id,+ params: expect.objectContaining({+ selections: [expect.objectContaining({ range: tableBodyRange })],+ }),+ });++ controller.dispose();+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-theme-ui.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-theme-ui.controller.spec.tsnew file mode 100644index 0000000000..6aeaa21d1f--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-theme-ui.controller.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 { SetRangeThemeMutation } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { SheetTableThemeUIController } from '../sheet-table-theme-ui.controller';++describe('SheetTableThemeUIController', () => {+ it('should emit refresh signal only for table custom theme updates', () => {+ const listeners: Array<(command: any) => void> = [];++ const controller = new SheetTableThemeUIController({+ onCommandExecuted: (listener: (command: any) => void) => {+ listeners.push(listener);+ return { dispose: vi.fn() };+ },+ } as any);++ const values: number[] = [];+ const subscription = controller.refreshTable$.subscribe((value) => values.push(value));++ listeners.forEach((listener) => listener({+ id: SetRangeThemeMutation.id,+ params: { styleName: 'table-custom-2026' },+ }));++ listeners.forEach((listener) => listener({+ id: SetRangeThemeMutation.id,+ params: { styleName: 'table-default-0' },+ }));++ expect(values.length).toBe(1);+ expect(typeof values[0]).toBe('number');++ subscription.unsubscribe();+ controller.dispose();+ });+});diff --git a/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui-service.spec.ts b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui-service.spec.tsnew file mode 100644index 0000000000..3ee26a2a8a--- /dev/null+++ b/packages/sheets-table-ui/src/services/__tests__/sheets-table-ui-service.spec.ts@@ -0,0 +1,142 @@+/**+ * 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 { SetRangeValuesMutation } from '@univerjs/sheets';+import { SetSheetTableFilterCommand, TableColumnFilterTypeEnum } from '@univerjs/sheets-table';+import { describe, expect, it, vi } from 'vitest';+import { FilterByEnum } from '../../types';+import { SheetsTableUiService } from '../sheets-table-ui-service';++describe('SheetsTableUiService', () => {+ it('should build panel props, compute cached filter items and clear cache on related commands', () => {+ const listeners: Array<(command: any) => void> = [];+ const executeCommand = vi.fn();++ const commandService = {+ onCommandExecuted: vi.fn((listener: (command: any) => void) => {+ listeners.push(listener);+ return { dispose: vi.fn() };+ }),+ executeCommand,+ };++ const table = {+ getId: () => 't1',+ getSubunitId: () => 's1',+ getRange: () => ({ startRow: 0, endRow: 3, startColumn: 1, endColumn: 2 }),+ getTableFilterRange: () => ({ startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 }),+ getTableFilterColumn: (index: number) => {+ if (index === 0) {+ return { filterType: TableColumnFilterTypeEnum.condition, condition: [] };+ }+ return { filterType: TableColumnFilterTypeEnum.manual, values: ['A', 'B'] };+ },+ };++ const tableManager = {+ getTable: vi.fn(() => table),+ getTablesBySubunitId: vi.fn(() => [table]),+ };++ const getCellValueWithConditionType = vi.fn((worksheet, row: number, col: number) => {+ if (row === 1 && col === 2) {+ return 'A';+ }+ if (row === 3 && col === 2) {+ return undefined;+ }+ return 'B';+ });++ const worksheet = {+ isRowFiltered: (row: number) => row === 2,+ };++ const univerInstanceService = {+ getUnit: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => worksheet),+ })),+ };++ const service = new SheetsTableUiService(+ tableManager as any,+ { getCellValueWithConditionType } as any,+ univerInstanceService as any,+ commandService as any,+ { t: (key: string) => (key === 'sheets-table.condition.empty' ? '(empty)' : key) } as any+ );++ expect(service.getTableFilterPanelInitProps('u1', 's1', 't1', 1)).toEqual({+ unitId: 'u1',+ subUnitId: 's1',+ tableFilter: { filterType: TableColumnFilterTypeEnum.condition, condition: [] },+ currentFilterBy: FilterByEnum.Condition,+ tableId: 't1',+ columnIndex: 0,+ });++ expect(service.getTableFilterCheckedItems('u1', 't1', 1)).toEqual(['A', 'B']);++ const first = service.getTableFilterItems('u1', 's1', 't1', 1);+ expect(first.allItemsCount).toBe(2);+ expect(first.data.map((item) => item.title)).toEqual(['A', '(empty)']);+ expect(first.itemsCountMap.get('A')).toBe(1);+ expect(first.itemsCountMap.get('(empty)')).toBe(1);+ const countAfterFirstBuild = getCellValueWithConditionType.mock.calls.length;++ const second = service.getTableFilterItems('u1', 's1', 't1', 1);+ expect(second).toEqual(first);+ expect(getCellValueWithConditionType).toHaveBeenCalledTimes(countAfterFirstBuild);++ listeners.forEach((listener) => listener({+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'u1',+ subUnitId: 's1',+ cellValue: {+ 1: {+ 2: { v: 'updated' },+ },+ },+ },+ }));++ service.getTableFilterItems('u1', 's1', 't1', 1);+ expect(getCellValueWithConditionType.mock.calls.length).toBeGreaterThan(countAfterFirstBuild);++ const countAfterRangeUpdate = getCellValueWithConditionType.mock.calls.length;+ listeners.forEach((listener) => listener({+ id: SetSheetTableFilterCommand.id,+ params: {+ unitId: 'u1',+ tableId: 't1',+ },+ }));++ service.getTableFilterItems('u1', 's1', 't1', 1);+ expect(getCellValueWithConditionType.mock.calls.length).toBeGreaterThan(countAfterRangeUpdate);++ service.setTableFilter('u1', 't1', 1, { filterType: TableColumnFilterTypeEnum.manual, values: ['A'] } as any);+ expect(executeCommand).toHaveBeenCalledWith(SetSheetTableFilterCommand.id, {+ unitId: 'u1',+ tableId: 't1',+ column: 1,+ tableFilter: { filterType: TableColumnFilterTypeEnum.manual, values: ['A'] },+ });++ service.dispose();+ });+});diff --git a/packages/sheets-table/src/__tests__/util.spec.ts b/packages/sheets-table/src/__tests__/util.spec.tsnew file mode 100644index 0000000000..51658a6ab3--- /dev/null+++ b/packages/sheets-table/src/__tests__/util.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 { CellValueType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { SheetsTableButtonStateEnum, SheetsTableSortStateEnum, TableColumnFilterTypeEnum } from '../types/enum';+import {+ convertCellDataToString,+ getColumnName,+ getExistingNamesSet,+ getStringFromDataStream,+ getTableFilterState,+ isConditionFilter,+ isManualTableFilter,+} from '../util';++describe('sheets-table util', () => {+ it('should format column names', () => {+ expect(getColumnName(3, 'Column')).toBe('Column 3');+ });++ it('should remove trailing CRLF from rich text stream', () => {+ expect(getStringFromDataStream({ body: { dataStream: 'A\r\n' } } as any)).toBe('A');+ expect(getStringFromDataStream({ body: { dataStream: 'B' } } as any)).toBe('B');+ });++ it('should convert different cell value types to string', () => {+ expect(convertCellDataToString(null)).toBe('');+ expect(convertCellDataToString({ p: { body: { dataStream: 'hello\r\n' } } as any } as any)).toBe('hello');+ expect(convertCellDataToString({ t: CellValueType.STRING, v: 'x' } as any)).toBe('x');+ expect(convertCellDataToString({ t: CellValueType.FORCE_STRING, v: 1 } as any)).toBe('1');+ expect(convertCellDataToString({ t: CellValueType.BOOLEAN, v: true } as any)).toBe('TRUE');+ expect(convertCellDataToString({ t: CellValueType.BOOLEAN, v: false } as any)).toBe('FALSE');+ expect(convertCellDataToString({ t: CellValueType.NUMBER, v: 12 } as any)).toBe('12');+ expect(convertCellDataToString({ v: true } as any)).toBe('TRUE');+ expect(convertCellDataToString({ v: undefined } as any)).toBe('');+ });++ it('should calculate filter button states from filter and sort state', () => {+ const manualFilter = { filterType: TableColumnFilterTypeEnum.manual, values: ['a'] } as any;++ expect(getTableFilterState(manualFilter, SheetsTableSortStateEnum.None)).toBe(SheetsTableButtonStateEnum.FilteredSortNone);+ expect(getTableFilterState(manualFilter, SheetsTableSortStateEnum.Asc)).toBe(SheetsTableButtonStateEnum.FilteredSortAsc);+ expect(getTableFilterState(manualFilter, SheetsTableSortStateEnum.Desc)).toBe(SheetsTableButtonStateEnum.FilteredSortDesc);++ expect(getTableFilterState(undefined, SheetsTableSortStateEnum.None)).toBe(SheetsTableButtonStateEnum.FilterNoneSortNone);+ expect(getTableFilterState(undefined, SheetsTableSortStateEnum.Asc)).toBe(SheetsTableButtonStateEnum.FilterNoneSortAsc);+ expect(getTableFilterState(undefined, SheetsTableSortStateEnum.Desc)).toBe(SheetsTableButtonStateEnum.FilterNoneSortDesc);+ });++ it('should detect condition/manual filter types', () => {+ const condition = { filterType: TableColumnFilterTypeEnum.condition } as any;+ const manual = { filterType: TableColumnFilterTypeEnum.manual, values: [] } as any;++ expect(isConditionFilter(condition)).toBe(true);+ expect(isConditionFilter(manual)).toBe(false);+ expect(isConditionFilter(undefined)).toBe(false);++ expect(isManualTableFilter(manual)).toBe(true);+ expect(isManualTableFilter(condition)).toBe(false);+ expect(isManualTableFilter(undefined)).toBe(false);+ });++ it('should collect existing names from sheets/tables/defined names as lowercase', () => {+ const workbook = {+ getSheets: () => [+ { getName: () => 'SheetA' },+ { getName: () => 'SheetB' },+ ],+ } as any;++ const names = getExistingNamesSet('unit-1', {+ univerInstanceService: {+ getUnit: () => workbook,+ } as any,+ tableManager: {+ getTableList: () => [+ { name: 'Table_One' },+ { name: 'Table_Two' },+ ],+ } as any,+ definedNamesService: {+ getDefinedNameMap: () => ({+ d1: { name: 'BudgetRange' },+ }),+ } as any,+ });++ expect(names).toEqual(new Set(['sheeta', 'sheetb', 'table_one', 'table_two', 'budgetrange']));+ });+});diff --git a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.tsnew file mode 100644index 0000000000..e54759a506--- /dev/null+++ b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts@@ -0,0 +1,106 @@+/**+ * 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 { ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';++import { describe, expect, it, vi } from 'vitest';+import { SheetsTableController } from '../../../controllers/sheets-table.controller';+import { TableManager } from '../../../model/table-manager';+import {+ SheetTableInsertColCommand,+ SheetTableInsertRowCommand,+ SheetTableRemoveColCommand,+ SheetTableRemoveRowCommand,+} from '../sheet-table-row-col.command';++const sheetsMocks = vi.hoisted(() => ({+ getSheetCommandTarget: vi.fn(),+ getMoveRangeUndoRedoMutations: vi.fn(),+ SheetsSelectionsService: Symbol('SheetsSelectionsService'),+}));++vi.mock('@univerjs/sheets', async () => {+ const actual = await vi.importActual('@univerjs/sheets');+ return {+ ...actual,+ getSheetCommandTarget: sheetsMocks.getSheetCommandTarget,+ getMoveRangeUndoRedoMutations: sheetsMocks.getMoveRangeUndoRedoMutations,+ SheetsSelectionsService: sheetsMocks.SheetsSelectionsService,+ };+});++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('sheet-table-row-col commands', () => {+ it('insert commands should return false when there is no sheet target', () => {+ sheetsMocks.getSheetCommandTarget.mockReturnValue(null);++ const accessor = createAccessor([+ [IUniverInstanceService, {}],+ ]);++ expect(SheetTableInsertRowCommand.handler(accessor)).toBe(false);+ expect(SheetTableInsertColCommand.handler(accessor)).toBe(false);+ });++ it('remove commands should return false for invalid params', () => {+ const accessor = createAccessor([+ [IUniverInstanceService, {}],+ ]);++ expect(SheetTableRemoveRowCommand.handler(accessor, undefined as any)).toBe(false);+ expect(SheetTableRemoveColCommand.handler(accessor, undefined as any)).toBe(false);+ });++ it('commands should stop when current selection is invalid or table is missing', () => {+ sheetsMocks.getSheetCommandTarget.mockReturnValue({+ unitId: 'u1',+ subUnitId: 's1',+ worksheet: {+ getRowCount: () => 100,+ getColumnCount: () => 100,+ getCellMatrix: () => ({ getDataRange: () => ({ endRow: 10, endColumn: 10 }) }),+ },+ workbook: {},+ });++ const accessor = createAccessor([+ [IUniverInstanceService, {}],+ [SheetsSelectionsService, { getCurrentSelections: () => [] }],+ [SheetsTableController, { getContainerTableWithRange: () => null }],+ [TableManager, {}],+ [ICommandService, { syncExecuteCommand: vi.fn(() => true) }],+ [IUndoRedoService, { pushUndoRedo: vi.fn() }],+ ]);++ expect(SheetTableInsertRowCommand.handler(accessor)).toBe(false);+ expect(SheetTableInsertColCommand.handler(accessor)).toBe(false);++ expect(SheetTableRemoveRowCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' } as any)).toBe(false);+ expect(SheetTableRemoveColCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' } as any)).toBe(false);+ });+});diff --git a/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.tsnew file mode 100644index 0000000000..59009f0e80--- /dev/null+++ b/packages/sheets-table/src/commands/commands/__tests__/table-commands.spec.ts@@ -0,0 +1,353 @@+/**+ * 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 { ICommandService, ILogService, IUndoRedoService, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { IDefinedNamesService } from '@univerjs/engine-formula';+import { AddRangeThemeMutation, RemoveRangeThemeMutation, SheetRangeThemeModel } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { TableManager } from '../../../model/table-manager';+import { IRangeOperationTypeEnum, IRowColTypeEnum } from '../../../types/type';+import { AddSheetTableMutation } from '../../mutations/add-sheet-table.mutation';+import { DeleteSheetTableMutation } from '../../mutations/delete-sheet-table.mutation';+import { SetSheetTableMutation } from '../../mutations/set-sheet-table.mutation';+import { SetSheetTableFilterMutation } from '../../mutations/set-table-filter.mutation';+import { AddSheetTableCommand } from '../add-sheet-table.command';+import { AddTableThemeCommand } from '../add-table-theme.command';+import { DeleteSheetTableCommand } from '../delete-sheet-table.command';+import { RemoveTableThemeCommand } from '../remove-table-theme.command';+import { SetSheetTableCommand } from '../set-sheet-table.command';+import { SetSheetTableFilterCommand } from '../set-table-filter.command';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const services = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!services.has(token)) {+ throw new Error(`Missing dependency: ${String(token)}`);+ }+ return services.get(token);+ },+ } as any;+}++describe('sheets-table commands', () => {+ it('AddSheetTableCommand should auto-generate table name and push undo/redo', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const pushUndoRedo = vi.fn();+ const tableManager = {+ getTableList: vi.fn(() => [{ name: 'table9' }]),+ getColumnHeader: vi.fn(() => ['Name']),+ };++ const accessor = createAccessor([+ [ICommandService, { syncExecuteCommand }],+ [IUndoRedoService, { pushUndoRedo }],+ [LocaleService, { t: (key: string) => (key === 'sheets-table.tablePrefix' ? 'Table' : 'Column') }],+ [TableManager, tableManager],+ [IUniverInstanceService, {+ getUnit: () => ({ getSheets: () => [{ getName: () => 'SheetA' }] }),+ }],+ [IDefinedNamesService, {+ getDefinedNameMap: () => ({ d1: { name: 'DefinedA' } }),+ }],+ ]);++ const result = AddSheetTableCommand.handler(accessor, {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },+ name: 'SheetA',+ });++ expect(result).toBe(true);+ expect(tableManager.getColumnHeader).toHaveBeenCalledWith(+ 'u1',+ 's1',+ { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },+ 'Column'+ );+ expect(syncExecuteCommand).toHaveBeenCalledWith(+ AddSheetTableMutation.id,+ expect.objectContaining({+ unitId: 'u1',+ subUnitId: 's1',+ name: 'Table10',+ header: ['Name'],+ }),+ undefined+ );+ expect(pushUndoRedo).toHaveBeenCalledTimes(1);+ });++ it('AddSheetTableCommand should return false when params are missing', () => {+ expect(AddSheetTableCommand.handler(createAccessor([]), undefined as any)).toBe(false);+ });++ it('DeleteSheetTableCommand should build undo mutations from table snapshot', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const pushUndoRedo = vi.fn();+ const tableSnapshot = {+ id: 't1',+ name: 'Table1',+ range: { startRow: 1, endRow: 5, startColumn: 2, endColumn: 4 },+ options: { headerRow: true },+ };+ const tableManager = {+ getTable: vi.fn(() => ({ toJSON: () => tableSnapshot })),+ };+ const accessor = createAccessor([+ [IUndoRedoService, { pushUndoRedo }],+ [ICommandService, { syncExecuteCommand }],+ [TableManager, tableManager],+ [ILogService, { error: vi.fn() }],+ ]);++ const result = DeleteSheetTableCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' });++ expect(result).toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith(DeleteSheetTableMutation.id, { unitId: 'u1', subUnitId: 's1', tableId: 't1' }, undefined);+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({+ unitID: 'u1',+ undoMutations: [+ expect.objectContaining({+ id: AddSheetTableMutation.id,+ params: expect.objectContaining({+ tableId: 't1',+ name: 'Table1',+ }),+ }),+ ],+ }));+ });++ it('DeleteSheetTableCommand should return false when table does not exist', () => {+ const logService = { error: vi.fn() };+ const accessor = createAccessor([+ [IUndoRedoService, { pushUndoRedo: vi.fn() }],+ [ICommandService, { syncExecuteCommand: vi.fn(() => true) }],+ [TableManager, { getTable: () => undefined }],+ [ILogService, logService],+ ]);++ expect(DeleteSheetTableCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' })).toBe(false);+ expect(logService.error).toHaveBeenCalled();+ });++ it('SetSheetTableCommand should reject invalid table name and warn', () => {+ const logService = { warn: vi.fn() };+ const commandService = { executeCommand: vi.fn() };+ const table = {+ getDisplayName: () => 'Old',+ getRange: () => ({ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }),+ getSubunitId: () => 's1',+ getTableStyleId: () => 'theme-1',+ };++ const accessor = createAccessor([+ [TableManager, { getTableById: () => table, getTableList: () => [] }],+ [LocaleService, { t: () => 'invalid name' }],+ [IUniverInstanceService, {+ getUnit: () => ({ getSheets: () => [{ getName: () => 'SheetA' }] }),+ }],+ [IDefinedNamesService, { getDefinedNameMap: () => ({}) }],+ [ICommandService, commandService],+ [IUndoRedoService, { pushUndoRedo: vi.fn() }],+ [ILogService, logService],+ ]);++ const result = SetSheetTableCommand.handler(accessor, {+ unitId: 'u1',+ tableId: 't1',+ name: 'SheetA',+ });++ expect(result).toBe(false);+ expect(logService.warn).toHaveBeenCalledWith('invalid name');+ expect(commandService.executeCommand).not.toHaveBeenCalled();+ });++ it('SetSheetTableCommand should execute mutation and build inverse undo config', () => {+ const executeCommand = vi.fn();+ const pushUndoRedo = vi.fn();+ const table = {+ getDisplayName: () => 'OldName',+ getRange: () => ({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 }),+ getSubunitId: () => 's1',+ getTableStyleId: () => 'theme-old',+ };++ const accessor = createAccessor([+ [TableManager, { getTableById: () => table, getTableList: () => [] }],+ [LocaleService, { t: () => 'msg' }],+ [IUniverInstanceService, { getUnit: () => ({ getSheets: () => [{ getName: () => 'SheetA' }] }) }],+ [IDefinedNamesService, { getDefinedNameMap: () => ({}) }],+ [ICommandService, { executeCommand }],+ [IUndoRedoService, { pushUndoRedo }],+ [ILogService, { warn: vi.fn() }],+ ]);++ const result = SetSheetTableCommand.handler(accessor, {+ unitId: 'u1',+ tableId: 't1',+ name: 'NewName',+ rowColOperation: {+ operationType: IRangeOperationTypeEnum.Insert,+ rowColType: IRowColTypeEnum.Col,+ index: 2,+ count: 1,+ },+ updateRange: {+ newRange: { startRow: 1, endRow: 6, startColumn: 1, endColumn: 4 },+ },+ theme: 'theme-new',+ });++ expect(result).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(+ SetSheetTableMutation.id,+ expect.objectContaining({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ config: expect.objectContaining({+ name: 'NewName',+ theme: 'theme-new',+ }),+ })+ );++ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({+ undoMutations: [+ expect.objectContaining({+ id: SetSheetTableMutation.id,+ params: expect.objectContaining({+ config: expect.objectContaining({+ name: 'OldName',+ theme: 'theme-old',+ rowColOperation: expect.objectContaining({ operationType: IRangeOperationTypeEnum.Delete }),+ }),+ }),+ }),+ ],+ }));+ });++ it('SetSheetTableFilterCommand should execute mutation with generated table id', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const pushUndoRedo = vi.fn();+ const accessor = createAccessor([+ [IUndoRedoService, { pushUndoRedo }],+ [ICommandService, { syncExecuteCommand }],+ ]);++ const result = SetSheetTableFilterCommand.handler(accessor, {+ unitId: 'u1',+ tableId: undefined as any,+ column: 1,+ tableFilter: { filterType: 'manual', values: ['A'] } as any,+ });++ expect(result).toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith(+ SetSheetTableFilterMutation.id,+ expect.objectContaining({+ unitId: 'u1',+ column: 1,+ tableFilter: { filterType: 'manual', values: ['A'] },+ }),+ undefined+ );+ const firstCall = syncExecuteCommand.mock.calls[0] as Array<any> | undefined;+ const tableId = (firstCall?.[1] as { tableId?: string } | undefined)?.tableId;+ expect(typeof tableId).toBe('string');+ expect((tableId ?? '').length).toBeGreaterThan(0);+ expect(pushUndoRedo).toHaveBeenCalled();+ });++ it('AddTableThemeCommand should register theme and update table style', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const pushUndoRedo = vi.fn();+ const themeStyle = {+ toJson: () => ({ name: 'theme-new' }),+ getName: () => 'theme-new',+ } as any;+ const table = {+ getSubunitId: () => 's1',+ getTableStyleId: () => 'theme-old',+ };++ const accessor = createAccessor([+ [TableManager, { getTableById: () => table }],+ [ICommandService, { syncExecuteCommand }],+ [IUndoRedoService, { pushUndoRedo }],+ ]);++ const result = AddTableThemeCommand.handler(accessor, {+ unitId: 'u1',+ tableId: 't1',+ themeStyle,+ });++ expect(result).toBe(true);+ expect(syncExecuteCommand).toHaveBeenNthCalledWith(1, AddRangeThemeMutation.id, {+ unitId: 'u1',+ subUnitId: 's1',+ styleJSON: { name: 'theme-new' },+ }, undefined);+ expect(syncExecuteCommand).toHaveBeenNthCalledWith(2, SetSheetTableMutation.id, {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ config: { theme: 'theme-new' },+ }, undefined);+ expect(pushUndoRedo).toHaveBeenCalled();+ });++ it('RemoveTableThemeCommand should select replacement theme and build undo payload', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const pushUndoRedo = vi.fn();++ const accessor = createAccessor([+ [TableManager, { getTableById: () => ({ getSubunitId: () => 's1' }) }],+ [SheetRangeThemeModel, {+ getRegisteredRangeThemes: () => ['table-default-0', 'table-default-1', 'table-custom-1', 'table-custom-2'],+ getDefaultRangeThemeStyle: () => ({ toJson: () => ({ name: 'table-custom-1' }) }),+ }],+ [ICommandService, { syncExecuteCommand }],+ [IUndoRedoService, { pushUndoRedo }],+ ]);++ const result = RemoveTableThemeCommand.handler(accessor, {+ unitId: 'u1',+ tableId: 't1',+ themeName: 'table-custom-1',+ });++ expect(result).toBe(true);+ expect(syncExecuteCommand).toHaveBeenNthCalledWith(1, SetSheetTableMutation.id, {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ config: { theme: 'table-custom-2' },+ }, undefined);+ expect(syncExecuteCommand).toHaveBeenNthCalledWith(2, RemoveRangeThemeMutation.id, {+ unitId: 'u1',+ subUnitId: 's1',+ styleName: 'table-custom-1',+ }, undefined);+ expect(pushUndoRedo).toHaveBeenCalled();+ });+});diff --git a/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts b/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.tsnew file mode 100644index 0000000000..5368f978d2--- /dev/null+++ b/packages/sheets-table/src/commands/mutations/__tests__/table-mutations.spec.ts@@ -0,0 +1,123 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { TableManager } from '../../../model/table-manager';+import { SheetTableService } from '../../../services/table-service';+import { AddSheetTableMutation } from '../add-sheet-table.mutation';+import { DeleteSheetTableMutation } from '../delete-sheet-table.mutation';+import { SetSheetTableMutation } from '../set-sheet-table.mutation';+import { SetSheetTableFilterMutation } from '../set-table-filter.mutation';++function accessorForService(service: SheetTableService) {+ return {+ get(token: unknown) {+ if (token === SheetTableService) {+ return service;+ }+ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as any;+}++function accessorForTableManager(tableManager: TableManager) {+ return {+ get(token: unknown) {+ if (token === TableManager) {+ return tableManager;+ }+ throw new Error(`Unknown token: ${String(token)}`);+ },+ } as any;+}++describe('sheets-table mutations', () => {+ it('AddSheetTableMutation should delegate to SheetTableService.addTable', () => {+ const service = {+ addTable: vi.fn(),+ } as unknown as SheetTableService;++ const result = AddSheetTableMutation.handler(accessorForService(service), {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ name: 'Table',+ header: ['A'],+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ options: { showHeader: true },+ });++ expect(result).toBe(true);+ expect(service.addTable).toHaveBeenCalledWith(+ 'u1',+ 's1',+ 'Table',+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ ['A'],+ 't1',+ { showHeader: true }+ );+ });++ it('DeleteSheetTableMutation should delegate to SheetTableService.deleteTable', () => {+ const service = {+ deleteTable: vi.fn(),+ } as unknown as SheetTableService;++ const result = DeleteSheetTableMutation.handler(accessorForService(service), {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ });++ expect(result).toBe(true);+ expect(service.deleteTable).toHaveBeenCalledWith('u1', 's1', 't1');+ });++ it('SetSheetTableMutation should return false without params and set config otherwise', () => {+ const tableManager = {+ setTableByConfig: vi.fn(),+ } as unknown as TableManager;++ expect(SetSheetTableMutation.handler(accessorForTableManager(tableManager), undefined as any)).toBe(false);++ const result = SetSheetTableMutation.handler(accessorForTableManager(tableManager), {+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ config: { name: 'NewName' },+ });++ expect(result).toBe(true);+ expect(tableManager.setTableByConfig).toHaveBeenCalledWith('u1', 't1', { name: 'NewName' });+ });++ it('SetSheetTableFilterMutation should delegate to TableManager.addFilter', () => {+ const tableManager = {+ addFilter: vi.fn(),+ } as unknown as TableManager;++ const result = SetSheetTableFilterMutation.handler(accessorForTableManager(tableManager), {+ unitId: 'u1',+ tableId: 't1',+ column: 0,+ tableFilter: { filterType: 'manual', values: ['A'] } as any,+ });++ expect(result).toBe(true);+ expect(tableManager.addFilter).toHaveBeenCalledWith('u1', 't1', 0, { filterType: 'manual', values: ['A'] });+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.tsnew file mode 100644index 0000000000..a9450433bb--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts@@ -0,0 +1,87 @@+/**+ * 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 { RemoveSuperTableMutation, SetSuperTableMutation } from '@univerjs/engine-formula';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SheetTableFormulaController } from '../sheet-table-formula.controller';++describe('SheetTableFormulaController', () => {+ it('should sync super table metadata on add/range/name/delete events', () => {+ const tableAdd$ = new Subject<any>();+ const tableRangeChanged$ = new Subject<any>();+ const tableDelete$ = new Subject<any>();+ const tableNameChanged$ = new Subject<any>();++ const table = {+ getTableInfo: () => ({+ name: 'Orders',+ subUnitId: 's1',+ range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ columns: [+ { displayName: 'id' },+ { displayName: 'amount' },+ ],+ }),+ };++ const tableManager = {+ tableAdd$,+ tableRangeChanged$,+ tableDelete$,+ tableNameChanged$,+ getTableById: vi.fn(() => table),+ };++ const executeCommand = vi.fn();+ const commandService = { executeCommand };++ const controller = new SheetTableFormulaController(tableManager as any, commandService as any);++ tableAdd$.next({ unitId: 'u1', tableId: 't1' });++ expect(executeCommand).toHaveBeenCalledWith(SetSuperTableMutation.id, expect.objectContaining({+ unitId: 'u1',+ tableName: 'Orders',+ reference: expect.objectContaining({+ sheetId: 's1',+ range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ }),+ }));++ const titleMap = executeCommand.mock.calls[0][1].reference.titleMap as Map<string, number>;+ expect(titleMap.get('id')).toBe(0);+ expect(titleMap.get('amount')).toBe(1);++ tableRangeChanged$.next({ unitId: 'u1', tableId: 't1' });+ expect(executeCommand).toHaveBeenCalledTimes(2);++ tableNameChanged$.next({ unitId: 'u1', tableId: 't1', oldTableName: 'Orders_Old' });+ expect(executeCommand).toHaveBeenNthCalledWith(3, RemoveSuperTableMutation.id, {+ unitId: 'u1',+ tableName: 'Orders_Old',+ });+ expect(executeCommand).toHaveBeenCalledTimes(4);++ tableDelete$.next({ unitId: 'u1', tableName: 'Orders' });+ expect(executeCommand).toHaveBeenLastCalledWith(RemoveSuperTableMutation.id, {+ unitId: 'u1',+ tableName: 'Orders',+ });++ controller.dispose();+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-range.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-range.controller.spec.tsnew file mode 100644index 0000000000..2f41016469--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-range.controller.spec.ts@@ -0,0 +1,76 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { FEATURE_TABLE_ID } from '../../const';+import { SheetTableRangeController } from '../sheet-table-range.controller';++describe('SheetTableRangeController', () => {+ it('should sync exclusive ranges on table add/range change/delete', () => {+ const tableRangeChanged$ = new Subject<any>();+ const tableAdd$ = new Subject<any>();+ const tableDelete$ = new Subject<any>();++ const tableManager = {+ tableRangeChanged$,+ tableAdd$,+ tableDelete$,+ };++ const exclusiveRangeService = {+ clearExclusiveRangesByGroupId: vi.fn(),+ addExclusiveRange: vi.fn(),+ };++ const controller = new SheetTableRangeController(tableManager as any, exclusiveRangeService as any);++ tableAdd$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 2 },+ });++ expect(exclusiveRangeService.addExclusiveRange).toHaveBeenCalledWith('u1', 's1', FEATURE_TABLE_ID, [{+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 2 },+ groupId: 't1',+ }]);++ tableRangeChanged$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ range: { startRow: 2, endRow: 4, startColumn: 1, endColumn: 3 },+ });++ expect(exclusiveRangeService.clearExclusiveRangesByGroupId).toHaveBeenCalledWith('u1', 's1', FEATURE_TABLE_ID, 't1');+ expect(exclusiveRangeService.addExclusiveRange).toHaveBeenLastCalledWith('u1', 's1', FEATURE_TABLE_ID, [{+ range: { startRow: 2, endRow: 4, startColumn: 1, endColumn: 3 },+ groupId: 't1',+ }]);++ tableDelete$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ });++ expect(exclusiveRangeService.clearExclusiveRangesByGroupId).toHaveBeenLastCalledWith('u1', 's1', FEATURE_TABLE_ID, 't1');++ controller.dispose();+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.tsnew file mode 100644index 0000000000..cf8d518bd6--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-ref-range.controller.spec.ts@@ -0,0 +1,78 @@+/**+ * 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 { InsertRowMutation } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { SheetTableRefRangeController } from '../sheet-table-ref-range.controller';++describe('SheetTableRefRangeController', () => {+ it('should return empty mutations for unsupported commands and update table range after row insertion', () => {+ let interceptCommandConfig: any;+ let commandExecutedListener: any;++ const table = {+ getId: () => 't1',+ getRange: () => ({ startRow: 5, endRow: 10, startColumn: 1, endColumn: 3 }),+ };++ const tableManager = {+ getTablesBySubunitId: vi.fn(() => [table]),+ updateTableRange: vi.fn(),+ };++ const controller = new SheetTableRefRangeController(+ {+ onCommandExecuted: vi.fn((listener: any) => {+ commandExecutedListener = listener;+ return { dispose: vi.fn() };+ }),+ } as any,+ {} as any,+ {} as any,+ {} as any,+ {+ interceptCommand: vi.fn((config: any) => {+ interceptCommandConfig = config;+ return { dispose: vi.fn() };+ }),+ } as any,+ tableManager as any,+ { t: () => 'Column' } as any+ );++ expect(interceptCommandConfig.getMutations({ id: 'unknown.command', params: {} })).toEqual({ redos: [], undos: [] });++ commandExecutedListener({+ id: InsertRowMutation.id,+ params: {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 2, startColumn: 0, endColumn: 10 },+ },+ });++ expect(tableManager.updateTableRange).toHaveBeenCalledWith('u1', 't1', {+ newRange: {+ startRow: 7,+ endRow: 12,+ startColumn: 1,+ endColumn: 3,+ },+ });++ controller.dispose();+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.tsnew file mode 100644index 0000000000..85918955df--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-theme.controller.spec.ts@@ -0,0 +1,132 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SheetsTableThemeController } from '../sheet-table-theme.controller';++describe('SheetsTableThemeController', () => {+ it('should initialize themes and react to table theme lifecycle events', () => {+ const tableAdd$ = new Subject<any>();+ const tableRangeChanged$ = new Subject<any>();+ const tableThemeChanged$ = new Subject<any>();+ const tableDelete$ = new Subject<any>();++ const table = {+ getTableStyleId: vi.fn(() => undefined),+ setTableStyleId: vi.fn(),+ getRange: vi.fn(() => ({ startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 })),+ };++ const tableManager = {+ tableAdd$,+ tableRangeChanged$,+ tableThemeChanged$,+ tableDelete$,+ getTable: vi.fn(() => table),+ };++ const sheetRangeThemeService = {+ registerRangeThemeStyle: vi.fn(),+ removeRangeThemeRule: vi.fn(),+ };+ const sheetRangeThemeModel = {+ registerDefaultRangeTheme: vi.fn(),+ };+ const configService = {+ getConfig: vi.fn(() => ({+ defaultThemeIndex: 1,+ userThemes: [{ name: 'user-theme', style: {} }],+ })),+ };++ const controller = new SheetsTableThemeController(+ tableManager as any,+ sheetRangeThemeService as any,+ sheetRangeThemeModel as any,+ configService as any+ );++ expect(sheetRangeThemeModel.registerDefaultRangeTheme).toHaveBeenCalledTimes(7);++ tableAdd$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ tableStyleId: '',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });++ expect(table.setTableStyleId).toHaveBeenCalledWith('table-default-0');+ expect(sheetRangeThemeService.registerRangeThemeStyle).toHaveBeenCalledWith('table-default-0', {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });++ tableRangeChanged$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ oldRange: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ range: { startRow: 1, endRow: 5, startColumn: 1, endColumn: 2 },+ });++ expect(sheetRangeThemeService.removeRangeThemeRule).toHaveBeenCalledWith('table-default-0', {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });+ expect(sheetRangeThemeService.registerRangeThemeStyle).toHaveBeenCalledWith('table-default-0', {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 5, startColumn: 1, endColumn: 2 },+ });++ tableThemeChanged$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ oldTheme: 'table-default-0',+ theme: 'table-default-1',+ });++ expect(sheetRangeThemeService.removeRangeThemeRule).toHaveBeenCalledWith('table-default-0', {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });+ expect(sheetRangeThemeService.registerRangeThemeStyle).toHaveBeenCalledWith('table-default-1', {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });++ tableDelete$.next({+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });++ expect(sheetRangeThemeService.removeRangeThemeRule).toHaveBeenCalledWith('table-default-0', {+ unitId: 'u1',+ subUnitId: 's1',+ range: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },+ });++ controller.dispose();+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/sheets-table.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheets-table.controller.spec.tsnew file mode 100644index 0000000000..b01e1bd47b--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/sheets-table.controller.spec.ts@@ -0,0 +1,106 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SheetsTableController } from '../sheets-table.controller';++describe('SheetsTableController', () => {+ it('should resolve containing table by range and inject header cell content', () => {+ const tableAdd$ = new Subject<any>();+ const tableRangeChanged$ = new Subject<any>();+ const tableDelete$ = new Subject<any>();++ const tableRange = { startRow: 2, endRow: 6, startColumn: 1, endColumn: 4 };+ const table = {+ getRange: () => tableRange,+ getColumnNameByIndex: (index: number) => ['Name', 'Qty', 'Price', 'Note'][index],+ };++ const tableManager = {+ tableAdd$,+ tableRangeChanged$,+ tableDelete$,+ getTable: vi.fn((_unitId: string, tableId: string) => (tableId === 't1' ? table : undefined)),+ getTablesBySubunitId: vi.fn(() => []),+ toJSON: vi.fn(() => ({})),+ fromJSON: vi.fn(),+ deleteUnitId: vi.fn(),+ };++ let cellContentHandler: any;+ const sheetInterceptorService = {+ intercept: vi.fn((_point: any, config: any) => {+ cellContentHandler = config.handler;+ return { dispose: vi.fn() };+ }),+ interceptCommand: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const resourceManagerService = {+ registerPluginResource: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const controller = new SheetsTableController(+ {+ getCurrentUnitOfType: vi.fn(() => null),+ } as any,+ sheetInterceptorService as any,+ tableManager as any,+ resourceManagerService as any+ );++ tableAdd$.next({+ unitId: 'u1',+ subUnitId: 's1',+ tableId: 't1',+ range: tableRange,+ });++ expect(+ controller.getContainerTableWithRange('u1', 's1', { startRow: 3, endRow: 4, startColumn: 2, endColumn: 3 })+ ).toBe(table);++ expect(+ controller.getContainerTableWithRange('u1', 's1', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 })+ ).toBeUndefined();++ const next = vi.fn((cell) => cell);+ const result = cellContentHandler(undefined, {+ row: 2,+ col: 2,+ unitId: 'u1',+ subUnitId: 's1',+ rawData: { s: 1 },+ }, next);++ expect(next).toHaveBeenCalledWith({ s: 1, v: 'Qty' });+ expect(result).toEqual({ s: 1, v: 'Qty' });++ const nextNonHeader = vi.fn((cell) => cell);+ cellContentHandler(undefined, {+ row: 3,+ col: 2,+ unitId: 'u1',+ subUnitId: 's1',+ rawData: { s: 1 },+ }, nextNonHeader);++ expect(nextNonHeader).toHaveBeenCalledWith(undefined);++ controller.dispose();+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.tsnew file mode 100644index 0000000000..8d1689f883--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/table-filter.controller.spec.ts@@ -0,0 +1,102 @@+/**+ * 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 { BehaviorSubject, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { TableFilterController } from '../table-filter.controller';++describe('TableFilterController', () => {+ it('should merge filtered rows from table filter events and initialize intercept behavior', () => {+ const tableFilterChanged$ = new Subject<any>();+ const tableInitStatus$ = new BehaviorSubject(false);++ const mainFilter = {+ doFilter: vi.fn(),+ getFilterOutRows: () => new Set([4]),+ };+ const mainTable = {+ getTableFilters: () => mainFilter,+ getTableFilterRange: () => ({ startRow: 1, endRow: 10, startColumn: 1, endColumn: 2 }),+ };++ const extraTable = {+ getTableFilters: () => ({+ getFilterOutRows: () => new Set([8]),+ }),+ };++ const tableManager = {+ tableFilterChanged$,+ tableInitStatus$,+ getTable: vi.fn(() => mainTable),+ getTablesBySubunitId: vi.fn(() => [mainTable, extraTable]),+ };++ let rowFilteredHandler: any;+ const sheetInterceptorService = {+ intercept: vi.fn((_point: any, config: any) => {+ rowFilteredHandler = config.handler;+ return { dispose: vi.fn() };+ }),+ };++ const activeSheet$ = new Subject<any>();+ const workbook = {+ getUnitId: () => 'u1',+ getActiveSheet: () => ({ getSheetId: () => 's1' }),+ activeSheet$,+ getSheetBySheetId: vi.fn(() => ({ id: 'sheet1' })),+ };++ const workbookType$ = new Subject<any>();+ const univerInstanceService = {+ getCurrentTypeOfUnit$: vi.fn(() => workbookType$),+ getCurrentUnitOfType: vi.fn(() => workbook),+ getUnit: vi.fn(() => workbook),+ };++ const zebraCrossingCacheController = {+ updateZebraCrossingCache: vi.fn(),+ };++ const controller = new TableFilterController(+ tableManager as any,+ sheetInterceptorService as any,+ univerInstanceService as any,+ zebraCrossingCacheController as any+ );++ controller.tableFilteredOutRows = new Set([10]);+ expect(rowFilteredHandler(false, { row: 10 }, vi.fn(() => false))).toBe(true);+ expect(rowFilteredHandler(false, { row: 11 }, vi.fn(() => false))).toBe(false);++ tableFilterChanged$.next({ unitId: 'u1', subUnitId: 's1', tableId: 't1' });++ expect(mainFilter.doFilter).toHaveBeenCalledWith({ id: 'sheet1' }, { startRow: 1, endRow: 10, startColumn: 1, endColumn: 2 });+ expect(controller.tableFilteredOutRows.has(4)).toBe(true);+ expect(controller.tableFilteredOutRows.has(8)).toBe(true);+ expect(zebraCrossingCacheController.updateZebraCrossingCache).toHaveBeenCalledWith('u1', 's1');++ tableInitStatus$.next(true);+ workbookType$.next(workbook);+ activeSheet$.next({ getSheetId: () => 's1' });++ expect(controller.tableFilteredOutRows.has(4)).toBe(true);+ expect(controller.tableFilteredOutRows.has(8)).toBe(true);++ controller.dispose();+ });+});diff --git a/packages/sheets-table/src/controllers/__tests__/table-theme.factory.spec.ts b/packages/sheets-table/src/controllers/__tests__/table-theme.factory.spec.tsnew file mode 100644index 0000000000..6c27352e33--- /dev/null+++ b/packages/sheets-table/src/controllers/__tests__/table-theme.factory.spec.ts@@ -0,0 +1,59 @@+/**+ * 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 { tableDefaultBorderStyle } from '../config.schema';+import { customEmptyThemeWithBorderStyle, processStyleWithBorderStyle, tableThemeConfig } from '../table-theme.factory';++describe('table-theme.factory', () => {+ it('should fill border style for specific theme keys when border is missing', () => {+ expect(processStyleWithBorderStyle('headerRowStyle', {} as any)).toEqual({+ bd: { t: tableDefaultBorderStyle },+ });++ expect(processStyleWithBorderStyle('lastRowStyle', {} as any)).toEqual({+ bd: { b: tableDefaultBorderStyle },+ });++ expect(processStyleWithBorderStyle('lastColumnStyle', {} as any)).toEqual({+ bd: { r: tableDefaultBorderStyle },+ });++ expect(processStyleWithBorderStyle('headerColumnStyle', {} as any)).toEqual({+ bd: { l: tableDefaultBorderStyle },+ });+ });++ it('should not override an existing border definition', () => {+ const style = { bd: { t: { s: 0 } }, bg: { rgb: '#fff' } } as any;+ expect(processStyleWithBorderStyle('headerRowStyle', style)).toBe(style);+ });++ it('should expose the default empty theme with four-side border', () => {+ expect(customEmptyThemeWithBorderStyle.headerRowStyle?.bd?.t).toEqual(tableDefaultBorderStyle);+ expect(customEmptyThemeWithBorderStyle.headerColumnStyle?.bd?.l).toEqual(tableDefaultBorderStyle);+ expect(customEmptyThemeWithBorderStyle.lastColumnStyle?.bd?.r).toEqual(tableDefaultBorderStyle);+ expect(customEmptyThemeWithBorderStyle.lastRowStyle?.bd?.b).toEqual(tableDefaultBorderStyle);+ });++ it('should generate built-in table themes with stable naming and border defaults', () => {+ expect(tableThemeConfig).toHaveLength(6);+ expect(tableThemeConfig[0].name).toBe('table-default-0');+ expect(tableThemeConfig[5].name).toBe('table-default-5');+ expect(tableThemeConfig[0].style.headerRowStyle?.bd?.t).toEqual(tableDefaultBorderStyle);+ expect(tableThemeConfig[0].style.lastColumnStyle?.bd?.r).toEqual(tableDefaultBorderStyle);+ });+});diff --git a/packages/sheets-table/src/services/__tests__/table-service.spec.ts b/packages/sheets-table/src/services/__tests__/table-service.spec.tsnew file mode 100644index 0000000000..ffb722ca83--- /dev/null+++ b/packages/sheets-table/src/services/__tests__/table-service.spec.ts@@ -0,0 +1,87 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import * as conditionUtil from '../../model/filter-util/condition';+import { TableConditionTypeEnum } from '../../types/enum';+import { SheetTableService } from '../table-service';++describe('SheetTableService', () => {+ it('should proxy table CRUD and metadata calls to table manager', () => {+ const setMeta = vi.fn();+ const setColumnMeta = vi.fn();+ const column = {+ getMeta: vi.fn(() => ({ key: 'column-meta' })),+ setMeta: setColumnMeta,+ };+ const table = {+ getTableInfo: vi.fn(() => ({ id: 'table-1', name: 'Table 1' })),+ getTableMeta: vi.fn(() => ({ key: 'table-meta' })),+ setTableMeta: setMeta,+ getTableColumnByIndex: vi.fn(() => column),+ };++ const tableManager = {+ getTable: vi.fn(() => table),+ getTableList: vi.fn(() => [{ id: 'table-1' }]),+ addTable: vi.fn(() => 'table-1'),+ deleteTable: vi.fn(),+ addFilter: vi.fn(),+ };++ const service = new SheetTableService(tableManager as any);++ expect(service.getTableInfo('u1', 'table-1')).toEqual({+ unitId: 'u1',+ id: 'table-1',+ name: 'Table 1',+ });+ expect(service.getTableList('u1')).toEqual([{ id: 'table-1' }]);+ expect(service.addTable('u1', 's1', 'Table 1', { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } as any)).toBe('table-1');++ service.deleteTable('u1', 's1', 'table-1');+ expect(tableManager.deleteTable).toHaveBeenCalledWith('u1', 'table-1');++ expect(service.getTableMeta('u1', 'table-1')).toEqual({ key: 'table-meta' });+ service.setTableMeta('u1', 'table-1', { updated: true } as any);+ expect(setMeta).toHaveBeenCalledWith({ updated: true });++ expect(service.getTableColumnMeta('u1', 'table-1', 0)).toEqual({ key: 'column-meta' });+ service.selTableColumnMeta('u1', 'table-1', 0, { updated: true } as any);+ expect(setColumnMeta).toHaveBeenCalledWith({ updated: true });++ service.addFilter('u1', 'table-1', 1, { filterType: 'manual', values: ['A'] } as any);+ expect(tableManager.addFilter).toHaveBeenCalledWith('u1', 'table-1', 1, { filterType: 'manual', values: ['A'] });+ });++ it('should return undefined when table does not exist', () => {+ const service = new SheetTableService({ getTable: () => undefined } as any);+ expect(service.getTableInfo('u1', 'missing')).toBeUndefined();+ expect(service.getTableMeta('u1', 'missing')).toBeUndefined();+ expect(service.getTableColumnMeta('u1', 'missing', 0)).toBeUndefined();+ });++ it('should delegate cell value extraction by condition type', () => {+ const spy = vi.spyOn(conditionUtil, 'getCellValueWithConditionType').mockReturnValue('ok' as any);+ const service = new SheetTableService({} as any);++ const worksheet = { id: 'sheet' } as any;+ const value = service.getCellValueWithConditionType(worksheet, 2, 3, TableConditionTypeEnum.Number);++ expect(value).toBe('ok');+ expect(spy).toHaveBeenCalledWith(worksheet, 2, 3, TableConditionTypeEnum.Number);+ });+});diff --git a/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.tsnew file mode 100644index 0000000000..41226b3f82--- /dev/null+++ b/packages/sheets-ui/src/commands/commands/__tests__/command-behavior.spec.ts@@ -0,0 +1,597 @@+/**+ * 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 {+ EDITOR_ACTIVATED,+ ICommandService,+ IConfigService,+ IConfirmService,+ IContextService,+ IUndoRedoService,+ IUniverInstanceService,+ LocaleService,+ ThemeService,+} from '@univerjs/core';+import {+ SetInlineFormatBoldCommand,+ SetInlineFormatFontFamilyCommand,+ SetInlineFormatFontSizeCommand,+ SetInlineFormatItalicCommand,+ SetInlineFormatStrikethroughCommand,+ SetInlineFormatSubscriptCommand,+ SetInlineFormatSuperscriptCommand,+ SetInlineFormatTextColorCommand,+ SetInlineFormatUnderlineCommand,+} from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';+import {+ AddRangeProtectionMutation,+ AddWorksheetProtectionCommand,+ DeleteRangeProtectionMutation,+ DeleteWorksheetProtectionCommand,+ RangeProtectionRuleModel,+ RemoveSheetCommand,+ SetBoldCommand,+ SetFontFamilyCommand,+ SetFontSizeCommand,+ SetItalicCommand,+ SetStrikeThroughCommand,+ SetTextColorCommand,+ SetUnderlineCommand,+ SheetsSelectionsService,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { SHEET_VIEW_KEY, SHEET_ZOOM_RANGE } from '../../../common/keys';+import { AutoWidthController } from '../../../controllers/auto-width.controller';+import * as menuUtils from '../../../controllers/menu/utils';+import { IEditorBridgeService } from '../../../services/editor-bridge.service';+import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';+import { SetScrollOperation } from '../../operations/scroll.operation';+import { SetZoomRatioOperation } from '../../operations/set-zoom-ratio.operation';+import { SheetPermissionOpenPanelOperation } from '../../operations/sheet-permission-open-panel.operation';+import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand } from '../headersize-changed.command';+import {+ ResetRangeTextColorCommand,+ SetRangeBoldCommand,+ SetRangeFontDecreaseCommand,+ SetRangeFontFamilyCommand,+ SetRangeFontIncreaseCommand,+ SetRangeFontSizeCommand,+ SetRangeItalicCommand,+ SetRangeStrickThroughCommand,+ SetRangeSubscriptCommand,+ SetRangeSuperscriptCommand,+ SetRangeTextColorCommand,+ SetRangeUnderlineCommand,+} from '../inline-format.command';+import {+ AddRangeProtectionFromContextMenuCommand,+ AddRangeProtectionFromSheetBarCommand,+ AddRangeProtectionFromToolbarCommand,+ DeleteRangeProtectionFromContextMenuCommand,+ SetRangeProtectionFromContextMenuCommand,+ ViewSheetPermissionFromContextMenuCommand,+ ViewSheetPermissionFromSheetBarCommand,+} from '../range-protection.command';+import { RemoveSheetConfirmCommand } from '../remove-sheet-confirm.command';+import { ResetScrollCommand, ScrollCommand, ScrollToCellCommand, SetScrollRelativeCommand } from '../set-scroll.command';+import { SetWorksheetColAutoWidthCommand } from '../set-worksheet-auto-col-width.command';+import { ChangeZoomRatioCommand, SetZoomRatioCommand } from '../set-zoom-ratio.command';+import { ShowMenuListCommand } from '../unhide.command';+import {+ ChangeSheetProtectionFromSheetBarCommand,+ DeleteWorksheetProtectionFormSheetBarCommand,+} from '../worksheet-protection.command';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ has(token: unknown) {+ return map.has(token);+ },+ } as any;+}++describe('sheets-ui command behaviors', () => {+ it('routes inline-format commands according to editor focus', async () => {+ const executeCommand = vi.fn(async () => true);+ const getContextValue = vi.fn((key: unknown) => key === EDITOR_ACTIVATED);+ const commandService = { executeCommand };+ const contextService = { getContextValue };+ const baseAccessor = createAccessor([+ [ICommandService, commandService],+ [IContextService, contextService],+ [ThemeService, { getColorFromTheme: vi.fn(() => '#111111') }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getActiveSheet: () => ({ getComposedCellStyle: () => ({ fs: 9 }) }) }) }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ primary: { startRow: 0, startColumn: 0 } }) }],+ ]);++ await SetRangeBoldCommand.handler(baseAccessor, undefined as any);+ await SetRangeItalicCommand.handler(baseAccessor, undefined as any);+ await SetRangeUnderlineCommand.handler(baseAccessor, undefined as any);+ await SetRangeStrickThroughCommand.handler(baseAccessor, undefined as any);+ await SetRangeSubscriptCommand.handler(baseAccessor, undefined as any);+ await SetRangeSuperscriptCommand.handler(baseAccessor, undefined as any);+ await SetRangeFontSizeCommand.handler(baseAccessor, { value: 10 } as any);+ await SetRangeFontFamilyCommand.handler(baseAccessor, { value: 'Arial' } as any);+ await SetRangeTextColorCommand.handler(baseAccessor, { value: '#fff' } as any);+ await ResetRangeTextColorCommand.handler(baseAccessor, undefined as any);++ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatBoldCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatItalicCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatUnderlineCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatStrikethroughCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatSubscriptCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatSuperscriptCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatFontSizeCommand.id, { value: 10 });+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatFontFamilyCommand.id, { value: 'Arial' });+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatTextColorCommand.id, { value: '#fff' });+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatTextColorCommand.id, { value: null });+ });++ it('routes inline-format commands to sheet commands in non-editor mode', async () => {+ const executeCommand = vi.fn(async () => true);+ const commandService = { executeCommand };+ const contextService = { getContextValue: vi.fn(() => false) };+ const baseAccessor = createAccessor([+ [ICommandService, commandService],+ [IContextService, contextService],+ [ThemeService, { getColorFromTheme: vi.fn(() => '#000000') }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getActiveSheet: () => ({ getComposedCellStyle: () => ({ fs: 12 }) }) }) }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ primary: { startRow: 0, startColumn: 0 } }) }],+ ]);++ await SetRangeBoldCommand.handler(baseAccessor, undefined as any);+ await SetRangeItalicCommand.handler(baseAccessor, undefined as any);+ await SetRangeUnderlineCommand.handler(baseAccessor, undefined as any);+ await SetRangeStrickThroughCommand.handler(baseAccessor, undefined as any);+ await SetRangeFontSizeCommand.handler(baseAccessor, { value: 14 } as any);+ await SetRangeFontFamilyCommand.handler(baseAccessor, { value: 'Times New Roman' } as any);+ await SetRangeTextColorCommand.handler(baseAccessor, { value: '#123456' } as any);+ await ResetRangeTextColorCommand.handler(baseAccessor, undefined as any);++ expect(executeCommand).toHaveBeenCalledWith(SetBoldCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetItalicCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetUnderlineCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetStrikeThroughCommand.id);+ expect(executeCommand).toHaveBeenCalledWith(SetFontSizeCommand.id, { value: 14 });+ expect(executeCommand).toHaveBeenCalledWith(SetFontFamilyCommand.id, { value: 'Times New Roman' });+ expect(executeCommand).toHaveBeenCalledWith(SetTextColorCommand.id, { value: '#123456' });+ expect(executeCommand).toHaveBeenCalledWith(SetTextColorCommand.id, { value: '#000000' });+ });++ it('returns false for subscript/superscript when not in editor mode', async () => {+ const accessor = createAccessor([+ [ICommandService, { executeCommand: vi.fn(async () => true) }],+ [IContextService, { getContextValue: vi.fn(() => false) }],+ ]);++ expect(await SetRangeSubscriptCommand.handler(accessor, undefined as any)).toBe(false);+ expect(await SetRangeSuperscriptCommand.handler(accessor, undefined as any)).toBe(false);+ });++ it('handles font increase/decrease bounds and empty selection', async () => {+ const executeCommand = vi.fn(async () => true);+ const getFontStyleAtCursor = vi.spyOn(menuUtils, 'getFontStyleAtCursor');++ getFontStyleAtCursor.mockReturnValueOnce({ ts: { fs: 400 } } as any);+ const increaseInEditorAccessor = createAccessor([+ [ICommandService, { executeCommand }],+ [IContextService, { getContextValue: vi.fn((key: unknown) => key === EDITOR_ACTIVATED) }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getActiveSheet: () => ({ getComposedCellStyle: () => ({ fs: 11 }) }) }) }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ primary: { startRow: 1, startColumn: 1 } }) }],+ ]);++ expect(await SetRangeFontIncreaseCommand.handler(increaseInEditorAccessor, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetInlineFormatFontSizeCommand.id, { value: 400 });++ const decreaseInCellAccessor = createAccessor([+ [ICommandService, { executeCommand }],+ [IContextService, { getContextValue: vi.fn(() => false) }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getActiveSheet: () => ({ getComposedCellStyle: () => ({ fs: 6 }) }) }) }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ primary: { startRow: 2, startColumn: 2 } }) }],+ ]);++ expect(await SetRangeFontDecreaseCommand.handler(decreaseInCellAccessor, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetFontSizeCommand.id, { value: 6 });++ const noSelectionAccessor = createAccessor([+ [ICommandService, { executeCommand }],+ [IContextService, { getContextValue: vi.fn(() => false) }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getActiveSheet: () => ({ getComposedCellStyle: () => ({ fs: 10 }) }) }) }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => null }],+ ]);+ expect(await SetRangeFontIncreaseCommand.handler(noSelectionAccessor, undefined as any)).toBe(false);+ });++ it('updates header sizes and custom header components', async () => {+ const rowHeader = { setCustomHeader: vi.fn() };+ const colHeader = { setCustomHeader: vi.fn() };+ const setRowHeaderSize = vi.fn();+ const setColumnHeaderSize = vi.fn();+ const render = {+ with: vi.fn(() => ({ setRowHeaderSize, setColumnHeaderSize })),+ components: new Map([+ [SHEET_VIEW_KEY.ROW, rowHeader],+ [SHEET_VIEW_KEY.COLUMN, colHeader],+ ]),+ };+ const renderManager = { getRenderById: vi.fn(() => render) };+ const accessor = createAccessor([[IRenderManagerService, renderManager]]);++ expect(await SetRowHeaderWidthCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', size: 32 })).toBe(true);+ expect(await SetColumnHeaderHeightCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', size: 26 })).toBe(true);+ expect(setRowHeaderSize).toHaveBeenCalledWith(render, 's1', 32);+ expect(setColumnHeaderSize).toHaveBeenCalledWith(render, 's1', 26);+ expect(rowHeader.setCustomHeader).toHaveBeenCalledWith({ headerStyle: { size: 32 } }, 's1');+ expect(colHeader.setCustomHeader).toHaveBeenCalledWith({ headerStyle: { size: 26 } }, 's1');+ });++ it('guards header-size commands when params or render manager are missing', async () => {+ const accessor = createAccessor([[IRenderManagerService, null]]);+ expect(await SetRowHeaderWidthCommand.handler(accessor, undefined as any)).toBe(false);+ expect(await SetColumnHeaderHeightCommand.handler(accessor, undefined as any)).toBe(false);+ });++ it('handles scroll commands with target and fallback branches', async () => {+ const executeCommand = vi.fn(async () => true);+ const syncExecuteCommand = vi.fn(() => true);+ const worksheet = { getSheetId: () => 'sheet-1', getConfig: () => ({ freeze: { xSplit: 2, ySplit: 1 } }) };+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ };+ const renderManager = {+ getRenderById: vi.fn(() => ({+ with: vi.fn(() => ({+ getCurrentScrollState: () => ({+ sheetViewStartRow: 4,+ sheetViewStartColumn: 5,+ offsetX: 12,+ offsetY: 30,+ }),+ })),+ })),+ };+ const univerInstanceService = {+ getCurrentUnitOfType: () => workbook,+ getCurrentUnitForType: () => workbook,+ };++ const accessor = createAccessor([+ [ICommandService, { executeCommand, syncExecuteCommand }],+ [IUniverInstanceService, univerInstanceService],+ [IRenderManagerService, renderManager],+ ]);++ expect(await SetScrollRelativeCommand.handler(accessor, { offsetX: -2, offsetY: 5 })).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetScrollOperation.id, expect.objectContaining({+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ offsetX: 10,+ offsetY: 35,+ sheetViewStartRow: 4,+ sheetViewStartColumn: 5,+ }));++ expect(ScrollCommand.handler(accessor, { offsetX: 66 } as any)).toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith(SetScrollOperation.id, expect.objectContaining({+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ sheetViewStartRow: 4,+ sheetViewStartColumn: 5,+ offsetX: 66,+ offsetY: 30,+ }));++ const scrollToRange = vi.fn(() => true);+ const scrollAccessor = createAccessor([+ [IUniverInstanceService, { getCurrentUnitForType: () => ({ getUnitId: () => 'unit-1' }) }],+ [IRenderManagerService, { getRenderById: () => ({ with: () => ({ scrollToRange }) }) }],+ ]);+ expect(ScrollToCellCommand.handler(scrollAccessor, { range: { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 } as any })).toBe(true);+ expect(scrollToRange).toHaveBeenCalledWith({ startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 }, undefined, undefined);++ expect(await ResetScrollCommand.handler(accessor, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetScrollOperation.id, {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ sheetViewStartRow: 0,+ sheetViewStartColumn: 0,+ });+ });++ it('guards scroll commands when params or targets are missing', async () => {+ const accessor = createAccessor([+ [ICommandService, { executeCommand: vi.fn(), syncExecuteCommand: vi.fn() }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => null, getCurrentUnitForType: () => null }],+ [IRenderManagerService, { getRenderById: vi.fn() }],+ ]);++ expect(await SetScrollRelativeCommand.handler(accessor, { offsetX: 1, offsetY: 1 })).toBe(false);+ expect(ScrollCommand.handler(accessor, undefined as any)).toBe(false);+ expect(ScrollCommand.handler(accessor, { offsetY: 10 } as any)).toBe(false);+ expect(await ResetScrollCommand.handler(accessor, undefined as any)).toBe(false);+ });++ it('handles zoom ratio commands with clamp and editor-visible guards', async () => {+ const executeCommand = vi.fn(() => true);+ const worksheet = {+ getSheetId: () => 'sheet-1',+ getConfig: () => ({ zoomRatio: 4 }),+ };+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ };+ const accessor = createAccessor([+ [IUniverInstanceService, { getCurrentUnitOfType: () => workbook }],+ [ICommandService, { executeCommand }],+ [IEditorBridgeService, { isVisible: () => ({ visible: false, unitId: 'other' }) }],+ ]);++ expect(ChangeZoomRatioCommand.handler(accessor, { delta: 0.5 })).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetZoomRatioOperation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ zoomRatio: SHEET_ZOOM_RANGE[1] / 100,+ });++ expect(SetZoomRatioCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', zoomRatio: 1.25 })).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SetZoomRatioOperation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ zoomRatio: 1.25,+ });++ const hiddenByEditorAccessor = createAccessor([+ [IUniverInstanceService, { getCurrentUnitOfType: () => workbook }],+ [ICommandService, { executeCommand }],+ [IEditorBridgeService, { isVisible: () => ({ visible: true, unitId: 'unit-1' }) }],+ ]);+ expect(ChangeZoomRatioCommand.handler(hiddenByEditorAccessor, { delta: -0.1 })).toBe(false);+ expect(SetZoomRatioCommand.handler(hiddenByEditorAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1', zoomRatio: 1 })).toBe(false);+ });++ it('guards zoom commands for invalid params or missing targets', () => {+ const accessor = createAccessor([+ [IUniverInstanceService, { getCurrentUnitOfType: () => null }],+ [ICommandService, { executeCommand: vi.fn() }],+ [IEditorBridgeService, { isVisible: () => ({ visible: false, unitId: 'none' }) }],+ ]);+ expect(ChangeZoomRatioCommand.handler(accessor, undefined as any)).toBe(false);+ expect(ChangeZoomRatioCommand.handler(accessor, { delta: 0.1 })).toBe(false);+ expect(SetZoomRatioCommand.handler(accessor, undefined as any)).toBe(false);+ });++ it('executes auto-width command with undo/redo and guards empty ranges', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const pushUndoRedo = vi.fn();+ const accessor = createAccessor([+ [ICommandService, { syncExecuteCommand }],+ [IUndoRedoService, { pushUndoRedo }],+ [SheetsSelectionsService, {+ getCurrentSelections: () => [{ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } }],+ }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getUnitId: () => 'unit-1', getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }) }) }],+ [AutoWidthController, {+ getUndoRedoParamsOfColWidth: vi.fn(() => ({+ redos: [{ id: 'redo-1', params: { a: 1 } }],+ undos: [{ id: 'undo-1', params: { b: 2 } }],+ })),+ }],+ ]);++ expect(SetWorksheetColAutoWidthCommand.handler(accessor, undefined as any)).toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith('redo-1', { a: 1 }, undefined);+ expect(pushUndoRedo).toHaveBeenCalledWith({+ unitID: 'unit-1',+ undoMutations: [{ id: 'undo-1', params: { b: 2 } }],+ redoMutations: [{ id: 'redo-1', params: { a: 1 } }],+ });++ const emptySelectionAccessor = createAccessor([+ [ICommandService, { syncExecuteCommand: vi.fn(() => true) }],+ [IUndoRedoService, { pushUndoRedo: vi.fn() }],+ [SheetsSelectionsService, { getCurrentSelections: () => [] }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => ({ getUnitId: () => 'unit-1', getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }) }) }],+ [AutoWidthController, { getUndoRedoParamsOfColWidth: vi.fn(() => ({ redos: [], undos: [] })) }],+ ]);+ expect(SetWorksheetColAutoWidthCommand.handler(emptySelectionAccessor, undefined as any)).toBe(false);+ });++ it('handles remove-sheet confirmation for both confirm and cancel', async () => {+ const executeCommand = vi.fn(async () => true);+ const confirm = vi.fn()+ .mockResolvedValueOnce(false)+ .mockResolvedValueOnce(true);+ const worksheet = {+ getCellMatrix: () => ({+ forEach: (fn: (...args: unknown[]) => void) => {+ fn();+ fn();+ },+ }),+ getSheetId: () => 'sheet-1',+ };+ const workbook = {+ getUnitId: () => 'unit-1',+ getSheetBySheetId: (subUnitId: string) => (subUnitId === 'sheet-1' ? worksheet : null),+ };++ const accessor = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, { t: (key: string) => key }],+ [IConfigService, { getConfig: () => ({ largeSheetOperation: { largeSheetCellCountThreshold: 1 } }) }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => workbook }],+ ]);++ expect(await RemoveSheetConfirmCommand.handler(accessor, { subUnitId: 'sheet-1' } as any)).toBe(false);+ expect(await RemoveSheetConfirmCommand.handler(accessor, { subUnitId: 'sheet-1' } as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(RemoveSheetCommand.id, { subUnitId: 'sheet-1' });+ });++ it('guards remove-sheet command when target sheet is missing', async () => {+ const accessor = createAccessor([+ [IConfirmService, { confirm: vi.fn() }],+ [ICommandService, { executeCommand: vi.fn() }],+ [LocaleService, { t: (key: string) => key }],+ [IConfigService, { getConfig: () => ({}) }],+ [IUniverInstanceService, { getCurrentUnitOfType: () => null }],+ ]);+ expect(await RemoveSheetConfirmCommand.handler(accessor, { subUnitId: 'sheet-1' } as any)).toBe(false);+ });++ it('handles worksheet protection commands', async () => {+ const executeCommand = vi.fn()+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true);+ const pushUndoRedo = vi.fn();+ const worksheet = { getSheetId: () => 'sheet-1' };+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ };+ const accessor = createAccessor([+ [ICommandService, { executeCommand }],+ [IUndoRedoService, { pushUndoRedo }],+ [WorksheetProtectionRuleModel, { getRule: () => ({ permissionId: 'perm-1' }) }],+ [IUniverInstanceService, { getCurrentUnitForType: () => workbook }],+ ]);++ expect(await DeleteWorksheetProtectionFormSheetBarCommand.handler(accessor, { ok: true } as any)).toBe(true);+ expect(pushUndoRedo).toHaveBeenCalledWith({+ unitID: 'unit-1',+ redoMutations: [{ id: DeleteWorksheetProtectionCommand.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1' } }],+ undoMutations: [{ id: AddWorksheetProtectionCommand.id, params: { unitId: 'unit-1', rule: { permissionId: 'perm-1' } } }],+ });++ expect(await ChangeSheetProtectionFromSheetBarCommand.handler(accessor, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith('sheet-permission.operation.openDialog');++ const noWorksheetAccessor = createAccessor([+ [ICommandService, { executeCommand: vi.fn() }],+ [IUndoRedoService, { pushUndoRedo: vi.fn() }],+ [WorksheetProtectionRuleModel, { getRule: vi.fn() }],+ [IUniverInstanceService, { getCurrentUnitForType: () => ({ getUnitId: () => 'unit-1', getActiveSheet: () => null }) }],+ ]);+ expect(await DeleteWorksheetProtectionFormSheetBarCommand.handler(noWorksheetAccessor, { ok: true } as any)).toBe(false);+ expect(await DeleteWorksheetProtectionFormSheetBarCommand.handler(noWorksheetAccessor, undefined as any)).toBe(false);+ });++ it('opens and deletes range protection from toolbar/context/sheet-bar', async () => {+ const executeCommand = vi.fn(async () => true);+ const accessor = createAccessor([[ICommandService, { executeCommand }]]);++ expect(await AddRangeProtectionFromToolbarCommand.handler(accessor, undefined as any)).toBe(true);+ expect(await AddRangeProtectionFromContextMenuCommand.handler(accessor, undefined as any)).toBe(true);+ expect(await ViewSheetPermissionFromContextMenuCommand.handler(accessor, undefined as any)).toBe(true);+ expect(await AddRangeProtectionFromSheetBarCommand.handler(accessor, undefined as any)).toBe(true);+ expect(await ViewSheetPermissionFromSheetBarCommand.handler(accessor, undefined as any)).toBe(true);++ expect(executeCommand).toHaveBeenCalledWith(SheetPermissionOpenPanelOperation.id, { showDetail: true });+ expect(executeCommand).toHaveBeenCalledWith(SheetPermissionOpenPanelOperation.id, { showDetail: false });+ expect(executeCommand).toHaveBeenCalledWith(SheetPermissionOpenPanelOperation.id, { fromSheetBar: true, showDetail: true });+ });++ it('handles delete/set range protection command branches', async () => {+ const executeCommand = vi.fn()+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce(true);+ const pushUndoRedo = vi.fn();+ const worksheet = { getSheetId: () => 'sheet-1' };+ const workbook = { getUnitId: () => 'unit-1', getActiveSheet: () => worksheet };+ const overlapRule = {+ id: 'rule-1',+ permissionId: 'perm-1',+ ranges: [{ startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 }],+ };++ const accessorWithWorksheetRule = createAccessor([+ [ICommandService, { executeCommand }],+ [IUniverInstanceService, { getCurrentUnitForType: () => workbook }],+ [IUndoRedoService, { pushUndoRedo }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }) }],+ [WorksheetProtectionRuleModel, { getRule: () => ({ permissionId: 'sheet-perm' }) }],+ [RangeProtectionRuleModel, { getSubunitRuleList: () => [overlapRule] }],+ ]);++ expect(await DeleteRangeProtectionFromContextMenuCommand.handler(accessorWithWorksheetRule, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(DeleteWorksheetProtectionCommand.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ rule: { permissionId: 'sheet-perm' },+ });++ expect(await SetRangeProtectionFromContextMenuCommand.handler(accessorWithWorksheetRule, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(SheetPermissionOpenPanelOperation.id, expect.objectContaining({+ showDetail: true,+ rule: expect.objectContaining({ unitId: 'unit-1', subUnitId: 'sheet-1' }),+ }));++ const accessorWithRangeRule = createAccessor([+ [ICommandService, { executeCommand }],+ [IUniverInstanceService, { getCurrentUnitForType: () => workbook }],+ [IUndoRedoService, { pushUndoRedo }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }) }],+ [WorksheetProtectionRuleModel, { getRule: () => null }],+ [RangeProtectionRuleModel, { getSubunitRuleList: () => [overlapRule] }],+ ]);++ expect(await DeleteRangeProtectionFromContextMenuCommand.handler(accessorWithRangeRule, undefined as any)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(DeleteRangeProtectionMutation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ruleIds: ['rule-1'],+ });+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({+ unitID: 'unit-1',+ redoMutations: [{ id: DeleteRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: ['rule-1'] } }],+ undoMutations: [{ id: AddRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [overlapRule] } }],+ }));++ expect(await SetRangeProtectionFromContextMenuCommand.handler(accessorWithRangeRule, undefined as any)).toBe(true);++ const accessorNoSelection = createAccessor([+ [ICommandService, { executeCommand }],+ [IUniverInstanceService, { getCurrentUnitForType: () => workbook }],+ [IUndoRedoService, { pushUndoRedo }],+ [SheetsSelectionsService, { getCurrentLastSelection: () => null }],+ [WorksheetProtectionRuleModel, { getRule: () => null }],+ [RangeProtectionRuleModel, { getSubunitRuleList: () => [] }],+ ]);++ expect(await DeleteRangeProtectionFromContextMenuCommand.handler(accessorNoSelection, undefined as any)).toBe(false);+ expect(await SetRangeProtectionFromContextMenuCommand.handler(accessorNoSelection, undefined as any)).toBe(false);+ });++ it('handles show-menu-list command', async () => {+ const triggerSheetBarMenu = vi.fn();+ const accessor = createAccessor([[ISheetBarService, { triggerSheetBarMenu }]]);+ expect(await ShowMenuListCommand.handler(accessor)).toBe(true);+ expect(triggerSheetBarMenu).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.tsnew file mode 100644index 0000000000..e28af68f80--- /dev/null+++ b/packages/sheets-ui/src/commands/commands/__tests__/confirm-and-clipboard.command.spec.ts@@ -0,0 +1,314 @@+/**+ * 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 { IRange } from '@univerjs/core';+import {+ ICommandService,+ IConfirmService,+ IUniverInstanceService,+ LocaleService,+} from '@univerjs/core';+import {+ DeleteRangeMoveLeftCommand,+ DeleteRangeMoveUpCommand,+ InsertRangeMoveDownCommand,+ InsertRangeMoveRightCommand,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import * as sheets from '@univerjs/sheets';+import { IClipboardInterfaceService } from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../../../services/clipboard/clipboard.service';+import {+ SheetCopyCommand,+ SheetCutCommand,+ SheetOptionalPasteCommand,+ SheetPasteBesidesBorderCommand,+ SheetPasteColWidthCommand,+ SheetPasteCommand,+ SheetPasteFormatCommand,+ SheetPasteShortKeyCommand,+ SheetPasteValueCommand,+} from '../clipboard.command';+import { DeleteRangeMoveLeftConfirmCommand } from '../delete-range-move-left-confirm.command';+import { DeleteRangeMoveUpConfirmCommand } from '../delete-range-move-up-confirm.command';+import { InsertRangeMoveDownConfirmCommand } from '../insert-range-move-down-confirm.command';+import { InsertRangeMoveRightConfirmCommand } from '../insert-range-move-right-confirm.command';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++function createWorksheet(options?: {+ rowCount?: number;+ colCount?: number;+ filteredRows?: number[];+ merges?: IRange[];+}) {+ const filtered = new Set(options?.filteredRows ?? []);+ return {+ getRowCount: () => options?.rowCount ?? 10,+ getColumnCount: () => options?.colCount ?? 8,+ getRowFiltered: (row: number) => filtered.has(row),+ getMergeData: () => options?.merges ?? [],+ } as any;+}++function createSelectionService(range?: IRange | null) {+ return {+ getCurrentSelections: () => (range ? [{ range }] : range === null ? null : [{ range: undefined }]),+ };+}++describe('insert/delete range confirm commands', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('InsertRangeMoveDownConfirm handles filtered rows, merge confirm and direct execute', async () => {+ const executeCommand = vi.fn(async () => true);+ const confirm = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const locale = { t: (key: string) => key };+ const rowSelection = { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 } as IRange;++ const filteredWorksheet = createWorksheet({ filteredRows: [2] });+ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: filteredWorksheet,+ } as any);+ const accessorFiltered = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, locale],+ [SheetsSelectionsService, createSelectionService(rowSelection)],+ [IUniverInstanceService, {}],+ ]);+ expect(await InsertRangeMoveDownConfirmCommand.handler(accessorFiltered)).toBe(false);+ expect(executeCommand).not.toHaveBeenCalled();++ const mergeWorksheet = createWorksheet({+ merges: [{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 } as IRange],+ });+ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: mergeWorksheet,+ } as any);+ const accessorMerge = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, locale],+ [SheetsSelectionsService, createSelectionService(rowSelection)],+ [IUniverInstanceService, {}],+ ]);++ expect(await InsertRangeMoveDownConfirmCommand.handler(accessorMerge)).toBe(true);+ expect(await InsertRangeMoveDownConfirmCommand.handler(accessorMerge)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(InsertRangeMoveDownCommand.id);++ const noMergeWorksheet = createWorksheet();+ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: noMergeWorksheet,+ } as any);+ expect(await InsertRangeMoveDownConfirmCommand.handler(accessorMerge)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(InsertRangeMoveDownCommand.id);+ });++ it('InsertRangeMoveRightConfirm executes directly and handles merge confirm', async () => {+ const executeCommand = vi.fn(async () => true);+ const confirm = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const locale = { t: (key: string) => key };+ const range = { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } as IRange;+ const accessor = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, locale],+ [SheetsSelectionsService, createSelectionService(range)],+ [IUniverInstanceService, {}],+ ]);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet(),+ } as any);+ expect(await InsertRangeMoveRightConfirmCommand.handler(accessor)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(InsertRangeMoveRightCommand.id);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet({+ merges: [{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 } as IRange],+ }),+ } as any);+ expect(await InsertRangeMoveRightConfirmCommand.handler(accessor)).toBe(true);+ expect(await InsertRangeMoveRightConfirmCommand.handler(accessor)).toBe(true);+ });++ it('DeleteRangeMoveUpConfirm handles filter/merge/no-merge branches', async () => {+ const executeCommand = vi.fn(async () => true);+ const confirm = vi.fn().mockResolvedValueOnce(true).mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const locale = { t: (key: string) => key };+ const range = { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 } as IRange;+ const accessor = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, locale],+ [SheetsSelectionsService, createSelectionService(range)],+ [IUniverInstanceService, {}],+ ]);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet({ filteredRows: [2] }),+ } as any);+ expect(await DeleteRangeMoveUpConfirmCommand.handler(accessor)).toBe(false);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet({+ merges: [{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 } as IRange],+ }),+ } as any);+ expect(await DeleteRangeMoveUpConfirmCommand.handler(accessor)).toBe(true);+ expect(await DeleteRangeMoveUpConfirmCommand.handler(accessor)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(DeleteRangeMoveUpCommand.id);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet(),+ } as any);+ expect(await DeleteRangeMoveUpConfirmCommand.handler(accessor)).toBe(true);+ });++ it('DeleteRangeMoveLeftConfirm handles merge/no-merge and guard branches', async () => {+ const executeCommand = vi.fn(async () => true);+ const confirm = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const locale = { t: (key: string) => key };+ const range = { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } as IRange;+ const accessor = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, locale],+ [SheetsSelectionsService, createSelectionService(range)],+ [IUniverInstanceService, {}],+ ]);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet({+ merges: [{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 } as IRange],+ }),+ } as any);+ expect(await DeleteRangeMoveLeftConfirmCommand.handler(accessor)).toBe(true);+ expect(await DeleteRangeMoveLeftConfirmCommand.handler(accessor)).toBe(true);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue({+ worksheet: createWorksheet(),+ } as any);+ expect(await DeleteRangeMoveLeftConfirmCommand.handler(accessor)).toBe(true);+ expect(executeCommand).toHaveBeenCalledWith(DeleteRangeMoveLeftCommand.id);++ const noSelectionAccessor = createAccessor([+ [IConfirmService, { confirm }],+ [ICommandService, { executeCommand }],+ [LocaleService, locale],+ [SheetsSelectionsService, createSelectionService(null)],+ [IUniverInstanceService, {}],+ ]);+ expect(await DeleteRangeMoveLeftConfirmCommand.handler(noSelectionAccessor)).toBe(false);++ vi.spyOn(sheets, 'getSheetCommandTarget').mockReturnValue(null);+ expect(await DeleteRangeMoveLeftConfirmCommand.handler(accessor)).toBe(false);+ });+});++describe('clipboard command branches', () => {+ it('runs copy/cut/paste and optional-paste command handlers', async () => {+ const copy = vi.fn(async () => true);+ const cut = vi.fn(async () => true);+ const paste = vi.fn(async () => true);+ const pasteByCopyId = vi.fn(async () => true);+ const legacyPaste = vi.fn();+ const rePasteWithPasteType = vi.fn(async () => true);+ const copyContentCache = vi.fn(() => ({ getLastCopyId: () => 'copy-1' }));+ const clipboardService = {+ copy,+ cut,+ paste,+ pasteByCopyId,+ legacyPaste,+ rePasteWithPasteType,+ copyContentCache,+ };+ const read = vi.fn(async () => [{ id: 'clip-1' }]);++ const accessor = createAccessor([+ [ISheetClipboardService, clipboardService],+ [IClipboardInterfaceService, { supportClipboard: true, read }],+ ]);++ expect(await SheetCopyCommand.handler(accessor)).toBe(true);+ expect(await SheetCutCommand.handler(accessor)).toBe(true);+ expect(await SheetPasteCommand.handler(accessor, { value: 'v' })).toBe(true);+ expect(paste).toHaveBeenCalledWith({ id: 'clip-1' }, 'v');++ const accessorWithoutClipboardAPI = createAccessor([+ [ISheetClipboardService, clipboardService],+ [IClipboardInterfaceService, { supportClipboard: false, read: vi.fn(async () => []) }],+ ]);+ expect(await SheetPasteCommand.handler(accessorWithoutClipboardAPI, { value: 'value-only' })).toBe(true);+ expect(pasteByCopyId).toHaveBeenCalledWith('copy-1', 'value-only');++ const accessorNoData = createAccessor([+ [ISheetClipboardService, {+ ...clipboardService,+ copyContentCache: () => ({ getLastCopyId: () => '' }),+ }],+ [IClipboardInterfaceService, { supportClipboard: true, read: vi.fn(async () => []) }],+ ]);+ expect(await SheetPasteCommand.handler(accessorNoData, { value: 'none' })).toBe(false);++ expect(await SheetPasteShortKeyCommand.handler(accessor, { htmlContent: '<b>x</b>', textContent: 'x', files: [] })).toBe(true);+ expect(legacyPaste).toHaveBeenCalledWith('<b>x</b>', 'x', []);++ expect(await SheetOptionalPasteCommand.handler(accessor, { type: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE })).toBe(true);+ expect(rePasteWithPasteType).toHaveBeenCalledWith(PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE);+ });++ it('routes special paste commands to SheetPasteCommand', async () => {+ const executeCommand = vi.fn(async () => true);+ const accessor = createAccessor([+ [ICommandService, { executeCommand }],+ ]);++ expect(await SheetPasteValueCommand.handler(accessor)).toBe(true);+ expect(await SheetPasteFormatCommand.handler(accessor)).toBe(true);+ expect(await SheetPasteColWidthCommand.handler(accessor)).toBe(true);+ expect(await SheetPasteBesidesBorderCommand.handler(accessor)).toBe(true);++ expect(executeCommand).toHaveBeenCalledWith(SheetPasteCommand.id, {+ value: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE,+ });+ expect(executeCommand).toHaveBeenCalledWith(SheetPasteCommand.id, {+ value: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT,+ });+ expect(executeCommand).toHaveBeenCalledWith(SheetPasteCommand.id, {+ value: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH,+ });+ expect(executeCommand).toHaveBeenCalledWith(SheetPasteCommand.id, {+ value: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_BESIDES_BORDER,+ });+ });+});diff --git a/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.tsindex a8ca93ad73..24a1d0b4db 100644--- a/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts+++ b/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts@@ -14,8 +14,57 @@* limitations under the License.*/-import { describe, expect, it } from 'vitest';-import { isAllColumnsCovered, isAllRowsCovered } from '../utils/selection-utils';+import { Direction, RANGE_TYPE } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import {+ checkIfShrink,+ expandToNextCell,+ expandToWholeSheet,+ findNextGapRange,+ findNextRange,+ getMergeableSelectionsByType,+ getStartRange,+ isAllColumnsCovered,+ isAllRowsCovered,+ MergeType,+ shrinkToNextCell,+} from '../utils/selection-utils';++vi.mock('@univerjs/sheets', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@univerjs/sheets')>();+ return {+ ...actual,+ alignToMergedCellsBorders: (range: any) => range,+ };+});++function createMatrix(hasValue = false) {+ return {+ forValue: (cb: (...args: any[]) => void) => {+ if (hasValue) {+ cb(0, 0, { v: 1 });+ }+ return {+ getLength: () => (hasValue ? 1 : 0),+ forValue: (cb2: (...args: any[]) => void) => {+ if (hasValue) {+ cb2(0, 0, { v: 1 });+ }+ },+ };+ },+ };+}++function createWorksheet() {+ return {+ getRowCount: () => 6,+ getColumnCount: () => 6,+ getRowVisible: (row: number) => row !== 1,+ getColVisible: (col: number) => col !== 1,+ getMatrixWithMergedCells: (_sr: number, _sc: number, _er: number, _ec: number) => createMatrix(false),+ };+}describe('Test selection utils', () => {it('Function isAllRowsCovered', () => {@@ -105,4 +154,69 @@ describe('Test selection utils', () => {)).toBeTruthy();});++ it('findNextRange should move with hidden rows/cols and wrap in boundary', () => {+ const worksheet = createWorksheet();+ const start = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };+ expect(findNextRange(start as any, Direction.DOWN, worksheet as any)).toEqual({ ...start, startRow: 2, endRow: 2 });+ expect(findNextRange(start as any, Direction.RIGHT, worksheet as any)).toEqual({ ...start, startColumn: 2, endColumn: 2 });+ expect(findNextRange(start as any, Direction.LEFT, worksheet as any)).toEqual({ startRow: 5, endRow: 5, startColumn: 5, endColumn: 5 });+ });++ it('findNextGapRange should continue to gap boundary on empty ranges', () => {+ const worksheet = createWorksheet();+ const start = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };+ expect(findNextGapRange(start as any, Direction.RIGHT, worksheet as any)).toEqual({ startRow: 0, endRow: 0, startColumn: 5, endColumn: 5 });+ expect(findNextGapRange(start as any, Direction.DOWN, worksheet as any)).toEqual({ startRow: 5, endRow: 5, startColumn: 0, endColumn: 0 });+ });++ it('expand/shrink helpers should return expected ranges', () => {+ const worksheet = createWorksheet();+ const start = { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 };++ expect(expandToNextCell(start as any, Direction.RIGHT, worksheet as any)).toEqual(expect.objectContaining({+ startRow: 2,+ endRow: 2,+ startColumn: 2,+ endColumn: 3,+ }));+ expect(shrinkToNextCell({ startRow: 2, endRow: 2, startColumn: 2, endColumn: 4 } as any, Direction.RIGHT, worksheet as any)).toEqual(expect.objectContaining({+ startRow: 2,+ endRow: 2,+ startColumn: 3,+ endColumn: 4,+ }));+ expect(expandToWholeSheet(worksheet as any)).toEqual({+ startRow: 0,+ startColumn: 0,+ endRow: 5,+ endColumn: 5,+ rangeType: RANGE_TYPE.ALL,+ });+ });++ it('getStartRange and checkIfShrink should follow direction and primary cell', () => {+ const range = { startRow: 0, endRow: 3, startColumn: 0, endColumn: 3 };+ const primary = { actualRow: 2, actualColumn: 1, startRow: 2, endRow: 2, startColumn: 1, endColumn: 1 };+ const worksheet = createWorksheet();++ expect(getStartRange(range as any, primary as any, Direction.DOWN)).toEqual({ ...range, startColumn: 1, endColumn: 1 });+ expect(getStartRange(range as any, primary as any, Direction.RIGHT)).toEqual({ ...range, startRow: 2, endRow: 2 });+ expect(checkIfShrink({ range, primary } as any, Direction.DOWN, worksheet as any)).toBe(true);+ expect(checkIfShrink({ range, primary: { ...primary, startColumn: 0, endColumn: 0 } } as any, Direction.RIGHT, worksheet as any)).toBe(false);+ });++ it('getMergeableSelectionsByType should filter single-cell ranges by merge mode', () => {+ const selections = [+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 },+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 },+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ ];++ expect(getMergeableSelectionsByType(MergeType.MergeAll, selections as any)?.length).toBe(3);+ expect(getMergeableSelectionsByType(MergeType.MergeVertical, selections as any)?.length).toBe(2);+ expect(getMergeableSelectionsByType(MergeType.MergeHorizontal, selections as any)?.length).toBe(2);+ expect(getMergeableSelectionsByType(MergeType.MergeAll, null)).toBeNull();+ });});diff --git a/packages/sheets-ui/src/commands/operations/__tests__/basic-operations.spec.ts b/packages/sheets-ui/src/commands/operations/__tests__/basic-operations.spec.tsnew file mode 100644index 0000000000..de625d2572--- /dev/null+++ b/packages/sheets-ui/src/commands/operations/__tests__/basic-operations.spec.ts@@ -0,0 +1,142 @@+/**+ * 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 { IUniverInstanceService } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { describe, expect, it, vi } from 'vitest';+import { IEditorBridgeService } from '../../../services/editor-bridge.service';+import { IFormatPainterService } from '../../../services/format-painter/format-painter.service';+import { SetActivateCellEditOperation } from '../activate-cell-edit.operation';+import { ScrollToRangeOperation } from '../scroll-to-range.operation';+import { SetScrollOperation } from '../scroll.operation';+import { SetFormatPainterOperation } from '../set-format-painter.operation';+import { SetZoomRatioOperation } from '../set-zoom-ratio.operation';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('sheets-ui basic operations', () => {+ it('SetFormatPainterOperation should guard empty params and update service', () => {+ const setStatus = vi.fn();+ const accessor = createAccessor([[IFormatPainterService, { setStatus }]]);++ expect(SetFormatPainterOperation.handler(accessor, undefined as any)).toBe(false);+ expect(SetFormatPainterOperation.handler(accessor, { status: 'ONCE' as any })).toBe(true);+ expect(setStatus).toHaveBeenCalledWith('ONCE');+ });++ it('SetActivateCellEditOperation should update current edit cell state', () => {+ const setEditCell = vi.fn();+ const accessor = createAccessor([[IEditorBridgeService, { setEditCell }]]);++ expect(SetActivateCellEditOperation.handler(accessor, { unitId: 'u1' } as any)).toBe(true);+ expect(setEditCell).toHaveBeenCalledWith({ unitId: 'u1' });+ });++ it('SetScrollOperation should compute final offsets with screen ratios', () => {+ const emitRawScrollParam = vi.fn();+ const renderUnit = {+ with: vi.fn(() => ({ emitRawScrollParam })),+ engine: { width: 200, height: 100 },+ };++ const renderManagerService = {+ getRenderById: vi.fn()+ .mockReturnValueOnce(renderUnit)+ .mockReturnValueOnce(renderUnit),+ };++ const accessor = createAccessor([[IRenderManagerService, renderManagerService]]);++ expect(SetScrollOperation.handler(accessor, {+ unitId: 'u1',+ sheetId: 's1',+ offsetX: 10,+ offsetY: 20,+ screenRatioX: 0.5,+ screenRatioY: 0.25,+ } as any)).toBe(true);++ expect(emitRawScrollParam).toHaveBeenCalledWith(expect.objectContaining({+ unitId: 'u1',+ sheetId: 's1',+ offsetX: 110,+ offsetY: 45,+ }));+ });++ it('SetScrollOperation should return false for empty params or missing render unit', () => {+ const accessor = createAccessor([[IRenderManagerService, { getRenderById: vi.fn() }]]);+ expect(SetScrollOperation.handler(accessor, undefined as any)).toBe(false);++ const renderManagerService = {+ getRenderById: vi.fn()+ .mockReturnValueOnce({ with: () => ({ emitRawScrollParam: vi.fn() }) })+ .mockReturnValueOnce(null),+ };+ const accessor2 = createAccessor([[IRenderManagerService, renderManagerService]]);+ expect(SetScrollOperation.handler(accessor2, { unitId: 'u1', sheetId: 's1' } as any)).toBe(false);+ });++ it('SetZoomRatioOperation should delegate to zoom controller', () => {+ const updateZoom = vi.fn(() => true);+ const renderManagerService = {+ getRenderById: vi.fn(() => ({ with: () => ({ updateZoom }) })),+ };+ const accessor = createAccessor([[IRenderManagerService, renderManagerService]]);++ expect(SetZoomRatioOperation.handler(accessor, {+ unitId: 'u1',+ subUnitId: 's1',+ zoomRatio: 1.25,+ })).toBe(true);+ expect(updateZoom).toHaveBeenCalledWith('s1', 1.25);++ const accessor2 = createAccessor([[IRenderManagerService, { getRenderById: () => null }]]);+ expect(SetZoomRatioOperation.handler(accessor2, { unitId: 'u1', subUnitId: 's1', zoomRatio: 1 } as any)).toBe(false);+ });++ it('ScrollToRangeOperation should guard params and call scroll controller', () => {+ const scrollToRange = vi.fn(() => true);+ const accessor = createAccessor([+ [IUniverInstanceService, { getCurrentUnitForType: () => ({ getUnitId: () => 'u1' }) }],+ [IRenderManagerService, { getRenderById: () => ({ with: () => ({ scrollToRange }) }) }],+ ]);++ expect(ScrollToRangeOperation.handler(accessor, undefined as any)).toBe(false);++ expect(ScrollToRangeOperation.handler(accessor, {+ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ forceTop: true,+ forceLeft: false,+ } as any)).toBe(true);++ expect(scrollToRange).toHaveBeenCalledWith(+ { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ true,+ false+ );+ });+});diff --git a/packages/sheets-ui/src/commands/operations/__tests__/cell-edit.operation.spec.ts b/packages/sheets-ui/src/commands/operations/__tests__/cell-edit.operation.spec.tsnew file mode 100644index 0000000000..f39a0e8ff9--- /dev/null+++ b/packages/sheets-ui/src/commands/operations/__tests__/cell-edit.operation.spec.ts@@ -0,0 +1,97 @@+/**+ * 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 { ICommandService, IConfigService, IUniverInstanceService } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { IEditorBridgeService } from '../../../services/editor-bridge.service';+import {+ SetCellEditVisibleArrowOperation,+ SetCellEditVisibleOperation,+ SetCellEditVisibleWithF2Operation,+} from '../cell-edit.operation';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('cell edit operations', () => {+ it('SetCellEditVisibleOperation guards empty params and disable-edit mode', () => {+ const changeVisible = vi.fn();+ const accessor = createAccessor([+ [IConfigService, { getConfig: vi.fn(() => ({ disableEdit: true })) }],+ [IUniverInstanceService, { getCurrentUnitForType: vi.fn(() => ({ getUnitId: () => 'u1' })) }],+ [IEditorBridgeService, { changeVisible }],+ ]);++ expect(SetCellEditVisibleOperation.handler(accessor, undefined as any)).toBe(false);+ expect(SetCellEditVisibleOperation.handler(accessor, { visible: true } as any)).toBe(false);+ expect(changeVisible).not.toHaveBeenCalled();+ });++ it('SetCellEditVisibleOperation returns false when no active workbook', () => {+ const accessor = createAccessor([+ [IConfigService, { getConfig: vi.fn(() => ({ disableEdit: false })) }],+ [IUniverInstanceService, { getCurrentUnitForType: vi.fn(() => null) }],+ [IEditorBridgeService, { changeVisible: vi.fn() }],+ ]);++ expect(SetCellEditVisibleOperation.handler(accessor, { visible: false } as any)).toBe(false);+ });++ it('SetCellEditVisibleOperation falls back to workbook unitId', () => {+ const changeVisible = vi.fn();+ const accessor = createAccessor([+ [IConfigService, { getConfig: vi.fn(() => ({ disableEdit: false })) }],+ [IUniverInstanceService, { getCurrentUnitForType: vi.fn(() => ({ getUnitId: () => 'workbook-u1' })) }],+ [IEditorBridgeService, { changeVisible }],+ ]);++ expect(SetCellEditVisibleOperation.handler(accessor, { visible: true } as any)).toBe(true);+ expect(changeVisible).toHaveBeenCalledWith({ visible: true, unitId: 'workbook-u1' });+ });++ it('SetCellEditVisibleWithF2Operation respects workbook existence and delegates command execution', () => {+ const syncExecuteCommand = vi.fn(() => true);+ const commandAccessor = createAccessor([+ [ICommandService, { syncExecuteCommand }],+ [IUniverInstanceService, { getCurrentUnitForType: vi.fn(() => ({ getUnitId: () => 'wb-u2' })) }],+ ]);++ expect(SetCellEditVisibleWithF2Operation.handler(commandAccessor, { visible: true } as any)).toBe(true);+ expect(syncExecuteCommand).toHaveBeenCalledWith(SetCellEditVisibleOperation.id, {+ visible: true,+ unitId: 'wb-u2',+ });++ const noWorkbookAccessor = createAccessor([+ [ICommandService, { syncExecuteCommand: vi.fn() }],+ [IUniverInstanceService, { getCurrentUnitForType: vi.fn(() => null) }],+ ]);+ expect(SetCellEditVisibleWithF2Operation.handler(noWorkbookAccessor, { visible: true } as any)).toBe(false);+ });++ it('SetCellEditVisibleArrowOperation is a no-op event operation', () => {+ expect(SetCellEditVisibleArrowOperation.handler({} as any, undefined as any)).toBe(true);+ });+});diff --git a/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.ts b/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.tsnew file mode 100644index 0000000000..b5f8327e48--- /dev/null+++ b/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.ts@@ -0,0 +1,95 @@+/**+ * 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 { IUniverInstanceService, LocaleService } from '@univerjs/core';+import { IEditorService } from '@univerjs/docs-ui';+import { getSheetCommandTarget } from '@univerjs/sheets';+import { ISidebarService } from '@univerjs/ui';+import { describe, expect, it, vi } from 'vitest';+import { DEFINED_NAME_CONTAINER } from '../../../views/defined-name/component-name';+import { SidebarDefinedNameOperation } from '../sidebar-defined-name.operation';++vi.mock('@univerjs/sheets', () => ({+ getSheetCommandTarget: vi.fn(),+}));++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('SidebarDefinedNameOperation', () => {+ it('returns false when there is no sheet command target', async () => {+ vi.mocked(getSheetCommandTarget).mockReturnValue(null as any);+ const open = vi.fn();+ const close = vi.fn();+ const accessor = createAccessor([+ [ISidebarService, { open, close }],+ [IEditorService, {}],+ [LocaleService, { t: vi.fn(() => 'Defined Name') }],+ [IUniverInstanceService, {}],+ ]);++ await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'open' } as any)).resolves.toBe(false);+ expect(open).not.toHaveBeenCalled();+ expect(close).not.toHaveBeenCalled();+ });++ it('opens sidebar with localized title when value is open', async () => {+ vi.mocked(getSheetCommandTarget).mockReturnValue({ unitId: 'u1', subUnitId: 's1' } as any);+ const open = vi.fn();+ const close = vi.fn();+ const accessor = createAccessor([+ [ISidebarService, { open, close }],+ [IEditorService, {}],+ [LocaleService, { t: vi.fn(() => 'Defined Name') }],+ [IUniverInstanceService, {}],+ ]);++ await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'open' } as any)).resolves.toBe(true);+ expect(open).toHaveBeenCalledWith(expect.objectContaining({+ id: DEFINED_NAME_CONTAINER,+ width: 333,+ header: { title: 'Defined Name' },+ children: { label: DEFINED_NAME_CONTAINER },+ }));+ expect(close).not.toHaveBeenCalled();+ });++ it('closes sidebar for close/default action', async () => {+ vi.mocked(getSheetCommandTarget).mockReturnValue({ unitId: 'u1', subUnitId: 's1' } as any);+ const close = vi.fn();+ const accessor = createAccessor([+ [ISidebarService, { open: vi.fn(), close }],+ [IEditorService, {}],+ [LocaleService, { t: vi.fn(() => 'Defined Name') }],+ [IUniverInstanceService, {}],+ ]);++ await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'close' } as any)).resolves.toBe(true);+ expect(close).toHaveBeenCalledTimes(1);++ await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'other' } as any)).resolves.toBe(true);+ expect(close).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/sheets-ui/src/common/__tests__/utils.spec.ts b/packages/sheets-ui/src/common/__tests__/utils.spec.tsnew file mode 100644index 0000000000..ae705d6c6e--- /dev/null+++ b/packages/sheets-ui/src/common/__tests__/utils.spec.ts@@ -0,0 +1,201 @@+/**+ * 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 { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';+import { describe, expect, it } from 'vitest';+import {+ checkCellContentInRange,+ checkCellContentInRanges,+ getCellIndexByOffsetWithMerge,+ getCellRealRange,+ getHoverCellPosition,+ getUserListEqual,+ getViewportByCell,+ transformBound2OffsetBound,+ transformPosition2Offset,+} from '../utils';++describe('common utils', () => {+ it('compares collaborator user lists by user id and role', () => {+ const list1 = [+ { id: 'b', subject: { userID: 'u2' }, role: 'viewer' },+ { id: 'a', subject: { userID: 'u1' }, role: 'editor' },+ ] as any;+ const list2 = [+ { id: 'a', subject: { userID: 'u1' }, role: 'editor' },+ { id: 'b', subject: { userID: 'u2' }, role: 'viewer' },+ ] as any;+ const list3 = [{ id: 'a', subject: { userID: 'u1' }, role: 'viewer' }] as any;++ expect(getUserListEqual(list1, list2)).toBe(true);+ expect(getUserListEqual(list1, list3)).toBe(false);+ expect(getUserListEqual(list2, [{ id: 'a', subject: { userID: 'u1' }, role: 'viewer' }, { id: 'b', subject: { userID: 'u2' }, role: 'viewer' }] as any)).toBe(false);+ });++ it('checks whether cell contents exist in single or multiple ranges', () => {+ const matrixWithValue = {+ forValue: (cb: (...args: any[]) => void) => {+ cb(0, 0, { v: 'primary' });+ cb(0, 1, { v: 'other' });+ },+ };+ const matrixWithoutValue = {+ forValue: (cb: (...args: any[]) => void) => {+ cb(0, 0, { v: 'primary' });+ cb(1, 1, null);+ },+ };++ const worksheet = {+ getMatrixWithMergedCells: (_sr: number, _sc: number, _er: number, ec: number) => (ec > 1 ? matrixWithoutValue : matrixWithValue),+ cellHasValue: (cell: any) => !!cell?.v,+ };++ expect(checkCellContentInRange(worksheet as any, { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } as any)).toBe(true);+ expect(checkCellContentInRanges(worksheet as any, [+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 2 },+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },+ ] as any)).toBe(true);+ });++ it('gets cell index by offset with merged-cell fallback', () => {+ const scene = {+ getActiveViewportByCoord: () => ({ viewportScrollX: 10, viewportScrollY: 20 }),+ getAncestorScale: () => ({ scaleX: 2, scaleY: 3 }),+ };+ const skeleton = {+ getCellIndexByOffset: () => ({ row: 4, column: 5 }),+ worksheet: {+ getMergedCell: () => ({ startRow: 1, startColumn: 2 }),+ },+ };++ const result = getCellIndexByOffsetWithMerge(100, 120, scene as any, skeleton as any)!;+ expect(result).toEqual(expect.objectContaining({+ row: 4,+ col: 5,+ actualRow: 1,+ actualCol: 2,+ }));++ const noViewport = {+ getActiveViewportByCoord: () => null,+ };+ expect(getCellIndexByOffsetWithMerge(1, 2, noViewport as any, skeleton as any)).toBeUndefined();+ });++ it('resolves viewport by cell with and without freeze panes', () => {+ const scene = {+ getViewport: (key: string) => key,+ };+ const noFreezeSheet = { getFreeze: () => null };+ expect(getViewportByCell(1, 1, scene as any, noFreezeSheet as any)).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN);++ const freezeSheet = { getFreeze: () => ({ startRow: 2, startColumn: 3 }) };+ expect(getViewportByCell(3, 3, scene as any, freezeSheet as any)).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN);+ expect(getViewportByCell(1, 1, scene as any, freezeSheet as any)).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);+ expect(getViewportByCell(1, 3, scene as any, freezeSheet as any)).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);+ expect(getViewportByCell(3, 1, scene as any, freezeSheet as any)).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT);+ });++ it('transforms sheet position to viewport offset', () => {+ const sceneNoViewport = {+ getAncestorScale: () => ({ scaleX: 2, scaleY: 2 }),+ getViewport: () => null,+ };+ expect(transformPosition2Offset(10, 20, sceneNoViewport as any, {} as any, {} as any)).toEqual({ x: 10, y: 20 });++ const scene = {+ getAncestorScale: () => ({ scaleX: 2, scaleY: 3 }),+ getViewport: () => ({ top: 50, left: 40, viewportScrollX: 5, viewportScrollY: 6 }),+ };+ const skeleton = {+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => {+ if (row === 1 && col === 2) {+ return { startX: 20, startY: 30 };+ }+ return { startX: 70, startY: 90 };+ },+ rowHeaderWidth: 10,+ columnHeaderHeight: 8,+ };+ const worksheet = {+ getFreeze: () => ({ startColumn: 3, startRow: 2, xSplit: 1, ySplit: 1 }),+ };++ const result = transformPosition2Offset(60, 20, scene as any, skeleton as any, worksheet as any);+ expect(result).toEqual({ x: 110, y: 76 });++ const bound = transformBound2OffsetBound({ left: 30, top: 20, right: 60, bottom: 70 } as any, scene as any, skeleton as any, worksheet as any);+ expect(bound.left).toBeTypeOf('number');+ expect(bound.right).toBeTypeOf('number');+ expect(bound.top).toBeTypeOf('number');+ expect(bound.bottom).toBeTypeOf('number');+ });++ it('gets real cell range and hover cell position with overflow and merge fallback', () => {+ const overflowRange = { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 };+ const skeleton = {+ overflowCache: {+ forValue: (cb: (...args: any[]) => void) => cb(1, 1, overflowRange),+ },+ getCellWithCoordByIndex: (row: number, col: number) => ({+ actualRow: row,+ actualColumn: col,+ mergeInfo: row === 1 && col === 1 ? { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 } : null,+ }),+ getOffsetByColumn: (col: number) => col * 20,+ getOffsetByRow: (row: number) => row * 10,+ getCellIndexByOffset: () => ({ row: 1, column: 1 }),+ worksheet: { getMergedCell: () => null },+ };+ const workbook = { getUnitId: () => 'unit-1' };+ const worksheet = { getSheetId: () => 'sheet-1' };++ const location = getCellRealRange(workbook as any, worksheet as any, skeleton as any, 2, 2);+ expect(location.row).toBe(1);+ expect(location.col).toBe(1);++ const scene = {+ getActiveViewportByCoord: () => ({ viewportScrollX: 3, viewportScrollY: 4 }),+ getAncestorScale: () => ({ scaleX: 2, scaleY: 2 }),+ };+ const currentRender = { scene };+ const hover = getHoverCellPosition(+ currentRender as any,+ workbook as any,+ worksheet as any,+ { skeleton, sheetId: 'sheet-1' } as any,+ 100,+ 120+ );+ expect(hover?.location.row).toBe(1);+ expect(hover?.overflowLocation.row).toBe(1);+ expect(hover?.position.startX).toBeTypeOf('number');++ const noCellIndexSkeleton = {+ ...skeleton,+ getCellIndexByOffset: () => ({ row: 1, column: 1 }),+ };+ const noActiveViewportRender = {+ scene: {+ getActiveViewportByCoord: () => null,+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),+ },+ };+ expect(getHoverCellPosition(noActiveViewportRender as any, workbook as any, worksheet as any, { skeleton: noCellIndexSkeleton, sheetId: 'sheet-1' } as any, 1, 2)).toBeNull();+ });+});diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editor-utils.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editor-utils.spec.tsnew file mode 100644index 0000000000..78fc9229ab--- /dev/null+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editor-utils.spec.ts@@ -0,0 +1,31 @@+/**+ * 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 { EMBEDDING_FORMULA_EDITOR, isEmbeddingFormulaEditor } from '../utils/is-embedding-formula-editor';+import { isRangeSelector, RANGE_SELECTOR_SYMBOLS } from '../utils/is-range-selector';++describe('editor utils', () => {+ it('should detect embedding formula editor unit ids', () => {+ expect(isEmbeddingFormulaEditor(`abc_${EMBEDDING_FORMULA_EDITOR}_xyz`)).toBe(true);+ expect(isEmbeddingFormulaEditor('normal-doc-id')).toBe(false);+ });++ it('should detect range selector unit ids', () => {+ expect(isRangeSelector(`abc_${RANGE_SELECTOR_SYMBOLS}_xyz`)).toBe(true);+ expect(isRangeSelector('normal-doc-id')).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/menu-advanced.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/menu-advanced.spec.tsnew file mode 100644index 0000000000..f5ce7a8172--- /dev/null+++ b/packages/sheets-ui/src/controllers/menu/__tests__/menu-advanced.spec.ts@@ -0,0 +1,107 @@+/**+ * 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 { Univer } from '@univerjs/core';+import { ICommandService, Injector, RANGE_TYPE } from '@univerjs/core';+import { SetRangeValuesMutation, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';+import { firstValueFrom, take } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ BackgroundColorSelectorMenuItemFactory,+ FontFamilySelectorMenuItemFactory,+ HorizontalAlignMenuItemFactory,+ ItalicMenuItemFactory,+ StrikeThroughMenuItemFactory,+ TextColorSelectorMenuItemFactory,+ TextRotateMenuItemFactory,+ UnderlineMenuItemFactory,+ VerticalAlignMenuItemFactory,+ WrapTextMenuItemFactory,+} from '../menu';+import { createMenuTestBed } from './create-menu-test-bed';++describe('advanced menu state streams', () => {+ let univer: Univer;+ let get: any;+ let commandService: ICommandService;+ let selectionService: SheetsSelectionsService;++ beforeEach(() => {+ const testBed = createMenuTestBed();+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ selectionService = get(SheetsSelectionsService);+ commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(SetRangeValuesMutation);+ selectionService.setSelections([+ {+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },+ primary: {+ startRow: 0,+ startColumn: 0,+ endRow: 0,+ endColumn: 0,+ actualRow: 0,+ actualColumn: 0,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ },+ ]);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('resolves formatting menu states from current cell', async () => {+ const injector = get(Injector);+ const italic = injector.invoke(ItalicMenuItemFactory);+ const underline = injector.invoke(UnderlineMenuItemFactory);+ const strike = injector.invoke(StrikeThroughMenuItemFactory);+ const fontFamily = injector.invoke(FontFamilySelectorMenuItemFactory);++ expect(await firstValueFrom(italic.activated$!.pipe(take(1)))).toBeTypeOf('boolean');+ expect(await firstValueFrom(underline.activated$!.pipe(take(1)))).toBeTypeOf('boolean');+ expect(await firstValueFrom(strike.activated$!.pipe(take(1)))).toBeTypeOf('boolean');+ expect(await firstValueFrom(fontFamily.value$!.pipe(take(1)))).toBeTypeOf('string');+ expect(await firstValueFrom(fontFamily.disabled$!.pipe(take(1)))).toBeTypeOf('boolean');+ });++ it('resolves color/alignment/wrap/rotation selector streams', async () => {+ const injector = get(Injector);+ const textColor = injector.invoke(TextColorSelectorMenuItemFactory);+ const bgColor = injector.invoke(BackgroundColorSelectorMenuItemFactory);+ const horizontal = injector.invoke(HorizontalAlignMenuItemFactory);+ const vertical = injector.invoke(VerticalAlignMenuItemFactory);+ const wrap = injector.invoke(WrapTextMenuItemFactory);+ const rotate = injector.invoke(TextRotateMenuItemFactory);++ const textColorSelections = textColor.selections as any[];+ const bgColorSelections = bgColor.selections as any[];++ expect(await firstValueFrom(textColor.value$!.pipe(take(1)))).toBeTypeOf('string');+ expect(await firstValueFrom(textColorSelections[0].value$!.pipe(take(1)))).toBeTypeOf('string');+ expect(await firstValueFrom(bgColor.value$!.pipe(take(1)))).toBeTypeOf('string');+ expect(await firstValueFrom(bgColorSelections[0].value$!.pipe(take(1)))).toBeTypeOf('string');+ expect(await firstValueFrom(horizontal.value$!.pipe(take(1)))).not.toBeUndefined();+ expect(await firstValueFrom(vertical.value$!.pipe(take(1)))).not.toBeUndefined();+ expect(await firstValueFrom(wrap.value$!.pipe(take(1)))).not.toBeUndefined();+ expect(await firstValueFrom(rotate.value$!.pipe(take(1)))).not.toBeUndefined();+ });+});diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/menu-factories.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/menu-factories.spec.tsnew file mode 100644index 0000000000..b6de453669--- /dev/null+++ b/packages/sheets-ui/src/controllers/menu/__tests__/menu-factories.spec.ts@@ -0,0 +1,188 @@+/**+ * 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 { Univer } from '@univerjs/core';+import {+ ICommandService,+ Injector,+ RANGE_TYPE,+} from '@univerjs/core';+import { SetSelectionsOperation, SetWorksheetHideCommand, SheetsSelectionsService } from '@univerjs/sheets';+import { firstValueFrom, take } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ SetRangeFontDecreaseCommand,+ SetRangeFontIncreaseCommand,+ SetRangeFontSizeCommand,+} from '../../../commands/commands/inline-format.command';+import { ShowMenuListCommand } from '../../../commands/commands/unhide.command';+import {+ FontSizeDecreaseMenuItemFactory,+ FontSizeIncreaseMenuItemFactory,+ FontSizeSelectorMenuItemFactory,+} from '../font.menu';+import {+ ColInsertMenuItemFactory,+ InsertColAfterMenuItemFactory,+ InsertColBeforeMenuItemFactory,+ InsertColLeftCellMenuItemFactory,+ InsertMultiColsLeftHeaderMenuItemFactory,+ InsertMultiColsRightHeaderMenuItemFactory,+ InsertMultiRowsAboveHeaderMenuItemFactory,+ InsertMultiRowsAfterHeaderMenuItemFactory,+ InsertRangeMoveDownMenuItemFactory,+ InsertRangeMoveRightMenuItemFactory,+ InsertRowAfterMenuItemFactory,+ InsertRowBeforeCellMenuItemFactory,+ InsertRowBeforeMenuItemFactory,+ RowInsertMenuItemFactory,+} from '../insert.menu';+import {+ ChangeColorSheetMenuItemFactory,+ CopySheetMenuItemFactory,+ DeleteSheetMenuItemFactory,+ HideSheetMenuItemFactory,+ RenameSheetMenuItemFactory,+ ShowMenuItemFactory,+ UnHideSheetMenuItemFactory,+} from '../sheet.menu';+import { createMenuTestBed } from './create-menu-test-bed';++describe('menu factories', () => {+ let univer: Univer;+ let get: any;+ let commandService: ICommandService;+ let selectionService: SheetsSelectionsService;++ beforeEach(() => {+ const testBed = createMenuTestBed();+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ selectionService = get(SheetsSelectionsService);+ commandService.registerCommand(SetSelectionsOperation);+ });++ afterEach(() => {+ univer.dispose();+ });++ function setSingleSelection(startRow: number, startColumn: number, endRow: number, endColumn: number) {+ selectionService.setSelections([+ {+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },+ primary: {+ startRow,+ startColumn,+ endRow,+ endColumn,+ actualRow: startRow,+ actualColumn: startColumn,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ },+ ]);+ }++ it('creates base insert selectors and header insert commands', async () => {+ const injector = get(Injector);+ const colInsert = injector.invoke(ColInsertMenuItemFactory);+ const rowInsert = injector.invoke(RowInsertMenuItemFactory);+ const insertRowBefore = injector.invoke(InsertRowBeforeMenuItemFactory);+ const insertRowAfter = injector.invoke(InsertRowAfterMenuItemFactory);+ const insertColBefore = injector.invoke(InsertColBeforeMenuItemFactory);+ const insertColAfter = injector.invoke(InsertColAfterMenuItemFactory);+ const insertMoveRight = injector.invoke(InsertRangeMoveRightMenuItemFactory);+ const insertMoveDown = injector.invoke(InsertRangeMoveDownMenuItemFactory);++ expect(colInsert.id).toBe('sheet.menu.col-insert');+ expect(rowInsert.id).toBe('sheet.menu.row-insert');+ expect(insertRowBefore.id).toBe('sheet.command.insert-row-before');+ expect(insertRowAfter.id).toBe('sheet.command.insert-row-after');+ expect(insertColBefore.id).toBe('sheet.command.insert-col-before');+ expect(insertColAfter.id).toBe('sheet.command.insert-col-after');+ expect(insertMoveRight.id).toBe('sheet.command.insert-range-move-right-confirm');+ expect(insertMoveDown.id).toBe('sheet.command.insert-range-move-down-confirm');++ expect(await firstValueFrom(colInsert.hidden$!.pipe(take(1)))).toBeTypeOf('boolean');+ expect(await firstValueFrom(rowInsert.hidden$!.pipe(take(1)))).toBeTypeOf('boolean');+ });++ it('computes row-based insert input menu values from current selection height', async () => {+ setSingleSelection(2, 1, 5, 4);+ const injector = get(Injector);+ const beforeCell = injector.invoke(InsertRowBeforeCellMenuItemFactory);+ const rowsAfter = injector.invoke(InsertMultiRowsAfterHeaderMenuItemFactory);+ const rowsAbove = injector.invoke(InsertMultiRowsAboveHeaderMenuItemFactory);++ expect(await firstValueFrom(beforeCell.value$!.pipe(take(1)))).toBe(4);+ expect(await firstValueFrom(rowsAfter.value$!.pipe(take(1)))).toBe(4);+ expect(await firstValueFrom(rowsAbove.value$!.pipe(take(1)))).toBe(4);+ });++ it('computes column-based insert input menu values from current selection width', async () => {+ setSingleSelection(1, 3, 4, 7);+ const injector = get(Injector);+ const leftCell = injector.invoke(InsertColLeftCellMenuItemFactory);+ const colsLeft = injector.invoke(InsertMultiColsLeftHeaderMenuItemFactory);+ const colsRight = injector.invoke(InsertMultiColsRightHeaderMenuItemFactory);++ expect(await firstValueFrom(leftCell.value$!.pipe(take(1)))).toBe(5);+ expect(await firstValueFrom(colsLeft.value$!.pipe(take(1)))).toBe(5);+ expect(await firstValueFrom(colsRight.value$!.pipe(take(1)))).toBe(5);+ });++ it('creates sheet menu items and resolves default disable states', async () => {+ const injector = get(Injector);+ const deleteSheet = injector.invoke(DeleteSheetMenuItemFactory);+ const copySheet = injector.invoke(CopySheetMenuItemFactory);+ const renameSheet = injector.invoke(RenameSheetMenuItemFactory);+ const colorSheet = injector.invoke(ChangeColorSheetMenuItemFactory);+ const hideSheet = injector.invoke(HideSheetMenuItemFactory);+ const unhideSheet = injector.invoke(UnHideSheetMenuItemFactory);+ const showMenu = injector.invoke(ShowMenuItemFactory);++ expect(deleteSheet.id).toBe('sheet.command.remove-sheet-confirm');+ expect(copySheet.id).toBe('sheet.command.copy-sheet');+ expect(renameSheet.id).toBe('sheet.operation.rename-sheet');+ expect(colorSheet.id).toBe('sheet.command.set-tab-color');+ expect(hideSheet.id).toBe(SetWorksheetHideCommand.id);+ expect(unhideSheet.id).toBe('sheet.command.set-worksheet-show');+ expect(showMenu.id).toBe(ShowMenuListCommand.id);++ expect(await firstValueFrom(deleteSheet.disabled$!.pipe(take(1)))).toBe(true);+ expect(await firstValueFrom(hideSheet.disabled$!.pipe(take(1)))).toBe(true);+ expect(await firstValueFrom(unhideSheet.disabled$!.pipe(take(1)))).toBe(true);+ expect(await firstValueFrom(showMenu.disabled$!.pipe(take(1)))).toBe(true);+ expect(await firstValueFrom((unhideSheet.selections as any).pipe(take(1)))).toEqual([]);+ });++ it('creates font-size menu items and exposes selector current value stream', async () => {+ setSingleSelection(0, 0, 0, 0);+ const injector = get(Injector);+ const sizeSelector = injector.invoke(FontSizeSelectorMenuItemFactory);+ const increase = injector.invoke(FontSizeIncreaseMenuItemFactory);+ const decrease = injector.invoke(FontSizeDecreaseMenuItemFactory);++ expect(sizeSelector.id).toBe(SetRangeFontSizeCommand.id);+ expect(increase.id).toBe(SetRangeFontIncreaseCommand.id);+ expect(decrease.id).toBe(SetRangeFontDecreaseCommand.id);+ expect(await firstValueFrom(sizeSelector.value$!.pipe(take(1)))).toBeTypeOf('number');+ expect(await firstValueFrom(sizeSelector.disabled$!.pipe(take(1)))).toBeTypeOf('boolean');+ });+});diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/menu-util.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/menu-util.spec.tsnew file mode 100644index 0000000000..52fb82f727--- /dev/null+++ b/packages/sheets-ui/src/controllers/menu/__tests__/menu-util.spec.ts@@ -0,0 +1,254 @@+/**+ * 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 {+ FOCUSING_COMMON_DRAWINGS,+ FOCUSING_FX_BAR_EDITOR,+ FOCUSING_SHAPE_TEXT_EDITOR,+ IContextService,+ IPermissionService,+ IUniverInstanceService,+ UserManagerService,+} from '@univerjs/core';+import {+ IExclusiveRangeService,+ RangeProtectionRuleModel,+ SheetsSelectionsService,+ WorkbookEditablePermission,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';+import { BehaviorSubject, firstValueFrom, of, skip, take } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { IEditorBridgeService } from '../../../services/editor-bridge.service';+import {+ deriveStateFromActiveSheet$,+ getBaseRangeMenuHidden$,+ getCellMenuHidden$,+ getCurrentExclusiveRangeInterest$,+ getCurrentRangeDisable$,+ getDeleteMenuHidden$,+ getInsertAfterMenuHidden$,+ getInsertBeforeMenuHidden$,+ getObservableWithExclusiveRange$,+ getWorkbookPermissionDisable$,+} from '../menu-util';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ has(token: unknown) {+ return map.has(token);+ },+ } as any;+}++function firstValue<T>(obs: { pipe: (...args: any[]) => any }) {+ return firstValueFrom(obs.pipe(take(1)));+}++interface IMenuAccessorOption {+ workbook?: any;+ worksheet?: any;+ selections?: any[] | undefined;+ subUnitRules?: any[];+ worksheetRule?: any;+ composePermissionAllTrue?: boolean;+ editorVisible?: any;+ hasEditorBridge?: boolean;+ formulaFocus?: boolean;+ drawingFocus?: boolean;+ shapeEditorFocus?: boolean;+ interestGroupIds?: string[];+}++function createMenuAccessor(option: Partial<IMenuAccessorOption> = {}) {+ const worksheet = option.worksheet ?? {+ getSheetId: () => 'sheet-1',+ getRowCount: () => 20,+ getColumnCount: () => 10,+ };++ const workbook = option.workbook ?? {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ activeSheet$: of(worksheet),+ };++ const selections = option.selections ?? [{ range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 } }];+ const selectionMoveEnd$ = new BehaviorSubject(selections);+ const selectionService = {+ selectionMoveEnd$,+ getCurrentSelections: () => selections,+ getCurrentLastSelection: () => selections[0] ?? null,+ };++ const subUnitRules = option.subUnitRules ?? [];+ const rangeProtectionRuleModel = {+ ruleChange$: new BehaviorSubject(null),+ getSubunitRuleList: () => subUnitRules,+ };++ const worksheetRule = option.worksheetRule ?? null;+ const worksheetProtectionRuleModel = {+ ruleChange$: new BehaviorSubject(null),+ getRule: () => worksheetRule,+ };++ const composePermissionAllTrue = option.composePermissionAllTrue ?? true;+ const permissionService = {+ composePermission$: (ids: string[]) => of(ids.map(() => ({ value: composePermissionAllTrue }))),+ composePermission: (ids: string[]) => ids.map((_id, index) => ({ value: index === 0 ? true : composePermissionAllTrue })),+ permissionPointUpdate$: new BehaviorSubject(null),+ };++ const formulaFocus = option.formulaFocus ?? false;+ const drawingFocus = option.drawingFocus ?? false;+ const shapeEditorFocus = option.shapeEditorFocus ?? false;+ const contextService = {+ subscribeContextValue$: (key: unknown) => {+ if (key === FOCUSING_FX_BAR_EDITOR) {+ return of(formulaFocus);+ }+ if (key === FOCUSING_COMMON_DRAWINGS) {+ return of(drawingFocus);+ }+ if (key === FOCUSING_SHAPE_TEXT_EDITOR) {+ return of(shapeEditorFocus);+ }+ return of(false);+ },+ };++ const interestGroupIds = option.interestGroupIds ?? [];+ const exclusiveRangeService = {+ getInterestGroupId: () => interestGroupIds,+ };++ const pairs: Array<[unknown, unknown]> = [+ [IUniverInstanceService, { getCurrentTypeOfUnit$: () => of(workbook), getCurrentUnitForType: () => workbook }],+ [SheetsSelectionsService, selectionService],+ [RangeProtectionRuleModel, rangeProtectionRuleModel],+ [WorksheetProtectionRuleModel, worksheetProtectionRuleModel],+ [IPermissionService, permissionService],+ [UserManagerService, { currentUser$: of({ userID: 'u1' }) }],+ [IContextService, contextService],+ [IExclusiveRangeService, exclusiveRangeService],+ ];++ if (option.hasEditorBridge) {+ pairs.push([IEditorBridgeService, { visible$: of(option.editorVisible ?? null) }]);+ }++ return createAccessor(pairs);+}++describe('menu-util', () => {+ it('deriveStateFromActiveSheet$ returns default without active sheet and callback value with active sheet', async () => {+ const noActive = { getCurrentTypeOfUnit$: () => of(null) };+ expect(await firstValue(deriveStateFromActiveSheet$(noActive as any, 'DEFAULT', () => of('ACTIVE')))).toBe('DEFAULT');++ const worksheet = { getSheetId: () => 'sheet-1' };+ const workbook = { activeSheet$: of(worksheet) };+ const withActive = { getCurrentTypeOfUnit$: () => of(workbook) };+ expect(await firstValue(deriveStateFromActiveSheet$(withActive as any, 'DEFAULT', () => of('ACTIVE')))).toBe('ACTIVE');+ });++ it('handles exclusive-range interest and derived observable state', async () => {+ const accessor = createMenuAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ interestGroupIds: ['group-a', 'group-b'],+ });++ expect(await firstValue(getCurrentExclusiveRangeInterest$(accessor))).toBe(true);+ expect(await firstValue(getCurrentExclusiveRangeInterest$(accessor, new Set(['group-z'])))).toBe(false);+ expect(await firstValue(getCurrentExclusiveRangeInterest$(accessor, new Set(['group-b'])))).toBe(true);+ expect(await firstValue(getObservableWithExclusiveRange$(accessor, of(false), new Set(['group-b'])))).toBe(true);+ });++ it('computes current-range disable with workbook/editor/drawing/permission states', async () => {+ const noWorkbookAccessor = createAccessor([+ [IUniverInstanceService, { getCurrentTypeOfUnit$: () => of(null) }],+ [UserManagerService, { currentUser$: of({ userID: 'u1' }) }],+ [IContextService, { subscribeContextValue$: () => of(false) }],+ ]);+ expect(await firstValue(getCurrentRangeDisable$(noWorkbookAccessor))).toBe(true);++ const editorVisibleAccessor = createMenuAccessor({+ hasEditorBridge: true,+ editorVisible: { visible: true, unitId: 'unit-1' },+ });+ expect(await firstValue(getCurrentRangeDisable$(editorVisibleAccessor))).toBe(true);++ const drawingFocusedAccessor = createMenuAccessor({+ drawingFocus: true,+ shapeEditorFocus: false,+ composePermissionAllTrue: true,+ });+ expect(await firstValueFrom(getCurrentRangeDisable$(drawingFocusedAccessor).pipe(skip(1), take(1)))).toBe(true);++ const enabledAccessor = createMenuAccessor({+ composePermissionAllTrue: true,+ drawingFocus: false,+ worksheetRule: null,+ subUnitRules: [],+ });+ expect(await firstValue(getCurrentRangeDisable$(enabledAccessor))).toBe(false);+ });++ it('computes base/insert/delete/cell menu hidden observables', async () => {+ const accessor = createMenuAccessor({+ composePermissionAllTrue: false,+ subUnitRules: [{ permissionId: 'r1', ranges: [{ startRow: 0, endRow: 5, startColumn: 0, endColumn: 5 }] }],+ selections: [{ range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 } }],+ });++ expect(await firstValue(getBaseRangeMenuHidden$(accessor))).toBe(true);+ expect(await firstValue(getInsertAfterMenuHidden$(accessor, 'row'))).toBe(true);+ expect(await firstValue(getInsertBeforeMenuHidden$(accessor, 'col'))).toBe(true);+ expect(await firstValue(getDeleteMenuHidden$(accessor, 'row'))).toBe(true);+ expect(await firstValue(getCellMenuHidden$(accessor, 'col'))).toBe(true);+ });++ it('computes workbook-permission disable with protection rules', async () => {+ const noWorkbookAccessor = createAccessor([+ [IUniverInstanceService, { getCurrentTypeOfUnit$: () => of(null) }],+ [WorksheetProtectionRuleModel, { getRule: () => null }],+ [RangeProtectionRuleModel, { getSubunitRuleList: () => [] }],+ [IPermissionService, { composePermission$: () => of([{ value: true }]) }],+ [UserManagerService, { currentUser$: of({ userID: 'u1' }) }],+ ]);+ expect(await firstValue(getWorkbookPermissionDisable$(noWorkbookAccessor, [WorkbookEditablePermission]))).toBe(true);++ const hasWorksheetRuleAccessor = createMenuAccessor({+ composePermissionAllTrue: true,+ worksheetRule: { permissionId: 'sheet-rule' },+ });+ expect(await firstValue(getWorkbookPermissionDisable$(hasWorksheetRuleAccessor, [WorkbookEditablePermission]))).toBe(true);++ const enabledAccessor = createMenuAccessor({+ composePermissionAllTrue: true,+ worksheetRule: null,+ subUnitRules: [],+ });+ expect(await firstValue(getWorkbookPermissionDisable$(enabledAccessor, [WorkbookEditablePermission]))).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/permission-menu-util.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/permission-menu-util.spec.tsnew file mode 100644index 0000000000..6ac4fee83a--- /dev/null+++ b/packages/sheets-ui/src/controllers/menu/__tests__/permission-menu-util.spec.ts@@ -0,0 +1,344 @@+/**+ * 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 {+ FOCUSING_COMMON_DRAWINGS,+ FOCUSING_FX_BAR_EDITOR,+ IContextService,+ IPermissionService,+ IUniverInstanceService,+ RANGE_TYPE,+ UserManagerService,+} from '@univerjs/core';+import {+ RangeProtectionCache,+ RangeProtectionRuleModel,+ SheetsSelectionsService,+ UnitAction,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';+import { BehaviorSubject, firstValueFrom, of, skip, take } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { IEditorBridgeService } from '../../../services/editor-bridge.service';+import {+ getAddPermissionDisableBase$,+ getAddPermissionFromSheetBarDisable$,+ getAddPermissionHidden$,+ getEditPermissionHidden$,+ getPermissionDisableBase$,+ getRemovePermissionDisable$,+ getRemovePermissionFromSheetBarDisable$,+ getSetPermissionFromSheetBarDisable$,+ getViewPermissionDisable$,+} from '../permission-menu-util';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ has(token: unknown) {+ return map.has(token);+ },+ } as any;+}++function firstValue<T>(obs: { pipe: (...args: any[]) => any }) {+ return firstValueFrom(obs.pipe(take(1)));+}++interface IMockOption {+ workbook: any;+ worksheet: any;+ selections?: any[] | undefined;+ subUnitRules?: any[];+ worksheetRule?: any;+ permissionAllTrue?: boolean;+ permissionPointValue?: boolean;+ formulaEditorFocus?: boolean;+ focusingDrawing?: boolean;+ editorVisible?: any;+ hasEditorBridge?: boolean;+ cellInfoByCoord?: Record<string, Record<string, boolean>>;+}++function createPermissionAccessor(option: Partial<IMockOption> = {}) {+ const worksheet = option.worksheet ?? { getSheetId: () => 'sheet-1' };+ const workbook = option.workbook ?? { getUnitId: () => 'unit-1', activeSheet$: of(worksheet) };+ const selections = option.selections;++ const selectionMoveEnd$ = new BehaviorSubject(null);+ const selectionService = {+ selectionMoveEnd$,+ getCurrentSelections: () => selections,+ };++ const subUnitRules = option.subUnitRules ?? [];+ const rangeProtectionRuleModel = {+ ruleChange$: new BehaviorSubject(null),+ getSubunitRuleList: () => subUnitRules,+ };++ const worksheetRule = option.worksheetRule ?? null;+ const worksheetProtectionRuleModel = {+ ruleChange$: new BehaviorSubject(null),+ getRule: () => worksheetRule,+ };++ const permissionAllTrue = option.permissionAllTrue ?? true;+ const permissionPointValue = option.permissionPointValue ?? true;+ const permissionService = {+ composePermission$: (ids: string[]) => of(ids.map(() => ({ value: permissionAllTrue }))),+ getPermissionPoint: () => ({ value: permissionPointValue }),+ getPermissionPoint$: () => of({ value: permissionPointValue }),+ };++ const formulaEditorFocus = option.formulaEditorFocus ?? false;+ const focusingDrawing = option.focusingDrawing ?? false;+ const contextService = {+ subscribeContextValue$: (key: unknown) => {+ if (key === FOCUSING_FX_BAR_EDITOR) {+ return of(formulaEditorFocus);+ }+ if (key === FOCUSING_COMMON_DRAWINGS) {+ return of(focusingDrawing);+ }+ return of(false);+ },+ };++ const cellInfoByCoord = option.cellInfoByCoord ?? {};+ const rangeProtectionCache = {+ getCellInfo: (_unitId: string, _subUnitId: string, row: number, col: number) => {+ return cellInfoByCoord[`${row},${col}`] ?? null;+ },+ };++ const pairs: Array<[unknown, unknown]> = [+ [IUniverInstanceService, { getCurrentTypeOfUnit$: () => of(workbook) }],+ [UserManagerService, { currentUser$: of({ userID: 'u1' }) }],+ [SheetsSelectionsService, selectionService],+ [RangeProtectionRuleModel, rangeProtectionRuleModel],+ [WorksheetProtectionRuleModel, worksheetProtectionRuleModel],+ [IPermissionService, permissionService],+ [IContextService, contextService],+ [RangeProtectionCache, rangeProtectionCache],+ ];++ if (option.hasEditorBridge) {+ pairs.push([IEditorBridgeService, { visible$: of(option.editorVisible ?? null) }]);+ }++ return createAccessor(pairs);+}++describe('permission-menu-util', () => {+ it('computes add-permission hidden by worksheet rule or range overlap', async () => {+ const overlapAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ subUnitRules: [{ ranges: [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }] }],+ });+ expect(await firstValue(getAddPermissionHidden$(overlapAccessor))).toBe(true);++ const worksheetRuleAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 } }],+ worksheetRule: { permissionId: 'sheet-permission' },+ subUnitRules: [],+ });+ expect(await firstValue(getAddPermissionHidden$(worksheetRuleAccessor))).toBe(true);++ const emptySelectionAccessor = createPermissionAccessor({+ selections: undefined,+ subUnitRules: [{ ranges: [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }] }],+ });+ expect(await firstValue(getAddPermissionHidden$(emptySelectionAccessor))).toBe(false);+ });++ it('computes edit-permission hidden with selection/rule/cell-action checks', async () => {+ const multiSelectionAccessor = createPermissionAccessor({+ selections: [+ { range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },+ { range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 } },+ ],+ });+ expect(await firstValue(getEditPermissionHidden$(multiSelectionAccessor))).toBe(true);++ const worksheetRuleAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ worksheetRule: { permissionId: 'sheet-rule' },+ permissionPointValue: false,+ });+ expect(await firstValue(getEditPermissionHidden$(worksheetRuleAccessor))).toBe(true);++ const blockedByCellAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ subUnitRules: [{ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }] }],+ cellInfoByCoord: { '1,1': { [UnitAction.ManageCollaborator]: false } },+ });+ expect(await firstValue(getEditPermissionHidden$(blockedByCellAccessor))).toBe(true);++ const allowedCellAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ subUnitRules: [{ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }] }],+ cellInfoByCoord: { '1,1': { [UnitAction.ManageCollaborator]: true } },+ });+ expect(await firstValue(getEditPermissionHidden$(allowedCellAccessor))).toBe(false);+ });++ it('computes base permission disable with permission result and selection count', async () => {+ const noPermissionAccessor = createPermissionAccessor({+ permissionAllTrue: false,+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ });+ expect(await firstValue(getPermissionDisableBase$(noPermissionAccessor))).toBe(true);++ const oneSelectionAccessor = createPermissionAccessor({+ permissionAllTrue: true,+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ });+ expect(await firstValue(getPermissionDisableBase$(oneSelectionAccessor))).toBe(false);++ const multiSelectionAccessor = createPermissionAccessor({+ permissionAllTrue: true,+ selections: [+ { range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },+ { range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 } },+ ],+ });+ expect(await firstValue(getPermissionDisableBase$(multiSelectionAccessor))).toBe(true);+ });++ it('computes add-permission disable base with editor/drawing/overlap checks', async () => {+ const editorVisibleAccessor = createPermissionAccessor({+ hasEditorBridge: true,+ editorVisible: { visible: true, unitId: 'unit-1' },+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ });+ expect(await firstValue(getAddPermissionDisableBase$(editorVisibleAccessor))).toBe(true);++ const focusingDrawingAccessor = createPermissionAccessor({+ focusingDrawing: true,+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ permissionAllTrue: true,+ });+ expect(await firstValueFrom(getAddPermissionDisableBase$(focusingDrawingAccessor).pipe(skip(1), take(1)))).toBe(true);++ const enabledAccessor = createPermissionAccessor({+ permissionAllTrue: true,+ selections: [{ range: { startRow: 5, endRow: 5, startColumn: 5, endColumn: 5 } }],+ subUnitRules: [{ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] }],+ });+ expect(await firstValue(getAddPermissionDisableBase$(enabledAccessor))).toBe(false);+ });++ it('computes sheet-bar add/remove/set disable states', async () => {+ const addAllowedAccessor = createPermissionAccessor({+ permissionAllTrue: true,+ subUnitRules: [{ permissionId: undefined }],+ });+ expect(await firstValue(getAddPermissionFromSheetBarDisable$(addAllowedAccessor))).toBe(false);++ const addDisabledAccessor = createPermissionAccessor({+ permissionAllTrue: true,+ subUnitRules: [{ permissionId: 'r1' }],+ });+ expect(await firstValue(getAddPermissionFromSheetBarDisable$(addDisabledAccessor))).toBe(true);++ const removeNoRuleAccessor = createPermissionAccessor({+ worksheetRule: null,+ });+ expect(await firstValue(getRemovePermissionFromSheetBarDisable$(removeNoRuleAccessor))).toBe(true);++ const removeWithRuleAccessor = createPermissionAccessor({+ worksheetRule: { permissionId: 'sheet-rule' },+ permissionPointValue: true,+ });+ expect(await firstValue(getRemovePermissionFromSheetBarDisable$(removeWithRuleAccessor))).toBe(false);++ const setDisabledAccessor = createPermissionAccessor({+ permissionAllTrue: false,+ subUnitRules: [],+ });+ expect(await firstValue(getSetPermissionFromSheetBarDisable$(setDisabledAccessor))).toBe(true);++ const setEnabledAccessor = createPermissionAccessor({+ permissionAllTrue: true,+ worksheetRule: { permissionId: 'sheet-rule' },+ });+ expect(await firstValue(getSetPermissionFromSheetBarDisable$(setEnabledAccessor))).toBe(false);+ });++ it('computes remove-permission disable from selection and permission detail', async () => {+ const noSelectionAccessor = createPermissionAccessor({+ selections: undefined,+ });+ expect(await firstValue(getRemovePermissionDisable$(noSelectionAccessor))).toBe(true);++ const rowSelectionAccessor = createPermissionAccessor({+ selections: [{+ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.ROW },+ }],+ });+ expect(await firstValue(getRemovePermissionDisable$(rowSelectionAccessor))).toBe(true);++ const worksheetRuleAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ worksheetRule: { permissionId: 'sheet-rule' },+ permissionPointValue: false,+ });+ expect(await firstValue(getRemovePermissionDisable$(worksheetRuleAccessor))).toBe(true);++ const blockedCellAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ subUnitRules: [{ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }] }],+ cellInfoByCoord: { '1,1': { [UnitAction.Delete]: false } },+ });+ expect(await firstValue(getRemovePermissionDisable$(blockedCellAccessor))).toBe(true);++ const allowedAccessor = createPermissionAccessor({+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } }],+ subUnitRules: [{ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }] }],+ cellInfoByCoord: { '1,1': { [UnitAction.Delete]: true } },+ });+ expect(await firstValue(getRemovePermissionDisable$(allowedAccessor))).toBe(false);+ });++ it('computes view-permission disable with workbook/editor/permission states', async () => {+ const noWorkbookAccessor = createAccessor([+ [IUniverInstanceService, { getCurrentTypeOfUnit$: () => of(null) }],+ [UserManagerService, { currentUser$: of({ userID: 'u1' }) }],+ [IPermissionService, { getPermissionPoint$: () => of({ value: true }) }],+ [IContextService, { subscribeContextValue$: () => of(false) }],+ ]);+ expect(await firstValue(getViewPermissionDisable$(noWorkbookAccessor))).toBe(true);++ const editorVisibleAccessor = createPermissionAccessor({+ hasEditorBridge: true,+ editorVisible: { visible: true, unitId: 'unit-1' },+ permissionPointValue: true,+ });+ expect(await firstValue(getViewPermissionDisable$(editorVisibleAccessor))).toBe(true);++ const allowedAccessor = createPermissionAccessor({+ permissionPointValue: true,+ });+ expect(await firstValue(getViewPermissionDisable$(allowedAccessor))).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/controllers/menu/__tests__/utils.spec.ts b/packages/sheets-ui/src/controllers/menu/__tests__/utils.spec.tsnew file mode 100644index 0000000000..dd278457e5--- /dev/null+++ b/packages/sheets-ui/src/controllers/menu/__tests__/utils.spec.ts@@ -0,0 +1,84 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { IEditorService } from '@univerjs/docs-ui';+import { describe, expect, it, vi } from 'vitest';+import { getFontStyleAtCursor } from '../utils';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('menu utils', () => {+ it('returns null when editor model or active range is missing', () => {+ const getUnit = vi.fn();+ getUnit.mockReturnValue(null);+ const getActiveTextRange = vi.fn();+ getActiveTextRange.mockReturnValue({ startOffset: 0, endOffset: 1 });+ const univerInstanceService = { getUnit };+ const textSelectionService = { getActiveTextRange };+ const editorService = { getFocusId: vi.fn(() => 'doc-1') };+ const accessor = createAccessor([+ [IUniverInstanceService, univerInstanceService],+ [DocSelectionManagerService, textSelectionService],+ [IEditorService, editorService],+ ]);++ expect(getFontStyleAtCursor(accessor)).toBeNull();++ getUnit.mockReturnValue({ getBody: () => ({ textRuns: [] }) });+ getActiveTextRange.mockReturnValue(null);+ expect(getFontStyleAtCursor(accessor)).toBeNull();+ });++ it('returns undefined when editor model body has no textRuns', () => {+ const accessor = createAccessor([+ [IUniverInstanceService, { getUnit: vi.fn(() => ({ getBody: () => ({}) })) }],+ [DocSelectionManagerService, { getActiveTextRange: vi.fn(() => ({ startOffset: 1, endOffset: 2 })) }],+ [IEditorService, { getFocusId: vi.fn(() => 'doc-1') }],+ ]);++ expect(getFontStyleAtCursor(accessor)).toBeUndefined();+ });++ it('uses default editor id and returns the text run at cursor', () => {+ const matchRun = { st: 10, ed: 20, ts: { bl: true } };+ const getUnit = vi.fn(() => ({+ getBody: () => ({+ textRuns: [{ st: 0, ed: 9 }, matchRun, { st: 21, ed: 30 }],+ }),+ }));++ const accessor = createAccessor([+ [IUniverInstanceService, { getUnit }],+ [DocSelectionManagerService, { getActiveTextRange: () => ({ startOffset: 12, endOffset: 18 }) }],+ [IEditorService, { getFocusId: () => undefined }],+ ]);++ expect(getFontStyleAtCursor(accessor)).toBe(matchRun);+ expect(getUnit).toHaveBeenCalledWith(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);+ });+});diff --git a/packages/sheets-ui/src/controllers/utils/__tests__/component-tools.spec.ts b/packages/sheets-ui/src/controllers/utils/__tests__/component-tools.spec.tsnew file mode 100644index 0000000000..080e7a31e8--- /dev/null+++ b/packages/sheets-ui/src/controllers/utils/__tests__/component-tools.spec.ts@@ -0,0 +1,149 @@+/**+ * 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 { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';+import { describe, expect, it, vi } from 'vitest';+import { SHEET_VIEW_KEY } from '../../../common/keys';+import { getCoordByCell, getCoordByOffset, getSheetObject, getTransformCoord } from '../component-tools';++function createSheetComponents() {+ const rowHeader = { id: 'row-header' };+ const columnHeader = { id: 'col-header' };+ const leftTop = { id: 'left-top' };+ const components = new Map<unknown, unknown>([+ [SHEET_VIEW_KEY.ROW, rowHeader],+ [SHEET_VIEW_KEY.COLUMN, columnHeader],+ [SHEET_VIEW_KEY.LEFT_TOP, leftTop],+ ]);++ return { components, rowHeader, columnHeader, leftTop };+}++describe('component tools', () => {+ it('getSheetObject returns null when no workbook or render is available', () => {+ const noWorkbookInstance = {+ getCurrentUnitForType: vi.fn(() => null),+ };+ const renderManager = {+ getRenderById: vi.fn(),+ };+ expect(getSheetObject(noWorkbookInstance as any, renderManager as any)).toBeNull();+ expect(renderManager.getRenderById).not.toHaveBeenCalled();++ const workbook = { getUnitId: () => 'unit-1' };+ const noRenderInstance = {+ getCurrentUnitForType: () => workbook,+ };+ expect(getSheetObject(noRenderInstance as any, renderManager as any)).toBeNull();+ expect(renderManager.getRenderById).toHaveBeenCalledWith('unit-1');+ });++ it('getSheetObject extracts spreadsheet components from render manager', () => {+ const workbook = { getUnitId: () => 'unit-1' };+ const { components, rowHeader, columnHeader, leftTop } = createSheetComponents();+ const render = {+ components,+ mainComponent: { id: 'spreadsheet' },+ scene: { id: 'scene' },+ engine: { id: 'engine' },+ };+ const instance = {+ getCurrentUnitForType: () => workbook,+ };+ const renderManager = {+ getRenderById: () => render,+ };++ const sheetObject = getSheetObject(instance as any, renderManager as any);+ expect(sheetObject).toEqual({+ spreadsheet: render.mainComponent,+ spreadsheetRowHeader: rowHeader,+ spreadsheetColumnHeader: columnHeader,+ spreadsheetLeftTopPlaceholder: leftTop,+ scene: render.scene,+ engine: render.engine,+ });+ });++ it('getSheetObject supports render context input', () => {+ const workbook = { getUnitId: () => 'unit-1' };+ const { components, rowHeader, columnHeader, leftTop } = createSheetComponents();+ const renderContext = {+ isMainScene: true,+ components,+ mainComponent: { id: 'spreadsheet' },+ scene: { id: 'scene' },+ engine: { id: 'engine' },+ };+ const instance = {+ getCurrentUnitForType: () => workbook,+ };++ const sheetObject = getSheetObject(instance as any, renderContext as any);+ expect(sheetObject?.spreadsheetRowHeader).toBe(rowHeader);+ expect(sheetObject?.spreadsheetColumnHeader).toBe(columnHeader);+ expect(sheetObject?.spreadsheetLeftTopPlaceholder).toBe(leftTop);+ });++ it('getCoordByCell returns cell coordinates from skeleton', () => {+ const getCellWithCoordByIndex = vi.fn(() => ({ startX: 1, startY: 2, endX: 3, endY: 4 }));+ const result = getCoordByCell(2, 3, {} as any, { getCellWithCoordByIndex } as any);++ expect(getCellWithCoordByIndex).toHaveBeenCalledWith(2, 3);+ expect(result).toEqual({ startX: 1, startY: 2, endX: 3, endY: 4 });+ });++ it('getCoordByOffset converts offsets to selected cell coordinates', () => {+ const scene = {+ getCoordRelativeToViewport: vi.fn(() => ({ x: 40, y: 60 })),+ getScrollXYInfoByViewport: vi.fn(() => ({ x: 6, y: 8 })),+ getAncestorScale: vi.fn(() => ({ scaleX: 2, scaleY: 4 })),+ };+ const skeleton = {+ getCellIndexByOffset: vi.fn(() => ({ row: 2, column: 3 })),+ getNoMergeCellWithCoordByIndex: vi.fn(() => ({ startX: 10, startY: 20, endX: 30, endY: 40 })),+ };++ const result = getCoordByOffset(100, 120, scene as any, skeleton as any, { id: 'vp' } as any, true);++ expect(skeleton.getCellIndexByOffset).toHaveBeenCalledWith(40, 60, 2, 4, { x: 6, y: 8 }, { closeFirst: true });+ expect(skeleton.getNoMergeCellWithCoordByIndex).toHaveBeenCalledWith(2, 3);+ expect(result).toEqual({+ row: 2,+ column: 3,+ startX: 10,+ startY: 20,+ endX: 30,+ endY: 40,+ });+ });++ it('getTransformCoord applies scroll and scale conversion', () => {+ const viewMain = { id: 'view-main' };+ const scene = {+ getCoordRelativeToViewport: vi.fn(() => ({ x: 11, y: 22 })),+ getViewport: vi.fn(() => viewMain),+ getScrollXYInfoByViewport: vi.fn(() => ({ x: 5, y: 7 })),+ getAncestorScale: vi.fn(() => ({ scaleX: 2, scaleY: 4 })),+ };++ const result = getTransformCoord(100, 40, scene as any, {} as any);++ expect(scene.getViewport).toHaveBeenCalledWith(SHEET_VIEWPORT_KEY.VIEW_MAIN);+ expect(scene.getScrollXYInfoByViewport).toHaveBeenCalledWith({ x: 11, y: 22 }, viewMain);+ expect(result).toEqual({ x: 55, y: 17 });+ });+});diff --git a/packages/sheets-ui/src/controllers/utils/__tests__/range-tools.spec.ts b/packages/sheets-ui/src/controllers/utils/__tests__/range-tools.spec.tsnew file mode 100644index 0000000000..be01327aab--- /dev/null+++ b/packages/sheets-ui/src/controllers/utils/__tests__/range-tools.spec.ts@@ -0,0 +1,41 @@+/**+ * 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 { virtualizeDiscreteRanges } from '../range-tools';++describe('range-tools', () => {+ it('should virtualize sparse discrete ranges and provide reverse mapping', () => {+ const { ranges, mapFunc } = virtualizeDiscreteRanges([+ {+ rows: [5, 7],+ cols: [10, 20],+ },+ {+ rows: [7, 9],+ cols: [20, 30],+ },+ ] as any);++ expect(ranges).toEqual([+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ ]);++ expect(mapFunc(0, 0)).toEqual({ row: 5, col: 10 });+ expect(mapFunc(2, 2)).toEqual({ row: 9, col: 30 });+ });+});diff --git a/packages/sheets-ui/src/controllers/utils/__tests__/selections-tools.spec.ts b/packages/sheets-ui/src/controllers/utils/__tests__/selections-tools.spec.tsnew file mode 100644index 0000000000..efacd0d298--- /dev/null+++ b/packages/sheets-ui/src/controllers/utils/__tests__/selections-tools.spec.ts@@ -0,0 +1,177 @@+/**+ * 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 { IUniverInstanceService, RANGE_TYPE } from '@univerjs/core';+import { MergeCellController, RangeProtectionRuleModel, SheetsSelectionsService } from '@univerjs/sheets';+import { BehaviorSubject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { getSheetSelectionsDisabled$, isThisColSelected, isThisRowSelected, matchedSelectionByRowColIndex } from '../selections-tools';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ const result = map.get(token);+ if (result == null) {+ throw new Error(`Missing token: ${String(token)}`);+ }+ return result;+ },+ } as any;+}++describe('selections tools', () => {+ it('detects selected rows/columns by range type and index', () => {+ const selections = [+ {+ range: {+ startRow: 1,+ endRow: 3,+ startColumn: 0,+ endColumn: 999,+ rangeType: RANGE_TYPE.ROW,+ },+ },+ {+ range: {+ startRow: 0,+ endRow: 999,+ startColumn: 4,+ endColumn: 6,+ rangeType: RANGE_TYPE.COLUMN,+ },+ },+ {+ range: {+ startRow: 0,+ endRow: 2,+ startColumn: 0,+ endColumn: 2,+ rangeType: RANGE_TYPE.NORMAL,+ },+ },+ {+ range: {+ startRow: 0,+ endRow: 999,+ startColumn: 0,+ endColumn: 999,+ rangeType: RANGE_TYPE.ALL,+ },+ },+ ] as any;++ expect(isThisRowSelected(selections, 2)).toBe(true);+ expect(isThisRowSelected(selections, 6)).toBe(false);+ expect(isThisColSelected(selections, 5)).toBe(true);+ expect(isThisColSelected(selections, 8)).toBe(false);++ expect(matchedSelectionByRowColIndex(selections, 2, RANGE_TYPE.ROW)).toBe(selections[0]);+ expect(matchedSelectionByRowColIndex(selections, 5, RANGE_TYPE.COLUMN)).toBe(selections[1]);+ expect(matchedSelectionByRowColIndex(selections, 1, RANGE_TYPE.COLUMN)).toBeUndefined();+ });++ it('computes disabled state from sheet/range/interceptor situations', () => {+ const workbook$ = new BehaviorSubject<any>(null);+ const selectionMoveEnd$ = new BehaviorSubject<any>(null);+ const activeSheet$ = new BehaviorSubject<any>(null);++ const workbook = {+ getUnitId: () => 'unit-1',+ activeSheet$,+ };+ const sheet = {+ getSheetId: () => 'sheet-1',+ };++ let interceptorDisabled = false;+ let protectedRanges: any[] = [];++ const mergeCellController = {+ interceptor: {+ fetchThroughInterceptors: vi.fn(() => vi.fn(() => interceptorDisabled)),+ },+ };++ const accessor = createAccessor([+ [SheetsSelectionsService, { selectionMoveEnd$ }],+ [RangeProtectionRuleModel, { getSubunitRuleList: vi.fn(() => [{ ranges: protectedRanges }]) }],+ [IUniverInstanceService, { getCurrentTypeOfUnit$: vi.fn(() => workbook$) }],+ [MergeCellController, mergeCellController],+ ]);++ const values: boolean[] = [];+ const subscription = getSheetSelectionsDisabled$(accessor).subscribe((v) => values.push(v));++ expect(values.at(-1)).toBe(false);++ workbook$.next(workbook);+ expect(values.at(-1)).toBe(false);++ activeSheet$.next(sheet);+ expect(values.at(-1)).toBe(false);++ selectionMoveEnd$.next([]);+ expect(values.at(-1)).toBe(false);++ interceptorDisabled = true;+ selectionMoveEnd$.next([+ {+ range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 },+ },+ ]);+ expect(values.at(-1)).toBe(true);++ interceptorDisabled = false;+ protectedRanges = [{ startRow: 2, endRow: 3, startColumn: 2, endColumn: 3 }];+ selectionMoveEnd$.next([+ {+ range: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 4 },+ },+ ]);+ expect(values.at(-1)).toBe(true);++ protectedRanges = [{ startRow: 1, endRow: 9, startColumn: 1, endColumn: 9 }];+ selectionMoveEnd$.next([+ {+ range: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 4 },+ },+ ]);+ expect(values.at(-1)).toBe(false);++ selectionMoveEnd$.next([+ {+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ },+ {+ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ },+ ]);+ expect(values.at(-1)).toBe(true);++ selectionMoveEnd$.next([+ {+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ },+ {+ range: { startRow: 3, endRow: 3, startColumn: 3, endColumn: 3 },+ },+ ]);+ expect(values.at(-1)).toBe(false);++ subscription.unsubscribe();+ });+});diff --git a/packages/sheets-ui/src/facade/__tests__/f-event.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-event.spec.tsnew file mode 100644index 0000000000..b930a4d5c9--- /dev/null+++ b/packages/sheets-ui/src/facade/__tests__/f-event.spec.ts@@ -0,0 +1,71 @@+/**+ * 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 { FEventName } from '@univerjs/core/facade';+import { describe, expect, it } from 'vitest';+import { CellFEventName, FSheetsUIEventName } from '../f-event';++describe('FSheetsUIEventName', () => {+ it('returns stable event keys for sheet-ui events', () => {+ const events = new FSheetsUIEventName();++ expect(events.BeforeClipboardChange).toBe('BeforeClipboardChange');+ expect(events.ClipboardChanged).toBe('ClipboardChanged');+ expect(events.BeforeClipboardPaste).toBe('BeforeClipboardPaste');+ expect(events.ClipboardPasted).toBe('ClipboardPasted');+ expect(events.BeforeSheetEditStart).toBe('BeforeSheetEditStart');+ expect(events.SheetEditStarted).toBe('SheetEditStarted');+ expect(events.SheetEditChanging).toBe('SheetEditChanging');+ expect(events.BeforeSheetEditEnd).toBe('BeforeSheetEditEnd');+ expect(events.SheetEditEnded).toBe('SheetEditEnded');++ expect(events.CellClicked).toBe(CellFEventName.CellClicked);+ expect(events.CellPointerDown).toBe(CellFEventName.CellPointerDown);+ expect(events.CellPointerUp).toBe(CellFEventName.CellPointerUp);+ expect(events.CellPointerMove).toBe(CellFEventName.CellPointerMove);+ expect(events.CellHover).toBe(CellFEventName.CellHover);++ expect(events.RowHeaderClick).toBe('RowHeaderClick');+ expect(events.RowHeaderPointerDown).toBe('RowHeaderPointerDown');+ expect(events.RowHeaderPointerUp).toBe('RowHeaderPointerUp');+ expect(events.RowHeaderHover).toBe('RowHeaderHover');+ expect(events.ColumnHeaderClick).toBe('ColumnHeaderClick');+ expect(events.ColumnHeaderPointerDown).toBe('ColumnHeaderPointerDown');+ expect(events.ColumnHeaderPointerUp).toBe('ColumnHeaderPointerUp');+ expect(events.ColumnHeaderHover).toBe('ColumnHeaderHover');++ expect(events.DragOver).toBe('DragOver');+ expect(events.Drop).toBe('Drop');+ expect(events.Scroll).toBe('Scroll');+ expect(events.SelectionMoveStart).toBe('SelectionMoveStart');+ expect(events.SelectionMoving).toBe('SelectionMoving');+ expect(events.SelectionMoveEnd).toBe('SelectionMoveEnd');+ expect(events.SelectionChanged).toBe('SelectionChanged');+ expect(events.BeforeSheetZoomChange).toBe('BeforeSheetZoomChange');+ expect(events.SheetZoomChanged).toBe('SheetZoomChanged');+ expect(events.SheetSkeletonChanged).toBe('SheetSkeletonChanged');+ });++ it('extends core FEventName with sheet-ui event accessors', () => {+ const mixed = new (FEventName as any)();++ expect(mixed.BeforeClipboardChange).toBe('BeforeClipboardChange');+ expect(mixed.ClipboardChanged).toBe('ClipboardChanged');+ expect(mixed.CellClicked).toBe('CellClicked');+ expect(mixed.SelectionChanged).toBe('SelectionChanged');+ expect(mixed.SheetZoomChanged).toBe('SheetZoomChanged');+ });+});diff --git a/packages/sheets-ui/src/facade/__tests__/f-range.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-range.spec.tsindex 82ccd6dc6c..96a8593740 100644--- a/packages/sheets-ui/src/facade/__tests__/f-range.spec.ts+++ b/packages/sheets-ui/src/facade/__tests__/f-range.spec.ts@@ -14,48 +14,272 @@* limitations under the License.*/-/* eslint-disable ts/no-non-null-asserted-optional-chain */+import { ILogService, RANGE_TYPE } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { CellAlertManagerService, CellAlertType, IMarkSelectionService, ISheetCellDropdownManagerService, ISheetClipboardService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { FRange } from '@univerjs/sheets/facade';+import { ComponentManager } from '@univerjs/ui';+import { describe, expect, it, vi } from 'vitest';+import { transformComponentKey } from '../f-range';-import type { FUniver } from '@univerjs/core/facade';-import { LifecycleStages } from '@univerjs/core';-import { beforeEach, describe, expect, it } from 'vitest';-import { createFacadeTestBed } from './create-test-bed';-import '@univerjs/sheets/facade';+function createFakeRange() {+ const tokens = new Map<unknown, unknown>();-describe('Test FRange', () => {- let univerAPI: FUniver;+ const range: any = {+ _range: {+ startRow: 1,+ startColumn: 2,+ endRow: 3,+ endColumn: 4,+ },+ _workbook: {+ getUnitId: () => 'unit-1',+ },+ _worksheet: {+ getSheetId: () => 'sheet-1',+ },+ getUnitId: () => 'unit-1',+ };- beforeEach(() => {- const testBed = createFacadeTestBed();+ range._injector = {+ get(token: unknown) {+ if (!tokens.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return tokens.get(token);+ },+ };++ // Methods call each other through `this`, so we bind prototype methods manually.+ range.getCell = (FRange.prototype as any).getCell;++ return { range, tokens };+}++describe('FRange UI mixin', () => {+ it('transforms component key for string and external component', () => {+ const registerDisposable = { dispose: vi.fn() };+ const componentManager = {+ register: vi.fn(() => registerDisposable),+ };- univerAPI = testBed.univerAPI;+ const stringResult = transformComponentKey({ componentKey: 'built-in-key' }, componentManager as any);+ expect(stringResult.key).toBe('built-in-key');+ stringResult.disposableCollection.dispose();+ expect(componentManager.register).not.toHaveBeenCalled();++ const componentResult = transformComponentKey(+ { componentKey: () => null, isVue3: true },+ componentManager as any+ );+ expect(componentResult.key.startsWith('External_')).toBe(true);+ expect(componentManager.register).toHaveBeenCalledWith(+ componentResult.key,+ expect.any(Function),+ { framework: 'vue3' }+ );+ componentResult.disposableCollection.dispose();+ expect(registerDisposable.dispose).toHaveBeenCalled();});- it('Range getCell', () => {- univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {- if (stage === LifecycleStages.Steady) {- const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();- const range = activeSheet?.getRange(2, 3);- const cell = range?.getCell()!;- expect(cell.actualColumn).toBe(3);- expect(cell.actualRow).toBe(2);- }+ it('gets cell/cellRect and throws when skeleton is unavailable', () => {+ const { range, tokens } = createFakeRange();+ const cellWithCoord = {+ startRow: 1,+ startColumn: 2,+ endRow: 1,+ endColumn: 2,+ startX: 8,+ startY: 12,+ endX: 28,+ endY: 42,+ actualRow: 1,+ actualColumn: 2,+ };++ const skeleton = {+ getCellWithCoordByIndex: vi.fn(() => cellWithCoord),+ };+ const logService = { error: vi.fn() };+ const render = {+ with: vi.fn(() => ({+ getSkeletonParam: vi.fn(() => ({ skeleton })),+ })),+ };+ const renderManager: any = {+ getRenderById: vi.fn(() => render),+ };++ tokens.set(IRenderManagerService, renderManager);+ tokens.set(ILogService, logService);++ const getCell = (FRange.prototype as any).getCell;+ const getCellRect = (FRange.prototype as any).getCellRect;++ expect(getCell.call(range)).toEqual(cellWithCoord);+ const rect = getCellRect.call(range);+ expect(rect).toMatchObject({+ x: 8,+ y: 12,+ width: 20,+ height: 30,+ top: 12,+ left: 8,+ bottom: 42,+ right: 28,});+ expect(typeof rect.toJSON).toBe('function');++ renderManager.getRenderById = vi.fn(() => ({+ with: vi.fn(() => ({+ getSkeletonParam: vi.fn(() => null),+ })),+ }));+ expect(() => getCell.call(range)).toThrowError('`FRange.getCell` can only be called in current worksheet');+ expect(logService.error).toHaveBeenCalled();});- it('Range getCellRect', () => {- univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {- if (stage === LifecycleStages.Steady) {- const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();- const range = activeSheet?.getRange(0, 0);- const cell = range?.getCell()!;- const rect = range?.getCellRect()!;- expect(rect.x).toBe(cell.startX);- expect(rect.y).toBe(cell.startY);- expect(rect.width).toBe(cell.endX - cell.startX);- expect(rect.height).toBe(cell.endY - cell.startY);- expect(rect.toJSON()).toContain(rect.height);- }+ it('generates html and manages popup/alert/highlight/dropdown lifecycle', () => {+ const { range, tokens } = createFakeRange();++ const clipboardService = {+ generateCopyContent: vi+ .fn()+ .mockReturnValueOnce({ html: '<b>copied</b>' })+ .mockReturnValueOnce(undefined),+ };+ tokens.set(ISheetClipboardService, clipboardService);++ const popupDisposable = { dispose: vi.fn() };+ const registerDisposable = { dispose: vi.fn() };+ const componentManager = {+ register: vi.fn(() => registerDisposable),+ };+ const canvasPopupService = {+ attachPopupToCell: vi+ .fn()+ .mockReturnValueOnce(popupDisposable)+ .mockReturnValueOnce(null),+ attachRangePopup: vi.fn().mockReturnValueOnce(popupDisposable),+ };+ tokens.set(ComponentManager, componentManager);+ tokens.set(SheetCanvasPopManagerService, canvasPopupService);++ const cellAlertService = {+ showAlert: vi.fn(),+ removeAlert: vi.fn(),+ };+ tokens.set(CellAlertManagerService, cellAlertService);++ const markSelectionService = {+ addShape: vi.fn().mockReturnValueOnce('shape-1').mockReturnValueOnce(null),+ removeShape: vi.fn(),+ };+ tokens.set(IMarkSelectionService, markSelectionService);++ const dropdownDisposable = { dispose: vi.fn() };+ const dropdownService = {+ showDropdown: vi.fn(() => dropdownDisposable),+ };+ tokens.set(ISheetCellDropdownManagerService, dropdownService);++ const generateHTML = (FRange.prototype as any).generateHTML;+ expect(generateHTML.call(range)).toBe('<b>copied</b>');+ expect(generateHTML.call(range)).toBe('');+ expect(clipboardService.generateCopyContent).toHaveBeenCalledWith('unit-1', 'sheet-1', range._range);++ const attachPopup = (FRange.prototype as any).attachPopup;+ const popupCollection = attachPopup.call(range, { componentKey: () => null });+ expect(canvasPopupService.attachPopupToCell).toHaveBeenCalledWith(+ 1,+ 2,+ expect.objectContaining({+ direction: 'horizontal',+ offset: [0, 0],+ componentKey: expect.stringMatching(/^External_/),+ extraProps: {},+ }),+ 'unit-1',+ 'sheet-1'+ );+ expect(popupCollection).toBeTruthy();+ popupCollection.dispose();+ expect(popupDisposable.dispose).toHaveBeenCalled();+ expect(registerDisposable.dispose).toHaveBeenCalled();++ const popupNull = attachPopup.call(range, { componentKey: () => null });+ expect(popupNull).toBeNull();++ const attachRangePopup = (FRange.prototype as any).attachRangePopup;+ const rangePopup = attachRangePopup.call(range, { componentKey: 'popup-key' });+ expect(canvasPopupService.attachRangePopup).toHaveBeenCalledWith(+ range._range,+ expect.objectContaining({+ direction: 'top-center',+ offset: [0, 0],+ componentKey: 'popup-key',+ }),+ 'unit-1',+ 'sheet-1'+ );+ rangePopup.dispose();++ const attachAlertPopup = (FRange.prototype as any).attachAlertPopup;+ const alertDisposable = attachAlertPopup.call(range, {+ key: 'alert-1',+ title: 'Title',+ message: 'Message',+ type: CellAlertType.WARNING,+ width: 120,+ height: 60,});+ expect(cellAlertService.showAlert).toHaveBeenCalledWith(+ expect.objectContaining({+ key: 'alert-1',+ location: expect.objectContaining({+ row: 1,+ col: 2,+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ }),+ })+ );+ alertDisposable.dispose();+ expect(cellAlertService.removeAlert).toHaveBeenCalledWith('alert-1');++ const highlight = (FRange.prototype as any).highlight;+ const highlightDisposable = highlight.call(+ range,+ { stroke: '#f00' },+ {+ startRow: 1,+ startColumn: 2,+ endRow: 1,+ endColumn: 2,+ actualRow: 1,+ actualColumn: 2,+ isMerged: false,+ isMergedMainCell: true,+ startX: 8,+ startY: 12,+ endX: 28,+ endY: 42,+ rangeType: RANGE_TYPE.NORMAL,+ }+ );+ expect(markSelectionService.addShape).toHaveBeenCalledWith(+ expect.objectContaining({+ range: range._range,+ })+ );+ highlightDisposable.dispose();+ expect(markSelectionService.removeShape).toHaveBeenCalledWith('shape-1');+ expect(() => highlight.call(range)).toThrowError('Failed to highlight current range');++ const showDropdown = (FRange.prototype as any).showDropdown;+ const dd = showDropdown.call(range, { type: 'list', props: { options: [] } });+ expect(dropdownService.showDropdown).toHaveBeenCalledWith({ type: 'list', props: { options: [] } });+ dd.dispose();+ expect(dropdownDisposable.dispose).toHaveBeenCalled();});});diff --git a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.tsnew file mode 100644index 0000000000..1afc8b76dc--- /dev/null+++ b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts@@ -0,0 +1,109 @@+/**+ * 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 { ICommandService, IPermissionService } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { EditorService, IEditorService } from '@univerjs/docs-ui';+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';+import { IRefSelectionsService, RefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';+import { EditorBridgeService, IEditorBridgeService, ISheetClipboardService, SheetPasteShortKeyCommand, SheetPermissionRenderManagerService } from '@univerjs/sheets-ui';+import { IClipboardInterfaceService } from '@univerjs/ui';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createFacadeTestBed } from './create-test-bed';+import '../f-univer';++describe('Test FUniver UI mixin', () => {+ const clipboardService = {+ generateCopyContent: vi.fn(() => ({ html: '<b>a</b>', plain: 'a' })),+ };++ const renderPermissionService = {+ setProtectedRangeShadowStrategy: vi.fn(),+ getProtectedRangeShadowStrategy: vi.fn(() => 'always' as const),+ getProtectedRangeShadowStrategy$: vi.fn(() => ({ subscribe: vi.fn() })),+ };++ const clipboardInterfaceService = {+ read: vi.fn(async () => []),+ };++ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should handle common facade methods and clipboard internals', async () => {+ const testBed = createFacadeTestBed(undefined, [+ [ISheetClipboardService, { useValue: clipboardService }],+ [SheetPermissionRenderManagerService, { useValue: renderPermissionService }],+ [IClipboardInterfaceService, { useValue: clipboardInterfaceService }],+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);++ const univerAPI = testBed.univerAPI as any;+ const commandService = testBed.get(ICommandService);+ const sheet = testBed.univerAPI.getActiveWorkbook()!.getActiveSheet();+ const activeWorkbookMock = {+ getId: () => 'test',+ getActiveSheet: () => sheet,+ getActiveRange: () => ({ getRange: () => ({ startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 }) }),+ };+ vi.spyOn(univerAPI, 'getActiveWorkbook').mockReturnValue(activeWorkbookMock as never);++ const executeSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as never);+ await expect(testBed.univerAPI.pasteIntoSheet('<i>x</i>', 'x')).resolves.toBe(true);+ expect(executeSpy).toHaveBeenCalledWith(SheetPasteShortKeyCommand.id, {+ htmlContent: '<i>x</i>',+ textContent: 'x',+ files: undefined,+ });++ testBed.univerAPI.setProtectedRangeShadowStrategy('none');+ expect(renderPermissionService.setProtectedRangeShadowStrategy).toHaveBeenCalledWith('none');+ expect(testBed.univerAPI.getProtectedRangeShadowStrategy()).toBe('always');+ expect(testBed.univerAPI.getProtectedRangeShadowStrategy$()).toBeTruthy();++ const permissionService = testBed.get(IPermissionService);+ const setShowComponentsSpy = vi.spyOn(permissionService, 'setShowComponents');+ testBed.univerAPI.setPermissionDialogVisible(false);+ expect(setShowComponentsSpy).toHaveBeenCalledWith(false);++ const copyParams = univerAPI._generateClipboardCopyParam();+ expect(copyParams?.text).toBe('a');+ expect(copyParams?.html).toBe('<b>a</b>');++ const pasteParams = univerAPI._generateClipboardPasteParam({ htmlContent: '<p>1</p>', textContent: '1' });+ expect(pasteParams?.text).toBe('1');+ expect(pasteParams?.html).toBe('<p>1</p>');++ const fireEventSpy = vi.spyOn(univerAPI, 'fireEvent');+ univerAPI._beforeClipboardPaste({ htmlContent: '<p>2</p>', textContent: '2' });+ univerAPI._clipboardPaste({ htmlContent: '<p>3</p>', textContent: '3' });+ expect(fireEventSpy).toHaveBeenCalled();++ await expect(univerAPI._generateClipboardPasteParamAsync()).resolves.toBeUndefined();+ await expect(univerAPI._beforeClipboardPasteAsync()).resolves.toBeUndefined();+ await expect(univerAPI._clipboardPasteAsync()).resolves.toBeUndefined();++ const eventTypes = fireEventSpy.mock.calls.map((i) => i[0]);+ expect(eventTypes.includes(univerAPI.Event.BeforeClipboardPaste)).toBe(true);+ expect(eventTypes.includes(univerAPI.Event.ClipboardPasted)).toBe(true);+ });+});diff --git a/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.tsnew file mode 100644index 0000000000..bd43cc9a7a--- /dev/null+++ b/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.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 { ICommandService } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { EditorService, IEditorService } from '@univerjs/docs-ui';+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';+import { IRefSelectionsService, RefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';+import { describe, expect, it, vi } from 'vitest';+import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';+import { EditorBridgeService, IEditorBridgeService } from '../../services/editor-bridge.service';+import { createFacadeTestBed } from './create-test-bed';+import '../f-workbook';+import '../f-worksheet';++describe('Test FWorkbook/FWorksheet UI mixin', () => {+ it('workbook and worksheet api basic flows', async () => {+ const testBed = createFacadeTestBed(undefined, [+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);++ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet()!;+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(SetCellEditVisibleOperation);++ const startResult = workbook.startEditing();+ expect(startResult).toBe(true);+ expect(workbook.isCellEditing()).toBe(true);++ await workbook.endEditingAsync(true);+ expect(workbook.isCellEditing()).toBe(false);++ await workbook.abortEditingAsync();++ const scrollState = workbook.getScrollStateBySheetId(worksheet.getSheetId());+ expect(scrollState === null || typeof scrollState === 'object').toBe(true);++ expect(workbook.disableSelection()).toBe(workbook);+ expect(workbook.enableSelection()).toBe(workbook);+ expect(workbook.transparentSelection()).toBe(workbook);+ expect(workbook.showSelection()).toBe(workbook);++ expect(typeof worksheet.getZoom()).toBe('number');++ const visibleRange = worksheet.getVisibleRange();+ expect(visibleRange === null || typeof visibleRange === 'object').toBe(true);++ const allViewportRanges = worksheet.getVisibleRangesOfAllViewports();+ expect(allViewportRanges === null || allViewportRanges instanceof Map).toBe(true);++ expect(worksheet.scrollToCell(10, 10, 0)).toBe(worksheet);+ expect(worksheet.getScrollState()).toBeTruthy();++ const onScrollSpy = vi.fn();+ const onScrollDis = worksheet.onScroll(onScrollSpy);+ onScrollDis.dispose();++ const skeleton = worksheet.getSkeleton();+ expect(skeleton == null || typeof skeleton === 'object').toBe(true);+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.tsnew file mode 100644index 0000000000..43c55842e6--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts@@ -0,0 +1,244 @@+/**+ * 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 { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import * as commonUtils from '../../common/utils';+import { SheetCanvasPopManagerService } from '../canvas-pop-manager.service';++function createEventSubject<T>() {+ const listeners = new Set<(event: T) => void>();+ return {+ subscribeEvent(cb: (event: T) => void) {+ listeners.add(cb);+ return {+ dispose() {+ listeners.delete(cb);+ },+ unsubscribe() {+ listeners.delete(cb);+ },+ };+ },+ emit(event: T) {+ listeners.forEach((cb) => cb(event));+ },+ };+}++function createService() {+ const canvas = document.createElement('canvas');+ canvas.style.width = '100px';+ vi.spyOn(canvas, 'getBoundingClientRect').mockReturnValue({+ top: 20,+ left: 10,+ width: 200,+ height: 120,+ right: 210,+ bottom: 140,+ x: 10,+ y: 20,+ toJSON: () => ({}),+ } as DOMRect);++ const commandListeners: Array<(info: { id: string; params?: any }) => void> = [];+ const onTransformChange$ = createEventSubject<unknown>();+ const worksheet = {+ getSheetId: () => 'sheet-1',+ getFreeze: () => ({ startRow: 1, startColumn: 1, xSplit: 0, ySplit: 0 }),+ };+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ getSheetBySheetId: () => worksheet,+ };+ const skeleton = {+ rowHeightAccumulation: [20, 40, 60],+ columnWidthAccumulation: [30, 60, 90],+ rowHeaderWidth: 20,+ columnHeaderHeight: 20,+ getCellWithCoordByIndex: (row: number, col: number) => ({+ startX: col * 30,+ endX: col * 30 + 30,+ startY: row * 20,+ endY: row * 20 + 20,+ isMergedMainCell: false,+ mergeInfo: {+ startX: col * 30,+ endX: col * 30 + 30,+ startY: row * 20,+ endY: row * 20 + 20,+ },+ }),+ };+ const viewport = { viewportScrollX: 0, viewportScrollY: 0 };+ const currentRender = {+ scene: {+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),+ },+ engine: {+ clientRect$: new BehaviorSubject({}),+ onTransformChange$,+ getCanvasElement: () => canvas,+ },+ with(_token: unknown) {+ return {+ ensureSkeleton: () => skeleton,+ getOrCreateSkeleton: () => skeleton,+ getSkeletonParam: () => ({ skeleton }),+ selectionMoving: false,+ };+ },+ };++ const popupService = {+ activePopupId: 'active',+ addPopup: vi.fn(() => 'popup-1'),+ removePopup: vi.fn(),+ };++ const service = new SheetCanvasPopManagerService(+ popupService as any,+ { getRenderById: () => currentRender } as any,+ {+ getCurrentUnitForType: () => workbook,+ getCurrentUnitOfType: () => workbook,+ getUnit: () => workbook,+ } as any,+ {+ watchRange: vi.fn((_unitId: string, _subUnitId: string, _range: any, _cb: any) => ({+ dispose: vi.fn(),+ })),+ } as any,+ {+ onCommandExecuted: (cb: (info: { id: string; params?: any }) => void) => {+ commandListeners.push(cb);+ return { dispose: vi.fn() };+ },+ emit(id: string, params?: any) {+ commandListeners.forEach((cb) => cb({ id, params }));+ },+ } as any,+ {+ selectionMoving$: new Subject<void>(),+ selectionMoveEnd$: new Subject<void>(),+ } as any,+ {+ selectionMoving$: new Subject<void>(),+ selectionMoveEnd$: new Subject<void>(),+ } as any+ );++ return {+ service,+ popupService,+ currentRender,+ workbook,+ worksheet,+ skeleton,+ viewport,+ };+}++describe('SheetCanvasPopManagerService', () => {+ beforeEach(() => {+ vi.spyOn(commonUtils, 'getViewportByCell').mockReturnValue({ viewportScrollX: 0, viewportScrollY: 0 } as any);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('registers and resolves feature menus', () => {+ const { service } = createService();+ const callback = vi.fn(() => [{ label: 'menu', index: 0, commandId: 'cmd', commandParams: {}, disable: false }]);++ service.registerFeatureMenu('image' as any, callback);+ service.registerFeatureMenuOffset('image' as any, 12, 8);++ expect(service.getFeatureMenu('u', 's', 'd', 'image' as any)).toEqual([+ { label: 'menu', index: 0, commandId: 'cmd', commandParams: {}, disable: false },+ ]);+ expect(service.getFeatureMenu('u', 's', 'd', 'chart' as any)).toBeUndefined();+ });++ it('attaches popup to absolute position and disposes correctly', () => {+ const { service, popupService } = createService();++ const bound = { top: 10, left: 20, right: 30, bottom: 40 };+ const disposable = service.attachPopupToAbsolutePosition(bound, { componentKey: 'comp' } as any, 'unit-1', 'sheet-1');+ expect(disposable).not.toBeNull();+ expect(popupService.addPopup).toHaveBeenCalled();+ expect(disposable?.canDispose()).toBe(true);++ disposable?.dispose();+ expect(popupService.removePopup).toHaveBeenCalledWith('popup-1');++ expect(service.attachPopupToAbsolutePosition(bound, { componentKey: 'comp' } as any, 'other', 'sheet-1')).toBeNull();+ });++ it('attaches popup to cell and range with watchers', () => {+ const { service, popupService } = createService();++ const cellPopup = service.attachPopupToCell(1, 1, { componentKey: 'comp' } as any);+ expect(cellPopup).not.toBeNull();+ expect(popupService.addPopup).toHaveBeenCalled();+ expect(cellPopup?.canDispose()).toBe(true);+ cellPopup?.dispose();++ const rangePopup = service.attachRangePopup(+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } as any,+ { componentKey: 'comp' } as any+ );+ expect(rangePopup).not.toBeNull();+ rangePopup?.dispose();+ expect(popupService.removePopup).toHaveBeenCalled();+ });++ it('calculates cell position and handles disposed skeleton/scene', () => {+ const { service, currentRender, skeleton, viewport } = createService();++ const calc = (service as any)._calcCellPositionByCell.bind(service);+ const normal = calc(1, 1, currentRender, skeleton, viewport);+ expect(normal.left).toBeGreaterThan(0);+ expect(normal.bottom).toBeGreaterThan(normal.top);++ const disposedSkeleton = { ...skeleton, _disposed: true };+ const disposedSceneRender = {+ ...currentRender,+ scene: {+ ...currentRender.scene,+ _disposed: true,+ },+ };+ expect(calc(1, 1, disposedSceneRender, disposedSkeleton, viewport)).toEqual({+ left: 0,+ right: 0,+ top: 0,+ bottom: 0,+ });+ });++ it('returns null for missing workbook/sheet in attachPopupToCell', () => {+ const { service } = createService();+ const mock = service as any;+ mock._univerInstanceService.getUnit = () => null;+ expect(service.attachPopupToCell(0, 0, { componentKey: 'comp' } as any, 'unit-x', 'sheet-1')).toBeNull();++ mock._univerInstanceService.getUnit = () => ({ getSheetBySheetId: () => null });+ expect(service.attachPopupToCell(0, 0, { componentKey: 'comp' } as any, 'unit-x', 'sheet-1')).toBeNull();+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.tsnew file mode 100644index 0000000000..435042dd94--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/cell-alert-manager.service.spec.ts@@ -0,0 +1,103 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { CellAlertManagerService, CellAlertType } from '../cell-alert-manager.service';++function createAlert(key: string) {+ return {+ key,+ type: CellAlertType.INFO,+ title: 'title',+ message: 'message',+ width: 180,+ height: 80,+ location: {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 3,+ col: 4,+ },+ };+}++describe('CellAlertManagerService', () => {+ it('adds/replaces/removes alerts and emits current list', () => {+ const oldPopupDispose = { dispose: vi.fn() };+ const newPopupDispose = { dispose: vi.fn() };+ const showPopup = vi+ .fn()+ .mockReturnValueOnce(oldPopupDispose)+ .mockReturnValueOnce(newPopupDispose);+ const service = new CellAlertManagerService(+ { getRenderById: vi.fn(() => ({ id: 'render' })) } as any,+ { showPopup } as any+ );++ const emitted: Array<[string, any][]> = [];+ service.currentAlert$.subscribe((value) => emitted.push(value));++ const first = createAlert('alert-1');+ service.showAlert(first as any);+ expect(showPopup).toHaveBeenCalledWith(+ first.location,+ expect.objectContaining({+ componentKey: 'univer.sheet.cell-alert',+ direction: 'horizontal',+ priority: 1,+ extraProps: { alert: first },+ })+ );+ expect(service.currentAlert.size).toBe(1);+ expect(emitted.at(-1)?.map(([key]) => key)).toEqual(['alert-1']);++ service.showAlert({ ...first, message: 'updated' } as any);+ expect(oldPopupDispose.dispose).toHaveBeenCalled();+ expect(service.currentAlert.get('alert-1')?.alert.message).toBe('message');+ expect(emitted.at(-1)?.map(([key]) => key)).toEqual(['alert-1']);++ service.removeAlert('alert-1');+ expect(newPopupDispose.dispose).toHaveBeenCalled();+ expect(service.currentAlert.size).toBe(0);+ expect(emitted.at(-1)).toEqual([]);+ });++ it('handles no-render and clear-all branches', () => {+ const popupA = { dispose: vi.fn() };+ const popupB = { dispose: vi.fn() };+ const showPopup = vi.fn().mockReturnValueOnce(popupA).mockReturnValueOnce(popupB);+ const renderManager: any = {+ getRenderById: vi.fn(() => ({ id: 'render' })),+ };+ const service = new CellAlertManagerService(renderManager as any, { showPopup } as any);++ service.showAlert(createAlert('a') as any);+ service.showAlert(createAlert('b') as any);+ expect(service.currentAlert.size).toBe(2);++ service.clearAlert();+ expect(service.currentAlert.size).toBe(0);+ expect(popupA.dispose).toHaveBeenCalled();+ expect(popupB.dispose).toHaveBeenCalled();++ renderManager.getRenderById = vi.fn(() => null);+ service.showAlert(createAlert('no-render') as any);+ expect(showPopup).toHaveBeenCalledTimes(2);+ expect(service.currentAlert.has('no-render')).toBe(true);++ service.removeAlert('not-found');+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/cell-dropdown-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/cell-dropdown-manager.service.spec.tsnew file mode 100644index 0000000000..8aab7642ea--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/cell-dropdown-manager.service.spec.ts@@ -0,0 +1,128 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { dropdownMap } from '../../views/dropdown';+import { SheetCellDropdownManagerService } from '../cell-dropdown-manager.service';++function createParam() {+ return {+ location: {+ row: 1,+ col: 2,+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ workbook: {},+ worksheet: {},+ },+ type: 'list',+ props: {+ options: [{ label: 'A', value: 'a' }],+ },+ } as any;+}++describe('SheetCellDropdownManagerService', () => {+ it('registers dropdown components and closes popup through outside click/hideFn', () => {+ const popupDisposable = { dispose: vi.fn() };+ const attachPopupToCell: any = vi.fn(() => popupDisposable);+ const componentManager = {+ register: vi.fn(() => ({ dispose: vi.fn() })),+ };+ const canvas = { id: 'canvas' } as any;+ const renderManager = {+ getRenderById: vi.fn((unitId: string) => {+ if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {+ return {+ engine: {+ getCanvasElement: () => canvas,+ },+ };+ }+ return null;+ }),+ };++ const service = new SheetCellDropdownManagerService(+ { attachPopupToCell } as any,+ { visible: false } as any,+ renderManager as any,+ componentManager as any+ );++ expect(componentManager.register).toHaveBeenCalledTimes(Object.keys(dropdownMap).length);++ const onHide = vi.fn();+ const disposable = service.showDropdown({+ ...createParam(),+ onHide,+ });+ const popupConfig: any = attachPopupToCell.mock.calls[0][2];+ expect(attachPopupToCell).toHaveBeenCalledWith(+ 1,+ 2,+ expect.objectContaining({+ offset: [0, 3],+ excludeOutside: [canvas],+ }),+ 'unit-1',+ 'sheet-1'+ );++ popupConfig.onClickOutside();+ expect(popupDisposable.dispose).toHaveBeenCalled();+ expect(onHide).toHaveBeenCalled();++ const disposable2 = service.showDropdown({+ ...createParam(),+ closeOnOutSide: false,+ onHide,+ });+ const popupConfig2: any = attachPopupToCell.mock.calls[1][2];+ popupConfig2.onClickOutside();+ expect(popupDisposable.dispose).toHaveBeenCalledTimes(1);+ popupConfig2.extraProps.hideFn();+ expect(popupDisposable.dispose).toHaveBeenCalledTimes(2);++ disposable.dispose();+ disposable2.dispose();+ });++ it('throws when zen mode is visible or popup cannot be attached', () => {+ const commonArgs = [+ { attachPopupToCell: vi.fn() },+ { getRenderById: vi.fn(() => null) },+ { register: vi.fn(() => ({ dispose: vi.fn() })) },+ ] as const;++ const zenVisibleService = new SheetCellDropdownManagerService(+ commonArgs[0] as any,+ { visible: true } as any,+ commonArgs[1] as any,+ commonArgs[2] as any+ );+ expect(() => zenVisibleService.showDropdown(createParam())).toThrowError('cannot show dropdown when zen mode is visible');++ const attachFailService = new SheetCellDropdownManagerService(+ { attachPopupToCell: vi.fn(() => null) } as any,+ { visible: false } as any,+ commonArgs[1] as any,+ commonArgs[2] as any+ );+ expect(() => attachFailService.showDropdown(createParam())).toThrowError('cannot show dropdown');+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.tsnew file mode 100644index 0000000000..0277009708--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/cell-popup-manager.service.spec.ts@@ -0,0 +1,100 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { CellPopupManagerService } from '../cell-popup-manager.service';++describe('CellPopupManagerService', () => {+ it('creates/sorts popups and removes them through returned disposables', () => {+ const popupDisposable = { dispose: vi.fn() };+ const sheetPopupService = {+ attachPopupToCell: vi.fn(() => popupDisposable),+ };+ const service = new CellPopupManagerService(sheetPopupService as any);+ const changes: any[] = [];+ service.change$.subscribe((change) => changes.push(change));++ const location = { unitId: 'unit-1', subUnitId: 'sheet-1', row: 4, col: 5 };+ const disposeLow = service.showPopup(location, {+ id: 'p-low',+ componentKey: 'component-a',+ priority: 10,+ } as any);+ const disposeHigh = service.showPopup(location, {+ id: 'p-high',+ componentKey: 'component-b',+ priority: 1,+ } as any);++ expect(sheetPopupService.attachPopupToCell).toHaveBeenCalledTimes(1);+ expect(service.getPopups('unit-1', 'sheet-1', 4, 5, 'horizontal').map((p) => p.id)).toEqual(['p-high', 'p-low']);+ expect(changes.at(-1)).toEqual({ ...location, direction: 'horizontal' });++ disposeHigh.dispose();+ expect(service.getPopups('unit-1', 'sheet-1', 4, 5, 'horizontal').map((p) => p.id)).toEqual(['p-low']);+ expect(popupDisposable.dispose).not.toHaveBeenCalled();++ disposeLow.dispose();+ expect(service.getPopups('unit-1', 'sheet-1', 4, 5, 'horizontal')).toEqual([]);+ expect(popupDisposable.dispose).toHaveBeenCalledTimes(1);+ });++ it('supports vertical cache and hidePopup clear logic', () => {+ const horizontalDisposable = { dispose: vi.fn() };+ const verticalDisposable = { dispose: vi.fn() };+ const sheetPopupService = {+ attachPopupToCell: vi+ .fn()+ .mockReturnValueOnce(horizontalDisposable)+ .mockReturnValueOnce(verticalDisposable),+ };+ const service = new CellPopupManagerService(sheetPopupService as any);+ const changes: any[] = [];+ service.change$.subscribe((change) => changes.push(change));++ const location = { unitId: 'unit-2', subUnitId: 'sheet-2', row: 1, col: 2 };+ service.showPopup(location, {+ id: 'h1',+ componentKey: 'h',+ direction: 'horizontal',+ priority: 1,+ } as any);+ service.showPopup(location, {+ id: 'v1',+ componentKey: 'v',+ direction: 'vertical',+ priority: 2,+ } as any);++ expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'horizontal').length).toBe(1);+ expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'vertical').length).toBe(1);++ service.hidePopup('unit-2', 'sheet-2', 1, 2);+ expect(horizontalDisposable.dispose).toHaveBeenCalled();+ expect(verticalDisposable.dispose).toHaveBeenCalled();+ expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'horizontal')).toEqual([]);+ expect(service.getPopups('unit-2', 'sheet-2', 1, 2, 'vertical')).toEqual([]);++ // No-op branch.+ service.hidePopup('unit-2', 'sheet-2', 9, 9);++ const directions = changes+ .filter((change) => change.unitId === 'unit-2' && change.subUnitId === 'sheet-2')+ .map((change) => change.direction);+ expect(directions.includes('horizontal')).toBe(true);+ expect(directions.includes('vertical')).toBe(true);+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/drag-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/drag-manager.service.spec.tsnew file mode 100644index 0000000000..fb80ea7c43--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/drag-manager.service.spec.ts@@ -0,0 +1,265 @@+/**+ * 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 { IUniverInstanceService, Nullable, UnitModel, Workbook, Worksheet } from '@univerjs/core';+import type { IDragEvent, IRender, IRenderManagerService } from '@univerjs/engine-render';+import type { Observable } from 'rxjs';+import type { IDragCellPosition } from '../drag-manager.service';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { getHoverCellPosition } from '../../common/utils';+import { DragManagerService } from '../drag-manager.service';+import { SheetScrollManagerService } from '../scroll-manager.service';+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';++vi.mock('../../common/utils', () => ({+ getHoverCellPosition: vi.fn(),+}));++type DragManagerInstanceServiceStub = Pick<IUniverInstanceService, 'getCurrentTypeOfUnit$' | 'getCurrentUnitForType'>;+type DragManagerRenderManagerStub = Pick<IRenderManagerService, 'getRenderById'>;++function createRender() {+ return {+ with: vi.fn((token: unknown) => {+ if (token === SheetSkeletonManagerService) {+ return {+ getCurrentParam: vi.fn(() => ({ skeleton: { id: 'skeleton' } })),+ };+ }++ if (token === SheetScrollManagerService) {+ return {+ getCurrentScrollState: vi.fn(() => ({ x: 0, y: 0 })),+ };+ }++ return null;+ }),+ };+}++function createUniverInstanceService(+ currentType$: Subject<unknown>,+ workbook: Workbook | null+): DragManagerInstanceServiceStub {+ return {+ getCurrentTypeOfUnit$<T extends UnitModel<object, number>>(): Observable<Nullable<T>> {+ return currentType$.asObservable() as Observable<Nullable<T>>;+ },+ getCurrentUnitForType<T extends UnitModel<object, number>>(): Nullable<T> {+ return workbook as Nullable<T>;+ },+ };+}++function createRenderManagerService(render: ReturnType<typeof createRender>): DragManagerRenderManagerStub {+ return {+ getRenderById() {+ return render as unknown as IRender;+ },+ };+}++function createHoverPosition(workbook: Workbook, worksheet: Worksheet, row: number, col: number, position: IDragCellPosition['position']) {+ const location = { unitId: 'unit-1', subUnitId: 'sheet-1', workbook, worksheet, row, col };++ return {+ location,+ overflowLocation: location,+ position,+ };+}++function createDragEvent(offsetX: number, offsetY: number, dataTransfer: DataTransfer | null): IDragEvent {+ return {+ altKey: false,+ button: 0,+ buttons: 0,+ clientX: offsetX,+ clientY: offsetY,+ ctrlKey: false,+ currentState: null,+ dataTransfer: dataTransfer as DataTransfer,+ defaultPrevented: false,+ detail: 0,+ deviceType: 0 as never,+ eventPhase: 0,+ inputIndex: 0,+ isTrusted: false,+ metaKey: false,+ movementX: 0,+ movementY: 0,+ offsetX,+ offsetY,+ previousState: null,+ returnValue: true,+ shiftKey: false,+ srcElement: null,+ target: null,+ timeStamp: 0,+ type: 'drag',+ view: null,+ x: offsetX,+ y: offsetY,+ bubbles: false,+ cancelBubble: false,+ cancelable: false,+ composed: false,+ composedPath: () => [],+ initEvent: vi.fn(),+ preventDefault: vi.fn(),+ stopImmediatePropagation: vi.fn(),+ stopPropagation: vi.fn(),+ NONE: 0,+ CAPTURING_PHASE: 0,+ AT_TARGET: 0,+ BUBBLING_PHASE: 0,+ initUIEvent: vi.fn(),+ } as unknown as IDragEvent;+}++describe('DragManagerService', () => {+ it('publishes drag-over/drop positions and handles null active cell', () => {+ const mockGetHoverCellPosition = vi.mocked(getHoverCellPosition);+ const worksheet = { getSheetId: () => 'sheet-1' } as unknown as Worksheet;+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ } as unknown as Workbook;+ const currentType$ = new Subject<unknown>();++ const univerInstanceService = createUniverInstanceService(currentType$, workbook);++ const render = createRender();+ const renderManagerService = createRenderManagerService(render);++ const service = new DragManagerService(+ univerInstanceService as unknown as IUniverInstanceService,+ renderManagerService as unknown as IRenderManagerService+ );+ const currentCells: Array<Nullable<IDragCellPosition>> = [];+ const endCells: Array<Nullable<IDragCellPosition>> = [];+ const currentSub = service.currentCell$.subscribe((v) => currentCells.push(v));+ const endSub = service.endCell$.subscribe((v) => endCells.push(v));++ mockGetHoverCellPosition.mockReturnValue(createHoverPosition(workbook, worksheet, 2, 3, { startX: 10, startY: 20, endX: 40, endY: 60 }));++ const dataTransfer = { files: [] } as unknown as DataTransfer;+ service.onDragOver(createDragEvent(12, 34, dataTransfer));+ expect(getHoverCellPosition).toHaveBeenCalledWith(+ render,+ workbook,+ worksheet,+ { skeleton: { id: 'skeleton' } },+ 12,+ 34+ );+ expect(currentCells.at(-1)).toEqual({+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', workbook, worksheet, row: 2, col: 3 },+ position: { startX: 10, startY: 20, endX: 40, endY: 60 },+ dataTransfer,+ });++ service.onDrop(createDragEvent(12, 34, dataTransfer));+ expect(endCells.at(-1)).toEqual({+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', workbook, worksheet, row: 2, col: 3 },+ position: { startX: 10, startY: 20, endX: 40, endY: 60 },+ dataTransfer,+ });++ mockGetHoverCellPosition.mockReturnValue(null);+ service.onDragOver(createDragEvent(1, 1, dataTransfer));+ service.onDrop(createDragEvent(1, 1, dataTransfer));+ expect(currentCells.at(-1)).toBeNull();+ expect(endCells.at(-1)).toBeNull();++ currentSub.unsubscribe();+ endSub.unsubscribe();+ });++ it('clears states when workbook becomes unavailable and supports dispose', () => {+ const currentType$ = new Subject<unknown>();+ const univerInstanceService = createUniverInstanceService(currentType$, null);+ const renderManagerService = createRenderManagerService(createRender());+ const service = new DragManagerService(+ univerInstanceService as unknown as IUniverInstanceService,+ renderManagerService as unknown as IRenderManagerService+ );+ const currentCells: Array<Nullable<IDragCellPosition>> = [];+ const endCells: Array<Nullable<IDragCellPosition>> = [];++ const currentSub = service.currentCell$.subscribe((v) => currentCells.push(v));+ const endSub = service.endCell$.subscribe((v) => endCells.push(v));++ currentType$.next(null);+ expect(currentCells.at(-1)).toBeNull();+ expect(endCells.at(-1)).toBeNull();++ service.onDragOver(createDragEvent(0, 0, null));+ service.onDrop(createDragEvent(0, 0, null));+ expect(currentCells.at(-1)).toBeNull();+ expect(endCells.at(-1)).toBeNull();++ currentSub.unsubscribe();+ endSub.unsubscribe();+ service.dispose();+ });++ it('deduplicates drag-over emissions when the pointer stays on the same cell', () => {+ const mockGetHoverCellPosition = vi.mocked(getHoverCellPosition);+ const worksheet = { getSheetId: () => 'sheet-1' } as unknown as Worksheet;+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ } as unknown as Workbook;++ const univerInstanceService = createUniverInstanceService(new Subject<unknown>(), workbook);+ const renderManagerService = createRenderManagerService(createRender());++ const service = new DragManagerService(+ univerInstanceService as unknown as IUniverInstanceService,+ renderManagerService as unknown as IRenderManagerService+ );+ const currentCells: Array<Nullable<IDragCellPosition>> = [];+ const currentSub = service.currentCell$.subscribe((value) => currentCells.push(value));++ mockGetHoverCellPosition+ .mockReturnValueOnce(createHoverPosition(workbook, worksheet, 2, 3, { startX: 10, startY: 20, endX: 30, endY: 40 }))+ .mockReturnValueOnce(createHoverPosition(workbook, worksheet, 2, 3, { startX: 11, startY: 21, endX: 31, endY: 41 }))+ .mockReturnValueOnce(createHoverPosition(workbook, worksheet, 4, 5, { startX: 12, startY: 22, endX: 32, endY: 42 }));++ service.onDragOver(createDragEvent(10, 20, { files: [] } as unknown as DataTransfer));+ service.onDragOver(createDragEvent(11, 21, { files: ['changed'] } as unknown as DataTransfer));+ service.onDragOver(createDragEvent(12, 22, { files: [] } as unknown as DataTransfer));++ expect(currentCells).toEqual([+ {+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', workbook, worksheet, row: 2, col: 3 },+ position: { startX: 10, startY: 20, endX: 30, endY: 40 },+ dataTransfer: { files: [] },+ },+ {+ location: { unitId: 'unit-1', subUnitId: 'sheet-1', workbook, worksheet, row: 4, col: 5 },+ position: { startX: 12, startY: 22, endX: 32, endY: 42 },+ dataTransfer: { files: [] },+ },+ ]);++ currentSub.unsubscribe();+ service.dispose();+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts b/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.tsnew file mode 100644index 0000000000..872e5014fa--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts@@ -0,0 +1,203 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';+import { DeviceInputEventType } from '@univerjs/engine-render';+import { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { EditorBridgeService } from '../editor-bridge.service';++function createService(options?: { hasFocusEditor?: boolean }) {+ const unitDisposed$ = new Subject<any>();+ const workbook = {+ getUnitId: () => 'unit-1',+ };++ const mocks = {+ unitDisposed$,+ sheetInterceptorService: {+ writeCellInterceptor: {+ fetchThroughInterceptors: vi.fn(() => (cell: unknown) => cell),+ },+ },+ renderManagerService: {+ getRenderUnitById: vi.fn(() => null),+ },+ themeService: {+ getColorFromTheme: vi.fn(() => '#d0d0d0'),+ },+ univerInstanceService: {+ getTypeOfUnitDisposed$: vi.fn(() => unitDisposed$.asObservable()),+ getCurrentUnitForType: vi.fn(() => workbook),+ },+ editorService: {+ getFocusEditor: vi.fn(() => (options?.hasFocusEditor ? { id: 'existing' } : null)),+ focus: vi.fn(),+ },+ contextService: {+ setContextValue: vi.fn(),+ },+ };++ const service = new EditorBridgeService(+ mocks.sheetInterceptorService as any,+ mocks.renderManagerService as any,+ mocks.themeService as any,+ mocks.univerInstanceService as any,+ mocks.editorService as any,+ mocks.contextService as any+ );++ return { service, mocks };+}++function createLatestState() {+ return {+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ row: 1,+ column: 2,+ documentLayoutObject: { id: 'doc-layout' },+ editorUnitId: 'doc-editor',+ position: {+ startX: 10,+ startY: 20,+ endX: 30,+ endY: 40,+ },+ canvasOffset: {+ left: 0,+ top: 0,+ },+ scaleX: 1,+ scaleY: 1,+ };+}++function createEditCellParam() {+ return {+ scene: {},+ engine: {},+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ primary: {+ startRow: 1,+ endRow: 1,+ startColumn: 2,+ endColumn: 2,+ actualRow: 1,+ actualColumn: 2,+ isMerged: false,+ isMergedMainCell: true,+ },+ } as any;+}++describe('EditorBridgeService', () => {+ it('syncs edit state/layout from latest state and reacts to disposed unit', () => {+ const { service, mocks } = createService();+ const latest = createLatestState();+ const currentEditCombined: any[] = [];+ service.currentEditCell$.subscribe((value) => currentEditCombined.push(value));++ const getLatestSpy = vi.spyOn(service, 'getLatestEditCellState');+ getLatestSpy.mockReturnValue(latest as any);+ service.setEditCell(createEditCellParam());++ expect(mocks.editorService.focus).toHaveBeenCalled();+ expect(mocks.contextService.setContextValue).toHaveBeenCalledTimes(2);+ expect(service.getEditCellState()).toEqual(latest);+ expect(service.getEditCellLayout()).toEqual({+ position: latest.position,+ canvasOffset: latest.canvasOffset,+ scaleX: 1,+ scaleY: 1,+ });+ expect(service.getEditLocation()).toEqual(+ expect.objectContaining({+ unitId: 'unit-1',+ sheetId: 'sheet-1',+ row: 1,+ column: 2,+ })+ );+ expect(currentEditCombined.at(-1)).toEqual(expect.objectContaining({ row: 1, column: 2 }));++ service.updateEditLocation(8, 9);+ expect(service.getEditLocation()).toEqual(expect.objectContaining({ row: 8, column: 9 }));++ getLatestSpy.mockReturnValue(null as any);+ service.refreshEditCellState();+ expect(service.getEditCellState()).toBeNull();++ getLatestSpy.mockReturnValue(latest as any);+ service.refreshEditCellState();+ expect(service.getEditCellState()).toEqual(latest);++ mocks.unitDisposed$.next({+ getUnitId: () => 'unit-1',+ });+ expect(service.getEditCellState()).toBeNull();+ expect(service.getEditCellLayout()).toBeNull();+ });++ it('manages visible/dirty/force-keep states and null-latest branches', () => {+ const { service, mocks } = createService({ hasFocusEditor: true });+ const visibleValues: any[] = [];+ const afterVisibleValues: any[] = [];+ const forceValues: boolean[] = [];+ service.visible$.subscribe((value) => visibleValues.push(value));+ service.afterVisible$.subscribe((value) => afterVisibleValues.push(value));+ service.forceKeepVisible$.subscribe((value) => forceValues.push(value));++ expect(service.getCurrentEditorId()).toBe(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);+ expect(service.getEditCellState()).toBeNull();+ expect(service.getEditCellLayout()).toBeNull();+ expect(service.getEditLocation()).toBeNull();+ expect(service.getEditorDirty()).toBe(false);++ service.changeEditorDirty(true);+ expect(service.getEditorDirty()).toBe(true);++ service.changeVisible({+ visible: true,+ eventType: DeviceInputEventType.Keyboard,+ unitId: 'unit-1',+ });+ expect(service.isVisible()).toEqual({+ visible: true,+ eventType: DeviceInputEventType.Keyboard,+ unitId: 'unit-1',+ });+ expect(service.getEditorDirty()).toBe(false);+ expect(visibleValues.at(-1)).toEqual(expect.objectContaining({ visible: true }));+ expect(afterVisibleValues.at(-1)).toEqual(expect.objectContaining({ visible: true }));++ service.enableForceKeepVisible();+ service.disableForceKeepVisible();+ expect(service.isForceKeepVisible()).toBe(false);+ expect(forceValues.slice(-2)).toEqual([true, false]);++ const getLatestSpy = vi.spyOn(service, 'getLatestEditCellState').mockReturnValue(undefined);+ service.setEditCell(createEditCellParam());+ expect(service.getEditCellState()).toBeNull();++ service.refreshEditCellState();+ service.refreshEditCellPosition();+ expect(getLatestSpy).toHaveBeenCalled();+ expect(mocks.editorService.focus).not.toHaveBeenCalled();+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.tsnew file mode 100644index 0000000000..6488c10787--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.spec.ts@@ -0,0 +1,216 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand } from '../../commands/commands/headersize-changed.command';+import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';++function createService() {+ const sheetDisposed$ = new Subject<any>();+ const worksheets = new Map<string, any>();+ const workbook = {+ sheetDisposed$,+ getStyles: vi.fn(() => ({ styles: true })),+ getSheetBySheetId: vi.fn((id: string) => worksheets.get(id) ?? null),+ };++ const mainViewport = { left: 46, top: 20 };+ const viewportMap = new Map<any, any>();+ const getOrCreateViewport = (key: unknown) => {+ if (!viewportMap.has(key)) {+ viewportMap.set(key, {+ setViewportSize: vi.fn(),+ left: 12,+ width: 46,+ });+ }+ return viewportMap.get(key);+ };+ const scene = {+ getViewports: vi.fn(() => [mainViewport]),+ getViewport: vi.fn((key: unknown) => getOrCreateViewport(key)),+ };++ const injector = {+ createInstance: vi.fn((_cls: unknown, worksheet: unknown, styles: unknown) => ({+ worksheet,+ styles,+ columnHeaderHeight: 20,+ rowHeaderWidth: 46,+ makeDirty: vi.fn(),+ calculate: vi.fn(),+ dispose: vi.fn(),+ getNoMergeCellWithCoordByIndex: vi.fn((row: number, col: number) => ({+ startX: col * 10,+ startY: row * 10,+ endX: col * 10 + 10,+ endY: row * 10 + 10,+ })),+ })),+ };++ const sheetSkService = {+ setSkeleton: vi.fn(),+ deleteSkeleton: vi.fn(),+ };++ const context = {+ unitId: 'unit-1',+ unit: workbook,+ scene,+ };++ const service = new SheetSkeletonManagerService(+ context as any,+ injector as any,+ sheetSkService as any+ );++ return {+ service,+ workbook,+ worksheets,+ scene,+ viewportMap,+ sheetSkService,+ sheetDisposed$,+ mainViewport,+ };+}++describe('SheetSkeletonManagerService', () => {+ it('creates/reuses skeleton and handles dirty/current lifecycle', () => {+ const { service, worksheets, sheetSkService, workbook } = createService();+ const worksheet = { getSheetId: () => 'sheet-1' };+ worksheets.set('sheet-1', worksheet);++ const beforeValues: any[] = [];+ const currentValues: any[] = [];+ service.currentSkeletonBefore$.subscribe((value) => beforeValues.push(value));+ service.currentSkeleton$.subscribe((value) => currentValues.push(value));++ expect(service.getCurrentSkeleton()).toBeUndefined();+ expect(service.getCurrent()).toBeUndefined();+ expect(service.getCurrentParam()).toBeUndefined();+ expect(service.getSkeleton('sheet-1')).toBeNull();+ expect(service.getWorksheetSkeleton('sheet-1')).toBeUndefined();++ service.setCurrent({ sheetId: 'sheet-1' });+ const param = service.getCurrentParam();+ expect(param?.sheetId).toBe('sheet-1');+ expect(service.getCurrentSkeleton()).toBe(param?.skeleton);+ expect(service.getUnitSkeleton('override-unit', 'sheet-1')?.unitId).toBe('override-unit');+ expect(beforeValues.at(-1)?.sheetId).toBe('sheet-1');+ expect(currentValues.at(-1)?.sheetId).toBe('sheet-1');+ expect(sheetSkService.setSkeleton).toHaveBeenCalled();++ const skeleton = param!.skeleton as any;+ service.makeDirty({ sheetId: 'sheet-1' });+ service.reCalculate(param);+ expect(skeleton.makeDirty).toHaveBeenCalledWith(true);+ expect(skeleton.calculate).toHaveBeenCalled();++ const ensured = service.ensureSkeleton('sheet-1');+ expect(ensured).toBe(skeleton);+ expect(service.getOrCreateSkeleton({ sheetId: 'sheet-1' })).toBe(skeleton);++ expect(service.ensureSkeleton('missing-sheet')).toBeUndefined();++ const rangeWithCoord = service.attachRangeWithCoord({+ startRow: 1,+ endRow: 1,+ startColumn: 2,+ endColumn: 2,+ } as any);+ expect(rangeWithCoord).toEqual({+ startRow: 1,+ endRow: 1,+ startColumn: 2,+ endColumn: 2,+ startX: 20,+ startY: 10,+ endX: 30,+ endY: 20,+ });++ worksheets.clear();+ service.setCurrent({ sheetId: 'not-found' });+ expect(workbook.getSheetBySheetId).toHaveBeenCalledWith('not-found');+ });++ it('updates header dimensions and publishes command ids', () => {+ const { service, worksheets, scene, viewportMap, mainViewport } = createService();+ const worksheet = { getSheetId: () => 'sheet-1' };+ worksheets.set('sheet-1', worksheet);+ service.setCurrent({ sheetId: 'sheet-1' });++ const selectionService = { getCurrentSelections: vi.fn(() => [{ range: 1 }]) };+ const selectionRenderService = { resetSelectionsByModelData: vi.fn() };+ const render = {+ unitId: 'unit-1',+ scene,+ with: vi.fn((token: unknown) => {+ if (token === ISheetSelectionRenderService) {+ return selectionRenderService;+ }+ return selectionService;+ }),+ };++ service.setColumnHeaderSize(render as any, 'sheet-1', 32);+ const skeleton = service.getSkeleton('sheet-1') as any;+ expect(skeleton.columnHeaderHeight).toBe(32);+ expect(mainViewport.top).toBe(32);+ const viewportCalls = Array.from(viewportMap.values()).flatMap((v) => v.setViewportSize.mock.calls);+ expect(viewportCalls.some((args) => args[0]?.height === 32)).toBe(true);+ expect(viewportCalls.some((args) => args[0]?.top === 32)).toBe(true);+ expect(selectionRenderService.resetSelectionsByModelData).toHaveBeenCalledWith([{ range: 1 }]);+ expect(service.getSkeletonParam('sheet-1')?.commandId).toBe(SetColumnHeaderHeightCommand.id);++ service.setRowHeaderSize(render as any, 'sheet-1', 60);+ expect(skeleton.rowHeaderWidth).toBe(60);+ expect(mainViewport.left).toBe(60);+ const viewportCallsAfter = Array.from(viewportMap.values()).flatMap((v) => v.setViewportSize.mock.calls);+ expect(viewportCallsAfter.some((args) => args[0]?.width === 60)).toBe(true);+ expect(viewportCallsAfter.some((args) => args[0]?.left === 26)).toBe(true);+ expect(service.getCurrentParam()?.commandId).toBe(SetRowHeaderWidthCommand.id);++ service.setColumnHeaderSize(null as any, 'sheet-1', 20);+ service.setRowHeaderSize(null as any, 'sheet-1', 20);+ service.disposeSkeleton('sheet-missing');+ });++ it('disposes skeleton on sheet disposal and service dispose', () => {+ const { service, worksheets, sheetDisposed$, sheetSkService } = createService();+ const worksheet = { getSheetId: () => 'sheet-1' };+ worksheets.set('sheet-1', worksheet);+ service.setCurrent({ sheetId: 'sheet-1' });++ const skeleton = service.getSkeleton('sheet-1') as any;+ expect(skeleton).toBeTruthy();++ sheetDisposed$.next({+ getSheetId: () => 'sheet-1',+ });+ expect(skeleton.dispose).toHaveBeenCalled();+ expect(sheetSkService.deleteSkeleton).toHaveBeenCalledWith(expect.any(String), 'sheet-1');+ expect(service.getSkeleton('sheet-1')).toBeNull();++ service.dispose();+ });+});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.tsnew file mode 100644index 0000000000..23bd07193e--- /dev/null+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clone.spec.ts@@ -0,0 +1,55 @@+/**+ * 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 { cloneCellDataWithSpanInfo } from '../clone';++describe('cloneCellDataWithSpanInfo', () => {+ it('should keep nullish values as-is', () => {+ expect(cloneCellDataWithSpanInfo(null)).toBeNull();+ expect(cloneCellDataWithSpanInfo(undefined as any)).toBeUndefined();+ });++ it('should deep clone object fields and keep primitive fields', () => {+ const source: any = {+ p: { body: { dataStream: 'abc' } },+ s: { bg: { rgb: '#fff' } },+ v: '1',+ t: 1,+ f: '=A1',+ ref: 'A1',+ xf: '=SUM()',+ si: 'sid',+ custom: { hello: 'world' },+ rowSpan: 2,+ colSpan: 3,+ plain: 'plain-text',+ };++ const cloned = cloneCellDataWithSpanInfo(source)!;+ expect(cloned).toEqual(source);++ expect(cloned.p).not.toBe(source.p);+ expect(cloned.s).not.toBe(source.s);+ expect(cloned.custom).not.toBe(source.custom);++ (cloned.s as any).bg.rgb = '#000';+ (cloned.custom as any).hello = 'changed';++ expect(source.s.bg.rgb).toBe('#fff');+ expect(source.custom.hello).toBe('world');+ });+});diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/copy-content-cache.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/copy-content-cache.spec.tsnew file mode 100644index 0000000000..d8cd25247d--- /dev/null+++ b/packages/sheets-ui/src/services/clipboard/__tests__/copy-content-cache.spec.ts@@ -0,0 +1,65 @@+/**+ * 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 { CopyContentCache, extractId, genId } from '../copy-content-cache';++describe('copy-content-cache', () => {+ it('should generate id with expected length and extract id from html', () => {+ const id = genId();+ expect(typeof id).toBe('string');+ expect(id.length).toBe(6);++ expect(extractId('<div data-copy-id="abc123"></div>')).toBe('abc123');+ expect(extractId('<div></div>')).toBeNull();+ });++ it('should support set/get/delete/clear and lastCopyId tracking', () => {+ const cache = new CopyContentCache();+ const events: Array<string | null> = [];+ const sub = cache.lastCopyId$.subscribe((value) => events.push(value));++ cache.set('id-1', { unitId: 'u1', subUnitId: 's1', range: { rows: [1], cols: [1] } as any, copyType: 'normal' as any, matrix: null });+ expect(cache.get('id-1')?.unitId).toBe('u1');+ expect(cache.getLastCopyId()).toBe('id-1');++ cache.del('id-1');+ expect(cache.get('id-1')).toBeUndefined();+ expect(cache.getLastCopyId()).toBeNull();++ cache.set('id-2', { unitId: 'u2', subUnitId: 's1', range: { rows: [2], cols: [2] } as any, copyType: 'normal' as any, matrix: null });+ cache.clear();+ expect(cache.get('id-2')).toBeUndefined();+ expect(cache.getLastCopyId()).toBeNull();++ expect(events[0]).toBeNull();+ expect(events).toContain('id-1');+ expect(events.at(-1)).toBeNull();++ sub.unsubscribe();+ });++ it('should clear cache entries by unit id', () => {+ const cache = new CopyContentCache();+ cache.set('id-u1', { unitId: 'u1', subUnitId: 's1', range: { rows: [1], cols: [1] } as any, copyType: 'normal' as any, matrix: null });+ cache.set('id-u2', { unitId: 'u2', subUnitId: 's1', range: { rows: [1], cols: [1] } as any, copyType: 'normal' as any, matrix: null });++ cache.clearWithUnitId('u1');++ expect(cache.get('id-u1')).toBeUndefined();+ expect(cache.get('id-u2')).toBeDefined();+ });+});diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-render-model.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-render-model.spec.tsnew file mode 100644index 0000000000..5a0db8ab3f--- /dev/null+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-render-model.spec.ts@@ -0,0 +1,126 @@+/**+ * 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 { RANGE_TYPE } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { SelectionRenderModel } from '../selection-render-model';++const BASE_RANGE = {+ startColumn: 1,+ startRow: 2,+ endColumn: 4,+ endRow: 6,+ startX: 10,+ startY: 20,+ endX: 40,+ endY: 80,+};++const BASE_CELL = {+ ...BASE_RANGE,+ actualRow: 3,+ actualColumn: 2,+};++describe('SelectionRenderModel', () => {+ it('provides default value and getter states', () => {+ const model = new SelectionRenderModel();++ expect(model.startColumn).toBe(-1);+ expect(model.startRow).toBe(-1);+ expect(model.endColumn).toBe(-1);+ expect(model.endRow).toBe(-1);+ expect(model.startX).toBe(0);+ expect(model.startY).toBe(0);+ expect(model.endX).toBe(0);+ expect(model.endY).toBe(0);+ expect(model.currentCell).toBeUndefined();+ expect(model.getCell()).toBeUndefined();+ expect(model.rangeType).toBe(RANGE_TYPE.NORMAL);+ expect(model.getRangeType()).toBe(RANGE_TYPE.NORMAL);+ expect(model.highlightToSelection()).toBeUndefined();+ });++ it('sets and reads value including range type and primary', () => {+ const model = new SelectionRenderModel();+ model.setValue(+ {+ ...BASE_RANGE,+ rangeType: RANGE_TYPE.ROW,+ } as any,+ BASE_CELL as any+ );++ expect(model.getRange()).toEqual({+ ...BASE_RANGE,+ rangeType: RANGE_TYPE.ROW,+ });+ expect(model.getValue()).toEqual({+ rangeWithCoord: {+ ...BASE_RANGE,+ rangeType: RANGE_TYPE.ROW,+ },+ primaryWithCoord: BASE_CELL,+ });+ expect(model.highlightToSelection()).toEqual({+ startRow: BASE_CELL.actualRow,+ endRow: BASE_CELL.actualRow,+ startColumn: BASE_CELL.actualColumn,+ endColumn: BASE_CELL.actualColumn,+ startX: BASE_CELL.startX,+ startY: BASE_CELL.startY,+ endX: BASE_CELL.endX,+ endY: BASE_CELL.endY,+ });+ expect(model.isEqual(BASE_RANGE as any)).toBe(true);+ expect(model.isEqual({ ...BASE_RANGE, endColumn: 5 } as any)).toBe(false);+ });++ it('keeps old rangeType/currentCell when setValue receives undefined fields', () => {+ const model = new SelectionRenderModel();+ model.setRangeType(RANGE_TYPE.COLUMN);+ model.setCurrentCell(BASE_CELL as any);++ model.setValue(+ {+ ...BASE_RANGE,+ startColumn: 8,+ endColumn: 8,+ rangeType: undefined,+ } as any,+ undefined as any+ );++ expect(model.rangeType).toBe(RANGE_TYPE.COLUMN);+ expect(model.currentCell).toEqual(BASE_CELL);+ expect(model.startColumn).toBe(8);+ expect(model.endColumn).toBe(8);+ });++ it('supports explicit current-cell clear flows', () => {+ const model = new SelectionRenderModel();+ model.setCurrentCell(BASE_CELL as any);+ expect(model.currentCell).toEqual(BASE_CELL);++ model.setValue(BASE_RANGE as any, null);+ expect(model.currentCell).toBeNull();++ model.setCurrentCell(BASE_CELL as any);+ model.clearCurrentCell();+ expect(model.currentCell).toBeNull();+ expect(model.highlightToSelection()).toBeUndefined();+ });+});diff --git a/packages/sheets-ui/src/services/selection/__tests__/util.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/util.spec.tsnew file mode 100644index 0000000000..4376c91065--- /dev/null+++ b/packages/sheets-ui/src/services/selection/__tests__/util.spec.ts@@ -0,0 +1,90 @@+/**+ * 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 { attachPrimaryWithCoord, attachRangeWithCoord, attachSelectionWithCoord } from '../util';++describe('selection util', () => {+ it('should attach coordinates and normalize reversed ranges', () => {+ const skeleton = {+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => {+ if (row === 1 && col === 2) return { startX: 10, startY: 20, endX: 20, endY: 30 };+ if (row === 3 && col === 4) return { startX: 40, startY: 60, endX: 50, endY: 80 };+ return { startX: 0, startY: 0, endX: 0, endY: 0 };+ },+ } as any;++ const range = attachRangeWithCoord(skeleton, {+ startRow: 3,+ endRow: 1,+ startColumn: 4,+ endColumn: 2,+ } as any);++ expect(range.startRow).toBe(3);+ expect(range.endRow).toBe(1);+ expect(range.startX).toBe(10);+ expect(range.startY).toBe(20);+ expect(range.endX).toBe(50);+ expect(range.endY).toBe(80);+ });++ it('should attach primary and selection coordinates', () => {+ const skeleton = {+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => {+ if (row === 2 && col === 3) return { startX: 30, startY: 40, endX: 35, endY: 45 };+ if (row === 1 && col === 1) return { startX: 10, startY: 10, endX: 15, endY: 15 };+ if (row === 4 && col === 5) return { startX: 50, startY: 70, endX: 80, endY: 90 };+ return { startX: 0, startY: 0, endX: 0, endY: 0 };+ },+ } as any;++ const primary = attachPrimaryWithCoord(skeleton, {+ actualRow: 2,+ actualColumn: 3,+ isMerged: true,+ isMergedMainCell: false,+ startRow: 1,+ startColumn: 1,+ endRow: 4,+ endColumn: 5,+ } as any);++ expect(primary.actualRow).toBe(2);+ expect(primary.startX).toBe(30);+ expect(primary.mergeInfo.startX).toBe(10);+ expect(primary.mergeInfo.endY).toBe(90);++ const selection = attachSelectionWithCoord({+ range: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 5 },+ primary: {+ actualRow: 2,+ actualColumn: 3,+ isMerged: true,+ isMergedMainCell: false,+ startRow: 1,+ startColumn: 1,+ endRow: 4,+ endColumn: 5,+ },+ style: { stroke: '#000' },+ } as any, skeleton);++ expect(selection.rangeWithCoord.startX).toBe(10);+ expect(selection.primaryWithCoord?.actualColumn).toBe(3);+ expect(selection.style).toEqual({ stroke: '#000' });+ });+});diff --git a/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.ts b/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.tsnew file mode 100644index 0000000000..e9bc835aee--- /dev/null+++ b/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.ts@@ -0,0 +1,234 @@+/**+ * 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 { HorizontalAlign, IUniverInstanceService, VerticalAlign } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { describe, expect, it, vi } from 'vitest';+import { IEditorBridgeService } from '../../editor-bridge.service';+import { calcPadding, getCustomRangePosition, getEditingCustomRangePosition } from '../doc-skeleton-util';++vi.mock('@univerjs/docs-ui', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@univerjs/docs-ui')>();+ return {+ ...actual,+ DOC_VERTICAL_PADDING: 2,+ getLineBounding: () => [{ top: 1, bottom: 3, left: 2, right: 4 }],+ NodePositionConvertToCursor: class {+ getRangePointData() {+ return { borderBoxPointGroup: [{}] };+ }+ },+ };+});++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++function createDocSkeleton(customRangeId = 'range-1') {+ return {+ findNodePositionByCharIndex: () => ({ segmentPage: 0, left: 0, top: 0 }),+ getSkeletonData: () => ({+ pages: [{ height: 4, width: 6 }],+ }),+ getViewModel: () => ({+ getBody: () => ({+ customRanges: [{ rangeId: customRangeId, startIndex: 0, endIndex: 3 }],+ dataStream: 'abcdef',+ }),+ }),+ } as any;+}++describe('doc-skeleton-util', () => {+ it('calcPadding handles vertical and horizontal alignment branches', () => {+ const cell = {+ mergeInfo: {+ startX: 10,+ endX: 60,+ startY: 20,+ endY: 50,+ },+ } as any;+ const font = {+ documentSkeleton: {+ getSkeletonData: () => ({ pages: [{ height: 10, width: 20 }] }),+ },+ verticalAlign: VerticalAlign.BOTTOM,+ horizontalAlign: HorizontalAlign.RIGHT,+ } as any;++ expect(calcPadding(cell, font, false)).toEqual({ paddingTop: 20, paddingLeft: 30 });++ const middleCenter = {+ ...font,+ verticalAlign: VerticalAlign.MIDDLE,+ horizontalAlign: HorizontalAlign.CENTER,+ };+ expect(calcPadding(cell, middleCenter, false)).toEqual({ paddingTop: 10, paddingLeft: 15 });++ const unspecifiedNumeric = {+ ...font,+ verticalAlign: VerticalAlign.UNSPECIFIED,+ horizontalAlign: HorizontalAlign.UNSPECIFIED,+ };+ expect(calcPadding(cell, unspecifiedNumeric, true)).toEqual({ paddingTop: 20, paddingLeft: 30 });+ });++ it('getCustomRangePosition returns transformed rects and label', () => {+ const docSkeleton = createDocSkeleton();+ const font = {+ documentSkeleton: docSkeleton,+ verticalAlign: VerticalAlign.BOTTOM,+ horizontalAlign: HorizontalAlign.RIGHT,+ };+ const cell = {+ actualRow: 1,+ actualColumn: 2,+ mergeInfo: {+ startX: 20,+ endX: 60,+ startY: 10,+ endY: 30,+ },+ };+ const skeleton = {+ getFont: () => font,+ getCellWithCoordByIndex: () => cell,+ overflowCache: {+ forValue: (cb: (r: number, c: number, range: { startRow: number; endRow: number; startColumn: number; endColumn: number }) => void) => {+ cb(1, 2, { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 });+ },+ },+ };+ const worksheet = {+ getSheetBySheetId: undefined,+ getSheetId: () => 'sheet-1',+ getCell: () => ({ fontRenderExtension: { topOffset: 1, leftOffset: 2 } }),+ };+ const workbook = {+ getUnitId: () => 'unit-1',+ getSheetBySheetId: () => worksheet,+ };+ const renderManagerService = {+ getRenderById: () => ({+ with: () => ({+ getSkeletonParam: () => ({ skeleton }),+ }),+ }),+ };+ const injector = createAccessor([+ [IUniverInstanceService, { getUnit: () => workbook }],+ [IRenderManagerService, renderManagerService],+ ]);++ const result = getCustomRangePosition(injector, 'unit-1', 'sheet-1', 1, 2, 'range-1');+ expect(result?.label).toBe('abcd');+ expect(result?.rects).toEqual([{ top: 30, bottom: 32, left: 58, right: 60 }]);+ });++ it('getCustomRangePosition returns null for missing workbook/worksheet/customRange', () => {+ const noWorkbookInjector = createAccessor([+ [IUniverInstanceService, { getUnit: () => null }],+ [IRenderManagerService, { getRenderById: () => null }],+ ]);+ expect(getCustomRangePosition(noWorkbookInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();++ const workbook = { getSheetBySheetId: () => null };+ const noWorksheetInjector = createAccessor([+ [IUniverInstanceService, { getUnit: () => workbook }],+ [IRenderManagerService, { getRenderById: () => null }],+ ]);+ expect(getCustomRangePosition(noWorksheetInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();++ const worksheet = { getSheetId: () => 'sheet-1' };+ const emptyDocSkeleton = createDocSkeleton('other-id');+ const skeleton = {+ getFont: () => ({+ documentSkeleton: emptyDocSkeleton,+ verticalAlign: VerticalAlign.BOTTOM,+ horizontalAlign: HorizontalAlign.RIGHT,+ }),+ getCellWithCoordByIndex: () => ({+ actualRow: 1,+ actualColumn: 2,+ mergeInfo: { startX: 0, endX: 10, startY: 0, endY: 10 },+ }),+ overflowCache: { forValue: () => {} },+ };+ const noRangeInjector = createAccessor([+ [IUniverInstanceService, { getUnit: () => ({ getUnitId: () => 'unit-1', getSheetBySheetId: () => worksheet }) }],+ [IRenderManagerService, { getRenderById: () => ({ with: () => ({ getSkeletonParam: () => ({ skeleton }) }) }) }],+ ]);+ expect(getCustomRangePosition(noRangeInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();+ });++ it('getEditingCustomRangePosition handles guards and success path', () => {+ const docSkeleton = createDocSkeleton();+ const editorBridgeService = {+ getEditCellState: () => ({ editorUnitId: 'doc-1', unitId: 'unit-1', sheetId: 'sheet-1', row: 1, column: 2 }),+ isVisible: () => ({ visible: true }),+ };+ const renderManagerService = {+ getRenderById: (id: string) => {+ if (id === 'doc-1') {+ return {+ with: () => ({ getSkeleton: () => docSkeleton }),+ engine: {+ getCanvasElement: () => ({+ getBoundingClientRect: () => ({ top: 100, left: 200 }),+ }),+ },+ };+ }+ if (id === 'unit-1') {+ return {+ with: () => ({ getSkeletonParam: () => ({ skeleton: {} }) }),+ };+ }+ return null;+ },+ };+ const injector = createAccessor([+ [IEditorBridgeService, editorBridgeService],+ [IRenderManagerService, renderManagerService],+ ]);++ const result = getEditingCustomRangePosition(injector, 'unit-1', 'sheet-1', 1, 2, 'range-1');+ expect(result?.label).toBe('abcd');+ expect(result?.rects).toEqual([{ top: 97, bottom: 107, left: 202, right: 204 }]);++ const noStateInjector = createAccessor([+ [IEditorBridgeService, { getEditCellState: () => null, isVisible: () => ({ visible: true }) }],+ [IRenderManagerService, renderManagerService],+ ]);+ expect(getEditingCustomRangePosition(noStateInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();++ const hiddenInjector = createAccessor([+ [IEditorBridgeService, { getEditCellState: () => ({ editorUnitId: 'doc-1', unitId: 'unit-1', sheetId: 'sheet-1', row: 1, column: 2 }), isVisible: () => ({ visible: false }) }],+ [IRenderManagerService, renderManagerService],+ ]);+ expect(getEditingCustomRangePosition(hiddenInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();+ });+});diff --git a/packages/sheets-ui/src/services/utils/__tests__/drawing-position-util.spec.ts b/packages/sheets-ui/src/services/utils/__tests__/drawing-position-util.spec.tsnew file mode 100644index 0000000000..a2b4546e1e--- /dev/null+++ b/packages/sheets-ui/src/services/utils/__tests__/drawing-position-util.spec.ts@@ -0,0 +1,108 @@+/**+ * 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 { convertPositionCellToSheetOverGrid, convertPositionSheetOverGridToAbsolute } from '../drawing-position-util';++describe('drawing-position-util', () => {+ it('should convert sheet-over-grid position to absolute transform', () => {+ const skeleton = {+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => {+ if (row === 1 && col === 1) return { startX: 10, startY: 20, endX: 30, endY: 40 };+ if (row === 3 && col === 4) return { startX: 60, startY: 80, endX: 90, endY: 120 };+ return { startX: 0, startY: 0, endX: 0, endY: 0 };+ },+ };++ const result = convertPositionSheetOverGridToAbsolute('u1', 's1', {+ from: { row: 1, column: 1, rowOffset: 0.26, columnOffset: 0.24 },+ to: { row: 3, column: 4, rowOffset: 4.44, columnOffset: 5.55 },+ } as any, {+ ensureSkeleton: () => skeleton,+ } as any);++ expect(result).toEqual({+ unitId: 'u1',+ subUnitId: 's1',+ left: 10.2,+ top: 20.3,+ width: 55.4,+ height: 64.1,+ });+ });++ it('should convert cell-over-grid position to sheet transform', () => {+ const skeleton = {+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => {+ if (row === 2 && col === 3) return { startX: 10, startY: 20, endX: 20, endY: 30 };+ return { startX: 0, startY: 0, endX: 0, endY: 0 };+ },+ };++ const result = convertPositionCellToSheetOverGrid('u1', 's1', {+ row: 2,+ column: 3,+ rowOffset: 0.3,+ columnOffset: 0.2,+ } as any, 50, 40, {+ getCellWithCoordByOffset: () => ({+ actualColumn: 9,+ actualRow: 8,+ startX: 55.7,+ startY: 58.9,+ }),+ } as any, {+ ensureSkeleton: () => skeleton,+ } as any);++ expect(result).toEqual({+ unitId: 'u1',+ subUnitId: 's1',+ sheetTransform: {+ from: { row: 2, column: 3, rowOffset: 0.3, columnOffset: 0.2 },+ to: { row: 8, column: 9, rowOffset: 1.4, columnOffset: 4.5 },+ },+ transform: {+ left: 10.2,+ top: 20.3,+ width: 50,+ height: 40,+ },+ });+ });++ it('should throw when skeleton or end cell is missing', () => {+ expect(() => convertPositionSheetOverGridToAbsolute('u1', 's1', {+ from: { row: 0, column: 0, rowOffset: 0, columnOffset: 0 },+ to: { row: 0, column: 0, rowOffset: 0, columnOffset: 0 },+ } as any, { ensureSkeleton: () => null } as any)).toThrow(/No current skeleton/);++ const skeleton = {+ getNoMergeCellWithCoordByIndex: () => ({ startX: 10, startY: 20, endX: 20, endY: 30 }),+ };++ expect(() => convertPositionCellToSheetOverGrid('u1', 's1', {+ row: 1,+ column: 1,+ rowOffset: 0,+ columnOffset: 0,+ } as any, 10, 10, {+ getCellWithCoordByOffset: () => null,+ } as any, {+ ensureSkeleton: () => skeleton,+ } as any)).toThrow(/No end selection cell/);+ });+});diff --git a/packages/sheets-ui/src/services/utils/__tests__/selection-util.spec.ts b/packages/sheets-ui/src/services/utils/__tests__/selection-util.spec.tsnew file mode 100644index 0000000000..1f81af16e1--- /dev/null+++ b/packages/sheets-ui/src/services/utils/__tests__/selection-util.spec.ts@@ -0,0 +1,34 @@+/**+ * 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 { createCopyPasteSelectionStyle } from '../selection-util';++describe('services/utils/selection-util', () => {+ it('should create copy-paste selection style based on theme color', () => {+ const style = createCopyPasteSelectionStyle({+ getColorFromTheme: () => '#3366ff',+ } as any);++ expect(style).toEqual({+ strokeWidth: 1.5,+ stroke: '#3366ff',+ fill: 'rgba(178, 178, 178, 0.10)',+ widgets: {},+ strokeDash: 8,+ });+ });+});diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/animate.spec.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/animate.spec.tsnew file mode 100644index 0000000000..523402f6a5--- /dev/null+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/animate.spec.ts@@ -0,0 +1,90 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { Animate } from '../animate';++describe('animate util', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('runs request -> success -> complete path', () => {+ let now = 0;+ const receive = vi.fn();+ const success = vi.fn();+ const complete = vi.fn();+ vi.spyOn(Date, 'now').mockImplementation(() => {+ now += 10;+ return now;+ });++ const animate = new Animate({+ begin: 0,+ end: 100,+ duration: 10,+ receive,+ success,+ complete,+ });+ animate.request();++ expect(receive).toHaveBeenCalled();+ expect(success).toHaveBeenCalled();+ expect(complete).toHaveBeenCalled();+ });++ it('runs cancel callback when animation was canceled', () => {+ let rafCallback: (() => void) | null = null;+ vi.spyOn(Date, 'now').mockImplementation(() => 0);+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb: FrameRequestCallback) => {+ rafCallback = () => cb(0);+ return 1;+ });+ const cancelAnimationFrameSpy = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});+ const cancel = vi.fn();+ const complete = vi.fn();+ const receive = vi.fn();++ const animate = new Animate({+ begin: 0,+ end: 100,+ duration: 100,+ receive,+ cancel,+ complete,+ });+ animate.request();+ animate.cancel();+ (animate as any)._fakeHandle();++ expect(receive).toHaveBeenCalled();+ expect(cancelAnimationFrameSpy).toHaveBeenCalledWith(1);+ expect(cancel).toHaveBeenCalled();+ expect(complete).toHaveBeenCalled();+ });++ it('Animate.success resolves after all non-loop animations succeed', async () => {+ const a1 = new Animate({ loop: false });+ const a2 = new Animate({ loop: false });+ const promise = Animate.success(a1, a2);++ (a1 as any)._config.success(1);+ (a2 as any)._config.success(2);++ await expect(promise).resolves.toBeUndefined();+ });+});diff --git a/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.ts b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.tsnew file mode 100644index 0000000000..92c82e5fac--- /dev/null+++ b/packages/sheets-ui/src/views/sheet-bar/sheet-bar-tabs/utils/__tests__/slide-tab-bar.spec.ts@@ -0,0 +1,256 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { SlideTabBar, SlideTabItem } from '../slide-tab-bar';++function rect(x: number, width: number, y = 0, height = 24): DOMRect {+ return {+ x,+ y,+ left: x,+ top: y,+ width,+ height,+ right: x + width,+ bottom: y + height,+ toJSON: () => ({}),+ } as DOMRect;+}++function setupDOM() {+ const root = document.createElement('div');+ const bar = document.createElement('div');+ bar.className = 'tab-bar';+ root.appendChild(bar);+ document.body.appendChild(root);++ const itemLefts = [0, 45, 90];+ const itemWidths = [40, 40, 40];+ for (let i = 0; i < 3; i++) {+ const item = document.createElement('div');+ item.className = 'tab-item';+ item.dataset.id = `sheet-${i}`;+ const span = document.createElement('span');+ span.innerText = `Sheet ${i}`;+ item.appendChild(span);+ bar.appendChild(item);+ }++ let scrollLeft = 0;+ Object.defineProperty(root, 'clientWidth', { configurable: true, value: 100 });+ Object.defineProperty(bar, 'scrollWidth', { configurable: true, value: 220 });+ Object.defineProperty(bar, 'scrollLeft', {+ configurable: true,+ get() {+ return scrollLeft;+ },+ set(v: number) {+ scrollLeft = v;+ },+ });++ vi.spyOn(bar, 'getBoundingClientRect').mockImplementation(() => rect(0, 100));++ Array.from(bar.querySelectorAll('.tab-item')).forEach((item, idx) => {+ vi.spyOn(item, 'getBoundingClientRect').mockImplementation(() => rect(itemLefts[idx], itemWidths[idx]));+ });++ return {+ root,+ bar,+ onScroll: vi.fn(),+ onSlideEnd: vi.fn(),+ onChangeTab: vi.fn(),+ onChangeName: vi.fn(),+ };+}++describe('slide-tab-bar', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ document.body.innerHTML = '';+ });++ it('guards invalid constructor config', () => {+ expect(() => new SlideTabBar({ slideTabBarContainer: null as any })).toThrowError('not found slide-tab-bar root element');+ const root = document.createElement('div');+ expect(() => new SlideTabBar({+ slideTabBarContainer: root as any,+ slideTabBarSelector: '.missing',+ })).toThrowError('not found slide-tab-bar');+ });++ it('handles scroll and calculation utilities', () => {+ const { root, onScroll, onSlideEnd, onChangeTab, onChangeName } = setupDOM();+ const bar = new SlideTabBar({+ slideTabBarSelector: '.tab-bar',+ slideTabBarItemSelector: '.tab-item',+ slideTabBarContainer: root as HTMLDivElement,+ slideTabBarItemAutoSort: true,+ currentIndex: 0,+ onScroll,+ onSlideEnd,+ onChangeTab,+ onChangeName,+ onNameCheckAlert: () => false,+ onNameChangeCheck: () => true,+ });++ expect(bar.getSlideTabItems().length).toBe(3);+ expect(bar.isLeftEnd()).toBe(true);+ expect(bar.isRightEnd()).toBe(false);+ expect(bar.calculateLeftScrollX()).toBeGreaterThanOrEqual(0);+ expect(bar.calculateRightScrollX()).toBeLessThanOrEqual(0);+ expect(bar.calculateTabItemScrollX(2)).toBeGreaterThanOrEqual(0);++ bar.setScroll(20);+ bar.setScroll(-10);+ bar.flipPage(1);+ bar.flipPage(-1);+ bar.scrollToItem(2);++ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ bar.scrollToItem(99);+ expect(errorSpy).toHaveBeenCalled();+ expect(onScroll).toHaveBeenCalled();++ bar.update(1);+ expect(bar.getActiveItem()?.getId()).toBe('sheet-1');++ bar.destroy();+ expect(bar.getSlideTabItems()).toEqual([]);+ });++ it('supports edit/fixed/animate behaviors on SlideTabItem', async () => {+ const { root, onScroll, onSlideEnd, onChangeTab, onChangeName } = setupDOM();+ const bar = new SlideTabBar({+ slideTabBarSelector: '.tab-bar',+ slideTabBarItemSelector: '.tab-item',+ slideTabBarContainer: root as HTMLDivElement,+ slideTabBarItemAutoSort: true,+ currentIndex: 0,+ onScroll,+ onSlideEnd,+ onChangeTab,+ onChangeName,+ onNameCheckAlert: () => false,+ onNameChangeCheck: () => true,+ });++ const item = bar.getSlideTabItems()[0];+ const editor = item.getEditor() as HTMLSpanElement;+ expect(SlideTabItem.leftLine(item)).toBe(0);+ expect(SlideTabItem.rightLine(item)).toBe(40);+ expect(item.translateX(10)).toBeTypeOf('number');+ expect(item.classList()).toBe(item.getSlideTabItem().classList);+ expect(item.equals(item)).toBe(true);++ const callback = vi.fn();+ item.setEditor(callback);+ expect(editor.getAttribute('contentEditable')).toBe('true');+ editor.innerText = 'Renamed';+ editor.dispatchEvent(new FocusEvent('focusout'));++ expect(onChangeName).toHaveBeenCalledWith('sheet-0', 'Renamed');+ expect(callback).toHaveBeenCalled();++ item.enableFixed();+ expect(document.body.contains(item.getSlideTabItem())).toBe(true);+ item.disableFixed();+ expect(item.getSlideTabItem().style.position).toBe('');++ const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1);+ const cafSpy = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});+ const anim = item.animate();+ anim.translateX(30);+ anim.cancel();+ expect(rafSpy).toHaveBeenCalled();+ expect(cafSpy).toHaveBeenCalled();+ });++ it('covers internal compare/sort/auto-scroll branches', () => {+ const { root, onScroll, onSlideEnd, onChangeTab, onChangeName } = setupDOM();+ const bar = new SlideTabBar({+ slideTabBarSelector: '.tab-bar',+ slideTabBarItemSelector: '.tab-item',+ slideTabBarContainer: root as HTMLDivElement,+ slideTabBarItemAutoSort: true,+ currentIndex: 1,+ onScroll,+ onSlideEnd,+ onChangeTab,+ onChangeName,+ onNameCheckAlert: () => false,+ onNameChangeCheck: () => true,+ });++ const items = bar.getSlideTabItems();+ const active = items[1];+ let activeX = 45;+ active.getBoundingRect = () => rect(activeX, 40);+ (bar as any)._activeTabItem = active;+ (bar as any)._activeTabItemIndex = 1;++ activeX = 110;+ (bar as any)._compareRight();+ expect((bar as any)._compareIndex).toBeGreaterThanOrEqual(1);++ activeX = -30;+ (bar as any)._compareLeft();+ expect((bar as any)._compareIndex).toBeLessThanOrEqual(1);++ (bar as any)._compareIndex = 0;+ (bar as any)._sortedItems();+ expect(bar.getSlideTabItems()[0].getId()).toBe('sheet-1');++ (bar as any)._leftBoundingLine = 20;+ (bar as any)._rightBoundingLine = 20;+ (bar as any)._scrollIncremental = 0;+ (bar as any)._scrollLeft({ pageX: 0 } as MouseEvent);+ expect((bar as any)._scrollIncremental).toBeLessThanOrEqual(0);+ (bar as any)._scrollRight({ pageX: 500 } as MouseEvent);+ expect((bar as any)._scrollIncremental).toBeGreaterThanOrEqual(0);++ const rafSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 2);+ const cafSpy = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});+ (bar as any)._moveActionX = 10;+ (bar as any)._startAutoScroll();+ expect((bar as any)._autoScrollTime).toBe(2);+ (bar as any)._closeAutoScroll();+ expect((bar as any)._autoScrollTime).toBeNull();+ expect(rafSpy).toHaveBeenCalled();+ expect(cafSpy).toHaveBeenCalled();+ });++ it('handles static selection helpers', () => {+ const el = document.createElement('span');+ el.innerText = 'abc';+ document.body.appendChild(el);++ SlideTabBar.keepSelectAll(el);+ SlideTabBar.keepLastIndex(el);++ const skip = document.createElement('div');+ skip.setAttribute('data-slide-skip', '1');+ const child = document.createElement('span');+ skip.appendChild(child);+ document.body.appendChild(skip);++ expect(SlideTabBar.checkedSkipSlide({ target: child } as unknown as MouseEvent)).toBe(true);+ expect(SlideTabBar.checkedSkipSlide({ target: document.body } as unknown as MouseEvent)).toBe(false);+ });+});diff --git a/packages/sheets-zen-editor/src/commands/commands/__tests__/zen-editor.command.spec.ts b/packages/sheets-zen-editor/src/commands/commands/__tests__/zen-editor.command.spec.tsnew file mode 100644index 0000000000..f1bbf32242--- /dev/null+++ b/packages/sheets-zen-editor/src/commands/commands/__tests__/zen-editor.command.spec.ts@@ -0,0 +1,193 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DOCS_ZEN_EDITOR_UNIT_ID_KEY, DocumentFlavor, IUniverInstanceService } from '@univerjs/core';+import { IEditorService } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';+import { IEditorBridgeService } from '@univerjs/sheets-ui';+import { ISidebarService, IZenZoneService } from '@univerjs/ui';+import { describe, expect, it, vi } from 'vitest';+import { CancelZenEditCommand, ConfirmZenEditCommand, OpenZenEditorCommand } from '../zen-editor.command';++function createAccessor(pairs: Array<[unknown, unknown]>) {+ const map = new Map<unknown, unknown>(pairs);+ return {+ get(token: unknown) {+ if (!map.has(token)) {+ throw new Error(`Unknown token: ${String(token)}`);+ }+ return map.get(token);+ },+ } as any;+}++describe('zen-editor commands', () => {+ it('OpenZenEditorCommand should clone edit snapshot into zen editor and clear history', async () => {+ const zenZoneService = { open: vi.fn() };+ const setDocumentData = vi.fn();+ const editor = {+ getDocumentData: () => ({ id: 'zen-doc-origin', documentStyle: {}, body: { dataStream: 'origin' } }),+ focus: vi.fn(),+ setDocumentData,+ clearUndoRedoHistory: vi.fn(),+ };++ const accessor = createAccessor([+ [IZenZoneService, zenZoneService],+ [IEditorService, { getEditor: () => editor }],+ [IEditorBridgeService, {+ getLatestEditCellState: () => ({+ documentLayoutObject: {+ documentModel: {+ getSnapshot: () => ({+ body: { dataStream: 'new content' },+ drawings: { d1: {} },+ drawingsOrder: ['d1'],+ tableSource: { source: 'table' },+ settings: { zoomRatio: 2 },+ }),+ },+ },+ }),+ }],+ [IUniverInstanceService, { focusUnit: vi.fn() }],+ [ISidebarService, { visible: false }],+ ]);++ const result = await OpenZenEditorCommand.handler(accessor);++ expect(result).toBe(true);+ expect(zenZoneService.open).toHaveBeenCalled();+ expect(editor.focus).toHaveBeenCalled();+ expect(setDocumentData).toHaveBeenCalledWith(expect.objectContaining({+ id: 'zen-doc-origin',+ body: { dataStream: 'new content' },+ drawings: { d1: {} },+ drawingsOrder: ['d1'],+ tableSource: { source: 'table' },+ settings: { zoomRatio: 2 },+ }), [{ startOffset: 0, endOffset: 0, collapsed: true }]);+ expect(editor.clearUndoRedoHistory).toHaveBeenCalled();+ });++ it('OpenZenEditorCommand should fail when editor or edit snapshot is missing', async () => {+ const noEditorAccessor = createAccessor([+ [IZenZoneService, { open: vi.fn() }],+ [IEditorService, { getEditor: () => null }],+ [IEditorBridgeService, { getLatestEditCellState: () => null }],+ [IUniverInstanceService, { focusUnit: vi.fn() }],+ [ISidebarService, { visible: false }],+ ]);+ await expect(OpenZenEditorCommand.handler(noEditorAccessor)).resolves.toBe(false);++ const noSnapshotAccessor = createAccessor([+ [IZenZoneService, { open: vi.fn() }],+ [IEditorService, { getEditor: () => ({ getDocumentData: () => ({ documentStyle: {} }), focus: vi.fn(), setDocumentData: vi.fn(), clearUndoRedoHistory: vi.fn() }) }],+ [IEditorBridgeService, { getLatestEditCellState: () => ({ documentLayoutObject: { documentModel: { getSnapshot: () => null } } }) }],+ [IUniverInstanceService, { focusUnit: vi.fn() }],+ [ISidebarService, { visible: false }],+ ]);+ await expect(OpenZenEditorCommand.handler(noSnapshotAccessor)).resolves.toBe(false);+ });++ it('CancelZenEditCommand should close zen zone and return to current sheet', async () => {+ const focusUnit = vi.fn();+ const refreshEditCellState = vi.fn();++ const result = await CancelZenEditCommand.handler(createAccessor([+ [IZenZoneService, { close: vi.fn() }],+ [IEditorBridgeService, { refreshEditCellState }],+ [IUniverInstanceService, {+ getCurrentUnitForType: () => ({ getUnitId: () => 'sheet-unit' }),+ focusUnit,+ }],+ [ISidebarService, { visible: false }],+ ]));++ expect(result).toBe(true);+ expect(focusUnit).toHaveBeenCalledWith('sheet-unit');+ expect(refreshEditCellState).toHaveBeenCalled();+ });++ it('CancelZenEditCommand should return false without an active sheet', async () => {+ const result = await CancelZenEditCommand.handler(createAccessor([+ [IZenZoneService, { close: vi.fn() }],+ [IEditorBridgeService, { refreshEditCellState: vi.fn() }],+ [IUniverInstanceService, { getCurrentUnitForType: () => null, focusUnit: vi.fn() }],+ [ISidebarService, { visible: false }],+ ]));++ expect(result).toBe(false);+ });++ it('ConfirmZenEditCommand should submit doc snapshot back to sheet editor', async () => {+ const submitCellData = vi.fn();+ const refreshEditCellState = vi.fn();+ const focusUnit = vi.fn();++ const result = await ConfirmZenEditCommand.handler(createAccessor([+ [IZenZoneService, { close: vi.fn() }],+ [IEditorBridgeService, { refreshEditCellState }],+ [IUniverInstanceService, {+ getCurrentUnitForType: () => ({ getUnitId: () => 'sheet-unit' }),+ focusUnit,+ }],+ [IEditorService, {+ getEditor: (unitId: string) => {+ if (unitId !== DOCS_ZEN_EDITOR_UNIT_ID_KEY) {+ return null;+ }+ return {+ getDocumentData: () => ({+ id: 'doc-1',+ documentStyle: { documentFlavor: DocumentFlavor.UNSPECIFIED },+ body: { dataStream: '' },+ }),+ };+ },+ }],+ [IRenderManagerService, {+ getRenderById: () => ({+ with: () => ({ submitCellData }),+ }),+ }],+ [ISidebarService, { visible: false }],+ ]));++ expect(result).toBe(true);+ expect(submitCellData).toHaveBeenCalledTimes(1);+ const submittedModel = submitCellData.mock.calls[0][0];+ expect(submittedModel.getSnapshot().documentStyle.documentFlavor).toBe(DocumentFlavor.UNSPECIFIED);+ expect(focusUnit).toHaveBeenCalledWith('sheet-unit');+ expect(refreshEditCellState).toHaveBeenCalled();+ });++ it('ConfirmZenEditCommand should return false without zen editor instance', async () => {+ const result = await ConfirmZenEditCommand.handler(createAccessor([+ [IZenZoneService, { close: vi.fn() }],+ [IEditorBridgeService, { refreshEditCellState: vi.fn() }],+ [IUniverInstanceService, {+ getCurrentUnitForType: () => ({ getUnitId: () => 'sheet-unit' }),+ focusUnit: vi.fn(),+ }],+ [IEditorService, { getEditor: () => null }],+ [IRenderManagerService, { getRenderById: () => null }],+ [ISidebarService, { visible: false }],+ ]));++ expect(result).toBe(false);+ });+});diff --git a/packages/sheets-zen-editor/src/controllers/__tests__/zen-editor-ui.controller.spec.ts b/packages/sheets-zen-editor/src/controllers/__tests__/zen-editor-ui.controller.spec.tsnew file mode 100644index 0000000000..162d48c453--- /dev/null+++ b/packages/sheets-zen-editor/src/controllers/__tests__/zen-editor-ui.controller.spec.ts@@ -0,0 +1,42 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';+import { ZEN_EDITOR_COMPONENT } from '../../views/zen-editor';+import { ZenEditorUIController } from '../zen-editor-ui.controller';++describe('ZenEditorUIController', () => {+ it('should register zen component, commands, menus and shortcuts', () => {+ const set = vi.fn(() => ({ dispose: vi.fn() }));+ const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));+ const mergeMenu = vi.fn();+ const registerShortcut = vi.fn(() => ({ dispose: vi.fn() }));++ const controller = new ZenEditorUIController(+ { set } as any,+ { registerCommand } as any,+ { mergeMenu } as any,+ { registerShortcut } as any+ );++ expect(set).toHaveBeenCalledWith(ZEN_EDITOR_COMPONENT, expect.any(Function));+ expect(registerCommand).toHaveBeenCalledTimes(3);+ expect(mergeMenu).toHaveBeenCalledTimes(1);+ expect(registerShortcut).toHaveBeenCalledTimes(2);++ controller.dispose();+ });+});diff --git a/packages/sheets-zen-editor/src/controllers/__tests__/zen-editor.controller.spec.ts b/packages/sheets-zen-editor/src/controllers/__tests__/zen-editor.controller.spec.tsnew file mode 100644index 0000000000..434559b4ac--- /dev/null+++ b/packages/sheets-zen-editor/src/controllers/__tests__/zen-editor.controller.spec.ts@@ -0,0 +1,100 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { ZenEditorController } from '../zen-editor.controller';++describe('ZenEditorController', () => {+ it('should calculate page placement and sync viewport scroll', () => {+ const resize = vi.fn();+ const translateDoc = vi.fn();+ const translateBg = vi.fn();+ const scrollToBarPos = vi.fn();++ const controller = new ZenEditorController(+ { position$: new Subject() } as any,+ { getRenderById: vi.fn(() => null) } as any+ );++ (controller as any)._calculatePagePosition({+ document: {+ width: 200,+ height: 300,+ pageMarginLeft: 20,+ pageMarginTop: 10,+ translate: translateDoc,+ },+ scene: {+ getParent: () => ({ width: 600, height: 500 }),+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),+ resize,+ getViewport: () => ({+ transScroll2ViewportScrollValue: (x: number) => ({ x }),+ scrollToBarPos,+ }),+ },+ docBackground: {+ translate: translateBg,+ },+ });++ expect(resize).toHaveBeenCalled();+ expect(translateDoc).toHaveBeenCalled();+ expect(translateBg).toHaveBeenCalled();+ expect(scrollToBarPos).toHaveBeenCalled();++ controller.dispose();+ });++ it('should ignore invalid render state and still support scroll-to-top helper', () => {+ const scrollToRange = vi.fn();+ const controller = new ZenEditorController(+ { position$: new Subject() } as any,+ {+ getRenderById: () => ({+ with: () => ({ scrollToRange }),+ }),+ } as any+ );++ const result = (controller as any)._calculatePagePosition({+ document: {+ width: Number.POSITIVE_INFINITY,+ height: Number.POSITIVE_INFINITY,+ pageMarginLeft: 20,+ pageMarginTop: 10,+ translate: vi.fn(),+ },+ scene: {+ getParent: () => null,+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),+ resize: vi.fn(),+ getViewport: vi.fn(),+ },+ docBackground: {+ translate: vi.fn(),+ },+ });++ expect(result).toBeUndefined();++ (controller as any)._scrollToTop();+ expect(scrollToRange).toHaveBeenCalledWith({ startOffset: 0, endOffset: 0 });++ controller.dispose();+ });+});diff --git a/packages/sheets-zen-editor/src/controllers/shortcuts/__tests__/zen-editor.shortcut.spec.ts b/packages/sheets-zen-editor/src/controllers/shortcuts/__tests__/zen-editor.shortcut.spec.tsnew file mode 100644index 0000000000..7846c9b3a7--- /dev/null+++ b/packages/sheets-zen-editor/src/controllers/shortcuts/__tests__/zen-editor.shortcut.spec.ts@@ -0,0 +1,49 @@+/**+ * 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 { EDITOR_ACTIVATED, FOCUSING_DOC, FOCUSING_EDITOR_STANDALONE, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { whenZenEditorActivated, ZenEditorCancelShortcut, ZenEditorConfirmShortcut } from '../zen-editor.shortcut';++function createContext(values: Record<string, boolean>) {+ return {+ getContextValue: (key: string) => values[key] ?? false,+ } as any;+}++describe('zen editor shortcuts', () => {+ it('should activate only when doc/editor are focused and standalone editor is off', () => {+ const context = createContext({+ [FOCUSING_DOC]: true,+ [FOCUSING_UNIVER_EDITOR]: true,+ [EDITOR_ACTIVATED]: true,+ [FOCUSING_EDITOR_STANDALONE]: false,+ });++ expect(whenZenEditorActivated(context)).toBe(true);+ expect(ZenEditorConfirmShortcut.preconditions?.(context as any)).toBe(true);+ expect(ZenEditorCancelShortcut.preconditions?.(context as any)).toBe(true);++ const standaloneContext = createContext({+ [FOCUSING_DOC]: true,+ [FOCUSING_UNIVER_EDITOR]: true,+ [EDITOR_ACTIVATED]: true,+ [FOCUSING_EDITOR_STANDALONE]: true,+ });++ expect(whenZenEditorActivated(standaloneContext)).toBe(false);+ });+});diff --git a/packages/sheets-zen-editor/src/services/__tests__/zen-editor.service.spec.ts b/packages/sheets-zen-editor/src/services/__tests__/zen-editor.service.spec.tsnew file mode 100644index 0000000000..5aed2660fc--- /dev/null+++ b/packages/sheets-zen-editor/src/services/__tests__/zen-editor.service.spec.ts@@ -0,0 +1,36 @@+/**+ * 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 { ZenEditorManagerService } from '../zen-editor.service';++describe('ZenEditorManagerService', () => {+ it('should expose and publish position updates', () => {+ const service = new ZenEditorManagerService();+ const values: Array<DOMRect | null | undefined | void> = [];+ const subscription = service.position$.subscribe((value) => values.push(value));++ const rect = new DOMRect(10, 20, 300, 200);+ service.setPosition(rect);++ expect(service.getPosition()).toBe(rect);+ expect(values).toEqual([null, rect]);++ subscription.unsubscribe();+ service.dispose();+ expect(service.getPosition()).toBeNull();+ });+});diff --git a/packages/sheets/src/basics/__tests__/utils.spec.ts b/packages/sheets/src/basics/__tests__/utils.spec.tsindex 8b98a44204..deeacff1c1 100644--- a/packages/sheets/src/basics/__tests__/utils.spec.ts+++ b/packages/sheets/src/basics/__tests__/utils.spec.ts@@ -14,10 +14,28 @@* limitations under the License.*/-import type { IRange } from '@univerjs/core';-import { cellToRange } from '@univerjs/core';-import { describe, expect, it } from 'vitest';-import { generateNullCell, generateNullCellStyle, generateNullCellValue } from '../utils';+import type { IAccessor, IRange } from '@univerjs/core';+import { cellToRange, IUniverInstanceService } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import {+ createUniqueKey,+ discreteRangeToRange,+ findFirstNonEmptyCell,+ generateNullCell,+ generateNullCellStyle,+ generateNullCellValue,+ getActiveWorksheet,+ getVisibleRanges,+ groupByKey,+ rangeToDiscreteRange,+} from '../utils';++function createAccessor(getter: (token: unknown) => unknown): IAccessor {+ return {+ get: (token: unknown) => getter(token) as never,+ has: () => true,+ } as unknown as IAccessor;+}describe('Test utils', () => {it('Test generateNullCell', () => {@@ -68,4 +86,178 @@ describe('Test utils', () => {},});});++ it('Test groupByKey', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => { });+ const grouped = groupByKey(+ [+ { key: 'fallback', v: 1 },+ { key: 'a', v: 2 },+ { key: '', v: 3 },+ { key: 42, v: 4 } as unknown as { key: string; v: number },+ ],+ 'key',+ 'fallback'+ );++ expect(grouped.a).toEqual([{ key: 'a', v: 2 }]);+ expect(grouped.fallback).toEqual([+ { key: 'fallback', v: 1 },+ { key: '', v: 3 },+ ]);+ expect(warnSpy).toHaveBeenCalled();+ warnSpy.mockRestore();+ });++ it('Test createUniqueKey', () => {+ const getKey = createUniqueKey(2);+ expect(getKey()).toBe(2);+ expect(getKey()).toBe(3);+ });++ it('Test findFirstNonEmptyCell', () => {+ const worksheet = {+ getCell: (row: number, col: number) => {+ if (row === 1 && col === 0) {+ return { p: { body: {} } };+ }+ return null;+ },+ };+ const range = { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 };++ expect(findFirstNonEmptyCell(range, worksheet as never)).toEqual({+ startRow: 1,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+ });+ });++ it('Test getActiveWorksheet', () => {+ const worksheet = { id: 'sheet-1' };+ const workbook = {+ getActiveSheet: () => worksheet,+ };+ const instanceService = {+ getCurrentUnitForType: () => workbook,+ };++ const [currentWorkbook, currentWorksheet] = getActiveWorksheet(instanceService as never);+ expect(currentWorkbook).toBe(workbook);+ expect(currentWorksheet).toBe(worksheet);+ });++ it('Test discreteRangeToRange', () => {+ expect(+ discreteRangeToRange({+ rows: [2, 4, 5],+ cols: [3, 6],+ })+ ).toEqual({+ startRow: 2,+ endRow: 5,+ startColumn: 3,+ endColumn: 6,+ });+ });++ it('Test rangeToDiscreteRange', () => {+ const worksheet = {+ getRowFiltered: (row: number) => row === 1,+ };+ const workbook = {+ getSheetBySheetId: () => worksheet,+ getActiveSheet: () => worksheet,+ };+ const instanceService = {+ getUnit: () => workbook,+ getCurrentUnitForType: () => workbook,+ };+ const accessor = createAccessor((token) => {+ if (token === IUniverInstanceService) {+ return instanceService;+ }+ return null;+ });++ expect(+ rangeToDiscreteRange(+ { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },+ accessor,+ 'unit-1',+ 'sheet-1'+ )+ ).toEqual({+ rows: [0, 2],+ cols: [0, 1],+ });+ });++ it('Test rangeToDiscreteRange returns null without worksheet', () => {+ const instanceService = {+ getUnit: () => null,+ getCurrentUnitForType: () => null,+ };+ const accessor = createAccessor((token) => {+ if (token === IUniverInstanceService) {+ return instanceService;+ }+ return null;+ });++ expect(+ rangeToDiscreteRange(+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ accessor+ )+ ).toBeNull();+ });++ it('Test getVisibleRanges', () => {+ const worksheet = {+ getRowFiltered: (row: number) => row === 1 || row === 4,+ getSheetId: () => 'sheet-1',+ };+ const workbook = {+ getSheetBySheetId: () => worksheet,+ getActiveSheet: () => worksheet,+ getUnitId: () => 'unit-1',+ };+ const instanceService = {+ getCurrentUnitOfType: () => workbook,+ getUnit: () => workbook,+ };+ const accessor = createAccessor((token) => {+ if (token === IUniverInstanceService) {+ return instanceService;+ }+ return null;+ });++ const ranges = [+ { startRow: 0, endRow: 3, startColumn: 0, endColumn: 0 },+ { startRow: 4, endRow: 6, startColumn: 0, endColumn: 0 },+ { startRow: 0, endRow: 1, startColumn: 1, endColumn: 1 },+ ];+ expect(getVisibleRanges(ranges, accessor, 'unit-1', 'sheet-1')).toEqual([+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ { startRow: 2, endRow: 3, startColumn: 0, endColumn: 0 },+ { startRow: 5, endRow: 6, startColumn: 0, endColumn: 0 },+ { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 },+ ]);+ });++ it('Test getVisibleRanges fallback without target', () => {+ const accessor = createAccessor((token) => {+ if (token === IUniverInstanceService) {+ return {+ getCurrentUnitOfType: () => null,+ };+ }+ return null;+ });+ const ranges = [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }];+ expect(getVisibleRanges(ranges, accessor)).toEqual(ranges);+ });});diff --git a/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.tsindex 7708c65bc8..eb53521ef7 100644--- a/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.ts+++ b/packages/sheets/src/commands/commands/__tests__/copy-worksheet.command.spec.ts@@ -15,10 +15,13 @@*/import type { Injector, Univer, Workbook, Worksheet } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, LocaleService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { ICommandService, IConfigService, IUniverInstanceService, LocaleService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SHEETS_PLUGIN_CONFIG_KEY } from '../../../controllers/config.schema';import enUS from '../../../locale/en-US';import zhCN from '../../../locale/zh-CN';+import { SheetLazyExecuteScheduleService } from '../../../services/lazy-execute-schedule.service';+import { CopyWorksheetEndMutation } from '../../mutations/copy-worksheet-end.mutation';import { InsertSheetMutation } from '../../mutations/insert-sheet.mutation';import { RemoveSheetMutation } from '../../mutations/remove-sheet.mutation';import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';@@ -43,6 +46,7 @@ describe('Test copy worksheet commands', () => {commandService.registerCommand(InsertSheetMutation);commandService.registerCommand(SetRangeValuesMutation);commandService.registerCommand(SetWorksheetActiveOperation);+ commandService.registerCommand(CopyWorksheetEndMutation);commandService.registerCommand(SetWorksheetActivateCommand);commandService.registerCommand(RemoveSheetCommand);commandService.registerCommand(RemoveSheetMutation);@@ -118,6 +122,50 @@ describe('Test copy worksheet commands', () => {expect(getCopyUniqueSheetName(workbook, localeService, name)).toBe('Sheet1 (Copy2)');});++ it('split large sheet copy should schedule remaining mutations and disable redo', async () => {+ const sourceWorkbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const sourceSheet = sourceWorkbook.getActiveSheet();+ sourceSheet.getCellMatrix().setValue(1, 0, { v: 'B1' });+ expect(sourceSheet.getConfig().cellData[1]).toBeDefined();++ const configService = get(IConfigService);+ configService.setConfig(SHEETS_PLUGIN_CONFIG_KEY, {+ largeSheetOperation: {+ largeSheetCellCountThreshold: 1,+ batchSize: 2,+ },+ });++ const scheduleService = get(SheetLazyExecuteScheduleService);+ const scheduleSpy = vi.spyOn(scheduleService, 'scheduleMutations');+ const syncSpy = vi.spyOn(commandService, 'syncExecuteCommand');++ expect(+ await commandService.executeCommand(CopySheetCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ })+ ).toBeTruthy();++ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ expect(workbook.getSheetSize()).toBe(2);+ expect(scheduleSpy).toHaveBeenCalledTimes(1);++ const [, copiedSheetId, scheduledMutations] = scheduleSpy.mock.calls[0] as unknown as [string, string, Array<{ id: string }>];+ expect(copiedSheetId).toBeTruthy();+ expect(scheduledMutations.length).toBeGreaterThan(0);++ const syncOnlyCalls = syncSpy.mock.calls.filter(([, , options]) => Boolean(options?.syncOnly));+ expect(syncOnlyCalls.length).toBeGreaterThan(0);+ expect(syncOnlyCalls.some(([id]) => id === CopyWorksheetEndMutation.id)).toBeTruthy();++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(workbook.getSheetSize()).toBe(1);+ // split mode writes empty redoMutations+ expect(await commandService.executeCommand(RedoCommand.id)).toBe(false);+ expect(workbook.getSheetSize()).toBe(1);+ });});});});diff --git a/packages/sheets/src/commands/commands/__tests__/remove-worksheet-merge.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/remove-worksheet-merge.command.spec.tsnew file mode 100644index 0000000000..b11662a4a7--- /dev/null+++ b/packages/sheets/src/commands/commands/__tests__/remove-worksheet-merge.command.spec.ts@@ -0,0 +1,137 @@+/**+ * 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 { Injector, IWorkbookData, Univer, Workbook } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, LocaleType, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';+import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';+import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';+import { SetSelectionsOperation } from '../../operations/selection.operation';+import { RemoveWorksheetMergeCommand } from '../remove-worksheet-merge.command';+import { createCommandTestBed } from './create-command-test-bed';++const TEST_WORKBOOK: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {+ s1: {+ ff: 'Arial',+ },+ },+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ rowCount: 20,+ columnCount: 20,+ mergeData: [+ {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ ],+ cellData: {+ 0: {+ 0: { v: 'A1', s: 's1' },+ 1: {},+ },+ 1: {+ 0: {},+ 1: {},+ },+ },+ rowData: {},+ columnData: {},+ },+ },+};++describe('remove-worksheet-merge.command', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;++ beforeEach(() => {+ const testBed = createCommandTestBed(TEST_WORKBOOK);+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ [+ RemoveWorksheetMergeCommand,+ AddWorksheetMergeMutation,+ RemoveWorksheetMergeMutation,+ SetRangeValuesMutation,+ SetSelectionsOperation,+ ].forEach((command) => commandService.registerCommand(command));+ });++ afterEach(() => {+ univer.dispose();+ });++ function getActiveWorksheet() {+ return get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();+ }++ it('returns false for empty ranges or no merge intersection', async () => {+ expect(+ await commandService.executeCommand(RemoveWorksheetMergeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [],+ })+ ).toBe(false);++ expect(+ await commandService.executeCommand(RemoveWorksheetMergeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 10, endRow: 11, startColumn: 10, endColumn: 11 }],+ })+ ).toBe(false);+ });++ it('removes merge and keeps main-cell style after unmerge', async () => {+ const worksheet = getActiveWorksheet();+ expect(worksheet.getMergeData()).toHaveLength(1);++ expect(+ await commandService.executeCommand(RemoveWorksheetMergeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ })+ ).toBe(true);++ expect(worksheet.getMergeData()).toHaveLength(0);+ expect(worksheet.getCell(0, 1)?.s).toBe('s1');+ expect(worksheet.getCell(1, 0)?.s).toBe('s1');+ expect(worksheet.getCell(1, 1)?.s).toBe('s1');++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ expect(worksheet.getMergeData()).toHaveLength(1);++ expect(await commandService.executeCommand(RedoCommand.id)).toBeTruthy();+ expect(worksheet.getMergeData()).toHaveLength(0);+ });+});diff --git a/packages/sheets/src/commands/commands/__tests__/util-extra.spec.ts b/packages/sheets/src/commands/commands/__tests__/util-extra.spec.tsnew file mode 100644index 0000000000..61e4c98ec1--- /dev/null+++ b/packages/sheets/src/commands/commands/__tests__/util-extra.spec.ts@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { ObjectMatrix } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { countCells, getSuitableRangesInView } from '../util';++describe('sheets command util', () => {+ it('should select nearest ranges and split overflow range by max visible row quota', () => {+ const ranges = [+ { startRow: 50, endRow: 749, startColumn: 0, endColumn: 2 },+ { startRow: 2000, endRow: 2499, startColumn: 0, endColumn: 2 },+ ];++ const result = getSuitableRangesInView(ranges, {+ worksheet: { getColumnCount: () => 10 },+ scrollY: 0,+ getOffsetRelativeToRowCol: () => ({ row: 100 }),+ } as any);++ expect(result.suitableRanges).toEqual([+ { startRow: 50, endRow: 749, startColumn: 0, endColumn: 2 },+ { startRow: 2000, endRow: 2299, startColumn: 0, endColumn: 2 },+ ]);+ expect(result.remainingRanges).toEqual([+ { startRow: 2300, endRow: 2499, startColumn: 0, endColumn: 2 },+ ]);+ });++ it('should return original ranges when skeleton is absent', () => {+ const ranges = [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }];+ const result = getSuitableRangesInView(ranges, null);+ expect(result).toEqual({ suitableRanges: ranges, remainingRanges: [] });+ });++ it('should count matrix cells with values only', () => {+ const matrix = new ObjectMatrix<number>();+ matrix.setValue(0, 0, 1);+ matrix.setValue(1, 2, 2);+ matrix.setValue(10, 4, 3);++ expect(countCells(matrix)).toBe(3);+ });+});diff --git a/packages/sheets/src/commands/mutations/__tests__/copy-worksheet-end.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/copy-worksheet-end.mutation.spec.tsnew file mode 100644index 0000000000..21e9fce764--- /dev/null+++ b/packages/sheets/src/commands/mutations/__tests__/copy-worksheet-end.mutation.spec.ts@@ -0,0 +1,24 @@+/**+ * 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 { CopyWorksheetEndMutation } from '../copy-worksheet-end.mutation';++describe('copy-worksheet-end.mutation', () => {+ it('marker mutation should always return true', () => {+ expect(CopyWorksheetEndMutation.handler(null as never, null as never)).toBe(true);+ });+});diff --git a/packages/sheets/src/commands/mutations/__tests__/numfmt-mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/numfmt-mutation.spec.tsnew file mode 100644index 0000000000..e5a9f4c973--- /dev/null+++ b/packages/sheets/src/commands/mutations/__tests__/numfmt-mutation.spec.ts@@ -0,0 +1,203 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import type { IRemoveNumfmtMutationParams, ISetNumfmtMutationParams } from '../numfmt-mutation';+import { cellToRange } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { INumfmtService } from '../../../services/numfmt/type';+import {+ factoryRemoveNumfmtUndoMutation,+ factorySetNumfmtUndoMutation,++ RemoveNumfmtMutation,+ SetNumfmtMutation,+ transformCellsToRange,+} from '../numfmt-mutation';++function createAccessor(numfmtService: {+ getValue: ReturnType<typeof vi.fn>;+ setValues: ReturnType<typeof vi.fn>;+ deleteValues: ReturnType<typeof vi.fn>;+}): IAccessor {+ return {+ get: (token: unknown) => {+ if (token === INumfmtService) {+ return numfmtService as never;+ }++ return null as never;+ },+ has: () => true,+ } as unknown as IAccessor;+}++describe('numfmt-mutation', () => {+ it('transformCellsToRange groups cells by pattern', () => {+ const result = transformCellsToRange('unit-1', 'sheet-1', [+ { pattern: '0%', row: 1, col: 1 },+ { pattern: '0%', row: 1, col: 2 },+ { pattern: '#,##0', row: 3, col: 0 },+ ]);++ expect(result.unitId).toBe('unit-1');+ expect(result.subUnitId).toBe('sheet-1');++ const rangesByPattern = Object.entries(result.refMap).reduce<Record<string, ReturnType<typeof cellToRange>[]>>(+ (acc, [key, ref]) => {+ acc[ref.pattern] = result.values[key].ranges;+ return acc;+ },+ {}+ );++ expect(rangesByPattern['0%']).toEqual([cellToRange(1, 1), cellToRange(1, 2)]);+ expect(rangesByPattern['#,##0']).toEqual([cellToRange(3, 0)]);+ });++ it('SetNumfmtMutation handler checks params and calls service', () => {+ const numfmtService = {+ getValue: vi.fn(),+ setValues: vi.fn(),+ deleteValues: vi.fn(),+ };+ const accessor = createAccessor(numfmtService);++ expect(SetNumfmtMutation.handler(accessor, undefined as never)).toBe(false);++ const result = SetNumfmtMutation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ refMap: {+ a: { pattern: '0%' },+ },+ values: {+ a: { ranges: [cellToRange(0, 0)] },+ b: { ranges: [cellToRange(1, 1)] }, // ignored because refMap has no b+ },+ });++ expect(result).toBe(true);+ expect(numfmtService.setValues).toHaveBeenCalledWith('unit-1', 'sheet-1', [+ { pattern: '0%', ranges: [cellToRange(0, 0)] },+ ]);+ });++ it('RemoveNumfmtMutation handler checks params and calls service', () => {+ const numfmtService = {+ getValue: vi.fn(),+ setValues: vi.fn(),+ deleteValues: vi.fn(),+ };+ const accessor = createAccessor(numfmtService);++ expect(RemoveNumfmtMutation.handler(accessor, undefined as never)).toBe(false);++ const result = RemoveNumfmtMutation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [cellToRange(2, 3)],+ });++ expect(result).toBe(true);+ expect(numfmtService.deleteValues).toHaveBeenCalledWith('unit-1', 'sheet-1', [cellToRange(2, 3)]);+ });++ it('factoryRemoveNumfmtUndoMutation rebuilds previous numfmt values', () => {+ const numfmtService = {+ getValue: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {+ if (row === 1 && col === 1) {+ return { pattern: '0%' };+ }+ return null;+ }),+ setValues: vi.fn(),+ deleteValues: vi.fn(),+ };+ const accessor = createAccessor(numfmtService);++ const result = factoryRemoveNumfmtUndoMutation(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }],+ });++ expect(result).toHaveLength(1);+ expect(result[0].id).toBe(SetNumfmtMutation.id);++ const params = result[0].params;+ const keys = Object.keys(params.refMap);+ expect(keys).toHaveLength(1);+ expect(params.refMap[keys[0]].pattern).toBe('0%');+ expect(params.values[keys[0]].ranges).toEqual([cellToRange(1, 1)]);+ });++ it('factoryRemoveNumfmtUndoMutation returns empty list when no old value', () => {+ const numfmtService = {+ getValue: vi.fn(() => null),+ setValues: vi.fn(),+ deleteValues: vi.fn(),+ };+ const accessor = createAccessor(numfmtService);++ expect(+ factoryRemoveNumfmtUndoMutation(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ ranges: [cellToRange(0, 0)],+ })+ ).toEqual([]);+ });++ it('factorySetNumfmtUndoMutation builds both set and remove undo mutations', () => {+ const numfmtService = {+ getValue: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {+ if (row === 1 && col === 1) {+ return { pattern: 'old-1' };+ }+ if (row === 2 && col === 2) {+ return { pattern: 'old-2' };+ }+ return null;+ }),+ setValues: vi.fn(),+ deleteValues: vi.fn(),+ };+ const accessor = createAccessor(numfmtService);++ const result = factorySetNumfmtUndoMutation(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ refMap: {+ a: { pattern: 'new-1' },+ b: { pattern: 'new-2' },+ },+ values: {+ a: { ranges: [cellToRange(1, 1), cellToRange(1, 2)] },+ b: { ranges: [cellToRange(2, 2)] },+ },+ });++ expect(result.map((item) => item.id)).toEqual([SetNumfmtMutation.id, RemoveNumfmtMutation.id]);++ const setParams = result[0].params as ISetNumfmtMutationParams;+ const setPatterns = Object.keys(setParams.refMap).map((key) => setParams.refMap[key].pattern).sort();+ expect(setPatterns).toEqual(['old-1', 'old-2']);++ const removeParams = result[1].params as IRemoveNumfmtMutationParams;+ expect(removeParams.ranges).toEqual([cellToRange(1, 2)]);+ });+});diff --git a/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.tsnew file mode 100644index 0000000000..65208196fd--- /dev/null+++ b/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts@@ -0,0 +1,247 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { IUniverInstanceService } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import {+ SetGridlinesColorMutation,+ SetGridlinesColorUndoMutationFactory,+} from '../set-gridlines-color.mutation';+import { SetWorksheetHideMutation, SetWorksheetHideMutationFactory } from '../set-worksheet-hide.mutation';+import { SetWorksheetNameMutation, SetWorksheetNameMutationFactory } from '../set-worksheet-name.mutation';++function createAccessor(instanceService: unknown): IAccessor {+ return {+ get: (token: unknown) => {+ if (token === IUniverInstanceService) {+ return instanceService as never;+ }+ return null as never;+ },+ has: () => true,+ } as unknown as IAccessor;+}++describe('worksheet meta mutations', () => {+ it('SetGridlinesColorUndoMutationFactory should read current sheet and throw on null sheet', () => {+ const goodAccessor = createAccessor({+ getUniverSheetInstance: vi.fn(() => ({})),+ });+ expect(+ SetGridlinesColorUndoMutationFactory(goodAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ color: '#ff0000',+ })+ ).toEqual({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ color: '#ff0000',+ });++ const badAccessor = createAccessor({+ getUniverSheetInstance: vi.fn(() => null),+ });+ expect(() =>+ SetGridlinesColorUndoMutationFactory(badAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ color: '#ff0000',+ })+ ).toThrowError('universheet is null error!');+ });++ it('SetGridlinesColorMutation should set color and return false when target missing', () => {+ const worksheetConfig: { gridlinesColor?: string } = {};+ const worksheet = {+ getConfig: () => worksheetConfig,+ getSheetId: () => 'sheet-1',+ };+ const workbook = {+ getSheetBySheetId: vi.fn(() => worksheet),+ getUnitId: () => 'unit-1',+ };+ const accessor = createAccessor({+ getUnit: vi.fn(() => workbook),+ });+ expect(+ SetGridlinesColorMutation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ color: '#00ff00',+ })+ ).toBe(true);+ expect(worksheetConfig.gridlinesColor).toBe('#00ff00');++ const badAccessor = createAccessor({+ getUnit: vi.fn(() => null),+ });+ expect(+ SetGridlinesColorMutation.handler(badAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ color: '#00ff00',+ })+ ).toBe(false);+ });++ it('SetWorksheetHide mutation factory and handler should cover true/false paths', () => {+ const worksheetConfig: { hidden?: number } = {};+ const worksheet = {+ getConfig: () => worksheetConfig,+ getSheetId: () => 'sheet-1',+ isSheetHidden: () => 1,+ };+ const workbook = {+ getSheetBySheetId: vi.fn(() => worksheet),+ };++ const accessor = createAccessor({+ getUnit: vi.fn(() => workbook),+ getUniverSheetInstance: vi.fn(() => workbook),+ });++ expect(+ SetWorksheetHideMutationFactory(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ hidden: 0,+ })+ ).toEqual({+ hidden: 1,+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ });++ expect(+ SetWorksheetHideMutation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ hidden: 0,+ })+ ).toBe(true);+ expect(worksheetConfig.hidden).toBe(0);++ const noWorkbookAccessor = createAccessor({+ getUniverSheetInstance: vi.fn(() => null),+ });+ expect(+ SetWorksheetHideMutation.handler(noWorkbookAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ hidden: 0,+ })+ ).toBe(false);++ const noSheetAccessor = createAccessor({+ getUniverSheetInstance: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => null),+ })),+ });+ expect(+ SetWorksheetHideMutation.handler(noSheetAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ hidden: 0,+ })+ ).toBe(false);++ const badFactoryAccessor = createAccessor({+ getUnit: vi.fn(() => null),+ });+ expect(() =>+ SetWorksheetHideMutationFactory(badFactoryAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ hidden: 0,+ })+ ).toThrowError('[SetWorksheetHideMutationFactory]: worksheet is null error!');+ });++ it('SetWorksheetName mutation factory and handler should cover true/false paths', () => {+ const worksheetConfig: { name?: string } = {};+ const worksheet = {+ getConfig: () => worksheetConfig,+ getSheetId: () => 'sheet-1',+ getName: () => 'old-name',+ };+ const workbook = {+ getSheetBySheetId: vi.fn(() => worksheet),+ };++ const accessor = createAccessor({+ getUnit: vi.fn(() => workbook),+ getUniverSheetInstance: vi.fn(() => workbook),+ });++ expect(+ SetWorksheetNameMutationFactory(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ name: 'new-name',+ })+ ).toEqual({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ name: 'old-name',+ });++ expect(+ SetWorksheetNameMutation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ name: 'new-name',+ })+ ).toBe(true);+ expect(worksheetConfig.name).toBe('new-name');++ const noWorkbookAccessor = createAccessor({+ getUniverSheetInstance: vi.fn(() => null),+ });+ expect(+ SetWorksheetNameMutation.handler(noWorkbookAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ name: 'new-name',+ })+ ).toBe(false);++ const noSheetAccessor = createAccessor({+ getUniverSheetInstance: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => null),+ })),+ });+ expect(+ SetWorksheetNameMutation.handler(noSheetAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ name: 'new-name',+ })+ ).toBe(false);++ const badFactoryAccessor = createAccessor({+ getUnit: vi.fn(() => null),+ });+ expect(() =>+ SetWorksheetNameMutationFactory(badFactoryAccessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ name: 'new-name',+ })+ ).toThrowError('[SetWorksheetNameMutationFactory]: worksheet is null error!');+ });+});diff --git a/packages/sheets/src/commands/operations/__tests__/selection.operation.spec.ts b/packages/sheets/src/commands/operations/__tests__/selection.operation.spec.tsnew file mode 100644index 0000000000..5695cb17b4--- /dev/null+++ b/packages/sheets/src/commands/operations/__tests__/selection.operation.spec.ts@@ -0,0 +1,194 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { ICommandService, IContextService, IUniverInstanceService } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { IRefSelectionsService } from '../../../services/selections/ref-selections.service';+import { SheetsSelectionsService } from '../../../services/selections/selection.service';+import { SelectRangeCommand, SetSelectionsOperation } from '../selection.operation';++function createAccessor(values: Map<unknown, unknown>): IAccessor {+ return {+ get: (token: unknown) => values.get(token) as never,+ has: () => true,+ } as unknown as IAccessor;+}++describe('selection.operation', () => {+ it('SetSelectionsOperation returns false without params', () => {+ const accessor = createAccessor(new Map());+ expect(SetSelectionsOperation.handler(accessor, undefined as never)).toBe(false);+ });++ it('SetSelectionsOperation sets selection with copied array', () => {+ const selectionService = {+ setSelections: vi.fn(),+ };+ const contextService = {+ getContextValue: vi.fn(() => false),+ };+ const accessor = createAccessor(+ new Map<unknown, unknown>([+ [IContextService, contextService],+ [SheetsSelectionsService, selectionService],+ ])+ );+ const selections = [+ {+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0, actualRow: 0, actualColumn: 0, isMerged: false, isMergedMainCell: false },+ style: null,+ },+ ];++ expect(+ SetSelectionsOperation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ selections,+ })+ ).toBe(true);++ expect(selectionService.setSelections).toHaveBeenCalledTimes(1);+ const callArgs = selectionService.setSelections.mock.calls[0];+ expect(callArgs[0]).toBe('unit-1');+ expect(callArgs[1]).toBe('sheet-1');+ expect(callArgs[2]).toEqual(selections);+ expect(callArgs[2]).not.toBe(selections);+ });++ it('SetSelectionsOperation uses ref selection service in ref mode', () => {+ const refSelectionService = {+ setSelections: vi.fn(),+ };+ const contextService = {+ getContextValue: vi.fn(() => true),+ };+ const accessor = createAccessor(+ new Map<unknown, unknown>([+ [IContextService, contextService],+ [IRefSelectionsService, refSelectionService],+ ])+ );++ expect(+ SetSelectionsOperation.handler(accessor, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ selections: [],+ })+ ).toBe(true);+ expect(refSelectionService.setSelections).toHaveBeenCalledWith('unit-1', 'sheet-1', [], undefined);+ });++ it('SelectRangeCommand returns false without params or target', () => {+ const commandService = {+ syncExecuteCommand: vi.fn(),+ };+ const accessorWithoutParams = createAccessor(+ new Map<unknown, unknown>([+ [ICommandService, commandService],+ ])+ );+ expect(SelectRangeCommand.handler(accessorWithoutParams, undefined as never)).toBe(false);++ const instanceService = {+ getCurrentUnitOfType: vi.fn(() => null),+ getUnit: vi.fn(() => null),+ };+ const accessorWithoutTarget = createAccessor(+ new Map<unknown, unknown>([+ [ICommandService, commandService],+ [IUniverInstanceService, instanceService],+ ])+ );+ expect(+ SelectRangeCommand.handler(accessorWithoutTarget, {+ unitId: 'unit-1',+ subUnit: 'sheet-1',+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ })+ ).toBe(false);+ });++ it('SelectRangeCommand dispatches SetSelectionsOperation', () => {+ const commandService = {+ syncExecuteCommand: vi.fn(() => true),+ };+ const worksheet = {+ getSheetId: () => 'sheet-1',+ getMergedCell: () => null,+ };+ const workbook = {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => worksheet,+ };+ const instanceService = {+ getCurrentUnitOfType: () => workbook,+ getUnit: () => workbook,+ };+ const accessor = createAccessor(+ new Map<unknown, unknown>([+ [ICommandService, commandService],+ [IUniverInstanceService, instanceService],+ ])+ );++ expect(+ SelectRangeCommand.handler(accessor, {+ unitId: 'unit-1',+ subUnit: 'sheet-1',+ range: { startRow: 2, endRow: 4, startColumn: 3, endColumn: 5 },+ })+ ).toBe(true);+ expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(1);++ const [commandId, params] = commandService.syncExecuteCommand.mock.calls[0] as unknown as [string, {+ unitId: string;+ subUnitId: string;+ selections: Array<{+ range: { startRow: number; endRow: number; startColumn: number; endColumn: number };+ primary: {+ startRow: number;+ endRow: number;+ startColumn: number;+ endColumn: number;+ actualRow: number;+ actualColumn: number;+ rangeType: number;+ isMerged: boolean;+ isMergedMainCell: boolean;+ };+ }>;+ }];+ expect(commandId).toBe(SetSelectionsOperation.id);+ expect(params.unitId).toBe('unit-1');+ expect(params.subUnitId).toBe('sheet-1');+ expect(params.selections[0].range).toEqual({ startRow: 2, endRow: 4, startColumn: 3, endColumn: 5 });+ expect(params.selections[0].primary).toEqual({+ startRow: 2,+ endRow: 2,+ startColumn: 3,+ endColumn: 3,+ actualRow: 2,+ actualColumn: 3,+ rangeType: 0,+ isMerged: false,+ isMergedMainCell: false,+ });+ });+});diff --git a/packages/sheets/src/model/__tests__/range-protection.cache.spec.ts b/packages/sheets/src/model/__tests__/range-protection.cache.spec.tsnew file mode 100644index 0000000000..2364a6e664--- /dev/null+++ b/packages/sheets/src/model/__tests__/range-protection.cache.spec.ts@@ -0,0 +1,163 @@+/**+ * 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 { Injector, Univer, Workbook } from '@univerjs/core';+import type { IRangeProtectionRule } from '../range-protection-rule.model';+import { IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { UnitAction, UnitObject } from '@univerjs/protocol';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../services/__tests__/util';+import { RangeProtectionPermissionEditPoint, RangeProtectionPermissionViewPoint } from '../../services/permission/permission-point';+import { RangeProtectionPermissionDeleteProtectionPoint } from '../../services/permission/permission-point/range/delete-protection';+import { RangeProtectionPermissionManageCollaPoint } from '../../services/permission/permission-point/range/manage-collaborator';+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../range-protection-rule.model';+import { RangeProtectionCache } from '../range-protection.cache';++describe('RangeProtectionCache', () => {+ let univer: Univer;+ let get: Injector['get'];+ let unitId: string;+ let subUnitId: string;+ let cache: RangeProtectionCache;+ let ruleModel: RangeProtectionRuleModel;+ let permissionService: IPermissionService;+ let seed = 0;++ const getRule = (overrides?: Partial<IRangeProtectionRule>): IRangeProtectionRule => {+ seed += 1;+ return {+ id: `rule-${seed}`,+ permissionId: `permission-${seed}`,+ unitId,+ subUnitId,+ unitType: UnitObject.SelectRange,+ viewState: ViewStateEnum.OthersCanView,+ editState: EditStateEnum.DesignedUserCanEdit,+ ranges: [{ startRow: 1, endRow: 2, startColumn: 2, endColumn: 3 }],+ ...overrides,+ };+ };++ const setupRulePermission = (rule: IRangeProtectionRule, values?: Partial<Record<UnitAction, boolean>>) => {+ const points = [+ new RangeProtectionPermissionEditPoint(rule.unitId, rule.subUnitId, rule.permissionId),+ new RangeProtectionPermissionViewPoint(rule.unitId, rule.subUnitId, rule.permissionId),+ new RangeProtectionPermissionManageCollaPoint(rule.unitId, rule.subUnitId, rule.permissionId),+ new RangeProtectionPermissionDeleteProtectionPoint(rule.unitId, rule.subUnitId, rule.permissionId),+ ];++ points.forEach((point) => {+ if (!permissionService.getPermissionPoint(point.id)) {+ permissionService.addPermissionPoint(point);+ }+ permissionService.updatePermissionPoint(point.id, values?.[point.subType] ?? true);+ });+ };++ beforeEach(() => {+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [+ [RangeProtectionRuleModel],+ [RangeProtectionCache],+ ]);++ univer = testBed.univer;+ get = testBed.get;+ cache = get(RangeProtectionCache);+ ruleModel = get(RangeProtectionRuleModel);+ permissionService = get(IPermissionService);++ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ unitId = workbook.getUnitId();+ subUnitId = workbook.getActiveSheet()!.getSheetId();+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should rebuild cache and return permission info by row/col/cell', () => {+ const rule = getRule();+ setupRulePermission(rule, {+ [UnitAction.Edit]: false,+ });+ ruleModel.addRule(unitId, subUnitId, rule);++ cache.reBuildCache(unitId, subUnitId);++ expect(cache.getRowPermissionInfo(unitId, subUnitId, 1, [UnitAction.Edit])).toBe(false);+ expect(cache.getColPermissionInfo(unitId, subUnitId, 2, [UnitAction.View])).toBe(true);+ expect(cache.getRowPermissionInfo(unitId, subUnitId, 99, [UnitAction.Edit])).toBe(true);+ expect(cache.getCellInfo(unitId, subUnitId, 1, 2)).toEqual({+ [UnitAction.Edit]: false,+ [UnitAction.View]: true,+ [UnitAction.ManageCollaborator]: true,+ [UnitAction.Delete]: true,+ ruleId: rule.id,+ ranges: rule.ranges,+ });+ });++ it('should update cached cell and row permissions when permission point changes', () => {+ const rule = getRule();+ setupRulePermission(rule, {+ [UnitAction.Edit]: true,+ });+ ruleModel.addRule(unitId, subUnitId, rule);+ cache.reBuildCache(unitId, subUnitId);++ expect(cache.getCellInfo(unitId, subUnitId, 1, 2)?.[UnitAction.Edit]).toBe(true);++ const editPoint = new RangeProtectionPermissionEditPoint(unitId, subUnitId, rule.permissionId);+ permissionService.updatePermissionPoint(editPoint.id, false);++ expect(cache.getCellInfo(unitId, subUnitId, 1, 2)?.[UnitAction.Edit]).toBe(false);+ expect(cache.getRowPermissionInfo(unitId, subUnitId, 1, [UnitAction.Edit])).toBe(false);+ });++ it('should drop rule cache after deleting range rule', () => {+ const rule = getRule({+ ranges: [{ startRow: 4, endRow: 4, startColumn: 5, endColumn: 5 }],+ });+ setupRulePermission(rule);+ ruleModel.addRule(unitId, subUnitId, rule);+ cache.reBuildCache(unitId, subUnitId);++ expect(cache.getCellInfo(unitId, subUnitId, 4, 5)?.ruleId).toBe(rule.id);++ ruleModel.deleteRule(unitId, subUnitId, rule.id);++ expect(cache.getCellInfo(unitId, subUnitId, 4, 5)).toBeUndefined();+ expect(cache.getRowPermissionInfo(unitId, subUnitId, 4, [UnitAction.Edit])).toBe(true);+ });++ it('should clear per-unit caches on deleteUnit', () => {+ const rule = getRule({+ ranges: [{ startRow: 7, endRow: 7, startColumn: 7, endColumn: 7 }],+ });+ setupRulePermission(rule);+ ruleModel.addRule(unitId, subUnitId, rule);+ cache.reBuildCache(unitId, subUnitId);++ expect(cache.getCellInfo(unitId, subUnitId, 7, 7)?.ruleId).toBe(rule.id);++ cache.deleteUnit(unitId);++ expect(cache.getCellInfo(unitId, subUnitId, 7, 7)).toBeUndefined();+ expect((cache as any)._cellRuleCache.has(unitId)).toBe(false);+ expect((cache as any)._rowInfoCache.has(unitId)).toBe(false);+ expect((cache as any)._colInfoCache.has(unitId)).toBe(false);+ });+});diff --git a/packages/sheets/src/model/__tests__/range-theme-model.spec.ts b/packages/sheets/src/model/__tests__/range-theme-model.spec.tsnew file mode 100644index 0000000000..f374a04665--- /dev/null+++ b/packages/sheets/src/model/__tests__/range-theme-model.spec.ts@@ -0,0 +1,144 @@+/**+ * 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 { Injector, IRange, Univer, Workbook } from '@univerjs/core';+import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../services/__tests__/util';+import { SheetInterceptorService } from '../../services/sheet-interceptor/sheet-interceptor.service';+import { SheetRangeThemeModel } from '../range-theme-model';+import { RangeThemeStyle } from '../range-theme-util';++describe('SheetRangeThemeModel', () => {+ let univer: Univer;+ let get: Injector['get'];+ let model: SheetRangeThemeModel;+ let unitId: string;+ let subUnitId: string;++ beforeEach(() => {+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [+ [SheetInterceptorService],+ [SheetRangeThemeModel],+ ]);++ univer = testBed.univer;+ get = testBed.get;+ model = get(SheetRangeThemeModel);++ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ unitId = workbook.getUnitId();+ subUnitId = workbook.getActiveSheet()!.getSheetId();+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should initialize default themes and support default theme unregister/register', () => {+ const defaultThemes = model.getRegisteredRangeThemes();+ expect(defaultThemes.length).toBeGreaterThan(0);+ expect(model.getDefaultRangeThemeStyle(defaultThemes[0])).toBeDefined();++ model.unRegisterDefaultRangeTheme(defaultThemes[0]);+ expect(model.getRegisteredRangeThemes().includes(defaultThemes[0])).toBe(false);++ model.registerDefaultRangeTheme(new RangeThemeStyle(defaultThemes[0]));+ expect(model.getRegisteredRangeThemes().includes(defaultThemes[0])).toBe(true);+ });++ it('should register custom theme style and notify changes', () => {+ const events: Array<{ type: 'add' | 'remove'; styleName: string }> = [];+ const sub = model.rangeThemeMapChange$.subscribe((event) => {+ events.push(event);+ });++ const customTheme = new RangeThemeStyle('custom-theme', {+ wholeStyle: { bg: { rgb: '#ffeeee' } as any },+ firstRowStyle: { bg: { rgb: '#aaffaa' } as any },+ });++ model.registerRangeThemeStyle(unitId, customTheme);+ expect(model.getCustomRangeThemeStyle(unitId, 'custom-theme')?.getName()).toBe('custom-theme');+ expect(model.getALLRegisteredTheme(unitId)).toContain('custom-theme');++ model.unregisterRangeThemeStyle(unitId, 'custom-theme');+ expect(model.getCustomRangeThemeStyle(unitId, 'custom-theme')).toBeUndefined();+ expect(events.some((event) => event.type === 'add' && event.styleName === 'custom-theme')).toBe(true);+ expect(events.some((event) => event.type === 'remove' && event.styleName === 'custom-theme')).toBe(true);+ sub.unsubscribe();+ });++ it('should register range theme rule and return style from cell query', () => {+ const customTheme = new RangeThemeStyle('rule-theme', {+ wholeStyle: { bg: { rgb: '#ccccff' } as any },+ });+ model.registerRangeThemeStyle(unitId, customTheme);++ const range: IRange = { startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 };+ model.registerRangeThemeRule('rule-theme', {+ unitId,+ subUnitId,+ range,+ });++ expect(model.getRegisteredRangeThemeStyle({ unitId, subUnitId, range })).toBe('rule-theme');+ expect(model.getCellStyle(unitId, subUnitId, 1, 1)).toBeDefined();++ model.removeRangeThemeRule('rule-theme', {+ unitId,+ subUnitId,+ range,+ });+ expect(model.getRegisteredRangeThemeStyle({ unitId, subUnitId, range })).toBeUndefined();+ });++ it('should refresh zebra crossing caches and clear stale entries', () => {+ const customTheme = new RangeThemeStyle('zebra-theme', {+ wholeStyle: { bg: { rgb: '#f5f5f5' } as any },+ });+ model.registerRangeThemeStyle(unitId, customTheme);++ const range: IRange = { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 };+ model.registerRangeThemeRule('zebra-theme', { unitId, subUnitId, range });+ expect((model as any)._zebraCrossingCacheMap.get(unitId)?.get(subUnitId)?.size).toBe(1);++ model.removeRangeThemeRule('zebra-theme', { unitId, subUnitId, range });+ model.refreshZebraCrossingCacheBySheet(unitId, subUnitId);+ expect((model as any)._zebraCrossingCacheMap.get(unitId)?.get(subUnitId)?.size).toBe(0);+ });++ it('should serialize/deserialize and remove unit resources', () => {+ const customTheme = new RangeThemeStyle('json-theme', {+ wholeStyle: { bg: { rgb: '#ddddee' } as any },+ });+ model.registerRangeThemeStyle(unitId, customTheme);++ const range: IRange = { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 };+ model.registerRangeThemeRule('json-theme', { unitId, subUnitId, range });++ const jsonText = model.toJson(unitId);+ const json = JSON.parse(jsonText);+ expect(json.rangeThemeStyleRuleMap).toBeDefined();+ expect(json.rangeThemeStyleMapJson).toBeDefined();++ model.deleteUnitId(unitId);+ expect(model.getALLRegisteredTheme(unitId)).toEqual([]);++ model.fromJSON(unitId, json);+ expect(model.getALLRegisteredTheme(unitId)).toContain('json-theme');+ });+});diff --git a/packages/sheets/src/model/__tests__/range-theme-util.spec.ts b/packages/sheets/src/model/__tests__/range-theme-util.spec.tsnew file mode 100644index 0000000000..704955fb53--- /dev/null+++ b/packages/sheets/src/model/__tests__/range-theme-util.spec.ts@@ -0,0 +1,129 @@+/**+ * 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 { BooleanNumber, BorderStyleTypes } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { composeStyles, RangeThemeStyle } from '../range-theme-util';++describe('range-theme-util', () => {+ it('composeStyles should return single style directly', () => {+ const style = { bg: { rgb: '#fff' } };+ expect(composeStyles([style])).toBe(style);+ });++ it('composeStyles should merge style list in order', () => {+ const merged = composeStyles([+ { bg: { rgb: '#111' }, bd: { b: { s: BorderStyleTypes.THIN, cl: { rgb: '#000' } } }, bl: 0 },+ { cl: { rgb: '#222' }, bd: { t: { s: BorderStyleTypes.DOUBLE, cl: { rgb: '#fff' } } }, ht: 1 },+ { vt: 2, bl: 1 },+ ]);++ expect(merged).toEqual({+ bg: { rgb: '#111' },+ cl: { rgb: '#222' },+ bd: {+ b: { s: BorderStyleTypes.THIN, cl: { rgb: '#000' } },+ t: { s: BorderStyleTypes.DOUBLE, cl: { rgb: '#fff' } },+ },+ ht: 1,+ vt: 2,+ bl: 1,+ });+ });++ it('RangeThemeStyle should compose style by row/column state', () => {+ const style = new RangeThemeStyle('demo');+ style.setWholeStyle({ bg: { rgb: '#111' } });+ style.setHeaderRowStyle({ cl: { rgb: '#222' } });+ style.setHeaderColumnStyle({ ol: { s: BooleanNumber.TRUE } });+ style.setFirstRowStyle({ bd: { b: { s: BorderStyleTypes.DASHED, cl: { rgb: '#ccc' } } } });+ style.setSecondRowStyle({ bd: { t: { s: BorderStyleTypes.DOTTED, cl: { rgb: '#ddd' } } } });+ style.setFirstColumnStyle({ ht: 1 });+ style.setSecondColumnStyle({ vt: 2 });+ style.setLastRowStyle({ bl: 0 });+ style.setLastColumnStyle({ bg: { rgb: '#999' } });++ expect(style.getName()).toBe('demo');+ expect(style.getStyle(-1, -1, false, false, false)).toBeNull();++ const headerStyle = style.getStyle(0, 0, false, false, false);+ expect(headerStyle).toEqual({+ bg: { rgb: '#111' },+ cl: { rgb: '#222' },+ ol: { s: BooleanNumber.TRUE },+ bd: { t: { s: BorderStyleTypes.DOTTED, cl: { rgb: '#ddd' } } },+ vt: 2,+ });++ const toggledStyle = style.getStyle(1, 1, true, true, true);+ expect(toggledStyle).toEqual({+ bg: { rgb: '#999' },+ bd: { t: { s: BorderStyleTypes.DOTTED, cl: { rgb: '#ddd' } } },+ ht: 1,+ bl: 0,+ });+ });++ it('RangeThemeStyle should cache merged styles and reset cache', () => {+ const style = new RangeThemeStyle('cache', {+ wholeStyle: { bg: { rgb: '#123' } },+ firstRowStyle: { cl: { rgb: '#456' } },+ });++ const first = style.getStyle(1, 1, false, false, false);+ const second = style.getStyle(1, 1, false, false, false);+ expect(first).toBe(second);+ expect((style as unknown as { _mergeCacheMap: Map<number, unknown> })._mergeCacheMap.size).toBeGreaterThan(0);++ style.setLastRowStyle({ bl: 1 });+ expect((style as unknown as { _mergeCacheMap: Map<number, unknown> })._mergeCacheMap.size).toBe(0);+ });++ it('RangeThemeStyle should serialize and deserialize', () => {+ const source = new RangeThemeStyle('json');+ source.setWholeStyle({ bg: { rgb: '#aaa' }, bl: 0 });+ source.setHeaderRowStyle({ cl: { rgb: '#bbb' } });+ source.setSecondColumnStyle({ vt: 1 });+ source.setLastColumnStyle({ ht: 2 });++ const json = source.toJson();+ expect(json).toEqual({+ name: 'json',+ wholeStyle: { bg: { rgb: '#aaa' }, bl: 0 },+ headerRowStyle: { cl: { rgb: '#bbb' } },+ secondColumnStyle: { vt: 1 },+ lastColumnStyle: { ht: 2 },+ });++ const target = new RangeThemeStyle('empty');+ target.fromJson(json);+ expect(target.getName()).toBe('json');+ expect(target.getWholeStyle()).toEqual({ bg: { rgb: '#aaa' }, bl: 0 });+ expect(target.getHeaderRowStyle()).toEqual({ cl: { rgb: '#bbb' } });+ expect(target.getSecondColumnStyle()).toEqual({ vt: 1 });+ expect(target.getLastColumnStyle()).toEqual({ ht: 2 });+ });++ it('dispose should clear internal cache', () => {+ const style = new RangeThemeStyle('dispose', {+ wholeStyle: { bg: { rgb: '#123' } },+ });+ style.getStyle(0, 0, false, false, false);+ expect((style as unknown as { _mergeCacheMap: Map<number, unknown> })._mergeCacheMap.size).toBeGreaterThan(0);+ style.dispose();+ expect((style as unknown as { _mergeCacheMap: Map<number, unknown> })._mergeCacheMap.size).toBe(0);+ });+});diff --git a/packages/sheets/src/services/__tests__/lazy-execute-schedule.service.spec.ts b/packages/sheets/src/services/__tests__/lazy-execute-schedule.service.spec.tsnew file mode 100644index 0000000000..56c432e3cc--- /dev/null+++ b/packages/sheets/src/services/__tests__/lazy-execute-schedule.service.spec.ts@@ -0,0 +1,152 @@+/**+ * 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 { IMutationInfo } from '@univerjs/core';+import type { ISetRangeValuesMutationParams } from '../../commands/mutations/set-range-values.mutation';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SheetLazyExecuteScheduleService } from '../lazy-execute-schedule.service';++function createMutation(unitId: string, subUnitId: string): IMutationInfo<ISetRangeValuesMutationParams> {+ return {+ id: 'sheet.mutation.set-range-values',+ params: {+ unitId,+ subUnitId,+ cellValue: {+ 0: { 0: { v: 1 } },+ },+ },+ };+}++describe('SheetLazyExecuteScheduleService', () => {+ let commandService: {+ syncExecuteCommand: ReturnType<typeof vi.fn>;+ };++ let getSheetBySheetId: ReturnType<typeof vi.fn>;++ let instanceService: {+ getUnit: ReturnType<typeof vi.fn>;+ };++ let service: SheetLazyExecuteScheduleService;++ beforeEach(() => {+ commandService = {+ syncExecuteCommand: vi.fn(),+ };++ getSheetBySheetId = vi.fn(() => ({}));+ instanceService = {+ getUnit: vi.fn(() => ({+ getSheetBySheetId,+ })),+ };++ vi.stubGlobal('requestIdleCallback', vi.fn(() => 1));+ vi.stubGlobal('cancelIdleCallback', vi.fn());++ service = new SheetLazyExecuteScheduleService(commandService as never, instanceService as never);+ });++ afterEach(() => {+ service.dispose();+ vi.unstubAllGlobals();+ });++ it('tracks pending tasks and can cancel scheduled mutations', () => {+ expect(service.hasPendingTasks()).toBe(false);+ expect(service.getPendingMutationsCount()).toBe(0);++ service.scheduleMutations('unit-1', 'sheet-1', []);+ expect(service.hasPendingTasks()).toBe(false);++ const mutations = [createMutation('unit-1', 'sheet-1'), createMutation('unit-1', 'sheet-1')];+ service.scheduleMutations('unit-1', 'sheet-1', mutations);+ expect(service.hasPendingTasks()).toBe(true);+ expect(service.getPendingMutationsCount()).toBe(2);++ service.cancelScheduledMutations('unit-1', 'sheet-1');+ expect(service.hasPendingTasks()).toBe(false);+ expect((globalThis as unknown as { cancelIdleCallback: ReturnType<typeof vi.fn> }).cancelIdleCallback).toHaveBeenCalled();+ });++ it('executes scheduled mutations in idle time and marks them onlyLocal', () => {+ service.scheduleMutations('unit-1', 'sheet-1', [+ createMutation('unit-1', 'sheet-1'),+ createMutation('unit-1', 'sheet-1'),+ ]);++ (+ service as unknown as {+ _processIdleTasks: (deadline: { didTimeout: boolean; timeRemaining: () => number }) => void;+ }+ )._processIdleTasks({+ didTimeout: true,+ timeRemaining: () => 0,+ });++ expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(2);+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(+ 1,+ 'sheet.mutation.set-range-values',+ expect.any(Object),+ { onlyLocal: true }+ );+ expect(service.hasPendingTasks()).toBe(false);+ });++ it('drops task when target sheet no longer exists', () => {+ getSheetBySheetId.mockReturnValue(null);+ service.scheduleMutations('unit-1', 'sheet-1', [createMutation('unit-1', 'sheet-1')]);++ (+ service as unknown as {+ _processIdleTasks: (deadline: { didTimeout: boolean; timeRemaining: () => number }) => void;+ }+ )._processIdleTasks({+ didTimeout: true,+ timeRemaining: () => 10,+ });++ expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();+ expect(service.hasPendingTasks()).toBe(false);+ });++ it('beforeunload handler blocks navigation when tasks are pending', () => {+ const beforeUnloadHandler = (+ service as unknown as { _beforeUnloadHandler: ((event: { preventDefault: () => void; returnValue: string }) => unknown) | null }+ )._beforeUnloadHandler;+ expect(beforeUnloadHandler).toBeTruthy();++ const event = {+ preventDefault: vi.fn(),+ returnValue: '',+ };++ beforeUnloadHandler!(event);+ expect(event.preventDefault).not.toHaveBeenCalled();++ service.scheduleMutations('unit-1', 'sheet-1', [createMutation('unit-1', 'sheet-1')]);+ beforeUnloadHandler!(event);+ expect(event.preventDefault).toHaveBeenCalled();+ expect(event.returnValue).toBe('');++ service.dispose();+ expect(service.hasPendingTasks()).toBe(false);+ });+});diff --git a/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.ts b/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.tsnew file mode 100644index 0000000000..e401d39cc3--- /dev/null+++ b/packages/sheets/src/services/auto-fill/__tests__/auto-fill.service.spec.ts@@ -0,0 +1,198 @@+/**+ * 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 { Injector, IRange, Univer, Workbook } from '@univerjs/core';+import type { IAutoFillRule } from '../type';+import { Direction, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { SetSelectionsOperation } from '../../../commands/operations/selection.operation';+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../__tests__/util';+import { SheetsSelectionsService } from '../../selections/selection.service';+import { AutoFillService } from '../auto-fill.service';+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE, AUTO_FILL_HOOK_TYPE } from '../type';++describe('AutoFillService', () => {+ let univer: Univer;+ let get: Injector['get'];+ let service: AutoFillService;+ let commandService: ICommandService;+ let unitId: string;+ let subUnitId: string;++ beforeEach(() => {+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [+ [SheetsSelectionsService],+ [AutoFillService],+ ]);++ univer = testBed.univer;+ get = testBed.get;+ service = get(AutoFillService);+ commandService = get(ICommandService);+ commandService.registerCommand(SetSelectionsOperation);++ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ unitId = workbook.getUnitId();+ subUnitId = workbook.getActiveSheet()!.getSheetId();+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should initialize default rules by priority', () => {+ const rules = service.getRules();+ expect(rules[0].type).toBe(AUTO_FILL_DATA_TYPE.DATE);+ expect(rules[rules.length - 1].type).toBe(AUTO_FILL_DATA_TYPE.OTHER);+ });++ it('should register rule by priority and reject duplicate type', () => {+ const customRule: IAutoFillRule = {+ type: 'custom-rule',+ priority: 2000,+ match: () => false,+ isContinue: () => false,+ };+ service.registerRule(customRule);+ expect(service.getRules()[0].type).toBe('custom-rule');++ expect(() => service.registerRule(customRule)).toThrow();+ });++ it('should add hooks with defaults and remove by disposable', () => {+ const disposable = service.addHook({+ id: 'append-hook',+ });++ const currentHook = service.getAllHooks().find((h) => h.id === 'append-hook');+ expect(currentHook?.type).toBe(AUTO_FILL_HOOK_TYPE.APPEND);+ expect(currentHook?.priority).toBe(0);++ expect(() => service.addHook({ id: 'append-hook' })).toThrow();++ disposable.dispose();+ expect(service.getAllHooks().find((h) => h.id === 'append-hook')).toBeUndefined();+ });++ it('should pick ONLY hook by max priority, otherwise default + append hooks', () => {+ service.autoFillLocation = {+ unitId,+ subUnitId,+ source: { rows: [0], cols: [0] },+ target: { rows: [1], cols: [0] },+ } as any;+ service.direction = Direction.DOWN;+ service.applyType = AUTO_FILL_APPLY_TYPE.COPY;++ const disposeDefaultLow = service.addHook({ id: 'default-low', type: AUTO_FILL_HOOK_TYPE.DEFAULT, priority: 1 });+ const disposeDefaultHigh = service.addHook({ id: 'default-high', type: AUTO_FILL_HOOK_TYPE.DEFAULT, priority: 9 });+ service.addHook({ id: 'append', type: AUTO_FILL_HOOK_TYPE.APPEND, priority: 1 });+ service.addHook({+ id: 'append-disabled',+ type: AUTO_FILL_HOOK_TYPE.APPEND,+ disable: () => true,+ });+ const disposeOnlyLow = service.addHook({ id: 'only-low', type: AUTO_FILL_HOOK_TYPE.ONLY, priority: 1 });+ const disposeOnlyHigh = service.addHook({ id: 'only-high', type: AUTO_FILL_HOOK_TYPE.ONLY, priority: 8 });++ expect(service.getActiveHooks().map((h) => h.id)).toEqual(['only-high']);++ disposeOnlyLow.dispose();+ disposeOnlyHigh.dispose();++ expect(service.getActiveHooks().map((h) => h.id)).toEqual(['default-high', 'append']);++ disposeDefaultLow.dispose();+ disposeDefaultHigh.dispose();+ });++ it('should toggle menu/status flags and apply type', () => {+ service.setDisableApplyType(AUTO_FILL_APPLY_TYPE.COPY, true);+ expect(service.menu.find((item) => item.value === AUTO_FILL_APPLY_TYPE.COPY)?.disable).toBe(true);++ let showMenu = false;+ const sub = service.showMenu$.subscribe((v) => {+ showMenu = v;+ });+ service.setShowMenu(true);+ expect(showMenu).toBe(true);+ sub.unsubscribe();++ service.setFillingStyle(false);+ expect(service.isFillingStyle()).toBe(false);+ });++ it('should return false when filling without location', () => {+ service.autoFillLocation = null;+ expect(service.fillData(AUTO_FILL_APPLY_TYPE.COPY)).toBe(false);+ });++ it('should trigger auto fill and set direction for expansion', async () => {+ const source: IRange = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };++ expect(await service.triggerAutoFill(unitId, subUnitId, source, source, AUTO_FILL_APPLY_TYPE.COPY)).toBe(false);++ const result = await service.triggerAutoFill(+ unitId,+ subUnitId,+ source,+ { startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 },+ AUTO_FILL_APPLY_TYPE.COPY+ );++ expect(result).toBe(true);+ expect(service.direction).toBe(Direction.DOWN);+ expect(service.autoFillLocation?.unitId).toBe(unitId);+ });++ it('should replay previous undo mutations before next fill', () => {+ service.autoFillLocation = {+ unitId,+ subUnitId,+ source: { rows: [0], cols: [0] },+ target: { rows: [1], cols: [0] },+ } as any;+ service.direction = Direction.DOWN;+ const prevRange = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };+ (service as any)._prevUndos = [{+ id: SetSelectionsOperation.id,+ params: {+ unitId,+ subUnitId,+ selections: [{ range: prevRange, primary: null, style: null }],+ },+ }];++ const syncSpy = vi.spyOn(commandService, 'syncExecuteCommand');+ service.fillData(AUTO_FILL_APPLY_TYPE.COPY);++ expect(syncSpy).toHaveBeenCalledWith(SetSelectionsOperation.id, {+ unitId,+ subUnitId,+ selections: [{ range: prevRange, primary: null, style: null }],+ });+ expect((service as any)._prevUndos).toEqual([]);+ });++ it('should skip auto-height mutation generation in NO_FORMAT mode', () => {+ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet()!;+ service.applyType = AUTO_FILL_APPLY_TYPE.NO_FORMAT;++ const result = (service as any)._getAutoHeightUndoRedos([], workbook, worksheet);+ expect(result).toEqual({ undos: [], redos: [] });+ });+});diff --git a/packages/sheets/src/services/auto-fill/__tests__/rules.spec.ts b/packages/sheets/src/services/auto-fill/__tests__/rules.spec.tsnew file mode 100644index 0000000000..a416a583fa--- /dev/null+++ b/packages/sheets/src/services/auto-fill/__tests__/rules.spec.ts@@ -0,0 +1,186 @@+/**+ * 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 { CellValueType, Direction } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import AutoFillRules from '../rules';+import { AUTO_FILL_APPLY_TYPE, AUTO_FILL_DATA_TYPE } from '../type';++const { dateRule, numberRule, extendNumberRule, chnNumberRule, chnWeek2Rule, chnWeek3Rule, loopSeriesRule, otherRule } = AutoFillRules;++describe('auto-fill rules', () => {+ it('date rule should match object-style date and reject formula cells', () => {+ expect(+ dateRule.match(+ {+ v: 45292,+ t: CellValueType.NUMBER,+ s: { n: { pattern: 'yyyy-mm-dd' } },+ },+ {} as any+ )+ ).toBe(true);++ expect(+ dateRule.match(+ {+ f: '=A1',+ v: 1,+ s: { n: { pattern: 'yyyy-mm-dd' } },+ },+ {} as any+ )+ ).toBe(false);++ const rightResult = dateRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 1 }, { v: 2 }], index: [0, 1] },+ 3,+ Direction.DOWN,+ {} as any+ );+ const leftResult = dateRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 1 }, { v: 2 }], index: [0, 1] },+ 3,+ Direction.LEFT,+ {} as any+ );++ expect(rightResult?.map((c) => c?.v)).toEqual([3, 4, 5]);+ expect(leftResult?.map((c) => c?.v)).toEqual([-2, -1, 0]);+ expect(dateRule.isContinue({ type: AUTO_FILL_DATA_TYPE.DATE, cellData: { v: 1 } }, { v: 2 })).toBe(true);+ });++ it('number rule should match numeric cells and generate series', () => {+ expect(numberRule.match({ v: 10 }, {} as any)).toBe(true);+ expect(numberRule.match({ t: CellValueType.NUMBER }, {} as any)).toBe(true);+ expect(numberRule.match({ v: '10' }, {} as any)).toBe(false);+ expect(numberRule.isContinue({ type: AUTO_FILL_DATA_TYPE.NUMBER, cellData: { v: 1 } }, { v: 2 })).toBe(true);++ const result = numberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 2 }, { v: 4 }], index: [0, 1] },+ 3,+ Direction.DOWN,+ {} as any+ );+ expect(result?.map((cell) => cell?.v)).toEqual([6, 8, 10]);+ });++ it('extend-number rule should support continue and copy fallback', () => {+ expect(extendNumberRule.match({ v: 'item-001' }, {} as any)).toBe(true);+ expect(extendNumberRule.match({ v: 'plain-text' }, {} as any)).toBe(false);+ expect(+ extendNumberRule.isContinue(+ { type: AUTO_FILL_DATA_TYPE.EXTEND_NUMBER, cellData: { v: 'A-001-Z' } },+ { v: 'A-002-Z' }+ )+ ).toBe(true);++ const oneCell = extendNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 'A-001' }], index: [0] },+ 2,+ Direction.DOWN,+ {} as any+ );+ expect(oneCell?.map((c) => `${c?.v}`)).toEqual(['A-002', 'A-003']);++ const fallbackCopy = extendNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 'A-001' }, { v: 'A-003' }, { v: 'A-010' }], index: [0, 1, 2] },+ 4,+ Direction.DOWN,+ {} as any+ );+ expect(fallbackCopy?.length).toBe(4);+ expect(`${fallbackCopy?.[0]?.v}`).toBe('A-001');+ });++ it('chinese-number rule should handle normal numbers and week cycle', () => {+ expect(chnNumberRule.match({ v: '三' }, {} as any)).toBe(true);+ expect(chnNumberRule.match({ v: 'abc' }, {} as any)).toBe(false);+ expect(chnNumberRule.isContinue({ type: AUTO_FILL_DATA_TYPE.CHN_NUMBER, cellData: { v: '一' } }, { v: '二' })).toBe(true);++ const normal = chnNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: '三' }], index: [0] },+ 2,+ Direction.DOWN,+ {} as any+ );+ expect(normal?.map((c) => c?.v)).toEqual(['四', '五']);++ const week = chnNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: '六' }, { v: '日' }], index: [0, 1] },+ 3,+ Direction.DOWN,+ {} as any+ );+ expect(week?.map((c) => c?.v)).toEqual(['一', '二', '三']);+ });++ it('chinese week rules should produce weekday sequence', () => {+ expect(chnWeek2Rule.match({ v: '周一' }, {} as any)).toBe(true);+ expect(chnWeek3Rule.match({ v: '星期一' }, {} as any)).toBe(true);+ expect(chnWeek2Rule.isContinue({ type: AUTO_FILL_DATA_TYPE.CHN_WEEK2, cellData: { v: '周一' } }, { v: '周二' })).toBe(true);+ expect(chnWeek3Rule.isContinue({ type: AUTO_FILL_DATA_TYPE.CHN_WEEK3, cellData: { v: '星期一' } }, { v: '星期二' })).toBe(true);++ const week2 = chnWeek2Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: '周六' }, { v: '周日' }], index: [0, 1] },+ 2,+ Direction.DOWN,+ {} as any+ );+ expect(week2?.map((c) => c?.v)).toEqual(['周一', '周二']);++ const week3 = chnWeek3Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: '星期六' }], index: [0] },+ 2,+ Direction.DOWN,+ {} as any+ );+ expect(week3?.map((c) => c?.v)).toEqual(['星期日', '星期一']);+ });++ it('loop-series rule should match and fill cyclic values', () => {+ expect(loopSeriesRule.match({ v: 'Jan' }, {} as any)).toBe(true);+ expect(loopSeriesRule.match({ v: 'custom' }, {} as any)).toBe(false);+ expect(+ loopSeriesRule.isContinue(+ { type: AUTO_FILL_DATA_TYPE.LOOP_SERIES, cellData: { v: 'Mon' } },+ { v: 'Tue' }+ )+ ).toBe(true);++ const oneValue = loopSeriesRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 'Dec' }], index: [0] },+ 2,+ Direction.DOWN,+ {} as any+ );+ expect(oneValue?.map((c) => c?.v)).toEqual(['Jan', 'Feb']);++ const reversed = loopSeriesRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(+ { data: [{ v: 'Mar' }, { v: 'Apr' }], index: [0, 1] },+ 2,+ Direction.LEFT,+ {} as any+ );+ expect(reversed?.length).toBe(2);+ });++ it('other rule should always match and continue only from OTHER', () => {+ expect(otherRule.match(undefined, {} as any)).toBe(true);+ expect(otherRule.isContinue({ type: AUTO_FILL_DATA_TYPE.OTHER, cellData: { v: 'x' } }, { v: 'y' })).toBe(true);+ expect(otherRule.isContinue({ type: AUTO_FILL_DATA_TYPE.NUMBER, cellData: { v: 1 } }, { v: 2 })).toBe(false);+ });+});diff --git a/packages/sheets/src/services/auto-fill/__tests__/tool.spec.ts b/packages/sheets/src/services/auto-fill/__tests__/tool.spec.tsindex ff3352c487..01ab87e025 100644--- a/packages/sheets/src/services/auto-fill/__tests__/tool.spec.ts+++ b/packages/sheets/src/services/auto-fill/__tests__/tool.spec.ts@@ -18,7 +18,36 @@ import { CellValueType } from '@univerjs/core';import { describe, expect, it } from 'vitest';import AutoFillTools from '../tools';-const { needsUpdateCellValue } = AutoFillTools;+const {+ chineseToNumber,+ numberToChinese,+ isChnNumber,+ matchExtendNumber,+ isChnWeek1,+ isChnWeek2,+ isChnWeek3,+ getLenS,+ isEqualDiff,+ getDataIndex,+ fillCopy,+ fillCopyStyles,+ isEqualRatio,+ getXArr,+ fillSeries,+ forecast,+ fillExtendNumber,+ fillOnlyFormat,+ fillChnWeek,+ fillChnNumber,+ isLoopSeries,+ getLoopSeriesInfo,+ fillLoopSeries,+ getAutoFillRepeatRange,+ needsUpdateCellValue,+ removeCellCustom,+ reverseIfNeed,+ generateNullCellValueRowCol,+} = AutoFillTools;describe('Test tool', () => {it('Function needsUpdateCellValue', () => {@@ -27,4 +56,192 @@ describe('Test tool', () => {expect(needsUpdateCellValue({ t: CellValueType.BOOLEAN })).toBeFalsy();expect(needsUpdateCellValue({ v: 1, t: CellValueType.NUMBER })).toBeTruthy();});++ it('converts chinese numbers correctly', () => {+ expect(chineseToNumber()).toBe(0);++ const numbers = [1, 9, 10, 11, 20, 101, 10005];+ numbers.forEach((n) => {+ expect(chineseToNumber(numberToChinese(n))).toBe(n);+ });+ });++ it('checks chinese text and week labels', () => {+ expect(isChnNumber('日')).toBeTruthy();+ expect(isChnNumber('十二')).toBeTruthy();+ expect(isChnNumber('abc')).toBeFalsy();+ expect(isChnNumber('十')).toBeFalsy();++ expect(isChnWeek1('日')).toBeTruthy();+ expect(isChnWeek1('八')).toBeFalsy();+ expect(isChnWeek2('周三')).toBeTruthy();+ expect(isChnWeek2('星期三')).toBeFalsy();+ expect(isChnWeek3('星期三')).toBeTruthy();+ expect(isChnWeek3('周三')).toBeFalsy();+ });++ it('matches and extends numeric suffix in text', () => {+ expect(matchExtendNumber('item12')).toEqual({+ isExtendNumber: true,+ matchTxt: 12,+ beforeTxt: 'item',+ afterTxt: '',+ });+ expect(matchExtendNumber('text')).toEqual({ isExtendNumber: false });+ });++ it('handles numeric helper utilities', () => {+ expect(getLenS([0, 2, 4], 3)).toBe(2);+ expect(isEqualDiff([1, 3, 5, 7])).toBeTruthy();+ expect(isEqualDiff([1, 3, 6])).toBeFalsy();+ expect(isEqualRatio([2, 4, 8])).toBeTruthy();+ expect(isEqualRatio([2, 4, 9])).toBeFalsy();+ expect(getXArr(4)).toEqual([1, 2, 3, 4]);+ });++ it('builds data index map for copy types', () => {+ const result = getDataIndex(4, 10, [0, 2]);+ expect(result[0]).toBe(0);+ expect(result[2]).toBe(1);+ expect(result[4]).toBe(2);+ expect(result[6]).toBe(3);+ expect(result[8]).toBe(4);+ });++ it('fills copy data and styles', () => {+ const data = [{ v: 1, s: 's1', custom: { a: 1 } }, { v: 2, s: 's2' }];++ const copied = fillCopy(data, 3);+ expect(copied.map((d) => d.v)).toEqual([1, 2, 1]);+ expect(copied[0].custom).toBeUndefined();+ expect(copied[0].p).toBeNull();++ const copiedStyles = fillCopyStyles(data, 3);+ expect(copiedStyles).toEqual([{ s: 's1' }, { s: 's2' }, { s: 's1' }]);+ });++ it('fills numeric series by regression and ratio', () => {+ const linearData = [{ v: 1 }, { v: 2 }, { v: 3 }];+ const linear = fillSeries(linearData, 2, 0);+ expect(linear.map((d) => d?.v)).toEqual([4, 5]);++ const ratioData = [{ v: 2 }, { v: 4 }, { v: 8 }];+ const ratio = fillSeries(ratioData, 2, 0);+ expect(ratio.map((d) => d?.v)).toEqual([16, 32]);++ const formulaData = [{ v: 1, f: '=A1' }, { v: 2 }, { v: 3 }];+ const formula = fillSeries(formulaData, 1, 0);+ expect(formula[0]?.v).toBe(1);+ });++ it('forecasts with fallback slope when x variance is zero', () => {+ expect(forecast(5, [2, 2, 2], [1, 1, 1], true)).toBe(6);+ expect(forecast(5, [2, 2, 2], [1, 1, 1], false)).toBe(-2);+ });++ it('fills extended text-number and format-only content', () => {+ const extended = fillExtendNumber([{ v: 'item12', s: 's1', custom: { flag: true } }], 2, 2);+ expect(extended.map((d) => d?.v)).toEqual(['item14', 'item16']);+ expect(extended[0]?.custom).toBeUndefined();++ const formatOnly = fillOnlyFormat([{ v: 1, s: 's1', custom: { flag: true } }], 1);+ expect(formatOnly[0]).toEqual({ s: 's1' });+ });++ it('fills chinese week and chinese number sequences', () => {+ const week = fillChnWeek([{ v: '日', custom: { flag: true } }], 3, 1, 0);+ expect(week.map((d) => d?.v)).toEqual(['一', '二', '三']);+ expect(week[0]?.custom).toBeUndefined();++ const weekBack = fillChnWeek([{ v: '一' }], 1, -2, 0);+ expect(weekBack[0]?.v).toBe('六');++ const chnNumber = fillChnNumber([{ v: '一' }], 2, 1);+ expect(chnNumber.map((d) => d?.v)).toEqual(['二', '三']);++ const belowZero = fillChnNumber([{ v: '一' }], 1, -2);+ expect(belowZero[0]?.v).toBe('零');+ });++ it('handles loop series detection and filling', () => {+ expect(isLoopSeries('Mon')).toBeTruthy();+ expect(isLoopSeries('NotInSeries')).toBeFalsy();++ const info = getLoopSeriesInfo('Mon');+ expect(info.name).toBe('enWeek1');+ expect(info.series).toHaveLength(7);++ const loop = fillLoopSeries([{ v: 'B' }], 2, 1, ['A', 'B', 'C']);+ expect(loop.map((d) => d?.v)).toEqual(['C', 'A']);++ const loopBack = fillLoopSeries([{ v: 'A' }], 1, -2, ['A', 'B', 'C']);+ expect(loopBack[0]?.v).toBe('B');+ });++ it('calculates auto-fill repeat ranges for each direction', () => {+ const sourceRange = {+ startRow: 1,+ endRow: 2,+ startColumn: 1,+ endColumn: 2,+ };++ expect(getAutoFillRepeatRange(sourceRange, sourceRange)).toEqual([]);++ const down = getAutoFillRepeatRange(sourceRange, {+ startRow: 3,+ endRow: 5,+ startColumn: 1,+ endColumn: 2,+ });+ expect(down).toHaveLength(2);+ expect(down[0].repeatStartCell).toEqual({ row: 3, col: 1 });+ expect(down[1].relativeRange.endRow).toBe(0);++ const up = getAutoFillRepeatRange(sourceRange, {+ startRow: -1,+ endRow: 0,+ startColumn: 1,+ endColumn: 2,+ });+ expect(up[0].repeatStartCell).toEqual({ row: -1, col: 1 });++ const right = getAutoFillRepeatRange(sourceRange, {+ startRow: 1,+ endRow: 2,+ startColumn: 3,+ endColumn: 5,+ });+ expect(right[0].repeatStartCell).toEqual({ row: 1, col: 3 });++ const left = getAutoFillRepeatRange(sourceRange, {+ startRow: 1,+ endRow: 2,+ startColumn: -2,+ endColumn: 0,+ });+ expect(left[0].repeatStartCell).toEqual({ row: 1, col: -1 });+ });++ it('removes custom field, reverses arrays and generates null matrix', () => {+ const cell = { v: 1, custom: { a: 1 } };+ removeCellCustom(cell);+ expect(cell.custom).toBeUndefined();++ expect(reverseIfNeed([1, 2, 3], false)).toEqual([1, 2, 3]);+ expect(reverseIfNeed([1, 2, 3], true)).toEqual([3, 2, 1]);++ const nullMatrix = generateNullCellValueRowCol([+ { rows: [0, 1], cols: [2] },+ { rows: [3], cols: [1, 2] },+ ]);+ expect(nullMatrix).toEqual({+ 0: { 2: { v: null, p: null, f: null, si: null, custom: null } },+ 1: { 2: { v: null, p: null, f: null, si: null, custom: null } },+ 3: {+ 1: { v: null, p: null, f: null, si: null, custom: null },+ 2: { v: null, p: null, f: null, si: null, custom: null },+ },+ });+ });});diff --git a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.tsnew file mode 100644index 0000000000..29169c8c58--- /dev/null+++ b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts@@ -0,0 +1,266 @@+/**+ * 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 { Injector, IRange, Univer, Workbook } from '@univerjs/core';+import type { IRangeProtectionRule } from '../../../../model/range-protection-rule.model';+import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { UnitObject } from '@univerjs/protocol';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { RemoveSheetCommand } from '../../../../commands/commands/remove-sheet.command';+import { AddRangeProtectionMutation } from '../../../../commands/mutations/add-range-protection.mutation';+import { DeleteRangeProtectionMutation } from '../../../../commands/mutations/delete-range-protection.mutation';+import { InsertColMutation, InsertRowMutation } from '../../../../commands/mutations/insert-row-col.mutation';+import { MoveColsMutation, MoveRowsMutation } from '../../../../commands/mutations/move-rows-cols.mutation';+import { SetRangeProtectionMutation } from '../../../../commands/mutations/set-range-protection.mutation';+import { RangeProtectionRenderModel } from '../../../../model/range-protection-render.model';+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../../model/range-protection-rule.model';+import { RangeProtectionCache } from '../../../../model/range-protection.cache';+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../../__tests__/util';+import { RefRangeService } from '../../../ref-range/ref-range.service';+import { SheetsSelectionsService } from '../../../selections/selection.service';+import { SheetInterceptorService } from '../../../sheet-interceptor/sheet-interceptor.service';+import { RangeProtectionRefRangeService } from '../range-protection.ref-range';++describe('RangeProtectionRefRangeService', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let service: RangeProtectionRefRangeService;+ let ruleModel: RangeProtectionRuleModel;+ let rangeProtectionCache: RangeProtectionCache;+ let refRangeService: RefRangeService;+ let sheetInterceptorService: SheetInterceptorService;+ let unitId: string;+ let subUnitId: string;+ let seed = 0;++ const createRule = (overrides?: Partial<IRangeProtectionRule>): IRangeProtectionRule => {+ seed += 1;+ return {+ id: `rule-${seed}`,+ permissionId: `permission-${seed}`,+ unitId,+ subUnitId,+ unitType: UnitObject.SelectRange,+ viewState: ViewStateEnum.OthersCanView,+ editState: EditStateEnum.DesignedUserCanEdit,+ ranges: [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 3 }],+ ...overrides,+ };+ };++ beforeEach(() => {+ const testBed = createTestBase(TEST_WORKBOOK_DATA_DEMO, [+ [SheetsSelectionsService],+ [RefRangeService],+ [SheetInterceptorService],+ [RangeProtectionRuleModel],+ [RangeProtectionRenderModel],+ [RangeProtectionCache],+ [RangeProtectionRefRangeService],+ ]);++ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ refRangeService = get(RefRangeService);+ rangeProtectionCache = get(RangeProtectionCache);+ ruleModel = get(RangeProtectionRuleModel);+ sheetInterceptorService = get(SheetInterceptorService);++ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ unitId = workbook.getUnitId();+ subUnitId = workbook.getActiveSheet()!.getSheetId();++ [+ AddRangeProtectionMutation,+ SetRangeProtectionMutation,+ InsertColMutation,+ InsertRowMutation,+ MoveRowsMutation,+ MoveColsMutation,+ ].forEach((command) => commandService.registerCommand(command));++ service = get(RangeProtectionRefRangeService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('should route handler by command id and fallback to empty mutations', () => {+ const spyMoveRows = vi.spyOn(service as any, '_getRefRangeMutationsByMoveRows').mockReturnValue({ redos: ['moveRows'], undos: [] });+ const spyMoveCols = vi.spyOn(service as any, '_getRefRangeMutationsByMoveCols').mockReturnValue({ redos: ['moveCols'], undos: [] });+ const spyInsertRows = vi.spyOn(service as any, '_getRefRangeMutationsByInsertRows').mockReturnValue({ redos: ['insertRows'], undos: [] });+ const spyInsertCols = vi.spyOn(service as any, '_getRefRangeMutationsByInsertCols').mockReturnValue({ redos: ['insertCols'], undos: [] });+ const spyDeleteCols = vi.spyOn(service as any, '_getRefRangeMutationsByDeleteCols').mockReturnValue({ redos: ['deleteCols'], undos: [] });+ const spyDeleteRows = vi.spyOn(service as any, '_getRefRangeMutationsByDeleteRows').mockReturnValue({ redos: ['deleteRows'], undos: [] });++ expect(service.refRangeHandle({ id: 'sheet.command.move-rows', params: {} } as any, unitId, subUnitId)).toEqual({ redos: ['moveRows'], undos: [] });+ expect(service.refRangeHandle({ id: 'sheet.command.move-cols', params: {} } as any, unitId, subUnitId)).toEqual({ redos: ['moveCols'], undos: [] });+ expect(service.refRangeHandle({ id: 'sheet.command.insert-row', params: {} } as any, unitId, subUnitId)).toEqual({ redos: ['insertRows'], undos: [] });+ expect(service.refRangeHandle({ id: 'sheet.command.insert-col', params: {} } as any, unitId, subUnitId)).toEqual({ redos: ['insertCols'], undos: [] });+ expect(service.refRangeHandle({ id: 'sheet.command.remove-col', params: {} } as any, unitId, subUnitId)).toEqual({ redos: ['deleteCols'], undos: [] });+ expect(service.refRangeHandle({ id: 'sheet.command.remove-row', params: {} } as any, unitId, subUnitId)).toEqual({ redos: ['deleteRows'], undos: [] });+ expect(service.refRangeHandle({ id: 'unknown', params: {} } as any, unitId, subUnitId)).toEqual({ redos: [], undos: [] });++ expect(spyMoveRows).toHaveBeenCalled();+ expect(spyMoveCols).toHaveBeenCalled();+ expect(spyInsertRows).toHaveBeenCalled();+ expect(spyInsertCols).toHaveBeenCalled();+ expect(spyDeleteCols).toHaveBeenCalled();+ expect(spyDeleteRows).toHaveBeenCalled();+ });++ it('should generate set and delete mutations for delete-cols', () => {+ const partialRule = createRule({+ ranges: [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 3 }],+ });+ ruleModel.addRule(unitId, subUnitId, partialRule);++ const partialResult = (service as any)._getRefRangeMutationsByDeleteCols(+ { range: { startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 } },+ unitId,+ subUnitId+ );+ expect(partialResult.redos[0].id).toBe(SetRangeProtectionMutation.id);+ expect(partialResult.redos[0].params.rule.ranges[0]).toEqual({+ startRow: 0,+ endRow: 0,+ startColumn: 1,+ endColumn: 2,+ });++ const fullRule = createRule({+ ranges: [{ startRow: 1, endRow: 1, startColumn: 4, endColumn: 5 }],+ });+ ruleModel.addRule(unitId, subUnitId, fullRule);++ const fullResult = (service as any)._getRefRangeMutationsByDeleteCols(+ { range: { startRow: 1, endRow: 1, startColumn: 4, endColumn: 5 } },+ unitId,+ subUnitId+ );+ expect(fullResult.redos.some((redo: any) => redo.id === DeleteRangeProtectionMutation.id)).toBe(true);+ });++ it('should generate insert and move mutations for overlap rules', () => {+ const rule = createRule({+ ranges: [{ startRow: 5, endRow: 8, startColumn: 5, endColumn: 8 }],+ });+ ruleModel.addRule(unitId, subUnitId, rule);++ const insertRows = (service as any)._getRefRangeMutationsByInsertRows(+ { range: { startRow: 6, endRow: 7, startColumn: 0, endColumn: 0 } },+ unitId,+ subUnitId+ );+ expect(insertRows.redos[0].params.rule.ranges[0]).toMatchObject({ startRow: 5, endRow: 10 });++ const insertCols = (service as any)._getRefRangeMutationsByInsertCols(+ { range: { startRow: 0, endRow: 0, startColumn: 6, endColumn: 7 } },+ unitId,+ subUnitId+ );+ expect(insertCols.redos[0].params.rule.ranges[0]).toMatchObject({ startColumn: 5, endColumn: 10 });++ const moveRows = (service as any)._getRefRangeMutationsByMoveRows(+ {+ fromRange: { startRow: 2, endRow: 3, startColumn: 0, endColumn: 0 },+ toRange: { startRow: 6, endRow: 7, startColumn: 0, endColumn: 0 },+ },+ unitId,+ subUnitId+ );+ expect(moveRows.redos[0].params.rule.ranges[0]).toMatchObject({ startRow: 3, endRow: 8 });++ const moveCols = (service as any)._getRefRangeMutationsByMoveCols(+ {+ fromRange: { startRow: 0, endRow: 0, startColumn: 2, endColumn: 3 },+ toRange: { startRow: 0, endRow: 0, startColumn: 6, endColumn: 7 },+ },+ unitId,+ subUnitId+ );+ expect(moveCols.redos[0].params.rule.ranges[0]).toMatchObject({ startColumn: 3, endColumn: 8 });+ expect((service as any)._checkIsRightRange({ startRow: 1, endRow: 0, startColumn: 0, endColumn: 0 })).toBe(false);+ });++ it('should rebuild cache when move mutation executes', async () => {+ const rebuildSpy = vi.spyOn(rangeProtectionCache, 'reBuildCache');++ await commandService.executeCommand(MoveRowsMutation.id, {+ unitId,+ subUnitId,+ sourceRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 },+ targetRange: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 1 },+ });++ expect(rebuildSpy).toHaveBeenCalledWith(unitId, subUnitId);+ });++ it('should register ref ranges after range protection mutation', async () => {+ const registerSpy = vi.spyOn(refRangeService, 'registerRefRange');+ const rule = createRule({+ ranges: [{ startRow: 3, endRow: 4, startColumn: 3, endColumn: 4 } as IRange],+ });++ await commandService.executeCommand(AddRangeProtectionMutation.id, {+ unitId,+ subUnitId,+ rules: [rule],+ });++ expect(registerSpy).toHaveBeenCalled();+ });++ it('should inject pre-redo and undo mutations when removing sheet', () => {+ const ruleA = createRule({ id: 'rule-a', permissionId: 'permission-a' });+ const ruleB = createRule({ id: 'rule-b', permissionId: 'permission-b' });+ ruleModel.addRule(unitId, subUnitId, ruleA);+ ruleModel.addRule(unitId, subUnitId, ruleB);++ const interceptorResult = sheetInterceptorService.onCommandExecute({+ id: RemoveSheetCommand.id,+ params: {+ unitId,+ subUnitId,+ },+ });++ expect(interceptorResult.preRedos).toEqual([+ {+ id: DeleteRangeProtectionMutation.id,+ params: {+ unitId,+ subUnitId,+ ruleIds: ['rule-a', 'rule-b'],+ },+ },+ ]);+ expect(interceptorResult.undos).toEqual([+ {+ id: AddRangeProtectionMutation.id,+ params: {+ unitId,+ subUnitId,+ name: '',+ rules: [ruleA, ruleB],+ },+ },+ ]);+ });+});diff --git a/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts b/packages/sheets/src/services/ref-range/__tests__/utils.spec.tsindex 8ed7f8c8da..9a7b80f8fe 100644--- a/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts+++ b/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts@@ -940,7 +940,7 @@ describe('test ref-range move', () => {const operators = handleInsertCol({id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.LEFT },},targetRange);@@ -952,7 +952,7 @@ describe('test ref-range move', () => {const operators = handleInsertCol({id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.LEFT },},targetRange);@@ -964,7 +964,7 @@ describe('test ref-range move', () => {const operators = handleInsertCol({id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.LEFT },},targetRange);@@ -976,7 +976,7 @@ describe('test ref-range move', () => {const operators = handleInsertCol({id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.LEFT },},targetRange);@@ -989,7 +989,7 @@ describe('test ref-range move', () => {const operators = handleInsertCol({id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.LEFT },},targetRange);@@ -1003,7 +1003,7 @@ describe('test ref-range move', () => {const operators = handleInsertCol({id: EffectRefRangId.InsertColCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.LEFT },},targetRange);@@ -1022,7 +1022,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);@@ -1034,7 +1034,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);@@ -1046,7 +1046,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);@@ -1058,7 +1058,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);@@ -1070,7 +1070,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);@@ -1083,7 +1083,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);@@ -1096,7 +1096,7 @@ describe('test ref-range move', () => {const operators = handleInsertRow({id: EffectRefRangId.InsertRowCommandId,- params: { range, unitId: '', subUnitId: '', direction: '' as any },+ params: { range, unitId: '', subUnitId: '', direction: Direction.UP },},targetRange);diff --git a/packages/sheets/src/services/selections/__tests__/ref-selections.service.spec.ts b/packages/sheets/src/services/selections/__tests__/ref-selections.service.spec.tsnew file mode 100644index 0000000000..0979f426a9--- /dev/null+++ b/packages/sheets/src/services/selections/__tests__/ref-selections.service.spec.ts@@ -0,0 +1,153 @@+/**+ * 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 { Workbook } from '@univerjs/core';+import type { WorkbookSelectionModel } from '../selection-data-model';+import { firstValueFrom, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { RefSelectionsService } from '../ref-selections.service';++function createWorkbook(unitId: string): Workbook {+ return {+ getUnitId: () => unitId,+ } as unknown as Workbook;+}++function createSelectionModelMock() {+ return {+ selectionMoveStart$: new Subject<unknown>(),+ selectionMoving$: new Subject<unknown>(),+ selectionMoveEnd$: new Subject<unknown>(),+ selectionSet$: new Subject<unknown>(),+ dispose: vi.fn(),+ clear: vi.fn(),+ };+}++class TestRefSelectionsService extends RefSelectionsService {+ public get modelMap() {+ const self = this as unknown as { __modelMap?: Map<string, ReturnType<typeof createSelectionModelMock>> };+ if (!self.__modelMap) {+ self.__modelMap = new Map<string, ReturnType<typeof createSelectionModelMock>>();+ }+ return self.__modelMap;+ }++ public get removedUnitIds() {+ const self = this as unknown as { __removedUnitIds?: string[] };+ if (!self.__removedUnitIds) {+ self.__removedUnitIds = [];+ }+ return self.__removedUnitIds;+ }++ protected override _ensureWorkbookSelection(unitId: string): WorkbookSelectionModel {+ let model = this.modelMap.get(unitId);+ if (!model) {+ model = createSelectionModelMock();+ this.modelMap.set(unitId, model);+ this._workbookSelections.set(unitId, model as unknown as WorkbookSelectionModel);+ }++ return model as unknown as WorkbookSelectionModel;+ }++ protected override _removeWorkbookSelection(unitId: string): void {+ this.removedUnitIds.push(unitId);+ this.modelMap.delete(unitId);+ this._workbookSelections.delete(unitId);+ }+}++describe('RefSelectionsService', () => {+ const workbookA = createWorkbook('wb-a');+ const workbookB = createWorkbook('wb-b');++ let add$: Subject<Workbook>;+ let disposed$: Subject<Workbook>;+ let instanceService: {+ getAllUnitsForType: ReturnType<typeof vi.fn>;+ getTypeOfUnitAdded$: ReturnType<typeof vi.fn>;+ getTypeOfUnitDisposed$: ReturnType<typeof vi.fn>;+ };++ let service: TestRefSelectionsService;++ beforeEach(() => {+ add$ = new Subject<Workbook>();+ disposed$ = new Subject<Workbook>();+ instanceService = {+ getAllUnitsForType: vi.fn(() => [workbookA]),+ getTypeOfUnitAdded$: vi.fn(() => add$.asObservable()),+ getTypeOfUnitDisposed$: vi.fn(() => disposed$.asObservable()),+ };+ });++ afterEach(() => {+ service?.dispose();+ add$.complete();+ disposed$.complete();+ });++ it('merges all workbook selection streams and handles workbook lifecycle', () => {+ service = new TestRefSelectionsService(instanceService as never);++ const startEvents: unknown[] = [];+ const movingEvents: unknown[] = [];+ const endEvents: unknown[] = [];+ const setEvents: unknown[] = [];++ service.selectionMoveStart$.subscribe((event) => startEvents.push(event));+ service.selectionMoving$.subscribe((event) => movingEvents.push(event));+ service.selectionMoveEnd$.subscribe((event) => endEvents.push(event));+ service.selectionSet$.subscribe((event) => setEvents.push(event));++ const modelA = service.modelMap.get('wb-a')!;+ modelA.selectionMoveStart$.next('a-start');+ modelA.selectionMoving$.next('a-moving');+ modelA.selectionMoveEnd$.next('a-end');+ modelA.selectionSet$.next('a-set');++ expect(startEvents).toEqual(['a-start']);+ expect(movingEvents).toEqual(['a-moving']);+ expect(endEvents).toEqual(['a-end']);+ expect(setEvents).toEqual(['a-set']);++ add$.next(workbookB);+ const modelB = service.modelMap.get('wb-b')!;+ modelB.selectionMoving$.next('b-moving');+ expect(movingEvents).toEqual(['a-moving', 'b-moving']);++ disposed$.next(workbookA);+ expect(service.removedUnitIds).toEqual(['wb-a']);+ modelA.selectionMoving$.next('a-moving-after-dispose');+ expect(movingEvents).toEqual(['a-moving', 'b-moving']);+ });++ it('clears workbook state and resets streams on dispose', async () => {+ service = new TestRefSelectionsService(instanceService as never);+ const modelA = service.modelMap.get('wb-a')!;++ service.dispose();++ expect(modelA.dispose).toHaveBeenCalled();+ expect((service as unknown as { _workbookSelections: Map<string, unknown> })._workbookSelections.size).toBe(0);+ await expect(firstValueFrom(service.selectionMoveStart$)).resolves.toBeNull();+ await expect(firstValueFrom(service.selectionMoving$)).resolves.toBeNull();+ await expect(firstValueFrom(service.selectionMoveEnd$)).resolves.toBeNull();+ await expect(firstValueFrom(service.selectionSet$)).resolves.toBeNull();+ });+});diff --git a/packages/telemetry/src/index.spec.ts b/packages/telemetry/src/index.spec.tsnew file mode 100644index 0000000000..6f6854ae9c--- /dev/null+++ b/packages/telemetry/src/index.spec.ts@@ -0,0 +1,26 @@+/**+ * 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 * as indexModule from './index';+import { ITelemetryService } from './services/telemetry-service';++describe('telemetry exports', () => {+ it('should re-export ITelemetryService identifier from index', () => {+ expect(indexModule.ITelemetryService).toBe(ITelemetryService);+ expect(String(ITelemetryService)).toContain('telemetry.service');+ });+});diff --git a/packages/telemetry/src/services/telemetry-service.ts b/packages/telemetry/src/services/telemetry-service.tsindex 329105b2e4..5bbf00aca9 100644--- a/packages/telemetry/src/services/telemetry-service.ts+++ b/packages/telemetry/src/services/telemetry-service.ts@@ -29,14 +29,14 @@ export interface ITelemetryService {* @param token* @param options*/- init: (options?: Record<string, any>) => void;+ init: (options?: object) => void;/*** Identify the user.* @param id* @param params* @returns*/- identify: (id: string, params?: Record<string, any>) => void;+ identify: (id: string, params?: object) => void;/*** Reset the user.*/@@ -46,7 +46,7 @@ export interface ITelemetryService {* @param eventName* @param params*/- capture: (eventName: string, params?: Record<string, any>) => void;+ capture: (eventName: string, params?: object) => void;/*** Start the timer.* @param functionName@@ -64,7 +64,7 @@ export interface ITelemetryService {trackPerformance: (params: {duration: number;functionName: string;- [prop: string]: any;+ [prop: string]: unknown;}) => void;/*** Track the page view.diff --git a/packages/thread-comment/src/commands/commands/__tests__/comment.command.spec.ts b/packages/thread-comment/src/commands/commands/__tests__/comment.command.spec.tsnew file mode 100644index 0000000000..e839ed0250--- /dev/null+++ b/packages/thread-comment/src/commands/commands/__tests__/comment.command.spec.ts@@ -0,0 +1,220 @@+/**+ * 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 { IDocumentBody, Injector, IWorkbookData } from '@univerjs/core';+import type { CommentUpdate } from '../../../models/thread-comment.model';+import type { IThreadComment } from '../../../types/interfaces/i-thread-comment';+import {+ ICommandService,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { ThreadCommentModel } from '../../../models/thread-comment.model';+import { UniverThreadCommentPlugin } from '../../../plugin';+import {+ AddCommentCommand,+ DeleteCommentCommand,+ DeleteCommentTreeCommand,+ ResolveCommentCommand,+ UpdateCommentCommand,+} from '../comment.command';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'unit-1',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet-1'],+ styles: {},+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet1',+ cellData: {},+ },+ },+ };+}++function createBody(text: string): IDocumentBody {+ return {+ dataStream: `${text}\r\n`,+ };+}++function createComment(overrides: Partial<IThreadComment> = {}): IThreadComment {+ const id = overrides.id ?? 'comment-1';++ return {+ id,+ threadId: overrides.threadId ?? overrides.parentId ?? id,+ ref: overrides.ref ?? 'A1',+ dT: overrides.dT ?? '2024-01-01T00:00:00.000Z',+ personId: overrides.personId ?? 'user-1',+ text: overrides.text ?? createBody(id),+ unitId: overrides.unitId ?? 'unit-1',+ subUnitId: overrides.subUnitId ?? 'sheet-1',+ attachments: overrides.attachments,+ children: overrides.children,+ mentions: overrides.mentions,+ parentId: overrides.parentId,+ resolved: overrides.resolved,+ updateT: overrides.updateT,+ updated: overrides.updated,+ };+}++describe('Thread comment commands', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;+ let threadCommentModel: ThreadCommentModel;++ beforeEach(() => {+ univer = new Univer();+ univer.registerPlugin(UniverThreadCommentPlugin);+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ const injector = univer.__getInjector();+ get = injector.get.bind(injector);+ get(IUniverInstanceService).focusUnit('unit-1');+ get(LifecycleService).stage = LifecycleStages.Rendered;++ commandService = get(ICommandService);+ threadCommentModel = get(ThreadCommentModel);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('adds root comments and replies through real commands', async () => {+ const events: CommentUpdate[] = [];+ const subscription = threadCommentModel.commentUpdate$.subscribe((event) => events.push(event));++ const root = createComment({ id: 'root-1', personId: 'owner' });+ const reply = createComment({+ id: 'reply-1',+ parentId: root.id,+ threadId: root.id,+ personId: 'guest',+ ref: '',+ });++ await commandService.executeCommand(AddCommentCommand.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ comment: root,+ });+ await commandService.executeCommand(AddCommentCommand.id, {+ unitId: reply.unitId,+ subUnitId: reply.subUnitId,+ comment: reply,+ });++ subscription.unsubscribe();++ expect(threadCommentModel.getThread('unit-1', 'sheet-1', root.id)).toEqual({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ threadId: root.id,+ root,+ children: [reply],+ relativeUsers: new Set(['owner', 'guest']),+ });+ expect(events.map((event) => ({ type: event.type, isRoot: event.type === 'add' ? event.isRoot : undefined }))).toEqual([+ { type: 'add', isRoot: true },+ { type: 'add', isRoot: false },+ ]);+ });++ it('resolves a thread and deletes the whole tree when deleting by reply id', async () => {+ const root = createComment({ id: 'root-2' });+ const reply = createComment({+ id: 'reply-2',+ parentId: root.id,+ threadId: root.id,+ ref: '',+ });+ const events: CommentUpdate[] = [];+ const subscription = threadCommentModel.commentUpdate$.subscribe((event) => events.push(event));++ await commandService.executeCommand(AddCommentCommand.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ comment: root,+ });+ await commandService.executeCommand(AddCommentCommand.id, {+ unitId: reply.unitId,+ subUnitId: reply.subUnitId,+ comment: reply,+ });++ await commandService.executeCommand(ResolveCommentCommand.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ commentId: root.id,+ resolved: true,+ });++ await commandService.executeCommand(DeleteCommentTreeCommand.id, {+ unitId: reply.unitId,+ subUnitId: reply.subUnitId,+ commentId: reply.id,+ });++ subscription.unsubscribe();++ expect(threadCommentModel.getComment('unit-1', 'sheet-1', root.id)).toBeUndefined();+ expect(threadCommentModel.getThread('unit-1', 'sheet-1', root.id)).toBeUndefined();+ expect(events.filter((event) => event.type === 'resolve')).toEqual([+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ type: 'resolve',+ payload: {+ commentId: root.id,+ resolved: true,+ },+ },+ ]);+ expect(events.filter((event) => event.type === 'delete').map((event) => event.payload.commentId)).toEqual(['root-2', 'reply-2']);+ });++ it('returns false when updating or deleting a missing comment', async () => {+ await expect(commandService.executeCommand(UpdateCommentCommand.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ payload: {+ commentId: 'missing-comment',+ text: createBody('updated'),+ updateT: '2024-01-02T00:00:00.000Z',+ },+ })).resolves.toBe(false);++ await expect(commandService.executeCommand(DeleteCommentCommand.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ commentId: 'missing-comment',+ })).resolves.toBe(false);+ });+});diff --git a/packages/thread-comment/src/controllers/__tests__/tc-resource.controller.spec.ts b/packages/thread-comment/src/controllers/__tests__/tc-resource.controller.spec.tsnew file mode 100644index 0000000000..9581df687a--- /dev/null+++ b/packages/thread-comment/src/controllers/__tests__/tc-resource.controller.spec.ts@@ -0,0 +1,174 @@+/**+ * 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 { IDocumentBody, Injector, IWorkbookData } from '@univerjs/core';+import type { IThreadComment } from '../../types/interfaces/i-thread-comment';+import {+ IResourceManagerService,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { ThreadCommentModel } from '../../models/thread-comment.model';+import { UniverThreadCommentPlugin } from '../../plugin';+import { SHEET_UNIVER_THREAD_COMMENT_PLUGIN } from '../tc-resource.controller';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'unit-1',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet-1'],+ styles: {},+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet1',+ cellData: {},+ },+ },+ };+}++function createBody(text: string): IDocumentBody {+ return {+ dataStream: `${text}\r\n`,+ };+}++function createComment(overrides: Partial<IThreadComment> = {}): IThreadComment {+ const id = overrides.id ?? 'comment-1';++ return {+ id,+ threadId: overrides.threadId ?? overrides.parentId ?? id,+ ref: overrides.ref ?? 'A1',+ dT: overrides.dT ?? '2024-01-01T00:00:00.000Z',+ personId: overrides.personId ?? 'user-1',+ text: overrides.text ?? createBody(id),+ unitId: overrides.unitId ?? 'unit-1',+ subUnitId: overrides.subUnitId ?? 'sheet-1',+ attachments: overrides.attachments,+ children: overrides.children,+ mentions: overrides.mentions,+ parentId: overrides.parentId,+ resolved: overrides.resolved,+ updateT: overrides.updateT,+ updated: overrides.updated,+ };+}++describe('ThreadCommentResourceController', () => {+ let univer: Univer;+ let get: Injector['get'];+ let resourceManagerService: IResourceManagerService;+ let threadCommentModel: ThreadCommentModel;++ beforeEach(() => {+ univer = new Univer();+ univer.registerPlugin(UniverThreadCommentPlugin);+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ const injector = univer.__getInjector();+ get = injector.get.bind(injector);+ get(IUniverInstanceService).focusUnit('unit-1');+ get(LifecycleService).stage = LifecycleStages.Rendered;++ resourceManagerService = get(IResourceManagerService);+ threadCommentModel = get(ThreadCommentModel);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('serializes thread comments by sub unit with children preserved', () => {+ const root = createComment({ id: 'root-1', ref: 'A1' });+ const reply = createComment({ id: 'reply-1', parentId: root.id, threadId: root.id, ref: '' });+ const sideThread = createComment({ id: 'root-2', subUnitId: 'sheet-2', ref: 'B2' });++ threadCommentModel.addComment('unit-1', 'sheet-1', root);+ threadCommentModel.addComment('unit-1', 'sheet-1', reply);+ threadCommentModel.addComment('unit-1', 'sheet-2', sideThread);++ const resource = resourceManagerService.getResourcesByType('unit-1', UniverInstanceType.UNIVER_SHEET)+ .find((item) => item.name === SHEET_UNIVER_THREAD_COMMENT_PLUGIN);++ expect(resource).toBeDefined();+ expect(JSON.parse(resource!.data)).toEqual({+ 'sheet-1': [+ {+ ...root,+ children: [reply],+ },+ ],+ 'sheet-2': [+ {+ ...sideThread,+ children: [],+ },+ ],+ });+ });++ it('loads serialized comments and clears them on unload', async () => {+ const root = createComment({ id: 'root-3', ref: 'C3' });+ const reply = createComment({ id: 'reply-3', parentId: root.id, threadId: root.id, ref: '' });++ resourceManagerService.loadResources('unit-1', [{+ name: SHEET_UNIVER_THREAD_COMMENT_PLUGIN,+ data: JSON.stringify({+ 'sheet-1': [+ {+ ...root,+ children: [reply],+ },+ ],+ }),+ }]);++ await Promise.resolve();++ expect(threadCommentModel.getThread('unit-1', 'sheet-1', root.id)).toEqual({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ threadId: root.id,+ root,+ children: [reply],+ relativeUsers: new Set(['user-1']),+ });++ resourceManagerService.unloadResources('unit-1', UniverInstanceType.UNIVER_SHEET);++ expect(threadCommentModel.getUnit('unit-1')).toEqual([]);+ });++ it('ignores invalid snapshot payloads', async () => {+ resourceManagerService.loadResources('unit-1', [{+ name: SHEET_UNIVER_THREAD_COMMENT_PLUGIN,+ data: '{invalid-json',+ }]);++ await Promise.resolve();++ expect(threadCommentModel.getUnit('unit-1')).toEqual([]);+ });+});diff --git a/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts b/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.tsnew file mode 100644index 0000000000..1aef321ccd--- /dev/null+++ b/packages/thread-comment/src/models/__tests__/thread-comment.model.spec.ts@@ -0,0 +1,289 @@+/**+ * 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 { IDocumentBody, Injector, IWorkbookData } from '@univerjs/core';+import type { IThreadComment } from '../../types/interfaces/i-thread-comment';+import type { CommentUpdate } from '../thread-comment.model';+import {+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { UniverThreadCommentPlugin } from '../../plugin';+import { IThreadCommentDataSourceService } from '../../services/tc-datasource.service';+import { ThreadCommentModel } from '../thread-comment.model';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'unit-1',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet-1', 'sheet-2'],+ styles: {},+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet1',+ cellData: {},+ },+ 'sheet-2': {+ id: 'sheet-2',+ name: 'Sheet2',+ cellData: {},+ },+ },+ };+}++function createBody(text: string): IDocumentBody {+ return {+ dataStream: `${text}\r\n`,+ };+}++function createComment(overrides: Partial<IThreadComment> = {}): IThreadComment {+ const id = overrides.id ?? 'comment-1';++ return {+ id,+ threadId: overrides.threadId ?? overrides.parentId ?? id,+ ref: overrides.ref ?? 'A1',+ dT: overrides.dT ?? '2024-01-01T00:00:00.000Z',+ personId: overrides.personId ?? 'user-1',+ text: overrides.text ?? createBody(id),+ unitId: overrides.unitId ?? 'unit-1',+ subUnitId: overrides.subUnitId ?? 'sheet-1',+ attachments: overrides.attachments,+ children: overrides.children,+ mentions: overrides.mentions,+ parentId: overrides.parentId,+ resolved: overrides.resolved,+ updateT: overrides.updateT,+ updated: overrides.updated,+ };+}++describe('ThreadCommentModel', () => {+ let univer: Univer;+ let get: Injector['get'];+ let lifecycleService: LifecycleService;+ let threadCommentModel: ThreadCommentModel;+ let dataSourceService: IThreadCommentDataSourceService;++ beforeEach(() => {+ univer = new Univer();+ univer.registerPlugin(UniverThreadCommentPlugin);+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ const injector = univer.__getInjector();+ get = injector.get.bind(injector);+ get(IUniverInstanceService).focusUnit('unit-1');++ lifecycleService = get(LifecycleService);+ threadCommentModel = get(ThreadCommentModel);+ dataSourceService = get(IThreadCommentDataSourceService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('queues sync requests before rendered and applies merged updates after lifecycle is rendered', async () => {+ const root = createComment({ id: 'root-1', ref: 'A1', text: createBody('before sync') });+ threadCommentModel.addComment('unit-1', 'sheet-1', root);++ const listComments = vi.fn(async () => [{+ ...root,+ text: createBody('after sync'),+ resolved: true,+ ref: 'SHOULD_NOT_REPLACE_EXISTING_REF',+ }]);+ dataSourceService.dataSource = {+ addComment: vi.fn(),+ updateComment: vi.fn(),+ resolveComment: vi.fn(),+ deleteComment: vi.fn(),+ listComments,+ saveCommentToSnapshot: vi.fn(),+ };++ const events: CommentUpdate[] = [];+ const subscription = threadCommentModel.commentUpdate$.subscribe((event) => events.push(event));++ await threadCommentModel.syncThreadComments('unit-1', 'sheet-1', ['root-1']);+ await threadCommentModel.syncThreadComments('unit-1', 'sheet-1', ['root-1']);++ expect(listComments).not.toHaveBeenCalled();++ lifecycleService.stage = LifecycleStages.Rendered;+ await new Promise((resolve) => setTimeout(resolve, 0));+ await new Promise((resolve) => setTimeout(resolve, 0));++ subscription.unsubscribe();++ expect(listComments).toHaveBeenCalledTimes(1);+ expect(listComments).toHaveBeenCalledWith('unit-1', 'sheet-1', ['root-1']);+ expect(threadCommentModel.getComment('unit-1', 'sheet-1', 'root-1')).toMatchObject({+ id: 'root-1',+ ref: 'A1',+ resolved: true,+ text: createBody('after sync'),+ });+ expect(events).toEqual([+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ type: 'syncUpdate',+ payload: expect.objectContaining({+ id: 'root-1',+ ref: 'A1',+ resolved: true,+ }),+ },+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ type: 'resolve',+ payload: {+ commentId: 'root-1',+ resolved: true,+ },+ },+ ]);+ });++ it('removes threads that are absent from sync results', async () => {+ lifecycleService.stage = LifecycleStages.Rendered;++ const keepRoot = createComment({ id: 'keep-root' });+ const removeRoot = createComment({ id: 'remove-root', subUnitId: 'sheet-2' });++ threadCommentModel.addComment('unit-1', 'sheet-1', keepRoot);+ threadCommentModel.addComment('unit-1', 'sheet-2', removeRoot);++ dataSourceService.dataSource = {+ addComment: vi.fn(),+ updateComment: vi.fn(),+ resolveComment: vi.fn(),+ deleteComment: vi.fn(),+ listComments: vi.fn(async () => [keepRoot]),+ saveCommentToSnapshot: vi.fn(),+ };++ await threadCommentModel.syncThreadComments('unit-1', 'sheet-1', ['keep-root']);+ await threadCommentModel.syncThreadComments('unit-1', 'sheet-2', ['remove-root']);++ expect(threadCommentModel.getThread('unit-1', 'sheet-1', 'keep-root')).toBeDefined();+ expect(threadCommentModel.getThread('unit-1', 'sheet-2', 'remove-root')).toBeUndefined();+ expect(threadCommentModel.getUnit('unit-1').map((thread) => thread.threadId)).toEqual(['keep-root']);+ });++ it('updates refs, exposes thread lookups, and deletes all comments in a unit', () => {+ lifecycleService.stage = LifecycleStages.Rendered;++ const root = createComment({ id: 'root-2', personId: 'owner' });+ const reply = createComment({+ id: 'reply-2',+ parentId: 'root-2',+ threadId: 'root-2',+ personId: 'guest',+ ref: '',+ });+ const otherRoot = createComment({ id: 'root-3', subUnitId: 'sheet-2' });++ threadCommentModel.addComment('unit-1', 'sheet-1', root);+ threadCommentModel.addComment('unit-1', 'sheet-1', reply);+ threadCommentModel.addComment('unit-1', 'sheet-2', otherRoot);++ const events: CommentUpdate[] = [];+ const subscription = threadCommentModel.commentUpdate$.subscribe((event) => events.push(event));++ expect(threadCommentModel.updateCommentRef('unit-1', 'sheet-1', {+ commentId: 'root-2',+ ref: 'C5',+ })).toBe(true);+ expect(threadCommentModel.updateCommentRef('unit-1', 'sheet-1', {+ commentId: 'missing',+ ref: 'D6',+ })).toBe(false);++ expect(threadCommentModel.getCommentWithChildren('unit-1', 'sheet-1', 'reply-2')).toEqual({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ threadId: 'root-2',+ root: {+ ...root,+ ref: 'C5',+ },+ children: [reply],+ relativeUsers: new Set(['owner', 'guest']),+ });+ expect(threadCommentModel.getAll()).toEqual([+ {+ unitId: 'unit-1',+ threads: [+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ threadId: 'root-2',+ root: {+ ...root,+ ref: 'C5',+ },+ children: [reply],+ relativeUsers: new Set(['owner', 'guest']),+ },+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-2',+ threadId: 'root-3',+ root: otherRoot,+ children: [],+ relativeUsers: new Set(['user-1']),+ },+ ],+ },+ ]);++ threadCommentModel.deleteUnit('unit-1');+ subscription.unsubscribe();++ expect(threadCommentModel.getUnit('unit-1')).toEqual([]);+ expect(events.filter((event) => event.type === 'updateRef')).toEqual([+ {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ type: 'updateRef',+ payload: {+ commentId: 'root-2',+ ref: 'C5',+ },+ threadId: 'root-2',+ silent: undefined,+ },+ ]);+ expect(events.filter((event) => event.type === 'delete').map((event) => event.payload.commentId)).toEqual([+ 'root-2',+ 'reply-2',+ 'root-3',+ ]);+ });+});diff --git a/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts b/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.tsnew file mode 100644index 0000000000..8c1ab9cbe8--- /dev/null+++ b/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts@@ -0,0 +1,130 @@+/**+ * 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 { IDocumentBody } from '@univerjs/core';+import type { IThreadComment } from '../../types/interfaces/i-thread-comment';+import { describe, expect, it, vi } from 'vitest';+import { ThreadCommentDataSourceService } from '../tc-datasource.service';++function createBody(text: string): IDocumentBody {+ return {+ dataStream: `${text}\r\n`,+ };+}++function createComment(overrides: Partial<IThreadComment> = {}): IThreadComment {+ const id = overrides.id ?? 'comment-1';++ return {+ id,+ threadId: overrides.threadId ?? overrides.parentId ?? id,+ ref: overrides.ref ?? 'A1',+ dT: overrides.dT ?? '2024-01-01T00:00:00.000Z',+ personId: overrides.personId ?? 'user-1',+ text: overrides.text ?? createBody(id),+ unitId: overrides.unitId ?? 'unit-1',+ subUnitId: overrides.subUnitId ?? 'sheet-1',+ attachments: overrides.attachments,+ children: overrides.children,+ mentions: overrides.mentions,+ parentId: overrides.parentId,+ resolved: overrides.resolved,+ updateT: overrides.updateT,+ updated: overrides.updated,+ };+}++describe('ThreadCommentDataSourceService', () => {+ it('falls back to local defaults when no external data source is configured', async () => {+ const service = new ThreadCommentDataSourceService();+ const comment = createComment({ threadId: undefined });++ await expect(service.addComment({ ...comment, threadId: undefined as unknown as string })).resolves.toEqual({+ ...comment,+ threadId: comment.id,+ });+ await expect(service.updateComment(comment)).resolves.toBe(true);+ await expect(service.resolveComment(comment)).resolves.toBe(true);+ await expect(service.deleteComment('unit-1', 'sheet-1', 'thread-1', 'comment-1')).resolves.toBe(true);+ await expect(service.getThreadComment('unit-1', 'sheet-1', 'thread-1')).resolves.toBeNull();+ await expect(service.listThreadComments('unit-1', 'sheet-1', ['thread-1'])).resolves.toBe(false);++ const snapshot = service.saveToSnapshot({+ 'sheet-1': [comment],+ }, 'unit-1');++ expect(snapshot).toEqual({+ 'sheet-1': [comment],+ });+ });++ it('delegates CRUD, query and snapshot behavior to the configured data source', async () => {+ const service = new ThreadCommentDataSourceService();+ const comment = createComment({ id: 'root-1' });++ const dataSource = {+ addComment: vi.fn(async (input: IThreadComment) => ({ ...input, threadId: 'server-thread' })),+ updateComment: vi.fn(async () => false),+ resolveComment: vi.fn(async () => false),+ deleteComment: vi.fn(async () => false),+ listComments: vi.fn(async () => [{+ ...comment,+ children: [createComment({ id: 'reply-1', parentId: 'root-1', threadId: 'root-1', ref: '' })],+ }]),+ saveCommentToSnapshot: vi.fn((input: IThreadComment) => ({+ id: input.id,+ threadId: input.threadId,+ ref: input.ref,+ personId: input.personId,+ })),+ };+ service.dataSource = dataSource;++ await expect(service.addComment(comment)).resolves.toEqual({+ ...comment,+ threadId: 'server-thread',+ });+ await expect(service.updateComment(comment)).resolves.toBe(false);+ await expect(service.resolveComment(comment)).resolves.toBe(false);+ await expect(service.deleteComment('unit-1', 'sheet-1', 'root-1', 'root-1')).resolves.toBe(false);+ await expect(service.getThreadComment('unit-1', 'sheet-1', 'root-1')).resolves.toEqual({+ ...comment,+ children: [createComment({ id: 'reply-1', parentId: 'root-1', threadId: 'root-1', ref: '' })],+ });+ await expect(service.listThreadComments('unit-1', 'sheet-1', ['root-1'])).resolves.toEqual([+ {+ ...comment,+ children: [createComment({ id: 'reply-1', parentId: 'root-1', threadId: 'root-1', ref: '' })],+ },+ ]);+ expect(service.saveToSnapshot({+ 'sheet-1': [comment],+ }, 'unit-1')).toEqual({+ 'sheet-1': [+ {+ id: 'root-1',+ threadId: 'root-1',+ ref: 'A1',+ personId: 'user-1',+ },+ ],+ });++ expect(dataSource.listComments).toHaveBeenNthCalledWith(1, 'unit-1', 'sheet-1', ['root-1']);+ expect(dataSource.listComments).toHaveBeenNthCalledWith(2, 'unit-1', 'sheet-1', ['root-1']);+ expect(dataSource.saveCommentToSnapshot).toHaveBeenCalledWith(comment, 0, [comment]);+ });+});diff --git a/packages/ui-adapter-vue3/src/plugin.ts b/packages/ui-adapter-vue3/src/plugin.tsindex 5af2457957..73dcf63222 100644--- a/packages/ui-adapter-vue3/src/plugin.ts+++ b/packages/ui-adapter-vue3/src/plugin.ts@@ -42,9 +42,9 @@ export class UniverVue3AdapterPlugin extends Plugin {const { createElement, useEffect, useRef } = this._componentManager.reactUtils;this._componentManager.setHandler('vue3', (component: IComponent['component']) => {- return (props: Record<string, any>) => createElement(VueComponentWrapper, {+ return (props: Record<string, unknown>) => createElement(VueComponentWrapper, {component,- props: Object.keys(props).reduce<Record<string, any>>((acc, key) => {+ props: Object.keys(props).reduce<Record<string, unknown>>((acc, key) => {if (key !== 'key') {acc[key] = props[key];}@@ -58,7 +58,7 @@ export class UniverVue3AdapterPlugin extends Plugin {export function VueComponentWrapper(options: {component: ReturnType<typeof defineComponent>;- props: Record<string, any>;+ props: Record<string, unknown>;reactUtils: typeof ComponentManager.prototype.reactUtils;}) {const { component, props, reactUtils } = options;diff --git a/packages/ui-adapter-web-component/src/plugin.ts b/packages/ui-adapter-web-component/src/plugin.tsindex dd237d0615..d7c6a5d9bf 100644--- a/packages/ui-adapter-web-component/src/plugin.ts+++ b/packages/ui-adapter-web-component/src/plugin.ts@@ -53,7 +53,9 @@ export class UniverWebComponentAdapterPlugin extends Plugin {export function WebComponentComponentWrapper(options: {component: CustomElementConstructor;- props?: Record<string, any>;+ props?: {+ name?: string;+ };reactUtils: typeof ComponentManager.prototype.reactUtils;}) {const { component, props, reactUtils } = options;diff --git a/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.ts b/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.tsnew file mode 100644index 0000000000..d225194079--- /dev/null+++ b/packages/ui/src/commands/operations/__tests__/toggle-shortcut-panel.operation.spec.ts@@ -0,0 +1,66 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { ShortcutPanelService } from '../../../services/shortcut/shortcut-panel.service';+import { ISidebarService } from '../../../services/sidebar/sidebar.service';+import { ShortcutPanelComponentName, ToggleShortcutPanelOperation } from '../toggle-shortcut-panel.operation';++function createAccessor(isOpen: boolean) {+ const shortcutPanelService = {+ isOpen,+ open: vi.fn(),+ close: vi.fn(),+ } as unknown as ShortcutPanelService;++ const sidebarService = {+ open: vi.fn(),+ close: vi.fn(),+ };++ const accessor = {+ get: (token: unknown) => {+ if (token === ShortcutPanelService) return shortcutPanelService;+ if (token === ISidebarService) return sidebarService;+ throw new Error('Unknown token');+ },+ } as unknown as IAccessor;++ return { accessor, shortcutPanelService, sidebarService };+}++describe('ToggleShortcutPanelOperation', () => {+ it('should close shortcut panel and sidebar when panel is open', () => {+ const { accessor, shortcutPanelService, sidebarService } = createAccessor(true);++ expect(ToggleShortcutPanelOperation.handler!(accessor, {})).toBe(true);+ expect(shortcutPanelService.close).toHaveBeenCalledOnce();+ expect(sidebarService.close).toHaveBeenCalledOnce();+ expect(sidebarService.open).not.toHaveBeenCalled();+ });++ it('should open shortcut panel and sidebar when panel is closed', () => {+ const { accessor, shortcutPanelService, sidebarService } = createAccessor(false);++ expect(ToggleShortcutPanelOperation.handler!(accessor, {})).toBe(true);+ expect(shortcutPanelService.open).toHaveBeenCalledOnce();+ expect(sidebarService.open).toHaveBeenCalledWith({+ header: { title: 'shortcut-panel.title' },+ children: { label: ShortcutPanelComponentName },+ });+ });+});diff --git a/packages/ui/src/common/__tests__/component-manager.spec.ts b/packages/ui/src/common/__tests__/component-manager.spec.tsnew file mode 100644index 0000000000..5352fa570d--- /dev/null+++ b/packages/ui/src/common/__tests__/component-manager.spec.ts@@ -0,0 +1,107 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { ComponentManager } from '../component-manager';++describe('ComponentManager', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should expose built-in icons, react utils and clear built-ins on dispose', () => {+ const manager = new ComponentManager();++ const iconComp = manager.get('ShortcutIcon');+ expect(iconComp).toBeDefined();+ expect(manager.reactUtils.createElement).toBeTypeOf('function');+ expect(manager.reactUtils.useEffect).toBeTypeOf('function');+ expect(manager.reactUtils.useRef).toBeTypeOf('function');++ manager.dispose();+ expect(manager.get('ShortcutIcon')).toBeUndefined();+ });++ it('should register default react component and support get/getKey/delete/disposable', () => {+ const manager = new ComponentManager();+ const Comp = () => null;++ const disposable = manager.register('test-comp', Comp);++ expect(manager.get('test-comp')).toBe(Comp);+ expect(manager.getKey(Comp)).toBe('test-comp');++ manager.delete('test-comp');+ expect(manager.get('test-comp')).toBeUndefined();++ manager.register('test-comp', Comp);+ disposable.dispose();+ expect(manager.get('test-comp')).toBeUndefined();++ manager.dispose();+ });++ it('should warn when register duplicate name', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const manager = new ComponentManager();+ const Comp = () => null;++ manager.register('dup-comp', Comp);+ manager.register('dup-comp', Comp);++ expect(warn).toHaveBeenCalledWith('Component dup-comp already exists.');++ manager.dispose();+ });++ it('should throw when registering vue3 without handler', () => {+ const manager = new ComponentManager();++ expect(() => manager.register('vue-comp', () => null, { framework: 'vue3' })).toThrow(+ '[ComponentManager] Vue3 support is no longer built-in since v0.9.0, please install @univerjs/ui-adapter-vue3 plugin.'+ );++ manager.dispose();+ });++ it('should use custom framework handler and throw when handler missing at get', () => {+ const manager = new ComponentManager();+ const CustomComp = () => null;++ manager.setHandler('custom', (component, name) => ({+ component,+ name,+ wrapped: true,+ }));++ manager.register('custom-comp', CustomComp, { framework: 'custom' });+ expect(manager.get('custom-comp')).toEqual({+ component: CustomComp,+ name: 'custom-comp',+ wrapped: true,+ });++ manager.register('unknown-framework-comp', CustomComp, { framework: 'unknown' });+ expect(() => manager.get('unknown-framework-comp')).toThrow(+ '[ComponentManager] No handler found for framework: unknown'+ );++ expect(manager.get('')).toBeUndefined();+ expect(manager.get('not-exists')).toBeUndefined();++ manager.dispose();+ });+});diff --git a/packages/ui/src/common/__tests__/lifecycle.spec.ts b/packages/ui/src/common/__tests__/lifecycle.spec.tsnew file mode 100644index 0000000000..44a5d63480--- /dev/null+++ b/packages/ui/src/common/__tests__/lifecycle.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { fromEvent, fromGlobalEvent } from '../lifecycle';++describe('lifecycle helpers', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should register and dispose global event listener', () => {+ const addSpy = vi.spyOn(window, 'addEventListener');+ const removeSpy = vi.spyOn(window, 'removeEventListener');+ const listener = vi.fn();++ const disposable = fromGlobalEvent('click', listener);++ expect(addSpy).toHaveBeenCalledWith('click', listener, undefined);++ disposable.dispose();+ expect(removeSpy).toHaveBeenCalledWith('click', listener, undefined);+ });++ it('should register and dispose element event listener', () => {+ const button = document.createElement('button');+ const addSpy = vi.spyOn(button, 'addEventListener');+ const removeSpy = vi.spyOn(button, 'removeEventListener');+ const listener = vi.fn();++ const disposable = fromEvent(button, 'click', listener);++ expect(addSpy).toHaveBeenCalledWith('click', listener, undefined);++ disposable.dispose();+ expect(removeSpy).toHaveBeenCalledWith('click', listener, undefined);+ });+});diff --git a/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts b/packages/ui/src/common/__tests__/menu-hidden-observable.spec.tsnew file mode 100644index 0000000000..fda49db7da--- /dev/null+++ b/packages/ui/src/common/__tests__/menu-hidden-observable.spec.ts@@ -0,0 +1,190 @@+/**+ * 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 { IAccessor, UniverInstanceType } from '@univerjs/core';+import { DocumentFlavor } from '@univerjs/core';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { getHeaderFooterMenuHiddenObservable, getMenuHiddenObservable } from '../menu-hidden-observable';++const TARGET_TYPE = 'sheet' as unknown as UniverInstanceType;+const OTHER_TYPE = 'doc' as unknown as UniverInstanceType;++function createDocModel(flavor: DocumentFlavor) {+ return {+ getSnapshot: () => ({+ documentStyle: {+ documentFlavor: flavor,+ },+ }),+ };+}++function createMenuAccessor(options?: {+ focusedUnitId?: string | null;+ unitType?: UniverInstanceType;+ docFlavorByUnitId?: Record<string, DocumentFlavor>;+ currentDocFlavor?: DocumentFlavor | null;+}) {+ const focused$ = new Subject<string | null>();+ const unitType = options?.unitType ?? TARGET_TYPE;+ const hasFocusedUnitId = options != null && Object.prototype.hasOwnProperty.call(options, 'focusedUnitId');+ const focusedUnitId = hasFocusedUnitId ? options.focusedUnitId! : 'unit-1';+ const docFlavorByUnitId = options?.docFlavorByUnitId ?? {};+ const hasCurrentDocFlavor = options != null && Object.prototype.hasOwnProperty.call(options, 'currentDocFlavor');+ const currentDocFlavor = hasCurrentDocFlavor ? options.currentDocFlavor! : null;++ const service = {+ focused$,+ getUnitType: vi.fn(() => unitType),+ getFocusedUnit: vi.fn(() => (focusedUnitId == null ? null : { getUnitId: () => focusedUnitId })),+ getUniverDocInstance: vi.fn((unitId: string) => {+ const flavor = docFlavorByUnitId[unitId];+ return flavor == null ? null : createDocModel(flavor);+ }),+ getCurrentUniverDocInstance: vi.fn(() => {+ if (currentDocFlavor == null) {+ return null;+ }+ return createDocModel(currentDocFlavor);+ }),+ };++ const accessor = {+ get: () => service,+ } as unknown as IAccessor;++ return { accessor, service };+}++describe('getMenuHiddenObservable', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should emit true when there is no focused unit initially', () => {+ const { accessor } = createMenuAccessor({ focusedUnitId: null });+ const hiddenValues: boolean[] = [];+ const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));++ expect(hiddenValues).toEqual([true]);+ sub.unsubscribe();+ });++ it('should emit false when focused unit type matches target type', () => {+ const { accessor } = createMenuAccessor({ unitType: TARGET_TYPE });+ const hiddenValues: boolean[] = [];+ const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));++ expect(hiddenValues).toEqual([false]);+ sub.unsubscribe();+ });++ it('should emit true when focused unit type does not match target type', () => {+ const { accessor } = createMenuAccessor({ unitType: OTHER_TYPE });+ const hiddenValues: boolean[] = [];+ const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));++ expect(hiddenValues).toEqual([true]);+ sub.unsubscribe();+ });++ it('should hide when focused unit does not match matchUnitId', () => {+ const { accessor, service } = createMenuAccessor({ focusedUnitId: 'expected-unit' });+ const hiddenValues: boolean[] = [];+ const sub = getMenuHiddenObservable(accessor, TARGET_TYPE, 'expected-unit').subscribe((hidden) => hiddenValues.push(hidden));++ service.focused$.next('other-unit');++ expect(hiddenValues).toEqual([false, true]);+ sub.unsubscribe();+ });++ it('should hide when needHideUnitId matches current unit (string and array)', () => {+ const { accessor, service } = createMenuAccessor({ focusedUnitId: 'unit-1' });+ const hiddenWithString: boolean[] = [];+ const hiddenWithArray: boolean[] = [];++ const sub1 = getMenuHiddenObservable(accessor, TARGET_TYPE, undefined, 'blocked-unit').subscribe((hidden) =>+ hiddenWithString.push(hidden)+ );+ const sub2 = getMenuHiddenObservable(accessor, TARGET_TYPE, undefined, ['blocked-unit']).subscribe((hidden) =>+ hiddenWithArray.push(hidden)+ );++ service.focused$.next('blocked-unit');++ expect(hiddenWithString).toEqual([false, true]);+ expect(hiddenWithArray).toEqual([false, true]);++ sub1.unsubscribe();+ sub2.unsubscribe();+ });++ it('should hide when focused$ emits null unit id', () => {+ const { accessor, service } = createMenuAccessor({ focusedUnitId: 'unit-1' });+ const hiddenValues: boolean[] = [];+ const sub = getMenuHiddenObservable(accessor, TARGET_TYPE).subscribe((hidden) => hiddenValues.push(hidden));++ service.focused$.next(null);++ expect(hiddenValues).toEqual([false, true]);+ sub.unsubscribe();+ });+});++describe('getHeaderFooterMenuHiddenObservable', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should emit true when current doc instance is missing', () => {+ const { accessor } = createMenuAccessor({ currentDocFlavor: null });+ const hiddenValues: boolean[] = [];+ const sub = getHeaderFooterMenuHiddenObservable(accessor).subscribe((hidden) => hiddenValues.push(hidden));++ expect(hiddenValues).toEqual([true]);+ sub.unsubscribe();+ });++ it('should emit false when current document flavor is traditional', () => {+ const { accessor } = createMenuAccessor({ currentDocFlavor: DocumentFlavor.TRADITIONAL });+ const hiddenValues: boolean[] = [];+ const sub = getHeaderFooterMenuHiddenObservable(accessor).subscribe((hidden) => hiddenValues.push(hidden));++ expect(hiddenValues).toEqual([false]);+ sub.unsubscribe();+ });++ it('should react to focused unit changes based on document flavor', () => {+ const { accessor, service } = createMenuAccessor({+ currentDocFlavor: DocumentFlavor.TRADITIONAL,+ docFlavorByUnitId: {+ modernDoc: DocumentFlavor.MODERN,+ traditionalDoc: DocumentFlavor.TRADITIONAL,+ },+ });+ const hiddenValues: boolean[] = [];+ const sub = getHeaderFooterMenuHiddenObservable(accessor).subscribe((hidden) => hiddenValues.push(hidden));++ service.focused$.next('modernDoc');+ service.focused$.next('traditionalDoc');+ service.focused$.next(null);++ expect(hiddenValues).toEqual([false, true, false, true]);+ sub.unsubscribe();+ });+});diff --git a/packages/ui/src/common/__tests__/menu-merge-configs.spec.ts b/packages/ui/src/common/__tests__/menu-merge-configs.spec.tsnew file mode 100644index 0000000000..62816f085d--- /dev/null+++ b/packages/ui/src/common/__tests__/menu-merge-configs.spec.ts@@ -0,0 +1,92 @@+/**+ * 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 { Observable } from 'rxjs';+import type { MenuItemConfig } from '../../services/menu/menu';+import { firstValueFrom, of } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { mergeMenuConfigs } from '../menu-merge-configs';++type MenuItemConfigWithReactiveState = MenuItemConfig & {+ hidden$?: Observable<boolean>;+ disabled$?: Observable<boolean>;+ activated$?: Observable<boolean>;+};++describe('mergeMenuConfigs', () => {+ it('should return base config when additional config is null', () => {+ const base = { title: 'Base title' };++ expect(mergeMenuConfigs(base, null)).toBe(base);+ });++ it('should return base config when base config is falsy', () => {+ expect(mergeMenuConfigs(null as unknown as MenuItemConfig, { title: 'New title' })).toBeNull();+ });++ it('should merge plain properties and ignore undefined values', () => {+ const base = {+ type: 1,+ icon: 'old-icon',+ title: 'old-title',+ tooltip: 'old-tooltip',+ } as unknown as MenuItemConfig;++ const additional = {+ title: 'new-title',+ tooltip: 'new-tooltip',+ icon: undefined,+ } as unknown as MenuItemConfig;++ const merged = mergeMenuConfigs(base, additional);++ expect(merged.title).toBe('new-title');+ expect(merged.tooltip).toBe('new-tooltip');+ expect(merged.icon).toBe('old-icon');+ });++ it('should create reactive observables when base config has no reactive properties', async () => {+ const base = {} as MenuItemConfigWithReactiveState;++ const merged = mergeMenuConfigs<MenuItemConfigWithReactiveState>(base, {+ hidden: true,+ disabled: false,+ activated: true,+ });++ await expect(firstValueFrom(merged.hidden$!)).resolves.toBe(true);+ await expect(firstValueFrom(merged.disabled$!)).resolves.toBe(false);+ await expect(firstValueFrom(merged.activated$!)).resolves.toBe(true);+ });++ it('should replace values from existing reactive observables', async () => {+ const base = {+ hidden$: of(false),+ disabled$: of(true),+ activated$: of(false),+ } as MenuItemConfigWithReactiveState;++ const merged = mergeMenuConfigs<MenuItemConfigWithReactiveState>(base, {+ hidden: true,+ disabled: false,+ activated: true,+ });++ await expect(firstValueFrom(merged.hidden$!)).resolves.toBe(true);+ await expect(firstValueFrom(merged.disabled$!)).resolves.toBe(false);+ await expect(firstValueFrom(merged.activated$!)).resolves.toBe(true);+ });+});diff --git a/packages/ui/src/common/__tests__/z-index-manager.spec.ts b/packages/ui/src/common/__tests__/z-index-manager.spec.tsnew file mode 100644index 0000000000..1f1a45ad40--- /dev/null+++ b/packages/ui/src/common/__tests__/z-index-manager.spec.ts@@ -0,0 +1,46 @@+/**+ * 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 { ZIndexManager } from '../z-index-manager';++describe('ZIndexManager', () => {+ it('should set, get and remove index values', () => {+ const manager = new ZIndexManager();++ manager.setIndex('dialog', 1000);+ expect(manager.getIndex('dialog')).toBe(1000);++ manager.removeIndex('dialog');+ expect(manager.getIndex('dialog')).toBeUndefined();+ });++ it('should return maximum index from all values', () => {+ const manager = new ZIndexManager();++ manager.setIndex('dialog', 2000);+ manager.setIndex('sidebar', 1500);+ manager.setIndex('tooltip', 9999);++ expect(manager.getMaxIndex()).toBe(9999);+ });++ it('should return default minimum when no index exists', () => {+ const manager = new ZIndexManager();++ expect(manager.getMaxIndex()).toBe(-9999999);+ });+});diff --git a/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts b/packages/ui/src/controllers/__tests__/misc-controllers.spec.tsnew file mode 100644index 0000000000..17a069aa5e--- /dev/null+++ b/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts@@ -0,0 +1,103 @@+/**+ * 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 { Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { ToggleShortcutPanelOperation } from '../../commands/operations/toggle-shortcut-panel.operation';+import { RibbonStartGroup } from '../../services/menu/types';+import { ErrorController } from '../error/error.controller';+import { menuSchema } from '../menus/menu.schema';+import { ShortcutPanelMenuItemFactory } from '../shortcut-display/menu';+import { ShortcutPanelController } from '../shortcut-display/shortcut-panel.controller';+import { IUIController } from '../ui/ui.controller';++describe('ErrorController', () => {+ it('should forward errors to message service', () => {+ const error$ = new Subject<{ errorKey: string }>();+ const errorService = {+ error$,+ };+ const messageService = {+ show: vi.fn(),+ };++ const controller = new ErrorController(errorService as any, messageService as any);+ error$.next({ errorKey: 'boom' });++ expect(messageService.show).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'boom',+ })+ );++ controller.dispose();+ });+});++describe('shortcut-display controllers', () => {+ it('should return shortcut panel menu item', () => {+ expect(ShortcutPanelMenuItemFactory()).toEqual({+ id: ToggleShortcutPanelOperation.id,+ title: 'toggle-shortcut-panel',+ tooltip: 'toggle-shortcut-panel',+ icon: 'ShortcutIcon',+ type: 0,+ });+ });++ it('should register panel component, command and shortcut', () => {+ const componentManager = {+ register: vi.fn(() => ({ dispose: vi.fn() })),+ };+ const shortcutService = {+ registerShortcut: vi.fn(() => ({ dispose: vi.fn() })),+ };+ const commandService = {+ registerCommand: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const controller = new ShortcutPanelController(+ {} as any,+ componentManager as any,+ shortcutService as any,+ {} as any,+ commandService as any+ );++ expect(componentManager.register).toHaveBeenCalledTimes(1);+ expect(commandService.registerCommand).toHaveBeenCalledWith(ToggleShortcutPanelOperation);+ expect(shortcutService.registerShortcut).toHaveBeenCalledTimes(1);++ controller.dispose();+ });+});++describe('menu schema and ui token', () => {+ it('should expose static menu schema entries', () => {+ const groupedSchema = menuSchema as Record<RibbonStartGroup.HISTORY | RibbonStartGroup.OTHERS, Record<string, unknown>>;+ const history = groupedSchema[RibbonStartGroup.HISTORY];+ const others = groupedSchema[RibbonStartGroup.OTHERS];++ expect(history).toBeDefined();+ expect(others).toBeDefined();+ expect(Object.keys(history).length).toBeGreaterThanOrEqual(2);+ expect(Object.keys(others).length).toBeGreaterThanOrEqual(1);+ });++ it('should expose ui controller identifier', () => {+ expect(IUIController).toBeDefined();+ });+});diff --git a/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.ts b/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.tsnew file mode 100644index 0000000000..a7e4decacd--- /dev/null+++ b/packages/ui/src/controllers/__tests__/shared-shortcut.controller.spec.ts@@ -0,0 +1,90 @@+/**+ * 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 { IContextService } from '@univerjs/core';+import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, FOCUSING_UNIVER_EDITOR } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import {+ CopyShortcutItem,+ CutShortcutItem,+ OnlyDisplayPasteShortcutItem,+ RedoShortcutItem,+ SharedController,+ UndoShortcutItem,+} from '../shared-shortcut.controller';++function createContext(values: Record<string, boolean>): IContextService {+ return {+ getContextValue: (key: string) => values[key] ?? false,+ } as unknown as IContextService;+}++describe('shared shortcut items', () => {+ it('should require editor focus for copy/cut and never trigger display-only paste', () => {+ const focused = createContext({ [FOCUSING_UNIVER_EDITOR]: true });+ const notFocused = createContext({ [FOCUSING_UNIVER_EDITOR]: false });++ expect(CopyShortcutItem.preconditions!(focused)).toBe(true);+ expect(CopyShortcutItem.preconditions!(notFocused)).toBe(false);+ expect(CutShortcutItem.preconditions!(focused)).toBe(true);+ expect(CutShortcutItem.preconditions!(notFocused)).toBe(false);+ expect(OnlyDisplayPasteShortcutItem.preconditions!(focused)).toBe(false);+ });++ it('should block undo/redo when editor or fx bar is activated', () => {+ const allowed = createContext({+ [FOCUSING_UNIVER_EDITOR]: true,+ [EDITOR_ACTIVATED]: false,+ [FOCUSING_FX_BAR_EDITOR]: false,+ });+ const blockedByEditor = createContext({+ [FOCUSING_UNIVER_EDITOR]: true,+ [EDITOR_ACTIVATED]: true,+ [FOCUSING_FX_BAR_EDITOR]: false,+ });+ const blockedByFxBar = createContext({+ [FOCUSING_UNIVER_EDITOR]: true,+ [EDITOR_ACTIVATED]: false,+ [FOCUSING_FX_BAR_EDITOR]: true,+ });++ expect(UndoShortcutItem.preconditions!(allowed)).toBe(true);+ expect(RedoShortcutItem.preconditions!(allowed)).toBe(true);+ expect(UndoShortcutItem.preconditions!(blockedByEditor)).toBe(false);+ expect(RedoShortcutItem.preconditions!(blockedByFxBar)).toBe(false);+ });+});++describe('SharedController', () => {+ it('should register clipboard commands and shared shortcuts on initialize', () => {+ const registerMultipleCommand = vi.fn(() => ({ dispose: vi.fn() }));+ const registerShortcut = vi.fn(() => ({ dispose: vi.fn() }));++ const commandService = {+ registerMultipleCommand,+ };+ const shortcutService = {+ registerShortcut,+ };++ const controller = new SharedController(shortcutService as any, commandService as any);++ expect(registerMultipleCommand).toHaveBeenCalledTimes(3);+ expect(registerShortcut).toHaveBeenCalledTimes(5);++ controller.dispose();+ });+});diff --git a/packages/ui/src/controllers/menus/__tests__/menus.spec.ts b/packages/ui/src/controllers/menus/__tests__/menus.spec.tsnew file mode 100644index 0000000000..6ad1874099--- /dev/null+++ b/packages/ui/src/controllers/menus/__tests__/menus.spec.ts@@ -0,0 +1,97 @@+/**+ * 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 { IAccessor } from '@univerjs/core';+import { EDITOR_ACTIVATED, FOCUSING_FX_BAR_EDITOR, IContextService, IUndoRedoService } from '@univerjs/core';+import { BehaviorSubject, Subject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { RedoMenuItemFactory, UndoMenuItemFactory } from '../menus';++function createAccessor() {+ const undoRedoStatus$ = new BehaviorSubject({ undos: 1, redos: 1 });+ const contextChanged$ = new Subject<void>();+ const contextStore: Record<string, boolean> = {+ [EDITOR_ACTIVATED]: false,+ [FOCUSING_FX_BAR_EDITOR]: false,+ };++ const undoRedoService = { undoRedoStatus$ };+ const contextService = {+ contextChanged$,+ getContextValue: (key: string) => contextStore[key] ?? false,+ };++ const accessor = {+ get: (token: unknown) => {+ if (token === IUndoRedoService) return undoRedoService;+ if (token === IContextService) return contextService;+ throw new Error('Unknown token');+ },+ } as unknown as IAccessor;++ return { accessor, undoRedoStatus$, contextChanged$, contextStore };+}++describe('menus controller factories', () => {+ it('should toggle undo disabled state by status and editor context', () => {+ const { accessor, undoRedoStatus$, contextChanged$, contextStore } = createAccessor();+ const item = UndoMenuItemFactory(accessor);+ const values: boolean[] = [];+ const sub = item.disabled$!.subscribe((v) => values.push(v));++ expect(values.at(-1)).toBe(false);++ undoRedoStatus$.next({ undos: 0, redos: 1 });+ expect(values.at(-1)).toBe(true);++ contextStore[EDITOR_ACTIVATED] = true;+ contextChanged$.next();+ undoRedoStatus$.next({ undos: 2, redos: 1 });+ expect(values.at(-1)).toBe(true);++ contextStore[EDITOR_ACTIVATED] = false;+ contextStore[FOCUSING_FX_BAR_EDITOR] = false;+ contextChanged$.next();+ undoRedoStatus$.next({ undos: 3, redos: 1 });+ expect(values.at(-1)).toBe(false);++ sub.unsubscribe();+ });++ it('should toggle redo disabled state by status and fx bar context', () => {+ const { accessor, undoRedoStatus$, contextChanged$, contextStore } = createAccessor();+ const item = RedoMenuItemFactory(accessor);+ const values: boolean[] = [];+ const sub = item.disabled$!.subscribe((v) => values.push(v));++ expect(values.at(-1)).toBe(false);++ undoRedoStatus$.next({ undos: 1, redos: 0 });+ expect(values.at(-1)).toBe(true);++ contextStore[FOCUSING_FX_BAR_EDITOR] = true;+ contextChanged$.next();+ undoRedoStatus$.next({ undos: 1, redos: 3 });+ expect(values.at(-1)).toBe(true);++ contextStore[FOCUSING_FX_BAR_EDITOR] = false;+ contextChanged$.next();+ undoRedoStatus$.next({ undos: 1, redos: 4 });+ expect(values.at(-1)).toBe(false);++ sub.unsubscribe();+ });+});diff --git a/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx b/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsxnew file mode 100644index 0000000000..d55a29d8d6--- /dev/null+++ b/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx@@ -0,0 +1,285 @@+/**+ * 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 { LifecycleStages } from '@univerjs/core';+import { render, unmount } from '@univerjs/design';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopUIController } from '../ui-desktop.controller';+import { MobileUIController } from '../ui-mobile.controller';++vi.mock('../../../utils/di', () => ({+ connectInjector: vi.fn((Comp: any) => Comp),+}));++vi.mock('@univerjs/design', async (importOriginal) => {+ const actual = await importOriginal<any>();+ return {+ ...actual,+ ColorPicker: () => null,+ render: vi.fn((element, _container) => {+ element.props?.onRendered?.(document.createElement('div'));+ }),+ unmount: vi.fn(),+ };+});++function createCommonDeps() {+ return {+ injector: {},+ lifecycleService: {+ onStage: vi.fn().mockResolvedValue(undefined),+ stage: LifecycleStages.Starting,+ },+ renderManagerService: {+ getRenderAll: vi.fn(() => new Map()),+ getRenderById: vi.fn(() => null),+ created$: new Subject<any>(),+ disposed$: new Subject<string>(),+ },+ layoutService: {+ registerRootContainerElement: vi.fn(() => ({ dispose: vi.fn() })),+ registerContentElement: vi.fn(() => ({ dispose: vi.fn() })),+ },+ instanceService: {+ focused$: new Subject<string>(),+ getFocusedUnit: vi.fn(() => null),+ },+ };+}++describe('DesktopUIController', () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('should bootstrap with existing container id and dispose resources', () => {+ vi.useFakeTimers();+ vi.mocked(render).mockClear();+ vi.mocked(unmount).mockClear();++ const deps = createCommonDeps();+ const container = document.createElement('div');+ container.id = 'existing-container';+ document.body.appendChild(container);++ const menuManagerService = {+ mergeMenu: vi.fn(),+ };+ const uiPartsService = {+ registerComponent: vi.fn(() => ({ dispose: vi.fn() })),+ };+ const componentManager = {+ register: vi.fn(() => ({ dispose: vi.fn() })),+ dispose: vi.fn(),+ };++ const controller = new DesktopUIController(+ { container: 'existing-container' } as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ menuManagerService as any,+ uiPartsService as any,+ componentManager as any+ );++ vi.advanceTimersByTime(3300);++ expect(menuManagerService.mergeMenu).toHaveBeenCalledTimes(1);+ expect(uiPartsService.registerComponent).toHaveBeenCalledTimes(3);+ expect(componentManager.register).toHaveBeenCalledTimes(6);+ expect(render).toHaveBeenCalledWith(expect.any(Object), container);++ controller.dispose();+ expect(unmount).toHaveBeenCalledWith(container);+ expect(componentManager.dispose).toHaveBeenCalledTimes(1);+ });++ it('should create container when id is missing and when no container is provided', () => {+ vi.useFakeTimers();+ vi.mocked(render).mockClear();+ vi.mocked(unmount).mockClear();++ const deps = createCommonDeps();+ const menuManagerService = { mergeMenu: vi.fn() };+ const uiPartsService = { registerComponent: vi.fn(() => ({ dispose: vi.fn() })) };+ const componentManager = { register: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn() };++ const withMissingId = new DesktopUIController(+ { container: 'missing-container' } as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ menuManagerService as any,+ uiPartsService as any,+ componentManager as any+ );++ const withDefault = new DesktopUIController(+ {} as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ menuManagerService as any,+ uiPartsService as any,+ componentManager as any+ );++ vi.advanceTimersByTime(3300);++ const mountContainers = vi.mocked(render).mock.calls.map(([, container]) => container);+ expect(mountContainers).toEqual([+ expect.objectContaining({ id: 'missing-container' }),+ expect.objectContaining({ id: 'univer' }),+ ]);++ withMissingId.dispose();+ withDefault.dispose();+ });++ it('should use HTMLElement container directly', () => {+ vi.useFakeTimers();+ vi.mocked(render).mockClear();+ vi.mocked(unmount).mockClear();++ const deps = createCommonDeps();+ const mountContainer = document.createElement('div');+ const menuManagerService = { mergeMenu: vi.fn() };+ const uiPartsService = { registerComponent: vi.fn(() => ({ dispose: vi.fn() })) };+ const componentManager = { register: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn() };++ const controller = new DesktopUIController(+ { container: mountContainer } as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ menuManagerService as any,+ uiPartsService as any,+ componentManager as any+ );++ vi.advanceTimersByTime(3300);+ expect(render).toHaveBeenCalledWith(expect.any(Object), mountContainer);++ controller.dispose();+ expect(unmount).toHaveBeenCalledWith(mountContainer);+ });+});++describe('MobileUIController', () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('should bootstrap and register mobile ui parts', () => {+ vi.useFakeTimers();+ vi.mocked(render).mockClear();+ vi.mocked(unmount).mockClear();++ const deps = createCommonDeps();+ const uiPartsService = {+ registerComponent: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const controller = new MobileUIController(+ { container: 'missing-mobile' } as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ uiPartsService as any+ );++ vi.advanceTimersByTime(3300);++ expect(uiPartsService.registerComponent).toHaveBeenCalledTimes(2);+ expect(render).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({ id: 'missing-mobile' }));++ controller.dispose();+ expect(unmount).toHaveBeenCalled();+ });++ it('should support existing id, html container and default container', () => {+ vi.useFakeTimers();+ vi.mocked(render).mockClear();+ vi.mocked(unmount).mockClear();++ const deps = createCommonDeps();+ const existing = document.createElement('div');+ existing.id = 'mobile-existing';+ document.body.appendChild(existing);+ const htmlContainer = document.createElement('section');++ const uiPartsService = {+ registerComponent: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const byExistingId = new MobileUIController(+ { container: 'mobile-existing' } as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ uiPartsService as any+ );++ const byElement = new MobileUIController(+ { container: htmlContainer } as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ uiPartsService as any+ );++ const byDefault = new MobileUIController(+ {} as any,+ deps.injector as any,+ deps.lifecycleService as any,+ deps.renderManagerService as any,+ deps.layoutService as any,+ deps.instanceService as any,+ uiPartsService as any+ );++ vi.advanceTimersByTime(3300);++ const mountContainers = vi.mocked(render).mock.calls.map(([, container]) => container);+ expect(mountContainers).toEqual([+ existing,+ htmlContainer,+ expect.objectContaining({ id: 'univer' }),+ ]);++ byExistingId.dispose();+ byElement.dispose();+ byDefault.dispose();+ });+});diff --git a/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts b/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.tsnew file mode 100644index 0000000000..6534fc3c4c--- /dev/null+++ b/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts@@ -0,0 +1,210 @@+/**+ * 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 } from '@univerjs/core';+import { LifecycleStages, LifecycleUnreachableError } from '@univerjs/core';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { SingleUnitUIController } from '../ui-shared.controller';++class TestSingleUnitUIController extends SingleUnitUIController {+ callbackPromise: Promise<void> | null = null;++ constructor(+ injector: any,+ instanceService: any,+ layoutService: any,+ lifecycleService: any,+ renderManagerService: any,+ private readonly _contentElement: HTMLElement,+ private readonly _containerElement: HTMLElement+ ) {+ super(injector, instanceService, layoutService, lifecycleService, renderManagerService);+ }++ runBootstrap() {+ this._bootstrapWorkbench();+ }++ override bootstrap(callback: (contentElement: HTMLElement, containerElement: HTMLElement) => void): IDisposable {+ this.callbackPromise = Promise.resolve(callback(this._contentElement, this._containerElement));+ return {+ dispose: vi.fn(),+ };+ }+}++function createRenderer(unitId: string) {+ return {+ unitId,+ activate: vi.fn(),+ deactivate: vi.fn(),+ engine: {+ mount: vi.fn(),+ unmount: vi.fn(),+ },+ };+}++describe('SingleUnitUIController', () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it('should bootstrap and switch renderers with lifecycle updates', async () => {+ vi.useFakeTimers();++ const layoutService = {+ registerRootContainerElement: vi.fn(() => ({ dispose: vi.fn() })),+ registerContentElement: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const focused$ = new Subject<string>();+ const created$ = new Subject<any>();+ const disposed$ = new Subject<string>();++ const render1 = createRenderer('__INTERNAL_EDITOR__skip');+ const render2 = createRenderer('render-2');+ const render3 = createRenderer('render-3');+ const rendererMap = new Map<string, any>([+ ['render-1', render1],+ ['render-2', render2],+ ['render-3', render3],+ ]);++ const renderManagerService = {+ getRenderAll: vi.fn(() => rendererMap),+ getRenderById: vi.fn((id: string) => rendererMap.get(id)),+ created$,+ disposed$,+ };++ const instanceService = {+ focused$,+ getFocusedUnit: vi.fn(() => ({ getUnitId: () => 'render-3' })),+ };++ const lifecycleService = {+ onStage: vi.fn().mockResolvedValue(undefined),+ stage: LifecycleStages.Starting,+ };++ const controller = new TestSingleUnitUIController(+ {} as any,+ instanceService,+ layoutService,+ lifecycleService,+ renderManagerService,+ document.createElement('div'),+ document.createElement('div')+ );++ controller.runBootstrap();++ await controller.callbackPromise;+ expect(layoutService.registerRootContainerElement).toHaveBeenCalledTimes(1);+ expect(layoutService.registerContentElement).toHaveBeenCalledTimes(1);++ vi.advanceTimersByTime(300);+ expect(render2.engine.mount).toHaveBeenCalledTimes(1);+ expect(render2.activate).toHaveBeenCalledTimes(1);+ expect(lifecycleService.stage).toBe(LifecycleStages.Rendered);++ focused$.next('render-2');+ expect(render2.engine.mount).toHaveBeenCalledTimes(1);++ focused$.next('render-3');+ expect(render2.deactivate).toHaveBeenCalledTimes(1);+ expect(render2.engine.unmount).toHaveBeenCalledTimes(1);+ expect(render3.engine.mount).toHaveBeenCalledTimes(1);++ created$.next({ unitId: 'render-3' });+ expect(render3.engine.mount).toHaveBeenCalledTimes(1);++ disposed$.next('render-3');+ focused$.next('render-3');+ expect(render3.engine.mount).toHaveBeenCalledTimes(2);++ vi.advanceTimersByTime(3000);+ expect(lifecycleService.stage).toBe(LifecycleStages.Steady);++ const clearTimeoutSpy = vi.spyOn(globalThis, 'clearTimeout');+ controller.dispose();+ expect(clearTimeoutSpy).toHaveBeenCalled();+ });++ it('should ignore LifecycleUnreachableError during bootstrap callback', async () => {+ const layoutService = {+ registerRootContainerElement: vi.fn(() => ({ dispose: vi.fn() })),+ registerContentElement: vi.fn(() => ({ dispose: vi.fn() })),+ };++ const controller = new TestSingleUnitUIController(+ {} as any,+ {+ focused$: new Subject<string>(),+ getFocusedUnit: vi.fn(() => null),+ },+ layoutService,+ {+ onStage: vi.fn().mockRejectedValue(new LifecycleUnreachableError(LifecycleStages.Ready)),+ stage: LifecycleStages.Starting,+ },+ {+ getRenderAll: vi.fn(() => new Map()),+ getRenderById: vi.fn(() => null),+ created$: new Subject<any>(),+ disposed$: new Subject<string>(),+ },+ document.createElement('div'),+ document.createElement('div')+ );++ controller.runBootstrap();+ await expect(controller.callbackPromise).resolves.toBeUndefined();+ });++ it('should rethrow non-lifecycle errors from bootstrap callback', async () => {+ const error = new Error('unexpected');+ const controller = new TestSingleUnitUIController(+ {} as any,+ {+ focused$: new Subject<string>(),+ getFocusedUnit: vi.fn(() => null),+ },+ {+ registerRootContainerElement: vi.fn(() => ({ dispose: vi.fn() })),+ registerContentElement: vi.fn(() => ({ dispose: vi.fn() })),+ },+ {+ onStage: vi.fn().mockRejectedValue(error),+ stage: LifecycleStages.Starting,+ },+ {+ getRenderAll: vi.fn(() => new Map()),+ getRenderById: vi.fn(() => null),+ created$: new Subject<any>(),+ disposed$: new Subject<string>(),+ },+ document.createElement('div'),+ document.createElement('div')+ );++ controller.runBootstrap();+ await expect(controller.callbackPromise).rejects.toThrow('unexpected');+ });+});diff --git a/packages/ui/src/services/__tests__/core-services.spec.ts b/packages/ui/src/services/__tests__/core-services.spec.tsnew file mode 100644index 0000000000..38c0679d73--- /dev/null+++ b/packages/ui/src/services/__tests__/core-services.spec.ts@@ -0,0 +1,193 @@+/**+ * 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 { IMenuButtonItem } from '../menu/menu';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { MenuItemType } from '../menu/menu';+import { MenuManagerService } from '../menu/menu-manager.service';+import { RibbonPosition, RibbonStartGroup } from '../menu/types';+import { UIPartsService } from '../parts/parts.service';+import { DesktopRibbonService } from '../ribbon/ribbon.service';++describe('MenuManagerService', () => {+ it('should merge and append menu, then build tree and flat schemas', () => {+ const invoke = vi.fn((factory: any) => factory({}));+ const configService = {+ getConfig: vi.fn(() => ({+ customItem: {+ tooltip: 'tooltip-from-config',+ },+ })),+ };+ const service = new MenuManagerService({ invoke } as any, configService as any);+ const changed = vi.fn();+ service.menuChanged$.subscribe(changed);++ const customFactory = () => ({+ id: 'customItem',+ type: MenuItemType.BUTTON,+ title: 'from-factory',+ tooltip: 'factory-tooltip',+ } as IMenuButtonItem);++ service.mergeMenu({+ [RibbonPosition.START]: {+ [RibbonStartGroup.HISTORY]: {+ customItem: {+ order: 1,+ title: 'history-item',+ menuItemFactory: customFactory,+ },+ },+ },+ });++ service.appendRootMenu({+ customRoot: {+ order: 1,+ testGroup: {+ order: 1,+ customItem: {+ order: 1,+ menuItemFactory: customFactory,+ },+ },+ },+ });++ const historyMenu = service.getMenuByPositionKey(RibbonStartGroup.HISTORY);+ const flatHistory = service.getFlatMenuByPositionKey(RibbonStartGroup.HISTORY);+ const customRoot = service.getMenuByPositionKey('customRoot');+ const mergedCustomItem = flatHistory.find((item) => item.item?.id === 'customItem');++ expect(changed).toHaveBeenCalled();+ expect(invoke).toHaveBeenCalled();+ expect(historyMenu.length).toBeGreaterThan(0);+ expect(flatHistory.length).toBeGreaterThanOrEqual(historyMenu.length);+ expect(mergedCustomItem?.item?.tooltip).toBe('tooltip-from-config');+ expect(customRoot.length).toBe(1);++ const complete = vi.fn();+ service.menuChanged$.subscribe({ complete });+ service.dispose();+ expect(complete).toHaveBeenCalledTimes(1);+ });+});++describe('DesktopRibbonService', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should update states and filter hidden ribbon items', () => {+ const hidden$ = new BehaviorSubject(false);+ let ribbonData: any[] = [+ {+ key: 'group',+ order: 0,+ children: [+ {+ key: 'item',+ order: 0,+ children: [+ {+ key: 'child',+ order: 0,+ item: {+ id: 'id-1',+ type: MenuItemType.BUTTON,+ hidden$,+ },+ },+ ],+ },+ ],+ },+ ];++ const menuChanged$ = new Subject<void>();+ const focused$ = new Subject<any>();+ const menuManagerService = {+ menuChanged$,+ getMenuByPositionKey: vi.fn(() => ribbonData),+ };+ const univerInstanceService = {+ focused$,+ };++ const service = new DesktopRibbonService(menuManagerService as any, univerInstanceService as any);++ let activatedTab = '';+ let collapsedIds: string[] = [];+ let fakeToolbarVisible = false;+ let currentRibbon: any[] = [];++ service.activatedTab$.subscribe((v) => (activatedTab = v));+ service.collapsedIds$.subscribe((v) => (collapsedIds = v));+ service.fakeToolbarVisible$.subscribe((v) => (fakeToolbarVisible = v));+ service.ribbon$.subscribe((v) => (currentRibbon = v));++ service.setActivatedTab(RibbonPosition.INSERT);+ service.setCollapsedIds(['x', 'y']);+ service.setFakeToolbarVisible(true);+ menuChanged$.next();++ expect(activatedTab).toBe(RibbonPosition.INSERT);+ expect(collapsedIds).toEqual(['x', 'y']);+ expect(fakeToolbarVisible).toBe(true);+ expect(currentRibbon.length).toBe(1);++ hidden$.next(true);+ focused$.next('unit');+ expect(currentRibbon).toEqual([]);++ ribbonData = [+ {+ key: 'plain',+ order: 0,+ children: [],+ },+ ];+ menuChanged$.next();+ expect(currentRibbon[0].key).toBe('plain');++ service.dispose();+ });+});++describe('UIPartsService', () => {+ it('should register components and manage visibility', () => {+ const service = new UIPartsService();+ const registered: string[] = [];+ service.componentRegistered$.subscribe((part) => registered.push(part));++ const Comp = () => null;+ const dis = service.registerComponent('toolbar', () => Comp);++ expect(service.getComponents('toolbar').size).toBe(1);++ service.setUIVisible('toolbar', false);+ expect(service.isUIVisible('toolbar')).toBe(false);+ expect(service.isUIVisible('never-set')).toBe(true);++ dis.dispose();+ expect(service.getComponents('toolbar').size).toBe(0);+ expect(registered.length).toBeGreaterThanOrEqual(2);++ service.dispose();+ });+});diff --git a/packages/ui/src/services/__tests__/desktop-services.spec.ts b/packages/ui/src/services/__tests__/desktop-services.spec.tsnew file mode 100644index 0000000000..bae681335a--- /dev/null+++ b/packages/ui/src/services/__tests__/desktop-services.spec.ts@@ -0,0 +1,315 @@+/**+ * 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 { IGalleryProps, IMessageProps } from '@univerjs/design';+import type { IConfirmPartMethodOptions } from '../../views/components/confirm-part/interface';+import type { IDialogPartMethodOptions } from '../../views/components/dialog-part/interface';+import localforage from 'localforage';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopBeforeCloseService } from '../before-close/before-close.service';+import { DesktopConfirmService } from '../confirm/desktop-confirm.service';+import { DesktopDialogService } from '../dialog/desktop-dialog.service';+import { DesktopGalleryService } from '../gallery/desktop-gallery.service';+import { DesktopLocalFileService } from '../local-file/desktop-local-file.service';+import { DesktopLocalStorageService } from '../local-storage/local-storage.service';+import { DesktopMessageService } from '../message/desktop-message.service';+import { DesktopNotificationService } from '../notification/desktop-notification.service';+import { BuiltInUIPart } from '../parts/parts.service';++vi.mock('@univerjs/design', async (importOriginal) => {+ const actual = await importOriginal<any>();+ return {+ ...actual,+ message: vi.fn(),+ removeMessage: vi.fn(),+ };+});++vi.mock('../../components/notification/Notification', () => ({+ Notification: () => null,+ notification: {+ show: vi.fn(),+ },+}));++vi.mock('localforage', () => ({+ default: {+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ clear: vi.fn(),+ key: vi.fn(),+ keys: vi.fn(),+ iterate: vi.fn(),+ },+}));++function createUiPartsService() {+ return {+ registerComponent: vi.fn(() => ({ dispose: vi.fn() })),+ };+}++describe('DesktopConfirmService', () => {+ it('should open, update, close and confirm options', async () => {+ const uiPartsService = createUiPartsService();+ const service = new DesktopConfirmService({} as any, uiPartsService as any);++ expect(uiPartsService.registerComponent).toHaveBeenCalledWith(BuiltInUIPart.GLOBAL, expect.any(Function));++ service.open({ id: 'confirm-1', title: 'A' } as IConfirmPartMethodOptions);+ expect(service.confirmOptions$.getValue()[0].visible).toBe(true);++ service.open({ id: 'confirm-1', title: 'B' } as IConfirmPartMethodOptions);+ expect(service.confirmOptions$.getValue()[0].title).toBe('B');++ service.close('confirm-1');+ expect(service.confirmOptions$.getValue()[0].visible).toBe(false);++ const promiseConfirm = service.confirm({ id: 'confirm-2', title: 'C' } as IConfirmPartMethodOptions);+ service.confirmOptions$.getValue().find((item) => item.id === 'confirm-2')?.onConfirm?.();+ await expect(promiseConfirm).resolves.toBe(true);++ const promiseClose = service.confirm({ id: 'confirm-3', title: 'D' } as IConfirmPartMethodOptions);+ service.confirmOptions$.getValue().find((item) => item.id === 'confirm-3')?.onClose?.();+ await expect(promiseClose).resolves.toBe(false);++ service.dispose();+ });+});++describe('DesktopDialogService', () => {+ it('should manage dialog lifecycle and streams', () => {+ const uiPartsService = createUiPartsService();+ const service = new DesktopDialogService({} as any, uiPartsService as any);++ const emitted: IDialogPartMethodOptions[][] = [];+ const complete = vi.fn();+ service.getDialogs$().subscribe({+ next: (v) => emitted.push(v),+ complete,+ });++ service.open({ id: 'dialog-1', title: 'A' } as IDialogPartMethodOptions);+ service.open({ id: 'dialog-1', title: 'B' } as IDialogPartMethodOptions);+ expect(emitted.at(-1)?.[0].open).toBe(true);+ expect(emitted.at(-1)?.[0].title).toBe('B');++ service.close('dialog-1');+ expect(emitted.at(-1)?.[0].open).toBe(false);++ service.open({ id: 'dialog-2', title: 'C' } as IDialogPartMethodOptions);+ service.closeAll(['dialog-2']);+ expect(emitted.at(-1)?.find((item) => item.id === 'dialog-2')?.open).toBe(true);++ service.closeAll();+ expect(emitted.at(-1)?.every((item) => item.open === false)).toBe(true);++ service.dispose();+ expect(complete).toHaveBeenCalledTimes(1);+ });+});++describe('DesktopMessageService', async () => {+ const { message, removeMessage } = await import('@univerjs/design');++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should show and remove messages', () => {+ vi.spyOn(Date, 'now').mockReturnValue(123);+ const uiPartsService = createUiPartsService();+ const service = new DesktopMessageService({} as any, uiPartsService as any);++ const disposable = service.show({ content: 'hello' } as IMessageProps);+ expect(message).toHaveBeenCalledWith(expect.objectContaining({ id: expect.stringContaining('message-123-') }));++ disposable.dispose();+ expect(removeMessage).toHaveBeenCalledWith(expect.any(String));++ service.show({ id: 'fixed-id', content: 'x' } as IMessageProps);+ expect(message).toHaveBeenCalledWith(expect.objectContaining({ id: 'fixed-id' }));++ service.remove('fixed-id');+ expect(removeMessage).toHaveBeenCalledWith('fixed-id');++ service.removeAll();+ expect(removeMessage).toHaveBeenCalledWith();++ service.dispose();+ expect(removeMessage).toHaveBeenCalledWith();+ });+});++describe('DesktopGalleryService', () => {+ it('should open and close gallery state', () => {+ const uiPartsService = createUiPartsService();+ const service = new DesktopGalleryService({} as any, uiPartsService as any);++ const emitted: IGalleryProps[] = [];+ const complete = vi.fn();+ service.gallery$.subscribe({+ next: (v) => emitted.push(v),+ complete,+ });++ const dis = service.open({ images: ['a'] } as any);+ expect(emitted.at(-1)).toEqual(expect.objectContaining({ open: true, images: ['a'] }));++ service.close();+ expect(emitted.at(-1)).toEqual({ open: false, images: [] });++ dis.dispose();+ expect(complete).toHaveBeenCalledTimes(1);++ service.dispose();+ });+});++describe('DesktopNotificationService', async () => {+ const { notification } = await import('../../components/notification/Notification');++ it('should register ui part and show notification', () => {+ const uiPartsService = createUiPartsService();+ const service = new DesktopNotificationService({} as any, uiPartsService as any);++ const dis = service.show({ title: 'hello', type: 'info' });+ expect(notification.show).toHaveBeenCalledWith({ title: 'hello', type: 'info' });++ dis.dispose();+ service.dispose();+ });+});++describe('DesktopBeforeCloseService', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should handle beforeunload and unload callbacks', () => {+ const listeners: Record<string, Function> = {};+ vi.spyOn(window, 'addEventListener').mockImplementation((event, handler) => {+ listeners[event] = handler as any;+ });++ const notificationService = {+ show: vi.fn(),+ };++ const service = new DesktopBeforeCloseService(notificationService as any);++ const onClose = vi.fn();+ const regClose = service.registerOnClose(onClose);++ const keep1 = service.registerBeforeClose(() => 'unsaved A');+ const keep2 = service.registerBeforeClose(() => undefined);++ const event = { returnValue: '' } as BeforeUnloadEvent;+ const result = listeners.beforeunload(event);+ expect(result).toContain('unsaved A');+ expect(event.returnValue).toContain('unsaved A');+ expect(notificationService.show).toHaveBeenCalled();++ Object.defineProperty(window, 'event', {+ configurable: true,+ value: { returnValue: '' },+ });+ const fallbackResult = listeners.beforeunload(undefined);+ expect(fallbackResult).toContain('unsaved A');++ listeners.unload();+ expect(onClose).toHaveBeenCalledTimes(1);++ keep1.dispose();+ keep2.dispose();+ regClose.dispose();++ const noMessageResult = listeners.beforeunload({ returnValue: '' } as BeforeUnloadEvent);+ expect(noMessageResult).toBeUndefined();+ });+});++describe('DesktopLocalFileService', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should open file chooser and download file', async () => {+ const service = new DesktopLocalFileService();++ const originalCreateElement = document.createElement.bind(document);+ const input = originalCreateElement('input') as HTMLInputElement;+ const anchor = originalCreateElement('a') as HTMLAnchorElement;+ const inputClick = vi.spyOn(input, 'click').mockImplementation(() => {+ Object.defineProperty(input, 'files', {+ configurable: true,+ value: [new File(['a'], 'a.txt')],+ });+ input.onchange?.({ target: input } as any);+ });+ const anchorClick = vi.spyOn(anchor, 'click').mockImplementation(() => {});++ vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {+ if (tagName === 'input') return input;+ if (tagName === 'a') return anchor;+ return originalCreateElement(tagName);+ });++ const createObjectURL = vi.spyOn(window.URL, 'createObjectURL').mockReturnValue('blob:mock');++ const files = await service.openFile({ accept: '.txt', multiple: true });+ expect(files.map((file) => file.name)).toEqual(['a.txt']);+ expect(input.accept).toBe('.txt');+ expect(input.multiple).toBe(true);+ expect(inputClick).toHaveBeenCalledTimes(1);++ service.downloadFile(new Blob(['abc']), 'f.txt');+ expect(anchor.download).toBe('f.txt');+ expect(anchor.href).toBe('blob:mock');+ expect(anchorClick).toHaveBeenCalledTimes(1);+ expect(createObjectURL).toHaveBeenCalledTimes(1);+ });+});++describe('DesktopLocalStorageService', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should proxy localforage APIs', async () => {+ vi.mocked(localforage.getItem).mockResolvedValue('v' as any);+ vi.mocked(localforage.setItem).mockResolvedValue('saved' as any);+ vi.mocked(localforage.removeItem).mockResolvedValue(undefined as any);+ vi.mocked(localforage.clear).mockResolvedValue(undefined as any);+ vi.mocked(localforage.key).mockResolvedValue('k' as any);+ vi.mocked(localforage.keys).mockResolvedValue(['k1', 'k2']);+ vi.mocked(localforage.iterate).mockResolvedValue('iter' as any);++ const service = new DesktopLocalStorageService();++ await expect(service.getItem('a')).resolves.toBe('v');+ await expect(service.setItem('a', 'b')).resolves.toBe('saved');+ await expect(service.removeItem('a')).resolves.toBeUndefined();+ await expect(service.clear()).resolves.toBeUndefined();+ await expect(service.key(0)).resolves.toBe('k');+ await expect(service.keys()).resolves.toEqual(['k1', 'k2']);+ await expect(service.iterate((v) => v)).resolves.toBe('iter');++ expect(localforage.getItem).toHaveBeenCalledWith('a');+ expect(localforage.setItem).toHaveBeenCalledWith('a', 'b');+ });+});diff --git a/packages/ui/src/services/__tests__/font.spec.ts b/packages/ui/src/services/__tests__/font.spec.tsindex 78c24b9a52..6ba6a192c7 100644--- a/packages/ui/src/services/__tests__/font.spec.ts+++ b/packages/ui/src/services/__tests__/font.spec.ts@@ -15,7 +15,7 @@*/import { IConfigService, Injector } from '@univerjs/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { FontService } from '../font.service';describe('FontService', () => {@@ -33,6 +33,10 @@ describe('FontService', () => {injector.add([FontService]);});+ afterEach(() => {+ vi.restoreAllMocks();+ });+it('should initialize with default fonts when no config is provided', () => {vi.mocked(configService.getConfig).mockReturnValue(undefined);fontService = injector.get(FontService);@@ -129,4 +133,65 @@ describe('FontService', () => {expect(fontService.getFontByValue('Arial')).toBeDefined();expect(fontService.getFonts()).toHaveLength(13);});++ it('should reset and complete subject when disposed', () => {+ vi.mocked(configService.getConfig).mockReturnValue(undefined);+ fontService = injector.get(FontService);+ fontService.addFont({ value: 'Disposable', label: 'Disposable Font' });++ expect(fontService.getFontByValue('Disposable')).toBeDefined();+ fontService.dispose();++ expect(fontService.getFontByValue('Disposable')).toBeUndefined();+ expect(fontService.getFonts()).toHaveLength(13);+ expect(fontService.fonts$.isStopped).toBe(true);+ });++ it('should return false when canvas context is unavailable', () => {+ vi.mocked(configService.getConfig).mockReturnValue(undefined);+ fontService = injector.get(FontService);++ const canvas = {+ getContext: vi.fn(() => null),+ } as unknown as HTMLCanvasElement;+ vi.spyOn(document, 'createElement').mockReturnValue(canvas as never);++ expect(fontService.isFontSupported('Any Font')).toBe(false);+ });++ it('should return true when measured width changes for candidate font', () => {+ vi.mocked(configService.getConfig).mockReturnValue(undefined);+ fontService = injector.get(FontService);++ const context = {+ font: '',+ measureText: vi.fn(() => ({+ width: context.font.includes('"Supported Font"') ? 120 : 100,+ })),+ } as unknown as CanvasRenderingContext2D;+ const canvas = {+ getContext: vi.fn(() => context),+ } as unknown as HTMLCanvasElement;+ vi.spyOn(document, 'createElement').mockReturnValue(canvas as never);++ expect(fontService.isFontSupported('Supported Font')).toBe(true);+ });++ it('should return false when candidate font keeps the same width', () => {+ vi.mocked(configService.getConfig).mockReturnValue(undefined);+ fontService = injector.get(FontService);++ const context = {+ font: '',+ measureText: vi.fn(() => ({+ width: 100,+ })),+ } as unknown as CanvasRenderingContext2D;+ const canvas = {+ getContext: vi.fn(() => context),+ } as unknown as HTMLCanvasElement;+ vi.spyOn(document, 'createElement').mockReturnValue(canvas as never);++ expect(fontService.isFontSupported('Unsupported Font')).toBe(false);+ });});diff --git a/packages/ui/src/services/__tests__/misc-services.spec.ts b/packages/ui/src/services/__tests__/misc-services.spec.tsnew file mode 100644index 0000000000..509ca6aa2b--- /dev/null+++ b/packages/ui/src/services/__tests__/misc-services.spec.ts@@ -0,0 +1,333 @@+/**+ * 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 { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { supportClipboardAPI } from '../clipboard/clipboard-utils';+import { ContextMenuHostService } from '../contextmenu/contextmenu-host.service';+import { ContextMenuService } from '../contextmenu/contextmenu.service';+import { IDialogService } from '../dialog/dialog.service';+import { CanvasFloatDomService } from '../dom/canvas-dom-layer.service';+import { IGalleryService } from '../gallery/gallery.service';+import { DesktopGlobalZoneService } from '../global-zone/desktop-global-zone.service';+import { IGlobalZoneService } from '../global-zone/global-zone.service';+import { ILocalFileService } from '../local-file/local-file.service';+import { isMenuButtonSelectorItem, isMenuSelectorItem, MenuItemType } from '../menu/menu';+import { IMessageService } from '../message/message.service';+import { INotificationService } from '../notification/notification.service';+import { CanvasPopupService } from '../popup/canvas-popup.service';+import { DesktopSidebarService } from '../sidebar/desktop-sidebar.service';+import { ILeftSidebarService, ISidebarService } from '../sidebar/sidebar.service';+import { ThemeSwitcherService } from '../theme-switcher/theme-switcher.service';+import { DesktopZenZoneService } from '../zen-zone/desktop-zen-zone.service';+import { IZenZoneService } from '../zen-zone/zen-zone.service';++describe('simple exported identifiers and helpers', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should expose identifier tokens', () => {+ expect(IGalleryService).toBeDefined();+ expect(IGlobalZoneService).toBeDefined();+ expect(IDialogService).toBeDefined();+ expect(ILocalFileService).toBeDefined();+ expect(IMessageService).toBeDefined();+ expect(INotificationService).toBeDefined();+ expect(ISidebarService).toBeDefined();+ expect(ILeftSidebarService).toBeDefined();+ expect(IZenZoneService).toBeDefined();+ });++ it('should detect clipboard api support', () => {+ Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });+ expect(supportClipboardAPI()).toBe(false);++ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: {+ readText: vi.fn(),+ },+ });+ expect(supportClipboardAPI()).toBe(true);+ });++ it('should detect menu selector item types', () => {+ expect(isMenuSelectorItem({ type: MenuItemType.SELECTOR } as any)).toBe(true);+ expect(isMenuSelectorItem({ type: MenuItemType.SUBITEMS } as any)).toBe(true);+ expect(isMenuSelectorItem({ type: MenuItemType.BUTTON_SELECTOR } as any)).toBe(false);++ expect(isMenuButtonSelectorItem({ type: MenuItemType.BUTTON_SELECTOR } as any)).toBe(true);+ expect(isMenuButtonSelectorItem({ type: MenuItemType.BUTTON } as any)).toBe(false);+ });+});++describe('context menu services', () => {+ it('should delegate context menu events to current handler', () => {+ const service = new ContextMenuService();+ const handler = {+ visible: true,+ handleContextMenu: vi.fn(),+ hideContextMenu: vi.fn(),+ };++ const dis = service.registerContextMenuHandler(handler);+ expect(() => service.registerContextMenuHandler(handler)).toThrow();++ const event = {+ stopPropagation: vi.fn(),+ } as any;+ service.triggerContextMenu(event, 'main');+ expect(event.stopPropagation).toHaveBeenCalledTimes(1);+ expect(handler.handleContextMenu).toHaveBeenCalledWith(event, 'main');+ expect(service.visible).toBe(true);++ service.disable();+ service.triggerContextMenu(event, 'disabled');+ expect(handler.handleContextMenu).toHaveBeenCalledTimes(1);++ service.enable();+ service.hideContextMenu();+ expect(handler.hideContextMenu).toHaveBeenCalledTimes(1);++ dis.dispose();+ expect(service.visible).toBe(false);+ });++ it('should manage active host menu', () => {+ const service = new ContextMenuHostService();+ const hideA = vi.fn();+ const hideB = vi.fn();++ const disA = service.registerMenu('a', hideA);+ const disB = service.registerMenu('b', hideB);++ service.activateMenu('a');+ expect(service.activeMenuId).toBe('a');++ service.activateMenu('b');+ expect(hideA).toHaveBeenCalledTimes(1);+ expect(service.activeMenuId).toBe('b');++ service.hideActiveMenu('b');+ expect(hideB).toHaveBeenCalledTimes(0);++ service.hideActiveMenu();+ expect(hideB).toHaveBeenCalledTimes(1);+ expect(service.activeMenuId).toBeNull();++ service.deactivateMenu('b');+ disA.dispose();+ disB.dispose();+ expect(service.activeMenuId).toBeNull();+ });+});++describe('CanvasFloatDomService', () => {+ it('should add, update, remove and clear float dom items', () => {+ const service = new CanvasFloatDomService();+ const events: any[] = [];+ service.domLayers$.subscribe((value) => events.push(value));++ service.addFloatDom({+ id: 'dom-1',+ componentKey: 'comp',+ onPointerMove: vi.fn(),+ onPointerDown: vi.fn(),+ onPointerUp: vi.fn(),+ onWheel: vi.fn(),+ unitId: 'u1',+ position$: new BehaviorSubject({+ left: 0,+ top: 0,+ rotate: 0,+ width: 10,+ height: 10,+ absolute: { left: true, top: true },+ }),+ } as any);++ expect(service.domLayers.length).toBe(1);++ service.updateFloatDom('dom-1', { componentKey: 'comp2' } as any);+ expect(service.domLayers[0][1].componentKey).toBe('comp2');++ service.updateFloatDom('not-found', { componentKey: 'x' } as any);++ service.removeFloatDom('dom-1');+ expect(service.domLayers.length).toBe(0);++ service.removeFloatDom('dom-1');+ service.removeAll();+ expect(events.length).toBeGreaterThanOrEqual(4);+ });+});++describe('CanvasPopupService', () => {+ it('should add/remove popups and track active popup id', () => {+ const service = new CanvasPopupService();++ const id = service.addPopup({+ componentKey: 'popup',+ unitId: 'u',+ subUnitId: 's',+ canvasElement: document.createElement('canvas'),+ anchorRect$: new BehaviorSubject({} as any),+ } as any);++ expect(id).toBeTruthy();+ expect(service.popups.length).toBe(1);++ const popup = service.popups[0][1];+ popup.onActiveChange?.(true);+ expect(service.activePopupId).toBe(id);++ popup.onActiveChange?.(false);+ expect(service.activePopupId).toBeNull();++ service.removePopup('not-found');+ service.removePopup(id);+ expect(service.popups.length).toBe(0);++ service.addPopup({+ componentKey: 'popup-2',+ unitId: 'u2',+ subUnitId: 's2',+ canvasElement: document.createElement('canvas'),+ anchorRect$: new BehaviorSubject({} as any),+ } as any);++ service.removeAll();+ expect(service.popups).toEqual([]);++ service.dispose();+ expect(service.popups).toEqual([]);+ });+});++describe('DesktopSidebarService', () => {+ it('should open and close sidebar with id checks and container', () => {+ const service = new DesktopSidebarService();+ const onClose = vi.fn();+ const emitted: any[] = [];+ service.sidebarOptions$.subscribe((v) => emitted.push(v));++ const dis = service.open({ id: 'side-1', title: 'A', onClose } as any);+ expect(service.visible).toBe(true);+ expect(service.options.id).toBe('side-1');++ service.close('other-id');+ expect(service.visible).toBe(true);++ service.close('side-1');+ expect(service.visible).toBe(false);+ expect(onClose).toHaveBeenCalledTimes(1);++ const container = document.createElement('div');+ service.setContainer(container);+ expect(service.getContainer()).toBe(container);++ dis.dispose();+ expect(service.visible).toBe(false);+ expect(emitted.length).toBeGreaterThanOrEqual(2);+ });+});++describe('ThemeSwitcherService', () => {+ it('should inject and replace theme css variables in document head', () => {+ const service = new ThemeSwitcherService();+ service.injectThemeToHead({+ color: {+ primary: '#fff',+ },+ spacing: 8,+ } as any);++ const style = document.getElementById('univer-theme-css-variables');+ expect(style).toBeTruthy();+ expect(style?.innerHTML).toContain('--univer-color-primary');++ service.injectThemeToHead({+ color: {+ primary: '#000',+ },+ } as any);++ const styles = document.querySelectorAll('#univer-theme-css-variables');+ expect(styles.length).toBe(1);++ service.dispose();+ });+});++describe('zone services', () => {+ it('should handle DesktopGlobalZoneService lifecycle', () => {+ const manager = {+ register: vi.fn(),+ delete: vi.fn(),+ };+ const service = new DesktopGlobalZoneService(manager as any);++ const visibleValues: boolean[] = [];+ const keyValues: string[] = [];+ service.visible$.subscribe((v) => visibleValues.push(v));+ service.componentKey$.subscribe((v) => keyValues.push(v));++ const dis = service.set('zone-key', (() => null) as any);+ expect(manager.register).toHaveBeenCalledWith('zone-key', expect.any(Function));+ expect(service.componentKey).toBe('zone-key');+ expect(keyValues).toEqual(['zone-key']);++ service.open();+ service.close();+ expect(visibleValues).toEqual([true, false]);++ dis.dispose();+ expect(manager.delete).toHaveBeenCalledWith('zone-key');+ });++ it('should handle DesktopZenZoneService lifecycle', () => {+ const manager = {+ register: vi.fn(),+ delete: vi.fn(),+ };+ const service = new DesktopZenZoneService(manager as any);++ const visibleValues: boolean[] = [];+ const hiddenValues: boolean[] = [];+ service.visible$.subscribe((v) => visibleValues.push(v));+ service.temporaryHidden$.subscribe((v) => hiddenValues.push(v));++ const dis = service.set('zen-key', (() => null) as any);+ expect(manager.register).toHaveBeenCalledWith('zen-key', expect.any(Function));++ service.hide();+ service.show();+ expect(service.temporaryHidden).toBe(false);++ service.open();+ expect(service.visible).toBe(true);+ service.close();+ expect(service.visible).toBe(false);++ dis.dispose();+ expect(manager.delete).toHaveBeenCalledWith('zen-key');++ service.dispose();+ expect(visibleValues.at(-1)).toBe(false);+ expect(hiddenValues).toContain(true);+ });+});diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.tsnew file mode 100644index 0000000000..691bf7993c--- /dev/null+++ b/packages/ui/src/services/clipboard/__tests__/clipboard-interface.service.spec.ts@@ -0,0 +1,144 @@+/**+ * 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 { ILogService, LocaleService } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { BrowserClipboardService } from '../clipboard-interface.service';+import { supportClipboardAPI } from '../clipboard-utils';++vi.mock('../clipboard-utils', () => ({+ supportClipboardAPI: vi.fn(),+}));++class MockClipboardItem {+ constructor(public readonly items: Record<string, Blob>) {}+}++function createService() {+ const localeService = {+ t: vi.fn((key: string) => key),+ } as unknown as LocaleService;+ const logService = {+ error: vi.fn(),+ } as unknown as ILogService;+ const notificationService = {+ show: vi.fn(),+ };++ const service = new BrowserClipboardService(localeService, logService, notificationService as any);++ return { service, localeService, logService, notificationService };+}++describe('BrowserClipboardService', () => {+ beforeEach(() => {+ vi.mocked(supportClipboardAPI).mockReturnValue(true);+ (globalThis as any).ClipboardItem = MockClipboardItem;+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: {+ write: vi.fn().mockResolvedValue(undefined),+ writeText: vi.fn().mockResolvedValue(undefined),+ read: vi.fn().mockResolvedValue([]),+ readText: vi.fn().mockResolvedValue('clipboard-text'),+ },+ });+ (document as any).execCommand = vi.fn(() => true);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should expose clipboard support from utility', () => {+ vi.mocked(supportClipboardAPI).mockReturnValue(true);+ const { service } = createService();+ expect(service.supportClipboard).toBe(true);+ });++ it('should write plain text and html with modern clipboard api', async () => {+ const { service } = createService();++ await service.write('plain', '<b>plain</b>');++ expect(navigator.clipboard.write).toHaveBeenCalledTimes(1);+ });++ it('should write text with modern clipboard api', async () => {+ const { service } = createService();++ await service.writeText('hello');+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('hello');+ });++ it('should fallback to legacy copy when clipboard api is unsupported', async () => {+ vi.mocked(supportClipboardAPI).mockReturnValue(false);+ const { service } = createService();++ const input = document.createElement('input');+ document.body.appendChild(input);+ input.focus();++ await service.writeText('legacy-text');+ await service.write('legacy', '<i>legacy</i>');++ expect(document.execCommand).toHaveBeenCalledWith('copy');+ });++ it('should show notification when write/writeText fails', async () => {+ const { service, logService, notificationService } = createService();+ vi.mocked(navigator.clipboard.writeText).mockRejectedValueOnce(new Error('writeText failed'));+ vi.mocked(navigator.clipboard.write).mockRejectedValueOnce(new Error('write failed'));++ await service.writeText('failed');+ await service.write('failed', '<b>failed</b>');++ expect(logService.error).toHaveBeenCalledTimes(2);+ expect(notificationService.show).toHaveBeenCalledWith({+ type: 'warning',+ title: 'clipboard.authentication.title',+ content: 'clipboard.authentication.content',+ });+ });++ it('should throw for read/readText when clipboard api is unsupported', async () => {+ vi.mocked(supportClipboardAPI).mockReturnValue(false);+ const { service } = createService();++ await expect(service.read()).rejects.toThrow('[BrowserClipboardService] read() is not supported on this platform.');+ await expect(service.readText()).rejects.toThrow('[BrowserClipboardService] read() is not supported on this platform.');+ });++ it('should read clipboard data when supported', async () => {+ const { service } = createService();++ await expect(service.read()).resolves.toEqual([]);+ await expect(service.readText()).resolves.toBe('clipboard-text');+ });++ it('should return fallback values and notify when read/readText fails', async () => {+ const { service, logService, notificationService } = createService();+ vi.mocked(navigator.clipboard.read).mockImplementationOnce(() => {+ throw new Error('read failed');+ });+ vi.mocked(navigator.clipboard.readText).mockRejectedValueOnce(new Error('readText failed'));++ await expect(service.read()).resolves.toEqual([]);+ await expect(service.readText()).resolves.toBe('');+ expect(logService.error).toHaveBeenCalledTimes(2);+ expect(notificationService.show).toHaveBeenCalled();+ });+});diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard.command.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard.command.spec.tsnew file mode 100644index 0000000000..f0c21b91ba--- /dev/null+++ b/packages/ui/src/services/clipboard/__tests__/clipboard.command.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 { IAccessor, IContextService } from '@univerjs/core';+import { CommandType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { CopyCommand, CutCommand, PasteCommand, SheetPasteShortKeyCommandName } from '../clipboard.command';++describe('clipboard commands', () => {+ it('should define copy/cut/paste command metadata', () => {+ expect(CopyCommand.id).toBe('univer.command.copy');+ expect(CutCommand.id).toBe('univer.command.cut');+ expect(PasteCommand.id).toBe('univer.command.paste');++ expect(CopyCommand.type).toBe(CommandType.COMMAND);+ expect(CutCommand.type).toBe(CommandType.COMMAND);+ expect(PasteCommand.type).toBe(CommandType.COMMAND);++ expect(CopyCommand.multi).toBe(true);+ expect(CutCommand.multi).toBe(true);+ expect(PasteCommand.multi).toBe(true);+ });++ it('should return fixed command behavior and short key name', async () => {+ const contextService = {} as IContextService;+ const accessor = {} as IAccessor;++ expect(CopyCommand.preconditions!(contextService)).toBe(false);+ expect(CutCommand.preconditions!(contextService)).toBe(false);+ expect(PasteCommand.preconditions!(contextService)).toBe(false);++ expect(CopyCommand.handler(accessor)).toBe(true);+ await expect(CutCommand.handler(accessor)).resolves.toBe(true);+ expect(PasteCommand.handler(accessor)).toBe(true);++ expect(SheetPasteShortKeyCommandName).toBe('sheet.command.paste-by-short-key');+ });+});diff --git a/packages/ui/src/services/menu/__tests__/types.spec.ts b/packages/ui/src/services/menu/__tests__/types.spec.tsnew file mode 100644index 0000000000..8c77486772--- /dev/null+++ b/packages/ui/src/services/menu/__tests__/types.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 {+ ContextMenuGroup,+ ContextMenuPosition,+ MenuManagerPosition,+ RibbonDataGroup,+ RibbonFormulasGroup,+ RibbonInsertGroup,+ RibbonOthersGroup,+ RibbonPosition,+ RibbonStartGroup,+ RibbonViewGroup,+} from '../types';++describe('menu type enums', () => {+ it('should expose ribbon positions and groups', () => {+ expect(MenuManagerPosition.RIBBON).toBe('ribbon');+ expect(RibbonPosition.START).toBe('ribbon.start');+ expect(RibbonPosition.OTHERS).toBe('ribbon.others');+ expect(RibbonStartGroup.HISTORY).toBe('ribbon.start.history');+ expect(RibbonInsertGroup.MEDIA).toBe('ribbon.insert.media');+ expect(RibbonFormulasGroup.BASIC).toBe('ribbon.formulas.basic');+ expect(RibbonDataGroup.RULES).toBe('ribbon.data.rules');+ expect(RibbonViewGroup.VISIBILITY).toBe('ribbon.view.Visibility');+ expect(RibbonOthersGroup.OTHERS).toBe('ribbon.others.others');+ });++ it('should expose context menu positions and groups', () => {+ expect(MenuManagerPosition.CONTEXT_MENU).toBe('contextMenu');+ expect(ContextMenuPosition.MAIN_AREA).toBe('contextMenu.mainArea');+ expect(ContextMenuPosition.PARAGRAPH).toBe('contextMenu.paragraph');+ expect(ContextMenuGroup.QUICK).toBe('contextMenu.quick');+ expect(ContextMenuGroup.OTHERS).toBe('contextMenu.others');+ });+});diff --git a/packages/ui/src/services/platform/__tests__/platform.service.spec.ts b/packages/ui/src/services/platform/__tests__/platform.service.spec.tsnew file mode 100644index 0000000000..c7ebc1ffa7--- /dev/null+++ b/packages/ui/src/services/platform/__tests__/platform.service.spec.ts@@ -0,0 +1,51 @@+/**+ * 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 { afterEach, describe, expect, it, vi } from 'vitest';+import { PlatformService } from '../platform.service';++describe('PlatformService', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('should detect Mac platform by appVersion', () => {+ vi.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Mac OS X');+ const service = new PlatformService();++ expect(service.isMac).toBe(true);+ expect(service.isWindows).toBe(false);+ expect(service.isLinux).toBe(false);+ });++ it('should detect Windows platform by appVersion', () => {+ vi.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Windows NT');+ const service = new PlatformService();++ expect(service.isMac).toBe(false);+ expect(service.isWindows).toBe(true);+ expect(service.isLinux).toBe(false);+ });++ it('should detect Linux platform by appVersion', () => {+ vi.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Linux x86_64');+ const service = new PlatformService();++ expect(service.isMac).toBe(false);+ expect(service.isWindows).toBe(false);+ expect(service.isLinux).toBe(true);+ });+});diff --git a/packages/ui/src/services/shortcut/__tests__/keycode.spec.ts b/packages/ui/src/services/shortcut/__tests__/keycode.spec.tsnew file mode 100644index 0000000000..d4fc99bd0f--- /dev/null+++ b/packages/ui/src/services/shortcut/__tests__/keycode.spec.ts@@ -0,0 +1,59 @@+/**+ * 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 { KeyCode, KeyCodeToChar, MetaKeys } from '../keycode';++describe('keycode mappings', () => {+ it('should map common control keys to labels', () => {+ expect(KeyCodeToChar[KeyCode.BACKSPACE]).toBe('Backspace');+ expect(KeyCodeToChar[KeyCode.ENTER]).toBe('Enter');+ expect(KeyCodeToChar[KeyCode.DELETE]).toBe('Del');+ expect(KeyCodeToChar[KeyCode.ESC]).toBe('Esc');+ expect(KeyCodeToChar[KeyCode.SPACE]).toBe('Space');+ });++ it('should map alphanumeric and function keys', () => {+ expect(KeyCodeToChar[KeyCode.Digit0]).toBe('0');+ expect(KeyCodeToChar[KeyCode.Digit9]).toBe('9');+ expect(KeyCodeToChar[KeyCode.A]).toBe('A');+ expect(KeyCodeToChar[KeyCode.Z]).toBe('Z');+ expect(KeyCodeToChar[KeyCode.F1]).toBe('F1');+ expect(KeyCodeToChar[KeyCode.F12]).toBe('F12');+ });++ it('should map punctuation and arrow keys', () => {+ expect(KeyCodeToChar[KeyCode.MINUS]).toBe('-');+ expect(KeyCodeToChar[KeyCode.EQUAL]).toBe('=');+ expect(KeyCodeToChar[KeyCode.PERIOD]).toBe('.');+ expect(KeyCodeToChar[KeyCode.COMMA]).toBe(',');+ expect(KeyCodeToChar[KeyCode.BACK_SLASH]).toBe('\\');+ expect(KeyCodeToChar[KeyCode.ARROW_LEFT]).toBe('←');+ expect(KeyCodeToChar[KeyCode.ARROW_RIGHT]).toBe('→');+ expect(KeyCodeToChar[KeyCode.ARROW_UP]).toBe('↑');+ expect(KeyCodeToChar[KeyCode.ARROW_DOWN]).toBe('↓');+ });++ it('should return undefined for unknown key code', () => {+ expect(KeyCodeToChar[KeyCode.UNKNOWN]).toBeUndefined();+ });++ it('should define non-overlapping meta key bitmasks', () => {+ expect(MetaKeys.SHIFT & MetaKeys.ALT).toBe(0);+ expect(MetaKeys.ALT & MetaKeys.CTRL_COMMAND).toBe(0);+ expect(MetaKeys.CTRL_COMMAND & MetaKeys.MAC_CTRL).toBe(0);+ });+});diff --git a/packages/ui/src/services/shortcut/__tests__/shortcut-panel.service.spec.ts b/packages/ui/src/services/shortcut/__tests__/shortcut-panel.service.spec.tsnew file mode 100644index 0000000000..2eb411acda--- /dev/null+++ b/packages/ui/src/services/shortcut/__tests__/shortcut-panel.service.spec.ts@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it } from 'vitest';+import { ShortcutPanelService } from '../shortcut-panel.service';++describe('ShortcutPanelService', () => {+ it('should open and close panel state', () => {+ const service = new ShortcutPanelService();++ expect(service.isOpen).toBe(false);++ service.open();+ expect(service.isOpen).toBe(true);++ service.close();+ expect(service.isOpen).toBe(false);+ });++ it('should emit distinct state values and complete on dispose', () => {+ const service = new ShortcutPanelService();+ const values: boolean[] = [];+ let completed = false;++ const sub = service.open$.subscribe({+ next: (value) => values.push(value),+ complete: () => {+ completed = true;+ },+ });++ service.close();+ service.open();+ service.open();+ service.close();++ expect(values).toEqual([false, true, false]);++ service.dispose();+ expect(completed).toBe(true);++ sub.unsubscribe();+ });+});diff --git a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.tsnew file mode 100644index 0000000000..cc0cc458f8--- /dev/null+++ b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts@@ -0,0 +1,215 @@+/**+ * 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 { IContextService } from '@univerjs/core';+import type { ILayoutService } from '../../layout/layout.service';+import { describe, expect, it, vi } from 'vitest';+import { KeyCode, MetaKeys } from '../keycode';+import { ShortcutService } from '../shortcut.service';++function createKeyboardEvent(+ keyCode: number,+ options?: { ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean; altKey?: boolean }+): KeyboardEvent {+ const event = new KeyboardEvent('keydown', {+ bubbles: true,+ cancelable: true,+ ctrlKey: options?.ctrlKey,+ metaKey: options?.metaKey,+ shiftKey: options?.shiftKey,+ altKey: options?.altKey,+ });++ Object.defineProperty(event, 'keyCode', {+ configurable: true,+ get: () => keyCode,+ });++ return event;+}++function createService(options?: {+ isMac?: boolean;+ isWindows?: boolean;+ isLinux?: boolean;+ layoutAllowed?: boolean;+}) {+ const executeCommand = vi.fn();+ const commandService = { executeCommand };+ const platformService = {+ isMac: options?.isMac ?? false,+ isWindows: options?.isWindows ?? true,+ isLinux: options?.isLinux ?? false,+ };+ const contextService = {} as IContextService;+ const layoutService = options?.layoutAllowed === undefined+ ? undefined+ : ({+ checkElementInCurrentContainers: vi.fn(() => options.layoutAllowed),+ } as unknown as ILayoutService);++ const service = new ShortcutService(commandService as any, platformService as any, contextService, layoutService);++ return { service, executeCommand, layoutService };+}++describe('ShortcutService', () => {+ it('should register and unregister shortcuts', () => {+ const { service } = createService();+ const changed = vi.fn();+ const sub = service.shortcutChanged$.subscribe(changed);++ const disposable = service.registerShortcut({+ id: 'cmd.save',+ binding: KeyCode.S | MetaKeys.CTRL_COMMAND,+ });++ expect(service.getAllShortcuts()).toHaveLength(1);+ expect(changed).toHaveBeenCalledTimes(1);++ disposable.dispose();+ expect(service.getAllShortcuts()).toHaveLength(0);+ expect(changed).toHaveBeenCalledTimes(2);++ sub.unsubscribe();+ service.dispose();+ });++ it('should ignore invalid shortcuts without binding', () => {+ const { service } = createService();++ service.registerShortcut({+ id: 'cmd.invalid',+ });++ expect(service.getAllShortcuts()).toHaveLength(0);+ service.dispose();+ });++ it('should resolve candidate by priority and preconditions', () => {+ const { service } = createService();+ const low = {+ id: 'cmd.low',+ binding: KeyCode.A | MetaKeys.CTRL_COMMAND,+ priority: 1,+ };+ const highBlocked = {+ id: 'cmd.blocked',+ binding: KeyCode.A | MetaKeys.CTRL_COMMAND,+ priority: 10,+ preconditions: () => false,+ };+ const highAllowed = {+ id: 'cmd.high',+ binding: KeyCode.A | MetaKeys.CTRL_COMMAND,+ priority: 9,+ preconditions: () => true,+ };++ service.registerShortcut(low);+ service.registerShortcut(highBlocked);+ service.registerShortcut(highAllowed);++ const event = createKeyboardEvent(KeyCode.A, { ctrlKey: true });+ const candidate = service.dispatch(event);++ expect(candidate?.id).toBe('cmd.high');+ service.dispose();+ });++ it('should ignore dispatch when escaped, disabled, or target not in layout container', () => {+ const escapedService = createService().service;+ escapedService.registerShortcut({+ id: 'cmd.esc',+ binding: KeyCode.A | MetaKeys.CTRL_COMMAND,+ });+ const escapedDisposable = escapedService.forceEscape();+ expect(escapedService.dispatch(createKeyboardEvent(KeyCode.A, { ctrlKey: true }))).toBeUndefined();+ escapedDisposable.dispose();+ escapedService.dispose();++ const disabledService = createService().service;+ disabledService.registerShortcut({+ id: 'cmd.disabled',+ binding: KeyCode.A | MetaKeys.CTRL_COMMAND,+ });+ const disableDisposable = disabledService.forceDisable();+ expect(disabledService.dispatch(createKeyboardEvent(KeyCode.A, { ctrlKey: true }))).toBeUndefined();+ disableDisposable.dispose();+ disabledService.dispose();++ const withLayout = createService({ layoutAllowed: false }).service;+ withLayout.registerShortcut({+ id: 'cmd.layout',+ binding: KeyCode.A | MetaKeys.CTRL_COMMAND,+ });+ const layoutEvent = createKeyboardEvent(KeyCode.A, { ctrlKey: true });+ Object.defineProperty(layoutEvent, 'target', {+ configurable: true,+ value: document.createElement('div'),+ });+ expect(withLayout.dispatch(layoutEvent)).toBeUndefined();+ withLayout.dispose();+ });++ it('should format shortcut display according to platform-specific bindings', () => {+ const mac = createService({ isMac: true, isWindows: false }).service;+ const macItem = {+ id: 'cmd.mac',+ binding: KeyCode.C,+ mac: KeyCode.C | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT | MetaKeys.ALT | MetaKeys.MAC_CTRL,+ };+ expect(mac.getShortcutDisplay(macItem)).toBe('⌘+⇧+⌥+⌃+C');+ mac.dispose();++ const win = createService({ isWindows: true }).service;+ const winItem = {+ id: 'cmd.win',+ binding: KeyCode.C | MetaKeys.CTRL_COMMAND | MetaKeys.ALT,+ win: KeyCode.C | MetaKeys.CTRL_COMMAND | MetaKeys.SHIFT,+ };+ expect(win.getShortcutDisplay(winItem)).toBe('Ctrl+Shift+C');+ win.dispose();+ });++ it('should return display string of command id and null when not found', () => {+ const { service } = createService();+ service.registerShortcut({+ id: 'cmd.find',+ binding: KeyCode.Z | MetaKeys.CTRL_COMMAND,+ });++ expect(service.getShortcutDisplayOfCommand('cmd.find')).toBe('Ctrl+Z');+ expect(service.getShortcutDisplayOfCommand('cmd.none')).toBeNull();+ service.dispose();+ });++ it('should execute command when native keydown matches registered shortcut', () => {+ const { service, executeCommand } = createService();+ service.registerShortcut({+ id: 'cmd.native',+ binding: KeyCode.V | MetaKeys.CTRL_COMMAND,+ staticParameters: { from: 'test' },+ });++ const event = createKeyboardEvent(KeyCode.V, { ctrlKey: true });+ window.dispatchEvent(event);++ expect(executeCommand).toHaveBeenCalledWith('cmd.native', { from: 'test' });+ expect(event.defaultPrevented).toBe(true);+ service.dispose();+ });+});diff --git a/packages/ui/src/services/sidebar/hooks/__tests__/use-sidebar-click.spec.tsx b/packages/ui/src/services/sidebar/hooks/__tests__/use-sidebar-click.spec.tsxnew file mode 100644index 0000000000..fa121989cc--- /dev/null+++ b/packages/ui/src/services/sidebar/hooks/__tests__/use-sidebar-click.spec.tsx@@ -0,0 +1,55 @@+/**+ * 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 { renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';+import { useDependency } from '../../../../utils/di';+import { useSidebarClick } from '../use-sidebar-click';++vi.mock('../../../../utils/di', () => ({+ useDependency: vi.fn(),+}));++describe('useSidebarClick', () => {+ it('should attach and detach mousedown listener when container exists', () => {+ const container = document.createElement('div');+ const addEventListener = vi.spyOn(container, 'addEventListener');+ const removeEventListener = vi.spyOn(container, 'removeEventListener');++ vi.mocked(useDependency).mockReturnValue({+ getContainer: () => container,+ } as any);++ const callback = vi.fn();+ const { unmount } = renderHook(() => useSidebarClick(callback));++ expect(addEventListener).toHaveBeenCalledWith('mousedown', callback);+ unmount();+ expect(removeEventListener).toHaveBeenCalledWith('mousedown', callback);+ });++ it('should skip listener binding when container is missing', () => {+ vi.mocked(useDependency).mockReturnValue({+ getContainer: () => undefined,+ } as any);++ const callback = vi.fn();+ const { unmount } = renderHook(() => useSidebarClick(callback));++ unmount();+ expect(callback).not.toHaveBeenCalled();+ });+});diff --git a/packages/ui/src/utils/__tests__/cell.spec.ts b/packages/ui/src/utils/__tests__/cell.spec.tsnew file mode 100644index 0000000000..3abee243aa--- /dev/null+++ b/packages/ui/src/utils/__tests__/cell.spec.ts@@ -0,0 +1,311 @@+/**+ * 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 {+ handelExcelToJson,+ handelTableToJson,+ handleDomToJson,+ handlePlainToJson,+ handleStringToStyle,+ handleTableColgroup,+ handleTableMergeData,+ handleTableRowGroup,+ splitSpanText,+} from '../cell';++describe('cell utils', () => {+ it('should handle div wrapper and mixed text nodes when converting dom', () => {+ const wrapped = document.createElement('div');+ wrapped.innerHTML = '<div><span style="font-weight:bold">A</span></div>';+ const wrappedData = handleDomToJson(wrapped);+ expect(typeof wrappedData).toBe('object');++ const mixed = document.createElement('div');+ const text = document.createTextNode('mixed-text');+ mixed.appendChild(text);+ mixed.appendChild(document.createElement('span'));++ const mixedData = handleDomToJson(mixed);+ expect(typeof mixedData).toBe('object');+ });++ it('should convert simple dom nodes to plain string', () => {+ const empty = document.createElement('div');+ empty.textContent = 'plain';+ expect(handleDomToJson(empty)).toBe('plain');++ const singleText = document.createElement('div');+ singleText.appendChild(document.createTextNode('hello'));+ expect(handleDomToJson(singleText)).toBe('hello');+ });++ it('should convert rich dom content to document data', () => {+ const rich = document.createElement('div');+ rich.innerHTML = '<span style="font-weight: bold">Hello</span><span>World</span>';++ const data = handleDomToJson(rich);+ expect(typeof data).toBe('object');+ if (typeof data !== 'string') {+ expect(data.body?.dataStream).toContain('\r\n');+ expect(data.body?.textRuns?.length).toBeGreaterThan(0);+ }+ });++ it('should parse style with text, alignment and border properties', () => {+ const element = document.createElement('span');+ element.dataset.vertical = '1';+ const style = handleStringToStyle(+ element,+ [+ 'font-weight:bold',+ 'font-style:italic',+ 'font-family:"Arial"',+ 'font-size:16px',+ 'color:rgb(1,2,3)',+ 'background-color:#ff0000',+ 'text-decoration-line:underline',+ 'text-decoration-color:rgb(9,9,9)',+ 'text-decoration-style:2',+ 'vertical-align:sub',+ 'transform:rotate(30deg)',+ 'text-align:center',+ 'word-wrap:break-word',+ 'border-color:rgb(1,1,1) rgb(2,2,2)',+ 'border-width:1px 2px',+ 'border-style:solid dashed',+ ].join(';')+ );++ expect(style.bl).toBe(1);+ expect(style.it).toBe(1);+ expect(style.ff).toBe('Arial');+ expect(style.fs).toBeGreaterThan(0);+ expect(style.cl).toBeDefined();+ expect(style.bg).toBeDefined();+ expect(style.ul?.s).toBe(1);+ expect(style.va).toBeDefined();+ expect(style.tr).toEqual({ a: 30, v: 1 });+ expect(style.ht).toBe(2);+ expect(style.tb).toBe(3);+ expect(style.bd).toBeDefined();+ });++ it('should parse additional style variants and clamp font sizes', () => {+ const style = handleStringToStyle(+ undefined,+ [+ 'font-size:2px',+ 'text-decoration:line-through solid',+ 'univer-underline:true',+ 'text-overflow:clip',+ 'white-space:nowrap',+ 'border:1px solid #111',+ '--data-rotate:(0deg ,1)',+ ].join(';')+ );+ expect(style.fs).toBe(9);+ expect(style.st?.s).toBe(1);+ expect(style.ul?.s).toBe(1);+ expect(style.tb).toBe(1);+ expect(style.bd).toBeDefined();+ expect(style.tr).toEqual({ a: 0, v: 1 });++ const largeStyle = handleStringToStyle(undefined, 'font-size:400px;vertical-align:super;text-align:right;');+ expect(largeStyle.fs).toBe(78);+ expect(largeStyle.ht).toBe(3);+ });++ it('should parse additional style branches and clean empty border objects', () => {+ const style = handleStringToStyle(+ undefined,+ [+ 'font-weight:normal',+ 'font-style:normal',+ 'text-decoration-line:line-through',+ 'text-decoration-color:#112233',+ 'text-decoration-style:3',+ 'text-decoration-line:overline',+ 'text-decoration-color:#445566',+ 'text-decoration-style:2',+ 'text-decoration:overline solid',+ 'vertical-align:top',+ 'vertical-align:middle',+ 'vertical-align:bottom',+ 'vertical-align:baseline',+ 'text-align:left',+ 'text-align:justify',+ 'text-align:inherit',+ 'text-break:overflow',+ 'white-space:normal',+ 'white-space:clip',+ 'border-color:rgb(1,1,1) rgb(2,2,2) rgb(3,3,3) rgb(4,4,4)',+ 'border-width:1px 2px 3px 4px',+ 'border-style:solid dashed dotted double',+ 'border-top:1px solid #123456',+ 'border-left:1px solid #654321',+ 'border-right:1px solid #abcdef',+ '--data-rotate:(-12deg)',+ ].join(';')+ );++ expect(style.bl).toBe(0);+ expect(style.it).toBe(0);+ expect(style.st?.s).toBe(1);+ expect(style.ol?.s).toBe(1);+ expect(style.vt).toBe(3);+ expect(style.va).toBeDefined();+ expect(style.ht).toBe(0);+ expect(style.tb).toBe(2);+ expect(style.bd).toBeDefined();+ expect(style.tr).toEqual({ a: -12 });++ const borderNone = handleStringToStyle(undefined, 'border:none;');+ expect(borderNone.bd).toBeUndefined();+ });++ it('should split span text with newline handling', () => {+ expect(splitSpanText('')).toEqual(['']);+ expect(splitSpanText('a\nb')).toEqual(['a', '\r\nb']);+ });++ it('should parse table colgroup widths', () => {+ expect(handleTableColgroup('<table><tr><td>A</td></tr></table>')).toEqual([]);++ const widths = handleTableColgroup(+ '<table><colgroup><col width="100px" span="2"/><col width="72pt"/><col width="96"/></colgroup><tr><td>A</td><td>B</td><td>C</td><td>D</td></tr></table>'+ );+ expect(widths.length).toBe(4);+ expect(widths[0]).toBe(100);+ });++ it('should parse table colgroup width fallback and empty row groups', () => {+ const widths = handleTableColgroup('<table><colgroup><col/></colgroup><tr><td>A</td></tr></table>');+ expect(widths).toEqual([72]);+ expect(handleTableRowGroup('<table></table>')).toEqual([]);+ });++ it('should parse table row heights', () => {+ const heights = handleTableRowGroup(+ '<table><tr><td style="height:20px">A</td><td rowSpan="2" style="height:99px">B</td></tr><tr><td style="height:30px">C</td></tr></table>'+ );++ expect(heights).toEqual([20, 30]);+ });++ it('should parse html table to sheet-like matrix with merge metadata', () => {+ const table = handelTableToJson(+ '<table><tr><td rowSpan="2" colSpan="2"><span style="font-weight:bold">A</span></td><td>C</td></tr><tr><td>D</td></tr></table>'+ );++ expect(table.length).toBe(2);+ expect(table[0][0].mc).toEqual({ rs: 1, cs: 1, r: 0, c: 0 });+ expect(table[0][2].v).toBe('C');+ expect(table[1][0]).toEqual({ mc: null });+ });++ it('should handle empty and irregular tables', () => {+ expect(handelTableToJson('<table></table>')).toEqual([]);++ const irregular = handelTableToJson(+ '<table><tr><td>A</td></tr><tr><td>B</td><td>C</td></tr></table>'+ );+ expect(irregular.length).toBe(2);+ expect(irregular[1][0].v).toBe('B');+ });++ it('should parse plain text grid and drop broken rows', () => {+ const plain = handlePlainToJson('A\tB\nC\tD\nE');+ expect(plain.length).toBe(2);+ expect(plain[0][0].v).toBe('A');+ expect(plain[1][1].m).toBe('D');+ });++ it('should map empty plain cells to null', () => {+ const plain = handlePlainToJson('A\t\nB\tC');+ expect(plain[0][1]).toBeNull();+ });++ it('should extract merge ranges and normalize merged placeholder cells', () => {+ const data = [+ [{ v: 'A', mc: { r: 0, c: 0, rs: 1, cs: 1 } }, { mc: null }],+ [{ mc: null }, { v: 'B' }],+ ];++ const result = handleTableMergeData(data as any, {+ startRow: 2,+ startColumn: 3,+ endRow: 3,+ endColumn: 4,+ });++ expect(result.mergeData).toEqual([{ startRow: 2, endRow: 3, startColumn: 3, endColumn: 4 }]);+ expect(result.data[0][0].mc).toBeUndefined();+ expect(result.data[0][1]).toBeNull();+ });++ it('should parse excel html with style and merged cells', () => {+ const html = `+ <html>+ <style>+ <!--+ .bold { font-weight: bold; color: rgb(1, 2, 3); }+ .bg { background-color: #00ff00; }+ -->+ </style>+ <table>+ <tr>+ <td class="bold" rowSpan="2" colSpan="2"><span>X</span></td>+ <td class="bg">Y</td>+ </tr>+ <tr>+ <td>Z</td>+ </tr>+ </table>+ </html>+ `;++ const result = handelExcelToJson(html);++ expect(result?.length).toBe(2);+ expect(result?.[0][0].mc).toEqual({ rs: 1, cs: 1, r: 0, c: 0 });+ expect(result?.[0][0].s).toBeDefined();+ expect(result?.[0][2].v).toBe('Y');+ });++ it('should return undefined when excel html has no style block', () => {+ expect(handelExcelToJson('<html><table><tr><td>A</td></tr></table></html>')).toBeUndefined();+ });++ it('should handle excel html with style but no row and irregular columns', () => {+ expect(handelExcelToJson('<html><style>.x{font-weight:bold;}</style><table></table></html>')).toEqual([]);++ const irregular = handelExcelToJson(`+ <html>+ <style>+ .x { font-weight: bold; }+ </style>+ <table>+ <tr><td class=\"x\">A</td></tr>+ <tr><td>B</td><td>C</td></tr>+ </table>+ </html>+ `);++ expect(irregular?.[0][0].v).toBe('A');+ expect(irregular?.[1][0].v).toBe('B');+ });+});diff --git a/packages/ui/src/utils/__tests__/di.spec.ts b/packages/ui/src/utils/__tests__/di.spec.tsnew file mode 100644index 0000000000..12ac9d436d--- /dev/null+++ b/packages/ui/src/utils/__tests__/di.spec.ts@@ -0,0 +1,58 @@+/**+ * 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 { act, renderHook } from '@testing-library/react';+import { Observable, Subject } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { useObservableRef } from '../di';++describe('useObservableRef', () => {+ it('should keep default value when observable is undefined', () => {+ const { result } = renderHook(() => useObservableRef<number>(undefined, 1));++ expect(result.current.current).toBe(1);+ });++ it('should update ref when observable emits', () => {+ const subject = new Subject<number>();+ const { result } = renderHook(() => useObservableRef(subject, 0));++ expect(result.current.current).toBe(0);++ act(() => subject.next(2));+ expect(result.current.current).toBe(2);+ });++ it('should support observable factory function', () => {+ const subject = new Subject<number>();+ const createObservable = vi.fn(() => subject.asObservable());+ const { result } = renderHook(() => useObservableRef(createObservable, 0));++ expect(createObservable).toHaveBeenCalledTimes(1);++ act(() => subject.next(5));+ expect(result.current.current).toBe(5);+ });++ it('should unsubscribe on unmount', () => {+ const unsubscribe = vi.fn();+ const observable = new Observable<number>(() => unsubscribe);+ const { unmount } = renderHook(() => useObservableRef(observable));++ unmount();+ expect(unsubscribe).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/watermark/src/controllers/watermark.render.controller.spec.ts b/packages/watermark/src/controllers/watermark.render.controller.spec.tsnew file mode 100644index 0000000000..56f9d77a8d--- /dev/null+++ b/packages/watermark/src/controllers/watermark.render.controller.spec.ts@@ -0,0 +1,149 @@+/**+ * 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 { IWatermarkTypeEnum, UNIVER_WATERMARK_STORAGE_KEY } from '@univerjs/engine-render';+import { Subject } from 'rxjs';++import { describe, expect, it, vi } from 'vitest';+import { WatermarkRenderController } from './watermark.render.controller';++const layerInstances: Array<{ updateConfig: ReturnType<typeof vi.fn> }> = [];++vi.mock('@univerjs/engine-render', async () => {+ const actual = await vi.importActual<typeof import('@univerjs/engine-render')>('@univerjs/engine-render');++ class WatermarkLayer {+ readonly updateConfig = vi.fn();++ constructor() {+ layerInstances.push(this);+ }+ }++ return {+ ...actual,+ IWatermarkTypeEnum: {+ UserInfo: 'userInfo',+ Text: 'text',+ Image: 'image',+ },+ UNIVER_WATERMARK_LAYER_INDEX: 1000,+ UNIVER_WATERMARK_STORAGE_KEY: 'UNIVER_WATERMARK_STORAGE_KEY',+ WatermarkLayer,+ };+});++function waitNextTick() {+ return new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+}++describe('WatermarkRenderController', () => {+ it('should init layer, load config and react to updates', async () => {+ layerInstances.length = 0;++ const updateConfig$ = new Subject<unknown>();+ const updateWatermarkConfig = vi.fn();+ const scene = {+ addLayer: vi.fn(),+ };+ const makeDirty = vi.fn();+ const localStorageService = {+ getItem: vi.fn(async () => ({+ type: IWatermarkTypeEnum.Text,+ config: { text: { content: 'init' } },+ })),+ };+ const userManagerService = {+ getCurrentUser: vi.fn(() => ({ id: 'u1' })),+ };++ const controller = new WatermarkRenderController(+ {+ scene,+ mainComponent: { makeDirty },+ } as never,+ {+ updateConfig$: updateConfig$.asObservable(),+ updateWatermarkConfig,+ } as never,+ localStorageService as never,+ userManagerService as never+ );++ expect(scene.addLayer).toHaveBeenCalledTimes(1);+ expect(localStorageService.getItem).toHaveBeenCalledWith(UNIVER_WATERMARK_STORAGE_KEY);++ await waitNextTick();+ expect(updateWatermarkConfig).toHaveBeenCalledWith({+ type: IWatermarkTypeEnum.Text,+ config: { text: { content: 'init' } },+ });+ expect(makeDirty).toHaveBeenCalled();++ const layer = layerInstances[0];+ expect(layer).toBeDefined();++ updateConfig$.next(null);+ expect(layer.updateConfig).toHaveBeenCalledWith();++ updateConfig$.next({+ type: IWatermarkTypeEnum.UserInfo,+ config: { userInfo: { name: true } },+ });+ expect(layer.updateConfig).toHaveBeenCalledWith(+ { type: IWatermarkTypeEnum.UserInfo, config: { userInfo: { name: true } } },+ { id: 'u1' }+ );++ updateConfig$.next({+ type: IWatermarkTypeEnum.Image,+ config: { image: { url: 'img' } },+ });+ expect(layer.updateConfig).toHaveBeenCalledWith({+ type: IWatermarkTypeEnum.Image,+ config: { image: { url: 'img' } },+ });++ await controller.dispose();+ });++ it('should skip init config update when storage is empty', async () => {+ layerInstances.length = 0;++ const updateConfig$ = new Subject<unknown>();+ const updateWatermarkConfig = vi.fn();+ const makeDirty = vi.fn();+ const _controller = new WatermarkRenderController(+ {+ scene: { addLayer: vi.fn() },+ mainComponent: { makeDirty },+ } as never,+ {+ updateConfig$: updateConfig$.asObservable(),+ updateWatermarkConfig,+ } as never,+ { getItem: vi.fn(async () => undefined) } as never,+ { getCurrentUser: vi.fn(() => ({ id: 'u1' })) } as never+ );+ expect(_controller).toBeDefined();++ await waitNextTick();+ expect(updateWatermarkConfig).not.toHaveBeenCalled();+ expect(makeDirty).not.toHaveBeenCalled();+ });+});diff --git a/packages/watermark/src/facade/f-univer.spec.ts b/packages/watermark/src/facade/f-univer.spec.tsnew file mode 100644index 0000000000..b781ea2bc0--- /dev/null+++ b/packages/watermark/src/facade/f-univer.spec.ts@@ -0,0 +1,105 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { describe, expect, it, vi } from 'vitest';++const mocked = vi.hoisted(() => ({+ extendUniver: vi.fn(),+ extendEnum: vi.fn(),+ IWatermarkTypeEnum: {+ Text: 'text',+ Image: 'image',+ },+}));++vi.mock('@univerjs/core/facade', () => {+ class FUniver {+ static extend = mocked.extendUniver;+ }+ class FEnum {+ static extend = mocked.extendEnum;+ }++ return {+ FUniver,+ FEnum,+ };+});++vi.mock('@univerjs/engine-render', () => ({+ IWatermarkTypeEnum: mocked.IWatermarkTypeEnum,+}));++class MockWatermarkService {}++vi.mock('@univerjs/watermark', () => ({+ WatermarkTextBaseConfig: { content: '', repeat: true },+ WatermarkImageBaseConfig: { url: '', width: 100 },+ WatermarkService: MockWatermarkService,+}));++describe('watermark facade', () => {+ it('should register facade mixins and support add/delete watermark', async () => {+ const module = await import('./f-univer');++ expect(mocked.extendUniver).toHaveBeenCalledWith(module.FUniverWatermarkMixin);+ expect(mocked.extendEnum).toHaveBeenCalledWith(module.FWatermarkEnum);++ const updateWatermarkConfig = vi.fn();+ const deleteWatermarkConfig = vi.fn();+ const thisArg = {+ _injector: {+ get: vi.fn(() => ({ updateWatermarkConfig, deleteWatermarkConfig })),+ },+ };++ const textResult = module.FUniverWatermarkMixin.prototype.addWatermark.call(+ thisArg,+ mocked.IWatermarkTypeEnum.Text as never,+ { content: 'hello' } as never+ );+ expect(textResult).toBe(thisArg);+ expect(updateWatermarkConfig).toHaveBeenCalledWith({+ type: mocked.IWatermarkTypeEnum.Text,+ config: { text: { content: 'hello', repeat: true } },+ });++ module.FUniverWatermarkMixin.prototype.addWatermark.call(+ thisArg,+ mocked.IWatermarkTypeEnum.Image as never,+ { url: 'https://img' } as never+ );+ expect(updateWatermarkConfig).toHaveBeenCalledWith({+ type: mocked.IWatermarkTypeEnum.Image,+ config: { image: { url: 'https://img', width: 100 } },+ });++ expect(() =>+ module.FUniverWatermarkMixin.prototype.addWatermark.call(thisArg, 'unknown' as never, {} as never)+ ).toThrow('Unknown watermark type');++ const deleteResult = module.FUniverWatermarkMixin.prototype.deleteWatermark.call(thisArg);+ expect(deleteResult).toBe(thisArg);+ expect(deleteWatermarkConfig).toHaveBeenCalledTimes(1);++ const enumObj = new module.FWatermarkEnum();+ expect(enumObj.IWatermarkTypeEnum).toBe(mocked.IWatermarkTypeEnum);+ });++ it('should run facade entry export', async () => {+ await expect(import('./index')).resolves.toBeDefined();+ });+});diff --git a/packages/watermark/src/facade/f-univer.ts b/packages/watermark/src/facade/f-univer.tsindex 19c8f704a0..9f90d652c0 100644--- a/packages/watermark/src/facade/f-univer.ts+++ b/packages/watermark/src/facade/f-univer.ts@@ -128,5 +128,6 @@ FEnum.extend(FWatermarkEnum);declare module '@univerjs/core/facade' {// eslint-disable-next-line ts/naming-conventioninterface FUniver extends IFUniverWatermarkMixin { }+ // eslint-disable-next-line ts/naming-conventioninterface FEnum extends FWatermarkEnum { }}diff --git a/packages/watermark/src/services/watermark.service.spec.ts b/packages/watermark/src/services/watermark.service.spec.tsnew file mode 100644index 0000000000..01a9e5e4f3--- /dev/null+++ b/packages/watermark/src/services/watermark.service.spec.ts@@ -0,0 +1,59 @@+/**+ * 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 { UNIVER_WATERMARK_STORAGE_KEY } from '@univerjs/engine-render';+import { describe, expect, it, vi } from 'vitest';+import { WatermarkService } from './watermark.service';++describe('WatermarkService', () => {+ it('should get/update/delete/refresh and dispose', async () => {+ const getItem = vi.fn(async () => ({ type: 'text' }));+ const setItem = vi.fn();+ const removeItem = vi.fn();+ const service = new WatermarkService({+ getItem,+ setItem,+ removeItem,+ } as never);++ await expect(service.getWatermarkConfig()).resolves.toEqual({ type: 'text' });+ expect(getItem).toHaveBeenCalledWith(UNIVER_WATERMARK_STORAGE_KEY);++ const updateValues: unknown[] = [];+ const refreshValues: number[] = [];+ service.updateConfig$.subscribe((value) => updateValues.push(value));+ service.refresh$.subscribe((value) => refreshValues.push(value));++ service.updateWatermarkConfig({ type: 'image', config: { image: { url: 'x' } } } as never);+ expect(setItem).toHaveBeenCalledWith(UNIVER_WATERMARK_STORAGE_KEY, {+ type: 'image',+ config: { image: { url: 'x' } },+ });++ service.deleteWatermarkConfig();+ expect(removeItem).toHaveBeenCalledWith(UNIVER_WATERMARK_STORAGE_KEY);+ expect(updateValues).toEqual([+ { type: 'image', config: { image: { url: 'x' } } },+ null,+ ]);++ service.refresh();+ expect(refreshValues.length).toBe(1);+ expect(refreshValues[0]).toBeTypeOf('number');++ service.dispose();+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 095cfad75f..fd7213513c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -16,13 +16,13 @@ importers:devDependencies:'@antfu/eslint-config':specifier: ^7.2.0- version: 7.2.0(@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 7.2.0(@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@commitlint/cli':- specifier: ^20.4.2- version: 20.4.2(@types/[email protected])([email protected])+ specifier: ^20.4.3+ version: 20.4.3(@types/[email protected])([email protected])'@commitlint/config-conventional':- specifier: ^20.4.2- version: 20.4.2+ specifier: ^20.4.3+ version: 20.4.3'@eslint-react/eslint-plugin':specifier: ^2.8.1@@ -31,16 +31,16 @@ importers:version: 1.57.0'@release-it-plugins/workspaces':specifier: ^5.0.3'@release-it/conventional-changelog':specifier: ^10.0.5- version: 10.0.5([email protected])([email protected])([email protected](@types/[email protected])([email protected]))+ version: 10.0.5([email protected])([email protected])([email protected](@types/[email protected])([email protected]))'@types/fs-extra':specifier: ^11.0.4version: 11.0.4'@types/node':- specifier: ^25.3.0- version: 25.3.0+ specifier: ^25.3.5+ version: 25.3.5'@types/react':specifier: 19.2.14version: 19.2.14@@ -55,7 +55,7 @@ importers:version: link:packages/design'@vitejs/plugin-react':specifier: ^5.1.4- version: 5.1.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.1.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))eslint:specifier: 9.39.2version: 9.39.2([email protected])@@ -72,17 +72,17 @@ importers:specifier: ^0.5.2version: 0.5.2([email protected]([email protected]))fs-extra:- specifier: ^11.3.3- version: 11.3.3+ specifier: ^11.3.4+ version: 11.3.4husky:specifier: ^9.1.7version: 9.1.7lint-staged:- specifier: ^16.2.7- version: 16.2.7+ specifier: ^16.3.2+ version: 16.3.2posthog-node:- specifier: ^5.25.0- version: 5.25.0+ specifier: ^5.28.0+ version: 5.28.0([email protected])react:specifier: 19.2.4version: 19.2.4@@ -91,10 +91,10 @@ importers:version: 19.2.4([email protected])release-it:specifier: ^19.2.4- version: 19.2.4(@types/[email protected])([email protected])+ version: 19.2.4(@types/[email protected])([email protected])serve:- specifier: ^14.2.5- version: 14.2.5+ specifier: ^14.2.6+ version: 14.2.6tailwindcss:specifier: 3.4.18version: 3.4.18@@ -102,14 +102,14 @@ importers:specifier: ^4.21.0version: 4.21.0turbo:- specifier: ^2.8.10- version: 2.8.10+ specifier: ^2.8.14+ version: 2.8.14typescript:specifier: ^5.9.3version: 5.9.3vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])common/debugger:dependencies:@@ -167,10 +167,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vue:specifier: ^3.5.27version: 3.5.27([email protected])@@ -324,13 +324,13 @@ importers:'@vitejs/plugin-react':specifier: ^5.1.4- version: 5.1.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.1.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitejs/plugin-vue':specifier: ^6.0.4- version: 6.0.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))+ version: 6.0.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))'@vitest/coverage-istanbul':specifier: ^4.0.18- version: 4.0.18([email protected](@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))+ version: 4.0.18([email protected](@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))autoprefixer:specifier: ^10.4.24version: 10.4.24([email protected])@@ -372,16 +372,16 @@ importers:version: 3.4.18vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-dts:specifier: ^4.5.4- version: 4.5.4(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.5.4(@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vite-plugin-external:specifier: ^6.2.2version: 6.2.2vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])devDependencies:'@types/fs-extra':specifier: ^11.0.4@@ -406,7 +406,7 @@ importers:version: 5.0.1([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))'@storybook/addon-docs':specifier: ^10.2.12- version: 10.2.12(@types/[email protected])([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))+ version: 10.2.12(@types/[email protected])([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))'@storybook/addon-links':specifier: ^10.2.12version: 10.2.12([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))@@ -677,7 +677,7 @@ importers:version: 19.2.4([email protected])react-mosaic-component:specifier: ^6.1.1- version: 6.1.1(@types/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ version: 6.1.1(@types/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])rxjs:specifier: ^7.8.2version: 7.8.2@@ -769,10 +769,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/core:dependencies:@@ -833,10 +833,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/data-validation:dependencies:@@ -861,10 +861,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/design:dependencies:@@ -949,10 +949,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs:dependencies:@@ -974,10 +974,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-drawing:dependencies:@@ -996,10 +996,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-drawing-ui:dependencies:@@ -1051,10 +1051,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-hyper-link:dependencies:@@ -1070,10 +1070,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-hyper-link-ui:dependencies:@@ -1122,10 +1122,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-mention-ui:dependencies:@@ -1165,10 +1165,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-quick-insert-ui:dependencies:@@ -1226,10 +1226,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-thread-comment-ui:dependencies:@@ -1278,10 +1278,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/docs-ui:dependencies:@@ -1336,10 +1336,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/drawing:dependencies:@@ -1361,10 +1361,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/drawing-ui:dependencies:@@ -1407,10 +1407,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/engine-formula:dependencies:@@ -1438,10 +1438,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/engine-render:dependencies:@@ -1470,6 +1470,9 @@ importers:'@univerjs-infra/shared':specifier: workspace:*version: link:../../common/shared+ jest-canvas-mock:+ specifier: ^2.5.2+ version: 2.5.2rxjs:specifier: ^7.8.2version: 7.8.2@@ -1478,10 +1481,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/find-replace:dependencies:@@ -1521,10 +1524,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/network:dependencies:@@ -1543,10 +1546,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/rpc:dependencies:@@ -1565,10 +1568,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/rpc-node:dependencies:@@ -1590,10 +1593,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets:dependencies:@@ -1627,10 +1630,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-conditional-formatting:dependencies:@@ -1661,10 +1664,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-conditional-formatting-ui:dependencies:@@ -1722,10 +1725,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-crosshair-highlight:dependencies:@@ -1771,10 +1774,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-data-validation:dependencies:@@ -1808,10 +1811,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-data-validation-ui:dependencies:@@ -1872,10 +1875,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-drawing:dependencies:@@ -1897,10 +1900,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-drawing-ui:dependencies:@@ -1958,10 +1961,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-filter:dependencies:@@ -1992,10 +1995,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-filter-ui:dependencies:@@ -2050,10 +2053,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-find-replace:dependencies:@@ -2084,10 +2087,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-formula:dependencies:@@ -2121,10 +2124,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-formula-ui:dependencies:@@ -2182,10 +2185,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-graphics:dependencies:@@ -2207,10 +2210,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-hyper-link:dependencies:@@ -2238,10 +2241,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-hyper-link-ui:dependencies:@@ -2305,10 +2308,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-note:dependencies:@@ -2330,10 +2333,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-note-ui:dependencies:@@ -2382,10 +2385,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-numfmt:dependencies:@@ -2410,10 +2413,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-numfmt-ui:dependencies:@@ -2465,10 +2468,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-sort:dependencies:@@ -2490,10 +2493,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-sort-ui:dependencies:@@ -2545,10 +2548,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-table:dependencies:@@ -2573,10 +2576,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-table-ui:dependencies:@@ -2634,10 +2637,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-thread-comment:dependencies:@@ -2665,10 +2668,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-thread-comment-ui:dependencies:@@ -2723,10 +2726,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-ui:dependencies:@@ -2787,10 +2790,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/sheets-zen-editor:dependencies:@@ -2842,10 +2845,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/slides:dependencies:@@ -2864,10 +2867,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/slides-ui:dependencies:@@ -2919,10 +2922,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/telemetry:dependencies:@@ -2938,10 +2941,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/themes:devDependencies:@@ -2950,7 +2953,7 @@ importers:version: link:../../common/sharedvite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/thread-comment:dependencies:@@ -2969,10 +2972,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/thread-comment-ui:dependencies:@@ -3015,10 +3018,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/ui:dependencies:@@ -3073,10 +3076,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/ui-adapter-vue3:dependencies:@@ -3095,10 +3098,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vue:specifier: ^3.5.27version: 3.5.27([email protected])@@ -3123,10 +3126,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/uniscript:dependencies:@@ -3169,10 +3172,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages/watermark:dependencies:@@ -3194,10 +3197,10 @@ importers:version: 5.9.3vite:specifier: ^7.3.1- version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])tests/formula-integration:dependencies:@@ -3249,7 +3252,7 @@ importers:version: 5.9.3vitest:specifier: ^4.0.18- version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])packages:@@ -3536,73 +3539,73 @@ packages:'@clack/[email protected]':resolution: {integrity: sha512-pMN5FcrEw9hUkZA4f+zLlzivQSeQf5dRGJjSUbvVYDLvpKCdQx5OaknvKzgbtXOizhP+SJJJjqEbOe55uKKfAw==}- '@commitlint/[email protected]':- resolution: {integrity: sha512-YjYSX2yj/WsVoxh9mNiymfFS2ADbg2EK4+1WAsMuckwKMCqJ5PDG0CJU/8GvmHWcv4VRB2V02KqSiecRksWqZQ==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-Z37EMoDT7+Upg500vlr/vZrgRsb6Xc5JAA3Tv7BYbobnN/ZpqUeZnSLggBg2+1O+NptRDtyujr2DD1CPV2qwhA==}engines: {node: '>=v18'}hasBin: true- '@commitlint/[email protected]':- resolution: {integrity: sha512-rwkTF55q7Q+6dpSKUmJoScV0f3EpDlWKw2UPzklkLS4o5krMN1tPWAVOgHRtyUTMneIapLeQwaCjn44Td6OzBQ==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-9RtLySbYQAs8yEqWEqhSZo9nYhbm57jx7qHXtgRmv/nmeQIjjMcwf6Dl+y5UZcGWgWx435TAYBURONaJIuCjWg==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-zShmKTF+sqyNOfAE0vKcqnpvVpG0YX8F9G/ZIQHI2CoKyK+PSdladXMSns400aZ5/QZs+0fN75B//3Q5CHw++w==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-jCZpZFkcSL3ZEdL5zgUzFRdytv3xPo8iukTe9VA+QGus/BGhpp1xXSVu2B006GLLb2gYUAEGEqv64kTlpZNgmA==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-WLQqaFx1pBooiVvBrA1YfJNFqZF8wS/YGOtr5RzApDbV9tQ52qT5VkTsY65hFTnXhW8PcDfZLaknfJTmPejmlw==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-WcXGKBNn0wBKpX8VlXgxqedyrLxedIlLBCMvdamLnJFEbUGJ9JZmBVx4vhLV3ZyA8uONGOb+CzW0Y9HDbQ+ONQ==}engines: {node: '>=v18'}'@commitlint/[email protected]':resolution: {integrity: sha512-xyCoOShoPuPL44gVa+5EdZsBVao/pNzpQhkzq3RdtlFdKZtjWcLlUFQHSWBuhk5utKYykeJPSz2i8ABHQA+ZZw==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-i3ki3WR0rgolFVX6r64poBHXM1t8qlFel1G1eCBvVgntE3fCJitmzSvH5JD/KVJN/snz6TfaX2CLdON7+s4WVQ==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-UDJVErjLbNghop6j111rsHJYGw6MjCKAi95K0GT2yf4eeiDHy3JDRLWYWEjIaFgO+r+dQSkuqgJ1CdMTtrvHsA==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-In5EO4JR1lNsAv1oOBBO24V9ND1IqdAJDKZiEpdfjDl2HMasAcT7oA+5BKONv1pRoLG380DGPE2W2RIcUwdgLA==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-W5VQKZ7fdJ1X3Tko+h87YZaqRMGN1KvQKXyCM8xFdxzMIf1KCZgN4uLz3osLB1zsFcVS4ZswHY64LI26/9ACag==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-buquzNRtFng6xjXvBU1abY/WPEEjCgUipNQrNmIWe8QuJ6LWLtei/LDBAzEe5ASm45+Q9L2Xi3/GVvlj50GAug==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-CYOXL23e+nRKij81+d0+dymtIi7Owl9QzvblJYbEfInON/4MaETNSLFDI74LDu+YJ0ML5HZyw9Vhp9QpckwQ0A==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-Dauup/GfjwffBXRJUdlX/YRKfSVXsXZLnINXKz0VZkXdKDcaEILAi9oflHGbfydonJnJAbXEbF3nXPm9rm3G6A==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-3cdJOUVP+VcgHa7bhJoWS+Z8mBNXB5aLWMBu7Q7uX8PSeWDzdbrBlR33J1MGGf7r1PZDp+mPPiFktk031PgdRw==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-B5lGtvHgiLAIsK5nLINzVW0bN5hXv+EW35sKhYHE8F7V9Uz1fR4tx3wt7mobA5UNhZKUNgB/+ldVMQE6IHZRyA==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-6akwCYrzcrFcTYz9GyUaWlhisY4lmQ3KvrnabmhoeAV8nRH4dXJAh4+EUQ3uArtxxKQkvxJS78hNX2EU3USgxQ==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-XNtZjeRcFuAfUnhYrCY02+mpxwY4OmnvD3ETbVPs25xJFFz1nRo/25nHj+5eM+zTeRFvWFwD4GXWU2JEtoK1/w==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-hzC3JCo3zs3VkQ833KnGVuWjWIzR72BWZWjQM7tY/7dfKreKAm7fEsy71tIFCRtxf2RtMP2d3RLF1U9yhFSccA==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-QfpFn6/I240ySEGv7YWqho4vxqtPpx40FS7kZZDjUJ+eHxu3azfhy7fFb5XzfTqVNp1hNoI3tEmiEPbDB44+cg==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-j42OWv3L31WfnP8WquVjHZRt03w50Y/gEE8FAyih7GQTrIv2+pZ6VZ6pWLD/ml/3PO+RV2SPtRtTp/MvlTb8rQ==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-ay1KM8q0t+/OnlpqXJ+7gEFQNlUtSU5Gxr8GEwnVf2TPN3+ywc5DzL3JCxmpucqxfHBTFwfRMXxPRRnR5Ki20g==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-QucxcOy+00FhS9s4Uy0OyS5HeUV+hbC6OLqkTSIm6fwMdKva+OEavaCDuLtgd9akZZlsUo//XzSmPP3sLKBPog==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-oz83pnp5Yq6uwwTAabuVQPNlPfeD2Y5ZjMb7Wx8FSUlu4sLYJjbBWt8031Z0osCFPfHzAwSYrjnfDFKtuSMdKg==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-Yuosd7Grn5qiT7FovngXLyRXTMUbj9PYiSkvUgWK1B5a7+ZvrbWDS7epeUapYNYatCy/KTpPFPbgLUdE+MUrBg==}engines: {node: '>=v18'}'@commitlint/[email protected]':resolution: {integrity: sha512-2l9gmwiCRqZNWgV+pX1X7z4yP0b3ex/86UmUFgoRt672Ez6cAM2lOQeHFRUTuE6sPpi8XBCGnd8Kh3bMoyHwJw==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-NDzq8Q6jmFaIIBC/GG6n1OQEaHdmaAAYdrZRlMgW6glYWGZ+IeuXmiymDvQNXPc82mVxq2KiE3RVpcs+1OeDeA==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-qD9xfP6dFg5jQ3NMrOhG0/w5y3bBUsVGyJvXxdWEwBm8hyx4WOk3kKXw28T5czBYvyeCVJgJJ6aoJZUWDpaacQ==}engines: {node: '>=v18'}- '@commitlint/[email protected]':- resolution: {integrity: sha512-aO5l99BQJ0X34ft8b0h7QFkQlqxC6e7ZPVmBKz13xM9O8obDaM1Cld4sQlJDXXU/VFuUzQ30mVtHjVz74TuStw==}+ '@commitlint/[email protected]':+ resolution: {integrity: sha512-51OWa1Gi6ODOasPmfJPq6js4pZoomima4XLZZCrkldaH2V5Nb3bVhNXPeT6XV0gubbainSpTw4zi68NqAeCNCg==}engines: {node: '>=v18'}'@conventional-changelog/[email protected]':@@ -4966,8 +4969,8 @@ packages:engines: {node: '>=18'}hasBin: true- '@posthog/[email protected]':- resolution: {integrity: sha512-GViD5mOv/mcbZcyzz3z9CS0R79JzxVaqEz4sP5Dsea178M/j3ZWe6gaHDZB9yuyGfcmIMQ/8K14yv+7QrK4sQQ==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-zTDdda9NuSHrnwSOfFMxX/pyXiycF4jtU1kTr8DL61dHhV+7LF6XF1ndRZZTuaGGbfbb/GJYkEsjEX9SXfNZeQ==}'@radix-ui/[email protected]':resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==}@@ -5527,6 +5530,10 @@ packages:resolution: {integrity: sha512-6rsHTjodIn/t90lv5snQjRPVtOosM7Vp0AKdrObymq45ojlgVwnpAqdc+0OBBrpEiy31zZ6/TKeIVqV1HwvnuQ==}engines: {node: '>=18'}+ '@simple-libs/[email protected]':+ resolution: {integrity: sha512-KxXvfapcixpz6rVEB6HPjOUZT22yN6v0vI0urQSk1L8MlEWPDFCZkhw2xmkyoTGYeFw7tWTZd7e3lVzRZRN/EA==}+ engines: {node: '>=18'}+'@sindresorhus/[email protected]':resolution: {integrity: sha512-TeheYy0ILzBEI/CO55CP6zJCSdSWeRtGnHy8U8dWSUH4I68iqTsy7HkMktR4xakThc9jotkPQUXT4ITdbV7cHA==}engines: {node: '>=18'}@@ -5851,6 +5858,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A==}+ '@types/[email protected]':+ resolution: {integrity: sha512-oX8xrhvpiyRCQkG1MFchB09f+cXftgIXb3a7UUa4Y3wpmZPw5tyZGTLWhlESOLq1Rq6oDlc8npVU2/9xiCuXMA==}+'@types/[email protected]':resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==}@@ -6741,8 +6751,8 @@ packages:resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}engines: {node: '>=18'}- resolution: {integrity: sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==}+ resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}engines: {node: '>=20'}@@ -6810,10 +6820,18 @@ packages:resolution: {integrity: sha512-GGf2Nipn1RUCAktxuVauVr1e3r8QrLP/B0lEUsFktmGqc3ddbQkhoJZHJctVU829U1c6mTSWftrVOCHaL85Q3w==}engines: {node: '>=18'}+ resolution: {integrity: sha512-DOuBwYSqWzfwuRByY9O4oOIvDlkUCTDzfbOgcSbkY+imXXj+4tmrEFao3K+FxemClYfYnZzsvudbwrhje9VHDA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-MnbEysR8wWa8dAEvbj5xcBgJKQlX/m0lhS8DsyAAWDHdfs2faDJxTgzRYlRYpXSe7UiKrIIlB4TrBKU9q9DgkA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-kYFx6gAyjSIMwNtASkI3ZE99U1fuVDJr0yTYgVy+I2QG46zNZfl2her+0+eoviG82c5WQvW1jMt1eOQTeJLodA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-SetDSntXLk8Jh1NOAl1Gu5uLiCNSYenB5tm0YVeZKePRIgDW9lQImromTwLa3c/Gae298tsgOM+/CYT9XAl0NA==}engines: {node: '>=18'}@@ -6837,6 +6855,11 @@ packages:engines: {node: '>=18'}hasBin: true+ resolution: {integrity: sha512-RfOq/Cqy9xV9bOA8N+ZH6DlrDR+5S3Mi0B5kACEjESpE+AviIpAptx9a9cFpWCCvgRtWT+0BbUw+e1BZfts9jg==}+ engines: {node: '>=18'}+ hasBin: true+resolution: {integrity: sha512-lqIdmw330QdMBgfL0e6+6q5OMKyIpy4OZNmepit6FS3GldhkG+70drZjuZ0A5NFpze5j85dlYs3GabQXl6sMHw==}engines: {node: '>=18'}@@ -6874,6 +6897,15 @@ packages:typescript:optional: true+ resolution: {integrity: sha512-hr4ihw+DBqcvrsEDioRO31Z17x71pUYoNe/4h6Z0wB72p7MU7/9gH8Q3s12NFhHPfYBBOV3qyfUxmr/Yn3shnQ==}+ engines: {node: '>=14'}+ peerDependencies:+ typescript: '>=4.9.5'+ peerDependenciesMeta:+ typescript:+ optional: true+resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}engines: {node: '>= 8'}@@ -7820,6 +7852,10 @@ packages:resolution: {integrity: sha512-VWSRii4t0AFm6ixFFmLLx1t7wS1gh+ckoa84aOeapGum0h+EZd1EhEumSB+ZdDLnEPuucsVB9oB7cxJHap6Afg==}engines: {node: '>=14.14'}+ resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==}+ engines: {node: '>=14.14'}+resolution: {integrity: sha512-QMUezzXWII9EV5aTFXW1UBVUO77wYPpjqIF8/AviUCThNeSYZykpoTixUeaNNBwmCev0AMDWMAni+f8Hxb1IFw==}@@ -7907,6 +7943,7 @@ packages:resolution: {integrity: sha512-ICsMM1Wk8xSGMowkOmPrzo2Fgmfo4bMHLNX6ytHjajRJUqvHOw/TFapQ+QG75c3X/tTDDhOSRPGC52dDbNM8FQ==}engines: {node: '>=16'}+ deprecated: This package is no longer maintained. For the JavaScript API, please use @conventional-changelog/git-client instead.hasBin: true@@ -8550,8 +8587,8 @@ packages:resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}- resolution: {integrity: sha512-lDIj4RnYmK7/kXMya+qJsmkRFkGolciXjrsZ6PC25GdTfWOAWetR0ZbsNXRAj1EHHImRSalc+whZFg56F5DVow==}+ resolution: {integrity: sha512-xKqhC2AeXLwiAHXguxBjuChoTTWFC6Pees0SHPwOpwlvI3BH7ZADFPddAdN3pgo3aiKgPUx/bxE78JfUnxQnlg==}engines: {node: '>=20.17'}hasBin: true@@ -8922,6 +8959,9 @@ packages:resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}+ resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}+resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==}engines: {node: '>=16 || 14 >=14.17'}@@ -8973,10 +9013,6 @@ packages:resolution: {integrity: sha512-S24aGsn+HLBxUGVAUFOwGpKs7LBcG4RudKU//eWzt/mQ97/NMKQxDWHyHx63UNWk/OOdihgmzoETn1tf5nQDzQ==}- resolution: {integrity: sha512-tacvGzUY5o2D8CBh2rrwxyNojUsZNU2zjNTzKQrkgGJQTbGAfArVWXSKMBokBeeg6C7OLRGUEyoFlYbfeWQIqw==}- engines: {node: '>=20.17'}-resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}@@ -9306,11 +9342,6 @@ packages:resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}engines: {node: '>=12'}- resolution: {integrity: sha512-eG2dWTVw5bzqGRztnHExczNxt5VGsE6OwTeCG3fdUf9KBsZzO3R5OIIIzWR+iZA0NtZ+RDVdaoE2dK1cn6jH4g==}- engines: {node: '>=0.10'}- hasBin: true-resolution: {integrity: sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==}engines: {node: '>=0.10.0'}@@ -9603,9 +9634,14 @@ packages:resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}engines: {node: ^10 || ^12 || >=14}- resolution: {integrity: sha512-DFE5lZAoD6hk7RATuT8qVQ7KFgFP5YlFTJciMbU2qq6NX0A8eJxiJcmEsMnB3g30jJJ9suiwGIq4I8ESwf9bZg==}+ resolution: {integrity: sha512-EETYV0zA+7BLQmXzY+vGyDMoQK8uHf8f/1utbRjKncI41gPkw+4piGP7l4UT5Luld+4vQpJPOR1q1YrbXm7XjQ==}engines: {node: ^20.20.0 || >=22.22.0}+ peerDependencies:+ rxjs: ^7.0.0+ peerDependenciesMeta:+ rxjs:+ optional: trueresolution: {integrity: sha512-ESF23V4SKG6lVSGZgYNpbsiaAkdab6ZgOxe52p7+Kid3W3u3bxR4Vfd/o21dmN7jSt0IwgZ4v5MUd26FEtXE9w==}@@ -10074,11 +10110,11 @@ packages:resolution: {integrity: sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==}- resolution: {integrity: sha512-x5RL9Y2p5+Sh3D38Fh9i/iQ5ZK+e4xuXRd/pGbM4D13tgo/MGwbttUk8emytcr1YYzBYs+apnUngBDFYfpjPuQ==}+ resolution: {integrity: sha512-CinAq1xWb0vR3twAv9evEU8cNWkXCb9kd5ePAHUKJBkOsUpR1wt/CvGdeca7vqumL1U5cSaeVQ6zZMxiJ3yWsg==}- resolution: {integrity: sha512-Qn/qMkzCcMFVPb60E/hQy+iRLpiU8PamOfOSYoAHmmF+fFFmpPpqa6Oci2iWYpTdOUM3VF+TINud7CfbQnsZbA==}+ resolution: {integrity: sha512-QEjUSA+sD4Rotm1znR8s50YqA3kYpRGPmtd5GlFxbaL9n/FdUNbqMhxClqdditSk0LlZyA/dhud6XNRTOC9x2Q==}engines: {node: '>= 14'}hasBin: true@@ -10289,10 +10325,6 @@ packages:resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}engines: {node: '>=8'}- resolution: {integrity: sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==}- engines: {node: '>=12'}-resolution: {integrity: sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==}engines: {node: '>=12'}@@ -10540,38 +10572,38 @@ packages:engines: {node: '>=18.0.0'}hasBin: true- resolution: {integrity: sha512-A03fXh+B7S8mL3PbdhTd+0UsaGrhfyPkODvzBDpKRY7bbeac4MDFpJ7I+Slf2oSkCEeSvHKR7Z4U71uKRUfX7g==}+ resolution: {integrity: sha512-9sFi7n2lLfEsGWi5OEoA/eTtQU2BPKtzSYKqufMtDeRmqMT9vKjbv9gJCRkllSVE9BOXA0qXC3diyX8V8rKIKw==}cpu: [x64]os: [darwin]- resolution: {integrity: sha512-sidzowgWL3s5xCHLeqwC9M3s9M0i16W1nuQF3Mc7fPHpZ+YPohvcbVFBB2uoRRHYZg6yBnwD4gyUHKTeXfwtXA==}+ resolution: {integrity: sha512-aS4yJuy6A1PCLws+PJpZP0qCURG8Y5iVx13z/WAbKyeDTY6W6PiGgcEllSaeLGxyn++382ztN/EZH85n2zZ6VQ==}cpu: [arm64]os: [darwin]- resolution: {integrity: sha512-YK9vcpL3TVtqonB021XwgaQhY9hJJbKKUhLv16osxV0HkcQASQWUqR56yMge7puh6nxU67rQlTq1b7ksR1T3KA==}+ resolution: {integrity: sha512-XC6wPUDJkakjhNLaS0NrHDMiujRVjH+naEAwvKLArgqRaFkNxjmyNDRM4eu3soMMFmjym6NTxYaF74rvET+Orw==}cpu: [x64]os: [linux]- resolution: {integrity: sha512-3+j2tL0sG95iBJTm+6J8/45JsETQABPqtFyYjVjBbi6eVGdtNTiBmHNKrbvXRlQ3ZbUG75bKLaSSDHSEEN+btQ==}+ resolution: {integrity: sha512-ChfE7isyVNjZrVSPDwcfqcHLG/FuIBbOFxnt1FM8vSuBGzHAs8AlTdwFNIxlEMJfZ8Ad9mdMxdmsCUPIWiQ6cg==}cpu: [arm64]os: [linux]- resolution: {integrity: sha512-hdeF5qmVY/NFgiucf8FW0CWJWtyT2QPm5mIsX0W1DXAVzqKVXGq+Zf+dg4EUngAFKjDzoBeN6ec2Fhajwfztkw==}+ resolution: {integrity: sha512-FTbIeQL1ycLFW2t9uQNMy+bRSzi3Xhwun/e7ZhFBdM+U0VZxxrtfYEBM9CHOejlfqomk6Jh7aRz0sJoqYn39Hg==}cpu: [x64]os: [win32]- resolution: {integrity: sha512-QGdr/Q8LWmj+ITMkSvfiz2glf0d7JG0oXVzGL3jxkGqiBI1zXFj20oqVY0qWi+112LO9SVrYdpHS0E/oGFrMbQ==}+ resolution: {integrity: sha512-KgZX12cTyhY030qS7ieT8zRkhZZE2VWJasDFVUSVVn17nR7IShpv68/7j5UqJNeRLIGF1XPK0phsP5V5yw3how==}cpu: [arm64]os: [win32]- resolution: {integrity: sha512-OxbzDES66+x7nnKGg2MwBA1ypVsZoDTLHpeaP4giyiHSixbsiTaMyeJqbEyvBdp5Cm28fc+8GG6RdQtic0ijwQ==}+ resolution: {integrity: sha512-UCTxeMNYT1cKaHiIFdLCQ7ulI+jw5i5uOnJOrRXsgUD7G3+OjlUjwVd7JfeVt2McWSVGjYA3EVW/v1FSsJ5DtA==}hasBin: true@@ -11101,7 +11133,7 @@ snapshots:'@alloc/[email protected]': {}- '@antfu/[email protected](@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@antfu/[email protected](@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@vue/[email protected])([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]([email protected])))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@antfu/install-pkg': 1.1.0'@clack/prompts': 0.11.0@@ -11110,7 +11142,7 @@ snapshots:'@stylistic/eslint-plugin': 5.7.1([email protected]([email protected]))'@typescript-eslint/eslint-plugin': 8.54.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- '@vitest/eslint-plugin': 1.6.6([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/eslint-plugin': 1.6.6([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))ansis: 4.2.0cac: 6.7.14eslint: 9.39.2([email protected])@@ -11415,7 +11447,7 @@ snapshots:'@babel/parser': 7.27.2'@babel/template': 7.27.2'@babel/types': 7.27.1- debug: 4.4.1+ debug: 4.4.3globals: 11.12.0transitivePeerDependencies:- supports-color@@ -11428,7 +11460,7 @@ snapshots:'@babel/parser': 7.28.3'@babel/template': 7.27.2'@babel/types': 7.28.2- debug: 4.4.1+ debug: 4.4.3transitivePeerDependencies:- supports-color@@ -11440,7 +11472,7 @@ snapshots:'@babel/parser': 7.28.4'@babel/template': 7.27.2'@babel/types': 7.28.4- debug: 4.4.1+ debug: 4.4.3transitivePeerDependencies:- supports-color@@ -11516,32 +11548,32 @@ snapshots:picocolors: 1.1.1sisteransi: 1.0.5dependencies:- '@commitlint/format': 20.4.0- '@commitlint/lint': 20.4.2- '@commitlint/load': 20.4.0(@types/[email protected])([email protected])- '@commitlint/read': 20.4.0- '@commitlint/types': 20.4.0+ '@commitlint/format': 20.4.3+ '@commitlint/lint': 20.4.3+ '@commitlint/load': 20.4.3(@types/[email protected])([email protected])+ '@commitlint/read': 20.4.3+ '@commitlint/types': 20.4.3tinyexec: 1.0.2yargs: 17.7.2transitivePeerDependencies:- '@types/node'- typescript- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/types': 20.4.0- conventional-changelog-conventionalcommits: 9.1.0+ '@commitlint/types': 20.4.3+ conventional-changelog-conventionalcommits: 9.3.0- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/types': 20.4.0+ '@commitlint/types': 20.4.3ajv: 8.18.0- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/types': 20.4.0+ '@commitlint/types': 20.4.3lodash.camelcase: 4.3.0lodash.kebabcase: 4.1.1lodash.snakecase: 4.1.1@@ -11550,31 +11582,31 @@ snapshots:'@commitlint/[email protected]': {}- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/types': 20.4.0+ '@commitlint/types': 20.4.3picocolors: 1.1.1- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/types': 20.4.0+ '@commitlint/types': 20.4.3semver: 7.7.4- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/is-ignored': 20.4.1- '@commitlint/parse': 20.4.1- '@commitlint/rules': 20.4.2- '@commitlint/types': 20.4.0+ '@commitlint/is-ignored': 20.4.3+ '@commitlint/parse': 20.4.3+ '@commitlint/rules': 20.4.3+ '@commitlint/types': 20.4.3dependencies:- '@commitlint/config-validator': 20.4.0+ '@commitlint/config-validator': 20.4.3'@commitlint/execute-rule': 20.0.0- '@commitlint/resolve-extends': 20.4.0- '@commitlint/types': 20.4.0- cosmiconfig: 9.0.0([email protected])- cosmiconfig-typescript-loader: 6.2.0(@types/[email protected])([email protected]([email protected]))([email protected])+ '@commitlint/resolve-extends': 20.4.3+ '@commitlint/types': 20.4.3+ cosmiconfig: 9.0.1([email protected])+ cosmiconfig-typescript-loader: 6.2.0(@types/[email protected])([email protected]([email protected]))([email protected])is-plain-obj: 4.1.0lodash.mergewith: 4.6.2picocolors: 1.1.1@@ -11582,47 +11614,47 @@ snapshots:- '@types/node'- typescript- '@commitlint/[email protected]': {}+ '@commitlint/[email protected]': {}- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/types': 20.4.0- conventional-changelog-angular: 8.1.0- conventional-commits-parser: 6.2.1+ '@commitlint/types': 20.4.3+ conventional-changelog-angular: 8.3.0+ conventional-commits-parser: 6.3.0- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/top-level': 20.4.0- '@commitlint/types': 20.4.0+ '@commitlint/top-level': 20.4.3+ '@commitlint/types': 20.4.3git-raw-commits: 4.0.0minimist: 1.2.8tinyexec: 1.0.2- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/config-validator': 20.4.0- '@commitlint/types': 20.4.0+ '@commitlint/config-validator': 20.4.3+ '@commitlint/types': 20.4.3global-directory: 4.0.1import-meta-resolve: 4.2.0lodash.mergewith: 4.6.2resolve-from: 5.0.0- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- '@commitlint/ensure': 20.4.1- '@commitlint/message': 20.4.0+ '@commitlint/ensure': 20.4.3+ '@commitlint/message': 20.4.3'@commitlint/to-lines': 20.0.0- '@commitlint/types': 20.4.0+ '@commitlint/types': 20.4.3'@commitlint/[email protected]': {}- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:escalade: 3.2.0- '@commitlint/[email protected]':+ '@commitlint/[email protected]':dependencies:- conventional-commits-parser: 6.2.1+ conventional-commits-parser: 6.3.0picocolors: 1.1.1@@ -12353,128 +12385,128 @@ snapshots:'@inquirer/[email protected]': {}- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/ansi': 1.0.2- '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])'@inquirer/figures': 1.0.15- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])yoctocolors-cjs: 2.1.3optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/ansi': 1.0.2'@inquirer/figures': 1.0.15- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])cli-width: 4.1.0mute-stream: 2.0.0signal-exit: 4.1.0wrap-ansi: 6.2.0yoctocolors-cjs: 2.1.3optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/external-editor': 1.0.3(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/external-editor': 1.0.3(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])yoctocolors-cjs: 2.1.3optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:chardet: 2.1.1iconv-lite: 0.7.1optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@inquirer/[email protected]': {}- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/ansi': 1.0.2- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])optionalDependencies:- '@types/node': 25.3.0-- '@inquirer/[email protected](@types/[email protected])':- dependencies:- '@inquirer/checkbox': 4.3.2(@types/[email protected])- '@inquirer/confirm': 5.1.21(@types/[email protected])- '@inquirer/editor': 4.2.23(@types/[email protected])- '@inquirer/expand': 4.0.23(@types/[email protected])- '@inquirer/input': 4.3.1(@types/[email protected])- '@inquirer/number': 3.0.23(@types/[email protected])- '@inquirer/password': 4.0.23(@types/[email protected])- '@inquirer/rawlist': 4.1.11(@types/[email protected])- '@inquirer/search': 3.2.2(@types/[email protected])- '@inquirer/select': 4.4.2(@types/[email protected])+ '@types/node': 25.3.5++ '@inquirer/[email protected](@types/[email protected])':+ dependencies:+ '@inquirer/checkbox': 4.3.2(@types/[email protected])+ '@inquirer/confirm': 5.1.21(@types/[email protected])+ '@inquirer/editor': 4.2.23(@types/[email protected])+ '@inquirer/expand': 4.0.23(@types/[email protected])+ '@inquirer/input': 4.3.1(@types/[email protected])+ '@inquirer/number': 3.0.23(@types/[email protected])+ '@inquirer/password': 4.0.23(@types/[email protected])+ '@inquirer/rawlist': 4.1.11(@types/[email protected])+ '@inquirer/search': 3.2.2(@types/[email protected])+ '@inquirer/select': 4.4.2(@types/[email protected])optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])yoctocolors-cjs: 2.1.3optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:- '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])'@inquirer/figures': 1.0.15- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])yoctocolors-cjs: 2.1.3optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':dependencies:'@inquirer/ansi': 1.0.2- '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])'@inquirer/figures': 1.0.15- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])yoctocolors-cjs: 2.1.3optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@inquirer/[email protected](@types/[email protected])':+ '@inquirer/[email protected](@types/[email protected])':optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@inversifyjs/[email protected]': {}@@ -12571,23 +12603,23 @@ snapshots:'@types/react': 19.2.14react: 19.2.4- '@microsoft/[email protected](@types/[email protected])':+ '@microsoft/[email protected](@types/[email protected])':dependencies:'@microsoft/tsdoc': 0.15.1'@microsoft/tsdoc-config': 0.17.1- '@rushstack/node-core-library': 5.13.1(@types/[email protected])+ '@rushstack/node-core-library': 5.13.1(@types/[email protected])transitivePeerDependencies:- '@types/node'- '@microsoft/[email protected](@types/[email protected])':+ '@microsoft/[email protected](@types/[email protected])':dependencies:- '@microsoft/api-extractor-model': 7.30.6(@types/[email protected])+ '@microsoft/api-extractor-model': 7.30.6(@types/[email protected])'@microsoft/tsdoc': 0.15.1'@microsoft/tsdoc-config': 0.17.1- '@rushstack/node-core-library': 5.13.1(@types/[email protected])+ '@rushstack/node-core-library': 5.13.1(@types/[email protected])'@rushstack/rig-package': 0.5.3- '@rushstack/terminal': 0.15.3(@types/[email protected])- '@rushstack/ts-command-line': 5.0.1(@types/[email protected])+ '@rushstack/terminal': 0.15.3(@types/[email protected])+ '@rushstack/ts-command-line': 5.0.1(@types/[email protected])lodash: 4.17.21minimatch: 3.0.8resolve: 1.22.10@@ -12815,7 +12847,7 @@ snapshots:dependencies:playwright: 1.57.0- '@posthog/[email protected]':+ '@posthog/[email protected]':dependencies:cross-spawn: 7.0.6@@ -13171,19 +13203,19 @@ snapshots:'@react-dnd/[email protected]': {}- '@release-it-plugins/[email protected]([email protected](@types/[email protected])([email protected]))':+ '@release-it-plugins/[email protected]([email protected](@types/[email protected])([email protected]))':dependencies:detect-indent: 6.1.0detect-newline: 3.1.0execa: 8.0.1- release-it: 19.2.4(@types/[email protected])([email protected])+ release-it: 19.2.4(@types/[email protected])([email protected])semver: 7.7.2url-join: 4.0.1validate-peer-dependencies: 1.2.0walk-sync: 2.2.0yaml: 2.8.0- '@release-it/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected]))':+ '@release-it/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected]))':dependencies:'@conventional-changelog/git-client': 2.5.1([email protected])([email protected])concat-stream: 2.0.0@@ -13191,7 +13223,7 @@ snapshots:conventional-changelog-angular: 8.1.0conventional-changelog-conventionalcommits: 9.1.0conventional-recommended-bump: 11.2.0- release-it: 19.2.4(@types/[email protected])([email protected])+ release-it: 19.2.4(@types/[email protected])([email protected])semver: 7.7.4transitivePeerDependencies:- conventional-commits-filter@@ -13284,34 +13316,34 @@ snapshots:'@rollup/[email protected]':optional: true- '@rushstack/[email protected](@types/[email protected])':+ '@rushstack/[email protected](@types/[email protected])':dependencies:ajv: 8.13.0ajv-draft-04: 1.0.0([email protected])ajv-formats: 3.0.1([email protected])- fs-extra: 11.3.3+ fs-extra: 11.3.4import-lazy: 4.0.0jju: 1.4.0resolve: 1.22.10semver: 7.5.4optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@rushstack/[email protected]':dependencies:resolve: 1.22.10strip-json-comments: 3.1.1- '@rushstack/[email protected](@types/[email protected])':+ '@rushstack/[email protected](@types/[email protected])':dependencies:- '@rushstack/node-core-library': 5.13.1(@types/[email protected])+ '@rushstack/node-core-library': 5.13.1(@types/[email protected])supports-color: 8.1.1optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5- '@rushstack/[email protected](@types/[email protected])':+ '@rushstack/[email protected](@types/[email protected])':dependencies:- '@rushstack/terminal': 0.15.3(@types/[email protected])+ '@rushstack/terminal': 0.15.3(@types/[email protected])'@types/argparse': 1.0.38argparse: 1.0.10string-argv: 0.3.2@@ -13327,14 +13359,16 @@ snapshots:dependencies:'@types/node': 22.19.11+ '@simple-libs/[email protected]': {}+'@sindresorhus/[email protected]': {}'@standard-schema/[email protected]': {}- '@storybook/[email protected](@types/[email protected])([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))':+ '@storybook/[email protected](@types/[email protected])([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))':dependencies:'@mdx-js/react': 3.1.1(@types/[email protected])([email protected])- '@storybook/csf-plugin': 10.2.12([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))+ '@storybook/csf-plugin': 10.2.12([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))'@storybook/react-dom-shim': 10.2.12([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))react: 19.2.4@@ -13401,14 +13435,14 @@ snapshots:storybook: 10.2.12(@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected])ts-dedent: 2.2.0- '@storybook/[email protected]([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))':+ '@storybook/[email protected]([email protected])([email protected])([email protected](@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@swc/[email protected])([email protected]))':dependencies:storybook: 10.2.12(@testing-library/[email protected])([email protected])([email protected]([email protected]))([email protected])unplugin: 2.3.11optionalDependencies:esbuild: 0.27.3rollup: 4.55.1- vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])webpack: 5.103.0(@swc/[email protected])([email protected])'@storybook/[email protected]': {}@@ -13655,7 +13689,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@types/[email protected]': {}@@ -13687,6 +13721,10 @@ snapshots:dependencies:undici-types: 7.18.2+ '@types/[email protected]':+ dependencies:+ undici-types: 7.18.2+'@types/[email protected]': {}'@types/[email protected]': {}@@ -13719,7 +13757,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@types/[email protected]': {}@@ -13731,7 +13769,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:@@ -13885,7 +13923,7 @@ snapshots:throttleit: 2.1.0undici: 6.23.0- '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.29.0'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])@@ -13893,17 +13931,17 @@ snapshots:'@rolldown/pluginutils': 1.0.0-rc.3'@types/babel__core': 7.20.5react-refresh: 0.18.0- vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color- '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))':+ '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]([email protected]))':dependencies:'@rolldown/pluginutils': 1.0.0-rc.2- vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vue: 3.5.27([email protected])- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])([email protected])([email protected]))':dependencies:'@istanbuljs/schema': 0.1.3'@jridgewell/gen-mapping': 0.3.13@@ -13915,18 +13953,18 @@ snapshots:magicast: 0.5.1obug: 2.1.1tinyrainbow: 3.0.3- vitest: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color- '@vitest/[email protected]([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@typescript-eslint/scope-manager': 8.54.0eslint: 9.39.2([email protected])optionalDependencies:typescript: 5.9.3- vitest: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vitest: 4.0.18(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -13947,13 +13985,13 @@ snapshots:chai: 6.2.2tinyrainbow: 3.0.3- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 4.0.18estree-walker: 3.0.3magic-string: 0.30.21optionalDependencies:- vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])'@vitest/[email protected]':dependencies:@@ -14446,7 +14484,7 @@ snapshots:base-log-factory: 2.1.4blf-colorful-appender: 1.0.6date-manip: 2.0.6- debug: 4.4.1+ debug: 4.4.3transitivePeerDependencies:- supports-color@@ -14701,7 +14739,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -14771,10 +14809,18 @@ snapshots:dependencies:compare-func: 2.0.0+ dependencies:+ compare-func: 2.0.0+dependencies:compare-func: 2.0.0+ dependencies:+ compare-func: 2.0.0+@@ -14803,6 +14849,11 @@ snapshots:dependencies:meow: 13.2.0+ dependencies:+ '@simple-libs/stream-utils': 1.2.0+ meow: 13.2.0+dependencies:'@conventional-changelog/git-client': 2.5.1([email protected])([email protected])@@ -14817,10 +14868,10 @@ snapshots:dependencies:browserslist: 4.28.1- [email protected](@types/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected]):dependencies:- '@types/node': 25.3.0- cosmiconfig: 9.0.0([email protected])+ '@types/node': 25.3.5+ cosmiconfig: 9.0.1([email protected])jiti: 2.6.1typescript: 5.9.3@@ -14842,6 +14893,15 @@ snapshots:optionalDependencies:typescript: 5.9.3+ dependencies:+ env-paths: 2.2.1+ import-fresh: 3.3.1+ js-yaml: 4.1.1+ parse-json: 5.2.0+ optionalDependencies:+ typescript: 5.9.3+dependencies:path-key: 3.1.1@@ -16039,6 +16099,12 @@ snapshots:jsonfile: 6.2.0universalify: 2.0.1+ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 6.2.0+ universalify: 2.0.1+@@ -16370,17 +16436,17 @@ snapshots:- [email protected](@types/[email protected]):+ [email protected](@types/[email protected]):dependencies:'@inquirer/ansi': 1.0.2- '@inquirer/core': 10.3.2(@types/[email protected])- '@inquirer/prompts': 7.10.1(@types/[email protected])- '@inquirer/type': 3.0.10(@types/[email protected])+ '@inquirer/core': 10.3.2(@types/[email protected])+ '@inquirer/prompts': 7.10.1(@types/[email protected])+ '@inquirer/type': 3.0.10(@types/[email protected])mute-stream: 2.0.0run-async: 4.0.6rxjs: 7.8.2optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5dependencies:@@ -16678,7 +16744,7 @@ snapshots:dependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5merge-stream: 2.0.0supports-color: 8.1.1@@ -16800,15 +16866,14 @@ snapshots:dependencies:- commander: 14.0.2+ commander: 14.0.3listr2: 9.0.5micromatch: 4.0.8- nano-spawn: 2.0.0- pidtree: 0.6.0string-argv: 0.3.2- yaml: 2.8.1+ tinyexec: 1.0.2+ yaml: 2.8.2dependencies:@@ -17343,6 +17408,10 @@ snapshots:dependencies:brace-expansion: 1.1.11+ dependencies:+ brace-expansion: 1.1.11+dependencies:brace-expansion: 2.0.1@@ -17400,8 +17469,6 @@ snapshots:- [email protected]: {}-@@ -17751,8 +17818,6 @@ snapshots:- [email protected]: {}-@@ -18114,9 +18179,11 @@ snapshots:picocolors: 1.1.1source-map-js: 1.2.1dependencies:- '@posthog/core': 1.23.1+ '@posthog/core': 1.23.2+ optionalDependencies:+ rxjs: 7.8.2@@ -18263,26 +18330,26 @@ snapshots:dependencies:dnd-core: 16.0.1- [email protected]([email protected])([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected]([email protected]))([email protected]):+ [email protected]([email protected])([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected]([email protected]))([email protected]):dependencies:dnd-core: 16.0.1dnd-multi-backend: 8.1.2([email protected])react: 19.2.4- react-dnd-preview: 8.1.2([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected])+ react-dnd-preview: 8.1.2([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected])react-dom: 19.2.4([email protected])- [email protected]([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected]):+ [email protected]([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected]):dependencies:react: 19.2.4dependencies:'@react-dnd/invariant': 4.0.2dnd-core: 16.0.1dependencies:'@react-dnd/invariant': 4.0.2'@react-dnd/shallowequal': 4.0.2@@ -18291,7 +18358,7 @@ snapshots:hoist-non-react-statics: 3.3.2react: 19.2.4optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5'@types/react': 19.2.14@@ -18339,7 +18406,7 @@ snapshots:- [email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]):+ [email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]):dependencies:classnames: 2.5.1immutability-helper: 3.1.1@@ -18347,9 +18414,9 @@ snapshots:prop-types: 15.8.1rdndmb-html5-to-touch: 8.1.2([email protected])react: 19.2.4react-dnd-html5-backend: 16.0.1- react-dnd-multi-backend: 8.1.2([email protected])([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected]([email protected]))([email protected])+ react-dnd-multi-backend: 8.1.2([email protected])([email protected](@types/[email protected])(@types/[email protected])([email protected]))([email protected]([email protected]))([email protected])react-dnd-touch-backend: 16.0.1uuid: 9.0.1transitivePeerDependencies:@@ -18484,7 +18551,7 @@ snapshots:dependencies:'@nodeutils/defaults-deep': 1.1.0'@octokit/rest': 22.0.1@@ -18494,7 +18561,7 @@ snapshots:ci-info: 4.3.1eta: 4.5.0git-url-parse: 16.1.0- inquirer: 12.11.1(@types/[email protected])+ inquirer: 12.11.1(@types/[email protected])issue-parser: 7.0.1lodash.merge: 4.6.2mime-types: 3.0.2@@ -18693,20 +18760,20 @@ snapshots:dependencies:randombytes: 2.1.0dependencies:bytes: 3.0.0content-disposition: 0.5.2mime-types: 2.1.18- minimatch: 3.1.2+ minimatch: 3.1.5path-is-inside: 1.0.2path-to-regexp: 3.3.0range-parser: 1.2.0dependencies:'@zeit/schemas': 2.36.0- ajv: 8.12.0+ ajv: 8.18.0arg: 5.0.2boxen: 7.0.0chalk: 5.0.1@@ -18714,7 +18781,7 @@ snapshots:clipboardy: 3.0.0compression: 1.8.1is-port-reachable: 4.0.0- serve-handler: 6.1.6+ serve-handler: 6.1.7update-check: 1.5.4transitivePeerDependencies:- supports-color@@ -18905,7 +18972,7 @@ snapshots:dependencies:eastasianwidth: 0.2.0emoji-regex: 9.2.2- strip-ansi: 7.1.0+ strip-ansi: 7.1.2dependencies:@@ -18976,10 +19043,6 @@ snapshots:dependencies:ansi-regex: 5.0.1- dependencies:- ansi-regex: 6.1.0-dependencies:ansi-regex: 6.1.0@@ -19211,32 +19274,32 @@ snapshots:optionalDependencies:fsevents: 2.3.3optional: trueoptional: trueoptional: trueoptional: trueoptional: trueoptional: trueoptionalDependencies:- turbo-darwin-64: 2.8.10- turbo-darwin-arm64: 2.8.10- turbo-linux-64: 2.8.10- turbo-linux-arm64: 2.8.10- turbo-windows-64: 2.8.10- turbo-windows-arm64: 2.8.10+ turbo-darwin-64: 2.8.14+ turbo-darwin-arm64: 2.8.14+ turbo-linux-64: 2.8.14+ turbo-linux-arm64: 2.8.14+ turbo-windows-64: 2.8.14+ turbo-windows-arm64: 2.8.14dependencies:@@ -19425,9 +19488,9 @@ snapshots:- [email protected](@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:- '@microsoft/api-extractor': 7.52.7(@types/[email protected])+ '@microsoft/api-extractor': 7.52.7(@types/[email protected])'@rollup/pluginutils': 5.1.4([email protected])'@volar/typescript': 2.4.13'@vue/language-core': 2.2.0([email protected])@@ -19438,7 +19501,7 @@ snapshots:magic-string: 0.30.17typescript: 5.9.3optionalDependencies:- vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- '@types/node'- rollup@@ -19453,7 +19516,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:esbuild: 0.27.2fdir: 6.5.0([email protected])@@ -19462,7 +19525,7 @@ snapshots:rollup: 4.55.1tinyglobby: 0.2.15optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5fsevents: 2.3.3jiti: 2.6.1sass: 1.87.0@@ -19470,10 +19533,10 @@ snapshots:tsx: 4.21.0yaml: 2.8.2- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:'@vitest/expect': 4.0.18- '@vitest/mocker': 4.0.18([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ '@vitest/mocker': 4.0.18([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/pretty-format': 4.0.18'@vitest/runner': 4.0.18'@vitest/snapshot': 4.0.18@@ -19490,10 +19553,10 @@ snapshots:tinyexec: 1.0.2tinyglobby: 0.2.15tinyrainbow: 3.0.3- vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 7.3.1(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])why-is-node-running: 2.3.0optionalDependencies:- '@types/node': 25.3.0+ '@types/node': 25.3.5happy-dom: 20.7.0jsdom: 27.0.1([email protected])transitivePeerDependencies:@@ -19515,7 +19578,7 @@ snapshots:base-log-factory: 2.1.4blf-debug-appender: 1.0.5figlet: 1.8.1- fs-extra: 11.3.3+ fs-extra: 11.3.4picocolors: 1.1.1transitivePeerDependencies:- supports-color@@ -19711,7 +19774,7 @@ snapshots:dependencies:ansi-styles: 6.2.3string-width: 5.1.2- strip-ansi: 7.1.0+ strip-ansi: 7.1.2dependencies: