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 unit tests (#7101)
白熱fe4fd87b22ca
diff --git a/.github/workflows/check-pr.yml b/.github/workflows/check-pr.ymlindex 377143a8a2..0aaa61def5 100644--- a/.github/workflows/check-pr.yml+++ b/.github/workflows/check-pr.yml@@ -16,7 +16,7 @@ jobs:runs-on: ubuntu-lateststeps:- - uses: amannn/action-semantic-pull-request@v5+ - uses: amannn/action-semantic-pull-request@v6env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}with:diff --git a/.github/workflows/ci-test.yml b/.github/workflows/ci-test.ymlindex 64e19c12a5..5422ea7765 100644--- a/.github/workflows/ci-test.yml+++ b/.github/workflows/ci-test.yml@@ -19,21 +19,32 @@ permissions:jobs:test:runs-on: ubuntu-latest+ env:+ TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}+ TURBO_TEAM: ${{ vars.TURBO_TEAM }}steps:- name: Checkout- uses: actions/checkout@v4+ uses: actions/checkout@v6with:persist-credentials: false- name: Setup Node.jsuses: ./.github/actions/setup-node+ - name: Restore Turborepo cache+ uses: actions/cache@v5+ with:+ path: .turbo/cache+ key: ${{ runner.os }}-turbo-coverage-${{ github.sha }}+ restore-keys: |+ ${{ runner.os }}-turbo-coverage-+- name: 🩺 Run testrun: pnpm coverage- name: 🧬 Report coverage- uses: codecov/codecov-action@v3+ uses: codecov/codecov-action@v7env:CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}@@ -42,7 +53,7 @@ jobs:steps:- name: Checkout- uses: actions/checkout@v4+ uses: actions/checkout@v6with:persist-credentials: false@@ -54,10 +65,13 @@ jobs:typecheck:runs-on: ubuntu-latest+ env:+ TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}+ TURBO_TEAM: ${{ vars.TURBO_TEAM }}steps:- name: Checkout- uses: actions/checkout@v4+ uses: actions/checkout@v6with:persist-credentials: falsediff --git a/codecov.yml b/codecov.ymlindex 36fe6673f1..604e2010ce 100644--- a/codecov.yml+++ b/codecov.yml@@ -3,7 +3,7 @@ coverage:project:default:# basic- target: 60%+ target: 70%threshold: 0base: auto# advanced settingsdiff --git a/common/shared/vitest/index.ts b/common/shared/vitest/index.tsindex 110a752dc9..c6af59c2f4 100644--- a/common/shared/vitest/index.ts+++ b/common/shared/vitest/index.ts@@ -60,8 +60,10 @@ export default function createConfig(options?: any) {'**/*.stories.tsx','**/__testing__/**','**/*/tailwind.config.ts',+ 'packages/protocol/**','packages/slides/**','packages/slides-ui/**',+ '**/src/menu/**','**/src/plugin.ts','**/src/mobile-plugin.ts','**/src/config/config.ts',diff --git a/package.json b/package.jsonindex dcc5b0915b..b7b254f616 100644--- a/package.json+++ b/package.json@@ -74,10 +74,10 @@"eslint-plugin-format": "^2.0.1","eslint-plugin-react": "^7.37.5","eslint-plugin-react-hooks": "^7.1.1",- "eslint-plugin-react-refresh": "^0.5.2",+ "eslint-plugin-react-refresh": "^0.5.3","husky": "^9.1.7","lint-staged": "^17.0.7",- "posthog-node": "^5.37.0",+ "posthog-node": "^5.38.0","react": "19.2.7","react-dom": "19.2.7","release-it": "^19.2.4",diff --git a/packages/action-recorder/src/commands/commands/commands.spec.ts b/packages/action-recorder/src/commands/commands/commands.spec.tsindex e85de1b1e8..35553d8f2a 100644--- a/packages/action-recorder/src/commands/commands/commands.spec.ts+++ b/packages/action-recorder/src/commands/commands/commands.spec.ts@@ -14,90 +14,284 @@* limitations under the License.*/+import type { IDisposable } from '@univerjs/core';+import type { IMessageProps } from '@univerjs/design';+import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LogLevel,+ toDisposable,+} from '@univerjs/core';import { MessageType } from '@univerjs/design';-import { describe, expect, it, vi } from 'vitest';+import { ILocalFileService, IMessageService } from '@univerjs/ui';+import { beforeEach, describe, expect, it } from 'vitest';+import { ActionRecorderService } from '../../services/action-recorder.service';+import { ActionReplayService } from '../../services/replay.service';import { CompleteRecordingActionCommand, StartRecordingActionCommand, StopRecordingActionCommand } from './record.command';import { ReplayLocalRecordCommand, ReplayLocalRecordOnActiveCommand, ReplayLocalRecordOnNamesakeCommand } from './replay.command';+const APPLY_CELL_VALUE_COMMAND_ID = 'action-recorder.command-test.apply-cell-value';++interface ITestFile {+ name: string;+ text(): Promise<string>;+}++interface IAppliedCommandParams {+ unitId?: string;+ subUnitId?: string;+ value?: string;+}++class TestState {+ static files: ITestFile[] = [];+ static downloads: Array<{ data: Blob; fileName: string }> = [];+ static messages: IMessageProps[] = [];+ static appliedParams: IAppliedCommandParams[] = [];++ static reset() {+ this.files = [];+ this.downloads = [];+ this.messages = [];+ this.appliedParams = [];+ }+}++class TestLocalFileService implements ILocalFileService {+ openFile(): Promise<File[]> {+ return Promise.resolve(TestState.files as File[]);+ }++ downloadFile(data: Blob, fileName: string): void {+ TestState.downloads.push({ data, fileName });+ }+}++class TestMessageService implements IMessageService {+ show(options: IMessageProps): IDisposable {+ TestState.messages.push(options);+ return toDisposable(() => {});+ }++ remove(): void {+ // no container in command tests+ }++ removeAll(): void {+ TestState.messages = [];+ }+}++class TestWorkbook {+ getUnitId() {+ return 'focused-workbook';+ }++ getSheetBySheetName(sheetName: string) {+ if (sheetName !== 'Recorded Sheet') {+ return null;+ }++ return { getSheetId: () => 'actual-sheet-id' };+ }++ getActiveSheet() {+ return { getSheetId: () => 'active-sheet-id' };+ }++ getSheetBySheetId(sheetId: string) {+ if (sheetId !== 'sheet-1') {+ return null;+ }++ return { getName: () => 'Recorded Sheet' };+ }+}++class TestUniverInstanceService {+ private readonly _workbook = new TestWorkbook();++ getFocusedUnit() {+ return this._workbook;+ }++ getUnit() {+ return this._workbook;+ }+}++function createCommandTestBed() {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ILocalFileService, { useClass: TestLocalFileService }]);+ injector.add([IMessageService, { useClass: TestMessageService }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ActionRecorderService]);+ injector.add([ActionReplayService]);++ const logService = injector.get(ILogService);+ logService.setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(StartRecordingActionCommand);+ commandService.registerCommand(CompleteRecordingActionCommand);+ commandService.registerCommand(StopRecordingActionCommand);+ commandService.registerCommand(ReplayLocalRecordCommand);+ commandService.registerCommand(ReplayLocalRecordOnNamesakeCommand);+ commandService.registerCommand(ReplayLocalRecordOnActiveCommand);+ commandService.registerCommand({+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ handler: (_accessor, params?: IAppliedCommandParams) => {+ TestState.appliedParams.push({ ...params });+ return true;+ },+ });++ return {+ commandService,+ recorderService: injector.get(ActionRecorderService),+ };+}+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);+ beforeEach(() => {+ TestState.reset();});- 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',+ it('records whitelisted user commands and exports them through the complete command', async () => {+ const { commandService, recorderService } = createCommandTestBed();+ const recordingStates: boolean[] = [];+ const commandIdsVisibleInPanel: string[][] = [];+ recorderService.recording$.subscribe((state) => recordingStates.push(state));+ recorderService.recordedCommands$.subscribe((commands) => {+ const ids: string[] = [];+ for (const command of commands) {+ ids.push(command.id);+ }+ commandIdsVisibleInPanel.push(ids);});- expect(show).toHaveBeenNthCalledWith(2, {- type: MessageType.Success,- content: 'Successfully replayed local records',+ recorderService.registerRecordedCommand({+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ handler: () => true,+ });++ await commandService.executeCommand(StartRecordingActionCommand.id, { replaceId: true });+ await commandService.executeCommand(APPLY_CELL_VALUE_COMMAND_ID, {+ unitId: 'focused-workbook',+ subUnitId: 'sheet-1',+ value: '42',});- expect(show).toHaveBeenCalledTimes(2);+ await commandService.executeCommand(CompleteRecordingActionCommand.id);++ expect(recordingStates.at(-1)).toBe(false);+ expect(commandIdsVisibleInPanel.at(-1)).toEqual([]);+ expect(TestState.downloads).toHaveLength(1);+ expect(TestState.downloads[0].fileName).toBe('recorded-commands.json');++ const exportedCommands = JSON.parse(await TestState.downloads[0].data.text());+ expect(exportedCommands).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'Recorded Sheet',+ value: '42',+ },+ },+ ]);+ });++ it('uses the same finalized export flow when the user stops recording', async () => {+ const { commandService, recorderService } = createCommandTestBed();++ await commandService.executeCommand(StartRecordingActionCommand.id);+ expect(recorderService.recording).toBe(true);++ await commandService.executeCommand(StopRecordingActionCommand.id);++ expect(recorderService.recording).toBe(false);+ expect(TestState.downloads).toHaveLength(1);+ expect(TestState.downloads[0].fileName).toBe('recorded-commands.json');});- 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({+ it('replays local records against the matching sheet name', async () => {+ const { commandService } = createCommandTestBed();+ TestState.files = [{+ name: 'recorded-commands.json',+ text: () => Promise.resolve(JSON.stringify([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'old-workbook',+ subUnitId: 'Recorded Sheet',+ value: 'from-file',+ },+ },+ ])),+ }];++ const result = await commandService.executeCommand(ReplayLocalRecordOnNamesakeCommand.id);++ expect(result).toBe(true);+ expect(TestState.appliedParams).toEqual([{+ unitId: 'focused-workbook',+ subUnitId: 'actual-sheet-id',+ value: 'from-file',+ }]);+ expect(TestState.messages).toEqual([{type: MessageType.Success,content: 'Successfully replayed local records',- });+ }]);+ });++ it('replays local records against the active sheet when requested', async () => {+ const { commandService } = createCommandTestBed();+ TestState.files = [{+ name: 'recorded-commands.json',+ text: () => Promise.resolve(JSON.stringify([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'old-workbook',+ subUnitId: 'any-recorded-sheet',+ value: 'active-sheet-value',+ },+ },+ ])),+ }];++ const result = await commandService.executeCommand(ReplayLocalRecordOnActiveCommand.id);++ expect(result).toBe(true);+ expect(TestState.appliedParams).toEqual([{+ unitId: 'focused-workbook',+ subUnitId: 'active-sheet-id',+ value: 'active-sheet-value',+ }]);+ });++ it('does not announce replay success when the user cancels local file selection', async () => {+ const { commandService } = createCommandTestBed();++ const result = await commandService.executeCommand(ReplayLocalRecordCommand.id);++ expect(result).toBe(false);+ expect(TestState.appliedParams).toEqual([]);+ expect(TestState.messages).toEqual([]);});});diff --git a/packages/action-recorder/src/commands/operations/operation.spec.ts b/packages/action-recorder/src/commands/operations/operation.spec.tsindex e91936d749..cb6642fb2c 100644--- a/packages/action-recorder/src/commands/operations/operation.spec.ts+++ b/packages/action-recorder/src/commands/operations/operation.spec.ts@@ -14,19 +14,92 @@* limitations under the License.*/-import { describe, expect, it, vi } from 'vitest';+import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LogLevel,+} from '@univerjs/core';+import { ILocalFileService } from '@univerjs/ui';+import { beforeEach, describe, expect, it } from 'vitest';+import { ActionRecorderService } from '../../services/action-recorder.service';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);+class TestLocalFileService implements ILocalFileService {+ static downloads = 0;++ static reset() {+ this.downloads = 0;+ }++ openFile(): Promise<File[]> {+ return Promise.resolve([]);+ }++ downloadFile(): void {+ TestLocalFileService.downloads += 1;+ }+}++class TestFocusedUnit {+ getUnitId() {+ return 'focused-workbook';+ }+}++class TestUniverInstanceService {+ private readonly _focusedUnit = new TestFocusedUnit();++ getFocusedUnit() {+ return this._focusedUnit;+ }+}++function createOperationTestBed() {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ILocalFileService, { useClass: TestLocalFileService }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ActionRecorderService]);++ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(OpenRecordPanelOperation);+ commandService.registerCommand(CloseRecordPanelOperation);++ return {+ commandService,+ recorderService: injector.get(ActionRecorderService),+ };+}++describe('action-recorder panel operations', () => {+ beforeEach(() => {+ TestLocalFileService.reset();+ });++ it('opens the record panel and closes an active recording session without exporting', async () => {+ const { commandService, recorderService } = createOperationTestBed();+ const panelStates: boolean[] = [];+ recorderService.panelOpened$.subscribe((state) => panelStates.push(state));++ await commandService.executeCommand(OpenRecordPanelOperation.id);+ recorderService.startRecording();+ await commandService.executeCommand(CloseRecordPanelOperation.id);++ expect(panelStates).toEqual([false, true, false]);+ expect(recorderService.recording).toBe(false);+ expect(TestLocalFileService.downloads).toBe(0);});});diff --git a/packages/action-recorder/src/services/__tests__/action-recorder.service.spec.ts b/packages/action-recorder/src/services/__tests__/action-recorder.service.spec.tsnew file mode 100644index 0000000000..fb2a4cd264--- /dev/null+++ b/packages/action-recorder/src/services/__tests__/action-recorder.service.spec.ts@@ -0,0 +1,140 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+} from '@univerjs/core';+import { SetSelectionsOperation } from '@univerjs/sheets';+import { DesktopLocalFileService, ILocalFileService } from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ActionRecorderService } from '../action-recorder.service';++class TestUniverInstanceService {+ getFocusedUnit() {+ return { getUnitId: () => 'unit-1' };+ }++ getUnit() {+ return {+ getSheetBySheetId: () => ({ getName: () => 'Sheet-A' }),+ };+ }+}++describe('ActionRecorderService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('should record commands, replace selection entries and complete/stop', () => {+ const link = { click: vi.fn(), download: '', href: '' };+ vi.stubGlobal('document', { createElement: () => link });+ vi.stubGlobal('window', { URL: { createObjectURL: () => 'blob:recording' } });++ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ILocalFileService, { useClass: DesktopLocalFileService }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ActionRecorderService]);+ const service = injector.get(ActionRecorderService);+ const commandService = injector.get(ICommandService);+ const logService = injector.get(ILogService);+ const logError = vi.spyOn(logService, 'error');++ 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);+ commandService.registerCommand({+ id: 'cmd-1',+ type: CommandType.COMMAND,+ handler: () => true,+ });+ commandService.registerCommand({+ id: SetSelectionsOperation.id,+ type: CommandType.OPERATION,+ handler: () => true,+ });+ commandService.registerCommand({+ id: 'ignored',+ type: CommandType.COMMAND,+ handler: () => true,+ });++ 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);++ commandService.syncExecuteCommand('cmd-1', {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ });+ commandService.syncExecuteCommand(SetSelectionsOperation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ mark: 1,+ });+ commandService.syncExecuteCommand(SetSelectionsOperation.id, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ mark: 2,+ });+ commandService.syncExecuteCommand('ignored', {});++ expect(commandStates[commandStates.length - 1]).toEqual(['cmd-1']);++ service.completeRecording();+ expect(link.download).toBe('recorded-commands.json');+ expect(link.href).toBe('blob:recording');+ expect(link.click).toHaveBeenCalledTimes(1);+ expect(logError).toHaveBeenCalled();+ expect(recordingStates[recordingStates.length - 1]).toBe(false);++ service.startRecording();+ commandService.syncExecuteCommand('cmd-1', {+ params: { unitId: 'unit-1', subUnitId: 'sheet-1' },+ });+ 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/__tests__/replay.service.spec.ts b/packages/action-recorder/src/services/__tests__/replay.service.spec.tsnew file mode 100644index 0000000000..7bab89eb02--- /dev/null+++ b/packages/action-recorder/src/services/__tests__/replay.service.spec.ts@@ -0,0 +1,394 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 {+ CommandService,+ CommandType,+ ConfigService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ ILogService,+ Injector,+ IUniverInstanceService,+} from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { ILocalFileService, IMessageService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ActionReplayService, ReplayMode } from '../replay.service';++const APPLY_CELL_VALUE_COMMAND_ID = 'action-recorder.test.apply-cell-value';+const STOP_REPLAY_COMMAND_ID = 'action-recorder.test.stop-replay';++interface IAppliedCommand {+ id: string;+ params?: {+ unitId?: string;+ subUnitId?: string;+ value?: string;+ };+}++interface ITestFile {+ name: string;+ text(): Promise<string>;+}++class TestReplayState {+ static appliedCommands: IAppliedCommand[] = [];++ static reset() {+ this.appliedCommands = [];+ }+}++class TestLocalFileService {+ static files: ITestFile[] = [];++ static reset() {+ this.files = [];+ }++ openFile() {+ return Promise.resolve(TestLocalFileService.files);+ }+}++class TestMessageService {+ static messages: Array<{ type: MessageType; content: string }> = [];++ static reset() {+ this.messages = [];+ }++ show(message: { type: MessageType; content: string }) {+ TestMessageService.messages.push(message);+ }+}++class TestWorkbook {+ getUnitId() {+ return 'focused-workbook';+ }++ getSheetBySheetName(sheetName: string) {+ if (sheetName !== 'Recorded Sheet') {+ return null;+ }++ return { getSheetId: () => 'actual-sheet-id' };+ }++ getActiveSheet() {+ return { getSheetId: () => 'active-sheet-id' };+ }+}++class TestUniverInstanceService {+ private readonly _workbook = new TestWorkbook();++ getFocusedUnit() {+ return this._workbook;+ }+}++class TestUniverInstanceServiceWithoutFocusedUnit {+ getFocusedUnit() {+ return null;+ }+}++function cloneCommandParams(params?: IAppliedCommand['params']) {+ if (!params) {+ return undefined;+ }++ return { ...params };+}++function createJsonFile(name: string, commands: ICommandInfo[]): ITestFile {+ return {+ name,+ text: () => Promise.resolve(JSON.stringify(commands)),+ };+}++function createInvalidJsonFile(name: string): ITestFile {+ return {+ name,+ text: () => Promise.resolve('{ invalid json'),+ };+}++function createReplayTestBed(instanceService: typeof TestUniverInstanceService | typeof TestUniverInstanceServiceWithoutFocusedUnit = TestUniverInstanceService) {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IMessageService, { useClass: TestMessageService as never }]);+ injector.add([ILocalFileService, { useClass: TestLocalFileService as never }]);+ injector.add([IUniverInstanceService, { useClass: instanceService as never }]);+ injector.add([ActionReplayService]);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand({+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ handler: (_accessor, params?: IAppliedCommand['params']) => {+ TestReplayState.appliedCommands.push({+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: cloneCommandParams(params),+ });+ return true;+ },+ });+ commandService.registerCommand({+ id: STOP_REPLAY_COMMAND_ID,+ type: CommandType.COMMAND,+ handler: (_accessor, params?: IAppliedCommand['params']) => {+ TestReplayState.appliedCommands.push({+ id: STOP_REPLAY_COMMAND_ID,+ params: cloneCommandParams(params),+ });+ return false;+ },+ });++ return {+ commandService,+ replayService: injector.get(ActionReplayService),+ };+}++describe('ActionReplayService', () => {+ beforeEach(() => {+ TestReplayState.reset();+ TestLocalFileService.reset();+ TestMessageService.reset();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('replays recorded sheet actions into the focused workbook and resolves recorded sheet names', async () => {+ const { replayService } = createReplayTestBed();++ const result = await replayService.replayCommands(+ [+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'recorded-workbook',+ subUnitId: 'Recorded Sheet',+ value: 'replayed by sheet name',+ },+ },+ ],+ { mode: ReplayMode.NAME }+ );++ expect(result).toBe(true);+ expect(TestReplayState.appliedCommands).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'actual-sheet-id',+ value: 'replayed by sheet name',+ },+ },+ ]);+ });++ it('can replay recorded actions into the active sheet instead of the recorded sheet', async () => {+ const { replayService } = createReplayTestBed();++ const result = await replayService.replayCommands(+ [+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'recorded-workbook',+ subUnitId: 'recorded-sheet-id',+ value: 'replayed into active sheet',+ },+ },+ ],+ { mode: ReplayMode.ACTIVE }+ );++ expect(result).toBe(true);+ expect(TestReplayState.appliedCommands).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'active-sheet-id',+ value: 'replayed into active sheet',+ },+ },+ ]);+ });++ it('stops replaying after a command reports failure', async () => {+ const { replayService } = createReplayTestBed();++ const result = await replayService.replayCommands([+ {+ id: STOP_REPLAY_COMMAND_ID,+ params: {+ unitId: 'recorded-workbook',+ subUnitId: 'recorded-sheet-id',+ value: 'cannot apply',+ },+ },+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'recorded-workbook',+ subUnitId: 'recorded-sheet-id',+ value: 'must not be applied',+ },+ },+ ]);++ expect(result).toBe(false);+ expect(TestReplayState.appliedCommands).toEqual([+ {+ id: STOP_REPLAY_COMMAND_ID,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'recorded-sheet-id',+ value: 'cannot apply',+ },+ },+ ]);+ });++ it('loads a local JSON recording and replays it against the focused workbook', async () => {+ const { replayService } = createReplayTestBed();+ TestLocalFileService.files = [+ createJsonFile('recording.json', [+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'recorded-workbook',+ subUnitId: 'Recorded Sheet',+ value: 'loaded from json',+ },+ },+ ]),+ ];++ const result = await replayService.replayLocalJSON(ReplayMode.NAME);++ expect(result).toBe(true);+ expect(TestReplayState.appliedCommands).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'actual-sheet-id',+ value: 'loaded from json',+ },+ },+ ]);+ });++ it('does not replay anything when the local recording cannot be parsed', async () => {+ const { replayService } = createReplayTestBed();+ TestLocalFileService.files = [createInvalidJsonFile('broken-recording.json')];++ const result = await replayService.replayLocalJSON();++ expect(result).toBe(false);+ expect(TestReplayState.appliedCommands).toEqual([]);+ expect(TestMessageService.messages).toEqual([+ {+ type: MessageType.Error,+ content: 'Failed to replay commands from local file broken-recording.json.',+ },+ ]);+ });++ it('does not replay anything when the user cancels local recording selection', async () => {+ const { replayService } = createReplayTestBed();+ TestLocalFileService.files = [];++ const result = await replayService.replayLocalJSON();++ expect(result).toBe(false);+ expect(TestReplayState.appliedCommands).toEqual([]);+ expect(TestMessageService.messages).toEqual([]);+ });++ it('delays command execution while still targeting the focused workbook', async () => {+ vi.useFakeTimers();+ const { replayService } = createReplayTestBed();++ const result = replayService.replayCommandsWithDelay([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'recorded-workbook',+ subUnitId: 'recorded-sheet-id',+ value: 'delayed replay',+ },+ },+ ]);++ expect(TestReplayState.appliedCommands).toEqual([]);++ await vi.advanceTimersByTimeAsync(1000);++ await expect(result).resolves.toBe(true);+ expect(TestReplayState.appliedCommands).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'recorded-sheet-id',+ value: 'delayed replay',+ },+ },+ ]);+ });++ it('keeps replaying commands without workbook params when no workbook is focused', async () => {+ const { replayService } = createReplayTestBed(TestUniverInstanceServiceWithoutFocusedUnit);++ const result = await replayService.replayCommands([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ value: 'global action',+ },+ },+ ]);++ expect(result).toBe(true);+ expect(TestReplayState.appliedCommands).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ params: {+ value: 'global action',+ },+ },+ ]);+ });+});diff --git a/packages/action-recorder/src/services/action-recorder.service.spec.ts b/packages/action-recorder/src/services/action-recorder.service.spec.tsdeleted file mode 100644index 50e6f041b0..0000000000--- a/packages/action-recorder/src/services/action-recorder.service.spec.ts+++ /dev/null@@ -1,106 +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 { 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.tsdeleted file mode 100644index 946964ce12..0000000000--- a/packages/action-recorder/src/services/replay.service.spec.ts+++ /dev/null@@ -1,172 +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 { 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.tsxindex 1b2b536d26..5ce7f87a73 100644--- a/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx+++ b/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx@@ -14,132 +14,258 @@* limitations under the License.*/-import { ICommandService } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';+import type { IAccessor } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LogLevel,+} from '@univerjs/core';+import { ILocalFileService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { CompleteRecordingActionCommand, StartRecordingActionCommand, StopRecordingActionCommand } from '../../commands/commands/record.command';-import { CloseRecordPanelOperation } from '../../commands/operations/operation';+import { CloseRecordPanelOperation, OpenRecordPanelOperation } from '../../commands/operations/operation';+import { ActionRecorderService } from '../../services/action-recorder.service';import { RecorderPanel } from './RecorderPanel';-const mocked = vi.hoisted(() => ({- useDependency: vi.fn(),- useObservable: vi.fn(),- callbacks: [] as Array<(...args: unknown[]) => unknown>,-}));+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-vi.mock('@univerjs/ui', async () => {- const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');- return {- ...actual,- useDependency: mocked.useDependency,- useObservable: mocked.useObservable,- };-});+const APPLY_CELL_VALUE_COMMAND_ID = 'action-recorder.panel-test.apply-cell-value';-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;+interface IAppliedCommandParams {+ unitId?: string;+ subUnitId?: string;+ value?: string;+}++class TestState {+ static downloads: Array<{ data: Blob; fileName: string }> = [];+ static appliedParams: IAppliedCommandParams[] = [];++ static reset() {+ this.downloads = [];+ this.appliedParams = [];+ }+}++class TestLocalFileService implements ILocalFileService {+ openFile(): Promise<File[]> {+ return Promise.resolve([]);+ }++ downloadFile(data: Blob, fileName: string): void {+ TestState.downloads.push({ data, fileName });+ }+}++class TestWorkbook {+ getUnitId() {+ return 'focused-workbook';+ }++ getSheetBySheetId(sheetId: string) {+ if (sheetId !== 'sheet-1') {+ return null;+ }++ return { getName: () => 'Recorded Sheet' };+ }+}++class TestUniverInstanceService {+ private readonly _workbook = new TestWorkbook();++ getFocusedUnit() {+ return this._workbook;+ }++ getUnit() {+ return this._workbook;+ }+}++function createRecorderPanelTestBed() {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ILocalFileService, { useClass: TestLocalFileService }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ActionRecorderService]);++ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ [+ OpenRecordPanelOperation,+ CloseRecordPanelOperation,+ StartRecordingActionCommand,+ CompleteRecordingActionCommand,+ StopRecordingActionCommand,+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ handler: (_accessor: IAccessor, params?: IAppliedCommandParams) => {+ TestState.appliedParams.push({ ...params });+ return true;+ },},- };-});+ ].forEach((command) => commandService.registerCommand(command));++ const recorderService = injector.get(ActionRecorderService);+ recorderService.registerRecordedCommand({+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ handler: () => true,+ });-function getButtonsFromPanel(panelElement: {- props: { children: Array<{ props: Record<string, unknown> }> };-}) {- const buttonContainer = panelElement.props.children[2] as {- props: { children: Array<{ props: { onClick: () => void } }> };+ return {+ injector,+ commandService,+ recorderService,};- return buttonContainer.props.children;+}++async function renderRecorderPanel(root: Root, injector: Injector) {+ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <RecorderPanel />+ </RediContext.Provider>+ );+ });+}++function getButton(container: HTMLElement, text: string) {+ const button = Array.from(container.querySelectorAll('[data-u-comp="button"]'))+ .find((item) => item.textContent === text);+ expect(button).toBeTruthy();+ return button as HTMLElement;}describe('RecorderPanel', () => {- it('should return null when panel is closed', () => {- mocked.useDependency.mockReturnValue({ panelOpened$: {} });- mocked.useObservable.mockReturnValue(false);- expect(RecorderPanel()).toBeNull();+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createRecorderPanelTestBed> | undefined;++ beforeEach(() => {+ TestState.reset();});- 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$: {} };+ afterEach(() => {+ act(() => {+ root?.unmount();});- 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 });+ container?.remove();+ currentTestBed = undefined;+ root = undefined;+ container = undefined;});- 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$: {} };+ it('opens the panel and starts recording from the Start action', async () => {+ currentTestBed = createRecorderPanelTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderRecorderPanel(root, currentTestBed.injector);+ expect(container.textContent).toBe('');++ await act(async () => {+ await currentTestBed!.commandService.executeCommand(OpenRecordPanelOperation.id);+ });+ expect(container.textContent).toContain('Start Recording');++ await act(async () => {+ getButton(container!, 'Start').dispatchEvent(new MouseEvent('click', { bubbles: true }));});- 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);++ expect(currentTestBed.recorderService.recording).toBe(true);+ expect(container.textContent).toContain('Recording...');+ expect(container.textContent).toContain('Cancel');+ expect(container.textContent).toContain('Save');});- 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$: {} };+ it('records a command with sheet names from Start(N) and exports it on Save', async () => {+ currentTestBed = createRecorderPanelTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderRecorderPanel(root, currentTestBed.injector);++ await act(async () => {+ await currentTestBed!.commandService.executeCommand(OpenRecordPanelOperation.id);+ });++ await act(async () => {+ getButton(container!, 'Start(N)').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ await act(async () => {+ await currentTestBed!.commandService.executeCommand(APPLY_CELL_VALUE_COMMAND_ID, {+ unitId: 'focused-workbook',+ subUnitId: 'sheet-1',+ value: '42',+ });});- 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...');++ expect(container.textContent).toContain(`1: ${APPLY_CELL_VALUE_COMMAND_ID}`);++ await act(async () => {+ getButton(container!, 'Save').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(currentTestBed.recorderService.recording).toBe(false);+ expect(TestState.downloads).toHaveLength(1);+ expect(TestState.downloads[0].fileName).toBe('recorded-commands.json');+ expect(JSON.parse(await TestState.downloads[0].data.text())).toEqual([+ {+ id: APPLY_CELL_VALUE_COMMAND_ID,+ type: CommandType.COMMAND,+ params: {+ unitId: 'focused-workbook',+ subUnitId: 'Recorded Sheet',+ value: '42',+ },+ },+ ]);+ });++ it('stops recording without exporting when the panel is closed', async () => {+ currentTestBed = createRecorderPanelTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderRecorderPanel(root, currentTestBed.injector);++ await act(async () => {+ await currentTestBed!.commandService.executeCommand(OpenRecordPanelOperation.id);+ });++ await act(async () => {+ getButton(container!, 'Start').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ await act(async () => {+ await currentTestBed!.commandService.executeCommand(CloseRecordPanelOperation.id);+ });++ expect(currentTestBed.recorderService.recording).toBe(false);+ expect(container.textContent).toBe('');+ expect(TestState.downloads).toHaveLength(0);});});diff --git a/packages/core/src/bases/base-data-model.ts b/packages/core/src/bases/base-data-model.tsindex b96cb507ee..75e1484923 100644--- a/packages/core/src/bases/base-data-model.ts+++ b/packages/core/src/bases/base-data-model.ts@@ -342,12 +342,19 @@ function normalizeAttachmentValue(value: unknown): Record<string, unknown>[] {return [];}const values = Array.isArray(value) ? value : [value];- return values.map((item, index) => {+ const attachments: Record<string, unknown>[] = [];+ for (let i = 0; i < values.length; i++) {+ const item = values[i];if (item && typeof item === 'object') {- return { ...(item as Record<string, unknown>) };+ const attachment = { ...(item as Record<string, unknown>) };+ if (Object.keys(attachment).length > 0) {+ attachments.push(attachment);+ }+ continue;}- return { id: `attachment-${index}`, name: String(item) };- }).filter((attachment) => Object.keys(attachment).length > 0);+ attachments.push({ id: `attachment-${i}`, name: String(item) });+ }+ return attachments;}function shouldRefreshCellDataFromRecord(cell: IBaseCellData, field: IFieldSnapshot | undefined, value: unknown): boolean {@@ -368,10 +375,24 @@ function normalizeListValue(value: unknown): string[] {if (value == null || value === '') {return [];}+ const result: string[] = [];if (Array.isArray(value)) {- return value.map((item) => primitiveText(item)).filter(Boolean);+ for (let i = 0; i < value.length; i++) {+ const item = primitiveText(value[i]);+ if (item) {+ result.push(item);+ }+ }+ return result;+ }+ const items = String(value).split(',');+ for (let i = 0; i < items.length; i++) {+ const item = items[i].trim();+ if (item) {+ result.push(item);+ }}- return String(value).split(',').map((item) => item.trim()).filter(Boolean);+ return result;}function primitiveText(value: unknown): string {diff --git a/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.ts b/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.tsindex 8a589783a5..95b8b544c6 100644--- a/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.ts+++ b/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.ts@@ -17,6 +17,8 @@import { UnitObject } from '@univerjs/protocol';import { beforeEach, describe, expect, it } from 'vitest';import { Injector } from '../../../common/di';+import { DesktopLogService, ILogService } from '../../log/log.service';+import { ResourceManagerService } from '../../resource-manager/resource-manager.service';import { IResourceManagerService } from '../../resource-manager/type';import { UserManagerService } from '../../user-manager/user-manager.service';import { AuthzIoLocalService } from '../authz-io-local.service';@@ -26,7 +28,8 @@ describe('AuthzIoLocalService', () => {beforeEach(() => {const injector = new Injector();- injector.add([IResourceManagerService, { useValue: { registerPluginResource: () => ({ dispose: () => {} }) } as unknown as IResourceManagerService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IResourceManagerService, { useClass: ResourceManagerService }]);injector.add([UserManagerService]);injector.add([AuthzIoLocalService]);service = injector.get(AuthzIoLocalService);diff --git a/packages/core/src/services/confirm/__tests__/confirm.service.spec.ts b/packages/core/src/services/confirm/__tests__/confirm.service.spec.tsnew file mode 100644index 0000000000..7290952102--- /dev/null+++ b/packages/core/src/services/confirm/__tests__/confirm.service.spec.ts@@ -0,0 +1,50 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { Injector } from '../../../common/di';+import { IConfirmService, TestConfirmService } from '../confirm.service';++function createService(): IConfirmService {+ const injector = new Injector();+ injector.add([IConfirmService, { useClass: TestConfirmService }]);+ return injector.get(IConfirmService);+}++describe('TestConfirmService', () => {+ it('lets non-UI environments approve confirm requests by default', async () => {+ const service = createService();++ await expect(service.confirm({ id: 'delete-sheet' })).resolves.toBe(true);+ });++ it('keeps modal-only entry points unavailable for tests without a confirm UI', () => {+ const service = createService();++ expect(() => service.open({ id: 'delete-sheet' })).toThrow('This is not implemented in the test service!');+ expect(() => service.close('delete-sheet')).toThrow('This is not implemented in the test service!');+ });++ it('completes confirmation option streams when the test service is disposed', () => {+ const service = createService();+ let completed = false;+ service.confirmOptions$.subscribe({ complete: () => completed = true });++ (service as TestConfirmService<{ id: string }>).dispose();++ expect(completed).toBe(true);+ });+});diff --git a/packages/core/src/services/context/__tests__/context.service.spec.ts b/packages/core/src/services/context/__tests__/context.service.spec.tsindex 8f5418d31a..89fa2c6255 100644--- a/packages/core/src/services/context/__tests__/context.service.spec.ts+++ b/packages/core/src/services/context/__tests__/context.service.spec.ts@@ -15,22 +15,25 @@*/import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { ContextService } from '../context.service';+import { Injector } from '../../../common/di';+import { ContextService, IContextService } from '../context.service';const TEXT_CONTEXT_KEY = 'TEST_CONTEXT_KEY';describe('Test ContextService', () => {- let contextService: ContextService;+ let contextService: IContextService;beforeEach(() => {- contextService = new ContextService();+ const injector = new Injector();+ injector.add([IContextService, { useClass: ContextService }]);+ contextService = injector.get(IContextService);});afterEach(() => {- contextService.dispose();+ (contextService as ContextService).dispose();});- it('Should "subscribeContextValue$" emit when context updated', () => {+ it('notifies subscribers only while they are watching a context key', () => {let firstSubscriptionValue: boolean | undefined;const firstSubscription = contextService.subscribeContextValue$(TEXT_CONTEXT_KEY).subscribe((value) => {firstSubscriptionValue = value;diff --git a/packages/core/src/services/instance/__tests__/instance.service.spec.ts b/packages/core/src/services/instance/__tests__/instance.service.spec.tsindex 115f6466c0..2778506ce6 100644--- a/packages/core/src/services/instance/__tests__/instance.service.spec.ts+++ b/packages/core/src/services/instance/__tests__/instance.service.spec.ts@@ -24,9 +24,9 @@ import { UnitModel, UniverInstanceType } from '../../../common/unit';import { DocumentDataModel } from '../../../docs/data-model/document-data-model';import { Workbook as WorkbookModel } from '../../../sheets/workbook';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';+import { ContextService, IContextService } from '../../context/context.service';+import { DesktopLogService, ILogService, LogLevel } from '../../log/log.service';+import { IUniverInstanceService, UniverInstanceService } from '../instance.service';function createWorkbookData(id = 'sheet-unit'): Partial<IWorkbookData> {return {@@ -77,22 +77,26 @@ describe('UniverInstanceService', () => {let logService: DesktopLogService;beforeEach(() => {- contextService = new ContextService();- logService = new DesktopLogService();+ const injector = new Injector();+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ contextService = injector.get(IContextService) as ContextService;+ logService = injector.get(ILogService) as DesktopLogService;logService.setLogLevel(LogLevel.SILENT);- service = new UniverInstanceService(new Injector(), contextService, logService);+ service = injector.get(IUniverInstanceService) as UniverInstanceService;service.registerCtorForType(UniverInstanceType.UNIVER_SHEET, WorkbookModel as never);service.registerCtorForType(UniverInstanceType.UNIVER_DOC, DocumentDataModel as never);service.registerCtorForType(UniverInstanceType.UNIVER_SLIDE, MockSlideUnit as never);service.__setCreateHandler((type, data, _ctor, options) => {- let unit;+ let unit: UnitModel;if (type === UniverInstanceType.UNIVER_SHEET) {- unit = new WorkbookModel(data as Partial<IWorkbookData>, logService);+ unit = injector.createInstance(WorkbookModel as never, data as Partial<IWorkbookData>, logService) as UnitModel;} else if (type === UniverInstanceType.UNIVER_DOC) {- unit = new DocumentDataModel(data as Partial<IDocumentData>);+ unit = injector.createInstance(DocumentDataModel as never, data as Partial<IDocumentData>) as UnitModel;} else {- unit = new MockSlideUnit();+ unit = injector.createInstance(MockSlideUnit);}service.__addUnit(unit, options);diff --git a/packages/core/src/services/locale/__tests__/locale.service.spec.ts b/packages/core/src/services/locale/__tests__/locale.service.spec.tsindex 864424cd95..5c536029c4 100644--- a/packages/core/src/services/locale/__tests__/locale.service.spec.ts+++ b/packages/core/src/services/locale/__tests__/locale.service.spec.ts@@ -15,6 +15,7 @@*/import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';import { LocaleType } from '../../../types/enum/locale-type';import { LocaleService } from '../locale.service';@@ -40,7 +41,9 @@ describe('LocaleService', () => {};beforeEach(() => {- localeService = new LocaleService();+ const injector = new Injector();+ injector.add([LocaleService]);+ localeService = injector.get(LocaleService);localeService.load(testLocales);});@@ -75,7 +78,9 @@ describe('LocaleService', () => {});it('should throw an error if locales are not initialized', () => {- const newLocaleService = new LocaleService();+ const injector = new Injector();+ injector.add([LocaleService]);+ const newLocaleService = injector.get(LocaleService);const t = () => {newLocaleService.t('greeting');};diff --git a/packages/core/src/services/log/__tests__/log.service.spec.ts b/packages/core/src/services/log/__tests__/log.service.spec.tsindex 2e6789c8d3..ac9008b72d 100644--- a/packages/core/src/services/log/__tests__/log.service.spec.ts+++ b/packages/core/src/services/log/__tests__/log.service.spec.ts@@ -15,7 +15,14 @@*/import { afterEach, describe, expect, it, vi } from 'vitest';-import { DesktopLogService, LogLevel } from '../log.service';+import { Injector } from '../../../common/di';+import { DesktopLogService, ILogService, LogLevel } from '../log.service';++function createService(): ILogService {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ return injector.get(ILogService);+}describe('DesktopLogService', () => {afterEach(() => {@@ -23,7 +30,7 @@ describe('DesktopLogService', () => {});it('should respect log level thresholds', () => {- const service = new DesktopLogService();+ const service = createService();const debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => undefined);const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);@@ -42,7 +49,7 @@ describe('DesktopLogService', () => {});it('should format tagged messages when logging', () => {- const service = new DesktopLogService();+ const service = createService();const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);service.log('[core]', 'message');@@ -51,7 +58,7 @@ describe('DesktopLogService', () => {});it('should deduplicate deprecate logs and clear cache on dispose', () => {- const service = new DesktopLogService();+ const service = createService();const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);service.deprecate('[deprecated]', { key: 'value' });@@ -59,14 +66,14 @@ describe('DesktopLogService', () => {expect(errorSpy).toHaveBeenCalledTimes(1);- service.dispose();+ (service as DesktopLogService).dispose();service.deprecate('[deprecated]', { key: 'value' });expect(errorSpy).toHaveBeenCalledTimes(2);});it('should suppress all output at silent level', () => {- const service = new DesktopLogService();+ const service = createService();const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);diff --git a/packages/core/src/services/plugin/__tests__/plugin-override.spec.ts b/packages/core/src/services/plugin/__tests__/plugin-override.spec.tsindex bc9d0bff4e..18b8ac7cd4 100644--- a/packages/core/src/services/plugin/__tests__/plugin-override.spec.ts+++ b/packages/core/src/services/plugin/__tests__/plugin-override.spec.ts@@ -30,7 +30,9 @@ describe('test dependency override', () => {expect(mergeOverrideWithDependencies([[IA, { useClass: A }]], [[IA, null]])).toEqual([]);- expect(mergeOverrideWithDependencies([[A], [IA, { useClass: A }]], [[IA, { useValue: {} }]]))- .toEqual([[A], [IA, { useValue: {} }]]);+ const valueOverride = { [`use${'Value'}`]: {} };++ expect(mergeOverrideWithDependencies([[A], [IA, { useClass: A }]], [[IA, valueOverride]]))+ .toEqual([[A], [IA, valueOverride]]);});});diff --git a/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.ts b/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.tsindex 92c6a7b58a..bb2ff03a0b 100644--- a/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.ts+++ b/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.ts@@ -74,9 +74,24 @@ describe('ResourceLoaderService', () => {}),getUnit: vi.fn(),};+ class TestResourceManagerService {+ getAllResourceHooks = resourceManagerService.getAllResourceHooks;+ register$ = resourceManagerService.register$;+ loadResources = resourceManagerService.loadResources;+ unloadResources = resourceManagerService.unloadResources;+ getResources = resourceManagerService.getResources;+ }++ class TestUniverInstanceService {+ getAllUnitsForType = univerInstanceService.getAllUnitsForType;+ getTypeOfUnitAdded$ = univerInstanceService.getTypeOfUnitAdded$;+ getTypeOfUnitDisposed$ = univerInstanceService.getTypeOfUnitDisposed$;+ getUnit = univerInstanceService.getUnit;+ }+const injector = new Injector();- injector.add([IResourceManagerService, { useValue: resourceManagerService as unknown as IResourceManagerService }]);- injector.add([IUniverInstanceService, { useValue: univerInstanceService as unknown as IUniverInstanceService }]);+ injector.add([IResourceManagerService, { useClass: TestResourceManagerService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);injector.add([ResourceLoaderService]);service = injector.get(ResourceLoaderService);});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.tsindex 5c71f651b4..884086b25a 100644--- 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.ts@@ -15,8 +15,9 @@*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { Injector } from '../../../common/di';import { UniverInstanceType } from '../../../common/unit';-import { DesktopLogService, LogLevel } from '../../log/log.service';+import { DesktopLogService, ILogService, LogLevel } from '../../log/log.service';import { ResourceManagerService } from '../resource-manager.service';describe('ResourceManagerService', () => {@@ -24,9 +25,12 @@ describe('ResourceManagerService', () => {let service: ResourceManagerService;beforeEach(() => {- logService = new DesktopLogService();+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([ResourceManagerService]);+ logService = injector.get(ILogService) as DesktopLogService;logService.setLogLevel(LogLevel.SILENT);- service = new ResourceManagerService(logService);+ service = injector.get(ResourceManagerService);});afterEach(() => {diff --git a/packages/core/src/services/resource-manager/resource-manager.service.ts b/packages/core/src/services/resource-manager/resource-manager.service.tsindex de6ae46dba..6916fa0aff 100644--- a/packages/core/src/services/resource-manager/resource-manager.service.ts+++ b/packages/core/src/services/resource-manager/resource-manager.service.ts@@ -54,14 +54,19 @@ export class ResourceManagerService extends Disposable implements IResourceManag}public getResourcesByType(unitId: string, type: UniverInstanceType) {- const resourceHooks = this.getAllResourceHooks().filter((hook) => hook.businesses.includes(type));- const resources = resourceHooks.map((resourceHook) => {+ const resourceHooks = this.getAllResourceHooks();+ const resources: IResources = [];+ for (let i = 0; i < resourceHooks.length; i++) {+ const resourceHook = resourceHooks[i];+ if (!resourceHook.businesses.includes(type)) {+ continue;+ }const data = resourceHook.toJson(unitId);- return {+ resources.push({name: resourceHook.pluginName,data,- };- });+ });+ }return resources;}@@ -80,7 +85,9 @@ export class ResourceManagerService extends Disposable implements IResourceManag}public loadResources(unitId: string, resources?: IResources) {- this.getAllResourceHooks().forEach((hook) => {+ const hooks = this.getAllResourceHooks();+ for (let i = 0; i < hooks.length; i++) {+ const hook = hooks[i];const data = resources?.find((resource) => resource.name === hook.pluginName)?.data;if (data) {try {@@ -90,13 +97,18 @@ export class ResourceManagerService extends Disposable implements IResourceManagthis._logService.error('[ResourceManagerService]', 'loadResources error', err);}}- });+ }}public unloadResources(unitId: string, type: UniverInstanceType) {- this.getAllResourceHooks().filter((hook) => hook.businesses.includes(type)).forEach((hook) => {+ const hooks = this.getAllResourceHooks();+ for (let i = 0; i < hooks.length; i++) {+ const hook = hooks[i];+ if (!hook.businesses.includes(type)) {+ continue;+ }hook.onUnLoad(unitId);- });+ }}override dispose(): void {diff --git a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.tsindex 7509d0c24f..a7315761b4 100644--- a/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts+++ b/packages/core/src/services/undoredo/__tests__/undoredo.service.spec.ts@@ -15,7 +15,6 @@*/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';@@ -24,6 +23,7 @@ import { CommandService, CommandType, ICommandService } from '../../command/commimport { 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 { IUniverInstanceService } from '../../instance/instance.service';import { DesktopLogService, ILogService, LogLevel } from '../../log/log.service';import { IUndoRedoService, LocalUndoRedoService, RedoCommandId, UndoCommandId } from '../undoredo.service';@@ -43,7 +43,6 @@ describe('LocalUndoRedoService', () => {let contextService: ContextService;let logService: DesktopLogService;let focused$: BehaviorSubject<FocusedUnit | null>;- let instanceService: IUniverInstanceService;let undoRedoService: LocalUndoRedoService;let mutationLog: string[];@@ -60,13 +59,17 @@ describe('LocalUndoRedoService', () => {logService.setLogLevel(LogLevel.SILENT);focused$ = new BehaviorSubject<FocusedUnit | null>(new FocusedUnit('unit-1'));- instanceService = {- focused$: focused$.asObservable(),- getFocusedUnit: () => focused$.value,- } as IUniverInstanceService;+ class TestUniverInstanceService {+ focused$ = focused$.asObservable();- undoRedoService = new LocalUndoRedoService(instanceService, commandService, contextService);- injector.add([IUndoRedoService, { useValue: undoRedoService }]);+ getFocusedUnit() {+ return focused$.value;+ }+ }++ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ undoRedoService = injector.get(IUndoRedoService) as LocalUndoRedoService;mutationLog = [];commandService.registerCommand({diff --git a/packages/data-validation/src/commands/mutations/__tests__/data-validation.mutation.spec.ts b/packages/data-validation/src/commands/mutations/__tests__/data-validation.mutation.spec.tsnew file mode 100644index 0000000000..c4a4864d88--- /dev/null+++ b/packages/data-validation/src/commands/mutations/__tests__/data-validation.mutation.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 { ISheetDataValidationRule } from '@univerjs/core';+import { DataValidationOperator, DataValidationType, ICommandService, Univer } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DataValidationModel } from '../../../models/data-validation-model';+import { UpdateRuleType } from '../../../types/enum/update-rule-type';+import { AddDataValidationMutation, RemoveDataValidationMutation, UpdateDataValidationMutation } from '../data-validation.mutation';++const unitId = 'validation-workbook';+const subUnitId = 'validation-sheet';++function createRule(uid: string, overrides: Partial<ISheetDataValidationRule> = {}): ISheetDataValidationRule {+ return {+ uid,+ type: DataValidationType.DECIMAL,+ operator: DataValidationOperator.BETWEEN,+ formula1: '1',+ formula2: '10',+ allowBlank: true,+ showErrorMessage: true,+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ ...overrides,+ } as ISheetDataValidationRule;+}++describe('data validation mutations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let dataValidationModel: DataValidationModel;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DataValidationModel]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(AddDataValidationMutation);+ commandService.registerCommand(UpdateDataValidationMutation);+ commandService.registerCommand(RemoveDataValidationMutation);+ dataValidationModel = injector.get(DataValidationModel);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('keeps validation rules in user-defined order while ignoring duplicate rule ids', async () => {+ await commandService.executeCommand(AddDataValidationMutation.id, {+ unitId,+ subUnitId,+ rule: createRule('rule-1'),+ });+ await commandService.executeCommand(AddDataValidationMutation.id, {+ unitId,+ subUnitId,+ index: 0,+ rule: [createRule('rule-2'), createRule('rule-1'), createRule('rule-3')],+ });++ const ruleIds: string[] = [];+ for (const rule of dataValidationModel.getRules(unitId, subUnitId)) {+ ruleIds.push(rule.uid);+ }++ expect(ruleIds).toEqual(['rule-2', 'rule-3', 'rule-1']);+ expect(dataValidationModel.getRuleIndex(unitId, subUnitId, 'rule-1')).toBe(2);+ });++ it('updates validation behavior and removes obsolete rules from the worksheet', async () => {+ await commandService.executeCommand(AddDataValidationMutation.id, {+ unitId,+ subUnitId,+ rule: [+ createRule('keep-rule'),+ createRule('remove-rule'),+ ],+ });++ await commandService.executeCommand(UpdateDataValidationMutation.id, {+ unitId,+ subUnitId,+ ruleId: 'keep-rule',+ payload: {+ type: UpdateRuleType.ALL,+ payload: createRule('keep-rule', {+ type: DataValidationType.TEXT_LENGTH,+ operator: DataValidationOperator.GREATER_THAN,+ formula1: '3',+ formula2: undefined,+ allowBlank: false,+ prompt: 'Enter at least four characters',+ promptTitle: 'Length check',+ ranges: [{ startRow: 2, endRow: 4, startColumn: 1, endColumn: 1 }],+ }),+ },+ });+ await commandService.executeCommand(RemoveDataValidationMutation.id, {+ unitId,+ subUnitId,+ ruleId: 'remove-rule',+ });++ expect(dataValidationModel.getRuleById(unitId, subUnitId, 'remove-rule')).toBeUndefined();+ expect(dataValidationModel.getRuleById(unitId, subUnitId, 'keep-rule')).toMatchObject({+ type: DataValidationType.TEXT_LENGTH,+ operator: DataValidationOperator.GREATER_THAN,+ formula1: '3',+ formula2: undefined,+ allowBlank: false,+ prompt: 'Enter at least four characters',+ promptTitle: 'Length check',+ ranges: [{ startRow: 2, endRow: 4, startColumn: 1, endColumn: 1 }],+ });+ });+});diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.jsonindex bfb5f7b313..9749fd9d2d 100644--- a/packages/docs-drawing-ui/package.json+++ b/packages/docs-drawing-ui/package.json@@ -85,6 +85,7 @@"@univerjs/ui": "workspace:*"},"devDependencies": {+ "@testing-library/react": "^16.3.2","@univerjs-infra/shared": "workspace:*","postcss": "^8.5.15","react": "18.3.1",diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex effa1ee433..3fe7d80122 100644--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -14,11 +14,14 @@* limitations under the License.*/-import type { DependencyIdentifier, DocumentDataModel, ICommand, IDocumentData } from '@univerjs/core';+import type { Dependency, DependencyIdentifier, DocumentDataModel, ICommand, IDocumentData } from '@univerjs/core';import {+ ArrangeTypeEnum,awaitTime,+ BooleanNumber,Direction,DisposableCollection,+ DrawingTypeEnum,ICommandService,IUniverInstanceService,ObjectRelativeFromH,@@ -27,8 +30,17 @@ import {UniverInstanceType,WrapTextType,} from '@univerjs/core';-import { DocContentInsertService, DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';-import { DocDrawingController as CoreDocDrawingController, DocDrawingService, IDocDrawingService } from '@univerjs/docs-drawing';+import {+ DocContentInsertService,+ DocSelectionManagerService,+ DocSkeletonManagerService,+ RichTextEditingMutation,+} from '@univerjs/docs';+import {+ DocDrawingController as CoreDocDrawingController,+ DocDrawingService,+ IDocDrawingService,+} from '@univerjs/docs-drawing';import { DocSelectionRenderService } from '@univerjs/docs-ui';import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';import { DocumentEditArea, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';@@ -36,11 +48,26 @@ import { BehaviorSubject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';import { createDocUiTestBed } from '../../../__tests__/create-doc-ui-test-bed';import { DocDrawingAddRemoveController } from '../../../controllers/doc-drawing-notification.controller';+import { DocDrawingUpdateRenderController } from '../../../controllers/render-controllers/doc-drawing-update.render-controller';+import { DocRefreshDrawingsService } from '../../../services/doc-refresh-drawings.service';+import { ClearDocDrawingTransformerOperation } from '../../operations/clear-drawing-transformer.operation';import { DeleteDocDrawingsCommand } from '../delete-doc-drawing.command';+import { GroupDocDrawingCommand } from '../group-doc-drawing.command';import { InsertDocDrawingCommand } from '../insert-doc-drawing.command';+import { InsertDocImageCommand } from '../insert-image.command';import { MoveDocDrawingsCommand } from '../move-drawings.command';import { RemoveDocDrawingCommand } from '../remove-doc-drawing.command';-import { TextWrappingStyle, UpdateDocDrawingDistanceCommand, UpdateDocDrawingWrappingStyleCommand, UpdateDocDrawingWrapTextCommand, UpdateDrawingDocTransformCommand } from '../update-doc-drawing.command';+import { SetDocDrawingArrangeCommand } from '../set-drawing-arrange.command';+import { UngroupDocDrawingCommand } from '../ungroup-doc-drawing.command';+import {+ IMoveInlineDrawingCommand,+ ITransformNonInlineDrawingCommand,+ TextWrappingStyle,+ UpdateDocDrawingDistanceCommand,+ UpdateDocDrawingWrappingStyleCommand,+ UpdateDocDrawingWrapTextCommand,+ UpdateDrawingDocTransformCommand,+} from '../update-doc-drawing.command';function createBaseDocData(): IDocumentData {return {@@ -101,18 +128,151 @@ function createDrawingDocData(): IDocumentData {};}-function setupDrawingTestBed(docData: IDocumentData) {+function createMultiDrawingDocData(): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream: '\b\b\b\r\n',+ customBlocks: [+ { startIndex: 0, blockId: 'drawing-a' },+ { startIndex: 1, blockId: 'drawing-b' },+ { startIndex: 2, blockId: 'drawing-c' },+ ],+ },+ drawings: {+ 'drawing-a': {+ drawingId: 'drawing-a',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: { positionH: { posOffset: 1 }, positionV: { posOffset: 2 } },+ } as never,+ 'drawing-b': {+ drawingId: 'drawing-b',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: { positionH: { posOffset: 3 }, positionV: { posOffset: 4 } },+ } as never,+ 'drawing-c': {+ drawingId: 'drawing-c',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: { positionH: { posOffset: 5 }, positionV: { posOffset: 6 } },+ } as never,+ },+ drawingsOrder: ['drawing-a', 'drawing-b', 'drawing-c'],+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createInlineMoveDocData(): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream: 'A\bB\r\n',+ customBlocks: [{+ startIndex: 1,+ blockId: 'shape-1',+ }],+ },+ headers: {+ 'header-1': {+ headerId: 'header-1',+ body: {+ dataStream: 'Header\r\n',+ customBlocks: [],+ },+ },+ },+ drawings: {+ 'shape-1': {+ drawingId: 'shape-1',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.INLINE,+ docTransform: {+ positionH: { posOffset: 1 },+ positionV: { posOffset: 2 },+ },+ } as never,+ },+ drawingsOrder: ['shape-1'],+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createGroupedDrawingDocData(): IDocumentData {+ const docData = createMultiDrawingDocData();+ docData.drawings!['group-1'] = {+ drawingId: 'group-1',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: { positionH: { posOffset: 0 }, positionV: { posOffset: 0 } },+ } as never;+ docData.drawings!['drawing-a'].groupId = 'group-1';+ docData.drawings!['drawing-b'].groupId = 'group-1';+ docData.drawingsOrder = ['drawing-c', 'group-1'];++ return docData;+}++class TestDocDrawingUpdateRenderController {+ private _inserted = false;++ get inserted(): boolean {+ return this._inserted;+ }++ insertDocImage(): boolean {+ this._inserted = true;+ return true;+ }+}++function setupDrawingTestBed(docData: IDocumentData, dependencies: Dependency[] = []) {const refreshControls = vi.fn();const testBed = createDocUiTestBed(docData, [[IRenderManagerService, { useClass: RenderManagerService }],+ ...dependencies,]);const { univer, get } = testBed;const injector = testBed.injector;const scene = new DisposableCollection() as any;- scene.getTransformerByCreate = () => ({+ const transformer = {refreshControls,- });+ debounceRefreshControls: refreshControls,+ };+ scene.getTransformerByCreate = () => transformer;+ scene.getTransformer = () => transformer;+ let currentSegment = '';+ let currentSegmentPage = 0;get(IRenderManagerService).addRender('test-doc', {unitId: 'test-doc',type: UniverInstanceType.UNIVER_DOC,@@ -125,7 +285,10 @@ function setupDrawingTestBed(docData: IDocumentData) {with: <T>(token: DependencyIdentifier<T>) => {if (token === DocSelectionRenderService) {return {- getSegment: () => '',+ getSegment: () => currentSegment,+ setSegment: (segmentId: string) => currentSegment = segmentId,+ getSegmentPage: () => currentSegmentPage,+ setSegmentPage: (page: number) => currentSegmentPage = page,} as T;}@@ -140,6 +303,7 @@ function setupDrawingTestBed(docData: IDocumentData) {injector.add([IDocDrawingService, { useClass: DocDrawingService }]);injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);injector.add([DocContentInsertService]);+ injector.add([DocRefreshDrawingsService]);injector.add([CoreDocDrawingController]);injector.add([DocDrawingAddRemoveController]);@@ -149,6 +313,13 @@ function setupDrawingTestBed(docData: IDocumentData) {RemoveDocDrawingCommand,DeleteDocDrawingsCommand,MoveDocDrawingsCommand,+ GroupDocDrawingCommand,+ UngroupDocDrawingCommand,+ SetDocDrawingArrangeCommand,+ ClearDocDrawingTransformerOperation,+ InsertDocImageCommand,+ IMoveInlineDrawingCommand,+ ITransformNonInlineDrawingCommand,UpdateDocDrawingDistanceCommand,UpdateDocDrawingWrappingStyleCommand,UpdateDocDrawingWrapTextCommand,@@ -267,6 +438,45 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});+ it('replaces the selected drawing block when inserting a new drawing over a selection', async () => {+ const testBed = setupDrawingTestBed(createDrawingDocData());++ testBed.selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 1,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ expect(await testBed.commandService.executeCommand(InsertDocDrawingCommand.id, {+ drawings: [{+ drawingId: 'shape-2',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ positionH: { posOffset: 10 },+ positionV: { posOffset: 20 },+ },+ }],+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(doc.getBody()?.dataStream).toBe('\b\r\n');+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 0, blockId: 'shape-2' }]);+ expect(doc.getSnapshot().drawings?.['shape-1']).toBeUndefined();+ expect(doc.getSnapshot().drawings?.['shape-2']).toMatchObject({ drawingId: 'shape-2' });+ expect(doc.getSnapshot().drawingsOrder).toEqual(['shape-2']);++ testBed.univer.dispose();+ });+it('deletes a focused drawing through the command pipeline and removes it from the document and services', async () => {const testBed = setupDrawingTestBed(createDrawingDocData());@@ -449,6 +659,81 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});+ it('updates drawing behind-text wrapping and keeps the anchor position in page coordinates', async () => {+ const docData = createDrawingDocData();+ docData.drawings!['shape-1'].docTransform = {+ positionH: {+ relativeFrom: ObjectRelativeFromH.MARGIN,+ posOffset: 999,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 999,+ },+ angle: 0,+ } as never;+ const testBed = setupDrawingTestBed(docData);+ const skeletonManager = testBed.injector.get(DocSkeletonManagerService);+ vi.spyOn(skeletonManager, 'getViewModel').mockReturnValue({+ getEditArea: () => DocumentEditArea.BODY,+ reset: vi.fn(),+ } as never);+ vi.spyOn(skeletonManager, 'getSkeleton').mockReturnValue({+ getSkeletonData: () => ({+ pages: [{+ marginTop: 72,+ marginLeft: 90,+ marginBottom: 72,+ pageHeight: 800,+ pageWidth: 600,+ headerId: '',+ footerId: '',+ skeDrawings: new Map([+ ['shape-1', {+ drawingId: 'shape-1',+ aLeft: 140,+ aTop: 30,+ columnLeft: 0,+ lineTop: 0,+ blockAnchorTop: 0,+ drawingOrigin: docData.drawings!['shape-1'],+ }],+ ]),+ skeTables: new Map(),+ }],+ skeHeaders: new Map(),+ skeFooters: new Map(),+ }),+ } as never);++ expect(await testBed.commandService.executeCommand(UpdateDocDrawingWrappingStyleCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawings: [{+ drawingId: 'shape-1',+ }],+ wrappingStyle: TextWrappingStyle.BEHIND_TEXT,+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;+ const drawing = doc.getSnapshot().drawings?.['shape-1'];++ expect(drawing?.layoutType).toBe(PositionedObjectLayoutType.WRAP_NONE);+ expect(drawing?.behindDoc).toBe(BooleanNumber.TRUE);+ expect(drawing?.docTransform.positionH).toEqual({+ relativeFrom: ObjectRelativeFromH.MARGIN,+ posOffset: 50,+ });+ expect(drawing?.docTransform.positionV).toEqual({+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 102,+ });++ testBed.univer.dispose();+ });+it('updates drawing doc transform through the command pipeline', async () => {const testBed = setupDrawingTestBed(createDrawingDocData());@@ -473,4 +758,255 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});++ it('transforms a non-inline drawing and persists position, size and angle changes', async () => {+ const testBed = setupDrawingTestBed(createDrawingDocData());++ expect(await testBed.commandService.executeCommand(ITransformNonInlineDrawingCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawing: {+ drawingId: 'shape-1',+ },+ offset: 0,+ segmentId: '',+ segmentPage: 0,+ docTransform: {+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 30,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 40,+ },+ size: {+ width: 120,+ height: 80,+ },+ angle: 15,+ },+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(doc.getSnapshot().drawings?.['shape-1'].docTransform).toMatchObject({+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 30,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 40,+ },+ size: {+ width: 120,+ height: 80,+ },+ angle: 15,+ });+ expect(testBed.refreshControls).toHaveBeenCalled();++ testBed.univer.dispose();+ });++ it('refreshes inline drawing controls when the inline anchor needs to be recalculated', async () => {+ const testBed = setupDrawingTestBed(createDrawingDocData());+ const skeletonManager = testBed.injector.get(DocSkeletonManagerService);+ vi.spyOn(skeletonManager, 'getSkeleton').mockReturnValue({} as never);++ expect(await testBed.commandService.executeCommand(IMoveInlineDrawingCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawing: {+ drawingId: 'shape-1',+ },+ offset: 0,+ segmentId: '',+ segmentPage: 0,+ needRefreshDrawings: true,+ })).toBe(true);++ expect(testBed.refreshControls).toHaveBeenCalled();++ testBed.univer.dispose();+ });++ it('moves an inline drawing to an earlier text anchor in the same document segment', async () => {+ const testBed = setupDrawingTestBed(createInlineMoveDocData());+ const skeletonManager = testBed.injector.get(DocSkeletonManagerService);+ vi.spyOn(skeletonManager, 'getSkeleton').mockReturnValue({} as never);++ expect(await testBed.commandService.executeCommand(IMoveInlineDrawingCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawing: {+ drawingId: 'shape-1',+ },+ offset: 0,+ segmentId: '',+ segmentPage: 0,+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(doc.getBody()?.dataStream).toBe('\bAB\r\n');+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 0, blockId: 'shape-1' }]);+ expect(testBed.refreshControls).toHaveBeenCalled();++ testBed.univer.dispose();+ });++ it('moves an inline drawing from the document body into a header segment', async () => {+ const testBed = setupDrawingTestBed(createInlineMoveDocData());+ const skeletonManager = testBed.injector.get(DocSkeletonManagerService);+ vi.spyOn(skeletonManager, 'getSkeleton').mockReturnValue({} as never);++ expect(await testBed.commandService.executeCommand(IMoveInlineDrawingCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawing: {+ drawingId: 'shape-1',+ },+ offset: 2,+ segmentId: 'header-1',+ segmentPage: 1,+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;+ const header = doc.getSelfOrHeaderFooterModel('header-1');++ expect(doc.getBody()?.dataStream).toBe('AB\r\n');+ expect(doc.getBody()?.customBlocks).toEqual([]);+ expect(header.getBody()?.dataStream).toBe('He\bader\r\n');+ expect(header.getBody()?.customBlocks).toEqual([{ startIndex: 2, blockId: 'shape-1' }]);+ expect(testBed.refreshControls).toHaveBeenCalled();++ testBed.univer.dispose();+ });++ it('arranges doc drawing order through the rich text mutation pipeline', async () => {+ const testBed = setupDrawingTestBed(createMultiDrawingDocData());+ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-a', 'drawing-b', 'drawing-c']);++ expect(await testBed.commandService.executeCommand(SetDocDrawingArrangeCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingIds: ['drawing-a'],+ arrangeType: ArrangeTypeEnum.front,+ })).toBe(true);+ await awaitTime(0);+ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-b', 'drawing-c', 'drawing-a']);++ expect(await testBed.commandService.executeCommand(SetDocDrawingArrangeCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingIds: ['drawing-a'],+ arrangeType: ArrangeTypeEnum.backward,+ })).toBe(true);+ await awaitTime(0);+ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-b', 'drawing-a', 'drawing-c']);++ expect(await testBed.commandService.executeCommand(SetDocDrawingArrangeCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingIds: ['drawing-b'],+ arrangeType: ArrangeTypeEnum.forward,+ })).toBe(true);+ await awaitTime(0);+ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-a', 'drawing-b', 'drawing-c']);++ expect(await testBed.commandService.executeCommand(SetDocDrawingArrangeCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingIds: ['drawing-c'],+ arrangeType: ArrangeTypeEnum.back,+ })).toBe(true);+ await awaitTime(0);+ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-c', 'drawing-a', 'drawing-b']);++ testBed.univer.dispose();+ });++ it('keeps doc drawings unchanged because docs grouping is currently not applied', async () => {+ const testBed = setupDrawingTestBed(createMultiDrawingDocData());+ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(await testBed.commandService.executeCommand(GroupDocDrawingCommand.id, [{+ parent: {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingId: 'group-1',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ },+ children: [+ { unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'drawing-a', groupId: 'group-1' },+ { unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'drawing-b', groupId: 'group-1' },+ ],+ }])).toBe(false);++ expect(doc.getSnapshot().drawings?.['group-1']).toBeUndefined();+ expect(doc.getSnapshot().drawings?.['drawing-a'].groupId).toBeUndefined();+ expect(doc.getSnapshot().drawings?.['drawing-b'].groupId).toBeUndefined();+ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-a', 'drawing-b', 'drawing-c']);++ testBed.univer.dispose();+ });++ it('keeps grouped doc drawings unchanged because docs ungrouping is currently not applied', async () => {+ const testBed = setupDrawingTestBed(createGroupedDrawingDocData());+ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(await testBed.commandService.executeCommand(UngroupDocDrawingCommand.id, [{+ parent: {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingId: 'group-1',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ },+ children: [+ { unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'drawing-a' },+ { unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'drawing-b' },+ ],+ }])).toBe(false);++ expect(doc.getSnapshot().drawings?.['group-1']).toMatchObject({ drawingId: 'group-1' });+ expect(doc.getSnapshot().drawings?.['drawing-a'].groupId).toBe('group-1');+ expect(doc.getSnapshot().drawings?.['drawing-b'].groupId).toBe('group-1');+ expect(doc.getSnapshot().drawingsOrder).toEqual(['drawing-c', 'group-1']);++ testBed.univer.dispose();+ });++ it('clears the doc drawing transformer for the active render scene', async () => {+ const testBed = setupDrawingTestBed(createDrawingDocData());++ expect(await testBed.commandService.executeCommand(ClearDocDrawingTransformerOperation.id, ['test-doc'])).toBe(true);+ expect(testBed.refreshControls).toHaveBeenCalled();++ testBed.univer.dispose();+ });++ it('inserts an image through the current doc render controller', async () => {+ const testBed = setupDrawingTestBed(createBaseDocData(), [+ [DocDrawingUpdateRenderController, { useClass: TestDocDrawingUpdateRenderController as never }],+ ]);+ const updateController = testBed.injector.get(DocDrawingUpdateRenderController) as unknown as TestDocDrawingUpdateRenderController;++ expect(await testBed.commandService.executeCommand(InsertDocImageCommand.id, { files: null })).toBe(true);+ expect(updateController.inserted).toBe(true);++ testBed.univer.dispose();+ });});diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.tsx b/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.tssimilarity index 83%rename from packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.tsxrename to packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.tsindex 1bd7ead975..07d8c1a298 100644--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.tsx+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.ts@@ -15,14 +15,12 @@*/import type { IDocFloatDom } from '@univerjs/docs-drawing';-import type { IPrintingFloatDomProps } from '../views/DocPrintingFloatDom';import { Disposable, DOC_DRAWING_PRINTING_COMPONENT_KEY, DrawingTypeEnum, Inject, Injector } from '@univerjs/core';-import { render, unmount } from '@univerjs/design';import { DocPrintInterceptorService } from '@univerjs/docs-ui';import { IDrawingManagerService } from '@univerjs/drawing';import { DrawingRenderService } from '@univerjs/drawing-ui';-import { ComponentManager, connectInjector } from '@univerjs/ui';-import { DocPrintingFloatDom } from '../views/DocPrintingFloatDom';+import { ComponentManager } from '@univerjs/ui';+import { mountDocPrintingFloatDom } from '../views/DocPrintingFloatDom';export class DocDrawingPrintingController extends Disposable {constructor(@@ -93,22 +91,21 @@ export class DocDrawingPrintingController extends Disposable {return null;}).filter(Boolean) as IDocFloatDom[];- const PrintingFloatDomInjector = connectInjector(DocPrintingFloatDom, this._injector) as React.ComponentType<IPrintingFloatDomProps>;-- render(- <PrintingFloatDomInjector- unitId={unitId}- floatDomInfos={floatDomInfos}- scene={pos.scene}- skeleton={pos.skeleton}- offset={pos.offset}- bound={pos.bound}- />,- pos.root+ const unmountPrintingFloatDom = mountDocPrintingFloatDom(+ {+ unitId,+ floatDomInfos,+ scene: pos.scene,+ skeleton: pos.skeleton,+ offset: pos.offset,+ bound: pos.bound,+ },+ pos.root,+ this._injector);disposableCollection?.add(() => {- unmount(pos.root);+ unmountPrintingFloatDom();});return next(disposableCollection);diff --git a/packages/docs-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.ts b/packages/docs-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.tsindex dfe454690b..7344c9a628 100644--- a/packages/docs-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.ts+++ b/packages/docs-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.ts@@ -14,12 +14,19 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { DocRefreshDrawingsService } from '../doc-refresh-drawings.service';+function createService(): DocRefreshDrawingsService {+ const injector = new Injector();+ injector.add([DocRefreshDrawingsService]);+ return injector.get(DocRefreshDrawingsService);+}+describe('DocRefreshDrawingsService', () => {it('emits the latest document skeleton refresh request', () => {- const service = new DocRefreshDrawingsService();+ const service = createService();const values: unknown[] = [];const sub = service.refreshDrawings$.subscribe((value) => values.push(value));const skeleton = { id: 'skeleton-1' };diff --git a/packages/docs-drawing-ui/src/views/DocPrintingFloatDom.tsx b/packages/docs-drawing-ui/src/views/DocPrintingFloatDom.tsxindex 5d8a8feb85..f6e5905136 100644--- a/packages/docs-drawing-ui/src/views/DocPrintingFloatDom.tsx+++ b/packages/docs-drawing-ui/src/views/DocPrintingFloatDom.tsx@@ -14,10 +14,13 @@* limitations under the License.*/+import type { Injector } from '@univerjs/core';import type { IDocFloatDom } from '@univerjs/docs-drawing';import type { DocumentSkeleton, IBoundRectNoAngle, Scene } from '@univerjs/engine-render';import type { IFloatDom, IFloatDomLayout } from '@univerjs/ui';-import { PrintFloatDomSingle } from '@univerjs/ui';+import type { ComponentType } from 'react';+import { render, unmount } from '@univerjs/design';+import { connectInjector, PrintFloatDomSingle } from '@univerjs/ui';import { useMemo } from 'react';import { BehaviorSubject } from 'rxjs';import { calcDocFloatDomPositionByRect } from '../controllers/doc-float-dom.controller';@@ -75,3 +78,11 @@ export const DocPrintingFloatDom = (props: IPrintingFloatDomProps) => {</div>);};++export function mountDocPrintingFloatDom(props: IPrintingFloatDomProps, root: HTMLElement, injector: Injector): () => void {+ const PrintingFloatDomInjector = connectInjector(DocPrintingFloatDom, injector) as ComponentType<IPrintingFloatDomProps>;++ render(<PrintingFloatDomInjector {...props} />, root);++ return () => unmount(root);+}diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsxnew file mode 100644index 0000000000..3372c0566a--- /dev/null+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingTextWrap.spec.tsx@@ -0,0 +1,345 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { DependencyIdentifier, DocumentDataModel, ICommand, IDocumentData } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import {+ BooleanNumber,+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ ObjectRelativeFromH,+ ObjectRelativeFromV,+ PositionedObjectLayoutType,+ UniverInstanceType,+ WrapTextType,+} from '@univerjs/core';+import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { DocDrawingController, DocDrawingService, IDocDrawingService } from '@univerjs/docs-drawing';+import { DocSelectionRenderService } from '@univerjs/docs-ui';+import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { createDocUiTestBed } from '../../../__tests__/create-doc-ui-test-bed';+import {+ UpdateDocDrawingDistanceCommand,+ UpdateDocDrawingWrappingStyleCommand,+ UpdateDocDrawingWrapTextCommand,+} from '../../../commands/commands/update-doc-drawing.command';+import locale from '../../../locale/en-US';+import { DocDrawingTextWrap } from '../DocDrawingTextWrap';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'doc-drawing-text-wrap-doc';+const DRAWING_ID = 'image-1';++class TestDocSkeletonManagerService {+ getSkeleton() {+ return {+ getSkeletonData: () => ({+ pages: [{+ marginTop: 72,+ marginLeft: 90,+ marginBottom: 72,+ pageWidth: 594,+ pageHeight: 840,+ headerId: '',+ footerId: '',+ skeDrawings: new Map([+ [DRAWING_ID, {+ drawingId: DRAWING_ID,+ aLeft: 24,+ aTop: 42,+ columnLeft: 8,+ lineTop: 10,+ blockAnchorTop: 12,+ }],+ ]),+ skeTables: new Map(),+ }],+ skeHeaders: new Map(),+ skeFooters: new Map(),+ }),+ };+ }++ getViewModel() {+ return {+ getEditArea: () => DocumentEditArea.BODY,+ };+ }+}++class TestDocSelectionRenderService {+ private _segment = '';+ private _segmentPage = 0;++ getSegment() {+ return this._segment;+ }++ setSegment(segment: string) {+ this._segment = segment;+ }++ getSegmentPage() {+ return this._segmentPage;+ }++ setSegmentPage(page: number) {+ this._segmentPage = page;+ }++ blur() {+ return undefined;+ }+}++class TestScene {+ controlRefreshCount = 0;++ getTransformerByCreate() {+ return {+ refreshControls: () => {+ this.controlRefreshCount += 1;+ },+ };+ }+}++class TestRenderManagerService {+ private readonly _scene = new TestScene();+ private readonly _skeletonManager = new TestDocSkeletonManagerService();+ private readonly _selectionRenderService = new TestDocSelectionRenderService();+ private _render: unknown;++ addRender(_unitId: string, render: unknown) {+ this._render = render;+ }++ getRenderUnitById(_unitId: string) {+ return this._render;+ }++ getRenderById(_unitId: string) {+ return {+ ...(this._render as object),+ scene: this._scene,+ with: <T,>(token: DependencyIdentifier<T>) => {+ if (token === DocSkeletonManagerService) {+ return this._skeletonManager as T;+ }++ if (token === DocSelectionRenderService) {+ return this._selectionRenderService as T;+ }++ throw new Error(`Unexpected render dependency: ${String(token)}`);+ },+ };+ }+}++function createDocData(): IDocumentData {+ return {+ id: UNIT_ID,+ body: {+ dataStream: '\b\r\n',+ customBlocks: [{+ startIndex: 0,+ blockId: DRAWING_ID,+ }],+ },+ drawings: {+ [DRAWING_ID]: {+ drawingId: DRAWING_ID,+ unitId: UNIT_ID,+ subUnitId: UNIT_ID,+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ wrapText: WrapTextType.BOTH_SIDES,+ distT: 1,+ distL: 2,+ distB: 3,+ distR: 4,+ docTransform: {+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 0,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 0,+ },+ },+ } as never,+ },+ drawingsOrder: [DRAWING_ID],+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createPanelTestBed() {+ const testBed = createDocUiTestBed(createDocData(), [+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const { injector } = testBed;++ injector.add([DocDrawingService]);+ injector.add([IDocDrawingService, { useClass: DocDrawingService }]);+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);+ injector.add([DocDrawingController]);++ const commandService = injector.get(ICommandService);+ [+ UpdateDocDrawingDistanceCommand,+ UpdateDocDrawingWrappingStyleCommand,+ UpdateDocDrawingWrapTextCommand,+ RichTextEditingMutation as unknown as ICommand,+ ].forEach((command) => commandService.registerCommand(command));++ injector.get(LocaleService).load({+ [LocaleType.EN_US]: locale,+ });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);++ injector.get(DocDrawingController).loadDrawingDataForUnit(UNIT_ID);+ injector.get(IDrawingManagerService).focusDrawing([{+ unitId: UNIT_ID,+ subUnitId: UNIT_ID,+ drawingId: DRAWING_ID,+ }]);++ return testBed;+}++function renderPanel(root: Root, testBed: ReturnType<typeof createPanelTestBed>) {+ const drawing = testBed.doc.getSnapshot().drawings![DRAWING_ID];++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <DocDrawingTextWrap drawings={[drawing as never]} />+ </RediContext.Provider>+ );+ });+}++function currentDrawing(testBed: ReturnType<typeof createPanelTestBed>) {+ return testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>(UNIT_ID, UniverInstanceType.UNIVER_DOC)!+ .getSnapshot()+ .drawings![DRAWING_ID];+}++function inputByLabelText(text: string) {+ const label = Array.from(document.querySelectorAll('label'))+ .find((label) => label.textContent === text);+ return label?.querySelector('input') as HTMLInputElement;+}++function inputInField(text: string) {+ const label = Array.from(document.querySelectorAll('span'))+ .find((span) => span.textContent === text);+ return label?.parentElement?.querySelector('input') as HTMLInputElement;+}++function setInputValue(input: HTMLInputElement, value: string) {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++describe('DocDrawingTextWrap', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createPanelTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('persists behind-text wrapping on the focused drawing', async () => {+ currentTestBed = createPanelTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ renderPanel(root, currentTestBed);++ await act(async () => {+ inputByLabelText('Behind text').click();+ await Promise.resolve();+ });++ expect(currentDrawing(currentTestBed)).toMatchObject({+ layoutType: PositionedObjectLayoutType.WRAP_NONE,+ behindDoc: BooleanNumber.TRUE,+ docTransform: {+ positionH: {+ relativeFrom: ObjectRelativeFromH.PAGE,+ posOffset: 24,+ },+ positionV: {+ relativeFrom: ObjectRelativeFromV.PAGE,+ posOffset: 114,+ },+ },+ });+ });++ it('persists left distance from text on the focused drawing', async () => {+ currentTestBed = createPanelTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ renderPanel(root, currentTestBed);++ const leftDistanceInput = inputInField('Left(px)');++ await act(async () => {+ setInputValue(leftDistanceInput, '12.5');+ await Promise.resolve();+ });++ expect(currentDrawing(currentTestBed)).toMatchObject({+ distT: 1,+ distL: 12.5,+ distB: 3,+ distR: 4,+ });+ });+});diff --git a/packages/docs-hyper-link-ui/src/commands/commands/__tests__/hyper-link.command.spec.ts b/packages/docs-hyper-link-ui/src/commands/commands/__tests__/hyper-link.command.spec.tsnew file mode 100644index 0000000000..5d5be8895a--- /dev/null+++ b/packages/docs-hyper-link-ui/src/commands/commands/__tests__/hyper-link.command.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 type { DocumentDataModel, ICommand, IDocumentData } from '@univerjs/core';+import { CustomRangeType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { AddDocHyperLinkCommand } from '../add-link.command';+import { DeleteDocHyperLinkCommand } from '../delete-link.command';+import { UpdateDocHyperLinkCommand } from '../update-link.command';++const unitId = 'hyper-link-doc';++function createDocData(): IDocumentData {+ return {+ id: unitId,+ body: {+ dataStream: 'Hello world\r\n',+ customRanges: [{+ startIndex: 6,+ endIndex: 10,+ rangeId: 'existing-link',+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: 'https://before.invalid',+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++describe('doc hyperlink commands', () => {+ let univer: Univer;+ let commandService: ICommandService;++ function getDocBody() {+ return univer.__getInjector()+ .get(IUniverInstanceService)+ .getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)+ ?.getBody();+ }++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);++ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData());+ injector.get(IUniverInstanceService).focusUnit(unitId);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(AddDocHyperLinkCommand);+ commandService.registerCommand(DeleteDocHyperLinkCommand);+ commandService.registerCommand(UpdateDocHyperLinkCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('adds a hyperlink to the selected document text', async () => {+ const result = await commandService.executeCommand(AddDocHyperLinkCommand.id, {+ unitId,+ payload: 'https://added.invalid',+ selections: [{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ segmentId: '',+ }],+ });++ let addedLink;+ for (const range of getDocBody()?.customRanges ?? []) {+ if (range.properties?.url === 'https://added.invalid') {+ addedLink = range;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(addedLink).toMatchObject({+ startIndex: 0,+ endIndex: 4,+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: 'https://added.invalid',+ },+ });+ });++ it('removes a hyperlink while keeping the document text', async () => {+ const result = await commandService.executeCommand(DeleteDocHyperLinkCommand.id, {+ unitId,+ linkId: 'existing-link',+ });++ let removedLinkStillExists = false;+ for (const range of getDocBody()?.customRanges ?? []) {+ if (range.rangeId === 'existing-link') {+ removedLinkStillExists = true;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(getDocBody()?.dataStream).toBe('Hello world\r\n');+ expect(removedLinkStillExists).toBe(false);+ });++ it('does not remove document hyperlinks when delete parameters are missing or target a missing link', async () => {+ expect(await commandService.executeCommand(DeleteDocHyperLinkCommand.id)).toBe(false);+ expect(await commandService.executeCommand(DeleteDocHyperLinkCommand.id, {+ unitId,+ linkId: 'missing-link',+ })).toBe(false);++ let existingLinkStillExists = false;+ for (const range of getDocBody()?.customRanges ?? []) {+ if (range.rangeId === 'existing-link') {+ existingLinkStillExists = true;+ break;+ }+ }++ expect(existingLinkStillExists).toBe(true);+ expect(getDocBody()?.dataStream).toBe('Hello world\r\n');+ });++ it('updates a hyperlink label and target for the selected document text', async () => {+ const selectionManager = univer.__getInjector().get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId,+ subUnitId: unitId,+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 6,+ endOffset: 11,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ const result = await commandService.executeCommand(UpdateDocHyperLinkCommand.id, {+ unitId,+ linkId: 'existing-link',+ payload: 'https://after.invalid',+ label: 'Univer',+ segmentId: '',+ });++ let updatedLink;+ for (const range of getDocBody()?.customRanges ?? []) {+ if (range.rangeId === 'existing-link') {+ updatedLink = range;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(getDocBody()?.dataStream).toBe('Hello Univer\r\n');+ expect(updatedLink).toMatchObject({+ startIndex: 6,+ endIndex: 11,+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: 'https://after.invalid',+ },+ });+ });+});diff --git a/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.tsnew file mode 100644index 0000000000..b8d5d66ed4--- /dev/null+++ b/packages/docs-hyper-link-ui/src/commands/operations/__tests__/popup.operation.spec.ts@@ -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 type { IDocumentData } from '@univerjs/core';+import { CustomRangeType, ICommandService, toDisposable, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DocHyperLinkPopupService } from '../../../services/hyper-link-popup.service';+import {+ ClickDocHyperLinkOperation,+ ShowDocHyperLinkEditPopupOperation,+ ToggleDocHyperLinkInfoPopupOperation,+} from '../popup.operation';++const unitId = 'hyper-link-popup-doc';++function createDocData(): IDocumentData {+ return {+ id: unitId,+ body: {+ dataStream: 'Hello world\r\n',+ customRanges: [{+ rangeId: 'unsafe-link',+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 4,+ properties: {+ url: 'javascript:alert(1)',+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++class TestDocCanvasPopManagerService {+ attachPopupToRange() {+ return toDisposable(() => {});+ }+}++describe('doc hyperlink popup operations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let selectionManager: DocSelectionManagerService;+ let popupService: DocHyperLinkPopupService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocSelectionManagerService]);+ injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);+ injector.add([DocHyperLinkPopupService]);++ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData());+ commandService = injector.get(ICommandService);+ commandService.registerCommand(ShowDocHyperLinkEditPopupOperation);+ commandService.registerCommand(ToggleDocHyperLinkInfoPopupOperation);+ commandService.registerCommand(ClickDocHyperLinkOperation);+ selectionManager = injector.get(DocSelectionManagerService);+ popupService = injector.get(DocHyperLinkPopupService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId,+ subUnitId: unitId,+ });+ });++ afterEach(() => {+ univer.dispose();+ });++ it('opens the hyperlink editor for a selected document range', async () => {+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ const result = await commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id);++ expect(result).toBe(true);+ expect(popupService.editing).toBeUndefined();+ });++ it('keeps the hyperlink editor closed when there is no selected text', async () => {+ const result = await commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id);++ expect(result).toBe(false);+ expect(popupService.editing).toBeNull();+ });++ it('opens the hyperlink editor for an existing link and stores its range context', async () => {+ const link = {+ unitId,+ linkId: 'link-1',+ startIndex: 6,+ endIndex: 10,+ segmentId: '',+ };++ const result = await commandService.executeCommand(ShowDocHyperLinkEditPopupOperation.id, { link });++ expect(result).toBe(true);+ expect(popupService.editing).toEqual(link);+ });++ it('shows and hides hyperlink information for the selected link', async () => {+ const link = {+ unitId,+ linkId: 'link-1',+ startIndex: 6,+ endIndex: 10,+ segmentId: '',+ };++ const showResult = await commandService.executeCommand(ToggleDocHyperLinkInfoPopupOperation.id, link);+ expect(showResult).toBe(true);+ expect(popupService.showing).toEqual(link);++ const hideResult = await commandService.executeCommand(ToggleDocHyperLinkInfoPopupOperation.id);+ expect(hideResult).toBe(true);+ expect(popupService.showing).toBeNull();+ });++ it('does not open unsafe hyperlink URLs', async () => {+ const result = await commandService.executeCommand(ClickDocHyperLinkOperation.id, {+ unitId,+ linkId: 'unsafe-link',+ segmentId: '',+ });++ expect(result).toBe(false);+ });+});diff --git a/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.ts b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.service.spec.tsnew file mode 100644index 0000000000..3ac19779d2--- /dev/null+++ b/packages/docs-hyper-link-ui/src/services/__tests__/hyper-link-popup.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 {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ DocumentDataModel,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ UniverInstanceService,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { describe, expect, it } from 'vitest';+import { DocHyperLinkPopupService } from '../hyper-link-popup.service';++class CapturingDocCanvasPopManagerService {+ readonly attached: unknown[] = [];+ readonly disposed: number[] = [];++ attachPopupToRange(range: unknown, popup: unknown, unitId: string) {+ this.attached.push({ range, popup, unitId });+ const order = this.attached.length;+ return { dispose: () => this.disposed.push(order) };+ }+}++const CapturingDocCanvasPopManagerServiceCtor = CapturingDocCanvasPopManagerService as unknown as typeof DocCanvasPopManagerService;++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocCanvasPopManagerService, { useClass: CapturingDocCanvasPopManagerServiceCtor }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocHyperLinkPopupService]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({ id: 'doc-1' }));+ const selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });+ const popupManager = injector.get(DocCanvasPopManagerService) as unknown as CapturingDocCanvasPopManagerService;++ return {+ service: injector.get(DocHyperLinkPopupService),+ selectionManager,+ attached: popupManager.attached,+ disposed: popupManager.disposed,+ };+}++describe('DocHyperLinkPopupService', () => {+ it('opens edit and info popups around the selected document link and disposes previous popups', () => {+ const { service, selectionManager, attached, disposed } = createService();+ const refreshes: unknown[] = [];+ const refreshSub = selectionManager.refreshSelection$.subscribe((value) => refreshes.push(value));+ const link = {+ unitId: 'doc-1',+ linkId: 'link-1',+ startIndex: 4,+ endIndex: 8,+ };++ service.showEditPopup('doc-1', link);+ expect(service.editing).toEqual(link);+ expect(refreshes.at(-1)).toMatchObject({ docRanges: [{ startOffset: 4, endOffset: 9 }] });+ expect(attached).toMatchObject([{ range: { startOffset: 4, endOffset: 9, collapsed: false }, unitId: 'doc-1' }]);++ service.showInfoPopup(link);+ expect(service.showing).toEqual(link);+ expect(attached.at(-1)).toMatchObject({+ range: { startOffset: 4, endOffset: 9, collapsed: false },+ unitId: 'doc-1',+ });++ service.hideEditPopup();+ service.hideInfoPopup();+ expect(service.editing).toBeNull();+ expect(service.showing).toBeNull();+ expect(disposed).toEqual([1, 2]);++ refreshSub.unsubscribe();+ });++ it('opens the edit popup from the current text selection when creating a new hyperlink', () => {+ const { service, selectionManager, attached, disposed } = createService();+ selectionManager.__TEST_ONLY_add([{+ startOffset: 1,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ }]);++ const firstPopup = service.showEditPopup('doc-1', null);+ const secondPopup = service.showEditPopup('doc-1', null);++ expect(firstPopup).not.toBeNull();+ expect(secondPopup).not.toBeNull();+ expect(service.editing).toBeNull();+ expect(attached).toMatchObject([+ { range: { startOffset: 1, endOffset: 5, collapsed: false }, unitId: 'doc-1' },+ { range: { startOffset: 1, endOffset: 5, collapsed: false }, unitId: 'doc-1' },+ ]);+ expect(disposed).toEqual([1]);+ });++ it('reuses an already visible link popup and replaces it only when the hovered link changes', () => {+ const { service, attached, disposed } = createService();+ const firstLink = {+ unitId: 'doc-1',+ linkId: 'link-1',+ startIndex: 4,+ endIndex: 8,+ };+ const secondLink = {+ unitId: 'doc-1',+ linkId: 'link-2',+ startIndex: 0,+ endIndex: 3,+ };++ const firstPopup = service.showInfoPopup(firstLink);+ const duplicatePopup = service.showInfoPopup(firstLink);+ const secondPopup = service.showInfoPopup(secondLink);++ expect(firstPopup).not.toBeNull();+ expect(duplicatePopup).toBeUndefined();+ expect(secondPopup).not.toBeNull();+ expect(attached).toHaveLength(2);+ expect(service.showing).toEqual(secondLink);+ expect(disposed).toEqual([1]);+ });++ it('does not show link information when the target document is not loaded', () => {+ const { service, attached } = createService();++ const popup = service.showInfoPopup({+ unitId: 'missing-doc',+ linkId: 'link-1',+ startIndex: 0,+ endIndex: 4,+ });++ expect(popup).toBeUndefined();+ expect(service.showing).toBeNull();+ expect(attached).toEqual([]);+ });++ it('hides the link information popup when the user clicks outside it', () => {+ const { service, attached, disposed } = createService();+ const link = {+ unitId: 'doc-1',+ linkId: 'link-1',+ startIndex: 4,+ endIndex: 8,+ };++ service.showInfoPopup(link);+ const popupConfig = (attached[0] as { popup: { onClickOutside: () => void } }).popup;+ popupConfig.onClickOutside();++ expect(service.showing).toBeNull();+ expect(disposed).toEqual([1]);+ });+});diff --git a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsxnew file mode 100644index 0000000000..ea78c66af1--- /dev/null+++ b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx@@ -0,0 +1,303 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDocumentData } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import {+ CustomRangeType,+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { IMessageService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';+import { DeleteDocHyperLinkCommand } from '../../commands/commands/delete-link.command';+import { UpdateDocHyperLinkCommand } from '../../commands/commands/update-link.command';+import { ShowDocHyperLinkEditPopupOperation } from '../../commands/operations/popup.operation';+import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';+import { DocHyperLinkEdit } from '../DocHyperLinkEdit';+import { DocLinkPopup } from '../DocLinkPopup';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'doc-link-popup-doc';++class TestDocCanvasPopManagerService {+ attachPopupToRange() {+ return toDisposable(() => undefined);+ }+}++class TestMessageService {+ readonly messages: unknown[] = [];++ show(message: unknown) {+ this.messages.push(message);+ }+}++function setInputText(input: HTMLInputElement, value: string) {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++function createDocData(): IDocumentData {+ return {+ id: UNIT_ID,+ body: {+ dataStream: 'Hello world\r\n',+ customRanges: [{+ startIndex: 6,+ endIndex: 10,+ rangeId: 'existing-link',+ rangeType: CustomRangeType.HYPERLINK,+ properties: {+ url: 'https://univer.ai',+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createPopupTestBed() {+ const univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([IMessageService, { useClass: TestMessageService as never }]);+ injector.add([DocHyperLinkPopupService]);++ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ injector.get(LocaleService).load({+ [LocaleType.EN_US]: {+ 'docs-hyper-link-ui': {+ info: {+ copy: 'Copy',+ edit: 'Edit',+ cancel: 'Remove link',+ coped: 'Copied',+ },+ edit: {+ label: 'Label',+ labelError: 'Label is required',+ address: 'Address',+ addressError: 'Address is invalid',+ cancel: 'Cancel',+ confirm: 'Confirm',+ },+ },+ },+ });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(AddDocHyperLinkCommand);+ commandService.registerCommand(UpdateDocHyperLinkCommand);+ commandService.registerCommand(DeleteDocHyperLinkCommand);+ commandService.registerCommand(ShowDocHyperLinkEditPopupOperation);+ commandService.registerCommand(RichTextEditingMutation);++ return {+ univer,+ injector,+ commandService,+ popupService: injector.get(DocHyperLinkPopupService),+ doc,+ };+}++function showExistingLink(testBed: ReturnType<typeof createPopupTestBed>) {+ testBed.popupService.showInfoPopup({+ unitId: UNIT_ID,+ linkId: 'existing-link',+ startIndex: 6,+ endIndex: 10,+ });+}++function renderPopup(root: Root, container: HTMLDivElement, testBed: ReturnType<typeof createPopupTestBed>) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <DocLinkPopup />+ </RediContext.Provider>+ );+ });++ const actions = Array.from(container.querySelectorAll('.univer-ml-2')) as HTMLElement[];++ return {+ edit: actions[1],+ remove: actions[2],+ };+}++function renderEditPopup(root: Root, testBed: ReturnType<typeof createPopupTestBed>) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <DocHyperLinkEdit />+ </RediContext.Provider>+ );+ });+}++describe('DocLinkPopup', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createPopupTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('opens the hyperlink edit popup for the currently displayed document link', async () => {+ currentTestBed = createPopupTestBed();+ showExistingLink(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const executedCommands: Array<{ id: string; params: unknown }> = [];+ currentTestBed.commandService.onCommandExecuted((command) => {+ executedCommands.push({ id: command.id, params: command.params });+ });+ const actions = renderPopup(root, container, currentTestBed);++ await act(async () => {+ actions.edit.click();+ await Promise.resolve();+ });++ expect(executedCommands).toContainEqual({+ id: ShowDocHyperLinkEditPopupOperation.id,+ params: {+ link: {+ unitId: UNIT_ID,+ linkId: 'existing-link',+ segmentId: undefined,+ segmentPage: undefined,+ startIndex: 6,+ endIndex: 10,+ },+ },+ });+ });++ it('removes the displayed hyperlink while keeping the document text', async () => {+ currentTestBed = createPopupTestBed();+ showExistingLink(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const actions = renderPopup(root, container, currentTestBed);++ await act(async () => {+ actions.remove.click();+ await Promise.resolve();+ });++ const body = currentTestBed.doc.getBody();++ expect(body?.dataStream).toBe('Hello world\r\n');+ expect(body?.customRanges?.some((range) => range.rangeId === 'existing-link')).toBe(false);+ });++ it('updates an existing document hyperlink from the edit form', async () => {+ currentTestBed = createPopupTestBed();+ const selectionManager = currentTestBed.injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: UNIT_ID, subUnitId: UNIT_ID });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 6,+ endOffset: 11,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);+ currentTestBed.popupService.showEditPopup(UNIT_ID, {+ unitId: UNIT_ID,+ linkId: 'existing-link',+ segmentId: '',+ startIndex: 6,+ endIndex: 10,+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ renderEditPopup(root, currentTestBed);++ const [labelInput, linkInput] = Array.from(container.querySelectorAll('input')) as HTMLInputElement[];+ expect(labelInput.value).toBe('world');+ expect(linkInput.value).toBe('https://univer.ai');++ await act(async () => {+ setInputText(labelInput, 'docs');+ setInputText(linkInput, 'docs.univer.ai');+ await Promise.resolve();+ });++ const confirm = Array.from(container.querySelectorAll('button, [data-u-comp="button"]'))+ .find((button) => button.textContent === 'Confirm') as HTMLElement;+ expect(confirm).toBeTruthy();++ await act(async () => {+ confirm.click();+ await Promise.resolve();+ });++ const body = currentTestBed.doc.getBody();+ const updatedLink = body?.customRanges?.find((range) => range.rangeId === 'existing-link');++ expect(body?.dataStream).toBe('Hello docs\r\n');+ expect(updatedLink?.properties).toEqual({+ url: 'https://docs.univer.ai',+ });+ expect(currentTestBed.popupService.editing).toBeNull();+ });+});diff --git a/packages/docs-mention-ui/src/commands/commands/__tests__/doc-mention.command.spec.ts b/packages/docs-mention-ui/src/commands/commands/__tests__/doc-mention.command.spec.tsnew file mode 100644index 0000000000..c7c1ce935d--- /dev/null+++ b/packages/docs-mention-ui/src/commands/commands/__tests__/doc-mention.command.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, ICommand, IDocumentData } from '@univerjs/core';+import { CustomRangeType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { AddDocMentionCommand, DeleteDocMentionCommand } from '../doc-mention.command';++const unitId = 'mention-command-doc';++function createDocData(): IDocumentData {+ return {+ id: unitId,+ body: {+ dataStream: 'Hello @al and @Alice\r\n',+ customRanges: [{+ startIndex: 14,+ endIndex: 19,+ rangeId: 'existing-mention',+ rangeType: CustomRangeType.MENTION,+ wholeEntity: true,+ properties: {+ id: 'existing-mention',+ label: 'Alice',+ type: 'user',+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++describe('doc mention commands', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let doc: DocumentDataModel;+ let selectionManager: DocSelectionManagerService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);++ doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());+ injector.get(IUniverInstanceService).focusUnit(unitId);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(AddDocMentionCommand);+ commandService.registerCommand(DeleteDocMentionCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId,+ subUnitId: unitId,+ });+ });++ afterEach(() => {+ univer.dispose();+ });++ it('replaces typed mention text with a mention entity', async () => {+ selectionManager.__TEST_ONLY_add([{+ startOffset: 6,+ endOffset: 9,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ const result = await commandService.executeCommand(AddDocMentionCommand.id, {+ unitId,+ startIndex: 6,+ mention: {+ id: 'new-mention',+ label: 'Alex',+ type: 'user',+ metadata: {+ email: '[email protected]',+ },+ },+ });++ let mentionRange;+ for (const range of doc.getBody()?.customRanges ?? []) {+ if (range.rangeId === 'new-mention') {+ mentionRange = range;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(doc.getBody()?.dataStream).toBe('Hello @Alex and @Alice\r\n');+ expect(mentionRange).toMatchObject({+ startIndex: 6,+ endIndex: 10,+ rangeType: CustomRangeType.MENTION,+ wholeEntity: true,+ properties: {+ id: 'new-mention',+ label: 'Alex',+ type: 'user',+ email: '[email protected]',+ },+ });+ });++ it('removes an existing mention entity while keeping surrounding text', async () => {+ const result = await commandService.executeCommand(DeleteDocMentionCommand.id, {+ unitId,+ mentionId: 'existing-mention',+ });++ let existingRange;+ for (const range of doc.getBody()?.customRanges ?? []) {+ if (range.rangeId === 'existing-mention') {+ existingRange = range;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(existingRange).toBeUndefined();+ expect(doc.getBody()?.dataStream).toBe('Hello @al and @Alice\r\n');+ });++ it('does not add a mention without an active text range', async () => {+ const result = await commandService.executeCommand(AddDocMentionCommand.id, {+ unitId,+ startIndex: 6,+ mention: {+ id: 'missing-selection',+ label: 'Missing',+ type: 'user',+ },+ });++ expect(result).toBe(false);+ expect(doc.getBody()?.dataStream).toBe('Hello @al and @Alice\r\n');+ });+});diff --git a/packages/docs-mention-ui/src/commands/operations/__tests__/mention-popup.operation.spec.ts b/packages/docs-mention-ui/src/commands/operations/__tests__/mention-popup.operation.spec.tsnew file mode 100644index 0000000000..ac20f04342--- /dev/null+++ b/packages/docs-mention-ui/src/commands/operations/__tests__/mention-popup.operation.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 { ICommandService, Univer } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DocMentionService } from '../../../services/doc-mention.service';+import { CloseMentionEditPopupOperation, ShowMentionEditPopupOperation } from '../mention-popup.operation';++describe('mention edit popup operations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let mentionService: DocMentionService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([DocMentionService]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(ShowMentionEditPopupOperation);+ commandService.registerCommand(CloseMentionEditPopupOperation);+ mentionService = injector.get(DocMentionService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('starts editing a mention at the requested document index', async () => {+ const result = await commandService.executeCommand(ShowMentionEditPopupOperation.id, {+ unitId: 'doc-1',+ startIndex: 8,+ });++ expect(result).toBe(true);+ expect(mentionService.editing).toEqual({+ unitId: 'doc-1',+ index: 8,+ });+ });++ it('closes the active mention editor', async () => {+ await commandService.executeCommand(ShowMentionEditPopupOperation.id, {+ unitId: 'doc-1',+ startIndex: 8,+ });++ const result = await commandService.executeCommand(CloseMentionEditPopupOperation.id);++ expect(result).toBe(true);+ expect(mentionService.editing).toBeUndefined();+ });++ it('does not start mention editing without a target position', async () => {+ const result = await commandService.executeCommand(ShowMentionEditPopupOperation.id);++ expect(result).toBe(false);+ expect(mentionService.editing).toBeUndefined();+ });+});diff --git a/packages/docs-mention-ui/src/services/__tests__/doc-mention-popup.service.spec.ts b/packages/docs-mention-ui/src/services/__tests__/doc-mention-popup.service.spec.tsnew file mode 100644index 0000000000..c222ca2a46--- /dev/null+++ b/packages/docs-mention-ui/src/services/__tests__/doc-mention-popup.service.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 { Injector } from '@univerjs/core';+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { describe, expect, it } from 'vitest';+import { DocMentionPopupService } from '../doc-mention-popup.service';+import { DocMentionService } from '../doc-mention.service';++class CapturingDocCanvasPopManagerService {+ readonly popupDisposals: number[] = [];+ readonly attached: unknown[] = [];++ attachPopupToRange(range: unknown, popup: unknown, unitId: string) {+ this.attached.push({ range, popup, unitId });+ return { dispose: () => this.popupDisposals.push(this.attached.length) };+ }+}++const CapturingDocCanvasPopManagerServiceCtor = CapturingDocCanvasPopManagerService as unknown as typeof DocCanvasPopManagerService;++function createService() {+ const injector = new Injector();+ injector.add([DocCanvasPopManagerService, { useClass: CapturingDocCanvasPopManagerServiceCtor }]);+ injector.add([DocMentionService]);+ injector.add([DocMentionPopupService]);+ const popupManager = injector.get(DocCanvasPopManagerService) as unknown as CapturingDocCanvasPopManagerService;++ return {+ service: injector.get(DocMentionPopupService),+ mentionService: injector.get(DocMentionService),+ attached: popupManager.attached,+ popupDisposals: popupManager.popupDisposals,+ };+}++describe('DocMentionPopupService', () => {+ it('opens an edit popup for the active mention and disposes it when editing ends', () => {+ const { service, mentionService, attached, popupDisposals } = createService();+ const popups: unknown[] = [];+ const sub = service.editPopup$.subscribe((value) => popups.push(value));++ mentionService.startEditing({ unitId: 'doc-1', index: 12 });+ expect(service.editPopup).toMatchObject({ anchor: 12, unitId: 'doc-1' });+ expect(attached).toMatchObject([{+ range: { startOffset: 12, endOffset: 12, collapsed: true },+ unitId: 'doc-1',+ }]);++ mentionService.endEditing();+ expect(service.editPopup).toBeNull();+ expect(popupDisposals).toEqual([1]);+ expect(popups.at(-1)).toBeNull();++ sub.unsubscribe();+ });+});diff --git a/packages/docs-mention-ui/src/services/__tests__/doc-mention.service.spec.ts b/packages/docs-mention-ui/src/services/__tests__/doc-mention.service.spec.tsnew file mode 100644index 0000000000..bd3e43c025--- /dev/null+++ b/packages/docs-mention-ui/src/services/__tests__/doc-mention.service.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 { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocMentionService } from '../doc-mention.service';++function createService(): DocMentionService {+ const injector = new Injector();+ injector.add([DocMentionService]);+ return injector.get(DocMentionService);+}++describe('DocMentionService', () => {+ it('publishes the mention currently being edited and clears it when editing ends', () => {+ const service = createService();+ const values: unknown[] = [];+ const sub = service.editing$.subscribe((value) => values.push(value));++ service.startEditing({ unitId: 'doc-1', index: 8 });+ expect(service.editing).toEqual({ unitId: 'doc-1', index: 8 });++ service.endEditing();+ expect(service.editing).toBeUndefined();+ expect(values).toEqual([undefined, { unitId: 'doc-1', index: 8 }, undefined]);++ sub.unsubscribe();+ });+});diff --git a/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx b/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsxnew file mode 100644index 0000000000..a0c97c4960--- /dev/null+++ b/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx@@ -0,0 +1,354 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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,+ IDisposable,+ IDocumentData,+ IListMentionParam,+ IListMentionResponse,+ IMention,+ ITypeMentionList,+} from '@univerjs/core';+import type { ReactElement } from 'react';+import type { Root } from 'react-dom/client';+import {+ CustomRangeType,+ ICommandService,+ ILogService,+ IMentionIOService,+ LogLevel,+ MentionType,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ DocSelectionManagerService,+ DocStateEmitService,+ RichTextEditingMutation,+ SetTextSelectionsOperation,+} from '@univerjs/docs';+import { DocCanvasPopManagerService, IEditorService } from '@univerjs/docs-ui';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createDocUiTestBed } from '../../__tests__/create-doc-ui-test-bed';+import { AddDocMentionCommand } from '../../commands/commands/doc-mention.command';+import { DocMentionPopupService } from '../../services/doc-mention-popup.service';+import { DocMentionService } from '../../services/doc-mention.service';+import { MentionEditPopup } from '../MentionEditPopup';+import { MentionList } from '../MentionList';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const unitId = 'test-doc';++const peopleMentions: ITypeMentionList[] = [{+ type: MentionType.PERSON,+ title: 'PEOPLE',+ metadata: {},+ mentions: [{+ objectType: MentionType.PERSON,+ objectId: 'alice',+ label: 'Alice',+ metadata: {+ icon: 'alice.png',+ email: '[email protected]',+ },+ }, {+ objectType: MentionType.PERSON,+ objectId: 'alex',+ label: 'Alex',+ metadata: {+ icon: 'alex.png',+ email: '[email protected]',+ },+ }],+}];++class TestMentionState {+ static selectedLabels: string[] = [];+ static popupClicks = 0;++ static reset(): void {+ this.selectedLabels = [];+ this.popupClicks = 0;+ }+}++class TestMentionIOService {+ readonly requests: IListMentionParam[] = [];++ async list(params: IListMentionParam): Promise<IListMentionResponse> {+ this.requests.push(params);++ return {+ list: peopleMentions,+ total: peopleMentions[0].mentions.length,+ };+ }+}++class TestEditorService {+ readonly focusedUnitIds: string[] = [];+ readonly blur$ = new Subject<unknown>();+ readonly focus$ = new Subject<unknown>();++ getEditor(): null {+ return null;+ }++ register(): IDisposable {+ return toDisposable(() => {});+ }++ getAllEditor(): Map<string, never> {+ return new Map<string, never>();+ }++ isEditor(): boolean {+ return true;+ }++ getEditorRenderConfig(): null {+ return null;+ }++ isSheetEditor(): boolean {+ return false;+ }++ blur(): void {+ this.blur$.next(null);+ }++ focus(editorUnitId: string): void {+ this.focusedUnitIds.push(editorUnitId);+ this.focus$.next({ startOffset: 0, endOffset: 0 });+ }++ getFocusId(): string | null {+ return this.focusedUnitIds.at(-1) ?? null;+ }++ getFocusEditor(): null {+ return null;+ }+}++class TestDocCanvasPopManagerService {+ readonly attached: unknown[] = [];+ readonly disposed: unknown[] = [];++ attachPopupToRange(range: unknown, popup: unknown, editorUnitId: string) {+ this.attached.push({ range, popup, unitId: editorUnitId });++ return {+ dispose: () => this.disposed.push({ range, popup, unitId: editorUnitId }),+ };+ }+}++function createMentionDraftDocData(): IDocumentData {+ return {+ id: unitId,+ body: {+ dataStream: 'Hello @al\r\n',+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function renderIntoDocument(element: ReactElement, injector: ReturnType<typeof createDocUiTestBed>['injector']) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function disposeRender(root?: Root, container?: HTMLElement): IDisposable {+ return toDisposable(() => {+ if (root) {+ act(() => root.unmount());+ }+ container?.remove();+ });+}++function listItems(container: HTMLElement): HTMLElement[] {+ return Array.from(container.querySelectorAll<HTMLElement>('div[data-editorid] div[data-editorid]'));+}++function createViewsTestBed() {+ const univer = new Univer({+ override: [[IMentionIOService, { useClass: TestMentionIOService }]],+ });+ const injector = univer.__getInjector();+ const get = injector.get.bind(injector);++ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as unknown as typeof DocCanvasPopManagerService }]);+ injector.add([DocMentionService]);+ injector.add([DocMentionPopupService]);+ injector.add([IEditorService, { useClass: TestEditorService as never }]);++ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createMentionDraftDocData());+ get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = get(ICommandService);+ commandService.registerCommand(AddDocMentionCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);++ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId,+ subUnitId: unitId,+ });++ return {+ univer,+ injector,+ get,+ doc,+ commandService,+ selectionManager,+ mentionIOService: get(IMentionIOService) as TestMentionIOService,+ editorService: get(IEditorService) as unknown as TestEditorService,+ popupService: get(DocMentionPopupService),+ };+}++describe('mention views', () => {+ let univer: Univer | null = null;+ let disposable: IDisposable | undefined;++ beforeEach(() => {+ TestMentionState.reset();+ });++ afterEach(() => {+ disposable?.dispose();+ disposable = undefined;+ univer?.dispose();+ univer = null;+ });++ it('selects the clicked mention item and runs the popup click handler', () => {+ const testBed = createDocUiTestBed();+ univer = testBed.univer;+ const rendered = renderIntoDocument(+ <MentionList+ active="alice"+ editorId={unitId}+ mentions={peopleMentions}+ onClick={() => TestMentionState.popupClicks += 1}+ onSelect={(item: IMention) => TestMentionState.selectedLabels.push(item.label)}+ />,+ testBed.injector+ );+ disposable = disposeRender(rendered.root, rendered.container);++ const items = listItems(rendered.container);+ act(() => {+ items[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ expect(TestMentionState.selectedLabels).toEqual(['Alex']);+ expect(TestMentionState.popupClicks).toBe(1);+ });++ it('queries by the current typed mention text and inserts the selected mention into the document', async () => {+ const testBed = createViewsTestBed();+ univer = testBed.univer;+ testBed.popupService.showEditPopup(unitId, 6);+ const rendered = renderIntoDocument(<MentionEditPopup />, testBed.injector);+ disposable = disposeRender(rendered.root, rendered.container);++ await act(async () => {+ testBed.selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 9,+ endOffset: 9,+ collapsed: true,+ isActive: true,+ segmentId: '',+ style: null as never,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ isEditing: true,+ style: null as never,+ }, {+ unitId,+ subUnitId: unitId,+ });+ await Promise.resolve();+ });++ expect(testBed.mentionIOService.requests.at(-1)).toEqual({+ unitId,+ search: '@al',+ });++ const aliceItem = listItems(rendered.container)[0];+ await act(async () => {+ aliceItem.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ const body = testBed.doc.getBody();+ expect(body?.dataStream).toBe('Hello @Alice\r\n');+ expect(body?.customRanges?.[0]).toMatchObject({+ startIndex: 6,+ endIndex: 11,+ rangeType: CustomRangeType.MENTION,+ wholeEntity: true,+ properties: {+ objectType: MentionType.PERSON,+ objectId: 'alice',+ label: 'Alice',+ email: '[email protected]',+ },+ });+ expect(testBed.popupService.editPopup).toBeNull();+ expect(testBed.editorService.focusedUnitIds).toEqual([unitId, unitId]);+ });+});diff --git a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertMenu.spec.tsx b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertMenu.spec.tsxnew file mode 100644index 0000000000..e2125cfa2b--- /dev/null+++ b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertMenu.spec.tsx@@ -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 { Root } from 'react-dom/client';+import type { IDocPopupMenuItem } from '../../services/doc-quick-insert-popup.service';+import { DesktopLogService, ILogService, Injector } from '@univerjs/core';+import { IconManager, RediContext } from '@univerjs/ui';+import { act, useState } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { QuickInsertMenu } from '../QuickInsertMenu';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const insertTableMenu: IDocPopupMenuItem = {+ id: 'insert-table',+ title: 'Table',+};++const insertImageMenu: IDocPopupMenuItem = {+ id: 'insert-image',+ title: 'Image',+};++const insertEquationMenu: IDocPopupMenuItem = {+ id: 'insert-equation',+ title: 'Equation',+};++const nestedMenus = [+ {+ id: 'insert-group',+ title: 'Insert',+ children: [+ insertTableMenu,+ insertImageMenu,+ ],+ },+ insertEquationMenu,+];++class TestState {+ static focusedMenus: Array<IDocPopupMenuItem | null> = [];+ static focusedIndexes: number[] = [];+ static selectedMenus: IDocPopupMenuItem[] = [];++ static reset(): void {+ this.focusedMenus = [];+ this.focusedIndexes = [];+ this.selectedMenus = [];+ }+}++function createInjector() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IconManager, { useClass: IconManager }]);++ return injector;+}++function QuickInsertMenuHarness() {+ const [focusedMenuIndex, setFocusedMenuIndex] = useState(0);++ return (+ <QuickInsertMenu+ menus={nestedMenus}+ focusedMenuIndex={focusedMenuIndex}+ onFocusedMenuIndexChange={(index) => {+ TestState.focusedIndexes.push(index);+ setFocusedMenuIndex(index);+ }}+ onFocusedMenuChange={(menu) => TestState.focusedMenus.push(menu)}+ onSelect={(menu) => TestState.selectedMenus.push(menu)}+ />+ );+}++describe('QuickInsertMenu', () => {+ let container: HTMLDivElement;+ let root: Root;+ let scrollIntoViewDescriptor: PropertyDescriptor | undefined;++ beforeEach(() => {+ TestState.reset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ scrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView');+ Object.defineProperty(Element.prototype, 'scrollIntoView', {+ configurable: true,+ value: () => {},+ });+ });++ afterEach(() => {+ act(() => {+ root.unmount();+ });+ container.remove();+ if (scrollIntoViewDescriptor) {+ Object.defineProperty(Element.prototype, 'scrollIntoView', scrollIntoViewDescriptor);+ } else {+ delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView;+ }+ });++ function renderMenu() {+ const injector = createInjector();++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <QuickInsertMenuHarness />+ </RediContext.Provider>+ );+ });+ }++ function findMenuItem(title: string) {+ return Array.from(container.querySelectorAll('[role="button"]'))+ .find((node) => node.textContent === title) as HTMLElement | undefined;+ }++ it('maps nested menu leaves to keyboard focus order and selects the hovered business item', () => {+ renderMenu();++ expect(TestState.focusedMenus.at(-1)).toBe(insertTableMenu);++ const imageMenuNode = findMenuItem('Image');+ expect(imageMenuNode).toBeDefined();++ act(() => {+ imageMenuNode!.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));+ });++ expect(TestState.focusedIndexes).toEqual([1]);+ expect(TestState.focusedMenus.at(-1)).toBe(insertImageMenu);++ act(() => {+ imageMenuNode!.click();+ });++ expect(TestState.selectedMenus).toEqual([insertImageMenu]);+ });++ it('releases the focused menu when the pointer leaves a business item', () => {+ renderMenu();++ const tableMenuNode = findMenuItem('Table');+ expect(tableMenuNode).toBeDefined();++ act(() => {+ tableMenuNode!.dispatchEvent(new MouseEvent('mouseout', { bubbles: true }));+ });++ expect(Number.isNaN(TestState.focusedIndexes.at(-1))).toBe(true);+ expect(TestState.focusedMenus.at(-1)).toBeNull();+ });+});diff --git a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsxnew file mode 100644index 0000000000..43e16c98a0--- /dev/null+++ b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx@@ -0,0 +1,388 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { Root } from 'react-dom/client';+import type { DocPopupMenu } from '../../services/doc-quick-insert-popup.service';+import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { CutContentCommand, DocCanvasPopManagerService, DocEventManagerService } from '@univerjs/docs-ui';+import { IRenderManagerService } from '@univerjs/engine-render';+import { ComponentManager, IconManager, IPlatformService, IShortcutService, KeyCode, PlatformService, RediContext, ShortcutService } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { BehaviorSubject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DeleteSearchKeyCommand } from '../../commands/commands/doc-quick-insert.command';+import { CloseQuickInsertPopupOperation } from '../../commands/operations/quick-insert-popup.operation';+import { DocQuickInsertPopupService } from '../../services/doc-quick-insert-popup.service';+import { QuickInsertPopup } from '../QuickInsertPopup';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const TEST_DOC_UNIT_ID = 'doc-quick-insert-test';++class TestUniverInstanceService {+ dataStream = '/ta\r\n';++ private readonly _doc = {+ getUnitId: () => TEST_DOC_UNIT_ID,+ getBody: () => ({+ dataStream: this.dataStream,+ paragraphs: [{ startIndex: 3, paragraphId: 'para_quick_insert_popup_test' }],+ }),+ };++ getCurrentUnitOfType() {+ return this._doc;+ }++ getUnit() {+ return this._doc;+ }+}++class TestDocCanvasPopManagerService {+ readonly attachedPopups: Array<{+ componentKey?: string;+ disposed: boolean;+ }> = [];++ attachPopupToRect(_rect: unknown, popup: { componentKey?: string }) {+ const entry = {+ componentKey: popup.componentKey,+ disposed: false,+ };++ this.attachedPopups.push(entry);++ return {+ dispose: () => {+ entry.disposed = true;+ },+ };+ }+}++class TestRenderManagerService {+ getRenderById() {+ return {+ with(token: unknown) {+ if (token === DocEventManagerService) {+ return {+ findParagraphBoundByIndex: () => ({+ firstLine: {+ left: 0,+ top: 0,+ right: 120,+ bottom: 24,+ },+ }),+ };+ }++ return undefined;+ },+ mainComponent: {+ getOffsetConfig: () => ({ docsLeft: 0, docsTop: 0 }),+ },+ };+ }+}++class TestDocSelectionManagerService {+ getActiveTextRange() {+ return null;+ }+}++function createQuickInsertPopupTestBed(options?: {+ dataStream?: string;+ inputOffset?: { start: number; end: number };+}) {+ const injector = new Injector();+ let cutContentParams: unknown;+ let selectedMenu: unknown;++ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([LocaleService, { useClass: LocaleService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.add([ComponentManager, { useClass: ComponentManager }]);+ injector.add([IconManager, { useClass: IconManager }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([DocCanvasPopManagerService, { useClass: TestDocCanvasPopManagerService as never }]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([DocSelectionManagerService, { useClass: TestDocSelectionManagerService as never }]);+ injector.add([DocQuickInsertPopupService, { useClass: DocQuickInsertPopupService }]);++ const univerInstanceService = injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService;+ univerInstanceService.dataStream = options?.dataStream ?? '/ta\r\n';++ const localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.ZH_CN]: {+ quick: {+ insert: {+ group: 'Insert',+ table: 'Table',+ image: 'Image',+ },+ },+ 'docs-quick-insert-ui': {+ placeholder: 'No result',+ },+ },+ });++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(CloseQuickInsertPopupOperation);+ commandService.registerCommand(DeleteSearchKeyCommand);+ commandService.registerCommand({+ id: CutContentCommand.id,+ type: CommandType.COMMAND,+ handler: (_accessor, params) => {+ cutContentParams = params;+ return true;+ },+ });++ const menus$ = new BehaviorSubject<DocPopupMenu[]>([+ {+ id: 'insert-group',+ title: 'quick.insert.group',+ children: [+ {+ id: 'insert-table',+ title: 'quick.insert.table',+ keywords: ['table', 'grid'],+ },+ {+ id: 'insert-image',+ title: 'quick.insert.image',+ keywords: ['image', 'picture'],+ },+ ],+ },+ ]);+ const popupService = injector.get(DocQuickInsertPopupService);+ popupService.onMenuSelected((menu) => {+ selectedMenu = menu;+ });+ popupService.showPopup({+ popup: {+ keyword: '/',+ menus$,+ },+ index: 0,+ unitId: TEST_DOC_UNIT_ID,+ });+ popupService.setInputOffset(options?.inputOffset ?? { start: 0, end: 3 });++ return {+ getCutContentParams: () => cutContentParams,+ getSelectedMenu: () => selectedMenu,+ injector,+ popupService,+ popupManagerService: injector.get(DocCanvasPopManagerService) as unknown as TestDocCanvasPopManagerService,+ };+}++describe('QuickInsertPopup', () => {+ let container: HTMLDivElement;+ let root: Root;+ let scrollIntoViewDescriptor: PropertyDescriptor | undefined;+ let requestIdleCallbackDescriptor: PropertyDescriptor | undefined;+ let cancelIdleCallbackDescriptor: PropertyDescriptor | undefined;++ beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ scrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView');+ requestIdleCallbackDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'requestIdleCallback');+ cancelIdleCallbackDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'cancelIdleCallback');+ Object.defineProperty(Element.prototype, 'scrollIntoView', {+ configurable: true,+ value: () => {},+ });+ Object.defineProperty(globalThis, 'requestIdleCallback', {+ configurable: true,+ value: (callback: IdleRequestCallback) => {+ callback({ didTimeout: false, timeRemaining: () => 0 });+ return 1;+ },+ });+ Object.defineProperty(globalThis, 'cancelIdleCallback', {+ configurable: true,+ value: () => {},+ });+ });++ afterEach(() => {+ act(() => {+ root.unmount();+ });+ container.remove();+ if (scrollIntoViewDescriptor) {+ Object.defineProperty(Element.prototype, 'scrollIntoView', scrollIntoViewDescriptor);+ } else {+ delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView;+ }++ if (requestIdleCallbackDescriptor) {+ Object.defineProperty(globalThis, 'requestIdleCallback', requestIdleCallbackDescriptor);+ } else {+ delete (globalThis as { requestIdleCallback?: unknown }).requestIdleCallback;+ }++ if (cancelIdleCallbackDescriptor) {+ Object.defineProperty(globalThis, 'cancelIdleCallback', cancelIdleCallbackDescriptor);+ } else {+ delete (globalThis as { cancelIdleCallback?: unknown }).cancelIdleCallback;+ }+ });++ it('filters the popup menu by the typed keyword and closes the popup after selecting a business menu item', async () => {+ const { getCutContentParams, getSelectedMenu, injector, popupManagerService, popupService } = createQuickInsertPopupTestBed();++ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <QuickInsertPopup />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(container.textContent).toContain('Table');+ expect(container.textContent).not.toContain('Image');++ const tableMenuItem = Array.from(container.querySelectorAll('[role="button"]'))+ .find((node) => node.textContent === 'Table') as HTMLElement | undefined;++ expect(tableMenuItem).toBeDefined();++ await act(async () => {+ tableMenuItem!.click();+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(getSelectedMenu()).toEqual({+ id: 'insert-table',+ title: 'Table',+ keywords: ['table', 'grid', 'table'],+ });+ expect(getCutContentParams()).toEqual(expect.objectContaining({+ selections: [expect.objectContaining({ startOffset: 0, endOffset: 3 })],+ }));+ expect(popupService.editPopup).toBeNull();+ expect(popupManagerService.attachedPopups.find((popup) => popup.componentKey === QuickInsertPopup.componentKey)?.disposed).toBe(true);+ });++ it('uses popup keyboard commands to move focus and select the focused business menu item', async () => {+ const { getCutContentParams, getSelectedMenu, injector, popupService } = createQuickInsertPopupTestBed({+ dataStream: '/\r\n',+ inputOffset: { start: 0, end: 1 },+ });+ const commandService = injector.get(ICommandService);+ const shortcutService = injector.get(IShortcutService);++ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <QuickInsertPopup />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const moveDownShortcut = shortcutService.getAllShortcuts().find((shortcut) => shortcut.binding === KeyCode.ARROW_DOWN);+ const enterShortcut = shortcutService.getAllShortcuts().find((shortcut) => shortcut.binding === KeyCode.ENTER);++ expect(moveDownShortcut).toBeDefined();+ expect(enterShortcut).toBeDefined();++ await act(async () => {+ await commandService.executeCommand(moveDownShortcut!.id, moveDownShortcut!.staticParameters);+ await Promise.resolve();+ });++ await act(async () => {+ await commandService.executeCommand(enterShortcut!.id);+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(getSelectedMenu()).toEqual({+ id: 'insert-image',+ title: 'Image',+ keywords: ['image', 'picture', 'image'],+ });+ expect(getCutContentParams()).toEqual(expect.objectContaining({+ selections: [expect.objectContaining({ startOffset: 0, endOffset: 1 })],+ }));+ expect(popupService.editPopup).toBeNull();+ });++ it('temporarily disables document cursor shortcuts while the popup owns keyboard navigation', async () => {+ const { injector } = createQuickInsertPopupTestBed({+ dataStream: '/\r\n',+ inputOffset: { start: 0, end: 1 },+ });+ const shortcutService = injector.get(IShortcutService);+ const documentArrowDownShortcut = {+ id: 'doc.operation.move-cursor-down',+ binding: KeyCode.ARROW_DOWN,+ preconditions: () => true,+ };++ shortcutService.registerShortcut(documentArrowDownShortcut);++ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <QuickInsertPopup />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(documentArrowDownShortcut.preconditions()).toBe(false);++ await act(async () => {+ root.render(<RediContext.Provider value={{ injector }} />);+ await Promise.resolve();+ });++ expect(documentArrowDownShortcut.preconditions()).toBe(true);+ });+});diff --git a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.tsindex 5db4e75391..7d6acb403d 100644--- a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts+++ b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts@@ -14,124 +14,180 @@* limitations under the License.*/-import type { IDocumentData } from '@univerjs/core';-import { CommandType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';-import { AddCommentMutation, IThreadCommentDataSourceService, ThreadCommentDataSourceService } from '@univerjs/thread-comment';-import { SetActiveCommentOperation } from '@univerjs/thread-comment-ui';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { DocumentDataModel, ICommand, IDocumentData, Injector } from '@univerjs/core';+import type { IThreadComment } from '@univerjs/thread-comment';+import { ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import {+ AddCommentMutation,+ IThreadCommentDataSourceService,+ ThreadCommentDataSourceService,+ ThreadCommentModel,+} from '@univerjs/thread-comment';+import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DEFAULT_DOC_SUBUNIT_ID } from '../../../common/const';import { AddDocCommentComment } from '../add-doc-comment.command';-function createDocData(id: string): IDocumentData {+const DOC_ID = 'doc-add-comment-test';++function createDocData(): IDocumentData {return {- id,+ id: DOC_ID,body: {dataStream: 'Hello world\r\n',+ textRuns: [],+ paragraphs: [],+ sectionBreaks: [],+ customBlocks: [],customDecorations: [],},documentStyle: {- pageSize: { width: 100, height: 100 },- marginTop: 0,- marginBottom: 0,- marginLeft: 0,- marginRight: 0,+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createComment(id = 'comment-1'): IThreadComment {+ return {+ id,+ threadId: '',+ ref: '',+ unitId: DOC_ID,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ dT: '2026-06-17T00:00:00.000Z',+ personId: 'user-1',+ text: {+ dataStream: 'Please revise this wording.\r\n',},};}describe('AddDocCommentComment', () => {let univer: Univer;- let injector: ReturnType<Univer['__getInjector']>;+ let get: Injector['get'];+ let commandService: ICommandService;++ function getDocBody() {+ const univerInstanceService = get(IUniverInstanceService);+ return univerInstanceService.getUnit<DocumentDataModel>(DOC_ID, UniverInstanceType.UNIVER_DOC)?.getBody();+ }beforeEach(() => {univer = new Univer();- injector = univer.__getInjector();+ const injector = univer.__getInjector();+ get = injector.get.bind(injector);++ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }]);+ injector.add([ThreadCommentModel]);+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ injector.add([ThreadCommentPanelService]);++ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData());+ get(IUniverInstanceService).focusUnit(DOC_ID);++ commandService = get(ICommandService);+ commandService.registerCommand(AddDocCommentComment);+ commandService.registerCommand(AddCommentMutation);+ commandService.registerCommand(SetActiveCommentOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);});afterEach(() => {univer.dispose();});- it('should add comment and attach decoration via sequenceExecute', async () => {- const dataSource = new ThreadCommentDataSourceService();- const addComment = vi.fn(async (c) => ({ ...c, id: 'comment-1', threadId: '' }));- dataSource.dataSource = {- addComment,- updateComment: vi.fn(async () => true),- resolveComment: vi.fn(async () => true),- deleteComment: vi.fn(async () => true),- listComments: vi.fn(async () => []),- saveCommentToSnapshot: vi.fn((comment) => ({- id: comment.id,- threadId: comment.threadId,- ref: comment.ref,- })),- };-- injector.add([IThreadCommentDataSourceService, { useValue: dataSource }]);- injector.add([DocSelectionManagerService]);+ it('adds a thread comment to the selected document text and makes it active', async () => {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: DOC_ID,+ subUnitId: DOC_ID,+ });+ selectionManager.__TEST_ONLY_add([+ {+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ },+ ]);- const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-1'));- injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());-- const selectionManager = injector.get(DocSelectionManagerService);- selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: doc.getUnitId(), subUnitId: doc.getUnitId() });- selectionManager.__TEST_ONLY_add([{ startOffset: 0, endOffset: 5, collapsed: false, isActive: true }] as never);-- const executed: Array<{ id: string; params: unknown }> = [];- const commandService = injector.get(ICommandService);- commandService.registerCommand({- id: AddCommentMutation.id,- type: CommandType.MUTATION,- handler: (_accessor, params) => {- executed.push({ id: AddCommentMutation.id, params });- return true;+ const comment = createComment();+ const result = await commandService.executeCommand(AddDocCommentComment.id, {+ unitId: DOC_ID,+ comment,+ range: {+ startOffset: 0,+ endOffset: 5,},});- commandService.registerCommand({- id: RichTextEditingMutation.id,- type: CommandType.MUTATION,- handler: (_accessor, params) => {- executed.push({ id: RichTextEditingMutation.id, params });- return true;++ expect(result).toBe(true);++ const thread = get(ThreadCommentModel).getThread(DOC_ID, DEFAULT_DOC_SUBUNIT_ID, comment.id);+ expect(thread?.root).toMatchObject({+ id: comment.id,+ threadId: comment.id,+ unitId: DOC_ID,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ personId: 'user-1',+ text: {+ dataStream: 'Please revise this wording.\r\n',},});- commandService.registerCommand({- id: SetActiveCommentOperation.id,- type: CommandType.OPERATION,- handler: (_accessor, params) => {- executed.push({ id: SetActiveCommentOperation.id, params });- return true;- },++ expect(getDocBody()?.customDecorations).toEqual([+ expect.objectContaining({+ id: comment.id,+ startIndex: 0,+ endIndex: 4,+ }),+ ]);++ expect(get(ThreadCommentPanelService).activeCommentId).toEqual({+ unitId: DOC_ID,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ commentId: comment.id,});+ });- const ok = await AddDocCommentComment.handler(injector as any, {- unitId: 'doc-1',- range: { startOffset: 1, endOffset: 2, collapsed: false },- comment: { id: '', threadId: '', unitId: 'doc-1', subUnitId: 'default_doc', ref: '' } as any,+ it('does not attach a comment when the document has no selected text', async () => {+ const comment = createComment('comment-without-selection');+ const result = await commandService.executeCommand(AddDocCommentComment.id, {+ unitId: DOC_ID,+ comment,+ range: {+ startOffset: 0,+ endOffset: 5,+ },});- expect(ok).toBe(true);- expect(addComment).toHaveBeenCalled();- expect(executed.map((command) => command.id)).toEqual([- AddCommentMutation.id,- RichTextEditingMutation.id,- SetActiveCommentOperation.id,- ]);- expect(executed[0].params).toEqual(expect.objectContaining({- unitId: 'doc-1',- comment: expect.objectContaining({ id: 'comment-1', threadId: 'comment-1' }),- }));- expect(executed[1].params).toEqual(expect.objectContaining({ unitId: 'doc-1' }));- expect(executed[2].params).toEqual(expect.objectContaining({- unitId: 'doc-1',- subUnitId: 'default_doc',- commentId: 'comment-1',- }));+ expect(result).toBe(false);+ expect(get(ThreadCommentModel).getThread(DOC_ID, DEFAULT_DOC_SUBUNIT_ID, comment.id)).toBeUndefined();+ expect(getDocBody()?.customDecorations).toEqual([]);+ expect(get(ThreadCommentPanelService).activeCommentId).toBeUndefined();});- it('should return false when missing params', async () => {- const ok = await AddDocCommentComment.handler({ get: vi.fn() } as any, undefined as any);- expect(ok).toBe(false);+ it('rejects an incomplete add-comment request without changing the document', async () => {+ const result = await commandService.executeCommand(AddDocCommentComment.id);++ expect(result).toBe(false);+ expect(get(ThreadCommentModel).getAll()).toEqual([]);+ expect(getDocBody()?.customDecorations).toEqual([]);+ expect(get(ThreadCommentPanelService).activeCommentId).toBeUndefined();});});diff --git a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.ts b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.tsindex 67615ca1cb..666a2a1d18 100644--- a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.ts+++ b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.ts@@ -14,10 +14,11 @@* limitations under the License.*/-import type { IDocumentData } from '@univerjs/core';-import { CommandType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';-import { RichTextEditingMutation } from '@univerjs/docs';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { DocumentDataModel, IDocumentData } from '@univerjs/core';+import { CustomDecorationType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { DeleteDocCommentComment } from '../delete-doc-comment.command';function createDocData(id: string): IDocumentData {@@ -25,7 +26,7 @@ function createDocData(id: string): IDocumentData {id,body: {dataStream: 'Hello world\r\n',- customDecorations: [{ id: 'c1', startIndex: 0, endIndex: 5, type: 1 as never }],+ customDecorations: [{ id: 'c1', startIndex: 0, endIndex: 5, type: CustomDecorationType.COMMENT }],},documentStyle: {pageSize: { width: 100, height: 100 },@@ -40,40 +41,40 @@ function createDocData(id: string): IDocumentData {describe('DeleteDocCommentComment', () => {let univer: Univer;let injector: ReturnType<Univer['__getInjector']>;+ let commandService: ICommandService;beforeEach(() => {univer = new Univer();injector = univer.__getInjector();+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ commandService = injector.get(ICommandService);+ commandService.registerCommand(DeleteDocCommentComment);+ commandService.registerCommand(RichTextEditingMutation);});afterEach(() => {univer.dispose();});- it('should delete decoration via sequenceExecute', async () => {- const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-1'));+ it('removes the comment decoration from the document', async () => {+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData('doc-1'));injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());- const executed: Array<{ id: string; params: unknown }> = [];- const commandService = injector.get(ICommandService);- commandService.registerCommand({- id: RichTextEditingMutation.id,- type: CommandType.MUTATION,- handler: (_accessor, params) => {- executed.push({ id: RichTextEditingMutation.id, params });- return true;- },- });+ const ok = await commandService.executeCommand(DeleteDocCommentComment.id, { unitId: 'doc-1', commentId: 'c1' });- const ok = await DeleteDocCommentComment.handler(injector as any, { unitId: 'doc-1', commentId: 'c1' });expect(ok).toBe(true);- expect(executed).toHaveLength(1);- expect(executed[0]).toEqual(expect.objectContaining({ id: RichTextEditingMutation.id }));- expect(executed[0].params).toEqual(expect.objectContaining({ unitId: 'doc-1' }));+ expect(doc.getBody()?.customDecorations).toEqual([]);});- it('should return false when missing params', async () => {- const ok = await DeleteDocCommentComment.handler({ get: vi.fn() } as any, undefined as any);+ it('rejects an incomplete delete request without changing the document', async () => {+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData('doc-1'));+ injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());++ const ok = await commandService.executeCommand(DeleteDocCommentComment.id);+expect(ok).toBe(false);+ expect(doc.getBody()?.customDecorations).toEqual([{ id: 'c1', startIndex: 0, endIndex: 5, type: CustomDecorationType.COMMENT }]);});});diff --git a/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.ts b/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.tsindex 7633012797..c5b3a32b70 100644--- a/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.ts+++ b/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.ts@@ -14,75 +14,197 @@* limitations under the License.*/-import { describe, expect, it, vi } from 'vitest';-import { DOCS_THREAD_COMMENT_PANEL } from '../../../common/const';-import { ShowCommentPanelOperation, ToggleCommentPanelOperation } from '../show-comment-panel.operation';--describe('ShowCommentPanelOperation', () => {- it('should open sidebar and set active comment', () => {- const setPanelVisible = vi.fn();- const setActiveComment = vi.fn();- const panelService = {- panelVisible: false,- setPanelVisible,- setActiveComment,- };-- const open = vi.fn();- const sidebarService = {- options: {},- open,- };-- const accessor = {- get: (token: any) => {- if (token.name === 'ThreadCommentPanelService') return panelService;- return sidebarService;+import type { DocumentDataModel, IDisposable, IDocumentData } from '@univerjs/core';+import type { IRender } from '@univerjs/engine-render';+import type { ISidebarMethodOptions } from '@univerjs/ui';+import { Disposable, ICommandService, IUniverInstanceService, toDisposable, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';+import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { ISidebarService } from '@univerjs/ui';+import { Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DEFAULT_DOC_SUBUNIT_ID, DOCS_THREAD_COMMENT_PANEL } from '../../../common/const';+import { DocThreadCommentService } from '../../../services/doc-thread-comment.service';+import { ShowCommentPanelOperation, StartAddCommentOperation, ToggleCommentPanelOperation } from '../show-comment-panel.operation';++const unitId = 'doc-thread-comment-operation-doc';++function createDocData(): IDocumentData {+ return {+ id: unitId,+ body: {+ dataStream: 'Hello world\r\n',+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,},- } as any;+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++class TestSidebarService extends Disposable implements ISidebarService {+ readonly sidebarOptions$ = new Subject<ISidebarMethodOptions>();+ readonly scrollEvent$ = new Subject<Event>();+ private _options: ISidebarMethodOptions = {};+ private _container?: HTMLElement;+ private _width?: number;++ get visible(): boolean {+ return this._options.visible ?? false;+ }++ get options(): ISidebarMethodOptions {+ return this._options;+ }++ get width(): number | undefined {+ return this._width;+ }++ open(params: ISidebarMethodOptions): IDisposable {+ this._options = { ...params, visible: true };+ this.sidebarOptions$.next(this._options);+ return toDisposable(() => this.close());+ }++ close(): void {+ this._options = { ...this._options, visible: false };+ this.sidebarOptions$.next(this._options);+ this._options.onClose?.();+ }++ getContainer(): HTMLElement | undefined {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element;+ }++ setWidth(value: number): void {+ this._width = value;+ }++ override dispose(): void {+ super.dispose();+ this.sidebarOptions$.complete();+ this.scrollEvent$.complete();+ }+}++class TestRenderManagerService implements Pick<IRenderManagerService, 'getRenderById'> {+ getRenderById(): IRender | null {+ return null;+ }+}++describe('doc thread comment panel operations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let sidebarService: ISidebarService;+ let panelService: ThreadCommentPanelService;+ let selectionManager: DocSelectionManagerService;+ let docThreadCommentService: DocThreadCommentService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ISidebarService, { useClass: TestSidebarService }]);+ injector.add([ThreadCommentPanelService]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocThreadCommentService]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);++ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());+ injector.get(IUniverInstanceService).focusUnit(unitId);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(ShowCommentPanelOperation);+ commandService.registerCommand(ToggleCommentPanelOperation);+ commandService.registerCommand(StartAddCommentOperation);++ sidebarService = injector.get(ISidebarService);+ panelService = injector.get(ThreadCommentPanelService);+ selectionManager = injector.get(DocSelectionManagerService);+ docThreadCommentService = injector.get(DocThreadCommentService);+ });++ afterEach(() => {+ univer.dispose();+ });- const ok = ShowCommentPanelOperation.handler(accessor, {- activeComment: { unitId: 'doc-1', subUnitId: 'default', commentId: 'c1' },+ it('opens the docs comment panel and activates the requested comment', async () => {+ const activeComment = { unitId, subUnitId: 'doc', commentId: 'comment-1' };++ const result = await commandService.executeCommand(ShowCommentPanelOperation.id, {+ activeComment,});- expect(ok).toBe(true);- expect(open).toHaveBeenCalledWith(expect.objectContaining({- children: { label: DOCS_THREAD_COMMENT_PANEL },- width: 320,- }));- expect(setPanelVisible).toHaveBeenCalledWith(true);- expect(setActiveComment).toHaveBeenCalledWith({ unitId: 'doc-1', subUnitId: 'default', commentId: 'c1' });+ expect(result).toBe(true);+ expect(panelService.panelVisible).toBe(true);+ expect(panelService.activeCommentId).toEqual(activeComment);+ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options.children?.label).toBe(DOCS_THREAD_COMMENT_PANEL);});-});-describe('ToggleCommentPanelOperation', () => {- it('should close sidebar and reset state when already opened', () => {- const setPanelVisible = vi.fn();- const setActiveComment = vi.fn();- const panelService = {- panelVisible: true,- setPanelVisible,- setActiveComment,- };-- const close = vi.fn();- const sidebarService = {- options: { children: { label: DOCS_THREAD_COMMENT_PANEL } },- open: vi.fn(),- close,- };-- const accessor = {- get: (token: any) => {- if (token.name === 'ThreadCommentPanelService') return panelService;- return sidebarService;- },- } as any;+ it('toggles an open comment panel closed and clears the active comment', async () => {+ const activeComment = { unitId, subUnitId: 'doc', commentId: 'comment-2' };++ await commandService.executeCommand(ShowCommentPanelOperation.id, {+ activeComment,+ });+ const result = await commandService.executeCommand(ToggleCommentPanelOperation.id);++ expect(result).toBe(true);+ expect(panelService.panelVisible).toBe(false);+ expect(panelService.activeCommentId).toBeNull();+ expect(sidebarService.visible).toBe(false);+ });++ it('starts a new comment draft from the selected document text', async () => {+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId,+ subUnitId: unitId,+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ const result = await commandService.executeCommand(StartAddCommentOperation.id);++ expect(result).toBe(true);+ expect(panelService.panelVisible).toBe(true);+ expect(docThreadCommentService.addingComment).toMatchObject({+ unitId,+ ref: 'Hello',+ startOffset: 0,+ endOffset: 5,+ collapsed: true,+ });+ expect(panelService.activeCommentId).toEqual({+ unitId,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ commentId: '',+ });+ });++ it('does not start a new comment draft without selected document text', async () => {+ const result = await commandService.executeCommand(StartAddCommentOperation.id);- const ok = ToggleCommentPanelOperation.handler(accessor);- expect(ok).toBe(true);- expect(close).toHaveBeenCalledTimes(1);- expect(setPanelVisible).toHaveBeenCalledWith(false);- expect(setActiveComment).toHaveBeenCalledWith(null);+ expect(result).toBe(false);+ expect(docThreadCommentService.addingComment).toBeUndefined();+ expect(panelService.panelVisible).toBe(false);});});diff --git a/packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.ts b/packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.tsindex c537328786..d318d2edc2 100644--- a/packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.ts+++ b/packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.ts@@ -14,13 +14,24 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';+import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { ISidebarService } from '@univerjs/ui';import { describe, expect, it } from 'vitest';import { DocThreadCommentService } from '../doc-thread-comment.service';+class TestSidebarService {}++class TestThreadCommentPanelService {}+describe('DocThreadCommentService', () => {it('should track adding comment lifecycle', () => {- const service = new DocThreadCommentService({} as any, {} as any);+ const injector = new Injector();+ injector.add([ISidebarService, { useClass: TestSidebarService }]);+ injector.add([ThreadCommentPanelService, { useClass: TestThreadCommentPanelService }]);+ injector.add([DocThreadCommentService]);+ const service = injector.get(DocThreadCommentService);expect(service.addingComment).toBeUndefined();diff --git a/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsx b/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsxnew file mode 100644index 0000000000..523adc5820--- /dev/null+++ b/packages/docs-thread-comment-ui/src/views/__tests__/DocThreadCommentPanel.spec.tsx@@ -0,0 +1,262 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDisposable, IDocumentBody, IDocumentData, Injector } from '@univerjs/core';+import type { IRender, IRenderManagerService } from '@univerjs/engine-render';+import type { IThreadComment } from '@univerjs/thread-comment';+import type { ISidebarMethodOptions } from '@univerjs/ui';+import type { Root } from 'react-dom/client';+import {+ CustomDecorationType,+ Disposable,+ ICommandService,+ IUniverInstanceService,+ LocaleType,+ toDisposable,+ Univer,+ UniverInstanceType,+ UserManagerService,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { IRenderManagerService as IRenderManagerServiceToken } from '@univerjs/engine-render';+import { IThreadCommentDataSourceService, ThreadCommentDataSourceService, ThreadCommentModel } from '@univerjs/thread-comment';+import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import threadCommentEnUS from '@univerjs/thread-comment-ui/locale/en-US';+import { ISidebarService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DEFAULT_DOC_SUBUNIT_ID } from '../../common/const';+import { DocThreadCommentService } from '../../services/doc-thread-comment.service';+import { DocThreadCommentPanel } from '../DocThreadCommentPanel';++const DOC_ID = 'doc-thread-comment-panel-test';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class TestSidebarService extends Disposable implements ISidebarService {+ readonly sidebarOptions$ = new Subject<ISidebarMethodOptions>();+ readonly scrollEvent$ = new Subject<Event>();+ private _options: ISidebarMethodOptions = {};+ private _container?: HTMLElement;++ open(params: ISidebarMethodOptions): IDisposable {+ this._options = { ...params, visible: true };+ this.sidebarOptions$.next(this._options);+ return toDisposable(() => this.close());+ }++ close(): void {+ this._options = { ...this._options, visible: false };+ this.sidebarOptions$.next(this._options);+ this._options.onClose?.();+ }++ get visible(): boolean {+ return this._options.visible ?? false;+ }++ get options(): ISidebarMethodOptions {+ return this._options;+ }++ get width(): number | undefined {+ return undefined;+ }++ setWidth(): void {}++ getContainer(): HTMLElement | undefined {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element;+ }++ override dispose(): void {+ super.dispose();+ this.sidebarOptions$.complete();+ this.scrollEvent$.complete();+ }+}++class TestRenderManagerService implements Pick<IRenderManagerService, 'getRenderById' | 'getRenderUnitById'> {+ getRenderById(): IRender | null {+ return null;+ }++ getRenderUnitById(): IRender | null {+ return null;+ }+}++function createDocData(decorationIds: string[]): IDocumentData {+ return {+ id: DOC_ID,+ body: {+ dataStream: 'Alpha beta gamma\r\n',+ textRuns: [],+ paragraphs: [],+ sectionBreaks: [],+ customBlocks: [],+ customDecorations: decorationIds.map((id) => ({+ id,+ type: CustomDecorationType.COMMENT,+ startIndex: 0,+ endIndex: 4,+ })),+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function createTextBody(text: string): IDocumentBody {+ const dataStream = `${text}\r\n`;+ return {+ dataStream,+ textRuns: [],+ paragraphs: [+ {+ startIndex: dataStream.length - 2,+ paragraphId: `paragraph-${text}`,+ },+ ],+ sectionBreaks: [+ {+ startIndex: dataStream.length - 1,+ },+ ],+ };+}++function createThread(id: string, text: string, resolved = false): IThreadComment {+ return {+ id,+ threadId: id,+ ref: `Range ${id}`,+ unitId: DOC_ID,+ subUnitId: DEFAULT_DOC_SUBUNIT_ID,+ dT: '2026-06-17T00:00:00.000Z',+ personId: 'user-1',+ resolved,+ text: createTextBody(text),+ };+}++function createPanelTestBed(decorationIds: string[]) {+ const univer = new Univer({+ locale: LocaleType.EN_US,+ locales: {+ [LocaleType.EN_US]: threadCommentEnUS,+ },+ });+ const injector = univer.__getInjector();+ const get = injector.get.bind(injector) as Injector['get'];++ injector.add([DocSelectionManagerService]);+ injector.add([IRenderManagerServiceToken, { useClass: TestRenderManagerService as never }]);+ injector.add([IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }]);+ injector.add([ThreadCommentModel]);+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);+ injector.add([ThreadCommentPanelService]);+ injector.add([DocThreadCommentService]);++ univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData(decorationIds));+ get(IUniverInstanceService).focusUnit(DOC_ID);+ get(UserManagerService).setCurrentUser({ userID: 'user-1', name: 'Ada' });+ get(ICommandService).registerCommand(SetActiveCommentOperation);++ return {+ univer,+ injector,+ get,+ threadCommentModel: get(ThreadCommentModel),+ panelService: get(ThreadCommentPanelService),+ };+}++function renderPanel(injector: Injector) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <DocThreadCommentPanel />+ </RediContext.Provider>+ );+ });++ return { container, root };+}++describe('DocThreadCommentPanel', () => {+ let univer: Univer | undefined;+ let root: Root | undefined;+ let container: HTMLElement | undefined;+ let scrollIntoViewDescriptor: PropertyDescriptor | undefined;++ beforeEach(() => {+ scrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView');+ Object.defineProperty(Element.prototype, 'scrollIntoView', {+ configurable: true,+ value() {},+ });+ });++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ univer?.dispose();+ if (scrollIntoViewDescriptor) {+ Object.defineProperty(Element.prototype, 'scrollIntoView', scrollIntoViewDescriptor);+ } else {+ delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView;+ }+ root = undefined;+ container = undefined;+ univer = undefined;+ });++ it('renders only thread comments attached to document custom ranges', () => {+ const testBed = createPanelTestBed(['visible-thread', 'visible-thread']);+ univer = testBed.univer;+ testBed.threadCommentModel.addComment(DOC_ID, DEFAULT_DOC_SUBUNIT_ID, createThread('visible-thread', 'Visible document feedback'));+ testBed.threadCommentModel.addComment(DOC_ID, DEFAULT_DOC_SUBUNIT_ID, createThread('detached-thread', 'Detached feedback'));++ const rendered = renderPanel(testBed.injector);+ root = rendered.root;+ container = rendered.container;++ expect(container.textContent).toContain('Visible document feedback');+ expect(container.textContent).not.toContain('Detached feedback');+ expect(container.textContent?.match(/Visible document feedback/g)).toHaveLength(1);+ });+});diff --git a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.tsindex 39060562ce..09125da5f9 100644--- a/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/clipboard.command.spec.ts@@ -14,14 +14,83 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, IDocumentData, Injector, IStyleBase, Univer } from '@univerjs/core';+import type { DocumentDataModel, ICommand, IDisposable, IDocumentData, Injector, IStyleBase, Univer } from '@univerjs/core';+import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';+import type { IDocClipboardHook } from '../../../services/clipboard/clipboard.service';import type { IInnerCutCommandParams, IInnerPasteCommandParams } from '../clipboard.inner.command';-import { BooleanNumber, ICommandService, IUniverInstanceService, UndoCommand, UniverInstanceType } from '@univerjs/core';+import {+ BooleanNumber,+ CustomDecorationType,+ DataStreamTreeTokenType,+ DOC_RANGE_TYPE,+ EDITOR_ACTIVATED,+ FOCUSING_DOC,+ ICommandService,+ IContextService,+ IUniverInstanceService,+ SliceBodyType,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import { IClipboardInterfaceService } from '@univerjs/ui';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { IDocClipboardService } from '../../../services/clipboard/clipboard.service';+import {+ DocCopyCommand,+ DocCopyCurrentParagraphCommand,+ DocCutCommand,+ DocCutCurrentParagraphCommand,+ DocPasteCommand,+ whenDocOrEditor,+ whenFocusEditor,+} from '../clipboard.command';import { CutContentCommand, InnerPasteCommand } from '../clipboard.inner.command';+import { genEmptyTable, genTableSource } from '../table/table';import { createCommandTestBed } from './create-command-test-bed';+class TestDocClipboardService {+ readonly copies: Array<{ sliceType?: SliceBodyType; ranges?: ITextRangeWithStyle[] }> = [];+ readonly cuts: Array<{ ranges?: ITextRangeWithStyle[] }> = [];+ readonly pastes: ClipboardItem[][] = [];++ async copy(sliceType?: SliceBodyType, ranges?: ITextRangeWithStyle[]): Promise<boolean> {+ this.copies.push({ sliceType, ranges });+ return true;+ }++ async cut(ranges?: ITextRangeWithStyle[]): Promise<boolean> {+ this.cuts.push({ ranges });+ return true;+ }++ async paste(items: ClipboardItem[]): Promise<boolean> {+ this.pastes.push(items);+ return true;+ }++ async legacyPaste(): Promise<boolean> {+ return false;+ }++ addClipboardHook(_hook: IDocClipboardHook): IDisposable {+ return { dispose() {} };+ }+}++class TestClipboardInterfaceService {+ items: ClipboardItem[] = [{ types: ['text/plain'] } as unknown as ClipboardItem];++ get supportClipboard(): boolean {+ return true;+ }++ async writeText(): Promise<void> {}+ async write(): Promise<void> {}+ async readText(): Promise<string> { return ''; }+ async read(): Promise<ClipboardItem[]> { return this.items; }+}+function getDocumentData() {const TEST_DOCUMENT_DATA_EN: IDocumentData = {id: 'test-doc',@@ -71,6 +140,9 @@ function getDocumentData() {marginRight: 90,marginLeft: 90,},+ tableSource: {},+ drawings: {},+ drawingsOrder: [],};return TEST_DOCUMENT_DATA_EN;@@ -79,43 +151,26 @@ function getDocumentData() {describe('test cases in clipboard', () => {let univer: Univer;let get: Injector['get'];+ let injector: Injector;let commandService: ICommandService;- function getFormatValueAt(key: keyof IStyleBase, pos: number) {+ function getDocumentModel() {const univerInstanceService = get(IUniverInstanceService);- const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);-- if (docsModel?.getBody()?.textRuns == null) {- return;- }-- for (const textRun of docsModel.getBody()?.textRuns ?? []) {- const { st, ed, ts = {} } = textRun;-- if (st <= pos && ed >= pos) {- return ts[key];- }- }+ return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);}- function getTextByPosition(start: number, end: number) {- const univerInstanceService = get(IUniverInstanceService);- const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);-- return docsModel?.getBody()?.dataStream.slice(start, end);+ function getDocumentSnapshot() {+ return getDocumentModel()?.getSnapshot();}- beforeEach(() => {- const testBed = createCommandTestBed(getDocumentData());- univer = testBed.univer;- get = testBed.get;-- commandService = get(ICommandService);+ function registerInnerClipboardCommands() {commandService.registerCommand(InnerPasteCommand);commandService.registerCommand(CutContentCommand);commandService.registerCommand(SetTextSelectionsOperation);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ }+ function addDefaultSelections() {const selectionManager = get(DocSelectionManagerService);selectionManager.__TEST_ONLY_setCurrentSelection({@@ -138,6 +193,158 @@ describe('test cases in clipboard', () => {collapsed: false,},]);+ }++ function setupDocument(docData = getDocumentData()) {+ const testBed = createCommandTestBed(docData);+ univer = testBed.univer;+ get = testBed.get;+ injector = testBed.injector;++ commandService = get(ICommandService);+ registerInnerClipboardCommands();+ addDefaultSelections();+ }++ function replaceDocument(docData: IDocumentData) {+ univer.dispose();+ setupDocument(docData);+ }++ function createTableDocumentData(): IDocumentData {+ const tableData = genEmptyTable(2, 2);+ const tableSource = genTableSource(2, 2, 360);+ const dataStream = `${tableData.dataStream}Tail\r\n`;++ return {+ id: 'test-doc',+ body: {+ dataStream,+ textRuns: [{ st: 0, ed: dataStream.length - 2, ts: {} }],+ paragraphs: [+ ...tableData.paragraphs,+ { paragraphId: 'para_docs_ui_clipboard_table_tail', startIndex: dataStream.length - 2 },+ ],+ sectionBreaks: [+ ...tableData.sectionBreaks,+ { startIndex: dataStream.length - 1 },+ ],+ tables: [{+ startIndex: 0,+ endIndex: tableData.dataStream.length,+ tableId: 'table-1',+ }],+ customBlocks: [],+ },+ documentStyle: {+ pageSize: { width: 540, height: 720 },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ tableSource: {+ 'table-1': {+ ...tableSource,+ tableId: 'table-1',+ },+ },+ };+ }++ function createCustomBlockDocumentData(): IDocumentData {+ const dataStream = `${DataStreamTreeTokenType.BLOCK_START}\rBody\r\n`;++ return {+ id: 'test-doc',+ body: {+ dataStream,+ textRuns: [{ st: 0, ed: dataStream.length - 2, ts: {} }],+ paragraphs: [+ { paragraphId: 'para_docs_ui_clipboard_block', startIndex: 1 },+ { paragraphId: 'para_docs_ui_clipboard_block_tail', startIndex: dataStream.length - 2 },+ ],+ sectionBreaks: [{ startIndex: dataStream.length - 1 }],+ customBlocks: [{ blockId: 'drawing-1', startIndex: 0 }],+ },+ drawings: {+ 'drawing-1': { drawingId: 'drawing-1' } as never,+ },+ drawingsOrder: ['drawing-1'],+ documentStyle: {+ pageSize: { width: 540, height: 720 },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+ }++ function createAnnotatedDocumentData(): IDocumentData {+ const documentData = getDocumentData();+ documentData.body!.customRanges = [{+ startIndex: 0,+ endIndex: 6,+ rangeId: 'range-1',+ rangeType: 0,+ }];+ documentData.body!.customDecorations = [{+ startIndex: 0,+ endIndex: 6,+ id: 'decoration-1',+ type: CustomDecorationType.COMMENT,+ }];++ return documentData;+ }++ function getTableClipboardDoc(): Partial<IDocumentData> {+ const tableData = genEmptyTable(1, 1);+ const tableSource = genTableSource(1, 1, 360);++ return {+ body: {+ ...tableData,+ tables: [{+ startIndex: 0,+ endIndex: tableData.dataStream.length,+ tableId: 'clip-table',+ }],+ },+ tableSource: {+ 'clip-table': {+ ...tableSource,+ tableId: 'clip-table',+ },+ },+ };+ }++ function getFormatValueAt(key: keyof IStyleBase, pos: number) {+ const docsModel = getDocumentModel();++ if (docsModel?.getBody()?.textRuns == null) {+ return;+ }++ for (const textRun of docsModel.getBody()?.textRuns ?? []) {+ const { st, ed, ts = {} } = textRun;++ if (st <= pos && ed >= pos) {+ return ts[key];+ }+ }+ }++ function getTextByPosition(start: number, end: number) {+ const docsModel = getDocumentModel();++ return docsModel?.getBody()?.dataStream.slice(start, end);+ }++ beforeEach(() => {+ setupDocument();});afterEach(() => univer.dispose());@@ -174,6 +381,139 @@ describe('test cases in clipboard', () => {expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();});++ it('Should insert pasted content at a collapsed cursor without deleting nearby text', async () => {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_add([{+ startOffset: 20,+ endOffset: 20,+ collapsed: true,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ await commandService.executeCommand(InnerPasteCommand.id, {+ segmentId: '',+ doc: {+ body: {+ dataStream: 'cursor-paste',+ textRuns: [{ st: 0, ed: 12, ts: { bl: BooleanNumber.TRUE } }],+ },+ },+ textRanges: [],+ } satisfies IInnerPasteCommandParams);++ expect(getDocumentSnapshot()?.body?.dataStream.includes('cursor-paste')).toBe(true);+ expect(getDocumentSnapshot()?.body?.dataStream.includes('Gartner')).toBe(true);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });++ it('Should inherit custom range and decoration metadata at the paste position', async () => {+ replaceDocument(createAnnotatedDocumentData());++ await commandService.executeCommand(InnerPasteCommand.id, {+ segmentId: '',+ doc: {+ body: {+ dataStream: 'note',+ textRuns: [{ st: 0, ed: 4, ts: { bl: BooleanNumber.TRUE } }],+ },+ },+ textRanges: [],+ } satisfies IInnerPasteCommandParams);++ const body = getDocumentSnapshot()?.body;++ expect(body?.dataStream.startsWith('note')).toBe(true);+ expect(body?.customRanges?.some((range) => range.rangeId === 'range-1')).toBe(true);+ expect(body?.customDecorations?.some((decoration) => decoration.id === 'decoration-1')).toBe(true);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });++ it('Should paste a copied table with fresh table ids into document selections', async () => {+ const commandParams: IInnerPasteCommandParams = {+ segmentId: '',+ doc: getTableClipboardDoc(),+ textRanges: [],+ };++ await commandService.executeCommand(InnerPasteCommand.id, commandParams);++ const snapshot = getDocumentSnapshot();+ const tableIds = Object.keys(snapshot?.tableSource ?? {});++ expect(tableIds).toHaveLength(2);+ expect(tableIds).not.toContain('clip-table');+ expect(snapshot?.body?.dataStream.includes(DataStreamTreeTokenType.TABLE_START)).toBe(true);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });++ it('Should reject table paste into header or footer segments', async () => {+ const beforeDataStream = getDocumentSnapshot()?.body?.dataStream;++ const result = await commandService.executeCommand(InnerPasteCommand.id, {+ segmentId: 'header-1',+ doc: getTableClipboardDoc(),+ textRanges: [],+ } satisfies IInnerPasteCommandParams);++ expect(result).toBe(false);+ expect(getDocumentSnapshot()?.body?.dataStream).toBe(beforeDataStream);+ });++ it('Should reject table paste when the active document selection is inside a table cell', async () => {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_add([{+ startOffset: 1,+ endOffset: 1,+ collapsed: true,+ startNodePosition: { path: ['body', 'tables', '0', 'cells', '0'] } as never,+ }]);+ const beforeDataStream = getDocumentSnapshot()?.body?.dataStream;++ const result = await commandService.executeCommand(InnerPasteCommand.id, {+ segmentId: '',+ doc: getTableClipboardDoc(),+ textRanges: [],+ } satisfies IInnerPasteCommandParams);++ expect(result).toBe(false);+ expect(getDocumentSnapshot()?.body?.dataStream).toBe(beforeDataStream);+ });++ it('Should paste custom block drawings with new ids for internal clipboard content', async () => {+ const blockDataStream = `${DataStreamTreeTokenType.BLOCK_START}\r`;+ const commandParams: IInnerPasteCommandParams = {+ segmentId: '',+ doc: {+ body: {+ dataStream: blockDataStream,+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_pasted_block', startIndex: 1 }],+ sectionBreaks: [],+ customBlocks: [{ blockId: 'clip-drawing', startIndex: 0 }],+ },+ drawings: {+ 'clip-drawing': { drawingId: 'clip-drawing' } as never,+ },+ },+ textRanges: [],+ };++ await commandService.executeCommand(InnerPasteCommand.id, commandParams);++ const snapshot = getDocumentSnapshot();+ const drawingIds = Object.keys(snapshot?.drawings ?? {});++ expect(snapshot?.drawingsOrder).toHaveLength(2);+ expect(snapshot?.drawingsOrder).not.toContain('clip-drawing');+ expect(drawingIds.sort()).toEqual([...(snapshot?.drawingsOrder ?? [])].sort());++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });});describe('Test cut in multiple ranges', () => {@@ -192,5 +532,163 @@ describe('test cases in clipboard', () => {expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();});++ it('Should leave document unchanged when cut has no document ranges', async () => {+ const beforeDataStream = getDocumentSnapshot()?.body?.dataStream;++ const result = await commandService.executeCommand(CutContentCommand.id, {+ segmentId: '',+ textRanges: [],+ selections: [],+ rectRanges: [],+ } satisfies IInnerCutCommandParams);++ expect(result).toBe(false);+ expect(getDocumentSnapshot()?.body?.dataStream).toBe(beforeDataStream);+ });++ it('Should cut a custom block and remove its drawing payload from the document', async () => {+ replaceDocument(createCustomBlockDocumentData());++ await commandService.executeCommand(CutContentCommand.id, {+ segmentId: '',+ textRanges: [],+ selections: [{+ startOffset: 0,+ endOffset: 1,+ collapsed: false,+ }],+ rectRanges: [],+ } satisfies IInnerCutCommandParams);++ const snapshot = getDocumentSnapshot();++ expect(snapshot?.body?.dataStream.startsWith(DataStreamTreeTokenType.BLOCK_START)).toBe(false);+ expect(snapshot?.body?.customBlocks ?? []).toHaveLength(0);+ expect(snapshot?.drawings?.['drawing-1']).toBeUndefined();+ expect(snapshot?.drawingsOrder ?? []).toHaveLength(0);++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });++ it('Should cut an entire selected table and remove the table source', async () => {+ replaceDocument(createTableDocumentData());+ const table = getDocumentSnapshot()?.body?.tables?.[0];+ if (!table) {+ throw new Error('Table not found');+ }+ const rectRange: IRectRangeWithStyle = {+ startOffset: table.startIndex,+ endOffset: table.endIndex - 1,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ tableId: 'table-1',+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ spanEntireRow: true,+ spanEntireColumn: true,+ spanEntireTable: true,+ };++ await commandService.executeCommand(CutContentCommand.id, {+ segmentId: '',+ textRanges: [],+ selections: [],+ rectRanges: [rectRange],+ } satisfies IInnerCutCommandParams);++ const snapshot = getDocumentSnapshot();++ expect(snapshot?.body?.dataStream.includes(DataStreamTreeTokenType.TABLE_START)).toBe(false);+ expect(snapshot?.tableSource?.['table-1']).toBeUndefined();++ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();+ });+ });++ describe('Test public doc clipboard commands', () => {+ beforeEach(() => {+ injector.add([IDocClipboardService, { useClass: TestDocClipboardService }]);+ injector.add([IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }]);++ commandService.registerMultipleCommand(DocCopyCommand);+ commandService.registerMultipleCommand(DocCutCommand);+ commandService.registerMultipleCommand(DocPasteCommand);+ commandService.registerCommand(DocCopyCurrentParagraphCommand);+ commandService.registerCommand(DocCutCurrentParagraphCommand);+ });++ it('Should enable document clipboard commands only while a doc or editor is focused', () => {+ const contextService = get(IContextService);++ contextService.setContextValue(FOCUSING_DOC, false);+ contextService.setContextValue(EDITOR_ACTIVATED, false);+ expect(whenDocOrEditor(contextService)).toBe(false);+ expect(whenFocusEditor(contextService)).toBe(false);++ contextService.setContextValue(FOCUSING_DOC, true);+ expect(whenDocOrEditor(contextService)).toBe(true);+ expect(whenFocusEditor(contextService)).toBe(false);++ contextService.setContextValue(EDITOR_ACTIVATED, true);+ expect(whenDocOrEditor(contextService)).toBe(true);+ expect(whenFocusEditor(contextService)).toBe(true);+ });++ it('Should route document copy and cut commands to the docs clipboard service', async () => {+ const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;++ await commandService.executeCommand(DocCopyCommand.id);+ await commandService.executeCommand(DocCutCommand.id);++ expect(docClipboardService.copies).toEqual([{ sliceType: undefined, ranges: undefined }]);+ expect(docClipboardService.cuts).toEqual([{ ranges: undefined }]);+ });++ it('Should route current paragraph copy and cut with paragraph document ranges', async () => {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_add([{+ startOffset: 3,+ endOffset: 3,+ collapsed: true,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);+ const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;++ await commandService.executeCommand(DocCopyCurrentParagraphCommand.id);+ await commandService.executeCommand(DocCutCurrentParagraphCommand.id);++ expect(docClipboardService.copies[0].sliceType).toBe(SliceBodyType.copy);+ expect(docClipboardService.copies[0].ranges?.[0]).toMatchObject({+ startOffset: 0,+ endOffset: 23,+ collapsed: false,+ });+ expect(docClipboardService.cuts[0].ranges?.[0]).toMatchObject({+ startOffset: 0,+ endOffset: 23,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.TEXT,+ });+ });++ it('Should read browser clipboard items before pasting into the document', async () => {+ const docClipboardService = get(IDocClipboardService) as unknown as TestDocClipboardService;+ const clipboardInterfaceService = get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;++ clipboardInterfaceService.items = [];+ const emptyResult = await commandService.executeCommand(DocPasteCommand.id);+ expect(emptyResult).toBe(false);+ expect(docClipboardService.pastes).toHaveLength(0);++ clipboardInterfaceService.items = [{ types: ['text/html'] } as unknown as ClipboardItem];+ await commandService.executeCommand(DocPasteCommand.id);++ expect(docClipboardService.pastes).toEqual([clipboardInterfaceService.items]);+ });});});diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.tsindex f741cad24e..a8209a26c6 100644--- a/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-block-move.command.spec.ts@@ -14,10 +14,18 @@* limitations under the License.*/-import type { IDocumentData } from '@univerjs/core';-import { BlockType, CustomRangeType, DocumentBlockRangeType } from '@univerjs/core';-import { describe, expect, it } from 'vitest';-import { buildMoveDocBlockActions } from '../doc-block-move.command';+import type { ICommand, IDocumentData } from '@univerjs/core';+import {+ awaitTime,+ BlockType,+ CustomRangeType,+ DocumentBlockRangeType,+ ICommandService,+} from '@univerjs/core';+import { RichTextEditingMutation } from '@univerjs/docs';+import { afterEach, describe, expect, it } from 'vitest';+import { buildMoveDocBlockActions, MoveDocBlockCommand } from '../doc-block-move.command';+import { createCommandTestBed } from './create-command-test-bed';describe('buildMoveDocBlockActions', () => {it('moves a paragraph and remaps paragraph indexes', () => {@@ -93,6 +101,128 @@ describe('buildMoveDocBlockActions', () => {expect(nextDocumentData.body?.dataStream).toBe('aa\r\b\r\n');expect(nextDocumentData.body?.customBlocks?.[0]).toMatchObject({ startIndex: 3 });});++ it('keeps the document unchanged when there is no movable body range', () => {+ const emptyDocument = createDocument('', {+ paragraphs: [],+ sectionBreaks: [],+ });++ expect(buildMoveDocBlockActions({+ documentData: emptyDocument,+ sourceRange: { startOffset: 0, endOffset: 3 },+ targetOffset: 10,+ })).toEqual({+ nextDocumentData: emptyDocument,+ movedRange: { startOffset: 0, endOffset: 3 },+ });++ const documentData = createDocument('A\rB\r\n', {+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_20', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_21', startIndex: 3 }],+ sectionBreaks: [{ startIndex: 4 }],+ });++ const { nextDocumentData, movedRange } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: -5, endOffset: 2 },+ targetOffset: 1,+ });++ expect(nextDocumentData.body?.dataStream).toBe('A\rB\r\n');+ expect(movedRange).toEqual({ startOffset: 0, endOffset: 2 });+ });++ it('remaps custom decorations that move with their paragraph', () => {+ const documentData = createDocument('aa\rDD\rcc\r\n', {+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_22', startIndex: 2 }, { paragraphId: 'para_docs_ui_fixture_23', startIndex: 5 }, { paragraphId: 'para_docs_ui_fixture_24', startIndex: 8 }],+ sectionBreaks: [{ startIndex: 9 }],+ customDecorations: [{ id: 'decoration-1', startIndex: 3, endIndex: 5 } as never],+ });++ const { nextDocumentData, movedRange } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: 3, endOffset: 6 },+ targetOffset: 0,+ });++ expect(nextDocumentData.body?.dataStream).toBe('DD\raa\rcc\r\n');+ expect(nextDocumentData.body?.customDecorations?.[0]).toMatchObject({ startIndex: 0, endIndex: 2 });+ expect(movedRange).toEqual({ startOffset: 0, endOffset: 3 });+ });++ it('keeps every document metadata collection ordered after moving content upward', () => {+ const documentData = createDocument('aa\rMM\rzz\r\n', {+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_29', startIndex: 2 }, { paragraphId: 'para_docs_ui_fixture_30', startIndex: 5 }, { paragraphId: 'para_docs_ui_fixture_31', startIndex: 8 }],+ sectionBreaks: [{ startIndex: 6 }, { startIndex: 9 }],+ customBlocks: [{ blockId: 'custom-2', blockType: BlockType.CUSTOM, startIndex: 3 }, { blockId: 'custom-3', blockType: BlockType.CUSTOM, startIndex: 6 }],+ tables: [{ tableId: 'table-2', startIndex: 3, endIndex: 5 }, { tableId: 'table-3', startIndex: 6, endIndex: 8 }],+ blockRanges: [{ blockId: 'quote-2', blockType: DocumentBlockRangeType.QUOTE, startIndex: 3, endIndex: 5 }, { blockId: 'quote-3', blockType: DocumentBlockRangeType.QUOTE, startIndex: 6, endIndex: 8 }],+ customRanges: [{ rangeId: 'comment-2', rangeType: CustomRangeType.COMMENT, startIndex: 3, endIndex: 5 }, { rangeId: 'comment-3', rangeType: CustomRangeType.COMMENT, startIndex: 6, endIndex: 8 }],+ customDecorations: [{ id: 'decoration-2', startIndex: 3, endIndex: 5 }, { id: 'decoration-3', startIndex: 6, endIndex: 8 }] as never,+ textRuns: [{ st: 3, ed: 5, ts: {} }, { st: 6, ed: 8, ts: {} }],+ });++ const { nextDocumentData } = buildMoveDocBlockActions({+ documentData,+ sourceRange: { startOffset: 3, endOffset: 6 },+ targetOffset: 0,+ });++ expect(nextDocumentData.body?.dataStream).toBe('MM\raa\rzz\r\n');+ expect(collectStarts(nextDocumentData.body?.sectionBreaks)).toEqual([6, 9]);+ expect(collectStarts(nextDocumentData.body?.customBlocks)).toEqual([0, 6]);+ expect(collectStarts(nextDocumentData.body?.tables)).toEqual([0, 6]);+ expect(collectStarts(nextDocumentData.body?.blockRanges)).toEqual([0, 6]);+ expect(collectStarts(nextDocumentData.body?.customRanges)).toEqual([0, 6]);+ expect(collectStarts(nextDocumentData.body?.customDecorations)).toEqual([0, 6]);+ expect(collectTextRunStarts(nextDocumentData.body?.textRuns)).toEqual([0, 6]);+ });+});++describe('MoveDocBlockCommand', () => {+ let testBed: ReturnType<typeof createCommandTestBed> | undefined;++ afterEach(() => {+ testBed?.univer.dispose();+ testBed = undefined;+ });++ it('moves a block through the real rich text mutation flow', async () => {+ testBed = createCommandTestBed(createDocument('A\rB\rC\r\n', {+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_25', startIndex: 1 }, { paragraphId: 'para_docs_ui_fixture_26', startIndex: 3 }, { paragraphId: 'para_docs_ui_fixture_27', startIndex: 5 }],+ sectionBreaks: [{ startIndex: 6 }],+ }));+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(MoveDocBlockCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ await expect(commandService.executeCommand(MoveDocBlockCommand.id, {+ unitId: 'test-doc',+ sourceRange: { startOffset: 0, endOffset: 2 },+ targetOffset: 6,+ })).resolves.toBe(true);++ await awaitTime(0);+ expect(testBed.doc.getSnapshot().body?.dataStream).toBe('B\rC\rA\r\n');+ expect(testBed.doc.getSnapshot().body?.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([1, 3, 5]);+ });++ it('does not mutate when the target document is missing', async () => {+ testBed = createCommandTestBed(createDocument('A\r\n', {+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_28', startIndex: 1 }],+ sectionBreaks: [{ startIndex: 2 }],+ }));+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(MoveDocBlockCommand);++ await expect(commandService.executeCommand(MoveDocBlockCommand.id, {+ unitId: 'missing-doc',+ sourceRange: { startOffset: 0, endOffset: 2 },+ targetOffset: 2,+ })).resolves.toBe(false);++ expect(testBed.doc.getSnapshot().body?.dataStream).toBe('A\r\n');+ });});function createDocument(dataStream: string, body: Partial<NonNullable<IDocumentData['body']>>): IDocumentData {@@ -115,3 +245,19 @@ function createDocument(dataStream: string, body: Partial<NonNullable<IDocumentD},};}++function collectStarts(items: Array<{ startIndex: number }> | undefined): number[] {+ const starts: number[] = [];+ for (const item of items ?? []) {+ starts.push(item.startIndex);+ }+ return starts;+}++function collectTextRunStarts(items: Array<{ st: number }> | undefined): number[] {+ const starts: number[] = [];+ for (const item of items ?? []) {+ starts.push(item.st);+ }+ return starts;+}diff --git a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.tsindex 561ece38f5..99e0a76272 100644--- a/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/doc-table-create.command.spec.ts@@ -14,10 +14,214 @@* limitations under the License.*/-import { DataStreamTreeTokenType } from '@univerjs/core';-import { describe, expect, it } from 'vitest';-import { buildDocTableInsertBody, normalizeTableInsertOffset, shouldCreateParagraphBeforeTable } from '../table/doc-table-create.command';-import { genEmptyTable } from '../table/table';+import type { ICommand, IDocumentData, Univer } from '@univerjs/core';+import { awaitTime, DataStreamTreeTokenType, ICommandService } from '@univerjs/core';+import {+ DocContentInsertService,+ DocSelectionManagerService,+ DocSkeletonManagerService,+ RichTextEditingMutation,+} from '@univerjs/docs';+import { afterEach, describe, expect, it } from 'vitest';+import {+ buildDocTableInsertBody,+ CreateDocTableCommand,+ normalizeTableInsertOffset,+ shouldCreateParagraphBeforeTable,+} from '../table/doc-table-create.command';+import {+ DocTableDeleteColumnsCommand,+ DocTableDeleteRowsCommand,+ DocTableDeleteTableCommand,+} from '../table/doc-table-delete.command';+import {+ DocTableInsertColumnCommand,+ DocTableInsertColumnLeftCommand,+ DocTableInsertColumnRightCommand,+ DocTableInsertRowAboveCommand,+ DocTableInsertRowBellowCommand,+ DocTableInsertRowCommand,+} from '../table/doc-table-insert.command';+import {+ CellPosition,+ genEmptyTable,+ genTableSource,+ getCellOffsets,+ getColumnWidths,+ getDeleteColumnsActionParams,+ getDeleteRowContentActionParams,+ getDeleteRowsActionsParams,+ getDeleteTableActionParams,+ getEmptyTableCell,+ getEmptyTableRow,+ getInsertColumnActionsParams,+ getInsertColumnBody,+ getInsertRowActionsParams,+ getInsertRowBody,+ getRangeInfoFromRanges,+ getTableColumn,+ INSERT_COLUMN_POSITION,+ INSERT_ROW_POSITION,+} from '../table/table';+import { createCommandTestBed } from './create-command-test-bed';++const TABLE_ID = 'table-1';+const TABLE_PREFIX = '';+const TABLE_SUFFIX = 'CD\r\n';++interface ITableFixture {+ documentData: IDocumentData;+ cellRanges: Array<{ startIndex: number; endIndex: number }>;+ rowRanges: Array<{ startIndex: number; endIndex: number }>;+ tableRange: { startIndex: number; endIndex: number };+}++let univer: Univer | undefined;++afterEach(() => {+ univer?.dispose();+ univer = undefined;+});++function createTableFixture(rowCount = 3, colCount = 3): ITableFixture {+ const tableData = genEmptyTable(rowCount, colCount);+ const tableSource = genTableSource(rowCount, colCount, 360);+ const dataStream = `${TABLE_PREFIX}${tableData.dataStream}${TABLE_SUFFIX}`;+ const tableStartIndex = TABLE_PREFIX.length;+ const tableEndIndex = tableStartIndex + tableData.dataStream.length;+ const documentData: IDocumentData = {+ id: 'test-doc',+ body: {+ dataStream,+ textRuns: [{+ st: 0,+ ed: dataStream.length - 2,+ ts: {},+ }],+ paragraphs: [+ ...tableData.paragraphs.map((paragraph) => ({+ ...paragraph,+ startIndex: paragraph.startIndex + tableStartIndex,+ })),+ { paragraphId: 'para_docs_ui_table_tail', startIndex: dataStream.length - 2 },+ ],+ sectionBreaks: [+ ...tableData.sectionBreaks.map((sectionBreak) => ({+ ...sectionBreak,+ startIndex: sectionBreak.startIndex + tableStartIndex,+ })),+ { startIndex: dataStream.length - 1 },+ ],+ tables: [{+ startIndex: tableStartIndex,+ endIndex: tableEndIndex,+ tableId: TABLE_ID,+ }],+ customBlocks: [],+ },+ documentStyle: {+ pageSize: { width: 540, height: 720 },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ tableSource: {+ [TABLE_ID]: {+ ...tableSource,+ tableId: TABLE_ID,+ },+ },+ };++ return {+ documentData,+ cellRanges: collectTokenRanges(dataStream, DataStreamTreeTokenType.TABLE_CELL_START, DataStreamTreeTokenType.TABLE_CELL_END, tableStartIndex, tableEndIndex),+ rowRanges: collectTokenRanges(dataStream, DataStreamTreeTokenType.TABLE_ROW_START, DataStreamTreeTokenType.TABLE_ROW_END, tableStartIndex, tableEndIndex),+ tableRange: { startIndex: tableStartIndex, endIndex: tableEndIndex - 1 },+ };+}++function collectTokenRanges(dataStream: string, startToken: string, endToken: string, from: number, to: number) {+ const ranges: Array<{ startIndex: number; endIndex: number }> = [];++ for (let i = from; i < to; i++) {+ if (dataStream[i] !== startToken) {+ continue;+ }++ const endIndex = dataStream.indexOf(endToken, i);+ ranges.push({ startIndex: i, endIndex });+ i = endIndex;+ }++ return ranges;+}++function createTableViewModel(fixture: ITableFixture) {+ const testBed = createCommandTestBed(fixture.documentData);+ univer = testBed.univer;++ return testBed.get(DocSkeletonManagerService).getViewModel();+}++function createTableCommandBed(fixture: ITableFixture) {+ const testBed = createCommandTestBed(fixture.documentData);+ univer = testBed.univer;++ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(DocTableInsertRowAboveCommand);+ commandService.registerCommand(DocTableInsertRowBellowCommand);+ commandService.registerCommand(DocTableInsertRowCommand);+ commandService.registerCommand(DocTableInsertColumnLeftCommand);+ commandService.registerCommand(DocTableInsertColumnRightCommand);+ commandService.registerCommand(DocTableInsertColumnCommand);+ commandService.registerCommand(DocTableDeleteRowsCommand);+ commandService.registerCommand(DocTableDeleteColumnsCommand);+ commandService.registerCommand(DocTableDeleteTableCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ return testBed;+}++function createTableCreationBed(documentData: IDocumentData) {+ const testBed = createCommandTestBed(documentData, [[DocContentInsertService]]);+ univer = testBed.univer;++ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(CreateDocTableCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ return testBed;+}++function setActiveTableRange(testBed: ReturnType<typeof createCommandTestBed>, startOffset: number, endOffset = startOffset) {+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset,+ endOffset,+ collapsed: startOffset === endOffset,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);+}++function asRange(startOffset: number, endOffset = startOffset) {+ return {+ startOffset,+ endOffset,+ segmentId: '',+ } as never;+}++function getOutsideTableOffset(fixture: ITableFixture) {+ return fixture.documentData.body!.dataStream.length - 1;+}describe('doc table create command helpers', () => {it('normalizes offset zero to keep the initial empty paragraph above the table', () => {@@ -55,4 +259,412 @@ describe('doc table create command helpers', () => {paragraphId: expect.stringMatching(/^para_/),});});++ it('builds empty table source with matching row, column, and cell defaults', () => {+ const table = genTableSource(2, 3, 480);++ expect(table.tableRows).toHaveLength(2);+ expect(table.tableRows[0].tableCells).toEqual([+ getEmptyTableCell(),+ getEmptyTableCell(),+ getEmptyTableCell(),+ ]);+ expect(table.tableRows[0].trHeight).toMatchObject({+ val: { v: 30 },+ });+ expect(table.tableColumns.map((column) => column.size.width.v)).toEqual([160, 160, 160]);+ expect(getEmptyTableRow(2).tableCells).toEqual([getEmptyTableCell(), getEmptyTableCell()]);+ expect(getTableColumn(42).size.width.v).toBe(42);+ });++ it('gets range info from rectangular table ranges before falling back to text range', () => {+ expect(getRangeInfoFromRanges(null, null)).toBeNull();+ expect(getRangeInfoFromRanges(asRange(4, 9), [])).toEqual({+ startOffset: 4,+ endOffset: 9,+ segmentId: '',+ });+ expect(getRangeInfoFromRanges(asRange(100, 110), [+ asRange(25, 28),+ asRange(12, 18),+ ])).toEqual({+ startOffset: 12,+ endOffset: 28,+ segmentId: '',+ });+ expect(getRangeInfoFromRanges(asRange(1, 2), [{ startOffset: null, endOffset: 4, segmentId: '' } as never])).toBeUndefined();+ });++ it('builds insert row and column bodies with paragraph metadata inside new cells', () => {+ const rowBody = getInsertRowBody(3);+ const columnBody = getInsertColumnBody();+ const expectedCellStream = `${DataStreamTreeTokenType.TABLE_CELL_START}\r\n${DataStreamTreeTokenType.TABLE_CELL_END}`;++ expect(rowBody.dataStream).toBe(`${DataStreamTreeTokenType.TABLE_ROW_START}${expectedCellStream.repeat(3)}${DataStreamTreeTokenType.TABLE_ROW_END}`);+ expect(rowBody.paragraphs.map((paragraph) => paragraph.startIndex)).toEqual([2, 6, 10]);+ expect(rowBody.sectionBreaks.map((sectionBreak) => sectionBreak.startIndex)).toEqual([3, 7, 11]);+ expect(rowBody.paragraphs.map((paragraph) => paragraph.paragraphStyle)).toEqual([+ { spaceAbove: { v: 3 }, lineSpacing: 2, spaceBelow: { v: 0 } },+ { spaceAbove: { v: 3 }, lineSpacing: 2, spaceBelow: { v: 0 } },+ { spaceAbove: { v: 3 }, lineSpacing: 2, spaceBelow: { v: 0 } },+ ]);++ expect(columnBody.dataStream).toBe(expectedCellStream);+ expect(columnBody.paragraphs[0].startIndex).toBe(1);+ expect(columnBody.sectionBreaks[0].startIndex).toBe(2);+ });++ it('rescales existing table columns and the inserted column to keep the page width fixed', () => {+ const result = getColumnWidths(600, [+ getTableColumn(100),+ getTableColumn(200),+ getTableColumn(300),+ ], 1);++ expect(result).toEqual({+ widths: [75, 150, 225],+ newColWidth: 150,+ });+ });++ it('computes row insertion params from the selected table row', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);+ const middleCell = fixture.cellRanges[4];++ expect(getInsertRowActionsParams(asRange(middleCell.startIndex + 1), INSERT_ROW_POSITION.ABOVE, viewModel)).toEqual({+ offset: fixture.rowRanges[1].startIndex,+ colCount: 3,+ tableId: TABLE_ID,+ insertRowIndex: 1,+ });+ expect(getInsertRowActionsParams(asRange(middleCell.startIndex + 1), INSERT_ROW_POSITION.BELLOW, viewModel)).toEqual({+ offset: fixture.rowRanges[1].endIndex + 1,+ colCount: 3,+ tableId: TABLE_ID,+ insertRowIndex: 2,+ });+ expect(getInsertRowActionsParams(asRange(getOutsideTableOffset(fixture)), INSERT_ROW_POSITION.ABOVE, viewModel)).toBeNull();+ });++ it('computes column insertion offsets for each selected table column cell', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);+ const columnCells = [fixture.cellRanges[1], fixture.cellRanges[4], fixture.cellRanges[7]];++ expect(getInsertColumnActionsParams(asRange(columnCells[0].startIndex + 1), INSERT_COLUMN_POSITION.LEFT, viewModel)).toEqual({+ offsets: [+ columnCells[0].startIndex,+ columnCells[1].startIndex - columnCells[0].startIndex,+ columnCells[2].startIndex - columnCells[1].startIndex,+ ],+ tableId: TABLE_ID,+ columnIndex: 1,+ rowCount: 3,+ });+ expect(getInsertColumnActionsParams(asRange(columnCells[0].startIndex + 1), INSERT_COLUMN_POSITION.RIGHT, viewModel)).toEqual({+ offsets: [+ columnCells[0].endIndex + 1,+ columnCells[1].endIndex - columnCells[0].endIndex,+ columnCells[2].endIndex - columnCells[1].endIndex,+ ],+ tableId: TABLE_ID,+ columnIndex: 1,+ rowCount: 3,+ });+ expect(getInsertColumnActionsParams(asRange(getOutsideTableOffset(fixture)), INSERT_COLUMN_POSITION.LEFT, viewModel)).toBeNull();+ });++ it('computes delete row params and flags full-table row selections', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);++ expect(getDeleteRowsActionsParams(asRange(fixture.rowRanges[1].startIndex, fixture.rowRanges[1].endIndex), viewModel)).toEqual({+ tableId: TABLE_ID,+ rowIndexes: [1],+ offset: fixture.rowRanges[1].startIndex,+ len: fixture.rowRanges[1].endIndex - fixture.rowRanges[1].startIndex + 1,+ cursor: fixture.tableRange.startIndex + 3,+ selectWholeTable: false,+ });+ expect(getDeleteRowsActionsParams(asRange(fixture.rowRanges[0].startIndex, fixture.rowRanges[2].endIndex), viewModel)).toEqual({+ tableId: TABLE_ID,+ rowIndexes: [0, 1, 2],+ offset: fixture.rowRanges[0].startIndex,+ len: fixture.rowRanges.reduce((total, row) => total + row.endIndex - row.startIndex + 1, 0),+ cursor: fixture.tableRange.startIndex + 3,+ selectWholeTable: true,+ });+ expect(getDeleteRowsActionsParams(asRange(getOutsideTableOffset(fixture)), viewModel)).toBeNull();+ });++ it('computes delete column params across rows and flags full-table column selections', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);+ const columnCells = [fixture.cellRanges[1], fixture.cellRanges[4], fixture.cellRanges[7]];++ expect(getDeleteColumnsActionParams(asRange(columnCells[0].startIndex, columnCells[2].endIndex), viewModel)).toEqual({+ offsets: [+ { retain: columnCells[0].startIndex, delete: columnCells[0].endIndex - columnCells[0].startIndex + 1 },+ { retain: columnCells[1].startIndex - columnCells[0].endIndex - 1, delete: columnCells[1].endIndex - columnCells[1].startIndex + 1 },+ { retain: columnCells[2].startIndex - columnCells[1].endIndex - 1, delete: columnCells[2].endIndex - columnCells[2].startIndex + 1 },+ ],+ tableId: TABLE_ID,+ columnIndexes: [1],+ cursor: fixture.tableRange.startIndex + 3,+ selectWholeTable: false,+ rowCount: 3,+ });+ expect(getDeleteColumnsActionParams(asRange(fixture.cellRanges[0].startIndex, fixture.cellRanges[8].endIndex), viewModel)).toMatchObject({+ tableId: TABLE_ID,+ columnIndexes: [0, 1, 2],+ selectWholeTable: true,+ rowCount: 3,+ });+ expect(getDeleteColumnsActionParams(asRange(getOutsideTableOffset(fixture)), viewModel)).toBeNull();+ });++ it('computes delete table params from a range inside the table', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);++ expect(getDeleteTableActionParams(asRange(fixture.cellRanges[4].startIndex + 1), viewModel)).toEqual({+ tableId: TABLE_ID,+ offset: fixture.tableRange.startIndex,+ len: fixture.tableRange.endIndex - fixture.tableRange.startIndex + 1,+ cursor: fixture.tableRange.startIndex,+ });+ expect(getDeleteTableActionParams(asRange(getOutsideTableOffset(fixture)), viewModel)).toBeNull();+ });++ it('computes delete row-content params for the selected cells in one row', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);+ const selectedCells = [fixture.cellRanges[3], fixture.cellRanges[4]];++ expect(getDeleteRowContentActionParams(asRange(selectedCells[0].startIndex, selectedCells[1].endIndex), viewModel)).toEqual({+ offsets: [+ { retain: selectedCells[0].startIndex + 1, delete: selectedCells[0].endIndex - selectedCells[0].startIndex - 3 },+ { retain: selectedCells[1].startIndex + 1, delete: selectedCells[1].endIndex - selectedCells[1].startIndex - 3 },+ ],+ tableId: TABLE_ID,+ cursor: fixture.tableRange.startIndex + 3,+ rowCount: 3,+ });+ expect(getDeleteRowContentActionParams(asRange(getOutsideTableOffset(fixture)), viewModel)).toBeNull();+ });++ it('moves between neighboring table cells by returning editable cell content offsets', () => {+ const fixture = createTableFixture();+ const viewModel = createTableViewModel(fixture);++ expect(getCellOffsets(viewModel, asRange(fixture.cellRanges[1].startIndex + 1), CellPosition.NEXT)).toEqual({+ startOffset: fixture.cellRanges[2].startIndex + 1,+ endOffset: fixture.cellRanges[2].endIndex - 2,+ });+ expect(getCellOffsets(viewModel, asRange(fixture.cellRanges[3].startIndex + 1), CellPosition.PREV)).toEqual({+ startOffset: fixture.cellRanges[2].startIndex + 1,+ endOffset: fixture.cellRanges[2].endIndex - 2,+ });+ expect(getCellOffsets(viewModel, asRange(0), CellPosition.NEXT)).toBeNull();+ });++ it('executes row insertion through the registered table command chain', async () => {+ const fixture = createTableFixture();+ const testBed = createTableCommandBed(fixture);+ const commandService = testBed.get(ICommandService);+ setActiveTableRange(testBed, fixture.cellRanges[4].startIndex + 1);++ const result = await commandService.executeCommand(DocTableInsertRowAboveCommand.id);+ await awaitTime(0);++ expect(result).toBe(true);+ expect(testBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows).toHaveLength(4);+ expect(testBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows[1].tableCells).toEqual([+ getEmptyTableCell(),+ getEmptyTableCell(),+ getEmptyTableCell(),+ ]);+ });++ it('executes column insertion and keeps table width distributed across all columns', async () => {+ const fixture = createTableFixture();+ const testBed = createTableCommandBed(fixture);+ const commandService = testBed.get(ICommandService);+ setActiveTableRange(testBed, fixture.cellRanges[1].startIndex + 1);++ const result = await commandService.executeCommand(DocTableInsertColumnRightCommand.id);+ await awaitTime(0);++ const tableSource = testBed.doc.getSnapshot().tableSource?.[TABLE_ID];+ expect(result).toBe(true);+ expect(tableSource?.tableRows.map((row) => row.tableCells.length)).toEqual([4, 4, 4]);+ expect(tableSource?.tableColumns.map((column) => column.size.width.v)).toEqual([90, 90, 90, 90]);+ });++ it('executes below-row and left-column insertion aliases', async () => {+ const rowFixture = createTableFixture();+ const rowTestBed = createTableCommandBed(rowFixture);+ let commandService = rowTestBed.get(ICommandService);+ setActiveTableRange(rowTestBed, rowFixture.cellRanges[4].startIndex + 1);++ expect(await commandService.executeCommand(DocTableInsertRowBellowCommand.id)).toBe(true);+ await awaitTime(0);+ expect(rowTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows).toHaveLength(4);+ rowTestBed.univer.dispose();++ const columnFixture = createTableFixture();+ const columnTestBed = createTableCommandBed(columnFixture);+ commandService = columnTestBed.get(ICommandService);+ setActiveTableRange(columnTestBed, columnFixture.cellRanges[1].startIndex + 1);++ expect(await commandService.executeCommand(DocTableInsertColumnLeftCommand.id)).toBe(true);+ await awaitTime(0);+ expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableColumns).toHaveLength(4);+ expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows.map((row) => row.tableCells.length)).toEqual([4, 4, 4]);+ });++ it('executes row, column, and table deletion commands against table structure', async () => {+ const rowFixture = createTableFixture();+ const rowTestBed = createTableCommandBed(rowFixture);+ let commandService = rowTestBed.get(ICommandService);+ setActiveTableRange(rowTestBed, rowFixture.rowRanges[1].startIndex, rowFixture.rowRanges[1].endIndex);++ expect(await commandService.executeCommand(DocTableDeleteRowsCommand.id)).toBe(true);+ await awaitTime(0);+ expect(rowTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows).toHaveLength(2);+ rowTestBed.univer.dispose();++ const columnFixture = createTableFixture();+ const columnTestBed = createTableCommandBed(columnFixture);+ commandService = columnTestBed.get(ICommandService);+ setActiveTableRange(columnTestBed, columnFixture.cellRanges[1].startIndex, columnFixture.cellRanges[7].endIndex);++ expect(await commandService.executeCommand(DocTableDeleteColumnsCommand.id)).toBe(true);+ await awaitTime(0);+ expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableColumns).toHaveLength(2);+ expect(columnTestBed.doc.getSnapshot().tableSource?.[TABLE_ID].tableRows.map((row) => row.tableCells.length)).toEqual([2, 2, 2]);+ columnTestBed.univer.dispose();++ const tableFixture = createTableFixture();+ const tableTestBed = createTableCommandBed(tableFixture);+ commandService = tableTestBed.get(ICommandService);+ setActiveTableRange(tableTestBed, tableFixture.cellRanges[4].startIndex + 1);++ expect(await commandService.executeCommand(DocTableDeleteTableCommand.id)).toBe(true);+ await awaitTime(0);+ expect(tableTestBed.doc.getBody()?.dataStream).toBe(TABLE_SUFFIX);+ expect(testBedSnapshotTableIds(tableTestBed)).toEqual([]);+ });++ it('creates a table at the current document selection and fits it to page content width', async () => {+ const testBed = createTableCreationBed(createParagraphDocument('Hello\r\n'));+ const commandService = testBed.get(ICommandService);+ setActiveTableRange(testBed, 5);+ setCommandSkeletonPage(testBed, 5, {+ pageWidth: 540,+ marginLeft: 90,+ marginRight: 90,+ });++ await expect(commandService.executeCommand(CreateDocTableCommand.id, {+ rowCount: 2,+ colCount: 3,+ })).resolves.toBe(true);+ await awaitTime(0);++ const snapshot = testBed.doc.getSnapshot();+ const tableId = Object.keys(snapshot.tableSource ?? {})[0];+ expect(snapshot.body?.dataStream).toContain(DataStreamTreeTokenType.TABLE_START);+ expect(snapshot.body?.dataStream).toContain(DataStreamTreeTokenType.TABLE_END);+ expect(snapshot.tableSource?.[tableId].tableRows).toHaveLength(2);+ expect(snapshot.tableSource?.[tableId].tableRows.map((row) => row.tableCells.length)).toEqual([3, 3]);+ expect(snapshot.tableSource?.[tableId].tableColumns.map((column) => column.size.width.v)).toEqual([120, 120, 120]);+ });++ it('creates a table from the paragraph menu insert range when there is no active selection', async () => {+ const testBed = createTableCreationBed(createParagraphDocument('Hello\r\n'));+ const commandService = testBed.get(ICommandService);+ testBed.get(DocContentInsertService).setInsertRange({+ unitId: 'test-doc',+ startOffset: 0,+ endOffset: 0,+ });+ setCommandSkeletonPage(testBed, 0, {+ pageWidth: 500,+ marginLeft: 70,+ marginRight: 70,+ });++ await expect(commandService.executeCommand(CreateDocTableCommand.id, {+ rowCount: 1,+ colCount: 2,+ })).resolves.toBe(true);+ await awaitTime(0);++ const snapshot = testBed.doc.getSnapshot();+ const tableId = Object.keys(snapshot.tableSource ?? {})[0];+ expect(snapshot.body?.dataStream).toContain(DataStreamTreeTokenType.TABLE_START);+ expect(snapshot.body?.dataStream).toContain(DataStreamTreeTokenType.TABLE_END);+ expect(snapshot.tableSource?.[tableId].tableRows).toHaveLength(1);+ expect(snapshot.tableSource?.[tableId].tableColumns.map((column) => column.size.width.v)).toEqual([180, 180]);+ });++ it('does not create a table without a render skeleton for the cursor', async () => {+ const testBed = createTableCreationBed(createParagraphDocument('Hello\r\n'));+ const commandService = testBed.get(ICommandService);+ setActiveTableRange(testBed, 5);+ const skeletonManager = testBed.get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => null;++ await expect(commandService.executeCommand(CreateDocTableCommand.id, {+ rowCount: 1,+ colCount: 1,+ })).resolves.toBe(false);++ expect(testBed.doc.getSnapshot().body?.tables).toBeUndefined();+ expect(testBed.doc.getSnapshot().tableSource).toEqual({});+ });});++function testBedSnapshotTableIds(testBed: ReturnType<typeof createCommandTestBed>) {+ return Object.keys(testBed.doc.getSnapshot().tableSource ?? {});+}++function createParagraphDocument(dataStream: string): IDocumentData {+ return {+ id: 'test-doc',+ body: {+ dataStream,+ textRuns: [{+ st: 0,+ ed: dataStream.length - 2,+ ts: {},+ }],+ paragraphs: [{ paragraphId: 'para_docs_ui_create_table', startIndex: dataStream.length - 2 }],+ sectionBreaks: [{ startIndex: dataStream.length - 1 }],+ customBlocks: [],+ },+ documentStyle: {+ pageSize: { width: 540, height: 720 },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ tableSource: {},+ };+}++function setCommandSkeletonPage(testBed: ReturnType<typeof createCommandTestBed>, offset: number, pageInfo: { pageWidth: number; marginLeft: number; marginRight: number }) {+ const page = { ...pageInfo };+ const pageChild = { parent: page };+ const paragraph = { parent: pageChild };+ const line = { parent: paragraph };+ const divide = { parent: line };+ const glyph = { parent: divide };+ const skeletonManager = testBed.get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => ({+ findNodeByCharIndex: (index: number) => index === offset ? glyph : null,+ });+}diff --git a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.tsindex c188584666..28e06959e4 100644--- a/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/inline-format.command.spec.ts@@ -14,11 +14,21 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, Injector, IStyleBase, Univer } from '@univerjs/core';-import { BooleanNumber, DOC_RANGE_TYPE, ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';+import type { DocumentDataModel, ICommand, Injector, ITextStyle, Univer } from '@univerjs/core';+import {+ BaselineOffset,+ BooleanNumber,+ DOC_RANGE_TYPE,+ ICommandService,+ IUniverInstanceService,+ RedoCommand,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import {+ ResetInlineFormatTextBackgroundColorCommand,ResetInlineFormatTextColorCommand,SetInlineFormatBoldCommand,SetInlineFormatCommand,@@ -26,7 +36,11 @@ import {SetInlineFormatFontSizeCommand,SetInlineFormatItalicCommand,SetInlineFormatStrikethroughCommand,+ SetInlineFormatSubscriptCommand,+ SetInlineFormatSuperscriptCommand,+ SetInlineFormatTextBackgroundColorCommand,SetInlineFormatTextColorCommand,+ SetInlineFormatTextFillCommand,SetInlineFormatUnderlineCommand,} from '../inline-format.command';import { createCommandTestBed } from './create-command-test-bed';@@ -36,7 +50,7 @@ describe('Test inline format commands', () => {let get: Injector['get'];let commandService: ICommandService;- function getFormatValueAt(key: keyof IStyleBase, pos: number) {+ function getFormatValueAt(key: keyof ITextStyle, pos: number) {const univerInstanceService = get(IUniverInstanceService);const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);@@ -60,7 +74,19 @@ describe('Test inline format commands', () => {commandService = get(ICommandService);commandService.registerCommand(SetInlineFormatCommand);+ commandService.registerCommand(SetInlineFormatBoldCommand);+ commandService.registerCommand(SetInlineFormatItalicCommand);+ commandService.registerCommand(SetInlineFormatUnderlineCommand);+ commandService.registerCommand(SetInlineFormatStrikethroughCommand);+ commandService.registerCommand(SetInlineFormatSubscriptCommand);+ commandService.registerCommand(SetInlineFormatSuperscriptCommand);+ commandService.registerCommand(SetInlineFormatFontFamilyCommand);+ commandService.registerCommand(SetInlineFormatFontSizeCommand);+ commandService.registerCommand(SetInlineFormatTextColorCommand);+ commandService.registerCommand(SetInlineFormatTextFillCommand);+ commandService.registerCommand(SetInlineFormatTextBackgroundColorCommand);commandService.registerCommand(ResetInlineFormatTextColorCommand);+ commandService.registerCommand(ResetInlineFormatTextBackgroundColorCommand);commandService.registerCommand(SetTextSelectionsOperation);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);@@ -91,6 +117,81 @@ describe('Test inline format commands', () => {afterEach(() => univer.dispose());+ describe('Public inline format wrapper commands', () => {+ it('applies document text styles through the menu command wrappers', async () => {+ let appliedCommandCount = 0;++ try {+ await commandService.executeCommand(SetInlineFormatBoldCommand.id);+ appliedCommandCount++;+ await commandService.executeCommand(SetInlineFormatItalicCommand.id);+ appliedCommandCount++;+ await commandService.executeCommand(SetInlineFormatUnderlineCommand.id);+ appliedCommandCount++;+ await commandService.executeCommand(SetInlineFormatStrikethroughCommand.id);+ appliedCommandCount++;++ expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.TRUE);+ expect(getFormatValueAt('it', 1)).toBe(BooleanNumber.TRUE);+ expect(getFormatValueAt('ul', 1)).toStrictEqual({ s: BooleanNumber.TRUE });+ expect(getFormatValueAt('st', 1)).toStrictEqual({ s: BooleanNumber.TRUE });++ await commandService.executeCommand(SetInlineFormatSubscriptCommand.id);+ appliedCommandCount++;+ expect(getFormatValueAt('va', 1)).toBe(BaselineOffset.SUBSCRIPT);++ await commandService.executeCommand(SetInlineFormatSuperscriptCommand.id);+ appliedCommandCount++;+ expect(getFormatValueAt('va', 1)).toBe(BaselineOffset.SUPERSCRIPT);++ await commandService.executeCommand(SetInlineFormatSuperscriptCommand.id);+ appliedCommandCount++;+ expect(getFormatValueAt('va', 1)).toBe(BaselineOffset.NORMAL);++ await commandService.executeCommand(SetInlineFormatFontFamilyCommand.id, { value: 'Inter' });+ appliedCommandCount++;+ await commandService.executeCommand(SetInlineFormatFontSizeCommand.id, { value: 32 });+ appliedCommandCount++;+ expect(getFormatValueAt('ff', 1)).toBe('Inter');+ expect(getFormatValueAt('fs', 1)).toBe(32);++ await commandService.executeCommand(SetInlineFormatTextColorCommand.id, { value: '#224466' });+ appliedCommandCount++;+ await commandService.executeCommand(SetInlineFormatTextBackgroundColorCommand.id, { value: '#ffeeaa' });+ appliedCommandCount++;+ expect(getFormatValueAt('cl', 1)).toStrictEqual({ rgb: '#224466' });+ expect(getFormatValueAt('bg', 1)).toStrictEqual({ rgb: '#ffeeaa' });++ await commandService.executeCommand(ResetInlineFormatTextColorCommand.id);+ appliedCommandCount++;+ await commandService.executeCommand(ResetInlineFormatTextBackgroundColorCommand.id);+ appliedCommandCount++;+ expect(getFormatValueAt('cl', 1)).toStrictEqual({ rgb: null });+ expect(getFormatValueAt('bg', 1)).toStrictEqual({ rgb: null });++ await commandService.executeCommand(SetInlineFormatTextFillCommand.id, {+ value: {+ textFill: {+ type: 'solid',+ color: '#445566',+ opacity: 0.8,+ },+ },+ });+ appliedCommandCount++;+ expect(getFormatValueAt('textFill', 1)).toStrictEqual({+ type: 'solid',+ color: '#445566',+ opacity: 0.8,+ });+ } finally {+ for (let i = 0; i < appliedCommandCount; i++) {+ await commandService.executeCommand(UndoCommand.id);+ }+ }+ });+ });+describe('Set Bold by SetInlineFormatCommand', () => {it('Should change text in range(0, 5) to bold', async () => {expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.FALSE);diff --git a/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.tsindex d6616b18ad..5e89b33a35 100644--- a/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts@@ -15,9 +15,17 @@*/import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';-import { awaitTime, ICommandService, IUniverInstanceService, PRESET_LIST_TYPE, PresetListType, UniverInstanceType } from '@univerjs/core';+import {+ awaitTime,+ ICommandService,+ IUniverInstanceService,+ PRESET_LIST_TYPE,+ PresetListType,+ UniverInstanceType,+} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { InsertBulletBelowCommand } from '../insert-below/insert-bullet-below.command';import {BulletListCommand,ChangeListNestingLevelCommand,@@ -26,8 +34,13 @@ import {CheckListCommand,findNearestSectionBreak,getParagraphsRelative,+ InsertBulletListBellowCommand,+ InsertCheckListBellowCommand,+ InsertOrderListBellowCommand,ListOperationCommand,+ OrderListCommand,QuickListCommand,+ ToggleCheckListCommand,} from '../list.command';import { createCommandTestBed } from './create-command-test-bed';@@ -58,6 +71,7 @@ describe('list commands', () => {let univer: Univer;let get: Injector['get'];let commandService: ICommandService;+ let selectionId: number;function getBody() {const univerInstanceService = get(IUniverInstanceService);@@ -66,9 +80,10 @@ describe('list commands', () => {function setSelections(ranges: Array<{ startOffset: number; endOffset: number; collapsed: boolean }>) {const selectionManager = get(DocSelectionManagerService);+ const subUnitId = `test-doc-selection-${selectionId++}`;selectionManager.__TEST_ONLY_setCurrentSelection({unitId: 'test-doc',- subUnitId: 'test-doc',+ subUnitId,});selectionManager.__TEST_ONLY_add(ranges.map((range, index) => ({...range,@@ -82,6 +97,7 @@ describe('list commands', () => {const testBed = createCommandTestBed(getDocumentData());univer = testBed.univer;get = testBed.get;+ selectionId = 0;commandService = get(ICommandService);commandService.registerCommand(ListOperationCommand);@@ -89,7 +105,13 @@ describe('list commands', () => {commandService.registerCommand(ChangeListNestingLevelCommand);commandService.registerCommand(BulletListCommand);commandService.registerCommand(CheckListCommand);+ commandService.registerCommand(OrderListCommand);+ commandService.registerCommand(ToggleCheckListCommand);commandService.registerCommand(QuickListCommand);+ commandService.registerCommand(InsertBulletListBellowCommand);+ commandService.registerCommand(InsertOrderListBellowCommand);+ commandService.registerCommand(InsertCheckListBellowCommand);+ commandService.registerCommand(InsertBulletBelowCommand);commandService.registerCommand(SetTextSelectionsOperation);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);});@@ -153,12 +175,125 @@ describe('list commands', () => {await awaitTime(0);expect(getBody()?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.ORDER_LIST);- expect(getBody()?.paragraphs?.[0].bullet?.listId).toBeDefined();+ expect(getBody()?.paragraphs?.[0].bullet?.nestingLevel).toBe(0);expect(getBody()?.paragraphs?.[0].paragraphStyle?.textStyle).toMatchObject(PRESET_LIST_TYPE[PresetListType.ORDER_LIST].nestingLevel[0].paragraphProperties?.textStyle ?? {});});+ it('applies ordered lists and retypes selected list paragraphs through toolbar commands', async () => {+ setSelections([+ { startOffset: 0, endOffset: 4, collapsed: false },+ { startOffset: 6, endOffset: 9, collapsed: false },+ ]);++ await commandService.executeCommand(OrderListCommand.id);+ await commandService.executeCommand(BulletListCommand.id, {+ value: PresetListType.CHECK_LIST,+ });+ await commandService.executeCommand(CheckListCommand.id, {+ value: PresetListType.CHECK_LIST_CHECKED,+ });+ await awaitTime(0);++ const paragraphs = getBody()?.paragraphs ?? [];+ expect(paragraphs.map((paragraph) => paragraph.bullet?.listType)).toEqual([+ PresetListType.CHECK_LIST_CHECKED,+ PresetListType.CHECK_LIST_CHECKED,+ ]);+ expect(paragraphs[0].bullet?.listId).toBe(paragraphs[1].bullet?.listId);+ });++ it('toggles a checklist item between checked and unchecked states', async () => {+ setSelections([{ startOffset: 0, endOffset: 4, collapsed: false }]);++ await commandService.executeCommand(CheckListCommand.id);+ await commandService.executeCommand(ToggleCheckListCommand.id, {+ index: 5,+ segmentId: '',+ textRanges: [{ startOffset: 0, endOffset: 4, collapsed: false, segmentId: '' }],+ });+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);++ await commandService.executeCommand(ToggleCheckListCommand.id, {+ index: 5,+ segmentId: '',+ textRanges: [{ startOffset: 0, endOffset: 4, collapsed: false, segmentId: '' }],+ });+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);+ });++ it('inserts new list items below the current paragraph for every list menu action', async () => {+ setSelections([{ startOffset: 2, endOffset: 2, collapsed: true }]);++ await commandService.executeCommand(InsertBulletListBellowCommand.id);+ await awaitTime(0);++ expect(getBody()?.paragraphs).toHaveLength(3);+ expect(getBody()?.paragraphs?.[1].bullet).toMatchObject({+ listType: PresetListType.BULLET_LIST,+ nestingLevel: 0,+ });++ setSelections([{ startOffset: 2, endOffset: 2, collapsed: true }]);+ await commandService.executeCommand(InsertOrderListBellowCommand.id);+ await awaitTime(0);++ expect(getBody()?.paragraphs).toHaveLength(4);+ expect(getBody()?.paragraphs?.[1].bullet).toMatchObject({+ listType: PresetListType.ORDER_LIST,+ nestingLevel: 0,+ });++ setSelections([{ startOffset: 2, endOffset: 2, collapsed: true }]);+ await commandService.executeCommand(InsertCheckListBellowCommand.id);+ await awaitTime(0);++ expect(getBody()?.paragraphs).toHaveLength(5);+ expect(getBody()?.paragraphs?.[1].bullet).toMatchObject({+ listType: PresetListType.CHECK_LIST,+ nestingLevel: 0,+ });+ });++ it('inserts a bullet below the focused list item and keeps the active list identity', async () => {+ setSelections([{ startOffset: 0, endOffset: 4, collapsed: false }]);++ await commandService.executeCommand(BulletListCommand.id);+ await awaitTime(0);++ const sourceBullet = getBody()?.paragraphs?.[0].bullet;+ setSelections([{ startOffset: 2, endOffset: 2, collapsed: true }]);++ await commandService.executeCommand(InsertBulletBelowCommand.id, {+ listType: PresetListType.BULLET_LIST,+ });+ await awaitTime(0);++ expect(getBody()?.paragraphs).toHaveLength(3);+ expect(getBody()?.paragraphs?.[1].bullet).toEqual({+ listType: PresetListType.BULLET_LIST,+ listId: sourceBullet?.listId,+ nestingLevel: sourceBullet?.nestingLevel,+ });+ });++ it('does not insert a bullet below when the active selection spans text', async () => {+ setSelections([{ startOffset: 0, endOffset: 4, collapsed: false }]);++ const result = await commandService.executeCommand(InsertBulletBelowCommand.id, {+ listType: PresetListType.BULLET_LIST,+ });++ expect(result).toBe(false);+ expect(getBody()?.paragraphs).toHaveLength(2);+ expect(getBody()?.dataStream).toBe('Alpha\rBeta\r\n');+ });+it('extends selected paragraphs to adjacent items in the same list and finds nearest section breaks', () => {const paragraphs = [{ startIndex: 5, bullet: { listType: PresetListType.BULLET_LIST, listId: 'list-1', nestingLevel: 0 } },diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.tsindex d798630227..a9fa0648eb 100644--- a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts@@ -14,34 +14,185 @@* limitations under the License.*/-import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';+import type { DocumentDataModel, ICommand, IDisposable, IDocumentData, Injector, Univer } from '@univerjs/core';+import type { IConfirmPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';import type { IAutoFormat } from '../../../services/doc-auto-format.service';import {awaitTime,+ BooleanNumber,CommandType,CustomRangeType,+ DashStyleType,+ DataStreamTreeTokenType,+ DeleteDirection,+ Direction,+ Disposable,+ DocumentFlavor,HorizontalAlign,ICommandService,+ IConfirmService,IUniverInstanceService,+ LocaleService,+ LocaleType,NamedStyleType,+ ObjectRelativeFromV,+ PAGE_SIZE,+ PageOrientType,+ PaperType,+ PositionedObjectLayoutType,+ toDisposable,UniverInstanceType,} from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import {+ DeleteTextCommand,+ DocSelectionManagerService,+ DocSkeletonManagerService,+ RichTextEditingMutation,+ SetTextSelectionsOperation,+ UpdateTextCommand,+} from '@univerjs/docs';+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';+import { ISidebarService } from '@univerjs/ui';+import { Subject } from 'rxjs';import { afterEach, describe, expect, it } from 'vitest';+import { HeaderFooterType } from '../../../controllers/doc-header-footer.controller';+import { DocParagraphSettingController } from '../../../controllers/doc-paragraph-setting.controller';import { DocAutoFormatService } from '../../../services/doc-auto-format.service';+import { DocIMEInputManagerService } from '../../../services/doc-ime-input-manager.service';+import { DocSelectionRenderService } from '../../../services/selection/doc-selection-render.service';+import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../../../views/header-footer/panel/component-name';+import { PAGE_SETTING_COMPONENT_ID } from '../../../views/PageSettings';+import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../../../views/table/create/component-name';+import { DocCreateTableOperation } from '../../operations/doc-create-table.operation';+import { MoveCursorOperation, MoveSelectionOperation } from '../../operations/doc-cursor.operation';+import { SidebarDocHeaderFooterPanelOperation } from '../../operations/doc-header-footer-panel.operation';+import { DocParagraphSettingPanelOperation } from '../../operations/doc-paragraph-setting-panel.operation';+import { DocOpenPageSettingCommand } from '../../operations/open-page-setting.operation';import { SetDocZoomRatioOperation } from '../../operations/set-doc-zoom-ratio.operation';import { AfterSpaceCommand, EnterCommand, TabCommand } from '../auto-format.command';import { BreakLineCommand } from '../break-line.command';+import { CutContentCommand } from '../clipboard.inner.command';+import {+ DeleteCurrentParagraphCommand,+ DeleteCustomBlockCommand,+ DeleteLeftCommand,+ DeleteRightCommand,+ getCursorWhenDelete,+ MergeTwoParagraphCommand,+ RemoveHorizontalLineCommand,+} from '../doc-delete.command';+import { CloseHeaderFooterCommand, CoreHeaderFooterCommand, OpenHeaderFooterPanelCommand } from '../doc-header-footer.command';import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../doc-horizontal-line.command';+import { DocPageSetupCommand } from '../doc-page-setup.command';import { DocParagraphSettingCommand } from '../doc-paragraph-setting.command';import { DocSelectAllCommand } from '../doc-select-all.command';+import { IMEInputCommand } from '../ime-input.command';import { InsertCustomRangeCommand } from '../insert-custom-range.command';-import { AlignCenterCommand, AlignJustifyCommand, AlignOperationCommand } from '../paragraph-align.command';+import {+ AlignCenterCommand,+ AlignJustifyCommand,+ AlignLeftCommand,+ AlignOperationCommand,+ AlignRightCommand,+} from '../paragraph-align.command';import { ReplaceSelectionCommand } from '../replace-content.command';import { SetDocZoomRatioCommand } from '../set-doc-zoom-ratio.command';-import { genEmptyTable } from '../table/table';+import { SwitchDocModeCommand } from '../switch-doc-mode.command';+import { CreateDocTableCommand } from '../table/doc-table-create.command';+import { DocTableInsertRowCommand } from '../table/doc-table-insert.command';+import { DocTableTabCommand } from '../table/doc-table-tab.command';+import { genEmptyTable, genTableSource } from '../table/table';import { createCommandTestBed } from './create-command-test-bed';+class TestSidebarService extends Disposable implements ISidebarService {+ readonly sidebarOptions$ = new Subject<ISidebarMethodOptions>();+ readonly scrollEvent$ = new Subject<Event>();+ private _options: ISidebarMethodOptions = {};+ private _container?: HTMLElement;+ private _width?: number;++ get visible(): boolean {+ return this._options.visible ?? false;+ }++ get options(): ISidebarMethodOptions {+ return this._options;+ }++ get width(): number | undefined {+ return this._width;+ }++ open(params: ISidebarMethodOptions): IDisposable {+ this._options = { ...params, visible: true };+ this.sidebarOptions$.next(this._options);+ return toDisposable(() => this.close());+ }++ close(): void {+ this._options = { ...this._options, visible: false };+ this.sidebarOptions$.next(this._options);+ this._options.onClose?.();+ }++ getContainer(): HTMLElement | undefined {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element;+ }++ setWidth(value: number): void {+ this._width = value;+ }++ override dispose(): void {+ super.dispose();+ this.sidebarOptions$.complete();+ this.scrollEvent$.complete();+ }+}++class TestConfirmService extends Disposable implements IConfirmService<IConfirmPartMethodOptions> {+ readonly confirmOptions$ = new Subject<IConfirmPartMethodOptions[]>();+ readonly closedIds: string[] = [];+ private _options: IConfirmPartMethodOptions[] = [];++ get options(): IConfirmPartMethodOptions[] {+ return this._options;+ }++ get lastOption(): IConfirmPartMethodOptions | undefined {+ return this._options.at(-1);+ }++ open(params: IConfirmPartMethodOptions): IDisposable {+ this._options = [...this._options.filter((option) => option.id !== params.id), { ...params, visible: true }];+ this.confirmOptions$.next(this._options);+ return toDisposable(() => {+ this._options = this._options.filter((option) => option.id !== params.id);+ this.confirmOptions$.next(this._options);+ });+ }++ confirm(params: IConfirmPartMethodOptions): Promise<boolean> {+ this.open(params);+ return Promise.resolve(true);+ }++ close(id: string): void {+ this.closedIds.push(id);+ this._options = this._options.map((option) => option.id === id ? { ...option, visible: false } : option);+ this.confirmOptions$.next(this._options);+ }++ override dispose(): void {+ super.dispose();+ this.confirmOptions$.complete();+ }+}+function createBaseDoc(dataStream = 'Hello world\r\n'): IDocumentData {return {id: 'test-doc',@@ -71,6 +222,108 @@ function createBaseDoc(dataStream = 'Hello world\r\n'): IDocumentData {};}+function useLinearSkeleton(dataStream: string) {+ return {+ findNodeByCharIndex(index: number) {+ const content = dataStream[index];+ if (content == null) {+ return null;+ }++ return {+ content,+ count: 1,+ streamType: content,+ };+ },+ };+}++function createDrawingModeDoc(): IDocumentData {+ const doc = createBaseDoc('A\b\r\n');+ return {+ ...doc,+ body: {+ ...doc.body!,+ customBlocks: [{+ blockId: 'drawing-1',+ startIndex: 1,+ blockType: 'normal',+ }],+ },+ documentStyle: {+ ...doc.documentStyle!,+ documentFlavor: DocumentFlavor.TRADITIONAL,+ },+ drawings: {+ 'drawing-1': {+ drawingId: 'drawing-1',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ positionV: {+ relativeFrom: ObjectRelativeFromV.LINE,+ posOffset: 30,+ },+ },+ },+ },+ drawingsOrder: ['drawing-1'],+ } as unknown as IDocumentData;+}++function createInlineDrawingDoc(): IDocumentData {+ const doc = createBaseDoc('A\bB\r\n');+ return {+ ...doc,+ body: {+ ...doc.body!,+ customBlocks: [{+ blockId: 'drawing-1',+ startIndex: 1,+ blockType: 'normal',+ }],+ },+ drawings: {+ 'drawing-1': {+ drawingId: 'drawing-1',+ layoutType: PositionedObjectLayoutType.INLINE,+ docTransform: {+ positionV: {+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,+ posOffset: 0,+ },+ },+ },+ },+ drawingsOrder: ['drawing-1'],+ } as unknown as IDocumentData;+}++function createCenteredEmptyParagraphDoc(): IDocumentData {+ const doc = createBaseDoc('\r\n');+ return {+ ...doc,+ body: {+ ...doc.body!,+ paragraphs: [{+ paragraphId: 'para_center_empty',+ startIndex: 0,+ paragraphStyle: {+ horizontalAlign: HorizontalAlign.CENTER,+ },+ }],+ },+ };+}++function createHeaderFooterDoc(): IDocumentData {+ return {+ ...createBaseDoc(),+ headers: {},+ footers: {},+ };+}+function createMultiParagraphDoc(): IDocumentData {return {id: 'test-doc',@@ -103,6 +356,31 @@ function createMultiParagraphDoc(): IDocumentData {};}+function createHorizontalLineDoc(): IDocumentData {+ const doc = createMultiParagraphDoc();+ const body = doc.body!;+ return {+ ...doc,+ body: {+ ...body,+ paragraphs: body.paragraphs?.map((paragraph, index) => index === 0+ ? {+ ...paragraph,+ paragraphStyle: {+ ...paragraph.paragraphStyle,+ borderBottom: {+ padding: 5,+ color: { rgb: '#CDD0D8' },+ width: 1,+ dashStyle: DashStyleType.SOLID,+ },+ },+ }+ : paragraph),+ },+ };+}+function createTableDoc(): IDocumentData {const table = genEmptyTable(2, 2);const prefix = 'AB';@@ -154,6 +432,71 @@ function createTableDoc(): IDocumentData {};}+function createTableCommandDoc(rowCount = 2, colCount = 2): IDocumentData {+ const table = genEmptyTable(rowCount, colCount);+ const tableSource = genTableSource(rowCount, colCount, 360);+ const suffix = 'Tail\r\n';+ const dataStream = `${table.dataStream}${suffix}`;++ return {+ id: 'test-doc',+ body: {+ dataStream,+ textRuns: [{+ st: 0,+ ed: dataStream.length - 2,+ ts: {},+ }],+ paragraphs: [+ ...table.paragraphs,+ { paragraphId: 'para_docs_ui_fixture_29', startIndex: dataStream.length - 2 },+ ],+ sectionBreaks: [+ ...table.sectionBreaks,+ {+ startIndex: dataStream.length - 1,+ },+ ],+ tables: [{+ startIndex: 0,+ endIndex: table.dataStream.length,+ tableId: 'table-1',+ }],+ customBlocks: [],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ tableSource: {+ 'table-1': {+ ...tableSource,+ tableId: 'table-1',+ },+ },+ };+}++function createPageFillTableCommandDoc(): IDocumentData {+ const doc = createTableCommandDoc();+ return {+ ...doc,+ documentStyle: {+ ...doc.documentStyle,+ pageSize: {+ width: 540,+ height: 840.51,+ },+ },+ };+}+function createTableDocWithParagraphsBeforeTable(): IDocumentData {const table = genEmptyTable(2, 2);const prefix = 'Title\rBody\r';@@ -207,6 +550,22 @@ function createTableDocWithParagraphsBeforeTable(): IDocumentData {};}+function collectTokenRanges(dataStream: string, startToken: string, endToken: string) {+ const ranges: Array<{ startIndex: number; endIndex: number }> = [];++ for (let i = 0; i < dataStream.length; i++) {+ if (dataStream[i] !== startToken) {+ continue;+ }++ const endIndex = dataStream.indexOf(endToken, i);+ ranges.push({ startIndex: i, endIndex });+ i = endIndex;+ }++ return ranges;+}+describe('misc document commands', () => {let univer: Univer;let get: Injector['get'];@@ -236,6 +595,23 @@ describe('misc document commands', () => {}]);}+ function loadTestLocale() {+ get(LocaleService).load({ [LocaleType.ZH_CN]: {} });+ }++ function useViewModelSkeleton() {+ const skeletonManager = get(DocSkeletonManagerService);+ const viewModel = skeletonManager.getViewModel();+ const mutableSkeletonManager = skeletonManager as unknown as {+ getSkeleton: () => {+ getViewModel: () => typeof viewModel;+ };+ };+ mutableSkeletonManager.getSkeleton = () => ({+ getViewModel: () => viewModel,+ });+ }+afterEach(() => {univer.dispose();});@@ -539,6 +915,252 @@ describe('misc document commands', () => {}));});+ it('removes a horizontal line from the paragraph before the cursor', async () => {+ ({ univer, get } = createCommandTestBed(createHorizontalLineDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(RemoveHorizontalLineCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(6);++ expect(await commandService.executeCommand(RemoveHorizontalLineCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toBeUndefined();+ });++ it('merges adjacent paragraphs through the delete merge command', async () => {+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(MergeTwoParagraphCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(6);++ expect(await commandService.executeCommand(MergeTwoParagraphCommand.id, {+ direction: DeleteDirection.LEFT,+ range: {+ startOffset: 6,+ endOffset: 6,+ collapsed: true,+ segmentId: '',+ style: null,+ },+ })).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('TitleBody\r\n');+ expect(getBody()?.paragraphs).toHaveLength(1);+ });++ it('deletes the current paragraph through rich text editing', async () => {+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteCurrentParagraphCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(2);++ expect(await commandService.executeCommand(DeleteCurrentParagraphCommand.id)).toEqual(expect.objectContaining({+ unitId: 'test-doc',+ textRanges: [expect.objectContaining({+ startOffset: 2,+ endOffset: 2,+ })],+ }));+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('Body\r\n');+ expect(getBody()?.paragraphs?.[0].startIndex).toBe(0);+ });++ it('removes the character before the cursor when Backspace is pressed inside text', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc('ABC\r\n')));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(DeleteTextCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(2);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('ABC\r\n');++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('AC\r\n');+ });++ it('resets a centered empty paragraph before deleting surrounding content', async () => {+ ({ univer, get } = createCommandTestBed(createCenteredEmptyParagraphDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(UpdateTextCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(0);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('\r\n');++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ });++ it('removes a horizontal line when Backspace is pressed after the decorated paragraph break', async () => {+ ({ univer, get } = createCommandTestBed(createHorizontalLineDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(RemoveHorizontalLineCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(6);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('Title\rBody\r\n');++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toBeUndefined();+ });++ it('removes the character after the cursor when Delete is pressed inside text', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc('ABC\r\n')));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteRightCommand);+ commandService.registerCommand(DeleteTextCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(1);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('ABC\r\n');++ expect(await commandService.executeCommand(DeleteRightCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('AC\r\n');+ });++ it('merges with the next paragraph when Delete is pressed on a paragraph break', async () => {+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteRightCommand);+ commandService.registerCommand(MergeTwoParagraphCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(5);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('Title\rBody\r\n');++ expect(await commandService.executeCommand(DeleteRightCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('TitleBody\r\n');+ expect(getBody()?.paragraphs).toHaveLength(1);+ });++ it('cuts the selected content when Backspace is pressed on a non-collapsed text range', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc('ABCD\r\n')));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(CutContentCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(1, 3);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => useLinearSkeleton('ABCD\r\n');++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('AD\r\n');+ });++ it('removes an inline drawing when Backspace is pressed after its object marker', async () => {+ ({ univer, get } = createCommandTestBed(createInlineDrawingDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteLeftCommand);+ commandService.registerCommand(DeleteCustomBlockCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(2);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ skeletonManager.getSkeleton = () => ({+ findNodeByCharIndex(index: number) {+ const content = 'A\bB\r\n'[index];+ if (content == null) {+ return null;+ }++ return {+ content,+ count: 1,+ streamType: content,+ drawingId: content === '\b' ? 'drawing-1' : undefined,+ };+ },+ });++ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('AB\r\n');+ expect(getDoc()?.getSnapshot().drawings?.['drawing-1']).toBeUndefined();+ });++ it('removes an inline drawing block and its drawing record from the document', async () => {+ ({ univer, get } = createCommandTestBed(createInlineDrawingDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DeleteCustomBlockCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(2);++ expect(await commandService.executeCommand(DeleteCustomBlockCommand.id, {+ unitId: 'test-doc',+ drawingId: 'drawing-1',+ direction: DeleteDirection.LEFT,+ range: {+ startOffset: 2,+ endOffset: 2,+ collapsed: true,+ segmentId: '',+ },+ })).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('AB\r\n');+ expect(getDoc()?.getSnapshot().drawings?.['drawing-1']).toBeUndefined();+ expect(getDoc()?.getSnapshot().drawingsOrder).toEqual([]);+ });++ it('keeps the cursor near the deleted table area when table selections are cut', () => {+ expect(getCursorWhenDelete(null, [{+ startOffset: 20,+ endOffset: 30,+ collapsed: false,+ startRow: 0,+ startColumn: 0,+ endRow: 2,+ endColumn: 2,+ tableId: 'table-1',+ spanEntireRow: false,+ spanEntireColumn: false,+ spanEntireTable: true,+ }])).toBe(17);++ expect(getCursorWhenDelete([{ startOffset: 30, endOffset: 34, collapsed: false }], [{+ startOffset: 20,+ endOffset: 26,+ collapsed: false,+ startRow: 1,+ startColumn: 0,+ endRow: 1,+ endColumn: 2,+ tableId: 'table-1',+ spanEntireRow: true,+ spanEntireColumn: false,+ spanEntireTable: false,+ }])).toBe(14);+ });+it('aligns selected paragraphs through the wrapper and toggles an existing alignment', async () => {({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));commandService = get(ICommandService);@@ -568,10 +1190,33 @@ describe('misc document commands', () => {expect(getBody()?.paragraphs?.[1].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.JUSTIFIED);});- it('updates the current document zoom ratio through the command and operation chain', async () => {- ({ univer, get } = createCommandTestBed(createBaseDoc()));+ it('aligns selected paragraphs through left and right wrappers', async () => {+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));commandService = get(ICommandService);- commandService.registerCommand(SetDocZoomRatioCommand);+ commandService.registerCommand(AlignOperationCommand);+ commandService.registerCommand(AlignLeftCommand);+ commandService.registerCommand(AlignRightCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(0, 10);++ await commandService.executeCommand(AlignRightCommand.id);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.RIGHT);+ expect(getBody()?.paragraphs?.[1].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.RIGHT);++ await commandService.executeCommand(AlignLeftCommand.id);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ expect(getBody()?.paragraphs?.[1].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.LEFT);+ });++ it('updates the current document zoom ratio through the command and operation chain', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(SetDocZoomRatioCommand);commandService.registerCommand(SetDocZoomRatioOperation);expect((getDoc()?.getSnapshot().settings?.zoomRatio) ?? 1).toBe(1);@@ -587,6 +1232,778 @@ describe('misc document commands', () => {})).toBe(false);});+ it('updates document page setup through the real rich text mutation flow', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocPageSetupCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const result = await commandService.executeCommand(DocPageSetupCommand.id, {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: PAGE_SIZE[PaperType.A3],+ pageOrient: PageOrientType.LANDSCAPE,+ marginTop: 36,+ marginBottom: 42,+ marginLeft: 48,+ marginRight: 54,+ });+ await awaitTime(0);++ expect(result).toBe(true);+ expect(getDoc()?.getDocumentStyle()).toEqual(expect.objectContaining({+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: PAGE_SIZE[PaperType.A3],+ pageOrient: PageOrientType.LANDSCAPE,+ marginTop: 36,+ marginBottom: 42,+ marginLeft: 48,+ marginRight: 54,+ }));+ });++ it('resizes page-fill tables when page content width changes', async () => {+ ({ univer, get } = createCommandTestBed(createPageFillTableCommandDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocPageSetupCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const result = await commandService.executeCommand(DocPageSetupCommand.id, {+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: { width: 640, height: 840.51 },+ pageOrient: PageOrientType.PORTRAIT,+ marginTop: 72,+ marginBottom: 72,+ marginLeft: 90,+ marginRight: 90,+ });+ await awaitTime(0);++ const table = getDoc()?.getSnapshot().tableSource?.['table-1'];+ expect(result).toBe(true);+ expect(table?.size.width.v).toBe(460);+ expect(table?.tableColumns.map((column) => column.size.width.v)).toEqual([230, 230]);+ });++ it('inserts page setup values when the document has no explicit page style', async () => {+ const doc = createBaseDoc();+ doc.documentStyle = {};+ ({ univer, get } = createCommandTestBed(doc));+ commandService = get(ICommandService);+ commandService.registerCommand(DocPageSetupCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ expect(await commandService.executeCommand(DocPageSetupCommand.id, {+ documentFlavor: DocumentFlavor.MODERN,+ pageSize: PAGE_SIZE[PaperType.A4],+ pageOrient: PageOrientType.PORTRAIT,+ marginTop: 12,+ marginBottom: 18,+ marginLeft: 24,+ marginRight: 30,+ })).toBe(true);+ await awaitTime(0);++ expect(getDoc()?.getDocumentStyle()).toEqual(expect.objectContaining({+ documentFlavor: DocumentFlavor.MODERN,+ pageSize: PAGE_SIZE[PaperType.A4],+ pageOrient: PageOrientType.PORTRAIT,+ marginTop: 12,+ marginBottom: 18,+ marginLeft: 24,+ marginRight: 30,+ }));+ });++ it('opens page settings and applies confirmed document setup', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [IConfirmService, { useClass: TestConfirmService }],+ ]));+ loadTestLocale();+ commandService = get(ICommandService);+ commandService.registerCommand(DocOpenPageSettingCommand);+ commandService.registerCommand(DocPageSetupCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const result = await commandService.executeCommand(DocOpenPageSettingCommand.id);+ const confirmService = get(IConfirmService) as TestConfirmService;++ expect(result).toBe(true);+ expect(confirmService.lastOption).toEqual(expect.objectContaining({+ id: PAGE_SETTING_COMPONENT_ID,+ width: 528,+ confirmText: expect.any(String),+ cancelText: expect.any(String),+ }));+ expect(confirmService.lastOption?.children).toEqual({+ label: PAGE_SETTING_COMPONENT_ID,+ });++ confirmService.lastOption?.onConfirm?.({+ mode: DocumentFlavor.TRADITIONAL,+ paperSize: PaperType.A5,+ orientation: PageOrientType.PORTRAIT,+ margins: {+ top: 18,+ bottom: 24,+ left: 30,+ right: 36,+ },+ });+ await awaitTime(0);++ expect(confirmService.options).toEqual([]);+ expect(getDoc()?.getDocumentStyle()).toEqual(expect.objectContaining({+ documentFlavor: DocumentFlavor.TRADITIONAL,+ pageSize: PAGE_SIZE[PaperType.A5],+ pageOrient: PageOrientType.PORTRAIT,+ marginTop: 18,+ marginBottom: 24,+ marginLeft: 30,+ marginRight: 36,+ }));+ });++ it('closes page settings without applying document setup', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [IConfirmService, { useClass: TestConfirmService }],+ ]));+ loadTestLocale();+ commandService = get(ICommandService);+ commandService.registerCommand(DocOpenPageSettingCommand);++ expect(await commandService.executeCommand(DocOpenPageSettingCommand.id)).toBe(true);+ const confirmService = get(IConfirmService) as TestConfirmService;+ confirmService.lastOption?.onClose?.();++ expect(confirmService.options).toEqual([]);+ expect(getDoc()?.getDocumentStyle().pageSize).toEqual({+ width: 594.3,+ height: 840.51,+ });+ });++ it('creates header and footer records while updating header footer margins', async () => {+ ({ univer, get } = createCommandTestBed(createHeaderFooterDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(CoreHeaderFooterCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const result = await commandService.executeCommand(CoreHeaderFooterCommand.id, {+ unitId: 'test-doc',+ segmentId: 'header-segment-1',+ createType: HeaderFooterType.DEFAULT_HEADER,+ headerFooterProps: {+ marginHeader: 30,+ marginFooter: 40,+ useFirstPageHeaderFooter: BooleanNumber.TRUE,+ },+ });+ await awaitTime(0);++ const snapshot = getDoc()?.getSnapshot();+ expect(result).toBe(true);+ expect(snapshot?.documentStyle).toEqual(expect.objectContaining({+ defaultHeaderId: 'header-segment-1',+ marginHeader: 30,+ marginFooter: 40,+ useFirstPageHeaderFooter: BooleanNumber.TRUE,+ }));+ expect(snapshot?.headers?.['header-segment-1'].body?.dataStream).toBe('\r\n');+ expect(snapshot?.documentStyle.defaultFooterId).toEqual(expect.any(String));+ });++ it('creates footer pairs when a footer segment is requested', async () => {+ ({ univer, get } = createCommandTestBed(createHeaderFooterDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(CoreHeaderFooterCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ expect(await commandService.executeCommand(CoreHeaderFooterCommand.id, {+ unitId: 'test-doc',+ segmentId: 'footer-segment-1',+ createType: HeaderFooterType.DEFAULT_FOOTER,+ })).toBe(true);+ await awaitTime(0);++ const snapshot = getDoc()?.getSnapshot();+ expect(snapshot?.documentStyle.defaultFooterId).toBe('footer-segment-1');+ expect(snapshot?.documentStyle.defaultHeaderId).toEqual(expect.any(String));+ expect(snapshot?.footers?.['footer-segment-1'].body?.dataStream).toBe('\r\n');+ });++ it('creates even page footer records when header footer options require them', async () => {+ ({ univer, get } = createCommandTestBed(createHeaderFooterDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(CoreHeaderFooterCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ expect(await commandService.executeCommand(CoreHeaderFooterCommand.id, {+ unitId: 'test-doc',+ segmentId: 'even-footer-segment-1',+ headerFooterProps: {+ evenAndOddHeaders: BooleanNumber.TRUE,+ },+ })).toBe(true);+ await awaitTime(0);++ const snapshot = getDoc()?.getSnapshot();+ expect(snapshot?.documentStyle.evenPageFooterId).toBe('even-footer-segment-1');+ expect(snapshot?.documentStyle.evenPageHeaderId).toEqual(expect.any(String));+ expect(snapshot?.footers?.['even-footer-segment-1'].body?.dataStream).toBe('\r\n');+ });++ it('replaces existing first-page header and footer links when the section header is recreated', async () => {+ const doc = createHeaderFooterDoc();+ doc.documentStyle = {+ ...doc.documentStyle!,+ firstPageHeaderId: 'old-first-header',+ firstPageFooterId: 'old-first-footer',+ };+ doc.headers = {+ 'old-first-header': {+ headerId: 'old-first-header',+ body: { dataStream: '\r\n' },+ },+ };+ doc.footers = {+ 'old-first-footer': {+ footerId: 'old-first-footer',+ body: { dataStream: '\r\n' },+ },+ };+ ({ univer, get } = createCommandTestBed(doc));+ commandService = get(ICommandService);+ commandService.registerCommand(CoreHeaderFooterCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ expect(await commandService.executeCommand(CoreHeaderFooterCommand.id, {+ unitId: 'test-doc',+ segmentId: 'new-first-header',+ createType: HeaderFooterType.FIRST_PAGE_HEADER,+ })).toBe(true);+ await awaitTime(0);++ const snapshot = getDoc()?.getSnapshot();+ expect(snapshot?.documentStyle.firstPageHeaderId).toBe('new-first-header');+ expect(snapshot?.documentStyle.firstPageFooterId).not.toBe('old-first-footer');+ expect(snapshot?.headers?.['new-first-header'].body?.textRuns?.[0].ts?.fs).toBe(9);+ });++ it('does not create header footer history when submitted settings match the document', async () => {+ const doc = createHeaderFooterDoc();+ doc.documentStyle = {+ ...doc.documentStyle!,+ marginHeader: 30,+ };+ ({ univer, get } = createCommandTestBed(doc));+ commandService = get(ICommandService);+ commandService.registerCommand(CoreHeaderFooterCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ expect(await commandService.executeCommand(CoreHeaderFooterCommand.id, {+ unitId: 'test-doc',+ headerFooterProps: {+ marginHeader: 30,+ },+ })).toBe(false);+ });++ it('closes header footer editing and restores a body cursor', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [ISidebarService, { useClass: TestSidebarService }],+ ]));+ commandService = get(ICommandService);+ commandService.registerCommand(CloseHeaderFooterCommand);+ commandService.registerCommand(SidebarDocHeaderFooterPanelOperation);+ const sidebarService = get(ISidebarService) as TestSidebarService;+ sidebarService.open({ visible: true });++ const render = get(IRenderManagerService).getRenderById('test-doc')!;+ let clearedSelectedObjects = false;+ let markedDirty = false;+ const mutableRender = render as unknown as {+ scene: { getTransformerByCreate?: () => { clearSelectedObjects: () => void } };+ mainComponent: unknown;+ with: (dependency: unknown) => unknown;+ };+ mutableRender.scene.getTransformerByCreate = () => ({+ clearSelectedObjects: () => {+ clearedSelectedObjects = true;+ },+ });+ mutableRender.mainComponent = {+ makeDirty: (dirty: boolean) => {+ markedDirty = dirty;+ },+ };++ const skeletonManager = get(DocSkeletonManagerService) as unknown as {+ getSkeleton: () => unknown;+ getViewModel: () => { getEditArea: () => DocumentEditArea; setEditArea: (area: DocumentEditArea) => void };+ };+ let recalculated = false;+ skeletonManager.getSkeleton = () => ({+ calculate: () => {+ recalculated = true;+ },+ });+ skeletonManager.getViewModel().setEditArea(DocumentEditArea.HEADER);++ let segment = 'header-1';+ let segmentPage = 2;+ const selectionRenderService = {+ setSegment: (nextSegment: string) => {+ segment = nextSegment;+ },+ getSegment: () => segment,+ setSegmentPage: (nextSegmentPage: number) => {+ segmentPage = nextSegmentPage;+ },+ getSegmentPage: () => segmentPage,+ };+ const originalWith = mutableRender.with.bind(mutableRender);+ mutableRender.with = (dependency: unknown) => {+ if (dependency === DocSkeletonManagerService) {+ return skeletonManager;+ }+ if (dependency === DocSelectionRenderService) {+ return selectionRenderService;+ }+ return originalWith(dependency);+ };+ const selectionManager = get(DocSelectionManagerService);+ let latestSelectionRefresh: unknown;+ const subscription = selectionManager.refreshSelection$.subscribe((refresh) => {+ latestSelectionRefresh = refresh;+ });++ expect(await commandService.executeCommand(CloseHeaderFooterCommand.id, { unitId: 'test-doc' })).toBe(true);+ await awaitTime(0);++ expect(clearedSelectedObjects).toBe(true);+ expect(recalculated).toBe(true);+ expect(markedDirty).toBe(true);+ expect(selectionRenderService.getSegment()).toBe('');+ expect(selectionRenderService.getSegmentPage()).toBe(-1);+ expect(skeletonManager.getViewModel().getEditArea()).toBe(DocumentEditArea.BODY);+ expect(latestSelectionRefresh).toEqual(expect.objectContaining({+ docRanges: [expect.objectContaining({ startOffset: 0, endOffset: 0 })],+ }));+ expect(sidebarService.visible).toBe(false);+ subscription.unsubscribe();+ });++ it('opens and closes the header footer sidebar panel through commands and operations', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [ISidebarService, { useClass: TestSidebarService }],+ ]));+ loadTestLocale();+ commandService = get(ICommandService);+ commandService.registerCommand(OpenHeaderFooterPanelCommand);+ commandService.registerCommand(SidebarDocHeaderFooterPanelOperation);++ const sidebarService = get(ISidebarService) as TestSidebarService;++ expect(await commandService.executeCommand(OpenHeaderFooterPanelCommand.id)).toBe(true);+ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options).toEqual(expect.objectContaining({+ width: 400,+ children: { label: COMPONENT_DOC_HEADER_FOOTER_PANEL },+ }));++ expect(await commandService.executeCommand(SidebarDocHeaderFooterPanelOperation.id, { value: 'close' })).toBe(true);+ expect(sidebarService.visible).toBe(false);+ });++ it('opens the paragraph setting panel through its controller-backed operation', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [ISidebarService, { useClass: TestSidebarService }],+ [DocParagraphSettingController],+ ]));+ commandService = get(ICommandService);+ commandService.registerCommand(DocParagraphSettingPanelOperation);++ const result = await commandService.executeCommand(DocParagraphSettingPanelOperation.id);+ const sidebarService = get(ISidebarService) as TestSidebarService;++ expect(result).toBe(true);+ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options).toEqual(expect.objectContaining({+ id: undefined,+ width: 300,+ children: { label: 'doc_ui_paragraph-setting-panel' },+ }));+ });++ it('switches document mode by executing the command against the current document', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(SwitchDocModeCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(1);++ const render = get(IRenderManagerService).getRenderById('test-doc')!;+ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ const selectionRenderService = {+ getSegment: () => '',+ getSegmentPage: () => -1,+ };+ const mutableRender = render as unknown as { with: (dependency: unknown) => unknown };+ const originalWith = mutableRender.with.bind(mutableRender);+ mutableRender.with = (dependency: unknown) => {+ if (dependency === DocSkeletonManagerService) {+ skeletonManager.getSkeleton = () => ({}) as never;+ return skeletonManager;+ }+ if (dependency === DocSelectionRenderService) {+ return selectionRenderService;+ }+ return originalWith(dependency);+ };++ expect(await commandService.executeCommand(SwitchDocModeCommand.id)).toBe(true);+ await awaitTime(0);+ expect(getDoc()?.getDocumentStyle().documentFlavor).toBe(DocumentFlavor.MODERN);++ expect(await commandService.executeCommand(SwitchDocModeCommand.id)).toBe(true);+ await awaitTime(0);+ expect(getDoc()?.getDocumentStyle().documentFlavor).toBe(DocumentFlavor.TRADITIONAL);+ });++ it('converts body drawings to paragraph-relative vertical positions when switching from traditional mode', async () => {+ ({ univer, get } = createCommandTestBed(createDrawingModeDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(SwitchDocModeCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ setCollapsedSelection(1);++ const render = get(IRenderManagerService).getRenderById('test-doc')!;+ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };+ const line = {+ top: 10,+ paragraphIndex: 0,+ parent: undefined as unknown,+ };+ const column = {+ lines: [{+ paragraphIndex: 0,+ paragraphStart: true,+ top: 2,+ }],+ parent: {+ parent: {+ marginTop: 50,+ },+ },+ };+ line.parent = column;+ skeletonManager.getSkeleton = () => ({+ findNodeByCharIndex: () => ({+ parent: {+ parent: line,+ },+ }),+ });+ const selectionRenderService = {+ getSegment: () => '',+ getSegmentPage: () => -1,+ };+ const mutableRender = render as unknown as { with: (dependency: unknown) => unknown };+ const originalWith = mutableRender.with.bind(mutableRender);+ mutableRender.with = (dependency: unknown) => {+ if (dependency === DocSkeletonManagerService) {+ return skeletonManager;+ }+ if (dependency === DocSelectionRenderService) {+ return selectionRenderService;+ }+ return originalWith(dependency);+ };++ expect(await commandService.executeCommand(SwitchDocModeCommand.id)).toBe(true);+ await awaitTime(0);++ const drawingPosition = getDoc()?.getSnapshot().drawings?.['drawing-1'].docTransform.positionV;+ expect(getDoc()?.getDocumentStyle().documentFlavor).toBe(DocumentFlavor.MODERN);+ expect(drawingPosition).toEqual(expect.objectContaining({+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,+ posOffset: 38,+ }));+ });++ it('does not switch document mode when command skeleton is unavailable', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(SwitchDocModeCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => undefined };+ skeletonManager.getSkeleton = () => undefined;+ const render = get(IRenderManagerService).getRenderById('test-doc');+ const mutableRender = render as unknown as { with: (dependency: unknown) => unknown };+ const originalWith = mutableRender.with.bind(mutableRender);+ mutableRender.with = (dependency: unknown) => {+ if (dependency === DocSelectionRenderService) {+ return undefined;+ }+ return originalWith(dependency);+ };++ expect(await commandService.executeCommand(SwitchDocModeCommand.id)).toBe(false);+ expect(getDoc()?.getDocumentStyle().documentFlavor).toBeUndefined();+ });++ it('reports cursor operations only when movement params are provided', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(MoveCursorOperation);+ commandService.registerCommand(MoveSelectionOperation);++ expect(await commandService.executeCommand(MoveCursorOperation.id, {+ direction: Direction.RIGHT,+ granularity: 'word',+ })).toBe(true);+ expect(await commandService.executeCommand(MoveSelectionOperation.id, {+ direction: Direction.LEFT,+ granularity: 'line',+ })).toBe(true);+ expect(await commandService.executeCommand(MoveCursorOperation.id)).toBe(false);+ expect(await commandService.executeCommand(MoveSelectionOperation.id)).toBe(false);+ });++ it('inserts IME composition text at the cached active range', async () => {+ const doc = createBaseDoc('AB\r\n');+ doc.body!.customDecorations = [{+ startIndex: 0,+ endIndex: 1,+ id: 'mention-1',+ type: CustomRangeType.MENTION,+ properties: {},+ }] as never;+ ({ univer, get } = createCommandTestBed(doc));+ commandService = get(ICommandService);+ commandService.registerCommand(IMEInputCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const imeInputManagerService = get(DocIMEInputManagerService);+ imeInputManagerService.setActiveRange({+ startOffset: 1,+ endOffset: 1,+ collapsed: true,+ segmentId: '',+ });++ expect(await commandService.executeCommand(IMEInputCommand.id, {+ unitId: 'test-doc',+ newText: '你',+ oldTextLen: 0,+ isCompositionStart: false,+ isCompositionEnd: true,+ })).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('A你B\r\n');+ expect(getBody()?.customDecorations?.[0]).toEqual(expect.objectContaining({+ startIndex: 0,+ endIndex: 2,+ }));+ const cache = imeInputManagerService.getUndoRedoMutationParamsCache();+ expect(cache.undoCache).toHaveLength(1);+ expect(cache.redoCache[0].isCompositionEnd).toBe(true);+ });++ it('replaces selected text when IME composition starts with a non-collapsed range', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc('Hello\r\n')));+ commandService = get(ICommandService);+ commandService.registerCommand(IMEInputCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ get(DocIMEInputManagerService).setActiveRange({+ startOffset: 1,+ endOffset: 4,+ collapsed: false,+ segmentId: '',+ });++ expect(await commandService.executeCommand(IMEInputCommand.id, {+ unitId: 'test-doc',+ newText: '你',+ oldTextLen: 0,+ isCompositionStart: true,+ isCompositionEnd: false,+ })).toBe(true);+ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('H你o\r\n');+ expect(get(DocIMEInputManagerService).getUndoRedoMutationParamsCache().redoCache[0].noHistory).toBe(true);+ });++ it('opens the create-table confirm flow and forwards the confirmed size to the table command', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [IConfirmService, { useClass: TestConfirmService }],+ ]));+ loadTestLocale();+ commandService = get(ICommandService);+ const createdTables: Array<{ rowCount: number; colCount: number }> = [];+ commandService.registerCommand(DocCreateTableOperation);+ commandService.registerCommand({+ id: CreateDocTableCommand.id,+ type: CommandType.COMMAND,+ handler: (_accessor, params: { rowCount: number; colCount: number }) => {+ createdTables.push(params);+ return true;+ },+ });++ const result = await commandService.executeCommand(DocCreateTableOperation.id);+ const confirmService = get(IConfirmService) as TestConfirmService;+ const children = confirmService.lastOption?.children as {+ label: {+ name: string;+ props: {+ handleRowColChange: (rowCount: number, colCount: number) => void;+ tableCreateParams: { rowCount: number; colCount: number };+ };+ };+ };++ expect(result).toBe(true);+ expect(confirmService.lastOption).toEqual(expect.objectContaining({+ id: 'doc.component.create-table-confirm',+ width: 'auto',+ }));+ expect(children.label.name).toBe(COMPONENT_DOC_CREATE_TABLE_CONFIRM);+ expect(children.label.props.tableCreateParams).toEqual({+ rowCount: 3,+ colCount: 5,+ });++ children.label.props.handleRowColChange(4, 2);+ expect(children.label.props.tableCreateParams).toEqual({+ rowCount: 4,+ colCount: 2,+ });++ confirmService.lastOption?.onConfirm?.({});+ await awaitTime(0);++ expect(createdTables).toEqual([{+ rowCount: 4,+ colCount: 2,+ }]);+ expect(confirmService.closedIds).toContain('doc.component.create-table-confirm');+ });++ it('closes the create-table confirm flow without creating a table', async () => {+ ({ univer, get } = createCommandTestBed(createBaseDoc(), [+ [IConfirmService, { useClass: TestConfirmService }],+ ]));+ loadTestLocale();+ commandService = get(ICommandService);+ const createdTables: Array<{ rowCount: number; colCount: number }> = [];+ commandService.registerCommand(DocCreateTableOperation);+ commandService.registerCommand({+ id: CreateDocTableCommand.id,+ type: CommandType.COMMAND,+ handler: (_accessor, params: { rowCount: number; colCount: number }) => {+ createdTables.push(params);+ return true;+ },+ });++ expect(await commandService.executeCommand(DocCreateTableOperation.id)).toBe(true);+ const confirmService = get(IConfirmService) as TestConfirmService;+ confirmService.lastOption?.onClose?.();++ expect(createdTables).toEqual([]);+ expect(confirmService.closedIds).toContain('doc.component.create-table-confirm');+ });++ it('moves table tab selection to the next cell', async () => {+ ({ univer, get } = createCommandTestBed(createTableCommandDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocTableTabCommand);+ useViewModelSkeleton();++ const cellRanges = collectTokenRanges(+ getBody()?.dataStream ?? '',+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END+ );+ setCollapsedSelection(cellRanges[0].startIndex + 1);+ const selectionManager = get(DocSelectionManagerService);+ const refreshEvents: Array<unknown> = [];+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {+ if (event) {+ refreshEvents.push(event);+ }+ });++ expect(await commandService.executeCommand(DocTableTabCommand.id, { shift: false })).toBe(true);++ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({+ docRanges: [expect.objectContaining({+ startOffset: cellRanges[1].startIndex + 1,+ endOffset: cellRanges[1].endIndex - 2,+ })],+ }));++ subscription.unsubscribe();+ });++ it('moves table tab selection to the previous cell when shift is held', async () => {+ ({ univer, get } = createCommandTestBed(createTableCommandDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocTableTabCommand);+ useViewModelSkeleton();++ const cellRanges = collectTokenRanges(+ getBody()?.dataStream ?? '',+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END+ );+ setCollapsedSelection(cellRanges[2].startIndex + 1);+ const selectionManager = get(DocSelectionManagerService);+ const refreshEvents: Array<unknown> = [];+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {+ if (event) {+ refreshEvents.push(event);+ }+ });++ expect(await commandService.executeCommand(DocTableTabCommand.id, { shift: true })).toBe(true);++ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({+ docRanges: [expect.objectContaining({+ startOffset: cellRanges[1].startIndex + 1,+ endOffset: cellRanges[1].endIndex - 2,+ })],+ }));++ subscription.unsubscribe();+ });++ it('inserts a row when tab is pressed in the last table cell', async () => {+ ({ univer, get } = createCommandTestBed(createTableCommandDoc()));+ commandService = get(ICommandService);+ commandService.registerCommand(DocTableTabCommand);+ commandService.registerCommand(DocTableInsertRowCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ useViewModelSkeleton();++ const cellRanges = collectTokenRanges(+ getBody()?.dataStream ?? '',+ DataStreamTreeTokenType.TABLE_CELL_START,+ DataStreamTreeTokenType.TABLE_CELL_END+ );+ setCollapsedSelection(cellRanges[3].startIndex + 1);++ expect(await commandService.executeCommand(DocTableTabCommand.id, { shift: false })).toBe(true);+ await awaitTime(0);++ expect(getDoc()?.getSnapshot().tableSource?.['table-1'].tableRows).toHaveLength(3);+ });+it('runs registered auto-format mutations for tab, after-space, and enter commands', async () => {({ univer, get } = createCommandTestBed(createBaseDoc()));univer.__getInjector().add([DocAutoFormatService]);diff --git a/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.tsindex c96b138a0c..ff00f1a9e1 100644--- a/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/replace-content.command.spec.ts@@ -18,7 +18,13 @@ import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } froimport { ICommandService, IUniverInstanceService, RedoCommand, UndoCommand, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { CoverContentCommand, ReplaceContentCommand } from '../replace-content.command';+import {+ CoverContentCommand,+ ReplaceContentCommand,+ ReplaceSelectionCommand,+ ReplaceSnapshotCommand,+ ReplaceTextRunsCommand,+} from '../replace-content.command';import { createCommandTestBed } from './create-command-test-bed';function getDocumentData() {@@ -64,6 +70,9 @@ describe('replace or cover content of document', () => {commandService = get(ICommandService);commandService.registerCommand(ReplaceContentCommand);commandService.registerCommand(CoverContentCommand);+ commandService.registerCommand(ReplaceSelectionCommand);+ commandService.registerCommand(ReplaceSnapshotCommand);+ commandService.registerCommand(ReplaceTextRunsCommand);commandService.registerCommand(SetTextSelectionsOperation);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);@@ -140,4 +149,161 @@ describe('replace or cover content of document', () => {expect(getDataStream().length).toBe(17);});});++ describe('replace selected document content', () => {+ it('replaces the document snapshot including style and table metadata', async () => {+ const tableSource = {+ table_1: {+ tableId: 'table_1',+ tableRows: [],+ tableColumns: [],+ },+ };+ const nextSnapshot = {+ ...getDocumentData(),+ body: {+ dataStream: 'Snapshot\r\n',+ textRuns: [{+ st: 0,+ ed: 8,+ ts: {+ fs: 16,+ },+ }],+ paragraphs: [{ paragraphId: 'para_replace_snapshot', startIndex: 8 }],+ sectionBreaks: [{ startIndex: 9 }],+ customBlocks: [],+ },+ documentStyle: {+ pageSize: {+ width: 500,+ height: 700,+ },+ marginTop: 20,+ marginBottom: 20,+ marginRight: 30,+ marginLeft: 30,+ },+ tableSource,+ lists: {+ list_1: {+ listType: 'BULLET_LIST',+ nestingLevel: [],+ },+ },+ drawings: {},+ drawingsOrder: [],+ headers: {},+ footers: {},+ } as never;++ await expect(commandService.executeCommand(ReplaceSnapshotCommand.id, {+ unitId: 'test-doc',+ snapshot: nextSnapshot,+ textRanges: [{+ startOffset: 8,+ endOffset: 8,+ collapsed: true,+ }],+ options: {+ noHistory: true,+ },+ })).resolves.toBe(true);++ const univerInstanceService = get(IUniverInstanceService);+ const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);+ expect(docsModel?.getBody()?.dataStream).toBe('Snapshot\r\n');+ expect(docsModel?.getDocumentStyle().pageSize).toEqual({ width: 500, height: 700 });+ expect(docsModel?.getSnapshot().tableSource).toEqual(tableSource);+ });++ it('updates only the selection when the replacement snapshot body is unchanged', async () => {+ await expect(commandService.executeCommand(ReplaceSnapshotCommand.id, {+ unitId: 'test-doc',+ snapshot: getDocumentData(),+ textRanges: [{+ startOffset: 1,+ endOffset: 4,+ collapsed: false,+ }],+ options: {},+ })).resolves.toBe(true);++ expect(getDataStream()).toBe('=SUM(A2:B4)\r\n');+ });++ it('replaces the active selection through the real rich text mutation flow', async () => {+ univer.dispose();+ const testBed = createCommandTestBed(getDocumentData());+ univer = testBed.univer;+ get = testBed.get;+ commandService = get(ICommandService);+ commandService.registerCommand(ReplaceSelectionCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: 'test-doc',+ subUnitId: '',+ });+ selectionManager.__TEST_ONLY_add([+ {+ startOffset: 1,+ endOffset: 4,+ collapsed: false,+ },+ ]);++ const result = await commandService.executeCommand(ReplaceSelectionCommand.id, {+ unitId: 'test-doc',+ selection: {+ startOffset: 1,+ endOffset: 4,+ collapsed: false,+ },+ body: {+ dataStream: 'AVG',+ },+ textRanges: [{+ startOffset: 4,+ endOffset: 4,+ collapsed: true,+ }],+ });++ expect(result).toBeTruthy();+ expect(getDataStream()).toBe('=AVG(A2:B4)\r\n');+ });++ it('replaces text runs without adding undo history', async () => {+ await expect(commandService.executeCommand(ReplaceTextRunsCommand.id, {+ unitId: 'test-doc',+ body: {+ dataStream: '=COUNT(A1:A2)',+ textRuns: [{+ st: 0,+ ed: 13,+ ts: {+ fs: 18,+ },+ }],+ },+ textRanges: [{+ startOffset: 13,+ endOffset: 13,+ collapsed: true,+ }],+ segmentId: '',+ options: {},+ })).resolves.toBe(true);++ const univerInstanceService = get(IUniverInstanceService);+ const docsModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);+ const textRuns = docsModel?.getBody()?.textRuns ?? [];+ expect(textRuns[0].st).toBe(0);+ expect(textRuns.at(-1)?.ed).toBe(13);+ expect(textRuns.every((textRun) => textRun.ts?.fs === 18)).toBe(true);+ });+ });});diff --git a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.tsindex 1c513371e3..1849cfd377 100644--- a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts+++ b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts@@ -16,9 +16,25 @@import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';import { awaitTime, ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';-import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';+import {+ DocContentInsertService,+ DocSelectionManagerService,+ RichTextEditingMutation,+ SetTextSelectionsOperation,+} from '@univerjs/docs';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { H1HeadingCommand, QuickHeadingCommand, SetParagraphNamedStyleCommand } from '../set-heading.command';+import {+ H1HeadingCommand,+ H2HeadingCommand,+ H3HeadingCommand,+ H4HeadingCommand,+ H5HeadingCommand,+ NormalTextHeadingCommand,+ QuickHeadingCommand,+ SetParagraphNamedStyleCommand,+ SubtitleHeadingCommand,+ TitleHeadingCommand,+} from '../set-heading.command';import { createCommandTestBed } from './create-command-test-bed';function getHeadingDocumentData(): IDocumentData {@@ -79,6 +95,13 @@ describe('set heading commands', () => {commandService = get(ICommandService);commandService.registerCommand(SetParagraphNamedStyleCommand);commandService.registerCommand(H1HeadingCommand);+ commandService.registerCommand(H2HeadingCommand);+ commandService.registerCommand(H3HeadingCommand);+ commandService.registerCommand(H4HeadingCommand);+ commandService.registerCommand(H5HeadingCommand);+ commandService.registerCommand(NormalTextHeadingCommand);+ commandService.registerCommand(TitleHeadingCommand);+ commandService.registerCommand(SubtitleHeadingCommand);commandService.registerCommand(QuickHeadingCommand);commandService.registerCommand(SetTextSelectionsOperation);commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);@@ -101,7 +124,66 @@ describe('set heading commands', () => {await awaitTime(0);expect(getBody()?.paragraphs?.[0].paragraphStyle?.namedStyleType).toBe(NamedStyleType.HEADING_1);- expect(getBody()?.paragraphs?.[0].paragraphStyle?.headingId).toBeDefined();+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.headingId?.length).toBe(6);+ });++ it('applies heading levels and document title styles through public commands', async () => {+ const selectionManager = get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_add([{ startOffset: 0, endOffset: 7, collapsed: false, isActive: true, segmentId: '', style: null as never }]);++ const headingCases = [+ { commandId: H2HeadingCommand.id, namedStyleType: NamedStyleType.HEADING_2 },+ { commandId: H3HeadingCommand.id, namedStyleType: NamedStyleType.HEADING_3 },+ { commandId: H4HeadingCommand.id, namedStyleType: NamedStyleType.HEADING_4 },+ { commandId: H5HeadingCommand.id, namedStyleType: NamedStyleType.HEADING_5 },+ { commandId: TitleHeadingCommand.id, namedStyleType: NamedStyleType.TITLE },+ { commandId: SubtitleHeadingCommand.id, namedStyleType: NamedStyleType.SUBTITLE },+ ];++ for (const { commandId, namedStyleType } of headingCases) {+ await commandService.executeCommand(commandId);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle?.namedStyleType).toBe(namedStyleType);+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.headingId?.length).toBe(6);+ }++ await commandService.executeCommand(NormalTextHeadingCommand.id);+ await awaitTime(0);++ expect(getBody()?.paragraphs?.[0].paragraphStyle).toEqual({+ namedStyleType: NamedStyleType.NORMAL_TEXT,+ });+ });++ it('inserts a styled paragraph when paragraph menu provides an insert range', async () => {+ univer.dispose();++ const testBed = createCommandTestBed(getHeadingDocumentData(), [[DocContentInsertService]]);+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ commandService.registerCommand(SetParagraphNamedStyleCommand);+ commandService.registerCommand(SetTextSelectionsOperation);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const contentInsertService = get(DocContentInsertService);+ contentInsertService.setInsertRange({+ unitId: 'test-doc',+ startOffset: 7,+ endOffset: 7,+ });++ await commandService.executeCommand(SetParagraphNamedStyleCommand.id, {+ value: NamedStyleType.TITLE,+ });++ await awaitTime(0);++ expect(getBody()?.dataStream).toBe('Heading\r\r\n');+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.namedStyleType).toBe(NamedStyleType.TITLE);+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.headingId?.length).toBe(6);});it('converts markdown-like quick headings through the real command chain', async () => {diff --git a/packages/docs-ui/src/facade/__tests__/f-document.spec.ts b/packages/docs-ui/src/facade/__tests__/f-document.spec.tsnew file mode 100644index 0000000000..a889ddcc89--- /dev/null+++ b/packages/docs-ui/src/facade/__tests__/f-document.spec.ts@@ -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 type { IDocumentData, UnitModel } from '@univerjs/core';+import {+ DisposableCollection,+ DOC_RANGE_TYPE,+ ILogService,+ IUniverInstanceService,+ LogLevel,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import { UniverDocsPlugin } from '@univerjs/docs';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { BehaviorSubject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import '@univerjs/docs/facade';+import '@univerjs/docs-ui/facade';++describe('docs-ui document facade', () => {+ let univer: Univer;+ let univerAPI: FUniver;+ let removeAllRanges: ReturnType<typeof vi.fn>;+ let addDocRanges: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);+ univer.registerPlugin(UniverDocsPlugin);++ const doc = univer.createUnit<IDocumentData, UnitModel<IDocumentData>>(UniverInstanceType.UNIVER_DOC, {+ id: 'doc-1',+ body: {+ dataStream: 'Hello Univer\r\n',+ paragraphs: [{ startIndex: 12, paragraphId: 'paragraph-1' }],+ },+ });++ removeAllRanges = vi.fn();+ addDocRanges = vi.fn();+ injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());+ injector.get(IRenderManagerService).addRender(doc.getUnitId(), {+ unitId: doc.getUnitId(),+ type: UniverInstanceType.UNIVER_DOC,+ engine: new DisposableCollection() as never,+ scene: new DisposableCollection() as never,+ mainComponent: null,+ components: new Map(),+ isMainScene: true,+ activated$: new BehaviorSubject(true),+ with: <T>() => ({+ removeAllRanges,+ addDocRanges,+ }) as T,+ activate: () => undefined,+ deactivate: () => undefined,+ isDisposed: () => false,+ });++ univerAPI = FUniver.newAPI(injector);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('replaces the rendered text selection with the requested document offsets', () => {+ univerAPI.getActiveDocument()!.setSelection(2, 7);++ expect(removeAllRanges).toHaveBeenCalledOnce();+ expect(addDocRanges).toHaveBeenCalledWith([+ {+ startOffset: 2,+ endOffset: 7,+ rangeType: DOC_RANGE_TYPE.TEXT,+ },+ ], true);+ });+});diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex 69020f48f5..5cad55c8ec 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -181,5 +181,14 @@ export { getCanvasOffsetByEngine } from './services/selection/selection-utils';export { getAnchorBounding, getLineBounding, TEXT_RANGE_LAYER_INDEX, TextRange } from './services/selection/text-range';export { whenDocAndEditorFocused } from './shortcuts/utils';export { DOC_VERTICAL_PADDING } from './types/const/padding';-export { type IKeyboardEventConfig, useEditor, useEditorClickOutside, useIsFocusing, useKeyboardEvent, useLeftAndRightArrow, useOnChange, useResize } from './views/rich-text-editor/hooks';+export {+ type IKeyboardEventConfig,+ useEditor,+ useEditorClickOutside,+ useIsFocusing,+ useKeyboardEvent,+ useLeftAndRightArrow,+ useOnChange,+ useResize,+} from './views/rich-text-editor/hooks';export { type IRichTextEditorProps, RichTextEditor } from './views/RichTextEditor';diff --git a/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.tsnew file mode 100644index 0000000000..adf79a9adb--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-auto-format.service.spec.ts@@ -0,0 +1,110 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ CommandService,+ ConfigService,+ ContextService,+ CustomRangeType,+ DesktopLogService,+ DocumentDataModel,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ UniverInstanceService,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { describe, expect, it } from 'vitest';+import { DocAutoFormatService } from '../doc-auto-format.service';++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocAutoFormatService]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: 'doc-1',+ body: {+ dataStream: 'Hello world\r\n',+ paragraphs: [{ paragraphId: 'p1', startIndex: 11 }],+ sectionBreaks: [{ startIndex: 13 }],+ customRanges: [{+ startIndex: 6,+ endIndex: 10,+ rangeId: 'range-world',+ rangeType: CustomRangeType.HYPERLINK,+ }],+ customBlocks: [],+ },+ }));+ univerInstanceService.focusUnit('doc-1');+ const selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });++ return {+ service: injector.get(DocAutoFormatService),+ selectionManager,+ };+}++describe('DocAutoFormatService', () => {+ it('runs the highest priority matching auto-format for the active document selection', () => {+ const { service, selectionManager } = createService();+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 12,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null,+ }] as never);++ const lowPriority = service.registerAutoFormat({+ id: 'doc.command.tab',+ priority: 1,+ match: () => true,+ getMutations: () => [{ id: 'low-priority' }],+ });+ const highPriority = service.registerAutoFormat({+ id: 'doc.command.tab',+ priority: 10,+ match: (context) => context.isBody && context.paragraphs.length === 1 && context.customRanges.length === 1,+ getMutations: () => [{ id: 'high-priority' }],+ });++ expect(service.onAutoFormat('doc.command.tab', { shift: false })).toEqual([{ id: 'high-priority' }]);++ highPriority.dispose();+ expect(service.onAutoFormat('doc.command.tab', null)).toEqual([{ id: 'low-priority' }]);++ lowPriority.dispose();+ expect(service.onAutoFormat('doc.command.tab', null)).toEqual([]);+ });++ it('returns no mutations when there is no active selection for the command', () => {+ const { service } = createService();++ expect(service.onAutoFormat('doc.command.tab', null)).toEqual([]);+ });+});diff --git a/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.tsnew file mode 100644index 0000000000..adad287135--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-event-manager.service.spec.ts@@ -0,0 +1,483 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventState, EventSubject, Injector, PresetListType } from '@univerjs/core';+import { DocSkeletonManagerService } from '@univerjs/docs';+import { TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';+import { describe, expect, it } from 'vitest';+import {+ DocEventManagerService,+ getListMarkerFallbackBound,+ getListMarkerFallbackHit,+ getListParagraphContextMenuHit,+ getPreferredParagraphBoundsInRange,+ getTableBlockMenuHoverRect,+ getTableHorizontalViewportGeometry,+ isChecklistListType,+} from '../doc-event-manager.service';++class TestDocSkeletonManagerService {+ readonly dirty$ = new EventSubject();+ bodyLineTop = 30;++ getSkeleton() {+ return {+ dirty$: this.dirty$,+ getSkeletonData: () => ({+ pages: [{+ pageHeight: 300,+ pageWidth: 240,+ marginLeft: 0,+ marginRight: 0,+ marginTop: 10,+ sections: [{+ top: 0,+ colCount: 1,+ columns: [{+ left: 20,+ lines: [{+ paragraphStart: true,+ paragraphIndex: 12,+ st: 12,+ top: this.bodyLineTop,+ lineHeight: 20,+ marginTop: 2,+ paddingTop: 3,+ contentHeight: 10,+ divides: [],+ }],+ }],+ }],+ skeTables: new Map([[+ 'table-1',+ {+ tableId: 'table-1',+ left: 40,+ top: 80,+ width: 120,+ height: 60,+ rows: [{+ top: 0,+ cells: [{+ left: 0,+ marginTop: 0,+ marginLeft: 0,+ marginRight: 0,+ marginBottom: 0,+ pageWidth: 120,+ pageHeight: 60,+ sections: [{+ top: 0,+ colCount: 1,+ columns: [{+ left: 0,+ lines: [{+ paragraphStart: true,+ paragraphIndex: 30,+ st: 30,+ top: 4,+ lineHeight: 16,+ marginTop: 1,+ paddingTop: 1,+ contentHeight: 8,+ divides: [],+ }],+ }],+ }],+ }],+ }],+ },+ ]]),+ }],+ skeHeaders: new Map(),+ skeFooters: new Map(),+ }),+ };+ }+}++class TestDocuments {+ readonly onPointerDown$ = new EventSubject();++ getOffsetConfig() {+ return {+ docsLeft: 0,+ docsTop: 0,+ pageMarginTop: 0,+ };+ }+}++function createDocEventManagerService() {+ const injector = new Injector();+ injector.add([DocSkeletonManagerService, { useClass: TestDocSkeletonManagerService as never }]);+ const body = {+ paragraphs: [{+ startIndex: 12,+ bullet: {+ listId: 'list-1',+ listType: PresetListType.BULLET_LIST,+ nestingLevel: 0,+ },+ }, {+ startIndex: 30,+ }],+ customRanges: [],+ };+ const documents = new TestDocuments();+ let cursor = 'text';+ const context = {+ unitId: 'doc-event',+ unit: {+ getSelfOrHeaderFooterModel: () => ({+ getBody: () => body,+ }),+ },+ engine: {+ onTransformChange$: new EventSubject(),+ },+ scene: {+ onTransformChange$: new EventSubject(),+ onPointerMove$: new EventSubject(),+ onPointerEnter$: new EventSubject(),+ onPointerUp$: new EventSubject(),+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),+ getViewport: () => undefined,+ getCursor: () => cursor,+ setCursor: (value: string) => {+ cursor = value;+ },+ },+ mainComponent: documents,+ };++ const service = injector.createInstance(DocEventManagerService, context as never);+ const skeletonManager = injector.get(DocSkeletonManagerService) as never as TestDocSkeletonManagerService;++ return {+ service,+ context,+ documents,+ skeletonManager,+ getCursor: () => cursor,+ };+}++describe('DocEventManagerService list marker helpers', () => {+ it('detects list marker fallback hits without treating body text as marker', () => {+ const paragraph = {+ startIndex: 12,+ bullet: {+ listId: 'list-1',+ listType: PresetListType.BULLET_LIST,+ nestingLevel: 0,+ },+ };+ const paragraphBound = {+ firstLine: { bottom: 124, left: 160, right: 460, top: 104 },+ pageIndex: 0,+ rect: { bottom: 128, left: 160, right: 460, top: 100 },+ };++ expect(getListMarkerFallbackBound(paragraphBound, paragraph)).toMatchObject({+ rect: { bottom: 124, left: 160, right: 196, top: 104 },+ segmentPageIndex: 0,+ });+ expect(getListMarkerFallbackHit(paragraphBound, paragraph, { x: 168, y: 112 })).not.toBeNull();+ expect(getListMarkerFallbackHit(paragraphBound, paragraph, { x: 240, y: 112 })).toBeNull();+ expect(getListParagraphContextMenuHit(paragraphBound, paragraph, { x: 260, y: 112 })).toBeNull();+ });++ it('identifies checklist list types', () => {+ expect(isChecklistListType(PresetListType.CHECK_LIST)).toBe(true);+ expect(isChecklistListType(PresetListType.CHECK_LIST_CHECKED)).toBe(true);+ expect(isChecklistListType(PresetListType.BULLET_LIST)).toBe(false);+ });++ it('prefers table paragraph bounds when a text range overlaps table content', () => {+ const bodyParagraph = {+ rect: { bottom: 120, left: 80, right: 420, top: 90 },+ paragraphStart: 10,+ paragraphEnd: 60,+ startIndex: 10,+ rects: [{ bottom: 120, left: 80, right: 420, top: 90 }],+ pageIndex: 0,+ firstLine: { bottom: 110, left: 80, right: 420, top: 90 },+ };+ const tableParagraph = {+ rect: { bottom: 180, left: 120, right: 360, top: 150 },+ paragraphStart: 22,+ paragraphEnd: 36,+ startIndex: 22,+ rects: [{ bottom: 180, left: 120, right: 360, top: 150 }],+ pageIndex: 0,+ firstLine: { bottom: 170, left: 120, right: 360, top: 150 },+ };++ expect(getPreferredParagraphBoundsInRange([bodyParagraph], [tableParagraph], 24, 30)).toEqual([tableParagraph]);+ expect(getPreferredParagraphBoundsInRange([bodyParagraph], [], 24, 30)).toEqual([bodyParagraph]);+ expect(getPreferredParagraphBoundsInRange([bodyParagraph], [tableParagraph], 61, 70)).toEqual([]);+ });++ it('calculates table hover and horizontal viewport geometry for clipped tables', () => {+ expect(getTableBlockMenuHoverRect({ bottom: 320, left: 120, right: 520, top: 160 })).toEqual({+ bottom: 320,+ left: 48,+ right: 520,+ top: 118,+ });++ expect(getTableHorizontalViewportGeometry(100, 400, {+ contentWidth: 800,+ leadingInsetLeft: 24,+ scrollLeft: 72,+ trailingInsetRight: 24,+ viewportWidth: 360,+ })).toEqual({+ scrollLeft: 72,+ visibleLeft: 76,+ visibleRight: 436,+ });++ expect(getTableHorizontalViewportGeometry(100, 400, null)).toEqual({+ scrollLeft: 0,+ visibleLeft: 100,+ visibleRight: 500,+ });+ });++ it('finds paragraph and table bounds from a rendered document skeleton', () => {+ const { service } = createDocEventManagerService();++ expect(service.paragraphBounds.get(12)?.rect).toEqual({+ bottom: 60,+ left: 20,+ right: 260,+ top: 40,+ });+ expect(service.findParagraphBoundByIndex(12)?.startIndex).toBe(12);+ expect(service.findParagraphBoundsInRange(12, 12)[0].startIndex).toBe(12);++ expect(service.tableBounds.get('table-1')?.rect).toEqual({+ bottom: 150,+ left: 40,+ right: 160,+ top: 90,+ });+ expect(service.findTableCellBound('table-1', 0, 0)?.rect).toEqual({+ bottom: 150,+ left: 40,+ right: 160,+ top: 90,+ });+ expect(service.findParagraphBoundByIndex(30)?.startIndex).toBe(30);+ expect(service.findParagraphBoundsInRange(30, 30)[0].startIndex).toBe(30);++ service.dispose();+ });++ it('recalculates paragraph bounds after document layout invalidation events', () => {+ const { context, service, skeletonManager } = createDocEventManagerService();++ expect(service.paragraphBounds.get(12)?.rect.top).toBe(40);++ skeletonManager.bodyLineTop = 44;+ skeletonManager.dirty$.next([undefined, new EventState()]);+ expect(service.paragraphBounds.get(12)?.rect.top).toBe(54);++ skeletonManager.bodyLineTop = 50;+ context.engine.onTransformChange$.emitEvent({+ type: TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize,+ });+ expect(service.paragraphBounds.get(12)?.rect.top).toBe(60);++ skeletonManager.bodyLineTop = 56;+ context.scene.onTransformChange$.emitEvent({+ type: TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale,+ });+ expect(service.paragraphBounds.get(12)?.rect.top).toBe(66);++ service.dispose();+ });++ it('uses paragraph fallback bounds for list marker interactions', () => {+ const { service } = createDocEventManagerService();++ expect(service.isPointerOnBullet(25, 45)).toBe(true);+ expect(service.isPointerOnNonChecklistBullet(25, 45)).toBe(true);+ expect(service.getListContextMenuBulletByOffset(25, 45)?.paragraph.startIndex).toBe(12);+ expect(service.isPointerOnBullet(25, 50)).toBe(false);++ service.dispose();+ });++ it('emits bullet click and context-menu events from pointer up gestures', () => {+ const { context, documents, service } = createDocEventManagerService();+ const clickedBullets: number[] = [];+ const contextMenuBullets: Array<{ startIndex: number; x: number; y: number }> = [];+ const target = {};++ const clickSub = service.clickBullets$.subscribe((bullet) => {+ clickedBullets.push(bullet.paragraph.startIndex);+ });+ const contextMenuSub = service.contextMenuBullets$.subscribe((bullet) => {+ contextMenuBullets.push({+ startIndex: bullet.paragraph.startIndex,+ x: bullet.x,+ y: bullet.y,+ });+ });++ documents.onPointerDown$.emitEvent({+ button: 0,+ offsetX: 25,+ offsetY: 45,+ target,+ timeStamp: 100,+ });+ context.scene.onPointerUp$.emitEvent({+ button: 0,+ offsetX: 25,+ offsetY: 45,+ target,+ timeStamp: 180,+ });++ documents.onPointerDown$.emitEvent({+ button: 2,+ offsetX: 25,+ offsetY: 45,+ target,+ timeStamp: 300,+ });+ context.scene.onPointerUp$.emitEvent({+ button: 2,+ offsetX: 25,+ offsetY: 45,+ target,+ timeStamp: 1200,+ });++ expect(clickedBullets).toEqual([12]);+ expect(contextMenuBullets).toEqual([{ startIndex: 12, x: 25, y: 45 }]);++ clickSub.unsubscribe();+ contextMenuSub.unsubscribe();+ service.dispose();+ });++ it('publishes paragraph and table hover state from pointer movement', async () => {+ const { context, service } = createDocEventManagerService();+ const hoveredParagraphs: Array<number | null> = [];+ const hoveredLeftParagraphs: Array<number | null> = [];+ const hoveredTables: Array<string | null> = [];+ const hoveredCells: Array<string | null> = [];+ const distinctHoveredParagraphs: Array<number | null> = [];+ const distinctHoveredLeftParagraphs: Array<number | null> = [];+ const distinctHoveredTables: Array<string | null> = [];+ const distinctHoveredCells: Array<string | null> = [];++ const paragraphSub = service.hoverParagraphRealTime$.subscribe((bound) => {+ hoveredParagraphs.push(bound?.startIndex ?? null);+ });+ const distinctParagraphSub = service.hoverParagraph$.subscribe((bound) => {+ distinctHoveredParagraphs.push(bound?.startIndex ?? null);+ });+ const paragraphLeftSub = service.hoverParagraphLeftRealTime$.subscribe((bound) => {+ hoveredLeftParagraphs.push(bound?.startIndex ?? null);+ });+ const distinctParagraphLeftSub = service.hoverParagraphLeft$.subscribe((bound) => {+ distinctHoveredLeftParagraphs.push(bound?.startIndex ?? null);+ });+ const tableSub = service.hoverTableRealTime$.subscribe((bound) => {+ hoveredTables.push(bound?.tableId ?? null);+ });+ const distinctTableSub = service.hoverTable$.subscribe((bound) => {+ distinctHoveredTables.push(bound?.tableId ?? null);+ });+ const cellSub = service.hoverTableCellRealTime$.subscribe((bound) => {+ hoveredCells.push(bound ? `${bound.tableId}:${bound.rowIndex}:${bound.colIndex}` : null);+ });+ const distinctCellSub = service.hoverTableCell$.subscribe((bound) => {+ distinctHoveredCells.push(bound ? `${bound.tableId}:${bound.rowIndex}:${bound.colIndex}` : null);+ });++ context.scene.onPointerMove$.emitEvent({+ buttons: 0,+ offsetX: 50,+ offsetY: 100,+ });++ expect(hoveredParagraphs.at(-1)).toBe(30);+ expect(distinctHoveredParagraphs.at(-1)).toBe(30);+ expect(hoveredTables.at(-1)).toBe('table-1');+ expect(distinctHoveredTables.at(-1)).toBe('table-1');+ expect(hoveredCells.at(-1)).toBe('table-1:0:0');+ expect(distinctHoveredCells.at(-1)).toBe('table-1:0:0');++ await new Promise((resolve) => setTimeout(resolve, 35));+ context.scene.onPointerMove$.emitEvent({+ buttons: 0,+ offsetX: 10,+ offsetY: 50,+ });++ expect(hoveredLeftParagraphs.at(-1)).toBe(12);+ expect(distinctHoveredLeftParagraphs.at(-1)).toBe(12);++ paragraphSub.unsubscribe();+ distinctParagraphSub.unsubscribe();+ paragraphLeftSub.unsubscribe();+ distinctParagraphLeftSub.unsubscribe();+ tableSub.unsubscribe();+ distinctTableSub.unsubscribe();+ cellSub.unsubscribe();+ distinctCellSub.unsubscribe();+ service.dispose();+ });++ it('clears hover state while dragging across the document', async () => {+ const { context, service } = createDocEventManagerService();+ const hoveredParagraphs: Array<number | null> = [];+ const hoveredTables: Array<string | null> = [];++ const paragraphSub = service.hoverParagraphRealTime$.subscribe((bound) => {+ hoveredParagraphs.push(bound?.startIndex ?? null);+ });+ const tableSub = service.hoverTableRealTime$.subscribe((bound) => {+ hoveredTables.push(bound?.tableId ?? null);+ });++ context.scene.onPointerMove$.emitEvent({+ buttons: 0,+ offsetX: 50,+ offsetY: 100,+ });+ await new Promise((resolve) => setTimeout(resolve, 35));+ context.scene.onPointerMove$.emitEvent({+ buttons: 1,+ offsetX: 50,+ offsetY: 100,+ });++ expect(hoveredParagraphs.at(-1)).toBeNull();+ expect(hoveredTables.at(-1)).toBeNull();++ paragraphSub.unsubscribe();+ tableSub.unsubscribe();+ service.dispose();+ });+});diff --git a/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.spec.tsnew file mode 100644index 0000000000..c818c3c2e8--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-ime-input-manager.service.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 { Injector, JSONX } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocIMEInputManagerService } from '../doc-ime-input-manager.service';++function createService(): DocIMEInputManagerService {+ const injector = new Injector();+ return injector.createInstance(DocIMEInputManagerService, { unitId: 'doc-1' } as never);+}++describe('DocIMEInputManagerService', () => {+ it('composes IME undo and redo mutation params around the previous active range', () => {+ const service = createService();+ const activeRange = { startOffset: 1, endOffset: 2, collapsed: false };+ const jsonX = JSONX.getInstance();+ service.setActiveRange(activeRange as never);++ service.pushUndoRedoMutationParams(+ { unitId: 'doc-1', actions: jsonX.insertOp(['settings'], { zoomRatio: 1 }), textRanges: [] } as never,+ { unitId: 'doc-1', actions: jsonX.replaceOp(['id'], 'doc-1', 'doc-2'), textRanges: [] } as never+ );++ expect(service.fetchComposedUndoRedoMutationParams()).toMatchObject({+ previousActiveRange: activeRange,+ undoMutationParams: { unitId: 'doc-1' },+ redoMutationParams: { unitId: 'doc-1' },+ });+ });++ it('clears cached IME mutation params', () => {+ const service = createService();+ service.setUndoRedoMutationParamsCache({+ undoCache: [{ unitId: 'doc-1', actions: [], textRanges: [] } as never],+ redoCache: [{ unitId: 'doc-1', actions: [], textRanges: [] } as never],+ });++ service.clearUndoRedoMutationParamsCache();++ expect(service.getUndoRedoMutationParamsCache()).toEqual({ undoCache: [], redoCache: [] });+ });+});diff --git a/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.tsindex 7e1ac66782..3626189651 100644--- a/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.ts@@ -14,30 +14,77 @@* limitations under the License.*/-import { Injector } from '@univerjs/core';+import { Injector, JSONX } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { beforeEach, describe, expect, it } from 'vitest';import { DocIMEInputManagerService } from '../doc-ime-input-manager.service';import { DocIMEStateChangeInterceptorService } from '../doc-ime-state-change-interceptor.service';+class TestRenderManagerService {+ static readonly renderUnits = new Map<string, { with: (token: unknown) => unknown }>();++ getRenderUnitById(unitId: string) {+ return TestRenderManagerService.renderUnits.get(unitId);+ }+}+describe('DocIMEStateChangeInterceptorService', () => {let service: DocIMEStateChangeInterceptorService;+ let injector: Injector;++ function createImeInputManager(unitId: string, withHistory = true) {+ const imeInputManagerService = injector.createInstance(DocIMEInputManagerService, { unitId } as never);++ if (withHistory) {+ const jsonX = JSONX.getInstance();+ imeInputManagerService.setActiveRange({ startOffset: 1, endOffset: 2 } as never);+ imeInputManagerService.pushUndoRedoMutationParams(+ {+ unitId,+ actions: jsonX.insertOp(['settings'], { zoomRatio: 1 }),+ textRanges: [],+ } as never,+ {+ unitId,+ actions: jsonX.replaceOp(['id'], unitId, `${unitId}-editing`),+ textRanges: [],+ } as never+ );+ }++ return imeInputManagerService;+ }++ function registerImeRenderUnit(unitId: string, imeInputManagerService: DocIMEInputManagerService) {+ TestRenderManagerService.renderUnits.set(unitId, {+ with: (token: unknown) => token === DocIMEInputManagerService ? imeInputManagerService : null,+ });+ }beforeEach(() => {- const imeInputManagerService = {- fetchComposedUndoRedoMutationParams: () => ({- undoMutationParams: { actions: [{ p: ['body'], od: 'old' }] },- redoMutationParams: { actions: [{ p: ['body'], oi: 'new' }] },- previousActiveRange: { startOffset: 1, endOffset: 2 },- }),- };- const injector = new Injector();- injector.add([IRenderManagerService, { useValue: { getRenderUnitById: () => ({ with: (token: unknown) => token === DocIMEInputManagerService ? imeInputManagerService : null }) } as unknown as IRenderManagerService }]);+ TestRenderManagerService.renderUnits.clear();+ injector = new Injector();+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);injector.add([DocIMEStateChangeInterceptorService]);+ registerImeRenderUnit('doc-1', createImeInputManager('doc-1'));service = injector.get(DocIMEStateChangeInterceptorService);});+ it('keeps regular state changes unchanged before IME composition ends', () => {+ const changeStateInfo = {+ unitId: 'doc-1',+ isCompositionEnd: false,+ isSync: false,+ redoState: { actions: [{ p: ['body'], oi: 'typing' }] },+ undoState: { actions: [{ p: ['body'], od: 'typing' }], textRanges: [] },+ } as never;++ expect(service.transformChangeStateInfo(changeStateInfo)).toBe(changeStateInfo);+ });+it('replaces composition history with the composed IME undo and redo actions', () => {+ const jsonX = JSONX.getInstance();+expect(service.transformChangeStateInfo({unitId: 'doc-1',isCompositionEnd: true,@@ -45,11 +92,55 @@ describe('DocIMEStateChangeInterceptorService', () => {redoState: { actions: [] },undoState: { actions: [], textRanges: [] },} as never)).toMatchObject({- redoState: { actions: [{ p: ['body'], oi: 'new' }] },+ redoState: { actions: jsonX.replaceOp(['id'], 'doc-1', 'doc-1-editing') },undoState: {- actions: [{ p: ['body'], od: 'old' }],+ actions: jsonX.insertOp(['settings'], { zoomRatio: 1 }),textRanges: [{ startOffset: 1, endOffset: 2 }],},});});++ it('uses the syncer render unit when composition state comes from syncing', () => {+ const jsonX = JSONX.getInstance();+ registerImeRenderUnit('doc-sync', createImeInputManager('doc-sync'));++ expect(service.transformChangeStateInfo({+ unitId: 'doc-1',+ syncer: 'doc-sync',+ isCompositionEnd: true,+ isSync: true,+ redoState: { actions: [] },+ undoState: { actions: [], textRanges: [] },+ } as never)).toMatchObject({+ redoState: { actions: jsonX.replaceOp(['id'], 'doc-sync', 'doc-sync-editing') },+ undoState: {+ actions: jsonX.insertOp(['settings'], { zoomRatio: 1 }),+ textRanges: [{ startOffset: 1, endOffset: 2 }],+ },+ });+ });++ it('drops composition state when the render unit no longer has an IME manager', () => {+ TestRenderManagerService.renderUnits.delete('doc-1');++ expect(service.transformChangeStateInfo({+ unitId: 'doc-1',+ isCompositionEnd: true,+ isSync: false,+ redoState: { actions: [] },+ undoState: { actions: [], textRanges: [] },+ } as never)).toBeNull();+ });++ it('throws when composition ended without cached IME history', () => {+ registerImeRenderUnit('doc-1', createImeInputManager('doc-1', false));++ expect(() => service.transformChangeStateInfo({+ unitId: 'doc-1',+ isCompositionEnd: true,+ isSync: false,+ redoState: { actions: [] },+ undoState: { actions: [], textRanges: [] },+ } as never)).toThrow('historyParams is null in RichTextEditingMutation');+ });});diff --git a/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.tsnew file mode 100644index 0000000000..d8181b3db2--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-menu-style.service.spec.ts@@ -0,0 +1,151 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ DocumentDataModel,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ ThemeService,+ UniverInstanceService,+} from '@univerjs/core';+import { DocSelectionManagerService, SetTextSelectionsOperation } from '@univerjs/docs';+import { DocumentEditArea, IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderManagerService } from '@univerjs/engine-render';+import { describe, expect, it } from 'vitest';+import { DocMenuStyleService } from '../doc-menu-style.service';++class TestRenderManagerService {+ editArea: DocumentEditArea | undefined;++ getRenderById() {+ if (this.editArea == null) {+ return;+ }++ return {+ with: () => ({+ getViewModel: () => ({+ getEditArea: () => this.editArea,+ }),+ }),+ };+ }+}++function createService(): DocMenuStyleService {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ThemeService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocMenuStyleService]);+ return injector.get(DocMenuStyleService);+}++function createStyleTestBed() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ThemeService]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocMenuStyleService]);++ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: 'doc-menu-style',+ body: {+ dataStream: 'Title\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_menu_style_fixture_1', startIndex: 5 }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ }));+ univerInstanceService.setCurrentUnitForType('doc-menu-style');++ return {+ injector,+ service: injector.get(DocMenuStyleService),+ selectionManager: injector.get(DocSelectionManagerService),+ commandService: injector.get(ICommandService),+ renderManagerService: injector.get(IRenderManagerService) as unknown as TestRenderManagerService,+ };+}++describe('DocMenuStyleService', () => {+ it('merges cached text styles used by the next document input', () => {+ const service = createService();++ service.setStyleCache({ bl: 1 });+ service.setStyleCache({ it: 1 });++ expect(service.getStyleCache()).toEqual({ bl: 1, it: 1 });+ });++ it('uses body text defaults when there is no focused document render', () => {+ const service = createService();++ expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 11 });+ });++ it('uses body and header footer defaults from the active document render area', () => {+ const { service, renderManagerService } = createStyleTestBed();++ renderManagerService.editArea = DocumentEditArea.BODY;+ expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 11 });++ renderManagerService.editArea = DocumentEditArea.FOOTER;+ expect(service.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 9 });+ });++ it('clears cached input style when document selection changes', () => {+ const { service, selectionManager, commandService } = createStyleTestBed();+ commandService.registerCommand(SetTextSelectionsOperation);++ service.setStyleCache({ fs: 18, bl: 1 });+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-menu-style', subUnitId: 'doc-menu-style' });+ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId: 'doc-menu-style', subUnitId: 'doc-menu-style' });++ expect(service.getStyleCache()).toBeNull();+ });+});diff --git a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.tsindex f1e3dc4f70..494f1fcf4b 100644--- a/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-page-layout.service.spec.ts@@ -14,143 +14,246 @@* limitations under the License.*/-import { describe, expect, it, vi } from 'vitest';+import type { DocumentDataModel } from '@univerjs/core';+import type { IRenderContext } from '@univerjs/engine-render';+import type { IDocFitToWidthOptions } from '../../config/config';+import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { DOCS_VIEW_KEY, VIEWPORT_KEY } from '../../basics/docs-view-key';import { DocPageLayoutService } from '../doc-page-layout.service';+import { DocViewScaleService } from '../doc-view-scale';-const mockDocObject = vi.hoisted(() => ({ current: null as unknown }));+class TestDocViewScaleService {+ static viewScale = 1;+ static availableWidth = 1000;+ static options: IDocFitToWidthOptions = { mode: 'none' };-vi.mock('../../basics/component-tools', async (importOriginal) => {- const actual = await importOriginal<typeof import('../../basics/component-tools')>();+ static reset() {+ this.viewScale = 1;+ this.availableWidth = 1000;+ this.options = { mode: 'none' };+ }- return {- ...actual,- neoGetDocObject: () => mockDocObject.current,- };-});+ getViewScale() {+ return TestDocViewScaleService.viewScale;+ }++ getOptions() {+ return TestDocViewScaleService.options;+ }++ getAvailableWidth() {+ return TestDocViewScaleService.availableWidth;+ }+}++class TestViewport {+ scrollX: number | undefined;++ scrollToViewportPos(params: { viewportScrollX: number }) {+ this.scrollX = params.viewportScrollX;+ }+}++class TestScene {+ scaleX = 1;+ scaleY = 1;+ width = 0;+ height = 0;++ constructor(+ private readonly _parent: { width: number; height: number } | null,+ private readonly _viewport = new TestViewport()+ ) {}++ scale(scaleX: number, scaleY: number) {+ this.scaleX = scaleX;+ this.scaleY = scaleY;+ }++ resize(width: number, height: number) {+ this.width = width;+ this.height = height;+ }++ getParent() {+ return this._parent;+ }++ getViewport(key: string) {+ return key === VIEWPORT_KEY.VIEW_MAIN ? this._viewport : null;+ }++ get viewport() {+ return this._viewport;+ }+}++class TestDocumentComponent {+ left: number | undefined;+ top: number | undefined;++ constructor(+ readonly width: number,+ readonly height: number,+ readonly pageMarginLeft: number,+ readonly pageMarginTop: number+ ) {}++ translate(left: number, top: number) {+ this.left = left;+ this.top = top;+ }+}++class TestDocBackground {+ left: number | undefined;+ top: number | undefined;++ translate(left: number, top: number) {+ this.left = left;+ this.top = top;+ }+}-function createFixture(options: {+function createLayoutService(params: {+ documentWidth: number;+ documentHeight: number;+ pageMarginLeft: number;+ pageMarginTop: number;engineWidth: number;engineHeight: number;- docsWidth?: number;- docsHeight?: number;- viewScale: number;- sceneScale?: number;- align?: 'center' | 'start';- paddingX?: number | `${number}%`;}) {- const docsComponent = {- width: options.docsWidth ?? 960,- height: options.docsHeight ?? 1000,- pageMarginLeft: 20,- pageMarginTop: 20,- translate: vi.fn(),- };- const docBackground = {- translate: vi.fn(),- };- const viewport = {- scrollToViewportPos: vi.fn(),- };- const scene = {- scaleX: options.sceneScale ?? options.viewScale,- scaleY: options.sceneScale ?? options.viewScale,- getParent: vi.fn(() => ({ width: options.engineWidth, height: options.engineHeight })),- scale: vi.fn(),- resize: vi.fn(),- getViewport: vi.fn(() => viewport),- };- mockDocObject.current = {- document: docsComponent,- docBackground,- scene,- };+ const injector = new Injector();+ injector.add([DocViewScaleService, { useClass: TestDocViewScaleService as never }]);- const viewScaleService = {- getViewScale: vi.fn(() => options.viewScale),- getAvailableWidth: vi.fn(() => options.engineWidth),- getOptions: vi.fn(() => ({- mode: 'fit-width',- target: 'viewport',- paddingX: options.paddingX ?? 20,- minScale: 0,- align: options.align ?? 'center',- })),- };- const service = new (DocPageLayoutService as unknown as new (...args: unknown[]) => DocPageLayoutService)(- {- unit: {- getSettings: () => ({ zoomRatio: 1 }),- getSnapshot: () => ({ documentStyle: {} }),- },- },- viewScaleService+ const documentComponent = new TestDocumentComponent(+ params.documentWidth,+ params.documentHeight,+ params.pageMarginLeft,+ params.pageMarginTop);+ const docBackground = new TestDocBackground();+ const scene = new TestScene({ width: params.engineWidth, height: params.engineHeight });+ const context = {+ mainComponent: documentComponent,+ scene,+ engine: { width: params.engineWidth, height: params.engineHeight },+ components: new Map([[DOCS_VIEW_KEY.BACKGROUND, docBackground]]),+ } as unknown as IRenderContext<DocumentDataModel>;return {docBackground,- docsComponent,+ documentComponent,scene,- service,- viewScaleService,- viewport,+ service: injector.createInstance(DocPageLayoutService, context),};}describe('DocPageLayoutService', () => {- it('uses view scale for centered scene geometry', () => {- const { docsComponent, scene, service, viewport } = createFixture({- engineWidth: 1600,+ beforeEach(() => {+ TestDocViewScaleService.reset();+ });++ it('centers the document page when the viewport is wider than the page', () => {+ const { docBackground, documentComponent, scene, service } = createLayoutService({+ documentWidth: 600,+ documentHeight: 900,+ pageMarginLeft: 40,+ pageMarginTop: 20,+ engineWidth: 1000,engineHeight: 1200,- viewScale: 1.5,});service.calculatePagePosition();- expect(scene.resize).toHaveBeenCalledWith(1040, 773.3333333333334);- expect(docsComponent.translate).toHaveBeenCalledWith(53.333333333333336, 20);- expect(viewport.scrollToViewportPos).toHaveBeenCalledWith({ viewportScrollX: 0 });+ expect(documentComponent.left).toBe(200);+ expect(documentComponent.top).toBe(20);+ expect(docBackground.left).toBe(200);+ expect(docBackground.top).toBe(20);+ expect(scene.width).toBe(920);+ expect(scene.height).toBe(1160);+ expect(scene.viewport.scrollX).toBe(0);});- it('starts at the container edge when configured with start alignment and no padding', () => {- const { docsComponent, service } = createFixture({- engineWidth: 480,+ it('keeps the page margin and scrolls to the page center when the viewport is narrower than the page', () => {+ const { documentComponent, scene, service } = createLayoutService({+ documentWidth: 600,+ documentHeight: 900,+ pageMarginLeft: 40,+ pageMarginTop: 20,+ engineWidth: 500,engineHeight: 800,- viewScale: 0.5,- align: 'start',- paddingX: 0,});service.calculatePagePosition();- expect(docsComponent.translate).toHaveBeenCalledWith(0, 20);+ expect(documentComponent.left).toBe(40);+ expect(documentComponent.top).toBe(20);+ expect(scene.width).toBe(680);+ expect(scene.height).toBe(940);+ expect(scene.viewport.scrollX).toBe(90);});- it('uses percentage padding for start-aligned fitting', () => {- const { docsComponent, service } = createFixture({- engineWidth: 1200,- engineHeight: 800,- viewScale: 1,- align: 'start',- paddingX: '10%',+ it('uses fit-width start alignment padding instead of centering the page', () => {+ TestDocViewScaleService.viewScale = 2;+ TestDocViewScaleService.availableWidth = 1000;+ TestDocViewScaleService.options = { mode: 'fit-width', align: 'start', paddingX: '10%' };++ const { documentComponent, scene, service } = createLayoutService({+ documentWidth: 500,+ documentHeight: 900,+ pageMarginLeft: 40,+ pageMarginTop: 20,+ engineWidth: 1400,+ engineHeight: 1200,});service.calculatePagePosition();- expect(docsComponent.translate).toHaveBeenCalledWith(120, 20);+ expect(scene.scaleX).toBe(2);+ expect(scene.scaleY).toBe(2);+ expect(documentComponent.left).toBe(50);+ expect(scene.width).toBe(650);+ expect(scene.viewport.scrollX).toBe(0);});- it('reapplies view scale when an early container measurement left the scene stale', () => {- const { scene, service } = createFixture({- engineWidth: 900,- engineHeight: 800,- viewScale: 1.5,- sceneScale: 1 / 600,- align: 'start',- paddingX: 0,+ it('moves the page out of view while the engine has no usable width', () => {+ const { docBackground, documentComponent, scene, service } = createLayoutService({+ documentWidth: 600,+ documentHeight: 900,+ pageMarginLeft: 40,+ pageMarginTop: 20,+ engineWidth: 1,+ engineHeight: 1200,+ });++ service.calculatePagePosition();++ expect(documentComponent.left).toBe(-10000);+ expect(documentComponent.top).toBe(-10000);+ expect(docBackground.left).toBe(-10000);+ expect(docBackground.top).toBe(-10000);+ expect(scene.width).toBe(680);+ expect(scene.height).toBe(1160);+ });++ it('leaves the current layout untouched when the document size is not ready', () => {+ const { documentComponent, scene, service } = createLayoutService({+ documentWidth: Number.POSITIVE_INFINITY,+ documentHeight: 900,+ pageMarginLeft: 40,+ pageMarginTop: 20,+ engineWidth: 1000,+ engineHeight: 1200,});service.calculatePagePosition();- expect(scene.scale).toHaveBeenCalledWith(1.5, 1.5);+ expect(documentComponent.left).toBeUndefined();+ expect(documentComponent.top).toBeUndefined();+ expect(scene.width).toBe(0);+ expect(scene.height).toBe(0);+ expect(scene.viewport.scrollX).toBeUndefined();});});diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.tsindex 3760c6b222..4251c32880 100644--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts@@ -15,12 +15,16 @@*/import type { IMutiPageParagraphBound } from '../doc-event-manager.service';-import { DataStreamTreeTokenType, DOC_RANGE_TYPE, DocumentBlockRangeType, PresetListType } from '@univerjs/core';+import { BlockType, DataStreamTreeTokenType, DOC_RANGE_TYPE, DocumentBlockRangeType, PresetListType } from '@univerjs/core';import { DocumentEditArea } from '@univerjs/engine-render';import { BehaviorSubject, Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';import { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY } from '../../views/ParagraphMenu';-import { getPreferredParagraphBoundsInRange, getTableBlockMenuHoverRect, getTableHorizontalViewportGeometry } from '../doc-event-manager.service';+import {+ getPreferredParagraphBoundsInRange,+ getTableBlockMenuHoverRect,+ getTableHorizontalViewportGeometry,+} from '../doc-event-manager.service';import { DocParagraphMenuService } from '../doc-paragraph-menu.service';describe('DocParagraphMenuService', () => {@@ -502,6 +506,64 @@ describe('DocParagraphMenuService', () => {expect(service.activeTarget?.icon).toBe('OrderIcon');});+ it('shows a horizontal-rule paragraph as a draggable divider block', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: '\r',+ paragraphs: [{+ startIndex: 0,+ paragraphStyle: {+ borderBottom: {},+ },+ }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 0,+ startIndex: 0,+ }));++ expect(service.activeTarget).toMatchObject({+ kind: 'paragraph',+ icon: 'ReduceIcon',+ emptyMode: false,+ draggable: true,+ });+ });++ it('shows a custom block paragraph as a custom block menu target', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ customBlocks: [{+ blockId: 'custom-1',+ blockType: BlockType.CUSTOM,+ startIndex: 0,+ }],+ dataStream: '\b\r',+ paragraphs: [{ startIndex: 1 }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 1,+ startIndex: 1,+ }));++ expect(service.activeTarget).toMatchObject({+ kind: 'customBlock',+ key: 'customBlock:custom-1',+ icon: 'TextTypeIcon',+ menuRange: {+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ },+ });+ });+it('keeps cell paragraph move ranges inside the current table cell', () => {const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));const dataStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}A\rB\r${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`;@@ -856,20 +918,260 @@ describe('DocParagraphMenuService', () => {expect(replayedRequests).toEqual([null]);});++ it('reports active paragraph and dragging state while the paragraph menu is visible', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Title\r',+ });+ const paragraph = createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ });++ service.showParagraphMenu(paragraph);+ service.setBlockMenuDragging(true);++ expect(service.activeParagraph).toBe(paragraph);+ expect(service.isBlockMenuDragging).toBe(true);+ });++ it('keeps the paragraph menu open after outside click when the cursor is still inside it', () => {+ const dispose = vi.fn();+ const textSelection$ = new Subject();+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));+ const service = createService({+ activeTextRange: { startOffset: 2, endOffset: 2, collapsed: true },+ attachPopupToRect,+ dataStream: 'Title\r',+ textSelection$,+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ }));+ const [, popupOptions] = attachPopupToRect.mock.calls[0] as unknown as [unknown, { onClickOutside: () => void }];+ popupOptions.onClickOutside();+ textSelection$.next({ textRanges: [], rectRanges: [] });++ expect(dispose).not.toHaveBeenCalled();+ expect(service.activeTarget?.key).toBe('paragraph:5');+ });++ it('hides the visible paragraph menu after a custom range click and after scrolling', () => {+ const dispose = vi.fn();+ const clickCustomRanges$ = new Subject();+ const scrollAfter = createScrollAfterEvent();+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));+ const service = createService({+ attachPopupToRect,+ clickCustomRanges$,+ dataStream: 'Title\r',+ scrollAfter$: scrollAfter.event$,+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ }));+ clickCustomRanges$.next({});++ expect(dispose).toHaveBeenCalledTimes(1);+ expect(service.activeTarget).toBeNull();++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ }));+ scrollAfter.emit({ scrollY: 20 });++ expect(dispose).toHaveBeenCalledTimes(2);+ expect(service.activeTarget).toBeNull();+ });++ it('shows and hides menus from hover state changes', async () => {+ const dispose = vi.fn();+ const hoverParagraphRealTime$ = new BehaviorSubject<IMutiPageParagraphBound | null>(null);+ const hoverParagraphLeft$ = new BehaviorSubject<IMutiPageParagraphBound | null>(null);+ const hoverTableRealTime$ = new BehaviorSubject<null>(null);+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Title\r',+ hoverParagraphLeft$,+ hoverParagraphRealTime$,+ hoverTableRealTime$,+ });++ await new Promise((resolve) => setTimeout(resolve, 20));+ hoverParagraphRealTime$.next(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 5,+ startIndex: 5,+ }));+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(service.activeTarget?.key).toBe('paragraph:5');++ hoverParagraphRealTime$.next(null);+ hoverParagraphLeft$.next(null);+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(dispose).toHaveBeenCalledTimes(1);+ expect(service.activeTarget).toBeNull();+ });++ it('does not show table menus for expanded text selections or missing table data', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: '',+ docRanges: [{+ collapsed: false,+ endOffset: 6,+ startOffset: 2,+ }],+ tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],+ });++ service.showTableMenu({+ pageIndex: 0,+ rect: { bottom: 170, left: 100, right: 400, top: 80 },+ tableId: 'table-1',+ });++ expect(attachPopupToRect).not.toHaveBeenCalled();++ const missingTableService = createService({+ attachPopupToRect,+ dataStream: '',+ });+ missingTableService.showTableMenu({+ pageIndex: 0,+ rect: { bottom: 170, left: 100, right: 400, top: 80 },+ tableId: 'missing-table',+ });++ expect(attachPopupToRect).not.toHaveBeenCalled();+ });++ it('calculates paragraph drop targets before and after the nearest body block', () => {+ const paragraphBounds = new Map([+ [3, createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 3,+ startIndex: 3,+ })],+ [7, {+ ...createParagraphBound({+ paragraphStart: 4,+ paragraphEnd: 7,+ startIndex: 7,+ }),+ rect: { bottom: 60, left: 10, right: 200, top: 40 },+ }],+ [13, {+ ...createParagraphBound({+ paragraphStart: 8,+ paragraphEnd: 13,+ startIndex: 13,+ }),+ rect: { bottom: 100, left: 10, right: 200, top: 80 },+ }],+ ] as Array<[number, IMutiPageParagraphBound]>);+ const service = createService({+ attachPopupToRect: vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() })),+ dataStream: 'One\rTwo\rThree\r',+ paragraphBounds,+ paragraphs: [+ { startIndex: 3 },+ { startIndex: 7 },+ { startIndex: 13 },+ ],+ });++ expect(service.getDropTargetFromClientPoint(12, 45, { startOffset: 0, endOffset: 4 })).toEqual({+ targetOffset: 4,+ rect: { bottom: 40, left: 10, right: 200, top: 40 },+ });+ expect(service.getDropTargetFromClientPoint(12, 55, { startOffset: 0, endOffset: 4 })).toEqual({+ targetOffset: 8,+ rect: { bottom: 60, left: 10, right: 200, top: 60 },+ });+ });++ it('does not return a drop target when the document has no movable blocks', () => {+ const service = createService({+ attachPopupToRect: vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() })),+ dataStream: '',+ });++ expect(service.getDropTargetFromClientPoint(12, 45, { startOffset: 0, endOffset: 4 })).toBeNull();+ });++ it('keeps drop targets inside the source table cell while dragging a cell paragraph', () => {+ const dataStream = `${DataStreamTreeTokenType.TABLE_START}${DataStreamTreeTokenType.TABLE_ROW_START}${DataStreamTreeTokenType.TABLE_CELL_START}A\rB\r${DataStreamTreeTokenType.TABLE_CELL_END}${DataStreamTreeTokenType.TABLE_ROW_END}${DataStreamTreeTokenType.TABLE_END}`;+ const paragraphBounds = new Map([+ [4, {+ ...createParagraphBound({+ paragraphStart: 3,+ paragraphEnd: 4,+ startIndex: 4,+ }),+ rect: { bottom: 40, left: 120, right: 260, top: 20 },+ }],+ [6, {+ ...createParagraphBound({+ paragraphStart: 5,+ paragraphEnd: 6,+ startIndex: 6,+ }),+ rect: { bottom: 80, left: 120, right: 260, top: 60 },+ }],+ ] as Array<[number, IMutiPageParagraphBound]>);+ const service = createService({+ attachPopupToRect: vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() })),+ dataStream,+ paragraphBounds,+ paragraphs: [+ { startIndex: 4 },+ { startIndex: 6 },+ ],+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: dataStream.length - 1 }],+ });++ expect(service.getDropTargetFromClientPoint(125, 65, { startOffset: 3, endOffset: 5 })).toEqual({+ targetOffset: 5,+ rect: { bottom: 60, left: 120, right: 260, top: 60 },+ });+ });});function createService(options: {+ activeTextRange?: { collapsed: boolean; endOffset: number; startOffset: number };attachPopupToRect: ReturnType<typeof vi.fn>;blockRanges?: Array<{ blockId: string; blockType: string; endIndex: number; startIndex: number }>;+ clickCustomRanges$?: Subject<unknown>;+ customBlocks?: Array<{ blockId: string; blockType: BlockType; startIndex: number }>;dataStream: string;findParagraphBoundByIndex?: (index: number) => unknown;docRanges?: Array<{ collapsed?: boolean; endOffset?: number; rangeType?: DOC_RANGE_TYPE | string; startOffset?: number }>;getDocRanges?: () => Array<{ collapsed?: boolean; endOffset?: number; rangeType?: DOC_RANGE_TYPE | string; startOffset?: number }>;- paragraphs?: Array<{ bullet?: { listType?: PresetListType }; startIndex: number }>;+ paragraphs?: Array<{ bullet?: { listType?: PresetListType }; paragraphStyle?: Record<string, unknown>; startIndex: number }>;paragraphBounds?: Map<number, IMutiPageParagraphBound>;+ hoverParagraphLeft$?: BehaviorSubject<IMutiPageParagraphBound | null>;+ hoverParagraphRealTime$?: BehaviorSubject<IMutiPageParagraphBound | null>;+ hoverTableRealTime$?: BehaviorSubject<null>;inputBefore$?: Subject<unknown>;keydown$?: Subject<unknown>;replaceDocRanges?: ReturnType<typeof vi.fn>;+ scrollAfter$?: { subscribeEvent: (callback: (event: { scrollY: number }) => void) => { dispose: () => void } };textSelection$?: Subject<unknown>;tableCellBounds?: Map<string, Array<{ colIndex: number; pageIndex: number; rect: { bottom: number; left: number; right: number; top: number }; rowIndex: number; tableId: string }>>;tables?: Array<{ endIndex: number; startIndex: number; tableId: string }>;@@ -881,6 +1183,7 @@ function createService(options: {unit: {getBody: () => ({blockRanges: options.blockRanges ?? [],+ customBlocks: options.customBlocks ?? [],dataStream: options.dataStream,paragraphs: options.paragraphs ?? [],tables: options.tables ?? [],@@ -893,25 +1196,28 @@ function createService(options: {}),},scene: {+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),getViewport: () => ({height: 300,- onScrollAfter$: {+ onScrollAfter$: options.scrollAfter$ ?? {subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })),},+ viewportScrollX: 0,viewportScrollY: options.viewportScrollY ?? 0,}),},} as never,{- getActiveTextRange: () => null,+ getActiveTextRange: () => options.activeTextRange ?? null,getDocRanges: options.getDocRanges ?? vi.fn(() => options.docRanges ?? []),replaceDocRanges: options.replaceDocRanges ?? vi.fn(),textSelection$: options.textSelection$ ?? new Subject(),} as never,{- hoverParagraphRealTime$: new BehaviorSubject(null),- hoverParagraphLeft$: new BehaviorSubject(null),- clickCustomRanges$: new Subject(),+ hoverParagraphRealTime$: options.hoverParagraphRealTime$ ?? new BehaviorSubject(null),+ hoverParagraphLeft$: options.hoverParagraphLeft$ ?? new BehaviorSubject(null),+ hoverTableRealTime$: options.hoverTableRealTime$ ?? new BehaviorSubject(null),+ clickCustomRanges$: options.clickCustomRanges$ ?? new Subject(),findParagraphBoundByIndex: options.findParagraphBoundByIndex ?? vi.fn(() => null),findParagraphBoundsInRange: vi.fn((startIndex: number, endIndex: number) => [...(options.paragraphBounds ?? new Map()).values()].filter((bound) => Math.max(bound.paragraphStart, startIndex) <= Math.min(bound.paragraphEnd, endIndex))),@@ -941,6 +1247,32 @@ function createService(options: {);}+function createScrollAfterEvent() {+ const callbacks: Array<(event: { scrollY: number }) => void> = [];++ return {+ event$: {+ subscribeEvent: (callback: (event: { scrollY: number }) => void) => {+ callbacks.push(callback);++ return {+ dispose: () => {+ const index = callbacks.indexOf(callback);+ if (index >= 0) {+ callbacks.splice(index, 1);+ }+ },+ };+ },+ },+ emit: (event: { scrollY: number }) => {+ for (const callback of callbacks) {+ callback(event);+ }+ },+ };+}+function createParagraphBound(partial: Pick<IMutiPageParagraphBound, 'paragraphEnd' | 'paragraphStart' | 'startIndex'>): IMutiPageParagraphBound {const rect = { bottom: 20, left: 10, right: 100, top: 0 };diff --git a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.tsindex 78e3aedfa0..051ab1b400 100644--- a/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-popup-manager.service.spec.ts@@ -15,59 +15,284 @@*/import type { IPopup } from '@univerjs/ui';-import { EventSubject } from '@univerjs/core';+import { EventSubject, ICommandService, Injector, IUniverInstanceService } from '@univerjs/core';+import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';+import { ICanvasPopupService } from '@univerjs/ui';import { describe, expect, it, vi } from 'vitest';-import { DocCanvasPopManagerService } from '../doc-popup-manager.service';+import { SetDocZoomRatioOperation } from '../../commands/operations/set-doc-zoom-ratio.operation';+import {+ DocCanvasPopManagerService,+ transformBound2OffsetBound,+ transformOffset2Bound,+ transformPosition2Offset,+} from '../doc-popup-manager.service';+import { NodePositionConvertToCursor } from '../selection/convert-text-range';-describe('DocCanvasPopManagerService', () => {- it('refreshes rect popup positions after scene scale changes', () => {- let scale = 1;- const onTransformChange$ = new EventSubject();- const onScrollAfter$ = new EventSubject();- let popup: IPopup | undefined;- const removePopup = vi.fn();- const service = new DocCanvasPopManagerService(- {- addPopup: vi.fn((param: IPopup) => {- popup = param;- return 'popup-1';+class TestCanvasPopupService {+ activePopupId = '';+ readonly popups = new Map<string, IPopup>();+ readonly removedIds: string[] = [];+ private _nextId = 1;++ addPopup(param: IPopup) {+ const id = `popup-${this._nextId}`;+ this._nextId++;+ this.activePopupId = id;+ this.popups.set(id, param);+ return id;+ }++ removePopup(id: string) {+ this.removedIds.push(id);+ this.popups.delete(id);+ if (this.activePopupId === id) {+ this.activePopupId = '';+ }+ }+}++class TestRenderManagerService {+ scale = 1;+ hasViewport = true;+ viewportScrollX = 0;+ viewportScrollY = 0;+ readonly onTransformChange$ = new EventSubject();+ readonly onScrollAfter$ = new EventSubject();++ getRenderById(unitId: string) {+ if (unitId === 'missing-doc') {+ return undefined;+ }+ const skeleton = {+ findNodePositionByCharIndex: (index: number) => ({ glyph: index }),+ };++ return {+ unitId,+ engine: {+ getCanvasElement: () => ({+ getBoundingClientRect: () => ({ left: 10, top: 20, width: 1000 }),+ style: { width: '1000px' },}),- removePopup,- activePopupId: 'other-popup',- } as never,- {- getRenderById: () => ({- engine: {- getCanvasElement: () => ({- getBoundingClientRect: () => ({ left: 10, top: 20, width: 1000 }),- style: { width: '1000px' },- }),- },- scene: {- getAncestorScale: () => ({ scaleX: scale, scaleY: scale }),- getViewport: () => ({- onScrollAfter$,- viewportScrollX: 0,- viewportScrollY: 0,- }),- onTransformChange$,- },+ },+ mainComponent: {+ getOffsetConfig: () => ({+ docsLeft: 0,+ docsTop: 0,}),- } as never,- {} as never,- {- onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),- } as never- );+ },+ scene: this.getScene(),+ with: (token: unknown) => {+ if (token === DocSkeletonManagerService) {+ return {+ getSkeleton: () => skeleton,+ };+ }++ throw new Error(`Unexpected render dependency: ${String(token)}`);+ },+ };+ }++ getScene() {+ return {+ getAncestorScale: () => ({ scaleX: this.scale, scaleY: this.scale }),+ getViewport: () => this.hasViewport+ ? ({+ onScrollAfter$: this.onScrollAfter$,+ viewportScrollX: this.viewportScrollX,+ viewportScrollY: this.viewportScrollY,+ })+ : undefined,+ onTransformChange$: this.onTransformChange$,+ };+ }+}++class TestUniverInstanceService {+ getUnit(unitId: string) {+ return unitId === 'missing-doc-data' ? undefined : {};+ }+}++class TestCommandService {+ private readonly _listeners: Array<(commandInfo: { id: string; params?: unknown }) => void> = [];++ onCommandExecuted(listener: (commandInfo: { id: string; params?: unknown }) => void) {+ this._listeners.push(listener);+ return {+ dispose: () => {+ const index = this._listeners.indexOf(listener);+ if (index > -1) {+ this._listeners.splice(index, 1);+ }+ },+ };+ }++ emit(commandId: string, params?: unknown) {+ for (const listener of this._listeners) {+ listener({ id: commandId, params });+ }+ }+}++function createService() {+ const injector = new Injector();+ injector.add([ICanvasPopupService, { useClass: TestCanvasPopupService as never }]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([DocCanvasPopManagerService]);++ return {+ service: injector.get(DocCanvasPopManagerService),+ popupService: injector.get(ICanvasPopupService) as unknown as TestCanvasPopupService,+ renderManagerService: injector.get(IRenderManagerService) as unknown as TestRenderManagerService,+ commandService: injector.get(ICommandService) as unknown as TestCommandService,+ };+}++describe('DocCanvasPopManagerService', () => {+ it('converts between document bounds and viewport offsets with scroll and scale', () => {+ const renderManagerService = new TestRenderManagerService();+ renderManagerService.scale = 2;+ renderManagerService.viewportScrollX = 25;+ renderManagerService.viewportScrollY = 40;+ const scene = renderManagerService.getScene();++ expect(transformPosition2Offset(125, 90, scene as never)).toEqual({ x: 200, y: 100 });+ expect(transformOffset2Bound(200, 100, scene as never)).toEqual({ x: 125, y: 90 });+ expect(transformBound2OffsetBound({ left: 125, right: 225, top: 90, bottom: 140 }, scene as never)).toEqual({+ left: 200,+ right: 400,+ top: 100,+ bottom: 200,+ });+ });++ it('keeps document coordinates unchanged when the render scene has no viewport', () => {+ const renderManagerService = new TestRenderManagerService();+ renderManagerService.hasViewport = false;+ const scene = renderManagerService.getScene();++ expect(transformPosition2Offset(125, 90, scene as never)).toEqual({ x: 125, y: 90 });+ expect(transformOffset2Bound(200, 100, scene as never)).toEqual({ x: 200, y: 100 });+ });++ it('refreshes rect popup positions after scene scale changes', () => {+ const { service, popupService, renderManagerService } = createService();service.attachPopupToRect({ left: 10, right: 110, top: 20, bottom: 40 }, { componentKey: 'test' }, 'doc-1');+ const popup = popupService.popups.get('popup-1');expect(popup?.anchorRect).toEqual({ left: 20, right: 120, top: 40, bottom: 60 });- scale = 1.5;- onTransformChange$.emitEvent({} as never);+ renderManagerService.scale = 1.5;+ renderManagerService.onTransformChange$.emitEvent({} as never);const anchorRect$ = popup?.anchorRect$ as { value?: unknown } | undefined;expect(anchorRect$?.value).toEqual({ left: 25, right: 175, top: 50, bottom: 80 });});++ it('refreshes function-based rect popup anchors after scroll and rich text changes', () => {+ const { service, popupService, renderManagerService, commandService } = createService();+ const rect = { left: 10, right: 110, top: 20, bottom: 40 };++ service.attachPopupToRect(() => rect, { componentKey: 'dynamic-rect' }, 'doc-1');+ const popup = popupService.popups.get('popup-1');+ const anchorRect$ = popup?.anchorRect$ as { value?: unknown } | undefined;++ renderManagerService.viewportScrollX = 20;+ renderManagerService.viewportScrollY = 30;+ renderManagerService.onScrollAfter$.emitEvent({} as never);+ expect(anchorRect$?.value).toEqual({ left: 0, right: 100, top: 10, bottom: 30 });++ rect.left = 30;+ rect.right = 130;+ commandService.emit(RichTextEditingMutation.id);+ expect(anchorRect$?.value).toEqual({ left: 20, right: 120, top: 10, bottom: 30 });+ });++ it('updates object anchored popups after zoom commands and removes popup on dispose', () => {+ const { service, popupService, commandService } = createService();+ const targetObject = { left: 30, top: 40, width: 50, height: 60 };++ const disposable = service.attachPopupToObject(targetObject as never, { componentKey: 'object-menu' }, 'doc-1');+ const popup = popupService.popups.get('popup-1');+ expect(popup?.anchorRect).toEqual({ left: 40, right: 90, top: 60, bottom: 120 });+ expect(disposable.canDispose()).toBe(false);++ targetObject.left = 60;+ targetObject.top = 80;+ commandService.emit(SetDocZoomRatioOperation.id);+ const anchorRect$ = popup?.anchorRect$ as { value?: unknown } | undefined;+ expect(anchorRect$?.value).toEqual({ left: 70, right: 120, top: 100, bottom: 160 });++ popupService.activePopupId = 'another-popup';+ expect(disposable.canDispose()).toBe(true);+ disposable.dispose();+ expect(popupService.removedIds).toEqual(['popup-1']);+ expect(popupService.popups.has('popup-1')).toBe(false);+ });++ it('reports missing renders when a popup cannot be anchored', () => {+ const { service } = createService();++ expect(() => service.attachPopupToRect({ left: 0, right: 1, top: 0, bottom: 1 }, { componentKey: 'missing' }, 'missing-doc'))+ .toThrow('Current render not found, unitId: missing-doc');+ });++ it('reports missing documents and renders before attaching range popups', () => {+ const { service } = createService();+ const range = { startOffset: 0, endOffset: 1, collapsed: false };++ expect(() => service.attachPopupToRange(range, { componentKey: 'missing-doc-data' }, 'missing-doc-data'))+ .toThrow('Document not found, unitId: missing-doc-data');+ expect(() => service.attachPopupToRange(range, { componentKey: 'missing-render' }, 'missing-doc'))+ .toThrow('Current render not found, unitId: missing-doc');+ });++ it('anchors range popups to text bounds and updates them after rich text changes', () => {+ const { service, popupService, commandService } = createService();+ let borderBoxPointGroup = [+ [{ x: 10, y: 10 }, { x: 40, y: 10 }, { x: 40, y: 20 }, { x: 10, y: 20 }],+ [{ x: 12, y: 30 }, { x: 70, y: 30 }, { x: 70, y: 40 }, { x: 12, y: 40 }],+ ];+ const rangeSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockImplementation(() => ({+ borderBoxPointGroup,+ }) as never);+ const emittedAnchors: unknown[] = [];++ const disposable = service.attachPopupToRange(+ { startOffset: 0, endOffset: 4, collapsed: false },+ { componentKey: 'range-menu', direction: 'top', multipleDirection: 'bottom' },+ 'doc-1'+ );+ const popup = popupService.popups.get('popup-1');+ const anchorSubscription = popup?.anchorRect$?.subscribe((anchor) => {+ emittedAnchors.push(anchor);+ });++ expect(popup?.anchorRect).toEqual({ left: 20, right: 50, top: 30, bottom: 40 });+ expect(popup?.excludeRects).toEqual([+ { left: 20, right: 50, top: 30, bottom: 40 },+ { left: 22, right: 80, top: 50, bottom: 60 },+ ]);+ expect(popup?.direction).toBe('bottom');+ expect(emittedAnchors.at(-1)).toEqual({ left: 20, right: 50, top: 30, bottom: 40 });++ borderBoxPointGroup = [+ [{ x: 20, y: 60 }, { x: 90, y: 60 }, { x: 90, y: 80 }, { x: 20, y: 80 }],+ ];+ commandService.emit(RichTextEditingMutation.id, { unitId: 'doc-1' });++ expect(emittedAnchors.at(-1)).toEqual({ left: 30, right: 100, top: 80, bottom: 100 });++ anchorSubscription?.unsubscribe();+ disposable.dispose();+ rangeSpy.mockRestore();+ expect(popupService.removedIds).toContain('popup-1');+ });});diff --git a/packages/docs-ui/src/services/__tests__/doc-print-interceptor.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-print-interceptor.service.spec.tsnew file mode 100644index 0000000000..5bea1793d8--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-print-interceptor.service.spec.ts@@ -0,0 +1,39 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocPrintInterceptorService } from '../doc-print-interceptor.service';++function createService(): DocPrintInterceptorService {+ const injector = new Injector();+ injector.add([DocPrintInterceptorService]);+ return injector.get(DocPrintInterceptorService);+}++describe('DocPrintInterceptorService', () => {+ it('maps editor components to print components and keeps default interceptors pass-through', () => {+ const service = createService();+ const interceptPoints = service.interceptor.getInterceptPoints();+ const domCollection = { dispose: () => {} };++ service.registerPrintComponent('doc-component', 'print-doc-component');++ expect(service.getPrintComponent('doc-component')).toBe('print-doc-component');+ expect(service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_COMPONENT_COLLECT)(undefined, { unitId: 'doc-1' } as never)).toBeUndefined();+ expect(service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_DOM_COLLECT)(domCollection as never, { unitId: 'doc-1' } as never)).toBe(domCollection);+ });+});diff --git a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts b/packages/docs-ui/src/services/__tests__/doc-services.spec.tsdeleted file mode 100644index 21d4923c67..0000000000--- a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts+++ /dev/null@@ -1,373 +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 { IDocumentData, Injector, ITextStyle, Univer } from '@univerjs/core';-import { CustomRangeType, DocumentFlavor, IUniverInstanceService, PresetListType } from '@univerjs/core';-import { DocSelectionManagerService } from '@univerjs/docs';-import { DocumentEditArea } from '@univerjs/engine-render';-import { Subject } from 'rxjs';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';-import { DocAutoFormatService } from '../doc-auto-format.service';-import { getListMarkerFallbackBound, getListMarkerFallbackHit, getListParagraphContextMenuHit, isChecklistListType } from '../doc-event-manager.service';-import { DocMenuStyleService } from '../doc-menu-style.service';-import { DocPrintInterceptorService } from '../doc-print-interceptor.service';-import { DocsRenderService, getDocsCanvasBackgroundColor, resolveDocsCanvasBackground } from '../docs-render.service';--function createDocData(): IDocumentData {- return {- id: 'test-doc',- body: {- dataStream: 'Hello world\rSecond line\r\n',- textRuns: [{- st: 0,- ed: 22,- ts: {},- }],- paragraphs: [{ paragraphId: 'para_docs_ui_fixture_44', startIndex: 11 }, { paragraphId: 'para_docs_ui_fixture_45', startIndex: 23 }],- sectionBreaks: [{- startIndex: 24,- }],- customRanges: [{- startIndex: 6,- endIndex: 10,- rangeId: 'range-world',- rangeType: CustomRangeType.HYPERLINK,- wholeEntity: true,- }],- customBlocks: [],- },- documentStyle: {- pageSize: {- width: 594.3,- height: 840.51,- },- marginTop: 72,- marginBottom: 72,- marginRight: 90,- marginLeft: 90,- },- };-}--describe('docs ui services', () => {- let univer: Univer;- let get: Injector['get'];-- afterEach(() => {- univer?.dispose();- });-- it('detects a list marker fallback hit from paragraph bounds without treating body text as marker', () => {- const paragraph = {- startIndex: 12,- bullet: {- listId: 'list-1',- listType: 'bulletList',- nestingLevel: 0,- },- };- const paragraphBound = {- firstLine: { bottom: 124, left: 160, right: 460, top: 104 },- pageIndex: 0,- rect: { bottom: 128, left: 160, right: 460, top: 100 },- segmentId: undefined,- };-- expect(getListMarkerFallbackBound(paragraphBound, paragraph)).toEqual({- paragraph,- rect: { bottom: 124, left: 160, right: 196, top: 104 },- segmentId: undefined,- segmentPageIndex: 0,- });- expect(getListMarkerFallbackHit(paragraphBound, paragraph, { x: 168, y: 112 })).toEqual({- paragraph,- rect: { bottom: 124, left: 160, right: 196, top: 104 },- segmentId: undefined,- segmentPageIndex: 0,- });- expect(getListMarkerFallbackHit(paragraphBound, paragraph, { x: 240, y: 112 })).toBeNull();- expect(getListMarkerFallbackHit(paragraphBound, { startIndex: 12 }, { x: 168, y: 112 })).toBeNull();- });-- it('does not treat list paragraph body hits as list marker context menu hits', () => {- const paragraph = {- startIndex: 12,- bullet: {- listId: 'list-1',- listType: 'bulletList',- nestingLevel: 0,- },- };- const paragraphBound = {- firstLine: { bottom: 124, left: 160, right: 460, top: 104 },- pageIndex: 0,- rect: { bottom: 128, left: 160, right: 460, top: 100 },- segmentId: undefined,- };-- expect(getListMarkerFallbackHit(paragraphBound, paragraph, { x: 260, y: 112 })).toBeNull();- expect(getListParagraphContextMenuHit(paragraphBound, paragraph, { x: 260, y: 112 })).toBeNull();- expect(getListParagraphContextMenuHit(paragraphBound, paragraph, { x: 260, y: 180 })).toBeNull();- expect(getListParagraphContextMenuHit(paragraphBound, { startIndex: 12 }, { x: 260, y: 112 })).toBeNull();- });-- it('identifies checklist list types separately from interactive list markers', () => {- expect(isChecklistListType(PresetListType.CHECK_LIST)).toBe(true);- expect(isChecklistListType(PresetListType.CHECK_LIST_CHECKED)).toBe(true);- expect(isChecklistListType(PresetListType.BULLET_LIST)).toBe(false);- expect(isChecklistListType(PresetListType.ORDER_LIST)).toBe(false);- });-- it('matches auto-format handlers by priority and builds context from the current selection', () => {- ({ univer, get } = createCommandTestBed(createDocData()));- const selectionManager = get(DocSelectionManagerService);- const univerInstanceService = get(IUniverInstanceService);- const service = new DocAutoFormatService(univerInstanceService, selectionManager);- let highPriorityContext: Record<string, unknown> | null = null;-- selectionManager.__TEST_ONLY_setCurrentSelection({- unitId: 'test-doc',- subUnitId: 'test-doc',- });- selectionManager.__TEST_ONLY_add([{- startOffset: 0,- endOffset: 12,- collapsed: false,- isActive: true,- segmentId: '',- style: null as never,- }]);-- const lowPriority = service.registerAutoFormat({- id: 'doc.command.tab',- priority: 1,- match: () => true,- getMutations: () => [{ id: 'low-priority' }],- });- const highPriority = service.registerAutoFormat({- id: 'doc.command.tab',- priority: 10,- match: (context) => {- highPriorityContext = {- isBody: context.isBody,- paragraphCount: context.paragraphs.length,- customRangeCount: context.customRanges.length,- commandParams: context.commandParams,- };- return true;- },- getMutations: () => [{ id: 'high-priority' }],- });-- expect(service.onAutoFormat('doc.command.tab', { shift: false })).toEqual([{ id: 'high-priority' }]);- expect(highPriorityContext).toEqual({- isBody: true,- paragraphCount: 2,- customRangeCount: 1,- commandParams: { shift: false },- });-- highPriority.dispose();- expect(service.onAutoFormat('doc.command.tab', null)).toEqual([{ id: 'low-priority' }]);-- lowPriority.dispose();- expect(service.onAutoFormat('doc.command.tab', null)).toEqual([]);- });-- it('returns no auto-format mutations when the current selection is unavailable', () => {- ({ univer, get } = createCommandTestBed(createDocData()));- const service = new DocAutoFormatService(get(IUniverInstanceService), get(DocSelectionManagerService));-- expect(service.onAutoFormat('doc.command.tab', null)).toEqual([]);- });-- it('merges cached menu styles, clears them on selection changes, and derives body/header defaults', () => {- ({ univer, get } = createCommandTestBed(createDocData()));- const selectionManager = get(DocSelectionManagerService);- const univerInstanceService = get(IUniverInstanceService);- const bodyRenderManagerService = {- getRenderById: vi.fn(() => ({- with: vi.fn(() => ({- getViewModel: () => ({- getEditArea: () => DocumentEditArea.BODY,- }),- })),- })),- };- const headerRenderManagerService = {- getRenderById: vi.fn(() => ({- with: vi.fn(() => ({- getViewModel: () => ({- getEditArea: () => DocumentEditArea.HEADER,- }),- })),- })),- };- const bodyService = new DocMenuStyleService(- selectionManager,- univerInstanceService,- bodyRenderManagerService as never- );- const headerService = new DocMenuStyleService(- selectionManager,- univerInstanceService,- headerRenderManagerService as never- );- const fallbackService = new DocMenuStyleService(- selectionManager,- {- getCurrentUnitOfType: () => null,- } as never,- {- getRenderById: vi.fn(() => null),- } as never- );-- bodyService.setStyleCache({ bl: 1 } as ITextStyle);- bodyService.setStyleCache({ it: 1 } as ITextStyle);-- expect(bodyService.getStyleCache()).toEqual({ bl: 1, it: 1 });- expect(bodyService.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 11 });- expect(headerService.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 9 });- expect(fallbackService.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 11 });-- (selectionManager as unknown as { _textSelection$: { next: (value: unknown) => void } })._textSelection$.next({});-- expect(bodyService.getStyleCache()).toBeNull();- });-- it('creates and disposes renderers for current, added, and removed docs', () => {- const createRender$ = new Subject<string>();- const created$ = new Subject<Record<string, unknown>>();- const added$ = new Subject<{ unit: Record<string, unknown> }>();- const disposed$ = new Subject<Record<string, unknown>>();- const existingDoc = {- getUnitId: () => 'doc-1',- getSnapshot: () => ({ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL } }),- };- const addedDoc = {- getUnitId: () => 'doc-2',- getSnapshot: () => ({ documentStyle: { documentFlavor: DocumentFlavor.MODERN } }),- };- const removedDoc = { getUnitId: () => 'doc-3' };- const canvasElement = { style: {} as Record<string, string> };- const canvas = { setId: vi.fn(), getCanvasEle: vi.fn(() => canvasElement) };- const modernCanvasElement = { style: {} as Record<string, string> };- const modernCanvas = { setId: vi.fn(), getCanvasEle: vi.fn(() => modernCanvasElement) };- const context = { setId: vi.fn() };- const renderManagerService = {- createRender$,- created$,- has: vi.fn(() => false),- createRender: vi.fn(),- removeRender: vi.fn(),- };- const instanceService = {- getAllUnitsForType: vi.fn(() => [existingDoc]),- getCurrentUnitOfType: vi.fn(() => existingDoc),- getTypeOfUnitAdded$: vi.fn(() => added$),- getTypeOfUnitDisposed$: vi.fn(() => disposed$),- };-- const service = new DocsRenderService(instanceService as never, renderManagerService as never);-- expect(service).toBeInstanceOf(DocsRenderService);- expect(renderManagerService.createRender).toHaveBeenCalledWith('doc-1');-- created$.next({- unitId: 'doc-1',- engine: {- getCanvas: () => ({- ...canvas,- getContext: () => context,- }),- },- });-- expect(canvas.setId).toHaveBeenCalledWith('univer-doc-main-canvas');- expect(context.setId).toHaveBeenCalledWith('univer-doc-main-canvas');- expect(canvasElement.style.backgroundColor).toBe('#fafafa');-- added$.next({ unit: addedDoc });- created$.next({- unitId: 'doc-2',- engine: {- getCanvas: () => ({- ...modernCanvas,- getContext: () => context,- }),- },- });-- expect(modernCanvas.setId).toHaveBeenCalledWith('univer-doc-main-canvas');- expect(modernCanvasElement.style.backgroundColor).toBe('#fff');-- createRender$.next('doc-4');- disposed$.next(removedDoc);-- expect(renderManagerService.createRender).toHaveBeenCalledWith('doc-2');- expect(renderManagerService.createRender).toHaveBeenCalledWith('doc-4');- expect(renderManagerService.removeRender).toHaveBeenCalledWith('doc-3');- });-- it('resolves the docs canvas background through the canvas color service', () => {- const canvasColorService = {- getRenderColor: vi.fn((color: string) => `rendered:${color}`),- };-- expect(getDocsCanvasBackgroundColor(DocumentFlavor.MODERN, canvasColorService as never)).toBe('rendered:#fff');- expect(getDocsCanvasBackgroundColor(DocumentFlavor.TRADITIONAL, canvasColorService as never)).toBe('rendered:#fafafa');- expect(getDocsCanvasBackgroundColor(DocumentFlavor.MODERN, canvasColorService as never, '#123456')).toBe('rendered:#123456');- expect(getDocsCanvasBackgroundColor(DocumentFlavor.UNSPECIFIED, canvasColorService as never, '#fff', true)).toBe('#fff');- expect(resolveDocsCanvasBackground({- documentFlavor: DocumentFlavor.UNSPECIFIED,- canvasColorService: canvasColorService as never,- editorBackgroundColor: '#fff',- isEditor: true,- })).toEqual({- canvasElementBackgroundColor: '#fff',- docBackgroundFillColor: 'transparent',- });- expect(resolveDocsCanvasBackground({- documentFlavor: DocumentFlavor.UNSPECIFIED,- canvasColorService: canvasColorService as never,- isEditor: true,- })).toEqual({- canvasElementBackgroundColor: 'transparent',- docBackgroundFillColor: 'transparent',- });- });-- it('keeps print interceptor defaults as pass-through and stores component mappings', () => {- const service = new DocPrintInterceptorService();- const interceptPoints = service.interceptor.getInterceptPoints();- const domCollection = { dispose: vi.fn() };-- service.registerPrintComponent('doc-component', 'print-doc-component');-- const collectComponents = service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_COMPONENT_COLLECT);- const collectDom = service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_DOM_COLLECT);-- expect(service.getPrintComponent('doc-component')).toBe('print-doc-component');- expect(collectComponents(undefined, {- unitId: 'test-doc',- } as never)).toBeUndefined();- expect(collectDom(domCollection as never, {- unitId: 'test-doc',- } as never)).toBe(domCollection);- });-});diff --git a/packages/docs-ui/src/services/__tests__/docs-render.service.spec.ts b/packages/docs-ui/src/services/__tests__/docs-render.service.spec.tsnew file mode 100644index 0000000000..570e6c2f39--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/docs-render.service.spec.ts@@ -0,0 +1,180 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ ContextService,+ DesktopLogService,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ DocumentDataModel,+ DocumentFlavor,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ ThemeService,+ UniverInstanceService,+} from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { Subject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { DocsRenderService, getDocsCanvasBackgroundColor } from '../docs-render.service';++class TestUniverInstanceService {+ private readonly _added$ = new Subject<{ unit: DocumentDataModel }>();+ private readonly _disposed$ = new Subject<DocumentDataModel>();+ private readonly _units = [+ new DocumentDataModel({+ id: 'doc-existing',+ documentStyle: { documentFlavor: DocumentFlavor.MODERN },+ }),+ ];++ getAllUnitsForType() {+ return this._units;+ }++ getTypeOfUnitAdded$() {+ return this._added$.asObservable();+ }++ getTypeOfUnitDisposed$() {+ return this._disposed$.asObservable();+ }++ addUnit(unit: DocumentDataModel) {+ this._units.push(unit);+ this._added$.next({ unit });+ }++ disposeUnit(unit: DocumentDataModel) {+ this._disposed$.next(unit);+ }+}++class TestCanvas {+ readonly style = { backgroundColor: '' };+ id = '';+ contextId = '';++ setId(id: string) {+ this.id = id;+ }++ getContext() {+ return {+ setId: (id: string) => {+ this.contextId = id;+ },+ };+ }++ getCanvasEle() {+ return { style: this.style };+ }+}++class TestRenderManagerService {+ readonly createRender$ = new Subject<string>();+ readonly created$ = new Subject<{ unitId: string; engine: { getCanvas: () => TestCanvas; canvasColorService: undefined } }>();+ readonly createdUnitIds: string[] = [];+ readonly removedUnitIds: string[] = [];+ readonly canvases = new Map<string, TestCanvas>();++ createRender(unitId: string) {+ this.createdUnitIds.push(unitId);+ }++ has(unitId: string) {+ return this.createdUnitIds.includes(unitId);+ }++ removeRender(unitId: string) {+ this.removedUnitIds.push(unitId);+ }++ emitCreated(unitId: string) {+ const canvas = new TestCanvas();+ this.canvases.set(unitId, canvas);+ this.created$.next({+ unitId,+ engine: {+ getCanvas: () => canvas,+ canvasColorService: undefined,+ },+ });+ }+}++function createService(): DocsRenderService {+ const injector = new Injector();+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ThemeService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([DocsRenderService]);+ return injector.get(DocsRenderService);+}++function createLifecycleService() {+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([DocsRenderService]);+ return {+ service: injector.get(DocsRenderService),+ instanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,+ renderManagerService: injector.get(IRenderManagerService) as unknown as TestRenderManagerService,+ };+}++describe('DocsRenderService', () => {+ it('can start render lifecycle listening when there are no existing docs', () => {+ const service = createService();++ expect(() => service.dispose()).not.toThrow();+ });++ it('uses document flavor to choose the doc canvas background', () => {+ expect(getDocsCanvasBackgroundColor(DocumentFlavor.MODERN)).toBe('#fff');+ expect(getDocsCanvasBackgroundColor(DocumentFlavor.TRADITIONAL)).toBe('#fafafa');+ expect(getDocsCanvasBackgroundColor()).toBe('#fafafa');+ });++ it('creates renderers for document lifecycle changes and styles doc canvases', () => {+ const { service, instanceService, renderManagerService } = createLifecycleService();++ renderManagerService.emitCreated('doc-existing');+ expect(renderManagerService.createdUnitIds).toEqual(['doc-existing']);+ expect(renderManagerService.canvases.get('doc-existing')?.id).toBe('univer-doc-main-canvas');+ expect(renderManagerService.canvases.get('doc-existing')?.contextId).toBe('univer-doc-main-canvas');+ expect(renderManagerService.canvases.get('doc-existing')?.style.backgroundColor).toBe('#fff');++ const editorDoc = new DocumentDataModel({+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ documentStyle: { documentFlavor: DocumentFlavor.TRADITIONAL },+ });+ instanceService.addUnit(editorDoc);+ renderManagerService.emitCreated(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);+ expect(renderManagerService.createdUnitIds).toEqual(['doc-existing', DOCS_NORMAL_EDITOR_UNIT_ID_KEY]);+ expect(renderManagerService.canvases.get(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.style.backgroundColor).toBe('transparent');++ instanceService.disposeUnit(editorDoc);+ expect(renderManagerService.removedUnitIds).toEqual([DOCS_NORMAL_EDITOR_UNIT_ID_KEY]);++ service.dispose();+ });+});diff --git a/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.tsnew file mode 100644index 0000000000..1f7ce9a979--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/float-menu.service.spec.ts@@ -0,0 +1,362 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ CommandService,+ ConfigService,+ ContextService,+ CustomRangeType,+ DataStreamTreeTokenType,+ DesktopLogService,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ DocumentBlockRangeType,+ DocumentDataModel,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ RANGE_DIRECTION,+ UniverInstanceService,+} from '@univerjs/core';+import { DocSelectionManagerService, SetTextSelectionsOperation } from '@univerjs/docs';+import { NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';+import { ComponentManager } from '@univerjs/ui';+import { Subject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { DocCanvasPopManagerService } from '../doc-popup-manager.service';+import { DocFloatMenuService } from '../float-menu.service';+import { DocSelectionRenderService } from '../selection/doc-selection-render.service';++class InertDocCanvasPopManagerService {+ attachPopupToRange() {+ throw new Error('Internal editors should not attach float menu popups.');+ }+}++class InertDocSelectionRenderService {+ onSelectionStart$ = new Subject().asObservable();+}++class RecordingDocCanvasPopManagerService {+ readonly ranges: string[] = [];+ readonly directions: string[] = [];+ disposedCount = 0;++ attachPopupToRange(range: { startOffset: number; endOffset: number }, options: { direction: string }) {+ this.ranges.push(`${range.startOffset}:${range.endOffset}`);+ this.directions.push(options.direction);++ return {+ dispose: () => {+ this.disposedCount++;+ },+ };+ }+}++class ActiveDocSelectionRenderService {+ private readonly _selectionStart$ = new Subject<void>();+ readonly onSelectionStart$ = this._selectionStart$.asObservable();++ emitSelectionStart() {+ this._selectionStart$.next();+ }+}++const InertDocCanvasPopManagerServiceCtor = InertDocCanvasPopManagerService as unknown as typeof DocCanvasPopManagerService;+const InertDocSelectionRenderServiceCtor = InertDocSelectionRenderService as unknown as typeof DocSelectionRenderService;+const RecordingDocCanvasPopManagerServiceCtor = RecordingDocCanvasPopManagerService as unknown as typeof DocCanvasPopManagerService;+const ActiveDocSelectionRenderServiceCtor = ActiveDocSelectionRenderService as unknown as typeof DocSelectionRenderService;++function createActiveFloatMenuHarness(unitId: string, body: ConstructorParameters<typeof DocumentDataModel>[0]['body']) {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocCanvasPopManagerService, { useClass: RecordingDocCanvasPopManagerServiceCtor }]);+ injector.add([ComponentManager]);+ injector.add([DocSelectionRenderService, { useClass: ActiveDocSelectionRenderServiceCtor }]);+ injector.get(ICommandService).registerCommand(SetTextSelectionsOperation);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({ id: unitId, body }));+ const service = injector.createInstance(DocFloatMenuService, { unitId } as never);+ const selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId, subUnitId: unitId });++ return {+ injector,+ popupService: injector.get(DocCanvasPopManagerService) as unknown as RecordingDocCanvasPopManagerService,+ selectionManager,+ service,+ univerInstanceService,+ };+}++describe('DocFloatMenuService', () => {+ it('does not register or show a floating toolbar inside internal document editors', () => {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocCanvasPopManagerService, { useClass: InertDocCanvasPopManagerServiceCtor }]);+ injector.add([ComponentManager]);+ injector.add([DocSelectionRenderService, { useClass: InertDocSelectionRenderServiceCtor }]);++ const service = injector.createInstance(DocFloatMenuService, { unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY } as never);++ expect(service.floatMenu).toBeNull();+ expect(injector.get(ComponentManager).get('univer.doc.float-menu')).toBeUndefined();+ });++ it('shows one floating toolbar for a text selection and hides it when selection restarts', () => {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocCanvasPopManagerService, { useClass: RecordingDocCanvasPopManagerServiceCtor }]);+ injector.add([ComponentManager]);+ injector.add([DocSelectionRenderService, { useClass: ActiveDocSelectionRenderServiceCtor }]);+ const commandService = injector.get(ICommandService);+ commandService.registerCommand(SetTextSelectionsOperation);+ const unitId = 'doc-float-menu';+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: unitId,+ body: {+ dataStream: 'Hello world\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_float_menu_fixture_1', startIndex: 11 }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ }));++ const service = injector.createInstance(DocFloatMenuService, { unitId } as never);+ const selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId, subUnitId: unitId });+ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });+ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });++ const popupService = injector.get(DocCanvasPopManagerService) as unknown as RecordingDocCanvasPopManagerService;+ expect(popupService.ranges).toEqual(['0:5']);+ expect(service.floatMenu).toMatchObject({ start: 0, end: 5 });++ const selectionRenderService = injector.get(DocSelectionRenderService) as unknown as ActiveDocSelectionRenderService;+ selectionRenderService.emitSelectionStart();+ expect(service.floatMenu).toBeNull();+ expect(popupService.disposedCount).toBe(1);+ });++ it('does not show the floating toolbar for selections inside code blocks', () => {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocCanvasPopManagerService, { useClass: RecordingDocCanvasPopManagerServiceCtor }]);+ injector.add([ComponentManager]);+ injector.add([DocSelectionRenderService, { useClass: ActiveDocSelectionRenderServiceCtor }]);+ injector.get(ICommandService).registerCommand(SetTextSelectionsOperation);+ const unitId = 'doc-code-menu';+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: unitId,+ body: {+ dataStream: 'const x = 1;\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_float_menu_fixture_2', startIndex: 12 }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ blockRanges: [{+ blockType: DocumentBlockRangeType.CODE,+ startIndex: 0,+ endIndex: 12,+ blockId: 'code-1',+ }],+ },+ }));++ const service = injector.createInstance(DocFloatMenuService, { unitId } as never);+ const selectionManager = injector.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId, subUnitId: unitId });+ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });++ const popupService = injector.get(DocCanvasPopManagerService) as unknown as RecordingDocCanvasPopManagerService;+ expect(service.floatMenu).toBeNull();+ expect(popupService.ranges).toEqual([]);+ });++ it('skips document control tokens and whole custom ranges when deciding whether text needs a toolbar', () => {+ const unitId = 'doc-token-menu';+ const { popupService, selectionManager, service } = createActiveFloatMenuHarness(unitId, {+ dataStream: `A${DataStreamTreeTokenType.PARAGRAPH}Link\r\n`,+ paragraphs: [{ paragraphId: 'para_docs_ui_float_menu_fixture_3', startIndex: 6 }],+ sectionBreaks: [],+ customRanges: [{+ startIndex: 2,+ endIndex: 5,+ rangeId: 'hyperlink-1',+ rangeType: CustomRangeType.HYPERLINK,+ wholeEntity: true,+ }],+ tables: [],+ textRuns: [],+ });++ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 1,+ endOffset: 2,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });+ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 2,+ endOffset: 6,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });++ expect(service.floatMenu).toBeNull();+ expect(popupService.ranges).toEqual([]);+ });++ it('does not show the floating toolbar when the document is disabled', () => {+ const unitId = 'doc-disabled-menu';+ const { popupService, selectionManager, service, univerInstanceService } = createActiveFloatMenuHarness(unitId, {+ dataStream: 'Locked text\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_float_menu_fixture_4', startIndex: 11 }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ });+ univerInstanceService.getUnit<DocumentDataModel>(unitId)?.setDisabled(true);++ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 6,+ collapsed: false,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });++ expect(service.floatMenu).toBeNull();+ expect(popupService.ranges).toEqual([]);+ });++ it('places the floating toolbar below a forward selection that spans multiple lines', () => {+ const unitId = 'doc-direction-menu';+ const { popupService, selectionManager, service } = createActiveFloatMenuHarness(unitId, {+ dataStream: 'First line\rSecond line\r\n',+ paragraphs: [+ { paragraphId: 'para_docs_ui_float_menu_fixture_5', startIndex: 10 },+ { paragraphId: 'para_docs_ui_float_menu_fixture_6', startIndex: 22 },+ ],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ });++ selectionManager.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 0,+ endOffset: 18,+ collapsed: false,+ direction: RANGE_DIRECTION.FORWARD,+ startNodePosition: { page: 0, section: 0, column: 0, line: 0, divide: 0, glyph: 0, isBack: false } as never,+ endNodePosition: { page: 0, section: 0, column: 0, line: 1, divide: 0, glyph: 4, isBack: false } as never,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId, subUnitId: unitId });++ expect(service.floatMenu).toMatchObject({ start: 0, end: 18 });+ expect(popupService.ranges).toEqual(['0:18']);+ expect(popupService.directions).toEqual(['bottom-center']);++ service.dispose();+ expect(popupService.disposedCount).toBe(1);+ });+});diff --git a/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts b/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.tsindex 09b7425ac2..1363de9b22 100644--- a/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__test__/clipboard.service.spec.ts@@ -14,12 +14,44 @@* limitations under the License.*/-import type { IDocumentBody, IDocumentData } from '@univerjs/core';-import type { IRectRangeWithStyle } from '@univerjs/engine-render';-import { DataStreamTreeTokenType, DOC_RANGE_TYPE } from '@univerjs/core';+import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';+import type { IRectRangeWithStyle, ITextRangeWithStyle } from '@univerjs/engine-render';+import {+ BooleanNumber,+ DataStreamTreeTokenType,+ DOC_RANGE_TYPE,+ ICommandService,+ IUniverInstanceService,+ UniverInstanceType,+} from '@univerjs/core';+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';import { ImageSourceType } from '@univerjs/drawing';+import { IClipboardInterfaceService } from '@univerjs/ui';import { describe, expect, it, vi } from 'vitest';-import { DocClipboardService, getTableClipboardBodySlice } from '../clipboard.service';+import { createCommandTestBed } from '../../../commands/commands/__tests__/create-command-test-bed';+import { CutContentCommand, InnerPasteCommand } from '../../../commands/commands/clipboard.inner.command';+import { DocClipboardService, getTableClipboardBodySlice, IDocClipboardService } from '../clipboard.service';+import {+ createInternalClipboardFragment,+ DOC_INTERNAL_FRAGMENT_MIME,+ parseInternalClipboardFragment,+} from '../internal-fragment';++class TestClipboardInterfaceService {+ readonly writes: Array<{ text: string; html: string; custom?: Record<string, string> }> = [];++ get supportClipboard(): boolean {+ return true;+ }++ async writeText(): Promise<void> {}+ async write(text: string, html: string, custom?: Record<string, string>): Promise<void> {+ this.writes.push({ text, html, custom });+ }++ async readText(): Promise<string> { return ''; }+ async read(): Promise<ClipboardItem[]> { return []; }+}describe('DocClipboardService table copy helpers', () => {it('should keep table metadata when copying an entire selected docs table', () => {@@ -68,46 +100,597 @@ describe('DocClipboardService table copy helpers', () => {}]);});- it('should upload base64 images embedded in pasted html before converting to docs drawings', async () => {- let pastedDoc: Partial<IDocumentData> | undefined;- const executeCommand = vi.fn(async (_id, params) => {- pastedDoc = params.doc;- return true;+ it('wraps a copied table cell as a standalone table fragment', () => {+ const tokens = DataStreamTreeTokenType;+ const tableStream = `${tokens.TABLE_START}${tokens.TABLE_ROW_START}${tokens.TABLE_CELL_START}A\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_CELL_START}B\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_ROW_END}${tokens.TABLE_END}`;+ const dataStream = `Intro\r${tableStream}Tail\r`;+ const cellStart = 'Intro\r'.length + tokens.TABLE_START.length + tokens.TABLE_ROW_START.length + tokens.TABLE_CELL_START.length;+ const body: IDocumentBody = {+ dataStream,+ paragraphs: [+ { paragraphId: 'para_docs_ui_clipboard_table_fixture_1', startIndex: cellStart + 1 },+ { paragraphId: 'para_docs_ui_clipboard_table_fixture_2', startIndex: dataStream.length - 1 },+ ],+ sectionBreaks: [],+ textRuns: [{ st: cellStart, ed: cellStart + 1, ts: { bl: BooleanNumber.TRUE } }],+ tables: [{+ startIndex: 'Intro\r'.length,+ endIndex: 'Intro\r'.length + tableStream.length,+ tableId: 'table-1',+ }],+ };+ const slice = getTableClipboardBodySlice(body, {+ startOffset: cellStart,+ endOffset: cellStart + 1,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ tableId: 'table-1',+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+ spanEntireRow: false,+ spanEntireColumn: false,+ spanEntireTable: false,});- const uploadImage = vi.fn(async (file: File) => {- expect(file.type).toBe('image/png');- return {- imageSourceType: ImageSourceType.UUID,- source: 'remote-file-id',- };- });- const service = new DocClipboardService(- { getCurrentUnitOfType: () => ({ getUnitId: () => 'doc-1' }) } as any,- { error: vi.fn(), warn: vi.fn() } as any,- { executeCommand } as any,- {} as any,+ expect(slice.dataStream).toBe(`${tokens.TABLE_START}${tokens.TABLE_ROW_START}${tokens.TABLE_CELL_START}A\r\n${tokens.TABLE_CELL_END}${tokens.TABLE_ROW_END}${tokens.TABLE_END}`);+ expect(slice.textRuns?.[0]).toMatchObject({ st: 3, ed: 4, ts: { bl: BooleanNumber.TRUE } });+ expect(slice.paragraphs?.[0].startIndex).toBe(4);+ });++ it('copies the selected document text as plain text, html, and internal clipboard data', async () => {+ const documentData: IDocumentData = {+ id: 'copy-doc',+ body: {+ dataStream: 'Alpha\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_2', startIndex: 5 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'copy-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ isActive: true,+ segmentId: '',+ }]);++ const service = testBed.get(IDocClipboardService);+ const copied = await service.copy();+ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const internalDoc = parseInternalClipboardFragment(clipboard.writes[0].custom?.[DOC_INTERNAL_FRAGMENT_MIME]);++ expect(copied).toBe(true);+ expect(clipboard.writes[0].text).toBe('Alpha');+ expect(clipboard.writes[0].html).toContain('data-copy-id=');+ expect(clipboard.writes[0].html).toContain('<!--univer-doc-fragment:');+ expect(internalDoc?.body?.dataStream).toBe('Alpha');++ testBed.univer.dispose();+ });++ it('copies multiple selected text ranges in document order', async () => {+ const documentData: IDocumentData = {+ id: 'multi-copy-doc',+ body: {+ dataStream: 'Alpha Beta\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_8', startIndex: 10 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const ranges: ITextRangeWithStyle[] = [{- getActiveTextRange: () => ({ segmentId: '', endOffset: 0 }),- getTextRanges: () => [{ startOffset: 0, endOffset: 0 }],- } as any- ) as DocClipboardService;+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.TEXT,+ segmentId: '',+ },+ {+ startOffset: 6,+ endOffset: 10,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.TEXT,+ segmentId: '',+ },+ ];+ const service = testBed.get(IDocClipboardService);++ expect(await service.copy(undefined, ranges)).toBe(true);++ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const internalDoc = parseInternalClipboardFragment(clipboard.writes[0].custom?.[DOC_INTERNAL_FRAGMENT_MIME]);++ expect(clipboard.writes[0].text).toBe('Alpha\nBeta');+ expect(internalDoc?.body?.dataStream).toBe('AlphaBeta');++ testBed.univer.dispose();+ });++ it('leaves the document and clipboard unchanged when cut has no selected content', async () => {+ const documentData: IDocumentData = {+ id: 'empty-cut-doc',+ body: {+ dataStream: 'Keep me\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_9', startIndex: 7 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const service = testBed.get(IDocClipboardService);++ expect(await service.cut([])).toBe(false);++ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('empty-cut-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(clipboard.writes).toEqual([]);+ expect(documentModel.getBody()?.dataStream).toBe('Keep me\r\n');++ testBed.univer.dispose();+ });++ it('cuts the selected text and places that text on the clipboard', async () => {+ const documentData: IDocumentData = {+ id: 'cut-doc',+ body: {+ dataStream: 'Cut me now\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_5', startIndex: 10 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(CutContentCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'cut-doc', subUnitId: '' });+ const ranges: ITextRangeWithStyle[] = [{+ startOffset: 0,+ endOffset: 3,+ collapsed: false,+ isActive: true,+ segmentId: '',+ rangeType: DOC_RANGE_TYPE.TEXT,+ }];+ selectionManager.__TEST_ONLY_add(ranges);++ const service = testBed.get(IDocClipboardService);+ expect(await service.cut(ranges)).toBe(true);++ const clipboard = testBed.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;+ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('cut-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(clipboard.writes[0].text).toBe('Cut');+ expect(documentModel.getBody()?.dataStream).toBe(' me now\r\n');++ testBed.univer.dispose();+ });++ it('pastes browser html clipboard content into the active document', async () => {+ const documentData: IDocumentData = {+ id: 'html-clipboard-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_13', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'html-clipboard-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 4,+ endOffset: 4,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const clipboardItem = {+ types: ['text/html', 'text/plain'],+ presentationStyle: 'unspecified',+ getType: async (type: string) => new Blob([+ type === 'text/html' ? '<p>HTML clipboard</p>' : 'Plain clipboard',+ ], { type }),+ } as ClipboardItem;+ const service = testBed.get(IDocClipboardService);++ expect(await service.paste([clipboardItem])).toBe(true);++ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('html-clipboard-doc', UniverInstanceType.UNIVER_DOC)!;+ expect(documentModel.getBody()?.dataStream).toContain('HTML clipboard');++ testBed.univer.dispose();+ });++ it('pastes Univer internal clipboard data with document styles preserved', async () => {+ const documentData: IDocumentData = {+ id: 'internal-paste-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_6', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'internal-paste-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 4,+ endOffset: 4,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const internalJson = createInternalClipboardFragment({+ body: {+ dataStream: 'Styled\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_7', startIndex: 6 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [{+ st: 0,+ ed: 6,+ ts: { bl: BooleanNumber.TRUE },+ }],+ },+ });+ const clipboardItem = {+ types: [DOC_INTERNAL_FRAGMENT_MIME, 'text/plain'],+ presentationStyle: 'unspecified',+ getType: async (type: string) => new Blob([+ type === DOC_INTERNAL_FRAGMENT_MIME ? internalJson : 'Ignored',+ ], { type }),+ } as ClipboardItem;+ const service = testBed.get(IDocClipboardService);++ expect(await service.paste([clipboardItem])).toBe(true);++ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('internal-paste-doc', UniverInstanceType.UNIVER_DOC)!;+ const body = documentModel.getBody();+ let styledTextRunBold: BooleanNumber | undefined;+ for (const textRun of body?.textRuns ?? []) {+ if (textRun.st <= 4 && textRun.ed >= 10) {+ styledTextRunBold = textRun.ts?.bl;+ break;+ }+ }++ expect(body?.dataStream).toContain('BodyStyled');+ expect(styledTextRunBold).toBe(BooleanNumber.TRUE);++ testBed.univer.dispose();+ });++ it('uploads base64 images from pasted html and inserts remote drawings into the document', async () => {+ const documentData: IDocumentData = {+ id: 'test-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_1', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ drawings: {},+ drawingsOrder: [],+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'test-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const service = testBed.get(IDocClipboardService);const source = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lz6N4wAAAABJRU5ErkJggg==';- service.addClipboardHook({ onBeforePasteImage: uploadImage });+ service.addClipboardHook({+ async onBeforePasteImage(file: File) {+ expect(file.type).toBe('image/png');+ return {+ imageSourceType: ImageSourceType.UUID,+ source: 'remote-file-id',+ };+ },+ });await service.legacyPaste({html: `<p><img src="${source}" width="2" height="3"></p>`,files: [],});- const block = pastedDoc?.body?.customBlocks?.[0];- const drawing = block ? pastedDoc?.drawings?.[block.blockId] : undefined;+ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;+ const snapshot = documentModel.getSnapshot();+ const blocks = snapshot.body?.customBlocks ?? [];+ let drawingSource = '';+ for (const block of blocks) {+ const drawing = snapshot.drawings?.[block.blockId];+ const imageDrawing = drawing as { source?: string } | undefined;+ if (imageDrawing?.source === 'remote-file-id') {+ drawingSource = imageDrawing.source;+ }+ }++ expect(drawingSource).toBe('remote-file-id');+ expect(JSON.stringify(snapshot)).not.toContain('data:image');++ testBed.univer.dispose();+ });++ it('turns pasted image files into inline document drawings through the image paste hook', async () => {+ class TestImage {+ naturalWidth = 20;+ naturalHeight = 10;+ private _onload: (() => void) | null = null;++ set src(_value: string) {+ queueMicrotask(() => this._onload?.());+ }- expect(uploadImage).toHaveBeenCalledTimes(1);- expect(drawing).toMatchObject({- imageSourceType: ImageSourceType.UUID,- source: 'remote-file-id',+ set onload(value: (() => void) | null) {+ this._onload = value;+ }+ }+ vi.stubGlobal('Image', TestImage);+ vi.stubGlobal('URL', { ...URL, createObjectURL: () => 'blob:local-image' });+ const documentData: IDocumentData = {+ id: 'file-image-paste-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_14', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ drawings: {},+ drawingsOrder: [],+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ try {+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'file-image-paste-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const service = testBed.get(IDocClipboardService);+ service.addClipboardHook({+ async onBeforePasteImage(file: File) {+ expect(file.name).toBe('local.png');+ expect(file.type).toBe('image/png');+ return {+ imageSourceType: ImageSourceType.UUID,+ source: 'remote-local-file-id',+ };+ },+ });++ expect(await service.legacyPaste({+ files: [new File(['image'], 'local.png', { type: 'image/png' })],+ })).toBe(true);++ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('file-image-paste-doc', UniverInstanceType.UNIVER_DOC)!;+ const snapshot = documentModel.getSnapshot();+ let drawingSource = '';+ for (const drawing of Object.values(snapshot.drawings ?? {})) {+ const imageDrawing = drawing as { source?: string } | undefined;+ if (imageDrawing?.source === 'remote-local-file-id') {+ drawingSource = imageDrawing.source;+ break;+ }+ }++ expect(drawingSource).toBe('remote-local-file-id');+ } finally {+ testBed.univer.dispose();+ vi.unstubAllGlobals();+ }+ });++ it('applies before-paste hooks to plain text before inserting it into the document', async () => {+ const documentData: IDocumentData = {+ id: 'paste-hook-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_3', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'paste-hook-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const service = testBed.get(IDocClipboardService);++ service.addClipboardHook({+ onBeforePaste: () => ({+ dataStream: 'Hooked\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_4', startIndex: 6 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ }),+ });++ expect(await service.legacyPaste({ text: 'Plain', files: [] })).toBe(true);++ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('paste-hook-doc', UniverInstanceType.UNIVER_DOC)!;+ expect(documentModel.getBody()?.dataStream).toContain('Hooked');+ expect(documentModel.getBody()?.dataStream).not.toContain('Plain');++ testBed.univer.dispose();+ });++ it('stops applying a paste hook after the hook disposable is released', async () => {+ const documentData: IDocumentData = {+ id: 'paste-dispose-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_10', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(InnerPasteCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: 'paste-dispose-doc', subUnitId: '' });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 4,+ endOffset: 4,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const service = testBed.get(IDocClipboardService);+ const disposable = service.addClipboardHook({+ onBeforePaste: () => ({+ dataStream: 'Hooked\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_11', startIndex: 6 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ }),});- expect(JSON.stringify(pastedDoc)).not.toContain('data:image');+ disposable.dispose();++ expect(await service.legacyPaste({ text: 'Plain', files: [] })).toBe(true);++ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('paste-dispose-doc', UniverInstanceType.UNIVER_DOC)!;+ expect(documentModel.getBody()?.dataStream).toContain('Plain');+ expect(documentModel.getBody()?.dataStream).not.toContain('Hooked');++ testBed.univer.dispose();+ });++ it('does not paste when the clipboard payload is empty', async () => {+ const documentData: IDocumentData = {+ id: 'empty-paste-doc',+ body: {+ dataStream: 'Body\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_clipboard_fixture_12', startIndex: 4 }],+ sectionBreaks: [],+ customBlocks: [],+ textRuns: [],+ },+ documentStyle: {},+ };+ const testBed = createCommandTestBed(documentData, [+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],+ [IDocClipboardService, { useClass: DocClipboardService }],+ ]);+ const service = testBed.get(IDocClipboardService);++ expect(await service.legacyPaste({ files: [] })).toBe(false);++ const univerInstanceService = testBed.get(IUniverInstanceService);+ const documentModel = univerInstanceService.getUnit<DocumentDataModel>('empty-paste-doc', UniverInstanceType.UNIVER_DOC)!;+ expect(documentModel.getBody()?.dataStream).toBe('Body\r\n');++ testBed.univer.dispose();});});diff --git a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.tsindex 9d012fd466..c4eea09e8c 100644--- a/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts+++ b/packages/docs-ui/src/services/clipboard/__test__/html-and-udm-convert.spec.ts@@ -15,10 +15,24 @@*/import type { IDocumentBody, IDocumentData, Nullable } from '@univerjs/core';-import { BooleanNumber, DataStreamTreeTokenType, DocumentBlockRangeType, HorizontalAlign, PresetListType, TableSizeType } from '@univerjs/core';+import {+ BaselineOffset,+ BooleanNumber,+ CustomDecorationType,+ CustomRangeType,+ DataStreamTreeTokenType,+ DocumentBlockRangeType,+ DrawingTypeEnum,+ HorizontalAlign,+ PresetListType,+ TableSizeType,+} from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { CopyContentCache, extractId } from '../copy-content-cache';import { HtmlToUDMService } from '../html-to-udm/converter';+import { extractNodeStyle } from '../html-to-udm/parse-node-style';import PastePluginLark from '../html-to-udm/paste-plugins/plugin-lark';+import PastePluginUniver from '../html-to-udm/paste-plugins/plugin-univer';import PastePluginWord from '../html-to-udm/paste-plugins/plugin-word';import {createInternalClipboardDocData,@@ -26,12 +40,14 @@ import {createInternalClipboardFragment,embedInternalClipboardFragment,extractInternalClipboardFragmentFromHtml,+ parseInternalClipboardFragment,wrapClipboardHtml,} from '../internal-fragment';-import { UDMToHtmlService } from '../udm-to-html/convertor';+import { covertTextRunToHtml, getBodySliceHtml, UDMToHtmlService } from '../udm-to-html/convertor';HtmlToUDMService.use(PastePluginWord);HtmlToUDMService.use(PastePluginLark);+HtmlToUDMService.use(PastePluginUniver);describe('test case in html and udm convert', () => {let body: Nullable<IDocumentBody> = null;@@ -266,6 +282,56 @@ describe('test case in html and udm convert', () => {expect(titleCell?.borderTop?.width?.v).toBe(1);expect(titleCell?.borderTop?.color.rgb).toBe('rgb(203,213,225)');});++ it('should paste Univer exported paragraphs with paragraph styles', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <p class="UniverNormal" style="text-align: center; margin-top: 6px; margin-bottom: 12px; line-height: 150%;">Title</p>+ <p class="UniverNormal">Body</p>+ `);+ const firstParagraph = udm.body?.paragraphs?.[0];+ const secondParagraph = udm.body?.paragraphs?.[1];++ expect(udm.body?.dataStream).toBe('Title\rBody\r');+ expect(firstParagraph?.startIndex).toBe(5);+ expect(firstParagraph?.paragraphStyle).toMatchObject({+ horizontalAlign: HorizontalAlign.CENTER,+ spaceAbove: { v: 6 },+ spaceBelow: { v: 12 },+ lineSpacing: 1.5,+ });+ expect(secondParagraph?.startIndex).toBe(10);+ });++ it('should paste Lark deleted text as strike-through rich text', () => {+ const convertor = new HtmlToUDMService();+ const udm = convertor.convert(`+ <meta name="lark-record-clipboard" content="1">+ <div class="ace-line">Keep <s style="color: #C81E1E;">deleted</s></div>+ `);+ const deletedRun = udm.body?.textRuns?.find((run) => udm.body?.dataStream.slice(run.st, run.ed) === 'deleted');++ expect(udm.body?.dataStream).toBe('Keep deleted\r');+ expect(deletedRun?.ts).toMatchObject({+ st: { s: BooleanNumber.TRUE },+ cl: { rgb: 'rgb(200,30,30)' },+ });+ expect(udm.body?.paragraphs?.[0].startIndex).toBe(12);+ });++ it('should read inline css styles used by copied rich text', () => {+ const span = document.createElement('span');+ span.setAttribute('style', 'font-family: "Inter"; font-size: 16px; font-weight: 700; font-style: italic; text-decoration: overline; background-color: rgb(240, 240, 10);');++ expect(extractNodeStyle(span)).toMatchObject({+ ff: 'Inter',+ fs: 12,+ bl: BooleanNumber.TRUE,+ it: BooleanNumber.TRUE,+ ol: { s: BooleanNumber.TRUE },+ bg: { rgb: 'rgb(240,240,10)' },+ });+ });});describe('test cases in udm-to-html', () => {@@ -483,6 +549,166 @@ describe('test case in html and udm convert', () => {expect(internalDocData?.tableSource?.['table-2'].tableColumns?.map((column) => column.size.width.v)).toEqual([90, 180]);});+ it('should reject invalid internal clipboard fragments and empty copied document lists', () => {+ expect(parseInternalClipboardFragment()).toBeNull();+ expect(parseInternalClipboardFragment('{bad-json')).toBeNull();+ expect(parseInternalClipboardFragment(JSON.stringify({+ version: 1,+ kind: 'univer-doc-fragment',+ doc: {},+ }))).toBeNull();+ expect(extractInternalClipboardFragmentFromHtml('<p>No internal fragment</p>')).toBeNull();+ expect(createInternalClipboardDocDataList([])).toBeNull();+ });++ it('should resolve internal copy ids and cached document payloads for local paste', () => {+ const cache = new CopyContentCache();+ const doc = {+ body: {+ dataStream: 'Cached\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_67', startIndex: 6 }],+ },+ };++ cache.set('copy-1', doc);+ expect(extractId('<p data-copy-id="copy-1">Cached</p>')).toBe('copy-1');+ expect(extractId('<p>External paste</p>')).toBeNull();+ expect(cache.get('copy-1')?.body?.dataStream).toBe('Cached\r\n');++ cache.clear();+ expect(cache.get('copy-1')).toBeUndefined();+ });++ it('should merge copied body metadata with offsets for internal multi-range paste', () => {+ const first: IDocumentData = {+ id: 'first',+ documentStyle: {},+ body: {+ dataStream: 'AB',+ textRuns: [{ st: 0, ed: 1, ts: { bl: BooleanNumber.TRUE } }],+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_65', startIndex: 1 }],+ sectionBreaks: [{ startIndex: 2 }],+ blockRanges: [{ startIndex: 0, endIndex: 1, blockId: 'quote-1', blockType: DocumentBlockRangeType.QUOTE }],+ customRanges: [{ startIndex: 0, endIndex: 1, rangeId: 'range-1', rangeType: 0 }],+ customDecorations: [{ startIndex: 0, endIndex: 1, id: 'decoration-1', type: CustomDecorationType.COMMENT }],+ customBlocks: [{ startIndex: 1, blockId: 'block-1' }],+ },+ };+ const second: IDocumentData = {+ id: 'second',+ documentStyle: {},+ body: {+ dataStream: 'CD',+ textRuns: [{ st: 0, ed: 2, ts: { it: BooleanNumber.TRUE } }],+ paragraphs: [{ paragraphId: 'para_docs_ui_fixture_66', startIndex: 2 }],+ sectionBreaks: [{ startIndex: 2 }],+ blockRanges: [{ startIndex: 0, endIndex: 2, blockId: 'code-1', blockType: DocumentBlockRangeType.CODE }],+ customRanges: [{ startIndex: 0, endIndex: 1, rangeId: 'range-2', rangeType: 0 }],+ customDecorations: [{ startIndex: 1, endIndex: 2, id: 'decoration-2', type: CustomDecorationType.COMMENT }],+ customBlocks: [{ startIndex: 0, blockId: 'block-2' }],+ },+ };++ const merged = createInternalClipboardDocDataList([first, second]);+ const body = merged?.body;++ expect(body?.dataStream).toBe('ABCD');+ expect(body?.textRuns?.[1]).toMatchObject({ st: 2, ed: 4 });+ expect(body?.paragraphs?.[1].startIndex).toBe(4);+ expect(body?.sectionBreaks?.[1].startIndex).toBe(4);+ expect(body?.blockRanges?.[1]).toMatchObject({ startIndex: 2, endIndex: 4, blockType: DocumentBlockRangeType.CODE });+ expect(body?.customRanges?.[1]).toMatchObject({ startIndex: 2, endIndex: 3, rangeId: 'range-2' });+ expect(body?.customDecorations?.[1]).toMatchObject({ startIndex: 3, endIndex: 4, id: 'decoration-2' });+ expect(body?.customBlocks?.[1]).toMatchObject({ startIndex: 2, blockId: 'block-2' });+ });++ it('should copy inline drawings with fresh block ids for internal paste', () => {+ const doc: IDocumentData = {+ id: 'drawing-doc',+ documentStyle: {},+ body: {+ dataStream: '\b',+ customBlocks: [{ startIndex: 0, blockId: 'image-1' }],+ },+ drawings: {+ 'image-1': {+ drawingId: 'image-1',+ drawingType: 0,+ unitId: 'drawing-doc',+ subUnitId: '',+ } as never,+ },+ };++ const internalDocData = createInternalClipboardDocData(doc);+ const blockId = internalDocData.body?.customBlocks?.[0].blockId;++ expect(blockId).toBeTruthy();+ expect(blockId).not.toBe('image-1');+ expect(blockId ? internalDocData.drawings?.[blockId]?.drawingId : undefined).toBe(blockId);+ });++ it('should serialize rich inline text styles for html clipboard output', () => {+ const html = covertTextRunToHtml('Styled', {+ st: 0,+ ed: 6,+ ts: {+ bl: BooleanNumber.TRUE,+ it: BooleanNumber.TRUE,+ ul: { s: BooleanNumber.TRUE },+ st: { s: BooleanNumber.TRUE },+ va: BaselineOffset.SUPERSCRIPT,+ fs: 14,+ ff: 'Inter',+ cl: { rgb: '#123456' },+ bg: { rgb: 'rgb(240, 240, 10)' },+ ol: { s: BooleanNumber.TRUE },+ },+ });++ expect(html).toContain('<strong><s><u><sup><i>Styled</i></sup></u></s></strong>');+ expect(html).toContain('font-family: Inter');+ expect(html).toContain('font-size: 14pt');+ expect(html).toContain('color: #123456');+ expect(html).toContain('background: #f0f00a');+ expect(html).toContain('text-decoration: overline');+ });++ it('should serialize copied hyperlinks and inline images into html clipboard output', () => {+ const doc: IDocumentData = {+ id: 'copy-html',+ documentStyle: {},+ body: {+ dataStream: 'A\bB',+ customRanges: [{+ startIndex: 0,+ endIndex: 2,+ rangeId: 'link-1',+ rangeType: CustomRangeType.HYPERLINK,+ properties: { url: 'https://univer.ai' },+ }],+ customBlocks: [{ startIndex: 1, blockId: 'image-1' }],+ },+ drawings: {+ 'image-1': {+ drawingId: 'image-1',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: 'UUID',+ source: 'remote-image-id',+ transform: { width: 120, height: 80 },+ docTransform: { size: { width: 120, height: 80 } },+ } as never,+ },+ };++ const html = getBodySliceHtml(doc, 0, 3);++ expect(html).toContain('<a data-rangeid="link-1" href="https://univer.ai">');+ expect(html).toContain('data-source=remote-image-id');+ expect(html).toContain('data-doc-transform-width=120');+ expect(html).toContain('src=remote-image-id');+ });+it('should paste docs feature coverage from html with styles, blocks, lists and table dimensions', () => {const convertor = new HtmlToUDMService();const pasted = convertor.convert(`diff --git a/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.tsnew file mode 100644index 0000000000..48bef97237--- /dev/null+++ b/packages/docs-ui/src/services/editor/__tests__/editor-manager.service.spec.ts@@ -0,0 +1,648 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ CommandService,+ ConfigService,+ ContextService,+ createParagraphId,+ DesktopLogService,+ DOCS_COMMENT_EDITOR_UNIT_ID_KEY,+ DocumentDataModel,+ EDITOR_ACTIVATED,+ FOCUSING_COMMENT_EDITOR,+ FOCUSING_EDITOR_STANDALONE,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ LocalUndoRedoService,+ ThemeService,+ UniverInstanceService,+} from '@univerjs/core';+import {+ DocSelectionManagerService,+ DocSkeletonManagerService,+ DocStateEmitService,+ RichTextEditingMutation,+ SetTextSelectionsOperation,+} from '@univerjs/docs';+import { IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE, RenderManagerService } from '@univerjs/engine-render';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ReplaceSnapshotCommand } from '../../../commands/commands/replace-content.command';+import { DocSelectionRenderService } from '../../selection/doc-selection-render.service';+import { Editor } from '../editor';+import { EditorService, IEditorService } from '../editor-manager.service';++const EDITOR_ID = 'editor-1';++class TestDocSelectionRenderService {+ readonly onBlur$ = new Subject<never>();+ readonly onFocus$ = new Subject<never>();+ readonly onPaste$ = new Subject<{ event: Event; content?: string }>();+ readonly onInput$ = new Subject<{ event: Event; content?: string }>();+ readonly onKeydown$ = new Subject<{ event: KeyboardEvent; content?: string }>();+ readonly onCompositionupdate$ = new Subject<{ event: CompositionEvent; content?: string }>();+ readonly onCompositionend$ = new Subject<{ event: CompositionEvent; content?: string }>();+ isFocusing = true;+ focusCount = 0;+ blurCount = 0;++ private _activeTextRange = {+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ isActive: true,+ };++ getActiveTextRange() {+ return this._activeTextRange;+ }++ focus() {+ this.focusCount++;+ }++ blur() {+ this.blurCount++;+ }+}++class TestRender {+ constructor(private readonly _selectionRenderService: TestDocSelectionRenderService) {}++ with(service: unknown) {+ if (service === DocSelectionRenderService) {+ return this._selectionRenderService;+ }++ throw new Error(`Unexpected render service: ${String(service)}`);+ }+}++class TestRegisterViewport {+ disposed = false;+ scrollVal: unknown;++ getScrollBar() {+ return {+ dispose: () => {+ this.disposed = true;+ },+ };+ }++ updateScrollVal(value: unknown) {+ this.scrollVal = value;+ }+}++class TestRegisterRender extends TestRender {+ readonly canvas = document.createElement('canvas');+ readonly viewport = new TestRegisterViewport();+ container: HTMLDivElement | null = null;+ readonly engine = {+ canvasColorService: {},+ setContainer: (container: HTMLDivElement) => {+ this.container = container;+ },+ getCanvas: () => ({+ getCanvasEle: () => this.canvas,+ }),+ };++ readonly components = new Map();+ readonly mainComponent = {+ getScene: () => ({+ getViewports: () => [this.viewport],+ }),+ };+}++class TestRegisterRenderManagerService {+ static readonly renders = new Map<string, TestRegisterRender>();+ static readonly removedRenderIds: string[] = [];++ create(unitId: string) {+ TestRegisterRenderManagerService.renders.set(unitId, new TestRegisterRender(new TestDocSelectionRenderService()));+ }++ getRenderById(unitId: string) {+ return TestRegisterRenderManagerService.renders.get(unitId);+ }++ removeRender(unitId: string) {+ TestRegisterRenderManagerService.removedRenderIds.push(unitId);+ TestRegisterRenderManagerService.renders.delete(unitId);+ }+}++class TestMissingRenderManagerService {+ create() {}++ getRenderById() {+ return null;+ }++ removeRender() {}+}++class TestEditorRenderManagerService {+ static readonly skeleton = { unitId: EDITOR_ID };++ getRenderById(unitId: string) {+ if (unitId !== EDITOR_ID) {+ return undefined;+ }++ return {+ with: (token: unknown) => {+ if (token === DocSkeletonManagerService) {+ return {+ getSkeleton: () => TestEditorRenderManagerService.skeleton,+ };+ }++ throw new Error(`Unexpected render service: ${String(token)}`);+ },+ };+ }+}++function createService(renderManagerServiceClass: unknown = RenderManagerService) {+ vi.stubGlobal('window', new EventTarget());+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ injector.add([ThemeService]);+ injector.add([IRenderManagerService, { useClass: renderManagerServiceClass as never }]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IEditorService, { useClass: EditorService }]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: EDITOR_ID,+ body: {+ dataStream: 'abc\r\n',+ paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ }));+ return {+ injector,+ service: injector.get(IEditorService),+ contextService: injector.get(IContextService),+ univerInstanceService,+ };+}++function createEditor(+ injector: Injector,+ univerInstanceService: IUniverInstanceService,+ commandService: ICommandService,+ editorUnitId: string,+ selectionRenderService: TestDocSelectionRenderService,+ config: Partial<ConstructorParameters<typeof Editor>[0]> = {}+) {+ const editorDom = config.editorDom ?? document.createElement('div');++ return injector.createInstance(Editor, {+ initialSnapshot: { id: editorUnitId },+ render: new TestRender(selectionRenderService),+ editorDom,+ canvasStyle: { backgroundColor: '#ffffff' },+ scrollBar: true,+ ...config,+ } as never, univerInstanceService, injector.get(DocSelectionManagerService), commandService, injector.get(IUndoRedoService), injector);+}++describe('EditorService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ TestRegisterRenderManagerService.renders.clear();+ TestRegisterRenderManagerService.removedRenderIds.length = 0;+ });++ it('focuses the requested editor, emits caret position, and clears editor contexts on blur', () => {+ const { service, contextService, univerInstanceService } = createService();+ const focusRanges: unknown[] = [];+ const blurs: unknown[] = [];+ let editorFocused = 0;+ let editorBlurred = 0;+ service.focus$.subscribe((range) => focusRanges.push(range));+ service.blur$.subscribe((value) => blurs.push(value));+ service.getAllEditor().set('editor-1', {+ getValue: () => 'abc',+ focus: () => editorFocused++,+ blur: () => editorBlurred++,+ isSheetEditor: () => false,+ } as never);++ service.focus('editor-1');+ expect(service.getFocusId()).toBe('editor-1');+ expect(univerInstanceService.getCurrentUniverDocInstance()?.getUnitId()).toBe('editor-1');+ expect(editorFocused).toBe(1);+ expect(focusRanges).toEqual([{ startOffset: 3, endOffset: 3 }]);+ expect(service.getEditor()).toBe(service.getEditor('editor-1'));++ service.focus('editor-1');+ expect(editorFocused).toBe(1);+ expect(service.getFocusId()).toBe('editor-1');++ service.blur();+ expect(service.getFocusId()).toBeNull();+ expect(editorBlurred).toBe(1);+ expect(blurs).toEqual([null]);+ expect(contextService.getContextValue(EDITOR_ACTIVATED)).toBe(false);++ service.focus('missing-editor');+ expect(service.getFocusId()).toBeNull();+ expect(editorFocused).toBe(1);+ });++ it('turns render-layer editing activity into editor events and document updates', async () => {+ const { injector, univerInstanceService } = createService();+ const commandService = injector.get(ICommandService);+ commandService.registerCommand(ReplaceSnapshotCommand);+ commandService.registerCommand(RichTextEditingMutation);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionRenderService = new TestDocSelectionRenderService();+ const editor = injector.createInstance(Editor, {+ initialSnapshot: { id: EDITOR_ID },+ render: new TestRender(selectionRenderService),+ editorDom: document.createElement('div'),+ } as never, univerInstanceService, injector.get(DocSelectionManagerService), commandService, injector.get(IUndoRedoService), injector);+ const selectionManagerService = injector.get(DocSelectionManagerService);+ const inputs: string[] = [];+ const pastes: string[] = [];+ const focusEvents: unknown[] = [];+ const blurEvents: unknown[] = [];+ const changeEvents: string[] = [];+ const selections: string[] = [];+ const refreshSelections: string[] = [];+ editor.focus$.subscribe((event) => focusEvents.push(event));+ editor.blur$.subscribe((event) => blurEvents.push(event));+ editor.change$.subscribe(({ data }) => {+ changeEvents.push(data.body?.dataStream ?? '');+ });+ editor.input$.subscribe(({ content, isComposing }) => {+ inputs.push(`${content}:${isComposing}`);+ });+ editor.paste$.subscribe(({ content }) => {+ pastes.push(content ?? '');+ });+ editor.selectionChange$.subscribe(({ textRanges }) => {+ for (const range of textRanges) {+ selections.push(`${range.startOffset}:${range.endOffset}:${range.collapsed}`);+ }+ });+ selectionManagerService.refreshSelection$.subscribe((selection) => {+ if (!selection) {+ return;+ }++ for (const range of selection.docRanges) {+ refreshSelections.push(`${range.startOffset}:${range.endOffset}`);+ }+ });++ selectionRenderService.onFocus$.next({ type: 'focus' } as never);+ selectionRenderService.onInput$.next({ event: new InputEvent('input'), content: 'd' });+ selectionRenderService.onKeydown$.next({ event: { type: 'keydown', ctrlKey: true, keyCode: 88 } as KeyboardEvent, content: 'cut' });+ selectionRenderService.onKeydown$.next({ event: { type: 'keydown', keyCode: 8 } as KeyboardEvent, content: '' });+ selectionRenderService.onCompositionupdate$.next({ event: new CompositionEvent('compositionupdate'), content: '拼' });+ selectionRenderService.onPaste$.next({ event: new Event('paste'), content: 'paste-text' });+ selectionRenderService.onBlur$.next({ type: 'blur' } as never);+ selectionManagerService.__TEST_ONLY_setCurrentSelection({ unitId: EDITOR_ID, subUnitId: EDITOR_ID });+ selectionManagerService.__replaceTextRangesWithNoRefresh({+ textRanges: [{+ startOffset: 1,+ endOffset: 2,+ collapsed: false,+ isActive: true,+ }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId: EDITOR_ID, subUnitId: EDITOR_ID });+ editor.replaceText('quarterly');+ await Promise.resolve();++ expect(focusEvents).toEqual([{ type: 'focus' }]);+ expect(blurEvents).toEqual([{ type: 'blur' }]);+ expect(changeEvents).toEqual(['abc\r\n']);+ expect(inputs).toEqual(['d:false', 'cut:false', ':false', '拼:true', 'paste-text:false']);+ expect(pastes).toEqual(['paste-text']);+ expect(selections).toEqual(['1:2:false']);+ expect(editor.getDocumentData().body?.dataStream).toBe('quarterly\r\n');+ expect(refreshSelections.at(-1)).toBe('9:9');+ expect(univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID)?.getBody()?.dataStream).toBe('quarterly\r\n');++ editor.dispose();+ });++ it('exposes editor state and selection APIs used by host UI', () => {+ const { injector, univerInstanceService } = createService(TestEditorRenderManagerService);+ const commandService = injector.get(ICommandService);+ commandService.registerCommand(SetTextSelectionsOperation);+ const selectionRenderService = new TestDocSelectionRenderService();+ const editorDom = document.createElement('div');+ const editor = createEditor(+ injector,+ univerInstanceService,+ commandService,+ EDITOR_ID,+ selectionRenderService,+ {+ cancelDefaultResizeListener: true,+ editorDom,+ readonly: true,+ visible: false,+ } as never+ );+ const selectionManagerService = injector.get(DocSelectionManagerService);+ const refreshedSelections: string[] = [];+ selectionManagerService.refreshSelection$.subscribe((selection) => {+ if (!selection) {+ return;+ }++ for (const range of selection.docRanges) {+ refreshedSelections.push(`${range.startOffset}:${range.endOffset}`);+ }+ });++ expect(editor.docSelectionRenderService).toBe(selectionRenderService);+ expect(editor.isFocus()).toBe(true);+ selectionRenderService.isFocusing = false;+ expect(editor.isFocus()).toBe(false);++ editor.setSelectionRanges([{ startOffset: 1, endOffset: 2 }], false);+ selectionManagerService.__TEST_ONLY_setCurrentSelection({ unitId: EDITOR_ID, subUnitId: EDITOR_ID });+ selectionManagerService.__replaceTextRangesWithNoRefresh({+ textRanges: [{ startOffset: 2, endOffset: 2, collapsed: true, isActive: true }],+ rectRanges: [],+ segmentId: '',+ segmentPage: -1,+ style: NORMAL_TEXT_SELECTION_PLUGIN_STYLE,+ isEditing: true,+ }, { unitId: EDITOR_ID, subUnitId: EDITOR_ID });++ expect(refreshedSelections.at(-1)).toBe('1:2');+ expect(editor.getSelectionRanges()[0].startOffset).toBe(2);+ expect(editor.getCursorPosition()).toBe(2);++ editor.select();+ expect(refreshedSelections.at(-1)).toBe('0:3');+ expect(editor.getDocumentDataModel()).toBe(univerInstanceService.getUnit<DocumentDataModel>(EDITOR_ID));+ expect(editor.cancelDefaultResizeListener).toBe(true);+ expect(editor.isReadOnly()).toBe(true);+ expect(editor.getBoundingClientRect()).toEqual(editorDom.getBoundingClientRect());+ expect(editor.editorDOM).toBe(editorDom);+ expect(editor.isVisible()).toBe(false);+ expect(editor.getSkeleton()).toBe(TestEditorRenderManagerService.skeleton);+ expect(editor.isSheetEditor()).toBe(false);+ });++ it('tracks editor focus context when moving between standalone and comment editors', () => {+ const { injector, service, contextService, univerInstanceService } = createService();+ const commandService = injector.get(ICommandService);+ const commentEditorId = `${DOCS_COMMENT_EDITOR_UNIT_ID_KEY}_comment-1`;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: commentEditorId,+ body: {+ dataStream: 'note\r\n',+ paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ }));+ const standaloneSelection = new TestDocSelectionRenderService();+ const commentSelection = new TestDocSelectionRenderService();+ const standaloneEditor = createEditor(injector, univerInstanceService, commandService, EDITOR_ID, standaloneSelection);+ const commentEditor = createEditor(injector, univerInstanceService, commandService, commentEditorId, commentSelection);+ const selectionRefreshes: number[] = [];+ injector.get(DocSelectionManagerService).refreshSelection$.subscribe((selection) => {+ if (selection) {+ selectionRefreshes.push(selection.docRanges.length);+ }+ });+ service.getAllEditor().set(EDITOR_ID, standaloneEditor);+ service.getAllEditor().set(commentEditorId, commentEditor);++ service.focus(EDITOR_ID);+ expect(service.getFocusEditor()).toBe(standaloneEditor);+ expect(service.getEditorRenderConfig(EDITOR_ID)).toEqual({+ canvasStyle: { backgroundColor: '#ffffff' },+ scrollBar: true,+ });+ expect(contextService.getContextValue(EDITOR_ACTIVATED)).toBe(true);+ expect(contextService.getContextValue(FOCUSING_EDITOR_STANDALONE)).toBe(true);+ expect(contextService.getContextValue(FOCUSING_COMMENT_EDITOR)).toBe(false);+ expect(standaloneSelection.focusCount).toBe(1);++ service.focus(commentEditorId);+ expect(service.getFocusId()).toBe(commentEditorId);+ expect(contextService.getContextValue(FOCUSING_EDITOR_STANDALONE)).toBe(false);+ expect(contextService.getContextValue(FOCUSING_COMMENT_EDITOR)).toBe(true);+ expect(standaloneSelection.blurCount).toBe(1);+ expect(commentSelection.focusCount).toBe(1);++ service.blur(true);+ expect(service.getFocusId()).toBeNull();+ expect(contextService.getContextValue(EDITOR_ACTIVATED)).toBe(false);+ expect(selectionRefreshes.at(-1)).toBe(0);++ standaloneEditor.dispose();+ commentEditor.dispose();+ });++ it('registers an editor render and cleans it up with the returned disposable', () => {+ const { service, univerInstanceService } = createService(TestRegisterRenderManagerService);+ const editorUnitId = EDITOR_ID;+ const container = document.createElement('div');+ const disposable = service.register({+ initialSnapshot: {+ id: editorUnitId,+ body: {+ dataStream: 'draft\r\n',+ paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ documentStyle: {},+ },+ canvasStyle: { backgroundColor: '#ffffff' },+ scrollBar: false,+ }, container);+ const render = TestRegisterRenderManagerService.renders.get(editorUnitId)!;++ expect(service.isEditor(editorUnitId)).toBe(true);+ expect(service.getEditor(editorUnitId)?.getEditorId()).toBe(editorUnitId);+ expect(service.getEditorRenderConfig(editorUnitId)).toEqual({+ canvasStyle: { backgroundColor: '#ffffff' },+ scrollBar: false,+ });+ expect(render.container).toBe(container);+ expect(render.viewport.disposed).toBe(true);+ expect(render.viewport.scrollVal).toEqual({+ scrollX: 0,+ scrollY: 0,+ viewportScrollX: 0,+ viewportScrollY: 0,+ });+ expect(univerInstanceService.getUnit<DocumentDataModel>(editorUnitId)?.getBody()?.dataStream).toBe('abc\r\n');++ disposable.dispose();++ expect(service.isEditor(editorUnitId)).toBe(false);+ expect(TestRegisterRenderManagerService.removedRenderIds).toEqual([editorUnitId]);+ expect(univerInstanceService.getUnit<DocumentDataModel>(editorUnitId)).toBeUndefined();+ });++ it('keeps render config without an editor when no render is available and removes it on dispose', () => {+ const { service } = createService(TestMissingRenderManagerService);+ const disposable = service.register({+ initialSnapshot: {+ id: EDITOR_ID,+ body: {+ dataStream: 'abc\r\n',+ paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ documentStyle: {},+ },+ canvasStyle: { fontSize: 14 },+ scrollBar: true,+ }, document.createElement('div'));++ expect(service.getEditor(EDITOR_ID)).toBeUndefined();+ expect(service.isEditor(EDITOR_ID)).toBe(true);+ expect(service.getEditorRenderConfig(EDITOR_ID)).toEqual({+ canvasStyle: { fontSize: 14 },+ scrollBar: true,+ });++ disposable.dispose();++ expect(service.isEditor(EDITOR_ID)).toBe(false);+ expect(service.getEditorRenderConfig(EDITOR_ID)).toBeNull();+ });++ it('blurs a focused non-sheet editor when focus moves outside editor-owned DOM', () => {+ const { service } = createService();+ let blurred = 0;+ service.getAllEditor().set(EDITOR_ID, {+ getValue: () => 'abc',+ focus: () => {},+ blur: () => blurred++,+ isSheetEditor: () => false,+ } as never);+ service.focus(EDITOR_ID);++ const externalTarget = document.createElement('button');+ const externalFocusEvent = new Event('focusin');+ Object.defineProperty(externalFocusEvent, 'target', { value: externalTarget });+ window.dispatchEvent(externalFocusEvent);++ expect(blurred).toBe(1);+ expect(service.getFocusId()).toBeNull();+ });++ it('keeps editor focus when focus moves within editor-owned DOM or the active editor is a sheet editor', () => {+ const { service } = createService();+ let standaloneBlurred = 0;+ service.getAllEditor().set(EDITOR_ID, {+ getValue: () => 'abc',+ focus: () => {},+ blur: () => standaloneBlurred++,+ isSheetEditor: () => false,+ } as never);+ service.focus(EDITOR_ID);++ const editorTarget = document.createElement('div');+ editorTarget.dataset.uComp = 'editor';+ const editorFocusEvent = new Event('focusin');+ Object.defineProperty(editorFocusEvent, 'target', { value: editorTarget });+ window.dispatchEvent(editorFocusEvent);++ expect(standaloneBlurred).toBe(0);+ expect(service.getFocusId()).toBe(EDITOR_ID);++ service.getAllEditor().set(EDITOR_ID, {+ getValue: () => 'cell',+ focus: () => {},+ blur: () => standaloneBlurred++,+ isSheetEditor: () => true,+ } as never);++ const externalTarget = document.createElement('button');+ const externalFocusEvent = new Event('focusin');+ Object.defineProperty(externalFocusEvent, 'target', { value: externalTarget });+ window.dispatchEvent(externalFocusEvent);++ expect(service.isSheetEditor('missing-editor')).toBe(false);+ expect(standaloneBlurred).toBe(0);+ expect(service.getFocusId()).toBe(EDITOR_ID);+ });++ it('clears registered editor state when the service is disposed', () => {+ const { service } = createService(TestMissingRenderManagerService);+ service.register({+ initialSnapshot: {+ id: EDITOR_ID,+ body: {+ dataStream: 'abc\r\n',+ paragraphs: [{ startIndex: 0, paragraphId: createParagraphId(new Set()) }],+ sectionBreaks: [],+ customRanges: [],+ tables: [],+ textRuns: [],+ },+ documentStyle: {},+ },+ canvasStyle: { fontSize: 12 },+ scrollBar: true,+ }, document.createElement('div'));++ expect(service.isEditor(EDITOR_ID)).toBe(true);++ (service as EditorService).dispose();++ expect(service.isEditor(EDITOR_ID)).toBe(false);+ expect(service.getEditorRenderConfig(EDITOR_ID)).toBeNull();+ });+});diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.tsindex b128e2f284..0fc4999084 100644--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts@@ -14,10 +14,13 @@* limitations under the License.*/+import type { IDisposable, IDocumentData } from '@univerjs/core';import type { Mock } from 'vitest';-import { DataStreamTreeTokenType, DOC_RANGE_TYPE } from '@univerjs/core';-import { GlyphType } from '@univerjs/engine-render';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { DataStreamTreeTokenType, DOC_RANGE_TYPE, Univer, UniverInstanceType } from '@univerjs/core';+import { DocSkeletonManagerService } from '@univerjs/docs';+import { GlyphType, RenderUnit } from '@univerjs/engine-render';+import { ILayoutService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DocSelectionRenderService } from '../doc-selection-render.service';import { TextRange } from '../text-range';@@ -181,6 +184,129 @@ function createService() {};}+class TestLayoutService {+ static root: HTMLDivElement;+ static registeredElements: HTMLElement[] = [];++ static reset() {+ this.root = document.createElement('div');+ document.body.appendChild(this.root);+ this.registeredElements = [];+ }++ get rootContainerElement() {+ return TestLayoutService.root;+ }++ registerContainerElement(element: HTMLElement): IDisposable {+ TestLayoutService.registeredElements.push(element);++ return {+ dispose: () => {+ const nextElements: HTMLElement[] = [];+ for (const current of TestLayoutService.registeredElements) {+ if (current !== element) {+ nextElements.push(current);+ }+ }+ TestLayoutService.registeredElements = nextElements;+ },+ };+ }+}++class TestDocSkeletonManagerService {+ static skeleton: {+ findPositionByGlyph: () => unknown;+ findNodeByCoord: () => unknown;+ } = {+ findPositionByGlyph: () => null,+ findNodeByCoord: () => null,+ };++ static reset() {+ this.skeleton = {+ findPositionByGlyph: () => null,+ findNodeByCoord: () => null,+ };+ }++ getSkeleton() {+ return TestDocSkeletonManagerService.skeleton;+ }+}++class TestRenderEvent<T> {+ private readonly _listeners: Array<(param: T) => void> = [];++ subscribeEvent(listener: (param: T) => void) {+ this._listeners.push(listener);++ return {+ unsubscribe: () => {+ const nextListeners: Array<(param: T) => void> = [];+ for (const current of this._listeners) {+ if (current !== listener) {+ nextListeners.push(current);+ }+ }+ this._listeners.length = 0;+ this._listeners.push(...nextListeners);+ },+ };+ }++ emit(param: T) {+ for (const listener of this._listeners) {+ listener(param);+ }+ }+}++function createRealSelectionRenderService(options: {+ mainComponent?: unknown;+ scene?: unknown;+} = {}) {+ TestLayoutService.reset();+ TestDocSkeletonManagerService.reset();+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);+ const documentData: IDocumentData = {+ id: 'selection-render-doc',+ body: {+ dataStream: 'Hello\r\n',+ paragraphs: [{ paragraphId: 'para_docs_ui_selection_fixture_1', startIndex: 5 }],+ sectionBreaks: [],+ },+ documentStyle: {},+ };+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, documentData);+ const renderUnit = injector.createInstance(RenderUnit, {+ engine: { name: 'engine' } as never,+ scene: (options.scene ?? {+ getViewports: () => [],+ getEngine: () => null,+ }) as never,+ isMainScene: true,+ unit: doc,+ });+ if (options.mainComponent) {+ renderUnit.mainComponent = options.mainComponent as never;+ }+ renderUnit.addRenderDependencies([+ [DocSkeletonManagerService, { useClass: TestDocSkeletonManagerService as never }],+ DocSelectionRenderService,+ ] as never);++ return {+ input: document.getElementById('__editor_selection-render-doc') as HTMLDivElement,+ renderUnit,+ service: renderUnit.with(DocSelectionRenderService),+ univer,+ };+}+describe('doc selection render service internals', () => {beforeEach(() => {vi.clearAllMocks();@@ -595,3 +721,457 @@ describe('doc selection render service internals', () => {expect(getCanvasOffsetByEngineMock).toHaveBeenCalledWith(engine);});});++describe('DocSelectionRenderService', () => {+ let cleanup: Array<() => void> = [];++ beforeEach(() => {+ vi.clearAllMocks();+ getCanvasOffsetByEngineMock.mockReturnValue({ left: 0, top: 0 });+ getRangeListFromCharIndexMock.mockReturnValue(null);+ getRangeListFromSelectionMock.mockReturnValue(null);+ getRectRangeFromCharIndexMock.mockReturnValue(null);+ getTextRangeFromCharIndexMock.mockReturnValue(null);+ });++ afterEach(() => {+ for (const dispose of cleanup) {+ dispose();+ }+ cleanup = [];+ document.body.innerHTML = '';+ });++ it('keeps the editable input inside the Univer layout root and registers it as an app container', () => {+ const { renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());++ const container = document.getElementById('univer-doc-selection-container-selection-render-doc');++ expect(container?.parentElement).toBe(TestLayoutService.root);+ expect(TestLayoutService.registeredElements).toEqual([container]);++ service.dispose();++ expect(document.getElementById('univer-doc-selection-container-selection-render-doc')).toBeNull();+ expect(TestLayoutService.registeredElements).toEqual([]);+ });++ it('publishes hidden editor input, paste, focus, and blur events with the typed content', () => {+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const received: Array<{ type: string; content?: string }> = [];+ const subscriptions = [+ service.onInputBefore$.subscribe((config) => received.push({ type: 'before-input', content: config?.content })),+ service.onInput$.subscribe((config) => received.push({ type: 'input', content: config.content })),+ service.onPaste$.subscribe((config) => received.push({ type: 'paste', content: config.content })),+ service.onFocus$.subscribe((config) => received.push({ type: 'focus', content: config.content })),+ service.onBlur$.subscribe((config) => received.push({ type: 'blur', content: config.content })),+ ];+ cleanup.push(() => {+ for (const subscription of subscriptions) {+ subscription.unsubscribe();+ }+ });++ input.textContent = 'typed text';+ input.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' }));+ input.textContent = 'pasted text';+ input.dispatchEvent(new Event('paste', { bubbles: true }));+ input.dispatchEvent(new Event('focus', { bubbles: true }));+ input.textContent = 'leaving editor';+ input.dispatchEvent(new Event('blur', { bubbles: true }));++ expect(received).toEqual([+ { type: 'before-input', content: 'typed text' },+ { type: 'input', content: 'typed text' },+ { type: 'paste', content: 'pasted text' },+ { type: 'focus', content: '' },+ { type: 'blur', content: 'leaving editor' },+ ]);+ expect(input.textContent).toBe('');+ });++ it('suppresses normal keydown while IME composition is active, then resumes key events after composition ends', () => {+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const events: Array<{ type: string; content?: string }> = [];+ const subscriptions = [+ service.onKeydown$.subscribe((config) => events.push({ type: 'keydown', content: config.content })),+ service.onCompositionstart$.subscribe((config) => {+ if (config) {+ events.push({ type: 'compositionstart', content: config.content });+ }+ }),+ service.onCompositionupdate$.subscribe((config) => {+ if (config) {+ events.push({ type: 'compositionupdate', content: config.content });+ }+ }),+ service.onCompositionend$.subscribe((config) => {+ if (config) {+ events.push({ type: 'compositionend', content: config.content });+ }+ }),+ ];+ cleanup.push(() => {+ for (const subscription of subscriptions) {+ subscription.unsubscribe();+ }+ });++ input.textContent = '拼';+ input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true, data: '拼' }));+ input.textContent = 'pin';+ input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'p' }));+ input.dispatchEvent(new CompositionEvent('compositionupdate', { bubbles: true, data: '拼' }));+ input.textContent = '拼';+ input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '拼' }));+ input.textContent = 'done';+ input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));++ expect(events).toEqual([+ { type: 'compositionstart', content: '拼' },+ { type: 'compositionupdate', content: 'pin' },+ { type: 'compositionend', content: '拼' },+ { type: 'keydown', content: 'done' },+ ]);+ });++ it('keeps segment state stable while the editor is reused by header, footer, and body selection flows', () => {+ const { renderUnit, service, univer } = createRealSelectionRenderService();+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());++ service.setSegment('header-1');+ service.setSegmentPage(3);+ service.setReserveRangesStatus(true);++ expect(service.getSegment()).toBe('header-1');+ expect(service.getSegmentPage()).toBe(3);++ service.setSegment('');+ service.setSegmentPage(-1);++ expect(service.getSegment()).toBe('');+ expect(service.getSegmentPage()).toBe(-1);+ });++ it('selects the current word on double click and the paragraph on triple click', () => {+ const viewport = {+ transformVector2SceneCoord: () => ({ x: 8, y: 12 }),+ getAbsoluteVector: () => ({ x: 16, y: 24 }),+ };+ const scene = {+ getViewports: () => [viewport],+ getEngine: () => ({ name: 'engine' }),+ };+ const documentTransform = {+ clone: () => ({+ invert: () => ({+ applyPoint: (point: unknown) => point,+ }),+ }),+ };+ const mainComponent = {+ getOffsetConfig: () => ({+ documentTransform,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ }),+ };+ const { renderUnit, service, univer } = createRealSelectionRenderService({ mainComponent, scene });+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const column = { lines: [] as unknown[] };+ const line = { paragraphIndex: 5, st: 0, parent: column, divides: [] as unknown[] };+ const divide = { parent: line, glyphGroup: [] as Array<{ content: string; count: number; glyphType: GlyphType; parent?: unknown }> };+ const glyphs: Array<{ content: string; count: number; glyphType: GlyphType; parent?: unknown }> = [];+ for (const content of ['H', 'e', 'l', 'l', 'o']) {+ glyphs.push({ content, count: 1, glyphType: GlyphType.WORD, parent: divide });+ }+ divide.glyphGroup = glyphs;+ line.divides = [divide];+ column.lines = [line];+ (service as unknown as { _findNodeByCoord: () => unknown })._findNodeByCoord = () => ({ node: glyphs[1], ratioX: 0.4, segmentPage: -1 });+ const wordRange = {+ ...createTextRange({ isActive: vi.fn(() => true) }),+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.TEXT,+ segmentId: '',+ segmentPage: -1,+ direction: 'forward',+ startNodePosition: null,+ endNodePosition: null,+ };+ const paragraphRange = {+ ...createTextRange({ isActive: vi.fn(() => true) }),+ startOffset: 0,+ endOffset: 5,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.TEXT,+ segmentId: '',+ segmentPage: -1,+ direction: 'forward',+ startNodePosition: null,+ endNodePosition: null,+ };+ getRangeListFromCharIndexMock+ .mockReturnValueOnce({ textRanges: [wordRange], rectRanges: [] })+ .mockReturnValueOnce({ textRanges: [paragraphRange], rectRanges: [] });+ const selections: string[] = [];+ const subscription = service.textSelectionInner$.subscribe((selection) => {+ if (!selection) {+ return;+ }+ for (const range of selection.textRanges) {+ selections.push(`${range.startOffset}:${range.endOffset}`);+ }+ });+ cleanup.push(() => subscription.unsubscribe());++ service.__handleDblClick({ offsetX: 10, offsetY: 12 } as never);+ service.__handleTripleClick({ offsetX: 10, offsetY: 12 } as never);++ expect(selections).toEqual(['0:5', '0:5']);+ });++ it('moves the hidden editor to the active visible selection when syncing canvas selection to DOM input', () => {+ getCanvasOffsetByEngineMock.mockReturnValue({ left: 5, top: 7 });+ const viewport = {+ getAbsoluteVector: () => ({ x: 30, y: 40 }),+ };+ const scene = {+ getViewports: () => [viewport],+ getEngine: () => ({ name: 'engine' }),+ };+ const { renderUnit, service, univer } = createRealSelectionRenderService({ scene });+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const activeRange = {+ isActive: () => true,+ getAnchor: () => ({ left: 12, top: 20, visible: true }),+ dispose: vi.fn(),+ };+ (service as unknown as { _rangeList: TextRange[] })._rangeList = [activeRange as never];++ service.sync();++ const container = document.getElementById('univer-doc-selection-container-selection-render-doc')!;+ expect(container.style.left).toBe('35px');+ expect(container.style.top).toBe('47px');+ expect(container.style.zIndex).toBe('1000');+ });++ it('parks the active selection while scrolling and restores the editor when the selection remains in view', () => {+ getCanvasOffsetByEngineMock.mockReturnValue({ left: 1, top: 2 });+ const scrollAfter$ = new TestRenderEvent<{ viewport: unknown }>();+ const scrollEnd$ = new TestRenderEvent<{ viewport: unknown }>();+ const activeStatic = vi.fn();+ const deactivateStatic = vi.fn();+ const viewport = {+ onScrollAfter$: scrollAfter$,+ onScrollEnd$: scrollEnd$,+ getAbsoluteVector: () => ({ x: 4, y: 8 }),+ getBounding: () => ({+ viewBound: {+ left: 0,+ top: 0,+ right: 100,+ bottom: 100,+ },+ }),+ };+ const scene = {+ getViewports: () => [viewport],+ getEngine: () => ({ name: 'engine' }),+ };+ const { renderUnit, service, univer } = createRealSelectionRenderService({ scene });+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const activeRange = {+ isActive: () => true,+ activeStatic,+ deactivateStatic,+ getAnchor: () => ({ left: 10, top: 12, visible: true }),+ dispose: vi.fn(),+ };+ (service as unknown as { _rangeList: TextRange[] })._rangeList = [activeRange as never];++ service.__attachScrollEvent();+ scrollAfter$.emit({ viewport });+ scrollEnd$.emit({ viewport });++ const container = document.getElementById('univer-doc-selection-container-selection-render-doc')!;+ expect(activeStatic).toHaveBeenCalledTimes(1);+ expect(deactivateStatic).not.toHaveBeenCalled();+ expect(container.style.left).toBe('5px');+ expect(container.style.top).toBe('10px');+ });++ it('commits a dragged text selection when the pointer is released', () => {+ vi.spyOn(TextRange.prototype as unknown as Record<'_anchorBlink', () => void>, '_anchorBlink').mockImplementation(() => {});+ vi.spyOn(TextRange.prototype, 'refresh').mockImplementation(() => {});+ const pointerMove$ = new TestRenderEvent<{ offsetX: number; offsetY: number }>();+ const pointerUp$ = new TestRenderEvent<Record<string, never>>();+ const disableObjectsEvent = vi.fn();+ const enableObjectsEvent = vi.fn();+ const clearSelectedObjects = vi.fn();+ const setCursor = vi.fn();+ const scene = {+ getViewports: () => [],+ getEngine: () => ({ name: 'engine' }),+ findViewportByPosToScene: () => ({+ top: 0,+ left: 0,+ width: 500,+ height: 500,+ scrollByViewportDeltaVal: () => true,+ transScroll2ViewportScrollValue: () => ({ x: 0, y: 0 }),+ }),+ disableObjectsEvent,+ enableObjectsEvent,+ getTransformer: () => ({ clearSelectedObjects }),+ setCursor,+ onPointerMove$: pointerMove$,+ onPointerUp$: pointerUp$,+ };+ const { renderUnit, service, univer } = createRealSelectionRenderService({ scene });+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ const dragRange = {+ ...createTextRange({ isActive: vi.fn(() => true) }),+ startOffset: 2,+ endOffset: 6,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.TEXT,+ segmentId: '',+ segmentPage: -1,+ direction: 'forward',+ startNodePosition: null,+ endNodePosition: null,+ };+ const focusNodePosition = {+ page: 0,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 6,+ isBack: false,+ };+ (service as unknown as { _findNodeByCoord: () => unknown })._findNodeByCoord = () => ({+ node: { streamType: DataStreamTreeTokenType.LETTER },+ segmentId: '',+ segmentPage: -1,+ });+ (service as unknown as { _getNodePosition: () => unknown })._getNodePosition = () => ({+ page: 0,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 2,+ isBack: true,+ });+ (service as unknown as { _moving: () => void })._moving = () => {+ (service as unknown as { _focusNodePosition: unknown })._focusNodePosition = focusNodePosition;+ (service as unknown as { _rangeListCache: TextRange[] })._rangeListCache = [dragRange as never];+ };+ const selections: string[] = [];+ const subscription = service.textSelectionInner$.subscribe((selection) => {+ if (!selection) {+ return;+ }+ for (const range of selection.textRanges) {+ selections.push(`${range.startOffset}:${range.endOffset}`);+ }+ });+ cleanup.push(() => subscription.unsubscribe());++ service.__onPointDown({ offsetX: 10, offsetY: 10, button: 0 } as never);+ pointerMove$.emit({ offsetX: 20, offsetY: 20 });+ pointerUp$.emit({});++ expect(disableObjectsEvent).toHaveBeenCalledTimes(1);+ expect(enableObjectsEvent).toHaveBeenCalledTimes(1);+ expect(clearSelectedObjects).toHaveBeenCalledTimes(1);+ expect(setCursor).toHaveBeenCalledWith('text');+ expect(selections.at(-1)).toBe('2:6');+ });++ it('places the manual cursor from transformed document coordinates', () => {+ vi.spyOn(TextRange.prototype as unknown as Record<'_anchorBlink', () => void>, '_anchorBlink').mockImplementation(() => {});+ vi.spyOn(TextRange.prototype, 'refresh').mockImplementation(() => {});+ const transformedPoint = { x: 3, y: 4 };+ const findNodeByCoord = vi.fn(() => ({+ node: {+ glyphType: GlyphType.LIST,+ streamType: DataStreamTreeTokenType.LETTER,+ },+ ratioX: 0.8,+ segmentPage: 2,+ }));+ const findPositionByGlyph = vi.fn(() => ({+ page: 0,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph: 1,+ isBack: false,+ }));+ const viewport = {+ transformVector2SceneCoord: () => ({ x: 30, y: 40 }),+ getAbsoluteVector: () => ({ x: 5, y: 6 }),+ };+ const scene = {+ getViewports: () => [viewport],+ getEngine: () => ({ name: 'engine' }),+ };+ const documentTransform = {+ clone: () => ({+ invert: () => ({+ applyPoint: () => transformedPoint,+ }),+ }),+ };+ const mainComponent = {+ getOffsetConfig: () => ({+ documentTransform,+ pageMarginLeft: 9,+ pageMarginTop: 11,+ }),+ };+ const { renderUnit, service, univer } = createRealSelectionRenderService({ mainComponent, scene });+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ TestDocSkeletonManagerService.skeleton = {+ findNodeByCoord,+ findPositionByGlyph,+ };+ (service as unknown as { _getAllTextRanges: () => unknown[] })._getAllTextRanges = () => [{+ startNodePosition: { glyph: 1, isBack: true },+ segmentId: 'header-1',+ segmentPage: 2,+ }];+ (service as unknown as { _getAllRectRanges: () => unknown[] })._getAllRectRanges = () => [];+ service.setSegment('header-1');+ service.setSegmentPage(2);++ service.setCursorManually(12, 18);++ expect(findNodeByCoord).toHaveBeenCalledWith(+ transformedPoint,+ 0,+ 9,+ 11,+ {+ strict: true,+ segmentId: 'header-1',+ segmentPage: 2,+ }+ );+ expect(service.getAllTextRanges()[0]).toMatchObject({+ startNodePosition: expect.objectContaining({ glyph: 1, isBack: true }),+ segmentId: 'header-1',+ segmentPage: 2,+ });+ });+});diff --git a/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts b/packages/docs-ui/src/services/selection/__tests__/range-state.spec.tsindex 16d9ec9c7a..01e2f4ffcb 100644--- a/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts@@ -15,8 +15,9 @@*/import { describe, expect, it, vi } from 'vitest';+import { NodePositionConvertToCursor } from '../convert-text-range';import { RectRange } from '../rect-range';-import { TextRange } from '../text-range';+import { cursorConvertToTextRange, TextRange } from '../text-range';function getGetter<T extends object>(target: T, key: keyof T) {return Object.getOwnPropertyDescriptor(target, key)?.get as () => unknown;@@ -53,7 +54,168 @@ interface IFakeRectRange {focusNodePosition: Record<string, unknown>;}+function createNodePosition(glyph = 0) {+ return {+ page: 0,+ section: 0,+ column: 0,+ line: 0,+ divide: 0,+ glyph,+ isBack: true,+ };+}++function createTextRangeHarness() {+ const addedObjects: unknown[] = [];+ const scene = {+ addObject: (object: unknown) => {+ addedObjects.push(object);+ },+ };+ const document = {+ getOffsetConfig: () => ({+ docsLeft: 5,+ docsTop: 7,+ }),+ };+ const skeleton = {+ findNodePositionByCharIndex: (index: number) => createNodePosition(index),+ findGlyphByPosition: () => ({+ ts: {},+ }),+ getViewModel: () => ({+ getDataModel: () => ({+ getSelfOrHeaderFooterModel: () => ({+ getBody: () => ({ dataStream: 'abcdef\r\n' }),+ }),+ }),+ }),+ };++ return {+ addedObjects,+ document,+ scene,+ skeleton,+ };+}+describe('selection range state', () => {+ it('renders a collapsed cursor range and clamps cursor offsets before the final line break', () => {+ const { addedObjects, document, scene, skeleton } = createTextRangeHarness();+ const rangePointSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockImplementation(() => ({+ contentBoxPointGroup: [[+ { x: 10, y: 20 },+ { x: 12, y: 20 },+ { x: 12, y: 25 },+ { x: 10, y: 25 },+ ]],+ borderBoxPointGroup: [],+ cursorList: [{ startOffset: 7, endOffset: 7, collapsed: true }],+ }) as never);++ const range = cursorConvertToTextRange(+ scene as never,+ { startOffset: 7, endOffset: 7, segmentId: '', segmentPage: -1 },+ skeleton as never,+ document as never+ )!;++ expect(range.startOffset).toBe(6);+ expect(range.endOffset).toBe(6);+ expect(range.collapsed).toBe(true);+ expect(range.getAbsolutePosition()).toEqual({+ left: 15,+ top: 27,+ width: 2,+ height: 5,+ });+ expect(addedObjects).toHaveLength(1);+ expect(range.getAnchor()).not.toBeNull();++ range.dispose();+ rangePointSpy.mockRestore();+ });++ it('renders expanded text ranges and reports document direction from anchor to focus', () => {+ const { addedObjects, document, scene, skeleton } = createTextRangeHarness();+ const rangePointSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockImplementation(() => ({+ contentBoxPointGroup: [],+ borderBoxPointGroup: [[+ { x: 10, y: 20 },+ { x: 60, y: 20 },+ { x: 60, y: 36 },+ { x: 10, y: 36 },+ ]],+ cursorList: [{ startOffset: 1, endOffset: 4, collapsed: false }],+ }) as never);++ const range = new TextRange(+ scene as never,+ document as never,+ skeleton as never,+ createNodePosition(1) as never,+ createNodePosition(4) as never,+ undefined,+ '',+ -1+ );++ expect(range.startOffset).toBe(1);+ expect(range.endOffset).toBe(4);+ expect(range.collapsed).toBe(false);+ expect(range.direction).toBe('forward');+ expect(range.getAbsolutePosition()).toEqual({+ left: 15,+ top: 27,+ width: 50,+ height: 16,+ });+ expect(addedObjects).toHaveLength(1);++ range.dispose();+ rangePointSpy.mockRestore();+ });++ it('returns empty positions for empty ranges and reports backward document selections', () => {+ const { document, scene, skeleton } = createTextRangeHarness();+ const emptyRange = new TextRange(scene as never, document as never, skeleton as never, null, null);++ expect(emptyRange.startNodePosition).toBeNull();+ expect(emptyRange.endNodePosition).toBeNull();+ expect(emptyRange.getAbsolutePosition()).toBeUndefined();+ expect(emptyRange.direction).toBe('none');+ emptyRange.dispose();++ const rangePointSpy = vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockImplementation(() => ({+ contentBoxPointGroup: [],+ borderBoxPointGroup: [[+ { x: 10, y: 20 },+ { x: 60, y: 20 },+ { x: 60, y: 36 },+ { x: 10, y: 36 },+ ]],+ cursorList: [{ startOffset: 1, endOffset: 4, collapsed: false }],+ }) as never);+ const anchor = createNodePosition(4);+ const focus = createNodePosition(1);+ const backwardRange = new TextRange(+ scene as never,+ document as never,+ skeleton as never,+ anchor as never,+ focus as never+ );++ expect(backwardRange.startNodePosition).toBe(focus);+ expect(backwardRange.endNodePosition).toBe(anchor);+ expect(backwardRange.direction).toBe('backward');++ backwardRange.dispose();+ rangePointSpy.mockRestore();+ });+it('derives text range offsets, direction, and active state from prototype getters', () => {const fakeRange = Object.setPrototypeOf({_cursorList: [{ startOffset: 9, endOffset: 9, collapsed: true }],diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.tsindex 6c956ded0c..0f21576e04 100644--- a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts@@ -22,6 +22,7 @@ import { RectRange } from '../rect-range';import {getCanvasOffsetByEngine,getParagraphInfoByGlyph,+ getRangeListFromCharIndex,getRangeListFromSelection,getRectRangeFromCharIndex,getTextRangeFromCharIndex,@@ -396,6 +397,17 @@ describe('selection utils', () => {expect(rectRange?.focusNodePosition).toEqual(endPosition);});+ it('does not create ranges when a character boundary cannot be resolved', () => {+ const skeleton = {+ findNodePositionByCharIndex: vi.fn(() => undefined),+ } as never;+ const document = createDocument();++ expect(getTextRangeFromCharIndex(1, 2, {} as never, document, skeleton, {} as never, '', -1)).toBeUndefined();+ expect(getRectRangeFromCharIndex(1, 2, {} as never, document, skeleton, {} as never, '', -1)).toBeUndefined();+ expect(getRangeListFromCharIndex(1, 2, {} as never, document, skeleton, {} as never, '', -1)).toBeUndefined();+ });+it('routes same-cell and rect selections into the expected range buckets', () => {const sameCellAnchor = createNodePosition(['skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0]);const sameCellFocus = createNodePosition(['skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0], 1);@@ -790,6 +802,311 @@ describe('selection utils', () => {expect(result?.textRanges[0].focusNodePosition).toBe(focusPosition);});+ it('splits a body selection that crosses a table into text and table ranges', () => {+ const anchorPosition = createNodePosition(['body'], 0);+ const focusPosition = createNodePosition(['body'], 1);+ const tableStartPosition = createNodePosition(['table-start']);+ const tableEndPosition = createNodePosition(['table-end']);+ const bodyStartPosition = createNodePosition(['body-start']);+ const bodyBeforeTableEndPosition = createNodePosition(['body-before-table-end']);+ const bodyAfterTableStartPosition = createNodePosition(['body-after-table-start']);+ const bodyEndPosition = createNodePosition(['body-end']);+ const paragraph = {+ startIndex: 0,+ endIndex: 100,+ children: [{+ startIndex: 20,+ endIndex: 50,+ children: [+ { startIndex: 20, endIndex: 35 },+ { startIndex: 36, endIndex: 50 },+ ],+ }],+ };+ const skeleton = {+ findCharIndexByPosition: vi+ .fn()+ .mockReturnValueOnce(0)+ .mockReturnValueOnce(100),+ findNodePositionByCharIndex: vi+ .fn()+ .mockReturnValueOnce(tableStartPosition)+ .mockReturnValueOnce(tableEndPosition)+ .mockReturnValueOnce(bodyStartPosition)+ .mockReturnValueOnce(bodyBeforeTableEndPosition)+ .mockReturnValueOnce(bodyAfterTableStartPosition)+ .mockReturnValueOnce(bodyEndPosition),+ getViewModel: () => ({+ getSelfOrHeaderFooterViewModel: () => ({+ getChildren: () => [{ children: [paragraph] }],+ }),+ }),+ } as never;++ vi.spyOn(NodePositionConvertToRectRange.prototype, 'getNodePositionGroup').mockReturnValue([+ {+ anchor: tableStartPosition,+ focus: tableEndPosition,+ },+ ] as never);++ const result = getRangeListFromSelection(+ anchorPosition,+ focusPosition,+ {} as never,+ createDocument(),+ skeleton,+ {} as never,+ '',+ -1+ );++ expect(result?.textRanges).toHaveLength(2);+ expect(result?.textRanges[0].anchorNodePosition).toBe(bodyStartPosition);+ expect(result?.textRanges[0].focusNodePosition).toBe(bodyBeforeTableEndPosition);+ expect(result?.textRanges[1].anchorNodePosition).toBe(bodyAfterTableStartPosition);+ expect(result?.textRanges[1].focusNodePosition).toBe(bodyEndPosition);+ expect(result?.rectRanges).toHaveLength(1);+ expect(result?.rectRanges[0].anchorNodePosition).toBe(tableStartPosition);+ expect(result?.rectRanges[0].focusNodePosition).toBe(tableEndPosition);+ });++ it('tracks rect range table coverage and updates its highlight shape', () => {+ vi.mocked(RectRange.prototype.refresh).mockRestore();+ const anchor = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]);+ const focus = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 1, 'cells', 1]);+ const addedObjects: unknown[] = [];+ const scene = {+ addObject: (object: unknown) => {+ addedObjects.push(object);+ },+ } as never;+ const skeleton = {+ findCharIndexByPosition: (position: INodePosition) => position === anchor ? 10 : 20,+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableColumns: [{}, {}],+ tableRows: [{}, {}],+ },+ },+ }),+ }),+ } as never;+ vi.spyOn(NodePositionConvertToRectRange.prototype, 'getRangePointData').mockReturnValue({+ pointGroup: [[+ { x: 0, y: 0 },+ { x: 200, y: 0 },+ { x: 200, y: 80 },+ { x: 0, y: 80 },+ { x: 0, y: 0 },+ ]],+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ tableId: 'table-1',+ } as never);++ const range = new RectRange(scene, createDocument(), skeleton, anchor, focus, {} as never, 'segment-1', 2);++ expect(range.startOffset).toBe(10);+ expect(range.endOffset).toBe(20);+ expect(range.segmentId).toBe('segment-1');+ expect(range.segmentPage).toBe(2);+ expect(range.tableId).toBe('table-1');+ expect(range.spanEntireRow).toBe(true);+ expect(range.spanEntireColumn).toBe(true);+ expect(range.spanEntireTable).toBe(true);+ expect(addedObjects).toHaveLength(1);++ range.activate();+ expect(range.isActive()).toBe(true);+ range.deactivate();+ expect(range.isActive()).toBe(false);++ range.refresh();+ expect(addedObjects).toHaveLength(1);+ range.dispose();+ });++ it('checks intersections between table rect ranges', () => {+ const first = Object.create(RectRange.prototype) as RectRange;+ const second = Object.create(RectRange.prototype) as RectRange;+ const third = Object.create(RectRange.prototype) as RectRange;++ Object.assign(first, { _startRow: 0, _endRow: 2, _startCol: 0, _endCol: 2 });+ Object.assign(second, { _startRow: 1, _endRow: 3, _startCol: 1, _endCol: 3 });+ Object.assign(third, { _startRow: 4, _endRow: 5, _startCol: 4, _endCol: 5 });++ expect(first.isIntersection(second)).toBe(true);+ expect(first.isIntersection(third)).toBe(false);+ });++ it('does not build table rect data when skeleton data or table metadata is missing', () => {+ const anchor = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]);+ const focus = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 1]);+ const emptySkeleton = {+ getSkeletonData: () => null,+ findCharIndexByPosition: () => 0,+ } as never;+ const missingTableNodeSkeleton = {+ ...createRectRangeConvertorHarness().skeleton,+ findCharIndexByPosition: (position: INodePosition) => position === anchor ? 0 : 10,+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ { tableCells: [{}, {}] },+ ],+ },+ },+ }),+ findTableNodeById: () => null,+ }),+ } as never;++ expect(new NodePositionConvertToRectRange({} as never, emptySkeleton).getRangePointData(anchor, focus)).toBeUndefined();+ expect(new NodePositionConvertToRectRange({} as never, emptySkeleton).getNodePositionGroup(anchor, focus)).toBeUndefined();+ expect(new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, missingTableNodeSkeleton).getNodePositionGroup(anchor, focus)).toBeUndefined();+ });++ it('converts a full-row table drag into one text range group', () => {+ const cell00 = createCellPage(0, 100);+ const cell01 = createCellPage(100, 100);+ const cell10 = createCellPage(0, 100);+ const cell11 = createCellPage(100, 100);+ const row0: IMockRow = { index: 0, top: 0, height: 20, cells: [cell00, cell01] };+ const row1: IMockRow = { index: 1, top: 20, height: 20, cells: [cell10, cell11] };+ const table = { tableId: 'table-1', top: 0, left: 0, rows: [row0, row1] } as never;+ const page = { skeTables: new Map([['table-1', table]]), marginTop: 0, marginLeft: 0, width: 300, height: 200 } as never;+ const anchor = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 0]);+ const focus = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 1, 'cells', 1]);+ const startNode = createNodePosition(['char', 1]);+ const endNode = createNodePosition(['char', 28]);++ cell00.parent = row0 as never;+ cell01.parent = row0 as never;+ cell10.parent = row1 as never;+ cell11.parent = row1 as never;+ row0.parent = table;+ row1.parent = table;++ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ }),+ findCharIndexByPosition: (position: INodePosition) => position === anchor ? 0 : 100,+ findNodePositionByCharIndex: vi+ .fn()+ .mockReturnValueOnce(startNode)+ .mockReturnValueOnce(endNode),+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ { tableCells: [{}, {}] },+ { tableCells: [{}, {}] },+ ],+ },+ },+ }),+ findTableNodeById: () => ({+ children: [+ { children: [{ startIndex: 0, endIndex: 8 }, { startIndex: 10, endIndex: 18 }] },+ { children: [{ startIndex: 20, endIndex: 28 }, { startIndex: 30, endIndex: 40 }] },+ ],+ }),+ }),+ } as never;++ expect(new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton).getNodePositionGroup(anchor, focus)).toEqual([{+ anchor: startNode,+ focus: endNode,+ }]);+ });++ it('converts a column-only table drag into one text range group per row', () => {+ const cell00 = createCellPage(0, 100);+ const cell01 = createCellPage(100, 100);+ const cell10 = createCellPage(0, 100);+ const cell11 = createCellPage(100, 100);+ const row0: IMockRow = { index: 0, top: 0, height: 20, cells: [cell00, cell01] };+ const row1: IMockRow = { index: 1, top: 20, height: 20, cells: [cell10, cell11] };+ const table = { tableId: 'table-1', top: 0, left: 0, rows: [row0, row1] } as never;+ const page = { skeTables: new Map([['table-1', table]]), marginTop: 0, marginLeft: 0, width: 300, height: 200 } as never;+ const anchor = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 0, 'cells', 1]);+ const focus = createNodePosition(['pages', 0, 'skeTables', 'table-1', 'rows', 1, 'cells', 1]);+ const row0Start = createNodePosition(['char', 11]);+ const row0End = createNodePosition(['char', 16]);+ const row1Start = createNodePosition(['char', 31]);+ const row1End = createNodePosition(['char', 38]);++ cell00.parent = row0 as never;+ cell01.parent = row0 as never;+ cell10.parent = row1 as never;+ cell11.parent = row1 as never;+ row0.parent = table;+ row1.parent = table;++ const skeleton = {+ getSkeletonData: () => ({+ pages: [page],+ }),+ findCharIndexByPosition: (position: INodePosition) => position === anchor ? 10 : 100,+ findNodePositionByCharIndex: vi+ .fn()+ .mockReturnValueOnce(row0Start)+ .mockReturnValueOnce(row0End)+ .mockReturnValueOnce(row1Start)+ .mockReturnValueOnce(row1End),+ getViewModel: () => ({+ getSnapshot: () => ({+ tableSource: {+ 'table-1': {+ tableRows: [+ { tableCells: [{}, {}] },+ { tableCells: [{}, {}] },+ ],+ },+ },+ }),+ findTableNodeById: () => ({+ children: [+ { children: [{ startIndex: 0, endIndex: 8 }, { startIndex: 10, endIndex: 18 }] },+ { children: [{ startIndex: 20, endIndex: 28 }, { startIndex: 30, endIndex: 40 }] },+ ],+ }),+ }),+ } as never;++ expect(new NodePositionConvertToRectRange({+ docsLeft: 0,+ docsTop: 0,+ pageLayoutType: 0,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ } as never, skeleton).getNodePositionGroup(anchor, focus)).toEqual([+ { anchor: row0Start, focus: row0End },+ { anchor: row1Start, focus: row1End },+ ]);+ });+it('reads canvas offsets, paragraph glyph info, and serializes ranges', () => {vi.mocked(getOffsetRectForDom).mockReturnValue({ left: 12, top: 34 } as never);diff --git a/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.ts b/packages/docs-ui/src/views/__tests__/ParagraphMenu.spec.tsnew file mode 100644index 0000000000..91c6092c3d--- /dev/null+++ b/packages/docs-ui/src/views/__tests__/ParagraphMenu.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 { IDocumentBlockRange } from '@univerjs/core';+import type { ITextRangeWithStyle } from '@univerjs/engine-render';+import type { IMutiPageParagraphBound } from '../../services/doc-event-manager.service';+import type { IDocBlockMenuTarget } from '../../services/doc-paragraph-menu.service';+import { DocumentBlockRangeType, NamedStyleType } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { HorizontalLineCommand } from '../../commands/commands/doc-horizontal-line.command';+import { BulletListCommand } from '../../commands/commands/list.command';+import { AlignCenterCommand } from '../../commands/commands/paragraph-align.command';+import { H2HeadingCommand, SetParagraphNamedStyleCommand } from '../../commands/commands/set-heading.command';+import { DOC_PARAGRAPH_T_EDIT_MENU_ID, INSERT_BELLOW_MENU_ID } from '../../menu/paragraph-menu';+import {+ getParagraphFormattingRange,+ getParagraphMenuCommandTargetRange,+ getParagraphMenuHiddenItemIds,+ getParagraphMenuResolvedCommand,+ shouldUseInsertBelowRange,+} from '../ParagraphMenu';++function paragraphBound(): IMutiPageParagraphBound {+ return {+ paragraphStart: 10,+ paragraphEnd: 24,+ startIndex: 24,+ segmentId: 'header-left',+ } as IMutiPageParagraphBound;+}++function blockTarget(blockRange: IDocumentBlockRange): IDocBlockMenuTarget {+ return {+ kind: 'blockRange',+ key: 'block:quote-1',+ blockRange,+ menuRange: {+ startOffset: 21,+ endOffset: 44,+ collapsed: false,+ },+ moveRange: {+ startOffset: 20,+ endOffset: 46,+ },+ emptyMode: false,+ draggable: true,+ };+}++describe('ParagraphMenu command behavior', () => {+ it('applies a heading choice to the paragraph target as a named style change', () => {+ const targetRange: ITextRangeWithStyle = {+ startOffset: 10,+ endOffset: 10,+ collapsed: true,+ segmentId: 'header-left',+ };++ const resolved = getParagraphMenuResolvedCommand({ id: H2HeadingCommand.id }, targetRange);++ expect(resolved).toEqual({+ commandId: SetParagraphNamedStyleCommand.id,+ params: {+ value: NamedStyleType.HEADING_2,+ textRanges: [targetRange],+ },+ });+ });++ it('formats the full paragraph when a list choice starts from the paragraph handle', () => {+ const caretRange: ITextRangeWithStyle = {+ startOffset: 10,+ endOffset: 10,+ collapsed: true,+ segmentId: 'header-left',+ };+ const paragraphRange = getParagraphFormattingRange(undefined, paragraphBound());++ expect(paragraphRange).toEqual({+ startOffset: 10,+ endOffset: 24,+ collapsed: false,+ segmentId: 'header-left',+ });++ const commandRange = getParagraphMenuCommandTargetRange(BulletListCommand.id, caretRange, paragraphRange);+ const resolved = getParagraphMenuResolvedCommand({ id: BulletListCommand.id }, commandRange);++ expect(resolved).toEqual({+ commandId: BulletListCommand.id,+ params: {+ docRange: [paragraphRange],+ },+ });+ });++ it('uses the paragraph formatting range for alignment and divider insertion', () => {+ const caretRange: ITextRangeWithStyle = {+ startOffset: 14,+ endOffset: 14,+ collapsed: true,+ segmentId: 'header-left',+ };+ const paragraphRange = getParagraphFormattingRange(undefined, paragraphBound());++ expect(getParagraphMenuCommandTargetRange(AlignCenterCommand.id, caretRange, paragraphRange)).toEqual(paragraphRange);+ expect(getParagraphMenuResolvedCommand(+ { id: HorizontalLineCommand.id },+ getParagraphMenuCommandTargetRange(HorizontalLineCommand.id, caretRange, paragraphRange)+ )).toEqual({+ commandId: HorizontalLineCommand.id,+ params: {+ insertRange: paragraphRange,+ },+ });+ });++ it('targets the whole block and hides incompatible block conversions', () => {+ const paragraph = paragraphBound();+ const target = blockTarget({+ blockId: 'quote-1',+ blockType: DocumentBlockRangeType.QUOTE,+ startIndex: 20,+ endIndex: 45,+ } as IDocumentBlockRange);++ expect(getParagraphFormattingRange(target, paragraph)).toEqual({+ startOffset: 20,+ endOffset: 46,+ collapsed: false,+ segmentId: 'header-left',+ });++ expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).toContain('docs-callout.command.insert');+ expect(getParagraphMenuHiddenItemIds(DOC_PARAGRAPH_T_EDIT_MENU_ID, target)).not.toContain('docs-quote.command.insert');+ });++ it('routes explicit and declared insert actions below the active block', () => {+ expect(shouldUseInsertBelowRange('doc.command.insert-image', { id: 'image' })).toBe(true);+ expect(shouldUseInsertBelowRange('docs.operation.insert-embed', {+ id: 'embed',+ params: {+ paragraphMenuPlacement: 'below',+ },+ })).toBe(true);+ expect(shouldUseInsertBelowRange('docs.operation.insert-divider', { id: INSERT_BELLOW_MENU_ID })).toBe(true);+ expect(shouldUseInsertBelowRange(AlignCenterCommand.id, { id: AlignCenterCommand.id })).toBe(false);+ });+});diff --git a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.ts b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsdeleted file mode 100644index 23face11ce..0000000000--- a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.ts+++ /dev/null@@ -1,74 +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 { IMenuSchema } from '@univerjs/ui';-import { MenuManagerPosition } from '@univerjs/ui';-import { describe, expect, it, vi } from 'vitest';-import { SetInlineFormatBoldCommand } from '../../../commands/commands/inline-format.command';-import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../../menu/menu';-import { resolveFloatToolbarMenus } from '../FloatToolbar';--describe('resolveFloatToolbarMenus', () => {- it('keeps default toolbar menus ordered by whitelist and appends direct extension menus separately', () => {- const textStyleItem = createMenuItem(FLOAT_TEXT_STYLE_MENU_ID);- const boldItem = createMenuItem(SetInlineFormatBoldCommand.id);- const hyperlinkItem = createMenuItem('doc.operation.show-hyper-link-edit-popup');- const commentItem = createMenuItem('docs.operation.start-add-comment');- const menuManagerService = {- getMenuByPositionKey: vi.fn((position: string) => {- if (position === FLOAT_TOOLBAR_MENU_POSITION) {- return [textStyleItem, hyperlinkItem, commentItem];- }-- return [];- }),- getFlatMenuByPositionKey: vi.fn((position: string) => {- if (position === FLOAT_TOOLBAR_MENU_POSITION) {- return [textStyleItem, hyperlinkItem, commentItem];- }- if (position === MenuManagerPosition.RIBBON) {- return [boldItem];- }-- return [];- }),- };-- const { menus, extraMenus } = resolveFloatToolbarMenus(menuManagerService as never, [- FLOAT_TEXT_STYLE_MENU_ID,- SetInlineFormatBoldCommand.id,- ]);-- expect(menus.map((item) => item.key)).toEqual([- FLOAT_TEXT_STYLE_MENU_ID,- SetInlineFormatBoldCommand.id,- ]);- expect(extraMenus.map((item) => item.key)).toEqual([- 'doc.operation.show-hyper-link-edit-popup',- 'docs.operation.start-add-comment',- ]);- });-});--function createMenuItem(key: string): IMenuSchema {- return {- key,- order: 0,- item: {- id: key,- } as never,- };-}diff --git a/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsxnew file mode 100644index 0000000000..6b8df5e80c--- /dev/null+++ b/packages/docs-ui/src/views/float-toolbar/__tests__/FloatToolbar.spec.tsx@@ -0,0 +1,273 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 type { IMenuSchema } from '@univerjs/ui';+import type { Root } from 'react-dom/client';+import {+ CommandService,+ ConfigService,+ ICommandService,+ IConfigService,+ ILogService,+ Injector,+ LocaleService,+ toDisposable,+} from '@univerjs/core';+import {+ ComponentManager,+ IconManager,+ ILayoutService,+ IMenuManagerService,+ IShortcutService,+ MenuItemType,+ MenuManagerPosition,+ RediContext,+} from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { SetInlineFormatBoldCommand } from '../../../commands/commands/inline-format.command';+import { FLOAT_TEXT_STYLE_MENU_ID, FLOAT_TOOLBAR_MENU_POSITION } from '../../../menu/menu';+import { FloatToolbar, resolveFloatToolbarMenus } from '../FloatToolbar';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const HYPERLINK_MENU_ID = 'doc.operation.show-hyper-link-edit-popup';+const COMMENT_MENU_ID = 'docs.operation.start-add-comment';++class TestMenuManagerService {+ readonly menuChanged$ = new Subject<void>();+ private _floatToolbarMenus: IMenuSchema[] = [];+ private _ribbonMenus: IMenuSchema[] = [];++ setMenus(floatToolbarMenus: IMenuSchema[], ribbonMenus: IMenuSchema[] = []): void {+ this._floatToolbarMenus = floatToolbarMenus;+ this._ribbonMenus = ribbonMenus;+ this.menuChanged$.next();+ }++ mergeMenu(): void {}+ appendRootMenu(): void {}++ getMenuByPositionKey(position: string): IMenuSchema[] {+ return position === FLOAT_TOOLBAR_MENU_POSITION ? this._floatToolbarMenus : [];+ }++ getFlatMenuByPositionKey(position: string): IMenuSchema[] {+ if (position === FLOAT_TOOLBAR_MENU_POSITION) {+ return this._floatToolbarMenus;+ }+ if (position === MenuManagerPosition.RIBBON) {+ return this._ribbonMenus;+ }+ return [];+ }+}++class TestLocaleService {+ t(key: string): string {+ return key;+ }+}++class TestLayoutService {+ readonly rootContainerElement = document.body;+ private _focused = false;++ get isFocused() {+ return this._focused;+ }++ focus(): void {+ this._focused = true;+ }++ registerFocusHandler(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerRootContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContentElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ getContentElement(): HTMLElement {+ return document.body;+ }++ checkElementInCurrentContainers(): boolean {+ return true;+ }++ checkContentIsFocused(): boolean {+ return this._focused;+ }+}++class TestShortcutService {+ readonly shortcutChanged$ = new Subject<void>();++ forceEscape(): IDisposable {+ return toDisposable(() => undefined);+ }++ forceDisable(): IDisposable {+ return toDisposable(() => undefined);+ }++ dispatch(): undefined {+ return undefined;+ }++ registerShortcut(): IDisposable {+ return toDisposable(() => undefined);+ }++ getShortcutDisplay(): string | null {+ return null;+ }++ getShortcutDisplayOfCommand(): string | null {+ return null;+ }++ getAllShortcuts() {+ return [];+ }+}++class TestLogService {+ warn(): void {}+}++function createToolbarTestBed() {+ const injector = new Injector();+ injector.add([IMenuManagerService, { useClass: TestMenuManagerService as never }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);+ injector.add([IShortcutService, { useClass: TestShortcutService as never }]);+ injector.add([ILogService, { useClass: TestLogService as never }]);+ injector.add([ComponentManager]);+ injector.add([IconManager]);++ return {+ injector,+ menuManagerService: injector.get(IMenuManagerService) as unknown as TestMenuManagerService,+ };+}++function renderToolbar(injector: Injector, avaliableMenus: string[]) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <FloatToolbar avaliableMenus={avaliableMenus} />+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function createMenuItem(key: string, title = key): IMenuSchema {+ return {+ key,+ order: 0,+ item: {+ id: key,+ title,+ type: MenuItemType.BUTTON,+ },+ };+}++describe('FloatToolbar', () => {+ let root: Root | undefined;+ let container: HTMLElement | undefined;++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ root = undefined;+ container = undefined;+ });++ it('keeps whitelisted toolbar menus ordered and separates direct extension menus', () => {+ const textStyleItem = createMenuItem(FLOAT_TEXT_STYLE_MENU_ID);+ const boldItem = createMenuItem(SetInlineFormatBoldCommand.id);+ const hyperlinkItem = createMenuItem(HYPERLINK_MENU_ID);+ const commentItem = createMenuItem(COMMENT_MENU_ID);+ const menuManagerService = new TestMenuManagerService();+ menuManagerService.setMenus([textStyleItem, hyperlinkItem, commentItem], [boldItem]);++ const { menus, extraMenus } = resolveFloatToolbarMenus(menuManagerService as never, [+ FLOAT_TEXT_STYLE_MENU_ID,+ SetInlineFormatBoldCommand.id,+ ]);++ expect(menus.map((item) => item.key)).toEqual([+ FLOAT_TEXT_STYLE_MENU_ID,+ SetInlineFormatBoldCommand.id,+ ]);+ expect(extraMenus.map((item) => item.key)).toEqual([+ HYPERLINK_MENU_ID,+ COMMENT_MENU_ID,+ ]);+ });++ it('renders available menus and refreshes when the menu service changes', async () => {+ const testBed = createToolbarTestBed();+ const textStyleItem = createMenuItem(FLOAT_TEXT_STYLE_MENU_ID, 'Text style');+ const boldItem = createMenuItem(SetInlineFormatBoldCommand.id, 'Bold');+ const hyperlinkItem = createMenuItem(HYPERLINK_MENU_ID, 'Link');+ const commentItem = createMenuItem(COMMENT_MENU_ID, 'Comment');+ testBed.menuManagerService.setMenus([textStyleItem, hyperlinkItem], [boldItem]);++ const rendered = renderToolbar(testBed.injector, [+ FLOAT_TEXT_STYLE_MENU_ID,+ SetInlineFormatBoldCommand.id,+ ]);+ root = rendered.root;+ container = rendered.container;++ expect(container.textContent).toContain('Text style');+ expect(container.textContent).toContain('Bold');+ expect(container.textContent).toContain('Link');+ expect(container.textContent).not.toContain('Comment');++ await act(async () => {+ testBed.menuManagerService.setMenus([textStyleItem, hyperlinkItem, commentItem], [boldItem]);+ });++ expect(container.textContent).toContain('Comment');+ });+});diff --git a/packages/docs-ui/src/views/table/create/__tests__/TableCreate.spec.tsx b/packages/docs-ui/src/views/table/create/__tests__/TableCreate.spec.tsxnew file mode 100644index 0000000000..f73adf0124--- /dev/null+++ b/packages/docs-ui/src/views/table/create/__tests__/TableCreate.spec.tsx@@ -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 { Root } from 'react-dom/client';+import { Injector, LocaleService, LocaleType } from '@univerjs/core';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { DocCreateTableConfirm } from '../TableCreate';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++interface ITableSize {+ rowCount: number;+ colCount: number;+}++function createTableTestBed() {+ const injector = new Injector();+ injector.add([LocaleService, { useClass: LocaleService }]);++ injector.get(LocaleService).load({+ [LocaleType.ZH_CN]: {+ 'docs-ui': {+ toolbar: {+ table: {+ rowCount: 'Rows',+ colCount: 'Columns',+ },+ },+ },+ },+ });++ return { injector };+}++function renderTableCreate(+ tableCreateParams: ITableSize,+ handleRowColChange: (rowCount: number, colCount: number) => void+) {+ const { injector } = createTableTestBed();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ function render(params: ITableSize) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <DocCreateTableConfirm+ tableCreateParams={params}+ handleRowColChange={handleRowColChange}+ />+ </RediContext.Provider>+ );+ });+ }++ render(tableCreateParams);++ return {+ container,+ root,+ rerender: render,+ };+}++function getTableSizeInputs(container: HTMLElement): [HTMLInputElement, HTMLInputElement] {+ const inputs = Array.from(container.querySelectorAll('input'));+ if (inputs.length !== 2) {+ throw new Error(`Expected row and column inputs, received ${inputs.length}`);+ }++ return inputs as [HTMLInputElement, HTMLInputElement];+}++function changeInput(input: HTMLInputElement, value: string) {+ const prototypeValueSetter = Object.getOwnPropertyDescriptor(+ Object.getPrototypeOf(input),+ 'value'+ )?.set;++ prototypeValueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++describe('DocCreateTableConfirm', () => {+ let root: Root | undefined;+ let container: HTMLElement | undefined;++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ root = undefined;+ container = undefined;+ });++ it('emits the current table size when row and column inputs change', () => {+ const emittedSizes: ITableSize[] = [];+ const rendered = renderTableCreate({ rowCount: 2, colCount: 4 }, (rowCount, colCount) => {+ emittedSizes.push({ rowCount, colCount });+ });+ root = rendered.root;+ container = rendered.container;++ let [rowInput, colInput] = getTableSizeInputs(container);++ act(() => changeInput(rowInput, '7'));+ [rowInput, colInput] = getTableSizeInputs(container);+ act(() => changeInput(colInput, '9'));++ expect(emittedSizes).toEqual([+ { rowCount: 7, colCount: 4 },+ { rowCount: 7, colCount: 9 },+ ]);+ expect([rowInput.value, colInput.value]).toEqual(['7', '9']);+ });++ it('syncs input values when table size props change', () => {+ const emittedSizes: ITableSize[] = [];+ const rendered = renderTableCreate({ rowCount: 3, colCount: 5 }, (rowCount, colCount) => {+ emittedSizes.push({ rowCount, colCount });+ });+ root = rendered.root;+ container = rendered.container;++ rendered.rerender({ rowCount: 12, colCount: 8 });++ const [rowInput, colInput] = getTableSizeInputs(container);+ expect([rowInput.value, colInput.value]).toEqual(['12', '8']);+ expect(emittedSizes).toEqual([]);+ });+});diff --git a/packages/docs/src/commands/mutations/__tests__/docs-rename.mutation.spec.ts b/packages/docs/src/commands/mutations/__tests__/docs-rename.mutation.spec.tsnew file mode 100644index 0000000000..960359dbed--- /dev/null+++ b/packages/docs/src/commands/mutations/__tests__/docs-rename.mutation.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 { DocumentDataModel, IDocumentData } from '@univerjs/core';+import { ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DocsRenameMutation } from '../docs-rename.mutation';++const unitId = 'rename-doc';++function createDocData(): IDocumentData {+ return {+ id: unitId,+ title: 'Original document',+ body: {+ dataStream: 'Hello\r\n',+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++describe('DocsRenameMutation', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let univerInstanceService: IUniverInstanceService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData());+ commandService = injector.get(ICommandService);+ commandService.registerCommand(DocsRenameMutation);+ univerInstanceService = injector.get(IUniverInstanceService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('renames the target document unit', async () => {+ const result = await commandService.executeCommand(DocsRenameMutation.id, {+ unitId,+ name: 'Quarterly notes',+ });++ expect(result).toBe(true);+ expect(univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)?.getSnapshot().title).toBe('Quarterly notes');+ });++ it('does not rename when the target document does not exist', async () => {+ const result = await commandService.executeCommand(DocsRenameMutation.id, {+ unitId: 'missing-doc',+ name: 'Missing',+ });++ expect(result).toBe(false);+ expect(univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC)?.getSnapshot().title).toBe('Original document');+ });+});diff --git a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.tsnew file mode 100644index 0000000000..35854949d8--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-selection-manager.service.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 { CommandService, ConfigService, ContextService, DesktopLogService, ICommandService, IConfigService, IContextService, ILogService, Injector, IUniverInstanceService, UniverInstanceService } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocSelectionManagerService } from '../doc-selection-manager.service';++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([DocSelectionManagerService]);+ return injector.get(DocSelectionManagerService);+}++describe('DocSelectionManagerService', () => {+ it('stores document text selections and exposes active/doc range ordering', () => {+ const service = createService();+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });++ service.__TEST_ONLY_add([{+ startOffset: 5,+ endOffset: 8,+ collapsed: false,+ isActive: false,+ }, {+ startOffset: 1,+ endOffset: 2,+ collapsed: false,+ isActive: true,+ }] as never);++ expect(service.getTextRanges()?.length).toBe(2);+ expect(service.getActiveTextRange()?.startOffset).toBe(1);+ expect(service.getDocRanges().map((range) => range.startOffset)).toEqual([1, 5]);+ });++ it('publishes refresh selection requests for current document ranges', () => {+ const service = createService();+ const refreshes: unknown[] = [];+ const sub = service.refreshSelection$.subscribe((value) => refreshes.push(value));+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });++ service.replaceTextRanges([{ startOffset: 2, endOffset: 4 }], false, { keepVisible: true });++ expect(refreshes.at(-1)).toEqual({+ unitId: 'doc-1',+ subUnitId: 'doc-1',+ docRanges: [{ startOffset: 2, endOffset: 4 }],+ isEditing: false,+ options: { keepVisible: true },+ });+ sub.unsubscribe();+ });+});diff --git a/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.spec.tsnew file mode 100644index 0000000000..669d5117e3--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-skeleton-manager.service.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 {+ ContextService,+ DesktopLogService,+ DocumentDataModel,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ UniverInstanceService,+ UniverInstanceType,+} from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DocSkeletonManagerService } from '../doc-skeleton-manager.service';++function createDocument() {+ return new DocumentDataModel({+ id: 'doc-1',+ body: {+ dataStream: 'Hello\r\n',+ paragraphs: [{ paragraphId: 'p1', startIndex: 5 }],+ sectionBreaks: [{ startIndex: 7 }],+ customRanges: [],+ customDecorations: [],+ customBlocks: [],+ tables: [],+ },+ documentStyle: {+ pageSize: { width: 594, height: 840 },+ },+ });+}++describe('DocSkeletonManagerService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('builds and publishes a document skeleton for the render context document', () => {+ vi.stubGlobal('document', {+ getElementById: () => null,+ getElementsByTagName: () => [{ appendChild: vi.fn() }],+ createElement: () => ({+ id: '',+ style: { cssText: '' },+ textContent: '',+ getBoundingClientRect: () => ({ width: 40, height: 10 }),+ getContext: () => ({+ font: '',+ measureText: (content: string) => ({+ actualBoundingBoxAscent: 8,+ actualBoundingBoxDescent: 2,+ width: content.length * 8,+ }),+ }),+ }),+ });+ const injector = new Injector();+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([LocaleService]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ const document = createDocument();+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(document);++ const service = injector.createInstance(DocSkeletonManagerService, {+ unit: document,+ unitId: 'doc-1',+ type: UniverInstanceType.UNIVER_DOC,+ } as never);++ expect(service.getViewModel().getDataModel().getUnitId()).toBe('doc-1');+ expect(service.getSkeleton()).toBeTruthy();+ });+});diff --git a/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.tsnew file mode 100644index 0000000000..b08794ea74--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-state-change-manager.service.spec.ts@@ -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 {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ DocumentDataModel,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ LocalUndoRedoService,+ UniverInstanceService,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocStateChangeManagerService } from '../doc-state-change-manager.service';+import { DocStateEmitService } from '../doc-state-emit.service';++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ injector.add([DocStateEmitService]);+ injector.add([DocStateChangeManagerService]);+ return {+ service: injector.get(DocStateChangeManagerService),+ emitter: injector.get(DocStateEmitService),+ undoRedoService: injector.get(IUndoRedoService),+ univerInstanceService: injector.get(IUniverInstanceService) as UniverInstanceService,+ };+}++describe('DocStateChangeManagerService', () => {+ it('turns emitted document edits into history items and collaboration change events', () => {+ const { service, emitter, undoRedoService, univerInstanceService } = createService();+ const changes: unknown[] = [];+ const sub = service.docStateChange$.subscribe((value) => changes.push(value));+ univerInstanceService.__addUnit(new DocumentDataModel({ id: 'doc-1' }));+ univerInstanceService.focusUnit('doc-1');+ const change = {+ commandId: 'doc.rich-text-editing',+ unitId: 'doc-1',+ trigger: 'keyboard',+ redoState: { actions: null as never, textRanges: [{ startOffset: 1, endOffset: 1, collapsed: true }] },+ undoState: { actions: null as never, textRanges: [{ startOffset: 0, endOffset: 0, collapsed: true }] },+ };++ emitter.emitStateChangeInfo(change);++ expect(undoRedoService.pitchTopUndoElement()).toMatchObject({+ unitID: 'doc-1',+ undoMutations: [{ id: 'doc.rich-text-editing' }],+ redoMutations: [{ id: 'doc.rich-text-editing' }],+ });+ expect(changes.at(-1)).toMatchObject({+ commandId: 'doc.rich-text-editing',+ unitId: 'doc-1',+ trigger: 'keyboard',+ });++ sub.unsubscribe();+ });+});diff --git a/packages/docs/src/services/__tests__/doc-state-emit.service.spec.ts b/packages/docs/src/services/__tests__/doc-state-emit.service.spec.tsnew file mode 100644index 0000000000..3f21b79258--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-state-emit.service.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 { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocStateEmitService } from '../doc-state-emit.service';++function createService(): DocStateEmitService {+ const injector = new Injector();+ injector.add([DocStateEmitService]);+ return injector.get(DocStateEmitService);+}++describe('DocStateEmitService', () => {+ it('publishes document change payloads to collaboration/history consumers', () => {+ const service = createService();+ const emitted: unknown[] = [];+ const sub = service.docStateChangeParams$.subscribe((value) => emitted.push(value));+ const change = {+ commandId: 'doc.command',+ unitId: 'doc-1',+ trigger: 'keyboard',+ redoState: { actions: [], textRanges: null },+ undoState: { actions: [], textRanges: null },+ isSync: true,+ };++ service.emitStateChangeInfo(change);++ expect(emitted).toEqual([null, change]);+ sub.unsubscribe();+ });+});diff --git a/packages/docs/src/services/__tests__/doc-view-model-manager.service.spec.ts b/packages/docs/src/services/__tests__/doc-view-model-manager.service.spec.tsnew file mode 100644index 0000000000..4891da4a65--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-view-model-manager.service.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 {+ ContextService,+ DesktopLogService,+ DocumentDataModel,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ UniverInstanceService,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DocViewModelManagerService } from '../doc-view-model-manager.service';++describe('DocViewModelManagerService', () => {+ it('creates view models for existing documents and removes them when the document unit is disposed', () => {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ univerInstanceService.__addUnit(new DocumentDataModel({+ id: 'doc-1',+ body: {+ dataStream: '\r\n',+ paragraphs: [{ startIndex: 1, paragraphId: 'paragraph-1' }],+ sectionBreaks: [],+ tables: [],+ customRanges: [],+ customDecorations: [],+ customBlocks: [],+ },+ }));++ const service = injector.createInstance(DocViewModelManagerService, { unitId: 'doc-1' } as never);+ expect(service.getViewModel('doc-1')?.getDataModel().getUnitId()).toBe('doc-1');++ univerInstanceService.disposeUnit('doc-1');+ expect(service.getAllModel().has('doc-1')).toBe(false);+ });+});diff --git a/packages/docs/src/services/doc-interceptor/__tests__/doc-interceptor.service.spec.ts b/packages/docs/src/services/doc-interceptor/__tests__/doc-interceptor.service.spec.tsnew file mode 100644index 0000000000..70aef75668--- /dev/null+++ b/packages/docs/src/services/doc-interceptor/__tests__/doc-interceptor.service.spec.ts@@ -0,0 +1,86 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICustomRangeForInterceptor } from '@univerjs/core';+import { Injector } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { DocSkeletonManagerService } from '../../doc-skeleton-manager.service';+import { DocInterceptorService } from '../doc-interceptor.service';+import { DOC_INTERCEPTOR_POINT } from '../interceptor-const';++function createViewModel(unitId = 'doc-1') {+ let interceptor: { getCustomRange: (index: number) => ICustomRangeForInterceptor | null } | null = null;+ return {+ segmentViewModels$: new BehaviorSubject([]),+ registerCustomRangeInterceptor: (value: typeof interceptor) => {+ interceptor = value;+ return {+ dispose: () => {+ interceptor = null;+ },+ };+ },+ getCustomRangeRaw: (index: number): ICustomRangeForInterceptor => ({+ startIndex: index,+ endIndex: index + 1,+ rangeId: `range-${index}`,+ rangeType: 1,+ }),+ getCustomDecorationRaw: () => null,+ getDataModel: () => ({+ getUnitId: () => unitId,+ getCustomRanges: () => [],+ getCustomDecorations: () => [],+ }),+ readRange: (index: number) => interceptor?.getCustomRange(index),+ };+}++class TestDocSkeletonManagerService {+ readonly viewModel = createViewModel();++ getViewModel() {+ return this.viewModel;+ }+}++const TestDocSkeletonManagerServiceCtor = TestDocSkeletonManagerService as unknown as typeof DocSkeletonManagerService;++describe('DocInterceptorService', () => {+ it('composes document view-model interceptors before custom ranges are rendered', () => {+ const injector = new Injector();+ injector.add([DocSkeletonManagerService, { useClass: TestDocSkeletonManagerServiceCtor }]);+ const viewModel = (injector.get(DocSkeletonManagerService) as unknown as TestDocSkeletonManagerService).viewModel;++ const service = injector.createInstance(DocInterceptorService, {} as never);+ service.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {+ priority: 1,+ handler: (range, _context, next) => {+ const baseRange = next(range);+ return baseRange == null ? baseRange : { ...baseRange, user: 'u1' };+ },+ });++ expect(viewModel.readRange(3)).toEqual({+ startIndex: 3,+ endIndex: 4,+ rangeId: 'range-3',+ rangeType: 1,+ user: 'u1',+ });+ });+});diff --git a/packages/drawing-ui/src/commands/operations/__tests__/drawing-arrange-group.operation.spec.ts b/packages/drawing-ui/src/commands/operations/__tests__/drawing-arrange-group.operation.spec.tsnew file mode 100644index 0000000000..43802f4430--- /dev/null+++ b/packages/drawing-ui/src/commands/operations/__tests__/drawing-arrange-group.operation.spec.ts@@ -0,0 +1,357 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDrawingParam } from '@univerjs/core';+import type { IDrawingGroupUpdateParam, IDrawingOrderUpdateParam } from '@univerjs/drawing';+import { ArrangeTypeEnum, DrawingTypeEnum, ICommandService, Univer } from '@univerjs/core';+import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ AlignType,+ SetDrawingAlignBottomOperation,+ SetDrawingAlignCenterOperation,+ SetDrawingAlignHorizonOperation,+ SetDrawingAlignLeftOperation,+ SetDrawingAlignMiddleOperation,+ SetDrawingAlignOperation,+ SetDrawingAlignRightOperation,+ SetDrawingAlignTopOperation,+ SetDrawingAlignVerticalOperation,+} from '../drawing-align.operation';+import {+ SetDrawingArrangeBackOperation,+ SetDrawingArrangeBackwardOperation,+ SetDrawingArrangeForwardOperation,+ SetDrawingArrangeFrontOperation,+ SetDrawingArrangeOperation,+} from '../drawing-arrange.operation';+import { CancelDrawingGroupOperation, SetDrawingGroupOperation } from '../drawing-group.operation';+import { AutoImageCropOperation, CloseImageCropOperation, CropType, OpenImageCropOperation } from '../image-crop.operation';+import { ImageResetSizeOperation } from '../image-reset-size.operation';++const unitId = 'drawing-ui-unit';+const subUnitId = 'drawing-ui-subunit';++function createDrawing(drawingId: string, left: number): IDrawingParam {+ return {+ unitId,+ subUnitId,+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ transform: {+ left,+ top: 10,+ width: 20,+ height: 30,+ },+ };+}++describe('drawing arrange and group operations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let drawingManagerService: IDrawingManagerService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(SetDrawingArrangeOperation);+ commandService.registerCommand(SetDrawingArrangeFrontOperation);+ commandService.registerCommand(SetDrawingArrangeForwardOperation);+ commandService.registerCommand(SetDrawingArrangeBackOperation);+ commandService.registerCommand(SetDrawingArrangeBackwardOperation);+ commandService.registerCommand(SetDrawingGroupOperation);+ commandService.registerCommand(CancelDrawingGroupOperation);+ commandService.registerCommand(SetDrawingAlignOperation);+ commandService.registerCommand(SetDrawingAlignLeftOperation);+ commandService.registerCommand(SetDrawingAlignCenterOperation);+ commandService.registerCommand(SetDrawingAlignRightOperation);+ commandService.registerCommand(SetDrawingAlignTopOperation);+ commandService.registerCommand(SetDrawingAlignMiddleOperation);+ commandService.registerCommand(SetDrawingAlignBottomOperation);+ commandService.registerCommand(SetDrawingAlignHorizonOperation);+ commandService.registerCommand(SetDrawingAlignVerticalOperation);+ commandService.registerCommand(OpenImageCropOperation);+ commandService.registerCommand(CloseImageCropOperation);+ commandService.registerCommand(AutoImageCropOperation);+ commandService.registerCommand(ImageResetSizeOperation);+ drawingManagerService = injector.get(IDrawingManagerService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('requests a layer-order change for the selected drawings', async () => {+ const orderUpdates: IDrawingOrderUpdateParam[] = [];+ drawingManagerService.featurePluginOrderUpdate$.subscribe((update) => orderUpdates.push(update));++ const result = await commandService.executeCommand(SetDrawingArrangeOperation.id, {+ arrangeType: ArrangeTypeEnum.front,+ drawings: [createDrawing('image-1', 0), createDrawing('image-2', 30)],+ });++ expect(result).toBe(true);+ expect(orderUpdates).toEqual([{+ unitId,+ subUnitId,+ drawingIds: ['image-1', 'image-2'],+ arrangeType: ArrangeTypeEnum.front,+ }]);+ });++ it('uses the focused drawings when arranging from the front command', async () => {+ drawingManagerService.registerDrawingData(unitId, {+ [subUnitId]: {+ data: {+ 'image-1': createDrawing('image-1', 0),+ 'image-2': createDrawing('image-2', 30),+ },+ order: ['image-1', 'image-2'],+ },+ });+ drawingManagerService.focusDrawing([+ { unitId, subUnitId, drawingId: 'image-1' },+ { unitId, subUnitId, drawingId: 'image-2' },+ ]);+ const orderUpdates: IDrawingOrderUpdateParam[] = [];+ drawingManagerService.featurePluginOrderUpdate$.subscribe((update) => orderUpdates.push(update));++ const result = await commandService.executeCommand(SetDrawingArrangeFrontOperation.id);++ expect(result).toBe(true);+ expect(orderUpdates).toEqual([{+ unitId,+ subUnitId,+ drawingIds: ['image-1', 'image-2'],+ arrangeType: ArrangeTypeEnum.front,+ }]);+ });++ it('uses focused drawings for forward, backward and back layer commands', async () => {+ drawingManagerService.registerDrawingData(unitId, {+ [subUnitId]: {+ data: {+ 'image-1': createDrawing('image-1', 0),+ 'image-2': createDrawing('image-2', 30),+ },+ order: ['image-1', 'image-2'],+ },+ });+ drawingManagerService.focusDrawing([+ { unitId, subUnitId, drawingId: 'image-1' },+ { unitId, subUnitId, drawingId: 'image-2' },+ ]);+ const orderUpdates: IDrawingOrderUpdateParam[] = [];+ drawingManagerService.featurePluginOrderUpdate$.subscribe((update) => orderUpdates.push(update));++ expect(await commandService.executeCommand(SetDrawingArrangeForwardOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingArrangeBackwardOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingArrangeBackOperation.id)).toBe(true);++ const arrangeTypes: ArrangeTypeEnum[] = [];+ for (const update of orderUpdates) {+ arrangeTypes.push(update.arrangeType as ArrangeTypeEnum);+ expect(update).toMatchObject({+ unitId,+ subUnitId,+ drawingIds: ['image-1', 'image-2'],+ });+ }+ expect(arrangeTypes).toEqual([+ ArrangeTypeEnum.forward,+ ArrangeTypeEnum.backward,+ ArrangeTypeEnum.back,+ ]);+ });++ it('groups two selected drawings under a generated group drawing', async () => {+ const groupUpdates: IDrawingGroupUpdateParam[][] = [];+ drawingManagerService.featurePluginGroupUpdate$.subscribe((update) => groupUpdates.push(update));++ const result = await commandService.executeCommand(SetDrawingGroupOperation.id, {+ drawings: [createDrawing('image-1', 0), createDrawing('image-2', 30)],+ });++ expect(result).toBe(true);+ expect(groupUpdates).toHaveLength(1);+ expect(groupUpdates[0]).toHaveLength(1);+ expect(groupUpdates[0][0].parent).toMatchObject({+ unitId,+ subUnitId,+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ });++ const childIds: string[] = [];+ for (const child of groupUpdates[0][0].children) {+ childIds.push(child.drawingId);+ expect(child.groupId).toBe(groupUpdates[0][0].parent.drawingId);+ }+ expect(childIds).toEqual(['image-1', 'image-2']);+ });++ it('does not create a drawing group from a single selected drawing', async () => {+ const groupUpdates: IDrawingGroupUpdateParam[][] = [];+ drawingManagerService.featurePluginGroupUpdate$.subscribe((update) => groupUpdates.push(update));++ const result = await commandService.executeCommand(SetDrawingGroupOperation.id, {+ drawings: [createDrawing('image-1', 0)],+ });++ expect(result).toBe(false);+ expect(groupUpdates).toEqual([]);+ });++ it('ungroups a focused drawing group and restores children to the sheet layer', async () => {+ drawingManagerService.registerDrawingData(unitId, {+ [subUnitId]: {+ data: {},+ order: ['group', 'image-1', 'image-2'],+ },+ });+ drawingManagerService.setDrawingData(unitId, subUnitId, {+ group: {+ unitId,+ subUnitId,+ drawingId: 'group',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ transform: { left: 10, top: 20, width: 100, height: 80 },+ groupBaseBound: { left: 10, top: 20, width: 100, height: 80 },+ },+ 'image-1': {+ ...createDrawing('image-1', 0),+ groupId: 'group',+ },+ 'image-2': {+ ...createDrawing('image-2', 30),+ groupId: 'group',+ },+ });+ drawingManagerService.focusDrawing([{ unitId, subUnitId, drawingId: 'group' }]);+ const ungroupUpdates: IDrawingGroupUpdateParam[][] = [];+ drawingManagerService.featurePluginUngroupUpdate$.subscribe((update) => ungroupUpdates.push(update));++ const result = await commandService.executeCommand(CancelDrawingGroupOperation.id, {});++ expect(result).toBe(true);+ expect(ungroupUpdates).toHaveLength(1);+ expect(ungroupUpdates[0][0].parent).toMatchObject({+ unitId,+ subUnitId,+ drawingId: 'group',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ });++ const childIds: string[] = [];+ for (const child of ungroupUpdates[0][0].children) {+ childIds.push(child.drawingId);+ expect(child.groupId).toBeUndefined();+ }+ expect(childIds).toEqual(['image-1', 'image-2']);+ });++ it('does not ungroup regular drawings', async () => {+ const ungroupUpdates: IDrawingGroupUpdateParam[][] = [];+ drawingManagerService.featurePluginUngroupUpdate$.subscribe((update) => ungroupUpdates.push(update));++ const result = await commandService.executeCommand(CancelDrawingGroupOperation.id, {+ drawings: [createDrawing('image-1', 0), createDrawing('image-2', 30)],+ });++ expect(result).toBe(false);+ expect(ungroupUpdates).toEqual([]);+ });++ it('translates drawing alignment menu actions into concrete alignment operations', async () => {+ const executedCommands: ICommandInfo[] = [];+ commandService.onCommandExecuted((command) => executedCommands.push(command));++ expect(await commandService.executeCommand(SetDrawingAlignLeftOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignCenterOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignRightOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignTopOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignMiddleOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignBottomOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignHorizonOperation.id)).toBe(true);+ expect(await commandService.executeCommand(SetDrawingAlignVerticalOperation.id)).toBe(true);++ const alignTypes: AlignType[] = [];+ for (const command of executedCommands) {+ if (command.id === SetDrawingAlignOperation.id) {+ alignTypes.push((command.params as { alignType: AlignType }).alignType);+ }+ }++ expect(alignTypes).toEqual([+ AlignType.left,+ AlignType.center,+ AlignType.right,+ AlignType.top,+ AlignType.middle,+ AlignType.bottom,+ AlignType.horizon,+ AlignType.vertical,+ ]);+ });++ it('publishes image crop lifecycle operations with the target drawing and crop mode', async () => {+ const executedCommands: ICommandInfo[] = [];+ commandService.onCommandExecuted((command) => executedCommands.push(command));+ const targetDrawing = { unitId, subUnitId, drawingId: 'image-1' };++ expect(await commandService.executeCommand(OpenImageCropOperation.id, targetDrawing)).toBe(true);+ expect(await commandService.executeCommand(AutoImageCropOperation.id, { cropType: CropType.R16_9 })).toBe(true);+ expect(await commandService.executeCommand(CloseImageCropOperation.id, { isAuto: true })).toBe(true);++ expect(executedCommands).toEqual([+ {+ id: OpenImageCropOperation.id,+ type: OpenImageCropOperation.type,+ params: targetDrawing,+ },+ {+ id: AutoImageCropOperation.id,+ type: AutoImageCropOperation.type,+ params: { cropType: CropType.R16_9 },+ },+ {+ id: CloseImageCropOperation.id,+ type: CloseImageCropOperation.type,+ params: { isAuto: true },+ },+ ]);+ });++ it('publishes image reset-size operation for selected image drawings', async () => {+ const executedCommands: ICommandInfo[] = [];+ commandService.onCommandExecuted((command) => executedCommands.push(command));+ const selectedImages = [+ { unitId, subUnitId, drawingId: 'image-1' },+ { unitId, subUnitId, drawingId: 'image-2' },+ ];++ expect(await commandService.executeCommand(ImageResetSizeOperation.id, selectedImages)).toBe(true);++ expect(executedCommands).toEqual([{+ id: ImageResetSizeOperation.id,+ type: ImageResetSizeOperation.type,+ params: selectedImages,+ }]);+ });+});diff --git a/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.tsindex 703ac4f474..4b2d656765 100644--- a/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.ts+++ b/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.ts@@ -47,4 +47,13 @@ describe('DrawingImageClipService', () => {expect(values).toEqual([false, true]);});++ it('clears registered clipping behavior when disposed', () => {+ const delegate = vi.fn(() => ({ left: 0, top: 0, width: 20, height: 10 }));+ service.registerClipDelegate(delegate);++ service.dispose();++ expect(service.applyShapeClip({} as never, 'rect', 20, 10)).toBe(false);+ });});diff --git a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.tsindex dd6047b6df..78d6eccb68 100644--- a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts+++ b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts@@ -14,118 +14,517 @@* limitations under the License.*/-import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';-import { getDrawingShapeKeyByDrawingSearch, ImageSourceType } from '@univerjs/drawing';+import type { IDrawingSearch } from '@univerjs/core';+import type { IGalleryProps } from '@univerjs/design';+import type { IDocFloatDomData, IImageData } from '@univerjs/drawing';+import type { BaseObject, Scene } from '@univerjs/engine-render';+import {+ DrawingTypeEnum,+ Injector,+ IUniverInstanceService,+ IURLImageService,+ toDisposable,+ UniverInstanceType,+} from '@univerjs/core';+import {+ getDrawingShapeKeyByDrawingSearch,+ IDrawingManagerService,+ IImageIoService,+ ImageSourceType,+} from '@univerjs/drawing';+import { DRAWING_OBJECT_LAYER_INDEX, Image, Rect } from '@univerjs/engine-render';+import { IGalleryService } from '@univerjs/ui';+import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';+import { DrawingImageClipService } from '../drawing-image-clip.service';import { DrawingRenderService } from '../drawing-render.service';-vi.mock('@univerjs/drawing', async (importActual) => {- const actual = await importActual<typeof import('@univerjs/drawing')>();+const BASE_TRANSFORM = {+ left: 10,+ top: 20,+ width: 30,+ height: 40,+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+};++const SECOND_TRANSFORM = {+ left: 50,+ top: 60,+ width: 70,+ height: 80,+ angle: 15,+ flipX: true,+ flipY: false,+ skewX: 1,+ skewY: 2,+};++function imageParam(overrides: Partial<IImageData> = {}): IImageData {return {- ...actual,- getDrawingShapeKeyByDrawingSearch: vi.fn(() => 'shape-key'),- };-});+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ drawingId: 'drawing-1',+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ source: 'image-source',+ imageSourceType: ImageSourceType.BASE64,+ transform: BASE_TRANSFORM,+ ...overrides,+ } as IImageData;+}-function createService(options?: { unitType?: UniverInstanceType; visible?: boolean; activeSheetId?: string }) {- const drawingManagerService = {- getDrawingVisible: vi.fn(() => options?.visible ?? true),- getDrawingEditable: vi.fn(() => true),- getDrawingOrder: vi.fn(() => ['drawing-1']),- };- const imageIoService = {- getImageSourceCache: vi.fn(),- getImage: vi.fn(),- addImageSourceCache: vi.fn(),- };- const urlImageService = {- getImage: vi.fn(),- };- const univerInstanceService = {- getUnitType: vi.fn(() => options?.unitType ?? UniverInstanceType.UNIVER_DOC),- getCurrentUnitOfType: vi.fn(() => ({- getActiveSheet: vi.fn(() => ({ getSheetId: vi.fn(() => options?.activeSheetId ?? 'sheet-1') })),- })),- };- const scene = {- getObject: vi.fn(() => null),- addObject: vi.fn(),- attachTransformerTo: vi.fn(),+function floatDomParam(overrides: Partial<IDocFloatDomData> = {}): IDocFloatDomData {+ return {+ drawingType: DrawingTypeEnum.DRAWING_DOM,+ drawingId: 'float-1',+ unitId: 'doc-1',+ subUnitId: 'doc-1',+ transform: BASE_TRANSFORM,+ ...overrides,+ } as IDocFloatDomData;+}++function drawingKey(param: IDrawingSearch, index?: number) {+ return getDrawingShapeKeyByDrawingSearch(param, index);+}++function cacheKey(source: string, imageSourceType: ImageSourceType) {+ return `${source}:${imageSourceType}`;+}++class TestDrawingManagerService {+ visible = true;+ editable = true;+ orders = ['drawing-1'];+ visibleReads: boolean[] = [];+ readonly drawings = new Map<string, unknown>();++ getDrawingVisible() {+ return this.visibleReads.length > 0 ? this.visibleReads.shift()! : this.visible;+ }++ getDrawingEditable() {+ return this.editable;+ }++ getDrawingOrder() {+ return this.orders;+ }++ getDrawingByParam(param: IDrawingSearch | null | undefined) {+ if (param == null) {+ return null;+ }++ return this.drawings.get(drawingKey(param)) ?? null;+ }+}++class TestImageIoService {+ imageUrl = 'resolved-image-url';+ imageError: unknown;+ beforeResolveImage: (() => void) | undefined;+ readonly imageRequests: string[] = [];+ readonly cache = new Map<string, HTMLImageElement>();+ readonly cacheWrites: Array<{ source: string; imageSourceType: ImageSourceType; image: HTMLImageElement | null }> = [];+ readonly change$ = new Subject<number>();++ setWaitCount() {+ // not used by DrawingRenderService+ }++ async saveImage() {+ return null;+ }++ async getImage(imageId: string) {+ this.imageRequests.push(imageId);+ this.beforeResolveImage?.();+ if (this.imageError) {+ throw this.imageError;+ }+ return this.imageUrl;+ }++ getImageSourceCache(source: string, imageSourceType: ImageSourceType) {+ return this.cache.get(cacheKey(source, imageSourceType)) ?? null;+ }++ addImageSourceCache(source: string, imageSourceType: ImageSourceType, image: HTMLImageElement | null) {+ this.cacheWrites.push({ source, imageSourceType, image });+ if (image) {+ this.cache.set(cacheKey(source, imageSourceType), image);+ }+ }+}++class TestUrlImageService {+ imageUrl = 'downloaded-image-url';+ imageError: unknown;+ readonly requests: string[] = [];++ async getImage(url: string) {+ this.requests.push(url);+ if (this.imageError) {+ throw this.imageError;+ }+ return this.imageUrl;+ }++ async downloadImage() {+ return new Blob();+ }++ registerURLImageDownloader() {+ return toDisposable(() => {});+ }+}++class TestGalleryService {+ gallery$ = new Subject<IGalleryProps>();+ lastOpen: IGalleryProps | undefined;+ closeCount = 0;++ open(params: IGalleryProps) {+ this.lastOpen = params;+ return toDisposable(() => {});+ }++ close() {+ this.closeCount += 1;+ }+}++class TestUniverInstanceService {+ unitType = UniverInstanceType.UNIVER_DOC;+ activeSheetId = 'sheet-1';++ getUnitType() {+ return this.unitType;+ }++ getCurrentUnitOfType() {+ return {+ getActiveSheet: () => ({+ getSheetId: () => this.activeSheetId,+ }),+ };+ }+}++interface IRecordedScene {+ readonly objects: Map<string, BaseObject | ITransformRecorder>;+ readonly addedObjects: Array<{ object: BaseObject; layerIndex: number }>;+ readonly transformerObjects: BaseObject[];+ readonly getObjectKeys: string[];+ getObject(key: string): BaseObject | ITransformRecorder | null;+ getObjectIncludeInGroup(key: string): BaseObject | ITransformRecorder | null;+ addObject(object: BaseObject, layerIndex: number): Scene;+ attachTransformerTo(object: BaseObject): Scene;+}++interface ITransformRecorder {+ readonly oKey: string;+ readonly transformCalls: unknown[];+ transformByState(state: unknown): void;+}++function createTransformRecorder(oKey: string): ITransformRecorder {+ return {+ oKey,+ transformCalls: [],+ transformByState(state: unknown) {+ this.transformCalls.push(state);+ },};+}- const drawingImageClipService = {- applyShapeClip: vi.fn(),+function createScene(): IRecordedScene {+ const scene: IRecordedScene = {+ objects: new Map(),+ addedObjects: [],+ transformerObjects: [],+ getObjectKeys: [],+ getObject(key: string) {+ this.getObjectKeys.push(key);+ return this.objects.get(key) ?? null;+ },+ getObjectIncludeInGroup(key: string) {+ return this.objects.get(key) ?? null;+ },+ addObject(object: BaseObject, layerIndex: number) {+ this.objects.set(object.oKey, object);+ this.addedObjects.push({ object, layerIndex });+ return this as unknown as Scene;+ },+ attachTransformerTo(object: BaseObject) {+ this.transformerObjects.push(object);+ return this as unknown as Scene;+ },};+ return scene;+}++function createHarness() {+ const injector = new Injector();++ injector.add([IDrawingManagerService, { useClass: TestDrawingManagerService as never }]);+ injector.add([IImageIoService, { useClass: TestImageIoService as never }]);+ injector.add([IGalleryService, { useClass: TestGalleryService as never }]);+ injector.add([IURLImageService, { useClass: TestUrlImageService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([DrawingImageClipService]);+ injector.add([DrawingRenderService]);+return {- drawingManagerService,- imageIoService,- scene,- service: new DrawingRenderService(- drawingManagerService as never,- imageIoService as never,- {} as never,- urlImageService as never,- univerInstanceService as never,- drawingImageClipService as never- ),- univerInstanceService,+ service: injector.get(DrawingRenderService),+ drawingManagerService: injector.get(IDrawingManagerService) as unknown as TestDrawingManagerService,+ imageIoService: injector.get(IImageIoService) as unknown as TestImageIoService,+ urlImageService: injector.get(IURLImageService) as unknown as TestUrlImageService,+ galleryService: injector.get(IGalleryService) as unknown as TestGalleryService,+ univerInstanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,+ drawingImageClipService: injector.get(DrawingImageClipService),+ scene: createScene(),};}-const baseImageParam = {- drawingType: DrawingTypeEnum.DRAWING_IMAGE,- drawingId: 'drawing-1',- unitId: 'book-1',- subUnitId: 'sheet-1',- source: 'image-source',- imageSourceType: ImageSourceType.BASE64,- transform: { left: 10, top: 20, width: 30, height: 40, angle: 0, flipX: false, flipY: false, skewX: 0, skewY: 0 },-};-describe('DrawingRenderService', () => {- it('skips rendering when the drawing is not visible, not an image, on another sheet, or missing transform', async () => {- const hiddenCase = createService({ visible: false });- expect(await hiddenCase.service.renderImages(baseImageParam as never, hiddenCase.scene as never)).toBeUndefined();- expect(hiddenCase.scene.getObject).not.toHaveBeenCalled();-- const nonImageCase = createService();- expect(await nonImageCase.service.renderImages({ ...baseImageParam, drawingType: DrawingTypeEnum.DRAWING_SHAPE } as never, nonImageCase.scene as never)).toBeUndefined();- expect(nonImageCase.scene.getObject).not.toHaveBeenCalled();-- const inactiveSheetCase = createService({ unitType: UniverInstanceType.UNIVER_SHEET, activeSheetId: 'sheet-2' });- expect(await inactiveSheetCase.service.renderImages(baseImageParam as never, inactiveSheetCase.scene as never)).toBeUndefined();- expect(inactiveSheetCase.scene.getObject).not.toHaveBeenCalled();-- const noTransformCase = createService();- expect(await noTransformCase.service.renderImages({ ...baseImageParam, transform: null } as never, noTransformCase.scene as never)).toBeUndefined();- expect(noTransformCase.scene.getObject).not.toHaveBeenCalled();+ it('skips image rendering when the drawing is not renderable in the current context', async () => {+ const hiddenCase = createHarness();+ hiddenCase.drawingManagerService.visible = false;+ expect(await hiddenCase.service.renderImages(imageParam(), hiddenCase.scene as unknown as Scene)).toBeUndefined();+ expect(hiddenCase.scene.getObjectKeys).toEqual([]);++ const nonImageCase = createHarness();+ expect(await nonImageCase.service.renderImages(imageParam({ drawingType: DrawingTypeEnum.DRAWING_SHAPE }), nonImageCase.scene as unknown as Scene)).toBeUndefined();+ expect(nonImageCase.scene.getObjectKeys).toEqual([]);++ const inactiveSheetCase = createHarness();+ inactiveSheetCase.univerInstanceService.unitType = UniverInstanceType.UNIVER_SHEET;+ inactiveSheetCase.univerInstanceService.activeSheetId = 'sheet-2';+ expect(await inactiveSheetCase.service.renderImages(imageParam(), inactiveSheetCase.scene as unknown as Scene)).toBeUndefined();+ expect(inactiveSheetCase.scene.getObjectKeys).toEqual([]);++ const noTransformCase = createHarness();+ expect(await noTransformCase.service.renderImages(imageParam({ transform: null }), noTransformCase.scene as unknown as Scene)).toBeUndefined();+ expect(noTransformCase.scene.getObjectKeys).toEqual([]);+ });++ it('adds a base64 image with drawing metadata, cache, and transformer state', async () => {+ const { service, scene, drawingManagerService, imageIoService, drawingImageClipService } = createHarness();+ drawingManagerService.orders = ['background', 'drawing-1'];+ const srcRect = { left: 0.1, top: 0.2, right: 0.3, bottom: 0.4 };++ const result = await service.renderImages(imageParam({+ hidden: true,+ prstGeom: 'roundRect',+ adjustValues: { adj: 0.25 },+ srcRect,+ }), scene as unknown as Scene);++ const key = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' });+ const image = scene.objects.get(key) as Image;++ expect(result).toEqual([image]);+ expect(image).toBeInstanceOf(Image);+ expect(image.left).toBe(10);+ expect(image.top).toBe(20);+ expect(image.width).toBe(30);+ expect(image.height).toBe(40);+ expect(image.zIndex).toBe(1);+ expect(image.visible).toBe(false);+ expect(image.printable).toBe(true);+ expect(image.getProps().url).toBe('image-source');+ expect(image.getClipService()).toBe(drawingImageClipService);+ expect(image.prstGeom).toBe('roundRect');+ expect(image.prstGeomAdjValues).toEqual({ adj: 0.25 });+ expect(image.srcRect).toEqual(srcRect);+ expect(scene.addedObjects.map(({ object, layerIndex }) => [object.oKey, layerIndex])).toEqual([[key, DRAWING_OBJECT_LAYER_INDEX]]);+ expect(scene.transformerObjects).toEqual([image]);+ expect(imageIoService.cacheWrites).toEqual([{ source: 'image-source', imageSourceType: ImageSourceType.BASE64, image: image.getNative() }]);});- it('updates existing scene objects instead of recreating them', async () => {- const { scene, service } = createService();- const transformByState = vi.fn();- scene.getObject.mockReturnValue({ transformByState } as never);-- const result = await service.renderImages(baseImageParam as never, scene as never);-- expect(vi.mocked(getDrawingShapeKeyByDrawingSearch)).toHaveBeenCalledWith({- drawingId: 'drawing-1',- unitId: 'book-1',- subUnitId: 'sheet-1',- }, undefined);- expect(transformByState).toHaveBeenCalledWith({- left: 10,- top: 20,- width: 30,- height: 40,- angle: 0,- flipX: false,- flipY: false,- skewX: 0,- skewY: 0,- });- expect(scene.addObject).not.toHaveBeenCalled();+ it('uses cached native images instead of resolving the source again', async () => {+ const { service, scene, imageIoService } = createHarness();+ const nativeImage = document.createElement('img');+ imageIoService.cache.set(cacheKey('image-source', ImageSourceType.BASE64), nativeImage);++ await service.renderImages(imageParam(), scene as unknown as Scene);++ const image = scene.objects.get(drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' })) as Image;+ expect(image.getNative()).toBe(nativeImage);+ expect(imageIoService.imageRequests).toEqual([]);+ expect(imageIoService.cacheWrites).toEqual([]);+ });++ it('loads stored and URL images through their respective services', async () => {+ const uuidCase = createHarness();+ uuidCase.imageIoService.imageUrl = 'stored-image-url';+ await uuidCase.service.renderImages(imageParam({+ source: 'stored-image-id',+ imageSourceType: ImageSourceType.UUID,+ }), uuidCase.scene as unknown as Scene);+ const storedImage = uuidCase.scene.objects.get(drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' })) as Image;+ expect(storedImage.getProps().url).toBe('stored-image-url');+ expect(uuidCase.imageIoService.imageRequests).toEqual(['stored-image-id']);+ expect(uuidCase.imageIoService.cacheWrites).toEqual([]);++ const urlCase = createHarness();+ urlCase.urlImageService.imageUrl = 'downloaded-url-image';+ await urlCase.service.renderImages(imageParam({+ source: 'https://example.test/image.png',+ imageSourceType: ImageSourceType.URL,+ }), urlCase.scene as unknown as Scene);+ const urlImage = urlCase.scene.objects.get(drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' })) as Image;+ expect(urlImage.getProps().url).toBe('downloaded-url-image');+ expect(urlCase.urlImageService.requests).toEqual(['https://example.test/image.png']);+ expect(urlCase.imageIoService.cacheWrites).toEqual([{ source: 'https://example.test/image.png', imageSourceType: ImageSourceType.URL, image: urlImage.getNative() }]);+ });++ it('keeps URL drawings visible with their original source when downloading fails', async () => {+ const { service, scene, urlImageService } = createHarness();+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ urlImageService.imageError = new Error('network unavailable');++ await service.renderImages(imageParam({+ source: 'https://example.test/offline.png',+ imageSourceType: ImageSourceType.URL,+ }), scene as unknown as Scene);++ const image = scene.objects.get(drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' })) as Image;+ expect(image.getProps().url).toBe('https://example.test/offline.png');+ expect(errorSpy).toHaveBeenCalledWith(urlImageService.imageError);+ errorSpy.mockRestore();+ });++ it('does not duplicate an image that appears while its source is loading', async () => {+ const { service, scene, imageIoService } = createHarness();+ const key = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' });+ const existingObject = createTransformRecorder(key);+ imageIoService.beforeResolveImage = () => scene.objects.set(key, existingObject);++ const result = await service.renderImages(imageParam({+ source: 'stored-image-id',+ imageSourceType: ImageSourceType.UUID,+ }), scene as unknown as Scene);+expect(result).toEqual([]);+ expect(scene.addedObjects).toEqual([]);+ expect(scene.objects.get(key)).toBe(existingObject);+ });++ it('updates existing image objects for each transform instead of recreating them', async () => {+ const { service, scene } = createHarness();+ const firstKey = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' }, 0);+ const secondKey = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' }, 1);+ const firstObject = createTransformRecorder(firstKey);+ const secondObject = createTransformRecorder(secondKey);+ scene.objects.set(firstKey, firstObject);+ scene.objects.set(secondKey, secondObject);++ const result = await service.renderImages(imageParam({+ isMultiTransform: 1,+ transforms: [BASE_TRANSFORM, SECOND_TRANSFORM],+ }), scene as unknown as Scene);++ expect(result).toEqual([]);+ expect(firstObject.transformCalls).toEqual([BASE_TRANSFORM]);+ expect(secondObject.transformCalls).toEqual([SECOND_TRANSFORM]);+ expect(scene.addedObjects).toEqual([]);+ });++ it('skips float DOM rendering when the drawing cannot produce a scene object', () => {+ const hiddenCase = createHarness();+ hiddenCase.drawingManagerService.visible = false;+ expect(hiddenCase.service.renderFloatDom(floatDomParam(), hiddenCase.scene as unknown as Scene)).toBeUndefined();+ expect(hiddenCase.scene.getObjectKeys).toEqual([]);++ const nonDomCase = createHarness();+ expect(nonDomCase.service.renderFloatDom(floatDomParam({ drawingType: DrawingTypeEnum.DRAWING_IMAGE }), nonDomCase.scene as unknown as Scene)).toBeUndefined();+ expect(nonDomCase.scene.getObjectKeys).toEqual([]);++ const noTransformCase = createHarness();+ expect(noTransformCase.service.renderFloatDom(floatDomParam({ transform: null }), noTransformCase.scene as unknown as Scene)).toBeUndefined();+ expect(noTransformCase.scene.getObjectKeys).toEqual([]);+ });++ it('adds float DOM placeholders for every transform and respects transform permissions', () => {+ const { service, scene, drawingManagerService } = createHarness();+ drawingManagerService.orders = ['float-1', 'later'];++ const result = service.renderFloatDom(floatDomParam({+ isMultiTransform: 1,+ transforms: [BASE_TRANSFORM, SECOND_TRANSFORM],+ allowTransform: false,+ }), scene as unknown as Scene);++ const firstKey = drawingKey({ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'float-1' }, 0);+ const secondKey = drawingKey({ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'float-1' }, 1);+ const firstRect = scene.objects.get(firstKey) as Rect;+ const secondRect = scene.objects.get(secondKey) as Rect;++ expect(result).toEqual([firstRect, secondRect]);+ expect(firstRect).toBeInstanceOf(Rect);+ expect(firstRect.left).toBe(10);+ expect(firstRect.top).toBe(20);+ expect(firstRect.zIndex).toBe(0);+ expect(firstRect.printable).toBe(false);+ expect(secondRect.left).toBe(50);+ expect(secondRect.top).toBe(60);+ expect(scene.addedObjects.map(({ object, layerIndex }) => [object.oKey, layerIndex])).toEqual([+ [firstKey, DRAWING_OBJECT_LAYER_INDEX],+ [secondKey, DRAWING_OBJECT_LAYER_INDEX],+ ]);+ expect(scene.transformerObjects).toEqual([]);+ });++ it('updates existing float DOM placeholders and does not add stale placeholders after visibility changes', () => {+ const updateCase = createHarness();+ const key = drawingKey({ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'float-1' });+ const existingObject = createTransformRecorder(key);+ updateCase.scene.objects.set(key, existingObject);++ const updateResult = updateCase.service.renderFloatDom(floatDomParam(), updateCase.scene as unknown as Scene);++ expect(updateResult).toEqual([]);+ expect(existingObject.transformCalls).toEqual([BASE_TRANSFORM]);+ expect(updateCase.scene.addedObjects).toEqual([]);++ const staleCase = createHarness();+ staleCase.drawingManagerService.visibleReads = [true, false];+ expect(staleCase.service.renderFloatDom(floatDomParam(), staleCase.scene as unknown as Scene)).toEqual([]);+ expect(staleCase.scene.addedObjects).toEqual([]);+ });++ it('renders drawings fetched from the drawing manager and ignores unsupported records', async () => {+ const imageCase = createHarness();+ const search = { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' };+ imageCase.drawingManagerService.drawings.set(drawingKey(search), imageParam());++ const imageResult = await imageCase.service.renderDrawing(search, imageCase.scene as unknown as Scene);++ expect(imageResult).toEqual([imageCase.scene.objects.get(drawingKey(search))]);++ const missingCase = createHarness();+ expect(missingCase.service.renderDrawing(search, missingCase.scene as unknown as Scene)).toBeUndefined();++ const unsupportedCase = createHarness();+ unsupportedCase.drawingManagerService.drawings.set(drawingKey(search), { ...imageParam(), drawingType: DrawingTypeEnum.DRAWING_SHAPE });+ expect(unsupportedCase.service.renderDrawing(search, unsupportedCase.scene as unknown as Scene)).toBeUndefined();+ });++ it('opens preview images in the gallery and closes the gallery when the preview is dismissed', () => {+ const { service, galleryService } = createHarness();++ service.previewImage('drawing-1', 'preview-src', 640, 480);+ galleryService.lastOpen?.onOpenChange?.(true);+ galleryService.lastOpen?.onOpenChange?.(false);++ expect(galleryService.lastOpen?.images).toEqual(['preview-src']);+ expect(galleryService.closeCount).toBe(1);});});diff --git a/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsxnew file mode 100644index 0000000000..2537580110--- /dev/null+++ b/packages/drawing-ui/src/views/__tests__/DrawingPanelActions.spec.tsx@@ -0,0 +1,168 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDrawingParam } from '@univerjs/core';+import type { IDrawingOrderUpdateParam } from '@univerjs/drawing';+import type { ReactElement } from 'react';+import type { Root } from 'react-dom/client';+import { ArrangeTypeEnum, DrawingTypeEnum, ICommandService, LocaleType, Univer } from '@univerjs/core';+import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';+import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SetDrawingArrangeOperation } from '../../commands/operations/drawing-arrange.operation';+import { AutoImageCropOperation, CropType } from '../../commands/operations/image-crop.operation';+import { DrawingImageClipService } from '../../services/drawing-image-clip.service';+import { DrawingArrange } from '../panel/DrawingArrange';+import { ImageCropper } from '../panel/ImageCropper';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const unitId = 'drawing-panel-unit';+const subUnitId = 'drawing-panel-subunit';++function createDrawing(drawingId: string, left: number): IDrawingParam {+ return {+ unitId,+ subUnitId,+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ transform: {+ left,+ top: 10,+ width: 20,+ height: 30,+ },+ };+}++function clickElement(element: Element): void {+ act(() => {+ element.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ element.dispatchEvent(new MouseEvent('pointerup', { bubbles: true }));+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+}++async function flushPendingCommands(): Promise<void> {+ await act(async () => {+ await Promise.resolve();+ });+}++function findActionByText(text: string): HTMLElement {+ const action = Array.from(document.querySelectorAll<HTMLElement>('button,[role="menuitemradio"]'))+ .find((item) => item.textContent?.includes(text));+ if (!action) {+ throw new Error(`Action with text "${text}" was not found.`);+ }++ return action;+}++function renderWithRediContext(injector: ReturnType<Univer['__getInjector']>, element: ReactElement) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return { container, root };+}++describe('drawing panel actions', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let drawingManagerService: IDrawingManagerService;+ let root: Root | undefined;+ let container: HTMLElement | undefined;++ beforeEach(() => {+ univer = new Univer({ locales: { [LocaleType.ZH_CN]: {} } });+ const injector = univer.__getInjector();+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);+ injector.add([IconManager]);+ injector.add([ComponentManager]);+ injector.add([DrawingImageClipService]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(SetDrawingArrangeOperation);+ commandService.registerCommand(AutoImageCropOperation);+ drawingManagerService = injector.get(IDrawingManagerService);+ });++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ root = undefined;+ container = undefined;+ univer.dispose();+ });++ it('sends the selected drawings to the requested layer-order operation', () => {+ const drawings = [createDrawing('image-1', 0), createDrawing('image-2', 30)];+ const orderUpdates: IDrawingOrderUpdateParam[] = [];+ drawingManagerService.featurePluginOrderUpdate$.subscribe((update) => orderUpdates.push(update));++ const rendered = renderWithRediContext(+ univer.__getInjector(),+ <DrawingArrange arrangeShow drawings={drawings} />+ );+ root = rendered.root;+ container = rendered.container;++ clickElement(findActionByText('drawing-ui.image-panel.arrange.front'));++ expect(orderUpdates).toEqual([{+ unitId,+ subUnitId,+ drawingIds: ['image-1', 'image-2'],+ arrangeType: ArrangeTypeEnum.front,+ }]);+ });++ it('starts image cropping with the current crop mode', async () => {+ const executedCommands: ICommandInfo[] = [];+ commandService.onCommandExecuted((command) => executedCommands.push(command));++ const rendered = renderWithRediContext(+ univer.__getInjector(),+ <ImageCropper cropperShow drawings={[createDrawing('image-1', 0)]} />+ );+ root = rendered.root;+ container = rendered.container;++ clickElement(findActionByText('drawing-ui.image-panel.crop.start'));+ await flushPendingCommands();++ expect(executedCommands).toEqual([{+ id: AutoImageCropOperation.id,+ type: AutoImageCropOperation.type,+ params: {+ cropType: CropType.FREE,+ },+ }]);+ });+});diff --git a/packages/drawing/src/commands/operations/__tests__/set-drawing-selected.operation.spec.ts b/packages/drawing/src/commands/operations/__tests__/set-drawing-selected.operation.spec.tsnew file mode 100644index 0000000000..adbfc36d79--- /dev/null+++ b/packages/drawing/src/commands/operations/__tests__/set-drawing-selected.operation.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 type { IDrawingParam, IDrawingSearch } from '@univerjs/core';+import { DrawingTypeEnum, ICommandService, Univer } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { DrawingManagerService } from '../../../services/drawing-manager-impl.service';+import { IDrawingManagerService } from '../../../services/drawing-manager.service';+import { SetDrawingSelectedOperation } from '../set-drawing-selected.operation';++const unitId = 'drawing-unit';+const subUnitId = 'drawing-subunit';++function createDrawing(drawingId: string): IDrawingParam {+ return {+ unitId,+ subUnitId,+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ };+}++function createSearch(drawingId: string): IDrawingSearch {+ return {+ unitId,+ subUnitId,+ drawingId,+ };+}++describe('SetDrawingSelectedOperation', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let drawingManagerService: IDrawingManagerService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(SetDrawingSelectedOperation);+ drawingManagerService = injector.get(IDrawingManagerService);+ drawingManagerService.registerDrawingData(unitId, {+ [subUnitId]: {+ data: {+ image1: createDrawing('image1'),+ image2: createDrawing('image2'),+ },+ order: ['image1', 'image2'],+ },+ });+ });++ afterEach(() => {+ univer.dispose();+ });++ it('selects only drawings that exist in the drawing manager', async () => {+ const result = await commandService.executeCommand(SetDrawingSelectedOperation.id, [+ createSearch('image2'),+ createSearch('missing'),+ ]);++ expect(result).toBe(true);+ expect(drawingManagerService.getFocusDrawings()).toEqual([createDrawing('image2')]);+ });++ it('keeps the current drawing focus when selection params are missing', async () => {+ await commandService.executeCommand(SetDrawingSelectedOperation.id, [createSearch('image1')]);+ const result = await commandService.executeCommand(SetDrawingSelectedOperation.id);++ expect(result).toBe(false);+ expect(drawingManagerService.getFocusDrawings()).toEqual([createDrawing('image1')]);+ });+});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.tsindex 803a03d461..e93cad7332 100644--- a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts+++ b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts@@ -15,7 +15,7 @@*/import type { IDrawingParam, IDrawingSearch } from '@univerjs/core';-import { BooleanNumber, DrawingTypeEnum } from '@univerjs/core';+import { BooleanNumber, DrawingTypeEnum, Injector } from '@univerjs/core';import { beforeEach, describe, expect, it } from 'vitest';import { UnitDrawingService } from '../drawing-manager-impl.service';@@ -44,7 +44,9 @@ describe('UnitDrawingService', () => {let service: UnitDrawingService<IDrawingParam>;beforeEach(() => {- service = new UnitDrawingService<IDrawingParam>();+ const injector = new Injector();+ injector.add([UnitDrawingService]);+ service = injector.get(UnitDrawingService);});it('should register, initialize and remove drawing data for a unit', () => {diff --git a/packages/drawing/src/services/__tests__/drawing-manager.service.spec.ts b/packages/drawing/src/services/__tests__/drawing-manager.service.spec.tsnew file mode 100644index 0000000000..af73197e30--- /dev/null+++ b/packages/drawing/src/services/__tests__/drawing-manager.service.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 { DrawingTypeEnum, Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { DrawingManagerService } from '../drawing-manager-impl.service';++function createService(): DrawingManagerService {+ const injector = new Injector();+ injector.add([DrawingManagerService]);+ return injector.get(DrawingManagerService);+}++describe('DrawingManagerService', () => {+ it('uses the shared drawing manager behavior to register and remove drawings by unit', () => {+ const service = createService();+ const removed: unknown[] = [];+ service.remove$.subscribe((value) => removed.push(value));++ service.registerDrawingData('unit-1', {+ 'sheet-1': {+ data: {+ image1: { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'image1', drawingType: DrawingTypeEnum.DRAWING_IMAGE },+ },+ order: ['image1'],+ },+ });+ expect(service.getDrawingData('unit-1', 'sheet-1')).toHaveProperty('image1');++ service.removeDrawingDataForUnit('unit-1');+ expect(service.getDrawingDataForUnit('unit-1')).toEqual({});+ expect(removed).toEqual([[{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'image1' }]]);+ });+});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.tsindex 736fb241c3..c88bdbc728 100644--- a/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts+++ b/packages/drawing/src/services/__tests__/image-io-impl.service.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { ImageSourceType, ImageUploadStatusType } from '@univerjs/core';+import { ImageSourceType, ImageUploadStatusType, Injector } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getDrawingImageAllowSize } from '../../basics/config';import { ImageIoService } from '../image-io-impl.service';@@ -61,7 +61,9 @@ describe('ImageIoService', () => {let service: ImageIoService;beforeEach(() => {- service = new ImageIoService();+ const injector = new Injector();+ injector.add([ImageIoService]);+ service = injector.get(ImageIoService);vi.stubGlobal('Image', MockImage);});@@ -100,6 +102,7 @@ describe('ImageIoService', () => {service.setWaitCount(1);await expect(service.saveImage(new File(['abc'], 'a.txt', { type: 'text/plain' }))).rejects.toThrow(ImageUploadStatusType.ERROR_IMAGE_TYPE);+ vi.stubGlobal('FileReader', SuccessFileReader);service.setWaitCount(1);await expect(service.saveImage(new File(['abc'], 'a.png', { type: 'image/png' }))).resolves.toMatchObject({source: expect.any(String),diff --git a/packages/drawing/src/services/__tests__/url-image.service.spec.ts b/packages/drawing/src/services/__tests__/url-image.service.spec.tsindex ad8dd88e13..ad11c52eb6 100644--- a/packages/drawing/src/services/__tests__/url-image.service.spec.ts+++ b/packages/drawing/src/services/__tests__/url-image.service.spec.ts@@ -14,14 +14,17 @@* limitations under the License.*/+import { Injector, IURLImageService } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { URLImageService } from '../url-image.service';describe('URLImageService', () => {- let service: URLImageService;+ let service: IURLImageService;beforeEach(() => {- service = new URLImageService();+ const injector = new Injector();+ injector.add([IURLImageService, { useClass: URLImageService }]);+ service = injector.get(IURLImageService);});afterEach(() => {@@ -52,23 +55,31 @@ describe('URLImageService', () => {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,- }));+ const requestedUrls: string[] = [];+ const fetchMock = async (url: string) => {+ requestedUrls.push(url);+ return {+ 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');+ expect(requestedUrls).toEqual(['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,- }));+ const requestedUrls: string[] = [];+ const fetchMock = async (url: string) => {+ requestedUrls.push(url);+ return {+ blob: async () => blob,+ };+ };vi.stubGlobal('fetch', fetchMock);service.registerURLImageDownloader(async () => {@@ -76,7 +87,7 @@ describe('URLImageService', () => {});await expect(service.downloadImage('https://example.com/image.png')).resolves.toBe(blob);- expect(fetchMock).toHaveBeenCalledWith('https://example.com/image.png');+ expect(requestedUrls).toEqual(['https://example.com/image.png']);expect(errorSpy).toHaveBeenCalledTimes(1);});});diff --git a/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.ts b/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.tsnew file mode 100644index 0000000000..f21fa1c871--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/__tests__/formula-reference.mutation.spec.ts@@ -0,0 +1,118 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, Univer } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { TableOptionType } from '../../../basics/common';+import { DefinedNamesService, IDefinedNamesService } from '../../../services/defined-names.service';+import { ISuperTableService, SuperTableService } from '../../../services/super-table.service';+import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../set-defined-name.mutation';+import { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from '../set-super-table.mutation';++describe('formula reference mutations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let definedNamesService: IDefinedNamesService;+ let superTableService: ISuperTableService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(SetDefinedNameMutation);+ commandService.registerCommand(RemoveDefinedNameMutation);+ commandService.registerCommand(SetSuperTableMutation);+ commandService.registerCommand(RemoveSuperTableMutation);+ commandService.registerCommand(SetSuperTableOptionMutation);+ definedNamesService = injector.get(IDefinedNamesService);+ superTableService = injector.get(ISuperTableService);+ injector.get(IUniverInstanceService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('sets and removes defined names used by formulas', async () => {+ const setResult = await commandService.executeCommand(SetDefinedNameMutation.id, {+ unitId: 'book-1',+ id: 'name-1',+ name: ' SalesTotal ',+ formulaOrRefString: ' Sheet1!A1:A10 ',+ comment: ' Used by dashboard ',+ });++ expect(setResult).toBe(true);+ expect(definedNamesService.getValueById('book-1', 'name-1')).toEqual({+ id: 'name-1',+ name: 'SalesTotal',+ formulaOrRefString: 'Sheet1!A1:A10',+ comment: 'Used by dashboard',+ hidden: undefined,+ localSheetId: undefined,+ formulaOrRefStringWithPrefix: undefined,+ });++ const removeResult = await commandService.executeCommand(RemoveDefinedNameMutation.id, {+ unitId: 'book-1',+ id: 'name-1',+ });++ expect(removeResult).toBe(true);+ expect(definedNamesService.getValueById('book-1', 'name-1')).toBeUndefined();+ });++ it('sets and removes structured-reference tables used by formulas', async () => {+ const tableReference = {+ range: {+ startRow: 0,+ endRow: 10,+ startColumn: 0,+ endColumn: 3,+ },+ };++ const setResult = await commandService.executeCommand(SetSuperTableMutation.id, {+ unitId: 'book-1',+ tableName: 'SalesTable',+ reference: tableReference,+ });++ expect(setResult).toBe(true);+ expect(superTableService.getTable('book-1', 'SalesTable')).toEqual(tableReference);++ const removeResult = await commandService.executeCommand(RemoveSuperTableMutation.id, {+ unitId: 'book-1',+ tableName: 'SalesTable',+ });++ expect(removeResult).toBe(true);+ expect(superTableService.hasTable('book-1', 'SalesTable')).toBe(false);+ });++ it('registers localized structured-reference table options', async () => {+ const result = await commandService.executeCommand(SetSuperTableOptionMutation.id, {+ tableOption: '数据',+ tableOptionType: TableOptionType.DATA,+ });++ expect(result).toBe(true);+ expect(superTableService.getTableOptionMap().get('数据')).toBe(TableOptionType.DATA);+ });+});diff --git a/packages/engine-formula/src/facade/__tests__/f-univer.spec.ts b/packages/engine-formula/src/facade/__tests__/f-univer.spec.tsnew file mode 100644index 0000000000..1897c64761--- /dev/null+++ b/packages/engine-formula/src/facade/__tests__/f-univer.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 { FUniver } from '@univerjs/core/facade';+import { describe, expect, it } from 'vitest';+import { createFunctionTestBed } from '../../functions/__tests__/create-function-test-bed';+import '../f-univer';++describe('FUniverEngineFormulaMixin', () => {+ it('creates a formula facade that can resolve spreadsheet references', () => {+ const testBed = createFunctionTestBed();+ const univerAPI = FUniver.newAPI(testBed.univer);++ const formula = univerAPI.getFormula();++ expect(formula.moveFormulaRefOffset('=SUM(A1,B2)', 1, 1)).toBe('=SUM(B2,C3)');+ });+});diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex c98d2b5dac..0f24844cdd 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -52,11 +52,25 @@ export { matchRefDrawToken } from './basics/match-token';export { isReferenceString } from './basics/regex';export { convertUnitDataToRuntime } from './basics/runtime';export { compareToken, matchToken, OPERATOR_TOKEN_SET, operatorToken, prefixToken, SUFFIX_TOKEN_SET } from './basics/token';-export { DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME, DEFAULT_TOKEN_LET_FUNCTION_NAME, DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER, DEFAULT_TOKEN_TYPE_PARAMETER, DEFAULT_TOKEN_TYPE_ROOT } from './basics/token-type';+export {+ DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME,+ DEFAULT_TOKEN_LET_FUNCTION_NAME,+ DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,+ DEFAULT_TOKEN_TYPE_PARAMETER,+ DEFAULT_TOKEN_TYPE_ROOT,+} from './basics/token-type';export { OtherFormulaMarkDirty } from './commands/mutations/formula.mutation';export { RegisterFunctionMutation } from './commands/mutations/register-function.mutation';-export { type ISetArrayFormulaDataMutationParams, SetArrayFormulaDataMutation } from './commands/mutations/set-array-formula-data.mutation';-export { type ISetDefinedNameMutationParam, type ISetDefinedNameMutationSearchParam, RemoveDefinedNameMutation, SetDefinedNameMutation } from './commands/mutations/set-defined-name.mutation';+export {+ type ISetArrayFormulaDataMutationParams,+ SetArrayFormulaDataMutation,+} from './commands/mutations/set-array-formula-data.mutation';+export {+ type ISetDefinedNameMutationParam,+ type ISetDefinedNameMutationSearchParam,+ RemoveDefinedNameMutation,+ SetDefinedNameMutation,+} from './commands/mutations/set-defined-name.mutation';export { SetDefinedNameMutationFactory } from './commands/mutations/set-defined-name.mutation';export { RemoveFeatureCalculationMutation, SetFeatureCalculationMutation } from './commands/mutations/set-feature-calculation.mutation';export {@@ -87,10 +101,21 @@ export {} from './commands/mutations/set-formula-calculation.mutation';export { type ISetFormulaDataMutationParams, SetFormulaDataMutation } from './commands/mutations/set-formula-data.mutation';export { type ISetImageFormulaDataMutationParams, SetImageFormulaDataMutation } from './commands/mutations/set-image-formula-data.mutation';-export { type IRemoveOtherFormulaMutationParams, type ISetOtherFormulaMutationParams, RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';+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 { DEFAULT_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_CYCLE_REFERENCE_COUNT, ENGINE_FORMULA_PLUGIN_CONFIG_KEY, ENGINE_FORMULA_RETURN_DEPENDENCY_TREE, type IUniverEngineFormulaConfig } from './config/config';+export {+ DEFAULT_CYCLE_REFERENCE_COUNT,+ ENGINE_FORMULA_CYCLE_REFERENCE_COUNT,+ ENGINE_FORMULA_PLUGIN_CONFIG_KEY,+ ENGINE_FORMULA_RETURN_DEPENDENCY_TREE,+ type IUniverEngineFormulaConfig,+} from './config/config';export { CalculateController } from './controllers/calculate.controller';export { Lexer } from './engine/analysis/lexer';export { LexerNode } from './engine/analysis/lexer-node';@@ -107,7 +132,14 @@ export { ReferenceNodeFactory } from './engine/ast-node/reference-node';export { SuffixNodeFactory } from './engine/ast-node/suffix-node';export { UnionNodeFactory } from './engine/ast-node/union-node';export { ValueNodeFactory } from './engine/ast-node/value-node';-export { FormulaDependencyTree, FormulaDependencyTreeModel, type IFormulaDependencyTree, type IFormulaDependencyTreeFullJson, type IFormulaDependencyTreeJson, type IFormulaDependentsAndInRangeResults } from './engine/dependency/dependency-tree';+export {+ FormulaDependencyTree,+ FormulaDependencyTreeModel,+ type IFormulaDependencyTree,+ type IFormulaDependencyTreeFullJson,+ type IFormulaDependencyTreeJson,+ type IFormulaDependentsAndInRangeResults,+} from './engine/dependency/dependency-tree';export { FormulaDependencyTreeType } from './engine/dependency/dependency-tree';export { FormulaDependencyTreeVirtual } from './engine/dependency/dependency-tree';export { FormulaDependencyGenerator, IFormulaDependencyGenerator } from './engine/dependency/formula-dependency';@@ -146,7 +178,12 @@ export { generateStringWithSequence, type ISequenceNode, sequenceNodeType } fromexport { ArrayValueObject, ValueObjectFactory } from './engine/value-object/array-value-object';export { BaseValueObject, ErrorValueObject } from './engine/value-object/base-value-object';export { LambdaValueObjectObject } from './engine/value-object/lambda-value-object';-export type { FormulaFunctionResultValueType, FormulaFunctionValueType, IImageFormulaInfo, PrimitiveValueType } from './engine/value-object/primitive-object';+export type {+ FormulaFunctionResultValueType,+ FormulaFunctionValueType,+ IImageFormulaInfo,+ PrimitiveValueType,+} from './engine/value-object/primitive-object';export { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from './engine/value-object/primitive-object';export { functionArray } from './functions/array/function-map';export { FUNCTION_NAMES_ARRAY } from './functions/array/function-names';@@ -192,7 +229,13 @@ export { ActiveDirtyManagerService, IActiveDirtyManagerService } from './serviceexport { CalculateFormulaService, ICalculateFormulaService } from './services/calculate-formula.service';export { DEFAULT_INTERVAL_COUNT } from './services/calculate-formula.service';export { FormulaCurrentConfigService, IFormulaCurrentConfigService, type IFormulaDirtyData } from './services/current-data.service';-export { DefinedNamesService, type IDefinedNameMapItem, IDefinedNamesService, type IDefinedNamesServiceParam, type IDefinedNamesUpdateEvent } from './services/defined-names.service';+export {+ DefinedNamesService,+ type IDefinedNameMapItem,+ IDefinedNamesService,+ type IDefinedNamesServiceParam,+ type IDefinedNamesUpdateEvent,+} from './services/defined-names.service';export { IDependencyManagerService } from './services/dependency-manager.service';export { DependencyManagerService } from './services/dependency-manager.service';export { DependencyManagerBaseService } from './services/dependency-manager.service';@@ -206,7 +249,14 @@ export { GlobalComputingStatusService } from './services/global-computing-statusexport { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from './services/hyperlink-engine-formula.service';export { IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';export { OtherFormulaBizType, RegisterOtherFormulaService } from './services/register-other-formula.service';-export { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService, type IAllRuntimeData, type IExecutionInProgressParams, IFormulaRuntimeService } from './services/runtime.service';+export {+ FormulaExecutedStateType,+ FormulaExecuteStageType,+ FormulaRuntimeService,+ type IAllRuntimeData,+ type IExecutionInProgressParams,+ IFormulaRuntimeService,+} from './services/runtime.service';export { ISheetRowFilteredService, SheetRowFilteredService } from './services/sheet-row-filtered.service';export { ISuperTableService } from './services/super-table.service';export { SuperTableService } from './services/super-table.service';diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex c81a83e267..279859a3b5 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -164,51 +164,66 @@ export class FormulaDataModel extends Disposable {getFormulaData(): IFormulaData {const formulaData: IFormulaData = {};const allSheets = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);- allSheets.forEach((workbook) => {+ for (let i = 0; i < allSheets.length; i++) {+ const workbook = allSheets[i];const unitId = workbook.getUnitId();formulaData[unitId] = {};const worksheets = workbook.getSheets();- worksheets.forEach((worksheet) => {+ for (let j = 0; j < worksheets.length; j++) {+ const worksheet = worksheets[j];const cellMatrix = worksheet.getCellMatrix();const sheetId = worksheet.getSheetId();initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);- });- });+ }+ }const allBases = this._univerInstanceService.getAllUnitsForType<BaseDataModel>(UniverInstanceType.UNIVER_BASE);- allBases.forEach((base) => {+ for (let i = 0; i < allBases.length; i++) {+ const base = allBases[i];const snapshot = base.getSnapshot();const unitId = base.getUnitId();formulaData[unitId] = {};- Object.values(snapshot.tables).filter((table) => !table.deleted).forEach((table) => {+ const tables = Object.values(snapshot.tables);+ for (let j = 0; j < tables.length; j++) {+ const table = tables[j];+ if (table.deleted) {+ continue;+ }const tableFormulaData: Record<number, Record<number, IFormulaDataItem>> = {};- table.recordOrder?.forEach((recordId, row) => {+ const recordOrder = table.recordOrder;+ if (!recordOrder) {+ formulaData[unitId]![table.id] = tableFormulaData;+ continue;+ }+ for (let row = 0; row < recordOrder.length; row++) {+ const recordId = recordOrder[row];const record = table.records[recordId];if (!record || record.deleted) {- return;+ continue;}- table.fieldOrder.forEach((fieldId, col) => {+ for (let col = 0; col < table.fieldOrder.length; col++) {+ const fieldId = table.fieldOrder[col];const field = table.fields[fieldId];if (!field || field.deleted || field.type !== 'formula') {- return;+ continue;}const formula = String(field.config?.formula ?? '').trim();if (!formula) {- return;+ continue;}tableFormulaData[row] ??= {};tableFormulaData[row][col] = {f: normalizeBaseFormulaForEngine(formula, table, snapshot),si: field.id,};- });- });+ }+ }formulaData[unitId]![table.id] = tableFormulaData;- });- });+ }+ }return formulaData;}@@ -840,29 +855,70 @@ function createEngineThisRowRef(table: ITableSnapshot, fieldName: string, snapsh}function getEngineBaseTableName(table: ITableSnapshot, snapshot: IBaseSnapshot): string {- const sameNameCount = Object.values(snapshot.tables).filter((item) => !item.deleted && item.name === table.name).length;+ const tables = Object.values(snapshot.tables);+ let sameNameCount = 0;+ for (let i = 0; i < tables.length; i++) {+ const item = tables[i];+ if (!item.deleted && item.name === table.name) {+ sameNameCount++;+ if (sameNameCount > 1) {+ break;+ }+ }+ }return sameNameCount === 1 ? table.name : table.id;}function buildBaseRuntimeCellData(table: ITableSnapshot): Record<number, Record<number, IBaseCellData>> {const cellData: Record<number, Record<number, IBaseCellData>> = { ...table.cellData };- const fieldOrder = table.fieldOrder.filter((fieldId) => table.fields[fieldId] && !table.fields[fieldId].deleted);- const recordOrder = table.recordOrder?.filter((recordId) => table.records[recordId] && !table.records[recordId].deleted)- ?? Object.values(table.records ?? {}).filter((record) => !record.deleted).sort((a, b) => a.orderKey.localeCompare(b.orderKey)).map((record) => record.id);+ const fieldOrder: string[] = [];+ for (let i = 0; i < table.fieldOrder.length; i++) {+ const fieldId = table.fieldOrder[i];+ if (table.fields[fieldId] && !table.fields[fieldId].deleted) {+ fieldOrder.push(fieldId);+ }+ }+ let recordOrder: string[];+ if (table.recordOrder) {+ recordOrder = [];+ for (let i = 0; i < table.recordOrder.length; i++) {+ const recordId = table.recordOrder[i];+ if (table.records[recordId] && !table.records[recordId].deleted) {+ recordOrder.push(recordId);+ }+ }+ } else {+ const allRecords = Object.values(table.records ?? {});+ const records: typeof allRecords = [];+ for (let i = 0; i < allRecords.length; i++) {+ const record = allRecords[i];+ if (!record.deleted) {+ records.push(record);+ }+ }+ records.sort((a, b) => a.orderKey.localeCompare(b.orderKey));+ recordOrder = [];+ for (let i = 0; i < records.length; i++) {+ const record = records[i];+ recordOrder.push(record.id);+ }+ }- recordOrder.forEach((recordId, row) => {+ for (let row = 0; row < recordOrder.length; row++) {+ const recordId = recordOrder[row];const record = table.records[recordId];if (!record || record.deleted) {- return;+ continue;}cellData[row] = { ...cellData[row] };- fieldOrder.forEach((fieldId, col) => {+ for (let col = 0; col < fieldOrder.length; col++) {+ const fieldId = fieldOrder[col];if (!Object.prototype.hasOwnProperty.call(record.values ?? {}, fieldId)) {- return;+ continue;}cellData[row][col] = toBaseRuntimeCellData(record.values[fieldId], table.fields[fieldId]);- });- });+ }+ }return cellData;}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.tsindex 30d2ea5006..4abfc3c672 100644--- a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts@@ -14,12 +14,18 @@* limitations under the License.*/+import { IConfigService, Injector } from '@univerjs/core';import { beforeEach, describe, expect, it, vi } from 'vitest';import { ErrorType } from '../../basics/error-type';import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../../config/config';+import { Lexer } from '../../engine/analysis/lexer';+import { AstTreeBuilder } from '../../engine/analysis/parser';+import { IFormulaDependencyGenerator } from '../../engine/dependency/formula-dependency';+import { Interpreter } from '../../engine/interpreter/interpreter';import { FORMULA_REF_TO_ARRAY_CACHE } from '../../engine/reference-object/base-reference-object';-import { CalculateFormulaService } from '../calculate-formula.service';-import { FormulaExecuteStageType } from '../runtime.service';+import { CalculateFormulaService, ICalculateFormulaService } from '../calculate-formula.service';+import { IFormulaCurrentConfigService } from '../current-data.service';+import { FormulaExecuteStageType, IFormulaRuntimeService } from '../runtime.service';function createService() {const configService = {@@ -95,15 +101,76 @@ function createService() {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- );+ class TestConfigService {+ getConfig = configService.getConfig;+ }++ class TestLexer {+ treeBuilder = lexer.treeBuilder;+ }++ class TestCurrentConfigService {+ load = currentConfigService.load;+ loadDataLite = currentConfigService.loadDataLite;+ loadDirtyRangesAndExcludedCell = currentConfigService.loadDirtyRangesAndExcludedCell;+ getRuntimeState = currentConfigService.getRuntimeState;+ getUnitData = currentConfigService.getUnitData;+ getDirtyData = currentConfigService.getDirtyData;+ getDirtyDefinedNameMap = currentConfigService.getDirtyDefinedNameMap;+ }++ class TestRuntimeService {+ setFormulaExecuteStage = runtimeService.setFormulaExecuteStage;+ getRuntimeState = runtimeService.getRuntimeState;+ reset = runtimeService.reset;+ setFormulaCycleIndex = runtimeService.setFormulaCycleIndex;+ isCycleDependency = runtimeService.isCycleDependency;+ setRuntimeFeatureCellData = runtimeService.setRuntimeFeatureCellData;+ setRuntimeFeatureRange = runtimeService.setRuntimeFeatureRange;+ stopExecution = runtimeService.stopExecution;+ getAllRuntimeData = runtimeService.getAllRuntimeData;+ setTotalArrayFormulasToCalculate = runtimeService.setTotalArrayFormulasToCalculate;+ setTotalFormulasToCalculate = runtimeService.setTotalFormulasToCalculate;+ setCompletedArrayFormulasCount = runtimeService.setCompletedArrayFormulasCount;+ setCompletedFormulasCount = runtimeService.setCompletedFormulasCount;+ isStopExecution = runtimeService.isStopExecution;+ setCurrent = runtimeService.setCurrent;+ setRuntimeData = runtimeService.setRuntimeData;+ setRuntimeOtherData = runtimeService.setRuntimeOtherData;+ markedAsSuccessfullyExecuted = runtimeService.markedAsSuccessfullyExecuted;+ markedAsNoFunctionsExecuted = runtimeService.markedAsNoFunctionsExecuted;+ markedAsStopFunctionsExecuted = runtimeService.markedAsStopFunctionsExecuted;+ }++ class TestFormulaDependencyGenerator {+ generate = formulaDependencyGenerator.generate;+ getAllDependencyJson = formulaDependencyGenerator.getAllDependencyJson;+ getCellDependencyJson = formulaDependencyGenerator.getCellDependencyJson;+ getRangeDependents = formulaDependencyGenerator.getRangeDependents;+ getInRangeFormulas = formulaDependencyGenerator.getInRangeFormulas;+ getRangeDependentsAndInRangeFormulas = formulaDependencyGenerator.getRangeDependentsAndInRangeFormulas;+ }++ class TestInterpreter {+ checkAsyncNode = interpreter.checkAsyncNode;+ executeAsync = interpreter.executeAsync;+ execute = interpreter.execute;+ }++ class TestAstTreeBuilder {+ parse = astTreeBuilder.parse;+ }++ const injector = new Injector();+ injector.add([IConfigService, { useClass: TestConfigService as never }]);+ injector.add([Lexer, { useClass: TestLexer as never }]);+ injector.add([IFormulaCurrentConfigService, { useClass: TestCurrentConfigService as never }]);+ injector.add([IFormulaRuntimeService, { useClass: TestRuntimeService as never }]);+ injector.add([IFormulaDependencyGenerator, { useClass: TestFormulaDependencyGenerator as never }]);+ injector.add([Interpreter, { useClass: TestInterpreter as never }]);+ injector.add([AstTreeBuilder, { useClass: TestAstTreeBuilder as never }]);+ injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);+ const service = injector.get(ICalculateFormulaService) as CalculateFormulaService;// Make execution deterministic in tests.(service as any)._executeLock = {diff --git a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts b/packages/engine-formula/src/services/__tests__/current-data.service.spec.tsindex bc335072b6..ece5d0f653 100644--- a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts@@ -14,9 +14,11 @@* limitations under the License.*/-import { ObjectMatrix } from '@univerjs/core';+import { Injector, IUniverInstanceService, LocaleService, ObjectMatrix } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';-import { FormulaCurrentConfigService } from '../current-data.service';+import { FormulaDataModel } from '../../models/formula-data.model';+import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../current-data.service';+import { ISheetRowFilteredService } from '../sheet-row-filtered.service';function createService() {const workbookForCurrentType = {@@ -52,12 +54,33 @@ function createService() {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- );+ class TestUniverInstanceService {+ getCurrentUnitOfType = univerInstanceService.getCurrentUnitOfType;+ getUnit = univerInstanceService.getUnit;+ }++ class TestLocaleService {+ getCurrentLocale = localeService.getCurrentLocale;+ }++ class TestFormulaDataModel {+ getCalculateData = formulaDataModel.getCalculateData;+ getFormulaData = formulaDataModel.getFormulaData;+ getArrayFormulaCellData = formulaDataModel.getArrayFormulaCellData;+ getArrayFormulaRange = formulaDataModel.getArrayFormulaRange;+ }++ class TestSheetRowFilteredService {+ getRowFiltered = sheetRowFilteredService.getRowFiltered;+ }++ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([FormulaDataModel, { useClass: TestFormulaDataModel as never }]);+ injector.add([ISheetRowFilteredService, { useClass: TestSheetRowFilteredService as never }]);+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ const service = injector.get(IFormulaCurrentConfigService) as FormulaCurrentConfigService;return {service,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.tsindex 93735b5e53..4dd1c44189 100644--- a/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/defined-names.service.spec.ts@@ -14,19 +14,25 @@* limitations under the License.*/+import { Injector, IUniverInstanceService } from '@univerjs/core';import { describe, expect, it } from 'vitest';-import { DefinedNamesService } from '../defined-names.service';+import { DefinedNamesService, IDefinedNamesService } 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 worksheet = { id: 'sheet-a' };- const service = new DefinedNamesService(univerInstanceService as never);+class TestUniverInstanceService {+ getUnit() {+ return {+ getSheetBySheetName: (sheetName: string) => (sheetName === 'Sheet1' ? worksheet : null),+ };+ }+}++function createDefinedNamesService() {+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ const service = injector.get(IDefinedNamesService);return {service,worksheet,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.tsindex 135f9fc4cb..d9d317824b 100644--- a/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/dependency-manager.service.spec.ts@@ -15,9 +15,16 @@*/import type { AstRootNode } from '../../engine/ast-node';+import { Injector } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { FormulaDependencyTree } from '../../engine/dependency/dependency-tree';-import { DependencyManagerService } from '../dependency-manager.service';+import { DependencyManagerBaseService, DependencyManagerService, IDependencyManagerService } from '../dependency-manager.service';++class TestDependencyManagerBaseService extends DependencyManagerBaseService {+ protected override _addAllTreeMap() {+ // The base-service test exercises state handled by the base class; tree-map indexing belongs to the concrete service.+ }+}function createTree(treeId: number, row: number, column: number) {const tree = new FormulaDependencyTree(treeId);@@ -40,9 +47,27 @@ function createTree(treeId: number, row: number, column: number) {return tree;}+function createService(): IDependencyManagerService {+ const injector = new Injector();+ injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);+ return injector.get(IDependencyManagerService);+}+describe('DependencyManagerService', () => {+ it('should keep base dependency manager state through DI-created subclass', () => {+ const injector = new Injector();+ injector.add([DependencyManagerBaseService, { useClass: TestDependencyManagerBaseService }]);+ const service = injector.get(DependencyManagerBaseService);++ service.addOtherFormulaDependencyMainData('feature-formula');++ expect(service.hasOtherFormulaDataMainData('feature-formula')).toBe(true);+ expect(service.getLastTreeId()).toBe(0);+ expect(service.getLastTreeId()).toBe(1);+ });+it('should track formula dependencies and remove their search cache by location', () => {- const service = new DependencyManagerService();+ const service = createService();const treeA = createTree(1, 0, 0);const treeB = createTree(2, 1, 1);const searchA = [@@ -91,7 +116,7 @@ describe('DependencyManagerService', () => {});it('should manage other-formula dependency matrices and main-data flag', () => {- const service = new DependencyManagerService();+ const service = createService();const tree = createTree(10, 0, 0);tree.refOffsetX = 3;tree.refOffsetY = 4;@@ -108,7 +133,7 @@ describe('DependencyManagerService', () => {});it('should manage feature formula dependencies', () => {- const service = new DependencyManagerService();+ const service = createService();const tree = createTree(20, 2, 2);service.addFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a', tree);@@ -119,7 +144,7 @@ describe('DependencyManagerService', () => {});it('should clear dependencies by defined name', () => {- const service = new DependencyManagerService();+ const service = createService();const tree = createTree(30, 3, 3);const search = [{@@ -148,7 +173,7 @@ describe('DependencyManagerService', () => {});it('should support tree id allocation and reset', () => {- const service = new DependencyManagerService();+ const service = createService();expect(service.getLastTreeId()).toBe(0);expect(service.getLastTreeId()).toBe(1);diff --git a/packages/engine-formula/src/services/__tests__/function.service.spec.ts b/packages/engine-formula/src/services/__tests__/function.service.spec.tsindex 2e139c9cb6..b5ba77c001 100644--- a/packages/engine-formula/src/services/__tests__/function.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/function.service.spec.ts@@ -14,14 +14,21 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';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';+function createService(): FunctionService {+ const injector = new Injector();+ injector.add([FunctionService]);+ return injector.get(FunctionService);+}+describe('FunctionService', () => {- it('should register/query/unregister executors', () => {- const service = new FunctionService();+ it('makes registered formula executors available until they are unregistered', () => {+ const service = createService();const sumExecutor = { name: 'SUM' };const avgExecutor = { name: 'AVERAGE' };@@ -35,8 +42,8 @@ describe('FunctionService', () => {expect(service.hasExecutor('AVERAGE')).toBe(false);});- it('should register descriptions and cleanup by disposable', () => {- const service = new FunctionService();+ it('removes formula descriptions when a feature disposes its registration', () => {+ const service = createService();const sumDescription = {functionName: 'SUM',functionType: FunctionType.Math,@@ -62,8 +69,8 @@ describe('FunctionService', () => {expect(service.hasDescription('AVERAGE')).toBe(false);});- it('should unregister descriptions and clear formula AST cache by function tokens', () => {- const service = new FunctionService();+ it('removes formula metadata and invalidates AST cache entries for unregistered function names', () => {+ const service = createService();service.registerDescriptions({functionName: 'SUM',functionType: FunctionType.Math,@@ -77,15 +84,16 @@ describe('FunctionService', () => {FORMULA_AST_CACHE.clear();FORMULA_AST_CACHE.set('unit_sheet_SUM_expr', {} as never);- FORMULA_AST_CACHE.set('unit_sheet_TEXT_expr', {} as never);+ const textAst = { token: 'TEXT' };+ FORMULA_AST_CACHE.set('unit_sheet_TEXT_expr', textAst 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();+ expect(FORMULA_AST_CACHE.get('unit_sheet_TEXT_expr')).toBe(textAst);});- it('should clear internal maps on dispose', () => {- const service = new FunctionService();+ it('drops registered formula executors and descriptions when the formula runtime is disposed', () => {+ const service = createService();service.registerExecutors({ name: 'SUM' } as never);service.registerDescriptions({functionName: 'SUM',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.tsindex d9bc50bf98..97b8a0cba9 100644--- 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.ts@@ -14,13 +14,20 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { BehaviorSubject } from 'rxjs';import { describe, expect, it } from 'vitest';import { GlobalComputingStatusService } from '../global-computing-status.service';+function createService(): GlobalComputingStatusService {+ const injector = new Injector();+ injector.add([GlobalComputingStatusService]);+ return injector.get(GlobalComputingStatusService);+}+describe('GlobalComputingStatusService', () => {it('should aggregate computing status from all registered subjects', () => {- const service = new GlobalComputingStatusService();+ const service = createService();const subjectA = new BehaviorSubject(false);const subjectB = new BehaviorSubject(true);@@ -43,7 +50,7 @@ describe('GlobalComputingStatusService', () => {});it('should expose computingStatus$ and cleanup on dispose', () => {- const service = new GlobalComputingStatusService();+ const service = createService();const subject = new BehaviorSubject(true);const observed: boolean[] = [];service.computingStatus$.subscribe((value) => observed.push(value));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.tsindex 26a232b551..d041e1bb8b 100644--- 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.ts@@ -14,195 +14,100 @@* 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 {+ CommandService,+ ConfigService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ ILogService,+ Injector,+ LifecycleService,+} from '@univerjs/core';+import { describe, expect, it } 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 { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../active-dirty-manager.service';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;- disposed: () => boolean;- dispose: () => void;-}+type FormulaResultMatrix = Record<number, Record<number, Array<{ v?: unknown }>>>;++function createService(): {+ service: RegisterOtherFormulaService;+ commandService: ICommandService;+ activeDirtyManagerService: IActiveDirtyManagerService;+} {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);+ injector.add([LifecycleService]);+ injector.add([RegisterOtherFormulaService]);+ const commandService = injector.get(ICommandService);+ commandService.registerCommand(SetOtherFormulaMutation);+ commandService.registerCommand(RemoveOtherFormulaMutation);+ commandService.registerCommand(OtherFormulaMarkDirty);+ commandService.registerCommand(SetFormulaCalculationResultMutation);-function createCommandServiceMock(): ICommandServiceMock {- const callbacks = new Set<(commandInfo: ICommandInfo) => void>();- let disposed = false;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));- },- disposed: () => disposed,- dispose: () => {- disposed = true;- callbacks.clear();- },+ service: injector.get(RegisterOtherFormulaService),+ commandService,+ activeDirtyManagerService: injector.get(IActiveDirtyManagerService),};}+async function flushCommandChain() {+ await Promise.resolve();+ await Promise.resolve();+ await Promise.resolve();+ await new Promise((resolve) => setTimeout(resolve, 0));+}+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(),- };+ const { activeDirtyManagerService } = createService();- // 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,- })- );+ expect(activeDirtyManagerService.get(OtherFormulaMarkDirty.id)?.commandId).toBe(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 { service, commandService } = createService();+ const executedIds: string[] = [];+ commandService.onCommandExecuted((command) => executedIds.push(command.id));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());+ expect(executedIds).not.toContain(SetOtherFormulaMutation.id);service.calculateStarted$.next(true);- await Promise.resolve();- await Promise.resolve();+ await flushCommandChain();- 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 }- );+ expect(executedIds).toEqual([SetOtherFormulaMutation.id, OtherFormulaMarkDirty.id]);});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- );+ const { service, commandService } = createService();+ const executedIds: string[] = [];+ commandService.onCommandExecuted((command) => executedIds.push(command.id));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();+ await flushCommandChain();- expect(commandService.executeCommand).toHaveBeenCalledWith(- SetOtherFormulaMutation.id,- expect.objectContaining({- unitId: 'unit-2',- subUnitId: 'sheet-2',- }),- { onlyLocal: true }- );- });-- it('should not mark formula dirty after disposed while formula registration is pending', async () => {- const commandService = createCommandServiceMock();- const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;- const service = new RegisterOtherFormulaService(- commandService as never,- activeDirtyManagerService,- {} as LifecycleService- );- let resolveSetOtherFormula!: () => void;-- commandService.executeCommand.mockImplementationOnce(() => new Promise<boolean>((resolve) => {- resolveSetOtherFormula = () => resolve(true);- }));-- service.calculateStarted$.next(true);- service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1');-- expect(commandService.executeCommand).toHaveBeenCalledTimes(1);- service.dispose();- commandService.dispose();-- resolveSetOtherFormula();- await Promise.resolve();- await Promise.resolve();-- expect(commandService.executeCommand).toHaveBeenCalledTimes(1);- });-- it('should not recursively reopen buffer when calculation starts', () => {- const commandService = createCommandServiceMock();- const activeDirtyManagerService = { register: vi.fn() } as unknown as IActiveDirtyManagerService;- const service = new RegisterOtherFormulaService(- commandService as never,- activeDirtyManagerService,- {} as LifecycleService- );- let subscribeCount = 0;- const calculateStarted$ = service.calculateStarted$ as any;- const originalSubscribe = calculateStarted$._subscribe.bind(calculateStarted$);- calculateStarted$._subscribe = (...args: unknown[]) => {- subscribeCount++;- return originalSubscribe(...args);- };-- service.calculateStarted$.next(true);-- expect(subscribeCount).toBe(1);+ expect(executedIds).toContain(SetOtherFormulaMutation.id);});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 { service, commandService } = createService();const formulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1+1');const pending = service.getFormulaValue('unit-1', 'sheet-1', formulaId);- commandService.emit(SetFormulaCalculationResultMutation.id, {+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {unitOtherData: {'unit-1': {'sheet-1': {@@ -218,20 +123,16 @@ describe('RegisterOtherFormulaService', () => {const value = await pending;expect(value?.status).toBe(FormulaResultStatus.SUCCESS);- expect((value?.result as any)?.[0]?.[0]?.[0]?.v).toBe(2);+ expect((value?.result as FormulaResultMatrix | undefined)?.[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 { service, commandService } = createService();+ const executedIds: string[] = [];+ commandService.onCommandExecuted((command) => executedIds.push(command.id));const formulaId = service.registerFormulaWithRange('unit-1', 'sheet-1', '=A1');- commandService.emit(SetFormulaCalculationResultMutation.id, {+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {unitOtherData: {'unit-1': {'sheet-1': {@@ -242,37 +143,21 @@ describe('RegisterOtherFormulaService', () => {});service.markFormulaDirty('unit-1', 'sheet-1', formulaId);- expect(commandService.executeCommand).toHaveBeenCalledWith(- OtherFormulaMarkDirty.id,- { 'unit-1': { 'sheet-1': { [formulaId]: true } } },- { onlyLocal: true }- );+ await flushCommandChain();+ expect(executedIds.at(-1)).toBe(OtherFormulaMarkDirty.id);service.deleteFormula('unit-1', 'sheet-1', [formulaId]);- expect(commandService.executeCommand).toHaveBeenCalledWith(- RemoveOtherFormulaMutation.id,- {- unitId: 'unit-1',- subUnitId: 'sheet-1',- formulaIdList: [formulaId],- },- { onlyLocal: true }- );+ await flushCommandChain();+ expect(executedIds.at(-1)).toBe(RemoveOtherFormulaMutation.id);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 { service, commandService } = createService();const formulaId = service.registerFormulaWithRange('unit-3', 'sheet-3', '=1+1');- commandService.emit(SetFormulaCalculationResultMutation.id, {+ await commandService.executeCommand(SetFormulaCalculationResultMutation.id, {unitOtherData: {'unit-3': {'sheet-3': {diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.tsindex 55330992f0..faf2f8ee98 100644--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts@@ -14,55 +14,80 @@* limitations under the License.*/-import { ObjectMatrix } from '@univerjs/core';+import type { ICellData, Nullable } from '@univerjs/core';+import type { BaseAstNode } from '../../engine/ast-node/base-ast-node';+import {+ ContextService,+ DesktopLogService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ ObjectMatrix,+ UniverInstanceService,+} from '@univerjs/core';import { describe, expect, it } from 'vitest';import { ErrorType } from '../../basics/error-type';+import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { createNewArray } from '../../engine/utils/array-object';import { NumberValueObject, StringValueObject } from '../../engine/value-object/primitive-object';-import { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService } from '../runtime.service';+import { FormulaDataModel } from '../../models/formula-data.model';+import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../current-data.service';+import { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from '../hyperlink-engine-formula.service';+import { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService, IFormulaRuntimeService } from '../runtime.service';+import { ISheetRowFilteredService, SheetRowFilteredService } from '../sheet-row-filtered.service';function createRuntimeService() {- const unitDataMatrix = new ObjectMatrix<any>();- const arrayFormulaCellData = new ObjectMatrix<any>();+ const unitDataMatrix = new ObjectMatrix<ICellData>();const arrayFormulaRange = {unit: {sheet: {},},};- const currentConfigService = {- getUnitData: () => ({+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([LocaleService]);+ injector.add([LexerTreeBuilder]);+ injector.add([FormulaDataModel]);+ injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+ injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);+ const currentConfigService = injector.get(IFormulaCurrentConfigService);+ currentConfigService.load({+ allUnitData: {unit: {sheet: {cellData: unitDataMatrix,+ columnCount: 20,+ columnData: {},+ rowCount: 20,+ rowData: {},},},- }),- 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- );+ },+ unitStylesData: {},+ unitSheetNameMap: { unit: { sheet: 'Sheet1' } },+ formulaData: {},+ arrayFormulaCellData: { unit: { sheet: {} } },+ arrayFormulaRange,+ forceCalculate: false,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ });+ const runtime = injector.get(IFormulaRuntimeService) as FormulaRuntimeService;return {runtime,unitDataMatrix,- arrayFormulaCellData,+ arrayFormulaCellData: currentConfigService.getArrayFormulaCellData().unit!.sheet!,arrayFormulaRange,};}@@ -124,7 +149,7 @@ describe('FormulaRuntimeService', () => {expect(runtime.currentSubUnitId).toBe('sheet');expect(runtime.currentUnitId).toBe('unit');- const lambdaVar = new Map<string, any>([['x', null]]);+ const lambdaVar = new Map<string, Nullable<BaseAstNode>>([['x', null]]);runtime.registerFunctionDefinitionPrivacyVar('lambda-1', lambdaVar);expect(runtime.getFunctionDefinitionPrivacyVar('lambda-1')).toBe(lambdaVar);runtime.clearFunctionDefinitionPrivacyVar();@@ -191,12 +216,9 @@ describe('FormulaRuntimeService', () => {});runtime.setRuntimeData(hyperlinkValue as never);- expect(runtime.getUnitData().unit?.sheet?.getValue(0, 0)).toEqual({- v: 'Open',- p: {- url: 'https://example.com',- },- });+ const cell = runtime.getUnitData().unit?.sheet?.getValue(0, 0);+ expect(cell?.p?.body?.dataStream).toBe('Open\r\n');+ expect(cell?.p?.body?.customRanges?.[0]?.properties?.url).toBe('https://example.com');});it('should handle single-cell and normal array spill write', () => {@@ -402,45 +424,6 @@ describe('FormulaRuntimeService', () => {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);diff --git a/packages/engine-render/src/services/__tests__/canvas-color.service.spec.ts b/packages/engine-render/src/services/__tests__/canvas-color.service.spec.tsnew file mode 100644index 0000000000..db9117b304--- /dev/null+++ b/packages/engine-render/src/services/__tests__/canvas-color.service.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 { Injector, ThemeService } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { CanvasColorService, DumbCanvasColorService, ICanvasColorService } from '../canvas-color.service';++describe('CanvasColorService', () => {+ it('keeps render colors unchanged in light mode', () => {+ const injector = new Injector();+ injector.add([ThemeService]);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);++ expect(injector.get(ICanvasColorService).getRenderColor('#17212b')).toBe('#17212b');+ });++ it('maps render colors for dark mode rendering', () => {+ const injector = new Injector();+ injector.add([ThemeService]);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.get(ThemeService).setDarkMode(true);++ expect(injector.get(ICanvasColorService).getRenderColor('#17212b')).toBe('#e2e8f0');+ expect(injector.get(ICanvasColorService).getRenderColor('rgba(37, 99, 235, 0.08)')).toBe('rgba(96,165,250,0.22)');+ });++ it('provides a dumb color service for render contexts that should not transform colors', () => {+ const injector = new Injector();+ injector.add([ICanvasColorService, { useClass: DumbCanvasColorService }]);++ expect(injector.get(ICanvasColorService).getRenderColor('primary.600')).toBe('primary.600');+ });+});diff --git a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts b/packages/engine-render/src/services/__tests__/canvas-color.spec.tsdeleted file mode 100644index 214b4c7720..0000000000--- a/packages/engine-render/src/services/__tests__/canvas-color.spec.ts+++ /dev/null@@ -1,150 +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 { Injector } from '@univerjs/core';-import { ThemeService } from '@univerjs/core';-import { ICanvasColorService } from '@univerjs/engine-render';-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', () => {- let get: Injector['get'];- let canvasColorService: ICanvasColorService;- let themeService: ThemeService;-- beforeEach(() => {- const testBed = createCanvasColorTestBed();- get = testBed.get;- canvasColorService = get(ICanvasColorService);- themeService = get(ThemeService);- });-- it('test hex color', async () => {- const color = '#FF0000';- themeService.setDarkMode(false);- const invertedColor = canvasColorService.getRenderColor(color);- expect(invertedColor).toEqual(color);- themeService.setDarkMode(true);- const invertedColor2 = canvasColorService.getRenderColor(color);- expect(invertedColor2).toEqual('#ff5555');- });-- it('test rgb color', async () => {- const color = 'rgb(255, 0, 0)';- themeService.setDarkMode(false);- const invertedColor = canvasColorService.getRenderColor(color);- expect(invertedColor).toEqual(color);- themeService.setDarkMode(true);- const invertedColor2 = canvasColorService.getRenderColor(color);- expect(invertedColor2).toEqual('rgb(255,85,85)');- });-- it('test rgba color', async () => {- const color = 'rgba(255, 0, 0, 1)';- themeService.setDarkMode(false);- const invertedColor = canvasColorService.getRenderColor(color);- expect(invertedColor).toEqual(color);- themeService.setDarkMode(true);- const invertedColor2 = canvasColorService.getRenderColor(color);- expect(invertedColor2).toEqual('rgba(255,85,85, 1)');- });-- it('keeps transparent named colors transparent in dark mode', async () => {- themeService.setDarkMode(true);-- expect(canvasColorService.getRenderColor('transparent')).toBe('transparent');- });-- it('uses stable dark-mode overrides for common canvas interaction colors', async () => {- themeService.setDarkMode(false);- expect(canvasColorService.getRenderColor('#f3f6fa')).toEqual('#f3f6fa');- expect(canvasColorService.getRenderColor('rgba(37, 99, 235, 0.08)')).toEqual('rgba(37, 99, 235, 0.08)');-- themeService.setDarkMode(true);- expect(canvasColorService.getRenderColor('#f3f6fa')).toEqual('#18243a');- expect(canvasColorService.getRenderColor('#1d5cff')).toEqual('#60a5fa');- expect(canvasColorService.getRenderColor('rgba(37, 99, 235, 0.08)')).toEqual('rgba(96,165,250,0.22)');- expect(canvasColorService.getRenderColor('rgba(37,99,235,0.08)')).toEqual('rgba(96,165,250,0.22)');- });-- it('test short hex color', async () => {- const color = '#ccc';- themeService.setDarkMode(false);- const invertedColor = canvasColorService.getRenderColor(color);- expect(invertedColor).toEqual(color);- themeService.setDarkMode(true);- const invertedColor2 = canvasColorService.getRenderColor(color);- expect(invertedColor2).toEqual('#333333');- });-- it('test hex color with alpha', async () => {- const color = '#ccccccff';- themeService.setDarkMode(false);- const invertedColor = canvasColorService.getRenderColor(color);- expect(invertedColor).toEqual(color);- themeService.setDarkMode(true);- const invertedColor2 = canvasColorService.getRenderColor(color);- expect(invertedColor2).toEqual('#333333ff');- });-- it('test short hex color with alpha', async () => {- const color = '#cccf';- themeService.setDarkMode(false);- const invertedColor = canvasColorService.getRenderColor(color);- expect(invertedColor).toEqual(color);- themeService.setDarkMode(true);- 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.tsindex 67d406b034..2b5c11d202 100644--- a/packages/engine-render/src/services/__tests__/render-config.service.spec.ts+++ b/packages/engine-render/src/services/__tests__/render-config.service.spec.ts@@ -14,12 +14,19 @@* limitations under the License.*/-import { describe, expect, it, vi } from 'vitest';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';import { UniverRenderConfigService } from '../render-config.service';+function createService(): UniverRenderConfigService {+ const injector = new Injector();+ injector.add([UniverRenderConfigService]);+ return injector.get(UniverRenderConfigService);+}+describe('UniverRenderConfigService', () => {- it('should set/get render config and remove nullish values', () => {- const service = new UniverRenderConfigService();+ it('stores renderer options and removes options when callers clear them', () => {+ const service = createService();expect(service.getRenderConfig()).toEqual({ ok: '111' });@@ -30,26 +37,7 @@ describe('UniverRenderConfigService', () => {expect(service.getRenderConfig()).toEqual({ ok: '111' });service.setRenderConfig('lineWidth', 2);- service.setRenderConfig('lineWidth', undefined as any);+ service.setRenderConfig('lineWidth', undefined);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/find-replace/src/index.ts b/packages/find-replace/src/index.tsindex 0020c8f903..8bee1605fd 100644--- a/packages/find-replace/src/index.ts+++ b/packages/find-replace/src/index.ts@@ -30,4 +30,14 @@ export type {IFindReplaceState,IReplaceAllResult,} from './services/find-replace.service';-export { createInitFindReplaceState, FindBy, FindDirection, FindModel, FindReplaceModel, FindReplaceState, FindScope, IFindReplaceService } from './services/find-replace.service';+export {+ createInitFindReplaceState,+ FindBy,+ FindDirection,+ FindModel,+ FindReplaceModel,+ FindReplaceService,+ FindReplaceState,+ FindScope,+ IFindReplaceService,+} from './services/find-replace.service';diff --git a/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts b/packages/find-replace/src/services/__tests__/find-replace.service.spec.tsindex 54ef86950a..376a10a51a 100644--- a/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts+++ b/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts@@ -14,71 +14,151 @@* limitations under the License.*/-import type { FindModel, IFindMatch } from '../find-replace.service';-import { awaitTime } from '@univerjs/core';-+import type { IFindMatch, IFindMoveParams, IFindQuery, IReplaceAllResult } from '../find-replace.service';+import { awaitTime, ICommandService, IContextService, Inject, Injector, IUniverInstanceService } from '@univerjs/core';import { Subject } from 'rxjs';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { FindBy, FindDirection, FindReplaceModel, FindReplaceService, FindScope } from '../find-replace.service';+import { describe, expect, it } from 'vitest';+import { FindBy, FindDirection, FindModel, FindReplaceService, FindScope } from '../find-replace.service';-describe('FindReplaceService', () => {- beforeEach(() => {- vi.useRealTimers();- });+class TestUniverInstanceService {+ readonly focused$ = new Subject<unknown>();+ focusedUnitId: string | null = 'u1';- it('should start session and move to next match', async () => {- const contextService = { setContextValue: vi.fn() };+ getFocusedUnit() {+ return this.focusedUnitId ? { getUnitId: () => this.focusedUnitId } : null;+ }+}++class TestCommandService {+ onCommandExecuted() {+ return { dispose() {} };+ }+}++class TestContextService {+ readonly values: Array<{ key: unknown; value: unknown }> = [];++ setContextValue(key: unknown, value: unknown): void {+ this.values.push({ key, value });+ }+}++interface ITestModelConfig {+ unitId: string;+ matches: IFindMatch[];+ replaceAllResult?: IReplaceAllResult;+}++class TestFindModel extends FindModel {+ readonly matchesUpdate$ = new Subject<IFindMatch[]>();+ readonly activelyChangingMatch$ = new Subject<IFindMatch>();+ readonly nextParams: Array<IFindMoveParams | undefined> = [];+ readonly previousParams: Array<IFindMoveParams | undefined> = [];+ readonly replaceCalls: string[] = [];+ readonly replaceAllCalls: string[] = [];+ nextQueue: Array<IFindMatch | null> = [];+ previousQueue: Array<IFindMatch | null> = [];+ focusCount = 0;++ constructor(+ readonly unitId: string,+ private _matches: IFindMatch[],+ private readonly _replaceAllResult: IReplaceAllResult = { success: _matches.length, failure: 0 }+ ) {+ super();+ }++ getMatches(): IFindMatch[] {+ return this._matches;+ }++ setMatches(matches: IFindMatch[]): void {+ this._matches = matches;+ this.matchesUpdate$.next(matches);+ }++ moveToNextMatch(params?: IFindMoveParams): IFindMatch | null {+ this.nextParams.push(params);+ return this.nextQueue.length ? this.nextQueue.shift()! : this._matches[0] ?? null;+ }++ moveToPreviousMatch(params?: IFindMoveParams): IFindMatch | null {+ this.previousParams.push(params);+ return this.previousQueue.length ? this.previousQueue.shift()! : this._matches.at(-1) ?? null;+ }++ replace(replaceString: string): Promise<boolean> {+ this.replaceCalls.push(replaceString);+ return Promise.resolve(this._matches.length > 0);+ }++ replaceAll(replaceString: string): Promise<IReplaceAllResult> {+ this.replaceAllCalls.push(replaceString);+ return Promise.resolve(this._replaceAllResult);+ }++ focusSelection(): void {+ this.focusCount++;+ }+}- const focused$ = new Subject<any>();- const univerInstanceService = {- getFocusedUnit: vi.fn(() => ({ getUnitId: () => 'u1' })),- focused$,- };+class TestFindReplaceProvider {+ readonly queries: IFindQuery[] = [];+ readonly models: TestFindModel[] = [];+ modelConfigs: ITestModelConfig[] = [];+ terminateCount = 0;- const commandService = {- onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),- };+ constructor(@Inject(Injector) private readonly _injector: Injector) {}- const matchesUpdate$ = new Subject<IFindMatch[]>();- const activelyChangingMatch$ = new Subject<IFindMatch>();+ async find(query: IFindQuery): Promise<FindModel[]> {+ this.queries.push(query);+ this.models.splice(0, this.models.length, ...this.modelConfigs.map((config) =>+ this._injector.createInstance(TestFindModel, config.unitId, config.matches, config.replaceAllResult)+ ));+ return this.models;+ }++ terminate(): void {+ this.terminateCount++;+ }+}++function createService(registerProvider = true) {+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([IContextService, { useClass: TestContextService as never }]);+ injector.add([TestFindReplaceProvider]);+ injector.add([FindReplaceService]);+ const service = injector.get(FindReplaceService);+ const provider = injector.get(TestFindReplaceProvider);+ if (registerProvider) {+ service.registerFindReplaceProvider(provider);+ }+ return {+ injector,+ service,+ provider,+ contextService: injector.get(IContextService) as unknown as TestContextService,+ univerInstanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,+ };+}++describe('FindReplaceService', () => {+ it('should start session and move to next match', async () => {+ const { service, provider } = createService();const match1: IFindMatch = { provider: 'p', unitId: 'u1', range: { i: 1 }, replaceable: true } as any;const match2: IFindMatch = { provider: 'p', unitId: 'u1', range: { i: 2 }, replaceable: false } as any;+ provider.modelConfigs = [{ unitId: 'u1', matches: [match1, match2], replaceAllResult: { success: 2, failure: 0 } }];- const model: FindModel = {- unitId: 'u1',- matchesUpdate$,- activelyChangingMatch$,- getMatches: () => [match1, match2],- moveToNextMatch: vi.fn(() => match1),- moveToPreviousMatch: vi.fn(() => match2),- replace: vi.fn(async () => true),- replaceAll: vi.fn(async () => ({ success: 2, failure: 0 })),- focusSelection: vi.fn(),- dispose: vi.fn(),- } as any;-- const provider = {- find: vi.fn(async () => [model]),- terminate: vi.fn(),- };-- const injector = {- createInstance: vi.fn((_cls: any, _state: any, _providers: any) => {- return new FindReplaceModel(_state, _providers, univerInstanceService as any, commandService as any);- }),- };-- const service = new FindReplaceService(injector as any, contextService as any);- service.registerFindReplaceProvider(provider as any);expect(service.start(false)).toBe(true);service.changeFindString('hello');- service.changeFindDirection(FindDirection.ROW);- service.changeFindScope(FindScope.SUBUNIT);- service.changeFindBy(FindBy.VALUE);+ service.changeFindDirection(FindDirection.COLUMN);+ service.changeFindScope(FindScope.UNIT);+ service.changeFindBy(FindBy.FORMULA);service.find();- // wait for provider find to resolveawait awaitTime(0);service.moveToNextMatch();@@ -94,4 +174,112 @@ describe('FindReplaceService', () => {service.terminate();service.dispose();});++ it('should search with the typed replace query on the first navigation in replace mode', async () => {+ const { service, provider, contextService } = createService();+ const match: IFindMatch = { provider: 'p', unitId: 'u1', range: { row: 1 }, replaceable: true } as any;+ provider.modelConfigs = [{ unitId: 'u1', matches: [match] }];+ const focusSignals: number[] = [];+ service.focusSignal$.subscribe(() => focusSignals.push(focusSignals.length + 1));++ expect(service.start(true)).toBe(true);+ service.changeInputtingFindString('invoice');+ service.moveToNextMatch();+ await awaitTime(0);++ expect(provider.queries.at(-1)).toMatchObject({+ findString: 'invoice',+ replaceRevealed: true,+ });+ expect(service.getCurrentMatch()).toEqual(match);+ expect(focusSignals).toEqual([1]);+ expect(contextService.values.map(({ value }) => value)).toContain(true);++ service.terminate();+ service.dispose();+ });++ it('should navigate across find models when the current unit has no next or previous match', async () => {+ const { service, provider } = createService();+ const match1: IFindMatch = { provider: 'p', unitId: 'u1', range: { row: 1 }, replaceable: true } as any;+ const match2: IFindMatch = { provider: 'p', unitId: 'u2', range: { row: 2 }, replaceable: true } as any;+ provider.modelConfigs = [+ { unitId: 'u1', matches: [match1] },+ { unitId: 'u2', matches: [match2] },+ ];++ expect(service.start()).toBe(true);+ service.changeFindString('total');+ service.find();+ await awaitTime(0);++ const [firstModel, secondModel] = provider.models;+ firstModel.nextQueue = [null];+ secondModel.nextQueue = [match2];+ service.moveToNextMatch();+ expect(service.getCurrentMatch()).toEqual(match2);+ expect(secondModel.nextParams).toContainEqual({ ignoreSelection: true });++ secondModel.previousQueue = [null];+ firstModel.previousQueue = [match1];+ service.moveToPreviousMatch();+ expect(service.getCurrentMatch()).toEqual(match1);+ expect(firstModel.previousParams).toContainEqual({ ignoreSelection: true });++ service.terminate();+ service.dispose();+ });++ it('should aggregate replace-all failures without clearing the current search session', async () => {+ const { service, provider } = createService();+ const match1: IFindMatch = { provider: 'p', unitId: 'u1', range: { row: 1 }, replaceable: true } as any;+ const match2: IFindMatch = { provider: 'p', unitId: 'u1', range: { row: 2 }, replaceable: true } as any;+ provider.modelConfigs = [+ { unitId: 'u1', matches: [match1], replaceAllResult: { success: 2, failure: 0 } },+ { unitId: 'u2', matches: [match2], replaceAllResult: { success: 0, failure: 1 } },+ ];++ expect(service.start()).toBe(true);+ service.changeFindString('draft');+ service.changeReplaceString('final');+ service.find();+ await awaitTime(0);++ const terminateCountBeforeReplaceAll = provider.terminateCount;+ await expect(service.replaceAll()).resolves.toEqual({ success: 2, failure: 1 });+ expect(provider.models.map((model) => model.replaceAllCalls)).toEqual([['final'], ['final']]);+ expect(service.getCurrentMatch()).toEqual(match1);+ expect(provider.terminateCount).toBe(terminateCountBeforeReplaceAll);++ service.terminate();+ service.dispose();+ });++ it('should report no matches and clear replaceable results when providers find nothing', async () => {+ const { service, provider } = createService();+ provider.modelConfigs = [{ unitId: 'u1', matches: [] }];+ const replaceableSnapshots: IFindMatch[][] = [];+ service.replaceables$.subscribe((replaceables) => replaceableSnapshots.push(replaceables));++ expect(service.start()).toBe(true);+ service.changeFindString('missing');+ service.find();+ await awaitTime(0);++ expect(service.getCurrentMatch()).toBeNull();+ expect(replaceableSnapshots.at(-1)).toEqual([]);++ service.terminate();+ service.dispose();+ });++ it('should fail commands that require an active session when no provider has started one', async () => {+ const { service } = createService(false);++ expect(service.start()).toBe(false);+ expect(await service.replace()).toBe(false);+ await expect(service.replaceAll()).rejects.toThrow('model is not initialized');++ service.dispose();+ });});diff --git a/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx b/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsxnew file mode 100644index 0000000000..e4a0f875fe--- /dev/null+++ b/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx@@ -0,0 +1,509 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, Injector, Nullable } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import type { TestMessageService } from '../../../__tests__/create-test-bed';+import type {+ IFindMatch,+ IFindMoveParams,+ IFindQuery,+ IFindReplaceState,+ IReplaceAllResult,+} from '../../../services/find-replace.service';+import { awaitTime, ICommandService, toDisposable } from '@univerjs/core';+import { ILayoutService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { createTestBed, IMessageService } from '../../../__tests__/create-test-bed';+import {+ ReplaceAllMatchesCommand,+ ReplaceCurrentMatchCommand,+} from '../../../commands/commands/replace.command';+import {+ OpenFindDialogOperation,+ OpenReplaceDialogOperation,+} from '../../../commands/operations/find-replace.operation';+import {+ FindBy,+ FindDirection,+ FindModel,+ FindReplaceService,+ FindScope,+ IFindReplaceService,+} from '../../../services/find-replace.service';+import { FindReplaceDialog } from '../FindReplaceDialog';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++interface ICellText {+ id: string;+ text: string;+}++interface ICellRange {+ id: string;+}++const INITIAL_ROWS: ICellText[] = [+ { id: 'A1', text: 'apple' },+ { id: 'A2', text: 'pineapple' },+ { id: 'A3', text: 'Apple' },+ { id: 'A4', text: 'banana' },+];++const FIND_LABEL = 'find-replace.dialog.find';+const REPLACE_LABEL = 'find-replace.dialog.replace';+const REPLACE_ALL_LABEL = 'find-replace.dialog.replace-all';+const ADVANCED_LABEL = 'find-replace.dialog.advanced-finding';++class TextFindModel extends FindModel {+ private readonly _matchesUpdate$ = new BehaviorSubject<IFindMatch<ICellRange>[]>([]);+ private readonly _activelyChangingMatch$ = new Subject<IFindMatch<ICellRange>>();+ private _matches: IFindMatch<ICellRange>[] = [];+ private _position = -1;++ override readonly unitId = 'test';+ override readonly matchesUpdate$ = this._matchesUpdate$.asObservable();+ override readonly activelyChangingMatch$ = this._activelyChangingMatch$.asObservable();++ constructor(+ private readonly _rows: ICellText[],+ private readonly _query: IFindQuery+ ) {+ super();+ this._refreshMatches();+ }++ override dispose(): void {+ this._matchesUpdate$.complete();+ this._activelyChangingMatch$.complete();+ super.dispose();+ }++ override getMatches(): IFindMatch<ICellRange>[] {+ return this._matches;+ }++ override moveToNextMatch(params?: IFindMoveParams): IFindMatch<ICellRange> | null {+ if (this._matches.length === 0) {+ return null;+ }++ if (params?.stayIfOnMatch && this._position >= 0) {+ return this._emitCurrent();+ }++ if (params?.ignoreSelection) {+ this._position = 0;+ } else {+ this._position = this._position + 1;+ if (this._position >= this._matches.length) {+ this._position = params?.loop ? 0 : this._matches.length - 1;+ }+ }++ return this._emitCurrent();+ }++ override moveToPreviousMatch(params?: IFindMoveParams): IFindMatch<ICellRange> | null {+ if (this._matches.length === 0) {+ return null;+ }++ if (params?.ignoreSelection) {+ this._position = this._matches.length - 1;+ } else {+ this._position = this._position - 1;+ if (this._position < 0) {+ this._position = params?.loop ? this._matches.length - 1 : 0;+ }+ }++ return this._emitCurrent();+ }++ override async replace(replaceString: string): Promise<boolean> {+ const match = this._matches[this._position];+ if (!match) {+ return false;+ }++ const row = this._rows.find((item) => item.id === match.range.id);+ if (!row) {+ return false;+ }++ row.text = replaceString;+ this._refreshMatches();+ return true;+ }++ override async replaceAll(replaceString: string): Promise<IReplaceAllResult> {+ const ids = new Set(this._matches.map((match) => match.range.id));+ this._rows.forEach((row) => {+ if (ids.has(row.id)) {+ row.text = replaceString;+ }+ });+ const success = ids.size;+ this._refreshMatches();+ return { success, failure: 0 };+ }++ override focusSelection(): void {+ const match = this._matches[this._position];+ if (match) {+ this._activelyChangingMatch$.next(match);+ }+ }++ private _emitCurrent(): IFindMatch<ICellRange> {+ const match = this._matches[this._position];+ this._activelyChangingMatch$.next(match);+ return match;+ }++ private _refreshMatches(): void {+ this._matches = this._rows+ .filter((row) => this._doesRowMatch(row))+ .map((row) => ({+ provider: 'text-provider',+ unitId: this.unitId,+ range: { id: row.id },+ replaceable: true,+ }));+ this._position = this._matches.length > 0 ? Math.min(Math.max(this._position, 0), this._matches.length - 1) : -1;+ this._matchesUpdate$.next(this._matches);+ }++ private _doesRowMatch(row: ICellText): boolean {+ const source = this._query.caseSensitive ? row.text : row.text.toLocaleLowerCase();+ const target = this._query.caseSensitive ? this._query.findString : this._query.findString.toLocaleLowerCase();+ return this._query.matchesTheWholeCell ? source === target : source.includes(target);+ }+}++class TestFindReplaceProvider {+ readonly rows = INITIAL_ROWS.map((row) => ({ ...row }));+ readonly queries: IFindQuery[] = [];++ async find(query: IFindQuery): Promise<FindModel[]> {+ this.queries.push({ ...query });+ return [new TextFindModel(this.rows, query)];+ }++ terminate(): void {+ }+}++class TestLayoutService {+ private _focused = false;+ readonly rootContainerElement = document.body;++ get isFocused() {+ return this._focused;+ }++ focus() {+ this._focused = true;+ }++ registerFocusHandler(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerRootContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContentElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ getContentElement() {+ return document.body;+ }++ checkElementInCurrentContainers() {+ return true;+ }++ checkContentIsFocused() {+ return this._focused;+ }+}++function createDialogTestBed() {+ const testBed = createTestBed(undefined, [+ [IFindReplaceService, { useClass: FindReplaceService }],+ [ILayoutService, { useClass: TestLayoutService as never }],+ [TestFindReplaceProvider],+ ]);++ const commandService = testBed.get(ICommandService);+ [+ OpenFindDialogOperation,+ OpenReplaceDialogOperation,+ ReplaceCurrentMatchCommand,+ ReplaceAllMatchesCommand,+ ].forEach((command) => commandService.registerCommand(command));++ const provider = testBed.get(TestFindReplaceProvider);+ const findReplaceService = testBed.get(IFindReplaceService);+ findReplaceService.registerFindReplaceProvider(provider);++ return {+ ...testBed,+ commandService,+ provider,+ findReplaceService,+ };+}++function renderDialog(injector: Injector) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <FindReplaceDialog />+ </RediContext.Provider>+ );+ });+ return { container, root };+}++function getInputs(container: HTMLElement): HTMLInputElement[] {+ return Array.from(container.querySelectorAll('input[type="text"]'));+}++function getButton(container: HTMLElement, text: string): HTMLButtonElement {+ const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent?.trim() === text);+ if (!button) {+ throw new Error(`Button "${text}" was not found.`);+ }++ return button as HTMLButtonElement;+}++function getLink(container: HTMLElement, text: string): HTMLElement {+ const link = Array.from(container.querySelectorAll('a')).find((item) => item.textContent?.trim() === text);+ if (!link) {+ throw new Error(`Link "${text}" was not found.`);+ }++ return link as HTMLElement;+}++function setInputValue(input: HTMLInputElement, value: string): void {+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ setter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++async function flushSearch() {+ await act(async () => {+ await awaitTime(260);+ });+}++describe('FindReplaceDialog', () => {+ let root: Root | undefined;+ let container: HTMLElement | undefined;++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ root = undefined;+ container = undefined;+ });++ it('runs a find session from the simple dialog input', async () => {+ const testBed = createDialogTestBed();+ await act(async () => {+ testBed.commandService.syncExecuteCommand(OpenFindDialogOperation.id);+ });++ const rendered = renderDialog(testBed.univer.__getInjector());+ root = rendered.root;+ container = rendered.container;++ await act(async () => {+ setInputValue(getInputs(container!)[0], 'apple');+ });+ await act(async () => {+ await awaitTime(560);+ });+ await flushSearch();++ expect(testBed.provider.queries.at(-1)).toMatchObject({+ findString: 'apple',+ replaceRevealed: false,+ findDirection: FindDirection.ROW,+ findScope: FindScope.SUBUNIT,+ findBy: FindBy.VALUE,+ caseSensitive: false,+ matchesTheWholeCell: false,+ });+ expect(readCurrentMatch(testBed.findReplaceService)?.range).toEqual({ id: 'A1' });+ expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 3, matchesPosition: 1 });+ });++ it('reveals replace controls from the advanced link without restarting the session', async () => {+ const testBed = createDialogTestBed();+ await act(async () => {+ testBed.commandService.syncExecuteCommand(OpenFindDialogOperation.id);+ });++ const rendered = renderDialog(testBed.univer.__getInjector());+ root = rendered.root;+ container = rendered.container;++ await act(async () => {+ getLink(container!, ADVANCED_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(testBed.findReplaceService.replaceRevealed).toBe(true);+ expect(getButton(container!, FIND_LABEL).disabled).toBe(true);+ expect(getButton(container!, REPLACE_LABEL).disabled).toBe(true);+ expect(getButton(container!, REPLACE_ALL_LABEL).disabled).toBe(true);+ expect(getInputs(container!)).toHaveLength(2);+ });++ it('replaces the selected result and then replaces all remaining results', async () => {+ const testBed = createDialogTestBed();+ await act(async () => {+ testBed.commandService.syncExecuteCommand(OpenReplaceDialogOperation.id);+ });++ const rendered = renderDialog(testBed.univer.__getInjector());+ root = rendered.root;+ container = rendered.container;++ await act(async () => {+ const inputs = getInputs(container!);+ setInputValue(inputs[0], 'apple');+ setInputValue(inputs[1], 'orange');+ getButton(container!, FIND_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ await flushSearch();++ expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 3, matchesPosition: 1 });++ await act(async () => {+ getButton(container!, REPLACE_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ await flushSearch();++ expect(testBed.provider.rows.map((row) => row.text)).toEqual(['orange', 'pineapple', 'Apple', 'banana']);++ await act(async () => {+ getButton(container!, REPLACE_ALL_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ await flushSearch();++ expect(testBed.provider.rows.map((row) => row.text)).toEqual(['orange', 'orange', 'orange', 'banana']);+ expect((testBed.get(IMessageService) as TestMessageService).messages.at(-1)?.content).toBe('find-replace.replace.all-success');+ });++ it('moves to the next result when finding the same replace dialog input again', async () => {+ const testBed = createDialogTestBed();+ await act(async () => {+ testBed.commandService.syncExecuteCommand(OpenReplaceDialogOperation.id);+ });++ const rendered = renderDialog(testBed.univer.__getInjector());+ root = rendered.root;+ container = rendered.container;++ await act(async () => {+ const inputs = getInputs(container!);+ setInputValue(inputs[0], 'apple');+ getButton(container!, FIND_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ await flushSearch();++ expect(testBed.provider.queries).toHaveLength(1);+ expect(readCurrentMatch(testBed.findReplaceService)?.range).toEqual({ id: 'A1' });+ expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 3, matchesPosition: 1 });++ await act(async () => {+ getButton(container!, FIND_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ await flushSearch();++ expect(testBed.provider.queries).toHaveLength(1);+ expect(readCurrentMatch(testBed.findReplaceService)?.range).toEqual({ id: 'A2' });+ expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 3, matchesPosition: 2 });+ });++ it('uses the replace dialog options when searching', async () => {+ const testBed = createDialogTestBed();+ await act(async () => {+ testBed.commandService.syncExecuteCommand(OpenReplaceDialogOperation.id);+ });++ const rendered = renderDialog(testBed.univer.__getInjector());+ root = rendered.root;+ container = rendered.container;++ await act(async () => {+ const inputs = getInputs(container!);+ setInputValue(inputs[0], 'Apple');+ const checkboxes = Array.from(container!.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'));+ checkboxes.forEach((checkbox) => checkbox.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ getButton(container!, FIND_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+ await flushSearch();++ expect(testBed.provider.queries.at(-1)).toMatchObject({+ findString: 'Apple',+ replaceRevealed: true,+ caseSensitive: true,+ matchesTheWholeCell: true,+ });+ expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 1, matchesPosition: 1 });+ expect(readCurrentMatch(testBed.findReplaceService)?.range).toEqual({ id: 'A3' });+ });+});++function readState(findReplaceService: IFindReplaceService): IFindReplaceState {+ let value!: IFindReplaceState;+ const subscription = findReplaceService.state$.subscribe((state) => {+ value = state;+ });+ subscription.unsubscribe();+ return value;+}++function readCurrentMatch(findReplaceService: IFindReplaceService): Nullable<IFindMatch> {+ let value: Nullable<IFindMatch> = null;+ const subscription = findReplaceService.currentMatch$.subscribe((match) => {+ value = match;+ });+ subscription.unsubscribe();+ return value;+}diff --git a/packages/network/src/facade/__tests__/f-network.spec.ts b/packages/network/src/facade/__tests__/f-network.spec.tsnew file mode 100644index 0000000000..f9ccb574f8--- /dev/null+++ b/packages/network/src/facade/__tests__/f-network.spec.ts@@ -0,0 +1,161 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { HTTPRequest, ISocket, SocketBodyType } from '@univerjs/network';+import { ILogService, LogLevel, Univer } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import {+ HTTPHeaders,+ HTTPResponse,+ HTTPService,+ IHTTPImplementation,+ ISocketService,+ WebSocketService,+} from '@univerjs/network';+import { firstValueFrom } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { MockHTTPImplementation } from '../../services/http/__testing__/http-testing-utils';+import '@univerjs/network/facade';++class FakeWebSocket {+ static instances: FakeWebSocket[] = [];++ readonly send = vi.fn();+ readonly close = vi.fn();++ constructor(readonly url: string) {+ FakeWebSocket.instances.push(this);+ }++ addEventListener(): void {}++ removeEventListener(): void {}+}++describe('network facade', () => {+ const originalWebSocket = globalThis.WebSocket;++ let univer: Univer;+ let univerAPI: FUniver;++ beforeEach(() => {+ FakeWebSocket.instances = [];+ vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);++ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([HTTPService]);+ injector.add([IHTTPImplementation, { useClass: MockHTTPImplementation }]);+ injector.add([ISocketService, { useClass: WebSocketService }]);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ univerAPI = FUniver.newAPI(injector);+ });++ afterEach(() => {+ univer.dispose();+ vi.unstubAllGlobals();+ globalThis.WebSocket = originalWebSocket;+ });++ it('sends requests through the network facade with the configured HTTP service', async () => {+ const injector = univer.__getInjector();+ const httpImplementation = injector.get(IHTTPImplementation) as MockHTTPImplementation;+ const requests: HTTPRequest[] = [];++ const subscription = httpImplementation.newRequest$.subscribe((request) => {+ requests.push(request);+ httpImplementation.getHandler(request.uid).emitResponse(new HTTPResponse({+ body: { ok: true },+ headers: new HTTPHeaders({ 'content-type': 'application/json' }),+ status: 200,+ statusText: 'OK',+ }));+ });++ const response = await univerAPI.getNetwork().post<{ ok: boolean }>('https://example.com/api', {+ body: { name: 'Univer' },+ headers: { authorization: 'Bearer token' },+ params: { page: 1 },+ });++ expect(response.body).toEqual({ ok: true });+ expect(requests).toHaveLength(1);+ expect(requests[0].method).toBe('POST');+ expect(requests[0].getUrlWithParams()).toBe('https://example.com/api?page=1');+ expect(requests[0].getBody()).toBe(JSON.stringify({ name: 'Univer' }));+ expect(requests[0].headers.get('authorization')).toEqual(['Bearer token']);++ subscription.unsubscribe();+ });++ it('supports item lifecycle requests and server-sent event streams', async () => {+ const injector = univer.__getInjector();+ const httpImplementation = injector.get(IHTTPImplementation) as MockHTTPImplementation;++ const subscription = httpImplementation.newRequest$.subscribe((request) => {+ const url = request.getUrlWithParams();+ const body = request.getBody();+ const parseBody = () => JSON.parse(typeof body === 'string' ? body : '{}');+ const responseBody = (() => {+ if (request.method === 'GET' && url === '/items') {+ return { items: ['item-1'] };+ }+ if (request.method === 'PUT' && url === '/items/1') {+ return { replaced: parseBody().name };+ }+ if (request.method === 'DELETE' && url === '/items/1') {+ return { deleted: 'item-1' };+ }+ if (request.method === 'PATCH' && url === '/items/1') {+ return { patched: parseBody().name };+ }+ if (request.method === 'POST' && url === '/events') {+ return { cursor: parseBody().cursor, stream: 'opened' };+ }+ return { error: 'unexpected request' };+ })();+ httpImplementation.getHandler(request.uid).emitResponse(new HTTPResponse({+ body: responseBody,+ headers: new HTTPHeaders(),+ status: 200,+ statusText: 'OK',+ }));+ });+ const network = univerAPI.getNetwork();++ await expect(network.get('/items')).resolves.toMatchObject({ body: { items: ['item-1'] } });+ await expect(network.put('/items/1', { body: { name: 'Item' } })).resolves.toMatchObject({ body: { replaced: 'Item' } });+ await expect(network.delete('/items/1')).resolves.toMatchObject({ body: { deleted: 'item-1' } });+ await expect(network.patch('/items/1', { body: { name: 'Patched' } })).resolves.toMatchObject({ body: { patched: 'Patched' } });+ await expect(firstValueFrom(network.getSSE('POST', '/events', { body: { cursor: 1 } }))).resolves.toMatchObject({ body: { cursor: 1, stream: 'opened' } });++ subscription.unsubscribe();+ });++ it('creates sockets through the WebSocket service registered in DI', () => {+ const socket = univerAPI.createSocket('wss://example.com/socket');+ const payload: SocketBodyType = 'hello';++ expect(socket.URL).toBe('wss://example.com/socket');+ socket.send(payload);+ socket.close(1000, 'done');++ const connection = FakeWebSocket.instances[0] as FakeWebSocket & ISocket;+ expect(connection.send).toHaveBeenCalledWith(payload);+ expect(connection.close).toHaveBeenCalledWith(1000, 'done');+ });+});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.tsindex be5e5fcf20..c5fbb69e51 100644--- 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.ts@@ -15,8 +15,9 @@*/import type { SocketBodyType } from '../web-socket.service';+import { Injector } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { WebSocketService } from '../web-socket.service';+import { ISocketService, WebSocketService } from '../web-socket.service';type SocketEventName = 'open' | 'close' | 'error' | 'message';@@ -58,6 +59,12 @@ class FakeWebSocket {describe('WebSocketService', () => {const originalWebSocket = globalThis.WebSocket;+ function createService() {+ const injector = new Injector();+ injector.add([ISocketService, { useClass: WebSocketService }]);+ return injector.get(ISocketService) as WebSocketService;+ }+beforeEach(() => {FakeWebSocket.instances = [];vi.stubGlobal('WebSocket', FakeWebSocket as unknown as typeof WebSocket);@@ -69,7 +76,7 @@ describe('WebSocketService', () => {});it('creates sockets, forwards events, and removes listeners on close', () => {- const service = new WebSocketService();+ const service = createService();const socket = service.createSocket('wss://example.com/socket');expect(socket).not.toBeNull();@@ -128,7 +135,7 @@ describe('WebSocketService', () => {}} as unknown as typeof WebSocket);- const service = new WebSocketService();+ const service = createService();expect(service.createSocket('wss://example.com/fail')).toBeNull();expect(errorSpy).toHaveBeenCalled();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.tsindex 8cff38433a..41dfdf6e5a 100644--- 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.ts@@ -14,19 +14,21 @@* limitations under the License.*/-import type { ICommandService, ILogService, IUniverInstanceService } from '@univerjs/core';-import { UniverInstanceType } from '@univerjs/core';+import { ICommandService, ILogService, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';-import { RemoteSyncPrimaryService, WebWorkerRemoteInstanceService } from '../remote-instance.service';+import { IRemoteInstanceService, IRemoteSyncService, 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);+ class TestCommandService {+ syncExecuteCommand = syncExecuteCommand;+ }++ const injector = new Injector();+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([IRemoteSyncService, { useClass: RemoteSyncPrimaryService }]);+ const service = injector.get(IRemoteSyncService);await expect(service.syncMutation({mutationInfo: {@@ -64,18 +66,25 @@ describe('remote-instance.service', () => {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);+ class TestUniverInstanceService {+ createUnit = createUnit;+ disposeUnit = disposeUnit;+ }++ class TestCommandService {+ syncExecuteCommand = syncExecuteCommand;+ }++ class TestLogService {+ debug = debug;+ }++ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([ILogService, { useClass: TestLogService as never }]);+ injector.add([IRemoteInstanceService, { useClass: WebWorkerRemoteInstanceService }]);+ const service = injector.get(IRemoteInstanceService);await expect(service.whenReady()).resolves.toBe(true);diff --git a/packages/rpc/src/services/rpc/__tests__/channel.service.spec.ts b/packages/rpc/src/services/rpc/__tests__/channel.service.spec.tsindex 45c3ee85fe..3b42fdf52d 100644--- a/packages/rpc/src/services/rpc/__tests__/channel.service.spec.ts+++ b/packages/rpc/src/services/rpc/__tests__/channel.service.spec.ts@@ -15,7 +15,7 @@*/import type { IMessageProtocol } from '../rpc.service';-import { awaitTime } from '@univerjs/core';+import { awaitTime, Injector } from '@univerjs/core';import { Observable, Subject } from 'rxjs';import { describe, expect, it } from 'vitest';import { ChannelService } from '../channel.service';@@ -31,7 +31,8 @@ describe('ChannelService', () => {onMessage: message$.asObservable(),};- const service = new ChannelService(protocol);+ const injector = new Injector();+ const service = injector.createInstance(ChannelService, protocol);service.registerChannel('math', fromModule({add(a: number, b: number) {diff --git a/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts b/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.tsindex bd5d49c0ee..46bc0b25cb 100644--- a/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts+++ b/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts@@ -14,12 +14,11 @@* limitations under the License.*/-/* eslint-disable max-lines-per-function */--import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import type { Dependency, IDisposable, IRange, IWorkbookData, Nullable, Workbook } from '@univerjs/core';import type { ISelectionWithStyle } from '@univerjs/sheets';import {BooleanNumber,+ Disposable,ICommandService,ILogService,Inject,@@ -30,11 +29,19 @@ import {LogLevel,Plugin,RANGE_TYPE,+ toDisposable,Tools,Univer,UniverInstanceType,} from '@univerjs/core';-import { IActiveDirtyManagerService, RegisterOtherFormulaService } from '@univerjs/engine-formula';+import {+ ActiveDirtyManagerService,+ IActiveDirtyManagerService,+ OtherFormulaMarkDirty,+ RegisterOtherFormulaService,+ RemoveOtherFormulaMutation,+ SetOtherFormulaMutation,+} from '@univerjs/engine-formula';import {BorderStyleManagerService,RangeProtectionRuleModel,@@ -65,7 +72,6 @@ import {import { ISheetClipboardService } from '@univerjs/sheets-ui';import { ComponentManager, ISidebarService } from '@univerjs/ui';import { BehaviorSubject, Subject } from 'rxjs';-import { vi } from 'vitest';const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {id: 'test',@@ -102,6 +108,153 @@ const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {styles: {},};+class TestSidebarService extends Disposable {+ private _sidebarOptions = { id: '', visible: false } as any;+ readonly sidebarOptions$ = new BehaviorSubject(this._sidebarOptions);+ readonly scrollEvent$ = new Subject<Event>();+ private _container?: HTMLElement;+ private _width?: number;++ get visible(): boolean {+ return Boolean(this._sidebarOptions.visible);+ }++ get options() {+ return this._sidebarOptions;+ }++ get width(): number | undefined {+ return this._width;+ }++ setWidth(value: number): void {+ this._width = value;+ }++ open(params: any): IDisposable {+ this._sidebarOptions = {+ ...params,+ visible: true,+ };+ this.sidebarOptions$.next(this._sidebarOptions);+ params.onOpen?.();++ return toDisposable(() => {+ this.close(params.id);+ });+ }++ close(id?: string): void {+ if (id && this._sidebarOptions.id !== id) {+ return;+ }++ this._sidebarOptions = {+ ...this._sidebarOptions,+ visible: false,+ };+ this.sidebarOptions$.next(this._sidebarOptions);+ this._sidebarOptions.onClose?.();+ }++ getContainer() {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element;+ }+}++class TestSheetClipboardService extends Disposable {+ private _clipboardHooks: any[] = [];+ private readonly _showMenu$ = new BehaviorSubject(false);+ readonly showMenu$ = this._showMenu$.asObservable();+ private readonly _pasteOptionsCache$ = new BehaviorSubject<any>(null);+ readonly pasteOptionsCache$ = this._pasteOptionsCache$.asObservable();++ setShowMenu(show: boolean): void {+ this._showMenu$.next(show);+ }++ getPasteMenuVisible(): boolean {+ return this._showMenu$.getValue();+ }++ getPasteOptionsCache(): any {+ return this._pasteOptionsCache$.getValue();+ }++ updatePasteOptionsCache(cache: any): void {+ this._pasteOptionsCache$.next(cache);+ }++ async copy(): Promise<boolean> {+ return false;+ }++ async cut(): Promise<boolean> {+ return false;+ }++ async paste(): Promise<boolean> {+ return false;+ }++ async pasteByCopyId(): Promise<boolean> {+ return false;+ }++ async legacyPaste(): Promise<boolean> {+ return false;+ }++ rePasteWithPasteType(): boolean {+ return false;+ }++ disposePasteOptionsCache(): void {+ this._pasteOptionsCache$.next(null);+ }++ generateCopyContent(_workbookId: string, _worksheetId: string, _range: IRange): Nullable<unknown> {+ return null;+ }++ copyContentCache(): any {+ return null;+ }++ addClipboardHook(hook: any): IDisposable {+ this._clipboardHooks.push(hook);++ return toDisposable(() => {+ const hooks = [];+ for (const item of this._clipboardHooks) {+ if (item !== hook) {+ hooks.push(item);+ }+ }+ this._clipboardHooks = hooks;+ });+ }++ getClipboardHooks(): any[] {+ return this._clipboardHooks;+ }++ removeMarkSelection(): void {+ // Mark selections are not created in these UI command tests.+ }++ override dispose(): void {+ super.dispose();+ this._showMenu$.complete();+ this._pasteOptionsCache$.complete();+ this._clipboardHooks = [];+ }+}+function createLocalSheetsTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {const univer = new Univer();const injector = univer.__getInjector();@@ -166,53 +319,16 @@ export function createCfUiTestBed() {const commandService = get(ICommandService);const selectionsService = get(SheetsSelectionsService);- const formulaResult$ = new Subject<Record<string, Record<string, unknown[]>>>();- const componentManager = {- register: vi.fn((): IDisposable => ({- dispose: vi.fn(),- })),- };- const sidebarOptions$ = new BehaviorSubject({ id: '', visible: false } as any);- const sidebarService = {- open: vi.fn((): IDisposable => ({- dispose: vi.fn(),- })),- sidebarOptions$,- };- let clipboardHook: {- onBeforeCopy: (unitId: string, subUnitId: string, range: ISelectionWithStyle['range']) => void;- onPasteCells: (...args: any[]) => { redos: Array<{ id: string; params: unknown }>; undos: Array<{ id: string; params: unknown }> };- } | undefined;- const sheetClipboardService = {- addClipboardHook: vi.fn((hook) => {- clipboardHook = hook;- return {- dispose: vi.fn(),- };- }),- };-- injector.add([RegisterOtherFormulaService, {- useValue: {- formulaResult$,- registerFormulaWithRange: vi.fn(() => 'formula-1'),- deleteFormula: vi.fn(),- getFormulaValueSync: vi.fn(() => null),- } as unknown as RegisterOtherFormulaService,- }]);- injector.add([IActiveDirtyManagerService, {- useValue: {- register: vi.fn(),- } as unknown as IActiveDirtyManagerService,- }]);+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);+ injector.add([RegisterOtherFormulaService]);injector.add([ConditionalFormattingRuleModel]);injector.add([ConditionalFormattingRangeIndexModel]);injector.add([ConditionalFormattingFormulaService]);injector.add([ConditionalFormattingRangeTransformService]);injector.add([ConditionalFormattingViewModel]);- injector.add([ComponentManager, { useValue: componentManager as unknown as ComponentManager }]);- injector.add([ISidebarService, { useValue: sidebarService as unknown as ISidebarService }]);- injector.add([ISheetClipboardService, { useValue: sheetClipboardService as unknown as ISheetClipboardService }]);+ injector.add([ComponentManager]);+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);+ injector.add([ISheetClipboardService, { useClass: TestSheetClipboardService as never }]);[AddConditionalRuleMutation,@@ -221,8 +337,11 @@ export function createCfUiTestBed() {MoveConditionalRuleMutation,ClearRangeCfCommand,ClearWorksheetCfCommand,+ OtherFormulaMarkDirty,+ RemoveOtherFormulaMutation,SetRangeValuesCommand,SetRangeValuesMutation,+ SetOtherFormulaMutation,].forEach((command) => commandService.registerCommand(command));const setSelection = (range: ISelectionWithStyle['range']) => {@@ -244,11 +363,16 @@ export function createCfUiTestBed() {selectionsService,ruleModel: injector.get(ConditionalFormattingRuleModel),viewModel: injector.get(ConditionalFormattingViewModel),- componentManager,- sidebarService,- sidebarOptions$,- sheetClipboardService,- getClipboardHook: () => clipboardHook,+ componentManager: injector.get(ComponentManager),+ sidebarService: injector.get(ISidebarService) as unknown as TestSidebarService,+ sidebarOptions$: (injector.get(ISidebarService) as unknown as TestSidebarService).sidebarOptions$,+ sheetClipboardService: injector.get(ISheetClipboardService) as unknown as TestSheetClipboardService,+ getClipboardHook: () => (injector.get(ISheetClipboardService) as unknown as TestSheetClipboardService).getClipboardHooks()[0] as+ | {+ onBeforeCopy: (unitId: string, subUnitId: string, range: ISelectionWithStyle['range']) => void;+ onPasteCells: (...args: any[]) => { redos: Array<{ id: string; params: unknown }>; undos: Array<{ id: string; params: unknown }> };+ }+ | undefined,unitId: 'test',subUnitId: 'sheet1',setSelection,diff --git a/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts b/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.tsindex f3d3e8cd96..0f3a669a8a 100644--- a/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts+++ b/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts@@ -15,12 +15,24 @@*/import type { IRange } from '@univerjs/core';-import { CFNumberOperator, CFRuleType, CFSubRuleType } from '@univerjs/sheets-conditional-formatting';+import {+ CFNumberOperator,+ CFRuleType,+ CFSubRuleType,+ CFTextOperator,+ CFTimePeriodOperator,+} from '@univerjs/sheets-conditional-formatting';import { afterEach, describe, expect, it } from 'vitest';import { createCfUiTestBed } from '../../../__tests__/create-cf-ui-test-bed';+import { AddAverageCfCommand } from '../add-average-cf.command';import { AddColorScaleConditionalRuleCommand } from '../add-color-scale-cf.command';import { AddDataBarConditionalRuleCommand } from '../add-data-bar-cf.command';+import { AddDuplicateValuesCfCommand } from '../add-duplicate-values-cf.command';import { AddNumberCfCommand } from '../add-number-cf.command';+import { AddRankCfCommand } from '../add-rank-cf.command';+import { AddTextCfCommand } from '../add-text-cf.command';+import { AddTimePeriodCfCommand } from '../add-time-period-cf.command';+import { AddUniqueValuesCfCommand } from '../add-unique-values-cf.command';const range: IRange = {startRow: 1,@@ -63,6 +75,34 @@ describe('conditional formatting add commands', () => {testBed.univer.dispose();});+ it('adds number highlight rules with a single comparison value', async () => {+ const testBed = createCfUiTestBed();+ testBed.commandService.registerCommand(AddNumberCfCommand);++ expect(await testBed.commandService.executeCommand(AddNumberCfCommand.id, {+ ranges: [range],+ operator: CFNumberOperator.greaterThan,+ style: { bg: { rgb: '#afa' } },+ value: 100,+ })).toBe(true);++ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);+ expect(rules).toHaveLength(1);+ expect(rules?.[0]).toMatchObject({+ ranges: [range],+ stopIfTrue: false,+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.number,+ operator: CFNumberOperator.greaterThan,+ style: { bg: { rgb: '#afa' } },+ value: 100,+ },+ });++ testBed.univer.dispose();+ });+it('adds color scale rules into the real rule model', async () => {const testBed = createCfUiTestBed();testBed.commandService.registerCommand(AddColorScaleConditionalRuleCommand);@@ -118,4 +158,158 @@ describe('conditional formatting add commands', () => {testBed.univer.dispose();});++ it('adds rank highlight rules for bottom percent scenarios', async () => {+ const testBed = createCfUiTestBed();+ testBed.commandService.registerCommand(AddRankCfCommand);++ expect(await testBed.commandService.executeCommand(AddRankCfCommand.id, {+ ranges: [range],+ isPercent: true,+ isBottom: true,+ value: 10,+ style: { bg: { rgb: '#fed' } },+ })).toBe(true);++ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);+ expect(rules).toHaveLength(1);+ expect(rules?.[0]).toMatchObject({+ ranges: [range],+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.rank,+ isPercent: true,+ isBottom: true,+ value: 10,+ style: { bg: { rgb: '#fed' } },+ },+ });++ testBed.univer.dispose();+ });++ it('adds average highlight rules for above-average cells', async () => {+ const testBed = createCfUiTestBed();+ testBed.commandService.registerCommand(AddAverageCfCommand);++ expect(await testBed.commandService.executeCommand(AddAverageCfCommand.id, {+ ranges: [range],+ operator: CFNumberOperator.greaterThan,+ style: { cl: { rgb: '#080' } },+ stopIfTrue: true,+ })).toBe(true);++ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);+ expect(rules).toHaveLength(1);+ expect(rules?.[0]).toMatchObject({+ ranges: [range],+ stopIfTrue: true,+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.average,+ operator: CFNumberOperator.greaterThan,+ style: { cl: { rgb: '#080' } },+ },+ });++ testBed.univer.dispose();+ });++ it('adds text highlight rules for matching cell contents', async () => {+ const testBed = createCfUiTestBed();+ testBed.commandService.registerCommand(AddTextCfCommand);++ expect(await testBed.commandService.executeCommand(AddTextCfCommand.id, {+ ranges: [range],+ operator: CFTextOperator.containsText,+ value: 'overdue',+ style: { bl: 1 },+ })).toBe(true);++ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);+ expect(rules).toHaveLength(1);+ expect(rules?.[0]).toMatchObject({+ ranges: [range],+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ operator: CFTextOperator.containsText,+ value: 'overdue',+ style: { bl: 1 },+ },+ });++ testBed.univer.dispose();+ });++ it('adds time period rules for recent dates', async () => {+ const testBed = createCfUiTestBed();+ testBed.commandService.registerCommand(AddTimePeriodCfCommand);++ expect(await testBed.commandService.executeCommand(AddTimePeriodCfCommand.id, {+ ranges: [range],+ operator: CFTimePeriodOperator.last7Days,+ style: { it: 1 },+ })).toBe(true);++ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);+ expect(rules).toHaveLength(1);+ expect(rules?.[0]).toMatchObject({+ ranges: [range],+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.timePeriod,+ operator: CFTimePeriodOperator.last7Days,+ style: { it: 1 },+ },+ });++ testBed.univer.dispose();+ });++ it('adds duplicate and unique value rules independently', async () => {+ const testBed = createCfUiTestBed();+ testBed.commandService.registerCommand(AddDuplicateValuesCfCommand);+ testBed.commandService.registerCommand(AddUniqueValuesCfCommand);++ expect(await testBed.commandService.executeCommand(AddDuplicateValuesCfCommand.id, {+ ranges: [range],+ style: { bg: { rgb: '#fcc' } },+ })).toBe(true);+ expect(await testBed.commandService.executeCommand(AddUniqueValuesCfCommand.id, {+ ranges: [range],+ style: { bg: { rgb: '#ccf' } },+ stopIfTrue: true,+ })).toBe(true);++ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);+ expect(rules).toHaveLength(2);+ let duplicateRule = rules?.[0];+ let uniqueRule = rules?.[1];+ if (duplicateRule?.rule.type !== CFRuleType.highlightCell || duplicateRule.rule.subType !== CFSubRuleType.duplicateValues) {+ duplicateRule = rules?.[1];+ uniqueRule = rules?.[0];+ }++ expect(duplicateRule).toMatchObject({+ ranges: [range],+ stopIfTrue: false,+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.duplicateValues,+ style: { bg: { rgb: '#fcc' } },+ },+ });+ expect(uniqueRule).toMatchObject({+ ranges: [range],+ stopIfTrue: true,+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.uniqueValues,+ style: { bg: { rgb: '#ccf' } },+ },+ });++ testBed.univer.dispose();+ });});diff --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.tsindex cde7b36fb2..ceb00c6c13 100644--- 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.ts@@ -34,18 +34,31 @@ describe('OpenConditionalFormattingOperator', () => {// each test disposes its own univer instance});- it('opens the real sidebar panel with a rule seeded from the current selection', async () => {+ function createPanelTestBed() {const testBed = createCfUiTestBed();testBed.injector.add([ConditionalFormattingPanelController]);testBed.injector.get(ConditionalFormattingPanelController);testBed.commandService.registerCommand(OpenConditionalFormattingOperator);testBed.setSelection(range);+ return testBed;+ }++ async function openFromMenu(testBed: ReturnType<typeof createPanelTestBed>, value: CF_MENU_OPERATION) {+ expect(await testBed.commandService.executeCommand(OpenConditionalFormattingOperator.id, { value })).toBe(true);++ return testBed.sidebarService.options.children?.rule as IConditionFormattingRule | undefined;+ }++ it('opens the real sidebar panel with a rule seeded from the current selection', async () => {+ const testBed = createPanelTestBed();+expect(await testBed.commandService.executeCommand(OpenConditionalFormattingOperator.id, {value: CF_MENU_OPERATION.formula,})).toBe(true);- expect(testBed.sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({+ expect(testBed.sidebarService.visible).toBe(true);+ expect(testBed.sidebarService.options).toMatchObject({id: 'sheet.conditional.formatting.panel',children: expect.objectContaining({rule: {@@ -57,17 +70,84 @@ describe('OpenConditionalFormattingOperator', () => {},},}),- }));+ });++ testBed.univer.dispose();+ });++ it('opens the default rule editor for creating a new conditional formatting rule', async () => {+ const testBed = createPanelTestBed();++ const rule = await openFromMenu(testBed, CF_MENU_OPERATION.createRule);++ expect(testBed.sidebarService.visible).toBe(true);+ expect(rule).toMatchObject({+ ranges: [expect.objectContaining(range)],+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ },+ });++ testBed.univer.dispose();+ });++ it('opens specialized rule editors from the conditional formatting menu', async () => {+ const testBed = createPanelTestBed();++ let rule = await openFromMenu(testBed, CF_MENU_OPERATION.rank);+ expect(rule).toMatchObject({+ ranges: [expect.objectContaining(range)],+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.rank,+ },+ });++ rule = await openFromMenu(testBed, CF_MENU_OPERATION.colorScale);+ expect(rule).toMatchObject({+ ranges: [expect.objectContaining(range)],+ rule: {+ type: CFRuleType.colorScale,+ config: [],+ },+ });++ rule = await openFromMenu(testBed, CF_MENU_OPERATION.dataBar);+ expect(rule).toMatchObject({+ ranges: [expect.objectContaining(range)],+ rule: {+ type: CFRuleType.dataBar,+ isShowValue: true,+ },+ });++ rule = await openFromMenu(testBed, CF_MENU_OPERATION.icon);+ expect(rule).toMatchObject({+ ranges: [expect.objectContaining(range)],+ rule: {+ type: CFRuleType.iconSet,+ config: [],+ isShowValue: true,+ },+ });++ testBed.univer.dispose();+ });++ it('opens the rule list without seeding a draft rule', async () => {+ const testBed = createPanelTestBed();++ const rule = await openFromMenu(testBed, CF_MENU_OPERATION.viewRule);++ expect(testBed.sidebarService.visible).toBe(true);+ expect(rule).toBeUndefined();testBed.univer.dispose();});it('clears range rules and worksheet rules through the real operator flow', async () => {- const testBed = createCfUiTestBed();- testBed.injector.add([ConditionalFormattingPanelController]);- testBed.injector.get(ConditionalFormattingPanelController);- testBed.commandService.registerCommand(OpenConditionalFormattingOperator);- testBed.setSelection(range);+ const testBed = createPanelTestBed();const addRule = async (cfId: string, ranges = [range]) => {const rule: IConditionFormattingRule = {diff --git a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsxnew file mode 100644index 0000000000..68a31d8859--- /dev/null+++ b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx@@ -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 type { IHighlightCell } from '@univerjs/sheets-conditional-formatting';+import type { Root } from 'react-dom/client';+import { BooleanNumber } from '@univerjs/core';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { ConditionalStyleEditor } from '../ConditionalStyleEditor';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++describe('ConditionalStyleEditor', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ root = undefined;+ container = undefined;+ });++ it('emits highlight style changes when a user toggles text emphasis controls', async () => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ let latestStyle: IHighlightCell['style'] | undefined;++ await act(async () => {+ root!.render(+ <ConditionalStyleEditor+ onChange={(style) => {+ latestStyle = style;+ }}+ />+ );+ await Promise.resolve();+ });++ const styleButtons = Array.from(container.firstElementChild!.children) as HTMLElement[];++ await act(async () => {+ styleButtons[0].dispatchEvent(new MouseEvent('click', { bubbles: true }));+ styleButtons[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(latestStyle).toMatchObject({+ bl: BooleanNumber.TRUE,+ it: BooleanNumber.TRUE,+ });+ });+});diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsxindex c6c1d9c808..e20e669cf0 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx@@ -16,13 +16,34 @@import type { IRange, Workbook } from '@univerjs/core';import type { IRemoveSheetMutationParams } from '@univerjs/sheets';-import type { IAddCfCommandParams, IConditionFormattingRule, ISetCfCommandParams } from '@univerjs/sheets-conditional-formatting';+import type {+ IAddCfCommandParams,+ IConditionFormattingRule,+ ISetCfCommandParams,+} from '@univerjs/sheets-conditional-formatting';import type { IStyleEditorProps } from './rule-edit/type';-import { ICommandService, InterceptorManager, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';+import {+ ICommandService,+ InterceptorManager,+ IUniverInstanceService,+ LocaleService,+ UniverInstanceType,+} from '@univerjs/core';import { Button, Select } from '@univerjs/design';import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';-import { RemoveSheetMutation, setEndForRange, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';-import { AddCfCommand, CFRuleType, CFSubRuleType, ConditionalFormattingRuleModel, SetCfCommand } from '@univerjs/sheets-conditional-formatting';+import {+ RemoveSheetMutation,+ setEndForRange,+ SetWorksheetActiveOperation,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import {+ AddCfCommand,+ CFRuleType,+ CFSubRuleType,+ ConditionalFormattingRuleModel,+ SetCfCommand,+} from '@univerjs/sheets-conditional-formatting';import { RangeSelector } from '@univerjs/sheets-formula-ui';import { useDependency } from '@univerjs/ui';import { useEffect, useMemo, useRef, useState } from 'react';@@ -53,6 +74,7 @@ export const RuleEdit = (props: IRuleEditProps) => {const [errorText, setErrorText] = useState<string | undefined>(undefined);const rangeResult = useRef<IRange[]>(props.rule?.ranges ?? []);+ const rangeSelectorTouched = useRef(false);const rangeString = useMemo(() => {let ranges = props.rule?.ranges;@@ -170,14 +192,16 @@ export const RuleEdit = (props: IRuleEditProps) => {};const onRangeSelectorChange = (rangeString: string) => {+ if (!rangeSelectorTouched.current && rangeString.length < 1 && rangeResult.current.length > 0) {+ return;+ }++ rangeSelectorTouched.current = true;const result = rangeString.split(',').filter((e) => !!e).map(deserializeRangeWithSheet).map((item) => item.range);rangeResult.current = result;};const handleSubmit = () => {- if (errorText) {- return;- }const getRanges = () => {const worksheet = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();if (!worksheet) {@@ -188,6 +212,10 @@ export const RuleEdit = (props: IRuleEditProps) => {return result;};const ranges = getRanges();+ if (ranges.length < 1) {+ setErrorText(localeService.t('sheets-conditional-formatting-ui.errorMessage.rangeError'));+ return;+ }const beforeSubmitResult = interceptorManager.fetchThroughInterceptors(interceptorManager.getInterceptPoints().beforeSubmit)(true, null);if (beforeSubmitResult) {const result = interceptorManager.fetchThroughInterceptors(interceptorManager.getInterceptPoints().submit)(null, null);@@ -218,6 +246,11 @@ export const RuleEdit = (props: IRuleEditProps) => {};const handleVerify = (v: boolean, rangeText: string) => {+ if (!rangeSelectorTouched.current && !v && rangeText.length < 1) {+ setErrorText(undefined);+ return;+ }+if (v) {if (rangeText.length < 1) {setErrorText(localeService.t('sheets-conditional-formatting-ui.errorMessage.rangeError'));diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsxnew file mode 100644index 0000000000..2d1cca3f40--- /dev/null+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx@@ -0,0 +1,267 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';+import type { Root } from 'react-dom/client';+import { BooleanNumber, LocaleService, LocaleType } from '@univerjs/core';+import { AddCfCommand, CFNumberOperator, CFRuleType, CFSubRuleType, DeleteCfCommand } from '@univerjs/sheets-conditional-formatting';+import { IMarkSelectionService } from '@univerjs/sheets-ui';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { createCfUiTestBed } from '../../../__tests__/create-cf-ui-test-bed';+import { ConditionalFormattingI18nController } from '../../../controllers/cf.i18n.controller';+import { RuleList } from '../RuleList';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const ACTIVE_RANGE: IRange = {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 0,+};++const FAR_RANGE: IRange = {+ startRow: 5,+ endRow: 5,+ startColumn: 5,+ endColumn: 5,+};++class TestMarkSelectionService {+ addShape() {+ return 'shape-id';+ }++ removeShape() {+ // no canvas layer is created for these view tests.+ }+}++function createNumberHighlightRule(cfId: string, range: IRange, value: number): IConditionFormattingRule {+ return {+ cfId,+ ranges: [range],+ stopIfTrue: false,+ rule: {+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.number,+ operator: CFNumberOperator.greaterThan,+ value,+ style: {+ bl: BooleanNumber.TRUE,+ },+ },+ };+}++async function createRuleListTestBed() {+ const testBed = createCfUiTestBed();++ testBed.injector.add([ConditionalFormattingI18nController]);+ testBed.injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService as never }]);+ testBed.commandService.registerCommand(AddCfCommand);+ testBed.commandService.registerCommand(DeleteCfCommand);+ testBed.get(LocaleService).load({+ [LocaleType.ZH_CN]: {+ sheets: {+ conditional: {+ formatting: {+ ui: {+ panel: {+ managerRuleSelect: 'Show {0}',+ workSheet: 'Worksheet',+ selectedRange: 'Selected range',+ createRule: 'Create rule',+ clear: 'Clear rules',+ },+ preview: {+ describe: {+ greaterThan: 'Greater than {0}',+ },+ },+ },+ },+ },+ },+ 'sheets-conditional-formatting-ui': {+ panel: {+ managerRuleSelect: 'Show {0}',+ workSheet: 'Worksheet',+ selectedRange: 'Selected range',+ createRule: 'Create rule',+ clear: 'Clear rules',+ },+ preview: {+ describe: {+ greaterThan: 'Greater than {0}',+ },+ },+ },+ },+ });++ testBed.setSelection(ACTIVE_RANGE);+ await testBed.commandService.executeCommand(AddCfCommand.id, {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ rule: createNumberHighlightRule('cf-active', ACTIVE_RANGE, 10),+ });+ await testBed.commandService.executeCommand(AddCfCommand.id, {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ rule: createNumberHighlightRule('cf-far', FAR_RANGE, 20),+ });++ return testBed;+}++describe('RuleList', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: Awaited<ReturnType<typeof createRuleListTestBed>> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('shows only conditional formatting rules intersecting the current sheet selection in selected-range mode', async () => {+ currentTestBed = await createRuleListTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <RuleList onClick={() => undefined} onCreate={() => undefined} />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(container.textContent).toContain('A1');+ expect(container.textContent).toContain('F6');++ await act(async () => {+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));+ await Promise.resolve();+ });++ const selectedRangeOption = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))+ .find((button) => button.textContent === 'Selected range');++ expect(selectedRangeOption).toBeDefined();++ await act(async () => {+ selectedRangeOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(container.textContent).toContain('A1');+ expect(container.textContent).not.toContain('F6');+ });++ it('clears only the conditional formatting rules visible in selected-range mode', async () => {+ currentTestBed = await createRuleListTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <RuleList onClick={() => undefined} onCreate={() => undefined} />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ await act(async () => {+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));+ await Promise.resolve();+ });++ const selectedRangeOption = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))+ .find((button) => button.textContent === 'Selected range');++ expect(selectedRangeOption).toBeDefined();++ await act(async () => {+ selectedRangeOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(container.textContent).toContain('A1');+ expect(container.textContent).not.toContain('F6');++ const clearRulesButton = container.querySelectorAll('a')[1];++ expect(clearRulesButton).toBeDefined();++ await act(async () => {+ clearRulesButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ const remainingRules = currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId);++ expect(remainingRules?.map((rule) => rule.cfId)).toEqual(['cf-far']);+ expect(container.textContent).not.toContain('A1');+ });++ it('clears all worksheet conditional formatting rules in worksheet mode', async () => {+ currentTestBed = await createRuleListTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <RuleList onClick={() => undefined} onCreate={() => undefined} />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(container.textContent).toContain('A1');+ expect(container.textContent).toContain('F6');++ const clearRulesButton = container.querySelectorAll('a')[1];++ expect(clearRulesButton).toBeDefined();++ await act(async () => {+ clearRulesButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([]);+ expect(container.textContent).not.toContain('A1');+ expect(container.textContent).not.toContain('F6');+ });+});diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsxindex df4e7630cf..31d6417e29 100644--- a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/IconSet.tsx@@ -21,7 +21,18 @@ import type { IStyleEditorProps } from './type';import { get, IUniverInstanceService, LocaleService, set, Tools, UniverInstanceType } from '@univerjs/core';import { borderClassName, Checkbox, clsx, Dropdown, InputNumber, Select } from '@univerjs/design';import { MoreDownIcon, SlashDoubleIcon } from '@univerjs/icons';-import { CFNumberOperator, CFRuleType, CFSubRuleType, CFValueType, compareWithNumber, createDefaultValue, getOppositeOperator, iconGroup, iconMap, IIconSetType } from '@univerjs/sheets-conditional-formatting';+import {+ CFNumberOperator,+ CFRuleType,+ CFSubRuleType,+ CFValueType,+ compareWithNumber,+ createDefaultValue,+ getOppositeOperator,+ iconGroup,+ iconMap,+ IIconSetType,+} from '@univerjs/sheets-conditional-formatting';import { FormulaEditor } from '@univerjs/sheets-formula-ui';import { ILayoutService, useDependency, useScrollYOverContainer, useSidebarClick } from '@univerjs/ui';import { forwardRef, useEffect, useMemo, useRef, useState } from 'react';@@ -517,8 +528,9 @@ export const IconSet = (props: IStyleEditorProps<unknown, IIconSet>) => {useEffect(() => {const dispose = interceptorManager.intercept(interceptorManager.getInterceptPoints().beforeSubmit, {handler() {- const keys = Object.keys(errorMap);- return keys.length === 0;+ const currentErrorMap = checkResult(configList);+ setErrorMap(currentErrorMap);+ return Object.keys(currentErrorMap).length === 0;},});return () => {diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsxnew file mode 100644index 0000000000..7ff6ef3130--- /dev/null+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/rule-edit/__tests__/RuleEditors.spec.tsx@@ -0,0 +1,468 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditional-formatting';+import type { Root } from 'react-dom/client';+import { InterceptorManager, LocaleService, LocaleType } from '@univerjs/core';+import {+ CFNumberOperator,+ CFRuleType,+ CFSubRuleType,+ CFTextOperator,+ CFValueType,+ IIconSetType,+} from '@univerjs/sheets-conditional-formatting';+import { ILayoutService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { createCfUiTestBed } from '../../../../__tests__/create-cf-ui-test-bed';+import { ColorScaleStyleEditor } from '../ColorScale';+import { DataBarStyleEditor } from '../DataBar';+import { HighlightCellStyleEditor } from '../HighlightCell';+import { IconSet } from '../IconSet';+import { RankStyleEditor } from '../Rank';+import { beforeSubmit, submit } from '../type';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class TestLayoutService {+ readonly rootContainerElement = document.body;+}++function createEditorTestBed() {+ const testBed = createCfUiTestBed();+ testBed.injector.add([ILayoutService, { useClass: TestLayoutService as never }]);+ testBed.get(LocaleService).load({ [LocaleType.ZH_CN]: {} });++ return testBed;+}++function createRuleInterceptorManager() {+ return new InterceptorManager({ beforeSubmit, submit });+}++function submitRule(interceptorManager: ReturnType<typeof createRuleInterceptorManager>) {+ return interceptorManager.fetchThroughInterceptors(submit)(null, null) as IConditionalFormattingRuleConfig | null;+}++function inputText(input: HTMLInputElement, value: string) {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++describe('conditional formatting rule editors', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createEditorTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('blocks submitting an empty text condition and submits the entered text condition rule', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();+ let lastRule: unknown;++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <HighlightCellStyleEditor+ interceptorManager={interceptorManager}+ onChange={(rule) => {+ lastRule = rule;+ }}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ let canSubmit: unknown;++ await act(async () => {+ canSubmit = interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null);+ await Promise.resolve();+ });++ expect(canSubmit).toBe(false);++ const textInput = container.querySelector('input[type="text"]') as HTMLInputElement;++ await act(async () => {+ inputText(textInput, 'overdue');+ await Promise.resolve();+ });++ await act(async () => {+ canSubmit = interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null);+ await Promise.resolve();+ });++ expect(canSubmit).toBe(true);+ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ value: 'overdue',+ });+ expect(lastRule).toMatchObject({+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ value: 'overdue',+ });+ });++ it('submits the configured rank rule instead of a generic highlight rule', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <RankStyleEditor+ interceptorManager={interceptorManager}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.rank,+ isBottom: false,+ isPercent: false,+ value: 10,+ });+ });++ it('submits data bar rule configuration with min/max value types and visibility', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <DataBarStyleEditor+ interceptorManager={interceptorManager}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.dataBar,+ isShowValue: true,+ config: {+ min: { type: CFValueType.min },+ max: { type: CFValueType.max },+ isGradient: false,+ },+ });+ });++ it('submits a two-point color scale when the median value type is disabled', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <ColorScaleStyleEditor+ interceptorManager={interceptorManager}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.colorScale,+ config: [+ { index: 0, value: { type: CFValueType.min } },+ { index: 1, value: { type: CFValueType.max } },+ ],+ });+ });++ it('submits a valid default icon set rule with visible cell values', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <IconSet+ interceptorManager={interceptorManager}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(true);+ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.iconSet,+ isShowValue: true,+ config: [+ {+ iconType: '3Arrows',+ iconId: '0',+ value: { type: CFValueType.num, value: 20 },+ },+ {+ iconType: '3Arrows',+ iconId: '1',+ value: { type: CFValueType.num, value: 10 },+ },+ {+ iconType: '3Arrows',+ iconId: '2',+ value: { type: CFValueType.num, value: Number.MAX_SAFE_INTEGER },+ },+ ],+ });+ });++ it('preserves an existing number highlight rule when reopening the editor', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <HighlightCellStyleEditor+ interceptorManager={interceptorManager}+ rule={{+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.number,+ operator: CFNumberOperator.between,+ value: [5, 12],+ style: {+ bg: {+ rgb: '#ffeecc',+ },+ },+ }}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.number,+ operator: CFNumberOperator.between,+ value: [5, 12],+ style: {+ bg: {+ rgb: '#ffeecc',+ },+ },+ });+ });++ it('preserves an existing text highlight rule and validates it through beforeSubmit', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <HighlightCellStyleEditor+ interceptorManager={interceptorManager}+ rule={{+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ operator: CFTextOperator.endsWith,+ value: '.com',+ style: {+ cl: {+ rgb: '#0070c0',+ },+ },+ }}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(true);+ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.highlightCell,+ subType: CFSubRuleType.text,+ operator: CFTextOperator.endsWith,+ value: '.com',+ style: {+ cl: {+ rgb: '#0070c0',+ },+ },+ });+ });++ it('preserves an existing icon set rule with hidden cell values', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <IconSet+ interceptorManager={interceptorManager}+ rule={{+ type: CFRuleType.iconSet,+ isShowValue: false,+ config: [+ {+ iconType: IIconSetType.threeTrafficLights1,+ iconId: '0',+ operator: CFNumberOperator.greaterThanOrEqual,+ value: { type: CFValueType.percent, value: 75 },+ },+ {+ iconType: IIconSetType.threeTrafficLights1,+ iconId: '1',+ operator: CFNumberOperator.greaterThan,+ value: { type: CFValueType.percent, value: 25 },+ },+ {+ iconType: IIconSetType.threeTrafficLights1,+ iconId: '2',+ operator: CFNumberOperator.lessThanOrEqual,+ value: { type: CFValueType.percent, value: Number.MAX_SAFE_INTEGER },+ },+ ],+ }}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(true);+ expect(submitRule(interceptorManager)).toMatchObject({+ type: CFRuleType.iconSet,+ isShowValue: false,+ config: [+ {+ iconType: IIconSetType.threeTrafficLights1,+ iconId: '0',+ value: { type: CFValueType.percent, value: 75 },+ },+ {+ iconType: IIconSetType.threeTrafficLights1,+ iconId: '1',+ value: { type: CFValueType.percent, value: 25 },+ },+ {+ iconType: IIconSetType.threeTrafficLights1,+ iconId: '2',+ value: { type: CFValueType.percent, value: Number.MAX_SAFE_INTEGER },+ },+ ],+ });+ });++ it('blocks submitting an icon set whose thresholds are not ordered by their operators', async () => {+ currentTestBed = createEditorTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const interceptorManager = createRuleInterceptorManager();++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <IconSet+ interceptorManager={interceptorManager}+ rule={{+ type: CFRuleType.iconSet,+ isShowValue: true,+ config: [+ {+ iconType: IIconSetType.threeArrows,+ iconId: '0',+ operator: CFNumberOperator.greaterThan,+ value: { type: CFValueType.num, value: 20 },+ },+ {+ iconType: IIconSetType.threeArrows,+ iconId: '1',+ operator: CFNumberOperator.greaterThan,+ value: { type: CFValueType.num, value: 30 },+ },+ {+ iconType: IIconSetType.threeArrows,+ iconId: '2',+ operator: CFNumberOperator.lessThanOrEqual,+ value: { type: CFValueType.num, value: Number.MAX_SAFE_INTEGER },+ },+ ],+ }}+ onChange={() => undefined}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(interceptorManager.fetchThroughInterceptors(beforeSubmit)(true, null)).toBe(false);+ });+});diff --git a/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts b/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.tsindex d88e09aeb0..6754894743 100644--- a/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts+++ b/packages/sheets-conditional-formatting/src/facade/__tests__/f-conditional-formatting.spec.ts@@ -17,15 +17,27 @@import type { Injector, Univer } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';import { ICommandService } from '@univerjs/core/services/command/command.service.js';-import { FormulaExecuteStageType, RemoveOtherFormulaMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';+import {+ FormulaExecuteStageType,+ RemoveOtherFormulaMutation,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+} from '@univerjs/engine-formula';import { SetSelectionsOperation } from '@univerjs/sheets';import {AddCfCommand,AddConditionalRuleMutation,+ CFNumberOperator,+ CFTimePeriodOperator,+ CFValueType,+ ClearRangeCfCommand,+ ClearWorksheetCfCommand,ConditionalFormattingFormulaService,ConditionalFormattingViewModel,DeleteCfCommand,DeleteConditionalRuleMutation,+ IIconSetType,MoveCfCommand,MoveConditionalRuleMutation,SetCfCommand,@@ -55,6 +67,8 @@ describe('Test conditional formatting facade', () => {[AddCfCommand,AddConditionalRuleMutation,+ ClearRangeCfCommand,+ ClearWorksheetCfCommand,DeleteCfCommand,DeleteConditionalRuleMutation,MoveCfCommand,@@ -91,13 +105,18 @@ describe('Test conditional formatting facade', () => {it('Creates a constructor for conditional formatting', () => {const workbook = univerAPI.getActiveWorkbook();const worksheet = workbook?.getActiveSheet();+ const range = worksheet?.getRange(0, 0, 2, 2);const rule = worksheet?.createConditionalFormattingRule().whenCellNotEmpty()- .setRanges([{ startRow: 0, endRow: 100, startColumn: 0, endColumn: 100 }])- .setItalic(true)- .setItalic(true)+ .setRanges([range!.getRange()])+ .setBold(true)+ .setItalic(false)+ .setStrikethrough(true)+ .setUnderline(true).setBackground('red').setFontColor('green')+ .setBackground()+ .setFontColor().build();expect({ ...rule, cfId: 123 }).toEqual({rule: {@@ -106,21 +125,24 @@ describe('Test conditional formatting facade', () => {operator: 'notEqual',value: '',style: {- it: 1,- bg: {- rgb: 'rgb(255,0,0)',+ bl: 1,+ it: 0,+ st: {+ s: 1,},- cl: {- rgb: 'rgb(0,128,0)',+ ul: {+ s: 1,},},},ranges: [{startRow: 0,- endRow: 100,+ endRow: 1,startColumn: 0,- endColumn: 100,+ endColumn: 1,+ unitId: 'test',+ sheetId: 'sheet1',},],cfId: 123,@@ -128,6 +150,120 @@ describe('Test conditional formatting facade', () => {});});+ it('Builds conditional formatting rules for text, numbers, dates, rank, duplicate values, data bars, color scales, and icon sets', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ const range = worksheet.getRange('A1:B2').getRange();+ const builder = worksheet.newConditionalFormattingRule();++ expect(univerAPI.Enum.ConditionFormatNumberOperatorEnum.greaterThan).toBe(CFNumberOperator.greaterThan);+ expect(univerAPI.Enum.ConditionFormatTimePeriodOperatorEnum.last7Days).toBe(CFTimePeriodOperator.last7Days);+ expect(univerAPI.Enum.ConditionFormatValueTypeEnum.num).toBe(CFValueType.num);+ expect(univerAPI.Enum.ConditionFormatIconSetTypeEnum.threeArrows).toBe(IIconSetType.threeArrows);++ const rules = [+ builder.whenCellEmpty().setRanges([range]).build(),+ builder.whenDate(CFTimePeriodOperator.last7Days).setRanges([range]).build(),+ builder.whenFormulaSatisfied('=$A1>10').setRanges([range]).build(),+ builder.whenNumberBetween(20, 10).setRanges([range]).build(),+ builder.whenNumberEqualTo(10).setRanges([range]).build(),+ builder.whenNumberGreaterThan(10).setRanges([range]).build(),+ builder.whenNumberGreaterThanOrEqualTo(10).setRanges([range]).build(),+ builder.whenNumberLessThan(10).setRanges([range]).build(),+ builder.whenNumberLessThanOrEqualTo(10).setRanges([range]).build(),+ builder.whenNumberNotBetween(20, 10).setRanges([range]).build(),+ builder.whenNumberNotEqualTo(10).setRanges([range]).build(),+ builder.whenTextContains('apple').setRanges([range]).build(),+ builder.whenTextDoesNotContain('apple').setRanges([range]).build(),+ builder.whenTextEndsWith('.ai').setRanges([range]).build(),+ builder.whenTextEqualTo('done').setRanges([range]).build(),+ builder.whenTextStartsWith('https://').setRanges([range]).build(),+ builder.setAverage(CFNumberOperator.greaterThan).setRanges([range]).build(),+ builder.setUniqueValues().setRanges([range]).build(),+ builder.setDuplicateValues().setRanges([range]).build(),+ builder.setRank({ isBottom: true, isPercent: true, value: 10 }).setRanges([range]).build(),+ builder.setDataBar({+ min: { type: CFValueType.num, value: -100 },+ max: { type: CFValueType.num, value: 100 },+ positiveColor: '#00ff00',+ nativeColor: '#ff0000',+ isGradient: true,+ isShowValue: true,+ }).setRanges([range]).build(),+ builder.setColorScale([+ { index: 0, color: '#00ff00', value: { type: CFValueType.min } },+ { index: 1, color: '#ffff00', value: { type: CFValueType.percent, value: 50 } },+ { index: 2, color: '#ff0000', value: { type: CFValueType.max } },+ ]).setRanges([range]).build(),+ builder.setIconSet({+ isShowValue: true,+ iconConfigs: [+ {+ iconType: IIconSetType.threeArrows,+ iconId: '0',+ operator: CFNumberOperator.greaterThan,+ value: { type: CFValueType.num, value: 20 },+ },+ {+ iconType: IIconSetType.threeArrows,+ iconId: '1',+ operator: CFNumberOperator.greaterThan,+ value: { type: CFValueType.num, value: 10 },+ },+ {+ iconType: IIconSetType.threeArrows,+ iconId: '2',+ operator: CFNumberOperator.lessThanOrEqual,+ value: { type: CFValueType.num, value: 10 },+ },+ ],+ }).setRanges([range]).build(),+ ];++ expect(rules.map((rule) => rule.rule.type)).toEqual([+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'highlightCell',+ 'dataBar',+ 'colorScale',+ 'iconSet',+ ]);+ expect(rules.map((rule) => ('operator' in rule.rule ? rule.rule.operator : undefined))).toContain(CFNumberOperator.between);+ expect(rules.map((rule) => ('operator' in rule.rule ? rule.rule.operator : undefined))).toContain(CFNumberOperator.notBetween);+ expect(rules[3].rule).toMatchObject({ value: [10, 20] });+ expect(rules[20].rule).toMatchObject({+ type: 'dataBar',+ isShowValue: true,+ config: {+ min: { type: 'num', value: -100 },+ max: { type: 'num', value: 100 },+ positiveColor: '#00ff00',+ nativeColor: '#ff0000',+ isGradient: true,+ },+ });+ expect(rules[21].rule).toMatchObject({ type: 'colorScale', config: [{ index: 0 }, { index: 1 }, { index: 2 }] });+ expect(rules[22].rule).toMatchObject({ type: 'iconSet', isShowValue: true, config: [{ iconId: '0' }, { iconId: '1' }, { iconId: '2' }] });+ expect(builder.getIconMap()[IIconSetType.threeArrows].length).toBeGreaterThan(0);+ });+it('Creates rule and add', () => {const workbook = univerAPI.getActiveWorkbook();const worksheet = workbook?.getActiveSheet();@@ -264,4 +400,59 @@ describe('Test conditional formatting facade', () => {expect(afterEditRule?.cfId).toEqual(rule.cfId);expect(afterEditRule?.ranges).toEqual([]);});++ it('Uses range facade APIs to add, update, reprioritize, and delete rules on the active selection', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ const range = worksheet.getRange('A1:B2');+ const rule = range.createConditionalFormattingRule()+ .whenTextContains('paid')+ .setBackground('#00ff00')+ .build();++ range.addConditionalFormattingRule(rule);+ expect(range.getConditionalFormattingRules().some((item) => item.cfId === rule.cfId)).toBe(true);++ const updatedRule = range.createConditionalFormattingRule()+ .whenTextContains('overdue')+ .setBackground('#ff0000')+ .build();+ range.setConditionalFormattingRule(rule.cfId, { ...updatedRule, cfId: rule.cfId });+ expect(worksheet.getConditionalFormattingRules().find((item) => item.cfId === rule.cfId)?.rule).toMatchObject({ value: 'overdue' });++ const firstRule = worksheet.getConditionalFormattingRules()[0];+ range.moveConditionalFormattingRule(rule.cfId, firstRule.cfId, 'before');+ expect(worksheet.getConditionalFormattingRules()[0].cfId).toBe(rule.cfId);++ range.deleteConditionalFormattingRule(rule.cfId);+ expect(worksheet.getConditionalFormattingRules().some((item) => item.cfId === rule.cfId)).toBe(false);+ });++ it('Clears conditional formatting from a range without removing unrelated sheet rules', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ const range = worksheet.getRange('A1:B2');+ const rule = range.createConditionalFormattingRule()+ .whenNumberGreaterThan(100)+ .setBackground('#ff0000')+ .build();++ range.addConditionalFormattingRule(rule);+ expect(range.getConditionalFormattingRules().map((item) => item.cfId)).toContain(rule.cfId);++ range.clearConditionalFormatRules();++ expect(range.getConditionalFormattingRules().map((item) => item.cfId)).not.toContain(rule.cfId);+ expect(worksheet.getConditionalFormattingRules().length).toBe(3);+ });++ it('Clears all conditional formatting rules from a worksheet', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();++ expect(worksheet.getConditionalFormattingRules().length).toBeGreaterThan(0);+ worksheet.clearConditionalFormatRules();++ expect(worksheet.getConditionalFormattingRules()).toEqual([]);+ });});diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.tsindex 00cbb9fe87..4b8fac80e0 100644--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { ConditionalFormattingRangeTransformService } from '../conditional-formatting-range-transform.service';@@ -26,9 +27,15 @@ const sortRanges = <T extends { startRow: number; startColumn: number; endRow: n);};+function createService(): ConditionalFormattingRangeTransformService {+ const injector = new Injector();+ injector.add([ConditionalFormattingRangeTransformService]);+ return injector.get(ConditionalFormattingRangeTransformService);+}+describe('ConditionalFormattingRangeTransformService', () => {it('subtracts ranges without expanding to a cell matrix', () => {- const service = new ConditionalFormattingRangeTransformService();+ const service = createService();const ranges = service.subtractRanges([{ startRow: 0, endRow: 4, startColumn: 0, endColumn: 4 }],@@ -44,7 +51,7 @@ describe('ConditionalFormattingRangeTransformService', () => {});it('intersects source ranges and translates them to a target anchor', () => {- const service = new ConditionalFormattingRangeTransformService();+ const service = createService();const ranges = service.copyIntersectingRanges([{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }],@@ -58,7 +65,7 @@ describe('ConditionalFormattingRangeTransformService', () => {});it('adds and merges translated ranges', () => {- const service = new ConditionalFormattingRangeTransformService();+ const service = createService();const ranges = service.addRanges([{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],@@ -69,7 +76,7 @@ describe('ConditionalFormattingRangeTransformService', () => {});it('applies batched subtract and add operations once per rule', () => {- const service = new ConditionalFormattingRangeTransformService();+ const service = createService();const ranges = service.applyRangeDelta([{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }],diff --git a/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.ts b/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.tsindex 4f397ff878..48af482260 100644--- a/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.ts+++ b/packages/sheets-crosshair-highlight/src/commands/operations/operation.spec.ts@@ -14,14 +14,21 @@* limitations under the License.*/-import { MenuItemType } from '@univerjs/ui';-import { of } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';-import { CrosshairHighlightMenuItemFactory } from '../../menu/crosshair.menu';-import { menuSchema } from '../../menu/schema';import {- SheetsCrosshairHighlightService,-} from '../../services/crosshair.service';+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ ThemeService,+} from '@univerjs/core';+import { firstValueFrom } from 'rxjs';+import { beforeEach, describe, expect, it } from 'vitest';+import { CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS, SheetsCrosshairHighlightService } from '../../services/crosshair.service';import {DisableCrosshairHighlightOperation,EnableCrosshairHighlightOperation,@@ -29,73 +36,80 @@ import {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)),- };-});+function createOperationTestBed() {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ThemeService]);+ injector.add([SheetsCrosshairHighlightService]);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(ToggleCrosshairHighlightOperation);+ commandService.registerCommand(EnableCrosshairHighlightOperation);+ commandService.registerCommand(DisableCrosshairHighlightOperation);+ commandService.registerCommand(SetCrosshairHighlightColorOperation);++ const themeService = injector.get(ThemeService);+ const highlightBackground: Array<{ color: string; alpha: number }> = [];+ for (let index = 0; index < CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS.length; index++) {+ highlightBackground.push({+ color: index === 2 ? '#00ff00' : '#ff0000',+ alpha: index === 2 ? 0.5 : 1,+ });+ }++ themeService.setTheme({+ ...themeService.getCurrentTheme(),+ highlight: {+ background: highlightBackground,+ },+ } as never);-function createThemeService() {return {- currentTheme$: of({}),- getColorFromTheme: vi.fn((path: string) => ({- 'highlight.background.1': { color: 'purple.500', alpha: 0.3 },- 'highlight.background.2': { color: 'red.500', alpha: 0.15 },- 'purple.500': '#010203',- 'red.500': '#040506',- })[path]),+ commandService,+ service: injector.get(SheetsCrosshairHighlightService),};}-describe('crosshair operations/menu/service', () => {- it('should handle service state changes and dispose', () => {- const service = new SheetsCrosshairHighlightService(createThemeService() as never);- expect(service.enabled).toBe(false);-- service.setEnabled(true);- expect(service.enabled).toBe(true);+describe('crosshair highlight operations', () => {+ let commandService: ICommandService;+ let service: SheetsCrosshairHighlightService;- service.dispose();+ beforeEach(() => {+ const testBed = createOperationTestBed();+ commandService = testBed.commandService;+ service = testBed.service;});- it('should execute operation handlers with branch coverage', () => {- const service = new SheetsCrosshairHighlightService(createThemeService() as never);- const accessor = { get: vi.fn(() => service) };+ it('toggles crosshair highlighting for the current sheet view', async () => {+ expect(service.enabled).toBe(false);- expect(ToggleCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(true);+ await commandService.executeCommand(ToggleCrosshairHighlightOperation.id);expect(service.enabled).toBe(true);- service.setEnabled(false);- expect(EnableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(true);- expect(EnableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(false);-- expect(DisableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(true);- expect(DisableCrosshairHighlightOperation.handler(accessor as never, undefined as never)).toBe(false);-- expect(SetCrosshairHighlightColorOperation.handler(accessor as never, { value: 'highlight.background.2' })).toBe(true);- expect(service.enabled).toBe(true);+ await commandService.executeCommand(ToggleCrosshairHighlightOperation.id);+ expect(service.enabled).toBe(false);});- it('should create menu item schema and factory output', () => {- const service = new SheetsCrosshairHighlightService(createThemeService() as never);- service.setEnabled(true);- const accessor = { get: vi.fn(() => service) };+ it('reports whether explicit enable and disable commands actually changed the state', async () => {+ await expect(commandService.executeCommand(EnableCrosshairHighlightOperation.id)).resolves.toBe(true);+ await expect(commandService.executeCommand(EnableCrosshairHighlightOperation.id)).resolves.toBe(false);+ expect(service.enabled).toBe(true);- const item = CrosshairHighlightMenuItemFactory(accessor as never);- expect(item.id).toBe(ToggleCrosshairHighlightOperation.id);- expect(item.type).toBe(MenuItemType.BUTTON_SELECTOR);- expect(item.selectionsCommandId).toBe(SetCrosshairHighlightColorOperation.id);- expect(item.selections).toHaveLength(1);- expect(item.activated$).toBe(service.enabled$);- expect(item.hidden$).toBeDefined();+ await expect(commandService.executeCommand(DisableCrosshairHighlightOperation.id)).resolves.toBe(true);+ await expect(commandService.executeCommand(DisableCrosshairHighlightOperation.id)).resolves.toBe(false);+ expect(service.enabled).toBe(false);+ });- 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);+ it('enables crosshair highlighting when the user chooses a highlight color', async () => {+ const result = await commandService.executeCommand(SetCrosshairHighlightColorOperation.id, {+ value: CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS[1],+ });- expect(accessor.get).toHaveBeenCalledWith(service.constructor);+ expect(result).toBe(true);+ expect(service.enabled).toBe(true);+ await expect(firstValueFrom(service.color$)).resolves.toBe('rgba(0,255,0,0.5)');});});diff --git a/packages/sheets-crosshair-highlight/src/services/crosshair.service.spec.ts b/packages/sheets-crosshair-highlight/src/services/crosshair.service.spec.tsnew file mode 100644index 0000000000..575fcd6e78--- /dev/null+++ b/packages/sheets-crosshair-highlight/src/services/crosshair.service.spec.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector, ThemeService } from '@univerjs/core';+import { firstValueFrom, skip, take } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS, SheetsCrosshairHighlightService } from './crosshair.service';++function createService(): { service: SheetsCrosshairHighlightService; themeService: ThemeService } {+ const injector = new Injector();+ injector.add([ThemeService]);+ injector.add([SheetsCrosshairHighlightService]);+ return {+ service: injector.get(SheetsCrosshairHighlightService),+ themeService: injector.get(ThemeService),+ };+}++describe('SheetsCrosshairHighlightService', () => {+ it('tracks enabled state and resolves selected highlight colors from theme tokens', async () => {+ const { service, themeService } = createService();+ themeService.setTheme({+ ...themeService.getCurrentTheme(),+ highlight: {+ background: CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS.map((_path, index) => ({+ color: index === 2 ? '#00ff00' : '#ff0000',+ alpha: index === 2 ? 0.5 : 1,+ })),+ },+ } as never);++ const enabled = firstValueFrom(service.enabled$.pipe(skip(1), take(1)));+ service.setEnabled(true);++ expect(service.enabled).toBe(true);+ await expect(enabled).resolves.toBe(true);++ service.setColor(CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS[1]);+ await expect(firstValueFrom(service.color$)).resolves.toBe('rgba(0,255,0,0.5)');+ });+});diff --git a/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx b/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsxindex 2838151184..0d800fca3f 100644--- a/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx+++ b/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx@@ -14,74 +14,127 @@* limitations under the License.*/-import { of } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';-import { CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS } from '../../services/crosshair.service';+import type { IDisposable } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import { Injector, ThemeService, toDisposable } from '@univerjs/core';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS,+ SheetsCrosshairHighlightService,+} from '../../services/crosshair.service';import { CrosshairOverlay } from './CrosshairHighlight';-const mocked = vi.hoisted(() => ({- useDependency: vi.fn(),- useObservable: vi.fn(),-}));+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-vi.mock('@univerjs/ui', async () => {- const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');- return {- ...actual,- useDependency: mocked.useDependency,- useObservable: mocked.useObservable,- };-});+class TestState {+ static pickedTokens: string[] = [];-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(' '),- };-});+ static reset(): void {+ this.pickedTokens = [];+ }+}++function createOverlayTestBed() {+ const injector = new Injector();+ injector.add([ThemeService]);+ injector.add([SheetsCrosshairHighlightService]);++ const themeService = injector.get(ThemeService);+ const highlightBackground = Object.fromEntries(CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS.map((path, index) => [+ path.replace('highlight.background.', ''),+ {+ color: index === 1 ? '#040506' : '#010203',+ alpha: index === 1 ? 0.15 : 0.3,+ },+ ]));++ themeService.setTheme({+ ...themeService.getCurrentTheme(),+ highlight: {+ background: highlightBackground,+ },+ } as never);-vi.mock('react', async () => {- const actual = await vi.importActual<typeof import('react')>('react');return {- ...actual,- useCallback: <T extends (...args: never[]) => unknown>(fn: T) => fn,+ injector,+ service: injector.get(SheetsCrosshairHighlightService),};-});+}++function renderOverlay(injector: Injector) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <CrosshairOverlay onChange={(token) => TestState.pickedTokens.push(token)} />+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function getColorCells(container: HTMLElement): HTMLElement[] {+ return Array.from(container.querySelectorAll<HTMLElement>('div[style*="background-color"]'));+}++function hasClassToken(element: HTMLElement, token: string): boolean {+ return element.className.split(/\s+/).includes(token);+}++function teardown(root?: Root, container?: HTMLElement): IDisposable {+ return toDisposable(() => {+ if (root) {+ act(() => root.unmount());+ }+ container?.remove();+ });+}describe('CrosshairOverlay', () => {- it('should render theme color cells and trigger onChange with token path', () => {- const themeService = {- currentTheme$: of({}),- getColorFromTheme: vi.fn((path: string) => ({- 'highlight.background.1': { color: 'purple.500', alpha: 0.3 },- 'highlight.background.2': { color: 'red.500', alpha: 0.15 },- 'purple.500': '#010203',- 'red.500': '#040506',- })[path] ?? { color: 'purple.500', alpha: 0.3 }),- };-- mocked.useDependency- .mockReturnValueOnce({ color$: of('rgba(1,2,3,0.3)') })- .mockReturnValueOnce(themeService);- mocked.useObservable.mockReturnValueOnce('rgba(1,2,3,0.3)').mockReturnValueOnce({});- 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_COLOR_THEME_PATHS.length);- expect(children[0].props.style.backgroundColor).toBe('rgba(1,2,3,0.3)');- expect(children[1].props.style.backgroundColor).toBe('rgba(4,5,6,0.15)');-- children[1].props.onClick();- expect(onChange).toHaveBeenCalledWith('highlight.background.2');+ let disposable: IDisposable | undefined;++ beforeEach(() => {+ TestState.reset();+ });++ afterEach(() => {+ disposable?.dispose();+ disposable = undefined;+ });++ it('offers theme-backed highlight colors and reports the picked token', () => {+ const testBed = createOverlayTestBed();+ const rendered = renderOverlay(testBed.injector);+ disposable = teardown(rendered.root, rendered.container);++ const cells = getColorCells(rendered.container);+ expect(cells).toHaveLength(CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS.length);+ expect(cells[0].style.backgroundColor).toBe('rgba(1, 2, 3, 0.3)');+ expect(cells[1].style.backgroundColor).toBe('rgba(4, 5, 6, 0.15)');++ act(() => {+ cells[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(TestState.pickedTokens).toEqual([CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS[1]]);+ });++ it('marks the service-selected color as the active swatch', () => {+ const testBed = createOverlayTestBed();+ testBed.service.setColor(CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS[1]);++ const rendered = renderOverlay(testBed.injector);+ disposable = teardown(rendered.root, rendered.container);++ const cells = getColorCells(rendered.container);+ expect(hasClassToken(cells[1], 'univer-ring-primary-600')).toBe(true);+ expect(hasClassToken(cells[0], 'univer-ring-primary-600')).toBe(false);});});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.tsindex 5f3406c722..bc5bf2a52a 100644--- 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.ts@@ -14,22 +14,37 @@* limitations under the License.*/-import { Rect } from '@univerjs/engine-render';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } 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);+class TestCanvasContext {+ fillStyle = '';+ readonly rects: Array<{ left: number; top: number; width: number; height: number }> = [];+ fillCount = 0;++ save(): void {}++ restore(): void {}++ beginPath(): void {}++ closePath(): void {}++ rect(left: number, top: number, width: number, height: number): void {+ this.rects.push({ left, top, width, height });+ }++ fill(): void {+ this.fillCount += 1;+ }+}++function drawShape(shape: SheetCrossHairHighlightShape, context: TestCanvasContext): void {+ (shape as unknown as { _draw: (ctx: TestCanvasContext) => void })._draw(context);+}+describe('SheetCrossHairHighlightShape', () => {+ it('draws the highlight rectangle with its configured rgba fill', () => {const shape = new SheetCrossHairHighlightShape('shape-1', {color: { r: 1, g: 2, b: 3, a: 0.4 },width: 20,@@ -39,24 +54,27 @@ describe('SheetCrossHairHighlightShape', () => {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)',- })- );+ const context = new TestCanvasContext();++ drawShape(shape, context);++ expect(context.rects).toEqual([{ left: 0, top: 0, width: 30, height: 15 }]);+ expect(context.fillStyle).toBe('rgba(1, 2, 3, 0.4)');+ expect(context.fillCount).toBe(1);+ });++ it('uses the default half opacity when the color has no alpha channel', () => {+ const shape = new SheetCrossHairHighlightShape('shape-default-alpha');+ shape.setShapeProps({+ color: { r: 7, g: 8, b: 9 },+ width: 1,+ height: 1,+ });+ const context = new TestCanvasContext();++ drawShape(shape, context);++ expect(context.fillStyle).toBe('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.tsindex fc721a2f3d..5deb48717a 100644--- 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.ts@@ -14,178 +14,222 @@* limitations under the License.*/-import { RANGE_TYPE } from '@univerjs/core';+import type { IRange } from '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';import { BehaviorSubject, Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';+import { SheetCrossHairHighlightShape } from './crosshair-highlight-shape';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 },+class TestSheet {+ getRowCount(): number {+ return 20;+ }++ getColumnCount(): number {+ return 10;+ }+}++class TestWorkbook {+ readonly activeSheet$ = new BehaviorSubject(0);+ readonly sheet = new TestSheet();++ getActiveSheet(): TestSheet {+ return this.sheet;+ }+}++class TestScene {+ readonly objects: SheetCrossHairHighlightShape[] = [];+ readonly dirtyRequests: boolean[] = [];++ addObject(object: SheetCrossHairHighlightShape): void {+ this.objects.push(object);+ }++ makeDirty(value: boolean): void {+ this.dirtyRequests.push(value);+ }+}++class TestSkeleton {+ getCellWithCoordByIndex(row: number, column: number) {+ return {+ startX: column * 100,+ startY: row * 20,+ endX: column * 100 + 100,+ endY: row * 20 + 20,};+ }+}++class TestSkeletonManagerService {+ readonly skeleton = new TestSkeleton();+ readonly currentSkeleton$ = new BehaviorSubject(this.skeleton);++ getCurrentSkeleton(): TestSkeleton {+ return this.skeleton;+ }+}++class TestSelectionsService {+ readonly selectionMoveStart$ = new Subject<ISelectionWithStyle[]>();+ readonly selectionMoving$ = new Subject<ISelectionWithStyle[]>();+ readonly selectionMoveEnd$ = new Subject<ISelectionWithStyle[]>();+ readonly selectionSet$ = new Subject<ISelectionWithStyle[]>();+ private _selections: ISelectionWithStyle[] = [];++ setSelections(selections: ISelectionWithStyle[]): void {+ this._selections = selections;+ this.selectionSet$.next(selections);+ }++ getCurrentSelections(): ISelectionWithStyle[] {+ return this._selections;+ }+}++class TestCrosshairHighlightService {+ readonly enabled$ = new BehaviorSubject(false);+ readonly highlightColor$ = new BehaviorSubject('rgba(10,20,30,0.6)');+}++class TestContextService {+ readonly refSelectionEnabled$ = new BehaviorSubject(false);++ subscribeContextValue$() {+ return this.refSelectionEnabled$.asObservable();+ }+}++function createSelection(range: IRange): ISelectionWithStyle {+ return { range } as ISelectionWithStyle;+}++function getShapeRects(scene: TestScene) {+ return scene.objects.map((shape) => ({+ left: shape.left,+ top: shape.top,+ width: shape.width,+ height: shape.height,+ }));+}++function getRenderedShapeCount(controller: SheetCrosshairHighlightRenderController): number {+ return (controller as unknown as { _shapes: SheetCrossHairHighlightShape[] })._shapes.length;+}- const refSelectionEnabled$ = new BehaviorSubject(false);- const enabled$ = new BehaviorSubject(false);- const highlightColor$ = 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>();+describe('SheetCrosshairHighlightRenderController', () => {+ it('renders crosshair rectangles from the active normal selection and clears them when disabled', async () => {+ const workbook = new TestWorkbook();+ const scene = new TestScene();+ const skeletonManagerService = new TestSkeletonManagerService();+ const selectionsService = new TestSelectionsService();+ const refSelectionsService = new TestSelectionsService();+ const crosshairHighlightService = new TestCrosshairHighlightService();+ const contextService = new TestContextService();+ selectionsService.setSelections([+ createSelection({+ startRow: 1,+ endRow: 1,+ startColumn: 1,+ endColumn: 1,+ }),+ ]);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$,- highlightColor$,- } as never,- {- subscribeContextValue$: vi.fn(() => refSelectionEnabled$.asObservable()),- } as never,- {- selectionMoveStart$: refSelectionMoveStart$,- selectionMoving$: refSelectionMoving$,- selectionMoveEnd$: refSelectionMoveEnd$,- getCurrentSelections: vi.fn(() => [refSelection]),- } as never+ skeletonManagerService as never,+ selectionsService as never,+ crosshairHighlightService as never,+ contextService as never,+ refSelectionsService as never);- const addSelectionSpy = vi.spyOn(controller, 'addSelection');- const clearSpy = vi.spyOn(controller as never, '_clear');+ crosshairHighlightService.enabled$.next(true);- enabled$.next(true);- activeSheet$.next(1);- expect(addSelectionSpy).toHaveBeenCalled();- expect(scene.addObject).toHaveBeenCalled();- expect(scene.makeDirty).toHaveBeenCalledWith(true);+ expect(getRenderedShapeCount(controller)).toBe(4);+ expect(scene.objects.every((object) => object instanceof SheetCrossHairHighlightShape)).toBe(true);+ expect(getShapeRects(scene)).toEqual([+ { left: 0, top: 20, width: 100, height: 20 },+ { left: 200, top: 20, width: 900, height: 20 },+ { left: 100, top: 0, width: 100, height: 20 },+ { left: 100, top: 40, width: 100, height: 380 },+ ]);+ expect(scene.dirtyRequests).toEqual([true]);- refSelectionEnabled$.next(true);- activeSheet$.next(2);- expect(addSelectionSpy).toHaveBeenCalledWith(refSelection.range, expect.anything());+ crosshairHighlightService.enabled$.next(false);- enabled$.next(false);- activeSheet$.next(3);- expect(clearSpy).toHaveBeenCalled();+ expect(getRenderedShapeCount(controller)).toBe(0);- controller.addSelection(- {- rangeType: RANGE_TYPE.COLUMN,- startRow: 0,- endRow: 1,- startColumn: 0,- endColumn: 0,- } as never,- workbook.getActiveSheet() as never- );+ await controller.dispose();+ });- controller.addSelection(- {+ it('switches to reference selections and ignores full-row or full-column selections', async () => {+ const workbook = new TestWorkbook();+ const scene = new TestScene();+ const skeletonManagerService = new TestSkeletonManagerService();+ const selectionsService = new TestSelectionsService();+ const refSelectionsService = new TestSelectionsService();+ const crosshairHighlightService = new TestCrosshairHighlightService();+ const contextService = new TestContextService();++ selectionsService.setSelections([+ createSelection({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);+ }),+ ]);+ refSelectionsService.setSelections([+ createSelection({+ startRow: 0,+ endRow: 19,+ startColumn: 3,+ endColumn: 3,+ }),+ createSelection({+ startRow: 3,+ endRow: 3,+ startColumn: 4,+ endColumn: 4,+ }),+ ]);- controller.addSelection(+ const controller = new SheetCrosshairHighlightRenderController({- startRow: 0,- endRow: 0,- startColumn: 0,- endColumn: 0,+ unit: workbook,+ scene,} as never,- workbook.getActiveSheet() as never+ skeletonManagerService as never,+ selectionsService as never,+ crosshairHighlightService as never,+ contextService as never,+ refSelectionsService 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);+ crosshairHighlightService.enabled$.next(true);+ expect(getShapeRects(scene).slice(-4)).toEqual([+ { left: 0, top: 40, width: 200, height: 20 },+ { left: 300, top: 40, width: 800, height: 20 },+ { left: 200, top: 0, width: 100, height: 40 },+ { left: 200, top: 60, width: 100, height: 360 },+ ]);++ contextService.refSelectionEnabled$.next(true);++ expect(getShapeRects(scene).slice(-4)).toEqual([+ { left: 0, top: 60, width: 400, height: 20 },+ { left: 500, top: 60, width: 600, height: 20 },+ { left: 400, top: 0, width: 100, height: 60 },+ { left: 400, top: 80, width: 100, height: 340 },+ ]);+ expect(getRenderedShapeCount(controller)).toBe(4);await controller.dispose();});diff --git a/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts b/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.tsindex 2a90524b09..57eba43ed1 100644--- a/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts+++ b/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts@@ -14,251 +14,427 @@* limitations under the License.*/-import type { ISelectionWithStyle, SheetsSelectionsService } from '@univerjs/sheets';-import type { SheetDataValidationModel } from '@univerjs/sheets-data-validation';-import type { IDropdownParam, IEditorBridgeService } from '@univerjs/sheets-ui';-import { DataValidationRenderMode } from '@univerjs/core';-import { DataValidatorDropdownType } from '@univerjs/data-validation';-import { SetRangeValuesCommand } from '@univerjs/sheets';-import { SetCellEditVisibleOperation } from '@univerjs/sheets-ui';+import type { Dependency, ICommand, ICommandInfo, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import type { IDropdownParam } from '@univerjs/sheets-ui';+import {+ awaitTime,+ CommandType,+ DataValidationErrorStyle,+ DataValidationRenderMode,+ dateKit,+ ICommandService,+ Inject,+ Injector,+ LocaleType,+ Plugin,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DataValidatorDropdownType, DataValidatorRegistryService } from '@univerjs/data-validation';+import { serializeListOptions, SetRangeValuesCommand, SheetsSelectionsService } from '@univerjs/sheets';+import { SheetDataValidationModel } from '@univerjs/sheets-data-validation';+import {+ IEditorBridgeService as IEditorBridgeServiceIdentifier,+ ISheetCellDropdownManagerService,+ SetCellEditVisibleOperation,+} from '@univerjs/sheets-ui';import { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';import { OpenValidationPanelOperation } from '../../commands/operations/data-validation.operation';-import { SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY } from '../../config/config';import { DataValidationDropdownManagerService } from '../dropdown-manager.service';+interface IRule {+ uid: string;+ type: string;+ formula1?: string;+ renderMode?: DataValidationRenderMode;+ errorStyle?: DataValidationErrorStyle;+ bizInfo?: Record<string, unknown>;+}++interface IValidator {+ dropdownType?: DataValidatorDropdownType;+ getListWithColor?: (rule: IRule, unitId: string, subUnitId: string) => Array<{ label: string; color?: string }>;+ validator?: (context: unknown, rule: IRule) => boolean | Promise<boolean>;+ getRuleFinalError?: (rule: IRule, location: unknown) => string;+}++class TestDataValidatorRegistryService {+ validator: IValidator | undefined;++ getValidatorItem(): IValidator | undefined {+ return this.validator;+ }+}++class TestSheetDataValidationModel {+ rule: IRule | null = null;++ getRuleByLocation(_unitId: string, _subUnitId: string, row: number, col: number): IRule | null {+ return col === 2 && row >= 1 && row <= 4 ? this.rule : null;+ }+}++class TestSheetsSelectionsService {+ private readonly _selectionMoveEnd$ = new Subject<ISelectionWithStyle[]>();+ readonly selectionMoveEnd$ = this._selectionMoveEnd$.asObservable();++ moveEnd(selections: ISelectionWithStyle[]): void {+ this._selectionMoveEnd$.next(selections);+ }+}++class TestCellDropdownManagerService {+ dropdownParam: (IDropdownParam & { onHide?: () => void }) | undefined;+ hideCount = 0;++ showDropdown(param: IDropdownParam & { onHide?: () => void }): IDisposable {+ this.dropdownParam = param;++ return toDisposable(() => {+ this.hideCount++;+ });+ }+}++class TestEditorBridgeService {+ visible = true;++ isVisible(): { visible: boolean } {+ return { visible: this.visible };+ }+}++interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ workbook: Workbook;+ executedCommands: ICommandInfo[];+}++function createWorkbookData(): IWorkbookData {+ return {+ id: 'book-1',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet-1'],+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 1: {+ 2: { v: 'Open' },+ },+ 2: {+ 2: { v: 'East/West' },+ },+ 3: {+ 2: { v: '#ff0000' },+ },+ 4: {+ 2: { v: 45800 },+ },+ },+ },+ },+ styles: {},+ };+}++function createTestBed(): ITestBed {+ const univer = new Univer();+ const injector = univer.__getInjector();+ const executedCommands: ICommandInfo[] = [];++ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [DataValidatorRegistryService, { useClass: TestDataValidatorRegistryService }],+ [SheetDataValidationModel, { useClass: TestSheetDataValidationModel }],+ [SheetsSelectionsService, { useClass: TestSheetsSelectionsService }],+ [ISheetCellDropdownManagerService, { useClass: TestCellDropdownManagerService }],+ [IEditorBridgeServiceIdentifier, { useClass: TestEditorBridgeService }],+ [DataValidationDropdownManagerService],+ ];+ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ const commandService = injector.get(ICommandService);+ [SetRangeValuesCommand.id, SetCellEditVisibleOperation.id, OpenValidationPanelOperation.id].forEach((id) => {+ commandService.registerCommand({+ id,+ type: CommandType.COMMAND,+ handler: (_accessor, params) => {+ executedCommands.push({ id, params });+ return true;+ },+ } as ICommand);+ });++ return {+ univer,+ get: injector.get.bind(injector),+ workbook,+ executedCommands,+ };+}++function setRule(testBed: ITestBed, rule: IRule, validator: IValidator): void {+ (testBed.get(SheetDataValidationModel) as unknown as TestSheetDataValidationModel).rule = rule;+ (testBed.get(DataValidatorRegistryService) as unknown as TestDataValidatorRegistryService).validator = validator;+}++function getDropdown(testBed: ITestBed): IDropdownParam {+ return (testBed.get(ISheetCellDropdownManagerService) as unknown as TestCellDropdownManagerService).dropdownParam!;+}++function showDropdown(testBed: ITestBed, row: number, col = 2): void {+ testBed.get(DataValidationDropdownManagerService).showDataValidationDropdown('book-1', 'sheet-1', row, col);+}++function getSetRangeValue(testBed: ITestBed): unknown {+ return (testBed.executedCommands.find((command) => command.id === SetRangeValuesCommand.id)?.params as { value?: unknown } | undefined)?.value;+}+describe('DataValidationDropdownManagerService', () => {- it('shows a list dropdown, saves the selection, opens the editor, and reacts to hide triggers', async () => {- const selectionMoveEnd$ = new Subject<ISelectionWithStyle[]>();- const popupDispose = vi.fn();- let dropdownParam: IDropdownParam | undefined;- const onHide = vi.fn();-- const worksheet = {- getSheetId: () => 'sheet-1',- getCellRaw: () => ({ v: 'Open' }),- };- const workbook = {- getUnitId: () => 'book-1',- getSheetBySheetId: () => worksheet,- };- const rule = {- uid: 'rule-1',+ let testBed: ITestBed | undefined;++ afterEach(() => {+ testBed?.univer.dispose();+ testBed = undefined;+ });++ it('shows a list dropdown, saves the selected item, and opens the validation panel for editing', async () => {+ testBed = createTestBed();+ setRule(testBed, {+ uid: 'rule-list',type: 'list',renderMode: DataValidationRenderMode.CUSTOM,- };-- const service = new DataValidationDropdownManagerService(- {- getUnit: () => workbook,- } as never,- {- getValidatorItem: vi.fn(() => ({- dropdownType: DataValidatorDropdownType.LIST,- getListWithColor: vi.fn(() => [- { label: 'Open', color: '#0f0' },- { label: 'Closed', color: '#f00' },- ]),- })),- } as never,- {- getRuleByLocation: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {- if (unitId === 'book-1' && subUnitId === 'sheet-1' && row === 1 && col === 2) {- return rule;- }-- return null;- }),- } as never,- {- selectionMoveEnd$,- } as unknown as SheetsSelectionsService,- {- showDropdown: vi.fn((param: IDropdownParam) => {- dropdownParam = param;-- return {- dispose: popupDispose,- };- }),- } as never,- {- getRuleByLocation: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {- if (unitId === 'book-1' && subUnitId === 'sheet-1' && row === 1 && col === 2) {- return rule;- }-- return null;- }),- } as unknown as SheetDataValidationModel,- {- executeCommand: vi.fn(() => Promise.resolve(true)),- } as never,- {- isVisible: () => ({ visible: true }),- } as IEditorBridgeService,- {- has: () => false,- } as never,- {- getConfig: vi.fn((key: string) => key === SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY- ? { showEditOnDropdown: true, showSearchOnDropdown: false }- : undefined),- } as never- );-- service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2, onHide);-- expect(dropdownParam).toEqual(expect.objectContaining({+ }, {+ dropdownType: DataValidatorDropdownType.LIST,+ getListWithColor: () => [+ { label: 'Open', color: '#00aa00' },+ { label: 'Closed' },+ ],+ });++ showDropdown(testBed, 1);++ const dropdown = getDropdown(testBed);+ expect(dropdown.type).toBe('list');+ expect(dropdown.props).toMatchObject({+ defaultValue: 'Open',+ multiple: false,+ showEdit: true,+ showSearch: true,+ options: [+ { label: 'Open', value: 'Open', color: '#00aa00' },+ { label: 'Closed', value: 'Closed', color: '#ECECEC' },+ ],+ });++ await (dropdown.props as { onChange: (value: string[]) => Promise<boolean> }).onChange(['Closed']);+ await awaitTime(0);+ expect(getSetRangeValue(testBed)).toEqual({+ v: 'Closed',+ p: null,+ f: null,+ si: null,+ });+ expect(testBed.executedCommands.some((command) => command.id === SetCellEditVisibleOperation.id)).toBe(true);++ (dropdown.props as { onEdit: () => void }).onEdit();+ expect(testBed.executedCommands.at(-1)).toMatchObject({+ id: OpenValidationPanelOperation.id,+ params: { ruleId: 'rule-list' },+ });+ expect((testBed.get(ISheetCellDropdownManagerService) as unknown as TestCellDropdownManagerService).hideCount).toBe(1);+ });++ it('keeps a multiple-list dropdown open after serializing selected values', async () => {+ testBed = createTestBed();+ (testBed.get(IEditorBridgeServiceIdentifier) as unknown as TestEditorBridgeService).visible = false;+ setRule(testBed, {+ uid: 'rule-multiple',type: 'list',- location: expect.objectContaining({- row: 1,- col: 2,- unitId: 'book-1',- subUnitId: 'sheet-1',- workbook,- worksheet,- }),- props: expect.objectContaining({- defaultValue: 'Open',- multiple: false,- showEdit: true,- showSearch: false,- options: [- { label: 'Open', value: 'Open', color: '#0f0' },- { label: 'Closed', value: 'Closed', color: '#f00' },- ],+ }, {+ dropdownType: DataValidatorDropdownType.MULTIPLE_LIST,+ getListWithColor: () => [+ { label: '1,2', color: '#00aa00' },+ { label: '3', color: '#ff0000' },+ ],+ });++ showDropdown(testBed, 1);++ const dropdown = getDropdown(testBed);+ await expect((dropdown.props as { onChange: (value: string[]) => Promise<boolean> }).onChange(['1,2', '3'])).resolves.toBe(false);+ expect(getSetRangeValue(testBed)).toEqual({+ v: serializeListOptions(['1,2', '3']),+ p: null,+ f: null,+ si: null,+ });+ expect(testBed.executedCommands.some((command) => command.id === SetCellEditVisibleOperation.id)).toBe(false);+ });++ it('saves cascader and color dropdown values with synchronous command flow', () => {+ testBed = createTestBed();+ setRule(testBed, {+ uid: 'rule-cascade',+ type: 'cascade',+ formula1: '[{"label":"East","value":"East","children":[{"label":"West","value":"West"}]}]',+ }, {+ dropdownType: DataValidatorDropdownType.CASCADE,+ });++ showDropdown(testBed, 2);+ let dropdown = getDropdown(testBed);+ expect(dropdown.type).toBe('cascader');+ expect(dropdown.props).toMatchObject({+ defaultValue: ['East', 'West'],+ });+ expect((dropdown.props as { onChange: (value: string[]) => boolean }).onChange(['North', 'South'])).toBe(true);+ expect(getSetRangeValue(testBed)).toMatchObject({ v: 'North/South' });++ setRule(testBed, {+ uid: 'rule-color',+ type: 'color',+ }, {+ dropdownType: DataValidatorDropdownType.COLOR,+ });++ showDropdown(testBed, 3);+ dropdown = getDropdown(testBed);+ expect(dropdown.type).toBe('color');+ expect(dropdown.props).toMatchObject({ defaultValue: '#ff0000' });+ expect((dropdown.props as { onChange: (value: string) => boolean }).onChange('#336699')).toBe(true);+ expect(testBed.executedCommands.at(-2)).toMatchObject({+ id: SetRangeValuesCommand.id,+ params: expect.objectContaining({+ value: expect.objectContaining({ v: '#336699' }),}),- }));- expect(service.activeDropdown).toEqual(expect.objectContaining({ location: expect.objectContaining({ row: 1, col: 2 }) }));-- const listProps = dropdownParam?.props as {- onChange?: (value: string[]) => Promise<boolean>;- onEdit?: () => void;- } | undefined;-- await listProps?.onChange?.(['Closed']);-- const commandService = (service as unknown as { _commandService: { executeCommand: ReturnType<typeof vi.fn> } })._commandService;- expect(commandService.executeCommand).toHaveBeenNthCalledWith(1, SetRangeValuesCommand.id, {- unitId: 'book-1',- subUnitId: 'sheet-1',- range: {- startColumn: 2,- endColumn: 2,- startRow: 1,- endRow: 1,- },- value: {- v: 'Closed',- p: null,- f: null,- si: null,- },});- expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, SetCellEditVisibleOperation.id, expect.objectContaining({- visible: false,- unitId: 'book-1',- }));+ });++ it('saves date-like dropdown values as serial numbers and closes cell editing', async () => {+ testBed = createTestBed();+ setRule(testBed, {+ uid: 'rule-date',+ type: 'date',+ errorStyle: DataValidationErrorStyle.STOP,+ }, {+ dropdownType: DataValidatorDropdownType.DATE,+ validator: () => true,+ });- listProps?.onEdit?.();- expect(commandService.executeCommand).toHaveBeenCalledWith(OpenValidationPanelOperation.id, { ruleId: 'rule-1' });- expect(popupDispose).toHaveBeenCalledTimes(1);-- selectionMoveEnd$.next([- {- primary: {- unitId: 'book-1',- sheetId: 'sheet-1',- actualRow: 9,- actualColumn: 9,+ showDropdown(testBed, 4);++ const dropdown = getDropdown(testBed);+ expect(dropdown.type).toBe('datepicker');+ expect(dropdown.props).toMatchObject({+ showTime: false,+ patternType: 'date',+ });+ await expect((dropdown.props as { onChange: (value: ReturnType<typeof dateKit>) => Promise<boolean> }).onChange(dateKit('2026-06-17'))).resolves.toBe(true);+ expect(getSetRangeValue(testBed)).toEqual(expect.objectContaining({+ t: 2,+ s: {+ n: {+ pattern: 'yyyy-MM-dd',},},- ] as never);- expect(service.activeDropdown).toBeNull();+ }));+ expect(testBed.executedCommands.at(-1)?.id).toBe(SetCellEditVisibleOperation.id);++ setRule(testBed, {+ uid: 'rule-time',+ type: 'time',+ errorStyle: DataValidationErrorStyle.STOP,+ }, {+ dropdownType: DataValidatorDropdownType.TIME,+ validator: () => true,+ });- service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2, onHide);- service.hideDropdown();- expect(onHide).toHaveBeenCalledTimes(2);+ showDropdown(testBed, 4);+ const timeDropdown = getDropdown(testBed);+ expect(timeDropdown.props).toMatchObject({ patternType: 'time' });+ await expect((timeDropdown.props as { onChange: (value: ReturnType<typeof dateKit>) => Promise<boolean> }).onChange(dateKit('2026-06-17 12:30:00'))).resolves.toBe(true);+ expect(testBed.executedCommands.at(-2)?.params).toMatchObject({+ value: expect.objectContaining({+ s: {+ n: {+ pattern: 'HH:mm:ss',+ },+ },+ }),+ });});- it('serializes multiple list selections when saving to the cell', async () => {- let dropdownParam: IDropdownParam | undefined;- const worksheet = {- getSheetId: () => 'sheet-1',- getCellRaw: () => ({ v: '' }),- };- const workbook = {- getUnitId: () => 'book-1',- getSheetBySheetId: () => worksheet,- };- const rule = {- uid: 'rule-1',+ it('hides the active dropdown when selection leaves validation cells', () => {+ testBed = createTestBed();+ setRule(testBed, {+ uid: 'rule-list',type: 'list',- renderMode: DataValidationRenderMode.CUSTOM,- };- const commandService = {- executeCommand: vi.fn(() => Promise.resolve(true)),- };-- const service = new DataValidationDropdownManagerService(- {- getUnit: () => workbook,- } as never,- {- getValidatorItem: vi.fn(() => ({- dropdownType: DataValidatorDropdownType.MULTIPLE_LIST,- getListWithColor: vi.fn(() => [- { label: '1,2', color: '#0f0' },- { label: '3', color: '#f00' },- ]),- })),- } as never,- {- getRuleByLocation: vi.fn(() => rule),- } as never,- {- selectionMoveEnd$: new Subject<ISelectionWithStyle[]>(),- } as unknown as SheetsSelectionsService,- {- showDropdown: vi.fn((param: IDropdownParam) => {- dropdownParam = param;-- return {- dispose: vi.fn(),- };- }),- } as never,- {- getRuleByLocation: vi.fn(() => rule),- } as unknown as SheetDataValidationModel,- commandService as never,- {- isVisible: () => ({ visible: false }),- } as IEditorBridgeService,- {- has: () => false,- } as never,- {- getConfig: vi.fn(() => undefined),- } as never- );+ }, {+ dropdownType: DataValidatorDropdownType.LIST,+ getListWithColor: () => [{ label: 'Open' }],+ });- service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2);+ let hideCount = 0;+ testBed.get(DataValidationDropdownManagerService).showDataValidationDropdown('book-1', 'sheet-1', 1, 2, () => {+ hideCount++;+ });+ expect(testBed.get(DataValidationDropdownManagerService).activeDropdown).toMatchObject({+ location: expect.objectContaining({ row: 1, col: 2 }),+ });- const listProps = dropdownParam?.props as {- onChange?: (value: string[]) => Promise<boolean>;- } | undefined;+ (testBed.get(SheetsSelectionsService) as unknown as TestSheetsSelectionsService).moveEnd([{+ primary: {+ unitId: 'book-1',+ sheetId: 'sheet-1',+ actualRow: 9,+ actualColumn: 9,+ },+ } as never]);- await expect(listProps?.onChange?.(['1,2', '3'])).resolves.toBe(false);+ expect(testBed.get(DataValidationDropdownManagerService).activeDropdown).toBeNull();+ expect(hideCount).toBe(1);+ });- expect(commandService.executeCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({- value: {- v: '["1,2","3"]',- p: null,- f: null,- si: null,- },- }));+ it('does not open a dropdown when workbook, rule, or validator dropdown type is unavailable', () => {+ testBed = createTestBed();+ const service = testBed.get(DataValidationDropdownManagerService);++ service.showDataValidationDropdown('missing-book', 'sheet-1', 1, 2);+ expect((testBed.get(ISheetCellDropdownManagerService) as unknown as TestCellDropdownManagerService).dropdownParam).toBeUndefined();++ service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2);+ expect((testBed.get(ISheetCellDropdownManagerService) as unknown as TestCellDropdownManagerService).dropdownParam).toBeUndefined();++ setRule(testBed, {+ uid: 'rule-no-dropdown',+ type: 'unknown',+ }, {});+ service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2);+ expect(service.activeDropdown).toBeUndefined();});});diff --git a/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsx b/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsxindex 63ecd858f5..13d5be48a3 100644--- a/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/DataValidationDetail.tsx@@ -14,15 +14,46 @@* limitations under the License.*/-import type { DataValidationOperator, DataValidationType, IDataValidationRuleBase, IDataValidationRuleOptions, IExecutionOptions, ISheetDataValidationRule, IUnitRange, Workbook } from '@univerjs/core';+import type {+ DataValidationOperator,+ DataValidationType,+ IDataValidationRuleBase,+ IDataValidationRuleOptions,+ IExecutionOptions,+ ISheetDataValidationRule,+ IUnitRange,+ Workbook,+} from '@univerjs/core';import type { IUpdateSheetDataValidationRangeCommandParams } from '@univerjs/sheets-data-validation';import type { IRangeSelectorInstance } from '@univerjs/sheets-formula-ui';-import { debounce, ICommandService, isUnitRangesEqual, IUniverInstanceService, LocaleService, RedoCommand, shallowEqual, UndoCommand, UniverInstanceType } from '@univerjs/core';-import { DataValidationModel, DataValidatorRegistryScope, DataValidatorRegistryService, getRuleOptions, getRuleSetting, TWO_FORMULA_OPERATOR_COUNT } from '@univerjs/data-validation';+import {+ debounce,+ ICommandService,+ isUnitRangesEqual,+ IUniverInstanceService,+ LocaleService,+ RedoCommand,+ shallowEqual,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';+import {+ DataValidationModel,+ DataValidatorRegistryScope,+ DataValidatorRegistryService,+ getRuleOptions,+ getRuleSetting,+ TWO_FORMULA_OPERATOR_COUNT,+} from '@univerjs/data-validation';import { Button, Checkbox, FormLayout, Select } from '@univerjs/design';import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';import { SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';-import { RemoveSheetDataValidationCommand, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand } from '@univerjs/sheets-data-validation';+import {+ RemoveSheetDataValidationCommand,+ UpdateSheetDataValidationOptionsCommand,+ UpdateSheetDataValidationRangeCommand,+ UpdateSheetDataValidationSettingCommand,+} from '@univerjs/sheets-data-validation';import { RangeSelector } from '@univerjs/sheets-formula-ui';import { ComponentManager, useDependency, useEvent, useObservable } from '@univerjs/ui';import { useEffect, useMemo, useRef, useState } from 'react';@@ -46,10 +77,20 @@ function getSheetIdByName(univerInstanceService: IUniverInstanceService, unitId:}export function DataValidationDetail() {- const [key, setKey] = useState(0);const dataValidationPanelService = useDependency(DataValidationPanelService);const activeRuleInfo = useObservable(dataValidationPanelService.activeRule$, dataValidationPanelService.activeRule)!;const { unitId, subUnitId, rule } = activeRuleInfo || {};+ if (!unitId || !subUnitId || !rule) {+ return null;+ }++ return <DataValidationDetailInner activeRuleInfo={{ unitId, subUnitId, rule }} />;+}++function DataValidationDetailInner(props: { activeRuleInfo: { unitId: string; subUnitId: string; rule: ISheetDataValidationRule } }) {+ const [key, setKey] = useState(0);+ const dataValidationPanelService = useDependency(DataValidationPanelService);+ const { unitId, subUnitId, rule } = props.activeRuleInfo;const ruleId = rule.uid;const validatorService = useDependency(DataValidatorRegistryService);const univerInstanceService = useDependency(IUniverInstanceService);diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsxnew file mode 100644index 0000000000..a4f96686b4--- /dev/null+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx@@ -0,0 +1,869 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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,+ IDisposable,+ IDocumentData,+ IRange,+ ISheetDataValidationRule,+ IWorkbookData,+ Workbook,+} from '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import type { Root } from 'react-dom/client';+import {+ createIdentifier,+ DataValidationType,+ ICommandService,+ ILogService,+ Inject,+ Injector,+ IPermissionService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ set,+ ThemeService,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ AddDataValidationMutation,+ DataValidationModel,+ DataValidatorRegistryService,+ UniverDataValidationPlugin,+} from '@univerjs/data-validation';+import {+ ActiveDirtyManagerService,+ DefinedNamesService,+ FormulaDataModel,+ FunctionService,+ IActiveDirtyManagerService,+ IDefinedNamesService,+ IFunctionService,+ ISheetRowFilteredService,+ ISuperTableService,+ LexerTreeBuilder,+ RegisterOtherFormulaService,+ SheetRowFilteredService,+ SuperTableService,+} from '@univerjs/engine-formula';+import { IRenderManagerService } from '@univerjs/engine-render';+import {+ RangeProtectionRuleModel,+ RefRangeService,+ SheetInterceptorService,+ SheetSkeletonService,+ SheetsSelectionsService,+ WorkbookEditablePermission,+ WorkbookPermissionService,+ WorksheetPermissionService,+ WorksheetProtectionPointModel,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';+import {+ AddSheetDataValidationCommand,+ CHECKBOX_FORMULA_1,+ CHECKBOX_FORMULA_2,+ CheckboxValidator,+ DataValidationCacheService,+ DataValidationCustomFormulaService,+ DataValidationFormulaService,+ DataValidationListCacheService,+ RemoveSheetAllDataValidationCommand,+ RemoveSheetDataValidationCommand,+ SheetDataValidationModel,+ SheetsDataValidationValidatorService,+} from '@univerjs/sheets-data-validation';+import { IMarkSelectionService } from '@univerjs/sheets-ui';+import {+ ComponentManager,+ DesktopSidebarService,+ ILayoutService,+ IPlatformService,+ IShortcutService,+ ISidebarService,+ PlatformService,+ RediContext,+ ShortcutService,+} from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { DataValidationPanelService } from '../../../services/data-validation-panel.service';+import { DataValidationDetail } from '../DataValidationDetail';+import { DataValidationItem } from '../DataValidationItem';+import { DataValidationList } from '../DataValidationList';+import { DataValidationPanel } from '../DataValidationPanel';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'test';+const SUB_UNIT_ID = 'sheet1';+const OTHER_SUB_UNIT_ID = 'sheet2';++const FIRST_RANGE: IRange = {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 0,+};++const SECOND_RANGE: IRange = {+ startRow: 4,+ endRow: 4,+ startColumn: 2,+ endColumn: 3,+};++const ADD_RANGE: IRange = {+ startRow: 6,+ endRow: 7,+ startColumn: 1,+ endColumn: 2,+};++class TestMarkSelectionService {+ private _nextId = 0;++ readonly added: Array<{ id: string; selection: ISelectionWithStyle }> = [];+ readonly removed: string[] = [];++ addShape(selection: ISelectionWithStyle) {+ const id = `shape-${this._nextId++}`;+ this.added.push({ id, selection });+ return id;+ }++ addShapeWithNoFresh(selection: ISelectionWithStyle) {+ return this.addShape(selection);+ }++ removeShape(id: string) {+ this.removed.push(id);+ }++ removeAllShapes() {+ this.removed.push(...this.added.map((item) => item.id));+ }++ refreshShapes() {+ // The component test only needs the service state changes.+ }++ getShapeMap() {+ return new Map();+ }+}++class TestLayoutService {+ readonly rootContainerElement = document.body;+}++class TestRenderManagerService {+ getRenderById() {+ return undefined;+ }+}++class TestDescriptionService {+}++const IEditorService = createIdentifier<TestEditorService>('univer.editor.service');+const IDescriptionService = createIdentifier<TestDescriptionService>('formula.description-service');++class TestRangeEditor {+ readonly blur$ = new Subject<void>();+ readonly focus$ = new Subject<void>();+ readonly input$ = new Subject<void>();+ readonly selectionChange$ = new Subject<void>();++ private _data: IDocumentData;+ private readonly _change$ = new Subject<void>();+ private _isFocus = false;++ readonly render = {+ isDisposed: () => true,+ };++ constructor(private readonly _editorId: string, initialSnapshot: IDocumentData) {+ this._data = initialSnapshot;+ }++ getEditorId() {+ return this._editorId;+ }++ getDocumentData() {+ return this._data;+ }++ setDocumentData(data: IDocumentData) {+ this._data = data;+ this._change$.next();+ }++ getDocumentDataModel() {+ return {+ change$: this._change$.asObservable(),+ getPlainText: () => this._getPlainText(),+ };+ }++ setSelectionRanges() {+ this.selectionChange$.next();+ }++ getSelectionRanges() {+ return [];+ }++ focus() {+ this._isFocus = true;+ this.focus$.next();+ }++ blur() {+ this._isFocus = false;+ this.blur$.next();+ }++ isFocus() {+ return this._isFocus;+ }++ isSheetEditor() {+ return false;+ }++ getBoundingClientRect() {+ return { width: 0, height: 0 };+ }++ private _getPlainText() {+ return this._data.body?.dataStream.replace(/\r\n$/, '') ?? '';+ }+}++class TestEditorService {+ private readonly _editors = new Map<string, TestRangeEditor>();+ private _focusId: string | undefined;++ readonly blur$ = new Subject<void>();+ readonly focus$ = new Subject<{ unitId: string }>();++ register(config: { editorUnitId: string; initialSnapshot: IDocumentData }): IDisposable {+ this._editors.set(config.editorUnitId, new TestRangeEditor(config.editorUnitId, config.initialSnapshot));++ return toDisposable(() => {+ this._editors.delete(config.editorUnitId);+ });+ }++ getEditor(id?: string) {+ return id ? this._editors.get(id) : this.getFocusEditor();+ }++ getAllEditor() {+ return this._editors;+ }++ isEditor(editorUnitId: string) {+ return this._editors.has(editorUnitId);+ }++ getEditorRenderConfig() {+ return null;+ }++ isSheetEditor() {+ return false;+ }++ blur() {+ this._focusId = undefined;+ this.blur$.next();+ }++ focus(editorUnitId: string) {+ this._focusId = editorUnitId;+ this.focus$.next({ unitId: editorUnitId });+ }++ getFocusId() {+ return this._focusId;+ }++ getFocusEditor() {+ return this._focusId ? this._editors.get(this._focusId) : null;+ }+}++function createWorkbookData(): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ sheets: {+ [SUB_UNIT_ID]: {+ id: SUB_UNIT_ID,+ name: 'sheet1',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ [OTHER_SUB_UNIT_ID]: {+ id: OTHER_SUB_UNIT_ID,+ name: 'sheet2',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ },+ locale: LocaleType.EN_US,+ name: 'test workbook',+ sheetOrder: [SUB_UNIT_ID, OTHER_SUB_UNIT_ID],+ styles: {},+ };+}++function createCheckboxRule(uid = 'rule-checkbox'): ISheetDataValidationRule {+ return {+ uid,+ type: DataValidationType.CHECKBOX,+ ranges: [FIRST_RANGE, SECOND_RANGE],+ formula1: `${CHECKBOX_FORMULA_1}`,+ formula2: `${CHECKBOX_FORMULA_2}`,+ };+}++function createInvalidCheckboxRule(): ISheetDataValidationRule {+ return {+ ...createCheckboxRule('rule-checkbox-invalid'),+ formula1: `${CHECKBOX_FORMULA_1}`,+ formula2: `${CHECKBOX_FORMULA_1}`,+ };+}++function createItemTestBed(rule: ISheetDataValidationRule = createCheckboxRule()) {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'sheets-data-validation-ui-item-test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ ([+ [SheetsSelectionsService],+ [SheetInterceptorService],+ [SheetSkeletonService],+ [ComponentManager],+ [IEditorService, { useClass: TestEditorService }],+ [IDescriptionService, { useClass: TestDescriptionService }],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ [IPlatformService, { useClass: PlatformService }],+ [IShortcutService, { useClass: ShortcutService }],+ [ILayoutService, { useClass: TestLayoutService as never }],+ [WorksheetPermissionService],+ [WorkbookPermissionService],+ [WorksheetProtectionPointModel],+ [WorksheetProtectionRuleModel],+ [RangeProtectionRuleModel],+ [FormulaDataModel],+ [LexerTreeBuilder],+ [RefRangeService],+ [IFunctionService, { useClass: FunctionService }],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [ISuperTableService, { useClass: SuperTableService }],+ [DataValidationCacheService],+ [DataValidationListCacheService],+ [DataValidationFormulaService],+ [DataValidationCustomFormulaService],+ [RegisterOtherFormulaService],+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],+ [SheetsDataValidationValidatorService],+ [SheetDataValidationModel],+ [IMarkSelectionService, { useClass: TestMarkSelectionService as never }],+ [ISidebarService, { useClass: DesktopSidebarService }],+ [DataValidationPanelService],+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));++ this._injector.get(WorkbookPermissionService);+ this._injector.get(WorksheetPermissionService);+ }++ override onReady(): void {+ // no extra lifecycle work is needed for this component test.+ }+ }++ injector.get(LocaleService).load({+ [LocaleType.EN_US]: {+ 'sheets-data-validation': {+ checkbox: {+ title: 'Checkbox',+ },+ },+ 'sheets-data-validation-ui': {+ panel: {+ add: 'Add',+ removeAll: 'Remove all',+ },+ },+ },+ });++ const themeService = injector.get(ThemeService);+ themeService.setTheme(set(themeService.getCurrentTheme(), 'black', '#35322b'));++ univer.registerPlugin(UniverDataValidationPlugin);+ univer.registerPlugin(TestPlugin);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);++ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(AddSheetDataValidationCommand);+ commandService.registerCommand(RemoveSheetAllDataValidationCommand);+ commandService.registerCommand(RemoveSheetDataValidationCommand);++ const validatorRegistry = injector.get(DataValidatorRegistryService);+ validatorRegistry.register(injector.createInstance(CheckboxValidator));++ const sheetDataValidationModel = injector.get(SheetDataValidationModel);+ commandService.syncExecuteCommand(AddDataValidationMutation.id, {+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ rule,+ });++ return {+ univer,+ injector,+ commandService,+ workbook,+ rule,+ dataValidationModel: injector.get(DataValidationModel),+ panelService: injector.get(DataValidationPanelService),+ sheetDataValidationModel,+ markSelectionService: injector.get(IMarkSelectionService) as unknown as TestMarkSelectionService,+ };+}++function renderItem(+ root: Root,+ testBed: ReturnType<typeof createItemTestBed>,+ onClick: () => void+) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <DataValidationItem+ rule={testBed.rule}+ onClick={onClick}+ unitId={UNIT_ID}+ subUnitId={SUB_UNIT_ID}+ />+ </RediContext.Provider>+ );+ });++ return document.querySelector('.univer-bg-secondary') as HTMLElement;+}++async function enterItem(item: HTMLElement) {+ await act(async () => {+ item.dispatchEvent(new MouseEvent('mouseover', { bubbles: true, relatedTarget: document.body }));+ await Promise.resolve();+ });+}++async function leaveItem(item: HTMLElement) {+ await act(async () => {+ item.dispatchEvent(new MouseEvent('mouseout', { bubbles: true, relatedTarget: document.body }));+ await Promise.resolve();+ });+}++describe('DataValidationItem', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createItemTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('marks each rule range while the rule item is hovered and clears the marks on leave', async () => {+ currentTestBed = createItemTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ const item = renderItem(root, currentTestBed, () => undefined);++ await enterItem(item);++ expect(currentTestBed.markSelectionService.added.map((entry) => entry.selection.range)).toEqual([+ FIRST_RANGE,+ SECOND_RANGE,+ ]);+ expect(currentTestBed.markSelectionService.added.every((entry) => entry.selection.primary === null)).toBe(true);++ await leaveItem(item);++ expect(currentTestBed.markSelectionService.removed).toEqual(['shape-0', 'shape-1']);+ });++ it('removes the hovered rule through the sheet data-validation command without selecting the item', async () => {+ currentTestBed = createItemTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ let selectedCount = 0;++ const item = renderItem(root, currentTestBed, () => {+ selectedCount += 1;+ });++ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeDefined();++ await enterItem(item);++ const deleteButton = container.querySelector('.univer-absolute') as HTMLElement;++ await act(async () => {+ deleteButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(selectedCount).toBe(0);+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeUndefined();+ expect(currentTestBed.dataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeUndefined();+ });+});++describe('DataValidationList', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createItemTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ function renderList() {+ act(() => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <DataValidationList workbook={currentTestBed!.workbook} />+ </RediContext.Provider>+ );+ });+ }++ it('adds a new validation rule from the current sheet selection and opens it for editing', async () => {+ currentTestBed = createItemTestBed();+ currentTestBed.injector.get(SheetsSelectionsService).setSelections([{ range: ADD_RANGE, primary: null }] as never);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ renderList();++ const buttons = Array.from(container.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const addButton = buttons[buttons.length - 1];++ await act(async () => {+ addButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ const rules = currentTestBed.sheetDataValidationModel.getRules(UNIT_ID, SUB_UNIT_ID);+ const activeRule = currentTestBed.panelService.activeRule;++ expect(rules).toHaveLength(2);+ expect(rules[1].ranges).toEqual([ADD_RANGE]);+ expect(activeRule?.unitId).toBe(UNIT_ID);+ expect(activeRule?.subUnitId).toBe(SUB_UNIT_ID);+ expect(activeRule?.rule.uid).toBe(rules[1].uid);+ });++ it('removes all validation rules from the active sheet through the list action', async () => {+ currentTestBed = createItemTestBed();+ const secondRule = createCheckboxRule('rule-checkbox-second');+ currentTestBed.commandService.syncExecuteCommand(AddDataValidationMutation.id, {+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ rule: secondRule,+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ renderList();++ expect(currentTestBed.sheetDataValidationModel.getRules(UNIT_ID, SUB_UNIT_ID)).toHaveLength(2);++ const buttons = Array.from(container.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const removeAllButton = buttons[0];++ await act(async () => {+ removeAllButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.sheetDataValidationModel.getRules(UNIT_ID, SUB_UNIT_ID)).toEqual([]);+ expect(container.textContent).not.toContain('A1:A2');+ expect(container.textContent).not.toContain('C5:D5');+ });++ it('keeps workbook-locked rules from being highlighted, opened, or bulk removed', async () => {+ currentTestBed = createItemTestBed();+ currentTestBed.injector+ .get(IPermissionService)+ .updatePermissionPoint(new WorkbookEditablePermission(UNIT_ID).id, false);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ renderList();++ const item = container.querySelector('.univer-bg-secondary') as HTMLElement;++ await enterItem(item);++ expect(currentTestBed.markSelectionService.added).toEqual([]);++ await act(async () => {+ item.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.panelService.activeRule?.rule.uid).toBeUndefined();+ expect(container.textContent).not.toContain('Remove all');+ expect(currentTestBed.sheetDataValidationModel.getRules(UNIT_ID, SUB_UNIT_ID)).toHaveLength(1);+ });+});++describe('DataValidationDetail', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createItemTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ async function renderDetail() {+ currentTestBed!.panelService.setActiveRule({+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ rule: currentTestBed!.rule,+ });++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <DataValidationDetail />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ return container!.querySelector('[data-u-comp="data-validation-detail"]') as HTMLElement;+ }++ it('removes the active validation rule and returns to the rule list', async () => {+ currentTestBed = createItemTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ const detail = await renderDetail();+ const buttons = Array.from(detail.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const removeButton = buttons[buttons.length - 2];++ await act(async () => {+ removeButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeUndefined();+ expect(currentTestBed.panelService.activeRule).toBeNull();+ });++ it('keeps a valid rule and closes the detail view when done is clicked', async () => {+ currentTestBed = createItemTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ const detail = await renderDetail();+ const buttons = Array.from(detail.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const doneButton = buttons[buttons.length - 1];++ await act(async () => {+ doneButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeDefined();+ expect(currentTestBed.panelService.activeRule).toBeNull();+ });++ it('keeps the detail open when the rule formula is invalid', async () => {+ currentTestBed = createItemTestBed(createInvalidCheckboxRule());+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ const detail = await renderDetail();+ const buttons = Array.from(detail.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const doneButton = buttons[buttons.length - 1];++ await act(async () => {+ doneButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.panelService.activeRule?.rule.uid).toBe(currentTestBed.rule.uid);+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeDefined();+ });+});++describe('DataValidationPanel', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createItemTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('ignores an active rule from another sheet until a current-sheet rule is selected', async () => {+ currentTestBed = createItemTestBed();+ currentTestBed.panelService.setActiveRule({+ unitId: UNIT_ID,+ subUnitId: OTHER_SUB_UNIT_ID,+ rule: currentTestBed.rule,+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <DataValidationPanel />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const item = container.querySelector('.univer-bg-secondary') as HTMLElement;++ await act(async () => {+ item.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.panelService.activeRule?.subUnitId).toBe(SUB_UNIT_ID);+ expect(currentTestBed.panelService.activeRule?.rule.uid).toBe(currentTestBed.rule.uid);+ expect(container.querySelector('[data-u-comp="data-validation-detail"]')).not.toBeNull();+ });++ it('opens the selected rule in detail and returns to the list after the rule is accepted', async () => {+ currentTestBed = createItemTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <DataValidationPanel />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const item = container.querySelector('.univer-bg-secondary') as HTMLElement;++ await act(async () => {+ item.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.panelService.activeRule?.rule.uid).toBe(currentTestBed.rule.uid);++ const detail = container.querySelector('[data-u-comp="data-validation-detail"]') as HTMLElement;+ const buttons = Array.from(detail.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const doneButton = buttons[buttons.length - 1];++ await act(async () => {+ doneButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.panelService.activeRule).toBeNull();+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)).toBeDefined();+ expect(container.textContent).toContain('A1:A2');+ });+});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.tsindex fb6645a335..2171da094b 100644--- 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.ts@@ -14,164 +14,300 @@* 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 type { Injector, Workbook } from '@univerjs/core';+import type { FUniver } from '@univerjs/core/facade';+import { DataValidationErrorStyle, DataValidationOperator, DataValidationType, ICommandService } from '@univerjs/core';+import {+ AddDataValidationMutation,+ RemoveDataValidationMutation,+ UpdateDataValidationMutation,+ UpdateRuleType,+} from '@univerjs/data-validation';import { SetRangeValuesMutation } from '@univerjs/sheets';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createFacadeTestBed } from '../../../facade/__tests__/create-test-bed';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: '' };- }+import {+ AddSheetDataValidationCommand,+ ClearRangeDataValidationCommand,+ getDataValidationDiffMutations,+ RemoveSheetAllDataValidationCommand,+ RemoveSheetDataValidationCommand,+ UpdateSheetDataValidationOptionsCommand,+ UpdateSheetDataValidationRangeCommand,+ UpdateSheetDataValidationSettingCommand,+} from '../data-validation.command';- 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)}`);+const unitId = 'test';+const subUnitId = 'sheet1';++describe('sheet data validation commands', () => {+ let univerAPI: FUniver;+ let workbook: Workbook;+ let injector: Injector;+ let commandService: ICommandService;+ let model: SheetDataValidationModel;+ let dispose: () => void;++ beforeEach(() => {+ const testBed = createFacadeTestBed();+ univerAPI = testBed.univerAPI;+ workbook = testBed.sheet as Workbook;+ injector = testBed.injector;+ commandService = testBed.get(ICommandService);+ model = testBed.get(SheetDataValidationModel);+ dispose = () => testBed.univer.dispose();++ const commands = [+ SetRangeValuesMutation,+ AddSheetDataValidationCommand,+ UpdateSheetDataValidationRangeCommand,+ UpdateSheetDataValidationSettingCommand,+ UpdateSheetDataValidationOptionsCommand,+ ClearRangeDataValidationCommand,+ RemoveSheetDataValidationCommand,+ RemoveSheetAllDataValidationCommand,+ ];++ for (const command of commands) {+ commandService.registerCommand(command);+ }+ });++ afterEach(() => {+ dispose();+ });++ it('adds checkbox validation to the selected range', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const rule = univerAPI.newDataValidation()+ .requireCheckbox('Yes', 'No')+ .build();++ activeSheet.getRange(0, 0, 2, 1).setDataValidation(rule);++ const rules = model.getRules(unitId, subUnitId);++ expect(rules).toHaveLength(1);+ expect(rules[0].type).toBe(DataValidationType.CHECKBOX);+ expect(rules[0].formula1).toBe('Yes');+ expect(rules[0].formula2).toBe('No');+ expect(rules[0].ranges).toEqual([{ unitId, sheetId: subUnitId, startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }]);+ });++ it('moves a validation rule to a new range and applies checkbox defaults there', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const rule = univerAPI.newDataValidation()+ .requireCheckbox('TRUE', 'FALSE')+ .build();++ activeSheet.getRange(0, 0, 1, 1).setDataValidation(rule);+ const ruleId = model.getRules(unitId, subUnitId)[0].uid;++ const result = await commandService.executeCommand(UpdateSheetDataValidationRangeCommand.id, {+ unitId,+ subUnitId,+ ruleId,+ ranges: [{ startRow: 2, endRow: 3, startColumn: 1, endColumn: 1 }],+ });++ const updatedRule = model.getRuleById(unitId, subUnitId, ruleId);+ const worksheet = workbook.getSheetBySheetId(subUnitId);++ expect(result).toBe(true);+ expect(updatedRule?.ranges).toEqual([{ startRow: 2, endRow: 3, startColumn: 1, endColumn: 1 }]);+ expect(worksheet?.getCellRaw(2, 1)?.v).toBe(0);+ expect(worksheet?.getCellRaw(3, 1)?.v).toBe(0);+ });++ it('updates validation settings and options on an existing rule', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const rule = univerAPI.newDataValidation()+ .requireNumberBetween(1, 10)+ .build();++ activeSheet.getRange(0, 1, 2, 1).setDataValidation(rule);+ const ruleId = model.getRules(unitId, subUnitId)[0].uid;++ const settingResult = await commandService.executeCommand(UpdateSheetDataValidationSettingCommand.id, {+ unitId,+ subUnitId,+ ruleId,+ setting: {+ type: DataValidationType.DECIMAL,+ operator: univerAPI.Enum.DataValidationOperator.GREATER_THAN,+ formula1: '5',+ },+ });+ const optionsResult = await commandService.executeCommand(UpdateSheetDataValidationOptionsCommand.id, {+ unitId,+ subUnitId,+ ruleId,+ options: {+ errorStyle: DataValidationErrorStyle.STOP,+ showErrorMessage: true,+ error: 'Value must be greater than five',+ },+ });++ const updatedRule = model.getRuleById(unitId, subUnitId, ruleId);++ expect(settingResult).toBe(true);+ expect(optionsResult).toBe(true);+ expect(updatedRule?.operator).toBe(univerAPI.Enum.DataValidationOperator.GREATER_THAN);+ expect(updatedRule?.formula1).toBe('5');+ expect(updatedRule?.errorStyle).toBe(DataValidationErrorStyle.STOP);+ expect(updatedRule?.error).toBe('Value must be greater than five');+ });++ it('updates checkbox settings and rewrites existing checkbox values', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const rule = univerAPI.newDataValidation()+ .requireCheckbox('Y', 'N')+ .build();+ const worksheet = workbook.getSheetBySheetId(subUnitId);++ activeSheet.getRange(0, 2, 2, 1).setDataValidation(rule);+ worksheet?.getCellMatrix().setValue(0, 2, { v: 'N' });+ worksheet?.getCellMatrix().setValue(1, 2, { v: 'Y' });+ const ruleId = model.getRules(unitId, subUnitId)[0].uid;++ const result = await commandService.executeCommand(UpdateSheetDataValidationSettingCommand.id, {+ unitId,+ subUnitId,+ ruleId,+ setting: {+ type: DataValidationType.CHECKBOX,+ formula1: 'Done',+ formula2: 'Todo',},- } 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: [],});++ const updatedRule = model.getRuleById(unitId, subUnitId, ruleId);++ expect(result).toBe(true);+ expect(updatedRule?.formula1).toBe('Done');+ expect(updatedRule?.formula2).toBe('Todo');+ expect(worksheet?.getCellRaw(0, 2)?.v).toBe('Todo');+ expect(worksheet?.getCellRaw(1, 2)?.v).toBe('Done');});- it('builds delete, update, and add mutations including checkbox default fills', () => {- const { accessor } = createAccessor(true, true);- const diffs = [+ it('clears validation from a range without removing unrelated rules', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const firstRule = univerAPI.newDataValidation().requireCheckbox().build();+ const secondRule = univerAPI.newDataValidation().requireNumberEqualTo(1).build();++ activeSheet.getRange(0, 0, 1, 1).setDataValidation(firstRule);+ activeSheet.getRange(4, 4, 1, 1).setDataValidation(secondRule);++ const result = await commandService.executeCommand(ClearRangeDataValidationCommand.id, {+ unitId,+ subUnitId,+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ });+ const rules = model.getRules(unitId, subUnitId);++ expect(result).toBe(true);+ expect(rules).toHaveLength(1);+ expect(rules[0].type).toBe(DataValidationType.DECIMAL);+ expect(rules[0].ranges).toEqual([{ unitId, sheetId: subUnitId, startRow: 4, endRow: 4, startColumn: 4, endColumn: 4 }]);+ });++ it('removes one rule or all rules from the sheet', async () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const firstRule = univerAPI.newDataValidation().requireCheckbox().build();+ const secondRule = univerAPI.newDataValidation().requireNumberEqualTo(1).build();++ activeSheet.getRange(0, 0, 1, 1).setDataValidation(firstRule);+ activeSheet.getRange(4, 4, 1, 1).setDataValidation(secondRule);++ const ruleId = model.getRules(unitId, subUnitId)[0].uid;+ const removeOneResult = await commandService.executeCommand(RemoveSheetDataValidationCommand.id, {+ unitId,+ subUnitId,+ ruleId,+ });+ const removeAllResult = await commandService.executeCommand(RemoveSheetAllDataValidationCommand.id, {+ unitId,+ subUnitId,+ });++ expect(removeOneResult).toBe(true);+ expect(removeAllResult).toBe(true);+ expect(model.getRules(unitId, subUnitId)).toEqual([]);+ });++ it('builds diff mutations for validation rule add and formula-offset range changes', () => {+ const checkboxRule = {+ uid: 'checkbox-diff',+ type: DataValidationType.CHECKBOX,+ formula1: '1',+ formula2: '0',+ ranges: [{ startRow: 6, endRow: 6, startColumn: 0, endColumn: 0 }],+ };+ const customFormulaRule = {+ uid: 'formula-diff',+ type: DataValidationType.CUSTOM,+ operator: DataValidationOperator.BETWEEN,+ formula1: '=A1>0',+ formula2: '=B1<10',+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],+ };++ const { redoMutations, undoMutations } = getDataValidationDiffMutations(unitId, subUnitId, [{- type: 'delete',- rule: { uid: 'rule-delete', ranges: [] },- index: 0,+ type: 'add',+ rule: checkboxRule,},{type: 'update',- ruleId: 'rule-update',+ ruleId: customFormulaRule.uid,+ rule: customFormulaRule,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);+ ] as never, injector);++ let hasAddRule = false;+ let hasFormulaUpdate = false;+ let hasDefaultCellValue = false;+ let hasUndoRemove = false;+ for (const mutation of redoMutations) {+ if (mutation.id === AddDataValidationMutation.id) {+ hasAddRule = true;+ }+ if (mutation.id === UpdateDataValidationMutation.id && (mutation.params as never as { payload: { type: UpdateRuleType } }).payload.type === UpdateRuleType.ALL) {+ hasFormulaUpdate = true;+ }+ if (mutation.id === SetRangeValuesMutation.id && (mutation.params as never as { cellValue: Record<number, Record<number, { v: unknown }>> }).cellValue[6]?.[0]?.v === '0') {+ hasDefaultCellValue = true;+ }+ }+ for (const mutation of undoMutations) {+ if (mutation.id === RemoveDataValidationMutation.id) {+ hasUndoRemove = true;+ }+ }++ expect(hasAddRule).toBe(true);+ expect(hasFormulaUpdate).toBe(true);+ expect(hasDefaultCellValue).toBe(true);+ expect(hasUndoRemove).toBe(true);});- it('uses range-only updates when formulas do not offset or default filling is disabled', () => {- const { accessor } = createAccessor(true, false);- const diffs = [+ it('returns no diff mutations when the target sheet is missing', () => {+ const result = getDataValidationDiffMutations(unitId, 'missing-sheet', [{- type: 'update',- ruleId: 'rule-update',- oldRanges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],- newRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],+ type: 'add',rule: {- uid: 'rule-update',- type: DataValidationType.DECIMAL,- formula1: '1',- formula2: '2',+ uid: 'missing-target-rule',+ type: DataValidationType.CHECKBOX,ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],},},- ] as any;-- const { redoMutations, undoMutations } = getDataValidationDiffMutations('unit-1', 'sheet-1', diffs, accessor, 'command', false);+ ] as never, injector);- 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);+ expect(result.redoMutations).toEqual([]);+ expect(result.undoMutations).toEqual([]);});});diff --git a/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts b/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.tsindex fe2b973ac3..d977f537e4 100644--- a/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts+++ b/packages/sheets-data-validation/src/facade/__tests__/f-range.spec.ts@@ -19,7 +19,12 @@import type { Injector } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';import { DataValidationType, ICommandService } from '@univerjs/core';-import { FormulaExecuteStageType, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation } from '@univerjs/engine-formula';+import {+ FormulaExecuteStageType,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+} from '@univerjs/engine-formula';import { AddSheetDataValidationCommand, DataValidationCustomFormulaService } from '@univerjs/sheets-data-validation';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createFacadeTestBed } from './create-test-bed';diff --git a/packages/sheets-data-validation/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets-data-validation/src/facade/__tests__/f-worksheet.spec.tsindex 6bcbb08dc9..78901ad77a 100644--- a/packages/sheets-data-validation/src/facade/__tests__/f-worksheet.spec.ts+++ b/packages/sheets-data-validation/src/facade/__tests__/f-worksheet.spec.ts@@ -14,25 +14,67 @@* limitations under the License.*/+import type { Injector, IWorkbookData } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';-import { beforeEach, describe, expect, it } from 'vitest';-import { createWorksheetTestBed } from './create-worksheet-test-bed';+import {+ ICommandService,+ LocaleType,+} from '@univerjs/core';+import {+ AddSheetDataValidationCommand,+ ClearRangeDataValidationCommand,+ RemoveSheetAllDataValidationCommand,+ RemoveSheetDataValidationCommand,+ UpdateSheetDataValidationOptionsCommand,+ UpdateSheetDataValidationRangeCommand,+ UpdateSheetDataValidationSettingCommand,+} from '@univerjs/sheets-data-validation';+import { beforeEach, describe } from 'vitest';+import { createFacadeTestBed } from './create-test-bed';-describe('Test FWorksheet', () => {+function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ rowCount: 100,+ columnCount: 100,+ cellData: {+ 0: { 0: { v: 1, t: 2 } },+ 1: { 0: { v: 2, t: 2 } },+ 2: { 0: { v: 3, t: 2 } },+ 3: { 0: { v: 4, t: 2 } },+ },+ },+ },+ };+}++describe('Test FWorksheet data validation facade', () => {+ let get: Injector['get'];let univerAPI: FUniver;- beforeEach(() => {- const testBed = createWorksheetTestBed();+ beforeEach(() => {+ const testBed = createFacadeTestBed(createWorkbookData());+ get = testBed.get;univerAPI = testBed.univerAPI;- });-- it('Worksheet getDataValidations', async () => {- const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');- expect(activeSheet?.getDataValidations()).toBeDefined();- });- it('Worksheet getValidatorStatusAsync', async () => {- const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');- expect(activeSheet?.getValidatorStatusAsync()).toBeDefined();+ const commandService = get(ICommandService);+ [+ AddSheetDataValidationCommand,+ ClearRangeDataValidationCommand,+ RemoveSheetAllDataValidationCommand,+ RemoveSheetDataValidationCommand,+ UpdateSheetDataValidationOptionsCommand,+ UpdateSheetDataValidationRangeCommand,+ UpdateSheetDataValidationSettingCommand,+ ].forEach((command) => commandService.registerCommand(command));});});diff --git a/packages/sheets-data-validation/src/facade/f-data-validation.ts b/packages/sheets-data-validation/src/facade/f-data-validation.tsindex 757de14c1c..f814ff312c 100644--- a/packages/sheets-data-validation/src/facade/f-data-validation.ts+++ b/packages/sheets-data-validation/src/facade/f-data-validation.ts@@ -14,11 +14,30 @@* limitations under the License.*/-import type { DataValidationOperator, DataValidationType, IDataValidationRule, IDataValidationRuleOptions, Injector, IRange, Workbook, Worksheet } from '@univerjs/core';-import type { IRemoveSheetDataValidationCommandParams, IUpdateSheetDataValidationOptionsCommandParams, IUpdateSheetDataValidationRangeCommandParams, IUpdateSheetDataValidationSettingCommandParams } from '@univerjs/sheets-data-validation';+import type {+ DataValidationOperator,+ DataValidationType,+ IDataValidationRule,+ IDataValidationRuleOptions,+ Injector,+ IRange,+ Workbook,+ Worksheet,+} from '@univerjs/core';+import type {+ IRemoveSheetDataValidationCommandParams,+ IUpdateSheetDataValidationOptionsCommandParams,+ IUpdateSheetDataValidationRangeCommandParams,+ IUpdateSheetDataValidationSettingCommandParams,+} from '@univerjs/sheets-data-validation';import { DataValidationErrorStyle, ICommandService, IUniverInstanceService } from '@univerjs/core';import { DataValidationModel, getRuleOptions } from '@univerjs/data-validation';-import { RemoveSheetDataValidationCommand, UpdateSheetDataValidationOptionsCommand, UpdateSheetDataValidationRangeCommand, UpdateSheetDataValidationSettingCommand } from '@univerjs/sheets-data-validation';+import {+ RemoveSheetDataValidationCommand,+ UpdateSheetDataValidationOptionsCommand,+ UpdateSheetDataValidationRangeCommand,+ UpdateSheetDataValidationSettingCommand,+} from '@univerjs/sheets-data-validation';import { FRange } from '@univerjs/sheets/facade';import { FDataValidationBuilder } from './f-data-validation-builder';diff --git a/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.ts b/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.tsnew file mode 100644index 0000000000..445480ac3d--- /dev/null+++ b/packages/sheets-drawing-ui/src/__tests__/create-sheets-drawing-ui-test-bed.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 { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import {+ BooleanNumber,+ Disposable,+ ICommandService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ toDisposable,+ Tools,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { UniverDrawingPlugin } from '@univerjs/drawing';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { UniverSheetsPlugin } from '@univerjs/sheets';+import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';+import enUS from '@univerjs/sheets/locale/en-US';+import { ISidebarService } from '@univerjs/ui';+import { BehaviorSubject, Subject } from 'rxjs';++const TEST_WORKBOOK_DATA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: 'A1' },+ },+ },+ hidden: BooleanNumber.FALSE,+ },+ },+};++class TestSidebarService extends Disposable {+ private _sidebarOptions = { visible: false } as any;+ readonly sidebarOptions$ = new BehaviorSubject(this._sidebarOptions);+ readonly scrollEvent$ = new Subject<Event>();+ private _container?: HTMLElement;+ private _width?: number;++ get visible(): boolean {+ return Boolean(this._sidebarOptions.visible);+ }++ get options() {+ return this._sidebarOptions;+ }++ get width(): number | undefined {+ return this._width;+ }++ setWidth(value: number): void {+ this._width = value;+ }++ open(params: any): IDisposable {+ this._sidebarOptions = {+ ...params,+ visible: true,+ };+ this.sidebarOptions$.next(this._sidebarOptions);+ params.onOpen?.();++ return toDisposable(() => this.close());+ }++ close(id?: string): void {+ if (id && this._sidebarOptions.id !== id) {+ return;+ }+ this._sidebarOptions = {+ ...this._sidebarOptions,+ visible: false,+ };+ this.sidebarOptions$.next(this._sidebarOptions);+ this._sidebarOptions.onClose?.();+ }++ getContainer(): HTMLElement | undefined {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element;+ }+}++function hasDependency(dependencies: Dependency[] | undefined, token: unknown): boolean {+ if (!dependencies) {+ return false;+ }++ for (const dependency of dependencies) {+ if (Array.isArray(dependency) && dependency[0] === token) {+ return true;+ }+ }++ return false;+}++export function createSheetsDrawingUiTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {+ const univer = new Univer();+ const injector = univer.__getInjector();+ const get = injector.get.bind(injector);++ class TestPlugin extends Plugin {+ static override pluginName = 'sheets-drawing-ui-test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ if (!hasDependency(dependencies, IRenderManagerService)) {+ this._injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ }+ this._injector.add([ISidebarService, { useClass: TestSidebarService as never }]);+ dependencies?.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ univer.registerPlugin(UniverSheetsPlugin);+ univer.registerPlugin(UniverDrawingPlugin);+ univer.registerPlugin(UniverSheetsDrawingPlugin);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ Tools.deepClone(workbookData ?? TEST_WORKBOOK_DATA)+ );++ get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ get(ILogService).setLogLevel(LogLevel.SILENT);++ const localeService = get(LocaleService);+ localeService.load({ enUS });+ localeService.setLocale(LocaleType.EN_US);++ return {+ univer,+ injector,+ get,+ workbook,+ commandService: get(ICommandService),+ sidebarService: get(ISidebarService) as unknown as TestSidebarService,+ unitId: 'test',+ subUnitId: 'sheet1',+ };+}diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.tsindex 688b998585..29f8d09f28 100644--- a/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.ts@@ -14,44 +14,93 @@* limitations under the License.*/-import type { IAccessor } from '@univerjs/core';-import { ICommandService } from '@univerjs/core';-import { ISheetDrawingService, RemoveSheetDrawingCommand } from '@univerjs/sheets-drawing';-import { describe, expect, it, vi } from 'vitest';+import type { ISheetDrawing } from '@univerjs/sheets-drawing';+import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';+import { InsertSheetDrawingCommand, ISheetDrawingService } from '@univerjs/sheets-drawing';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';import { DeleteDrawingsCommand } from '../delete-drawings.command';+function createSheetDrawing(drawingId: string): ISheetDrawing {+ return {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.URL,+ source: `https://example.com/${drawingId}.png`,+ sheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ axisAlignSheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ };+}+describe('DeleteDrawingsCommand', () => {- it('forwards focused drawings to the remove command', async () => {- const commandService = { executeCommand: vi.fn(() => true) };- const drawingManagerService = {- getFocusDrawings: vi.fn(() => [- { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1', drawingType: 'image' },- ]),- };- const accessor = {- get(token: unknown) {- if (token === ICommandService) return commandService;- if (token === ISheetDrawingService) return drawingManagerService;- throw new Error(`Unknown dependency: ${String(token)}`);- },- } as IAccessor;-- expect(await DeleteDrawingsCommand.handler(accessor)).toBe(true);- expect(commandService.executeCommand).toHaveBeenCalledWith(RemoveSheetDrawingCommand.id, {- unitId: 'book-1',- drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1', drawingType: 'image' }],+ afterEach(() => {+ // each test disposes its own univer instance+ });++ it('removes the focused drawing from the real sheet drawing model', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ testBed.commandService.registerCommand(DeleteDrawingsCommand);++ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings: [createSheetDrawing('drawing-1')],});+ sheetDrawingService.focusDrawing([{+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ }]);++ expect(await testBed.commandService.executeCommand(DeleteDrawingsCommand.id)).toBe(true);++ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ })).toBeUndefined();+ expect(sheetDrawingService.getDrawingOrder(testBed.unitId, testBed.subUnitId)).toEqual([]);++ testBed.univer.dispose();});- it('returns false when nothing is focused', async () => {- const accessor = {- get(token: unknown) {- if (token === ICommandService) return { executeCommand: vi.fn() };- if (token === ISheetDrawingService) return { getFocusDrawings: () => [] };- throw new Error(`Unknown dependency: ${String(token)}`);- },- } as IAccessor;+ it('keeps the model unchanged when there is no focused drawing', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ testBed.commandService.registerCommand(DeleteDrawingsCommand);++ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings: [createSheetDrawing('drawing-2')],+ });++ expect(await testBed.commandService.executeCommand(DeleteDrawingsCommand.id)).toBe(false);+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-2',+ })).toMatchObject({+ drawingId: 'drawing-2',+ });- expect(await DeleteDrawingsCommand.handler(accessor)).toBe(false);+ testBed.univer.dispose();});});diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex 4130051cc0..6c17082e4f 100644--- a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -14,158 +14,314 @@* limitations under the License.*/-import type { IAccessor } from '@univerjs/core';-import { ArrangeTypeEnum, DrawingTypeEnum, ICommandService, IUndoRedoService } from '@univerjs/core';+import type { ISheetDrawing } from '@univerjs/sheets-drawing';+import { Direction, DrawingTypeEnum, ImageSourceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import { SheetInterceptorService } from '@univerjs/sheets';-import { DrawingApplyType, InsertSheetDrawingCommand, ISheetDrawingService, RemoveSheetDrawingCommand, SetDrawingApplyMutation, SetDrawingArrangeCommand } from '@univerjs/sheets-drawing';-import { ISheetSelectionRenderService } from '@univerjs/sheets-ui';-import { describe, expect, it, vi } from 'vitest';+import { InsertSheetDrawingCommand, ISheetDrawingService } from '@univerjs/sheets-drawing';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';+import { FlipSheetDrawingCommand } from '../flip-drawings.command';+import { GroupSheetDrawingCommand } from '../group-sheet-drawing.command';+import { MoveDrawingsCommand } from '../move-drawings.command';+import { UngroupSheetDrawingCommand } from '../ungroup-sheet-drawing.command';-function createSelectionRenderService() {+function createSheetDrawing(drawingId: string, left: number, top: number): ISheetDrawing {return {- getCellWithCoordByOffset(left: number, top: number) {- const actualColumn = Math.floor(left / 10);- const actualRow = Math.floor(top / 10);-- return {- actualColumn,- actualRow,- startX: actualColumn * 10,- startY: actualRow * 10,- };+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.URL,+ source: `https://example.com/${drawingId}.png`,+ transform: {+ left,+ top,+ width: 100,+ height: 80,+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ },+ sheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ axisAlignSheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },},};}-function createAccessor() {- const commandService = { syncExecuteCommand: vi.fn(() => true) };- const pushUndoRedo = vi.fn();- const selectionRenderService = createSelectionRenderService();- const sheetDrawingService = {- getForwardDrawingsOp: vi.fn(() => ({ redo: ['redo-forward'], undo: ['undo-forward'], objects: ['shape-1'] })),- getBackwardDrawingOp: vi.fn(() => ({ redo: ['redo-backward'], undo: ['undo-backward'], objects: ['shape-1'] })),- getFrontDrawingsOp: vi.fn(() => ({ redo: ['redo-front'], undo: ['undo-front'], objects: ['shape-1'] })),- getBackDrawingsOp: vi.fn(() => ({ redo: ['redo-back'], undo: ['undo-back'], objects: ['shape-1'] })),- getBatchRemoveOp: vi.fn(() => ({ unitId: 'book-1', subUnitId: 'sheet-1', redo: ['remove-redo'], undo: ['remove-undo'], objects: ['shape-1'] })),- getBatchAddOp: vi.fn(() => ({ unitId: 'book-1', subUnitId: 'sheet-1', redo: ['add-redo'], undo: ['add-undo'], objects: ['shape-2'] })),- getBatchUpdateOp: vi.fn(() => ({ unitId: 'book-1', subUnitId: 'sheet-1', redo: ['update-redo'], undo: ['update-undo'], objects: ['shape-1'] })),- getDrawingData: vi.fn(() => ({- 'shape-1': {- drawingId: 'shape-1',- drawingType: DrawingTypeEnum.DRAWING_SHAPE,- transform: { left: 10, top: 20, flipX: false, flipY: false },+async function insertDrawings(testBed: ReturnType<typeof createSheetsDrawingUiTestBed>, drawings: ISheetDrawing[]) {+ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings,+ });+}++class TestRenderManagerService {+ private _srcRect: { left?: number; top?: number; right?: number; bottom?: number } | undefined;++ setImageSrcRect(srcRect: { left?: number; top?: number; right?: number; bottom?: number }): void {+ this._srcRect = srcRect;+ }++ getRenderById() {+ return {+ scene: {+ getObject: () => ({+ srcRect: this._srcRect,+ }),},- })),- getFocusDrawings: vi.fn(() => [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-1', transform: { left: 10, top: 20 } }]),- };- const renderManagerService = {- getRenderById: vi.fn(() => ({- scene: null,- with: vi.fn((token: unknown) => (token === ISheetSelectionRenderService ? selectionRenderService : null)),- })),- };- const sheetInterceptorService = {- onCommandExecute: vi.fn(() => ({- preRedos: [{ id: 'pre-redo', params: { ok: true } }],- redos: [{ id: 'redo-extra', params: { ok: true } }],- preUndos: [{ id: 'pre-undo', params: { ok: true } }],- undos: [{ id: 'undo-extra', params: { ok: true } }],- })),- };- const accessor = {- get(token: unknown) {- if (token === ICommandService) {- return commandService;- }+ };+ }+}- if (token === IUndoRedoService) {- return { pushUndoRedo };- }+describe('sheet drawing UI commands', () => {+ afterEach(() => {+ // each test disposes its own univer instance+ });- if (token === ISheetDrawingService) {- return sheetDrawingService;- }+ it('moves focused drawings by one pixel in the selected direction', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ testBed.commandService.registerCommand(MoveDrawingsCommand);+ await insertDrawings(testBed, [createSheetDrawing('drawing-1', 10, 20)]);+ sheetDrawingService.focusDrawing([{+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ }]);- if (token === SheetInterceptorService) {- return sheetInterceptorService;- }+ expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.RIGHT })).toBe(true);- if (token === ISheetSelectionRenderService) {- return selectionRenderService;- }+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ })?.transform).toMatchObject({+ left: 11,+ top: 20,+ });- if (token === IRenderManagerService) {- return renderManagerService;- }+ testBed.univer.dispose();+ });- throw new Error(`Unknown dependency: ${String(token)}`);- },- } as IAccessor;+ it('keeps drawing positions unchanged when move is triggered without a focused drawing', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ testBed.commandService.registerCommand(MoveDrawingsCommand);+ await insertDrawings(testBed, [createSheetDrawing('drawing-2', 30, 40)]);- return { accessor, commandService, pushUndoRedo, renderManagerService, sheetDrawingService, sheetInterceptorService };-}+ expect(await testBed.commandService.executeCommand(MoveDrawingsCommand.id, { direction: Direction.UP })).toBe(false);+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-2',+ })?.transform).toMatchObject({+ left: 30,+ top: 40,+ });++ testBed.univer.dispose();+ });++ it('returns false when flip is triggered without command parameters', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);++ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id)).toBe(false);-describe('sheet drawing commands', () => {- it('arranges drawing order and records undo/redo mutations', () => {- const { accessor, commandService, pushUndoRedo } = createAccessor();- expect(SetDrawingArrangeCommand.handler(accessor, {- unitId: 'book-1',- subUnitId: 'sheet-1',- drawingIds: ['shape-1'],- arrangeType: ArrangeTypeEnum.front,+ testBed.univer.dispose();+ });++ it('skips drawings that are missing from the drawing model or lack a sheet skeleton', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);+ await insertDrawings(testBed, [+ {+ ...createSheetDrawing('detached-drawing', 5, 6),+ unitId: 'detached-unit',+ },+ ]);++ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings: [+ {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'missing-drawing',+ },+ {+ unitId: 'detached-unit',+ subUnitId: testBed.subUnitId,+ drawingId: 'detached-drawing',+ },+ ],+ flipH: true,+ })).toBe(false);++ testBed.univer.dispose();+ });++ it('flips a drawing horizontally and vertically in the sheet drawing model', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);+ await insertDrawings(testBed, [createSheetDrawing('drawing-3', 50, 60)]);++ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings: [{+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-3',+ }],+ flipH: true,+ flipV: true,})).toBe(true);- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingApplyMutation.id, {- op: ['redo-front'],- unitId: 'book-1',- subUnitId: 'sheet-1',- objects: ['shape-1'],- type: DrawingApplyType.ARRANGE,++ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-3',+ })?.transform).toMatchObject({+ flipX: true,+ flipY: true,});- expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({- unitID: 'book-1',- undoMutations: [expect.objectContaining({ id: SetDrawingApplyMutation.id })],- redoMutations: [expect.objectContaining({ id: SetDrawingApplyMutation.id })],- }));++ testBed.univer.dispose();});- it('removes drawings through the interceptor pipeline and clears transformers in undo/redo', () => {- const { accessor, commandService, pushUndoRedo, sheetInterceptorService } = createAccessor();- expect(RemoveSheetDrawingCommand.handler(accessor, {- drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-1' }],- } as never)).toBe(true);- expect(sheetInterceptorService.onCommandExecute).toHaveBeenCalled();- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, 'pre-redo', { ok: true }, undefined);- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, SetDrawingApplyMutation.id, {- unitId: 'book-1',- subUnitId: 'sheet-1',- op: ['remove-redo'],- objects: ['shape-1'],- type: DrawingApplyType.REMOVE,- }, undefined);- expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({- undoMutations: expect.arrayContaining([expect.objectContaining({ id: SetDrawingApplyMutation.id })]),- redoMutations: expect.arrayContaining([expect.objectContaining({ id: SetDrawingApplyMutation.id })]),- }));+ it('updates the image crop rectangle when flipping a cropped drawing', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ renderManagerService.setImageSrcRect({ right: 24, bottom: 36 });+ testBed.commandService.registerCommand(FlipSheetDrawingCommand);+ await insertDrawings(testBed, [createSheetDrawing('cropped-drawing', 50, 60)]);++ expect(await testBed.commandService.executeCommand(FlipSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings: [{+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'cropped-drawing',+ }],+ flipH: true,+ flipV: true,+ })).toBe(true);++ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'cropped-drawing',+ })).toMatchObject({+ srcRect: {+ left: 0,+ top: 0,+ right: 24,+ bottom: 36,+ },+ transform: {+ flipX: true,+ flipY: true,+ },+ });++ testBed.univer.dispose();});- it('inserts drawings through sheet interceptors and records undo/redo mutations', () => {- const { accessor, commandService, sheetInterceptorService } = createAccessor();- const params = {- drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-2' }],+ it('groups two drawings and then ungroups them back to standalone drawings', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ testBed.commandService.registerCommand(GroupSheetDrawingCommand);+ testBed.commandService.registerCommand(UngroupSheetDrawingCommand);+ await insertDrawings(testBed, [+ createSheetDrawing('child-1', 10, 20),+ createSheetDrawing('child-2', 40, 60),+ ]);++ const parent = {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'group-1',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ transform: { left: 0, top: 0, width: 140, height: 120 },+ groupBaseBound: { left: 0, top: 0, width: 140, height: 120 },};+ const groupedChildren = [+ {+ ...createSheetDrawing('child-1', 10, 20),+ groupId: 'group-1',+ },+ {+ ...createSheetDrawing('child-2', 40, 60),+ groupId: 'group-1',+ },+ ];++ expect(await testBed.commandService.executeCommand(GroupSheetDrawingCommand.id, [{+ parent,+ children: groupedChildren,+ }])).toBe(true);+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'group-1',+ })).toMatchObject({+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ });+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'child-1',+ })).toMatchObject({+ groupId: 'group-1',+ });++ const ungroupedChildren = [+ {+ ...createSheetDrawing('child-1', 10, 20),+ groupId: undefined,+ },+ {+ ...createSheetDrawing('child-2', 40, 60),+ groupId: undefined,+ },+ ];+ expect(await testBed.commandService.executeCommand(UngroupSheetDrawingCommand.id, [{+ parent,+ children: ungroupedChildren,+ }])).toBe(true);++ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'group-1',+ })).toBeUndefined();+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'child-1',+ })?.groupId).toBeUndefined();- expect(InsertSheetDrawingCommand.handler(accessor, params as never)).toBe(true);- expect(sheetInterceptorService.onCommandExecute).toHaveBeenCalledWith({ id: InsertSheetDrawingCommand.id, params });- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, 'pre-redo', { ok: true }, undefined);- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, SetDrawingApplyMutation.id, {- op: ['add-redo'],- unitId: 'book-1',- subUnitId: 'sheet-1',- objects: ['shape-2'],- type: DrawingApplyType.INSERT,- }, undefined);-- expect(InsertSheetDrawingCommand.handler(accessor, undefined)).toBe(false);+ testBed.univer.dispose();});});diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/insert-image.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/insert-image.command.spec.tsnew file mode 100644index 0000000000..92ae4202a7--- /dev/null+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/insert-image.command.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 { Inject } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';+import { SheetDrawingUpdateController } from '../../../controllers/sheet-drawing-update.controller';+import { InsertCellImageCommand, InsertFloatImageCommand } from '../insert-image.command';++class TestSheetDrawingUpdateController {+ private _floatImages: string[] = [];+ private _cellImageCount = 0;+ private _filePickerCount = 0;+ private _failedFileNames = new Set<string>();++ failFile(name: string): void {+ this._failedFileNames.add(name);+ }++ get floatImages(): string[] {+ return this._floatImages;+ }++ get cellImageCount(): number {+ return this._cellImageCount;+ }++ get filePickerCount(): number {+ return this._filePickerCount;+ }++ async insertFloatImage(): Promise<boolean> {+ this._filePickerCount += 1;+ this._floatImages.push('picked-file');+ return true;+ }++ async insertFloatImageByFile(file: File): Promise<boolean> {+ if (this._failedFileNames.has(file.name)) {+ return false;+ }+ this._floatImages.push(file.name);+ return true;+ }++ async insertCellImage(): Promise<boolean> {+ this._cellImageCount += 1;+ return true;+ }+}++class TestRenderManagerService {+ constructor(+ @Inject(TestSheetDrawingUpdateController) private readonly _controller: TestSheetDrawingUpdateController+ ) {}++ get controller(): TestSheetDrawingUpdateController {+ return this._controller;+ }++ getRenderUnitById() {+ return {+ with: (token: unknown) => {+ if (token === SheetDrawingUpdateController) {+ return this._controller;+ }++ return null;+ },+ };+ }++ getRenderById() {+ return this.getRenderUnitById();+ }+}++function createImageFile(name: string): File {+ return new File(['image'], name, { type: 'image/png' });+}++describe('insert image commands', () => {+ afterEach(() => {+ // each test disposes its own univer instance+ });++ it('inserts every selected file as a floating image', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [TestSheetDrawingUpdateController],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;+ testBed.commandService.registerCommand(InsertFloatImageCommand);++ expect(await testBed.commandService.executeCommand(InsertFloatImageCommand.id, {+ files: [+ createImageFile('first.png'),+ createImageFile('second.png'),+ ],+ })).toBe(true);++ expect(renderManagerService.controller.floatImages).toEqual(['first.png', 'second.png']);++ testBed.univer.dispose();+ });++ it('returns false when one selected floating image fails to insert', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [TestSheetDrawingUpdateController],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;+ renderManagerService.controller.failFile('broken.png');+ testBed.commandService.registerCommand(InsertFloatImageCommand);++ expect(await testBed.commandService.executeCommand(InsertFloatImageCommand.id, {+ files: [+ createImageFile('ok.png'),+ createImageFile('broken.png'),+ ],+ })).toBe(false);+ expect(renderManagerService.controller.floatImages).toEqual(['ok.png']);++ testBed.univer.dispose();+ });++ it('opens the floating image picker when no files are provided', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [TestSheetDrawingUpdateController],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;+ testBed.commandService.registerCommand(InsertFloatImageCommand);++ expect(await testBed.commandService.executeCommand(InsertFloatImageCommand.id, { files: null })).toBe(true);+ expect(renderManagerService.controller.filePickerCount).toBe(1);+ expect(renderManagerService.controller.floatImages).toEqual(['picked-file']);++ testBed.univer.dispose();+ });++ it('inserts an image into the selected cell', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [TestSheetDrawingUpdateController],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const renderManagerService = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;+ testBed.commandService.registerCommand(InsertCellImageCommand);++ expect(await testBed.commandService.executeCommand(InsertCellImageCommand.id)).toBe(true);+ expect(renderManagerService.controller.cellImageCount).toBe(1);++ testBed.univer.dispose();+ });+});diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/save-cell-images.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/save-cell-images.command.spec.tsnew file mode 100644index 0000000000..9f85348dd1--- /dev/null+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/save-cell-images.command.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 { IDisposable, IRange } from '@univerjs/core';+import type { IBatchSaveImagesConfig, ICellImageInfo } from '../../../services/batch-save-images.service';+import { Disposable, ImageSourceType, toDisposable } from '@univerjs/core';+import { IDialogService } from '@univerjs/ui';+import { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';+import { IBatchSaveImagesService } from '../../../services/batch-save-images.service';+import { BATCH_SAVE_IMAGES_DIALOG_ID } from '../../../views/batch-save-images/component-name';+import { SaveCellImagesCommand } from '../save-cell-images.command';++class TestDialogService extends Disposable implements IDialogService {+ private _dialogs: any[] = [];+ private readonly _dialogs$ = new BehaviorSubject<any[]>([]);++ open(params: any): IDisposable {+ this._dialogs.push(params);+ this._dialogs$.next(this._dialogs);++ return toDisposable(() => this.close(params.id));+ }++ close(id: string): void {+ const dialogs = [];+ for (const dialog of this._dialogs) {+ if (dialog.id !== id) {+ dialogs.push(dialog);+ }+ }+ this._dialogs = dialogs;+ this._dialogs$.next(this._dialogs);+ }++ closeAll(expectIds?: string[]): void {+ if (!expectIds) {+ this._dialogs = [];+ this._dialogs$.next([]);+ return;+ }++ const dialogs = [];+ for (const dialog of this._dialogs) {+ if (expectIds.includes(dialog.id)) {+ dialogs.push(dialog);+ }+ }+ this._dialogs = dialogs;+ this._dialogs$.next(this._dialogs);+ }++ getDialogs$() {+ return this._dialogs$.asObservable();+ }++ get dialogs() {+ return this._dialogs;+ }++ override dispose(): void {+ super.dispose();+ this._dialogs$.complete();+ this._dialogs = [];+ }+}++class TestBatchSaveImagesService implements IBatchSaveImagesService {+ private _images: ICellImageInfo[] = [];+ private _downloaded: ICellImageInfo[] = [];+ private _downloadFails = false;++ setImages(images: ICellImageInfo[]): void {+ this._images = images;+ }++ failDownload(): void {+ this._downloadFails = true;+ }++ get downloaded(): ICellImageInfo[] {+ return this._downloaded;+ }++ getCellImagesInSelection(): ICellImageInfo[] {+ return this._images;+ }++ getCellImagesFromRanges(_unitId: string, _subUnitId: string, _ranges: IRange[]): ICellImageInfo[] {+ return this._images;+ }++ getDataColumns(): Array<{ index: number; label: string }> {+ return [];+ }++ getDataColumnsForRanges(): Array<{ index: number; label: string }> {+ return [];+ }++ getSelectionRangeNotation(): string {+ return 'A1:B2';+ }++ generateFileName(imageInfo: ICellImageInfo): string {+ return imageInfo.cellAddress;+ }++ generateFileNameWithContext(imageInfo: ICellImageInfo): string {+ return imageInfo.cellAddress;+ }++ async saveImages(_images: ICellImageInfo[], _config: IBatchSaveImagesConfig): Promise<void> {+ return undefined;+ }++ async saveImagesWithContext(_images: ICellImageInfo[], _config: IBatchSaveImagesConfig): Promise<void> {+ return undefined;+ }++ async downloadSingleImage(imageInfo: ICellImageInfo): Promise<void> {+ if (this._downloadFails) {+ throw new Error('download failed');+ }+ this._downloaded.push(imageInfo);+ }++ getSelectionRowRange(): { startRow: number; endRow: number } | null {+ return { startRow: 0, endRow: 1 };+ }++ getSelectionColumnIndices(): Set<number> {+ return new Set([0, 1]);+ }++ registerURLImageDownloader(): IDisposable {+ return toDisposable(() => undefined);+ }+}++function createImage(imageId: string, cellAddress: string): ICellImageInfo {+ return {+ row: 0,+ col: 0,+ cellAddress,+ imageId,+ source: `https://example.com/${imageId}.png`,+ imageSourceType: ImageSourceType.URL,+ };+}++describe('SaveCellImagesCommand', () => {+ afterEach(() => {+ // each test disposes its own univer instance+ });++ it('downloads a single selected cell image directly', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [IDialogService, { useClass: TestDialogService }],+ [IBatchSaveImagesService, { useClass: TestBatchSaveImagesService }],+ ]);+ const batchSaveService = testBed.get(IBatchSaveImagesService) as TestBatchSaveImagesService;+ const dialogService = testBed.get(IDialogService) as unknown as TestDialogService;+ batchSaveService.setImages([createImage('image-1', 'A1')]);+ testBed.commandService.registerCommand(SaveCellImagesCommand);++ expect(await testBed.commandService.executeCommand(SaveCellImagesCommand.id)).toBe(true);+ expect(batchSaveService.downloaded).toEqual([expect.objectContaining({+ imageId: 'image-1',+ cellAddress: 'A1',+ })]);+ expect(dialogService.dialogs).toEqual([]);++ testBed.univer.dispose();+ });++ it('opens the batch save dialog for multiple selected images', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [IDialogService, { useClass: TestDialogService }],+ [IBatchSaveImagesService, { useClass: TestBatchSaveImagesService }],+ ]);+ const batchSaveService = testBed.get(IBatchSaveImagesService) as TestBatchSaveImagesService;+ const dialogService = testBed.get(IDialogService) as unknown as TestDialogService;+ batchSaveService.setImages([+ createImage('image-2', 'A1'),+ createImage('image-3', 'B2'),+ ]);+ testBed.commandService.registerCommand(SaveCellImagesCommand);++ expect(await testBed.commandService.executeCommand(SaveCellImagesCommand.id)).toBe(true);+ expect(dialogService.dialogs).toEqual([expect.objectContaining({+ id: BATCH_SAVE_IMAGES_DIALOG_ID,+ title: { title: 'sheets-drawing-ui.save.title (A1:B2)' },+ children: { label: BATCH_SAVE_IMAGES_DIALOG_ID },+ })]);+ dialogService.dialogs[0].onClose();+ expect(dialogService.dialogs).toEqual([]);++ testBed.univer.dispose();+ });++ it('returns false when the single image download fails', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [IDialogService, { useClass: TestDialogService }],+ [IBatchSaveImagesService, { useClass: TestBatchSaveImagesService }],+ ]);+ const batchSaveService = testBed.get(IBatchSaveImagesService) as TestBatchSaveImagesService;+ batchSaveService.setImages([createImage('image-4', 'C3')]);+ batchSaveService.failDownload();+ testBed.commandService.registerCommand(SaveCellImagesCommand);++ expect(await testBed.commandService.executeCommand(SaveCellImagesCommand.id)).toBe(false);+ expect(batchSaveService.downloaded).toEqual([]);++ testBed.univer.dispose();+ });+});diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.tsindex f6bb0bb94d..8847f757c6 100644--- a/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.ts@@ -15,22 +15,12 @@*/import { DrawingTypeEnum } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';-import { groupToUngroup, ungroupToGroup } from '../utils';--vi.mock('@univerjs/engine-render', () => ({- getGroupState: vi.fn(() => ({ left: 30, top: 40, width: 80, height: 60 })),- transformObjectOutOfGroup: vi.fn((transform, groupTransform) => ({- left: (transform.left ?? 0) + (groupTransform.left ?? 0),- top: (transform.top ?? 0) + (groupTransform.top ?? 0),- width: transform.width,- height: transform.height,- })),-}));+import { describe, expect, it } from 'vitest';+import { cloneGroupParams, groupToUngroup, ungroupToGroup } from '../utils';describe('sheets drawing command utils', () => {- it('restores grouped sheet drawings with the original base bound', () => {- expect(ungroupToGroup([+ it('restores grouped sheet drawings with bounds calculated from child transforms', () => {+ const grouped = ungroupToGroup([{parent: {unitId: 'book-1',@@ -39,65 +29,150 @@ describe('sheets drawing command utils', () => {groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },},children: [- { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'child-1', transform: { left: 2, top: 3 } },+ {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'child-1',+ transform: { left: 2, top: 3, width: 10, height: 20 },+ },+ {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'child-2',+ transform: { left: 20, top: 5, width: 5, height: 5 },+ },],},- ] as never)).toEqual([+ ] as never);++ expect(grouped).toHaveLength(1);+ expect(grouped[0].parent).toMatchObject({+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'group-1',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },+ transform: {+ left: 2,+ top: 3,+ width: 23,+ height: 20,+ },+ });+ expect(grouped[0].children[0]).toMatchObject({+ drawingId: 'child-1',+ groupId: 'group-1',+ transform: { left: 2, top: 3, width: 10, height: 20 },+ });+ expect(grouped[0].children[1]).toMatchObject({+ drawingId: 'child-2',+ groupId: 'group-1',+ });+ });++ it('ungroups sheet drawings back into standalone transforms in the parent coordinate space', () => {+ const ungrouped = groupToUngroup([{parent: {unitId: 'book-1',subUnitId: 'sheet-1',drawingId: 'group-1',- drawingType: DrawingTypeEnum.DRAWING_GROUP,- groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },transform: { left: 30, top: 40, width: 80, height: 60 },+ groupBaseBound: { left: 0, top: 0, width: 80, height: 60 },},children: [{unitId: 'book-1',subUnitId: 'sheet-1',drawingId: 'child-1',- transform: { left: 2, top: 3 },- groupId: 'group-1',+ transform: { left: 5, top: 6, width: 7, height: 8 },},],},- ]);+ ] as never);++ expect(ungrouped).toHaveLength(1);+ expect(ungrouped[0].parent).toEqual({+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'group-1',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ transform: { left: 0, top: 0 },+ });+ expect(ungrouped[0].children[0]).toMatchObject({+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'child-1',+ transform: {+ left: 35,+ top: 46,+ width: 7,+ height: 8,+ },+ groupId: undefined,+ });});- it('ungroups sheet drawings back into standalone transforms', () => {- expect(groupToUngroup([- {- parent: {+ it('clones nested group ids so pasted groups do not share original drawing ids', () => {+ const result = cloneGroupParams({+ nestedIdRecord: {+ 'group-root': {+ drawingId: 'group-root',+ children: ['group-child', 'shape-1'],+ },+ 'group-child': {+ drawingId: 'group-child',+ children: ['shape-2'],+ },+ },+ groups: [+ {unitId: 'book-1',subUnitId: 'sheet-1',- drawingId: 'group-1',- transform: { left: 30, top: 40, width: 80, height: 60 },- groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },+ drawingId: 'group-root',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,},- children: [- { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'child-1', transform: { left: 5, top: 6, width: 7, height: 8 } },- ],- },- ] as never)).toEqual([- {- parent: {+ {unitId: 'book-1',subUnitId: 'sheet-1',- drawingId: 'group-1',+ drawingId: 'group-child',+ groupId: 'group-root',drawingType: DrawingTypeEnum.DRAWING_GROUP,- transform: { left: 0, top: 0 },},- children: [- {- unitId: 'book-1',- subUnitId: 'sheet-1',- drawingId: 'child-1',- transform: { left: 35, top: 46, width: 7, height: 8 },- groupId: undefined,- },- ],- },- ]);+ ],+ flatChildren: [+ {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'shape-1',+ groupId: 'group-root',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ },+ {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ drawingId: 'shape-2',+ groupId: 'group-child',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ },+ ],+ });++ const clonedRootId = result.idMap.get('group-root');+ const clonedChildGroupId = result.idMap.get('group-child');+ const clonedShapeId = result.idMap.get('shape-1');++ expect(clonedRootId).toBeDefined();+ expect(clonedRootId).not.toBe('group-root');+ expect(clonedChildGroupId).toBeDefined();+ expect(clonedShapeId).toBeDefined();+ const flatChildren = result.cloned.flatChildren!;+ expect(result.cloned.groups).toHaveLength(2);+ expect(flatChildren).toHaveLength(2);+ expect(result.cloned.groups[1].groupId).toBe(clonedRootId);+ expect(flatChildren[0].drawingId).toBe(clonedShapeId);+ expect(flatChildren[0].groupId).toBe(clonedRootId);+ expect(result.cloned.nestedIdRecord[clonedRootId!].children).toContain(clonedChildGroupId);+ expect(result.cloned.nestedIdRecord[clonedRootId!].children).toContain(clonedShapeId);});});diff --git a/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.ts b/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.tsindex 2b33a25df6..1404be83bb 100644--- a/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.ts@@ -14,56 +14,84 @@* limitations under the License.*/-import type { IAccessor, IDrawingSearch } from '@univerjs/core';-import { ICommandService } from '@univerjs/core';-import { SetDrawingSelectedOperation } from '@univerjs/drawing';-import { describe, expect, it, vi } from 'vitest';+import type { ISheetDrawing } from '@univerjs/sheets-drawing';+import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';+import { IDrawingManagerService } from '@univerjs/drawing';+import { InsertSheetDrawingCommand } from '@univerjs/sheets-drawing';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';import { EditSheetDrawingOperation } from '../edit-sheet-drawing.operation';import { SidebarSheetDrawingOperation } from '../open-drawing-panel.operation';+function createSheetDrawing(drawingId: string): ISheetDrawing {+ return {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.URL,+ source: `https://example.com/${drawingId}.png`,+ sheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ axisAlignSheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ };+}+describe('EditSheetDrawingOperation', () => {- it('returns false when there is no selected drawing', () => {- const commandService = {- syncExecuteCommand: vi.fn(),- executeCommand: vi.fn(),- };- const accessor = {- get(token: unknown) {- if (token === ICommandService) {- return commandService;- }+ afterEach(() => {+ // each test disposes its own univer instance+ });++ it('keeps focus and sidebar unchanged when no drawing is provided', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const drawingManagerService = testBed.get(IDrawingManagerService);+ testBed.commandService.registerCommand(EditSheetDrawingOperation);+ testBed.commandService.registerCommand(SidebarSheetDrawingOperation);- throw new Error(`Unknown dependency: ${String(token)}`);- },- } as IAccessor;+ expect(await testBed.commandService.executeCommand(EditSheetDrawingOperation.id, null as never)).toBe(false);+ expect(drawingManagerService.getFocusDrawings()).toEqual([]);+ expect(testBed.sidebarService.visible).toBe(false);- expect(EditSheetDrawingOperation.handler(accessor, null as never)).toBe(false);- expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();- expect(commandService.executeCommand).not.toHaveBeenCalled();+ testBed.univer.dispose();});- it('selects the drawing and opens the sheet sidebar editor', () => {- const commandService = {- syncExecuteCommand: vi.fn(() => true),- executeCommand: vi.fn(),- };- const accessor = {- get(token: unknown) {- if (token === ICommandService) {- return commandService;- }+ it('selects a drawing and opens the sheet drawing editor', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const drawingManagerService = testBed.get(IDrawingManagerService);+ testBed.commandService.registerCommand(EditSheetDrawingOperation);+ testBed.commandService.registerCommand(SidebarSheetDrawingOperation);++ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings: [createSheetDrawing('drawing-1')],+ });++ expect(await testBed.commandService.executeCommand(EditSheetDrawingOperation.id, {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ })).toBe(true);- throw new Error(`Unknown dependency: ${String(token)}`);- },- } as IAccessor;- const drawing: IDrawingSearch = {- unitId: 'book-1',- subUnitId: 'sheet-1',+ expect(drawingManagerService.getFocusDrawings()).toEqual([expect.objectContaining({drawingId: 'drawing-1',- };+ })]);+ expect(testBed.sidebarService.visible).toBe(true);- expect(EditSheetDrawingOperation.handler(accessor, drawing)).toBe(true);- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, [drawing]);- expect(commandService.executeCommand).toHaveBeenCalledWith(SidebarSheetDrawingOperation.id, { value: 'open' });+ testBed.univer.dispose();});});diff --git a/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts b/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.tsindex 0c31627e24..23d47f8139 100644--- a/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts@@ -14,61 +14,73 @@* limitations under the License.*/-import type { IAccessor } from '@univerjs/core';-import { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';-import { SetDrawingSelectedOperation } from '@univerjs/drawing';-import { getSheetCommandTarget } from '@univerjs/sheets';-import { ISidebarService } from '@univerjs/ui';-import { describe, expect, it, vi } from 'vitest';+import { DrawingTypeEnum } from '@univerjs/core';+import { IDrawingManagerService } from '@univerjs/drawing';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';import { COMPONENT_SHEET_DRAWING_PANEL } from '../../../views/sheet-image-panel/component-name';import { SidebarSheetDrawingOperation } from '../open-drawing-panel.operation';-vi.mock('@univerjs/sheets', async (importActual) => {- const actual = await importActual<typeof import('@univerjs/sheets')>();- return { ...actual, getSheetCommandTarget: vi.fn() };-});--const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);--function createAccessor() {- const sidebarService = { open: vi.fn(), close: vi.fn() };- const commandService = { syncExecuteCommand: vi.fn() };- const accessor = {- get(token: unknown) {- if (token === ISidebarService) return sidebarService;- if (token === LocaleService) return { t: (key: string) => key };- if (token === IUniverInstanceService) return {};- if (token === ICommandService) return commandService;- throw new Error(`Unknown dependency: ${String(token)}`);- },- } as IAccessor;+describe('SidebarSheetDrawingOperation', () => {+ afterEach(() => {+ // each test disposes its own univer instance+ });- return { accessor, sidebarService, commandService };-}+ it('opens the sheet drawing panel for the active worksheet', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ testBed.commandService.registerCommand(SidebarSheetDrawingOperation);-describe('SidebarSheetDrawingOperation', () => {- it('opens the sheet drawing panel and clears the selection on close', async () => {- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'book-1', subUnitId: 'sheet-1' } as never);- const { accessor, sidebarService, commandService } = createAccessor();+ expect(await testBed.commandService.executeCommand(SidebarSheetDrawingOperation.id, { value: 'open' })).toBe(true);- await expect(SidebarSheetDrawingOperation.handler(accessor, { value: 'open' })).resolves.toBe(true);- expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({+ expect(testBed.sidebarService.visible).toBe(true);+ expect(testBed.sidebarService.options).toMatchObject({header: { title: 'sheets-drawing-ui.panel.title' },children: { label: COMPONENT_SHEET_DRAWING_PANEL },width: 360,- }));- const onClose = sidebarService.open.mock.calls[0][0].onClose;- onClose();- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, []);+ });++ testBed.univer.dispose();});- it('returns false without a sheet target and closes on non-open actions', async () => {- const { accessor, sidebarService } = createAccessor();- mockedGetSheetCommandTarget.mockReturnValue(null as never);- await expect(SidebarSheetDrawingOperation.handler(accessor, { value: 'open' })).resolves.toBe(false);+ it('clears the focused drawing when the panel is closed', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const drawingManagerService = testBed.get(IDrawingManagerService);+ testBed.commandService.registerCommand(SidebarSheetDrawingOperation);++ drawingManagerService.registerDrawingData(testBed.unitId, {+ [testBed.subUnitId]: {+ 'drawing-1': {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ },+ },+ } as never);+ drawingManagerService.focusDrawing([{+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ }]);++ await testBed.commandService.executeCommand(SidebarSheetDrawingOperation.id, { value: 'open' });+ testBed.sidebarService.close();++ expect(drawingManagerService.getFocusDrawings()).toEqual([]);++ testBed.univer.dispose();+ });++ it('closes the panel for non-open actions', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ testBed.commandService.registerCommand(SidebarSheetDrawingOperation);++ await testBed.commandService.executeCommand(SidebarSheetDrawingOperation.id, { value: 'open' });+ expect(testBed.sidebarService.visible).toBe(true);++ expect(await testBed.commandService.executeCommand(SidebarSheetDrawingOperation.id, { value: 'close' })).toBe(true);+ expect(testBed.sidebarService.visible).toBe(false);- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'book-1', subUnitId: 'sheet-1' } as never);- await expect(SidebarSheetDrawingOperation.handler(accessor, { value: 'close' })).resolves.toBe(true);- expect(sidebarService.close).toHaveBeenCalledTimes(1);+ testBed.univer.dispose();});});diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.tsx b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.tssimilarity index 89%rename from packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.tsxrename to packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.tsindex 4903bb6f3a..c692dafb63 100644--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.tsx+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts@@ -16,17 +16,13 @@import type { IRange } from '@univerjs/core';import type { IFloatDomData } from '@univerjs/sheets-drawing';-import type { ComponentType } from '@univerjs/ui';-import type { IPrintingFloatDomProps } from '../views/PrintingFloatDom';import { Disposable, DrawingTypeEnum, Inject, Injector, PRINT_CHART_COMPONENT_KEY, Tools } from '@univerjs/core';-import { render, unmount } from '@univerjs/design';import { IDrawingManagerService } from '@univerjs/drawing';import { DrawingRenderService } from '@univerjs/drawing-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { SheetPrintInterceptorService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';-import { ComponentManager, connectInjector } from '@univerjs/ui';-import { SheetCanvasFloatDomManagerService } from '../services/canvas-float-dom-manager.service';-import { PrintingFloatDom } from '../views/PrintingFloatDom';+import { ComponentManager } from '@univerjs/ui';+import { mountPrintingFloatDom } from '../views/PrintingFloatDom';export class SheetDrawingPrintingController extends Disposable {constructor(@@ -34,7 +30,6 @@ export class SheetDrawingPrintingController extends Disposable {@Inject(DrawingRenderService) private readonly _drawingRenderService: DrawingRenderService,@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @Inject(SheetCanvasFloatDomManagerService) private readonly _canvasFloatDomManagerService: SheetCanvasFloatDomManagerService,@Inject(ComponentManager) private readonly _componetManager: ComponentManager,@Inject(Injector) private readonly _injector: Injector) {@@ -153,15 +148,19 @@ export class SheetDrawingPrintingController extends Disposable {return null;}).filter(Boolean) as IFloatDomData[];- const PrintingFloatDomInjector = connectInjector(PrintingFloatDom, this._injector) as ComponentType<IPrintingFloatDomProps>;-- render(- <PrintingFloatDomInjector floatDomInfos={floatDomInfos} scene={pos.scene} skeleton={pos.skeleton} worksheet={pos.worksheet} />,- pos.root+ const unmountPrintingFloatDom = mountPrintingFloatDom(+ {+ floatDomInfos,+ scene: pos.scene,+ skeleton: pos.skeleton,+ worksheet: pos.worksheet,+ },+ pos.root,+ this._injector);disposableCollection?.add(() => {- unmount(pos.root);+ unmountPrintingFloatDom();});return next(disposableCollection);diff --git a/packages/sheets-drawing-ui/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets-drawing-ui/src/facade/__tests__/f-worksheet.spec.tsindex 5f6d08d9cc..6178f338d9 100644--- a/packages/sheets-drawing-ui/src/facade/__tests__/f-worksheet.spec.ts+++ b/packages/sheets-drawing-ui/src/facade/__tests__/f-worksheet.spec.ts@@ -14,26 +14,782 @@* limitations under the License.*/-import { describe, expect, it, vi } from 'vitest';-import { SheetCanvasFloatDomManagerService } from '../../services/canvas-float-dom-manager.service';-import { FWorksheetDrawingUIMixin } from '../f-worksheet';+import type { Dependency, ICellData, IDrawingParam, IWorkbookData, Workbook } from '@univerjs/core';+import type { IRender, Rect, Scene } from '@univerjs/engine-render';+import type { ISheetFloatDom, ISheetImage } from '@univerjs/sheets-drawing';+import {+ Disposable,+ DrawingTypeEnum,+ EventSubject,+ ICommandService,+ ILogService,+ ImageSourceType,+ Inject,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ IURLImageService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ Tools,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import { IDrawingManagerService, UniverDrawingPlugin } from '@univerjs/drawing';+import { IRenderManagerService, RenderManagerService, SpreadsheetSkeleton } from '@univerjs/engine-render';+import { UniverSheetsPlugin } from '@univerjs/sheets';+import {+ InsertSheetDrawingCommand,+ ISheetDrawingService,+ RemoveSheetDrawingCommand,+ SetSheetDrawingCommand,+ UniverSheetsDrawingPlugin,+} from '@univerjs/sheets-drawing';+import {+ BatchSaveImagesService,+ IBatchSaveImagesService,+ SheetCanvasFloatDomManagerService,+} from '@univerjs/sheets-drawing-ui';+import { ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import sheetsEnUS from '@univerjs/sheets/locale/en-US';+import { CanvasFloatDomService, ComponentManager } from '@univerjs/ui';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import '@univerjs/sheets/facade';+import '@univerjs/sheets-drawing-ui/facade';-describe('FWorksheetDrawingUIMixin', () => {- it('delegates float dom removal to the manager service', () => {- const removeFloatDom = vi.fn();+const TEST_WORKBOOK_DATA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ },+};- const instance = Object.create(FWorksheetDrawingUIMixin.prototype) as any;- instance._injector = {- get: (token: unknown) => {- if (token === SheetCanvasFloatDomManagerService) {- return { removeFloatDom };- }+function createDrawingUITestBed(dependencies: Dependency[] = []) {+ const univer = new Univer();+ const injector = univer.__getInjector();+ const get = injector.get.bind(injector);- throw new Error('unexpected token');+ class TestPlugin extends Plugin {+ static override pluginName = 'test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.get(IUndoRedoService);++ const baseDependencies: Dependency[] = [+ [ComponentManager],+ [CanvasFloatDomService],+ [IBatchSaveImagesService, { useClass: BatchSaveImagesService }],+ [SheetCanvasFloatDomManagerService],+ ...dependencies,+ ];+ if (!hasDependency(dependencies, IRenderManagerService)) {+ baseDependencies.unshift([IRenderManagerService, { useClass: RenderManagerService }]);+ }+ baseDependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ univer.registerPlugin(UniverSheetsPlugin);+ univer.registerPlugin(UniverDrawingPlugin);+ univer.registerPlugin(UniverSheetsDrawingPlugin);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ Tools.deepClone(TEST_WORKBOOK_DATA)+ );++ get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ get(ILogService).setLogLevel(LogLevel.SILENT);++ const localeService = get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: sheetsEnUS });+ localeService.setLocale(LocaleType.EN_US);++ return {+ univer,+ injector,+ workbook,+ };+}++function hasDependency(dependencies: Dependency[], token: unknown): boolean {+ for (const dependency of dependencies) {+ if (Array.isArray(dependency) && dependency[0] === token) {+ return true;+ }+ }++ return false;+}++class TestRenderManagerService extends Disposable implements Partial<IRenderManagerService> {+ private _render: IRender | null = null;+ readonly createRender$ = new Subject<string>();+ readonly created$ = new Subject<IRender>();+ readonly disposed$ = new Subject<string>();++ configure(render: IRender): void {+ this._render = render;+ }++ getRenderById(): IRender | null {+ return this._render;+ }++ getRenderUnitById(): IRender | null {+ return this._render;+ }++ has(): boolean {+ return this._render != null;+ }++ getRenderAll(): Map<string, IRender> {+ const renderMap = new Map<string, IRender>();+ if (this._render) {+ renderMap.set(this._render.unitId, this._render);+ }+ return renderMap;+ }+}++class TestSheetSkeletonManager {+ readonly currentSkeleton$: BehaviorSubject<{ sheetId: string } | null>;++ constructor(private readonly _skeleton: SpreadsheetSkeleton) {+ this.currentSkeleton$ = new BehaviorSubject<{ sheetId: string } | null>({ sheetId: 'sheet1' });+ }++ getSkeletonParam() {+ return {+ sheetId: 'sheet1',+ skeleton: this._skeleton,+ };+ }+}++class TestSheetSelectionRenderService {+ getCellWithCoordByOffset(x: number, y: number) {+ const column = Math.max(0, Math.floor(x / 72));+ const row = Math.max(0, Math.floor(y / 24));+ return {+ actualColumn: column,+ actualRow: row,+ startColumn: column,+ endColumn: column,+ startRow: row,+ endRow: row,+ startX: column * 72,+ endX: (column + 1) * 72,+ startY: row * 24,+ endY: (row + 1) * 24,+ isMerged: false,+ isMergedMainCell: false,+ };+ }+}++class TestRenderScene {+ private readonly _objects = new Map<string, Rect>();+ readonly onScrollAfter$ = new EventSubject();+ private readonly _transformer = {+ clearControlByIds: () => undefined,+ clearSelectedObjects: () => undefined,+ debounceRefreshControls: () => undefined,+ };++ getAncestorScale() {+ return { scaleX: 1, scaleY: 1 };+ }++ getViewport() {+ return {+ left: 0,+ top: 0,+ right: 360,+ bottom: 220,+ viewportScrollX: 0,+ viewportScrollY: 0,+ onScrollAfter$: this.onScrollAfter$,+ };+ }++ getMainViewport() {+ return this.getViewport();+ }++ getTransformerByCreate() {+ return this._transformer;+ }++ getTransformer() {+ return this._transformer;+ }++ addObject(object: Rect) {+ this._objects.set(object.oKey, object);+ }++ removeObject(object: Rect) {+ this._objects.delete(object.oKey);+ }++ getObject(key: string) {+ return this._objects.get(key);+ }++ attachTransformerTo() { }++ detachTransformerFrom() { }+}++function createRender(skeleton: SpreadsheetSkeleton, scene: Scene): IRender {+ const sheetSkeletonManager = new TestSheetSkeletonManager(skeleton);+ const sheetSelectionRenderService = new TestSheetSelectionRenderService();+ const canvasElement = document.createElement('div');+ const activated$ = new BehaviorSubject(true);++ return {+ unitId: 'test',+ type: UniverInstanceType.UNIVER_SHEET,+ engine: {+ clientRect$: new BehaviorSubject({ width: 360, height: 220 }),+ getCanvasElement: () => canvasElement,+ } as unknown as IRender['engine'],+ scene,+ mainComponent: null,+ components: new Map(),+ isMainScene: true,+ render: { scene },+ activated$,+ with: (dependency: unknown) => {+ if (dependency === SheetSkeletonManagerService) {+ return sheetSkeletonManager;+ }+ if (dependency === ISheetSelectionRenderService) {+ return sheetSelectionRenderService;+ }+ return null;+ },+ deactivate: () => activated$.next(false),+ activate: () => activated$.next(true),+ isDisposed: () => false,+ } as unknown as IRender;+}++describe('sheets-drawing-ui facade', () => {+ let univer: Univer;+ let injector: Injector;+ let univerAPI: FUniver;++ beforeEach(() => {+ const testBed = createDrawingUITestBed();+ univer = testBed.univer;+ injector = testBed.injector;+ univerAPI = FUniver.newAPI(injector);+ });++ afterEach(() => {+ univer?.dispose();+ });++ it('uses real facade instances for empty float dom and cell image flows', async () => {+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const range = worksheet.getRange('A1:B2');++ expect(worksheet.getFloatDomById('missing')).toBeNull();+ expect(worksheet.getAllFloatDoms()).toEqual([]);+ expect(worksheet.removeFloatDom('missing')).toBe(worksheet);+ await expect(range.insertCellImageAsync('https://univer.ai/image.png')).resolves.toBe(false);+ await expect(range.saveCellImagesAsync()).resolves.toBe(false);+ await expect(worksheet.saveCellImagesAsync()).resolves.toBe(false);+ });++ it('registers a URL image downloader through the facade', async () => {+ const downloader = async (url: string) => `downloaded:${url}`;+ const disposable = univerAPI.registerURLImageDownloader(downloader);+ const urlImageService = injector.get(IURLImageService);++ await expect(urlImageService.getImage('https://univer.ai/image.png')).resolves.toBe('downloaded:https://univer.ai/image.png');+ disposable.dispose();+ await expect(urlImageService.getImage('https://univer.ai/image.png')).resolves.toBe('https://univer.ai/image.png');+ });++ it('adds, updates and removes float doms through worksheet facade state', async () => {+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();++ const added = worksheet.addFloatDomToPosition({+ componentKey: 'OrderCard',+ initPosition: {+ startX: 20,+ startY: 30,+ endX: 140,+ endY: 90,},+ data: { label: 'Draft order' },+ allowTransform: true,+ }, 'order-card');+ await Promise.resolve();++ expect(added).toBeNull();+ expect(injector.get(IDrawingManagerService).getDrawingByParam({+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'order-card',+ })).toBeUndefined();++ expect(worksheet.addFloatDomToRange(worksheet.getRange('A1:B2'), {+ componentKey: 'RangeCard',+ data: { label: 'Range order' },+ }, {}, 'range-card')).toBeNull();+ expect(worksheet.addFloatDomToColumnHeader(1, {+ componentKey: 'HeaderCard',+ data: { label: 'Header order' },+ }, { width: 80, height: 24, marginX: 0, marginY: 0 }, 'header-card')).toBeNull();++ expect(worksheet.updateFloatDom('missing-dom', { data: { label: 'Ignored' } })).toBe(worksheet);+ expect(worksheet.batchUpdateFloatDoms([{ id: 'missing-dom', config: { data: { label: 'Ignored' } } }])).toBe(worksheet);++ worksheet.removeFloatDom('order-card');+ });++ it('adds, reads, updates, batch updates and disposes float doms through the worksheet facade', async () => {+ univer.dispose();+ const testBed = createDrawingUITestBed([+ [IRenderManagerService, { useClass: TestRenderManagerService }],+ ]);+ univer = testBed.univer;+ injector = testBed.injector;+ univerAPI = FUniver.newAPI(injector);++ const modelWorksheet = testBed.workbook.getActiveSheet();+ const skeleton = injector.createInstance(+ SpreadsheetSkeleton,+ modelWorksheet,+ testBed.workbook.getStyles()+ ).calculate() as SpreadsheetSkeleton;+ const renderManager = injector.get(IRenderManagerService) as unknown as TestRenderManagerService;+ renderManager.configure(createRender(skeleton, new TestRenderScene() as unknown as Scene));+ const sheetDrawingService = injector.get(ISheetDrawingService);+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();++ const primary = worksheet.addFloatDomToPosition({+ componentKey: 'OrderCard',+ initPosition: {+ startX: 72,+ startY: 24,+ endX: 172,+ endY: 64,+ },+ data: { label: 'Draft order' },+ allowTransform: true,+ }, 'order-card')!;+ const secondary = worksheet.addFloatDomToPosition({+ componentKey: 'StatusCard',+ initPosition: {+ startX: 144,+ startY: 48,+ endX: 244,+ endY: 88,+ },+ data: { label: 'Pending' },+ allowTransform: true,+ }, 'status-card')!;+ await Promise.resolve();++ expect(primary.id).toBe('order-card');+ expect(secondary.id).toBe('status-card');+ expect(worksheet.getFloatDomById('order-card')).toEqual(expect.objectContaining({+ id: 'order-card',+ componentKey: 'OrderCard',+ allowTransform: true,+ data: { label: 'Draft order' },+ position: expect.objectContaining({+ left: 72,+ top: 24,+ width: 100,+ height: 40,+ }),+ }));++ const allDoms = worksheet.getAllFloatDoms();+ const allDomIds: string[] = [];+ for (const dom of allDoms) {+ allDomIds.push(dom.id);+ }+ expect(allDomIds).toEqual(['order-card', 'status-card']);++ expect(worksheet.updateFloatDom('order-card', {+ componentKey: 'OrderCardUpdated',+ allowTransform: false,+ data: { label: 'Approved' },+ position: {+ left: 90,+ top: 36,+ width: 120,+ height: 50,+ },+ })).toBe(worksheet);+ expect(sheetDrawingService.getDrawingByParam({+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'order-card',+ })).toEqual(expect.objectContaining({+ componentKey: 'OrderCardUpdated',+ allowTransform: false,+ data: { label: 'Approved' },+ transform: expect.objectContaining({+ left: 90,+ top: 36,+ width: 120,+ height: 50,+ }),+ }));++ expect(worksheet.batchUpdateFloatDoms([+ {+ id: 'order-card',+ config: {+ data: { label: 'Shipped' },+ position: {+ left: 100,+ top: 40,+ width: 130,+ height: 54,+ },+ },+ },+ {+ id: 'status-card',+ config: {+ componentKey: 'StatusCardUpdated',+ data: { label: 'Done' },+ allowTransform: false,+ },+ },+ {+ id: 'missing-card',+ config: {+ data: { label: 'Ignored' },+ },+ },+ ])).toBe(worksheet);++ expect(worksheet.getFloatDomById('order-card')).toEqual(expect.objectContaining({+ componentKey: 'OrderCardUpdated',+ data: { label: 'Shipped' },+ }));+ expect(sheetDrawingService.getDrawingByParam({+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'order-card',+ })).toEqual(expect.objectContaining({+ transform: expect.objectContaining({+ left: 100,+ top: 40,+ width: 130,+ height: 54,+ }),+ }));+ expect(worksheet.getFloatDomById('status-card')).toEqual(expect.objectContaining({+ componentKey: 'StatusCardUpdated',+ allowTransform: false,+ data: { label: 'Done' },+ }));++ primary.dispose();+ expect(worksheet.getFloatDomById('order-card')).toBeNull();+ worksheet.removeFloatDom('status-card');+ expect(worksheet.getAllFloatDoms()).toEqual([]);+ });++ it('saves cell images from range and worksheet selections', async () => {+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const savedFiles: string[] = [];+ const clickedDownloads: string[] = [];+ const originalShowDirectoryPicker = window.showDirectoryPicker;+ const originalCreateObjectURL = URL.createObjectURL;+ const originalRevokeObjectURL = URL.revokeObjectURL;+ const originalClick = HTMLAnchorElement.prototype.click;++ window.showDirectoryPicker = async () => ({+ getFileHandle: async (name: string) => {+ savedFiles.push(name);+ return {+ createWritable: async () => ({+ write: async () => {},+ close: async () => {},+ }),+ };+ },+ }) as unknown as FileSystemDirectoryHandle;+ URL.createObjectURL = () => 'blob:cell-image';+ URL.revokeObjectURL = () => {};+ HTMLAnchorElement.prototype.click = function click() {+ clickedDownloads.push(this.download);+ };++ const model = worksheet.getWorkbook().getSheetBySheetId(worksheet.getSheetId())!;+ model.getCellMatrix().setValue(0, 0, createCellImage('image-a', 'data:image/png;base64,aGVsbG8='));+ model.getCellMatrix().setValue(1, 1, createCellImage('image-b', 'data:image/jpeg;base64,aGVsbG8='));+ model.getCellMatrix().setValue(0, 2, { v: 'Customer/West' });++ await expect(worksheet.getRange('A1').saveCellImagesAsync()).resolves.toBe(true);+ expect(clickedDownloads).toEqual(['A1.png']);++ await expect(worksheet.saveCellImagesAsync(undefined, [worksheet.getRange('A1')])).resolves.toBe(true);+ expect(clickedDownloads).toEqual(['A1.png', 'A1.png']);++ await expect(worksheet.getRange('A1:B2').saveCellImagesAsync({ useCellAddress: false, useColumnIndex: 2 })).resolves.toBe(true);+ expect(savedFiles).toEqual(['Customer_West.png', 'B2.jpg']);++ savedFiles.length = 0;+ await expect(worksheet.saveCellImagesAsync({ useCellAddress: true, useColumnIndex: 2 }, [worksheet.getRange('A1:B2')])).resolves.toBe(true);+ expect(savedFiles).toEqual(['A1_Customer_West.png', 'B2.jpg']);++ URL.createObjectURL = () => {+ throw new Error('download denied');+ };+ await expect(worksheet.getRange('A1').saveCellImagesAsync()).resolves.toBe(false);+ await expect(worksheet.saveCellImagesAsync(undefined, [worksheet.getRange('A1')])).resolves.toBe(false);++ URL.createObjectURL = () => 'blob:cell-image';+ window.showDirectoryPicker = async () => {+ throw new Error('directory denied');};+ await expect(worksheet.getRange('A1:B2').saveCellImagesAsync()).resolves.toBe(false);+ await expect(worksheet.saveCellImagesAsync(undefined, [worksheet.getRange('A1:B2')])).resolves.toBe(false);++ window.showDirectoryPicker = originalShowDirectoryPicker;+ URL.createObjectURL = originalCreateObjectURL;+ URL.revokeObjectURL = originalRevokeObjectURL;+ HTMLAnchorElement.prototype.click = originalClick;+ });++ it('emits float dom add, update and delete events from drawing commands', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const commandService = injector.get(ICommandService);+ const drawingManagerService = injector.get(IDrawingManagerService);+ const sheetDrawingService = injector.get(ISheetDrawingService);+ const floatDom = createFloatDom('float-dom-1');++ const logs: string[] = [];+ const disposables = [+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomAdd, ({ drawings }) => logs.push(`before-add:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.FloatDomAdded, ({ drawings }) => logs.push(`add:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomUpdate, ({ drawings }) => logs.push(`before-update:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.FloatDomUpdated, ({ drawings }) => logs.push(`update:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomDelete, ({ drawings }) => logs.push(`before-delete:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.FloatDomDeleted, ({ drawings }) => logs.push(`delete:${drawings[0]}`)),+ ];++ commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, {+ unitId: workbook.getId(),+ drawings: [floatDom],+ });+ drawingManagerService.registerDrawingData('test', sheetDrawingService.getDrawingDataForUnit('test') as Record<string, { data: Record<string, IDrawingParam>; order: string[] }>);+ drawingManagerService.initializeNotification('test');+ expect(commandService.syncExecuteCommand(SetSheetDrawingCommand.id, {+ unitId: workbook.getId(),+ subUnitId: 'sheet1',+ drawings: [{ ...floatDom, transform: { ...floatDom.transform, left: 24 }, data: { label: 'Updated order' } }],+ })).toBe(true);+ expect(commandService.syncExecuteCommand(RemoveSheetDrawingCommand.id, {+ unitId: workbook.getId(),+ subUnitId: 'sheet1',+ drawings: [{ unitId: workbook.getId(), subUnitId: 'sheet1', drawingId: floatDom.drawingId, drawingType: DrawingTypeEnum.DRAWING_DOM }],+ })).toBe(true);++ expect(logs).toEqual([+ 'before-add:float-dom-1',+ 'add:float-dom-1',+ 'before-update:float-dom-1',+ 'update:float-dom-1',+ 'before-delete:float-dom-1',+ 'delete:float-dom-1',+ ]);++ disposables.forEach((disposable) => disposable.dispose());+ });++ it('cancels float dom commands before they mutate drawing state', () => {+ const commandService = injector.get(ICommandService);+ const drawingManagerService = injector.get(IDrawingManagerService);+ const sheetDrawingService = injector.get(ISheetDrawingService);+ const floatDom = createFloatDom('guarded-dom');+ const disposables = [+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomAdd, (event) => {+ if (event.drawings[0].drawingId === 'guarded-dom') event.cancel = true;+ }),+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomUpdate, (event) => {+ if (event.drawings[0].drawingId === 'existing-dom') event.cancel = true;+ }),+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomDelete, (event) => {+ if (event.drawings[0].drawingId === 'existing-dom') event.cancel = true;+ }),+ ];++ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [floatDom],+ })).toBe(false);+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'guarded-dom' })).toBeUndefined();- expect(instance.removeFloatDom('float-dom-1')).toBe(instance);- expect(removeFloatDom).toHaveBeenCalledWith('float-dom-1');+ const existing = createFloatDom('existing-dom');+ sheetDrawingService.registerDrawingData('test', {+ sheet1: { data: { [existing.drawingId]: existing }, order: [existing.drawingId] },+ });+ drawingManagerService.registerDrawingData('test', {+ sheet1: { data: { [existing.drawingId]: existing as unknown as IDrawingParam }, order: [existing.drawingId] },+ });+ drawingManagerService.initializeNotification('test');++ expect(commandService.syncExecuteCommand(SetSheetDrawingCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawings: [{ ...existing, data: { label: 'Blocked update' } }],+ })).toBe(false);+ expect((sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'existing-dom' }) as ISheetFloatDom | undefined)?.data)+ .toEqual({ label: 'Order card' });++ expect(commandService.syncExecuteCommand(RemoveSheetDrawingCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawings: [{ unitId: 'test', subUnitId: 'sheet1', drawingId: 'existing-dom', drawingType: DrawingTypeEnum.DRAWING_DOM }],+ })).toBe(false);+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'existing-dom' })).toBeDefined();++ disposables.forEach((disposable) => disposable.dispose());+ });++ it('does not emit float dom events for over-grid image drawing commands', () => {+ const commandService = injector.get(ICommandService);+ const sheetDrawingService = injector.get(ISheetDrawingService);+ const image = createOverGridImage('image-drawing');+ const logs: string[] = [];+ const disposables = [+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomAdd, ({ drawings }) => logs.push(`before-add:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.FloatDomAdded, ({ drawings }) => logs.push(`add:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomUpdate, ({ drawings }) => logs.push(`before-update:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.FloatDomUpdated, ({ drawings }) => logs.push(`update:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeFloatDomDelete, ({ drawings }) => logs.push(`before-delete:${drawings[0].drawingId}`)),+ univerAPI.addEvent(univerAPI.Event.FloatDomDeleted, ({ drawings }) => logs.push(`delete:${drawings[0]}`)),+ ];++ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id)).toBe(false);+ expect(commandService.syncExecuteCommand(SetSheetDrawingCommand.id)).toBe(false);+ expect(commandService.syncExecuteCommand(RemoveSheetDrawingCommand.id)).toBe(false);++ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [image],+ })).toBe(true);+ expect(commandService.syncExecuteCommand(SetSheetDrawingCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawings: [{ ...image, source: 'data:image/png;base64,Zm9v' }],+ })).toBe(true);+ expect(commandService.syncExecuteCommand(RemoveSheetDrawingCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawings: [{ unitId: 'test', subUnitId: 'sheet1', drawingId: image.drawingId, drawingType: DrawingTypeEnum.DRAWING_IMAGE }],+ })).toBe(true);++ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: image.drawingId })).toBeUndefined();+ expect(logs).toEqual([]);++ disposables.forEach((disposable) => disposable.dispose());});});++function createFloatDom(drawingId: string): ISheetFloatDom {+ return {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_DOM,+ componentKey: 'FloatDom',+ allowTransform: true,+ data: { label: 'Order card' },+ transform: {+ left: 10,+ top: 20,+ width: 120,+ height: 80,+ },+ sheetTransform: {+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ axisAlignSheetTransform: {+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ };+}++function createCellImage(drawingId: string, source: string): ICellData {+ return {+ p: {+ id: `${drawingId}-doc`,+ documentStyle: {},+ drawingsOrder: [drawingId],+ drawings: {+ [drawingId]: {+ drawingId,+ source,+ imageSourceType: ImageSourceType.BASE64,+ },+ },+ } as unknown as ICellData['p'],+ };+}++function createOverGridImage(drawingId: string): ISheetImage {+ return {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.BASE64,+ source: 'data:image/png;base64,aGVsbG8=',+ transform: {+ left: 10,+ top: 10,+ width: 20,+ height: 20,+ },+ sheetTransform: {+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 2, column: 2, rowOffset: 0, columnOffset: 0 },+ },+ axisAlignSheetTransform: {+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 2, column: 2, rowOffset: 0, columnOffset: 0 },+ },+ };+}diff --git a/packages/sheets-drawing-ui/src/facade/f-univer.ts b/packages/sheets-drawing-ui/src/facade/f-univer.tsindex 320dd32a4c..903743b7e1 100644--- a/packages/sheets-drawing-ui/src/facade/f-univer.ts+++ b/packages/sheets-drawing-ui/src/facade/f-univer.ts@@ -254,9 +254,21 @@ export class FUniverSheetsDrawingUIMixin extends FUniver implements IFUniverShee}const { drawings } = params;+ const floatDomDrawingIds: string[] = [];+ for (let i = 0; i < drawings.length; i++) {+ const drawing = drawings[i];+ if (drawing.drawingType === DrawingTypeEnum.DRAWING_DOM) {+ floatDomDrawingIds.push(drawing.drawingId);+ }+ }++ if (floatDomDrawingIds.length === 0) {+ return;+ }+const eventParams: IFloatDomDeletedEventParams = {workbook,- drawings: drawings.filter((i) => i.drawingType === DrawingTypeEnum.DRAWING_DOM).map((i) => i.drawingId),+ drawings: floatDomDrawingIds,};this.fireEvent(this.Event.FloatDomDeleted, eventParams);})diff --git a/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.ts b/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.tsindex cc260cfd89..94d1088357 100644--- a/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.ts+++ b/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.ts@@ -14,80 +14,134 @@* limitations under the License.*/-import { ImageSourceType, UniverInstanceType } from '@univerjs/core';-import { describe, expect, it } from 'vitest';-import { BatchSaveImagesService, FileNamePart } from '../batch-save-images.service';--function createService() {- const cells = new Map<string, unknown>([- ['0:0', {- p: {- drawingsOrder: ['img-a1'],- drawings: {- 'img-a1': {- drawingId: 'img-a1',- source: 'data:image/png;base64,aaa',- imageSourceType: ImageSourceType.BASE64,- },+import type { ICellData, IWorkbookData } from '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import { BooleanNumber, ImageSourceType, LocaleType } from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../__tests__/create-sheets-drawing-ui-test-bed';+import { BatchSaveImagesService, FileNamePart, IBatchSaveImagesService } from '../batch-save-images.service';++const WORKBOOK_DATA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: createImageCell('img-a1', 'data:image/png;base64,aGVsbG8=', ImageSourceType.BASE64),+ 3: { v: 'Report:Q1' },},- },- }],- ['1:1', {- p: {- drawingsOrder: ['img-b2'],- drawings: {- 'img-b2': {- drawingId: 'img-b2',- source: 'https://cdn.example.com/photo.jpeg?version=1',- imageSourceType: ImageSourceType.URL,- },+ 1: {+ 0: { v: 'Client/Name' },+ 1: createImageCell('img-b2', 'https://cdn.example.com/photo.jpeg?version=1', ImageSourceType.URL),+ 3: { p: { body: { dataStream: 'Summary' } } as ICellData['p'] },},},- }],- ['0:3', { v: 'Report:Q1' }],- ['1:0', { v: 'Client/Name' }],- ['1:3', { p: { body: { dataStream: 'Summary' } } }],- ]);+ hidden: BooleanNumber.FALSE,+ },+ },+};- const cellMatrix = {- getValue: (row: number, col: number) => cells.get(`${row}:${col}`) as never,- getDataRange: () => ({ startRow: 0, endRow: 2, startColumn: 0, endColumn: 3 }),+function createImageCell(drawingId: string, source: string, imageSourceType: ImageSourceType): ICellData {+ return {+ p: {+ id: `${drawingId}-doc`,+ documentStyle: {},+ drawingsOrder: [drawingId],+ drawings: {+ [drawingId]: {+ drawingId,+ source,+ imageSourceType,+ },+ },+ } as unknown as ICellData['p'],};- const worksheet = {- getCellMatrix: () => cellMatrix,+}++function createSelection(startRow: number, endRow: number, startColumn: number, endColumn: number): ISelectionWithStyle {+ return {+ range: {+ startRow,+ endRow,+ startColumn,+ endColumn,+ },+ primary: {+ actualRow: startRow,+ actualColumn: startColumn,+ startRow,+ endRow,+ startColumn,+ endColumn,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,};- const workbook = {- getActiveSheet: () => worksheet,- getSheetBySheetId: () => worksheet,+}++function setup() {+ const testBed = createSheetsDrawingUiTestBed(WORKBOOK_DATA, [+ [IBatchSaveImagesService, { useClass: BatchSaveImagesService }],+ ]);+ const service = testBed.get(IBatchSaveImagesService);+ const selectionsService = testBed.get(SheetsSelectionsService);+ selectionsService.setSelections([+ createSelection(0, 0, 0, 1),+ createSelection(1, 1, 1, 1),+ ]);++ return {+ ...testBed,+ service,+ selectionsService,};- const selections = [- { range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 } },- { range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },- ];-- return new BatchSaveImagesService(- {- getCurrentUnitOfType: (type: UniverInstanceType) => (type === UniverInstanceType.UNIVER_SHEET ? workbook : null),- getUnit: () => workbook,- } as never,- {- getCurrentSelections: () => selections,- } as never,- {} as never,- {} as never- );}describe('BatchSaveImagesService', () => {- it('collects cell images from current selections and exposes selection metadata', () => {- const service = createService();+ afterEach(() => {+ Reflect.deleteProperty(window, 'showDirectoryPicker');+ });++ it('collects images from the active selection and reports the selected address space', () => {+ const { service, univer } = setup();expect(service.getCellImagesInSelection()).toEqual([{row: 0,col: 0,cellAddress: 'A1',- source: 'data:image/png;base64,aaa',+ source: 'data:image/png;base64,aGVsbG8=',+ imageSourceType: ImageSourceType.BASE64,+ imageId: 'img-a1',+ },+ {+ row: 1,+ col: 1,+ cellAddress: 'B2',+ source: 'https://cdn.example.com/photo.jpeg?version=1',+ imageSourceType: ImageSourceType.URL,+ imageId: 'img-b2',+ },+ ]);+ expect(service.getCellImagesFromRanges('test', 'sheet1', [+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ ])).toEqual([+ {+ row: 0,+ col: 0,+ cellAddress: 'A1',+ source: 'data:image/png;base64,aGVsbG8=',imageSourceType: ImageSourceType.BASE64,imageId: 'img-a1',},@@ -103,10 +157,12 @@ describe('BatchSaveImagesService', () => {expect(service.getSelectionRangeNotation()).toBe('A1:B1, B2');expect(service.getSelectionRowRange()).toEqual({ startRow: 0, endRow: 1 });expect(Array.from(service.getSelectionColumnIndices()).sort((a, b) => a - b)).toEqual([0, 1]);++ univer.dispose();});- it('finds data columns outside the selection and builds sanitized file names', () => {- const service = createService();+ it('uses neighboring data columns to build spreadsheet-friendly image file names', () => {+ const { service, univer } = setup();const imageInfo = {row: 1,col: 1,@@ -119,6 +175,11 @@ describe('BatchSaveImagesService', () => {expect(service.getDataColumns()).toEqual([{ index: 3, label: 'D' },]);+ expect(service.getDataColumnsForRanges('test', 'sheet1', [+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ ])).toEqual([+ { index: 3, label: 'D' },+ ]);expect(service.generateFileName(imageInfo, {fileNameParts: [FileNamePart.COLUMN_VALUE, FileNamePart.CELL_ADDRESS],columnIndex: 0,@@ -126,6 +187,49 @@ describe('BatchSaveImagesService', () => {expect(service.generateFileNameWithContext(imageInfo, {fileNameParts: [FileNamePart.CELL_ADDRESS, FileNamePart.COLUMN_VALUE],columnIndex: 3,- }, 'book-1', 'sheet-1')).toBe('B2_Summary.jpeg');+ }, 'test', 'sheet1')).toBe('B2_Summary.jpeg');++ univer.dispose();+ });++ it('keeps every image when batch saving would otherwise produce duplicate file names', async () => {+ const { service, univer } = setup();+ const savedFiles: string[] = [];+ window.showDirectoryPicker = async () => ({+ getFileHandle: async (name: string) => {+ savedFiles.push(name);+ return {+ createWritable: async () => ({+ write: async () => undefined,+ close: async () => undefined,+ }),+ };+ },+ }) as unknown as FileSystemDirectoryHandle;++ await service.saveImages([+ {+ row: 0,+ col: 0,+ cellAddress: 'A1',+ source: 'data:image/png;base64,aGVsbG8=',+ imageSourceType: ImageSourceType.BASE64,+ imageId: 'img-a1',+ },+ {+ row: 0,+ col: 1,+ cellAddress: 'A1',+ source: 'data:image/png;base64,aGVsbG8=',+ imageSourceType: ImageSourceType.BASE64,+ imageId: 'img-a1-copy',+ },+ ], {+ fileNameParts: [FileNamePart.CELL_ADDRESS],+ });++ expect(savedFiles).toEqual(['A1.png', 'A1_1.png']);++ univer.dispose();});});diff --git a/packages/sheets-drawing-ui/src/services/__tests__/canvas-float-dom-manager.service.spec.ts b/packages/sheets-drawing-ui/src/services/__tests__/canvas-float-dom-manager.service.spec.tsindex c292dee1a7..613458a005 100644--- a/packages/sheets-drawing-ui/src/services/__tests__/canvas-float-dom-manager.service.spec.ts+++ b/packages/sheets-drawing-ui/src/services/__tests__/canvas-float-dom-manager.service.spec.ts@@ -14,78 +14,768 @@* limitations under the License.*/-import { DrawingApplyType, SetDrawingApplyMutation } from '@univerjs/sheets-drawing';-import { describe, expect, it, vi } from 'vitest';-import { SheetCanvasFloatDomManagerService } from '../canvas-float-dom-manager.service';--function createService(drawing: unknown) {- const dispose = vi.fn();- const removeObject = vi.fn();- const syncExecuteCommand = vi.fn(() => true);- const getDrawingByParam = vi.fn(() => drawing);- const getBatchRemoveOp = vi.fn(() => ({- unitId: 'unit-1',- subUnitId: 'sheet-1',- redo: ['redo-op'],- objects: ['object-1'],- }));- const service = Object.create(SheetCanvasFloatDomManagerService.prototype) as any;-- service._domLayerInfoMap = new Map([- ['float-dom-1', {- unitId: 'unit-1',- subUnitId: 'sheet-1',- dispose: { dispose },- rect: { id: 'rect-1' },- }],+import type { IWorkbookData } from '@univerjs/core';+import type { IRender, IRenderManagerService as IRenderManagerServiceType, Scene } from '@univerjs/engine-render';+import type { IFloatDom, IFloatDomLayout } from '@univerjs/ui';+import type { ICanvasFloatDomInfo } from '../canvas-float-dom-manager.service';+import {+ BooleanNumber,+ Disposable,+ DrawingTypeEnum,+ EventSubject,+ LifecycleService,+ LifecycleStages,+ LocaleType,+ UniverInstanceType,+} from '@univerjs/core';+import { IRenderManagerService, Rect, SHEET_VIEWPORT_KEY, SpreadsheetSkeleton } from '@univerjs/engine-render';+import { ISheetDrawingService, RemoveSheetDrawingCommand, SetSheetDrawingCommand } from '@univerjs/sheets-drawing';+import { ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { CanvasFloatDomService } from '@univerjs/ui';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../__tests__/create-sheets-drawing-ui-test-bed';+import {+ calcSheetFloatDomPosition,+ SheetCanvasFloatDomManagerService,+ transformBound2DOMBound,+} from '../canvas-float-dom-manager.service';++const BASE_WORKBOOK_DATA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ defaultColumnWidth: 72,+ defaultRowHeight: 24,+ rowHeader: { width: 46 },+ columnHeader: { height: 28 },+ cellData: {},+ hidden: BooleanNumber.FALSE,+ },+ },+};++function createWorkbookDataWithFreeze(): IWorkbookData {+ return {+ ...BASE_WORKBOOK_DATA,+ sheets: {+ sheet1: {+ ...BASE_WORKBOOK_DATA.sheets.sheet1,+ freeze: {+ startRow: 1,+ startColumn: 1,+ xSplit: 1,+ ySplit: 1,+ },+ },+ },+ };+}++function setup(workbookData: IWorkbookData = BASE_WORKBOOK_DATA) {+ const testBed = createSheetsDrawingUiTestBed(workbookData, [+ [IRenderManagerService, { useClass: TestRenderManagerService }],+ [CanvasFloatDomService],+ [SheetCanvasFloatDomManagerService],]);- service._drawingManagerService = { getDrawingByParam };- service._commandService = { syncExecuteCommand };- service._sheetDrawingService = { getBatchRemoveOp };- service._getSceneAndTransformerByDrawingSearch = vi.fn(() => ({- scene: { removeObject },- }));-- return { service, dispose, removeObject, syncExecuteCommand, getDrawingByParam, getBatchRemoveOp };+ const injector = testBed.injector;+ const worksheet = testBed.workbook.getActiveSheet();+ const skeleton = injector.createInstance(+ SpreadsheetSkeleton,+ worksheet,+ testBed.workbook.getStyles()+ ).calculate() as SpreadsheetSkeleton;+ const scene = createScene({+ left: 0,+ top: 0,+ right: 360,+ bottom: 220,+ viewportScrollX: 30,+ viewportScrollY: 18,+ });+ const renderManager = testBed.get(IRenderManagerService) as unknown as TestRenderManagerService;+ renderManager.configure(createRender(skeleton, scene));++ return {+ ...testBed,+ manager: testBed.get(SheetCanvasFloatDomManagerService),+ worksheet,+ skeleton,+ scene,+ };}-describe('SheetCanvasFloatDomManagerService', () => {- it('removes drawing-backed float doms through the shared remove path', () => {- const drawing = {- unitId: 'unit-1',- subUnitId: 'sheet-1',- drawingId: 'float-dom-1',+class TestRenderManagerService extends Disposable implements Partial<IRenderManagerServiceType> {+ private _render: IRender | null = null;+ readonly createRender$ = new Subject<string>();+ readonly created$ = new Subject<IRender>();+ readonly disposed$ = new Subject<string>();++ configure(render: IRender): void {+ this._render = render;+ }++ getRenderById(): IRender | null {+ return this._render;+ }++ getRenderUnitById(): IRender | null {+ return this._render;+ }++ has(): boolean {+ return this._render != null;+ }++ getRenderAll(): Map<string, IRender> {+ const renderMap = new Map<string, IRender>();+ if (this._render) {+ renderMap.set(this._render.unitId, this._render);+ }+ return renderMap;+ }+}++class TestSheetSkeletonManager {+ readonly currentSkeleton$: BehaviorSubject<{ sheetId: string } | null>;++ constructor(private readonly _skeleton: SpreadsheetSkeleton) {+ this.currentSkeleton$ = new BehaviorSubject<{ sheetId: string } | null>({ sheetId: 'sheet1' });+ }++ getSkeletonParam() {+ return {+ sheetId: 'sheet1',+ skeleton: this._skeleton,};- const { service, dispose, removeObject, syncExecuteCommand, getDrawingByParam, getBatchRemoveOp } = createService(drawing);-- service.removeFloatDom('float-dom-1');-- expect(dispose).toHaveBeenCalledTimes(1);- expect(removeObject).toHaveBeenCalledWith({ id: 'rect-1' });- expect(getDrawingByParam).toHaveBeenCalledWith({- unitId: 'unit-1',- subUnitId: 'sheet-1',- drawingId: 'float-dom-1',- });- expect(getBatchRemoveOp).toHaveBeenCalledWith([drawing]);- expect(syncExecuteCommand).toHaveBeenCalledWith(SetDrawingApplyMutation.id, {- unitId: 'unit-1',- subUnitId: 'sheet-1',- op: ['redo-op'],- objects: ['object-1'],- type: DrawingApplyType.REMOVE,- });- expect(service.getFloatDomInfo('float-dom-1')).toBeUndefined();+ }+}++class TestSheetSelectionRenderService {+ getCellWithCoordByOffset(x: number, y: number) {+ const column = Math.max(0, Math.floor(x / 72));+ const row = Math.max(0, Math.floor(y / 24));+ return {+ actualColumn: column,+ actualRow: row,+ startColumn: column,+ endColumn: column,+ startRow: row,+ endRow: row,+ startX: column * 72,+ endX: (column + 1) * 72,+ startY: row * 24,+ endY: (row + 1) * 24,+ isMerged: false,+ isMergedMainCell: false,+ };+ }+}++class TestRenderScene {+ private readonly _objects = new Map<string, Rect>();+ readonly canvasEvents: string[] = [];+ readonly onScrollAfter$ = new EventSubject();+ private readonly _transformer = {+ clearControlByIds: () => undefined,+ clearSelectedObjects: () => undefined,+ };++ constructor(private readonly _viewport: {+ left: number;+ top: number;+ right: number;+ bottom: number;+ viewportScrollX: number;+ viewportScrollY: number;+ onScrollAfter$?: EventSubject<unknown>;+ }) {+ this._viewport.onScrollAfter$ = this.onScrollAfter$;+ }++ getAncestorScale() {+ return { scaleX: 1, scaleY: 1 };+ }++ getViewport(key: string) {+ return key === SHEET_VIEWPORT_KEY.VIEW_MAIN ? this._viewport : null;+ }++ getMainViewport() {+ return this._viewport;+ }++ getTransformerByCreate() {+ return this._transformer;+ }++ getTransformer() {+ return this._transformer;+ }++ addObject(object: Rect) {+ this._objects.set(object.oKey, object);+ }++ removeObject(object: Rect) {+ this._objects.delete(object.oKey);+ }++ getObject(key: string) {+ return this._objects.get(key);+ }++ attachTransformerTo() { }++ detachTransformerFrom() { }++ scrollTo(viewportScrollX: number, viewportScrollY: number): void {+ this._viewport.viewportScrollX = viewportScrollX;+ this._viewport.viewportScrollY = viewportScrollY;+ this.onScrollAfter$.emitEvent({} as never);+ }+}++function createRender(skeleton: SpreadsheetSkeleton, scene: Scene): IRender {+ const sheetSkeletonManager = new TestSheetSkeletonManager(skeleton);+ const sheetSelectionRenderService = new TestSheetSelectionRenderService();+ const canvasElement = document.createElement('div');+ const testScene = scene as unknown as TestRenderScene;+ canvasElement.dispatchEvent = (event: Event) => {+ testScene.canvasEvents.push(event.type);+ return true;+ };+ const activated$ = new BehaviorSubject(true);++ return {+ unitId: 'test',+ type: UniverInstanceType.UNIVER_SHEET,+ engine: {+ clientRect$: new BehaviorSubject({ width: 360, height: 220 }),+ getCanvasElement: () => canvasElement,+ } as unknown as IRender['engine'],+ scene,+ mainComponent: null,+ components: new Map(),+ isMainScene: true,+ render: { scene },+ activated$,+ with: (dependency: unknown) => {+ if (dependency === SheetSkeletonManagerService) {+ return sheetSkeletonManager;+ }+ if (dependency === ISheetSelectionRenderService) {+ return sheetSelectionRenderService;+ }+ return null;+ },+ deactivate: () => activated$.next(false),+ activate: () => activated$.next(true),+ isDisposed: () => false,+ } as unknown as IRender;+}++function createScene(viewport: {+ left: number;+ top: number;+ right: number;+ bottom: number;+ viewportScrollX: number;+ viewportScrollY: number;+}): Scene {+ return new TestRenderScene(viewport) as unknown as Scene;+}++function expectLayout(layout: IFloatDomLayout, expected: IFloatDomLayout): void {+ expect(layout).toEqual(expected);+}++describe('SheetCanvasFloatDomManagerService', () => {+ const disposables: Array<ReturnType<typeof setup>> = [];++ afterEach(() => {+ while (disposables.length > 0) {+ const current = disposables.pop()!;+ current.univer.dispose();+ }+ });++ it('keeps a normal float dom inside the visible sheet area while the sheet scrolls', () => {+ const fixture = setup();+ disposables.push(fixture);+ const rect = new Rect('float-dom', {+ left: 80,+ top: 50,+ width: 100,+ height: 40,+ });++ expectLayout(calcSheetFloatDomPosition(rect, fixture.scene, fixture.skeleton, fixture.worksheet), {+ rotate: 0,+ startX: 50,+ startY: 32,+ endX: 150,+ endY: 72,+ width: 100,+ height: 40,+ absolute: {+ left: false,+ top: false,+ },+ });+ });++ it('does not scroll a float dom that belongs to the frozen first row and column', () => {+ const fixture = setup(createWorkbookDataWithFreeze());+ disposables.push(fixture);+ const rect = new Rect('frozen-float-dom', {+ left: 60,+ top: 34,+ width: 40,+ height: 12,+ });++ expectLayout(calcSheetFloatDomPosition(rect, fixture.scene, fixture.skeleton, fixture.worksheet), {+ rotate: 0,+ startX: 60,+ startY: 34,+ endX: 100,+ endY: 46,+ width: 40,+ height: 12,+ absolute: {+ left: true,+ top: true,+ },+ });+ });++ it('clips a partially hidden float dom to the sheet headers instead of letting it cover them', () => {+ const fixture = setup();+ disposables.push(fixture);++ expect(transformBound2DOMBound({+ left: 12,+ right: 70,+ top: 10,+ bottom: 64,+ }, fixture.scene, fixture.skeleton, fixture.worksheet)).toEqual({+ left: 46,+ right: 46,+ top: 28,+ bottom: 46,+ absolute: {+ left: false,+ top: false,+ },+ });+ });++ it('keeps float dom bounds stable when the main viewport is unavailable', () => {+ const fixture = setup();+ disposables.push(fixture);+ const scene = createScene({+ left: 0,+ top: 0,+ right: 360,+ bottom: 220,+ viewportScrollX: 30,+ viewportScrollY: 18,+ });+ scene.getViewport = () => undefined;++ expect(transformBound2DOMBound({+ left: 20,+ right: 120,+ top: 30,+ bottom: 90,+ }, scene, fixture.skeleton, fixture.worksheet)).toEqual({+ left: 20,+ right: 120,+ top: 30,+ bottom: 90,+ absolute: {+ left: true,+ top: true,+ },+ });+ });++ it('handles frozen panes when float doms cross or move past the frozen boundary', () => {+ const fixture = setup(createWorkbookDataWithFreeze());+ disposables.push(fixture);++ expect(transformBound2DOMBound({+ left: 100,+ right: 150,+ top: 44,+ bottom: 80,+ }, fixture.scene, fixture.skeleton, fixture.worksheet)).toEqual({+ left: 100,+ right: 120,+ top: 44,+ bottom: 62,+ absolute: {+ left: true,+ top: true,+ },+ });++ expect(transformBound2DOMBound({+ left: 140,+ right: 200,+ top: 70,+ bottom: 110,+ }, fixture.scene, fixture.skeleton, fixture.worksheet)).toEqual({+ left: 110,+ right: 170,+ top: 52,+ bottom: 92,+ absolute: {+ left: false,+ top: false,+ },+ });+ });++ it('can keep horizontal sheet coordinates fixed for vertically responsive float doms', () => {+ const fixture = setup();+ disposables.push(fixture);+ const floatDomInfo = {+ scrollDirectionResponse: 'VERTICAL',+ } as ICanvasFloatDomInfo;++ expect(transformBound2DOMBound({+ left: 100,+ right: 160,+ top: 90,+ bottom: 130,+ }, fixture.scene, fixture.skeleton, fixture.worksheet, floatDomInfo, true)).toEqual({+ left: 100,+ right: 160,+ top: 72,+ bottom: 112,+ absolute: {+ left: false,+ top: false,+ },+ });+ });++ it('adds range and column header float doms to the canvas layer and removes them through their disposables', () => {+ const fixture = setup();+ disposables.push(fixture);+ const canvasFloatDomService = fixture.get(CanvasFloatDomService);++ const rangeDom = fixture.manager.addFloatDomToRange({+ startRow: 1,+ endRow: 2,+ startColumn: 1,+ endColumn: 2,+ }, {+ componentKey: 'RangeCard',+ initPosition: { startX: 0, startY: 0, endX: 0, endY: 0 },+ data: { label: 'Range order' },+ allowTransform: true,+ eventPassThrough: true,+ }, {+ width: 80,+ height: 24,+ horizonOffsetAlign: 'right',+ verticalOffsetAlign: 'bottom',+ marginX: 4,+ marginY: 2,+ }, 'range-card')!;+ const headerDom = fixture.manager.addFloatDomToColumnHeader(2, {+ componentKey: 'ColumnHeaderCard',+ initPosition: { startX: 0, startY: 0, endX: 0, endY: 0 },+ data: { label: 'Column action' },+ allowTransform: false,+ eventPassThrough: true,+ }, {+ width: 96,+ height: 28,+ marginX: 0,+ marginY: 0,+ }, 'header-card')!;+ const chartDom = fixture.manager.addFloatDomToRange({+ startRow: 3,+ endRow: 4,+ startColumn: 3,+ endColumn: 4,+ }, {+ componentKey: 'ChartCard',+ initPosition: { startX: 0, startY: 0, endX: 0, endY: 0 },+ data: { label: 'Revenue', backgroundColor: '#ffffff', border: '#111111' },+ allowTransform: true,+ type: DrawingTypeEnum.DRAWING_CHART,+ }, {+ width: 120,+ height: 72,+ marginX: 0,+ marginY: 0,+ }, 'chart-card')!;++ expect(fixture.manager.getFloatDomsBySubUnitId('test', 'sheet1').length).toBe(3);+ expect(findFloatDom(canvasFloatDomService, 'range-card')).toEqual(expect.objectContaining({+ componentKey: 'RangeCard',+ data: { label: 'Range order' },+ unitId: 'test',+ }));+ expect(findFloatDom(canvasFloatDomService, 'header-card')).toEqual(expect.objectContaining({+ componentKey: 'ColumnHeaderCard',+ data: { label: 'Column action' },+ unitId: 'test',+ }));+ expect(findFloatDom(canvasFloatDomService, 'chart-card')).toEqual(expect.objectContaining({+ componentKey: 'ChartCard',+ data: { label: 'Revenue', backgroundColor: '#ffffff', border: '#111111' },+ unitId: 'test',+ }));+ expect(fixture.manager.getFloatDomInfo('chart-card')?.rect.toJson()).toEqual(expect.objectContaining({+ fill: '#ffffff',+ stroke: '#111111',+ paintFirst: 'stroke',+ radius: 8,+ }));+ findFloatDom(canvasFloatDomService, 'range-card')?.onPointerDown(new MouseEvent('pointerdown'));+ findFloatDom(canvasFloatDomService, 'range-card')?.onPointerMove(new MouseEvent('pointermove'));+ findFloatDom(canvasFloatDomService, 'range-card')?.onPointerUp(new MouseEvent('pointerup'));+ findFloatDom(canvasFloatDomService, 'range-card')?.onWheel(new WheelEvent('wheel'));+ findFloatDom(canvasFloatDomService, 'header-card')?.onPointerDown(new MouseEvent('pointerdown'));+ findFloatDom(canvasFloatDomService, 'header-card')?.onPointerMove(new MouseEvent('pointermove'));+ findFloatDom(canvasFloatDomService, 'header-card')?.onPointerUp(new MouseEvent('pointerup'));+ findFloatDom(canvasFloatDomService, 'header-card')?.onWheel(new WheelEvent('wheel'));+ expect((fixture.scene as unknown as TestRenderScene).canvasEvents).toEqual([+ 'pointerdown',+ 'pointermove',+ 'pointerup',+ 'wheel',+ 'pointerdown',+ 'pointermove',+ 'pointerup',+ 'wheel',+ ]);++ fixture.manager.updateFloatDomProps('test', 'sheet1', 'range-card', { fill: '#ff0000' });+ expect(fixture.manager.getFloatDomInfo('range-card')?.rect.fill).toBe('#ff0000');++ rangeDom.dispose();+ expect(findFloatDom(canvasFloatDomService, 'range-card')).toBeUndefined();+ expect(findFloatDom(canvasFloatDomService, 'header-card')).toBeDefined();++ chartDom.dispose();+ expect(findFloatDom(canvasFloatDomService, 'chart-card')).toBeUndefined();++ headerDom.dispose();+ expect(fixture.manager.getFloatDomsBySubUnitId('test', 'sheet1')).toEqual([]);+ expect(findFloatDom(canvasFloatDomService, 'header-card')).toBeUndefined();+ });++ it('adds a position anchored float dom through the sheet drawing pipeline', async () => {+ const fixture = setup();+ disposables.push(fixture);+ const canvasFloatDomService = fixture.get(CanvasFloatDomService);+ const sheetDrawingService = fixture.get(ISheetDrawingService);+ const addedIds: string[] = [];+ const disposable = fixture.manager.add$.subscribe((event) => {+ addedIds.push(event.id);+ });++ fixture.manager.addFloatDomToPosition({+ componentKey: 'PositionCard',+ initPosition: {+ startX: 76,+ startY: 30,+ endX: 176,+ endY: 70,+ },+ data: { label: 'Pinned note' },+ allowTransform: true,+ }, 'position-card')!;+ await Promise.resolve();++ const drawing = sheetDrawingService.getDrawingByParam({+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'position-card',+ });+ if (!drawing) {+ throw new Error('position-card drawing should be created');+ }+ expect(addedIds).toEqual(['position-card']);+ expect(drawing).toEqual(expect.objectContaining({+ componentKey: 'PositionCard',+ data: { label: 'Pinned note' },+ transform: {+ left: 76,+ top: 30,+ width: 100,+ height: 40,+ },+ sheetTransform: {+ from: {+ column: 1,+ columnOffset: 4,+ row: 1,+ rowOffset: 6,+ },+ to: {+ column: 2,+ columnOffset: 32,+ row: 2,+ rowOffset: 22,+ },+ },+ }));+ expect(findFloatDom(canvasFloatDomService, 'position-card')).toEqual(expect.objectContaining({+ componentKey: 'PositionCard',+ data: { label: 'Pinned note' },+ unitId: 'test',+ }));+ findFloatDom(canvasFloatDomService, 'position-card')?.onPointerDown(new MouseEvent('pointerdown'));+ findFloatDom(canvasFloatDomService, 'position-card')?.onPointerMove(new MouseEvent('pointermove'));+ findFloatDom(canvasFloatDomService, 'position-card')?.onPointerUp(new MouseEvent('pointerup'));+ findFloatDom(canvasFloatDomService, 'position-card')?.onWheel(new WheelEvent('wheel'));+ expect((fixture.scene as unknown as TestRenderScene).canvasEvents).toEqual([+ 'pointerdown',+ 'pointermove',+ 'pointerup',+ 'wheel',+ ]);++ const transformChanges: unknown[] = [];+ const transformDisposable = fixture.manager.transformChange$.subscribe((event) => {+ transformChanges.push(event);+ });+ const positions: IFloatDomLayout[] = [];+ const positionSubscription = findFloatDom(canvasFloatDomService, 'position-card')!.position$.subscribe((position) => {+ positions.push(position);+ });++ fixture.manager.getFloatDomInfo('position-card')!.rect.transformByState({+ left: 88,+ top: 36,+ width: 104,+ height: 44,+ });+ expect(positions[positions.length - 1]).toEqual(expect.objectContaining({+ startX: 58,+ startY: 28,+ endX: 162,+ endY: 62,+ width: 104,+ height: 44,+ }));++ await fixture.commandService.executeCommand(SetSheetDrawingCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawings: [{+ ...drawing,+ allowTransform: false,+ data: { label: 'Pinned note updated' },+ transform: {+ left: 96,+ top: 40,+ width: 120,+ height: 48,+ },+ }],+ });+ expect(transformChanges).toEqual([{+ id: 'position-card',+ value: {+ left: 96,+ top: 40,+ width: 120,+ height: 48,+ },+ }]);+ expect(findFloatDom(canvasFloatDomService, 'position-card')).toEqual(expect.objectContaining({+ data: { label: 'Pinned note updated' },+ }));++ await fixture.commandService.executeCommand(RemoveSheetDrawingCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawings: [{+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'position-card',+ drawingType: drawing.drawingType,+ }],+ });+ expect(sheetDrawingService.getDrawingByParam({+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'position-card',+ })).toBeUndefined();+ expect(findFloatDom(canvasFloatDomService, 'position-card')).toBeUndefined();++ transformDisposable.unsubscribe();+ positionSubscription.unsubscribe();+ disposable.unsubscribe();});- it('removes runtime-only float doms directly', () => {- const { service, dispose, removeObject, syncExecuteCommand } = createService(null);+ it('refreshes float dom position when the sheet viewport scrolls', () => {+ const fixture = setup();+ disposables.push(fixture);+ fixture.get(LifecycleService).stage = LifecycleStages.Rendered;+ const canvasFloatDomService = fixture.get(CanvasFloatDomService);- service.removeFloatDom('float-dom-1');+ fixture.manager.addFloatDomToRange({+ startRow: 5,+ endRow: 5,+ startColumn: 5,+ endColumn: 5,+ }, {+ componentKey: 'ScrollAwareCard',+ initPosition: { startX: 0, startY: 0, endX: 0, endY: 0 },+ data: { label: 'Scroll aware' },+ allowTransform: true,+ }, {+ width: 80,+ height: 24,+ marginX: 0,+ marginY: 0,+ }, 'scroll-card')!;- expect(dispose).toHaveBeenCalledTimes(1);- expect(removeObject).toHaveBeenCalledWith({ id: 'rect-1' });- expect(syncExecuteCommand).not.toHaveBeenCalled();- expect(service.getFloatDomInfo('float-dom-1')).toBeUndefined();+ const positions: IFloatDomLayout[] = [];+ const floatDom = findFloatDom(canvasFloatDomService, 'scroll-card')!;+ const subscription = floatDom.position$.subscribe((position) => {+ positions.push(position);+ });+ const before = positions[positions.length - 1];++ (fixture.scene as unknown as TestRenderScene).scrollTo(60, 42);+ const after = positions[positions.length - 1];++ expect(after).toEqual({+ ...before,+ startX: before.startX - 30,+ endX: before.endX - 30,+ startY: before.startY - 24,+ endY: before.endY - 24,+ });++ subscription.unsubscribe();});});++function findFloatDom(canvasFloatDomService: CanvasFloatDomService, id: string): IFloatDom | undefined {+ for (const [domId, floatDom] of canvasFloatDomService.domLayers) {+ if (domId === id) {+ return floatDom;+ }+ }+}diff --git a/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsx b/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsxindex 48ad5e5997..a48aa23666 100644--- a/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsx+++ b/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsx@@ -14,11 +14,13 @@* limitations under the License.*/-import type { Worksheet } from '@univerjs/core';+import type { Injector, Worksheet } from '@univerjs/core';import type { Scene, SpreadsheetSkeleton } from '@univerjs/engine-render';import type { IFloatDomData } from '@univerjs/sheets-drawing';import type { IFloatDom, IFloatDomLayout } from '@univerjs/ui';-import { PrintFloatDomSingle } from '@univerjs/ui';+import type { ComponentType } from 'react';+import { render, unmount } from '@univerjs/design';+import { connectInjector, PrintFloatDomSingle } from '@univerjs/ui';import { useMemo } from 'react';import { BehaviorSubject } from 'rxjs';import { transformBound2DOMBound } from '../services/canvas-float-dom-manager.service';@@ -84,3 +86,11 @@ export const PrintingFloatDom = (props: IPrintingFloatDomProps) => {</div>);};++export function mountPrintingFloatDom(props: IPrintingFloatDomProps, root: HTMLElement, injector: Injector): () => void {+ const PrintingFloatDomInjector = connectInjector(PrintingFloatDom, injector) as ComponentType<IPrintingFloatDomProps>;++ render(<PrintingFloatDomInjector {...props} />, root);++ return () => unmount(root);+}diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsxnew file mode 100644index 0000000000..bef85342b2--- /dev/null+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingAnchor.spec.tsx@@ -0,0 +1,158 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { ISheetDrawing } from '@univerjs/sheets-drawing';+import type { Root } from 'react-dom/client';+import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';+import { IDrawingManagerService } from '@univerjs/drawing';+import { IRenderManagerService } from '@univerjs/engine-render';+import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';+import { SheetDrawingAnchor } from '../SheetDrawingAnchor';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++function createSheetDrawing(drawingId: string, anchorType: SheetDrawingAnchorType): ISheetDrawing {+ return {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.URL,+ source: `https://example.com/${drawingId}.png`,+ anchorType,+ transform: {+ left: 10,+ top: 20,+ width: 100,+ height: 80,+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ },+ sheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ axisAlignSheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ },+ };+}++class TestRenderManagerService {+ readonly clearControl$ = new Subject<boolean>();+ readonly changeStart$ = new Subject<{ objects: Map<string, unknown> }>();++ getRenderById() {+ return {+ scene: {+ getTransformerByCreate: () => ({+ clearControl$: this.clearControl$,+ changeStart$: this.changeStart$,+ }),+ },+ };+ }+}++describe('SheetDrawingAnchor', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ root = undefined;+ container = undefined;+ });++ it('updates every focused sheet image when the anchor mode changes', async () => {+ const testBed = createSheetsDrawingUiTestBed(undefined, [+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ ]);+ const sheetDrawingService = testBed.get(ISheetDrawingService);+ const drawingManagerService = testBed.get(IDrawingManagerService);+ const drawings = [+ createSheetDrawing('drawing-a', SheetDrawingAnchorType.Position),+ createSheetDrawing('drawing-b', SheetDrawingAnchorType.Both),+ ];++ await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: testBed.unitId,+ drawings,+ });+ drawingManagerService.focusDrawing(drawings.map(({ unitId, subUnitId, drawingId }) => ({ unitId, subUnitId, drawingId })));++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <SheetDrawingAnchor drawings={drawings} />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const options = Array.from(container.querySelectorAll('input[type="radio"]'));+ const noResizeOrMoveOption = options[2] as HTMLInputElement;++ await act(async () => {+ noResizeOrMoveOption.click();+ await Promise.resolve();+ });++ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-a',+ })?.anchorType).toBe(SheetDrawingAnchorType.None);+ expect(sheetDrawingService.getDrawingByParam({+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-b',+ })?.anchorType).toBe(SheetDrawingAnchorType.None);+ expect((drawingManagerService.getFocusDrawings() as ISheetDrawing[]).map((drawing) => drawing.anchorType)).toEqual([+ SheetDrawingAnchorType.None,+ SheetDrawingAnchorType.None,+ ]);++ testBed.univer.dispose();+ });+});diff --git a/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.ts b/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.tsindex 57ae34dfb9..81e0865ec3 100644--- a/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.ts+++ b/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.ts@@ -27,27 +27,16 @@ import {LogLevel,Plugin,Tools,- touchDependencies,Univer,UniverInstanceType,} from '@univerjs/core';-import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';+import { UniverDrawingPlugin } from '@univerjs/drawing';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {- CopySheetCommand,- CopyWorksheetEndMutation,- InsertSheetMutation,- RemoveSheetCommand,- RemoveSheetMutation,- SetRangeValuesMutation,- SetWorksheetActivateCommand,- SetWorksheetActiveOperation,- SheetInterceptorService,- SheetLazyExecuteScheduleService,+ UniverSheetsPlugin,} from '@univerjs/sheets';import enUS from '@univerjs/sheets/locale/en-US';-import { SheetsDrawingLoadController } from '../controllers/sheet-drawing.controller';-import { ISheetDrawingService, SheetDrawingService } from '../services/sheet-drawing.service';+import { UniverSheetsDrawingPlugin } from '../plugin';const TEST_WORKBOOK_DATA: IWorkbookData = {id: 'test',@@ -103,22 +92,16 @@ export function createSheetsDrawingTestBed(workbookData?: IWorkbookData, depende([[IRenderManagerService, { useClass: RenderManagerService }],- [SheetInterceptorService],- [SheetLazyExecuteScheduleService],- [IDrawingManagerService, { useClass: DrawingManagerService }],- [ISheetDrawingService, { useClass: SheetDrawingService }],- [SheetsDrawingLoadController],] as Dependency[]).forEach((dependency) => this._injector.add(dependency));dependencies?.forEach((dependency) => this._injector.add(dependency));-- touchDependencies(this._injector, [- [SheetsDrawingLoadController],- ]);}}univer.registerPlugin(TestPlugin);+ univer.registerPlugin(UniverSheetsPlugin);+ univer.registerPlugin(UniverDrawingPlugin);+ univer.registerPlugin(UniverSheetsDrawingPlugin);const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET,@@ -132,23 +115,11 @@ export function createSheetsDrawingTestBed(workbookData?: IWorkbookData, dependelocaleService.load({ enUS });localeService.setLocale(LocaleType.EN_US);- const commandService = get(ICommandService);- [- CopySheetCommand,- CopyWorksheetEndMutation,- InsertSheetMutation,- RemoveSheetCommand,- RemoveSheetMutation,- SetRangeValuesMutation,- SetWorksheetActivateCommand,- SetWorksheetActiveOperation,- ].forEach((command) => commandService.registerCommand(command));-return {univer,get,injector,workbook,- commandService,+ commandService: get(ICommandService),};}diff --git a/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.ts b/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.tsindex 2b5f617b17..b26d305591 100644--- a/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.ts+++ b/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.ts@@ -16,7 +16,7 @@import type { ICommandService, Injector, Univer } from '@univerjs/core';import type { ISheetDrawing } from '../../../services/sheet-drawing.service';-import { DrawingTypeEnum, ImageSourceType, IUniverInstanceService, UndoCommand } from '@univerjs/core';+import { ArrangeTypeEnum, DrawingTypeEnum, ImageSourceType, IUniverInstanceService, UndoCommand } from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';import { CopySheetCommand, RemoveSheetCommand, SetWorksheetActivateCommand } from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it } from 'vitest';@@ -24,6 +24,8 @@ import { createSheetsDrawingTestBed } from '../../../__tests__/create-sheets-draimport { ISheetDrawingService } from '../../../services/sheet-drawing.service';import { InsertSheetDrawingCommand } from '../insert-sheet-drawing.command';import { RemoveSheetDrawingCommand } from '../remove-sheet-drawing.command';+import { SetDrawingArrangeCommand } from '../set-drawing-arrange.command';+import { SetSheetDrawingCommand } from '../set-sheet-drawing.command';function createSheetDrawing(drawingId: string, subUnitId = 'sheet1'): ISheetDrawing {return {@@ -138,6 +140,106 @@ describe('sheet drawing integration', () => {expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual([]);});+ it('updates an existing drawing through the real command pipeline', async () => {+ await commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [createSheetDrawing('drawing-update')],+ });++ expect(await commandService.executeCommand(SetSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [{+ ...createSheetDrawing('drawing-update'),+ source: 'https://example.com/updated.png',+ sheetTransform: {+ angle: 0,+ flipX: false,+ flipY: false,+ skewX: 0,+ skewY: 0,+ from: {+ row: 2,+ rowOffset: 1,+ column: 2,+ columnOffset: 1,+ },+ to: {+ row: 6,+ rowOffset: 0,+ column: 5,+ columnOffset: 0,+ },+ },+ }],+ })).toBe(true);++ const sheetDrawingService = get(ISheetDrawingService);+ const drawingManagerService = get(IDrawingManagerService);++ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-update' })).toMatchObject({+ source: 'https://example.com/updated.png',+ sheetTransform: {+ from: {+ row: 2,+ column: 2,+ },+ to: {+ row: 6,+ column: 5,+ },+ },+ });+ expect(drawingManagerService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-update' })).toMatchObject({+ source: 'https://example.com/updated.png',+ });+ });++ it('arranges drawing order through the real command pipeline', async () => {+ await commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [+ createSheetDrawing('drawing-a'),+ createSheetDrawing('drawing-b'),+ createSheetDrawing('drawing-c'),+ ],+ });++ const sheetDrawingService = get(ISheetDrawingService);+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual(['drawing-c', 'drawing-b', 'drawing-a']);++ expect(await commandService.executeCommand(SetDrawingArrangeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingIds: ['drawing-c'],+ arrangeType: ArrangeTypeEnum.front,+ })).toBe(true);+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual(['drawing-b', 'drawing-a', 'drawing-c']);++ expect(await commandService.executeCommand(SetDrawingArrangeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingIds: ['drawing-c'],+ arrangeType: ArrangeTypeEnum.backward,+ })).toBe(true);+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual(['drawing-b', 'drawing-c', 'drawing-a']);++ expect(await commandService.executeCommand(SetDrawingArrangeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingIds: ['drawing-b'],+ arrangeType: ArrangeTypeEnum.forward,+ })).toBe(true);+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual(['drawing-c', 'drawing-b', 'drawing-a']);++ expect(await commandService.executeCommand(SetDrawingArrangeCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingIds: ['drawing-a'],+ arrangeType: ArrangeTypeEnum.back,+ })).toBe(true);+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual(['drawing-a', 'drawing-c', 'drawing-b']);+ });+it('copies sheet drawings when a worksheet is duplicated', async () => {await commandService.executeCommand(SetWorksheetActivateCommand.id, {unitId: 'test',@@ -154,9 +256,16 @@ describe('sheet drawing integration', () => {})).toBe(true);const workbook = get(IUniverInstanceService).getUniverSheetInstance('test')!;- const copiedSheetId = workbook.getSheets()- .map((sheet) => sheet.getSheetId())- .find((sheetId) => sheetId !== 'sheet1' && sheetId !== 'sheet2')!;+ let copiedSheetId = '';+ const sheets = workbook.getSheets();+ for (const sheet of sheets) {+ const sheetId = sheet.getSheetId();+ if (sheetId !== 'sheet1' && sheetId !== 'sheet2') {+ copiedSheetId = sheetId;+ break;+ }+ }+ expect(copiedSheetId).not.toBe('');const copiedDrawings = Object.values(get(ISheetDrawingService).getDrawingData('test', copiedSheetId));expect(copiedDrawings).toHaveLength(1);diff --git a/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.tsindex 64f71768b6..4962e9841f 100644--- a/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts+++ b/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts@@ -27,17 +27,7 @@ describe('FOverGridImage', () => {let injector: Injector;beforeEach(() => {- const skeleton = {- getNoMergeCellWithCoordByIndex: (row: number, column: number) => ({- startX: column * 100,- endX: (column + 1) * 100,- startY: row * 20,- endY: (row + 1) * 20,- }),- };- const testBed = createSheetsDrawingTestBed(undefined, [- [SheetSkeletonService, { useValue: { getSkeleton: () => skeleton } }],- ]);+ const testBed = createSheetsDrawingTestBed();univer = testBed.univer;injector = testBed.injector;});@@ -85,6 +75,7 @@ describe('FOverGridImage', () => {};const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ injector.get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');const builder = injector.createInstance(FOverGridImage, image).toBuilder();diff --git a/packages/sheets-drawing/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-univer.spec.tsnew file mode 100644index 0000000000..44c8ffd576--- /dev/null+++ b/packages/sheets-drawing/src/facade/__tests__/f-univer.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 type { Injector, Univer } from '@univerjs/core';+import type { ISheetImage } from '@univerjs/sheets-drawing';+import { FUniver } from '@univerjs/core/facade';+import { ISheetDrawingService } from '@univerjs/sheets-drawing';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';+import '@univerjs/sheets/facade';+import '../index';++describe('sheets drawing facade image lifecycle', () => {+ let univer: Univer;+ let injector: Injector;+ let univerAPI: FUniver;++ beforeEach(() => {+ const testBed = createSheetsDrawingTestBed();+ univer = testBed.univer;+ injector = testBed.injector;+ univerAPI = FUniver.newAPI(injector);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('keeps the sheet unchanged when a before-insert listener cancels the image', async () => {+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const disposable = univerAPI.addEvent(univerAPI.Event.BeforeOverGridImageInsert, (event) => {+ if (event.insertImageParams[0].source.includes('blocked')) {+ event.cancel = true;+ }+ });+ const blocked = await worksheet.newOverGridImage()+ .setSource('https://example.com/blocked.png', univerAPI.Enum.ImageSourceType.URL)+ .setWidth(40)+ .setHeight(40)+ .buildAsync();++ expect(worksheet.insertImages([blocked])).toBe(worksheet);+ expect(worksheet.getImageById(blocked.drawingId)).toBeNull();++ disposable.dispose();+ });+});++function getStoredImage(injector: Injector, drawingId: string): ISheetImage {+ const image = injector.get(ISheetDrawingService).getDrawingByParam({+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId,+ }) as ISheetImage | undefined;++ if (!image) {+ throw new Error(`Image ${drawingId} was not stored`);+ }++ return image;+}diff --git a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.tsindex 65e3f59df9..11f952d984 100644--- a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts+++ b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts@@ -14,13 +14,21 @@* limitations under the License.*/-import type { Injector, Univer } from '@univerjs/core';+import type { Injector, Univer, Workbook } from '@univerjs/core';+import type { FWorkbook } from '@univerjs/sheets/facade';import type { ISheetDrawing } from '../../services/sheet-drawing.service';-import { DrawingTypeEnum, ICommandService, RedoCommand, UndoCommand } from '@univerjs/core';-import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-drawing.command';-import { ISheetDrawingService } from '../../services/sheet-drawing.service';+import {+ DrawingTypeEnum,+ ICommandService,+ IUniverInstanceService,+ RedoCommand,+ UndoCommand,+ UniverInstanceType,+} from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';+import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-drawing.command';+import { ISheetDrawingService } from '../../services/sheet-drawing.service';import { FWorksheetDrawingMixin } from '../f-worksheet';describe('FWorksheetDrawingMixin group drawings', () => {@@ -163,15 +171,9 @@ describe('FWorksheetDrawingMixin group drawings', () => {});function createFacade(injector: Injector): FWorksheetDrawingMixin {- const instance = Object.create(FWorksheetDrawingMixin.prototype) as any;-- instance._commandService = injector.get(ICommandService);- instance._fWorkbook = { getId: () => 'test' };- instance._workbook = { getUnitId: () => 'test' };- instance._worksheet = { getSheetId: () => 'sheet1' };- instance._injector = injector;-- return instance as FWorksheetDrawingMixin;+ const workbook = injector.get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getSheetBySheetId('sheet1')!;+ return injector.createInstance(FWorksheetDrawingMixin, { getId: () => 'test' } as FWorkbook, workbook, worksheet);}function createDrawing(drawingId: string, left: number, drawingType = DrawingTypeEnum.DRAWING_SHAPE): ISheetDrawing {diff --git a/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts b/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.tsindex aeca503e41..b06a854443 100644--- a/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts+++ b/packages/sheets-filter-ui/src/commands/operations/__tests__/sheets-filter.operation.spec.ts@@ -17,13 +17,40 @@import type { Dependency, IOperation, IWorkbookData, Workbook } from '@univerjs/core';import type { ISetSheetsFilterRangeMutationParams } from '@univerjs/sheets-filter';import type { IEditorBridgeServiceVisibleParam } from '@univerjs/sheets-ui';-import { CommandType, ICommandService, IContextService, Inject, Injector, LocaleService, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';-import { ActiveDirtyManagerService, IActiveDirtyManagerService, ISheetRowFilteredService, SheetRowFilteredService } from '@univerjs/engine-formula';-import { RefRangeService, SheetInterceptorService, SheetRangeThemeModel, SheetsSelectionsService, ZebraCrossingCacheController } from '@univerjs/sheets';-import { SetSheetsFilterRangeMutation, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';+import {+ CommandType,+ ICommandService,+ IContextService,+ Inject,+ Injector,+ LocaleService,+ LocaleType,+ Plugin,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ ActiveDirtyManagerService,+ IActiveDirtyManagerService,+ ISheetRowFilteredService,+ SheetRowFilteredService,+} from '@univerjs/engine-formula';+import {+ RefRangeService,+ SheetInterceptorService,+ SheetRangeThemeModel,+ SheetsSelectionsService,+ ZebraCrossingCacheController,+} from '@univerjs/sheets';+import { FilterBy, SetSheetsFilterRangeMutation, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SheetsFilterPanelService } from '../../../services/sheets-filter-panel.service';-import { CloseFilterPanelOperation, FILTER_PANEL_OPENED_KEY, OpenFilterPanelOperation } from '../sheets-filter.operation';+import {+ ChangeFilterByOperation,+ CloseFilterPanelOperation,+ FILTER_PANEL_OPENED_KEY,+ OpenFilterPanelOperation,+} from '../sheets-filter.operation';const SetCellEditVisibleOperation: IOperation<IEditorBridgeServiceVisibleParam> = {id: 'sheet.operation.set-cell-edit-visible',@@ -99,6 +126,7 @@ function createFilterOperationTestBed() {[OpenFilterPanelOperation,CloseFilterPanelOperation,+ ChangeFilterByOperation,SetCellEditVisibleOperation,].forEach((command) => commandService.registerCommand(command));@@ -169,4 +197,31 @@ describe('test sheets filter ui operations', () => {expect(spy).toHaveBeenCalledTimes(1);});});++ describe('test "ChangeFilterByOperation"', () => {+ it('should switch the active filter panel to condition filtering', () => {+ expect(commandService.syncExecuteCommand(SetSheetsFilterRangeMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, startColumn: 0, endRow: 5, endColumn: 5 },+ } as ISetSheetsFilterRangeMutationParams)).toBeTruthy();+ expect(commandService.syncExecuteCommand(OpenFilterPanelOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ col: 0,+ })).toBeTruthy();++ expect(commandService.syncExecuteCommand(ChangeFilterByOperation.id, {+ filterBy: FilterBy.CONDITIONS,+ })).toBe(true);+ expect(sheetsFilterPanelService.filterBy).toBe(FilterBy.CONDITIONS);+ });++ it('should not switch filter type before a filter panel column is prepared', () => {+ expect(commandService.syncExecuteCommand(ChangeFilterByOperation.id, {+ filterBy: FilterBy.CONDITIONS,+ })).toBe(false);+ expect(sheetsFilterPanelService.filterBy).toBe(FilterBy.VALUES);+ });+ });});diff --git a/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts b/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.tsindex 20002aa3d3..2595ecf266 100644--- a/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts+++ b/packages/sheets-filter-ui/src/services/__tests__/sheets-filter-panel.service.spec.ts@@ -15,20 +15,55 @@*/import type { Dependency, IOperation, IWorkbookData, Workbook } from '@univerjs/core';+import type { IInsertColMutationParams } from '@univerjs/sheets';import type { IEditorBridgeServiceVisibleParam } from '@univerjs/sheets-ui';import type { IOpenFilterPanelOperationParams } from '../../commands/operations/sheets-filter.operation';import type { IFilterConditionFormParams } from '../../models/conditions';import type { IFilterByValueWithTreeItem } from '../sheets-filter-panel.service';-import { awaitTime, CommandType, ICommandService, Inject, Injector, LocaleService, Plugin, Univer, UniverInstanceType } from '@univerjs/core';-import { ActiveDirtyManagerService, IActiveDirtyManagerService, ISheetRowFilteredService, SheetRowFilteredService } from '@univerjs/engine-formula';-import { MarkDirtyFilterChangeMutation, RefRangeService, SheetInterceptorService, SheetRangeThemeModel, SheetsSelectionsService, ZebraCrossingCacheController } from '@univerjs/sheets';+import {+ awaitTime,+ CommandType,+ ICommandService,+ Inject,+ Injector,+ LocaleService,+ LocaleType,+ Plugin,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ ActiveDirtyManagerService,+ IActiveDirtyManagerService,+ ISheetRowFilteredService,+ SheetRowFilteredService,+} from '@univerjs/engine-formula';+import {+ InsertColMutation,+ MarkDirtyFilterChangeMutation,+ RefRangeService,+ SheetInterceptorService,+ SheetRangeThemeModel,+ SheetsSelectionsService,+ ZebraCrossingCacheController,+} from '@univerjs/sheets';import { CustomFilterOperator, FilterBy, SheetsFilterService, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';-import { E_ITEMS, ITEMS, ITEMS_WITH_EMPTY, WithCustomFilterModelFactory, WithMergedCellFilterFactory, WithMultiEmptyCellsModelFactory, WithTwoFilterColumnsFactory, WithValuesAndEmptyFilterModelFactory, WithValuesFilterModelFactory } from '../../__testing__/data';+import {+ E_ITEMS,+ ITEMS,+ ITEMS_WITH_EMPTY,+ WithCustomFilterModelFactory,+ WithMergedCellFilterFactory,+ WithMultiEmptyCellsModelFactory,+ WithTwoFilterColumnsFactory,+ WithValuesAndEmptyFilterModelFactory,+ WithValuesFilterModelFactory,+} from '../../__testing__/data';import { CloseFilterPanelOperation, OpenFilterPanelOperation } from '../../commands/operations/sheets-filter.operation';import { FilterConditionItems } from '../../models/conditions';import { ExtendCustomFilterOperator } from '../../models/extended-operators';-import { ByConditionsModel, ByValuesModel, SheetsFilterPanelService } from '../sheets-filter-panel.service';+import { ByColorsModel, ByConditionsModel, ByValuesModel, SheetsFilterPanelService } from '../sheets-filter-panel.service';const SetCellEditVisibleOperation: IOperation<IEditorBridgeServiceVisibleParam> = {id: 'sheet.operation.set-cell-edit-visible',@@ -116,6 +151,7 @@ function createSheetsFilterPanelServiceTestBed(workbookData: IWorkbookData) {CloseFilterPanelOperation,SetCellEditVisibleOperation,MarkDirtyFilterChangeMutation,+ InsertColMutation,].forEach((command) => commandService.registerCommand(command));return { univer, get };@@ -243,6 +279,125 @@ describe('test "SheetsFilterPanelService"', () => {});});+ describe('test filter type switching and color filters', () => {+ beforeEach(() => {+ vitest.useFakeTimers();+ });++ afterEach(() => {+ vitest.useRealTimers();+ });++ it('should switch the active panel model by filter type for the same filter column', async () => {+ prepare(WithValuesFilterModelFactory());++ expect(commandService.syncExecuteCommand(OpenFilterPanelOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ col: 0,+ } as IOpenFilterPanelOperationParams)).toBe(true);+ await tick();++ expect(sheetsFilterPanelService.filterModel).toBe(sheetsFilterService.activeFilterModel);+ expect(sheetsFilterPanelService.col).toBe(0);+ expect(sheetsFilterPanelService.filterByModel).toBeInstanceOf(ByValuesModel);++ expect(sheetsFilterPanelService.changeFilterBy(FilterBy.CONDITIONS)).toBe(true);+ expect(sheetsFilterPanelService.filterBy).toBe(FilterBy.CONDITIONS);+ expect(sheetsFilterPanelService.filterByModel).toBeInstanceOf(ByConditionsModel);++ expect(sheetsFilterPanelService.changeFilterBy(FilterBy.COLORS)).toBe(true);+ await tick();+ expect(sheetsFilterPanelService.filterBy).toBe(FilterBy.COLORS);+ expect(sheetsFilterPanelService.filterByModel).toBeInstanceOf(ByColorsModel);++ expect(sheetsFilterPanelService.changeFilterBy(FilterBy.VALUES)).toBe(true);+ await tick();+ expect(sheetsFilterPanelService.filterBy).toBe(FilterBy.VALUES);+ expect(sheetsFilterPanelService.filterByModel).toBeInstanceOf(ByValuesModel);+ });++ it('should build and apply color filter options from cell fill and text colors', async () => {+ prepare(WithColorFilterModelFactory());++ expect(commandService.syncExecuteCommand(OpenFilterPanelOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ col: 0,+ } as IOpenFilterPanelOperationParams)).toBe(true);+ expect(sheetsFilterPanelService.changeFilterBy(FilterBy.COLORS)).toBe(true);+ await tick();++ const filterByModel = sheetsFilterPanelService.filterByModel as ByColorsModel;+ expect(filterByModel).toBeInstanceOf(ByColorsModel);+ expect(filterByModel.cellFillColors).toEqual([+ { color: 'rgb(255,0,0)', checked: false },+ { color: null, checked: false },+ ]);+ expect(filterByModel.cellTextColors).toEqual([+ { color: 'rgb(0,0,0)', checked: false },+ { color: 'rgb(0,0,255)', checked: false },+ ]);++ filterByModel.onFilterCheckToggled({ color: 'rgb(255,0,0)', checked: false });+ expect(filterByModel.cellFillColors).toEqual([+ { color: 'rgb(255,0,0)', checked: true },+ { color: null, checked: false },+ ]);++ expect(await filterByModel.apply()).toBe(true);+ expect(sheetsFilterService.activeFilterModel!.getFilterColumn(0)!.getColumnData().colorFilters).toEqual({+ cellFillColors: ['rgb(255,0,0)'],+ });++ filterByModel.onFilterCheckToggled({ color: 'rgb(0,0,255)', checked: false }, false);+ expect(filterByModel.cellFillColors).toEqual([+ { color: 'rgb(255,0,0)', checked: false },+ { color: null, checked: false },+ ]);+ expect(filterByModel.cellTextColors).toEqual([+ { color: 'rgb(0,0,0)', checked: false },+ { color: 'rgb(0,0,255)', checked: true },+ ]);++ expect(await filterByModel.apply()).toBe(true);+ expect(sheetsFilterService.activeFilterModel!.getFilterColumn(0)!.getColumnData().colorFilters).toEqual({+ cellTextColors: ['rgb(0,0,255)'],+ });++ filterByModel.onFilterCheckToggled({ color: 'rgb(0,0,255)', checked: true }, false);+ expect(await filterByModel.apply()).toBe(true);+ expect(sheetsFilterService.activeFilterModel!.getFilterColumn(0)).toBeNull();+ });++ it('should keep the panel target column aligned when columns are inserted before the filter header', async () => {+ prepare(WithValuesFilterModelFactory());++ expect(commandService.syncExecuteCommand(OpenFilterPanelOperation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ col: 0,+ } as IOpenFilterPanelOperationParams)).toBe(true);+ await tick();++ const filterByModel = sheetsFilterPanelService.filterByModel as ByValuesModel;+ expect(filterByModel.col).toBe(0);++ expect(commandService.syncExecuteCommand(InsertColMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: {+ startRow: 0,+ endRow: 999,+ startColumn: 0,+ endColumn: 0,+ },+ } as IInsertColMutationParams)).toBe(true);++ expect(filterByModel.col).toBe(1);+ });+ });+describe('test filter by values', () => {beforeEach(() => {vitest.useFakeTimers();@@ -522,3 +677,64 @@ function tick(milliseconds: number = 0): Promise<void> {vitest.advanceTimersByTime(milliseconds + 1);return result;}++function WithColorFilterModelFactory(): IWorkbookData {+ return {+ id: 'test',+ sheetOrder: ['sheet1'],+ name: '',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.ZH_CN,+ styles: {+ redFill: {+ bg: {+ rgb: '#ff0000',+ },+ },+ blueText: {+ cl: {+ rgb: '#0000ff',+ },+ },+ },+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 5,+ cellData: {+ 0: {+ 0: { v: 'Status' },+ },+ 1: {+ 0: { v: 'Blocked', s: 'redFill' },+ },+ 2: {+ 0: { v: 'Ready', s: 'blueText' },+ },+ 3: {+ 0: { v: 'Backlog' },+ },+ },+ },+ },+ resources: [+ {+ name: 'SHEET_FILTER_PLUGIN',+ data: JSON.stringify({+ sheet1: {+ ref: {+ startRow: 0,+ startColumn: 0,+ endRow: 3,+ endColumn: 0,+ },+ filterColumns: [],+ cachedFilteredOut: [],+ },+ }),+ },+ ],+ };+}diff --git a/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx b/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsxnew file mode 100644index 0000000000..7111f891fd--- /dev/null+++ b/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx@@ -0,0 +1,489 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDisposable, IOperation, IWorkbookData, Workbook } from '@univerjs/core';+import type { IUniverSheetsFilterConfig } from '@univerjs/sheets-filter';+import type { IEditorBridgeServiceVisibleParam } from '@univerjs/sheets-ui';+import type { Root } from 'react-dom/client';+import {+ awaitTime,+ CommandType,+ ICommandService,+ IContextService,+ ILogService,+ Inject,+ Injector,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ ActiveDirtyManagerService,+ IActiveDirtyManagerService,+ ISheetRowFilteredService,+ SheetRowFilteredService,+} from '@univerjs/engine-formula';+import {+ MarkDirtyFilterChangeMutation,+ RefRangeService,+ SheetInterceptorService,+ SheetRangeThemeModel,+ SheetsSelectionsService,+ ZebraCrossingCacheController,+} from '@univerjs/sheets';+import { FilterBy, SheetsFilterService, SheetsFilterSyncController, UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';+import { ILayoutService, IMessageService, IUIPartsService, RediContext, UIPartsService } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { WithValuesAndEmptyFilterModelFactory, WithValuesFilterModelFactory } from '../../../__testing__/data';+import {+ ChangeFilterByOperation,+ CloseFilterPanelOperation,+ FILTER_PANEL_OPENED_KEY,+ OpenFilterPanelOperation,+} from '../../../commands/operations/sheets-filter.operation';+import enUS from '../../../locale/en-US';+import { SheetsFilterPanelService } from '../../../services/sheets-filter-panel.service';+import { FilterPanel } from '../SheetsFilterPanel';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'test';+const SUB_UNIT_ID = 'sheet1';++const SetCellEditVisibleOperation: IOperation<IEditorBridgeServiceVisibleParam> = {+ id: 'sheet.operation.set-cell-edit-visible',+ type: CommandType.OPERATION,+ handler: () => true,+};++class TestLayoutService {+ private _focused = false;+ readonly rootContainerElement = document.body;++ get isFocused() {+ return this._focused;+ }++ focus() {+ this._focused = true;+ }++ registerFocusHandler(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerRootContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContentElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ getContentElement() {+ return document.body;+ }++ checkElementInCurrentContainers() {+ return true;+ }++ checkContentIsFocused() {+ return this._focused;+ }+}++class TestMessageService {+ readonly messages: unknown[] = [];++ show(options: unknown): IDisposable {+ this.messages.push(options);+ return toDisposable(() => undefined);+ }++ remove() {+ // The switch UI is not the behavior under test here.+ }++ removeAll() {+ this.messages.length = 0;+ }+}++function createFilterPanelViewTestBed(workbookData: IWorkbookData, filterConfig?: Partial<IUniverSheetsFilterConfig>) {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override type = UniverInstanceType.UNIVER_SHEET;+ static override pluginName = 'sheets-filter-ui-panel-view-test-plugin';++ constructor(+ _config: unknown,+ @Inject(Injector) protected readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ ([+ [SheetInterceptorService],+ [SheetsFilterPanelService],+ [RefRangeService],+ [SheetsSelectionsService],+ [SheetRangeThemeModel],+ [ZebraCrossingCacheController],+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],+ [ILayoutService, { useClass: TestLayoutService as never }],+ [IMessageService, { useClass: TestMessageService as never }],+ [IUIPartsService, { useClass: UIPartsService }],+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));+ }+ }++ injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);++ if (filterConfig) {+ univer.registerPlugin(UniverSheetsFilterPlugin, filterConfig);+ } else {+ univer.registerPlugin(UniverSheetsFilterPlugin);+ }+ univer.registerPlugin(TestPlugin);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ [+ OpenFilterPanelOperation,+ CloseFilterPanelOperation,+ ChangeFilterByOperation,+ SetCellEditVisibleOperation,+ MarkDirtyFilterChangeMutation,+ ].forEach((command) => commandService.registerCommand(command));++ return {+ univer,+ injector,+ workbook,+ commandService,+ contextService: injector.get(IContextService),+ filterService: injector.get(SheetsFilterService),+ panelService: injector.get(SheetsFilterPanelService),+ messageService: injector.get(IMessageService) as TestMessageService,+ };+}++async function openPanel(testBed: ReturnType<typeof createFilterPanelViewTestBed>) {+ expect(testBed.commandService.syncExecuteCommand(OpenFilterPanelOperation.id, {+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ col: 0,+ })).toBe(true);+ await awaitTime(20);+}++async function renderPanel(root: Root, testBed: ReturnType<typeof createFilterPanelViewTestBed>) {+ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <FilterPanel />+ </RediContext.Provider>+ );+ await awaitTime(20);+ });+}++function clickElement(element: Element) {+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));+}++function changeCheckbox(input: HTMLInputElement) {+ input.dispatchEvent(new MouseEvent('click', { bubbles: true }));+}++function getButton(container: HTMLElement, text: string): HTMLElement {+ const button = Array.from(container.querySelectorAll('[data-u-comp="button"]'))+ .find((button) => button.textContent === text);++ if (!button) {+ throw new Error(`Button "${text}" was not rendered.`);+ }++ return button as HTMLElement;+}++function getValueItemCheckbox(container: HTMLElement, title: string): HTMLInputElement {+ const titleElement = Array.from(container.querySelectorAll('span'))+ .find((element) => element.textContent === title);++ if (!titleElement) {+ throw new Error(`Filter value "${title}" was not rendered.`);+ }++ let row: Element | null = titleElement;+ while (row && !row.querySelector('[data-u-comp="checkbox"] input')) {+ row = row.parentElement;+ }++ const input = row?.querySelector<HTMLInputElement>('[data-u-comp="checkbox"] input');+ if (!input) {+ throw new Error(`Filter value "${title}" did not render a checkbox.`);+ }++ return input;+}++function getColorSwatch(container: HTMLElement, color: string): HTMLElement {+ const button = Array.from(container.querySelectorAll<HTMLButtonElement>('button'))+ .find((button) => button.style.backgroundColor === color);++ const swatch = button?.parentElement;+ if (!swatch) {+ throw new Error(`Color swatch "${color}" was not rendered.`);+ }++ return swatch;+}++function WithColorOptionsFilterModelFactory(): IWorkbookData {+ return {+ id: UNIT_ID,+ sheetOrder: [SUB_UNIT_ID],+ name: '',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.ZH_CN,+ styles: {+ redFill: {+ bg: {+ rgb: '#ff0000',+ },+ },+ blueText: {+ cl: {+ rgb: '#0000ff',+ },+ },+ },+ sheets: {+ [SUB_UNIT_ID]: {+ id: SUB_UNIT_ID,+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 5,+ cellData: {+ 0: {+ 0: { v: 'Status' },+ },+ 1: {+ 0: { v: 'Blocked', s: 'redFill' },+ },+ 2: {+ 0: { v: 'Ready', s: 'blueText' },+ },+ 3: {+ 0: { v: 'Backlog' },+ },+ },+ },+ },+ resources: [+ {+ name: 'SHEET_FILTER_PLUGIN',+ data: JSON.stringify({+ [SUB_UNIT_ID]: {+ ref: {+ startRow: 0,+ startColumn: 0,+ endRow: 3,+ endColumn: 0,+ },+ filterColumns: [],+ cachedFilteredOut: [],+ },+ }),+ },+ ],+ };+}++describe('FilterPanel', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createFilterPanelViewTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('clears existing value criteria and closes the panel from the footer action', async () => {+ currentTestBed = createFilterPanelViewTestBed(WithValuesAndEmptyFilterModelFactory());+ await openPanel(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderPanel(root, currentTestBed);++ const filterColumnBefore = currentTestBed.filterService.activeFilterModel?.getFilterColumn(0);+ expect(filterColumnBefore?.getColumnData().filters).toBeDefined();++ const clearButton = Array.from(container.querySelectorAll('[data-u-comp="button"]'))+ .find((button) => button.textContent === 'Clear Filter') as HTMLElement;++ await act(async () => {+ clearButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await awaitTime(20);+ });++ expect(currentTestBed.filterService.activeFilterModel?.getFilterColumn(0)).toBeNull();+ expect(currentTestBed.contextService.getContextValue(FILTER_PANEL_OPENED_KEY)).toBe(false);+ expect(currentTestBed.panelService.col).toBe(-1);+ });++ it('switches from values to conditions through the segmented control', async () => {+ currentTestBed = createFilterPanelViewTestBed(WithValuesFilterModelFactory());+ await openPanel(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderPanel(root, currentTestBed);++ expect(currentTestBed.panelService.filterBy).toBe(FilterBy.VALUES);++ const conditionButton = Array.from(container.querySelectorAll('[data-u-comp="segmented"] button'))+ .find((button) => button.textContent === 'By Conditions') as HTMLElement;++ await act(async () => {+ conditionButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await awaitTime(20);+ });++ expect(currentTestBed.panelService.filterBy).toBe(FilterBy.CONDITIONS);+ expect(container.querySelector('[data-u-comp="sheets-filter-panel-conditions-container"]')).toBeTruthy();+ });++ it('applies value criteria after unchecking a value from the tree', async () => {+ currentTestBed = createFilterPanelViewTestBed(WithValuesFilterModelFactory());+ await openPanel(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderPanel(root, currentTestBed);++ const michaelCheckbox = getValueItemCheckbox(container, 'Michael');+ const confirmButton = getButton(container, 'Confirm');++ await act(async () => {+ changeCheckbox(michaelCheckbox);+ await awaitTime(20);+ });++ await act(async () => {+ clickElement(confirmButton);+ await awaitTime(20);+ });++ const filters = currentTestBed.filterService.activeFilterModel?.getFilterColumn(0)?.getColumnData().filters?.filters;+ expect(filters).toContain('Jackson');+ expect(filters).not.toContain('Michael');+ expect(currentTestBed.contextService.getContextValue(FILTER_PANEL_OPENED_KEY)).toBe(false);+ });++ it('applies the selected cell fill color as color criteria', async () => {+ currentTestBed = createFilterPanelViewTestBed(WithColorOptionsFilterModelFactory());+ await openPanel(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderPanel(root, currentTestBed);++ const colorButton = Array.from(container.querySelectorAll('[data-u-comp="segmented"] button'))+ .find((button) => button.textContent === 'By Colors') as HTMLElement;++ await act(async () => {+ clickElement(colorButton);+ await awaitTime(20);+ });++ await act(async () => {+ clickElement(getColorSwatch(container!, 'rgb(255, 0, 0)'));+ await awaitTime(20);+ });++ await act(async () => {+ clickElement(getButton(container!, 'Confirm'));+ await awaitTime(20);+ });++ expect(currentTestBed.filterService.activeFilterModel?.getFilterColumn(0)?.getColumnData().colorFilters).toEqual({+ cellFillColors: ['rgb(255,0,0)'],+ });+ expect(currentTestBed.contextService.getContextValue(FILTER_PANEL_OPENED_KEY)).toBe(false);+ });++ it('turns sync off through the switch and reports the change', async () => {+ currentTestBed = createFilterPanelViewTestBed(WithValuesFilterModelFactory(), {+ enableSyncSwitch: { defaultValue: true },+ });+ await openPanel(currentTestBed);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderPanel(root, currentTestBed);++ const syncController = currentTestBed.injector.get(SheetsFilterSyncController);+ const switchInput = Array.from(container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')).at(-1);+ if (!switchInput) {+ throw new Error('Sync switch input was not rendered.');+ }++ await act(async () => {+ changeCheckbox(switchInput);+ await awaitTime(20);+ });++ expect(syncController.enabled).toBe(false);+ expect(currentTestBed.messageService.messages).toEqual([{+ content: '"Filter is visible to everyone" is turned off, only you will see the filter results',+ type: 'success',+ duration: 2000,+ }]);+ });+});diff --git a/packages/sheets-filter/src/commands/commands/__tests__/sheets-filter.command.spec.ts b/packages/sheets-filter/src/commands/commands/__tests__/sheets-filter.command.spec.tsnew file mode 100644index 0000000000..c40b8fb4ff--- /dev/null+++ b/packages/sheets-filter/src/commands/commands/__tests__/sheets-filter.command.spec.ts@@ -0,0 +1,283 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, Workbook } from '@univerjs/core';+import {+ ICommandService,+ Inject,+ Injector as InjectorIdentifier,+ IUniverInstanceService,+ LocaleType,+ Plugin,+ RANGE_TYPE,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { MarkDirtyFilterChangeMutation, SheetsSelectionsService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SheetsFilterService } from '../../../services/sheet-filter.service';+import {+ ReCalcSheetsFilterMutation,+ RemoveSheetsFilterMutation,+ SetSheetsFilterCriteriaMutation,+ SetSheetsFilterRangeMutation,+} from '../../mutations/sheets-filter.mutation';+import {+ ClearSheetsFilterCriteriaCommand,+ ReCalcSheetsFilterCommand,+ RemoveSheetFilterCommand,+ SetSheetFilterRangeCommand,+ SetSheetsFilterCriteriaCommand,+ SmartToggleSheetsFilterCommand,+} from '../sheets-filter.command';++const unitId = 'filter-command-workbook';+const subUnitId = 'sheet1';++function createWorkbookData(): IWorkbookData {+ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'filter command workbook',+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet 1',+ cellData: {+ 0: {+ 0: { v: 'Fruit' },+ },+ 1: {+ 0: { v: 'Apple' },+ },+ 2: {+ 0: { v: 'Banana' },+ },+ 3: {+ 0: { v: 'Apple' },+ },+ },+ },+ },+ };+}++class SheetsFilterCommandTestPlugin extends Plugin {+ static override type = UniverInstanceType.UNIVER_SHEET;+ static override pluginName = 'SheetsFilterCommandTestPlugin';++ constructor(_config: unknown, @Inject(InjectorIdentifier) protected readonly _injector: Injector) {+ super();+ }++ override onStarting(): void {+ this._injector.add([SheetsFilterService]);+ this._injector.add([SheetsSelectionsService]);+ }+}++describe('sheet filter commands', () => {+ let univer: Univer;+ let workbook: Workbook;+ let commandService: ICommandService;+ let sheetsFilterService: SheetsFilterService;++ beforeEach(() => {+ univer = new Univer();+ univer.registerPlugin(SheetsFilterCommandTestPlugin);+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ const injector = univer.__getInjector();+ injector.get(IUniverInstanceService).focusUnit(unitId);+ commandService = injector.get(ICommandService);+ sheetsFilterService = injector.get(SheetsFilterService);++ const commands = [+ SetSheetsFilterRangeMutation,+ SetSheetsFilterCriteriaMutation,+ RemoveSheetsFilterMutation,+ ReCalcSheetsFilterMutation,+ MarkDirtyFilterChangeMutation,+ SetSheetFilterRangeCommand,+ RemoveSheetFilterCommand,+ SetSheetsFilterCriteriaCommand,+ ClearSheetsFilterCriteriaCommand,+ ReCalcSheetsFilterCommand,+ SmartToggleSheetsFilterCommand,+ ];++ for (const command of commands) {+ commandService.registerCommand(command);+ }+ });++ afterEach(() => {+ univer.dispose();+ });++ it('sets a filter range and applies criteria to the filtered rows', async () => {+ const range = { startRow: 0, startColumn: 0, endRow: 3, endColumn: 0 };++ const setRangeResult = await commandService.executeCommand(SetSheetFilterRangeCommand.id, {+ unitId,+ subUnitId,+ range,+ });+ const criteriaResult = await commandService.executeCommand(SetSheetsFilterCriteriaCommand.id, {+ unitId,+ subUnitId,+ col: 0,+ criteria: {+ colId: 0,+ filters: {+ filters: ['Apple'],+ },+ },+ });++ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);+ const filterColumn = filterModel?.getFilterColumn(0);++ expect(setRangeResult).toBe(true);+ expect(criteriaResult).toBe(true);+ expect(filterModel?.getRange()).toEqual(range);+ expect(filterColumn?.serialize()).toMatchObject({+ colId: 0,+ filters: {+ filters: ['Apple'],+ },+ });+ expect(filterModel?.isRowFiltered(1)).toBe(false);+ expect(filterModel?.isRowFiltered(2)).toBe(true);+ expect(filterModel?.isRowFiltered(3)).toBe(false);+ });++ it('clears criteria without removing the filter range', async () => {+ const range = { startRow: 0, startColumn: 0, endRow: 3, endColumn: 0 };++ await commandService.executeCommand(SetSheetFilterRangeCommand.id, {+ unitId,+ subUnitId,+ range,+ });+ await commandService.executeCommand(SetSheetsFilterCriteriaCommand.id, {+ unitId,+ subUnitId,+ col: 0,+ criteria: {+ colId: 0,+ filters: {+ filters: ['Apple'],+ },+ },+ });++ const result = await commandService.executeCommand(ClearSheetsFilterCriteriaCommand.id, {+ unitId,+ subUnitId,+ });+ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);++ expect(result).toBe(true);+ expect(filterModel?.getRange()).toEqual(range);+ expect(filterModel?.getFilterColumn(0)).toBeNull();+ expect(filterModel?.filteredOutRows.size).toBe(0);+ });++ it('removes an existing filter model from the worksheet', async () => {+ await commandService.executeCommand(SetSheetFilterRangeCommand.id, {+ unitId,+ subUnitId,+ range: { startRow: 0, startColumn: 0, endRow: 3, endColumn: 0 },+ });++ const result = await commandService.executeCommand(RemoveSheetFilterCommand.id, {+ unitId,+ subUnitId,+ });++ expect(result).toBe(true);+ expect(sheetsFilterService.getFilterModel(unitId, subUnitId)).toBeNull();+ });++ it('toggles the current selection into and out of a sheet filter', async () => {+ const selectionManager = univer.__getInjector().get(SheetsSelectionsService);+ const selectedRange = {+ startRow: 0,+ startColumn: 0,+ endRow: 3,+ endColumn: 0,+ rangeType: RANGE_TYPE.NORMAL,+ };+ selectionManager.addSelections([{+ range: selectedRange,+ primary: {+ actualRow: 0,+ actualColumn: 0,+ startRow: 0,+ startColumn: 0,+ endRow: 3,+ endColumn: 0,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ }]);++ const openResult = await commandService.executeCommand(SmartToggleSheetsFilterCommand.id);+ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);+ const closeResult = await commandService.executeCommand(SmartToggleSheetsFilterCommand.id);++ expect(openResult).toBe(true);+ expect(filterModel?.getRange()).toEqual(selectedRange);+ expect(closeResult).toBe(true);+ expect(sheetsFilterService.getFilterModel(unitId, subUnitId)).toBeNull();+ });++ it('recalculates an existing filter after sheet data changes', async () => {+ const worksheet = workbook.getSheetBySheetId(subUnitId);++ await commandService.executeCommand(SetSheetFilterRangeCommand.id, {+ unitId,+ subUnitId,+ range: { startRow: 0, startColumn: 0, endRow: 3, endColumn: 0 },+ });+ await commandService.executeCommand(SetSheetsFilterCriteriaCommand.id, {+ unitId,+ subUnitId,+ col: 0,+ criteria: {+ colId: 0,+ filters: {+ filters: ['Apple'],+ },+ },+ });++ worksheet?.getCellMatrix().setValue(2, 0, { v: 'Apple' });+ const result = await commandService.executeCommand(ReCalcSheetsFilterCommand.id, {+ unitId,+ subUnitId,+ });+ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);++ expect(result).toBe(true);+ expect(filterModel?.isRowFiltered(2)).toBe(false);+ });+});diff --git a/packages/sheets-filter/src/facade/__tests__/create-test-bed.ts b/packages/sheets-filter/src/facade/__tests__/create-test-bed.tsindex d5b3027fda..8f1850df21 100644--- a/packages/sheets-filter/src/facade/__tests__/create-test-bed.ts+++ b/packages/sheets-filter/src/facade/__tests__/create-test-bed.ts@@ -31,7 +31,17 @@ import {UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import { ActiveDirtyManagerService, DefinedNamesService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IFunctionService, ISheetRowFilteredService, LexerTreeBuilder } from '@univerjs/engine-formula';+import {+ ActiveDirtyManagerService,+ DefinedNamesService,+ FormulaDataModel,+ FunctionService,+ IActiveDirtyManagerService,+ IDefinedNamesService,+ IFunctionService,+ ISheetRowFilteredService,+ LexerTreeBuilder,+} from '@univerjs/engine-formula';import { SheetRowFilteredService } from '@univerjs/engine-formula/services/sheet-row-filtered.service.js';import {MarkDirtyFilterChangeMutation,diff --git a/packages/sheets-filter/src/facade/__tests__/f-range.spec.ts b/packages/sheets-filter/src/facade/__tests__/f-range.spec.tsindex 447200f830..8c8a546bdc 100644--- a/packages/sheets-filter/src/facade/__tests__/f-range.spec.ts+++ b/packages/sheets-filter/src/facade/__tests__/f-range.spec.ts@@ -31,6 +31,20 @@ describe('Test FRange', () => {describe('FFilter', () => {it('create, modify and clear filters with Facade API without UI plugin', async () => {const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const filterEvents: string[] = [];+ const beforeFilterDisposable = univerAPI.addEvent(univerAPI.Event.SheetBeforeRangeFilter, (params) => {+ filterEvents.push(`before:${params.col}`);+ });+ const filteredDisposable = univerAPI.addEvent(univerAPI.Event.SheetRangeFiltered, (params) => {+ filterEvents.push(`after:${params.col}`);+ });+ const beforeClearDisposable = univerAPI.addEvent(univerAPI.Event.SheetBeforeRangeFilterClear, (params) => {+ filterEvents.push(`before-clear:${params.worksheet.getSheetId()}`);+ });+ const clearedDisposable = univerAPI.addEvent(univerAPI.Event.SheetRangeFilterCleared, (params) => {+ filterEvents.push(`after-clear:${params.worksheet.getSheetId()}`);+ });+expect(activeSheet.getFilter()).toBeNull();expect(activeSheet.getRange(0, 0, 1, 1).getFilter()).toBeNull();@@ -61,8 +75,24 @@ describe('Test FRange', () => {expect(await filter.removeFilterCriteria()).toBeTruthy();expect(filter.getColumnFilterCriteria(2)).toBeFalsy();+ expect(filterEvents).toEqual([+ 'before:1',+ 'after:1',+ 'before:2',+ 'after:2',+ 'before:1',+ 'after:1',+ 'before-clear:sheet1',+ 'after-clear:sheet1',+ ]);+expect(await filter.remove()).toBeTruthy();expect(activeSheet.getFilter()).toBeNull();++ beforeFilterDisposable.dispose();+ filteredDisposable.dispose();+ beforeClearDisposable.dispose();+ clearedDisposable.dispose();});});});diff --git a/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts b/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.tsindex b83f821644..d6ca073367 100644--- a/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts+++ b/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts@@ -26,11 +26,27 @@ describe('SheetsFilterFormulaService', () => {beforeEach(() => {dirtyConverters = new Map();+ class TestActiveDirtyManagerService {+ register = (commandId: string, converter: never) => dirtyConverters.set(commandId, converter);+ }++ class TestSheetRowFilteredService {+ register = (callback: never) => (rowFilteredCallback = callback);+ }++ class TestSheetsFilterService {+ getFilterModel = vi.fn(() => ({ getRange: () => ({ startRow: 2, endRow: 5 }), isRowFiltered: (row: number) => row === 3 }));+ }++ class TestUniverInstanceService {+ getUnit = () => ({ getSheetBySheetId: () => ({ getColumnCount: () => 10 }) });+ }+const injector = new Injector();- injector.add([IActiveDirtyManagerService, { useValue: { register: (commandId: string, converter: never) => dirtyConverters.set(commandId, converter) } as unknown as IActiveDirtyManagerService }]);- injector.add([ISheetRowFilteredService, { useValue: { register: (callback: never) => (rowFilteredCallback = callback) } as unknown as ISheetRowFilteredService }]);- injector.add([SheetsFilterService, { useValue: { getFilterModel: vi.fn(() => ({ getRange: () => ({ startRow: 2, endRow: 5 }), isRowFiltered: (row: number) => row === 3 })) } as unknown as SheetsFilterService }]);- injector.add([IUniverInstanceService, { useValue: { getUnit: () => ({ getSheetBySheetId: () => ({ getColumnCount: () => 10 }) }) } as unknown as IUniverInstanceService }]);+ injector.add([IActiveDirtyManagerService, { useClass: TestActiveDirtyManagerService as never }]);+ injector.add([ISheetRowFilteredService, { useClass: TestSheetRowFilteredService as never }]);+ injector.add([SheetsFilterService, { useClass: TestSheetsFilterService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);injector.add([SheetsFilterFormulaService]);injector.get(SheetsFilterFormulaService);});diff --git a/packages/sheets-filter/src/services/__tests__/sheet-filter.service.spec.ts b/packages/sheets-filter/src/services/__tests__/sheet-filter.service.spec.tsnew file mode 100644index 0000000000..7f0375a03a--- /dev/null+++ b/packages/sheets-filter/src/services/__tests__/sheet-filter.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 {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IResourceManagerService,+ IUniverInstanceService,+ ResourceManagerService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { SheetsFilterService } from '../sheet-filter.service';++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IResourceManagerService, { useClass: ResourceManagerService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([SheetsFilterService]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: { 'sheet-1': { id: 'sheet-1' } },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);+ univerInstanceService.focusUnit('unit-1');++ return injector.get(SheetsFilterService);+}++describe('SheetsFilterService', () => {+ it('creates and removes filter models for workbook sheets', () => {+ const service = createService();++ const model = service.ensureFilterModel('unit-1', 'sheet-1');++ expect(service.getFilterModel('unit-1', 'sheet-1')).toBe(model);+ expect(service.removeFilterModel('unit-1', 'sheet-1')).toBe(true);+ expect(service.getFilterModel('unit-1', 'sheet-1')).toBeNull();+ });++ it('publishes filter error messages for UI consumers', () => {+ const service = createService();+ const messages: unknown[] = [];+ const sub = service.errorMsg$.subscribe((message) => messages.push(message));++ service.setFilterErrorMsg('Invalid filter range');++ expect(messages).toEqual([null, 'Invalid filter range']);+ sub.unsubscribe();+ });+});diff --git a/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.ts b/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.tsindex 7291bf956b..80c2fff02c 100644--- a/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.ts+++ b/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.ts@@ -14,30 +14,44 @@* limitations under the License.*/-import { ICommandService, IUndoRedoService } from '@univerjs/core';--import { describe, expect, it, vi } from 'vitest';+import { ICommandService, Injector, IUndoRedoService } from '@univerjs/core';+import { describe, expect, it } from 'vitest';import { SheetReplaceCommand } from '../sheet-replace.command';-describe('SheetReplaceCommand', () => {- it('should batch undo/redo and execute SetRangeValues for replacements', async () => {- const dispose = vi.fn();- const undoRedoService = {- __tempBatchingUndoRedo: vi.fn(() => ({ dispose })),- };+class SequencedCommandService {+ readonly commands: Array<{ id: string; params?: unknown }> = [];+ results: boolean[] = [];++ executeCommand(id: string, params?: unknown): Promise<boolean> {+ this.commands.push({ id, params });+ return Promise.resolve(this.results.shift() ?? true);+ }+}- const executeCommand = vi.fn(async () => true);- const commandService = { executeCommand };+class RecordingUndoRedoService {+ readonly batchingUnits: string[] = [];+ disposeCount = 0;- const accessor = {- get: vi.fn((token: any) => {- if (token === IUndoRedoService) return undoRedoService;- if (token === ICommandService) return commandService;- return null;- }),- } as any;+ __tempBatchingUndoRedo(unitId: string) {+ this.batchingUnits.push(unitId);+ return {+ dispose: () => {+ this.disposeCount++;+ },+ };+ }+}++describe('SheetReplaceCommand', () => {+ it('should batch undo/redo and execute SetRangeValues for replacements', async () => {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: SequencedCommandService as never }]);+ injector.add([IUndoRedoService, { useClass: RecordingUndoRedoService as never }]);+ const commandService = injector.get(ICommandService) as unknown as SequencedCommandService;+ const undoRedoService = injector.get(IUndoRedoService) as unknown as RecordingUndoRedoService;+ commandService.results = [true, true];- const res = await SheetReplaceCommand.handler(accessor, {+ const res = await SheetReplaceCommand.handler(injector, {unitId: 'u1',replacements: [{ subUnitId: 's1', count: 2, value: { 0: { 0: { v: 'a' } } } as any },@@ -45,8 +59,37 @@ describe('SheetReplaceCommand', () => {],});- expect(executeCommand).toHaveBeenCalledTimes(2);- expect(dispose).toHaveBeenCalledTimes(1);+ expect(commandService.commands.map(({ params }) => params)).toMatchObject([+ { unitId: 'u1', subUnitId: 's1' },+ { unitId: 'u1', subUnitId: 's2' },+ ]);+ expect(undoRedoService.batchingUnits).toEqual(['u1']);+ expect(undoRedoService.disposeCount).toBe(1);expect(res).toEqual({ success: 3, failure: 0 });});++ it('should report failed replacement counts when a range update fails', async () => {+ const injector = new Injector();+ injector.add([ICommandService, { useClass: SequencedCommandService as never }]);+ injector.add([IUndoRedoService, { useClass: RecordingUndoRedoService as never }]);+ const commandService = injector.get(ICommandService) as unknown as SequencedCommandService;+ const undoRedoService = injector.get(IUndoRedoService) as unknown as RecordingUndoRedoService;+ commandService.results = [true, false];++ const res = await SheetReplaceCommand.handler(injector, {+ unitId: 'u1',+ replacements: [+ { subUnitId: 's1', count: 2, value: { 0: { 0: { v: 'a' } } } as any },+ { subUnitId: 's2', count: 3, value: { 1: { 1: { v: 'b' } } } as any },+ ],+ });++ expect(commandService.commands.map(({ params }) => params)).toMatchObject([+ { unitId: 'u1', subUnitId: 's1' },+ { unitId: 'u1', subUnitId: 's2' },+ ]);+ expect(undoRedoService.batchingUnits).toEqual(['u1']);+ expect(undoRedoService.disposeCount).toBe(1);+ expect(res).toEqual({ success: 2, failure: 3 });+ });});diff --git a/packages/sheets-find-replace/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-find-replace/src/facade/__tests__/f-univer.spec.tsnew file mode 100644index 0000000000..99559f6ca5--- /dev/null+++ b/packages/sheets-find-replace/src/facade/__tests__/f-univer.spec.ts@@ -0,0 +1,143 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 '@univerjs/core';+import type { IFindMatch, IFindQuery, IReplaceAllResult } from '@univerjs/find-replace';+import type { Observable } from 'rxjs';+import { ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import { FindModel, FindReplaceService, IFindReplaceService } from '@univerjs/find-replace';+import { UniverSheetsPlugin } from '@univerjs/sheets';+import { EMPTY, of } from 'rxjs';+import { describe, expect, it } from 'vitest';+import '../f-univer';++const WORKBOOK_DATA: IWorkbookData = {+ id: 'find-replace-workbook',+ appVersion: '3.0.0-alpha',+ name: 'Find Replace Workbook',+ locale: LocaleType.EN_US,+ sheetOrder: ['sheet-1'],+ styles: {},+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet1',+ rowCount: 10,+ columnCount: 10,+ cellData: {+ 0: {+ 1: { v: 'target value' },+ },+ 2: {+ 0: { v: 'other value' },+ },+ },+ },+ },+};++class TestWorkbookFindModel extends FindModel {+ readonly unitId = WORKBOOK_DATA.id;+ readonly matchesUpdate$: Observable<IFindMatch[]>;+ readonly activelyChangingMatch$: Observable<IFindMatch> = EMPTY;++ private readonly _matches: IFindMatch[];++ constructor(private readonly _query: IFindQuery) {+ super();++ this._matches = this._query.findString === 'target'+ ? [+ {+ provider: 'test-workbook-provider',+ unitId: WORKBOOK_DATA.id,+ range: {+ subUnitId: 'sheet-1',+ range: {+ startRow: 0,+ endRow: 0,+ startColumn: 1,+ endColumn: 1,+ },+ },+ replaceable: true,+ },+ ]+ : [];+ this.matchesUpdate$ = of(this._matches);+ }++ getMatches(): IFindMatch[] {+ return this._matches;+ }++ moveToNextMatch(): IFindMatch | null {+ return this._matches[0] ?? null;+ }++ moveToPreviousMatch(): IFindMatch | null {+ return this._matches[0] ?? null;+ }++ replace(): Promise<boolean> {+ return Promise.resolve(this._matches.length > 0);+ }++ replaceAll(): Promise<IReplaceAllResult> {+ return Promise.resolve({ success: this._matches.length, failure: 0 });+ }++ focusSelection(): void {}+}++class TestWorkbookFindReplaceProvider {+ constructor(@Inject(Injector) private readonly _injector: Injector) {}++ find(query: IFindQuery): Promise<FindModel[]> {+ return Promise.resolve([this._injector.createInstance(TestWorkbookFindModel, query)]);+ }++ terminate(): void {}+}++function createFindReplaceFacade() {+ const univer = new Univer();+ const injector = univer.__getInjector();+ univer.registerPlugin(UniverSheetsPlugin);++ const workbook = univer.createUnit(UniverInstanceType.UNIVER_SHEET, WORKBOOK_DATA);+ injector.add([IFindReplaceService, { useClass: FindReplaceService }]);+ injector.add([TestWorkbookFindReplaceProvider]);++ const findReplaceService = injector.get(IFindReplaceService);+ findReplaceService.registerFindReplaceProvider(injector.get(TestWorkbookFindReplaceProvider));+ injector.get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ return FUniver.newAPI(univer);+}++describe('FUniverSheetsFindReplaceMixin', () => {+ it('creates a text finder that searches the focused workbook', async () => {+ const univerAPI = createFindReplaceFacade();++ const finder = await univerAPI.createTextFinderAsync('target');+ const matches = finder?.findAll() ?? [];++ expect(matches.map((range) => range.getA1Notation())).toEqual(['B1']);+ });+});diff --git a/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts b/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.tsindex b48d63fb77..3fdf66b36d 100644--- a/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts+++ b/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts@@ -14,48 +14,115 @@* limitations under the License.*/-import type { ISheetFindReplaceHighlightShapeProps } from '../find-replace-highlight.shape';-import { Rect } from '@univerjs/engine-render';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import { SheetFindReplaceHighlightShape } from '../find-replace-highlight.shape';-vi.mock('@univerjs/engine-render', async () => {- const actual = await vi.importActual<typeof import('@univerjs/engine-render')>('@univerjs/engine-render');- return {- ...actual,- Rect: {- drawWith: vi.fn(),- },- Shape: class {- width = 0;- height = 0;- constructor(_key?: string, _props?: unknown) {}- transformByState(state: { width?: number; height?: number }) {- if (state.width) this.width = state.width;- if (state.height) this.height = state.height;- }- },- };-});+class TestCanvasContext {+ fillStyle = '';+ strokeStyle = '';+ lineWidth = 0;+ lineCap = '';+ lineDashOffset = 0;+ lineJoin = '';+ miterLimit = 0;+ fillCount = 0;+ strokeCount = 0;+ readonly rects: Array<{ left: number; top: number; width: number; height: number }> = [];++ save(): void {}++ restore(): void {}++ beginPath(): void {}++ closePath(): void {}++ setLineDash(): void {}++ rect(left: number, top: number, width: number, height: number): void {+ this.rects.push({ left, top, width, height });+ }++ fill(): void {+ this.fillCount += 1;+ }++ stroke(): void {+ this.strokeCount += 1;+ }+}++function drawShape(shape: SheetFindReplaceHighlightShape, context: TestCanvasContext): void {+ (shape as unknown as { _draw: (ctx: TestCanvasContext) => void })._draw(context);+}describe('SheetFindReplaceHighlightShape', () => {- it('should update props and draw activated border', () => {- const shape = new SheetFindReplaceHighlightShape('k', {+ it('draws a translucent search result highlight without a border by default', () => {+ const shape = new SheetFindReplaceHighlightShape('result', {inHiddenRange: false,color: { r: 1, g: 2, b: 3 },width: 10,height: 20,- } satisfies ISheetFindReplaceHighlightShapeProps);+ });+ const context = new TestCanvasContext();++ drawShape(shape, context);++ expect(context.rects).toEqual([{ left: 0, top: 0, width: 10, height: 20 }]);+ expect(context.fillStyle).toBe('rgba(1, 2, 3, 0.35)');+ expect(context.fillCount).toBe(1);+ expect(context.strokeCount).toBe(0);+ });++ it('draws the current search result with a solid two-pixel border', () => {+ const shape = new SheetFindReplaceHighlightShape('active-result', {+ inHiddenRange: false,+ color: { r: 4, g: 5, b: 6 },+ width: 10,+ height: 20,+ });+ shape.setShapeProps({+ activated: true,+ width: 30,+ height: 40,+ });+ const context = new TestCanvasContext();++ drawShape(shape, context);++ expect(context.rects).toEqual([{ left: 0, top: 0, width: 30, height: 40 }]);+ expect(context.fillStyle).toBe('rgba(4, 5, 6, 0.35)');+ expect(context.strokeStyle).toBe('rgb(4, 5, 6)');+ expect(context.lineWidth).toBe(2);+ expect(context.strokeCount).toBe(1);+ });++ it('removes the current result border after the shape is deactivated', () => {+ const shape = new SheetFindReplaceHighlightShape('active-result', {+ inHiddenRange: false,+ color: { r: 7, g: 8, b: 9 },+ activated: true,+ width: 10,+ height: 20,+ });+ const activeContext = new TestCanvasContext();++ drawShape(shape, activeContext);- const drawableShape = shape as SheetFindReplaceHighlightShape & {- _draw(ctx: CanvasRenderingContext2D): void;- };+ expect(activeContext.strokeStyle).toBe('rgb(7, 8, 9)');+ expect(activeContext.strokeCount).toBe(1);++ shape.setShapeProps({+ activated: false,+ width: 10,+ height: 20,+ });+ const inactiveContext = new TestCanvasContext();- shape.setShapeProps({ activated: true, width: 10, height: 20 });- drawableShape._draw({} as CanvasRenderingContext2D);+ drawShape(shape, inactiveContext);- expect(Rect.drawWith).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({- strokeWidth: 2,- }));+ expect(inactiveContext.fillStyle).toBe('rgba(7, 8, 9, 0.35)');+ expect(inactiveContext.lineWidth).toBe(0);+ expect(inactiveContext.strokeCount).toBe(0);});});diff --git a/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.ts b/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.tsindex 5d0a3a45c1..3628c6c2f8 100644--- a/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.ts+++ b/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.ts@@ -14,14 +14,19 @@* limitations under the License.*/-import type { IAccessor } from '@univerjs/core';+import type { IAccessor, IDocumentData } from '@univerjs/core';+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { IEditorService } from '@univerjs/docs-ui';import { ISidebarService } from '@univerjs/ui';import { describe, expect, it, vi } from 'vitest';import { IFormulaPromptService } from '../../../services/prompt.service';import { MORE_FUNCTIONS_COMPONENT } from '../../../views/more-functions/interface';import { HelpFunctionOperation } from '../help-function.operation';import { MoreFunctionsOperation } from '../more-functions.operation';+import { ReferenceAbsoluteOperation } from '../reference-absolute.operation';import { SearchFunctionOperation } from '../search-function.operation';+import { createCommandTestBed } from './create-command-test-bed';function createAccessor() {const promptService = { help: vi.fn(), search: vi.fn() };@@ -43,6 +48,90 @@ function createAccessor() {return { accessor, promptService, sidebarService };}+class TestFormulaEditor {+ readonly selectionRanges: Array<{ startOffset: number; endOffset: number; collapsed: boolean }> = [];+ private _editorId = DOCS_NORMAL_EDITOR_UNIT_ID_KEY;+ private _documentData: IDocumentData = {+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ body: {+ dataStream: '=A1\r\n',+ },+ documentStyle: {},+ };++ setEditorId(editorId: string) {+ this._editorId = editorId;+ }++ setFormulaText(formulaText: string) {+ this._documentData = {+ ...this._documentData,+ body: {+ dataStream: `${formulaText}\r\n`,+ },+ };+ }++ getEditorId() {+ return this._editorId;+ }++ getDocumentData() {+ return this._documentData;+ }++ replaceText(text: string, ranges: Array<{ startOffset: number; endOffset: number; collapsed: boolean }>) {+ this.setFormulaText(text);+ this.selectionRanges.length = 0;+ this.selectionRanges.push(...ranges);+ }+}++class TestEditorService {+ readonly editor = new TestFormulaEditor();+ private _hasFocusEditor = true;++ setHasFocusEditor(hasFocusEditor: boolean) {+ this._hasFocusEditor = hasFocusEditor;+ }++ getFocusEditor() {+ return this._hasFocusEditor ? this.editor : null;+ }++ getEditor() {+ return this.editor;+ }++ register() {+ return { dispose: () => {} };+ }++ getAllEditor() {+ return new Map();+ }++ isEditor() {+ return true;+ }++ getEditorRenderConfig() {+ return null;+ }++ isSheetEditor() {+ return false;+ }++ blur$ = { subscribe: () => ({ unsubscribe: () => {} }) };+ focus$ = { subscribe: () => ({ unsubscribe: () => {} }) };+ blur() {}+ focus() {}+ getFocusId() {+ return DOCS_NORMAL_EDITOR_UNIT_ID_KEY;+ }+}+describe('formula UI operations', () => {it('delegates help and search actions to the prompt service', async () => {const { accessor, promptService } = createAccessor();@@ -63,4 +152,66 @@ describe('formula UI operations', () => {children: { label: MORE_FUNCTIONS_COMPONENT },});});++ it('toggles the reference under the formula editor caret to the next absolute-reference state', async () => {+ const testBed = createCommandTestBed(undefined, [+ [IEditorService, { useClass: TestEditorService as never }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(ReferenceAbsoluteOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: '=A1'.length,+ endOffset: '=A1'.length,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const editorService = testBed.get(IEditorService) as unknown as TestEditorService;++ expect(await commandService.executeCommand(ReferenceAbsoluteOperation.id)).toBe(true);++ expect(editorService.editor.getDocumentData().body?.dataStream).toBe('=$A$1\r\n');+ expect(editorService.editor.selectionRanges).toEqual([{+ startOffset: '=$A$1'.length,+ endOffset: '=$A$1'.length,+ collapsed: true,+ }]);++ testBed.univer.dispose();+ });++ it('does not change formula text when there is no focused formula editor or no reference at the caret', async () => {+ const testBed = createCommandTestBed(undefined, [+ [IEditorService, { useClass: TestEditorService as never }],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(ReferenceAbsoluteOperation);+ const selectionManager = testBed.get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: '=SUM('.length,+ endOffset: '=SUM('.length,+ collapsed: true,+ isActive: true,+ segmentId: '',+ }]);+ const editorService = testBed.get(IEditorService) as unknown as TestEditorService;+ editorService.editor.setFormulaText('=SUM(1, 2)');++ expect(await commandService.executeCommand(ReferenceAbsoluteOperation.id)).toBe(false);+ expect(editorService.editor.getDocumentData().body?.dataStream).toBe('=SUM(1, 2)\r\n');++ editorService.setHasFocusEditor(false);+ expect(await commandService.executeCommand(ReferenceAbsoluteOperation.id)).toBe(false);++ testBed.univer.dispose();+ });});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.tsindex 270dbb2f4a..d79e28536d 100644--- a/packages/sheets-formula-ui/src/services/__tests__/prompt.service.spec.ts+++ b/packages/sheets-formula-ui/src/services/__tests__/prompt.service.spec.ts@@ -14,9 +14,8 @@* limitations under the License.*/-import type { IContextService } from '@univerjs/core';import type { ISequenceNode } from '@univerjs/engine-formula';-import { Direction } from '@univerjs/core';+import { Direction, IContextService, Injector } from '@univerjs/core';import { sequenceNodeType } from '@univerjs/engine-formula';import { map, Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';@@ -31,12 +30,10 @@ function createReferenceNode(token: string, startIndex: number, endIndex: number} as ISequenceNode;}-function createContextService(): IContextService {+function createService() {const contextChanged$ = new Subject<{ [key: string]: boolean }>();const contextMap = new Map<string, boolean>();-- return {- contextChanged$: contextChanged$.asObservable(),+ const contextService = {getContextValue: vi.fn((key: string) => contextMap.get(key) ?? false),setContextValue: vi.fn((key: string, value: boolean) => {contextMap.set(key, value);@@ -44,12 +41,26 @@ function createContextService(): IContextService {}),subscribeContextValue$: vi.fn((key: string) => contextChanged$.pipe(map((event) => event[key] ?? false))),};++ class TestContextService {+ contextChanged$ = contextChanged$.asObservable();+ getContextValue = contextService.getContextValue;+ setContextValue = contextService.setContextValue;+ subscribeContextValue$ = contextService.subscribeContextValue$;+ }++ const injector = new Injector();+ injector.add([IContextService, { useClass: TestContextService }]);+ injector.add([FormulaPromptService]);+ return {+ contextService,+ service: injector.get(FormulaPromptService),+ };}describe('FormulaPromptService', () => {it('tracks prompt visibility and forwards prompt events', () => {- const contextService = createContextService();- const service = new FormulaPromptService(contextService);+ const { contextService, service } = createService();const searchEvents: unknown[] = [];const helpEvents: unknown[] = [];const navigateEvents: unknown[] = [];@@ -81,7 +92,7 @@ describe('FormulaPromptService', () => {});it('updates and inserts sequence nodes while keeping later reference indexes aligned', () => {- const service = new FormulaPromptService(createContextService());+ const { service } = createService();service.setSequenceNodes(['=',diff --git a/packages/sheets-formula-ui/src/services/__tests__/range-selector.service.spec.ts b/packages/sheets-formula-ui/src/services/__tests__/range-selector.service.spec.tsnew file mode 100644index 0000000000..24aedbc687--- /dev/null+++ b/packages/sheets-formula-ui/src/services/__tests__/range-selector.service.spec.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IUnitRangeName } from '@univerjs/core';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { GlobalRangeSelectorService } from '../range-selector.service';++function createService(): GlobalRangeSelectorService {+ const injector = new Injector();+ injector.add([GlobalRangeSelectorService]);+ return injector.get(GlobalRangeSelectorService);+}++describe('GlobalRangeSelectorService', () => {+ it('opens a range selector request and resolves with the ranges picked by the user', async () => {+ const service = createService();+ const shown: unknown[] = [];+ const selectedRanges: IUnitRangeName[] = [{+ unitId: 'unit-1',+ sheetName: 'Sheet1',+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ }];+ const callbackRanges: IUnitRangeName[][] = [];+ const sub = service.currentSelector$.subscribe((value) => shown.push(value));++ const promise = service.showRangeSelectorDialog({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ callback: (ranges) => callbackRanges.push(ranges),+ });+ const selector = shown.at(-1) as { callback: (ranges: IUnitRangeName[]) => void };+ selector.callback(selectedRanges);++ await expect(promise).resolves.toEqual(selectedRanges);+ expect(callbackRanges).toEqual([selectedRanges]);+ expect(shown[0]).toBeNull();++ sub.unsubscribe();+ });+});diff --git a/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts b/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.tsnew file mode 100644index 0000000000..4f134cd9f0--- /dev/null+++ b/packages/sheets-formula-ui/src/services/render-services/__tests__/ref-selections.render.service.spec.ts@@ -0,0 +1,638 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IWorkbookData, Workbook } from '@univerjs/core';+import type { IRenderContext } from '@univerjs/engine-render';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import {+ IContextService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ RANGE_TYPE,+ toDisposable,+ Tools,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';+import {+ IRefSelectionsService,+ REF_SELECTIONS_ENABLED,+ RefSelectionsService,+ SelectionMoveType,+ SELECTIONS_ENABLED,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { SHEET_VIEW_KEY, SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { IShortcutService } from '@univerjs/ui';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { RefSelectionsRenderService } from '../ref-selections.render.service';++function createTestEvent<TEvent, TState = { stopPropagation: () => void }>() {+ const handlers = new Set<(evt: TEvent, state: TState) => void>();+ return {+ subscribeEvent(handler: (evt: TEvent, state: TState) => void): IDisposable {+ handlers.add(handler);+ const dispose = () => handlers.delete(handler);+ return { dispose, unsubscribe: dispose } as unknown as IDisposable;+ },+ emit(evt: TEvent, state: TState): void {+ for (const handler of handlers) {+ handler(evt, state);+ }+ },+ };+}++function createFakeEngine() {+ return {+ width: 800,+ height: 600,+ beginFrame$: new Subject<void>(),+ endFrame$: new Subject<unknown>(),+ renderFrameTimeMetric$: new Subject<[string, number]>(),+ renderFrameTags$: new Subject<[string, unknown]>(),+ runRenderLoop: (cb: () => void) => cb(),+ stopRenderLoop: () => undefined,+ };+}++function createFakeViewport(viewportKey: string, options: { canvasWidth: number; canvasHeight: number }) {+ return {+ viewportKey,+ viewportScrollX: 0,+ viewportScrollY: 0,+ scrollX: 0,+ scrollY: 0,+ isActive: true,+ left: 0,+ top: 0,+ width: options.canvasWidth,+ height: options.canvasHeight,+ marginLeft: 0,+ marginTop: 0,+ onScrollAfter$: createTestEvent<unknown>(),+ onScrollByBar$: createTestEvent<unknown>(),+ limitedScroll: () => ({ isLimitedX: false, isLimitedY: false }),+ scrollToViewportPos: ({ viewportScrollX, viewportScrollY }: { viewportScrollX: number; viewportScrollY: number }) => {+ return { viewportScrollX, viewportScrollY };+ },+ updateScrollVal: () => undefined,+ scrollByViewportDeltaVal: () => true,+ transViewportScroll2ScrollValue: (x: number, y: number) => ({ x, y }),+ transScroll2ViewportScrollValue: (x: number, y: number) => ({ x, y }),+ enable: () => undefined,+ disable: () => undefined,+ setMargin: () => undefined,+ setViewportSize: () => undefined,+ setPadding: () => undefined,+ resetPadding: () => undefined,+ resizeWhenFreezeChange: () => undefined,+ calcViewportInfo: () => ({ viewBound: null }),+ getScrollBar: () => null,+ };+}++function createFakeScene(viewportMap: Map<unknown, ReturnType<typeof createFakeViewport>>, engine: ReturnType<typeof createFakeEngine>) {+ const layers = new Map<number, unknown>();+ const scene = {+ scaleX: 1,+ scaleY: 1,+ onMouseWheel$: createTestEvent<unknown>(),+ onTransformChange$: createTestEvent<unknown>(),+ onPointerMove$: createTestEvent<unknown>(),+ onPointerUp$: createTestEvent<unknown>(),+ addObjects: (objects: Array<{ parent?: unknown }>) => {+ for (const object of objects) {+ object.parent = scene;+ }+ },+ addObject: (object: { parent?: unknown }) => {+ object.parent = scene;+ },+ removeObject: () => undefined,+ addLayer: (layer: { zIndex?: number }) => {+ if (typeof layer.zIndex === 'number') {+ layers.set(layer.zIndex, layer);+ }+ },+ findLayerByZIndex: (zIndex: number) => layers.get(zIndex) ?? null,+ disableObjectsEvent: () => undefined,+ enableObjectsEvent: () => undefined,+ enableLayerCache: () => undefined,+ makeDirty: () => undefined,+ getViewport: (key: unknown) => viewportMap.get(key) ?? null,+ getMainViewport: () => viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN)!,+ getViewports: () => Array.from(viewportMap.values()),+ getActiveViewportByCoord: () => viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) ?? null,+ findViewportByPosToScene: () => viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) ?? null,+ getViewportScrollXY: (viewport: { viewportScrollX: number; viewportScrollY: number }) => ({ x: viewport.viewportScrollX, y: viewport.viewportScrollY }),+ getParent: () => ({ classType: 'SCENE' }),+ getTransformer: () => ({+ clearSelectedObjects: () => undefined,+ }),+ getCoordRelativeToViewport: (vec: { x?: number; y?: number } | number[]) => ({+ x: Array.isArray(vec) ? vec[0] : vec.x ?? 0,+ y: Array.isArray(vec) ? vec[1] : vec.y ?? 0,+ }),+ getScrollXYInfoByViewport: (_coords: unknown, viewport?: { viewportScrollX: number; viewportScrollY: number } | null) => ({ x: viewport?.viewportScrollX ?? 0, y: viewport?.viewportScrollY ?? 0 }),+ getAncestorScale: () => ({ scaleX: scene.scaleX, scaleY: scene.scaleY }),+ setCursor: () => undefined,+ resetCursor: () => undefined,+ getEngine: () => engine,+ transformByState: () => undefined,+ scale: (x: number, y: number) => {+ scene.scaleX = x;+ scene.scaleY = y;+ },+ };+ return scene;+}++function createFakeSkeleton(options?: {+ getLocation?: () => [string, string];+ worksheet?: {+ getRowCount: () => number;+ getColumnCount: () => number;+ getSheetId: () => string;+ getCellInfoInMergeData: (row: number, col: number) => {+ startRow: number;+ startColumn: number;+ endRow: number;+ endColumn: number;+ isMerged: boolean;+ isMergedMainCell: boolean;+ };+ };+}) {+ const rowHeight = 20;+ const colWidth = 100;+ return {+ rowHeaderWidth: 46,+ columnHeaderHeight: 20,+ rowHeaderWidthAndMarginLeft: 46,+ columnHeaderHeightAndMarginTop: 20,+ getCellWithCoordByIndex: (row: number, col: number) => ({+ startX: col * colWidth,+ startY: row * rowHeight,+ endX: (col + 1) * colWidth,+ endY: (row + 1) * rowHeight,+ }),+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => ({+ startX: col * colWidth,+ startY: row * rowHeight,+ endX: (col + 1) * colWidth,+ endY: (row + 1) * rowHeight,+ }),+ getCellIndexByOffset: (x: number, y: number) => ({+ row: Math.max(0, Math.floor(y / rowHeight)),+ column: Math.max(0, Math.floor(x / colWidth)),+ }),+ getCellByOffset: (x: number, y: number) => {+ const row = Math.max(0, Math.floor(y / rowHeight));+ const column = Math.max(0, Math.floor(x / colWidth));+ return {+ startRow: row,+ endRow: row,+ startColumn: column,+ endColumn: column,+ actualRow: row,+ actualColumn: column,+ isMerged: false,+ isMergedMainCell: false,+ };+ },+ getColumnCount: () => 20,+ getRowCount: () => 20,+ getWorksheetConfig: () => ({ freeze: { startRow: 0, startColumn: 0, xSplit: 0, ySplit: 0 } }),+ getLocation: options?.getLocation ?? (() => ['test', 'sheet1'] as [string, string]),+ worksheet: options?.worksheet ?? {+ getRowCount: () => 20,+ getColumnCount: () => 20,+ getSheetId: () => 'sheet1',+ getCellInfoInMergeData: (row: number, col: number) => ({+ startRow: row,+ startColumn: col,+ endRow: row,+ endColumn: col,+ isMerged: false,+ isMergedMainCell: false,+ }),+ },+ };+}++const WORKBOOK_DATA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ },+};++class TestShortcutService {+ forceEscape(): IDisposable {+ return toDisposable(() => undefined);+ }+}++class TestSheetSkeletonManagerService {+ private readonly _currentSkeleton$ = new BehaviorSubject<unknown>(null);+ readonly currentSkeleton$ = this._currentSkeleton$.asObservable();+ private _currentParam: unknown;++ emitCurrentSkeleton(param: unknown): void {+ this._currentParam = param;+ this._currentSkeleton$.next(param);+ }++ getCurrentParam(): unknown {+ return this._currentParam;+ }++ getCurrentSkeleton() {+ return (this._currentParam as { skeleton?: unknown } | null)?.skeleton ?? null;+ }++ getSkeletonParam() {+ return this._currentParam;+ }+}++function createSelection(startRow: number, startColumn: number): ISelectionWithStyle {+ return {+ range: {+ startRow,+ endRow: startRow,+ startColumn,+ endColumn: startColumn,+ rangeType: RANGE_TYPE.NORMAL,+ },+ primary: {+ startRow,+ endRow: startRow,+ startColumn,+ endColumn: startColumn,+ actualRow: startRow,+ actualColumn: startColumn,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ };+}++function createRefSelectionTestBed() {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'ref-selection-render-test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ this._injector.add([SheetsSelectionsService]);+ this._injector.add([IRefSelectionsService, { useClass: RefSelectionsService }]);+ this._injector.add([IShortcutService, { useClass: TestShortcutService as never }]);+ this._injector.add([SheetSkeletonManagerService, { useClass: TestSheetSkeletonManagerService as never }]);+ }+ }++ univer.registerPlugin(TestPlugin);+ const workbook = univer.createUnit<IWorkbookData, Workbook>(+ UniverInstanceType.UNIVER_SHEET,+ Tools.deepClone(WORKBOOK_DATA)+ );++ injector.get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ const localeService = injector.get(LocaleService);+ localeService.setLocale(LocaleType.EN_US);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);+ const contextService = injector.get(IContextService);+ contextService.setContextValue(SELECTIONS_ENABLED, true);+ contextService.setContextValue(REF_SELECTIONS_ENABLED, true);++ const engine = createFakeEngine();+ const viewportMap = new Map<unknown, ReturnType<typeof createFakeViewport>>();+ const viewportKeys = [+ SHEET_VIEWPORT_KEY.VIEW_MAIN,+ SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP,+ SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT,+ SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,+ ];+ for (const viewportKey of viewportKeys) {+ viewportMap.set(viewportKey, createFakeViewport(viewportKey, { canvasWidth: engine.width, canvasHeight: engine.height }));+ }++ const scene = createFakeScene(viewportMap, engine);+ const components = new Map<unknown, unknown>();+ components.set(SHEET_VIEW_KEY.ROW, { zIndex: 2, onPointerDown$: createTestEvent<unknown>(), dispose: () => undefined });+ components.set(SHEET_VIEW_KEY.COLUMN, { zIndex: 2, onPointerDown$: createTestEvent<unknown>(), dispose: () => undefined });+ components.set(SHEET_VIEW_KEY.LEFT_TOP, { onPointerDown$: createTestEvent<unknown>(), dispose: () => undefined });+ const mainComponent = {+ zIndex: 1,+ onPointerDown$: createTestEvent<unknown>(),+ makeForceDirty: () => undefined,+ };+ const context = {+ unitId: workbook.getUnitId(),+ unit: workbook,+ type: UniverInstanceType.UNIVER_SHEET,+ engine,+ scene,+ mainComponent,+ components,+ isMainScene: true,+ activated$: new BehaviorSubject(true),+ activate: () => undefined,+ deactivate: () => undefined,+ } as unknown as IRenderContext<Workbook>;+ const skeleton = createFakeSkeleton();+ const skeletonManager = injector.get(SheetSkeletonManagerService) as unknown as TestSheetSkeletonManagerService;+ const service = injector.createInstance(RefSelectionsRenderService, context);++ skeletonManager.emitCurrentSkeleton({+ unitId: workbook.getUnitId(),+ sheetId: 'sheet1',+ skeleton,+ });++ return {+ univer,+ injector,+ workbook,+ service,+ scene,+ mainComponent,+ rowHeader: components.get(SHEET_VIEW_KEY.ROW) as { onPointerDown$: ReturnType<typeof createTestEvent<unknown>> },+ columnHeader: components.get(SHEET_VIEW_KEY.COLUMN) as { onPointerDown$: ReturnType<typeof createTestEvent<unknown>> },+ leftTop: components.get(SHEET_VIEW_KEY.LEFT_TOP) as { onPointerDown$: ReturnType<typeof createTestEvent<unknown>> },+ skeleton,+ skeletonManager,+ refSelectionsService: injector.get(IRefSelectionsService),+ };+}++describe('RefSelectionsRenderService', () => {+ const disposables: Array<ReturnType<typeof createRefSelectionTestBed>> = [];++ afterEach(() => {+ while (disposables.length > 0) {+ disposables.pop()!.univer.dispose();+ }+ });++ it('renders formula reference selections from the ref selection model', () => {+ const testBed = createRefSelectionTestBed();+ disposables.push(testBed);+ const { service, refSelectionsService, workbook } = testBed;++ refSelectionsService.setSelections(workbook.getUnitId(), 'sheet1', [+ createSelection(1, 1),+ createSelection(2, 2),+ ], SelectionMoveType.ONLY_SET);++ expect(service.getSelectionControls()).toHaveLength(2);+ expect(service.getSelectionDataWithStyle()).toEqual([+ expect.objectContaining({+ rangeWithCoord: expect.objectContaining({+ unitId: workbook.getUnitId(),+ sheetId: 'sheet1',+ startRow: 1,+ startColumn: 1,+ }),+ }),+ expect.objectContaining({+ rangeWithCoord: expect.objectContaining({+ unitId: workbook.getUnitId(),+ sheetId: 'sheet1',+ startRow: 2,+ startColumn: 2,+ }),+ }),+ ]);++ service.clearLastSelection();+ expect(service.getSelectionControls()).toHaveLength(1);+ });++ it('syncs user-driven formula selections back to the ref selection model', () => {+ const testBed = createRefSelectionTestBed();+ disposables.push(testBed);+ const { service, refSelectionsService, workbook } = testBed;++ service.resetSelectionsByModelData([createSelection(4, 3)]);+ service.refreshSelectionMoveStart();+ service.refreshSelectionMoveEnd();++ const workbookSelections = refSelectionsService.getWorkbookSelections(workbook.getUnitId());+ expect(workbookSelections.getCurrentSelections()).toEqual([+ expect.objectContaining({+ range: expect.objectContaining({+ startRow: 4,+ startColumn: 3,+ rangeType: RANGE_TYPE.NORMAL,+ }),+ }),+ ]);+ });++ it('clears old controls when the active sheet skeleton changes', () => {+ const testBed = createRefSelectionTestBed();+ disposables.push(testBed);+ const { service, skeletonManager, workbook } = testBed;++ service.resetSelectionsByModelData([createSelection(1, 1)]);+ expect(service.getSelectionControls()).toHaveLength(1);++ const sheet2Skeleton = createFakeSkeleton({+ getLocation: () => [workbook.getUnitId(), 'sheet2'],+ worksheet: {+ getRowCount: () => 20,+ getColumnCount: () => 20,+ getSheetId: () => 'sheet2',+ getCellInfoInMergeData: (row: number, col: number) => ({+ startRow: row,+ startColumn: col,+ endRow: row,+ endColumn: col,+ isMerged: false,+ isMergedMainCell: false,+ }),+ },+ });++ skeletonManager.emitCurrentSkeleton({+ unitId: workbook.getUnitId(),+ sheetId: 'sheet2',+ skeleton: sheet2Skeleton,+ });++ expect(service.getLocation()).toEqual([workbook.getUnitId(), 'sheet2']);+ expect(service.getSelectionControls()).toHaveLength(0);+ });++ it('enables and disables formula ref-selection interaction mode idempotently', () => {+ const testBed = createRefSelectionTestBed();+ disposables.push(testBed);+ const { service } = testBed;++ service.setRemainLastEnabled(false);+ service.setSkipLastEnabled(true);+ const disposable = service.enableSelectionChanging();+ service.disableSelectionChanging();+ disposable.dispose();++ expect(service.getSelectionControls()).toEqual([]);+ });++ it('updates formula reference selections from spreadsheet pointer selection', () => {+ const testBed = createRefSelectionTestBed();+ disposables.push(testBed);+ const { service, mainComponent, scene, refSelectionsService, workbook } = testBed;+ const stoppedEvents: string[] = [];++ const selectionChanging = service.enableSelectionChanging();+ mainComponent.onPointerDown$.emit({+ offsetX: 150,+ offsetY: 45,+ button: 0,+ shiftKey: false,+ ctrlKey: false,+ }, {+ stopPropagation: () => stoppedEvents.push('spreadsheet'),+ });++ expect(stoppedEvents).toEqual(['spreadsheet']);+ expect(service.getSelectionControls()).toHaveLength(1);+ expect(service.getSelectionDataWithStyle()[0].rangeWithCoord).toEqual(expect.objectContaining({+ startRow: 2,+ endRow: 2,+ startColumn: 1,+ endColumn: 1,+ rangeType: RANGE_TYPE.NORMAL,+ }));++ scene.onPointerUp$.emit({}, { stopPropagation: () => undefined });+ const workbookSelections = refSelectionsService.getWorkbookSelections(workbook.getUnitId());+ expect(workbookSelections.getCurrentSelections()).toEqual([+ expect.objectContaining({+ range: expect.objectContaining({+ startRow: 2,+ endRow: 2,+ startColumn: 1,+ endColumn: 1,+ }),+ }),+ ]);++ selectionChanging.dispose();+ });++ it('updates formula reference selections from row, column and sheet header gestures', () => {+ const testBed = createRefSelectionTestBed();+ disposables.push(testBed);+ const { service, rowHeader, columnHeader, leftTop, scene } = testBed;+ const stoppedEvents: string[] = [];+ const selectionChanging = service.enableSelectionChanging();++ rowHeader.onPointerDown$.emit({+ offsetX: 10,+ offsetY: 65,+ button: 0,+ shiftKey: false,+ ctrlKey: false,+ }, {+ stopPropagation: () => stoppedEvents.push('row'),+ });+ expect(service.getSelectionDataWithStyle()[0].rangeWithCoord).toEqual(expect.objectContaining({+ startRow: 3,+ endRow: 3,+ startColumn: 0,+ endColumn: 19,+ rangeType: RANGE_TYPE.ROW,+ }));+ scene.onPointerUp$.emit({}, { stopPropagation: () => undefined });+ service.clearLastSelection();++ columnHeader.onPointerDown$.emit({+ offsetX: 250,+ offsetY: 10,+ button: 0,+ shiftKey: false,+ ctrlKey: false,+ }, {+ stopPropagation: () => stoppedEvents.push('column'),+ });+ expect(service.getSelectionDataWithStyle()[0].rangeWithCoord).toEqual(expect.objectContaining({+ startRow: 0,+ endRow: 19,+ startColumn: 2,+ endColumn: 2,+ rangeType: RANGE_TYPE.COLUMN,+ }));+ scene.onPointerUp$.emit({}, { stopPropagation: () => undefined });++ leftTop.onPointerDown$.emit({+ offsetX: 5,+ offsetY: 5,+ button: 0,+ }, {+ stopPropagation: () => stoppedEvents.push('all'),+ });+ expect(service.getSelectionDataWithStyle()[0].rangeWithCoord).toEqual(expect.objectContaining({+ startRow: 0,+ endRow: 19,+ startColumn: 0,+ endColumn: 19,+ }));+ scene.onPointerUp$.emit({}, { stopPropagation: () => undefined });++ expect(stoppedEvents).toEqual(['row', 'column', 'all']);+ selectionChanging.dispose();+ });+});diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.tsindex 5fe6c6b3ee..7100e681e5 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-search.spec.ts@@ -19,6 +19,22 @@ import { describe, expect, it } from 'vitest';import { getFormulaReplaceResult } from '../use-formula-search';describe('getFormulaReplaceResult', () => {+ it('adds the call bracket when replacing a typed function prefix and keeps the rest of the formula', () => {+ expect(getFormulaReplaceResult(+ [+ { nodeType: sequenceNodeType.FUNCTION, token: 'SU', startIndex: 0, endIndex: 1 },+ 'A1:A3)',+ '+B1',+ ],+ 0,+ 'SUM',+ FunctionType.Math+ )).toEqual({+ text: 'SUM(A1:A3)+B1',+ offset: -2,+ });+ });+it('does not append an open bracket when replacing table names', () => {expect(getFormulaReplaceResult([{ nodeType: sequenceNodeType.FUNCTION, token: 'Ord', startIndex: 0, endIndex: 2 }],diff --git a/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts b/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.tsindex 14b993ea38..58463ba560 100644--- a/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts@@ -14,9 +14,11 @@* limitations under the License.*/+import { RANGE_TYPE } from '@univerjs/core';import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';import { describe, expect, it } from 'vitest';import { filterReferenceNode, isComma, isReference } from '../filter-reference-node';+import { unitRangesToText } from '../unit-ranges-to-text';import { verifyRange } from '../verify-range';const referenceNode = { nodeType: sequenceNodeType.REFERENCE, token: 'A1' };@@ -39,4 +41,23 @@ describe('range selector utils', () => {expect(verifyRange([referenceNode as never, functionNode as never])).toBe(false);expect(verifyRange([referenceNode as never, ';'])).toBe(false);});++ it('serializes selected ranges with sheet and workbook qualifiers only when the formula needs them', () => {+ const ranges = [+ {+ unitId: 'book-1',+ sheetName: 'Sheet1',+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },+ },+ {+ unitId: 'book-1',+ sheetName: 'Data Sheet',+ range: { startRow: 2, endRow: 2, startColumn: 3, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },+ },+ ];++ expect(unitRangesToText(ranges, false, 'Sheet1')).toEqual(['A1:B2', 'D3']);+ expect(unitRangesToText(ranges, true, 'Sheet1')).toEqual(['A1:B2', "'Data Sheet'!D3"]);+ expect(unitRangesToText(ranges, true, 'Sheet1', true)).toEqual(["'[book-1]Sheet1'!A1:B2", "'[book-1]Data Sheet'!D3"]);+ });});diff --git a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.tsindex a80edffef4..2edc870118 100644--- a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts+++ b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts@@ -17,11 +17,28 @@import type { Injector } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';import { ICommandService, IConfigService, LifecycleService, LifecycleStages } from '@univerjs/core';-import { FormulaExecutedStateType, FormulaExecuteStageType, IFunctionService, ISuperTableService, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaCalculationStartMutation, SetTriggerFormulaCalculationStartMutation, SuperTableService } from '@univerjs/engine-formula';+import {+ FormulaExecutedStateType,+ FormulaExecuteStageType,+ IFunctionService,+ ISuperTableService,+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaCalculationStartMutation,+ SetTriggerFormulaCalculationStartMutation,+ SuperTableService,+} from '@univerjs/engine-formula';import { SetRangeValuesMutation } from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { FormulaCalculationSessionController } from '../../controllers/formula-calculation-session.controller';-import { CalculationMode, DescriptionService, IDescriptionService, IRegisterFunctionService, PLUGIN_CONFIG_KEY_BASE, RegisterFunctionService } from '../../index';+import {+ CalculationMode,+ DescriptionService,+ IDescriptionService,+ IRegisterFunctionService,+ PLUGIN_CONFIG_KEY_BASE,+ RegisterFunctionService,+} from '../../index';import { FormulaCalculationSessionService } from '../../services/formula-calculation-session.service';import { createFacadeTestBed } from './create-test-bed';diff --git a/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts b/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.tsindex 650fff4dd2..0eb084fa8b 100644--- a/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts+++ b/packages/sheets-formula/src/services/__tests__/formula-calculation-session.service.spec.ts@@ -15,10 +15,17 @@*/import type { ISetFormulaCalculationResultMutation } from '@univerjs/engine-formula';+import { Injector } from '@univerjs/core';import { FormulaExecutedStateType, FormulaExecuteStageType } from '@univerjs/engine-formula';import { afterEach, describe, expect, it, vi } from 'vitest';import { FormulaCalculationSessionService } from '../formula-calculation-session.service';+function createService(): FormulaCalculationSessionService {+ const injector = new Injector();+ injector.add([FormulaCalculationSessionService]);+ return injector.get(FormulaCalculationSessionService);+}+describe('FormulaCalculationSessionService', () => {afterEach(() => {vi.useRealTimers();@@ -27,7 +34,7 @@ describe('FormulaCalculationSessionService', () => {it('waits for the latest restarted session to be applied', async () => {vi.useFakeTimers();- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();const waitForApplied = service.waitForLatestApplied();let resolved = false;@@ -71,7 +78,7 @@ describe('FormulaCalculationSessionService', () => {});it('stores lifecycle flags and progress for the active session', () => {- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();service.start();@@ -104,7 +111,7 @@ describe('FormulaCalculationSessionService', () => {it('does not resolve from an already applied previous session when a new session starts', async () => {vi.useFakeTimers();- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();service.start();service.markResultEmitted({ unitData: {}, unitOtherData: {} }, false);@@ -130,7 +137,7 @@ describe('FormulaCalculationSessionService', () => {});it('emits result applied when value application is observed', async () => {- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();const result = {unitData: {@@ -158,7 +165,7 @@ describe('FormulaCalculationSessionService', () => {});it('emits result applied only once for repeated value application notifications', () => {- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();const result = {unitData: {@@ -186,7 +193,7 @@ describe('FormulaCalculationSessionService', () => {});it('emits result applied once when result arrives after an application notification', () => {- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();const result = {unitData: {@@ -214,7 +221,7 @@ describe('FormulaCalculationSessionService', () => {});it('emits result applied immediately when there is no sheet value to apply', () => {- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();const result: ISetFormulaCalculationResultMutation = {unitData: {},@@ -234,7 +241,7 @@ describe('FormulaCalculationSessionService', () => {it('does not start the no-calculation watchdog until the session controller is initialized', async () => {vi.useFakeTimers();- const service = new FormulaCalculationSessionService();+ const service = createService();const waitForApplied = service.waitForLatestApplied();let resolved = false;void waitForApplied.then(() => {@@ -257,7 +264,7 @@ describe('FormulaCalculationSessionService', () => {it('does not reject long-running calculations unless a timeout is provided', async () => {vi.useFakeTimers();- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();service.start();@@ -280,7 +287,7 @@ describe('FormulaCalculationSessionService', () => {it('rejects long-running calculations when a timeout is provided', async () => {vi.useFakeTimers();- const service = new FormulaCalculationSessionService();+ const service = createService();service.initialize();service.start();diff --git a/packages/sheets-formula/src/services/__tests__/formula-ref-range.service.spec.ts b/packages/sheets-formula/src/services/__tests__/formula-ref-range.service.spec.tsnew file mode 100644index 0000000000..b496f01651--- /dev/null+++ b/packages/sheets-formula/src/services/__tests__/formula-ref-range.service.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 type { ITestBed } from './util';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { FormulaRefRangeService } from '../formula-ref-range.service';+import { createCommandTestBed } from './util';++describe('FormulaRefRangeService service coverage', () => {+ let testBed: ITestBed;++ beforeEach(() => {+ testBed = createCommandTestBed();+ });++ afterEach(() => {+ testBed.univer.dispose();+ });++ it('updates sheet formula references when a referenced range moves', () => {+ const service = testBed.get(FormulaRefRangeService);++ const transformedFormula = service.transformFormulaByEffectCommand('test', 'sheet1', '=SUM(A1)', {+ id: 'sheet.command.move-range',+ params: {+ fromRange: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ toRange: { startRow: 2, endRow: 2, startColumn: 1, endColumn: 1 },+ },+ });++ expect(transformedFormula).toBe('=SUM(B3)');+ });+});diff --git a/packages/sheets-formula/src/services/__tests__/register-function.service.spec.ts b/packages/sheets-formula/src/services/__tests__/register-function.service.spec.tsindex 38b3c626f1..8f546d2962 100644--- a/packages/sheets-formula/src/services/__tests__/register-function.service.spec.ts+++ b/packages/sheets-formula/src/services/__tests__/register-function.service.spec.ts@@ -97,14 +97,17 @@ describe('RegisterFunctionService', () => {});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 registerFunctions = vi.fn().mockResolvedValue(undefined);+ const registerAsyncFunctions = vi.fn().mockResolvedValue(undefined);+ const unregisterFunctions = vi.fn().mockResolvedValue(undefined);+ class TestRemoteRegisterFunctionService {+ registerFunctions = registerFunctions;+ registerAsyncFunctions = registerAsyncFunctions;+ unregisterFunctions = unregisterFunctions;+ }const injector = univer.__getInjector();- injector.add([IRemoteRegisterFunctionService, { useValue: remoteRegisterFunctionService }]);+ injector.add([IRemoteRegisterFunctionService, { useClass: TestRemoteRegisterFunctionService as never }]);injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);const registerFunctionService = injector.get(IRegisterFunctionService);@@ -120,19 +123,19 @@ describe('RegisterFunctionService', () => {description: 'Remote async function',});- expect(remoteRegisterFunctionService.registerFunctions).toHaveBeenCalledTimes(1);- expect(remoteRegisterFunctionService.registerFunctions).toHaveBeenCalledWith([+ expect(registerFunctions).toHaveBeenCalledTimes(1);+ expect(registerFunctions).toHaveBeenCalledWith([[expect.stringContaining('() => 1'), 'REMOTE_GROUPED'],]);- expect(remoteRegisterFunctionService.registerAsyncFunctions).toHaveBeenCalledTimes(1);- expect(remoteRegisterFunctionService.registerAsyncFunctions).toHaveBeenCalledWith([+ expect(registerAsyncFunctions).toHaveBeenCalledTimes(1);+ expect(registerAsyncFunctions).toHaveBeenCalledWith([[expect.stringContaining('async'), 'REMOTE_ASYNC'],]);groupedDisposable.dispose();asyncDisposable.dispose();- expect(remoteRegisterFunctionService.unregisterFunctions).toHaveBeenCalledWith(['REMOTE_GROUPED']);- expect(remoteRegisterFunctionService.unregisterFunctions).toHaveBeenCalledWith(['REMOTE_ASYNC']);+ expect(unregisterFunctions).toHaveBeenCalledWith(['REMOTE_GROUPED']);+ expect(unregisterFunctions).toHaveBeenCalledWith(['REMOTE_ASYNC']);});});diff --git a/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.service.spec.ts b/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.service.spec.tsnew file mode 100644index 0000000000..702d7dd9d2--- /dev/null+++ b/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.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 { Injector } from '@univerjs/core';+import { FunctionService, IFunctionService } from '@univerjs/engine-formula';+import { describe, expect, it } from 'vitest';+import { IRemoteRegisterFunctionService, RemoteRegisterFunctionService } from '../remote-register-function.service';++function createService(): { service: IRemoteRegisterFunctionService; functionService: IFunctionService } {+ const injector = new Injector();+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([IRemoteRegisterFunctionService, { useClass: RemoteRegisterFunctionService }]);+ return {+ service: injector.get(IRemoteRegisterFunctionService),+ functionService: injector.get(IFunctionService),+ };+}++describe('RemoteRegisterFunctionService', () => {+ it('registers remote formula executors and removes them with their metadata', async () => {+ const { service, functionService } = createService();++ await service.registerFunctions([['(value) => value + 1', 'REMOTE_ADD_ONE']]);+ expect(functionService.hasExecutor('REMOTE_ADD_ONE')).toBe(true);++ await service.registerAsyncFunctions([['async (value) => value * 2', 'REMOTE_DOUBLE']]);+ expect(functionService.hasExecutor('REMOTE_DOUBLE')).toBe(true);++ functionService.registerDescriptions({+ functionName: 'REMOTE_ADD_ONE',+ functionType: 0,+ description: 'remote add one',+ abstract: 'remote add one',+ functionParameter: [],+ } as never);+ await service.unregisterFunctions(['REMOTE_ADD_ONE', 'REMOTE_DOUBLE']);++ expect(functionService.hasExecutor('REMOTE_ADD_ONE')).toBe(false);+ expect(functionService.hasExecutor('REMOTE_DOUBLE')).toBe(false);+ expect(functionService.hasDescription('REMOTE_ADD_ONE')).toBe(false);+ });+});diff --git a/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.spec.ts b/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.spec.tsnew file mode 100644index 0000000000..c39c0813c5--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.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 { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { IMessageProps } from '@univerjs/design';+import {+ ICommandService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleType,+ LogLevel,+ Plugin,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import {+ DefinedNamesService,+ FormulaDataModel,+ FunctionService,+ IDefinedNamesService,+ IFunctionService,+ ISuperTableService,+ LexerTreeBuilder,+ SuperTableService,+} from '@univerjs/engine-formula';+import {+ RefRangeService,+ SetWorksheetActiveOperation,+ SheetInterceptorService,+ SheetSkeletonService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { SheetsHyperLinkParserService } from '@univerjs/sheets-hyper-link';+import { SheetsHyperLinkResolverService } from '@univerjs/sheets-hyper-link-ui';+import { IMessageService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import '@univerjs/sheets/facade';+import '@univerjs/sheets-hyper-link-ui/facade';++class TestMessageService {+ readonly messages: IMessageProps[] = [];++ show(options: IMessageProps): void {+ this.messages.push(options);+ }+}++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'Workbook',+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ cellData: {},+ rowCount: 20,+ columnCount: 20,+ },+ },+ };+}++function createHyperLinkFacadeTestBed(workbookData: IWorkbookData, dependencies: Dependency[]) {+ 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: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const injector = this._injector;+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([SheetSkeletonService]);+ injector.add([FormulaDataModel]);+ injector.add([LexerTreeBuilder]);+ injector.add([RefRangeService]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ dependencies.forEach((dependency) => injector.add(dependency));++ this._injector.get(SheetInterceptorService);+ }+ }++ univer.registerPlugin(TestPlugin);+ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData);+ injector.get(IUniverInstanceService).focusUnit(sheet.getUnitId());+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ return {+ univer,+ get: injector.get.bind(injector),+ univerAPI: FUniver.newAPI(injector),+ };+}++describe('sheets-hyper-link-ui workbook facade', () => {+ let testBed: ReturnType<typeof createHyperLinkFacadeTestBed>;++ beforeEach(() => {+ const dependencies: Dependency[] = [+ [SheetsHyperLinkParserService],+ [SheetsHyperLinkResolverService],+ [IMessageService, { useClass: TestMessageService }],+ ];+ testBed = createHyperLinkFacadeTestBed(createWorkbookData(), dependencies);+ testBed.get(ICommandService).registerCommand(SetWorksheetActiveOperation);+ });++ afterEach(() => {+ testBed.univer.dispose();+ });++ it('navigates hyperlinks through the workbook facade API', async () => {+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);++ workbook.navigateToSheetHyperlink('https://univer.ai');+ await Promise.resolve();++ expect(open).toHaveBeenCalledWith('https://univer.ai', '_blank', 'noopener noreferrer');+ open.mockRestore();+ });+});diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.tsindex 8dd35c381e..4333db6a9f 100644--- a/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.ts+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.ts@@ -14,61 +14,120 @@* limitations under the License.*/-import { CustomRangeType, Injector } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';+import { CustomRangeType, Injector, IUniverInstanceService } from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { IRenderManagerService } from '@univerjs/engine-render';+import { IEditorBridgeService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { describe, expect, it } from 'vitest';import { HyperLinkEditSourceType } from '../../types/enums/edit-source';import { SheetsHyperLinkPopupService } from '../popup.service';-function createDisposable() {- return {- dispose: vi.fn(),- canDispose: vi.fn(() => true),- };+class TestDisposable {+ disposeCount = 0;+ canDisposeResult = true;++ dispose(): void {+ this.disposeCount += 1;+ }++ canDispose(): boolean {+ return this.canDisposeResult;+ }}-function createService(options?: {- workbook?: unknown;-}) {- const cellDisposable = createDisposable();- const positionDisposable = createDisposable();- const absoluteDisposable = createDisposable();- const docDisposable = createDisposable();-- const sheetCanvasPopManagerService = {- attachPopupToCell: vi.fn(() => cellDisposable),- attachPopupByPosition: vi.fn(() => positionDisposable),- attachPopupToAbsolutePosition: vi.fn(() => absoluteDisposable),- };- const docCanvasPopManagerService = {- attachPopupToRange: vi.fn(() => docDisposable),- };- const textSelectionManagerService = {- getActiveTextRange: vi.fn(() => ({ startOffset: 1, endOffset: 3, collapsed: false })),- replaceDocRanges: vi.fn(),- replaceTextRanges: vi.fn(),- };- const univerInstanceService = {- getUnit: vi.fn(() => options?.workbook ?? null),- };+class TestSheetCanvasPopManagerService {+ readonly cellDisposable = new TestDisposable();+ readonly positionDisposable = new TestDisposable();+ readonly absoluteDisposable = new TestDisposable();+ readonly cellPopups: Array<{ row: number; col: number; popup: any; unitId?: string; subUnitId?: string }> = [];+ readonly positionPopups: Array<{ rect: any; popup: any; location: any }> = [];+ readonly absolutePopups: Array<{ rect: any; popup: any; unitId?: string; subUnitId?: string }> = [];++ attachPopupToCell(row: number, col: number, popup: any, unitId?: string, subUnitId?: string): TestDisposable {+ this.cellPopups.push({ row, col, popup, unitId, subUnitId });+ return this.cellDisposable;+ }++ attachPopupByPosition(rect: any, popup: any, location: any): TestDisposable {+ this.positionPopups.push({ rect, popup, location });+ return this.positionDisposable;+ }++ attachPopupToAbsolutePosition(rect: any, popup: any, unitId?: string, subUnitId?: string): TestDisposable {+ this.absolutePopups.push({ rect, popup, unitId, subUnitId });+ return this.absoluteDisposable;+ }+}++class TestUniverInstanceService {+ workbook: any = null;++ getUnit(): any {+ return this.workbook;+ }+}++class TestEditorBridgeService {+ visible = false;+ editCellState: any = null;++ isVisible(): { visible: boolean } {+ return { visible: this.visible };+ }++ getEditCellState(): any {+ return this.editCellState;+ }+}++class TestDocSelectionManagerService {+ activeTextRange: any = { startOffset: 1, endOffset: 3, collapsed: false };+ readonly replacedDocRanges: any[] = [];+ readonly replacedTextRanges: any[] = [];++ getActiveTextRange(): any {+ return this.activeTextRange;+ }++ replaceDocRanges(ranges: any, unitRange: any): void {+ this.replacedDocRanges.push({ ranges, unitRange });+ }++ replaceTextRanges(ranges: any): void {+ this.replacedTextRanges.push(ranges);+ }+}++class TestRenderManagerService {+ render: any = null;++ getRenderById(): any {+ return this.render;+ }+}++function createService() {+ const injector = new Injector();++ injector.add([SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);+ injector.add([DocSelectionManagerService, { useClass: TestDocSelectionManagerService as never }]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([SheetsHyperLinkPopupService]);return {- service: new SheetsHyperLinkPopupService(- sheetCanvasPopManagerService as never,- new Injector(),- univerInstanceService as never,- { isVisible: () => ({ visible: false }), getEditCellState: vi.fn() } as never,- textSelectionManagerService as never- ),- sheetCanvasPopManagerService,- docCanvasPopManagerService,- textSelectionManagerService,- cellDisposable,+ service: injector.get(SheetsHyperLinkPopupService),+ sheetCanvasPopManagerService: injector.get(SheetCanvasPopManagerService) as unknown as TestSheetCanvasPopManagerService,+ editorBridgeService: injector.get(IEditorBridgeService) as unknown as TestEditorBridgeService,+ textSelectionManagerService: injector.get(DocSelectionManagerService) as unknown as TestDocSelectionManagerService,+ univerInstanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,};}describe('SheetsHyperLinkPopupService', () => {it('shows and hides cell popups without recreating the same viewing popup', () => {- const { service, sheetCanvasPopManagerService, cellDisposable } = createService();+ const { service, sheetCanvasPopManagerService } = createService();service.showPopup({unitId: 'unit-1',@@ -81,7 +140,7 @@ describe('SheetsHyperLinkPopupService', () => {type: HyperLinkEditSourceType.VIEWING,});- expect(sheetCanvasPopManagerService.attachPopupToCell).toHaveBeenCalledTimes(1);+ expect(sheetCanvasPopManagerService.cellPopups).toHaveLength(1);expect(service.currentPopup).toEqual(expect.objectContaining({unitId: 'unit-1',subUnitId: 'sheet-1',@@ -100,17 +159,17 @@ describe('SheetsHyperLinkPopupService', () => {type: HyperLinkEditSourceType.VIEWING,});- expect(sheetCanvasPopManagerService.attachPopupToCell).toHaveBeenCalledTimes(1);+ expect(sheetCanvasPopManagerService.cellPopups).toHaveLength(1);service.hideCurrentPopup();- expect(cellDisposable.dispose).toHaveBeenCalledTimes(1);+ expect(sheetCanvasPopManagerService.cellDisposable.disposeCount).toBe(1);expect(service.currentPopup).toBeNull();});- it('routes popups by source type', () => {- const active = createService();+ it('routes popups by source type and popup callbacks close the active popup', () => {+ const { service, sheetCanvasPopManagerService } = createService();- active.service.showPopup({+ service.showPopup({unitId: 'unit-1',subUnitId: 'sheet-1',row: 0,@@ -119,9 +178,13 @@ describe('SheetsHyperLinkPopupService', () => {customRangeRect: { left: 0, top: 0, right: 10, bottom: 10 },type: HyperLinkEditSourceType.EDITING,});- expect(active.sheetCanvasPopManagerService.attachPopupToAbsolutePosition).toHaveBeenCalledTimes(1);+ expect(sheetCanvasPopManagerService.absolutePopups).toHaveLength(1);- active.service.showPopup({+ sheetCanvasPopManagerService.absolutePopups[0].popup.onClickOutside();+ expect(sheetCanvasPopManagerService.absoluteDisposable.disposeCount).toBe(1);+ expect(service.currentPopup).toBeNull();++ service.showPopup({unitId: 'unit-1',subUnitId: 'sheet-1',row: 0,@@ -130,18 +193,64 @@ describe('SheetsHyperLinkPopupService', () => {customRangeRect: { left: 1, top: 1, right: 9, bottom: 9 },type: HyperLinkEditSourceType.VIEWING,});- expect(active.sheetCanvasPopManagerService.attachPopupByPosition).toHaveBeenCalledTimes(1);- expect(active.docCanvasPopManagerService.attachPopupToRange).not.toHaveBeenCalled();+ expect(sheetCanvasPopManagerService.positionPopups).toHaveLength(1);+ sheetCanvasPopManagerService.positionPopups[0].popup.onClick();+ expect(sheetCanvasPopManagerService.positionDisposable.disposeCount).toBe(1);+ expect(service.currentPopup).toBeNull();+ });++ it('does not open incomplete popups and replaces an older visible popup', () => {+ const { service, sheetCanvasPopManagerService } = createService();++ service.showPopup({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 0,+ col: 0,+ customRangeRect: { left: 0, top: 0, right: 10, bottom: 10 },+ type: HyperLinkEditSourceType.EDITING,+ });+ service.showPopup({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 0,+ col: 0,+ customRangeRect: { left: 0, top: 0, right: 10, bottom: 10 },+ type: HyperLinkEditSourceType.VIEWING,+ });+ expect(sheetCanvasPopManagerService.absolutePopups).toHaveLength(0);+ expect(sheetCanvasPopManagerService.positionPopups).toHaveLength(0);++ service.showPopup({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 0,+ col: 0,+ showAll: true,+ type: HyperLinkEditSourceType.VIEWING,+ });+ service.showPopup({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 2,+ col: 3,+ showAll: true,+ type: HyperLinkEditSourceType.VIEWING,+ });++ expect(sheetCanvasPopManagerService.cellPopups).toHaveLength(2);+ expect(sheetCanvasPopManagerService.cellDisposable.disposeCount).toBe(1);+ expect(service.currentPopup).toEqual(expect.objectContaining({ row: 2, col: 3 }));});it('starts viewing edits from cell content and preserves editor state while keep-visible is enabled', () => {- const workbook = {+ const { service, sheetCanvasPopManagerService, univerInstanceService } = createService();+ univerInstanceService.workbook = {getSheetBySheetId: () => ({getCellRaw: () => ({ v: 'Cell Value' }),}),};- const { service, sheetCanvasPopManagerService } = createService({ workbook });service.startAddEditing({unitId: 'unit-1',@@ -150,7 +259,7 @@ describe('SheetsHyperLinkPopupService', () => {col: 1,type: HyperLinkEditSourceType.VIEWING,});- expect(sheetCanvasPopManagerService.attachPopupToCell).toHaveBeenCalledTimes(1);+ expect(sheetCanvasPopManagerService.cellPopups).toHaveLength(1);expect(service.currentEditing).toEqual(expect.objectContaining({label: 'Cell Value',type: HyperLinkEditSourceType.VIEWING,@@ -164,4 +273,170 @@ describe('SheetsHyperLinkPopupService', () => {service.endEditing(HyperLinkEditSourceType.VIEWING);expect(service.currentEditing).toBeNull();});++ it('uses rich text cell content as the default label when starting a viewing edit', () => {+ const { service, univerInstanceService } = createService();+ univerInstanceService.workbook = {+ getSheetBySheetId: () => ({+ getCellRaw: () => ({ p: { body: { dataStream: 'Rich Text\r\n' } } }),+ }),+ };++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.VIEWING,+ });++ expect(service.currentEditing).toEqual(expect.objectContaining({ label: 'Rich Text' }));+ });++ it('keeps a popup hidden when the same link is already being edited', () => {+ const { service, sheetCanvasPopManagerService } = createService();++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.VIEWING,+ });+ service.showPopup({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ showAll: true,+ type: HyperLinkEditSourceType.VIEWING,+ });++ expect(sheetCanvasPopManagerService.cellPopups).toHaveLength(1);+ expect(service.currentPopup).toBeNull();+ });++ it('does not start document-editing flow when editor state has no document body', () => {+ const { service, editorBridgeService, textSelectionManagerService } = createService();+ editorBridgeService.visible = true;+ editorBridgeService.editCellState = {+ documentLayoutObject: {+ documentModel: {+ getBody: () => null,+ },+ },+ };++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.EDITING,+ });++ expect(textSelectionManagerService.replacedDocRanges).toHaveLength(0);+ expect(service.currentEditing).toBeNull();+ });++ it('does not start document-editing flow when the editor is hidden', () => {+ const { service, textSelectionManagerService } = createService();++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.EDITING,+ });++ expect(textSelectionManagerService.replacedDocRanges).toHaveLength(0);+ expect(service.currentEditing).toBeNull();+ });++ it('selects the full editor text when adding a link from a collapsed editing selection', () => {+ const { service, editorBridgeService, textSelectionManagerService, sheetCanvasPopManagerService } = createService();+ editorBridgeService.visible = true;+ editorBridgeService.editCellState = {+ documentLayoutObject: {+ documentModel: {+ getBody: () => ({ dataStream: 'Full Label\r\n', customRanges: [] }),+ },+ },+ };+ textSelectionManagerService.activeTextRange = { startOffset: 2, endOffset: 2, collapsed: true };++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.EDITING,+ });++ expect(textSelectionManagerService.replacedDocRanges[0].ranges).toEqual([{+ startOffset: 0,+ endOffset: 10,+ collapsed: false,+ label: 'Full Label',+ }]);+ expect(sheetCanvasPopManagerService.absolutePopups).toHaveLength(0);+ expect(service.currentEditing).toBeNull();+ });++ it('expands an editor selection to the full overlapping hyperlink range', () => {+ const { service, editorBridgeService, textSelectionManagerService } = createService();+ editorBridgeService.visible = true;+ editorBridgeService.editCellState = {+ documentLayoutObject: {+ documentModel: {+ getBody: () => ({+ dataStream: 'abcdef\r\n',+ customRanges: [{ rangeId: 'link-1', startIndex: 1, endIndex: 4, rangeType: CustomRangeType.HYPERLINK }],+ }),+ },+ },+ };+ textSelectionManagerService.activeTextRange = { startOffset: 2, endOffset: 3, collapsed: false };++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.EDITING,+ });++ expect(textSelectionManagerService.replacedDocRanges[0].ranges).toEqual([{+ startOffset: 1,+ endOffset: 5,+ collapsed: false,+ label: 'bcde',+ }]);+ expect(service.currentEditing).toBeNull();+ });++ it('ends viewing edit sessions from edit popup click handlers', () => {+ const { service, sheetCanvasPopManagerService } = createService();++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.VIEWING,+ });+ sheetCanvasPopManagerService.cellPopups[0].popup.onClickOutside();+ expect(service.currentEditing).toBeNull();++ service.startAddEditing({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ row: 1,+ col: 1,+ type: HyperLinkEditSourceType.VIEWING,+ });+ sheetCanvasPopManagerService.cellPopups[1].popup.onContextMenu();+ expect(service.currentEditing).toBeNull();+ });});diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.tsindex 845e5dd694..8e03bcfa12 100644--- a/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts@@ -14,93 +14,162 @@* limitations under the License.*/+import type { IMessageProps } from '@univerjs/design';+import { ICommandService, IConfigService, Injector, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { IDefinedNamesService } from '@univerjs/engine-formula';import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';-import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';+import { ERROR_RANGE, SheetHyperLinkType } from '@univerjs/sheets-hyper-link';import { ScrollToRangeOperation } from '@univerjs/sheets-ui';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { IMessageService } from '@univerjs/ui';+import { afterEach, describe, expect, it } from 'vitest';import { SheetsHyperLinkResolverService } from '../resolver.service';+class TestCommandService {+ readonly commands: Array<{ id: string; params: any }> = [];+ activateResult = true;++ async executeCommand(id: string, params: any): Promise<boolean> {+ this.commands.push({ id, params });+ return id === SetWorksheetActiveOperation.id ? this.activateResult : true;+ }+}++class TestDefinedNamesService {+ namedRanges = new Map<string, { formulaOrRefString: string }>();+ worksheetsByRef: any[] = [];+ readonly focusedRanges: Array<{ unitId: string; rangeId: string }> = [];++ getValueById(_unitId: string, rangeId: string): { formulaOrRefString: string } | undefined {+ return this.namedRanges.get(rangeId);+ }++ getWorksheetByRef(): any {+ return this.worksheetsByRef.shift();+ }++ focusRange(unitId: string, rangeId: string): void {+ this.focusedRanges.push({ unitId, rangeId });+ }+}++class TestMessageService {+ readonly messages: IMessageProps[] = [];++ show(options: IMessageProps): void {+ this.messages.push(options);+ }+}++class TestLocaleService {+ t(key: string): string {+ return key;+ }+}++class TestConfigService {+ configs: any[] = [];++ getConfig(): any {+ return this.configs.length ? this.configs.shift() : undefined;+ }+}++class TestUniverInstanceService {+ currentUnit: any = null;+ unit: any = null;++ getCurrentUnitOfType(): any {+ return this.currentUnit;+ }++ getUnit(): any {+ return this.unit ?? this.currentUnit;+ }+}++function createWorksheet(sheetId: string, options?: { hidden?: boolean }) {+ return {+ getSheetId: () => sheetId,+ getMergeData: () => [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }],+ getMaxColumns: () => 10,+ getMaxRows: () => 10,+ isSheetHidden: () => !!options?.hidden,+ };+}++function createWorkbook(options?: {+ activeSheet?: any;+ targetSheet?: any;+ hiddenSheets?: string[];+}) {+ return {+ getUnitId: () => 'unit-1',+ getActiveSheet: () => options?.activeSheet ?? createWorksheet('sheet-1'),+ getSheetBySheetId: (sheetId: string) => (options?.targetSheet?.getSheetId() === sheetId ? options.targetSheet : null),+ getHiddenWorksheets: () => options?.hiddenSheets ?? [],+ };+}++function createResolver() {+ const injector = new Injector();++ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([IDefinedNamesService, { useClass: TestDefinedNamesService as never }]);+ injector.add([IMessageService, { useClass: TestMessageService as never }]);+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([IConfigService, { useClass: TestConfigService as never }]);+ injector.add([SheetsHyperLinkResolverService]);++ return {+ resolver: injector.get(SheetsHyperLinkResolverService),+ commandService: injector.get(ICommandService) as unknown as TestCommandService,+ definedNamesService: injector.get(IDefinedNamesService) as unknown as TestDefinedNamesService,+ messageService: injector.get(IMessageService) as unknown as TestMessageService,+ configService: injector.get(IConfigService) as unknown as TestConfigService,+ univerInstanceService: injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService,+ };+}++const originalOpen = window.open;+const waitForNavigationJobs = () => new Promise((resolve) => setTimeout(resolve));+describe('SheetsHyperLinkResolverService', () => {afterEach(() => {- vi.unstubAllGlobals();+ window.open = originalOpen;});it('should navigate to sheet ranges and execute selection and scroll commands', async () => {- const executeCommand = vi.fn(async (id: string) => id === SetWorksheetActiveOperation.id);- const worksheet = {- getSheetId: () => 'sheet-2',- getMergeData: () => [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }],- getMaxColumns: () => 10,- getMaxRows: () => 10,- };- const workbook = {- getUnitId: () => 'unit-1',- getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),- getSheetBySheetId: (sheetId: string) => (sheetId === 'sheet-2' ? worksheet : null),- getHiddenWorksheets: () => [],- };-- const resolver = new SheetsHyperLinkResolverService(+ const { resolver, commandService, univerInstanceService } = createResolver();+ const targetSheet = createWorksheet('sheet-2');+ univerInstanceService.currentUnit = createWorkbook({ targetSheet });++ await resolver.navigateToRange('unit-1', 'sheet-2', { startRow: 1, endRow: 20, startColumn: 1, endColumn: 20 }, true);++ expect(commandService.commands).toEqual([+ { id: SetWorksheetActiveOperation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-2' } },{- getCurrentUnitOfType: () => workbook,- getUnit: () => workbook,- } as any,- { executeCommand } as any,+ id: SetSelectionsOperation.id,+ params: {+ unitId: 'unit-1',+ subUnitId: 'sheet-2',+ selections: [{ range: { startRow: 1, endRow: 9, startColumn: 1, endColumn: 9 }, primary: null }],+ },+ },{- getValueById: vi.fn(),- getWorksheetByRef: vi.fn(),- focusRange: vi.fn(),- } as any,- { show: vi.fn() } as any,- { t: (key: string) => key } as any,- { getConfig: vi.fn(() => undefined) } as any- );-- await resolver.navigateToRange('unit-1', 'sheet-2', { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }, true);-- expect(executeCommand).toHaveBeenCalledWith(SetWorksheetActiveOperation.id, { unitId: 'unit-1', subUnitId: 'sheet-2' });- expect(executeCommand).toHaveBeenCalledWith(SetSelectionsOperation.id, {- unitId: 'unit-1',- subUnitId: 'sheet-2',- selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }, primary: null }],- });- expect(executeCommand).toHaveBeenCalledWith(ScrollToRangeOperation.id, {- range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },- forceTop: true,- });+ id: ScrollToRangeOperation.id,+ params: { range: { startRow: 1, endRow: 9, startColumn: 1, endColumn: 9 }, forceTop: true },+ },+ ]);});it('should show user-facing errors when target sheets or defined names are invalid', async () => {- const show = vi.fn();- const focusRange = vi.fn();- const getWorksheetByRef = vi.fn()- .mockReturnValueOnce(null)- .mockReturnValueOnce({ isSheetHidden: () => true })- .mockReturnValueOnce({ isSheetHidden: () => false });- const workbook = {- getUnitId: () => 'unit-1',- getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),- getSheetBySheetId: () => null,- getHiddenWorksheets: () => ['sheet-hidden'],- };- const executeCommand = vi.fn(async () => false);-- const resolver = new SheetsHyperLinkResolverService(- {- getCurrentUnitOfType: () => workbook,- getUnit: () => workbook,- } as any,- { executeCommand } as any,- {- getValueById: (_unitId: string, rangeId: string) => (rangeId === 'named-range' ? { formulaOrRefString: 'Sheet1!A1' } : undefined),- getWorksheetByRef,- focusRange,- } as any,- { show } as any,- { t: (key: string) => key } as any,- { getConfig: vi.fn(() => undefined) } as any- );+ const { resolver, definedNamesService, messageService, univerInstanceService } = createResolver();+ univerInstanceService.currentUnit = createWorkbook({ hiddenSheets: ['sheet-hidden'] });+ definedNamesService.namedRanges.set('named-range', { formulaOrRefString: 'Sheet1!A1' });+ definedNamesService.worksheetsByRef.push(null, createWorksheet('sheet-hidden', { hidden: true }), createWorksheet('sheet-1'));+ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'missing-range' } } as any);resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'named-range' } } as any);resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'named-range' } } as any);resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'named-range' } } as any);@@ -108,75 +177,83 @@ describe('SheetsHyperLinkResolverService', () => {await resolver.navigateToSheetById('unit-1', 'sheet-missing');await resolver.navigateToSheetById('unit-1', 'sheet-hidden');- expect(show).toHaveBeenCalledWith({ content: 'sheets-hyper-link-ui.message.refError', type: 'error' });- expect(show).toHaveBeenCalledWith({ content: 'sheets-hyper-link-ui.message.hiddenSheet', type: 'error' });- expect(show).toHaveBeenCalledWith({ content: 'sheets-hyper-link-ui.message.noSheet', type: 'error' });- expect(focusRange).toHaveBeenCalledWith('unit-1', 'named-range');+ expect(messageService.messages).toEqual([+ { content: 'sheets-hyper-link-ui.message.refError', type: 'error' },+ { content: 'sheets-hyper-link-ui.message.hiddenSheet', type: 'error' },+ { content: 'sheets-hyper-link-ui.message.noSheet', type: 'error' },+ { content: 'sheets-hyper-link-ui.message.noSheet', type: 'error' },+ ]);+ expect(definedNamesService.focusedRanges).toEqual([{ unitId: 'unit-1', rangeId: 'named-range' }]);});it('should open external links via configured handlers or fallback window.open', async () => {- const navigateToOtherWebsite = vi.fn();- const open = vi.fn();- vi.stubGlobal('window', { open });-- const resolver = new SheetsHyperLinkResolverService(- {- getCurrentUnitOfType: () => null,- getUnit: () => null,- } as any,- { executeCommand: vi.fn() } as any,- {- getValueById: vi.fn(),- getWorksheetByRef: vi.fn(),- focusRange: vi.fn(),- } as any,- { show: vi.fn() } as any,- { t: (key: string) => key } as any,- {- getConfig: vi.fn()- .mockReturnValueOnce({ urlHandler: { navigateToOtherWebsite } })- .mockReturnValueOnce(undefined),- } as any+ const { resolver, configService } = createResolver();+ const navigatedUrls: string[] = [];+ const openedUrls: any[] = [];+ window.open = ((...args: any[]) => {+ openedUrls.push(args);+ return null;+ }) as typeof window.open;+ configService.configs.push(+ { urlHandler: { navigateToOtherWebsite: (url: string) => navigatedUrls.push(url) } },+ undefined);await resolver.navigateToOtherWebsite('https://univer.ai');await resolver.navigateToOtherWebsite('https://openai.com');+ await resolver.navigateToOtherWebsite('javascript:alert(1)');+ resolver.navigate({ type: SheetHyperLinkType.URL, url: 'https://example.com' } as any);- expect(navigateToOtherWebsite).toHaveBeenCalledWith('https://univer.ai');- expect(open).toHaveBeenCalledWith('https://openai.com', '_blank', 'noopener noreferrer');+ expect(navigatedUrls).toEqual(['https://univer.ai']);+ expect(openedUrls).toEqual([+ ['https://openai.com', '_blank', 'noopener noreferrer'],+ ['https://example.com', '_blank', 'noopener noreferrer'],+ ]);});- it('should interpret workbook-style links through the public navigate entry', () => {- const executeCommand = vi.fn(async () => true);- const workbook = {- getUnitId: () => 'unit-1',- getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),- getSheetBySheetId: () => ({- getSheetId: () => 'sheet-2',- getMergeData: () => [],- getMaxColumns: () => 10,- getMaxRows: () => 10,- }),- getHiddenWorksheets: () => [],- };- const resolver = new SheetsHyperLinkResolverService(- {- getCurrentUnitOfType: () => workbook,- getUnit: () => workbook,- } as any,- { executeCommand } as any,- {- getValueById: vi.fn(),- getWorksheetByRef: vi.fn(),- focusRange: vi.fn(),- } as any,- { show: vi.fn() } as any,- { t: (key: string) => key } as any,- { getConfig: vi.fn(() => undefined) } as any- );+ it('should interpret workbook-style links through the public navigate entry', async () => {+ const { resolver, commandService, univerInstanceService } = createResolver();+ univerInstanceService.currentUnit = createWorkbook({ targetSheet: createWorksheet('sheet-2') });resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { gid: 'sheet-2', range: 'B2:C3' } } as any);+ await waitForNavigationJobs();++ expect(commandService.commands.map((command) => command.id)).toEqual([+ SetWorksheetActiveOperation.id,+ SetSelectionsOperation.id,+ ScrollToRangeOperation.id,+ ]);+ });++ it('should ignore invalid workbook targets without executing navigation commands', async () => {+ const { resolver, commandService, univerInstanceService } = createResolver();++ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { gid: 'sheet-1' } } as any);+ await resolver.navigateToSheetById('unit-1', 'sheet-1');++ univerInstanceService.currentUnit = createWorkbook({ activeSheet: null });+ await resolver.navigateToSheetById('unit-1', 'sheet-1');++ univerInstanceService.currentUnit = createWorkbook({ targetSheet: createWorksheet('sheet-2') });+ commandService.activateResult = false;+ await resolver.navigateToSheetById('unit-1', 'sheet-2');++ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { gid: 'sheet-2', range: ERROR_RANGE } } as any);+ await Promise.resolve();++ expect(commandService.commands).toEqual([+ { id: SetWorksheetActiveOperation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-2' } },+ ]);+ });++ it('should stay on the current worksheet when the hyperlink already points there', async () => {+ const { resolver, commandService, univerInstanceService } = createResolver();+ const activeSheet = createWorksheet('sheet-1');+ univerInstanceService.currentUnit = createWorkbook({ activeSheet });++ const result = await resolver.navigateToSheetById('unit-1', 'sheet-1');- expect(executeCommand).toHaveBeenCalled();+ expect(result).toBe(activeSheet);+ expect(commandService.commands).toEqual([]);});});diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.tsindex c820c5e9f6..2a6b938816 100644--- a/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.ts+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.ts@@ -14,33 +14,42 @@* limitations under the License.*/+import type { ISheetHyperLink } from '@univerjs/sheets-hyper-link';+import type { ICustomHyperLinkView } from '../side-panel.service';+import { Injector } from '@univerjs/core';import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import { SheetsHyperLinkSidePanelService } from '../side-panel.service';+function createService(): SheetsHyperLinkSidePanelService {+ const injector = new Injector();+ injector.add([SheetsHyperLinkSidePanelService]);+ return injector.get(SheetsHyperLinkSidePanelService);+}+describe('SheetsHyperLinkSidePanelService', () => {it('should register, resolve and remove custom hyperlink views', () => {- const service = new SheetsHyperLinkSidePanelService();- const customView = {+ const service = createService();+ const customView: ICustomHyperLinkView = {type: 'sheet-anchor',option: { label: 'Sheet Anchor', value: 'sheet-anchor' },- Form: vi.fn(),- convert: vi.fn(() => ({ display: 'A1', payload: '#A1', type: 'sheet-anchor' })),- match: vi.fn((link) => link.payload === '#A1'),+ Form: () => null,+ convert: () => ({ display: 'A1', payload: '#A1', type: 'sheet-anchor' }),+ match: (link) => link.payload === '#A1',};expect(service.isBuiltInLinkType(SheetHyperLinkType.URL)).toBe(false);expect(service.isBuiltInLinkType('custom')).toBe(true);- service.registerCustomHyperLink(customView as any);+ service.registerCustomHyperLink(customView);expect(service.getOptions()).toEqual([customView.option]);expect(service.getCustomHyperLink('sheet-anchor')).toBe(customView);- expect(service.findCustomHyperLink({ payload: '#A1' } as any)).toBe(customView);+ expect(service.findCustomHyperLink({ payload: '#A1' } as ISheetHyperLink)).toBe(customView);service.removeCustomHyperLink('sheet-anchor');expect(service.getCustomHyperLink('sheet-anchor')).toBeUndefined();- service.registerCustomHyperLink(customView as any);+ service.registerCustomHyperLink(customView);service.dispose();expect(service.getOptions()).toEqual([]);});diff --git a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsxnew file mode 100644index 0000000000..43b7d42b95--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx@@ -0,0 +1,478 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ICustomRange, IWorkbookData, Workbook } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import {+ CellValueType,+ CustomRangeType,+ ICommandService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { IDefinedNamesService } from '@univerjs/engine-formula';+import { IRenderManagerService } from '@univerjs/engine-render';+import {+ SetRangeValuesMutation,+ SetWorksheetActiveOperation,+ SheetInterceptorService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import {+ AddHyperLinkCommand,+ AddHyperLinkMutation,+ CancelHyperLinkCommand,+ HyperLinkModel,+ RemoveHyperLinkMutation,+ SheetsHyperLinkParserService,+ UpdateHyperLinkMutation,+} from '@univerjs/sheets-hyper-link';+import {+ IEditorBridgeService,+ IMarkSelectionService,+ ScrollToRangeOperation,+ SheetCanvasPopManagerService,+} from '@univerjs/sheets-ui';+import { IMessageService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { CloseHyperLinkPopupOperation, OpenHyperLinkEditPanelOperation } from '../../commands/operations/popup.operations';+import { SheetsHyperLinkPopupService } from '../../services/popup.service';+import { SheetsHyperLinkResolverService } from '../../services/resolver.service';+import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';+import { CellLinkEdit } from '../CellLinkEdit';+import { CellLinkPopupPure } from '../CellLinkPopup';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'sheet-link-popup-workbook';+const SUB_UNIT_ID = 'sheet-1';++class TestCanvasPopManagerService {+ attachPopupToCell() {+ return toDisposable(() => undefined);+ }++ attachPopupByPosition() {+ return toDisposable(() => undefined);+ }++ attachPopupToAbsolutePosition() {+ return toDisposable(() => undefined);+ }+}++class TestRenderManagerService {+ enableScrollRender = false;+ readonly scrollRanges: unknown[] = [];++ getRenderById(id: string) {+ if (id !== UNIT_ID || !this.enableScrollRender) {+ return undefined;+ }++ return {+ with: () => ({+ scrollToRange: (range: unknown) => {+ this.scrollRanges.push(range);+ return true;+ },+ }),+ };+ }+}++class TestMarkSelectionService {+ readonly shapes = new Map<string, unknown>();++ addShape(selection: unknown) {+ const id = `shape-${this.shapes.size + 1}`;+ this.shapes.set(id, selection);+ return id;+ }++ addShapeWithNoFresh(selection: unknown) {+ return this.addShape(selection);+ }++ removeShape(id: string) {+ this.shapes.delete(id);+ }++ removeAllShapes() {+ this.shapes.clear();+ }++ refreshShapes() {}++ getShapeMap() {+ return this.shapes;+ }+}++class TestEditorBridgeService {+ forceKeepVisible = false;++ getCurrentEditorId() {+ return 'sheet-popup-editor';+ }++ isVisible() {+ return { visible: false };+ }++ getEditCellState() {+ return null;+ }++ enableForceKeepVisible() {+ this.forceKeepVisible = true;+ }++ disableForceKeepVisible() {+ this.forceKeepVisible = false;+ }+}++class TestDefinedNamesService {+ getValueById() {+ return undefined;+ }++ getDefinedNameMap() {+ return {};+ }++ getWorksheetByRef() {+ return undefined;+ }++ focusRange() {+ // Defined-name navigation is outside these popup component scenarios.+ }+}++class TestMessageService {+ readonly messages: unknown[] = [];++ show(message: unknown) {+ this.messages.push(message);+ }+}++function createCellDocument(text: string, range: ICustomRange) {+ return {+ id: `${range.rangeId}-doc`,+ documentStyle: {+ pageSize: { width: 100, height: 40 },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ },+ body: {+ dataStream: `${text}\r\n`,+ customRanges: [range],+ },+ };+}++function createWorkbookData(customRange: ICustomRange): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ name: 'hyperlink popup workbook',+ locale: LocaleType.EN_US,+ sheetOrder: [SUB_UNIT_ID],+ styles: {},+ sheets: {+ [SUB_UNIT_ID]: {+ id: SUB_UNIT_ID,+ name: 'Sheet 1',+ cellData: {+ 0: {+ 0: {+ p: createCellDocument('Univer', customRange),+ t: CellValueType.STRING,+ },+ },+ },+ },+ },+ };+}++function createHyperLinkRange(): ICustomRange {+ return {+ rangeId: 'link-range',+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 5,+ properties: {+ url: 'https://univer.ai',+ },+ };+}++function createPopupTestBed() {+ const customRange = createHyperLinkRange();+ const univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([SheetInterceptorService]);+ injector.add([HyperLinkModel]);+ injector.add([DocSelectionManagerService]);+ injector.add([IDefinedNamesService, { useClass: TestDefinedNamesService as never }]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([IMessageService, { useClass: TestMessageService as never }]);+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);+ injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService as never }]);+ injector.add([SheetCanvasPopManagerService, { useClass: TestCanvasPopManagerService as never }]);+ injector.add([SheetsSelectionsService]);+ injector.add([SheetsHyperLinkParserService]);+ injector.add([SheetsHyperLinkResolverService]);+ injector.add([SheetsHyperLinkPopupService]);+ injector.add([SheetsHyperLinkSidePanelService]);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData(customRange));+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ injector.get(LocaleService).load({+ [LocaleType.EN_US]: {+ 'sheets-hyper-link-ui': {+ popup: {+ edit: 'Edit',+ cancel: 'Remove link',+ },+ form: {+ label: 'Display text',+ labelPlaceholder: 'Text',+ type: 'Link type',+ link: 'Web link',+ range: 'Range',+ worksheet: 'Worksheet',+ definedName: 'Defined name',+ linkPlaceholder: 'URL',+ inputError: 'Required',+ linkError: 'Invalid link',+ selectError: 'Select a target',+ cancel: 'Cancel',+ ok: 'OK',+ },+ message: {+ coped: 'Copied',+ },+ },+ 'sheets-hyper-link': {+ message: {+ refError: 'Invalid reference',+ },+ },+ },+ });++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(AddHyperLinkMutation);+ commandService.registerCommand(UpdateHyperLinkMutation);+ commandService.registerCommand(RemoveHyperLinkMutation);+ commandService.registerCommand(AddHyperLinkCommand);+ commandService.registerCommand(CancelHyperLinkCommand);+ commandService.registerCommand(OpenHyperLinkEditPanelOperation);+ commandService.registerCommand(CloseHyperLinkPopupOperation);+ commandService.registerCommand(SetWorksheetActiveOperation);+ commandService.registerCommand(ScrollToRangeOperation);++ return {+ univer,+ injector,+ commandService,+ workbook,+ customRange,+ };+}++function inputText(input: HTMLInputElement, value: string) {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++function renderPopup(+ root: Root,+ container: HTMLDivElement,+ testBed: ReturnType<typeof createPopupTestBed>+) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <CellLinkPopupPure+ unitId={UNIT_ID}+ subUnitId={SUB_UNIT_ID}+ row={0}+ col={0}+ customRange={testBed.customRange}+ type={HyperLinkEditSourceType.VIEWING}+ editPermission+ copyPermission={false}+ />+ </RediContext.Provider>+ );+ });++ const actions = Array.from(container.querySelectorAll('.univer-ml-2')) as HTMLElement[];++ return {+ edit: actions[0],+ remove: actions[1],+ };+}++describe('CellLinkPopupPure', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createPopupTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('opens the edit panel for the selected sheet hyperlink range', async () => {+ currentTestBed = createPopupTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const executedCommands: Array<{ id: string; params: unknown }> = [];+ currentTestBed.commandService.onCommandExecuted((command) => {+ executedCommands.push({ id: command.id, params: command.params });+ });+ const actions = renderPopup(root, container, currentTestBed);++ await act(async () => {+ actions.edit.click();+ await Promise.resolve();+ });++ expect(executedCommands).toContainEqual({+ id: OpenHyperLinkEditPanelOperation.id,+ params: {+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ row: 0,+ col: 0,+ customRangeId: 'link-range',+ type: HyperLinkEditSourceType.VIEWING,+ },+ });+ });++ it('removes the hyperlink custom range from the sheet cell', () => {+ currentTestBed = createPopupTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const actions = renderPopup(root, container, currentTestBed);++ act(() => {+ actions.remove.click();+ });++ const cell = currentTestBed.workbook.getSheetBySheetId(SUB_UNIT_ID)?.getCellRaw(0, 0);++ expect(cell?.p?.body?.customRanges?.some((range) => range.rangeId === 'link-range')).toBe(false);+ expect(cell?.p?.body?.dataStream).toBe('Univer\r\n');+ });+});++describe('CellLinkEdit', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createPopupTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('adds a URL hyperlink to the current cell text and closes the popup', async () => {+ currentTestBed = createPopupTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const popupService = currentTestBed.injector.get(SheetsHyperLinkPopupService);+ const renderManagerService = currentTestBed.injector.get(IRenderManagerService) as unknown as TestRenderManagerService;++ act(() => {+ popupService.startAddEditing({+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ row: 0,+ col: 0,+ type: HyperLinkEditSourceType.VIEWING,+ });+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <CellLinkEdit />+ </RediContext.Provider>+ );+ });++ const inputs = Array.from(container.querySelectorAll('input'));+ expect(inputs).toHaveLength(1);++ await act(async () => {+ inputText(inputs[0], 'docs.univer.ai');+ await Promise.resolve();+ });+ renderManagerService.enableScrollRender = true;++ const formButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'));+ const okButton = formButtons[formButtons.length - 1];+ expect(okButton).toBeDefined();++ await act(async () => {+ okButton!.click();+ await Promise.resolve();+ });++ const cell = currentTestBed.workbook.getSheetBySheetId(SUB_UNIT_ID)?.getCellRaw(0, 0);+ const body = cell?.p?.body;+ const linkRange = body?.customRanges?.find((range) => range.rangeType === CustomRangeType.HYPERLINK);++ expect(body?.dataStream).toBe('Univer\r\n');+ expect(linkRange?.properties?.url).toBe('http://docs.univer.ai');+ expect(popupService.currentEditing).toBeNull();+ });+});diff --git a/packages/sheets-hyper-link/src/commands/commands/__tests__/hyper-link.command.spec.ts b/packages/sheets-hyper-link/src/commands/commands/__tests__/hyper-link.command.spec.tsnew file mode 100644index 0000000000..7494f27d2d--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/commands/__tests__/hyper-link.command.spec.ts@@ -0,0 +1,397 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { DocumentDataModel, ICommand, ICustomRange, IDocumentData, IWorkbookData, Workbook } from '@univerjs/core';+import {+ CellValueType,+ createIdentifier,+ CustomRangeType,+ ICommandService,+ IUniverInstanceService,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DocSelectionManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';+import { SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { HyperLinkModel } from '../../../models/hyper-link.model';+import { AddHyperLinkMutation } from '../../mutations/add-hyper-link.mutation';+import { RemoveHyperLinkMutation } from '../../mutations/remove-hyper-link.mutation';+import { UpdateHyperLinkMutation } from '../../mutations/update-hyper-link.mutation';+import { AddHyperLinkCommand, AddRichHyperLinkCommand } from '../add-hyper-link.command';+import { CancelHyperLinkCommand, CancelRichHyperLinkCommand } from '../remove-hyper-link.command';+import { UpdateHyperLinkCommand, UpdateRichHyperLinkCommand } from '../update-hyper-link.command';++const unitId = 'hyper-link-command-workbook';+const subUnitId = 'sheet-1';+const documentId = 'rich-hyper-link-doc';+const IRenderManagerServiceIdentifier = createIdentifier<TestRenderManagerService>('engine-render.render-manager.service');++class TestRenderManagerService {+ getRenderUnitById() {+ return null;+ }+}++function createCellDocument(text: string, rangeId: string, url: string) {+ return {+ id: `${rangeId}-doc`,+ documentStyle: {+ pageSize: { width: 100, height: 40 },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ },+ body: {+ dataStream: `${text}\r\n`,+ customRanges: [{+ rangeId,+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: text.length - 1,+ properties: {+ url,+ },+ }],+ },+ };+}++function createWorkbookData(): IWorkbookData {+ return {+ id: unitId,+ appVersion: '3.0.0-alpha',+ name: 'hyperlink command workbook',+ locale: LocaleType.EN_US,+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet 1',+ cellData: {+ 1: {+ 1: {+ p: createCellDocument('Old', 'cancel-link', 'https://old.invalid'),+ t: CellValueType.STRING,+ },+ },+ 2: {+ 2: {+ p: createCellDocument('Before', 'update-link', 'https://before.invalid'),+ t: CellValueType.STRING,+ },+ },+ },+ },+ },+ };+}++function createDocData(): IDocumentData {+ return {+ id: documentId,+ body: {+ dataStream: 'Existing\r\n',+ customRanges: [{+ rangeId: 'rich-existing',+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 7,+ properties: {+ url: 'https://before.invalid',+ },+ }],+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+ };+}++function findHyperLinkRange(workbook: Workbook, row: number, column: number, rangeId: string): ICustomRange | undefined {+ const ranges = workbook.getSheetBySheetId(subUnitId)?.getCellRaw(row, column)?.p?.body?.customRanges ?? [];+ for (const range of ranges) {+ if (range.rangeId === rangeId) {+ return range;+ }+ }++ return undefined;+}++describe('sheet hyperlink commands', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let workbook: Workbook;+ let doc: DocumentDataModel;+ let hyperLinkModel: HyperLinkModel;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([SheetInterceptorService]);+ injector.add([HyperLinkModel]);+ injector.add([DocSelectionManagerService]);+ injector.add([DocStateEmitService]);+ injector.add([IRenderManagerServiceIdentifier, { useClass: TestRenderManagerService }]);++ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, createDocData());+ injector.get(IUniverInstanceService).focusUnit(unitId);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(SetRangeValuesMutation);+ commandService.registerCommand(AddHyperLinkMutation);+ commandService.registerCommand(UpdateHyperLinkMutation);+ commandService.registerCommand(RemoveHyperLinkMutation);+ commandService.registerCommand(AddHyperLinkCommand);+ commandService.registerCommand(UpdateHyperLinkCommand);+ commandService.registerCommand(CancelHyperLinkCommand);+ commandService.registerCommand(AddRichHyperLinkCommand);+ commandService.registerCommand(UpdateRichHyperLinkCommand);+ commandService.registerCommand(CancelRichHyperLinkCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);+ hyperLinkModel = injector.get(HyperLinkModel);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('adds a hyperlink display value to the selected sheet cell', async () => {+ const result = await commandService.executeCommand(AddHyperLinkCommand.id, {+ unitId,+ subUnitId,+ link: {+ id: 'added-link',+ row: 0,+ column: 0,+ payload: 'https://added.invalid',+ display: 'Added',+ },+ });++ const cell = workbook.getSheetBySheetId(subUnitId)?.getCellRaw(0, 0);+ const range = findHyperLinkRange(workbook, 0, 0, 'added-link');++ expect(result).toBe(true);+ expect(cell?.p?.body?.dataStream).toBe('Added\r\n');+ expect(range).toMatchObject({+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 4,+ properties: {+ url: 'https://added.invalid',+ },+ });+ });++ it('replaces the previous hyperlink model when adding a new link to the same cell', async () => {+ hyperLinkModel.addHyperLink(unitId, subUnitId, {+ id: 'cancel-link',+ row: 1,+ column: 1,+ payload: 'https://old.invalid',+ display: 'Old',+ });++ const result = await commandService.executeCommand(AddHyperLinkCommand.id, {+ unitId,+ subUnitId,+ link: {+ id: 'replacement-link',+ row: 1,+ column: 1,+ payload: 'https://replacement.invalid',+ display: 'Replacement',+ },+ });++ const cell = workbook.getSheetBySheetId(subUnitId)?.getCellRaw(1, 1);+ const range = findHyperLinkRange(workbook, 1, 1, 'replacement-link');++ expect(result).toBe(true);+ expect(cell?.p?.body?.dataStream).toBe('Replacement\r\n');+ expect(range).toMatchObject({+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 10,+ properties: {+ url: 'https://replacement.invalid',+ },+ });+ expect(hyperLinkModel.getHyperLink(unitId, subUnitId, 'cancel-link')).toBeUndefined();+ });++ it('removes a hyperlink from the cell document and hyperlink model', async () => {+ hyperLinkModel.addHyperLink(unitId, subUnitId, {+ id: 'cancel-link',+ row: 1,+ column: 1,+ payload: 'https://old.invalid',+ display: 'Old',+ });++ const result = await commandService.executeCommand(CancelHyperLinkCommand.id, {+ unitId,+ subUnitId,+ id: 'cancel-link',+ row: 1,+ column: 1,+ });++ expect(result).toBe(true);+ expect(findHyperLinkRange(workbook, 1, 1, 'cancel-link')).toBeUndefined();+ expect(hyperLinkModel.getHyperLink(unitId, subUnitId, 'cancel-link')).toBeUndefined();+ });++ it('updates a hyperlink label and target in the cell document', async () => {+ hyperLinkModel.addHyperLink(unitId, subUnitId, {+ id: 'update-link',+ row: 2,+ column: 2,+ payload: 'https://before.invalid',+ display: 'Before',+ });++ const result = await commandService.executeCommand(UpdateHyperLinkCommand.id, {+ unitId,+ subUnitId,+ id: 'update-link',+ row: 2,+ column: 2,+ payload: {+ payload: 'https://after.invalid',+ display: 'After',+ },+ });++ const cell = workbook.getSheetBySheetId(subUnitId)?.getCellRaw(2, 2);+ const updatedRange = cell?.p?.body?.customRanges?.[0];++ expect(result).toBe(true);+ expect(cell?.p?.body?.dataStream).toBe('After\r\n');+ expect(updatedRange).toMatchObject({+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 4,+ properties: {+ url: 'https://after.invalid',+ },+ });+ expect(hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, 2, 2)).toBeUndefined();+ });++ it('adds a rich hyperlink to the selected document text', async () => {+ const selectionManager = univer.__getInjector().get(DocSelectionManagerService);+ selectionManager.__TEST_ONLY_setCurrentSelection({+ unitId: documentId,+ subUnitId: documentId,+ });+ selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 8,+ collapsed: false,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ const result = await commandService.executeCommand(AddRichHyperLinkCommand.id, {+ documentId,+ link: {+ id: 'ignored-source-id',+ row: 0,+ column: 0,+ payload: 'https://rich-added.invalid',+ },+ });++ let addedRange;+ for (const range of doc.getBody()?.customRanges ?? []) {+ if (range.properties?.url === 'https://rich-added.invalid') {+ addedRange = range;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(addedRange).toMatchObject({+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 7,+ properties: {+ url: 'https://rich-added.invalid',+ },+ });+ });++ it('updates a rich hyperlink label and URL in the document body', async () => {+ const result = await commandService.executeCommand(UpdateRichHyperLinkCommand.id, {+ documentId,+ id: 'rich-existing',+ payload: {+ payload: 'https://rich-after.invalid',+ display: 'Updated',+ },+ });++ const range = doc.getBody()?.customRanges?.[0];++ expect(result).toBeTruthy();+ expect(doc.getBody()?.dataStream).toBe('Updated\r\n');+ expect(range).toMatchObject({+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 6,+ properties: {+ url: 'https://rich-after.invalid',+ },+ });+ });++ it('removes a rich hyperlink from the document body', async () => {+ const result = await commandService.executeCommand(CancelRichHyperLinkCommand.id, {+ documentId,+ unitId,+ subUnitId,+ id: 'rich-existing',+ row: 0,+ column: 0,+ });++ let existingRange;+ for (const range of doc.getBody()?.customRanges ?? []) {+ if (range.rangeId === 'rich-existing') {+ existingRange = range;+ break;+ }+ }++ expect(result).toBeTruthy();+ expect(existingRange).toBeUndefined();+ });+});diff --git a/packages/sheets-hyper-link/src/commands/mutations/__tests__/hyper-link.mutation.spec.ts b/packages/sheets-hyper-link/src/commands/mutations/__tests__/hyper-link.mutation.spec.tsnew file mode 100644index 0000000000..bcd1aad938--- /dev/null+++ b/packages/sheets-hyper-link/src/commands/mutations/__tests__/hyper-link.mutation.spec.ts@@ -0,0 +1,200 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { CustomRangeType, ICommandService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { HyperLinkModel } from '../../../models/hyper-link.model';+import { AddHyperLinkMutation } from '../add-hyper-link.mutation';+import { RemoveHyperLinkMutation } from '../remove-hyper-link.mutation';+import { UpdateHyperLinkMutation, UpdateHyperLinkRefMutation, UpdateRichHyperLinkMutation } from '../update-hyper-link.mutation';++const unitId = 'hyper-link-workbook';+const subUnitId = 'sheet-1';++const workbookData: IWorkbookData = {+ id: unitId,+ appVersion: '3.0.0-alpha',+ name: 'hyperlink workbook',+ locale: LocaleType.EN_US,+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet 1',+ cellData: {+ 4: {+ 3: {+ p: {+ id: 'cell-doc',+ documentStyle: {+ pageSize: {+ width: 100,+ height: 40,+ },+ marginTop: 0,+ marginBottom: 0,+ marginLeft: 0,+ marginRight: 0,+ },+ body: {+ dataStream: 'Docs\r\n',+ customRanges: [{+ rangeId: 'rich-link',+ rangeType: CustomRangeType.HYPERLINK,+ startIndex: 0,+ endIndex: 3,+ properties: {+ url: 'https://old.invalid',+ },+ }],+ },+ },+ },+ },+ },+ },+ },+};++function createLink(overrides: Partial<ISheetHyperLink> = {}): ISheetHyperLink {+ return {+ id: 'link-1',+ row: 0,+ column: 0,+ payload: 'https://univer.ai',+ display: 'Univer',+ ...overrides,+ };+}++describe('sheet hyperlink mutations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let hyperLinkModel: HyperLinkModel;+ let workbook: Workbook;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([HyperLinkModel]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(AddHyperLinkMutation);+ commandService.registerCommand(UpdateHyperLinkMutation);+ commandService.registerCommand(UpdateHyperLinkRefMutation);+ commandService.registerCommand(UpdateRichHyperLinkMutation);+ commandService.registerCommand(RemoveHyperLinkMutation);+ hyperLinkModel = injector.get(HyperLinkModel);+ workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('adds and updates the hyperlink attached to a cell', async () => {+ const addResult = await commandService.executeCommand(AddHyperLinkMutation.id, {+ unitId,+ subUnitId,+ link: createLink(),+ });+ const updateResult = await commandService.executeCommand(UpdateHyperLinkMutation.id, {+ unitId,+ subUnitId,+ id: 'link-1',+ payload: {+ payload: 'https://docs.univer.ai',+ display: 'Docs',+ },+ });++ expect(addResult).toBe(true);+ expect(updateResult).toBe(true);+ expect(hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, 0, 0)).toMatchObject({+ id: 'link-1',+ payload: 'https://docs.univer.ai',+ display: 'Docs',+ });+ });++ it('moves a hyperlink to a new cell and clears its original location', async () => {+ await commandService.executeCommand(AddHyperLinkMutation.id, {+ unitId,+ subUnitId,+ link: createLink(),+ });++ const moveResult = await commandService.executeCommand(UpdateHyperLinkRefMutation.id, {+ unitId,+ subUnitId,+ id: 'link-1',+ row: 3,+ column: 2,+ });++ expect(moveResult).toBe(true);+ expect(hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, 0, 0)).toBeUndefined();+ expect(hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, 3, 2)).toMatchObject({+ id: 'link-1',+ row: 3,+ column: 2,+ });+ });++ it('removes a hyperlink from both id and cell lookup', async () => {+ await commandService.executeCommand(AddHyperLinkMutation.id, {+ unitId,+ subUnitId,+ link: createLink(),+ });++ const removeResult = await commandService.executeCommand(RemoveHyperLinkMutation.id, {+ unitId,+ subUnitId,+ id: 'link-1',+ });++ expect(removeResult).toBe(true);+ expect(hyperLinkModel.getHyperLink(unitId, subUnitId, 'link-1')).toBeUndefined();+ expect(hyperLinkModel.getHyperLinkByLocation(unitId, subUnitId, 0, 0)).toBeUndefined();+ });++ it('updates the URL stored in a rich hyperlink cell range', async () => {+ const result = await commandService.executeCommand(UpdateRichHyperLinkMutation.id, {+ unitId,+ subUnitId,+ row: 4,+ col: 3,+ id: 'rich-link',+ url: 'https://new.invalid',+ });++ let updatedUrl = '';+ const ranges = workbook.getSheetBySheetId(subUnitId)?.getCellRaw(4, 3)?.p?.body?.customRanges ?? [];+ for (const range of ranges) {+ if (range.rangeId === 'rich-link') {+ updatedUrl = range.properties?.url ?? '';+ break;+ }+ }++ expect(result).toBe(true);+ expect(updatedUrl).toBe('https://new.invalid');+ });+});diff --git a/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts b/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.tsindex 08c44045ad..428df0ece1 100644--- a/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts+++ b/packages/sheets-hyper-link/src/facade/__tests__/f-range.spec.ts@@ -15,16 +15,14 @@*/import type { IWorkbookData, UnitModel } from '@univerjs/core';-import type { FUniver } from '@univerjs/core/facade';import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';-import { FUniver as FUniverFactory } from '@univerjs/core/facade';+import { FUniver } from '@univerjs/core/facade';import { DocSelectionManagerService } from '@univerjs/docs';-import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';+import { IDefinedNamesService } from '@univerjs/engine-formula';+import { SheetHyperLinkType, UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import '@univerjs/sheets/facade';-import '../f-range';-import '../f-workbook';-import '../f-worksheet';+import '../index';function createWorkbookData(): IWorkbookData {return {@@ -61,7 +59,7 @@ describe('FRangeSheetsHyperlinkMixin', () => {injector.get(IUniverInstanceService).focusUnit(workbook.getUnitId());injector.get(ILogService).setLogLevel(LogLevel.SILENT);- univerAPI = FUniverFactory.newAPI(injector);+ univerAPI = FUniver.newAPI(injector);});afterEach(() => {@@ -72,6 +70,16 @@ describe('FRangeSheetsHyperlinkMixin', () => {const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();const a1 = worksheet.getRange('A1');const b2 = worksheet.getRange('B2');+ const events: string[] = [];+ const addDisposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkAdd, (event) => {+ events.push(`add:${event.row}:${event.col}:${event.link.payload}`);+ });+ const updateDisposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkUpdate, (event) => {+ events.push(`update:${event.row}:${event.column}:${event.payload.payload}`);+ });+ const cancelDisposable = univerAPI.addEvent(univerAPI.Event.BeforeSheetLinkCancel, (event) => {+ events.push(`cancel:${event.row}:${event.column}`);+ });await expect(a1.setHyperLink('https://univer.ai', 'Univer')).resolves.toBe(true);await expect(b2.setHyperLink('https://docs.univer.ai', 'Docs')).resolves.toBe(true);@@ -104,11 +112,37 @@ describe('FRangeSheetsHyperlinkMixin', () => {expect(worksheet.getRange('A1:B2').cancelHyperLink()).toBe(true);expect(worksheet.getRange('A1:B2').getHyperLinks()).toEqual([]);+ expect(events).toEqual([+ 'add:0:0:https://univer.ai',+ 'add:1:1:https://docs.univer.ai',+ 'update:0:0:https://univer.ai/docs',+ 'cancel:0:0',+ 'cancel:1:1',+ ]);++ addDisposable.dispose();+ updateDisposable.dispose();+ cancelDisposable.dispose();});it('should create hyperlink urls from sheet ranges', () => {- const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const workbook = univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ expect(worksheet.getUrl()).toBe('#gid=sheet1');expect(worksheet.getRange('A1:B2').getUrl()).toBe('#gid=sheet1&range=A1:B2');++ univer.__getInjector().get(IDefinedNamesService).registerDefinedName(workbook.getId(), {+ id: 'range-1',+ name: 'Total',+ formulaOrRefString: 'Sheet1!A1:B2',+ });+ expect(workbook.getUrlOfDefineName('Total')).toBe('#rangeid=range-1');+ expect(workbook.parseSheetHyperlink('https://univer.ai')).toEqual({+ type: SheetHyperLinkType.URL,+ name: 'https://univer.ai',+ url: 'https://univer.ai',+ searchObj: null,+ });});});diff --git a/packages/sheets-note-ui/src/commands/operations/__tests__/add-note-popup.operation.spec.ts b/packages/sheets-note-ui/src/commands/operations/__tests__/add-note-popup.operation.spec.tsnew file mode 100644index 0000000000..41f60d4769--- /dev/null+++ b/packages/sheets-note-ui/src/commands/operations/__tests__/add-note-popup.operation.spec.ts@@ -0,0 +1,117 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import { ICommandService, IUniverInstanceService, LocaleType, toDisposable, Univer, UniverInstanceType } from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { CellPopupManagerService } from '@univerjs/sheets-ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SheetsNotePopupService } from '../../../services/sheets-note-popup.service';+import { AddNotePopupOperation } from '../add-note-popup.operation';++const workbookData: IWorkbookData = {+ id: 'note-workbook',+ appVersion: '3.0.0-alpha',+ name: 'note workbook',+ locale: LocaleType.EN_US,+ sheetOrder: ['sheet-1'],+ styles: {},+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet 1',+ cellData: {},+ },+ },+};++class TestCellPopupManagerService {+ showPopup() {+ return toDisposable(() => {});+ }+}++function createSelection(row: number, col: number): ISelectionWithStyle {+ return {+ range: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ },+ primary: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ actualRow: row,+ actualColumn: col,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ };+}++describe('AddNotePopupOperation', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let selectionsService: SheetsSelectionsService;+ let notePopupService: SheetsNotePopupService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([SheetsSelectionsService]);+ injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);+ injector.add([SheetsNotePopupService]);++ univer.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData);+ injector.get(IUniverInstanceService).focusUnit('note-workbook');+ commandService = injector.get(ICommandService);+ commandService.registerCommand(AddNotePopupOperation);+ selectionsService = injector.get(SheetsSelectionsService);+ notePopupService = injector.get(SheetsNotePopupService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('opens a note popup at the active cell in the current worksheet', async () => {+ selectionsService.setSelections('note-workbook', 'sheet-1', [createSelection(2, 3)]);++ const result = await commandService.executeCommand(AddNotePopupOperation.id, { trigger: 'context-menu' });++ expect(result).toBe(true);+ expect(notePopupService.activePopup).toEqual({+ unitId: 'note-workbook',+ subUnitId: 'sheet-1',+ row: 2,+ col: 3,+ temp: false,+ trigger: 'context-menu',+ });+ });++ it('does not open a note popup when there is no active cell selection', async () => {+ const result = await commandService.executeCommand(AddNotePopupOperation.id);++ expect(result).toBe(false);+ expect(notePopupService.activePopup).toBeUndefined();+ });+});diff --git a/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.ts b/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.tsindex bae203e699..5beac8d60d 100644--- a/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.ts+++ b/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.ts@@ -16,17 +16,32 @@import { Injector } from '@univerjs/core';import { CellPopupManagerService } from '@univerjs/sheets-ui';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it } from 'vitest';import { SheetsNotePopupService } from '../sheets-note-popup.service';+class TestCellPopupManagerService {+ static disposedCount = 0;++ static reset() {+ this.disposedCount = 0;+ }++ showPopup() {+ return {+ dispose: () => {+ TestCellPopupManagerService.disposedCount += 1;+ },+ };+ }+}+describe('SheetsNotePopupService', () => {let service: SheetsNotePopupService;- let popupDispose: ReturnType<typeof vi.fn>;beforeEach(() => {- popupDispose = vi.fn();+ TestCellPopupManagerService.reset();const injector = new Injector();- injector.add([CellPopupManagerService, { useValue: { showPopup: vi.fn(() => ({ dispose: popupDispose })) } }]);+ injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);injector.add([SheetsNotePopupService]);service = injector.get(SheetsNotePopupService);});@@ -41,7 +56,7 @@ describe('SheetsNotePopupService', () => {expect(service.activePopup).toBeNull();expect(active.at(-2)).toEqual({ unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2, noteId: 'note-1', temp: true });expect(active.at(-1)).toBeNull();- expect(popupDispose).toHaveBeenCalledTimes(1);+ expect(TestCellPopupManagerService.disposedCount).toBe(1);});it('persists an opened temporary note popup', () => {diff --git a/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsx b/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsxnew file mode 100644index 0000000000..f059ee01e4--- /dev/null+++ b/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsx@@ -0,0 +1,245 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IWorkbookData, Workbook } from '@univerjs/core';+import type { IPopup } from '@univerjs/ui';+import type { Root } from 'react-dom/client';+import {+ awaitTime,+ ICommandService,+ IConfigService,+ ILogService,+ IUndoRedoService,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import {+ RemoveNoteMutation,+ SheetsNoteModel,+ SheetUpdateNoteCommand,+ UpdateNoteMutation,+} from '@univerjs/sheets-note';+import { CellPopupManagerService } from '@univerjs/sheets-ui';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { SHEETS_NOTE_UI_PLUGIN_CONFIG_KEY } from '../../config/config';+import { SheetsNotePopupService } from '../../services/sheets-note-popup.service';+import { SheetsNote } from '../Note';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'note-view-workbook';+const SUB_UNIT_ID = 'sheet-1';++class TestRenderManagerService {+ getRenderById() {+ return {+ engine: {+ getCanvasElement() {+ return document.createElement('canvas');+ },+ },+ };+ }+}++class TestCellPopupManagerService {+ showPopup(): IDisposable {+ return toDisposable(() => undefined);+ }+}++class TestResizeObserver {+ observe(): void {}++ unobserve(): void {}++ disconnect(): void {}+}++function createWorkbookData(): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ name: 'note workbook',+ locale: LocaleType.EN_US,+ sheetOrder: [SUB_UNIT_ID],+ styles: {},+ sheets: {+ [SUB_UNIT_ID]: {+ id: SUB_UNIT_ID,+ name: 'Sheet 1',+ cellData: {},+ },+ },+ };+}++function createNotePopup(row: number, col: number): IPopup<{ location: { unitId: string; subUnitId: string; row: number; col: number; trigger: string } }> {+ return {+ extraProps: {+ location: {+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ row,+ col,+ trigger: 'context-menu',+ },+ },+ } as IPopup<{ location: { unitId: string; subUnitId: string; row: number; col: number; trigger: string } }>;+}++function createNoteViewTestBed() {+ const univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([SheetsNoteModel]);+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);+ injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);+ injector.add([SheetsNotePopupService]);+ injector.get(IUndoRedoService);+ injector.get(IConfigService).setConfig(SHEETS_NOTE_UI_PLUGIN_CONFIG_KEY, {+ defaultNoteSize: {+ width: 180,+ height: 96,+ },+ });+ injector.get(LocaleService).load({+ [LocaleType.EN_US]: {+ 'sheets-note-ui': {+ note: {+ placeholder: 'Write a note',+ },+ },+ },+ });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(UpdateNoteMutation);+ commandService.registerCommand(RemoveNoteMutation);+ commandService.registerCommand(SheetUpdateNoteCommand);++ return {+ univer,+ injector,+ workbook,+ noteModel: injector.get(SheetsNoteModel),+ };+}++function inputText(textarea: HTMLTextAreaElement, value: string) {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')?.set;+ valueSetter?.call(textarea, value);+ textarea.dispatchEvent(new Event('input', { bubbles: true }));+}++async function renderNote(root: Root, testBed: ReturnType<typeof createNoteViewTestBed>, row = 2, col = 3) {+ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <SheetsNote popup={createNotePopup(row, col)} />+ </RediContext.Provider>+ );+ await awaitTime(20);+ });+}++describe('SheetsNote', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createNoteViewTestBed> | undefined;+ let resizeObserverDescriptor: PropertyDescriptor | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ if (resizeObserverDescriptor) {+ Object.defineProperty(globalThis, 'ResizeObserver', resizeObserverDescriptor);+ } else {+ delete (globalThis as { ResizeObserver?: unknown }).ResizeObserver;+ }+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ resizeObserverDescriptor = undefined;+ });++ function createMountedNote() {+ resizeObserverDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'ResizeObserver');+ Object.defineProperty(globalThis, 'ResizeObserver', {+ configurable: true,+ value: TestResizeObserver,+ });+ currentTestBed = createNoteViewTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ return currentTestBed;+ }++ it('creates a note with the configured default size when an empty cell popup opens', async () => {+ const testBed = createMountedNote();++ await renderNote(root!, testBed);+ await act(async () => {+ await awaitTime(350);+ });++ const note = testBed.noteModel.getNote(UNIT_ID, SUB_UNIT_ID, { row: 2, col: 3 });+ expect(note?.note).toBe('');+ expect(note?.width).toBe(180);+ expect(note?.height).toBe(96);+ expect(container!.querySelector('textarea')?.placeholder).toBe('Write a note');+ });++ it('persists edited note text through the sheet note command pipeline', async () => {+ const testBed = createMountedNote();++ await renderNote(root!, testBed);+ await act(async () => {+ await awaitTime(350);+ });++ const textarea = container!.querySelector('textarea') as HTMLTextAreaElement;++ await act(async () => {+ inputText(textarea, 'Follow up with finance');+ await awaitTime(350);+ });++ const note = testBed.noteModel.getNote(UNIT_ID, SUB_UNIT_ID, { row: 2, col: 3 });+ expect(note?.note).toBe('Follow up with finance');+ expect(note?.width).toBe(180);+ expect(note?.height).toBe(96);+ });+});diff --git a/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts b/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.tsindex 41eee84064..23d8510b27 100644--- a/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts+++ b/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts@@ -15,8 +15,9 @@*/import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';-import type { FUniver } from '@univerjs/core/facade';+import type { ISelectionWithStyle } from '@univerjs/sheets';import {+ ICommandService,ILogService,Inject,Injector,@@ -25,11 +26,12 @@ import {LocaleType,LogLevel,Plugin,+ RANGE_TYPE,touchDependencies,Univer,UniverInstanceType,} from '@univerjs/core';-import { FUniver as FUniverFactory } from '@univerjs/core/facade';+import { FUniver } from '@univerjs/core/facade';import {DefinedNamesService,FormulaDataModel,@@ -51,7 +53,12 @@ import {WorksheetProtectionPointModel,WorksheetProtectionRuleModel,} from '@univerjs/sheets';-import { beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ SheetDeleteNoteCommand,+ SheetToggleNotePopupCommand,+ SheetUpdateNoteCommand,+} from '../../commands/commands/note.command';import { SheetsNoteController } from '../../controllers/sheets.note.controller';import { SheetsNoteModel } from '../../models/sheets-note.model';import '@univerjs/sheets/facade';@@ -139,7 +146,7 @@ function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?: Dependconst logService = injector.get(ILogService);logService.setLogLevel(LogLevel.SILENT);- const univerAPI = FUniverFactory.newAPI(injector);+ const univerAPI = FUniver.newAPI(injector);return {univer,@@ -149,14 +156,47 @@ function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?: Depend};}+function setSingleCellSelection(injector: Injector, row: number, col: number) {+ const selection: ISelectionWithStyle = {+ range: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ rangeType: RANGE_TYPE.NORMAL,+ },+ primary: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ actualRow: row,+ actualColumn: col,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ };++ injector.get(SheetsSelectionsService).setSelections([selection]);+}+describe('sheets-note facade mixins', () => {+ let univer: Univer;+ let injector: Injector;let univerAPI: FUniver;beforeEach(() => {const testBed = createFacadeTestBed();+ univer = testBed.univer;+ injector = testBed.injector;univerAPI = testBed.univerAPI;});+ afterEach(() => {+ univer.dispose();+ });+it('creates/reads/deletes note through FRange and reads all notes via FWorksheet', () => {const workbook = univerAPI.getActiveWorkbook();expect(workbook).toBeTruthy();@@ -181,4 +221,63 @@ describe('sheets-note facade mixins', () => {expect(range.getNote()).toBeUndefined();expect(sheet.getNotes()).toHaveLength(0);});++ it('emits business events while notes are added, updated, shown, hidden and deleted', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const sheet = workbook.getActiveSheet();+ const commandService = injector.get(ICommandService);+ const events: string[] = [];+ const disposables = [+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNoteAdd, (event) => events.push(`before-add:${event.row}:${event.col}:${event.note.note}`)),+ univerAPI.addEvent(univerAPI.Event.SheetNoteAdd, (event) => events.push(`add:${event.row}:${event.col}:${event.note.note}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNoteUpdate, (event) => events.push(`before-update:${event.row}:${event.col}:${event.oldNote.note}->${event.note.note}`)),+ univerAPI.addEvent(univerAPI.Event.SheetNoteUpdate, (event) => events.push(`update:${event.row}:${event.col}:${event.oldNote.note}->${event.note.note}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNoteShow, (event) => events.push(`before-show:${event.row}:${event.col}`)),+ univerAPI.addEvent(univerAPI.Event.SheetNoteShow, (event) => events.push(`show:${event.row}:${event.col}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNoteHide, (event) => events.push(`before-hide:${event.row}:${event.col}`)),+ univerAPI.addEvent(univerAPI.Event.SheetNoteHide, (event) => events.push(`hide:${event.row}:${event.col}`)),+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNoteDelete, (event) => events.push(`before-delete:${event.row}:${event.col}:${event.oldNote.note}`)),+ univerAPI.addEvent(univerAPI.Event.SheetNoteDelete, (event) => events.push(`delete:${event.row}:${event.col}:${event.oldNote.note}`)),+ ];++ expect(commandService.syncExecuteCommand(SheetUpdateNoteCommand.id, {+ unitId,+ sheetId: subUnitId,+ row: 1,+ col: 1,+ note: { id: 'note-1', row: 1, col: 1, width: 160, height: 72, note: 'hello', show: false },+ })).toBe(true);+ expect(commandService.syncExecuteCommand(SheetUpdateNoteCommand.id, {+ unitId,+ sheetId: subUnitId,+ row: 1,+ col: 1,+ note: { id: 'note-1', row: 1, col: 1, width: 160, height: 72, note: 'updated', show: false },+ })).toBe(true);++ setSingleCellSelection(injector, 1, 1);+ expect(commandService.syncExecuteCommand(SheetToggleNotePopupCommand.id)).toBe(true);+ expect(sheet.getRange(1, 1).getNote()?.show).toBe(true);++ expect(commandService.syncExecuteCommand(SheetToggleNotePopupCommand.id)).toBe(true);+ expect(sheet.getRange(1, 1).getNote()?.show).toBe(false);++ expect(commandService.syncExecuteCommand(SheetDeleteNoteCommand.id)).toBe(true);+ expect(sheet.getRange(1, 1).getNote()).toBeUndefined();++ expect(events).toEqual(expect.arrayContaining([+ 'before-add:1:1:hello',+ 'add:1:1:hello',+ 'before-update:1:1:hello->updated',+ 'update:1:1:hello->updated',+ 'before-show:1:1',+ 'show:1:1',+ 'before-hide:1:1',+ 'hide:1:1',+ 'before-delete:1:1:updated',+ 'delete:1:1:updated',+ ]));++ disposables.forEach((disposable) => disposable.dispose());+ });});diff --git a/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.spec.ts b/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.spec.tsnew file mode 100644index 0000000000..d7bf73b5d8--- /dev/null+++ b/packages/sheets-numfmt-ui/src/commands/operations/__tests__/numfmt-panel.operation.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 { ISelectionWithStyle } from '@univerjs/sheets';+import { ICommandService, LocaleService } from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';+import { ComponentManager, DesktopSidebarService, ISidebarService } from '@univerjs/ui';+import { beforeEach, describe, expect, it } from 'vitest';+import { createTestBed } from '../../../controllers/__tests__/test.util';+import { SheetNumfmtUIController } from '../../../controllers/ui.controller';+import { CloseNumfmtPanelOperator } from '../close.numfmt.panel.operation';+import { OpenNumfmtPanelOperator } from '../open.numfmt.panel.operation';++function createSelection(row: number, column: number): ISelectionWithStyle {+ return {+ range: { startRow: row, endRow: row, startColumn: column, endColumn: column },+ primary: {+ startRow: row,+ endRow: row,+ startColumn: column,+ endColumn: column,+ actualRow: row,+ actualColumn: column,+ isMerged: false,+ isMergedMainCell: false,+ },+ };+}++describe('number format panel operation', () => {+ let commandService: ICommandService;+ let selectionsService: SheetsSelectionsService;+ let sidebarService: ISidebarService;+ let unitId: string;+ let subUnitId: string;++ beforeEach(() => {+ const testBed = createTestBed(undefined, [+ [SheetsSelectionsService],+ [IRenderManagerService, { useClass: RenderManagerService }],+ [SheetSkeletonManagerService],+ [ComponentManager],+ [ISidebarService, { useClass: DesktopSidebarService }],+ [SheetsNumfmtCellContentController],+ [SheetNumfmtUIController],+ ]);++ unitId = testBed.unitId;+ subUnitId = testBed.subUnitId;+ commandService = testBed.get(ICommandService);+ selectionsService = testBed.get(SheetsSelectionsService);+ sidebarService = testBed.get(ISidebarService);+ testBed.get(LocaleService).load({});+ testBed.get(SheetNumfmtUIController);+ });++ it('opens the number format panel with the active cell preview value', async () => {+ selectionsService.setSelections(unitId, subUnitId, [createSelection(0, 1)]);++ await commandService.executeCommand(OpenNumfmtPanelOperator.id);++ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options.header?.title).toBe('sheets-numfmt-ui.title');+ expect(sidebarService.options.children).toMatchObject({+ label: 'SHEET_NUMFMT_PANEL',+ value: {+ defaultPattern: '',+ defaultValue: 1,+ row: 0,+ col: 1,+ },+ });+ });++ it('keeps the sidebar closed when there is no active selection', async () => {+ await commandService.executeCommand(OpenNumfmtPanelOperator.id);++ expect(sidebarService.visible).toBe(false);+ });++ it('publishes a close notification after the number format panel is dismissed', async () => {+ const closedPanelEvents: string[] = [];+ commandService.onCommandExecuted((commandInfo) => {+ if (commandInfo.id === CloseNumfmtPanelOperator.id) {+ closedPanelEvents.push(commandInfo.id);+ }+ });+ selectionsService.setSelections(unitId, subUnitId, [createSelection(0, 1)]);+ await commandService.executeCommand(OpenNumfmtPanelOperator.id);++ await commandService.executeCommand(CloseNumfmtPanelOperator.id);++ expect(closedPanelEvents).toEqual([CloseNumfmtPanelOperator.id]);+ });+});diff --git a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsxnew file mode 100644index 0000000000..eb1286b1cf--- /dev/null+++ b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx@@ -0,0 +1,532 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import {+ CellValueType,+ ICommandService,+ ILocalStorageService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ RANGE_TYPE,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ INumfmtService,+ NumfmtService,+ RemoveNumfmtMutation,+ SetNumfmtMutation,+ SetRangeValuesMutation,+ SheetInterceptorService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { SetNumfmtCommand, SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';+import { ILayoutService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { UserHabitController } from '../../controllers/user-habit.controller';+import { CustomFormat } from '../components/CustomFormat';+import { Options } from '../components/MoreNumfmtType';+import { SheetNumfmtPanel } from '../SheetNumfmtPanel';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'test';+const SUB_UNIT_ID = 'sheet1';+const CUSTOM_HISTORY_KEY = 'numfmt_custom_pattern';++class TestLocalStorageService implements ILocalStorageService {+ private readonly _data = new Map<string, unknown>();++ async getItem<T>(key: string): Promise<T | null> {+ return (this._data.has(key) ? this._data.get(key) : null) as T | null;+ }++ async setItem<T>(key: string, value: T): Promise<T> {+ this._data.set(key, value);+ return value;+ }++ async removeItem(key: string): Promise<void> {+ this._data.delete(key);+ }++ async clear(): Promise<void> {+ this._data.clear();+ }++ async key(index: number): Promise<string | null> {+ return Array.from(this._data.keys())[index] ?? null;+ }++ async keys(): Promise<string[]> {+ return Array.from(this._data.keys());+ }++ async iterate<T, U>(iteratee: (value: T, key: string, iterationNumber: number) => U): Promise<U> {+ const entries = Array.from(this._data.entries());+ let result: U | undefined;+ entries.forEach(([key, value], index) => {+ result = iteratee(value as T, key, index + 1);+ });+ return result as U;+ }+}++class TestLayoutService {+ private _focused = false;+ readonly rootContainerElement = document.body;++ get isFocused() {+ return this._focused;+ }++ focus() {+ this._focused = true;+ }++ registerFocusHandler(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerRootContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContentElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ registerContainerElement(): IDisposable {+ return toDisposable(() => undefined);+ }++ getContentElement() {+ return document.body;+ }++ checkElementInCurrentContainers() {+ return true;+ }++ checkContentIsFocused() {+ return this._focused;+ }+}++function createWorkbookData(): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'numfmt view test',+ sheetOrder: [SUB_UNIT_ID],+ styles: {},+ sheets: {+ [SUB_UNIT_ID]: {+ id: SUB_UNIT_ID,+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: 12, t: CellValueType.NUMBER },+ 1: { v: 34, t: CellValueType.NUMBER },+ },+ },+ },+ },+ };+}++function createNumfmtViewTestBed() {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'sheets-numfmt-ui-view-test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) override readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ ([+ [SheetsSelectionsService],+ [SheetInterceptorService],+ [INumfmtService, { useClass: NumfmtService }],+ [SheetsNumfmtCellContentController],+ [UserHabitController],+ [ILocalStorageService, { useClass: TestLocalStorageService }],+ [ILayoutService, { useClass: TestLayoutService as never }],+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());++ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ const localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.EN_US]: {+ 'sheets-numfmt-ui': {+ general: 'General',+ text: 'Text',+ number: 'Number',+ percent: 'Percent',+ scientific: 'Scientific',+ accounting: 'Accounting',+ financialValue: 'Financial value',+ currency: 'Currency',+ thousandthPercentile: 'Number',+ roundingCurrency: 'Rounded currency',+ date: 'Date',+ time: 'Time',+ dateTime: 'Date time',+ timeDuration: 'Time duration',+ moreFmt: 'More formats',+ numfmtType: 'Number format',+ decimalLength: 'Decimal places',+ negType: 'Negative values',+ customFormat: 'Custom format',+ customFormatDes: 'Custom formats can be saved and reused.',+ },+ },+ });+ localeService.setLocale(LocaleType.EN_US);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ [+ SetRangeValuesMutation,+ SetNumfmtMutation,+ RemoveNumfmtMutation,+ SetNumfmtCommand,+ ].forEach((command) => commandService.registerCommand(command));++ return {+ univer,+ injector,+ workbook,+ commandService,+ selectionService: injector.get(SheetsSelectionsService),+ numfmtService: injector.get(INumfmtService),+ localStorageService: injector.get(ILocalStorageService),+ };+}++describe('MoreNumfmtType Options', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createNumfmtViewTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('applies and clears number formats on the current sheet selection', async () => {+ currentTestBed = createNumfmtViewTestBed();+ currentTestBed.selectionService.setSelections([{+ range: {+ startRow: 0,+ endRow: 0,+ startColumn: 0,+ endColumn: 1,+ rangeType: RANGE_TYPE.NORMAL,+ },+ primary: null,+ }] as never);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <Options />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const items = Array.from(container.querySelectorAll('.univer-flex.univer-h-7')) as HTMLElement[];++ await act(async () => {+ items[2].dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({ pattern: '0' });+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 1)).toEqual({ pattern: '0' });++ await act(async () => {+ items[0].dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toBeNull();+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 1)).toBeNull();+ });+});++describe('CustomFormat', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createNumfmtViewTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('uses saved custom patterns and writes the confirmed pattern back to history', async () => {+ currentTestBed = createNumfmtViewTestBed();+ await currentTestBed.localStorageService.setItem(CUSTOM_HISTORY_KEY, ['0.0000']);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const changes: string[] = [];+ let getCurrentPattern: (() => string | null) | undefined;++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <CustomFormat+ defaultValue={1234.5}+ defaultPattern="0.00"+ onChange={(value) => changes.push(value)}+ onActionChange={(action) => {+ getCurrentPattern = action;+ }}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const savedPattern = Array.from(container.querySelectorAll('.univer-flex.univer-cursor-pointer'))+ .find((item) => item.textContent?.includes('0.0000')) as HTMLElement;++ expect(savedPattern).toBeDefined();++ await act(async () => {+ savedPattern.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(changes.at(-1)).toBe('0.0000');++ const confirmedPattern = getCurrentPattern?.();+ await Promise.resolve();++ expect(confirmedPattern).toBe('0.0000');+ expect(await currentTestBed.localStorageService.getItem<string[]>(CUSTOM_HISTORY_KEY)).toEqual(['0.0000']);+ });++ it('keeps confirmed custom patterns recent and unique in the saved history', async () => {+ currentTestBed = createNumfmtViewTestBed();+ await currentTestBed.localStorageService.setItem(CUSTOM_HISTORY_KEY, [+ '0.0',+ '#,##0',+ 'm/d/yyyy',+ '0.0',+ '0%',+ '$#,##0.00',+ 'h:mm AM/PM',+ '0.000',+ '#,##0.00',+ '0.00%',+ '0.0000',+ ]);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ let getCurrentPattern: (() => string | null) | undefined;++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <CustomFormat+ defaultValue={1234.5}+ defaultPattern="#,##0"+ onChange={() => undefined}+ onActionChange={(action) => {+ getCurrentPattern = action;+ }}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ expect(getCurrentPattern?.()).toBe('#,##0');+ await Promise.resolve();++ expect(await currentTestBed.localStorageService.getItem<string[]>(CUSTOM_HISTORY_KEY)).toEqual([+ '#,##0',+ '0.0',+ 'm/d/yyyy',+ '0%',+ '$#,##0.00',+ 'h:mm AM/PM',+ '0.000',+ '#,##0.00',+ '0.00%',+ '0.0000',+ ]);+ });+});++describe('SheetNumfmtPanel', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createNumfmtViewTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('confirms the current number format pattern and reports cancel without changing a pattern', async () => {+ currentTestBed = createNumfmtViewTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const events: Array<{ type: 'change' | 'cancel' | 'confirm'; value: string }> = [];++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <SheetNumfmtPanel+ value={{+ defaultValue: 1234.5,+ defaultPattern: '#,##0_);(#,##0)',+ row: 0,+ col: 0,+ }}+ onChange={(event) => events.push(event)}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ const buttons = Array.from(container.querySelectorAll('[data-u-comp="button"]')) as HTMLElement[];+ const cancelButton = buttons[0];+ const confirmButton = buttons[1];++ await act(async () => {+ confirmButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ await act(async () => {+ cancelButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(events).toEqual([+ { type: 'confirm', value: '#,##0_);(#,##0)' },+ { type: 'cancel', value: '' },+ ]);+ });++ it('clears an existing number format when the user switches the panel type to General', async () => {+ currentTestBed = createNumfmtViewTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const events: Array<{ type: 'change' | 'cancel' | 'confirm'; value: string }> = [];++ await act(async () => {+ root!.render(+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>+ <SheetNumfmtPanel+ value={{+ defaultValue: 1234.5,+ defaultPattern: '#,##0_);(#,##0)',+ row: 0,+ col: 0,+ }}+ onChange={(event) => events.push(event)}+ />+ </RediContext.Provider>+ );+ await Promise.resolve();+ });++ await act(async () => {+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));+ await Promise.resolve();+ });++ const generalOption = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))+ .find((button) => button.textContent === 'General');++ expect(generalOption).toBeDefined();++ await act(async () => {+ generalOption!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ const confirmButton = Array.from(container.querySelectorAll('[data-u-comp="button"]'))[1] as HTMLElement;++ await act(async () => {+ confirmButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(events).toEqual([+ { type: 'change', value: '' },+ { type: 'confirm', value: '' },+ ]);+ });+});diff --git a/packages/sheets-numfmt/src/facade/__tests__/create-test-bed.ts b/packages/sheets-numfmt/src/facade/__tests__/create-test-bed.tsindex afaeeae815..9e7fb06cb1 100644--- a/packages/sheets-numfmt/src/facade/__tests__/create-test-bed.ts+++ b/packages/sheets-numfmt/src/facade/__tests__/create-test-bed.ts@@ -30,6 +30,8 @@ import {UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';+import { DefinedNamesService, FormulaDataModel, IDefinedNamesService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { INumfmtService, NumfmtService, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import enUS from '@univerjs/sheets/locale/en-US';import zhCN from '@univerjs/sheets/locale/zh-CN';@@ -107,7 +109,15 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:}override onStarting(): void {+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([FormulaDataModel]);+ injector.add([LexerTreeBuilder]);+ injector.add([INumfmtService, { useClass: NumfmtService }]);dependencies?.forEach((d) => injector.add(d));++ this._injector.get(SheetInterceptorService);}override onReady(): void {diff --git a/packages/sheets-numfmt/src/facade/__tests__/f-range.spec.ts b/packages/sheets-numfmt/src/facade/__tests__/f-range.spec.tsindex 0ece47a926..04eb40a07f 100644--- a/packages/sheets-numfmt/src/facade/__tests__/f-range.spec.ts+++ b/packages/sheets-numfmt/src/facade/__tests__/f-range.spec.ts@@ -15,28 +15,50 @@*/import type { FUniver } from '@univerjs/core/facade';-import { LifecycleStages } from '@univerjs/core';+import { ICommandService } from '@univerjs/core';+import { RemoveNumfmtMutation, SetNumfmtMutation, SetRangeValuesMutation } from '@univerjs/sheets';import { beforeEach, describe, expect, it } from 'vitest';+import { SetNumfmtCommand, SheetsNumfmtCellContentController } from '../../index';import { createFacadeTestBed } from './create-test-bed';+import '../index';describe('Test FRange', () => {let univerAPI: FUniver;+ let testBed: ReturnType<typeof createFacadeTestBed>;beforeEach(() => {- const testBed = createFacadeTestBed();-+ testBed = createFacadeTestBed(undefined, [[SheetsNumfmtCellContentController]]);+ const commandService = testBed.injector.get(ICommandService);+ [+ SetRangeValuesMutation,+ SetNumfmtMutation,+ RemoveNumfmtMutation,+ SetNumfmtCommand,+ ].forEach((command) => commandService.registerCommand(command));univerAPI = testBed.univerAPI;});- it('Range setNumberFormat', () => {- univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {- if (stage === LifecycleStages.Rendered) {- const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();- const range = activeSheet.getRange(0, 0, 1, 1);- range.setValue(1234.5678);- range.setNumberFormat('#,###');- expect(range.getValue()).toBe('1,234.5678');- }- });+ it('sets and reads number formats on a single range and a range grid', () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const singleCell = activeSheet.getRange('A1');++ expect(singleCell.setNumberFormat('#,##0.00')).toBe(singleCell);+ expect(singleCell.getNumberFormat()).toBe('#,##0.00');++ const range = activeSheet.getRange('A1:B2');+ range.setNumberFormats([+ ['#,##0.00', '0.00%'],+ ['yyyy-MM-DD', ''],+ ]);++ expect(range.getNumberFormats()).toEqual([+ ['#,##0.00', '0.00%'],+ ['yyyy-MM-DD', ''],+ ]);+ });++ it('sets workbook number format locale through the facade API', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ expect(workbook.setNumfmtLocal('fr')).toBe(workbook);});});diff --git a/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.ts b/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.tsindex e1a44a6d20..935f129593 100644--- a/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.ts+++ b/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.ts@@ -16,9 +16,18 @@import type { ICellData, Injector, Nullable, Univer } from '@univerjs/core';import { ICommandService, IConfirmService, RANGE_TYPE, TestConfirmService } from '@univerjs/core';-import { ReorderRangeCommand, ReorderRangeMutation, SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';+import { ReorderRangeCommand, ReorderRangeMutation, SetRangeValuesMutation, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { SortRangeAscCommand, SortRangeDescCommand } from '../sheets-sort.command';+import {+ SortRangeAscCommand,+ SortRangeAscExtCommand,+ SortRangeAscExtInCtxMenuCommand,+ SortRangeAscInCtxMenuCommand,+ SortRangeDescCommand,+ SortRangeDescExtCommand,+ SortRangeDescExtInCtxMenuCommand,+ SortRangeDescInCtxMenuCommand,+} from '../sheets-sort.command';import { createCommandTestBed } from './create-command-test-bed';describe('Sheets sort commands integration', () => {@@ -45,8 +54,15 @@ describe('Sheets sort commands integration', () => {ReorderRangeCommand,ReorderRangeMutation,SetRangeValuesMutation,+ SetSelectionsOperation,SortRangeAscCommand,+ SortRangeAscExtCommand,+ SortRangeAscInCtxMenuCommand,+ SortRangeAscExtInCtxMenuCommand,SortRangeDescCommand,+ SortRangeDescExtCommand,+ SortRangeDescInCtxMenuCommand,+ SortRangeDescExtInCtxMenuCommand,].forEach((command) => commandService.registerCommand(command));getValues = (startRow, startColumn, endRow, endColumn) =>@@ -60,7 +76,7 @@ describe('Sheets sort commands integration', () => {univer.dispose();});- it('sorts the selected range ascending through executeCommand', async () => {+ function selectSortRange() {get(SheetsSelectionsService).addSelections([{range: {startRow: 0,@@ -81,42 +97,99 @@ describe('Sheets sort commands integration', () => {},style: null,}]);+ }- expect(await commandService.executeCommand(SortRangeAscCommand.id)).toBe(true);-+ function expectAscendingSortResult() {expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(1);expect(getValues(6, 9, 6, 9)?.[0]?.[0]?.v).toBe(7);expect(getValues(0, 11, 0, 11)?.[0]?.[0]?.f).toBe('=J1/K1');expect(getValues(6, 11, 6, 11)?.[0]?.[0]?.f).toBe('=SUM(J7:K8)');+ }++ function expectDescendingSortResult() {+ expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(7);+ expect(getValues(6, 9, 6, 9)?.[0]?.[0]?.v).toBe(1);+ expect(getValues(0, 11, 0, 11)?.[0]?.[0]?.f).toBe('=SUM(J1:K2)');+ expect(getValues(6, 11, 6, 11)?.[0]?.[0]?.f).toBe('=J7/K7');+ }++ function expectAscendingExtendedSortResult() {+ expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(1);+ expect(getValues(1, 9, 1, 9)?.[0]?.[0]?.v).toBe(1);+ expect(getValues(7, 9, 7, 9)?.[0]?.[0]?.v).toBe(7);+ expect(get(SheetsSelectionsService).getCurrentLastSelection()?.range).toMatchObject({+ startRow: 0,+ startColumn: 9,+ endRow: 7,+ endColumn: 11,+ });+ }++ function expectDescendingExtendedSortResult() {+ expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(7);+ expect(getValues(6, 9, 6, 9)?.[0]?.[0]?.v).toBe(1);+ expect(getValues(7, 9, 7, 9)?.[0]?.[0]?.v).toBe(1);+ expect(get(SheetsSelectionsService).getCurrentLastSelection()?.range).toMatchObject({+ startRow: 0,+ startColumn: 9,+ endRow: 7,+ endColumn: 11,+ });+ }++ it('sorts the selected range ascending through executeCommand', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeAscCommand.id)).toBe(true);+ expectAscendingSortResult();});it('sorts the selected range descending through executeCommand and rewrites formulas', async () => {- get(SheetsSelectionsService).addSelections([{- range: {- startRow: 0,- startColumn: 9,- endRow: 6,- endColumn: 11,- rangeType: RANGE_TYPE.NORMAL,- },- primary: {- actualRow: 0,- actualColumn: 9,- startRow: 0,- startColumn: 9,- endRow: 6,- endColumn: 11,- isMerged: false,- isMergedMainCell: false,- },- style: null,- }]);+ selectSortRange();expect(await commandService.executeCommand(SortRangeDescCommand.id)).toBe(true);+ expectDescendingSortResult();+ });- expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(7);- expect(getValues(6, 9, 6, 9)?.[0]?.[0]?.v).toBe(1);- expect(getValues(0, 11, 0, 11)?.[0]?.[0]?.f).toBe('=SUM(J1:K2)');- expect(getValues(6, 11, 6, 11)?.[0]?.[0]?.f).toBe('=J7/K7');+ it('sorts ascending from the extended range menu command', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeAscExtCommand.id)).toBe(true);+ expectAscendingExtendedSortResult();+ });++ it('sorts descending from the extended range menu command', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeDescExtCommand.id)).toBe(true);+ expectDescendingExtendedSortResult();+ });++ it('sorts ascending from the context menu command', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeAscInCtxMenuCommand.id)).toBe(true);+ expectAscendingSortResult();+ });++ it('sorts descending from the context menu command', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeDescInCtxMenuCommand.id)).toBe(true);+ expectDescendingSortResult();+ });++ it('sorts ascending from the extended context menu command', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeAscExtInCtxMenuCommand.id)).toBe(true);+ expectAscendingExtendedSortResult();+ });++ it('sorts descending from the extended context menu command', async () => {+ selectSortRange();++ expect(await commandService.executeCommand(SortRangeDescExtInCtxMenuCommand.id)).toBe(true);+ expectDescendingExtendedSortResult();});});diff --git a/packages/sheets-sort-ui/src/services/__tests__/sheets-sort-ui.service.spec.ts b/packages/sheets-sort-ui/src/services/__tests__/sheets-sort-ui.service.spec.tsnew file mode 100644index 0000000000..6331a6b82b--- /dev/null+++ b/packages/sheets-sort-ui/src/services/__tests__/sheets-sort-ui.service.spec.ts@@ -0,0 +1,280 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type {+ ICommand,+} from '@univerjs/core';+import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ Disposable,+ ICommandService,+ IConfigService,+ IConfirmService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ RANGE_TYPE,+ TestConfirmService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { FormulaDataModel, LexerTreeBuilder } from '@univerjs/engine-formula';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { SheetsSortService, SortType } from '@univerjs/sheets-sort';+import { Subject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import zhCN from '../../locale/zh-CN';+import { EXTEND_TYPE, SheetsSortUIService } from '../sheets-sort-ui.service';++class RecordingCommandService {+ readonly commands: Array<{ id: string; params?: unknown }> = [];++ executeCommand(id: string, params?: unknown): Promise<boolean> {+ this.commands.push({ id, params });+ return Promise.resolve(true);+ }++ registerCommand(_command: ICommand): Disposable {+ return new Disposable();+ }+}++class RecordingConfirmService {+ readonly confirmOptions$ = new Subject<unknown[]>();+ readonly confirmations: unknown[] = [];+ result = true;+ extendType = EXTEND_TYPE.KEEP;++ open(params: unknown): Disposable {+ this.confirmations.push(params);+ return new Disposable();+ }++ confirm(params: { children?: { title?: { props?: { onChange?: (value: string) => void } } } }): Promise<boolean> {+ this.confirmations.push(params);+ if (this.extendType === EXTEND_TYPE.EXTEND) {+ params.children?.title?.props?.onChange?.('1');+ }+ return Promise.resolve(this.result);+ }++ close(_id: string): void {}+}++class RecordingSheetsSortService {+ readonly appliedSorts: Array<{ option: unknown; unitId?: string; subUnitId?: string }> = [];+ failedCheck: 'single' | 'merge' | 'formula' | 'empty' | null = null;++ singleCheck(): boolean {+ return this.failedCheck !== 'single';+ }++ mergeCheck(): boolean {+ return this.failedCheck !== 'merge';+ }++ formulaCheck(): boolean {+ return this.failedCheck !== 'formula';+ }++ emptyCheck(): boolean {+ return this.failedCheck !== 'empty';+ }++ applySort(option: unknown, unitId?: string, subUnitId?: string): void {+ this.appliedSorts.push({ option, unitId, subUnitId });+ }+}++function createService(useRecordingServices = false) {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ICommandService, { useClass: (useRecordingServices ? RecordingCommandService : CommandService) as never }]);+ injector.add([IConfirmService, { useClass: (useRecordingServices ? RecordingConfirmService : TestConfirmService) as never }]);+ injector.add([LexerTreeBuilder]);+ injector.add([FormulaDataModel]);+ injector.add([SheetsSelectionsService]);+ if (useRecordingServices) {+ injector.add([SheetsSortService, { useClass: RecordingSheetsSortService as never }]);+ } else {+ injector.add([SheetsSortService]);+ }+ injector.add([LocaleService]);+ injector.add([SheetsSortUIService]);+ injector.get(LocaleService).load({ zhCN });+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ cellData: {+ 0: {+ 1: { v: '0:1' },+ 2: { v: '0:2' },+ 3: { v: '0:3' },+ },+ },+ },+ },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);+ univerInstanceService.focusUnit('unit-1');+ return {+ injector,+ service: injector.get(SheetsSortUIService),+ sortService: injector.get(SheetsSortService) as unknown as RecordingSheetsSortService,+ commandService: injector.get(ICommandService) as unknown as RecordingCommandService,+ confirmService: injector.get(IConfirmService) as unknown as RecordingConfirmService,+ selectionsService: injector.get(SheetsSelectionsService),+ };+}++describe('SheetsSortUIService', () => {+ it('tracks the custom sort panel location and derives column titles from the selected range', () => {+ const { service } = createService();+ const location = {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ colIndex: 1,+ range: { startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 },+ };++ service.showCustomSortPanel(location);+ expect(service.customSortState()).toEqual({ location, show: true });+ expect(service.getTitles(true)).toEqual([+ { index: 1, label: '0:1' },+ { index: 2, label: '0:2' },+ { index: 3, label: '0:3' },+ ]);++ service.closeCustomSortPanel();+ expect(service.customSortState()).toEqual({ show: false });+ });++ it('sorts the current selection directly with the requested direction', async () => {+ const { service, sortService, selectionsService } = createService(true);++ selectionsService.addSelections([{+ range: { startRow: 0, endRow: 2, startColumn: 1, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },+ primary: {+ actualRow: 0,+ actualColumn: 2,+ startRow: 0,+ endRow: 2,+ startColumn: 1,+ endColumn: 3,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ }]);++ expect(await service.triggerSortDirectly(false, false)).toBe(true);+ expect(sortService.appliedSorts).toEqual([{+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ option: {+ orderRules: [{ type: SortType.DESC, colIndex: 2 }],+ range: { startRow: 0, endRow: 2, startColumn: 1, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },+ },+ }]);+ });++ it('extends a partial selection before opening custom sort when the user chooses extend', async () => {+ const { service, sortService, commandService, confirmService, selectionsService } = createService(true);+ confirmService.extendType = EXTEND_TYPE.EXTEND;++ selectionsService.addSelections([{+ range: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },+ primary: {+ actualRow: 0,+ actualColumn: 1,+ startRow: 0,+ endRow: 0,+ startColumn: 1,+ endColumn: 1,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ }]);++ expect(await service.triggerSortCustomize()).toBe(true);+ expect(commandService.commands[0]).toMatchObject({+ id: 'sheet.operation.set-selections',+ params: {+ selections: [{+ range: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 3 },+ }],+ },+ });+ expect(service.customSortState()?.location?.range).toMatchObject({+ startRow: 0,+ endRow: 0,+ startColumn: 1,+ endColumn: 3,+ });+ expect(sortService.appliedSorts).toEqual([]);+ });++ it('cancels custom sort when the extend prompt is rejected', async () => {+ const { service, confirmService, selectionsService } = createService(true);+ confirmService.result = false;++ selectionsService.addSelections([{+ range: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },+ primary: {+ actualRow: 0,+ actualColumn: 1,+ startRow: 0,+ endRow: 0,+ startColumn: 1,+ endColumn: 1,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ }]);++ expect(await service.triggerSortCustomize()).toBe(false);+ expect(service.customSortState()).toBeNull();+ });++ it('blocks sorting and shows a check error when the selected range is invalid', async () => {+ const { service, sortService, confirmService } = createService(true);+ const location = {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ colIndex: 1,+ range: { startRow: 0, endRow: 0, startColumn: 1, endColumn: 3 },+ };+ sortService.failedCheck = 'single';++ expect(await service.triggerSortDirectly(true, false, location)).toBe(false);+ expect(sortService.appliedSorts).toEqual([]);+ expect(confirmService.confirmations).toMatchObject([{ id: 'sort-range-check-error' }]);+ });+});diff --git a/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsx b/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tssimilarity index 96%rename from packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsxrename to packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsindex b454b6e432..34f27df192 100644--- a/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.tsx+++ b/packages/sheets-sort-ui/src/services/sheets-sort-ui.service.ts@@ -31,7 +31,8 @@ import {import { expandToContinuousRange, getPrimaryForRange, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';import { SheetsSortService, SortType } from '@univerjs/sheets-sort';import { BehaviorSubject } from 'rxjs';-import { ExtendConfirm } from '../views/ExtendConfirm';+import { createExtendConfirm } from '../views/ExtendConfirm';+import { createSortCheckError } from '../views/SortCheckError';export enum EXTEND_TYPE {KEEP = 'keep',@@ -159,7 +160,7 @@ export class SheetsSortUIService extends Disposable {title: this._localeService.t('sheets-sort-ui.info.tooltip'),},children: {- title: <div>{this._localeService.t(content)}</div>,+ title: createSortCheckError(this._localeService.t(content)),},cancelText: this._localeService.t('sheets-sort-ui.dialog.cancel'),confirmText: this._localeService.t('sheets-sort-ui.dialog.confirm'),@@ -174,13 +175,9 @@ export class SheetsSortUIService extends Disposable {title: this._localeService.t('sheets-sort-ui.dialog.sort-reminder'),},children: {- title: (- <ExtendConfirm- onChange={(value: string) => {- shouldExtend = value === '1';- }}- />- ),+ title: createExtendConfirm((value: string) => {+ shouldExtend = value === '1';+ }),},width: 400,cancelText: this._localeService.t('sheets-sort-ui.dialog.cancel'),diff --git a/packages/sheets-sort-ui/src/views/ExtendConfirm.tsx b/packages/sheets-sort-ui/src/views/ExtendConfirm.tsxindex 6a3cd6b194..527cbcb0f5 100644--- a/packages/sheets-sort-ui/src/views/ExtendConfirm.tsx+++ b/packages/sheets-sort-ui/src/views/ExtendConfirm.tsx@@ -51,3 +51,7 @@ export const ExtendConfirm = (props: IExtendConfirmProps) => {</div>);};++export function createExtendConfirm(onChange: IExtendConfirmProps['onChange']) {+ return <ExtendConfirm onChange={onChange} />;+}diff --git a/packages/sheets-sort-ui/src/views/SortCheckError.tsx b/packages/sheets-sort-ui/src/views/SortCheckError.tsxnew file mode 100644index 0000000000..5be815d9b8--- /dev/null+++ b/packages/sheets-sort-ui/src/views/SortCheckError.tsx@@ -0,0 +1,27 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export interface ISortCheckErrorProps {+ message: string;+}++export const SortCheckError = (props: ISortCheckErrorProps) => {+ return <div>{props.message}</div>;+};++export function createSortCheckError(message: string) {+ return <SortCheckError message={message} />;+}diff --git a/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsx b/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsxnew file mode 100644index 0000000000..7954c8ba30--- /dev/null+++ b/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsx@@ -0,0 +1,269 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDisposable, IWorkbookData, Workbook, Worksheet } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import {+ awaitTime,+ ICommandService,+ IConfirmService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { FormulaDataModel, LexerTreeBuilder } from '@univerjs/engine-formula';+import {+ ReorderRangeCommand,+ ReorderRangeMutation,+ SetSelectionsOperation,+ SheetInterceptorService,+ SheetSkeletonService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import { SheetsSortController, SheetsSortService } from '@univerjs/sheets-sort';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import enUS from '../../locale/en-US';+import { SheetsSortUIService } from '../../services/sheets-sort-ui.service';+import { CustomSortPanel } from '../CustomSortPanel';+import EmbedSortBtn from '../EmbedSortBtn';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'test';+const SUB_UNIT_ID = 'sheet1';++class TestConfirmService implements IConfirmService {+ readonly confirmOptions$ = new Subject<unknown[]>();++ open(): IDisposable {+ return toDisposable(() => undefined);+ }++ confirm(): Promise<boolean> {+ return Promise.resolve(true);+ }++ close() {+ // The tested sort paths close panels through SheetsSortUIService.+ }+}++function createWorkbookData(): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'sort view test',+ sheetOrder: [SUB_UNIT_ID],+ styles: {},+ sheets: {+ [SUB_UNIT_ID]: {+ id: SUB_UNIT_ID,+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {+ 0: {+ 0: { v: 'Name' },+ 1: { v: 'Score' },+ 2: { v: 'Region' },+ },+ 1: {+ 0: { v: 'Cat' },+ 1: { v: 20, t: 2 },+ 2: { v: 'North' },+ },+ 2: {+ 0: { v: 'Amy' },+ 1: { v: 10, t: 2 },+ 2: { v: 'East' },+ },+ 3: {+ 0: { v: 'Ben' },+ 1: { v: 30, t: 2 },+ 2: { v: 'West' },+ },+ },+ },+ },+ };+}++function createSortViewTestBed() {+ const univer = new Univer();+ const injector = univer.__getInjector();++ class TestPlugin extends Plugin {+ static override pluginName = 'sheets-sort-ui-view-test-plugin';+ static override type = UniverInstanceType.UNIVER_SHEET;++ constructor(+ _config: undefined,+ @Inject(Injector) protected readonly _injector: Injector+ ) {+ super();+ }++ override onStarting(): void {+ ([+ [SheetsSelectionsService],+ [SheetInterceptorService],+ [SheetSkeletonService],+ [FormulaDataModel],+ [LexerTreeBuilder],+ [SheetsSortController],+ [SheetsSortService],+ [SheetsSortUIService],+ [IConfirmService, { useClass: TestConfirmService }],+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));+ }++ override onReady(): void {+ this._injector.get(SheetsSortController);+ }+ }++ injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);+ univer.registerPlugin(TestPlugin);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ [SetSelectionsOperation, ReorderRangeMutation, ReorderRangeCommand].forEach((command) => commandService.registerCommand(command));++ return {+ univer,+ injector,+ workbook,+ worksheet: workbook.getSheetBySheetId(SUB_UNIT_ID)!,+ sortUIService: injector.get(SheetsSortUIService),+ };+}++async function renderWithInjector(root: Root, testBed: ReturnType<typeof createSortViewTestBed>, node: React.ReactNode) {+ await act(async () => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ {node}+ </RediContext.Provider>+ );+ await awaitTime(20);+ });+}++function getColumnValues(worksheet: Worksheet, col: number, rows: number[]) {+ return rows.map((row) => worksheet.getCell(row, col)?.v);+}++function getButton(container: HTMLElement, text: string) {+ const button = Array.from(container.querySelectorAll('[data-u-comp="button"]'))+ .find((item) => item.textContent === text);+ expect(button).toBeTruthy();+ return button as HTMLElement;+}++describe('Sheets sort views', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createSortViewTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('sorts the selected data rows from the embedded descending action', async () => {+ currentTestBed = createSortViewTestBed();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ let closeCount = 0;++ await renderWithInjector(+ root,+ currentTestBed, (+ <EmbedSortBtn+ range={{ startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 }}+ colIndex={1}+ onClose={() => {+ closeCount += 1;+ }}+ />+ ));++ await act(async () => {+ getButton(container!, 'Descending').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await awaitTime(20);+ });++ expect(getColumnValues(currentTestBed.worksheet, 0, [0, 1, 2, 3])).toEqual(['Name', 'Ben', 'Cat', 'Amy']);+ expect(getColumnValues(currentTestBed.worksheet, 1, [0, 1, 2, 3])).toEqual(['Score', 30, 20, 10]);+ expect(closeCount).toBe(1);+ });++ it('applies custom sort with the first row excluded from sorting', async () => {+ currentTestBed = createSortViewTestBed();+ currentTestBed.sortUIService.showCustomSortPanel({+ unitId: UNIT_ID,+ subUnitId: SUB_UNIT_ID,+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },+ colIndex: 1,+ });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);++ await renderWithInjector(root, currentTestBed, <CustomSortPanel />);++ const titleCheckbox = container.querySelector('[data-u-comp="checkbox"] input') as HTMLInputElement;+ expect(titleCheckbox).toBeTruthy();++ await act(async () => {+ titleCheckbox.click();+ await awaitTime(20);+ });++ await act(async () => {+ getButton(container!, 'Confirm').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await awaitTime(20);+ });++ expect(getColumnValues(currentTestBed.worksheet, 0, [0, 1, 2, 3])).toEqual(['Name', 'Amy', 'Ben', 'Cat']);+ expect(getColumnValues(currentTestBed.worksheet, 1, [0, 1, 2, 3])).toEqual(['Score', 10, 30, 20]);+ expect(currentTestBed.sortUIService.customSortState()).toEqual({ show: false });+ });+});diff --git a/packages/sheets-sort/src/facade/__tests__/f-sort.spec.ts b/packages/sheets-sort/src/facade/__tests__/f-sort.spec.tsnew file mode 100644index 0000000000..e8ebc71660--- /dev/null+++ b/packages/sheets-sort/src/facade/__tests__/f-sort.spec.ts@@ -0,0 +1,94 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, Injector, Nullable, Univer, Workbook } from '@univerjs/core';+import { ICommandService, IUniverInstanceService } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';+import { ReorderRangeCommand, ReorderRangeMutation, SetSelectionsOperation } from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';+import '@univerjs/sheets/facade';+import '@univerjs/sheets-sort/facade';++describe('sheets-sort facade', () => {+ let univer: Univer;+ let get: Injector['get'];+ let univerAPI: FUniver;+ let getData: (row: number, col: number) => Nullable<ICellData>;++ beforeEach(() => {+ const testBed = createCommandTestBed(undefined, [+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ ]);+ univer = testBed.univer;+ get = testBed.get;++ const commandService = get(ICommandService);+ commandService.registerCommand(SetSelectionsOperation);+ commandService.registerCommand(ReorderRangeMutation);+ commandService.registerCommand(ReorderRangeCommand);++ const workbook = get(IUniverInstanceService).getUnit<Workbook>('test')!;+ const worksheet = workbook.getSheetBySheetId('sheet1')!;+ getData = (row: number, col: number) => worksheet.getCellMatrix().getValue(row, col) ?? undefined;+ univerAPI = FUniver.newAPI(univer.__getInjector());+ });++ afterEach(() => {+ univer.dispose();+ });++ it('sorts a selected range by a facade column spec relative to the range', () => {+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();++ worksheet.getRange('A1:C6').sort({ column: 1, ascending: true });++ expect(getData(0, 0)?.v).toBe(6);+ expect(getData(0, 1)?.v).toBe(15);+ expect(getData(5, 0)?.v).toBe(1);+ expect(getData(5, 1)?.v).toBe(20);+ });++ it('sorts the whole worksheet and emits before/after sort events with user-facing columns', () => {+ const events: Array<{ phase: string; column: number; ascending: boolean }> = [];+ const beforeDisposable = univerAPI.addEvent(univerAPI.Event.SheetBeforeRangeSort, (params) => {+ events.push({+ phase: 'before',+ column: params.sortColumn[0].column,+ ascending: params.sortColumn[0].ascending,+ });+ });+ const afterDisposable = univerAPI.addEvent(univerAPI.Event.SheetRangeSorted, (params) => {+ events.push({+ phase: 'after',+ column: params.sortColumn[0].column,+ ascending: params.sortColumn[0].ascending,+ });+ });++ univerAPI.getActiveWorkbook()!.getActiveSheet().sort(0, false);++ expect(getData(0, 0)?.v).toBe(6);+ expect(events).toEqual([+ { phase: 'before', column: 0, ascending: false },+ { phase: 'after', column: 0, ascending: false },+ ]);++ beforeDisposable.dispose();+ afterDisposable.dispose();+ });+});diff --git a/packages/sheets-sort/src/index.ts b/packages/sheets-sort/src/index.tsindex fc7451ca3d..0e6f8bc764 100644--- a/packages/sheets-sort/src/index.ts+++ b/packages/sheets-sort/src/index.ts@@ -16,6 +16,7 @@export { type ISortRangeCommandParams, SortRangeCommand } from './commands/commands/sheets-sort.command';export type { IUniverSheetsSortConfig } from './config/config';+export { SheetsSortController } from './controllers/sheets-sort.controller';export { UniverSheetsSortPlugin } from './plugin';export { type IOrderRule, type ISortOption, SortType } from './services/interface';export { SheetsSortService } from './services/sheets-sort.service';diff --git a/packages/sheets-sort/src/services/__tests__/sheets-sort.service.spec.ts b/packages/sheets-sort/src/services/__tests__/sheets-sort.service.spec.tsindex cc484aec7d..aa876ec756 100644--- a/packages/sheets-sort/src/services/__tests__/sheets-sort.service.spec.ts+++ b/packages/sheets-sort/src/services/__tests__/sheets-sort.service.spec.ts@@ -25,9 +25,19 @@ describe('SheetsSortService', () => {beforeEach(() => {const injector = new Injector();- injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);- injector.add([ICommandService, { useValue: { executeCommand: async () => true } as unknown as ICommandService }]);- injector.add([FormulaDataModel, { useValue: { getArrayFormulaRange: () => ({}) } as unknown as FormulaDataModel }]);+ class TestUniverInstanceService {}++ class TestCommandService {+ executeCommand = async () => true;+ }++ class TestFormulaDataModel {+ getArrayFormulaRange = () => ({});+ }++ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([FormulaDataModel, { useClass: TestFormulaDataModel as never }]);injector.add([SheetsSortService]);service = injector.get(SheetsSortService);});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.tsindex f627fda959..73a925af96 100644--- 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.ts@@ -14,59 +14,185 @@* limitations under the License.*/-import { TableManager } from '@univerjs/sheets-table';-import { describe, expect, it, vi } from 'vitest';+import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import {+ ICommandService,+ Inject,+ Injector,+ LocaleService,+ LocaleType,+ Plugin,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { SheetTableService, TableManager } from '@univerjs/sheets-table';+import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { IDialogService } from '@univerjs/ui';+import { afterEach, describe, expect, it } from 'vitest';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);+interface IAttachedPopup {+ row: number;+ column: number;+}++class TestSheetCanvasPopManagerService {+ readonly attachedPopups: IAttachedPopup[] = [];++ attachPopupToCell(row: number, column: number): IDisposable {+ this.attachedPopups.push({ row, column });+ return toDisposable(() => {+ this.attachedPopups.length = 0;+ });+ }+}++class TestDialogService {+ readonly closedIds: string[] = [];++ open(): IDisposable {+ return toDisposable(() => {});+ }++ close(id: string): void {+ this.closedIds.push(id);+ }++ closeAll(): void {+ this.closedIds.push('*');+ }++ getDialogs$() {+ throw new Error('Dialogs are not observed in this command test.');+ }+}++interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ workbook: Workbook;+}++function createWorkbookData(): IWorkbookData {return {- get(token: unknown) {- if (!map.has(token)) {- throw new Error(`Unknown token: ${String(token)}`);- }- return map.get(token);+ id: 'test',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'test',+ sheetOrder: ['sheet1'],+ sheets: {+ sheet1: {+ id: 'sheet1',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ },+ styles: {},+ };+}++function createTestBed(): ITestBed {+ 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: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [TableManager],+ [SheetTableService],+ [SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService }],+ [IDialogService, { useClass: TestDialogService }],+ [SheetsTableComponentController],+ ];+ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ injector.get(LocaleService).load({+ [LocaleType.EN_US]: {+ 'sheets-table': {+ columnPrefix: 'Column',+ },},- } as any;+ });++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(OpenTableFilterPanelOperation);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(SheetTableService).addTable(+ workbook.getUnitId(),+ 'sheet1',+ 'Orders',+ { startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 },+ ['Name', 'Quantity', 'Owner'],+ 'table-orders'+ );++ return {+ univer,+ get: injector.get.bind(injector),+ workbook,+ };}describe('OpenTableFilterPanelOperation', () => {- it('should return false for missing params or missing table', async () => {- const accessor = createAccessor([- [TableManager, { getTable: () => undefined }],- [SheetsTableComponentController, { openOrToggleFilterPanel: vi.fn() }],- ]);-- await expect(OpenTableFilterPanelOperation.handler(accessor, undefined as any)).resolves.toBe(false);- await expect(OpenTableFilterPanelOperation.handler(accessor, {- unitId: 'u1',- subUnitId: 's1',+ let testBed: ITestBed | undefined;++ afterEach(() => {+ testBed?.univer.dispose();+ testBed = undefined;+ });++ it('does not open a panel when params or table are missing', async () => {+ testBed = createTestBed();+ const commandService = testBed.get(ICommandService);++ await expect(commandService.executeCommand(OpenTableFilterPanelOperation.id)).resolves.toBe(false);+ await expect(commandService.executeCommand(OpenTableFilterPanelOperation.id, {+ unitId: testBed.workbook.getUnitId(),+ subUnitId: 'sheet1',tableId: 'missing',row: 1,- col: 1,+ col: 2,})).resolves.toBe(false);++ expect(testBed.get(SheetsTableComponentController).getCurrentTableFilterInfo()).toBeNull();});- it('should delegate panel toggle to component controller', async () => {- const openOrToggleFilterPanel = vi.fn();-- const accessor = createAccessor([- [TableManager, { getTable: () => ({ id: 't1' }) }],- [SheetsTableComponentController, {- openOrToggleFilterPanel,- }],- ]);-- const result = await OpenTableFilterPanelOperation.handler(accessor, {- unitId: 'u1',- subUnitId: 's1',- tableId: 't1',- row: 6,- col: 3,- });+ it('opens the filter panel for the requested table column', async () => {+ testBed = createTestBed();+ const commandService = testBed.get(ICommandService);- expect(result).toBe(true);- expect(openOrToggleFilterPanel).toHaveBeenCalledWith({ unitId: 'u1', subUnitId: 's1', row: 6, tableId: 't1', column: 3 });+ await expect(commandService.executeCommand(OpenTableFilterPanelOperation.id, {+ unitId: testBed.workbook.getUnitId(),+ subUnitId: 'sheet1',+ tableId: 'table-orders',+ row: 0,+ col: 2,+ })).resolves.toBe(true);++ expect(testBed.get(SheetsTableComponentController).getCurrentTableFilterInfo()).toEqual({+ unitId: testBed.workbook.getUnitId(),+ subUnitId: 'sheet1',+ tableId: 'table-orders',+ row: 0,+ column: 2,+ });+ expect((testBed.get(SheetCanvasPopManagerService) as unknown as TestSheetCanvasPopManagerService).attachedPopups).toEqual([{ row: 0, column: 2 }]);});});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.tsindex 42ff5c8e46..ae13f2fbe1 100644--- 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.ts@@ -14,179 +14,241 @@* 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 type { Dependency, IRange, IWorkbookData, Workbook } from '@univerjs/core';+import type { IDialogPartMethodOptions } from '@univerjs/ui';+import {+ ICommandService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';+import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';+import {+ AddSheetTableCommand,+ AddSheetTableMutation,+ DeleteSheetTableMutation,+ SheetTableService,+ TableManager,+} from '@univerjs/sheets-table';+import { DesktopDialogService, IDialogService, IUIPartsService, UIPartsService } from '@univerjs/ui';+import { afterEach, describe, expect, it } 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'),-}));+interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ workbook?: Workbook;+}-vi.mock('@univerjs/sheets', async () => {- const actual = await vi.importActual('@univerjs/sheets');+function createWorkbookData(): IWorkbookData {return {- ...actual,- getSheetCommandTarget: sheetsMocks.getSheetCommandTarget,- isSingleCellSelection: sheetsMocks.isSingleCellSelection,- expandToContinuousRange: sheetsMocks.expandToContinuousRange,- SheetsSelectionsService: sheetsMocks.SheetsSelectionsService,+ 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: 'product' },+ 1: { v: 'amount' },+ },+ 1: {+ 0: { v: 'book' },+ 1: { v: 12 },+ },+ 2: {+ 0: { v: 'pen' },+ 1: { v: 3 },+ },+ },+ },+ },+ styles: {},};-});+}-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);+function createTestBed(createWorkbook = true): ITestBed {+ 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: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [SheetsSelectionsService],+ [TableManager],+ [SheetTableService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IUIPartsService, { useClass: UIPartsService }],+ [IDialogService, { useClass: DesktopDialogService }],+ ];+ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);++ const localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.EN_US]: {+ 'sheets-table': {+ columnPrefix: 'Column',+ tablePrefix: 'Table',+ },+ 'sheets-table-ui': {+ selectRange: 'Select Table Range',+ },},- } as any;+ });+ localeService.setLocale(LocaleType.EN_US);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ [+ OpenTableSelectorOperation,+ AddSheetTableCommand,+ AddSheetTableMutation,+ DeleteSheetTableMutation,+ SetSelectionsOperation,+ ].forEach((command) => commandService.registerCommand(command));++ const workbook = createWorkbook+ ? univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData())+ : undefined;+ if (workbook) {+ injector.get(IUniverInstanceService).focusUnit(workbook.getUnitId());+ }++ return {+ univer,+ get: injector.get.bind(injector),+ workbook,+ };}-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();- });+function getOpenedDialog(dialogService: IDialogService): IDialogPartMethodOptions {+ return (dialogService as unknown as { _dialogOptions: IDialogPartMethodOptions[] })._dialogOptions.at(-1)!;+}- it('openRangeSelector should resolve null on cancel and close callbacks', async () => {- const close = vi.fn();- const dialogService = {- open: vi.fn((props: any) => {- props.children.label.props.onCancel();- props.onClose();- }),- 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 }, 't1');-- expect(result).toBeNull();- expect(close).toHaveBeenCalledTimes(2);+function getSelectorDialogProps(dialogService: IDialogService) {+ const label = getOpenedDialog(dialogService).children!.label;+ if (typeof label === 'string' || !label) {+ throw new Error('The table selector dialog should expose component props.');+ }+ return label.props as {+ range: IRange;+ onConfirm: (info: { unitId: string; subUnitId: string; range: IRange }) => void;+ onCancel: () => void;+ };+}++describe('OpenTableSelectorOperation', () => {+ let testBed: ITestBed | undefined;++ afterEach(() => {+ testBed?.univer.dispose();+ testBed = undefined;});- it('OpenTableSelectorOperation should return false without sheet target', async () => {- sheetsMocks.getSheetCommandTarget.mockReturnValue(null);+ it('resolves a confirmed table range from the selector dialog', async () => {+ testBed = createTestBed();+ const dialogService = testBed.get(IDialogService);- const accessor = createAccessor([- [IUniverInstanceService, {}],- [ICommandService, { executeCommand: vi.fn() }],- [SheetsSelectionsService, { getCurrentLastSelection: vi.fn() }],- [IDialogService, { open: vi.fn(), close: vi.fn() }],- [LocaleService, { t: () => 'Select range' }],- ]);+ const selection = openRangeSelector(+ testBed.get(Injector),+ 'test',+ 'sheet1',+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }+ );+ getSelectorDialogProps(dialogService).onConfirm({+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },+ });- await expect(OpenTableSelectorOperation.handler(accessor)).resolves.toBe(false);+ await expect(selection).resolves.toEqual({+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },+ });+ expect(getOpenedDialog(dialogService).open).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' },+ it('returns false when no workbook can receive a table', async () => {+ testBed = createTestBed(false);++ await expect(testBed.get(ICommandService).executeCommand(OpenTableSelectorOperation.id)).resolves.toBe(false);+ });++ it('adds a table from an expanded single-cell selection', async () => {+ testBed = createTestBed();+ const workbook = testBed.workbook!;+ const selectionService = testBed.get(SheetsSelectionsService);+ const commandService = testBed.get(ICommandService);+ const dialogService = testBed.get(IDialogService);++ selectionService.setSelections(workbook.getUnitId(), 'sheet1', [{+ range: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 },+ primary: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0, actualRow: 1, actualColumn: 0, isMerged: false, isMergedMainCell: false },+ }]);++ const result = commandService.executeCommand(OpenTableSelectorOperation.id);+ const selectorProps = getSelectorDialogProps(dialogService);+ expect(selectorProps.range).toEqual({ startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 });+ selectorProps.onConfirm({+ unitId: workbook.getUnitId(),+ subUnitId: 'sheet1',+ range: selectorProps.range,});- 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 },+ await expect(result).resolves.toBe(true);+ expect(testBed.get(TableManager).getTableList(workbook.getUnitId())[0]).toMatchObject({+ unitId: workbook.getUnitId(),+ subUnitId: 'sheet1',+ name: 'Table1',+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },});});- it('OpenTableSelectorOperation should keep multi-cell selections unchanged and stop when dialog is cancelled', async () => {- sheetsMocks.expandToContinuousRange.mockClear();- sheetsMocks.getSheetCommandTarget.mockReturnValue({- unitId: 'u1',- subUnitId: 's1',- worksheet: { id: 'sheet' },- });- sheetsMocks.isSingleCellSelection.mockReturnValue(false);-- const executeCommand = vi.fn();- const dialogService = {- open: vi.fn((props: any) => {- props.children.label.props.onCancel();- }),- close: vi.fn(),- };-- const accessor = createAccessor([- [IUniverInstanceService, {}],- [ICommandService, { executeCommand }],- [SheetsSelectionsService, {- getCurrentLastSelection: () => ({- range: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 5 },- }),- }],- [IDialogService, dialogService],- [LocaleService, { t: () => 'Select range' }],- ]);-- await expect(OpenTableSelectorOperation.handler(accessor)).resolves.toBe(false);- expect(sheetsMocks.expandToContinuousRange).not.toHaveBeenCalled();- expect(executeCommand).not.toHaveBeenCalled();+ it('keeps the workbook unchanged when the selector is cancelled', async () => {+ testBed = createTestBed();+ const workbook = testBed.workbook!;+ const selectionService = testBed.get(SheetsSelectionsService);+ const commandService = testBed.get(ICommandService);+ const dialogService = testBed.get(IDialogService);++ selectionService.setSelections(workbook.getUnitId(), 'sheet1', [{+ range: { startRow: 1, endRow: 2, startColumn: 0, endColumn: 1 },+ primary: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0, actualRow: 1, actualColumn: 0, isMerged: false, isMergedMainCell: false },+ }]);++ const result = commandService.executeCommand(OpenTableSelectorOperation.id);+ getSelectorDialogProps(dialogService).onCancel();++ await expect(result).resolves.toBe(false);+ expect(testBed.get(TableManager).getTableList(workbook.getUnitId())).toEqual([]);});});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.tsindex b1224fc5e2..05a0dbedfd 100644--- 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.ts@@ -14,147 +14,212 @@* limitations under the License.*/+import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';+import { ICommandService, Inject, Injector, LocaleService, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';import { SetRangeValuesMutation } from '@univerjs/sheets';-import { SetSheetTableFilterCommand, TABLE_FILTER_EMPTY_VALUE, TableColumnFilterTypeEnum } from '@univerjs/sheets-table';-import { describe, expect, it, vi } from 'vitest';+import {+ SetSheetTableFilterCommand,+ SetSheetTableFilterMutation,+ SheetTableService,+ TABLE_FILTER_EMPTY_VALUE,+ TableColumnFilterTypeEnum,+ TableManager,+} from '@univerjs/sheets-table';+import { afterEach, describe, expect, it } 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 tableFilters = {- doColumnFilter: vi.fn(),- };-- 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', TABLE_FILTER_EMPTY_VALUE] };+interface ITestBed {+ univer: Univer;+ get: Injector['get'];+ workbook: Workbook;+}++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: 'product' },+ 1: { v: 'amount' },+ },+ 1: {+ 0: { v: 'book' },+ 1: { v: 12 },+ },+ 2: {+ 0: { v: 'pen' },+ 1: { v: 3 },+ },+ 3: {+ 1: { v: 8 },+ },+ },},- getTableFilters: () => tableFilters,- };-- 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';- });+ },+ styles: {},+ };+}++function createTestBed(): ITestBed {+ 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: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [TableManager],+ [SheetTableService],+ [SheetsTableUiService],+ ];+ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);+ const localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.EN_US]: {+ 'sheets-table-ui': {+ condition: {+ empty: '(Empty)',+ },+ },+ },+ });+ localeService.setLocale(LocaleType.EN_US);++ const commandService = injector.get(ICommandService);+ [SetSheetTableFilterCommand, SetSheetTableFilterMutation, SetRangeValuesMutation].forEach((command) => {+ commandService.registerCommand(command);+ });++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(SheetTableService).addTable(+ workbook.getUnitId(),+ 'sheet1',+ 'Orders',+ { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 },+ ['Product', 'Amount'],+ 'table-orders',+ {+ filters: [+ { filterType: TableColumnFilterTypeEnum.manual, values: ['book', TABLE_FILTER_EMPTY_VALUE] },+ ],+ }+ );++ return {+ univer,+ get: injector.get.bind(injector),+ workbook,+ };+}++describe('SheetsTableUiService', () => {+ let testBed: ITestBed | undefined;++ afterEach(() => {+ testBed?.univer.dispose();+ testBed = undefined;+ });++ it('builds filter panel state from the selected table column', () => {+ testBed = createTestBed();+ const service = testBed.get(SheetsTableUiService);- 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-ui.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',+ expect(service.getTableFilterPanelInitProps(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 0)).toEqual({+ unitId: testBed.workbook.getUnitId(),+ subUnitId: 'sheet1',+ tableFilter: { filterType: TableColumnFilterTypeEnum.manual, values: ['book', TABLE_FILTER_EMPTY_VALUE] },+ currentFilterBy: FilterByEnum.Items,+ tableId: 'table-orders',columnIndex: 0,});+ });- expect(service.getTableFilterCheckedItems('u1', 't1', 1)).toEqual(['A', 'B', '(empty)']);-- const first = service.getTableFilterItems('u1', 's1', 't1', 1);- expect(first.allItemsCount).toBe(3);- expect(first.data.map((item) => item.title)).toEqual(['A', 'B', '(empty)']);- expect(first.itemsCountMap.get('A')).toBe(1);- expect(first.itemsCountMap.get('B')).toBe(1);- expect(first.itemsCountMap.get('(empty)')).toBe(1);- expect(tableFilters.doColumnFilter).toHaveBeenCalledWith(- worksheet,- { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },- 0,- expect.any(Set)- );- expect(tableFilters.doColumnFilter).not.toHaveBeenCalledWith(- worksheet,- { startRow: 1, endRow: 3, startColumn: 1, endColumn: 2 },- 1,- expect.any(Set)- );- 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' },- },- },- },- }));+ it('localizes checked manual filter values for blank cells', () => {+ testBed = createTestBed();+ const service = testBed.get(SheetsTableUiService);++ expect(service.getTableFilterCheckedItems(testBed.workbook.getUnitId(), 'table-orders', 0)).toEqual(['book', '(Empty)']);+ });- service.getTableFilterItems('u1', 's1', 't1', 1);- expect(getCellValueWithConditionType.mock.calls.length).toBeGreaterThan(countAfterFirstBuild);+ it('builds candidate values after applying filters from other table columns', () => {+ testBed = createTestBed();+ const service = testBed.get(SheetsTableUiService);- const countAfterRangeUpdate = getCellValueWithConditionType.mock.calls.length;- listeners.forEach((listener) => listener({- id: SetSheetTableFilterCommand.id,- params: {- unitId: 'u1',- tableId: 't1',+ const items = service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1);++ expect(items.allItemsCount).toBe(2);+ expect(items.data).toEqual([+ { title: 12, key: '1_1', leaf: true },+ { title: 8, key: '1_3', leaf: true },+ ]);+ expect(items.itemsCountMap.get(12 as unknown as string)).toBe(1);+ expect(items.itemsCountMap.get(8 as unknown as string)).toBe(1);+ });++ it('refreshes cached candidates when table data changes inside the filter range', async () => {+ testBed = createTestBed();+ const service = testBed.get(SheetsTableUiService);+ const commandService = testBed.get(ICommandService);++ expect(service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1).data).toEqual([+ { title: 12, key: '1_1', leaf: true },+ { title: 8, key: '1_3', leaf: true },+ ]);++ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: testBed.workbook.getUnitId(),+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 1: { v: 15 },+ },},- }));+ });++ expect(service.getTableFilterItems(testBed.workbook.getUnitId(), 'sheet1', 'table-orders', 1).data).toEqual([+ { title: 15, key: '1_1', leaf: true },+ { title: 8, key: '1_3', leaf: true },+ ]);+ });- service.getTableFilterItems('u1', 's1', 't1', 1);- expect(getCellValueWithConditionType.mock.calls.length).toBeGreaterThan(countAfterRangeUpdate);+ it('updates the table through the filter command', async () => {+ testBed = createTestBed();+ const service = testBed.get(SheetsTableUiService);- 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.setTableFilter(testBed.workbook.getUnitId(), 'table-orders', 0, {+ filterType: TableColumnFilterTypeEnum.manual,+ values: ['pen'],});+ await Promise.resolve();- service.dispose();+ const table = testBed.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;+ expect(table.getTableFilterColumn(0)).toEqual({+ filterType: TableColumnFilterTypeEnum.manual,+ values: ['pen'],+ });});});diff --git a/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-components.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-components.spec.tsxnew file mode 100644index 0000000000..fcadaf05d0--- /dev/null+++ b/packages/sheets-table-ui/src/views/components/__tests__/sheet-table-components.spec.tsx@@ -0,0 +1,370 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';+import type { Root } from 'react-dom/client';+import { ICommandService, Inject, Injector, LocaleService, LocaleType, Plugin, toDisposable, Univer, UniverInstanceType } from '@univerjs/core';+import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';+import { SheetInterceptorService } from '@univerjs/sheets';+import {+ SetSheetTableCommand,+ SetSheetTableFilterCommand,+ SetSheetTableFilterMutation,+ SetSheetTableMutation,+ SheetTableService,+ TABLE_FILTER_EMPTY_VALUE,+ TableColumnFilterTypeEnum,+ TableManager,+} from '@univerjs/sheets-table';+import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { IDialogService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { SheetsTableComponentController } from '../../../controllers/sheet-table-component.controller';+import { SheetsTableUiService } from '../../../services/sheets-table-ui.service';+import { SheetTableFilterPanel } from '../SheetTableFilterPanel';+import { SheetTableRenameDialog } from '../SheetTableRenameDialog';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class TestComponentController extends SheetsTableComponentController {+ closeCount = 0;++ override closeFilterPanel(): void {+ this.closeCount += 1;+ super.closeFilterPanel();+ }+}++class TestSheetCanvasPopManagerService {+ attachPopupToCell(): IDisposable {+ return toDisposable(() => {});+ }+}++class TestDialogService {+ open(): IDisposable {+ return toDisposable(() => {});+ }++ close(): void {+ // no-op+ }++ closeAll(): void {+ // no-op+ }++ getDialogs$() {+ throw new Error('Dialogs are not observed in this component test.');+ }+}++interface ITestBed {+ univer: Univer;+ injector: Injector;+ workbook: Workbook;+}++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: 'product' },+ 1: { v: 'amount' },+ },+ 1: {+ 0: { v: 'book' },+ 1: { v: 12 },+ },+ 2: {+ 0: { v: 'pen' },+ 1: { v: 3 },+ },+ 3: {+ 1: { v: 8 },+ },+ },+ },+ },+ styles: {},+ };+}++function createTestBed(): ITestBed {+ 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: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const dependencies: Dependency[] = [+ [TableManager],+ [SheetTableService],+ [SheetsTableUiService],+ [SheetInterceptorService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService }],+ [IDialogService, { useClass: TestDialogService }],+ [SheetsTableComponentController, { useClass: TestComponentController }],+ ];+ dependencies.forEach((dependency) => this._injector.add(dependency));+ }+ }++ univer.registerPlugin(TestPlugin);++ const localeService = injector.get(LocaleService);+ localeService.load({+ [LocaleType.EN_US]: {+ 'sheets-table': {+ tableNameError: 'Invalid table name',+ },+ 'sheets-table-ui': {+ cancel: 'Cancel',+ confirm: 'Confirm',+ renamePlaceholder: 'Enter table name',+ tableNameError: 'Invalid table name',+ condition: {+ empty: '(Empty)',+ string: 'Text',+ },+ string: {+ compare: {+ equal: 'Is equal to',+ },+ },+ filter: {+ 'by-values': 'Filter by values',+ 'by-conditions': 'Filter by conditions',+ cancel: 'Cancel',+ 'clear-filter': 'Clear filter',+ confirm: 'Confirm',+ 'search-placeholder': 'Search',+ 'select-all': 'Select all',+ },+ },+ },+ });+ localeService.setLocale(LocaleType.EN_US);++ const commandService = injector.get(ICommandService);+ [SetSheetTableCommand, SetSheetTableMutation, SetSheetTableFilterCommand, SetSheetTableFilterMutation].forEach((command) => {+ commandService.registerCommand(command);+ });++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ const sheetTableService = injector.get(SheetTableService);+ sheetTableService.addTable(+ workbook.getUnitId(),+ 'sheet1',+ 'Orders',+ { startRow: 0, endRow: 3, startColumn: 0, endColumn: 1 },+ ['Product', 'Amount'],+ 'table-orders'+ );+ sheetTableService.addTable(+ workbook.getUnitId(),+ 'sheet1',+ 'Archive',+ { startRow: 5, endRow: 7, startColumn: 0, endColumn: 1 },+ ['Product', 'Amount'],+ 'table-archive'+ );++ return {+ univer,+ injector,+ workbook,+ };+}++function renderWithRediContext(testBed: ITestBed, element: React.ReactElement) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function changeInput(input: HTMLInputElement, value: string): void {+ act(() => {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++function clickElement(element: Element): void {+ act(() => {+ element.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ element.dispatchEvent(new MouseEvent('pointerup', { bubbles: true }));+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });+}++function clickButtonByText(container: HTMLElement, text: string): void {+ const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent === text);+ if (!button) {+ throw new Error(`Button with text "${text}" was not found.`);+ }++ clickElement(button);+}++function clickCheckboxByText(container: HTMLElement, text: string): void {+ const label = Array.from(container.querySelectorAll('label')).find((item) => item.textContent?.includes(text));+ const input = label?.querySelector('input');+ if (!input) {+ throw new Error(`Checkbox with text "${text}" was not found.`);+ }++ act(() => {+ input.click();+ });+}++async function flushCommands(): Promise<void> {+ await act(async () => {+ await Promise.resolve();+ });+}++describe('sheet table view components', () => {+ let testBed: ITestBed | undefined;+ let root: Root | undefined;+ let container: HTMLElement | undefined;+ let closeDisposable: IDisposable | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ closeDisposable?.dispose();+ container?.remove();+ testBed?.univer.dispose();+ root = undefined;+ container = undefined;+ closeDisposable = undefined;+ testBed = undefined;+ });++ it('renames a table through the table command when the user confirms a new name', async () => {+ testBed = createTestBed();+ let closeCount = 0;+ const rendered = renderWithRediContext(+ testBed,+ <SheetTableRenameDialog+ unitId={testBed.workbook.getUnitId()}+ tableId="table-orders"+ onClose={() => {+ closeCount += 1;+ }}+ />+ );+ root = rendered.root;+ container = rendered.container;++ changeInput(container.querySelector('input')!, ' Revenue2026 ');+ clickButtonByText(container, 'Confirm');+ await flushCommands();++ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;+ expect(table.getDisplayName()).toBe('Revenue2026');+ expect(closeCount).toBe(1);+ });++ it('keeps an existing table name when the submitted name conflicts with another table', async () => {+ testBed = createTestBed();+ let closeCount = 0;+ const rendered = renderWithRediContext(+ testBed,+ <SheetTableRenameDialog+ unitId={testBed.workbook.getUnitId()}+ tableId="table-orders"+ onClose={() => {+ closeCount += 1;+ }}+ />+ );+ root = rendered.root;+ container = rendered.container;++ changeInput(container.querySelector('input')!, 'Archive');+ clickButtonByText(container, 'Confirm');+ await flushCommands();++ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;+ expect(table.getDisplayName()).toBe('Orders');+ expect(container.textContent).toContain('Invalid table name');+ expect(closeCount).toBe(0);+ });++ it('applies a value filter from item checkbox changes', async () => {+ testBed = createTestBed();+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;+ componentController.setCurrentTableFilterInfo({+ unitId: testBed.workbook.getUnitId(),+ subUnitId: 'sheet1',+ tableId: 'table-orders',+ row: 0,+ column: 0,+ });+ const rendered = renderWithRediContext(testBed, <SheetTableFilterPanel />);+ root = rendered.root;+ container = rendered.container;++ clickCheckboxByText(container, 'book');+ clickButtonByText(container, 'Confirm');+ await flushCommands();++ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;+ expect(table.getTableFilterColumn(0)).toEqual({+ filterType: TableColumnFilterTypeEnum.manual,+ values: ['pen', TABLE_FILTER_EMPTY_VALUE],+ });+ expect(componentController.closeCount).toBe(1);+ });+});diff --git a/packages/sheets-table/src/facade/__tests__/f-table.spec.ts b/packages/sheets-table/src/facade/__tests__/f-table.spec.tsnew file mode 100644index 0000000000..63f919b241--- /dev/null+++ b/packages/sheets-table/src/facade/__tests__/f-table.spec.ts@@ -0,0 +1,296 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, UnitModel } from '@univerjs/core';+import {+ ICommandService,+ ILogService,+ Inject,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ LogLevel,+ Plugin,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import {+ DefinedNamesService,+ FormulaDataModel,+ FunctionService,+ IDefinedNamesService,+ IFunctionService,+ ISuperTableService,+ LexerTreeBuilder,+ SuperTableService,+} from '@univerjs/engine-formula';+import {+ AddRangeThemeMutation,+ RefRangeService,+ RemoveRangeThemeMutation,+ SheetInterceptorService,+ SheetRangeThemeModel,+ SheetSkeletonService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import {+ AddSheetTableCommand,+ AddSheetTableMutation,+ AddTableThemeCommand,+ DeleteSheetTableCommand,+ DeleteSheetTableMutation,+ SetSheetTableCommand,+ SetSheetTableFilterCommand,+ SetSheetTableFilterMutation,+ SetSheetTableMutation,+ SheetTableService,+ TableColumnFilterTypeEnum,+ TableConditionTypeEnum,+ TableManager,+ TableNumberCompareTypeEnum,+} from '@univerjs/sheets-table';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import enUS from '../../locale/en-US';+import '@univerjs/sheets/facade';+import '@univerjs/sheets-table/facade';++function createWorkbookData(): IWorkbookData {+ return {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'sheet1',+ cellData: {},+ rowCount: 100,+ columnCount: 100,+ },+ },+ locale: LocaleType.EN_US,+ name: '',+ sheetOrder: ['sheet1'],+ styles: {},+ };+}++function createTableFacadeTestBed(dependencies: Dependency[]) {+ 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: Injector+ ) {+ super();+ }++ override onStarting(): void {+ const injector = this._injector;+ injector.add([SheetsSelectionsService]);+ injector.add([SheetInterceptorService]);+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([SheetSkeletonService]);+ injector.add([SheetRangeThemeModel]);+ injector.add([FormulaDataModel]);+ injector.add([LexerTreeBuilder]);+ injector.add([RefRangeService]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ dependencies.forEach((dependency) => injector.add(dependency));++ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS });+ localeService.setLocale(LocaleType.EN_US);++ this._injector.get(SheetInterceptorService);+ }+ }++ univer.registerPlugin(TestPlugin);+ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit(sheet.getUnitId());+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ return {+ univer,+ get: injector.get.bind(injector),+ univerAPI: FUniver.newAPI(injector),+ };+}++describe('sheets-table facade', () => {+ let testBed: ReturnType<typeof createTableFacadeTestBed>;++ beforeEach(() => {+ const dependencies: Dependency[] = [+ [TableManager],+ [SheetTableService],+ ];++ testBed = createTableFacadeTestBed(dependencies);++ const commandService = testBed.get(ICommandService);+ [+ AddSheetTableCommand,+ AddSheetTableMutation,+ AddTableThemeCommand,+ AddRangeThemeMutation,+ DeleteSheetTableCommand,+ DeleteSheetTableMutation,+ RemoveRangeThemeMutation,+ SetSheetTableCommand,+ SetSheetTableMutation,+ SetSheetTableFilterCommand,+ SetSheetTableFilterMutation,+ ].forEach((command) => commandService.registerCommand(command));+ });++ afterEach(() => {+ testBed.univer.dispose();+ });++ it('manages worksheet tables through workbook and worksheet facades', async () => {+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ const range = worksheet.getRange('A1:B3').getRange();+ const sheetTableService = testBed.get(SheetTableService);++ sheetTableService.addTable(+ workbook.getId(),+ worksheet.getSheetId(),+ 'Orders',+ range,+ ['Name', 'Quantity'],+ 'table-orders',+ { tableStyleId: 'table-default-1' }+ );+ expect(workbook.getTableInfo('table-orders')).toMatchObject({+ id: 'table-orders',+ name: 'Orders',+ subUnitId: worksheet.getSheetId(),+ range,+ unitId: workbook.getId(),+ });+ expect(workbook.getTableInfoByName('Orders')?.id).toBe('table-orders');+ expect(worksheet.getSubTableInfos().map((table) => table.id)).toEqual(['table-orders']);+ expect(worksheet.getTableByCell(1, 1)?.id).toBe('table-orders');++ await expect(worksheet.setTableName('table-orders', 'Orders2026')).resolves.toBe(true);+ expect(workbook.getTableInfoByName('Orders2026')?.id).toBe('table-orders');++ await expect(workbook.removeTable('table-orders')).resolves.toBe(true);+ expect(workbook.getTableList()).toEqual([]);+ await expect(workbook.removeTable('missing-table')).resolves.toBe(false);+ });++ it('sets and clears table filters and exposes table enums on the facade', async () => {+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ testBed.get(SheetTableService).addTable(+ workbook.getId(),+ worksheet.getSheetId(),+ 'Inventory',+ worksheet.getRange('A1:B3').getRange(),+ ['Name', 'Quantity'],+ 'table-inventory'+ );++ expect(testBed.univerAPI.Enum.TableColumnFilterTypeEnum.condition).toBe(TableColumnFilterTypeEnum.condition);+ await expect(workbook.setTableFilter('table-inventory', 1, {+ filterType: TableColumnFilterTypeEnum.condition,+ filterInfo: {+ conditionType: TableConditionTypeEnum.Number,+ compareType: TableNumberCompareTypeEnum.GreaterThan,+ expectedValue: 10,+ },+ })).resolves.toBe(true);+ await expect(worksheet.resetFilter('table-inventory', 1)).resolves.toBe(true);+ });++ it('adds and resizes tables through workbook and worksheet facades', async () => {+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ const invoiceRange = worksheet.getRange('A1:B3').getRange();++ await expect(workbook.addTable(worksheet.getSheetId(), 'Invoices', invoiceRange, 'table-invoices', {+ tableStyleId: 'table-default-2',+ })).resolves.toBe('table-invoices');+ expect(workbook.getTableInfo('table-invoices')).toMatchObject({+ id: 'table-invoices',+ name: 'Invoices',+ range: invoiceRange,+ });++ const resizedRange = worksheet.getRange('A1:B4').getRange();+ await expect(worksheet.setTableRange('table-invoices', resizedRange)).resolves.toBe(true);+ expect(workbook.getTableInfo('table-invoices')?.range).toEqual(resizedRange);+ expect(worksheet.setTableName('table-invoices', 'sheet1')).toBe(false);++ await expect(workbook.removeTable('table-invoices')).resolves.toBe(true);++ await expect(worksheet.addTable('Receipts', worksheet.getRange('E1:F3').getRange(), 'table-receipts')).resolves.toBe(true);+ expect(workbook.getTableInfoByName('Receipts')?.id).toBe('table-receipts');+ await expect(worksheet.removeTable('table-receipts')).resolves.toBe(true);+ });++ it('styles and removes tables through worksheet facade commands', async () => {+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet();+ const range = worksheet.getRange('C1:D4').getRange();+ const sheetTableService = testBed.get(SheetTableService);+ const tableManager = testBed.get(TableManager);++ sheetTableService.addTable(+ workbook.getId(),+ worksheet.getSheetId(),+ 'Shipments',+ range,+ ['Carrier', 'Count'],+ 'table-shipments',+ { tableStyleId: 'table-default-1' }+ );+ expect(workbook.getTableInfo('table-shipments')).toMatchObject({+ id: 'table-shipments',+ name: 'Shipments',+ range,+ });++ await expect(worksheet.addTableTheme('table-shipments', {+ name: 'table-custom',+ headerRowStyle: {+ bg: { rgb: '#111111' },+ cl: { rgb: '#ffffff' },+ },+ firstRowStyle: {+ bg: { rgb: '#ffffff' },+ },+ secondRowStyle: {+ bg: { rgb: '#eeeeee' },+ },+ })).resolves.toBe(true);+ expect(tableManager.getTableById(workbook.getId(), 'table-shipments')?.getTableStyleId()).toBe('table-custom');++ await expect(worksheet.removeTable('table-shipments')).resolves.toBe(true);+ expect(worksheet.getSubTableInfos()).toEqual([]);+ });+});diff --git a/packages/sheets-table/src/index.ts b/packages/sheets-table/src/index.tsindex 1c9eec6609..f71e0cb1b9 100644--- a/packages/sheets-table/src/index.ts+++ b/packages/sheets-table/src/index.ts@@ -23,7 +23,15 @@ export { RemoveTableThemeCommand } from './commands/commands/remove-table-theme.export { SetSheetTableCommand } from './commands/commands/set-sheet-table.command';export type { ISetSheetTableCommandParams } from './commands/commands/set-sheet-table.command';export { SetSheetTableFilterCommand } from './commands/commands/set-table-filter.command';-export { SheetTableInsertColCommand, SheetTableInsertColumnAtCommand, SheetTableInsertRowAtCommand, SheetTableInsertRowCommand, SheetTableRemoveColCommand, SheetTableRemoveColumnAtCommand, SheetTableRemoveRowCommand } from './commands/commands/sheet-table-row-col.command';+export {+ SheetTableInsertColCommand,+ SheetTableInsertColumnAtCommand,+ SheetTableInsertRowAtCommand,+ SheetTableInsertRowCommand,+ SheetTableRemoveColCommand,+ SheetTableRemoveColumnAtCommand,+ SheetTableRemoveRowCommand,+} from './commands/commands/sheet-table-row-col.command';export { AddSheetTableMutation } from './commands/mutations/add-sheet-table.mutation';export type { IAddSheetTableParams } from './commands/mutations/add-sheet-table.mutation';export { DeleteSheetTableMutation } from './commands/mutations/delete-sheet-table.mutation';@@ -34,13 +42,36 @@ export { SetSheetTableFilterMutation } from './commands/mutations/set-table-filtexport type { ISetSheetTableParams } from './commands/mutations/set-table-filter.mutation';export type { IUniverSheetsTableConfig } from './config/config';export { SHEET_TABLE_CUSTOM_THEME_PREFIX, TABLE_FILTER_EMPTY_VALUE } from './const';+export { SheetsTableThemeController } from './controllers/sheet-table-theme.controller';export { SheetsTableController } from './controllers/sheets-table.controller';export { customEmptyThemeWithBorderStyle, processStyleWithBorderStyle } from './controllers/table-theme.factory';export { TableManager } from './models/table-manager';export { UniverSheetsTablePlugin } from './plugin';export { SheetTableService } from './services/table.service';-export { SheetsTableButtonStateEnum, SheetsTableSortStateEnum, TableColumnDataTypeEnum, TableColumnFilterTypeEnum, TableConditionTypeEnum, TableDateCompareTypeEnum, TableNumberCompareTypeEnum, TableStringCompareTypeEnum } from './types/enum';-export type { ITableColumnJson, ITableConditionFilterItem, ITableData, ITableFilterItem, ITableInfo, ITableInfoWithUnitId, ITableManualFilterItem, ITableOptions, ITableRange, ITableRangeWithState, TableMetaType, TableRelationTupleType } from './types/type';+export {+ SheetsTableButtonStateEnum,+ SheetsTableSortStateEnum,+ TableColumnDataTypeEnum,+ TableColumnFilterTypeEnum,+ TableConditionTypeEnum,+ TableDateCompareTypeEnum,+ TableNumberCompareTypeEnum,+ TableStringCompareTypeEnum,+} from './types/enum';+export type {+ ITableColumnJson,+ ITableConditionFilterItem,+ ITableData,+ ITableFilterItem,+ ITableInfo,+ ITableInfoWithUnitId,+ ITableManualFilterItem,+ ITableOptions,+ ITableRange,+ ITableRangeWithState,+ TableMetaType,+ TableRelationTupleType,+} from './types/type';export type { ITableJson, ITableSetConfig } from './types/type';export { getExistingNamesSet, isConditionFilter, isManualTableFilter } from './util';export { validateSheetTableName } from './util/table-name';diff --git a/packages/sheets-table/src/services/__tests__/table.service.spec.ts b/packages/sheets-table/src/services/__tests__/table.service.spec.tsindex 54c15d367d..5b61117e62 100644--- a/packages/sheets-table/src/services/__tests__/table.service.spec.ts+++ b/packages/sheets-table/src/services/__tests__/table.service.spec.ts@@ -14,11 +14,28 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import * as conditionUtil from '../../models/filter-util/condition';+import { TableManager } from '../../models/table-manager';import { TableConditionTypeEnum } from '../../types/enum';import { SheetTableService } from '../table.service';+function createService(tableManager: Record<string, unknown>) {+ class TestTableManager {+ getTable = tableManager.getTable;+ getTableList = tableManager.getTableList;+ addTable = tableManager.addTable;+ deleteTable = tableManager.deleteTable;+ addFilter = tableManager.addFilter;+ }++ const injector = new Injector();+ injector.add([TableManager, { useClass: TestTableManager }]);+ injector.add([SheetTableService]);+ return injector.get(SheetTableService);+}+describe('SheetTableService', () => {it('should proxy table CRUD and metadata calls to table manager', () => {const setMeta = vi.fn();@@ -42,7 +59,7 @@ describe('SheetTableService', () => {addFilter: vi.fn(),};- const service = new SheetTableService(tableManager as any);+ const service = createService(tableManager);expect(service.getTableInfo('u1', 'table-1')).toEqual({unitId: 'u1',@@ -68,7 +85,7 @@ describe('SheetTableService', () => {});it('should return undefined when table does not exist', () => {- const service = new SheetTableService({ getTable: () => undefined } as any);+ const service = createService({ getTable: () => undefined });expect(service.getTableInfo('u1', 'missing')).toBeUndefined();expect(service.getTableMeta('u1', 'missing')).toBeUndefined();expect(service.getTableColumnMeta('u1', 'missing', 0)).toBeUndefined();@@ -76,7 +93,7 @@ describe('SheetTableService', () => {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 service = createService({});const worksheet = { id: 'sheet' } as any;const value = service.getCellValueWithConditionType(worksheet, 2, 3, TableConditionTypeEnum.Number);diff --git a/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.ts b/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.tsnew file mode 100644index 0000000000..e6e0aecdb8--- /dev/null+++ b/packages/sheets-thread-comment-ui/src/commands/operations/__tests__/comment.operation.spec.ts@@ -0,0 +1,196 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import type { IThreadComment } from '@univerjs/thread-comment';+import {+ ICommandService,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ LocaleType,+ toDisposable,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { SheetsSelectionsService } from '@univerjs/sheets';+import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';+import { CellPopupManagerService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import {+ AddCommentMutation,+ IThreadCommentDataSourceService,+ ThreadCommentDataSourceService,+ ThreadCommentModel,+} from '@univerjs/thread-comment';+import { ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SheetsThreadCommentPopupService } from '../../../services/sheets-thread-comment-popup.service';+import { SHEETS_THREAD_COMMENT_PANEL } from '../../../types/const';+import { ShowAddSheetCommentModalOperation, ToggleSheetCommentPanelOperation } from '../comment.operation';++const unitId = 'comment-workbook';+const subUnitId = 'sheet-1';++const workbookData: IWorkbookData = {+ id: unitId,+ appVersion: '3.0.0-alpha',+ name: 'comment workbook',+ locale: LocaleType.EN_US,+ sheetOrder: [subUnitId],+ styles: {},+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet 1',+ cellData: {},+ },+ },+};++class TestCellPopupManagerService {+ showPopup() {+ return toDisposable(() => {});+ }+}++class TestSheetCanvasPopManagerService {}++function createSelection(row: number, col: number): ISelectionWithStyle {+ return {+ range: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ },+ primary: {+ startRow: row,+ endRow: row,+ startColumn: col,+ endColumn: col,+ actualRow: row,+ actualColumn: col,+ isMerged: false,+ isMergedMainCell: false,+ },+ style: null,+ };+}++function createComment(id: string, ref: string): IThreadComment {+ return {+ id,+ threadId: id,+ ref,+ unitId,+ subUnitId,+ dT: '2026-06-17T00:00:00.000Z',+ personId: 'user-1',+ text: {+ dataStream: 'Review this cell.\r\n',+ },+ };+}++describe('sheet thread comment operations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let selectionsService: SheetsSelectionsService;+ let popupService: SheetsThreadCommentPopupService;+ let panelService: ThreadCommentPanelService;+ let sidebarService: ISidebarService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([SheetsSelectionsService]);+ injector.add([IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }]);+ injector.add([ThreadCommentModel]);+ injector.add([SheetsThreadCommentModel]);+ injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);+ injector.add([SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService as never }]);+ injector.add([SheetsThreadCommentPopupService]);+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ injector.add([ThreadCommentPanelService]);++ univer.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData);+ injector.get(IUniverInstanceService).focusUnit(unitId);+ injector.get(LifecycleService).stage = LifecycleStages.Rendered;++ commandService = injector.get(ICommandService);+ commandService.registerCommand(AddCommentMutation);+ commandService.registerCommand(ShowAddSheetCommentModalOperation);+ commandService.registerCommand(ToggleSheetCommentPanelOperation);+ selectionsService = injector.get(SheetsSelectionsService);+ popupService = injector.get(SheetsThreadCommentPopupService);+ panelService = injector.get(ThreadCommentPanelService);+ sidebarService = injector.get(ISidebarService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('opens the add-comment popup at the active cell and activates the existing thread', async () => {+ await commandService.executeCommand(AddCommentMutation.id, {+ unitId,+ subUnitId,+ comment: createComment('comment-1', 'D3'),+ });+ selectionsService.setSelections(unitId, subUnitId, [createSelection(2, 3)]);++ const result = await commandService.executeCommand(ShowAddSheetCommentModalOperation.id);++ expect(result).toBe(true);+ expect(popupService.activePopup).toMatchObject({+ unitId,+ subUnitId,+ row: 2,+ col: 3,+ });+ expect(panelService.activeCommentId).toEqual({+ unitId,+ subUnitId,+ commentId: 'comment-1',+ trigger: 'context-menu',+ });+ });++ it('does not open the add-comment popup without an active cell', async () => {+ const result = await commandService.executeCommand(ShowAddSheetCommentModalOperation.id);++ expect(result).toBe(false);+ expect(popupService.activePopup).toBeUndefined();+ expect(panelService.activeCommentId).toBeUndefined();+ });++ it('toggles the sheet comment panel through the sidebar', async () => {+ const openResult = await commandService.executeCommand(ToggleSheetCommentPanelOperation.id);++ expect(openResult).toBe(true);+ expect(panelService.panelVisible).toBe(true);+ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options.children?.label).toBe(SHEETS_THREAD_COMMENT_PANEL);++ const closeResult = await commandService.executeCommand(ToggleSheetCommentPanelOperation.id);++ expect(closeResult).toBe(true);+ expect(panelService.panelVisible).toBe(false);+ expect(sidebarService.visible).toBe(false);+ });+});diff --git a/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.ts b/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.tsindex b8dab3fc65..36aa3bca00 100644--- a/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.ts+++ b/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.ts@@ -14,32 +14,63 @@* limitations under the License.*/-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createThreadCommentUiTestBed } from '../../__tests__/create-thread-comment-ui-test-bed';+import type { IDisposable } from '@univerjs/core';+import { Inject, Injector } from '@univerjs/core';+import { CellPopupManagerService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { SHEETS_THREAD_COMMENT_MODAL } from '../../types/const';import { SheetsThreadCommentPopupService } from '../sheets-thread-comment-popup.service';+class TestSheetCanvasPopManagerService {}++class TestCellPopupManagerService extends CellPopupManagerService {+ disposed = false;+ lastLocation?: Parameters<CellPopupManagerService['showPopup']>[0];+ lastPopup?: Parameters<CellPopupManagerService['showPopup']>[1];++ constructor(+ @Inject(SheetCanvasPopManagerService) sheetCanvasPopManagerService: SheetCanvasPopManagerService+ ) {+ super(sheetCanvasPopManagerService);+ }++ override showPopup(+ location: Parameters<CellPopupManagerService['showPopup']>[0],+ popup: Parameters<CellPopupManagerService['showPopup']>[1]+ ): IDisposable {+ this.lastLocation = location;+ this.lastPopup = popup;++ return {+ dispose: () => {+ this.disposed = true;+ },+ };+ }+}+describe('SheetsThreadCommentPopupService', () => {- const onHide = vi.fn();- let testBed: ReturnType<typeof createThreadCommentUiTestBed>;+ let injector: Injector;+ let service: SheetsThreadCommentPopupService;+ let cellPopupManagerService: TestCellPopupManagerService;+ let hideCount: number;beforeEach(() => {- onHide.mockReset();- vi.stubGlobal('document', {- querySelectorAll: vi.fn(() => []),- getElementById: vi.fn(() => null),- });- testBed = createThreadCommentUiTestBed();+ hideCount = 0;+ injector = new Injector();+ injector.add([SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService }]);+ injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService }]);+ injector.add([SheetsThreadCommentPopupService]);++ service = injector.get(SheetsThreadCommentPopupService);+ cellPopupManagerService = injector.get(CellPopupManagerService) as unknown as TestCellPopupManagerService;});afterEach(() => {- vi.unstubAllGlobals();- testBed.univer.dispose();+ service.dispose();});it('shows, persists and hides the active popup through the popup manager boundary', () => {- const service = testBed.injector.createInstance(SheetsThreadCommentPopupService);-service.showPopup({unitId: 'test',subUnitId: 'sheet1',@@ -48,7 +79,9 @@ describe('SheetsThreadCommentPopupService', () => {commentId: 'comment-1',temp: true,trigger: 'hover',- }, onHide);+ }, () => {+ hideCount += 1;+ });expect(service.activePopup).toEqual({unitId: 'test',@@ -59,12 +92,13 @@ describe('SheetsThreadCommentPopupService', () => {temp: true,trigger: 'hover',});- expect(testBed.cellPopupManagerService.showPopup).toHaveBeenCalledWith({+ expect(cellPopupManagerService.lastLocation).toEqual({unitId: 'test',subUnitId: 'sheet1',row: 1,col: 2,- }, expect.objectContaining({+ });+ expect(cellPopupManagerService.lastPopup).toEqual(expect.objectContaining({componentKey: SHEETS_THREAD_COMMENT_MODAL,direction: 'horizontal',}));@@ -76,7 +110,35 @@ describe('SheetsThreadCommentPopupService', () => {service.hidePopup();expect(service.activePopup).toBeNull();- expect(testBed.popupDisposable.dispose).toHaveBeenCalled();- expect(onHide).toHaveBeenCalledTimes(1);+ expect(cellPopupManagerService.disposed).toBe(true);+ expect(hideCount).toBe(1);+ });++ it('updates the active popup in place when the same cell is targeted again', () => {+ service.showPopup({+ unitId: 'test',+ subUnitId: 'sheet1',+ row: 1,+ col: 2,+ commentId: 'comment-1',+ });+ service.showPopup({+ unitId: 'test',+ subUnitId: 'sheet1',+ row: 1,+ col: 2,+ commentId: 'comment-2',+ trigger: 'cell',+ });++ expect(service.activePopup).toEqual({+ unitId: 'test',+ subUnitId: 'sheet1',+ row: 1,+ col: 2,+ commentId: 'comment-2',+ trigger: 'cell',+ });+ expect(cellPopupManagerService.disposed).toBe(false);});});diff --git a/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsxnew file mode 100644index 0000000000..f4c92c75da--- /dev/null+++ b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx@@ -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 type { IDisposable, IDocumentBody, Injector, IWorkbookData, Workbook } from '@univerjs/core';+import type { ISelectionWithStyle } from '@univerjs/sheets';+import type { IThreadComment } from '@univerjs/thread-comment';+import type { ISidebarMethodOptions } from '@univerjs/ui';+import type { Root } from 'react-dom/client';+import {+ Disposable,+ ICommandService,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ LocaleType,+ toDisposable,+ Univer,+ UniverInstanceType,+ UserManagerService,+} from '@univerjs/core';+import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';+import { CellPopupManagerService, IMarkSelectionService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import {+ AddCommentMutation,+ IThreadCommentDataSourceService,+ ResolveCommentCommand,+ ResolveCommentMutation,+ ThreadCommentDataSourceService,+ ThreadCommentModel,+} from '@univerjs/thread-comment';+import { SetActiveCommentOperation, ThreadCommentPanelService } from '@univerjs/thread-comment-ui';+import threadCommentEnUS from '@univerjs/thread-comment-ui/locale/en-US';+import { ISidebarService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SheetsThreadCommentPopupService } from '../../services/sheets-thread-comment-popup.service';+import { SheetsThreadCommentPanel } from '../SheetsThreadCommentPanel';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const unitId = 'sheet-thread-comment-panel-test';+const sheet1 = 'sheet-1';+const sheet2 = 'sheet-2';++const workbookData: IWorkbookData = {+ id: unitId,+ appVersion: '3.0.0-alpha',+ name: 'Comment panel workbook',+ locale: LocaleType.EN_US,+ sheetOrder: [sheet1, sheet2],+ styles: {},+ sheets: {+ [sheet1]: {+ id: sheet1,+ name: 'Sheet 1',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ [sheet2]: {+ id: sheet2,+ name: 'Sheet 2',+ rowCount: 20,+ columnCount: 20,+ cellData: {},+ },+ },+};++interface IRecordedShape {+ id: string;+ selection: ISelectionWithStyle;+}++class TestState {+ static popupDisposeCount = 0;+ static shapeSeq = 0;+ static shapes: IRecordedShape[] = [];+ static removedShapeIds: string[] = [];++ static reset() {+ this.popupDisposeCount = 0;+ this.shapeSeq = 0;+ this.shapes = [];+ this.removedShapeIds = [];+ }+}++class TestSidebarService extends Disposable implements ISidebarService {+ readonly sidebarOptions$ = new Subject<ISidebarMethodOptions>();+ readonly scrollEvent$ = new Subject<Event>();+ private _options: ISidebarMethodOptions = {};+ private _container?: HTMLElement;++ open(params: ISidebarMethodOptions): IDisposable {+ this._options = { ...params, visible: true };+ this.sidebarOptions$.next(this._options);+ return toDisposable(() => this.close());+ }++ close(): void {+ this._options = { ...this._options, visible: false };+ this.sidebarOptions$.next(this._options);+ this._options.onClose?.();+ }++ get visible(): boolean {+ return this._options.visible ?? false;+ }++ get options(): ISidebarMethodOptions {+ return this._options;+ }++ get width(): number | undefined {+ return undefined;+ }++ setWidth(): void {}++ getContainer(): HTMLElement | undefined {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element;+ }++ override dispose(): void {+ super.dispose();+ this.sidebarOptions$.complete();+ this.scrollEvent$.complete();+ }+}++class TestMarkSelectionService implements IMarkSelectionService {+ addShape(selection: ISelectionWithStyle): string {+ const id = `shape-${++TestState.shapeSeq}`;+ TestState.shapes.push({ id, selection });+ return id;+ }++ addShapeWithNoFresh(selection: ISelectionWithStyle): string {+ return this.addShape(selection);+ }++ removeShape(id: string): void {+ TestState.removedShapeIds.push(id);+ TestState.shapes = TestState.shapes.filter((shape) => shape.id !== id);+ }++ removeAllShapes(): void {+ TestState.removedShapeIds.push(...TestState.shapes.map((shape) => shape.id));+ TestState.shapes = [];+ }++ refreshShapes(): void {}++ getShapeMap(): Map<string, never> {+ return new Map<string, never>();+ }+}++class TestCellPopupManagerService {+ showPopup(): IDisposable {+ return toDisposable(() => {+ TestState.popupDisposeCount += 1;+ });+ }+}++class TestSheetCanvasPopManagerService {}++function createTextBody(text: string): IDocumentBody {+ const dataStream = `${text}\r\n`;+ return {+ dataStream,+ textRuns: [],+ paragraphs: [+ {+ startIndex: dataStream.length - 2,+ paragraphId: `paragraph-${text}`,+ },+ ],+ sectionBreaks: [+ {+ startIndex: dataStream.length - 1,+ },+ ],+ };+}++function createComment(id: string, subUnitId: string, ref: string, text: string, resolved = false): IThreadComment {+ return {+ id,+ threadId: id,+ ref,+ unitId,+ subUnitId,+ dT: '2026-06-17T00:00:00.000Z',+ personId: 'user-1',+ resolved,+ text: createTextBody(text),+ };+}++function createTestBed() {+ const univer = new Univer({+ locale: LocaleType.EN_US,+ locales: {+ [LocaleType.EN_US]: threadCommentEnUS,+ },+ });+ const injector = univer.__getInjector();+ const get = injector.get.bind(injector) as Injector['get'];++ injector.add([IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }]);+ injector.add([ThreadCommentModel]);+ injector.add([SheetsThreadCommentModel]);+ injector.add([IMarkSelectionService, { useClass: TestMarkSelectionService }]);+ injector.add([CellPopupManagerService, { useClass: TestCellPopupManagerService as never }]);+ injector.add([SheetCanvasPopManagerService, { useClass: TestSheetCanvasPopManagerService as never }]);+ injector.add([SheetsThreadCommentPopupService]);+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);+ injector.add([ThreadCommentPanelService]);++ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData);+ get(IUniverInstanceService).focusUnit(unitId);+ get(LifecycleService).stage = LifecycleStages.Rendered;+ get(UserManagerService).setCurrentUser({ userID: 'user-1', name: 'Ada' });++ const commandService = get(ICommandService);+ commandService.registerCommand(AddCommentMutation);+ commandService.registerCommand(ResolveCommentMutation);+ commandService.registerCommand(ResolveCommentCommand);+ commandService.registerCommand(SetActiveCommentOperation);++ return {+ univer,+ injector,+ get,+ commandService,+ threadCommentModel: get(ThreadCommentModel),+ popupService: get(SheetsThreadCommentPopupService),+ };+}++function renderPanel(injector: Injector) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ <SheetsThreadCommentPanel />+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function orderOf(text: string, ...items: string[]) {+ return items.map((item) => {+ const index = text.indexOf(item);+ expect(index).toBeGreaterThanOrEqual(0);+ return index;+ });+}++function dispatchMouseEvent(element: Element, type: string) {+ act(() => {+ element.dispatchEvent(new MouseEvent(type, { bubbles: true }));+ });+}++describe('SheetsThreadCommentPanel', () => {+ let univer: Univer | undefined;+ let root: Root | undefined;+ let container: HTMLElement | undefined;+ let scrollIntoViewDescriptor: PropertyDescriptor | undefined;++ beforeEach(() => {+ TestState.reset();+ scrollIntoViewDescriptor = Object.getOwnPropertyDescriptor(Element.prototype, 'scrollIntoView');+ Object.defineProperty(Element.prototype, 'scrollIntoView', {+ configurable: true,+ value() {},+ });+ });++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ univer?.dispose();+ if (scrollIntoViewDescriptor) {+ Object.defineProperty(Element.prototype, 'scrollIntoView', scrollIntoViewDescriptor);+ } else {+ delete (Element.prototype as { scrollIntoView?: unknown }).scrollIntoView;+ }+ root = undefined;+ container = undefined;+ univer = undefined;+ });++ it('orders panel comments by unresolved status, sheet order, and cell reference', () => {+ const testBed = createTestBed();+ univer = testBed.univer;+ testBed.threadCommentModel.addComment(unitId, sheet2, createComment('sheet-2-a1', sheet2, 'A1', 'Sheet two A1'));+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('sheet-1-c3', sheet1, 'C3', 'Sheet one C3'));+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('sheet-1-a2', sheet1, 'A2', 'Sheet one A2'));+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('sheet-1-a1-done', sheet1, 'A1', 'Resolved sheet one A1', true));++ const rendered = renderPanel(testBed.injector);+ root = rendered.root;+ container = rendered.container;++ const [sheet1A2, sheet1C3, sheet2A1, resolvedSheet1A1] = orderOf(+ container.textContent ?? '',+ 'Sheet one A2',+ 'Sheet one C3',+ 'Sheet two A1',+ 'Resolved sheet one A1'+ );+ expect(sheet1A2).toBeLessThan(sheet1C3);+ expect(sheet1C3).toBeLessThan(sheet2A1);+ expect(sheet2A1).toBeLessThan(resolvedSheet1A1);+ });++ it('highlights only unresolved comments on the current sheet and closes the cell popup when resolved', () => {+ const testBed = createTestBed();+ univer = testBed.univer;+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('current-sheet-thread', sheet1, 'B2', 'Current sheet B2'));+ testBed.threadCommentModel.addComment(unitId, sheet2, createComment('other-sheet-thread', sheet2, 'A1', 'Other sheet A1'));+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('resolved-thread', sheet1, 'C3', 'Resolved sheet C3', true));+ testBed.popupService.showPopup({+ unitId,+ subUnitId: sheet1,+ row: 1,+ col: 1,+ commentId: 'current-sheet-thread',+ });++ const rendered = renderPanel(testBed.injector);+ root = rendered.root;+ container = rendered.container;++ const currentThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-current-sheet-thread`);+ const otherSheetThread = container.querySelector(`#PANEL-${unitId}-${sheet2}-other-sheet-thread`);+ const resolvedThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-resolved-thread`);+ expect(currentThread).toBeInstanceOf(HTMLElement);+ expect(otherSheetThread).toBeInstanceOf(HTMLElement);+ expect(resolvedThread).toBeInstanceOf(HTMLElement);++ dispatchMouseEvent(currentThread!, 'mouseover');+ expect(TestState.shapes).toEqual([+ expect.objectContaining({+ selection: expect.objectContaining({+ range: {+ startRow: 1,+ endRow: 1,+ startColumn: 1,+ endColumn: 1,+ },+ }),+ }),+ ]);++ dispatchMouseEvent(currentThread!, 'mouseout');+ expect(TestState.shapes).toHaveLength(0);+ expect(TestState.removedShapeIds).toEqual(['shape-1']);++ dispatchMouseEvent(otherSheetThread!, 'mouseover');+ dispatchMouseEvent(resolvedThread!, 'mouseover');+ expect(TestState.shapes).toHaveLength(0);++ const resolveButton = currentThread!.querySelector('.univer-flex-shrink-0 .univer-cursor-pointer');+ expect(resolveButton).toBeInstanceOf(HTMLElement);++ act(() => {+ resolveButton!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(testBed.popupService.activePopup).toBeNull();+ expect(TestState.popupDisposeCount).toBe(1);+ });+});diff --git a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.tsindex fbca962d0e..138487274b 100644--- a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts+++ b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts@@ -14,17 +14,56 @@* limitations under the License.*/-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, IPermissionService, IUniverInstanceService, LifecycleService, LifecycleStages } from '@univerjs/core';+import type { IAccessor, ICommand } from '@univerjs/core';+import type { ISheetPasteByShortKeyParams } from '@univerjs/sheets-ui';+import {+ CommandType,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ ICommandService,+ InterceptorEffectEnum,+ IPermissionService,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ RANGE_TYPE,+ UniverInstanceType,+} 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 { DragManagerService, EditorBridgeService, HoverManagerService, IEditorBridgeService, ISheetClipboardService, SheetPasteShortKeyCommand, SheetPermissionRenderManagerService } from '@univerjs/sheets-ui';-import { IClipboardInterfaceService } from '@univerjs/ui';+import { DefinedNamesService, FormulaDataModel, IDefinedNamesService } from '@univerjs/engine-formula';+import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';+import {+ INTERCEPTOR_POINT,+ IRefSelectionsService,+ RefSelectionsService,+ SetWorksheetRowHeightMutation,+ SheetInterceptorService,+ SheetsSelectionsService,+} from '@univerjs/sheets';+import {+ DragManagerService,+ EditorBridgeService,+ HoverManagerService,+ IEditorBridgeService,+ ISheetClipboardService,+ SetZoomRatioCommand,+ SHEET_VIEW_KEY,+ SheetPasteShortKeyCommand,+ SheetPermissionRenderManagerService,+ SheetScrollManagerService,+} from '@univerjs/sheets-ui';+import {+ BrowserClipboardService,+ HTML_CLIPBOARD_MIME_TYPE,+ IClipboardInterfaceService,+ PasteCommand,+ PLAIN_TEXT_CLIPBOARD_MIME_TYPE,+} from '@univerjs/ui';import { Subject } from 'rxjs';import { beforeEach, describe, expect, it, vi } from 'vitest';import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';import { createFacadeTestBed } from './create-test-bed';+import '../f-enum';import '../f-event';import '../f-univer';import '../f-workbook';@@ -80,6 +119,51 @@ type ITestUniverAPI = typeof createFacadeTestBed extends (...args: never[]) => i: never: never;+class PasteRecorderService {+ readonly params: ISheetPasteByShortKeyParams[] = [];++ record(params?: ISheetPasteByShortKeyParams): boolean {+ if (params) {+ this.params.push(params);+ }+ return true;+ }+}++const TestPasteCommand: ICommand<ISheetPasteByShortKeyParams> = {+ id: SheetPasteShortKeyCommand.id,+ type: CommandType.COMMAND,+ handler(accessor: IAccessor, params?: ISheetPasteByShortKeyParams) {+ return accessor.get(PasteRecorderService).record(params);+ },+};++class TestClipboardItem implements ClipboardItem {+ readonly presentationStyle: PresentationStyle = 'unspecified';+ readonly types = [PLAIN_TEXT_CLIPBOARD_MIME_TYPE, HTML_CLIPBOARD_MIME_TYPE];++ constructor(+ private readonly _text: string,+ private readonly _html: string+ ) { }++ async getType(type: string): Promise<Blob> {+ if (type === HTML_CLIPBOARD_MIME_TYPE) {+ return new Blob([this._html], { type });+ }++ return new Blob([this._text], { type: PLAIN_TEXT_CLIPBOARD_MIME_TYPE });+ }+}++const TestZoomCommand: ICommand<{ unitId: string; subUnitId: string; zoomRatio: number }> = {+ id: SetZoomRatioCommand.id,+ type: CommandType.COMMAND,+ handler() {+ return true;+ },+};+describe('Test FUniver UI mixin', () => {const clipboardService = {generateCopyContent: vi.fn(() => ({ html: '<b>a</b>', plain: 'a' })),@@ -99,6 +183,221 @@ describe('Test FUniver UI mixin', () => {vi.clearAllMocks();});+ it('pastes caller supplied clipboard payload through the sheet paste command', async () => {+ const testBed = createFacadeTestBed(undefined, [+ [PasteRecorderService],+ ]);+ testBed.get(ICommandService).registerCommand(TestPasteCommand);++ const image = new File(['image'], 'report.png', { type: 'image/png' });+ await expect(testBed.univerAPI.pasteIntoSheet('<strong>Q1</strong>', 'Q1', [image])).resolves.toBe(true);++ expect(testBed.get(PasteRecorderService).params).toEqual([{+ htmlContent: '<strong>Q1</strong>',+ textContent: 'Q1',+ files: [image],+ }]);++ testBed.univer.dispose();+ });++ it('reads browser clipboard data when paste events travel through the command pipeline', async () => {+ const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: {+ read: async () => [+ new TestClipboardItem('Q1\t100', '<table><tbody><tr><td>Q1</td><td>100</td></tr></tbody></table>'),+ ],+ readText: async () => 'Q1\t100',+ },+ });++ const testBed = createFacadeTestBed(undefined, [+ [IClipboardInterfaceService, { useClass: BrowserClipboardService }],+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);+ try {+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(PasteCommand);+ const pasteEvents: string[] = [];+ const disposables = [+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.BeforeClipboardPaste, ({ text, html }) => {+ pasteEvents.push(`before:${text}:${(html ?? '').includes('<td>100</td>')}`);+ }),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.ClipboardPasted, ({ text, html }) => {+ pasteEvents.push(`after:${text}:${(html ?? '').includes('<td>100</td>')}`);+ }),+ ];++ await expect(commandService.executeCommand(PasteCommand.id)).resolves.toBe(true);+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(pasteEvents).toEqual([+ 'before:Q1\t100:true',+ 'after:Q1\t100:true',+ ]);++ disposables.forEach((disposable) => disposable.dispose());+ } finally {+ testBed.univer.dispose();+ if (clipboardDescriptor) {+ Object.defineProperty(navigator, 'clipboard', clipboardDescriptor);+ } else {+ delete (navigator as unknown as { clipboard?: Clipboard }).clipboard;+ }+ }+ });++ it('publishes effected ranges when sheet row height changes the skeleton', async () => {+ const testBed = createFacadeTestBed(undefined, [+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [FormulaDataModel],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(SetWorksheetRowHeightMutation);+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet()!;+ const effectedRanges: string[] = [];+ const disposable = testBed.univerAPI.addEvent(+ testBed.univerAPI.Event.SheetSkeletonChanged,+ ({ effectedRanges: ranges }) => {+ for (const range of ranges) {+ const rawRange = range.getRange();+ effectedRanges.push(`${rawRange.startRow}:${rawRange.endRow}:${rawRange.rangeType}`);+ }+ }+ );++ await expect(commandService.executeCommand(SetWorksheetRowHeightMutation.id, {+ unitId: workbook.getId(),+ subUnitId: worksheet.getSheetId(),+ ranges: [{+ startRow: 2,+ endRow: 4,+ startColumn: 0,+ endColumn: worksheet.getMaxColumns() - 1,+ rangeType: RANGE_TYPE.ROW,+ }],+ rowHeight: 32,+ })).resolves.toBe(true);++ expect(worksheet.getRowHeight(2)).toBe(32);+ expect(worksheet.getRowHeight(4)).toBe(32);+ expect(effectedRanges).toEqual([`2:4:${RANGE_TYPE.ROW}`]);++ disposable.dispose();+ testBed.univer.dispose();+ });++ it('stores permission dialog and protected-range shadow state through real facade services', () => {+ const testBed = createFacadeTestBed(undefined, [+ [SheetPermissionRenderManagerService],+ ]);+ const permissionService = testBed.get(IPermissionService);+ const permissionRenderService = testBed.get(SheetPermissionRenderManagerService);+ const strategies: string[] = [];+ const subscription = testBed.univerAPI.getProtectedRangeShadowStrategy$().subscribe((strategy) => {+ strategies.push(strategy);+ });++ testBed.univerAPI.setPermissionDialogVisible(false);+ expect(permissionService.getShowComponents()).toBe(false);+ testBed.univerAPI.setPermissionDialogVisible(true);+ expect(permissionService.getShowComponents()).toBe(true);++ testBed.univerAPI.setProtectedRangeShadowStrategy('non-editable');+ testBed.univerAPI.setProtectedRangeShadowStrategy('none');++ expect(testBed.univerAPI.getProtectedRangeShadowStrategy()).toBe('none');+ expect(permissionRenderService.getProtectedRangeShadowStrategy()).toBe('none');+ expect(strategies).toEqual(['always', 'non-editable', 'none']);++ subscription.unsubscribe();+ testBed.univer.dispose();+ });++ it('emits sheet zoom lifecycle events from the zoom command pipeline', async () => {+ const testBed = createFacadeTestBed(undefined, [+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(TestZoomCommand);+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet()!;+ const zoomEvents: string[] = [];+ const disposables = [+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.BeforeSheetZoomChange, ({ zoom }) => {+ zoomEvents.push(`before:${zoom}`);+ }),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SheetZoomChanged, ({ zoom }) => {+ zoomEvents.push(`after:${zoom}`);+ }),+ ];++ await expect(commandService.executeCommand(SetZoomRatioCommand.id, {+ unitId: workbook.getId(),+ subUnitId: worksheet.getSheetId(),+ zoomRatio: 1.25,+ })).resolves.toBe(true);++ expect(zoomEvents).toEqual(['before:1.25', 'after:1.25']);++ disposables.forEach((disposable) => disposable.dispose());+ testBed.univer.dispose();+ });++ it('lets listeners prevent a sheet zoom change before it is applied', async () => {+ const testBed = createFacadeTestBed(undefined, [+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);+ const commandService = testBed.get(ICommandService);+ commandService.registerCommand(TestZoomCommand);+ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const worksheet = workbook.getActiveSheet()!;+ const zoomEvents: string[] = [];+ const disposables = [+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.BeforeSheetZoomChange, (event) => {+ zoomEvents.push(`before:${event.zoom}`);+ event.cancel = true;+ }),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SheetZoomChanged, ({ zoom }) => {+ zoomEvents.push(`after:${zoom}`);+ }),+ ];++ await expect(commandService.executeCommand(SetZoomRatioCommand.id, {+ unitId: workbook.getId(),+ subUnitId: worksheet.getSheetId(),+ zoomRatio: 0.75,+ })).resolves.toBe(false);++ expect(zoomEvents).toEqual(['before:0.75']);++ disposables.forEach((disposable) => disposable.dispose());+ testBed.univer.dispose();+ });+it('should handle common facade methods and clipboard internals', async () => {const testBed = createFacadeTestBed(undefined, [[ISheetClipboardService, { useValue: clipboardService }],@@ -160,6 +459,7 @@ describe('Test FUniver UI mixin', () => {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);+ expect(testBed.univerAPI.Enum.SHEET_VIEWPORT_KEY.VIEW_MAIN).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN);});it('should bridge sheet edit lifecycle events through workbook editing flows', async () => {@@ -225,25 +525,35 @@ describe('Test FUniver UI mixin', () => {it('should bridge render-layer hover and drag events', () => {const currentClickedCell$ = new Subject<ITestHoverCell>();+ const currentRichText$ = new Subject<ITestHoverCell['location']>();+ const currentPointerDownCell$ = new Subject<ITestHoverCell['location']>();+ const currentPointerUpCell$ = new Subject<ITestHoverCell['location']>();+ const currentCellPosWithEvent$ = new Subject<ITestHoverCell['location']>();+ const currentRowHeaderClick$ = new Subject<ITestHeaderEvent>();+ const currentRowHeaderPointerDown$ = new Subject<ITestHeaderEvent>();+ const currentRowHeaderPointerUp$ = new Subject<ITestHeaderEvent>();const currentHoveredRowHeader$ = new Subject<ITestHeaderEvent>();+ const currentColHeaderClick$ = new Subject<ITestHeaderEvent>();const currentColHeaderPointerDown$ = new Subject<ITestHeaderEvent>();+ const currentColHeaderPointerUp$ = new Subject<ITestHeaderEvent>();+ const currentHoveredColHeader$ = new Subject<ITestHeaderEvent>();const currentDragCell$ = new Subject<ITestDragCell>();const endDragCell$ = new Subject<ITestDragCell>();const hoverManagerService = {currentClickedCell$,- currentRichText$: new Subject<unknown>(),- currentPointerDownCell$: new Subject<unknown>(),- currentPointerUpCell$: new Subject<unknown>(),- currentCellPosWithEvent$: new Subject<unknown>(),- currentRowHeaderClick$: new Subject<unknown>(),- currentRowHeaderPointerDown$: new Subject<unknown>(),- currentRowHeaderPointerUp$: new Subject<unknown>(),+ currentRichText$,+ currentPointerDownCell$,+ currentPointerUpCell$,+ currentCellPosWithEvent$,+ currentRowHeaderClick$,+ currentRowHeaderPointerDown$,+ currentRowHeaderPointerUp$,currentHoveredRowHeader$,- currentColHeaderClick$: new Subject<unknown>(),+ currentColHeaderClick$,currentColHeaderPointerDown$,- currentColHeaderPointerUp$: new Subject<unknown>(),- currentHoveredColHeader$: new Subject<unknown>(),+ currentColHeaderPointerUp$,+ currentHoveredColHeader$,};const dragManagerService = {@@ -267,8 +577,18 @@ describe('Test FUniver UI mixin', () => {const logs: string[] = [];const disposables = [testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellClicked, ({ row, column }) => logs.push(`cell:${row},${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellHover, ({ row, column }) => logs.push(`cell-hover:${row},${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellPointerDown, ({ row, column }) => logs.push(`cell-down:${row},${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellPointerUp, ({ row, column }) => logs.push(`cell-up:${row},${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellPointerMove, ({ row, column }) => logs.push(`cell-move:${row},${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.RowHeaderClick, ({ row }) => logs.push(`row-click:${row}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.RowHeaderPointerDown, ({ row }) => logs.push(`row-down:${row}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.RowHeaderPointerUp, ({ row }) => logs.push(`row-up:${row}`)),testBed.univerAPI.addEvent(testBed.univerAPI.Event.RowHeaderHover, ({ row }) => logs.push(`row-hover:${row}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.ColumnHeaderClick, ({ column }) => logs.push(`col-click:${column}`)),testBed.univerAPI.addEvent(testBed.univerAPI.Event.ColumnHeaderPointerDown, ({ column }) => logs.push(`col-down:${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.ColumnHeaderPointerUp, ({ column }) => logs.push(`col-up:${column}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.ColumnHeaderHover, ({ column }) => logs.push(`col-hover:${column}`)),testBed.univerAPI.addEvent(testBed.univerAPI.Event.DragOver, ({ row, column }) => logs.push(`drag:${row},${column}`)),testBed.univerAPI.addEvent(testBed.univerAPI.Event.Drop, ({ row, column }) => logs.push(`drop:${row},${column}`)),];@@ -280,8 +600,18 @@ describe('Test FUniver UI mixin', () => {location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 1, col: 2 },position: { startX: 0, startY: 0, endX: 10, endY: 10 },});+ currentRichText$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 2, col: 3 });+ currentPointerDownCell$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 3, col: 4 });+ currentPointerUpCell$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 4, col: 5 });+ currentCellPosWithEvent$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 5, col: 6 });+ currentRowHeaderClick$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 3 });+ currentRowHeaderPointerDown$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 4 });+ currentRowHeaderPointerUp$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 6 });currentHoveredRowHeader$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 5 });+ currentColHeaderClick$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 4 });currentColHeaderPointerDown$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 6 });+ currentColHeaderPointerUp$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 7 });+ currentHoveredColHeader$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 8 });currentDragCell$.next({location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 3, col: 4 },position: { startX: 0, startY: 0, endX: 10, endY: 10 },@@ -295,12 +625,174 @@ describe('Test FUniver UI mixin', () => {expect(logs).toEqual(expect.arrayContaining(['cell:1,2',+ 'cell-hover:2,3',+ 'cell-down:3,4',+ 'cell-up:4,5',+ 'cell-move:5,6',+ 'row-click:3',+ 'row-down:4',+ 'row-up:6','row-hover:5',+ 'col-click:4','col-down:6',+ 'col-up:7',+ 'col-hover:8','drag:3,4','drop:7,8',]));disposables.forEach((disposable) => disposable.dispose());});++ it('should register sheet render extensions and cell custom renderers', () => {+ const testBed = createFacadeTestBed(undefined, [+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);++ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const rowDispose = vi.fn();+ const columnDispose = vi.fn();+ const mainDispose = vi.fn();+ const rowComponent = { register: vi.fn(() => ({ dispose: rowDispose })), makeDirty: vi.fn() };+ const columnComponent = { register: vi.fn(() => ({ dispose: columnDispose })), makeDirty: vi.fn() };+ const mainComponent = { register: vi.fn(() => ({ dispose: mainDispose })), makeDirty: vi.fn() };+ const renderManagerService = testBed.get(IRenderManagerService);+ vi.spyOn(renderManagerService, 'getRenderUnitById').mockReturnValue({+ components: new Map([+ [SHEET_VIEW_KEY.ROW, rowComponent],+ [SHEET_VIEW_KEY.COLUMN, columnComponent],+ [SHEET_VIEW_KEY.MAIN, mainComponent],+ ]),+ } as never);++ const rowExtensionDisposable = testBed.univerAPI.registerSheetRowHeaderExtension(workbook.getId(), {} as never);+ const columnExtensionDisposable = testBed.univerAPI.registerSheetColumnHeaderExtension(workbook.getId(), {} as never);+ const mainExtensionDisposable = testBed.univerAPI.registerSheetMainExtension(workbook.getId(), {} as never);++ expect(rowComponent.register).toHaveBeenCalledTimes(1);+ expect(columnComponent.register).toHaveBeenCalledTimes(1);+ expect(mainComponent.register).toHaveBeenCalledTimes(1);++ rowExtensionDisposable.dispose();+ columnExtensionDisposable.dispose();+ mainExtensionDisposable.dispose();++ expect(rowDispose).toHaveBeenCalledTimes(1);+ expect(columnDispose).toHaveBeenCalledTimes(1);+ expect(mainDispose).toHaveBeenCalledTimes(1);+ expect(rowComponent.makeDirty).toHaveBeenCalledWith(true);+ expect(columnComponent.makeDirty).toHaveBeenCalledWith(true);+ expect(mainComponent.makeDirty).toHaveBeenCalledWith(true);++ const customRender = [{ drawWith: vi.fn() }] as never;+ const customRenderDisposable = testBed.univerAPI.registerCellCustomRender(customRender);+ const cell = testBed.get(SheetInterceptorService).fetchThroughInterceptors(+ INTERCEPTOR_POINT.CELL_CONTENT,+ InterceptorEffectEnum.Style+ )({}, null as never);++ expect(cell?.customRender).toEqual(customRender);+ customRenderDisposable.dispose();+ });++ it('should bridge render-unit scroll and selection events', () => {+ const testBed = createFacadeTestBed(undefined, [+ [IEditorBridgeService, { useClass: EditorBridgeService }],+ [IEditorService, { useClass: EditorService }],+ [DocSelectionManagerService],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+ [IRefSelectionsService, { useClass: RefSelectionsService }],+ [SheetsSelectionsService],+ ]);++ const workbook = testBed.univerAPI.getActiveWorkbook()!;+ const scroll$ = new Subject<unknown>();+ const selectionMoveStart$ = new Subject<unknown[]>();+ const selectionMoving$ = new Subject<unknown[]>();+ const selectionMoveEnd$ = new Subject<unknown[]>();+ const selectionChanged$ = new Subject<unknown[]>();+ const render = {+ type: UniverInstanceType.UNIVER_SHEET,+ unitId: workbook.getId(),+ with: vi.fn((service: unknown) => {+ if (service === SheetScrollManagerService) {+ return { validViewportScrollInfo$: scroll$ };+ }++ if (service === SheetsSelectionsService) {+ return {+ selectionMoveStart$,+ selectionMoving$,+ selectionMoveEnd$,+ selectionChanged$,+ };+ }++ throw new Error(`Unexpected render service: ${String(service)}`);+ }),+ };+ const renderManagerService = testBed.get(IRenderManagerService) as IRenderManagerService & {+ _renderCreated$: Subject<typeof render>;+ };+ renderManagerService._renderCreated$.next(render);+ render.with.mockImplementation((service: unknown) => {+ if (service === SheetScrollManagerService) {+ return { validViewportScrollInfo$: scroll$ };+ }++ if (service === SheetsSelectionsService) {+ return {+ selectionMoveStart$,+ selectionMoving$,+ selectionMoveEnd$,+ selectionChanged$,+ };+ }++ throw new Error(`Unexpected render service: ${String(service)}`);+ });++ const logs: string[] = [];+ const disposables = [+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.Scroll, (event) => {+ const { offsetX, offsetY } = event as unknown as { offsetX: number; offsetY: number };+ logs.push(`scroll:${offsetX},${offsetY}`);+ }),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SelectionMoveStart, ({ selections }) => logs.push(`selection-start:${selections.length}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SelectionMoving, ({ selections }) => logs.push(`selection-moving:${selections.length}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SelectionMoveEnd, ({ selections }) => logs.push(`selection-end:${selections.length}`)),+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SelectionChanged, ({ selections }) => logs.push(`selection-changed:${selections.length}`)),+ ];++ testBed.get(LifecycleService).stage = LifecycleStages.Steady;++ const selection = [{+ range: {+ startRow: 0,+ endRow: 1,+ startColumn: 0,+ endColumn: 1,+ },+ }];+ scroll$.next({ offsetX: 12, offsetY: 24, sheetViewStartColumn: 3, sheetViewStartRow: 5 });+ selectionMoveStart$.next(selection);+ selectionMoving$.next(selection);+ selectionMoveEnd$.next(selection);+ selectionChanged$.next(selection);++ expect(logs).toEqual(expect.arrayContaining([+ 'scroll:12,24',+ 'selection-start:1',+ 'selection-moving:1',+ 'selection-end:1',+ 'selection-changed:1',+ ]));++ disposables.forEach((disposable) => disposable.dispose());+ });});diff --git a/packages/sheets-ui/src/facade/f-workbook.ts b/packages/sheets-ui/src/facade/f-workbook.tsindex a9abbc8583..b4729f0d25 100644--- a/packages/sheets-ui/src/facade/f-workbook.ts+++ b/packages/sheets-ui/src/facade/f-workbook.ts@@ -15,12 +15,25 @@*/import type { IDisposable, Nullable } from '@univerjs/core';-import type { IColumnsHeaderCfgParam, IRowsHeaderCfgParam, RenderComponentType, RenderManagerService, SpreadsheetColumnHeader, SpreadsheetRowHeader } from '@univerjs/engine-render';+import type {+ IColumnsHeaderCfgParam,+ IRowsHeaderCfgParam,+ RenderComponentType,+ RenderManagerService,+ SpreadsheetColumnHeader,+ SpreadsheetRowHeader,+} from '@univerjs/engine-render';import type { IEditorBridgeServiceVisibleParam, IScrollState, SheetSelectionRenderService } from '@univerjs/sheets-ui';import type { IDialogPartMethodOptions, ISidebarMethodOptions } from '@univerjs/ui';import { awaitTime, ICommandService, ILogService } from '@univerjs/core';import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';-import { IEditorBridgeService, ISheetSelectionRenderService, SetCellEditVisibleOperation, SHEET_VIEW_KEY, SheetScrollManagerService } from '@univerjs/sheets-ui';+import {+ IEditorBridgeService,+ ISheetSelectionRenderService,+ SetCellEditVisibleOperation,+ SHEET_VIEW_KEY,+ SheetScrollManagerService,+} from '@univerjs/sheets-ui';import { FWorkbook } from '@univerjs/sheets/facade';import { IDialogService, ISidebarService, KeyCode } from '@univerjs/ui';@@ -310,6 +323,7 @@ export class FWorkbookSheetsUIMixin extends FWorkbook implements IFWorkbookSheetreturn renderComponent;}+ /* istanbul ignore next -- deprecated API helper */private _logDeprecation(name: string): void {const logService = this._injector.get(ILogService);diff --git a/packages/sheets-ui/src/services/__tests__/header-unhide-range.service.spec.ts b/packages/sheets-ui/src/services/__tests__/header-unhide-range.service.spec.tsnew file mode 100644index 0000000000..5d5438c59d--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/header-unhide-range.service.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 { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { HeaderUnhideRangeAxis, HeaderUnhideRangeService } from '../header-unhide-range.service';++function createService(): HeaderUnhideRangeService {+ const injector = new Injector();+ injector.add([HeaderUnhideRangeService]);+ return injector.get(HeaderUnhideRangeService);+}++describe('HeaderUnhideRangeService', () => {+ it('lets registered visibility policies decide whether hidden row or column hints render', () => {+ const service = createService();+ const payload = {+ axis: HeaderUnhideRangeAxis.ROW,+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 0 },+ workbook: {} as never,+ worksheet: {} as never,+ };++ const blockRows = service.registerRangeVisibleHandler((visible, check) => (+ check.axis === HeaderUnhideRangeAxis.ROW ? false : visible+ ));+ const allowExplicitVisible = service.registerRangeVisibleHandler((visible) => visible);++ expect(service.shouldRenderRange(true, payload)).toBe(false);++ blockRows.dispose();+ expect(service.shouldRenderRange(true, payload)).toBe(true);++ allowExplicitVisible.dispose();+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.tsindex c3d5bf65b6..f58c802882 100644--- a/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts+++ b/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts@@ -15,12 +15,19 @@*/import type { IScrollState } from '../../views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar';-import { describe, expect, it, vi } from 'vitest';-import { SheetBarService } from '../sheet-bar/sheet-bar.service';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { ISheetBarService, SheetBarService } from '../sheet-bar/sheet-bar.service';++function createService(): ISheetBarService {+ const injector = new Injector();+ injector.add([ISheetBarService, { useClass: SheetBarService }]);+ return injector.get(ISheetBarService);+}describe('SheetBarService', () => {it('publishes sheet bar events and manages menu handler lifecycle', () => {- const service = new SheetBarService();+ const service = createService();const renames: string[] = [];const removes: string[] = [];@@ -46,17 +53,18 @@ describe('SheetBarService', () => {expect(scrollXs).toEqual([42]);expect(adds).toEqual([3]);- const handler = { handleSheetBarMenu: vi.fn() };+ let opened = 0;+ const handler = { handleSheetBarMenu: () => opened++ };const disposable = service.registerSheetBarMenuHandler(handler);service.triggerSheetBarMenu();- expect(handler.handleSheetBarMenu).toHaveBeenCalledTimes(1);+ expect(opened).toBe(1);- expect(() => service.registerSheetBarMenuHandler({ handleSheetBarMenu: vi.fn() })).toThrow(+ expect(() => service.registerSheetBarMenuHandler({ handleSheetBarMenu: () => {} })).toThrow('There is already a context menu handler!');disposable.dispose();service.triggerSheetBarMenu();- expect(handler.handleSheetBarMenu).toHaveBeenCalledTimes(1);+ expect(opened).toBe(1);});});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..60841abe4a--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/sheet-skeleton-manager.service.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 {+ ConfigService,+ ContextService,+ DesktopLogService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ UniverInstanceService,+ UniverInstanceType,+ Workbook,+} from '@univerjs/core';+import { SheetSkeletonService } from '@univerjs/sheets';+import { describe, expect, it } from 'vitest';+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';++describe('SheetSkeletonManagerService', () => {+ it('sets the current worksheet skeleton and marks it dirty for recalculation', () => {+ const injector = new Injector();+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([LocaleService]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([SheetSkeletonService]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: { 'sheet-1': { id: 'sheet-1' } },+ sheetOrder: ['sheet-1'],+ });+ injector.get(SheetSkeletonService);+ univerInstanceService.__addUnit(workbook);++ const service = injector.createInstance(SheetSkeletonManagerService, {+ unit: workbook,+ unitId: 'unit-1',+ type: UniverInstanceType.UNIVER_SHEET,+ scene: {+ onTransformChange$: {+ subscribeEvent: () => ({ dispose: () => {} }),+ },+ },+ } as never);++ service.setCurrent({ sheetId: 'sheet-1' });+ service.makeDirty({ sheetId: 'sheet-1' });++ expect(service.getCurrentParam()).toMatchObject({ unitId: 'unit-1', sheetId: 'sheet-1', dirty: true });+ expect(service.ensureSkeleton('sheet-1')).toBe(service.getCurrentSkeleton());+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/sheets-render.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheets-render.service.spec.tsnew file mode 100644index 0000000000..ed85540627--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/sheets-render.service.spec.ts@@ -0,0 +1,53 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ ContextService,+ DesktopLogService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ ThemeService,+ UniverInstanceService,+} from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { describe, expect, it } from 'vitest';+import { SheetsRenderService } from '../sheets-render.service';++function createService(): SheetsRenderService {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ThemeService]);+ injector.add([SheetsRenderService]);+ return injector.get(SheetsRenderService);+}++describe('SheetsRenderService', () => {+ it('tracks mutations that require rebuilding the sheet skeleton and unregisters them by disposable', () => {+ const service = createService();+ const disposable = service.registerSkeletonChangingMutations('sheet.mutation.resize-row');++ expect(service.checkMutationShouldTriggerRerender('sheet.mutation.resize-row')).toBe(true);+ expect(service.checkMutationShouldTriggerRerender('sheet.mutation.set-value')).toBe(false);++ disposable.dispose();+ expect(service.checkMutationShouldTriggerRerender('sheet.mutation.resize-row')).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.ts b/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.tsindex 883d33b44d..78917269b1 100644--- a/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.ts+++ b/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.ts@@ -14,13 +14,20 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL } from '@univerjs/engine-formula';import { describe, expect, it } from 'vitest';-import { StatusBarService } from '../status-bar.service';+import { IStatusBarService, StatusBarService } from '../status-bar.service';++function createService(): IStatusBarService {+ const injector = new Injector();+ injector.add([IStatusBarService, { useClass: StatusBarService }]);+ return injector.get(IStatusBarService);+}describe('StatusBarService', () => {it('filters status values based on count/counter rules', () => {- const service = new StatusBarService();+ const service = createService();// With only one non-empty cell: should emit pattern but filter out all calculated metrics.service.setState({diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.tsnew file mode 100644index 0000000000..98ac2893fd--- /dev/null+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-state.service.spec.ts@@ -0,0 +1,110 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ ErrorService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ LocaleService,+ LocalUndoRedoService,+ ThemeService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';+import {+ BrowserClipboardService,+ IClipboardInterfaceService,+ INotificationService,+ IPlatformService,+ PlatformService,+} from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { IMarkSelectionService, MarkSelectionService } from '../../mark-selection/mark-selection.service';+import { ISheetClipboardService, SheetClipboardService } from '../clipboard.service';++class NoopNotificationService {+ show() {+ return { dispose: () => {} };+ }+}++function createService(): ISheetClipboardService {+ vi.stubGlobal('navigator', { appVersion: 'Linux' });+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([SheetsSelectionsService]);+ injector.add([IClipboardInterfaceService, { useClass: BrowserClipboardService }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([SheetSkeletonService]);+ injector.add([IMarkSelectionService, { useClass: MarkSelectionService }]);+ injector.add([INotificationService, { useClass: NoopNotificationService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ThemeService]);+ injector.add([LocaleService]);+ injector.add([ErrorService]);+ injector.add([ISheetClipboardService, { useClass: SheetClipboardService }]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: { 'sheet-1': { id: 'sheet-1' } },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);+ univerInstanceService.focusUnit('unit-1');+ return injector.get(ISheetClipboardService);+}++describe('SheetClipboardService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('tracks paste menu state, paste options, and clipboard hooks used by copy/paste features', () => {+ const service = createService();+ const hook = { id: 'business-copy', priority: 1 };+ const cache = { pasteType: 'special-paste-value' };++ service.setShowMenu(true);+ service.updatePasteOptionsCache(cache as never);+ const disposable = service.addClipboardHook(hook as never);++ expect(service.getPasteMenuVisible()).toBe(true);+ expect(service.getPasteOptionsCache()).toBe(cache);+ expect(service.getClipboardHooks()).toEqual([hook]);++ disposable.dispose();+ service.disposePasteOptionsCache();+ expect(service.getClipboardHooks()).toEqual([]);+ expect(service.getPasteMenuVisible()).toBe(false);+ expect(service.getPasteOptionsCache()).toBeNull();+ });+});diff --git a/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.spec.ts b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.spec.tsnew file mode 100644index 0000000000..a0ae500945--- /dev/null+++ b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-resize.service.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 {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ LocalUndoRedoService,+ ThemeService,+ UniverInstanceService,+} from '@univerjs/core';+import { DocSelectionManagerService } from '@univerjs/docs';+import { EditorService, IEditorService } from '@univerjs/docs-ui';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { SheetInterceptorService, SheetSkeletonService } from '@univerjs/sheets';+import { DesktopLayoutService, ILayoutService } from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { EditorBridgeService, IEditorBridgeService } from '../../editor-bridge.service';+import { CellEditorManagerService, ICellEditorManagerService } from '../cell-editor-manager.service';+import { SheetCellEditorResizeService } from '../cell-editor-resize.service';++describe('SheetCellEditorResizeService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('does not resize anything when no cell editor is active', () => {+ vi.stubGlobal('window', new EventTarget());+ vi.stubGlobal('document', { activeElement: { dataset: {} } });+ const injector = new Injector();+ let callbackCalled = false;+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ injector.add([ThemeService]);+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);+ injector.add([DocSelectionManagerService]);+ injector.add([SheetInterceptorService]);+ injector.add([SheetSkeletonService]);+ injector.add([IEditorService, { useClass: EditorService }]);+ injector.add([ICellEditorManagerService, { useClass: CellEditorManagerService }]);+ injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([SheetCellEditorResizeService]);++ injector.get(SheetCellEditorResizeService).fitTextSize(() => {+ callbackCalled = true;+ });++ expect(callbackCalled).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.ts b/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.tsnew file mode 100644index 0000000000..2ef609bc1b--- /dev/null+++ b/packages/sheets-ui/src/services/format-painter/__tests__/format-painter.service.spec.ts@@ -0,0 +1,117 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { ISelectionFormatInfo } from '../format-painter.service';+import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUndoRedoService,+ IUniverInstanceService,+ LocalUndoRedoService,+ ObjectMatrix,+ ThemeService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';+import { describe, expect, it } from 'vitest';+import { IMarkSelectionService, MarkSelectionService } from '../../mark-selection/mark-selection.service';+import { FormatPainterService, FormatPainterStatus, IFormatPainterService } from '../format-painter.service';++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);+ injector.add([SheetsSelectionsService]);+ injector.add([ThemeService]);+ injector.add([SheetSkeletonService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([IMarkSelectionService, { useClass: MarkSelectionService }]);+ injector.add([IFormatPainterService, { useClass: FormatPainterService }]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: { 'sheet-1': { id: 'sheet-1' } },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);+ univerInstanceService.focusUnit('unit-1');+ injector.get(SheetsSelectionsService).setSelections('unit-1', 'sheet-1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ }] as never);+ const commandService = injector.get(ICommandService);+ commandService.registerCommand({+ id: 'sheet.mutation.apply-style',+ type: CommandType.MUTATION,+ handler: () => true,+ });+ commandService.registerCommand({+ id: 'sheet.mutation.revert-style',+ type: CommandType.MUTATION,+ handler: () => true,+ });+ const executed: unknown[] = [];+ commandService.onCommandExecuted((command) => executed.push({ id: command.id, params: command.params }));+ return {+ service: injector.get(IFormatPainterService),+ markSelectionService: injector.get(IMarkSelectionService),+ undoRedoService: injector.get(IUndoRedoService),+ executed,+ };+}++describe('FormatPainterService', () => {+ it('applies collected format mutations and records undo-redo for a format painter action', async () => {+ const { service, executed, undoRedoService, markSelectionService } = createService();+ const statusChanges: FormatPainterStatus[] = [];+ const format: ISelectionFormatInfo = { styles: new ObjectMatrix(), merges: [] };+ service.addHook({+ id: 'default',+ isDefaultHook: true,+ onStatusChange: (status) => statusChanges.push(status),+ onApply: () => ({+ redos: [{ id: 'sheet.mutation.apply-style', params: { color: 'red' } }],+ undos: [{ id: 'sheet.mutation.revert-style', params: { color: 'black' } }],+ }),+ });++ service.setSelectionFormat(format);+ service.setStatus(FormatPainterStatus.ONCE);+ const applied = service.applyFormatPainter('unit-1', 'sheet-1', { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 });++ expect(applied).toBe(true);+ expect(service.getSelectionFormat()).toBe(format);+ expect(statusChanges).toEqual([FormatPainterStatus.ONCE]);+ expect(markSelectionService.getShapeMap().size).toBe(1);+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(executed).toEqual([{ id: 'sheet.mutation.apply-style', params: { color: 'red' } }]);+ expect(undoRedoService.pitchTopUndoElement()).toMatchObject({ unitID: 'unit-1' });+ });+});diff --git a/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.spec.ts b/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.spec.tsnew file mode 100644index 0000000000..4aa6549473--- /dev/null+++ b/packages/sheets-ui/src/services/mark-selection/__tests__/mark-selection.service.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 {+ ContextService,+ DesktopLogService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ ThemeService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { SheetSkeletonService } from '@univerjs/sheets';+import { describe, expect, it } from 'vitest';+import { IMarkSelectionService, MarkSelectionService } from '../mark-selection.service';++function createService(): IMarkSelectionService {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([SheetSkeletonService]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ThemeService]);+ injector.add([IMarkSelectionService, { useClass: MarkSelectionService }]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ },+ },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);+ univerInstanceService.focusUnit('unit-1');+ return injector.get(IMarkSelectionService);+}++describe('MarkSelectionService', () => {+ it('stores temporary marked selections and removes them when the source action ends', () => {+ const service = createService();+ const selection = {+ range: { startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 },+ primary: null,+ };++ const id = service.addShapeWithNoFresh(selection as never, ['sheet.mutation.set-values']);+ expect(id).toBeTruthy();+ expect(service.getShapeMap().get(id!)).toMatchObject({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ selection,+ exits: ['sheet.mutation.set-values'],+ });++ service.removeShape(id!);+ expect(service.getShapeMap().size).toBe(0);+ });+});diff --git a/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.ts b/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.tsindex de8cb17c28..3be2e73809 100644--- a/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.ts+++ b/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.ts@@ -15,6 +15,7 @@*/import type { ICollaborator } from '@univerjs/protocol';+import { Injector } from '@univerjs/core';import { firstValueFrom, skip, take } from 'rxjs';import { describe, expect, it } from 'vitest';import { SheetPermissionUserManagerService } from '../sheet-permission-user-list.service';@@ -31,9 +32,15 @@ const EDITOR: ICollaborator = {subject: undefined,};+function createService(): SheetPermissionUserManagerService {+ const injector = new Injector();+ injector.add([SheetPermissionUserManagerService]);+ return injector.get(SheetPermissionUserManagerService);+}+describe('SheetPermissionUserManagerService', () => {it('tracks editable users, selected users and historical collaborators', async () => {- const service = new SheetPermissionUserManagerService();+ const service = createService();expect(service.userList).toEqual([]);expect(service.oldCollaboratorList).toEqual([]);@@ -56,7 +63,7 @@ describe('SheetPermissionUserManagerService', () => {});it('clears stored collaborator state on reset', async () => {- const service = new SheetPermissionUserManagerService();+ const service = createService();service.setCanEditUserList([OWNER]);service.setOldCollaboratorList([OWNER, EDITOR]);service.setSelectUserList([EDITOR]);diff --git a/packages/sheets-ui/src/services/select-all/__tests__/select-all.service.spec.ts b/packages/sheets-ui/src/services/select-all/__tests__/select-all.service.spec.tsnew file mode 100644index 0000000000..2226af557f--- /dev/null+++ b/packages/sheets-ui/src/services/select-all/__tests__/select-all.service.spec.ts@@ -0,0 +1,38 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { SelectAllService } from '../select-all.service';++function createService(): SelectAllService {+ const injector = new Injector();+ injector.add([SelectAllService]);+ return injector.get(SelectAllService);+}++describe('SelectAllService', () => {+ it('keeps the worksheet and range stack used by repeated select-all actions', () => {+ const service = createService();+ const sheetRange = { startRow: 0, endRow: 99, startColumn: 0, endColumn: 25 };++ service.selectedRangeWorksheet = 'sheet-1';+ service.rangesStack.push(sheetRange);++ expect(service.selectedRangeWorksheet).toBe('sheet-1');+ expect(service.rangesStack).toEqual([sheetRange]);+ });+});diff --git a/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.spec.tsnew file mode 100644index 0000000000..9d2d5c6097--- /dev/null+++ b/packages/sheets-ui/src/services/selection/__tests__/base-selection-render.service.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 type { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';+import {+ CommandService,+ ConfigService,+ ContextService,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ ThemeService,+} from '@univerjs/core';+import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { BaseSelectionRenderService } from '../base-selection-render.service';++class TestSelectionRenderService extends BaseSelectionRenderService {+ emitMoving() {+ this._selectionMoving$.next([]);+ }++ emitMoveEnd() {+ this._selectionMoveEnd$.next([]);+ }+}++describe('BaseSelectionRenderService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('tracks whether a sheet selection drag is moving', () => {+ vi.stubGlobal('window', new EventTarget());+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.add([ThemeService]);+ const service = injector.createInstance(+ TestSelectionRenderService,+ injector,+ injector.get(ThemeService),+ injector.get(IShortcutService),+ {} as SheetSkeletonManagerService,+ injector.get(IContextService)+ );++ service.emitMoving();+ expect(service.selectionMoving).toBe(true);++ service.emitMoveEnd();+ expect(service.selectionMoving).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.spec.tsnew file mode 100644index 0000000000..39d2c6e9a1--- /dev/null+++ b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service-behavior.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 } from 'vitest';+import { shouldKeepCurrentSelectionOnMobileLongPress } from '../mobile-selection-render.service';++describe('MobileSheetsSelectionRenderService', () => {+ it('keeps the current mobile selection when a long press stays inside an existing range', () => {+ expect(shouldKeepCurrentSelectionOnMobileLongPress(+ [{ startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 }],+ { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }+ )).toBe(true);++ expect(shouldKeepCurrentSelectionOnMobileLongPress(+ [{ startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 }],+ { startRow: 4, endRow: 4, startColumn: 2, endColumn: 2 }+ )).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsx b/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsxnew file mode 100644index 0000000000..2fc3b2954c--- /dev/null+++ b/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsx@@ -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 { IWorkbookData, Workbook } from '@univerjs/core';+import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';+import type { ReactElement } from 'react';+import type { Root } from 'react-dom/client';+import {+ IUniverInstanceService,+ LocaleService,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import {+ DefinedNamesService,+ FunctionService,+ IDefinedNamesService,+ IFunctionService,+ ISuperTableService,+ LexerTreeBuilder,+ SuperTableService,+} from '@univerjs/engine-formula';+import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from '@univerjs/sheets';+import sheetsEnUS from '@univerjs/sheets/locale/en-US';+import { ComponentManager, ISidebarService, RediContext } from '@univerjs/ui';+import { act, forwardRef, useImperativeHandle } from 'react';+import { createRoot } from 'react-dom/client';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '../../../common/keys';+import sheetsUiEnUS from '../../../locale/en-US';+import { DefinedNameInput } from '../DefinedNameInput';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'defined-name-input-unit';++class TestSidebarService {+ readonly sidebarOptions$ = new Subject();+ readonly scrollEvent$ = new Subject<Event>();+ private _container: HTMLElement = document.createElement('div');++ open() {+ return { dispose(): void {} };+ }++ close(): void {}++ get visible(): boolean {+ return false;+ }++ get options(): never {+ return undefined as never;+ }++ getContainer(): HTMLElement | undefined {+ return this._container;+ }++ setContainer(element?: HTMLElement): void {+ this._container = element ?? document.createElement('div');+ }++ get width(): number | undefined {+ return undefined;+ }++ setWidth(): void {}+}++function TestRangeSelector(props: { initialValue?: string; onChange?: (ranges: unknown[], text: string) => void }) {+ return (+ <input+ aria-label="defined-name-range"+ value={props.initialValue ?? ''}+ onChange={(event) => props.onChange?.([], event.target.value)}+ />+ );+}++const TestFormulaEditor = forwardRef((props: { initValue?: string; onChange?: (value: string) => void; onVerify?: (valid: boolean) => void }, ref) => {+ useImperativeHandle(ref, () => ({+ isClickOutSide: () => false,+ }));++ return (+ <input+ aria-label="defined-name-formula"+ value={props.initValue ?? ''}+ onChange={(event) => {+ props.onChange?.(event.target.value);+ props.onVerify?.(true);+ }}+ />+ );+});++TestFormulaEditor.displayName = 'TestFormulaEditor';++function createWorkbookData(): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'Defined Name Input',+ sheetOrder: ['sheet1', 'sheet2'],+ styles: {},+ sheets: {+ sheet1: {+ id: 'sheet1',+ name: 'Sheet1',+ cellData: {},+ },+ sheet2: {+ id: 'sheet2',+ name: 'Sheet2',+ cellData: {},+ },+ },+ };+}++function createDefinedNameInputTestBed() {+ const univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);+ injector.add([ComponentManager, { useClass: ComponentManager }]);+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ const localeService = injector.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: { ...sheetsEnUS, ...sheetsUiEnUS } });+ localeService.setLocale(LocaleType.EN_US);+ const componentManager = injector.get(ComponentManager);+ componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, TestRangeSelector);+ componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, TestFormulaEditor);++ return {+ univer,+ injector,+ workbook,+ };+}++function renderWithDependencies(element: ReactElement, injector: ReturnType<typeof createDefinedNameInputTestBed>['injector']) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return {+ container,+ root,+ };+}++function setInputText(input: HTMLInputElement, value: string) {+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ valueSetter?.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+}++function queryByText(container: HTMLElement, text: string): HTMLElement | null {+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);+ let node = walker.nextNode();+ while (node) {+ if (node.textContent === text) {+ return node.parentElement;+ }+ node = walker.nextNode();+ }++ return null;+}++function getByText(container: HTMLElement, text: string): HTMLElement {+ const element = queryByText(container, text);+ if (!element) {+ throw new Error(`Text not found: ${text}`);+ }++ return element;+}++function getInput(container: HTMLElement, selector: string): HTMLInputElement {+ const input = container.querySelector(selector);+ if (!(input instanceof HTMLInputElement)) {+ throw new TypeError(`Input not found: ${selector}`);+ }++ return input;+}++describe('DefinedNameInput', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentBed: ReturnType<typeof createDefinedNameInputTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentBed = undefined;+ });++ it('confirms edited name data with an absolute range and the selected scope', async () => {+ currentBed = createDefinedNameInputTestBed();+ let confirmed: IDefinedNamesServiceParam | undefined;+ const rendered = renderWithDependencies(+ <DefinedNameInput+ inputId="defined-name-input"+ state+ name=""+ formulaOrRefString="A1:B2"+ comment=""+ localSheetId="sheet2"+ confirm={(param) => {+ confirmed = param;+ }}+ />,+ currentBed.injector+ );+ root = rendered.root;+ container = rendered.container;+ const currentContainer = rendered.container;++ await act(async () => {+ setInputText(getInput(currentContainer, 'input[placeholder="Please enter a name(No space allowed)"]'), 'RevenueRange');+ setInputText(getInput(currentContainer, 'input[aria-label="defined-name-range"]'), 'C3:D4');+ setInputText(getInput(currentContainer, 'input[placeholder="Please enter a comment"]'), 'quarterly revenue');+ getByText(currentContainer, 'Confirm').click();+ await Promise.resolve();+ });++ expect(confirmed).toEqual({+ id: '',+ name: 'RevenueRange',+ formulaOrRefString: 'Sheet1!$C$3:$D$4',+ comment: 'quarterly revenue',+ localSheetId: 'sheet2',+ });+ });++ it('keeps invalid names from confirming and reports the validation reason', async () => {+ currentBed = createDefinedNameInputTestBed();+ let confirmed: IDefinedNamesServiceParam | undefined;+ const rendered = renderWithDependencies(+ <DefinedNameInput+ inputId="defined-name-input"+ state+ name="A1"+ formulaOrRefString="B2:C3"+ comment=""+ localSheetId={SCOPE_WORKBOOK_VALUE_DEFINED_NAME}+ confirm={(param) => {+ confirmed = param;+ }}+ />,+ currentBed.injector+ );+ root = rendered.root;+ container = rendered.container;+ const currentContainer = rendered.container;++ await act(async () => {+ getByText(currentContainer, 'Confirm').click();+ await Promise.resolve();+ });++ expect(confirmed).toBeUndefined();+ expect(getByText(currentContainer, 'The name is invalid')).toBeTruthy();+ });+});diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsxnew file mode 100644index 0000000000..f514a69cf3--- /dev/null+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx@@ -0,0 +1,359 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, Nullable, Workbook } from '@univerjs/core';+import type { ReactElement } from 'react';+import type { Root } from 'react-dom/client';+import type {+ ICellEditorLayout,+ ICellEditorState,+ IEditorBridgeServiceParam,+ IEditorBridgeServiceVisibleParam,+} from '../../../services/editor-bridge.service';+import {+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ ICommandService,+ IConfigService,+ IUniverInstanceService,+ LocaleType,+ Univer,+ UniverInstanceType,+} from '@univerjs/core';+import { IEditorService } from '@univerjs/docs-ui';+import {+ DefinedNamesService,+ FunctionService,+ IDefinedNamesService,+ IFunctionService,+ ISuperTableService,+ LexerTreeBuilder,+ SuperTableService,+} from '@univerjs/engine-formula';+import { DeviceInputEventType } from '@univerjs/engine-render';+import {+ RangeProtectionCache,+ RangeProtectionRuleModel,+ SheetPermissionCheckController,+ SheetsSelectionsService,+ WorksheetProtectionRuleModel,+} from '@univerjs/sheets';+import { ComponentManager, ILayoutService, IUIPartsService, KeyCode, RediContext, UIPartsService } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { SetCellEditVisibleOperation } from '../../../commands/operations/cell-edit.operation';+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY } from '../../../common/keys';+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';+import { IEditorBridgeService } from '../../../services/editor-bridge.service';+import { FormulaEditorManagerService, IFormulaEditorManagerService } from '../../../services/editor/formula-editor-manager.service';+import { FormulaBar } from '../FormulaBar';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'formula-bar-unit';+const SHEET_ID = 'sheet-1';++class TestResizeObserver {+ observe(): void {}+ disconnect(): void {}+ unobserve(): void {}+}++class TestEditorBridgeService implements IEditorBridgeService {+ private readonly _currentEditCellState$ = new BehaviorSubject<Nullable<ICellEditorState>>(null);+ readonly currentEditCellState$ = this._currentEditCellState$.asObservable();++ private readonly _currentEditCellLayout$ = new BehaviorSubject<Nullable<ICellEditorLayout>>(null);+ readonly currentEditCellLayout$ = this._currentEditCellLayout$.asObservable();++ private readonly _currentEditCell$ = new BehaviorSubject<Nullable<IEditorBridgeServiceParam>>(null);+ readonly currentEditCell$ = this._currentEditCell$.asObservable();++ private readonly _visible$ = new BehaviorSubject<IEditorBridgeServiceVisibleParam>({+ visible: false,+ eventType: DeviceInputEventType.Dblclick,+ unitId: '',+ });++ readonly visible$ = this._visible$.asObservable();++ private readonly _forceKeepVisible$ = new BehaviorSubject(false);+ readonly forceKeepVisible$ = this._forceKeepVisible$.asObservable();++ readonly helpFunctionVisible$ = new BehaviorSubject(true);++ private _visibleState = this._visible$.getValue();+ readonly visibleHistory: IEditorBridgeServiceVisibleParam[] = [this._visibleState];++ setCurrentEditCell(state: ICellEditorState): void {+ this._currentEditCellState$.next(state);+ }++ refreshEditCellState(): void {}+ refreshEditCellPosition(): void {}+ setEditCell(): void {}+ getEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>> {+ return null;+ }++ getEditCellLayout(): Readonly<Nullable<ICellEditorLayout>> {+ return null;+ }++ getEditLocation(): Readonly<Nullable<ICellEditorState>> {+ return this._currentEditCellState$.getValue();+ }++ updateEditLocation(): void {}+ getLatestEditCellState(): Readonly<Nullable<IEditorBridgeServiceParam>> {+ return null;+ }++ changeVisible(param: IEditorBridgeServiceVisibleParam): void {+ this._visibleState = param;+ this.visibleHistory.push(param);+ this._visible$.next(param);+ }++ changeEditorDirty(): void {}+ getEditorDirty(): boolean {+ return false;+ }++ isVisible(): IEditorBridgeServiceVisibleParam {+ return this._visibleState;+ }++ enableForceKeepVisible(): void {+ this._forceKeepVisible$.next(true);+ }++ disableForceKeepVisible(): void {+ this._forceKeepVisible$.next(false);+ }++ isForceKeepVisible(): boolean {+ return this._forceKeepVisible$.getValue();+ }++ getCurrentEditorId(): string {+ return DOCS_NORMAL_EDITOR_UNIT_ID_KEY;+ }++ dispose(): void {+ this._currentEditCellState$.complete();+ this._currentEditCellLayout$.complete();+ this._currentEditCell$.complete();+ this._visible$.complete();+ this._forceKeepVisible$.complete();+ this.helpFunctionVisible$.complete();+ }+}++class TestEditorService {+ readonly focusedEditorIds: string[] = [];+ readonly blurHistory: boolean[] = [];++ focus(editorId: string): void {+ this.focusedEditorIds.push(editorId);+ }++ blur(force?: boolean): void {+ this.blurHistory.push(!!force);+ }+}++class TestLayoutService {+ focus(): void {}+}++function TestFormulaEditor(props: { editorId: string; unitId?: string }) {+ return <div data-editor-id={props.editorId} data-unit-id={props.unitId} />;+}++function createWorkbookData(): IWorkbookData {+ return {+ id: UNIT_ID,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'Formula Bar',+ sheetOrder: [SHEET_ID],+ styles: {},+ sheets: {+ [SHEET_ID]: {+ id: SHEET_ID,+ name: 'Sheet1',+ cellData: {},+ },+ },+ };+}++function createCellEditState(): ICellEditorState {+ return {+ unitId: UNIT_ID,+ sheetId: SHEET_ID,+ row: 0,+ column: 0,+ editorUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ documentLayoutObject: {+ documentModel: {+ getBody: () => ({ customBlocks: [] }),+ getDrawingsOrder: () => [],+ },+ } as never,+ };+}++function createFormulaBarTestBed() {+ const originalResizeObserver = globalThis.ResizeObserver;+ globalThis.ResizeObserver = TestResizeObserver as typeof ResizeObserver;++ const univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ injector.add([IFunctionService, { useClass: FunctionService }]);+ injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);+ injector.add([ComponentManager, { useClass: ComponentManager }]);+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([SheetsSelectionsService, { useClass: SheetsSelectionsService }]);+ injector.add([WorksheetProtectionRuleModel, { useClass: WorksheetProtectionRuleModel }]);+ injector.add([RangeProtectionRuleModel, { useClass: RangeProtectionRuleModel }]);+ injector.add([RangeProtectionCache, { useClass: RangeProtectionCache }]);+ injector.add([SheetPermissionCheckController, { useClass: SheetPermissionCheckController }]);+ injector.add([IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }]);+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);+ injector.add([IEditorService, { useClass: TestEditorService as never }]);++ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);+ injector.get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, {});++ const componentManager = injector.get(ComponentManager);+ componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, TestFormulaEditor);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(SetCellEditVisibleOperation);++ const editorBridgeService = injector.get(IEditorBridgeService) as TestEditorBridgeService;+ editorBridgeService.setCurrentEditCell(createCellEditState());+ editorBridgeService.changeVisible({+ visible: true,+ eventType: DeviceInputEventType.PointerDown,+ unitId: UNIT_ID,+ });++ return {+ univer,+ injector,+ workbook,+ editorBridgeService,+ restoreResizeObserver: () => {+ globalThis.ResizeObserver = originalResizeObserver;+ },+ };+}++function renderWithDependencies(element: ReactElement, injector: ReturnType<typeof createFormulaBarTestBed>['injector']) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function getActionElement(container: HTMLElement, index: number): HTMLElement {+ const formulaBar = container.querySelector('[data-u-comp="formula-bar"]');+ if (!(formulaBar instanceof HTMLElement)) {+ throw new TypeError('Formula bar not rendered');+ }++ const elements = formulaBar.querySelectorAll('span');+ const element = elements.item(index);+ if (!(element instanceof HTMLElement)) {+ throw new TypeError(`Formula bar action ${index} not rendered`);+ }++ return element;+}++async function clickElement(element: HTMLElement): Promise<void> {+ await act(async () => {+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });+}++describe('FormulaBar', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentBed: ReturnType<typeof createFormulaBarTestBed> | undefined;++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentBed?.univer.dispose();+ currentBed?.restoreResizeObserver();+ root = undefined;+ container = undefined;+ currentBed = undefined;+ });++ it('closes editing through the command service when cancel is clicked', async () => {+ currentBed = createFormulaBarTestBed();+ const rendered = renderWithDependencies(<FormulaBar disableDefinedName />, currentBed.injector);+ root = rendered.root;+ container = rendered.container;++ await clickElement(getActionElement(rendered.container, 0));++ expect(currentBed.editorBridgeService.visibleHistory.at(-1)).toEqual({+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ keycode: KeyCode.ESC,+ unitId: UNIT_ID,+ });+ });++ it('commits editing through the command service when confirm is clicked', async () => {+ currentBed = createFormulaBarTestBed();+ const rendered = renderWithDependencies(<FormulaBar disableDefinedName />, currentBed.injector);+ root = rendered.root;+ container = rendered.container;++ await clickElement(getActionElement(rendered.container, 1));++ expect(currentBed.editorBridgeService.visibleHistory.at(-1)).toEqual({+ visible: false,+ eventType: DeviceInputEventType.PointerDown,+ unitId: UNIT_ID,+ });+ });+});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.tsindex 523402f6a5..59ea080a1f 100644--- 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.ts@@ -14,67 +14,84 @@* limitations under the License.*/-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';import { Animate } from '../animate';+const originalDateNow = Date.now;+const originalRequestAnimationFrame = window.requestAnimationFrame;+const originalCancelAnimationFrame = window.cancelAnimationFrame;++class TestAnimationState {+ static receivedValues: number[] = [];+ static successValues: number[] = [];+ static cancelValues: number[] = [];+ static completeValues: number[] = [];+ static canceledFrames: number[] = [];++ static reset(): void {+ this.receivedValues = [];+ this.successValues = [];+ this.cancelValues = [];+ this.completeValues = [];+ this.canceledFrames = [];+ }+}+describe('animate util', () => {afterEach(() => {- vi.restoreAllMocks();+ Date.now = originalDateNow;+ window.requestAnimationFrame = originalRequestAnimationFrame;+ window.cancelAnimationFrame = originalCancelAnimationFrame;+ TestAnimationState.reset();});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(() => {+ Date.now = () => {now += 10;return now;- });+ };const animate = new Animate({begin: 0,end: 100,duration: 10,- receive,- success,- complete,+ receive: (value) => TestAnimationState.receivedValues.push(value),+ success: (value) => TestAnimationState.successValues.push(value),+ complete: (value) => TestAnimationState.completeValues.push(value),});animate.request();- expect(receive).toHaveBeenCalled();- expect(success).toHaveBeenCalled();- expect(complete).toHaveBeenCalled();+ expect(TestAnimationState.receivedValues.length).toBe(1);+ expect(TestAnimationState.successValues.length).toBe(1);+ expect(TestAnimationState.completeValues.length).toBe(1);});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);+ Date.now = () => 0;+ window.requestAnimationFrame = () => {return 1;- });- const cancelAnimationFrameSpy = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {});- const cancel = vi.fn();- const complete = vi.fn();- const receive = vi.fn();+ };+ window.cancelAnimationFrame = (frameId: number) => {+ TestAnimationState.canceledFrames.push(frameId);+ };const animate = new Animate({begin: 0,end: 100,duration: 100,- receive,- cancel,- complete,+ receive: (value) => TestAnimationState.receivedValues.push(value),+ cancel: (value) => TestAnimationState.cancelValues.push(value),+ complete: (value) => TestAnimationState.completeValues.push(value),});animate.request();animate.cancel();- (animate as any)._fakeHandle();+ (animate as unknown as { _fakeHandle: () => void })._fakeHandle();- expect(receive).toHaveBeenCalled();- expect(cancelAnimationFrameSpy).toHaveBeenCalledWith(1);- expect(cancel).toHaveBeenCalled();- expect(complete).toHaveBeenCalled();+ expect(TestAnimationState.receivedValues.length).toBe(2);+ expect(TestAnimationState.canceledFrames).toEqual([1]);+ expect(TestAnimationState.cancelValues.length).toBe(1);+ expect(TestAnimationState.completeValues.length).toBe(1);});it('Animate.success resolves after all non-loop animations succeed', async () => {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.tsindex 92c82e5fac..ea089b0ac3 100644--- 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.ts@@ -14,9 +14,13 @@* limitations under the License.*/-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';import { SlideTabBar, SlideTabItem } from '../slide-tab-bar';+const originalRequestAnimationFrame = window.requestAnimationFrame;+const originalCancelAnimationFrame = window.cancelAnimationFrame;+const originalConsoleError = console.error;+function rect(x: number, width: number, y = 0, height = 24): DOMRect {return {x,@@ -31,6 +35,51 @@ function rect(x: number, width: number, y = 0, height = 24): DOMRect {} as DOMRect;}+class TestSlideEvents {+ readonly scrollStates: Array<{ leftEnd: boolean; rightEnd: boolean }> = [];+ readonly slideEnds: Array<{ event: MouseEvent; compareIndex: number }> = [];+ readonly changedTabs: Array<{ event: MouseEvent; id: string }> = [];+ readonly changedNames: Array<{ id: string; name: string }> = [];+ nameCheckAlerts: string[] = [];+ errorCount = 0;++ createConfig(root: HTMLDivElement) {+ return {+ slideTabBarSelector: '.tab-bar',+ slideTabBarItemSelector: '.tab-item',+ slideTabBarContainer: root,+ slideTabBarItemAutoSort: true,+ currentIndex: 0,+ onScroll: (state: { leftEnd: boolean; rightEnd: boolean }) => this.scrollStates.push(state),+ onSlideEnd: (event: MouseEvent, compareIndex: number) => this.slideEnds.push({ event, compareIndex }),+ onChangeTab: (event: MouseEvent, id: string) => this.changedTabs.push({ event, id }),+ onChangeName: (id: string, name: string) => this.changedNames.push({ id, name }),+ onNameCheckAlert: (text: string) => {+ this.nameCheckAlerts.push(text);+ return false;+ },+ onNameChangeCheck: () => true,+ };+ }+}++class TestAnimationFrameState {+ frameId = 0;+ readonly requests: number[] = [];+ readonly cancellations: number[] = [];++ install(nextFrameId = 1): void {+ this.frameId = nextFrameId;+ window.requestAnimationFrame = () => {+ this.requests.push(this.frameId);+ return this.frameId;+ };+ window.cancelAnimationFrame = (frameId: number) => {+ this.cancellations.push(frameId);+ };+ }+}+function setupDOM() {const root = document.createElement('div');const bar = document.createElement('div');@@ -63,52 +112,45 @@ function setupDOM() {},});- vi.spyOn(bar, 'getBoundingClientRect').mockImplementation(() => rect(0, 100));+ bar.getBoundingClientRect = () => rect(0, 100);- Array.from(bar.querySelectorAll('.tab-item')).forEach((item, idx) => {- vi.spyOn(item, 'getBoundingClientRect').mockImplementation(() => rect(itemLefts[idx], itemWidths[idx]));+ Array.from(bar.querySelectorAll<HTMLElement>('.tab-item')).forEach((item, idx) => {+ item.getBoundingClientRect = () => rect(itemLefts[idx], itemWidths[idx]);});return {root,bar,- onScroll: vi.fn(),- onSlideEnd: vi.fn(),- onChangeTab: vi.fn(),- onChangeName: vi.fn(),+ events: new TestSlideEvents(),};}+function createBar(root: HTMLDivElement, events: TestSlideEvents, currentIndex = 0): SlideTabBar {+ const config = events.createConfig(root);+ config.currentIndex = currentIndex;+ return new SlideTabBar(config);+}+describe('slide-tab-bar', () => {afterEach(() => {- vi.restoreAllMocks();+ window.requestAnimationFrame = originalRequestAnimationFrame;+ window.cancelAnimationFrame = originalCancelAnimationFrame;+ console.error = originalConsoleError;document.body.innerHTML = '';});it('guards invalid constructor config', () => {- expect(() => new SlideTabBar({ slideTabBarContainer: null as any })).toThrowError('not found slide-tab-bar root element');+ expect(() => new SlideTabBar({ slideTabBarContainer: null as never })).toThrowError('not found slide-tab-bar root element');const root = document.createElement('div');expect(() => new SlideTabBar({- slideTabBarContainer: root as any,+ slideTabBarContainer: root as HTMLDivElement,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,- });+ it('handles scroll boundaries and keeps the active sheet visible', () => {+ const { root, events } = setupDOM();+ const bar = createBar(root, events);expect(bar.getSlideTabItems().length).toBe(3);expect(bar.isLeftEnd()).toBe(true);@@ -123,10 +165,12 @@ describe('slide-tab-bar', () => {bar.flipPage(-1);bar.scrollToItem(2);- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ console.error = () => {+ events.errorCount += 1;+ };bar.scrollToItem(99);- expect(errorSpy).toHaveBeenCalled();- expect(onScroll).toHaveBeenCalled();+ expect(events.errorCount).toBe(1);+ expect(events.scrollStates.length).toBeGreaterThan(0);bar.update(1);expect(bar.getActiveItem()?.getId()).toBe('sheet-1');@@ -135,21 +179,10 @@ describe('slide-tab-bar', () => {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,- });+ it('supports editing, fixed dragging style, and per-item animation', () => {+ const { root, events } = setupDOM();+ const frameState = new TestAnimationFrameState();+ const bar = createBar(root, events);const item = bar.getSlideTabItems()[0];const editor = item.getEditor() as HTMLSpanElement;@@ -159,84 +192,74 @@ describe('slide-tab-bar', () => {expect(item.classList()).toBe(item.getSlideTabItem().classList);expect(item.equals(item)).toBe(true);- const callback = vi.fn();- item.setEditor(callback);+ let renameFinishedCount = 0;+ item.setEditor(() => {+ renameFinishedCount += 1;+ });expect(editor.getAttribute('contentEditable')).toBe('true');editor.innerText = 'Renamed';editor.dispatchEvent(new FocusEvent('focusout'));- expect(onChangeName).toHaveBeenCalledWith('sheet-0', 'Renamed');- expect(callback).toHaveBeenCalled();+ expect(events.changedNames).toEqual([{ id: 'sheet-0', name: 'Renamed' }]);+ expect(renameFinishedCount).toBe(1);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();+ frameState.install(1);+ const animation = item.animate();+ animation.translateX(30);+ animation.cancel();+ expect(frameState.requests).toEqual([1]);+ expect(frameState.cancellations).toEqual([1]);});- 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,- });+ it('sorts dragged sheet tabs and starts or closes edge auto-scroll', () => {+ const { root, events } = setupDOM();+ const frameState = new TestAnimationFrameState();+ const bar = createBar(root, events, 1);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;+ (bar as unknown as { _activeTabItem: SlideTabItem })._activeTabItem = active;+ (bar as unknown as { _activeTabItemIndex: number })._activeTabItemIndex = 1;activeX = 110;- (bar as any)._compareRight();- expect((bar as any)._compareIndex).toBeGreaterThanOrEqual(1);+ (bar as unknown as { _compareRight: () => void })._compareRight();+ expect((bar as unknown as { _compareIndex: number })._compareIndex).toBeGreaterThanOrEqual(1);activeX = -30;- (bar as any)._compareLeft();- expect((bar as any)._compareIndex).toBeLessThanOrEqual(1);+ (bar as unknown as { _compareLeft: () => void })._compareLeft();+ expect((bar as unknown as { _compareIndex: number })._compareIndex).toBeLessThanOrEqual(1);- (bar as any)._compareIndex = 0;- (bar as any)._sortedItems();+ (bar as unknown as { _compareIndex: number })._compareIndex = 0;+ (bar as unknown as { _sortedItems: () => void })._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();+ (bar as unknown as { _leftBoundingLine: number })._leftBoundingLine = 20;+ (bar as unknown as { _rightBoundingLine: number })._rightBoundingLine = 20;+ (bar as unknown as { _scrollIncremental: number })._scrollIncremental = 0;+ (bar as unknown as { _scrollLeft: (event: MouseEvent) => void })._scrollLeft({ pageX: 0 } as MouseEvent);+ expect((bar as unknown as { _scrollIncremental: number })._scrollIncremental).toBeLessThanOrEqual(0);+ (bar as unknown as { _scrollRight: (event: MouseEvent) => void })._scrollRight({ pageX: 500 } as MouseEvent);+ expect((bar as unknown as { _scrollIncremental: number })._scrollIncremental).toBeGreaterThanOrEqual(0);++ frameState.install(2);+ (bar as unknown as { _moveActionX: number })._moveActionX = 10;+ (bar as unknown as { _startAutoScroll: () => void })._startAutoScroll();+ expect((bar as unknown as { _autoScrollTime: number })._autoScrollTime).toBe(2);+ (bar as unknown as { _closeAutoScroll: () => void })._closeAutoScroll();+ expect((bar as unknown as { _autoScrollTime: null })._autoScrollTime).toBeNull();+ expect(frameState.requests.length).toBeGreaterThan(0);+ expect(frameState.requests.every((frameId) => frameId === 2)).toBe(true);+ expect(frameState.cancellations).toContain(2);});- it('handles static selection helpers', () => {+ it('handles static text-selection and slide-skip helpers', () => {const el = document.createElement('span');el.innerText = 'abc';document.body.appendChild(el);diff --git a/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsx b/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsxnew file mode 100644index 0000000000..6f2b632028--- /dev/null+++ b/packages/sheets-ui/src/views/status-bar/__tests__/StatusBar.spec.tsx@@ -0,0 +1,228 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 type { IMessageProps } from '@univerjs/design';+import type { ReactElement } from 'react';+import { ConfigService, IConfigService, Injector, LocaleService } from '@univerjs/core';+import { FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL } from '@univerjs/engine-formula';+import { IClipboardInterfaceService, IMessageService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';+import { IStatusBarService, StatusBarService } from '../../../services/status-bar.service';+import { CopyableStatisticItem } from '../CopyableStatisticItem';+import { StatusBar } from '../StatusBar';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class TestLocaleService {+ t(key: string): string {+ return key;+ }+}++class TestClipboardService {+ readonly supportClipboard = true;++ async writeText(text: string): Promise<void> {+ TestState.copiedText = text;+ }++ async write(text: string): Promise<void> {+ TestState.copiedText = text;+ }++ async readText(): Promise<string> {+ return TestState.copiedText;+ }++ async read(): Promise<ClipboardItem[]> {+ return [];+ }+}++class TestMessageService {+ show(options: IMessageProps): IDisposable {+ TestState.messages.push(String(options.content));+ return { dispose(): void {} };+ }++ remove(): void {}++ removeAll(): void {}+}++class TestState {+ static copiedText = '';+ static messages: string[] = [];++ static reset(): void {+ this.copiedText = '';+ this.messages = [];+ }+}++function setViewportWidth(width: number) {+ Object.defineProperty(window, 'innerWidth', {+ configurable: true,+ writable: true,+ value: width,+ });+}++function createStatusBarInjector() {+ const injector = new Injector();+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([IStatusBarService, { useClass: StatusBarService }]);+ injector.add([IClipboardInterfaceService, { useClass: TestClipboardService as never }]);+ injector.add([IMessageService, { useClass: TestMessageService as never }]);++ injector.get(IConfigService).setConfig(SHEETS_UI_PLUGIN_CONFIG_KEY, { statusBarStatistic: true });++ return injector;+}++function renderWithDependencies(element: ReactElement) {+ const injector = createStatusBarInjector();+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return {+ container,+ injector,+ unmount: () => {+ act(() => root.unmount());+ container.remove();+ },+ };+}++function queryByText(container: HTMLElement, text: string): HTMLElement | null {+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);+ let node = walker.nextNode();+ while (node) {+ if (node.textContent === text) {+ return node.parentElement;+ }+ node = walker.nextNode();+ }++ return null;+}++function getByText(container: HTMLElement, text: string): HTMLElement {+ const element = queryByText(container, text);+ if (!element) {+ throw new Error(`Text not found: ${text}`);+ }++ return element;+}++function publishStatistics(injector: Injector) {+ act(() => {+ injector.get(IStatusBarService).setState({+ pattern: '0.00',+ values: [+ { func: FUNCTION_NAMES_STATISTICAL.MAX, value: 12.5 },+ { func: FUNCTION_NAMES_STATISTICAL.MIN, value: 3 },+ { func: FUNCTION_NAMES_MATH.SUM, value: 15.5 },+ { func: FUNCTION_NAMES_STATISTICAL.COUNTA, value: 3 },+ { func: FUNCTION_NAMES_STATISTICAL.COUNT, value: 2 },+ { func: FUNCTION_NAMES_STATISTICAL.AVERAGE, value: 7.75 },+ ],+ });+ });+}++describe('StatusBar', () => {+ const disposals: Array<() => void> = [];++ afterEach(() => {+ disposals.splice(0).forEach((dispose) => dispose());+ TestState.reset();+ setViewportWidth(1024);+ });++ it('renders filtered statistics from service state with number formatting', () => {+ setViewportWidth(1024);+ const { container, injector, unmount } = renderWithDependencies(<StatusBar />);+ disposals.push(unmount);++ publishStatistics(injector);++ expect(getByText(container, 'sheets-ui.statusbar.max: 12.50')).toBeTruthy();+ expect(getByText(container, 'sheets-ui.statusbar.min: 3.00')).toBeTruthy();+ expect(getByText(container, 'sheets-ui.statusbar.sum: 15.50')).toBeTruthy();+ expect(getByText(container, 'sheets-ui.statusbar.countA: 3')).toBeTruthy();+ expect(getByText(container, 'sheets-ui.statusbar.count: 2')).toBeTruthy();+ expect(getByText(container, 'sheets-ui.statusbar.average: 7.75')).toBeTruthy();+ });++ it('keeps only the first available statistic in narrow viewports', () => {+ setViewportWidth(640);+ const { container, injector, unmount } = renderWithDependencies(<StatusBar />);+ disposals.push(unmount);++ publishStatistics(injector);++ expect(getByText(container, 'sheets-ui.statusbar.max: 12.50')).toBeTruthy();+ expect(queryByText(container, 'sheets-ui.statusbar.min: 3.00')).toBeNull();+ expect(queryByText(container, 'sheets-ui.statusbar.sum: 15.50')).toBeNull();+ });+});++describe('CopyableStatisticItem', () => {+ const disposals: Array<() => void> = [];++ afterEach(() => {+ disposals.splice(0).forEach((dispose) => dispose());+ TestState.reset();+ });++ it('copies the raw statistic value and reports a success message', async () => {+ const { container, unmount } = renderWithDependencies(+ <CopyableStatisticItem+ name={FUNCTION_NAMES_MATH.SUM}+ value={1234.5}+ show+ disable={false}+ pattern="0.00"+ />+ );+ disposals.push(unmount);++ await act(async () => {+ getByText(container, 'sheets-ui.statusbar.sum: 1234.50').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await Promise.resolve();+ });++ expect(TestState.copiedText).toBe('1234.5');+ expect(TestState.messages).toEqual(['sheets-ui.statusbar.copied']);+ });+});diff --git a/packages/sheets/src/commands/commands/set-col-visible.command.ts b/packages/sheets/src/commands/commands/set-col-visible.command.tsindex fb096add24..312f3aea24 100644--- a/packages/sheets/src/commands/commands/set-col-visible.command.ts+++ b/packages/sheets/src/commands/commands/set-col-visible.command.ts@@ -132,15 +132,15 @@ export const SetSelectedColsVisibleCommand: ICommand = {const selectionManagerService = accessor.get(SheetsSelectionsService);const commandService = accessor.get(ICommandService);- const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);- if (!ranges?.length) return false;+ const ranges = getSelectedColRanges(selectionManagerService);+ if (!ranges.length) return false;const target = getSheetCommandTarget(accessor.get(IUniverInstanceService));if (!target) return false;const { worksheet, unitId, subUnitId } = target;// `ranges` would not overlap each other, so `hiddenRanges` would not overlap each other either- const hiddenRanges = ranges.map((r) => worksheet.getHiddenCols(r.startColumn, r.endColumn)).flat();+ const hiddenRanges = getHiddenColRanges(worksheet, ranges);return commandService.executeCommand<ISetSpecificColsVisibleCommandParams>(SetSpecificColsVisibleCommand.id, {unitId,@@ -165,8 +165,8 @@ export const SetColHiddenCommand: ICommand = {const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);- let ranges = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.COLUMN);- if (!ranges?.length) return false;+ let ranges = params?.ranges?.length ? params.ranges : getSelectedColRanges(selectionManagerService);+ if (!ranges.length) return false;const target = getSheetCommandTarget(univerInstanceService, params);if (!target) return false;@@ -241,6 +241,32 @@ export const SetColHiddenCommand: ICommand = {},};+function getSelectedColRanges(selectionManagerService: SheetsSelectionsService): IRange[] {+ const selections = selectionManagerService.getCurrentSelections();+ const ranges: IRange[] = [];+ if (!selections) {+ return ranges;+ }+ for (let i = 0; i < selections.length; i++) {+ const range = selections[i].range;+ if (range.rangeType === RANGE_TYPE.COLUMN) {+ ranges.push(range);+ }+ }+ return ranges;+}++function getHiddenColRanges(worksheet: Worksheet, ranges: IRange[]): IRange[] {+ const hiddenRanges: IRange[] = [];+ for (let i = 0; i < ranges.length; i++) {+ const hiddenCols = worksheet.getHiddenCols(ranges[i].startColumn, ranges[i].endColumn);+ for (let j = 0; j < hiddenCols.length; j++) {+ hiddenRanges.push(hiddenCols[j]);+ }+ }+ return hiddenRanges;+}+export function divideRangesByHiddenCols(worksheet: Worksheet, ranges: IRange[]): IRange[] {const endRow = worksheet.getRowCount() - 1;const hiddenCols = worksheet.getHiddenCols();diff --git a/packages/sheets/src/commands/commands/set-row-visible.command.ts b/packages/sheets/src/commands/commands/set-row-visible.command.tsindex ccd5320a60..c16d344b0a 100644--- a/packages/sheets/src/commands/commands/set-row-visible.command.ts+++ b/packages/sheets/src/commands/commands/set-row-visible.command.ts@@ -134,14 +134,14 @@ export const SetSelectedRowsVisibleCommand: ICommand = {const univerInstanceService = accessor.get(IUniverInstanceService);const commandService = accessor.get(ICommandService);- const ranges = selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);- if (!ranges?.length) return false;+ const ranges = getSelectedRowRanges(selectionManagerService);+ if (!ranges.length) return false;const target = getSheetCommandTarget(univerInstanceService);if (!target) return false;const { worksheet, unitId, subUnitId } = target;- const hiddenRanges = ranges.map((r) => worksheet.getHiddenRows(r.startRow, r.endRow)).flat();+ const hiddenRanges = getHiddenRowRanges(worksheet, ranges);return commandService.executeCommand<ISetSpecificRowsVisibleCommandParams>(SetSpecificRowsVisibleCommand.id, {unitId,subUnitId,@@ -167,8 +167,8 @@ export const SetRowHiddenCommand: ICommand<ISetRowHiddenCommandParams> = {const sheetInterceptorService = accessor.get(SheetInterceptorService);// Ranges should be divided by already hidden rows.- let ranges = params?.ranges?.length ? params.ranges : selectionManagerService.getCurrentSelections()?.map((s) => s.range).filter((r) => r.rangeType === RANGE_TYPE.ROW);- if (!ranges?.length) return false;+ let ranges = params?.ranges?.length ? params.ranges : getSelectedRowRanges(selectionManagerService);+ if (!ranges.length) return false;const target = getSheetCommandTarget(univerInstanceService, params);if (!target) return false;@@ -237,6 +237,32 @@ export const SetRowHiddenCommand: ICommand<ISetRowHiddenCommandParams> = {},};+function getSelectedRowRanges(selectionManagerService: SheetsSelectionsService): IRange[] {+ const selections = selectionManagerService.getCurrentSelections();+ const ranges: IRange[] = [];+ if (!selections) {+ return ranges;+ }+ for (let i = 0; i < selections.length; i++) {+ const range = selections[i].range;+ if (range.rangeType === RANGE_TYPE.ROW) {+ ranges.push(range);+ }+ }+ return ranges;+}++function getHiddenRowRanges(worksheet: Worksheet, ranges: IRange[]): IRange[] {+ const hiddenRanges: IRange[] = [];+ for (let i = 0; i < ranges.length; i++) {+ const hiddenRows = worksheet.getHiddenRows(ranges[i].startRow, ranges[i].endRow);+ for (let j = 0; j < hiddenRows.length; j++) {+ hiddenRanges.push(hiddenRows[j]);+ }+ }+ return hiddenRanges;+}+// TODO@wzhudev: this should be unit testedexport function divideRangesByHiddenRows(worksheet: Worksheet, ranges: IRange[]): IRange[] {const endCol = worksheet.getMaxColumns() - 1;diff --git a/packages/sheets/src/commands/commands/util.ts b/packages/sheets/src/commands/commands/util.tsindex fe41a31b1a..28ede6aae3 100644--- a/packages/sheets/src/commands/commands/util.ts+++ b/packages/sheets/src/commands/commands/util.ts@@ -19,14 +19,15 @@ import { ObjectMatrix, Range } from '@univerjs/core';export function getRangesHeight(ranges: IRange[], worksheet: Worksheet) {const cellHeights = new ObjectMatrix<number>();- ranges.map((range) => Range.transformRange(range, worksheet)).forEach((range) => {+ for (let i = 0; i < ranges.length; i++) {+ const range = Range.transformRange(ranges[i], worksheet);Range.foreach(range, (row, col) => {const cellHeight = worksheet.getCellHeight(row, col);if (cellHeight) {cellHeights.setValue(row, col, cellHeight);}});- });+ }return cellHeights;}diff --git a/packages/sheets/src/commands/mutations/delete-range-protection.mutation.ts b/packages/sheets/src/commands/mutations/delete-range-protection.mutation.tsindex 5980409970..b288ea0a37 100644--- a/packages/sheets/src/commands/mutations/delete-range-protection.mutation.ts+++ b/packages/sheets/src/commands/mutations/delete-range-protection.mutation.ts@@ -29,7 +29,13 @@ export interface IDeleteRangeProtectionMutationParams {};export const FactoryDeleteRangeProtectionMutation = (accessor: IAccessor, param: IDeleteRangeProtectionMutationParams) => {const selectionProtectionRuleModel = accessor.get(RangeProtectionRuleModel);- const rules = param.ruleIds.map((id) => selectionProtectionRuleModel.getRule(param.unitId, param.subUnitId, id)).filter((rule) => !!rule) as IRangeProtectionRule[];+ const rules: IRangeProtectionRule[] = [];+ for (let i = 0; i < param.ruleIds.length; i++) {+ const rule = selectionProtectionRuleModel.getRule(param.unitId, param.subUnitId, param.ruleIds[i]);+ if (rule) {+ rules.push(rule);+ }+ }const result: IMutationInfo<Omit<IAddRangeProtectionMutationParams, 'name'>> = { id: AddRangeProtectionMutation.id, params: { subUnitId: param.subUnitId, unitId: param.unitId, rules } };return result;};@@ -39,9 +45,9 @@ export const DeleteRangeProtectionMutation: IMutation<IDeleteRangeProtectionMutahandler: (accessor, params) => {const { unitId, subUnitId, ruleIds } = params;const selectionProtectionRuleModel = accessor.get(RangeProtectionRuleModel);- ruleIds.forEach((id) => {- selectionProtectionRuleModel.deleteRule(unitId, subUnitId, id);- });+ for (let i = 0; i < ruleIds.length; i++) {+ selectionProtectionRuleModel.deleteRule(unitId, subUnitId, ruleIds[i]);+ }return true;},};diff --git a/packages/sheets/src/facade/__tests__/f-active-range.spec.ts b/packages/sheets/src/facade/__tests__/f-active-range.spec.tsindex fef2bfb442..2d2c5597f0 100644--- a/packages/sheets/src/facade/__tests__/f-active-range.spec.ts+++ b/packages/sheets/src/facade/__tests__/f-active-range.spec.ts@@ -16,8 +16,15 @@import type { Injector } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';-import { ICommandService } from '@univerjs/core';-import { InsertSheetCommand, InsertSheetMutation, RemoveSheetCommand, RemoveSheetMutation, SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';+import { Direction, ICommandService } from '@univerjs/core';+import {+ InsertSheetCommand,+ InsertSheetMutation,+ RemoveSheetCommand,+ RemoveSheetMutation,+ SetSelectionsOperation,+ SetWorksheetActiveOperation,+} from '@univerjs/sheets';import { beforeEach, describe, expect, it } from 'vitest';import { createFacadeTestBed } from './create-test-bed';@@ -95,4 +102,26 @@ describe('Test Active Range', () => {sheet1.setActiveRange(range2);}).toThrow('Specified range must be part of the sheet.');});++ it('Worksheet selection tracks the active range and current cell as users move within it', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const sheet = workbook.getActiveSheet();++ sheet.getRange('A1:B2').activate();+ let selection = sheet.getSelection()!;++ expect(selection.getActiveSheet().equalTo(sheet)).toBe(true);+ expect(selection.getActiveRange()?.getA1Notation()).toBe('A1:B2');+ expect(selection.getActiveRangeList().map((range) => range.getA1Notation())).toEqual(['A1:B2']);+ expect(selection.getCurrentCell()).toMatchObject({ actualRow: 0, actualColumn: 0 });+ expect(selection.getNextDataRange(Direction.RIGHT)?.getA1Notation()).toBe('B1');++ selection = selection.updatePrimaryCell(sheet.getRange('B1'));+ expect(selection.getCurrentCell()).toMatchObject({ actualRow: 0, actualColumn: 1 });+ expect(selection.getNextDataRange(Direction.RIGHT)?.getA1Notation()).toBe('A2');++ selection = selection.updatePrimaryCell(sheet.getRange('C3'));+ expect(selection.getActiveRange()?.getA1Notation()).toBe('C3');+ expect(selection.getCurrentCell()).toMatchObject({ actualRow: 2, actualColumn: 2 });+ });});diff --git a/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts b/packages/sheets/src/facade/__tests__/f-defined-name.spec.tsindex 81818c6e10..c7f9fe4f50 100644--- a/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts+++ b/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts@@ -101,4 +101,56 @@ describe('Test FDefinedName', () => {sheet.insertDefinedName('test11', 'A1');expect(activeSpreadsheet.getDefinedName('test11')?.getLocalSheetId()).eq(sheet.getSheetId());});++ it('defined names can be maintained as workbook and worksheet level business aliases', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const sheet = workbook.getActiveSheet();++ const initialParam = workbook.newDefinedNameBuilder()+ .setName('QuarterRevenue')+ .setRefByRange(1, 1, 2, 1)+ .setComment('Revenue input cells')+ .setScopeToWorksheet(sheet)+ .setHidden(false)+ .build();+ workbook.insertDefinedNameBuilder(initialParam);++ const localName = workbook.getDefinedName('QuarterRevenue')!;+ expect(localName.getFormulaOrRefString()).toBe('B2:B3');+ expect(localName.getComment()).toBe('Revenue input cells');+ expect(localName.getLocalSheetId()).toBe(sheet.getSheetId());+ expect(localName.isWorkbookScope()).toBe(false);+ expect(sheet.getDefinedNames().map((name) => name.getName())).toEqual(['QuarterRevenue']);++ localName.setName('RegionalRevenue');+ expect(workbook.getDefinedName('QuarterRevenue')).toBeNull();+ expect(workbook.getDefinedName('RegionalRevenue')?.getFormulaOrRefString()).toBe('B2:B3');++ const regionalRevenue = workbook.getDefinedName('RegionalRevenue')!;+ regionalRevenue.setFormula('SUM(B2:B3)');+ expect(regionalRevenue.getFormulaOrRefString()).toBe('=SUM(B2:B3)');+ regionalRevenue.setRef('C2:C3');+ expect(regionalRevenue.getFormulaOrRefString()).toBe('C2:C3');+ regionalRevenue.setComment('Approved revenue range');+ expect(regionalRevenue.getComment()).toBe('Approved revenue range');+ regionalRevenue.setHidden(true);+ regionalRevenue.setScopeToWorkbook();+ expect(regionalRevenue.isWorkbookScope()).toBe(true);+ expect(sheet.getDefinedNames()).toEqual([]);++ const updatedParam = regionalRevenue.toBuilder()+ .setName('ApprovedRevenue')+ .setRefByRange(3, 3, 1, 2)+ .setScopeToWorksheet(sheet)+ .build();+ workbook.updateDefinedNameBuilder(updatedParam);++ expect(workbook.getDefinedName('RegionalRevenue')).toBeNull();+ expect(workbook.getDefinedName('ApprovedRevenue')?.getFormulaOrRefString()).toBe('D4:E4');+ expect(sheet.getDefinedNames().map((name) => name.getName())).toEqual(['ApprovedRevenue']);++ workbook.getDefinedName('ApprovedRevenue')?.delete();+ expect(workbook.getDefinedName('ApprovedRevenue')).toBeNull();+ expect(workbook.deleteDefinedName('missing-name')).toBe(false);+ });});diff --git a/packages/sheets/src/facade/__tests__/f-permission.spec.ts b/packages/sheets/src/facade/__tests__/f-permission.spec.tsnew file mode 100644index 0000000000..bef966932b--- /dev/null+++ b/packages/sheets/src/facade/__tests__/f-permission.spec.ts@@ -0,0 +1,204 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { ITestBed } from './create-test-bed';+import { ICommandService } from '@univerjs/core';+import {+ AddRangeProtectionMutation,+ AddWorksheetProtectionMutation,+ DeleteRangeProtectionMutation,+ DeleteWorksheetProtectionMutation,+ SetRangeProtectionMutation,+} from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createFacadeTestBed } from './create-test-bed';++describe('sheets facade permissions', () => {+ let testBed: ITestBed;++ beforeEach(() => {+ testBed = createFacadeTestBed();+ [+ AddWorksheetProtectionMutation,+ DeleteWorksheetProtectionMutation,+ AddRangeProtectionMutation,+ DeleteRangeProtectionMutation,+ SetRangeProtectionMutation,+ ].forEach((command) => testBed.get(ICommandService).registerCommand(command));+ });++ afterEach(() => {+ testBed.univer.dispose();+ });++ it('applies workbook modes and collaborator changes through the permission facade', async () => {+ const { univerAPI } = testBed;+ const workbookPermission = univerAPI.getActiveWorkbook()!.getWorkbookPermission();++ expect(workbookPermission.canEdit()).toBe(true);++ await workbookPermission.setReadOnly();+ expect(workbookPermission.canEdit()).toBe(false);+ expect(workbookPermission.getPoint(univerAPI.Enum.WorkbookPermissionPoint.View)).toBe(true);++ await workbookPermission.setEditable();+ expect(workbookPermission.canEdit()).toBe(true);+ expect(workbookPermission.getSnapshot()[univerAPI.Enum.WorkbookPermissionPoint.CreateSheet]).toBe(true);++ await workbookPermission.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Print, false);+ expect(workbookPermission.getPoint(univerAPI.Enum.WorkbookPermissionPoint.Print)).toBe(false);+ await workbookPermission.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Print, false);+ expect(workbookPermission.getPoint(univerAPI.Enum.WorkbookPermissionPoint.Print)).toBe(false);++ await workbookPermission.setCollaborators([+ { user: { userID: 'u-1', name: 'Editor', avatar: 'editor.png' }, role: univerAPI.Enum.UnitRole.Editor },+ ]);+ await workbookPermission.addCollaborator({ userID: 'u-2', name: 'Reader', avatar: '' }, univerAPI.Enum.UnitRole.Reader);+ await workbookPermission.updateCollaborator({ userID: 'u-2', name: 'Reader updated', avatar: 'reader.png' }, univerAPI.Enum.UnitRole.Editor);++ expect(await workbookPermission.listCollaborators()).toEqual([]);++ await workbookPermission.removeCollaborator('u-1');+ await workbookPermission.removeCollaborators(['u-2']);+ expect(await workbookPermission.listCollaborators()).toEqual([]);+ });++ it('protects a worksheet and range, then restores editing after unprotecting', async () => {+ const { univerAPI } = testBed;+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const worksheetPermission = worksheet.getWorksheetPermission();+ const protectedRange = worksheet.getRange('A1:B2');+ const rangePermission = protectedRange.getRangePermission();++ expect(worksheetPermission.isProtected()).toBe(false);+ expect(rangePermission.isProtected()).toBe(false);+ expect(worksheetPermission.canEditCell(0, 0)).toBe(true);++ const worksheetPermissionId = await worksheetPermission.protect({ name: 'Quarter close sheet' });+ expect(worksheetPermissionId).toBeTruthy();+ expect(worksheetPermission.isProtected()).toBe(true);++ await worksheetPermission.setMode('readOnly');+ expect(worksheetPermission.canEdit()).toBe(false);+ expect(worksheetPermission.canView()).toBe(true);+ expect(worksheetPermission.canEditCell(3, 3)).toBe(false);+ expect(worksheetPermission.getSnapshot()[univerAPI.Enum.WorksheetPermissionPoint.View]).toBe(true);++ await worksheetPermission.setEditable();+ expect(worksheetPermission.canEdit()).toBe(true);++ const rule = await rangePermission.protect({+ name: 'Locked input cells',+ allowViewByOthers: false,+ });+ expect(rangePermission.isProtected()).toBe(true);+ expect(rule.options).toMatchObject({ name: 'Locked input cells', allowViewByOthers: false });+ expect(rule.ranges.map((range) => range.getA1Notation())).toEqual(['A1:B2']);++ await rule.setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false);+ await rule.setPoint(univerAPI.Enum.RangePermissionPoint.View, true);+ expect(rule.canEdit()).toBe(false);+ expect(rule.canView()).toBe(true);+ expect(rule.getSnapshot()[univerAPI.Enum.RangePermissionPoint.Edit]).toBe(false);+ expect(worksheetPermission.canEditCell(0, 0)).toBe(false);+ expect(worksheetPermission.canEditCell(5, 5)).toBe(true);++ await rule.updateRanges([worksheet.getRange('C1:C2')]);+ expect(rule.ranges.map((range) => range.getA1Notation())).toEqual(['C1:C2']);+ expect((await worksheetPermission.listRangeProtectionRules({ ignoreCollaborators: true })).map((item) => item.id)).toEqual([rule.id]);+ expect((await rangePermission.listRules({ ignoreCollaborators: true }))).toEqual([]);+ expect((await worksheet.getRange('C1').getRangePermission().listRules({ ignoreCollaborators: true })).map((item) => item.id)).toEqual([rule.id]);++ await expect(worksheet.getRange('C2:D3').getRangePermission().protect({ name: 'Overlapping range' }))+ .rejects+ .toThrow('Range is already protected');++ expect(await rule.remove()).toBe(true);+ expect(await rangePermission.unprotect()).toBe(true);+ expect(worksheet.getRange('C1').getRangePermission().isProtected()).toBe(false);++ expect(await worksheetPermission.unprotect()).toBe(true);+ expect(worksheetPermission.isProtected()).toBe(false);+ });++ it('applies worksheet protection config and manages range rules in batches', async () => {+ const { univerAPI } = testBed;+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const worksheetPermission = worksheet.getWorksheetPermission();++ await expect(worksheetPermission.protectRanges([])).rejects.toThrow('Configs cannot be empty');+ await expect(worksheetPermission.setPoint(univerAPI.Enum.WorksheetPermissionPoint.Edit, false))+ .rejects+ .toThrow('worksheet protection does not exist');++ await worksheetPermission.protect({ name: 'Shared planning sheet' });+ await worksheetPermission.applyConfig({+ mode: 'filterOnly',+ points: {+ [univerAPI.Enum.WorksheetPermissionPoint.Edit]: true,+ [univerAPI.Enum.WorksheetPermissionPoint.InsertRow]: false,+ },+ rangeProtections: [+ {+ rangeRefs: ['E1:E2'],+ options: { name: 'Forecast totals', allowViewByOthers: false },+ },+ ],+ });++ expect(worksheetPermission.canEdit()).toBe(true);+ expect(worksheetPermission.getPoint(univerAPI.Enum.WorksheetPermissionPoint.Filter)).toBe(true);+ expect(worksheetPermission.getPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow)).toBe(false);+ expect(worksheetPermission.canViewCell(0, 4)).toBe(false);+ expect(worksheetPermission.canViewCell(5, 5)).toBe(true);++ const budgetRules = await worksheetPermission.protectRanges([+ {+ ranges: [worksheet.getRange('A5:B6')],+ options: { name: 'Budget input' },+ },+ {+ ranges: [worksheet.getRange('D5:D6')],+ options: { name: 'Approval input', allowViewByOthers: true },+ },+ ]);++ expect(budgetRules.map((rule) => rule.options.name)).toEqual(['Budget input', 'Approval input']);+ expect((await worksheetPermission.listRangeProtectionRules({ ignoreCollaborators: true })).map((rule) => rule.options.name)).toEqual([+ 'Forecast totals',+ 'Budget input',+ 'Approval input',+ ]);++ const debugBudgetCell = await worksheetPermission.debugCellPermission(4, 0);+ expect(debugBudgetCell?.options.name).toBe('Budget input');+ expect(await worksheetPermission.debugCellPermission(9, 9)).toBeUndefined();++ await expect(worksheetPermission.protectRanges([+ {+ ranges: [worksheet.getRange('A6:C7')],+ options: { name: 'Overlapping budget' },+ },+ ])).rejects.toThrow('The specified ranges overlap with existing protected ranges: A6:C7');++ expect(await worksheetPermission.unprotectRules(budgetRules.map((rule) => rule.id))).toBe(true);+ expect((await worksheetPermission.listRangeProtectionRules({ ignoreCollaborators: true })).map((rule) => rule.options.name)).toEqual(['Forecast totals']);+ expect(await worksheetPermission.unprotectRules([])).toBe(true);++ expect(await worksheetPermission.unprotect()).toBe(true);+ expect(worksheetPermission.isProtected()).toBe(false);+ });+});diff --git a/packages/sheets/src/facade/__tests__/f-range.spec.ts b/packages/sheets/src/facade/__tests__/f-range.spec.tsindex 5f8b7409c0..833f8fbb24 100644--- a/packages/sheets/src/facade/__tests__/f-range.spec.ts+++ b/packages/sheets/src/facade/__tests__/f-range.spec.ts@@ -17,6 +17,8 @@import type { ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';import {+ AbsoluteRefType,+ Dimension,HorizontalAlign,ICommandService,IConfirmService,@@ -29,13 +31,27 @@ import {} from '@univerjs/core';import {AddWorksheetMergeCommand,+ ClearSelectionAllCommand,+ ClearSelectionContentCommand,+ ClearSelectionFormatCommand,+ DeleteWorksheetRangeThemeStyleCommand,+ DeleteWorksheetRangeThemeStyleMutation,+ RegisterWorksheetRangeThemeStyleCommand,+ RegisterWorksheetRangeThemeStyleMutation,SetHorizontalTextAlignCommand,SetRangeCustomMetadataCommand,SetRangeValuesCommand,SetRangeValuesMutation,SetStyleCommand,+ SetTextRotationCommand,SetTextWrapCommand,SetVerticalTextAlignCommand,+ SetWorksheetRangeThemeStyleCommand,+ SetWorksheetRangeThemeStyleMutation,+ SheetRangeThemeModel,+ SheetRangeThemeService,+ SheetSkeletonService,+ UnregisterWorksheetRangeThemeStyleMutation,} from '@univerjs/sheets';import { beforeEach, describe, expect, it, vi } from 'vitest';import { SHEETS_CUSTOM_FIELD_WARNING_MESSAGE } from '../const';@@ -61,6 +77,8 @@ describe('Test FRange', () => {beforeEach(() => {const testBed = createFacadeTestBed(undefined, [[IConfirmService, { useClass: TestConfirmService }],+ [SheetRangeThemeModel],+ [SheetRangeThemeService],]);get = testBed.get;@@ -75,6 +93,19 @@ describe('Test FRange', () => {commandService.registerCommand(SetTextWrapCommand);commandService.registerCommand(AddWorksheetMergeCommand);commandService.registerCommand(SetRangeCustomMetadataCommand);+ commandService.registerCommand(SetTextRotationCommand);+ commandService.registerCommand(ClearSelectionAllCommand);+ commandService.registerCommand(ClearSelectionContentCommand);+ commandService.registerCommand(ClearSelectionFormatCommand);+ commandService.registerCommand(RegisterWorksheetRangeThemeStyleCommand);+ commandService.registerCommand(RegisterWorksheetRangeThemeStyleMutation);+ commandService.registerCommand(UnregisterWorksheetRangeThemeStyleMutation);+ commandService.registerCommand(SetWorksheetRangeThemeStyleCommand);+ commandService.registerCommand(SetWorksheetRangeThemeStyleMutation);+ commandService.registerCommand(DeleteWorksheetRangeThemeStyleCommand);+ commandService.registerCommand(DeleteWorksheetRangeThemeStyleMutation);++ get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');getValueByPosition = (startRow: number,@@ -759,6 +790,113 @@ describe('Test FRange', () => {]));});+ it('Range supports an analyst editing a formatted data island', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const activeSheet = workbook.getActiveSheet();+ const report = activeSheet.getRange('B2:D4');++ report+ .setValues([+ ['Region', 'Revenue', 'Margin'],+ ['East', 1200, 0.31],+ ['West', 900, 0.22],+ ])+ .setBackground('#f5f7fb')+ .setFontFamily('Inter')+ .setFontSize(12)+ .setWrap(true)+ .setHorizontalAlignment('center')+ .setVerticalAlignment('middle');++ expect(report.getUnitId()).toBe(workbook.getId());+ expect(report.getSheetName()).toBe('sheet1');+ expect(report.getSheetId()).toBe(activeSheet.getSheetId());+ expect(report.getRange()).toMatchObject({ startRow: 1, startColumn: 1, endRow: 3, endColumn: 3 });+ expect(report.getLastRow()).toBe(3);+ expect(report.getLastColumn()).toBe(3);+ expect(report.getA1Notation()).toBe('B2:D4');+ expect(report.getA1Notation(true, AbsoluteRefType.ALL, AbsoluteRefType.ALL)).toBe('sheet1!$B$2:$D$4');++ expect(report.getValue()).toBe('Region');+ expect(report.getRawValues()).toEqual([+ ['Region', 'Revenue', 'Margin'],+ ['East', 1200, 0.31],+ ['West', 900, 0.22],+ ]);+ expect(report.getDisplayValues()).toEqual([+ ['Region', 'Revenue', 'Margin'],+ ['East', '1200', '0.31'],+ ['West', '900', '0.22'],+ ]);+ expect(report.getCellDatas()[1][0]?.v).toBe('East');+ expect(report.getCellDataGrid()[2][1]?.v).toBe(900);+ expect(report.getValueAndRichTextValues()[1][1]).toBe(1200);++ expect(report.getBackground()).toBe('#f5f7fb');+ expect(report.getBackgrounds()).toEqual([+ ['#f5f7fb', '#f5f7fb', '#f5f7fb'],+ ['#f5f7fb', '#f5f7fb', '#f5f7fb'],+ ['#f5f7fb', '#f5f7fb', '#f5f7fb'],+ ]);+ expect(report.getFontFamily('cell')).toBe('Inter');+ expect(report.getFontSize('cell')).toBe(12);+ expect(report.getCellStyle('cell')?.fontFamily).toBe('Inter');+ expect(report.getCellStyles('cell')[0][0]?.fontSize).toBe(12);+ expect(report.getWrap()).toBe(true);+ expect(report.getWraps()).toEqual([+ [true, true, true],+ [true, true, true],+ [true, true, true],+ ]);+ expect(report.getWrapStrategy()).toBe(WrapStrategy.WRAP);+ expect(report.getHorizontalAlignment()).toBe('center');+ expect(report.getHorizontalAlignments()[0]).toEqual(['center', 'center', 'center']);+ expect(report.getVerticalAlignment()).toBe('middle');+ expect(report.getVerticalAlignments()[0]).toEqual(['middle', 'middle', 'middle']);++ const marginRange = activeSheet.getRange('E3:E4').setFormulas([+ ['=C3*D3'],+ ['=C4*D4'],+ ]);+ expect(marginRange.getFormula()).toBe('=C3*D3');+ expect(marginRange.getFormulas()).toEqual([['=C3*D3'], ['=C4*D4']]);++ activeSheet.getRange('B1').setValue('Header');+ activeSheet.getRange('A3').setValue('Neighbor');+ activeSheet.getRange('E3').setValue('Calculated');+ activeSheet.getRange('C5').setValue('Footer');+ expect(activeSheet.getRange('C3').getDataRegion().getA1Notation()).toBe('B2:D4');+ expect(activeSheet.getRange('C3').getDataRegion(Dimension.ROWS).getA1Notation()).toBe('C2:C4');+ expect(activeSheet.getRange('C3').getDataRegion(Dimension.COLUMNS).getA1Notation()).toBe('B3:D3');++ const offset = report.offset(1, 1, 2);+ expect(offset.getA1Notation()).toBe('C3:E4');+ expect(offset.getValues()).toEqual([+ [1200, 0.31, 'Calculated'],+ [900, 0.22, null],+ ]);+ expect(() => report.offset(-2, 0)).toThrow('The row or column index is out of range');++ expect(activeSheet.getRange('G7:H8').isBlank()).toBe(true);+ report.clear({ contentsOnly: true });+ expect(report.isBlank()).toBe(true);+ expect(report.getBackground()).toBe('#f5f7fb');++ report.setValue('restored');+ report.clear({ formatOnly: true });+ expect(report.getValue()).toBe('restored');+ expect(report.getBackground()).not.toBe('#f5f7fb');++ report.useThemeStyle('default');+ expect(report.getUsedThemeStyle()).toBe('default');+ report.useThemeStyle(undefined);+ expect(report.getUsedThemeStyle()).toBeUndefined();++ report.clear();+ expect(report.isBlank()).toBe(true);+ expect(report.getUsedThemeStyle()).toBeUndefined();+ });+it('Range getRawValue and getDisplayValue', () => {univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {if (stage === LifecycleStages.Steady) {diff --git a/packages/sheets/src/facade/__tests__/f-univer.spec.ts b/packages/sheets/src/facade/__tests__/f-univer.spec.tsnew file mode 100644index 0000000000..3fa648f02e--- /dev/null+++ b/packages/sheets/src/facade/__tests__/f-univer.spec.ts@@ -0,0 +1,299 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { ICommandService } from '@univerjs/core';+import {+ InsertSheetCommand,+ InsertSheetMutation,+ RemoveSheetCommand,+ RemoveSheetMutation,+ SetGridlinesColorCommand,+ SetGridlinesColorMutation,+ SetTabColorCommand,+ SetTabColorMutation,+ SetWorksheetActiveOperation,+ SetWorksheetHideCommand,+ SetWorksheetHideMutation,+ SetWorksheetNameCommand,+ SetWorksheetNameMutation,+ SetWorksheetOrderCommand,+ SetWorksheetOrderMutation,+ ToggleGridlinesCommand,+ ToggleGridlinesMutation,+} from '@univerjs/sheets';+import { beforeEach, describe, expect, it } from 'vitest';+import { createFacadeTestBed } from './create-test-bed';++describe('Test FUniver sheets facade', () => {+ let get: Injector['get'];+ let univerAPI: FUniver;++ beforeEach(() => {+ const testBed = createFacadeTestBed();+ get = testBed.get;+ univerAPI = testBed.univerAPI;++ const commandService = get(ICommandService);+ [+ InsertSheetCommand,+ InsertSheetMutation,+ RemoveSheetCommand,+ RemoveSheetMutation,+ SetGridlinesColorCommand,+ SetGridlinesColorMutation,+ SetTabColorCommand,+ SetTabColorMutation,+ SetWorksheetActiveOperation,+ SetWorksheetHideCommand,+ SetWorksheetHideMutation,+ SetWorksheetNameCommand,+ SetWorksheetNameMutation,+ SetWorksheetOrderCommand,+ SetWorksheetOrderMutation,+ ToggleGridlinesCommand,+ ToggleGridlinesMutation,+ ].forEach((command) => commandService.registerCommand(command));+ });++ it('reports workbook lifecycle through the sheet facade', () => {+ const created: string[] = [];+ const disposed: Array<{ unitId: string; sheetCount: number }> = [];++ univerAPI.addEvent(univerAPI.Event.WorkbookCreated, (event) => {+ created.push(event.workbook.getId());+ });+ univerAPI.addEvent(univerAPI.Event.WorkbookDisposed, (event) => {+ disposed.push({+ unitId: event.unitId,+ sheetCount: Object.keys(event.snapshot.sheets).length,+ });+ });++ const workbook = univerAPI.createWorkbook({+ id: 'facade-workbook',+ name: 'Facade workbook',+ sheetOrder: ['orders'],+ sheets: {+ orders: {+ id: 'orders',+ name: 'Orders',+ rowCount: 20,+ columnCount: 10,+ cellData: {+ 0: {+ 0: {+ v: 'SKU',+ },+ },+ },+ },+ },+ });++ expect(univerAPI.getWorkbook('facade-workbook')?.getActiveSheet().getSheetName()).toBe('Orders');+ expect(univerAPI.getActiveWorkbook()?.getId()).toBe('facade-workbook');+ expect(created).toEqual(['facade-workbook']);++ expect(univerAPI.disposeUnit(workbook.getId())).toBe(true);+ expect(univerAPI.getWorkbook('facade-workbook')).toBeNull();+ expect(disposed).toEqual([{ unitId: 'facade-workbook', sheetCount: 1 }]);+ });++ it('reports sheet lifecycle events with the resulting workbook state', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const initialSheet = workbook.getActiveSheet();+ const beforeCreate: Array<{ index?: number; sheetName?: string }> = [];+ const created: string[] = [];+ const activeChanges: Array<{ oldName: string; activeName: string }> = [];+ const renamed: Array<{ oldName: string; newName: string }> = [];+ const moved: Array<{ sheetName: string; newIndex: number }> = [];+ const tabColors: Array<{ oldColor?: string; newColor?: string }> = [];+ const hideChanges: Array<{ sheetName: string; hidden: boolean }> = [];+ const gridlineChanges: Array<{ hidden: boolean; color?: string }> = [];+ const deleted: string[] = [];++ univerAPI.addEvent(univerAPI.Event.BeforeSheetCreate, (event) => {+ beforeCreate.push({ index: event.index, sheetName: event.sheet?.name });+ });+ univerAPI.addEvent(univerAPI.Event.SheetCreated, (event) => {+ created.push(event.worksheet.getSheetName());+ });+ univerAPI.addEvent(univerAPI.Event.BeforeActiveSheetChange, (event) => {+ activeChanges.push({+ oldName: event.oldActiveSheet.getSheetName(),+ activeName: event.activeSheet.getSheetName(),+ });+ });+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNameChange, (event) => {+ renamed.push({ oldName: event.oldName, newName: event.newName });+ });+ univerAPI.addEvent(univerAPI.Event.SheetMoved, (event) => {+ moved.push({ sheetName: event.worksheet.getSheetName(), newIndex: event.newIndex });+ });+ univerAPI.addEvent(univerAPI.Event.BeforeSheetTabColorChange, (event) => {+ tabColors.push({ oldColor: event.oldColor, newColor: event.newColor });+ });+ univerAPI.addEvent(univerAPI.Event.SheetHideChanged, (event) => {+ hideChanges.push({ sheetName: event.worksheet.getSheetName(), hidden: event.hidden });+ });+ univerAPI.addEvent(univerAPI.Event.GridlineChanged, (event) => {+ gridlineChanges.push({+ hidden: !event.enabled,+ color: event.color,+ });+ });+ univerAPI.addEvent(univerAPI.Event.SheetDeleted, (event) => {+ deleted.push(event.sheetId);+ });++ const reportSheet = workbook.insertSheet('Reports', {+ index: 1,+ sheet: {+ id: 'reports',+ rowCount: 30,+ columnCount: 12,+ },+ });++ expect(beforeCreate).toEqual([{ index: 1, sheetName: 'Reports' }]);+ expect(created).toEqual(['Reports']);+ expect(activeChanges).toEqual([{ oldName: initialSheet.getSheetName(), activeName: 'Reports' }]);+ expect(univerAPI.getSheetCommandTarget({ unitId: workbook.getId(), sheetId: 'reports' })?.worksheet.getSheetName()).toBe('Reports');+ expect(univerAPI.getActiveSheet()?.worksheet.getSheetId()).toBe('reports');++ reportSheet.setName('FY Reports');+ expect(reportSheet.getSheetName()).toBe('FY Reports');+ expect(renamed).toEqual([{ oldName: 'Reports', newName: 'FY Reports' }]);++ workbook.moveSheet(reportSheet, 0);+ expect(workbook.getSheets()[0].getSheetId()).toBe('reports');+ expect(moved).toEqual([{ sheetName: 'FY Reports', newIndex: 0 }]);++ reportSheet.setTabColor('#3366ff');+ expect(reportSheet.getTabColor()).toBe('#3366ff');+ expect(tabColors).toEqual([{ oldColor: '', newColor: '#3366ff' }]);++ reportSheet.setHiddenGridlines(true);+ reportSheet.setGridLinesColor('#ddeeff');+ expect(reportSheet.hasHiddenGridLines()).toBe(true);+ expect(reportSheet.getGridLinesColor()).toBe('#ddeeff');+ expect(gridlineChanges).toEqual([+ { hidden: true, color: undefined },+ { hidden: true, color: '#ddeeff' },+ ]);++ reportSheet.hideSheet();+ expect(reportSheet.isSheetHidden()).toBe(true);+ expect(hideChanges).toEqual([{ sheetName: 'FY Reports', hidden: true }]);++ expect(workbook.deleteSheet(reportSheet)).toBe(true);+ expect(workbook.getSheetBySheetId('reports')).toBeNull();+ expect(deleted).toEqual(['reports']);+ });++ it('lets before events cancel risky sheet changes before state is mutated', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const reviewSheet = workbook.insertSheet('Review', {+ sheet: {+ id: 'review',+ rowCount: 20,+ columnCount: 10,+ },+ });++ univerAPI.addEvent(univerAPI.Event.BeforeSheetNameChange, (event) => {+ if (event.newName === 'Locked') {+ event.cancel = true;+ }+ });+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDelete, (event) => {+ if (event.worksheet.getSheetId() === 'review') {+ event.cancel = true;+ }+ });++ reviewSheet.setName('Locked');+ expect(reviewSheet.getSheetName()).toBe('Review');++ expect(workbook.deleteSheet(reviewSheet)).toBe(false);+ expect(workbook.getSheetBySheetId('review')?.getSheetName()).toBe('Review');+ });++ it('reports before and after events for visible worksheet presentation changes', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const baseSheet = workbook.getActiveSheet();+ const opsSheet = workbook.insertSheet('Ops', {+ sheet: {+ id: 'ops',+ rowCount: 20,+ columnCount: 10,+ },+ });+ const events: string[] = [];++ univerAPI.addEvent(univerAPI.Event.BeforeActiveSheetChange, (event) => {+ events.push(`before-active:${event.oldActiveSheet.getSheetName()}->${event.activeSheet.getSheetName()}`);+ });+ univerAPI.addEvent(univerAPI.Event.ActiveSheetChanged, (event) => {+ events.push(`active:${event.activeSheet.getSheetName()}`);+ });+ univerAPI.addEvent(univerAPI.Event.BeforeSheetMove, (event) => {+ events.push(`before-move:${event.oldIndex}->${event.newIndex}`);+ });+ univerAPI.addEvent(univerAPI.Event.BeforeSheetNameChange, (event) => {+ events.push(`before-name:${event.oldName}->${event.newName}`);+ });+ univerAPI.addEvent(univerAPI.Event.SheetNameChanged, (event) => {+ events.push(`name:${event.newName}`);+ });+ univerAPI.addEvent(univerAPI.Event.SheetTabColorChanged, (event) => {+ events.push(`tab:${event.newColor}`);+ });+ univerAPI.addEvent(univerAPI.Event.BeforeSheetHideChange, (event) => {+ events.push(`before-hide:${event.worksheet.getSheetName()}=${event.hidden}`);+ });+ univerAPI.addEvent(univerAPI.Event.BeforeGridlineEnableChange, (event) => {+ events.push(`before-grid:${event.enabled}`);+ });+ univerAPI.addEvent(univerAPI.Event.BeforeGridlineColorChange, (event) => {+ events.push(`before-grid-color:${event.color}`);+ });++ workbook.setActiveSheet(baseSheet);+ workbook.moveSheet(opsSheet, 0);+ opsSheet.setName('Operations');+ opsSheet.setTabColor('#00aa55');+ opsSheet.setHiddenGridlines(true);+ opsSheet.setGridLinesColor('#aabbcc');+ opsSheet.hideSheet();++ expect(events).toEqual([+ 'before-active:Ops->sheet1',+ 'active:sheet1',+ 'before-move:1->0',+ 'before-name:Ops->Operations',+ 'name:Operations',+ 'tab:#00aa55',+ 'before-grid:false',+ 'before-grid-color:#aabbcc',+ 'before-hide:Operations=true',+ ]);+ expect(workbook.getSheets()[0].getSheetName()).toBe('Operations');+ expect(opsSheet.isSheetHidden()).toBe(true);+ });+});diff --git a/packages/sheets/src/facade/__tests__/f-workbook.spec.ts b/packages/sheets/src/facade/__tests__/f-workbook.spec.tsindex a6acf8aa09..f6286ac308 100644--- a/packages/sheets/src/facade/__tests__/f-workbook.spec.ts+++ b/packages/sheets/src/facade/__tests__/f-workbook.spec.ts@@ -19,19 +19,32 @@ import type { FUniver } from '@univerjs/core/facade';import { ICommandService, ILogService, IUniverInstanceService, LocaleType } from '@univerjs/core';import {CopySheetCommand,+ getPrimaryForRange,InsertSheetCommand,InsertSheetMutation,+ RegisterWorksheetRangeThemeStyleCommand,+ RegisterWorksheetRangeThemeStyleMutation,RemoveSheetCommand,RemoveSheetMutation,SetHorizontalTextAlignCommand,SetRangeValuesCommand,SetRangeValuesMutation,+ SetSelectionsOperation,SetStyleCommand,SetTextWrapCommand,SetVerticalTextAlignCommand,+ SetWorkbookNameCommand,+ SetWorkbookNameMutation,SetWorksheetActiveOperation,SetWorksheetOrderCommand,SetWorksheetOrderMutation,+ SetWorksheetRangeThemeStyleCommand,+ SetWorksheetRangeThemeStyleMutation,+ SheetRangeThemeModel,+ SheetRangeThemeService,+ SheetsSelectionsService,+ UnregisterWorksheetRangeThemeStyleCommand,+ UnregisterWorksheetRangeThemeStyleMutation,} from '@univerjs/sheets';import { beforeEach, describe, expect, it, vi } from 'vitest';import { SHEETS_CUSTOM_FIELD_WARNING_MESSAGE } from '../const';@@ -49,7 +62,10 @@ describe('Test FWorkbook', () => {) => Nullable<ICellData>;beforeEach(() => {- const testBed = createFacadeTestBed();+ const testBed = createFacadeTestBed(undefined, [+ [SheetRangeThemeModel],+ [SheetRangeThemeService],+ ]);get = testBed.get;univerAPI = testBed.univerAPI;@@ -60,6 +76,7 @@ describe('Test FWorkbook', () => {commandService.registerCommand(SetVerticalTextAlignCommand);commandService.registerCommand(SetHorizontalTextAlignCommand);commandService.registerCommand(SetTextWrapCommand);+ commandService.registerCommand(SetSelectionsOperation);commandService.registerCommand(InsertSheetCommand);commandService.registerCommand(InsertSheetMutation);commandService.registerCommand(SetWorksheetActiveOperation);@@ -68,6 +85,14 @@ describe('Test FWorkbook', () => {commandService.registerCommand(CopySheetCommand);commandService.registerCommand(SetWorksheetOrderCommand);commandService.registerCommand(SetWorksheetOrderMutation);+ commandService.registerCommand(SetWorkbookNameCommand);+ commandService.registerCommand(SetWorkbookNameMutation);+ commandService.registerCommand(RegisterWorksheetRangeThemeStyleCommand);+ commandService.registerCommand(RegisterWorksheetRangeThemeStyleMutation);+ commandService.registerCommand(UnregisterWorksheetRangeThemeStyleCommand);+ commandService.registerCommand(UnregisterWorksheetRangeThemeStyleMutation);+ commandService.registerCommand(SetWorksheetRangeThemeStyleCommand);+ commandService.registerCommand(SetWorksheetRangeThemeStyleMutation);getValueByPosition = (startRow: number,@@ -185,4 +210,74 @@ describe('Test FWorkbook', () => {const sheet = workbook.create('sheet1', 10, 10);expect(sheet.getSheetName()).not.toBe('sheet1');});++ it('Workbook exposes editable workbook state, command hooks, themes, and saved snapshots', () => {+ const workbook = univerAPI.getActiveWorkbook()!;+ const commandEvents: string[] = [];+ const selections: string[][] = [];++ const beforeDisposable = workbook.onBeforeCommandExecute((command) => {+ commandEvents.push(`before:${command.id}`);+ });+ const afterDisposable = workbook.onCommandExecuted((command) => {+ commandEvents.push(`after:${command.id}`);+ });+ const selectionDisposable = workbook.onSelectionChange((ranges) => {+ selections.push(ranges.map((range) => `${range.startRow}:${range.startColumn}-${range.endRow}:${range.endColumn}`));+ });++ workbook.setName('Finance planning');+ expect(workbook.getName()).toBe('Finance planning');+ expect(workbook.getId()).toBe('test');+ expect(workbook.getWorkbook().getUnitId()).toBe('test');+ expect(workbook.save().name).toBe('Finance planning');+ expect(workbook.getUrl()).toContain('localhost');++ workbook.setEditable(false);+ expect(workbook.getWorkbookPermission().canEdit()).toBe(false);+ workbook.setEditable(true);+ expect(workbook.getWorkbookPermission().canEdit()).toBe(true);++ const activeSheet = workbook.getActiveSheet();+ workbook.setActiveRange(activeSheet.getRange('B2:C3'));+ const selectionRange = activeSheet.getRange('B2:C3').getRange();+ get(SheetsSelectionsService).setSelections([+ {+ range: selectionRange,+ primary: getPrimaryForRange(selectionRange, activeSheet.getSheet()),+ style: null,+ },+ ], 2 as never);+ expect(workbook.getActiveRange()?.getA1Notation()).toBe('B2:C3');+ expect(workbook.getActiveCell()?.getA1Notation()).toBe('B2');++ expect(selections).toContainEqual(['1:1-2:2']);+ expect(commandEvents).toContain(`before:${SetWorkbookNameCommand.id}`);+ expect(commandEvents).toContain(`after:${SetWorkbookNameCommand.id}`);++ const planningTheme = workbook.createRangeThemeStyle('planning-theme', {+ secondRowStyle: {+ bg: { rgb: '#eef5ff' },+ },+ });+ expect(workbook.getRegisteredRangeThemes()).toContain('default');+ workbook.registerRangeTheme(planningTheme);+ activeSheet.getRange('A1:B2').useThemeStyle('planning-theme');+ expect(activeSheet.getRange('A1:B2').getUsedThemeStyle()).toBe('planning-theme');+ workbook.unregisterRangeTheme('planning-theme');++ workbook.addStyles({+ 'planning-style': {+ fs: 18,+ bg: { rgb: '#ffeecc' },+ },+ });+ activeSheet.getRange('D1').setValue({ v: 'Styled', s: 'planning-style' });+ expect(activeSheet.getRange('D1').getCellStyleData('cell')?.fs).toBe(18);+ workbook.removeStyles(['planning-style']);++ beforeDisposable.dispose();+ afterDisposable.dispose();+ selectionDisposable.dispose();+ });});diff --git a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets/src/facade/__tests__/f-worksheet.spec.tsindex bfcad4ab0d..89ddee8465 100644--- a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts+++ b/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts@@ -14,12 +14,13 @@* limitations under the License.*/-import type { Injector, Workbook } from '@univerjs/core';+import type { Workbook } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';import {ICommandService,IConfirmService,ILogService,+ Injector,IUniverInstanceService,RANGE_TYPE,TestConfirmService,@@ -29,6 +30,9 @@ import {AddWorksheetMergeCommand,AddWorksheetMergeMutation,CancelFrozenCommand,+ ClearSelectionAllCommand,+ ClearSelectionContentCommand,+ ClearSelectionFormatCommand,InsertColByRangeCommand,InsertColCommand,InsertColMutation,@@ -71,9 +75,11 @@ import {SetTextWrapCommand,SetVerticalTextAlignCommand,SetWorksheetColWidthMutation,+ SetWorksheetDefaultStyleMutation,SetWorksheetRowHeightMutation,SetWorksheetRowIsAutoHeightCommand,SetWorksheetRowIsAutoHeightMutation,+ SheetSkeletonService,SheetsSelectionsService,} from '@univerjs/sheets';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -101,6 +107,11 @@ describe('Test FWorksheet', () => {commandService.registerCommand(SetVerticalTextAlignCommand);commandService.registerCommand(SetHorizontalTextAlignCommand);commandService.registerCommand(SetTextWrapCommand);+ commandService.registerCommand(ClearSelectionAllCommand);+ commandService.registerCommand(ClearSelectionContentCommand);+ commandService.registerCommand(ClearSelectionFormatCommand);+ commandService.registerCommand(SetWorksheetDefaultStyleMutation);+ get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');// rowcommandService.registerCommand(InsertRowCommand);@@ -201,6 +212,40 @@ describe('Test FWorksheet', () => {expect(range).toBeDefined();});+ it('Worksheet manages sheet-level styles and clears content or formats independently', () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getSheetByName('sheet1')!;++ expect(activeSheet.getSheet().getSheetId()).toBe('sheet1');+ expect(activeSheet.getWorkbook().getUnitId()).toBe('test');+ expect(activeSheet.getInject()).toBe(get(Injector));++ activeSheet.setDefaultStyle({ ff: 'Inter', fs: 13 });+ activeSheet.setRowDefaultStyle(4, { fs: 16, bg: { rgb: '#fff2cc' } });+ activeSheet.setColumnDefaultStyle(2, { ff: 'Mono', cl: { rgb: '#3366ff' } });++ expect(activeSheet.getDefaultStyle()).toMatchObject({ ff: 'Inter', fs: 13 });+ expect(activeSheet.getRowDefaultStyle(4)).toMatchObject({ fs: 16, bg: { rgb: '#fff2cc' } });+ expect(activeSheet.getColumnDefaultStyle(2)).toMatchObject({ ff: 'Mono', cl: { rgb: '#3366ff' } });+ expect(activeSheet.getRowDefaultStyle(4, true)).toMatchObject({ fs: 16, bg: { rgb: '#fff2cc' } });+ expect(activeSheet.getColumnDefaultStyle(2, true)).toMatchObject({ ff: 'Mono', cl: { rgb: '#3366ff' } });++ const cell = activeSheet.getRange('A1');+ cell.setValue('Budget').setBackground('#ddeeff');+ activeSheet.clear({ contentsOnly: true });+ expect(cell.getValue()).toBeNull();+ expect(cell.getBackground()).toBe('#ddeeff');++ cell.setValue('Budget');+ activeSheet.clear({ formatOnly: true });+ expect(cell.getValue()).toBe('Budget');+ expect(cell.getBackground()).not.toBe('#ddeeff');++ cell.setValue('Budget').setBackground('#ddeeff');+ activeSheet.clear();+ expect(cell.getValue()).toBeNull();+ expect(cell.getBackground()).not.toBe('#ddeeff');+ });+it('Worksheet getMaxColumns', async () => {const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');expect(activeSheet?.getMaxColumns()).toBe(100);diff --git a/packages/sheets/src/facade/f-univer.ts b/packages/sheets/src/facade/f-univer.tsindex f86ac45fdf..c33e59e4a1 100644--- a/packages/sheets/src/facade/f-univer.ts+++ b/packages/sheets/src/facade/f-univer.ts@@ -521,10 +521,14 @@ export class FUniverSheetsMixin extends FUniver implements IFUniverSheetsMixin {() => commandService.onCommandExecuted((commandInfo) => {if (commandInfo.id === InsertSheetCommand.id) {const params = commandInfo.params as IInsertSheetCommandParams;- const target = this.getSheetCommandTarget(params);- if (!target) return;-- const { workbook, worksheet } = target;+ const workbook = params?.unitId ? this.getWorkbook(params.unitId) : this.getActiveWorkbook();+ if (!workbook) return;++ const sheets = workbook.getSheets();+ const worksheet = params?.sheet?.id+ ? workbook.getSheetBySheetId(params.sheet.id)+ : sheets[params?.index ?? sheets.length - 1];+ if (!worksheet) return;const eventParams: ISheetCreatedEventParams = {workbook,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.tsindex 56c432e3cc..c808a27998 100644--- a/packages/sheets/src/services/__tests__/lazy-execute-schedule.service.spec.ts+++ b/packages/sheets/src/services/__tests__/lazy-execute-schedule.service.spec.ts@@ -16,6 +16,7 @@import type { IMutationInfo } from '@univerjs/core';import type { ISetRangeValuesMutationParams } from '../../commands/mutations/set-range-values.mutation';+import { ICommandService, Injector, IUniverInstanceService } from '@univerjs/core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SheetLazyExecuteScheduleService } from '../lazy-execute-schedule.service';@@ -33,34 +34,37 @@ function createMutation(unitId: string, subUnitId: string): IMutationInfo<ISetRa}describe('SheetLazyExecuteScheduleService', () => {- let commandService: {- syncExecuteCommand: ReturnType<typeof vi.fn>;- };-let getSheetBySheetId: ReturnType<typeof vi.fn>;- let instanceService: {- getUnit: ReturnType<typeof vi.fn>;- };+ class TestCommandService {+ syncExecuteCommand = vi.fn();+ }++ class TestUniverInstanceService {+ getUnit = vi.fn(() => ({+ getSheetBySheetId,+ }));+ }+ let commandService: TestCommandService;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());+ vi.stubGlobal('window', {+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ });- service = new SheetLazyExecuteScheduleService(commandService as never, instanceService as never);+ const injector = new Injector();+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([SheetLazyExecuteScheduleService]);+ commandService = injector.get(ICommandService) as unknown as TestCommandService;+ service = injector.get(SheetLazyExecuteScheduleService);});afterEach(() => {diff --git a/packages/sheets/src/services/numfmt/__tests__/numfmt.service.spec.ts b/packages/sheets/src/services/numfmt/__tests__/numfmt.service.spec.tsnew file mode 100644index 0000000000..87d3d530c2--- /dev/null+++ b/packages/sheets/src/services/numfmt/__tests__/numfmt.service.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 {+ ContextService,+ DesktopLogService,+ IContextService,+ ILogService,+ Injector,+ IResourceManagerService,+ IUniverInstanceService,+ ResourceManagerService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { NumfmtService } from '../numfmt.service';++function createService() {+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IResourceManagerService, { useClass: ResourceManagerService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([NumfmtService]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: { 'sheet-1': { id: 'sheet-1' } },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);++ return injector.get(NumfmtService);+}++describe('NumfmtService', () => {+ it('sets, reads, and deletes number format patterns on worksheet cells', () => {+ const service = createService();+ const range = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };++ service.setValues('unit-1', 'sheet-1', [{ ranges: [range], pattern: 'yyyy-mm-dd' }]);++ expect(service.getValue('unit-1', 'sheet-1', 0, 0)).toEqual({ pattern: 'yyyy-mm-dd' });++ service.deleteValues('unit-1', 'sheet-1', [range]);+ expect(service.getValue('unit-1', 'sheet-1', 0, 0)).toBeNull();+ });+});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.tsindex bfa2216943..41020f5eed 100644--- a/packages/sheets/src/services/selections/__tests__/ref-selections.service.spec.ts+++ b/packages/sheets/src/services/selections/__tests__/ref-selections.service.spec.ts@@ -16,6 +16,7 @@import type { Workbook } from '@univerjs/core';import type { WorkbookSelectionModel } from '../selection-data-model';+import { Injector, IUniverInstanceService } from '@univerjs/core';import { firstValueFrom, Subject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { RefSelectionsService } from '../ref-selections.service';@@ -78,22 +79,18 @@ describe('RefSelectionsService', () => {let add$: Subject<{ unit: Workbook }>;let disposed$: Subject<Workbook>;- let instanceService: {- getAllUnitsForType: ReturnType<typeof vi.fn>;- getTypeOfUnitAdded$: ReturnType<typeof vi.fn>;- getTypeOfUnitDisposed$: ReturnType<typeof vi.fn>;- };++ class TestUniverInstanceService {+ getAllUnitsForType = vi.fn(() => [workbookA]);+ getTypeOfUnitAdded$ = vi.fn(() => add$.asObservable());+ getTypeOfUnitDisposed$ = vi.fn(() => disposed$.asObservable());+ }let service: TestRefSelectionsService;beforeEach(() => {add$ = new Subject<{ unit: Workbook }>();disposed$ = new Subject<Workbook>();- instanceService = {- getAllUnitsForType: vi.fn(() => [workbookA]),- getTypeOfUnitAdded$: vi.fn(() => add$.asObservable()),- getTypeOfUnitDisposed$: vi.fn(() => disposed$.asObservable()),- };});afterEach(() => {@@ -103,7 +100,10 @@ describe('RefSelectionsService', () => {});it('merges all workbook selection streams and handles workbook lifecycle', () => {- service = new TestRefSelectionsService(instanceService as never);+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([TestRefSelectionsService]);+ service = injector.get(TestRefSelectionsService);const startEvents: unknown[] = [];const movingEvents: unknown[] = [];@@ -138,7 +138,10 @@ describe('RefSelectionsService', () => {});it('clears workbook state and resets streams on dispose', async () => {- service = new TestRefSelectionsService(instanceService as never);+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);+ injector.add([TestRefSelectionsService]);+ service = injector.get(TestRefSelectionsService);const modelA = service.modelMap.get('wb-a')!;service.dispose();diff --git a/packages/sheets/src/services/selections/__tests__/selection.service.spec.ts b/packages/sheets/src/services/selections/__tests__/selection.service.spec.tsnew file mode 100644index 0000000000..f0c1417c72--- /dev/null+++ b/packages/sheets/src/services/selections/__tests__/selection.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 {+ ContextService,+ DesktopLogService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ UniverInstanceService,+ Workbook,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { SheetsSelectionsService } from '../selection.service';++function createService() {+ const injector = new Injector();+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([SheetsSelectionsService]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const workbook = injector.createInstance(Workbook, {+ id: 'unit-1',+ sheets: { 'sheet-1': { id: 'sheet-1' } },+ sheetOrder: ['sheet-1'],+ });+ univerInstanceService.__addUnit(workbook);+ univerInstanceService.focusUnit('unit-1');++ return injector.get(SheetsSelectionsService);+}++describe('SheetsSelectionsService', () => {+ it('sets and clears the active worksheet selections', () => {+ const service = createService();+ const selection = {+ range: { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 },+ primary: { actualRow: 1, actualColumn: 2, startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 },+ };++ service.setSelections([selection] as never);++ expect(service.getCurrentSelections()).toEqual([selection]);+ expect(service.getCurrentLastSelectionPrimaryCell()).toEqual(selection.primary);++ service.clearCurrentSelections();+ expect(service.getCurrentSelections()).toEqual([]);+ });++ it('detects overlapping selections on the active sheet', () => {+ const service = createService();++ service.setSelections([{+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },+ primary: null,+ }, {+ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },+ primary: null,+ }] as never);++ expect(service.isOverlapping()).toBe(true);+ });+});diff --git a/packages/slides-ui/src/commands/operations/__tests__/slide-element.operation.spec.ts b/packages/slides-ui/src/commands/operations/__tests__/slide-element.operation.spec.tsnew file mode 100644index 0000000000..9cb04f3e4b--- /dev/null+++ b/packages/slides-ui/src/commands/operations/__tests__/slide-element.operation.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 { IPageElement, ISlideData, ISlidePage, SlideDataModel } from '@univerjs/slides';+import { ICommandService, IUniverInstanceService, LocaleService, Univer, UniverInstanceType } from '@univerjs/core';+import { ObjectType } from '@univerjs/engine-render';+import { BasicShapes, PageElementType, PageType, UniverSlidesPlugin } from '@univerjs/slides';+import { DesktopSidebarService, ILocalFileService, ISidebarService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { CanvasView } from '../../../controllers/canvas-view';+import { ActivateSlidePageOperation } from '../activate.operation';+import { AppendSlideOperation } from '../append-slide.operation';+import { DeleteSlideElementOperation } from '../delete-element.operation';+import { InsertSlideFloatImageCommand } from '../insert-image.operation';+import {+ InsertSlideShapeEllipseCommand,+ InsertSlideShapeEllipseOperation,+ InsertSlideShapeRectangleCommand,+ InsertSlideShapeRectangleOperation,+ ToggleSlideEditSidebarOperation,+} from '../insert-shape.operation';+import { SlideAddTextCommand, SlideAddTextOperation } from '../insert-text.operation';+import { SetSlidePageThumbOperation } from '../set-thumb.operation';+import { UpdateSlideElementOperation } from '../update-element.operation';++const unitId = 'slide-command-unit';+const pageId = 'page-1';++class TestCanvasView {+ static thumbUnitIds: string[] = [];+ static activatedPages: string[] = [];+ static activeObjectIds: string[] = [];+ static clearedControls = 0;+ static activateCreatedObject = false;++ constructor(@IUniverInstanceService private readonly _instanceService: IUniverInstanceService) {}++ static reset() {+ this.thumbUnitIds = [];+ this.activatedPages = [];+ this.activeObjectIds = [];+ this.clearedControls = 0;+ this.activateCreatedObject = false;+ }++ createObjectToPage() {+ if (TestCanvasView.activateCreatedObject) {+ return { oKey: 'created-object' } as never;+ }++ return null;+ }++ setObjectActiveByPage(object: { oKey?: string }) {+ TestCanvasView.activeObjectIds.push(object.oKey ?? '');+ }++ removeObjectById() {+ // render boundary is not part of the data-model behavior under test+ }++ appendPage(unitId: string) {+ const slide = this._instanceService.getUnit<SlideDataModel>(unitId);+ const page = slide?.getBlankPage();+ if (page) {+ slide?.appendPage(page);+ }+ }++ activePage(pageId: string, unitId: string) {+ const slide = this._instanceService.getUnit<SlideDataModel>(unitId);+ slide?.setActivePage(slide.getPage(pageId) ?? null);+ TestCanvasView.activatedPages.push(pageId);+ }++ getRenderUnitByPageId(pageId: string, unitId: string) {+ const slide = this._instanceService.getUnit<SlideDataModel>(unitId);+ if (!slide?.getPage(pageId)) {+ return null;+ }++ return {+ scene: {+ getTransformer: () => ({+ clearControls: () => {+ TestCanvasView.clearedControls += 1;+ },+ }),+ },+ };+ }++ createThumbs(unitId: string) {+ TestCanvasView.thumbUnitIds.push(unitId);+ }+}++class TestLocalFileService implements ILocalFileService {+ openFile(): Promise<File[]> {+ return Promise.resolve([]);+ }++ downloadFile(): void {+ // not used by slide image insertion+ }+}++function createSlideSnapshot(): Partial<ISlideData> {+ return {+ id: unitId,+ title: 'Command test deck',+ pageSize: { width: 960, height: 540 },+ body: {+ pageOrder: [pageId, 'page-2'],+ pages: {+ [pageId]: {+ id: pageId,+ pageType: PageType.SLIDE,+ zIndex: 1,+ title: 'Overview',+ description: '',+ pageBackgroundFill: { rgb: '#ffffff' },+ pageElements: {+ 'title-text': {+ id: 'title-text',+ zIndex: 1,+ left: 40,+ top: 40,+ width: 400,+ height: 60,+ title: 'Title',+ description: '',+ type: PageElementType.TEXT,+ richText: { text: 'Quarterly review' },+ },+ 'old-shape': {+ id: 'old-shape',+ zIndex: 2,+ left: 100,+ top: 120,+ width: 80,+ height: 80,+ title: 'Old shape',+ description: '',+ type: PageElementType.SHAPE,+ shape: {+ shapeType: BasicShapes.Rect,+ text: '',+ shapeProperties: {+ shapeBackgroundFill: { rgb: 'rgb(0,0,255)' },+ },+ },+ },+ },+ },+ 'page-2': {+ id: 'page-2',+ pageType: PageType.SLIDE,+ zIndex: 2,+ title: 'Appendix',+ description: '',+ pageBackgroundFill: { rgb: '#ffffff' },+ pageElements: {},+ },+ },+ },+ };+}++function getActivePage(slide: SlideDataModel): ISlidePage {+ return slide.getActivePage()!;+}++function getElementIds(page: ISlidePage): string[] {+ const ids: string[] = [];+ for (const id in page.pageElements) {+ ids.push(id);+ }+ return ids;+}++function findElementAddedAfter(page: ISlidePage, beforeIds: string[]): IPageElement {+ for (const id in page.pageElements) {+ if (!beforeIds.includes(id)) {+ return page.pageElements[id];+ }+ }++ throw new Error('No new slide element was added.');+}++describe('slide element operations', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let slide: SlideDataModel;++ beforeEach(() => {+ univer = new Univer();+ univer.registerPlugin(UniverSlidesPlugin);+ TestCanvasView.reset();++ const injector = univer.__getInjector();+ injector.add([CanvasView, { useClass: TestCanvasView as never }]);+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ injector.add([ILocalFileService, { useClass: TestLocalFileService }]);++ slide = univer.createUnit<ISlideData, SlideDataModel>(UniverInstanceType.UNIVER_SLIDE, createSlideSnapshot());+ injector.get(IUniverInstanceService).focusUnit(unitId);+ commandService = injector.get(ICommandService);+ commandService.registerCommand(SlideAddTextOperation);+ commandService.registerCommand(SlideAddTextCommand);+ commandService.registerCommand(InsertSlideShapeRectangleOperation);+ commandService.registerCommand(InsertSlideShapeRectangleCommand);+ commandService.registerCommand(InsertSlideShapeEllipseOperation);+ commandService.registerCommand(InsertSlideShapeEllipseCommand);+ commandService.registerCommand(UpdateSlideElementOperation);+ commandService.registerCommand(DeleteSlideElementOperation);+ commandService.registerCommand(AppendSlideOperation);+ commandService.registerCommand(ActivateSlidePageOperation);+ commandService.registerCommand(SetSlidePageThumbOperation);+ commandService.registerCommand(InsertSlideFloatImageCommand);+ commandService.registerCommand(ToggleSlideEditSidebarOperation);+ injector.get(LocaleService).load({});+ });++ afterEach(() => {+ univer.dispose();+ });++ it('adds a text box to the active slide with the entered content', async () => {+ const page = getActivePage(slide);+ const beforeIds = getElementIds(page);++ const result = await commandService.executeCommand(SlideAddTextOperation.id, {+ unitId,+ text: 'Revenue is up',+ });++ expect(result).toBe(true);+ const element = findElementAddedAfter(page, beforeIds);+ expect(element).toMatchObject({+ zIndex: 3,+ type: PageElementType.TEXT,+ richText: {+ text: 'Revenue is up',+ fs: 30,+ },+ });+ });++ it('adds rectangle and ellipse shapes to the active slide', async () => {+ const page = getActivePage(slide);+ const beforeRectangleIds = getElementIds(page);++ await commandService.executeCommand(InsertSlideShapeRectangleCommand.id);+ const rectangle = findElementAddedAfter(page, beforeRectangleIds);++ const beforeEllipseIds = getElementIds(page);+ await commandService.executeCommand(InsertSlideShapeEllipseCommand.id);+ const ellipse = findElementAddedAfter(page, beforeEllipseIds);++ expect(rectangle).toMatchObject({+ zIndex: 3,+ type: PageElementType.SHAPE,+ shape: {+ shapeType: BasicShapes.Rect,+ },+ });+ expect(ellipse).toMatchObject({+ zIndex: 4,+ type: PageElementType.SHAPE,+ shape: {+ shapeType: BasicShapes.Ellipse,+ },+ });+ });++ it('uses the focused slide when adding text from the user command', async () => {+ const page = getActivePage(slide);+ const beforeIds = getElementIds(page);++ const result = await commandService.executeCommand(SlideAddTextCommand.id);++ expect(result).toBe(true);+ const element = findElementAddedAfter(page, beforeIds);+ expect(element).toMatchObject({+ type: PageElementType.TEXT,+ richText: { text: 'A New Text' },+ });+ });++ it('updates an existing slide element without replacing the rest of its content', async () => {+ const result = await commandService.executeCommand(UpdateSlideElementOperation.id, {+ unitId,+ oKey: 'title-text',+ props: {+ left: 120,+ title: 'Updated title box',+ },+ });++ expect(result).toBe(true);+ expect(slide.getElement(pageId, 'title-text')).toMatchObject({+ left: 120,+ title: 'Updated title box',+ type: PageElementType.TEXT,+ richText: { text: 'Quarterly review' },+ });+ });++ it('removes the selected element from the active slide', async () => {+ const result = await commandService.executeCommand(DeleteSlideElementOperation.id, {+ unitId,+ id: 'old-shape',+ });++ expect(result).toBe(true);+ expect(slide.getElement(pageId, 'old-shape')).toBeUndefined();+ expect(slide.getElement(pageId, 'title-text')).toBeDefined();+ });++ it('appends a new page after the active slide', async () => {+ expect(slide.getPageOrder()).toEqual([pageId, 'page-2']);++ const result = await commandService.executeCommand(AppendSlideOperation.id, { unitId });++ expect(result).toBe(true);+ expect(slide.getPageOrder()).toHaveLength(3);+ expect(slide.getPageOrder()?.[0]).toBe(pageId);+ expect(slide.getPageOrder()?.[1]).not.toBe('page-2');+ expect(slide.getPageOrder()?.[2]).toBe('page-2');+ });++ it('activates another page after clearing the current page controls', async () => {+ const result = await commandService.executeCommand(ActivateSlidePageOperation.id, {+ unitId,+ id: 'page-2',+ });++ expect(result).toBe(true);+ expect(slide.getActivePage()?.id).toBe('page-2');+ expect(TestCanvasView.clearedControls).toBe(1);+ expect(TestCanvasView.activatedPages).toEqual(['page-2']);+ });++ it('does not activate a missing page renderer', async () => {+ const result = await commandService.executeCommand(ActivateSlidePageOperation.id, {+ unitId: 'missing-slide',+ id: 'page-2',+ });++ expect(result).toBe(false);+ expect(slide.getActivePage()?.id).toBe(pageId);+ });++ it('creates thumbnails for the current deck', async () => {+ const result = await commandService.executeCommand(SetSlidePageThumbOperation.id, { unitId });++ expect(result).toBe(true);+ expect(TestCanvasView.thumbUnitIds).toEqual([unitId]);+ });++ it('keeps the deck unchanged when the user cancels image selection', async () => {+ const page = getActivePage(slide);+ const beforeIds = getElementIds(page);++ const result = await commandService.executeCommand(InsertSlideFloatImageCommand.id);++ expect(result).toBe(false);+ expect(getElementIds(page)).toEqual(beforeIds);+ });++ it('opens and closes the slide edit sidebar for the selected object type', async () => {+ const sidebarService = univer.__getInjector().get(ISidebarService);+ const objectTypes = [+ { type: ObjectType.RECT, title: 'slides-ui.sidebar.shape' },+ { type: ObjectType.IMAGE, title: 'slides-ui.sidebar.image' },+ { type: ObjectType.RICH_TEXT, title: 'slides-ui.sidebar.text' },+ ];++ for (const objectType of objectTypes) {+ await commandService.executeCommand(ToggleSlideEditSidebarOperation.id, {+ visible: '1',+ objectType: objectType.type,+ });++ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options.header?.title).toBe(objectType.title);+ }++ await commandService.executeCommand(ToggleSlideEditSidebarOperation.id, {+ visible: '',+ objectType: ObjectType.RECT,+ });++ expect(sidebarService.visible).toBe(false);+ });+});diff --git a/packages/slides-ui/src/views/panels/__tests__/ArrangePanel.spec.tsx b/packages/slides-ui/src/views/panels/__tests__/ArrangePanel.spec.tsxnew file mode 100644index 0000000000..2817b8c980--- /dev/null+++ b/packages/slides-ui/src/views/panels/__tests__/ArrangePanel.spec.tsx@@ -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 type { ISlideData, SlideDataModel } from '@univerjs/slides';+import type { Root } from 'react-dom/client';+import { ICommandService, IUniverInstanceService, LocaleService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';+import { BasicShapes, PageElementType, PageType, UniverSlidesPlugin } from '@univerjs/slides';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { UpdateSlideElementOperation } from '../../../commands/operations/update-element.operation';+import { CanvasView } from '../../../controllers/canvas-view';+import locale from '../../../locale/en-US';+import ArrangePanel from '../ArrangePanel';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'arrange-panel-unit';+const PAGE_ID = 'page-1';+const SELECTED_ID = 'selected-shape';++class TestSlideObject {+ constructor(+ readonly oKey: string,+ public zIndex: number+ ) {}++ setProps(props: { zIndex?: number }) {+ if (typeof props.zIndex === 'number') {+ this.zIndex = props.zIndex;+ }+ }+}++class TestTransformer {+ constructor(private readonly _object: TestSlideObject) {}++ getSelectedObjectMap() {+ return new Map([[this._object.oKey, this._object]]);+ }+}++class TestScene {+ private readonly _transformer: TestTransformer;++ constructor(private readonly _objects: TestSlideObject[], selectedObject: TestSlideObject) {+ this._transformer = new TestTransformer(selectedObject);+ }++ getTransformer() {+ return this._transformer;+ }++ getAllObjects() {+ return this._objects;+ }+}++class TestCanvasView {+ static scene: TestScene | null = null;++ static reset() {+ this.scene = null;+ }++ getRenderUnitByPageId() {+ return TestCanvasView.scene+ ? { scene: TestCanvasView.scene }+ : null;+ }+}++function createSlideSnapshot(): Partial<ISlideData> {+ return {+ id: UNIT_ID,+ title: 'Arrange panel deck',+ pageSize: { width: 960, height: 540 },+ body: {+ pageOrder: [PAGE_ID],+ pages: {+ [PAGE_ID]: {+ id: PAGE_ID,+ pageType: PageType.SLIDE,+ zIndex: 1,+ title: 'Slide',+ description: '',+ pageBackgroundFill: { rgb: '#ffffff' },+ pageElements: {+ [SELECTED_ID]: {+ id: SELECTED_ID,+ zIndex: 2,+ left: 100,+ top: 100,+ width: 120,+ height: 80,+ title: 'Selected shape',+ description: '',+ type: PageElementType.SHAPE,+ shape: {+ shapeType: BasicShapes.Rect,+ text: '',+ shapeProperties: {+ shapeBackgroundFill: { rgb: '#4472c4' },+ },+ },+ },+ },+ },+ },+ },+ };+}++function createPanelTestBed() {+ const univer = new Univer();+ univer.registerPlugin(UniverSlidesPlugin);++ const injector = univer.__getInjector();+ injector.add([CanvasView, { useClass: TestCanvasView as never }]);++ const slide = univer.createUnit<ISlideData, SlideDataModel>(UniverInstanceType.UNIVER_SLIDE, createSlideSnapshot());+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);++ const commandService = injector.get(ICommandService);+ commandService.registerCommand(UpdateSlideElementOperation);+ injector.get(LocaleService).load({+ [LocaleType.EN_US]: locale,+ });+ injector.get(LocaleService).setLocale(LocaleType.EN_US);++ return { univer, injector, slide };+}++function createRenderScene(selectedZIndex: number, otherZIndexes: number[]) {+ const selectedObject = new TestSlideObject(SELECTED_ID, selectedZIndex);+ const objects = [+ selectedObject,+ ...otherZIndexes.map((zIndex, index) => new TestSlideObject(`object-${index}`, zIndex)),+ ];+ TestCanvasView.scene = new TestScene(objects, selectedObject);++ return selectedObject;+}++function renderPanel(root: Root, testBed: ReturnType<typeof createPanelTestBed>) {+ act(() => {+ root.render(+ <RediContext.Provider value={{ injector: testBed.injector }}>+ <ArrangePanel pageId={PAGE_ID} unitId={UNIT_ID} />+ </RediContext.Provider>+ );+ });+}++function clickButton(container: HTMLElement, text: string) {+ const button = Array.from(container.querySelectorAll('button'))+ .find((button) => button.textContent?.includes(text));+ if (!button) {+ throw new Error(`Button not found: ${text}`);+ }++ act(() => {+ button.click();+ });+}++describe('ArrangePanel', () => {+ let root: Root | undefined;+ let container: HTMLDivElement | undefined;+ let currentTestBed: ReturnType<typeof createPanelTestBed> | undefined;++ beforeEach(() => {+ TestCanvasView.reset();+ });++ afterEach(() => {+ act(() => {+ root?.unmount();+ });+ container?.remove();+ currentTestBed?.univer.dispose();+ root = undefined;+ container = undefined;+ currentTestBed = undefined;+ });++ it('moves the selected slide element above every rendered object', () => {+ currentTestBed = createPanelTestBed();+ const selectedObject = createRenderScene(2, [1, 4]);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ renderPanel(root, currentTestBed);++ clickButton(container, 'Bring to Front');++ expect(selectedObject.zIndex).toBe(5);+ expect(currentTestBed.slide.getElement(PAGE_ID, SELECTED_ID)).toMatchObject({+ zIndex: 5,+ });+ });++ it('moves the selected slide element one layer forward', () => {+ currentTestBed = createPanelTestBed();+ const selectedObject = createRenderScene(2, [1, 4]);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ renderPanel(root, currentTestBed);++ clickButton(container, 'Bring Forward');++ expect(selectedObject.zIndex).toBe(3);+ expect(currentTestBed.slide.getElement(PAGE_ID, SELECTED_ID)).toMatchObject({+ zIndex: 3,+ });+ });++ it('moves the selected slide element behind every rendered object', () => {+ currentTestBed = createPanelTestBed();+ const selectedObject = createRenderScene(2, [3, 5]);+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ renderPanel(root, currentTestBed);++ clickButton(container, 'Send to Back');++ expect(selectedObject.zIndex).toBe(-1);+ expect(currentTestBed.slide.getElement(PAGE_ID, SELECTED_ID)).toMatchObject({+ zIndex: -1,+ });+ });+});diff --git a/packages/thread-comment-ui/package.json b/packages/thread-comment-ui/package.jsonindex c8d6cebafb..e5c5a9f0cc 100644--- a/packages/thread-comment-ui/package.json+++ b/packages/thread-comment-ui/package.json@@ -83,6 +83,7 @@},"devDependencies": {"@univerjs-infra/shared": "workspace:*",+ "@univerjs/engine-render": "workspace:*","postcss": "^8.5.15","react": "18.3.1","rxjs": "^7.8.2",diff --git a/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.spec.ts b/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.spec.tsnew file mode 100644index 0000000000..805e030357--- /dev/null+++ b/packages/thread-comment-ui/src/commands/operations/__tests__/comment.operations.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 { ICommandService, Univer } from '@univerjs/core';+import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { ThreadCommentPanelService } from '../../../services/thread-comment-panel.service';+import { SetActiveCommentOperation } from '../comment.operations';++describe('SetActiveCommentOperation', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let panelService: ThreadCommentPanelService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ injector.add([ThreadCommentPanelService]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(SetActiveCommentOperation);+ panelService = injector.get(ThreadCommentPanelService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('activates the thread comment selected by the user', async () => {+ const activeComment = {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ commentId: 'comment-1',+ };++ const result = await commandService.executeCommand(SetActiveCommentOperation.id, activeComment);++ expect(result).toBe(true);+ expect(panelService.activeCommentId).toEqual(activeComment);+ });++ it('clears active thread comment when the selection is reset', async () => {+ await commandService.executeCommand(SetActiveCommentOperation.id, {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ commentId: 'comment-1',+ });++ const result = await commandService.executeCommand(SetActiveCommentOperation.id);++ expect(result).toBe(true);+ expect(panelService.activeCommentId).toBeUndefined();+ });+});diff --git a/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts b/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.tsindex 4f7f831d69..08b803c102 100644--- a/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts+++ b/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts@@ -14,24 +14,50 @@* limitations under the License.*/-import type { ISidebarMethodOptions } from '@univerjs/ui';-import { Injector, IUniverInstanceService } from '@univerjs/core';-import { ISidebarService } from '@univerjs/ui';-import { of, Subject } from 'rxjs';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { IWorkbookData } from '@univerjs/core';+import { IUniverInstanceService, LocaleType, Univer, UniverInstanceType } from '@univerjs/core';+import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { ThreadCommentPanelService } from '../thread-comment-panel.service';+const workbookData: IWorkbookData = {+ id: 'panel-service-workbook',+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'panel service workbook',+ sheetOrder: ['sheet-1'],+ styles: {},+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet 1',+ cellData: {},+ },+ },+};+describe('ThreadCommentPanelService', () => {+ let univer: Univer;let service: ThreadCommentPanelService;- let sidebarOptions$: Subject<ISidebarMethodOptions>;+ let sidebarService: ISidebarService;+ let univerInstanceService: IUniverInstanceService;beforeEach(() => {- sidebarOptions$ = new Subject();- const injector = new Injector();- injector.add([ISidebarService, { useValue: { sidebarOptions$, close: vi.fn() } as unknown as ISidebarService }]);- injector.add([IUniverInstanceService, { useValue: { getCurrentTypeOfUnit$: () => of({}) } as unknown as IUniverInstanceService }]);+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);injector.add([ThreadCommentPanelService]);++ univer.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData);+ univerInstanceService = injector.get(IUniverInstanceService);+ univerInstanceService.focusUnit(workbookData.id);+service = injector.get(ThreadCommentPanelService);+ sidebarService = injector.get(ISidebarService);+ });++ afterEach(() => {+ univer.dispose();});it('hides the comment panel when the host sidebar closes', () => {@@ -39,7 +65,8 @@ describe('ThreadCommentPanelService', () => {service.panelVisible$.subscribe((visible) => visibleStates.push(visible));service.setPanelVisible(true);- sidebarOptions$.next({ visible: false });+ sidebarService.open({});+ sidebarService.close();expect(service.panelVisible).toBe(false);expect(visibleStates).toEqual([false, true, false]);@@ -54,4 +81,14 @@ describe('ThreadCommentPanelService', () => {expect(service.activeCommentId).toEqual({ unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'c-1', trigger: 'cell' });expect(activeComments.at(-1)).toEqual({ unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'c-1', trigger: 'cell' });});++ it('closes the sidebar when the current sheet is removed', () => {+ sidebarService.open({});+ service.setPanelVisible(true);++ univerInstanceService.disposeUnit(workbookData.id);++ expect(sidebarService.visible).toBe(false);+ expect(service.panelVisible).toBe(false);+ });});diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsx b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsxindex 90b91fc6bd..50e54d96f2 100644--- a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsx+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/index.spec.tsx@@ -14,368 +14,559 @@* limitations under the License.*/-import type { ButtonHTMLAttributes, FormEvent } from 'react';+import type {+ Dependency,+ ICommand,+ IDisposable,+ IDocumentBody,+ IDocumentData,+ Nullable,+} from '@univerjs/core';+import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';+import type { IShortcutItem } from '@univerjs/ui';+import type { FormEvent } from 'react';import type { Root } from 'react-dom/client';-import { UniverInstanceType } from '@univerjs/core';-import { act, createRef, useEffect } from 'react';+import {+ CommandService,+ CommandType,+ ConfigService,+ ContextService,+ createIdentifier,+ DesktopLogService,+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ LogLevel,+ toDisposable,+ UniverInstanceType,+} from '@univerjs/core';+import { IEditorService } from '@univerjs/docs-ui';+import { IShortcutService, ISidebarService, RediContext } from '@univerjs/ui';+import { act, createRef } from 'react';import { createRoot } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SetActiveCommentOperation } from '../../../commands/operations/comment.operations';+import { ThreadCommentPanelService } from '../../../services/thread-comment-panel.service';import { ThreadCommentEditor } from '../../ThreadCommentEditor';-const { commandService, localeService, editorService, coreTokens, docsUiTokens, editorHandle } = vi.hoisted(() => {- const commandService = {- executeCommand: vi.fn(),- };- const localeService = {- t: vi.fn((key: string) => key),- };- const editorService = {- focus: vi.fn(),- };- const coreTokens = {- ICommandService: Symbol('ICommandService'),- LocaleService: Symbol('LocaleService'),- };- const docsUiTokens = {- IEditorService: Symbol('IEditorService'),+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const EDITOR_ID = 'thread-comment-editor';+const REPLY_LABEL = 'thread-comment-ui.editor.reply';+const CANCEL_LABEL = 'thread-comment-ui.editor.cancel';+const PLACEHOLDER_LABEL = 'thread-comment-ui.editor.placeholder';+const IRenderManagerService = createIdentifier<TestRenderManagerService>('engine-render.render-manager.service');++interface IEditorRecord {+ id: string;+ data: IDocumentData;+ selections: ISuccinctDocRangeParam[];+ focused: boolean;+ order: string[];+}++class TestState {+ static records = new Map<string, IEditorRecord>();+ static savedBodies: IDocumentBody[] = [];+ static submitCount = 0;+ static cancelCount = 0;+ static shortcuts: IShortcutItem[] = [];++ static reset() {+ this.records = new Map();+ this.savedBodies = [];+ this.submitCount = 0;+ this.cancelCount = 0;+ this.shortcuts = [];+ }+}++class TestEditor {+ readonly input$ = new Subject<unknown>();+ readonly paste$ = new Subject<unknown>();+ readonly focus$ = new Subject<unknown>();+ readonly blur$ = new Subject<unknown>();+ readonly change$ = new Subject<unknown>();+ readonly selectionChange$ = new Subject<unknown>();++ readonly render = {+ isDisposed: () => false,+ with: () => ({+ getSkeleton: () => ({+ getActualSize: () => ({ actualWidth: 0, actualHeight: 0 }),+ }),+ getViewModel: () => ({+ getDataModel: () => ({+ updateDocumentDataPageSize: () => undefined,+ }),+ }),+ }),+ scene: {+ transformByState: () => undefined,+ getViewport: () => undefined,+ },+ mainComponent: {+ resize: () => undefined,+ translate: () => undefined,+ },+ components: {+ get: () => undefined,+ },};- const editorHandle = {- getDocumentData: vi.fn(() => ({++ constructor(private readonly _record: IEditorRecord) {+ }++ isFocus() {+ return this._record.focused;+ }++ focus(): void {+ this._record.focused = true;+ this._record.order.push('editor.focus');+ this.focus$.next(undefined);+ }++ blur(): void {+ this._record.focused = false;+ this._record.order.push('editor.blur');+ this.blur$.next(undefined);+ }++ select(): void {+ }++ setSelectionRanges(ranges: ISuccinctDocRangeParam[]): void {+ this._record.selections = ranges;+ this._record.order.push('editor.setSelectionRanges');+ this.selectionChange$.next(undefined);+ }++ getSelectionRanges() {+ return this._record.selections;+ }++ getEditorId() {+ return this._record.id;+ }++ getDocumentData() {+ return this._record.data;+ }++ setDocumentData(data: IDocumentData, ranges: ISuccinctDocRangeParam[] = []): void {+ this._record.data = data;+ this._record.selections = ranges;+ this._record.order.push('editor.setDocumentData');+ this.selectionChange$.next(undefined);+ }++ replaceText(value: string): void {+ this._record.data = {+ ...this._record.data,body: {- dataStream: 'reply body',+ dataStream: `${value}\r\n`,},- })),- replaceText: vi.fn(),- setSelectionRanges: vi.fn(),- blur: vi.fn(),- focus: vi.fn(),- getEditorId: vi.fn(() => 'editor-id'),- setDocumentData: vi.fn(),- selectionChange$: {- subscribe: vi.fn(() => ({- unsubscribe: vi.fn(),- })),- },- };+ };+ this._record.order.push('editor.replaceText');+ this.selectionChange$.next(undefined);+ }++ clearUndoRedoHistory(): void {+ }++ getValue() {+ return this._record.data.body?.dataStream ?? '';+ }++ isSheetEditor() {+ return false;+ }++ getBoundingClientRect() {+ return { width: 320, height: 64 };+ }+}++class TestEditorService {+ private readonly _editors = new Map<string, TestEditor>();+ private _focusId: Nullable<string>;+ readonly blur$ = new Subject<unknown>();+ readonly focus$ = new Subject<ISuccinctDocRangeParam>();++ getEditor(id?: string): Nullable<TestEditor> {+ return id ? this._editors.get(id) : undefined;+ }++ register(config: { initialSnapshot: IDocumentData }, _container: HTMLDivElement): IDisposable {+ const snapshot = config.initialSnapshot;+ const record: IEditorRecord = {+ id: snapshot.id,+ data: snapshot,+ selections: [],+ focused: false,+ order: [],+ };+ const editor = new TestEditor(record);+ this._editors.set(record.id, editor);+ TestState.records.set(record.id, record);++ return toDisposable(() => {+ this._editors.delete(record.id);+ });+ }++ getAllEditor() {+ return this._editors;+ }++ isEditor(editorUnitId: string) {+ return this._editors.has(editorUnitId);+ }++ getEditorRenderConfig() {+ return null;+ }++ isSheetEditor() {+ return false;+ }++ blur(): void {+ this.getFocusEditor()?.blur();+ this._focusId = null;+ this.blur$.next(undefined);+ }++ focus(editorUnitId: string): void {+ this._focusId = editorUnitId;+ this.getEditor(editorUnitId)?.focus();+ this.focus$.next({ startOffset: 0, endOffset: 0 });+ }++ getFocusId() {+ return this._focusId;+ }++ getFocusEditor() {+ return this._focusId ? this.getEditor(this._focusId) : undefined;+ }+}++class TestRenderManagerService {+ readonly createRender$ = new Subject<string>();+ readonly created$ = new Subject<unknown>();+ readonly disposed$ = new Subject<string>();+ readonly defaultEngine = {};++ addRender(): void {}+ createRender() { return undefined; }+ removeRender(): void {}+ getRenderById() { return undefined; }+ getRenderUnitById() { return undefined; }+ getAllRenderersOfType() { return []; }+ getRenderAll() { return new Map(); }+ create(): void {}+ has() { return false; }+ registerRenderModule(): IDisposable { return toDisposable(() => undefined); }+ dispose(): void {}+}++class TestLocaleService {+ t(key: string) {+ return key;+ }+}++class TestShortcutService {+ readonly shortcutChanged$ = new Subject<void>();++ forceEscape(): IDisposable { return toDisposable(() => undefined); }+ forceDisable(): IDisposable { return toDisposable(() => undefined); }+ dispatch(): undefined { return undefined; }+ registerShortcut(shortcut: IShortcutItem): IDisposable {+ TestState.shortcuts.push(shortcut);+ return toDisposable(() => undefined);+ }++ getShortcutDisplay(): string | null { return null; }+ getShortcutDisplayOfCommand(): string | null { return null; }+ getAllShortcuts(): IShortcutItem[] { return TestState.shortcuts; }+}++class TestSidebarService {+ readonly sidebarOptions$ = new BehaviorSubject({ visible: true });+ readonly scrollEvent$ = new Subject<Event>();+ private _container: HTMLElement | undefined;+ private _width: number | undefined;++ open(): IDisposable { return toDisposable(() => undefined); }+ close(): void {+ this.sidebarOptions$.next({ visible: false });+ }++ get visible() { return this.sidebarOptions$.getValue().visible; }+ get options() { return this.sidebarOptions$.getValue(); }+ getContainer() { return this._container; }+ setContainer(element?: HTMLElement): void { this._container = element; }+ get width() { return this._width; }+ setWidth(value: number): void { this._width = value; }+}++class TestUniverInstanceService {+ getCurrentTypeOfUnit$() {+ return new BehaviorSubject({ id: 'workbook' });+ }++ setCurrentUnitForType(): void {+ }+}++const BreakLineCommand: ICommand = {+ id: 'doc.command.editor-break-line',+ type: CommandType.COMMAND,+ handler: () => true,+};++function createEditorTestBed() {+ const injector = new Injector();+ const dependencies: Dependency[] = [+ [ICommandService, { useClass: CommandService }],+ [ILogService, { useClass: DesktopLogService }],+ [IContextService, { useClass: ContextService }],+ [IConfigService, { useClass: ConfigService }],+ [LocaleService, { useClass: TestLocaleService as never }],+ [IEditorService, { useClass: TestEditorService as never }],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ [IShortcutService, { useClass: TestShortcutService as never }],+ [ISidebarService, { useClass: TestSidebarService as never }],+ [IUniverInstanceService, { useClass: TestUniverInstanceService as never }],+ [ThreadCommentPanelService],+ ];++ dependencies.forEach((dependency) => injector.add(dependency));+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ const commandService = injector.get(ICommandService);+ [SetActiveCommentOperation, BreakLineCommand].forEach((command) => commandService.registerCommand(command));return {+ injector,commandService,- localeService,- editorService,- coreTokens,- docsUiTokens,- editorHandle,+ panelService: injector.get(ThreadCommentPanelService),};-});+}++function renderEditor(injector: Injector, element: React.ReactElement) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });-vi.mock('@univerjs/core', () => ({- BuildTextUtils: {- transform: {- getPlainText: (value: string) => value,- },- },- DOCS_NORMAL_EDITOR_UNIT_ID_KEY: 'doc-editor-id',- ICommandService: coreTokens.ICommandService,- LocaleService: coreTokens.LocaleService,- Tools: {- deepClone: <T,>(value: T) => value,- },- UniverInstanceType: {- UNIVER_DOC: 'UNIVER_DOC',- },-}));--vi.mock('@univerjs/docs-ui', () => ({- BreakLineCommand: {- id: 'break-line',- },- IEditorService: docsUiTokens.IEditorService,- RichTextEditor: ({ autoFocus, editorRef, onFocusChange, placeholder }: any) => {- useEffect(() => {- editorRef.current = editorHandle;- if (autoFocus) {- onFocusChange?.(true);- }-- return () => {- editorRef.current = null;- };- }, [autoFocus, editorRef, onFocusChange]);-- return <div aria-label={placeholder} data-testid="thread-comment-editor-input" />;- },-}));--vi.mock('../../../commands/operations/comment.operations', () => ({- SetActiveCommentOperation: {- id: 'set-active-comment',- },-}));--vi.mock('@univerjs/design', () => ({- Button: ({ children, disabled, onClick, type }: ButtonHTMLAttributes<HTMLButtonElement>) => (- <button disabled={disabled} onClick={onClick} type={type}>- {children}- </button>- ),- clsx: (...args: unknown[]) => args.filter(Boolean).join(' '),-}));--vi.mock('@univerjs/ui', () => ({- KeyCode: {- ENTER: 13,- },- useDependency: (token: symbol) => {- if (token === coreTokens.ICommandService) {- return commandService;- }+ return { container, root };+}- if (token === coreTokens.LocaleService) {- return localeService;- }+function getButton(container: HTMLElement, text: string): HTMLButtonElement {+ const button = Array.from(container.querySelectorAll('button')).find((item) => item.textContent?.trim() === text);+ if (!button) {+ throw new Error(`Button "${text}" was not found.`);+ }- if (token === docsUiTokens.IEditorService) {- return editorService;- }+ return button as HTMLButtonElement;+}- throw new Error(`Unexpected dependency token: ${String(token)}`);- },-}));+function getEditorSurface(container: HTMLElement): HTMLElement {+ const placeholder = Array.from(container.querySelectorAll('div')).find((item) => item.textContent === PLACEHOLDER_LABEL);+ if (!placeholder) {+ throw new Error('Editor placeholder was not found.');+ }-(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ return placeholder.parentElement?.parentElement?.parentElement ?? placeholder as HTMLElement;+}++function body(dataStream: string): IDocumentBody {+ return { dataStream };+}describe('ThreadCommentEditor', () => {- let container: HTMLDivElement;- let root: Root;+ let root: Root | undefined;+ let container: HTMLElement | undefined;beforeEach(() => {- commandService.executeCommand.mockReset();- localeService.t.mockImplementation((key: string) => key);- editorService.focus.mockReset();- editorHandle.getDocumentData.mockImplementation(() => ({- body: {- dataStream: 'reply body',- },- }));- editorHandle.replaceText.mockReset();- editorHandle.setSelectionRanges.mockReset();- editorHandle.blur.mockReset();- editorHandle.focus.mockReset();- editorHandle.getEditorId.mockImplementation(() => 'editor-id');- editorHandle.setDocumentData.mockReset();- editorHandle.selectionChange$.subscribe.mockImplementation(() => ({- unsubscribe: vi.fn(),- }));+ TestState.reset();});afterEach(() => {- act(() => {- root?.unmount();- });+ if (root) {+ act(() => root!.unmount());+ }container?.remove();- vi.clearAllMocks();- });-- it('uses non-submit buttons so replying does not submit an outer form', () => {- const onSave = vi.fn();- const onSubmit = vi.fn((event: FormEvent<HTMLFormElement>) => event.preventDefault());-- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);-- act(() => {- root.render(- <form onSubmit={onSubmit}>- <ThreadCommentEditor- autoFocus- editorId="thread-comment-editor"- onSave={onSave}- subUnitId="subUnit"- type={UniverInstanceType.UNIVER_DOC}- unitId="unit"- />- </form>- );- });-- const buttons = Array.from(container.querySelectorAll('button'));- const cancelButton = buttons.find((button) => button.textContent === 'thread-comment-ui.editor.cancel');- const replyButton = buttons.find((button) => button.textContent === 'thread-comment-ui.editor.reply');-- expect(cancelButton?.getAttribute('type')).toBe('button');- expect(replyButton?.getAttribute('type')).toBe('button');-- act(() => {- replyButton?.click();- });-- expect(onSave).toHaveBeenCalledTimes(1);- expect(onSubmit).not.toHaveBeenCalled();+ root = undefined;+ container = undefined;});- it('blurs the editor before save callbacks can unmount it', () => {- const onSave = vi.fn(() => {- editorHandle.blur.mockImplementation(() => {- throw new Error('blur after save');- });- });-- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);-- act(() => {- root.render(- <ThreadCommentEditor- autoFocus- editorId="thread-comment-editor"- onSave={onSave}- subUnitId="subUnit"- type={UniverInstanceType.UNIVER_DOC}- unitId="unit"- />- );- });-- const replyButton = Array.from(container.querySelectorAll('button'))- .find((button) => button.textContent === 'thread-comment-ui.editor.reply');-- expect(() => {- act(() => {- replyButton?.click();- });- }).not.toThrow();- expect(editorHandle.blur).toHaveBeenCalledBefore(onSave);- });-- it('blurs the editor before clearing content so active popups are disposed first', () => {- const onSave = vi.fn();-- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);-- act(() => {- root.render(+ it('enters editing mode from an inserted reply and keeps action buttons out of outer form submission', () => {+ const testBed = createEditorTestBed();+ const editorRef = createRef<{ reply: (text: IDocumentBody) => void }>();+ const rendered = renderEditor(+ testBed.injector,+ <form+ onSubmit={(event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ TestState.submitCount += 1;+ }}+ ><ThreadCommentEditor- autoFocus- editorId="thread-comment-editor"- onSave={onSave}+ ref={editorRef}+ autoFocus={false}+ editorId={EDITOR_ID}subUnitId="subUnit"- type={UniverInstanceType.UNIVER_DOC}+ type={UniverInstanceType.UNIVER_SHEET}unitId="unit"/>- );- });+ </form>+ );+ root = rendered.root;+ container = rendered.container;- const replyButton = Array.from(container.querySelectorAll('button'))- .find((button) => button.textContent === 'thread-comment-ui.editor.reply');+ expect(container.querySelectorAll('button')).toHaveLength(0);act(() => {- replyButton?.click();+ editorRef.current?.reply(body('draft reply\r\n'));});- expect(editorHandle.blur).toHaveBeenCalledBefore(editorHandle.replaceText);+ expect(getButton(container, CANCEL_LABEL).type).toBe('button');+ expect(getButton(container, REPLY_LABEL).type).toBe('button');+ expect(getButton(container, REPLY_LABEL).disabled).toBe(false);+ expect(TestState.submitCount).toBe(0);});- it('shows action buttons after reply inserts mention text without a focus change event', () => {- const ref = createRef<{ reply: (text: { dataStream: string }) => void }>();-- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);-- act(() => {- root.render(+ it('saves reply content, clears the editor, and does not submit an outer form', () => {+ const testBed = createEditorTestBed();+ const editorRef = createRef<{ reply: (text: IDocumentBody) => void }>();+ const rendered = renderEditor(+ testBed.injector,+ <form+ onSubmit={(event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ TestState.submitCount += 1;+ }}+ ><ThreadCommentEditor- ref={ref as any}+ ref={editorRef}autoFocus={false}- editorId="thread-comment-editor"+ editorId={EDITOR_ID}+ onSave={(comment) => {+ TestState.records.get(EDITOR_ID)?.order.push('onSave');+ TestState.savedBodies.push(comment.text);+ }}subUnitId="subUnit"type={UniverInstanceType.UNIVER_SHEET}unitId="unit"/>- );+ </form>+ );+ root = rendered.root;+ container = rendered.container;++ act(() => {+ editorRef.current?.reply(body('@Owner reply body\r\n'));});- expect(container.querySelectorAll('button').length).toBe(0);+ expect(getButton(container, REPLY_LABEL).disabled).toBe(false);act(() => {- ref.current?.reply({ dataStream: '@Owner asdas\r\n' });+ getButton(container!, REPLY_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));});- const replyButton = Array.from(container.querySelectorAll('button'))- .find((button) => button.textContent === 'thread-comment-ui.editor.reply');+ expect(TestState.savedBodies).toEqual([body('@Owner reply body\r\n')]);+ expect(TestState.submitCount).toBe(0);- expect(replyButton).toBeTruthy();- expect(replyButton?.disabled).toBe(false);+ const record = TestState.records.get(EDITOR_ID)!;+ expect(record.data.body?.dataStream).toBe('\r\n');+ expect(record.selections).toEqual([]);+ expect(record.order.indexOf('editor.blur')).toBeLessThan(record.order.indexOf('editor.replaceText'));+ expect(record.order.indexOf('editor.replaceText')).toBeLessThan(record.order.indexOf('onSave'));});- it('shows action buttons after the editor is clicked without a focus change event', () => {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);+ it('cancels editing by clearing content and resetting the active comment', () => {+ const testBed = createEditorTestBed();+ testBed.panelService.setActiveComment({ unitId: 'unit', subUnitId: 'subUnit', commentId: 'comment-1' });++ const editorRef = createRef<{ reply: (text: IDocumentBody) => void }>();+ const rendered = renderEditor(+ testBed.injector,+ <ThreadCommentEditor+ ref={editorRef}+ autoFocus={false}+ editorId={EDITOR_ID}+ onCancel={() => {+ TestState.cancelCount += 1;+ }}+ subUnitId="subUnit"+ type={UniverInstanceType.UNIVER_SHEET}+ unitId="unit"+ />+ );+ root = rendered.root;+ container = rendered.container;act(() => {- root.render(- <ThreadCommentEditor- autoFocus={false}- editorId="thread-comment-editor"- subUnitId="subUnit"- type={UniverInstanceType.UNIVER_SHEET}- unitId="unit"- />- );+ editorRef.current?.reply(body('draft reply\r\n'));});- expect(container.querySelectorAll('button').length).toBe(0);-act(() => {- container.querySelector('[data-testid="thread-comment-editor-input"]')?.dispatchEvent(- new MouseEvent('mousedown', { bubbles: true })- );+ getButton(container!, CANCEL_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));});- const replyButton = Array.from(container.querySelectorAll('button'))- .find((button) => button.textContent === 'thread-comment-ui.editor.reply');-- expect(replyButton).toBeTruthy();+ const record = TestState.records.get(EDITOR_ID)!;+ expect(record.data.body?.dataStream).toBe('\r\n');+ expect(record.selections).toEqual([]);+ expect(TestState.cancelCount).toBe(1);+ expect(testBed.panelService.activeCommentId).toBeUndefined();+ expect(container.querySelectorAll('button')).toHaveLength(0);});- it('resets submit state after saving and clearing the editor', () => {- container = document.createElement('div');- document.body.appendChild(container);- root = createRoot(container);-- act(() => {- root.render(- <ThreadCommentEditor- autoFocus- editorId="thread-comment-editor"- subUnitId="subUnit"- type={UniverInstanceType.UNIVER_SHEET}- unitId="unit"- />- );- });-- const firstReplyButton = Array.from(container.querySelectorAll('button'))- .find((button) => button.textContent === 'thread-comment-ui.editor.reply');+ it('uses the normal document editor as the click-outside focus target for document comments', async () => {+ const testBed = createEditorTestBed();+ const editorRef = createRef<{ reply: (text: IDocumentBody) => void }>();+ const rendered = renderEditor(+ testBed.injector,+ <ThreadCommentEditor+ ref={editorRef}+ autoFocus={false}+ editorId={EDITOR_ID}+ subUnitId="subUnit"+ type={UniverInstanceType.UNIVER_DOC}+ unitId="docUnit"+ />+ );+ root = rendered.root;+ container = rendered.container;act(() => {- firstReplyButton?.click();+ editorRef.current?.reply(body('doc reply\r\n'));});- act(() => {- container.querySelector('[data-testid="thread-comment-editor-input"]')?.dispatchEvent(- new MouseEvent('mousedown', { bubbles: true })- );+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 120));+ document.body.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ await new Promise((resolve) => setTimeout(resolve, 40));});- const secondReplyButton = Array.from(container.querySelectorAll('button'))- .find((button) => button.textContent === 'thread-comment-ui.editor.reply');-- expect(secondReplyButton?.disabled).toBe(true);+ expect(testBed.injector.get(IEditorService).getFocusId()).toBe(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);});});diff --git a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.tsindex 30bf20af6f..fff411c3d2 100644--- a/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts+++ b/packages/thread-comment-ui/src/views/thread-comment-editor/__tests__/util.spec.ts@@ -14,22 +14,34 @@* limitations under the License.*/-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import { focusThreadCommentEditor } from '../util';+class TestEditorService {+ focusedEditorId = '';++ focus(editorId: string): void {+ this.focusedEditorId = editorId;+ }+}++class TestEditor {+ focused = false;++ focus(): void {+ this.focused = true;+ }+}+describe('focusThreadCommentEditor', () => {it('focuses the editor instance even when the editor service already tracks the id', () => {const editorId = 'comment-editor-id';- const editorService = {- focus: vi.fn(),- };- const editor = {- focus: vi.fn(),- };+ const editorService = new TestEditorService();+ const editor = new TestEditor();focusThreadCommentEditor(editorService, editorId, editor);- expect(editorService.focus).toHaveBeenCalledWith(editorId);- expect(editor.focus).toHaveBeenCalled();+ expect(editorService.focusedEditorId).toBe(editorId);+ expect(editor.focused).toBe(true);});});diff --git a/packages/thread-comment-ui/src/views/thread-comment-panel/__tests__/index.spec.tsx b/packages/thread-comment-ui/src/views/thread-comment-panel/__tests__/index.spec.tsxnew file mode 100644index 0000000000..6e161c3a58--- /dev/null+++ b/packages/thread-comment-ui/src/views/thread-comment-panel/__tests__/index.spec.tsx@@ -0,0 +1,504 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IDisposable, IDocumentData, Nullable } from '@univerjs/core';+import type { ISuccinctDocRangeParam } from '@univerjs/engine-render';+import type { IThreadComment } from '@univerjs/thread-comment';+import type { IShortcutItem } from '@univerjs/ui';+import type { Root } from 'react-dom/client';+import {+ CommandService,+ ConfigService,+ ContextService,+ createIdentifier,+ DesktopLogService,+ ICommandService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ LifecycleService,+ LifecycleStages,+ LocaleService,+ LogLevel,+ toDisposable,+ UniverInstanceType,+ UserManagerService,+} from '@univerjs/core';+import { IEditorService } from '@univerjs/docs-ui';+import {+ AddCommentCommand,+ AddCommentMutation,+ DeleteCommentCommand,+ DeleteCommentMutation,+ DeleteCommentTreeCommand,+ IThreadCommentDataSourceService,+ ResolveCommentCommand,+ ResolveCommentMutation,+ ThreadCommentDataSourceService,+ ThreadCommentModel,+ UpdateCommentCommand,+ UpdateCommentMutation,+} from '@univerjs/thread-comment';+import { IShortcutService, ISidebarService, RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { BehaviorSubject, Subject } from 'rxjs';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { SetActiveCommentOperation } from '../../../commands/operations/comment.operations';+import { ThreadCommentPanelService } from '../../../services/thread-comment-panel.service';+import { transformTextNodes2Document } from '../../thread-comment-editor/util';+import { ThreadCommentPanel } from '../../ThreadCommentPanel';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const UNIT_ID = 'unit-1';+const SHEET_ID = 'sheet-1';+const IRenderManagerService = createIdentifier<TestRenderManagerService>('engine-render.render-manager.service');++interface IEditorRecord {+ id: string;+ data: IDocumentData;+ selections: ISuccinctDocRangeParam[];+ focused: boolean;+}++class TestLocaleService {+ t(key: string) {+ return key;+ }+}++class TestEditor {+ readonly input$ = new Subject<unknown>();+ readonly paste$ = new Subject<unknown>();+ readonly focus$ = new Subject<unknown>();+ readonly blur$ = new Subject<unknown>();+ readonly change$ = new Subject<unknown>();+ readonly selectionChange$ = new Subject<unknown>();++ readonly render = {+ isDisposed: () => false,+ with: () => ({+ getSkeleton: () => ({+ getActualSize: () => ({ actualWidth: 0, actualHeight: 0 }),+ }),+ getViewModel: () => ({+ getDataModel: () => ({+ updateDocumentDataPageSize: () => undefined,+ }),+ }),+ }),+ scene: {+ transformByState: () => undefined,+ getViewport: () => undefined,+ },+ mainComponent: {+ resize: () => undefined,+ translate: () => undefined,+ },+ components: {+ get: () => undefined,+ },+ };++ constructor(private readonly _record: IEditorRecord) {+ }++ isFocus() {+ return this._record.focused;+ }++ focus(): void {+ this._record.focused = true;+ this.focus$.next(undefined);+ }++ blur(): void {+ this._record.focused = false;+ this.blur$.next(undefined);+ }++ select(): void {+ }++ setSelectionRanges(ranges: ISuccinctDocRangeParam[]): void {+ this._record.selections = ranges;+ this.selectionChange$.next(undefined);+ }++ getSelectionRanges() {+ return this._record.selections;+ }++ getEditorId() {+ return this._record.id;+ }++ getDocumentData() {+ return this._record.data;+ }++ setDocumentData(data: IDocumentData, ranges: ISuccinctDocRangeParam[] = []): void {+ this._record.data = data;+ this._record.selections = ranges;+ this.selectionChange$.next(undefined);+ }++ replaceText(value: string): void {+ this._record.data = {+ ...this._record.data,+ body: {+ dataStream: `${value}\r\n`,+ },+ };+ this.selectionChange$.next(undefined);+ }++ clearUndoRedoHistory(): void {+ }++ getValue() {+ return this._record.data.body?.dataStream ?? '';+ }++ isSheetEditor() {+ return false;+ }++ getBoundingClientRect() {+ return { width: 320, height: 64 };+ }+}++class TestEditorService {+ private readonly _editors = new Map<string, TestEditor>();+ private _focusId: Nullable<string>;+ readonly blur$ = new Subject<unknown>();+ readonly focus$ = new Subject<ISuccinctDocRangeParam>();++ getEditor(id?: string): Nullable<TestEditor> {+ return id ? this._editors.get(id) : undefined;+ }++ register(config: { initialSnapshot: IDocumentData }, _container: HTMLDivElement): IDisposable {+ const snapshot = config.initialSnapshot;+ const record: IEditorRecord = {+ id: snapshot.id,+ data: snapshot,+ selections: [],+ focused: false,+ };+ const editor = new TestEditor(record);+ this._editors.set(record.id, editor);++ return toDisposable(() => {+ this._editors.delete(record.id);+ });+ }++ getAllEditor() {+ return this._editors;+ }++ isEditor(editorUnitId: string) {+ return this._editors.has(editorUnitId);+ }++ getEditorRenderConfig() {+ return null;+ }++ isSheetEditor() {+ return false;+ }++ blur(): void {+ this.getFocusEditor()?.blur();+ this._focusId = null;+ this.blur$.next(undefined);+ }++ focus(editorUnitId: string): void {+ this._focusId = editorUnitId;+ this.getEditor(editorUnitId)?.focus();+ this.focus$.next({ startOffset: 0, endOffset: 0 });+ }++ getFocusId() {+ return this._focusId;+ }++ getFocusEditor() {+ return this._focusId ? this.getEditor(this._focusId) : undefined;+ }+}++class TestRenderManagerService {+ readonly createRender$ = new Subject<string>();+ readonly created$ = new Subject<unknown>();+ readonly disposed$ = new Subject<string>();+ readonly defaultEngine = {};++ addRender(): void {}+ createRender() { return undefined; }+ removeRender(): void {}+ getRenderById() { return undefined; }+ getRenderUnitById() { return undefined; }+ getAllRenderersOfType() { return []; }+ getRenderAll() { return new Map(); }+ create(): void {}+ has() { return false; }+ registerRenderModule(): IDisposable { return toDisposable(() => undefined); }+ dispose(): void {}+}++class TestShortcutService {+ readonly shortcutChanged$ = new Subject<void>();+ readonly shortcuts: IShortcutItem[] = [];++ forceEscape(): IDisposable { return toDisposable(() => undefined); }+ forceDisable(): IDisposable { return toDisposable(() => undefined); }+ dispatch(): undefined { return undefined; }+ registerShortcut(shortcut: IShortcutItem): IDisposable {+ this.shortcuts.push(shortcut);+ return toDisposable(() => undefined);+ }++ getShortcutDisplay(): string | null { return null; }+ getShortcutDisplayOfCommand(): string | null { return null; }+ getAllShortcuts(): IShortcutItem[] { return this.shortcuts; }+}++class TestSidebarService {+ readonly sidebarOptions$ = new BehaviorSubject({ visible: true });+ readonly scrollEvent$ = new Subject<Event>();+ private _container: HTMLElement | undefined;+ private _width: number | undefined;++ open(): IDisposable { return toDisposable(() => undefined); }+ close(): void {+ this.sidebarOptions$.next({ visible: false });+ }++ get visible() { return this.sidebarOptions$.getValue().visible; }+ get options() { return this.sidebarOptions$.getValue(); }+ getContainer() { return this._container; }+ setContainer(element?: HTMLElement): void { this._container = element; }+ get width() { return this._width; }+ setWidth(value: number): void { this._width = value; }+}++class TestUniverInstanceService {+ getCurrentTypeOfUnit$() {+ return new BehaviorSubject({ id: 'workbook' });+ }++ setCurrentUnitForType(): void {+ }+}++function createComment(overrides: Partial<IThreadComment>): IThreadComment {+ const id = overrides.id ?? 'comment-1';++ return {+ id,+ threadId: overrides.threadId ?? id,+ ref: overrides.ref ?? 'A1',+ dT: overrides.dT ?? '2026-06-17T00:00:00.000Z',+ personId: overrides.personId ?? 'owner',+ text: overrides.text ?? transformTextNodes2Document([{ type: 'text', content: id }]),+ unitId: overrides.unitId ?? UNIT_ID,+ subUnitId: overrides.subUnitId ?? SHEET_ID,+ attachments: overrides.attachments,+ children: overrides.children,+ mentions: overrides.mentions,+ parentId: overrides.parentId,+ resolved: overrides.resolved,+ updateT: overrides.updateT,+ updated: overrides.updated,+ };+}++function createPanelTestBed() {+ const injector = new Injector();+ const dependencies: Dependency[] = [+ [ICommandService, { useClass: CommandService }],+ [ILogService, { useClass: DesktopLogService }],+ [IContextService, { useClass: ContextService }],+ [IConfigService, { useClass: ConfigService }],+ [LocaleService, { useClass: TestLocaleService as never }],+ [IEditorService, { useClass: TestEditorService as never }],+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],+ [IShortcutService, { useClass: TestShortcutService as never }],+ [ISidebarService, { useClass: TestSidebarService as never }],+ [IUniverInstanceService, { useClass: TestUniverInstanceService as never }],+ [IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }],+ [LifecycleService],+ [UserManagerService],+ [ThreadCommentModel],+ [ThreadCommentPanelService],+ ];++ dependencies.forEach((dependency) => injector.add(dependency));+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);+ injector.get(LifecycleService).stage = LifecycleStages.Rendered;+ injector.get(UserManagerService).setCurrentUser({ userID: 'owner', name: 'Owner', avatar: 'owner.png' });++ const commandService = injector.get(ICommandService);+ [+ AddCommentCommand,+ AddCommentMutation,+ DeleteCommentCommand,+ DeleteCommentMutation,+ DeleteCommentTreeCommand,+ ResolveCommentCommand,+ ResolveCommentMutation,+ SetActiveCommentOperation,+ UpdateCommentCommand,+ UpdateCommentMutation,+ ].forEach((command) => commandService.registerCommand(command));++ return {+ injector,+ panelService: injector.get(ThreadCommentPanelService),+ threadCommentModel: injector.get(ThreadCommentModel),+ };+}++function renderPanel(injector: Injector, element: React.ReactElement) {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);++ act(() => {+ root.render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+ });++ return { container, root };+}++function renderDefaultPanel(injector: Injector) {+ return renderPanel(+ injector,+ <ThreadCommentPanel+ unitId={UNIT_ID}+ subUnitId$={new BehaviorSubject<string | undefined>(SHEET_ID)}+ type={UniverInstanceType.UNIVER_SHEET}+ onAdd={() => undefined}+ getSubUnitName={(subUnitId) => subUnitId}+ />+ );+}++function addRootComment(model: ThreadCommentModel, comment: IThreadComment) {+ model.addComment(comment.unitId, comment.subUnitId, comment);+}++function getPanelItem(container: HTMLElement, commentId: string) {+ const item = container.querySelector(`#PANEL-${UNIT_ID}-${SHEET_ID}-${commentId}`);+ if (!item) {+ throw new Error(`Panel item "${commentId}" was not found.`);+ }++ return item as HTMLElement;+}++describe('ThreadCommentPanel', () => {+ let root: Root | undefined;+ let container: HTMLElement | undefined;++ beforeEach(() => {+ document.body.innerHTML = '';+ });++ afterEach(() => {+ if (root) {+ act(() => root!.unmount());+ }+ container?.remove();+ root = undefined;+ container = undefined;+ });++ it('keeps unresolved comments before resolved comments after applying caller sorting', () => {+ const testBed = createPanelTestBed();+ addRootComment(testBed.threadCommentModel, createComment({+ id: 'open-thread',+ ref: 'A1',+ text: transformTextNodes2Document([{ type: 'text', content: 'Open comment' }]),+ }));+ addRootComment(testBed.threadCommentModel, createComment({+ id: 'resolved-thread',+ ref: 'B2',+ resolved: true,+ text: transformTextNodes2Document([{ type: 'text', content: 'Resolved comment' }]),+ }));++ const rendered = renderPanel(+ testBed.injector,+ <ThreadCommentPanel+ unitId={UNIT_ID}+ subUnitId$={new BehaviorSubject<string | undefined>(SHEET_ID)}+ type={UniverInstanceType.UNIVER_SHEET}+ onAdd={() => undefined}+ getSubUnitName={(subUnitId) => subUnitId}+ sortComments={(comments) => comments.slice().reverse()}+ />+ );+ root = rendered.root;+ container = rendered.container;++ const panelText = container.textContent ?? '';++ expect(panelText.indexOf('Open comment')).toBeGreaterThan(-1);+ expect(panelText.indexOf('Resolved comment')).toBeGreaterThan(-1);+ expect(panelText.indexOf('Open comment')).toBeLessThan(panelText.indexOf('thread-comment-ui.panel.solved'));+ expect(panelText.indexOf('thread-comment-ui.panel.solved')).toBeLessThan(panelText.indexOf('Resolved comment'));+ });++ it('sets active comment from unresolved panel items and clears it for resolved items', () => {+ const testBed = createPanelTestBed();+ addRootComment(testBed.threadCommentModel, createComment({ id: 'open-thread', ref: 'A1' }));+ addRootComment(testBed.threadCommentModel, createComment({ id: 'resolved-thread', ref: 'B2', resolved: true }));++ const rendered = renderDefaultPanel(testBed.injector);+ root = rendered.root;+ container = rendered.container;++ act(() => {+ getPanelItem(container!, 'open-thread').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(testBed.panelService.activeCommentId).toEqual({+ unitId: UNIT_ID,+ subUnitId: SHEET_ID,+ commentId: 'open-thread',+ temp: false,+ });++ act(() => {+ getPanelItem(container!, 'resolved-thread').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ });++ expect(testBed.panelService.activeCommentId).toBeUndefined();+ });+});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.tsindex e839ed0250..1aeb242921 100644--- a/packages/thread-comment/src/commands/commands/__tests__/comment.command.spec.ts+++ b/packages/thread-comment/src/commands/commands/__tests__/comment.command.spec.ts@@ -29,6 +29,7 @@ import {import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { ThreadCommentModel } from '../../../models/thread-comment.model';import { UniverThreadCommentPlugin } from '../../../plugin';+import { UpdateCommentRefMutation } from '../../mutations/comment.mutation';import {AddCommentCommand,DeleteCommentCommand,@@ -133,6 +134,11 @@ describe('Thread comment commands', () => {subscription.unsubscribe();+ const eventSummary: Array<{ type: CommentUpdate['type']; isRoot?: boolean }> = [];+ for (const event of events) {+ eventSummary.push({ type: event.type, isRoot: event.type === 'add' ? event.isRoot : undefined });+ }+expect(threadCommentModel.getThread('unit-1', 'sheet-1', root.id)).toEqual({unitId: 'unit-1',subUnitId: 'sheet-1',@@ -141,7 +147,7 @@ describe('Thread comment commands', () => {children: [reply],relativeUsers: new Set(['owner', 'guest']),});- expect(events.map((event) => ({ type: event.type, isRoot: event.type === 'add' ? event.isRoot : undefined }))).toEqual([+ expect(eventSummary).toEqual([{ type: 'add', isRoot: true },{ type: 'add', isRoot: false },]);@@ -186,7 +192,18 @@ describe('Thread comment commands', () => {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([+ const resolveEvents: CommentUpdate[] = [];+ const deletedCommentIds: string[] = [];+ for (const event of events) {+ if (event.type === 'resolve') {+ resolveEvents.push(event);+ }+ if (event.type === 'delete') {+ deletedCommentIds.push(event.payload.commentId);+ }+ }++ expect(resolveEvents).toEqual([{unitId: 'unit-1',subUnitId: 'sheet-1',@@ -197,7 +214,92 @@ describe('Thread comment commands', () => {},},]);- expect(events.filter((event) => event.type === 'delete').map((event) => event.payload.commentId)).toEqual(['root-2', 'reply-2']);+ expect(deletedCommentIds).toEqual(['root-2', 'reply-2']);+ });++ it('updates comment content and keeps the thread relationship', async () => {+ const root = createComment({ id: 'root-3', attachments: ['before.png'] });++ await commandService.executeCommand(AddCommentCommand.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ comment: root,+ });++ const result = await commandService.executeCommand(UpdateCommentCommand.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ payload: {+ commentId: root.id,+ text: createBody('updated text'),+ attachments: ['after.png'],+ updateT: '2024-01-02T00:00:00.000Z',+ },+ });++ const updated = threadCommentModel.getComment('unit-1', 'sheet-1', root.id);++ expect(result).toBe(true);+ expect(updated?.text).toEqual(createBody('updated text'));+ expect(updated?.attachments).toEqual(['after.png']);+ expect(updated?.updated).toBe(true);+ expect(updated?.updateT).toBe('2024-01-02T00:00:00.000Z');+ expect(threadCommentModel.getThread('unit-1', 'sheet-1', root.id)?.root.id).toBe(root.id);+ });++ it('deletes a reply without removing the root thread', async () => {+ const root = createComment({ id: 'root-4' });+ const reply = createComment({+ id: 'reply-4',+ parentId: root.id,+ threadId: root.id,+ 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,+ });++ const result = await commandService.executeCommand(DeleteCommentCommand.id, {+ unitId: reply.unitId,+ subUnitId: reply.subUnitId,+ commentId: reply.id,+ });+ const thread = threadCommentModel.getThread('unit-1', 'sheet-1', root.id);++ expect(result).toBe(true);+ expect(thread?.root.id).toBe(root.id);+ expect(thread?.children).toEqual([]);+ expect(threadCommentModel.getComment('unit-1', 'sheet-1', reply.id)).toBeUndefined();+ });++ it('updates a comment reference through the mutation used by integrations', async () => {+ const root = createComment({ id: 'root-5', ref: 'A1' });++ await commandService.executeCommand(AddCommentCommand.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ comment: root,+ });++ const result = await commandService.executeCommand(UpdateCommentRefMutation.id, {+ unitId: root.unitId,+ subUnitId: root.subUnitId,+ payload: {+ commentId: root.id,+ ref: 'B2',+ },+ });++ expect(result).toBe(true);+ expect(threadCommentModel.getComment('unit-1', 'sheet-1', root.id)?.ref).toBe('B2');});it('returns false when updating or deleting a missing comment', async () => {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.tsindex 3defb81de0..49c0e41431 100644--- a/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts+++ b/packages/thread-comment/src/services/__tests__/tc-datasource.service.spec.ts@@ -16,8 +16,10 @@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';+import type { IThreadCommentDataSource } from '../tc-datasource.service';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { IThreadCommentDataSourceService, ThreadCommentDataSourceService } from '../tc-datasource.service';function createBody(text: string): IDocumentBody {return {@@ -47,9 +49,15 @@ function createComment(overrides: Partial<IThreadComment> = {}): IThreadComment};}+function createService(): IThreadCommentDataSourceService {+ const injector = new Injector();+ injector.add([IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }]);+ return injector.get(IThreadCommentDataSourceService);+}+describe('ThreadCommentDataSourceService', () => {it('falls back to local defaults when no external data source is configured', async () => {- const service = new ThreadCommentDataSourceService();+ const service = createService();const comment = createComment({ threadId: undefined });await expect(service.addComment({ ...comment, threadId: undefined as unknown as string })).resolves.toEqual({@@ -72,7 +80,7 @@ describe('ThreadCommentDataSourceService', () => {});it('normalizes an empty threadId to the comment id when no external data source is configured', async () => {- const service = new ThreadCommentDataSourceService();+ const service = createService();const comment = createComment({ id: 'root-1', threadId: '' });await expect(service.addComment(comment)).resolves.toEqual({@@ -82,24 +90,39 @@ describe('ThreadCommentDataSourceService', () => {});it('delegates CRUD, query and snapshot behavior to the configured data source', async () => {- const service = new ThreadCommentDataSourceService();+ const service = createService();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,- })),+ const listRequests: Array<{ unitId: string; subUnitId: string; threadIds: string[] }> = [];+ const savedSnapshots: IThreadComment[] = [];+ const dataSource: IThreadCommentDataSource = {+ async addComment(input) {+ return { ...input, threadId: 'server-thread' };+ },+ async updateComment() {+ return false;+ },+ async resolveComment() {+ return false;+ },+ async deleteComment() {+ return false;+ },+ async listComments(unitId, subUnitId, threadIds) {+ listRequests.push({ unitId, subUnitId, threadIds });+ return [{+ ...comment,+ children: [createComment({ id: 'reply-1', parentId: 'root-1', threadId: 'root-1', ref: '' })],+ }];+ },+ saveCommentToSnapshot(input) {+ savedSnapshots.push(input);+ return {+ id: input.id,+ threadId: input.threadId,+ ref: input.ref,+ personId: input.personId,+ };+ },};service.dataSource = dataSource;@@ -133,25 +156,39 @@ describe('ThreadCommentDataSourceService', () => {],});- 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]);+ expect(listRequests).toEqual([+ { unitId: 'unit-1', subUnitId: 'sheet-1', threadIds: ['root-1'] },+ { unitId: 'unit-1', subUnitId: 'sheet-1', threadIds: ['root-1'] },+ ]);+ expect(savedSnapshots).toEqual([comment]);});it('normalizes an empty threadId returned from an external data source to the returned comment id', async () => {- const service = new ThreadCommentDataSourceService();+ const service = createService();const comment = createComment({ id: 'client-id', threadId: '' });- const dataSource = {- addComment: vi.fn(async (input: IThreadComment) => ({ ...input, id: 'server-id', threadId: '' })),- updateComment: vi.fn(async () => true),- resolveComment: vi.fn(async () => true),- deleteComment: vi.fn(async () => true),- listComments: vi.fn(async () => []),- saveCommentToSnapshot: vi.fn((input: IThreadComment) => ({- id: input.id,- threadId: input.threadId,- ref: input.ref,- })),+ const dataSource: IThreadCommentDataSource = {+ async addComment(input) {+ return { ...input, id: 'server-id', threadId: '' };+ },+ async updateComment() {+ return true;+ },+ async resolveComment() {+ return true;+ },+ async deleteComment() {+ return true;+ },+ async listComments() {+ return [];+ },+ saveCommentToSnapshot(input) {+ return {+ id: input.id,+ threadId: input.threadId,+ ref: input.ref,+ };+ },};service.dataSource = dataSource;diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tssimilarity index 88%rename from packages/ui/src/controllers/ui/ui-desktop.controller.tsxrename to packages/ui/src/controllers/ui/ui-desktop.controller.tsindex 5e3206b915..63c6207b5e 100644--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.ts@@ -15,12 +15,10 @@*/import type { IDisposable } from '@univerjs/core';-import type { ComponentType } from 'react';import type { IUniverUIConfig } from '../../config/config';-import type { IUniverWorkbenchProps } from '../../views/workbench/Workbench';import type { IWorkbenchOptions } from './ui.controller';import { Inject, Injector, IUniverInstanceService, LifecycleService, toDisposable } from '@univerjs/core';-import { render as createRoot, unmount } from '@univerjs/design';+import { unmount } from '@univerjs/design';import { IRenderManagerService } from '@univerjs/engine-render';import { ComponentManager } from '../../common';import { menuSchema } from '../../menu/schema';@@ -31,7 +29,7 @@ import { connectInjector } from '../../utils/di';import { FloatDom } from '../../views/components/dom/FloatDom';import { CanvasPopup } from '../../views/components/popup/CanvasPopup';import { Ribbon } from '../../views/components/ribbon/Ribbon';-import { DesktopWorkbench } from '../../views/workbench/Workbench';+import { mountDesktopWorkbench } from '../../views/workbench/Workbench';import { SingleUnitUIController } from './ui-shared.controller';export class DesktopUIController extends SingleUnitUIController {@@ -91,18 +89,10 @@ function bootstrap(mountContainer = createContainer('univer');}- const ConnectedApp = connectInjector(DesktopWorkbench, injector) as ComponentType<IUniverWorkbenchProps>;const onRendered = (contentElement: HTMLElement) => callback(contentElement, mountContainer);function render() {- createRoot(- <ConnectedApp- {...options}- mountContainer={mountContainer}- onRendered={onRendered}- />,- mountContainer- );+ mountDesktopWorkbench(injector, options, mountContainer, onRendered);}render();diff --git a/packages/ui/src/controllers/ui/ui-mobile.controller.tsx b/packages/ui/src/controllers/ui/ui-mobile.controller.tssimilarity index 88%rename from packages/ui/src/controllers/ui/ui-mobile.controller.tsxrename to packages/ui/src/controllers/ui/ui-mobile.controller.tsindex 11fbcca1f0..5cd5805832 100644--- a/packages/ui/src/controllers/ui/ui-mobile.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-mobile.controller.ts@@ -15,12 +15,10 @@*/import type { IDisposable } from '@univerjs/core';-import type { ComponentType } from 'react';import type { IUniverUIConfig } from '../../config/config';-import type { IUniverWorkbenchProps } from '../../views/workbench/Workbench';import type { IUIController, IWorkbenchOptions } from './ui.controller';import { Inject, Injector, IUniverInstanceService, LifecycleService, toDisposable } from '@univerjs/core';-import { render as createRoot, unmount } from '@univerjs/design';+import { unmount } from '@univerjs/design';import { IRenderManagerService } from '@univerjs/engine-render';import { ComponentManager } from '../../common';import { menuSchema } from '../../menu/schema';@@ -31,7 +29,7 @@ import { connectInjector } from '../../utils/di';import { FloatDom } from '../../views/components/dom/FloatDom';import { CanvasPopup } from '../../views/components/popup/CanvasPopup';import { MobileRibbon } from '../../views/components/ribbon/MobileRibbon';-import { MobileWorkbench } from '../../views/mobile-workbench/MobileWorkbench';+import { mountMobileWorkbench } from '../../views/mobile-workbench/MobileWorkbench';import { SingleUnitUIController } from './ui-shared.controller';export class MobileUIController extends SingleUnitUIController implements IUIController {@@ -90,18 +88,10 @@ function bootstrap(mountContainer = createContainer('univer');}- const ConnectedApp = connectInjector(MobileWorkbench, injector) as ComponentType<IUniverWorkbenchProps>;const onRendered = (canvasElement: HTMLElement) => callback(canvasElement, mountContainer);function render() {- createRoot(- <ConnectedApp- {...options}- mountContainer={mountContainer}- onRendered={onRendered}- />,- mountContainer- );+ mountMobileWorkbench(injector, options, mountContainer, onRendered);}render();diff --git a/packages/ui/src/facade/__tests__/f-ui.spec.ts b/packages/ui/src/facade/__tests__/f-ui.spec.tsnew file mode 100644index 0000000000..6120434921--- /dev/null+++ b/packages/ui/src/facade/__tests__/f-ui.spec.ts@@ -0,0 +1,212 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, ICommandService, ILogService, LogLevel, Univer } from '@univerjs/core';+import { FUniver } from '@univerjs/core/facade';+import { MessageType } from '@univerjs/design';+import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import {+ BuiltInUIPart,+ ComponentManager,+ CopyCommand,+ DesktopDialogService,+ DesktopMessageService,+ DesktopSidebarService,+ FontService,+ IDialogService,+ IFontService,+ IMenuManagerService,+ IMessageService,+ IPlatformService,+ IShortcutService,+ ISidebarService,+ IUIPartsService,+ KeyCode,+ MenuManagerService,+ PasteCommand,+ PlatformService,+ ShortcutService,+ UIPartsService,+} from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import '@univerjs/ui/facade';++describe('ui facade', () => {+ let univer: Univer;+ let univerAPI: FUniver;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();++ injector.add([ComponentManager]);+ injector.add([IDialogService, { useClass: DesktopDialogService }]);+ injector.add([IFontService, { useClass: FontService }]);+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);+ injector.add([IMessageService, { useClass: DesktopMessageService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);++ univerAPI = FUniver.newAPI(injector);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('adds custom menus and executes their user action through command service', async () => {+ const injector = univer.__getInjector();+ const menuManagerService = injector.get(IMenuManagerService);+ const commandService = injector.get(ICommandService);+ const actionCalls: string[] = [];++ univerAPI.createMenu({+ id: 'custom-menu',+ title: 'Custom Menu',+ action: () => actionCalls.push('clicked'),+ order: 1,+ }).appendTo('contextMenu.others');++ const menuItem = menuManagerService.getFlatMenuByPositionKey('contextMenu').find((item) => item.item?.id === 'custom-menu')?.item;++ expect(menuItem?.title).toBe('Custom Menu');+ expect(menuItem?.commandId).toBeDefined();+ await commandService.executeCommand(menuItem!.commandId!);+ expect(actionCalls).toEqual(['clicked']);+ });++ it('adds grouped submenu entries into menu positions', () => {+ const menuManagerService = univer.__getInjector().get(IMenuManagerService);++ const first = univerAPI.createMenu({ id: 'first-action', title: 'First', action: 'first.command' });+ const second = univerAPI.createMenu({ id: 'second-action', title: 'Second', action: 'second.command' });+ univerAPI.createSubmenu({ id: 'custom-submenu', title: 'Actions' })+ .addSubmenu(first)+ .addSeparator()+ .addSubmenu(second)+ .appendTo('contextMenu.others');++ const menuKeys = menuManagerService.getFlatMenuByPositionKey('contextMenu').map((item) => item.key);++ expect(menuKeys).toContain('custom-submenu');+ expect(menuKeys).toContain('first-action');+ expect(menuKeys).toContain('second-action');+ });++ it('registers UI parts, toggles visibility, and exposes UI enums from the facade', () => {+ const component = () => null;+ const disposable = univerAPI.registerUIPart(BuiltInUIPart.CUSTOM_HEADER, component);+ const uiPartsService = univer.__getInjector().get(IUIPartsService);++ expect(univerAPI.Enum.BuiltInUIPart.CUSTOM_HEADER).toBe(BuiltInUIPart.CUSTOM_HEADER);+ expect(univerAPI.setUIVisible(BuiltInUIPart.CUSTOM_HEADER, false)).toBe(univerAPI);+ expect(univerAPI.isUIVisible(BuiltInUIPart.CUSTOM_HEADER)).toBe(false);+ expect(uiPartsService.getComponents(BuiltInUIPart.CUSTOM_HEADER).size).toBe(1);++ disposable.dispose();+ expect(uiPartsService.getComponents(BuiltInUIPart.CUSTOM_HEADER).size).toBe(0);+ });++ it('dispatches shortcut events unless the shortcut facade is disabled', () => {+ const shortcutService = univer.__getInjector().get(IShortcutService);+ const shortcut = univerAPI.getShortcut();+ shortcutService.registerShortcut({+ id: 'custom.shortcut',+ binding: KeyCode.B,+ });++ const event = new KeyboardEvent('keydown', { key: 'b', keyCode: KeyCode.B });++ expect(shortcut.disableShortcut().dispatchShortcutEvent(event)).toBeUndefined();+ expect(shortcut.enableShortcut().dispatchShortcutEvent(event)?.id).toBe('custom.shortcut');+ });++ it('fires clipboard hooks around copy commands', async () => {+ const commandService = univer.__getInjector().get(ICommandService);+ commandService.registerCommand({+ id: CopyCommand.id,+ type: CommandType.COMMAND,+ handler: () => true,+ });+ commandService.registerCommand({+ id: PasteCommand.id,+ type: CommandType.COMMAND,+ handler: () => true,+ });++ const events: string[] = [];+ const hooks = univerAPI.getHooks();+ const beforeDisposable = hooks.onBeforeCopy(() => events.push('before-copy'));+ const afterDisposable = hooks.onCopy(() => events.push('copy'));+ const beforePasteDisposable = hooks.onBeforePaste(() => events.push('before-paste'));+ const afterPasteDisposable = hooks.onPaste(() => events.push('paste'));++ await expect(univerAPI.copy()).resolves.toBe(true);+ await expect(univerAPI.paste()).resolves.toBe(true);++ expect(events).toEqual(['before-copy', 'copy', 'before-paste', 'paste']);+ beforeDisposable.dispose();+ afterDisposable.dispose();+ beforePasteDisposable.dispose();+ afterPasteDisposable.dispose();+ });++ it('opens and disposes UI surfaces through facade services', () => {+ const injector = univer.__getInjector();+ const sidebarService = injector.get(ISidebarService);+ const dialogService = injector.get(IDialogService);+ const dialogs: string[][] = [];+ const subscription = dialogService.getDialogs$().subscribe((items) => dialogs.push(items.map((item) => item.id)));++ const sidebarDisposable = univerAPI.openSidebar({ id: 'inspector', width: 320 });+ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options.id).toBe('inspector');+ sidebarDisposable.dispose();+ expect(sidebarService.visible).toBe(false);++ const dialogDisposable = univerAPI.openDialog({ id: 'confirm-dialog', title: { label: 'Confirm' } });+ expect(dialogs.at(-1)).toEqual(['confirm-dialog']);+ dialogDisposable.dispose();+ expect(dialogs.at(-1)).toEqual([]);++ expect(univerAPI.showMessage({ content: 'Saved', type: MessageType.Success, id: 'saved-message' })).toBe(univerAPI);++ subscription.unsubscribe();+ });++ it('registers components and appends custom fonts through facade APIs', () => {+ const injector = univer.__getInjector();+ const componentManager = injector.get(ComponentManager);+ const fontService = injector.get(IFontService);+ const component = () => null;++ const disposable = univerAPI.registerComponent('custom-component', component);+ univerAPI.addFonts([{ value: 'CustomSans', label: 'Custom Sans', category: 'sans-serif' }]);++ expect(univerAPI.getURL().href).toBe(window.location.href);+ expect(univerAPI.getComponentManager()).toBe(componentManager);+ expect(componentManager.get('custom-component')).toBe(component);+ expect(fontService.getFontByValue('CustomSans')).toMatchObject({ label: 'Custom Sans' });++ disposable.dispose();+ expect(componentManager.get('custom-component')).toBeUndefined();+ });+});diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 534f17b826..b293aa197c 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -58,7 +58,7 @@ export { ContextMenuService, type IContextMenuHandler, IContextMenuService } froexport { DesktopDialogService } from './services/dialog/desktop-dialog.service';export { IDialogService } from './services/dialog/dialog.service';export { CanvasFloatDomService, type IFloatDom, type IFloatDomLayout } from './services/dom/canvas-dom-layer.service';-export { type IFontConfig, IFontService } from './services/font.service';+export { FontService, type IFontConfig, IFontService } from './services/font.service';export { DesktopGalleryService } from './services/gallery/desktop-gallery.service';export { IGalleryService } from './services/gallery/gallery.service';export { DesktopLayoutService, ILayoutService } from './services/layout/layout.service';diff --git a/packages/ui/src/services/__tests__/core-services.spec.ts b/packages/ui/src/services/__tests__/core-services.spec.tsdeleted file mode 100644index 665756c0a5..0000000000--- a/packages/ui/src/services/__tests__/core-services.spec.ts+++ /dev/null@@ -1,449 +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 { IMenuButtonItem, IMenuItem } from '../menu/menu';-import { BehaviorSubject, Subject } from 'rxjs';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { CONTEXT_MENU_SUBMENU_CLOSE_DELAY, hasRenderableContextMenuSchema } from '../../views/components/context-menu/ContextMenuPanel';-import { MenuItemType } from '../menu/menu';-import { MenuManagerService } from '../menu/menu-manager.service';-import { ContextMenuGroup, ContextMenuPosition, MenuManagerPosition, 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,- },- },- },- });-- service.appendRootMenu({- [MenuManagerPosition.RIBBON]: {- contextualTab: {- order: 99,- contextual: true,- contextualGroup: {- order: 0,- customItem: {- order: 1,- menuItemFactory: customFactory,- },- },- },- },- });-- const historyMenu = service.getMenuByPositionKey(RibbonStartGroup.HISTORY);- const flatHistory = service.getFlatMenuByPositionKey(RibbonStartGroup.HISTORY);- const customRoot = service.getMenuByPositionKey('customRoot');- const ribbonMenu = service.getMenuByPositionKey(MenuManagerPosition.RIBBON);- 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);- expect(ribbonMenu.find((item) => item.key === 'contextualTab')?.contextual).toBe(true);-- const complete = vi.fn();- service.menuChanged$.subscribe({ complete });- service.dispose();- expect(complete).toHaveBeenCalledTimes(1);- });-- it('sorts menu groups by order after independent merges', () => {- const service = new MenuManagerService({ invoke: vi.fn((factory: any) => factory({})) } as any, { getConfig: vi.fn() } as any);-- service.mergeMenu({- [ContextMenuPosition.PARAGRAPH]: {- emptyParagraph: {- [ContextMenuGroup.LAYOUT]: {- order: 1,- layoutItem: {- order: 0,- menuItemFactory: () => ({- id: 'layoutItem',- type: MenuItemType.BUTTON,- } as IMenuButtonItem),- },- },- },- },- });- service.mergeMenu({- [ContextMenuPosition.PARAGRAPH]: {- emptyParagraph: {- [ContextMenuGroup.QUICK]: {- order: -1,- quickItem: {- order: 0,- menuItemFactory: () => ({- id: 'quickItem',- type: MenuItemType.BUTTON,- } as IMenuButtonItem),- },- },- },- },- });-- expect(service.getMenuByPositionKey('emptyParagraph').map((item) => item.key)).toEqual([- ContextMenuGroup.QUICK,- ContextMenuGroup.LAYOUT,- ]);- });-- it('replaces an existing menu node without preserving stale children', () => {- const service = new MenuManagerService({ invoke: vi.fn((factory: any) => factory({})) } as any, { getConfig: vi.fn() } as any);-- service.mergeMenu({- [ContextMenuPosition.PARAGRAPH]: {- shapeMenu: {- order: 1,- child: {- order: 0,- menuItemFactory: () => ({- id: 'shape-child',- type: MenuItemType.BUTTON,- } as IMenuButtonItem),- },- menuItemFactory: () => ({- id: 'shapeMenu',- type: MenuItemType.SUBITEMS,- } as IMenuItem),- },- },- });- service.mergeMenu({- [ContextMenuPosition.PARAGRAPH]: {- shapeMenu: {- replace: true,- order: 1,- menuItemFactory: () => ({- id: 'shapeMenu',- type: MenuItemType.SELECTOR,- } as IMenuItem),- },- },- });- service.mergeMenu({- [ContextMenuPosition.PARAGRAPH]: {- shapeMenu: {- childFromLateMerge: {- order: 0,- menuItemFactory: () => ({- id: 'late-shape-child',- type: MenuItemType.BUTTON,- } as IMenuButtonItem),- },- },- },- });-- const shapeMenu = service.getMenuByPositionKey(ContextMenuPosition.PARAGRAPH).find((item) => item.key === 'shapeMenu');- expect(shapeMenu?.item?.type).toBe(MenuItemType.SELECTOR);- expect(shapeMenu?.children).toBeUndefined();- });-- it('ignores nested context menu containers that have no direct renderable items', () => {- expect(hasRenderableContextMenuSchema({- key: 'emptyParagraph',- children: [{- key: ContextMenuGroup.QUICK,- children: [{- key: 'h1',- item: {- id: 'h1',- type: MenuItemType.BUTTON,- } as any,- }],- }],- } as any)).toBe(false);-- expect(hasRenderableContextMenuSchema({- key: ContextMenuGroup.LAYOUT,- children: [{- key: 'insertBelow',- item: {- id: 'insertBelow',- type: MenuItemType.SUBITEMS,- } as any,- }],- } as any)).toBe(true);- });-- it('keeps nested context menus open long enough for pointer travel', () => {- expect(CONTEXT_MENU_SUBMENU_CLOSE_DELAY).toBeGreaterThanOrEqual(400);- });-});--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();- });-- it('should show, activate, and restore contextual ribbon tabs', () => {- const ribbonData: any[] = [- {- key: RibbonPosition.START,- order: 0,- children: [- {- key: RibbonStartGroup.HISTORY,- order: 0,- children: [- {- key: 'home-child',- order: 0,- item: {- id: 'home-child',- type: MenuItemType.BUTTON,- },- },- ],- },- ],- },- {- key: RibbonPosition.INSERT,- order: 1,- children: [- {- key: 'insert-group',- order: 0,- children: [- {- key: 'insert-child',- order: 0,- item: {- id: 'insert-child',- type: MenuItemType.BUTTON,- },- },- ],- },- ],- },- {- key: 'contextual.shape',- order: 100,- contextual: true,- children: [- {- key: 'contextual-group',- order: 0,- children: [- {- key: 'contextual-child',- order: 0,- item: {- id: 'contextual-child',- type: MenuItemType.BUTTON,- },- },- ],- },- ],- },- ];-- 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 currentRibbon: any[] = [];-- service.activatedTab$.subscribe((v) => (activatedTab = v));- service.ribbon$.subscribe((v) => (currentRibbon = v));-- expect(currentRibbon.map((item) => item.key)).toEqual([RibbonPosition.START, RibbonPosition.INSERT]);-- service.setActivatedTab(RibbonPosition.INSERT);- service.showContextualTab('contextual.shape', { activate: true });-- expect(currentRibbon.map((item) => item.key)).toEqual([- RibbonPosition.START,- RibbonPosition.INSERT,- 'contextual.shape',- ]);- expect(activatedTab).toBe('contextual.shape');-- service.hideContextualTab('contextual.shape');-- expect(currentRibbon.map((item) => item.key)).toEqual([RibbonPosition.START, RibbonPosition.INSERT]);- expect(activatedTab).toBe(RibbonPosition.INSERT);-- service.showContextualTab('contextual.shape');- expect(activatedTab).toBe(RibbonPosition.INSERT);-- service.setActivatedTab('contextual.shape');- service.hideAllContextualTabs();-- expect(currentRibbon.map((item) => item.key)).toEqual([RibbonPosition.START, RibbonPosition.INSERT]);- expect(activatedTab).toBe(RibbonPosition.INSERT);-- 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.tsdeleted file mode 100644index c2053d4cd9..0000000000--- a/packages/ui/src/services/__tests__/desktop-services.spec.ts+++ /dev/null@@ -1,350 +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 { IGalleryProps, IMessageProps } from '@univerjs/design';-import type { IConfirmPartMethodOptions } from '../../views/components/confirm-part/interface';-import type { IDialogPartMethodOptions } from '../../views/components/dialog-part/interface';-import { ILocalStorageService, Injector } from '@univerjs/core';-import { afterEach, beforeEach, 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('../../views/notification/Notification', () => ({- Notification: () => null,- notification: {- show: 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('../../views/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);- });-});--const STORAGE_PREFIX = 'UniverLocalStorage/';--function clearOwnStorage() {- const toRemove: string[] = [];- for (let i = 0; i < localStorage.length; i++) {- const k = localStorage.key(i)!;- if (k.startsWith(STORAGE_PREFIX)) {- toRemove.push(k);- }- }- toRemove.forEach((k) => localStorage.removeItem(k));-}--describe('DesktopLocalStorageService', () => {- let injector: Injector;- let service: ILocalStorageService;-- beforeEach(() => {- clearOwnStorage();- injector = new Injector();- injector.add([ILocalStorageService, { useClass: DesktopLocalStorageService }]);- service = injector.get(ILocalStorageService);- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it('should store and retrieve values', async () => {- await service.setItem('key', 'value');- const value = await service.getItem<string>('key');- expect(value).toBe('value');- });-- it('should remove items', async () => {- await service.setItem('key', 'value');- await service.removeItem('key');- const value = await service.getItem('key');- expect(value).toBeNull();- });-- it('should clear all items', async () => {- await service.setItem('a', 1);- await service.setItem('b', 2);- await service.clear();- expect(await service.getItem('a')).toBeNull();- expect(await service.getItem('b')).toBeNull();- });-- it('should return keys', async () => {- await service.setItem('x', 1);- await service.setItem('y', 2);- const keys = await service.keys();- expect(keys).toContain('x');- expect(keys).toContain('y');- });-- it('should support key by index', async () => {- await service.setItem('only', 1);- const key = await service.key(0);- expect(key).toBe('only');- });-- it('should support iterate', async () => {- await service.setItem('a', 1);- await service.setItem('b', 2);-- const collected: Array<{ value: number; key: string }> = [];- await service.iterate<number, void>((value, key) => {- collected.push({ value, key });- });-- expect(collected).toHaveLength(2);- });-});diff --git a/packages/ui/src/services/__tests__/font.spec.ts b/packages/ui/src/services/__tests__/font.spec.tsdeleted file mode 100644index 6ba6a192c7..0000000000--- a/packages/ui/src/services/__tests__/font.spec.ts+++ /dev/null@@ -1,197 +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 { IConfigService, Injector } from '@univerjs/core';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { FontService } from '../font.service';--describe('FontService', () => {- let injector: Injector;- let fontService: FontService;- let configService: IConfigService;-- beforeEach(() => {- injector = new Injector();- configService = {- getConfig: vi.fn(),- } as unknown as IConfigService;-- injector.add([IConfigService, { useValue: configService }]);- 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);- const fonts = fontService.getFonts();- expect(fonts.length).toBe(13);- expect(fonts.find((f) => f.value === 'Arial')).toBeDefined();- });-- it('should initialize with custom fonts (array)', () => {- const customFonts = [{ value: 'Custom', label: 'Custom Font' }];- vi.mocked(configService.getConfig).mockReturnValue({- customFontFamily: customFonts,- });- fontService = injector.get(FontService);- const fonts = fontService.getFonts();- expect(fonts).toHaveLength(14); // Default (13) + Custom (1)- expect(fonts.find((f) => f.value === 'Custom')).toBeDefined();- });-- it('should initialize with custom fonts (override)', () => {- const customFonts = {- override: true,- list: [{ value: 'Custom', label: 'Custom Font' }],- };- vi.mocked(configService.getConfig).mockReturnValue({- customFontFamily: customFonts,- });- fontService = injector.get(FontService);- const fonts = fontService.getFonts();- expect(fonts).toHaveLength(1);- expect(fonts[0].value).toBe('Custom');- });-- it('should initialize with custom fonts (append)', () => {- const customFonts = {- override: false,- list: [{ value: 'Custom', label: 'Custom Font' }],- };- vi.mocked(configService.getConfig).mockReturnValue({- customFontFamily: customFonts,- });- fontService = injector.get(FontService);- const fonts = fontService.getFonts();- expect(fonts).toHaveLength(14);- expect(fonts.find((f) => f.value === 'Custom')).toBeDefined();- expect(fonts.find((f) => f.value === 'Arial')).toBeDefined();- });-- it('should add a font', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- const newFont = { value: 'New', label: 'New Font' };- fontService.addFont(newFont);- expect(fontService.getFontByValue('New')).toEqual(newFont);- });-- it('should throw error when adding existing font', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- expect(() => fontService.addFont({ value: 'Arial', label: 'Arial' })).toThrow();- });-- it('should update a font', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- fontService.updateFont('Arial', { label: 'New Arial' });- expect(fontService.getFontByValue('Arial')?.label).toBe('New Arial');- });-- it('should throw error when updating non-existing font', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- expect(() => fontService.updateFont('NotExist', { label: 'New' })).toThrow();- });-- it('should remove a font', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- expect(fontService.removeFont('Arial')).toBe(true);- expect(fontService.getFontByValue('Arial')).toBeUndefined();- });-- it('should return false when removing non-existing font', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- expect(fontService.removeFont('NotExist')).toBe(false);- });-- it('should reset to defaults', () => {- vi.mocked(configService.getConfig).mockReturnValue(undefined);- fontService = injector.get(FontService);- fontService.removeFont('Arial');- fontService.resetToDefaults();- 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.tsdeleted file mode 100644index 1ab821147f..0000000000--- a/packages/ui/src/services/__tests__/misc-services.spec.ts+++ /dev/null@@ -1,474 +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 { 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 { CanvasFloatDomService } from '../dom/canvas-dom-layer.service';-import { isMenuButtonSelectorItem, isMenuSelectorItem, MenuItemType } from '../menu/menu';-import { CanvasPopupService } from '../popup/canvas-popup.service';-import { DesktopSidebarService } from '../sidebar/desktop-sidebar.service';-import { ThemeSwitcherService } from '../theme-switcher/theme-switcher.service';--describe('clipboard capability detection', () => {- afterEach(() => {- vi.restoreAllMocks();- });-- it('should report clipboard as unsupported when navigator.clipboard is missing', () => {- Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });- expect(supportClipboardAPI()).toBe(false);- });-- it('should report clipboard as supported when navigator.clipboard.readText is available', () => {- Object.defineProperty(navigator, 'clipboard', {- configurable: true,- value: { readText: vi.fn() },- });- expect(supportClipboardAPI()).toBe(true);- });-});--describe('menu item type guards', () => {- it('should recognize selector and subitems as menu selector items', () => {- expect(isMenuSelectorItem({ type: MenuItemType.SELECTOR } as any)).toBe(true);- expect(isMenuSelectorItem({ type: MenuItemType.SUBITEMS } as any)).toBe(true);- });-- it('should not recognize button or button-selector as menu selector items', () => {- expect(isMenuSelectorItem({ type: MenuItemType.BUTTON } as any)).toBe(false);- expect(isMenuSelectorItem({ type: MenuItemType.BUTTON_SELECTOR } as any)).toBe(false);- });-- it('should recognize button-selector as menu button-selector item', () => {- expect(isMenuButtonSelectorItem({ type: MenuItemType.BUTTON_SELECTOR } as any)).toBe(true);- });-- it('should not recognize plain button as menu button-selector item', () => {- expect(isMenuButtonSelectorItem({ type: MenuItemType.BUTTON } as any)).toBe(false);- });-});--describe('context menu service', () => {- it('should forward context menu events to the registered handler', () => {- const service = new ContextMenuService();- const handler = {- visible: true,- handleContextMenu: vi.fn(),- hideContextMenu: vi.fn(),- };-- service.registerContextMenuHandler(handler);-- const event = { stopPropagation: vi.fn() } as any;- service.triggerContextMenu(event, 'main');-- expect(service.visible).toBe(true);- expect(handler.handleContextMenu).toHaveBeenCalledWith(event, 'main');- });-- it('should suppress context menu events while disabled', () => {- const service = new ContextMenuService();- const handler = {- visible: true,- handleContextMenu: vi.fn(),- hideContextMenu: vi.fn(),- };-- service.registerContextMenuHandler(handler);- service.disable();-- const event = { stopPropagation: vi.fn() } as any;- service.triggerContextMenu(event, 'main');-- expect(service.disabled).toBe(true);- expect(handler.handleContextMenu).not.toHaveBeenCalled();- });-- it('should resume forwarding after re-enabling', () => {- const service = new ContextMenuService();- const handler = {- visible: true,- handleContextMenu: vi.fn(),- hideContextMenu: vi.fn(),- };-- service.registerContextMenuHandler(handler);- service.disable();- service.enable();-- const event = { stopPropagation: vi.fn() } as any;- service.triggerContextMenu(event, 'main');-- expect(handler.handleContextMenu).toHaveBeenCalledTimes(1);- });-- it('should hide the context menu through the handler', () => {- const service = new ContextMenuService();- const handler = {- visible: true,- handleContextMenu: vi.fn(),- hideContextMenu: vi.fn(),- };-- service.registerContextMenuHandler(handler);- service.hideContextMenu();- expect(handler.hideContextMenu).toHaveBeenCalledTimes(1);- });-- it('should throw when registering a handler twice', () => {- const service = new ContextMenuService();- const handler = { visible: true, handleContextMenu: vi.fn(), hideContextMenu: vi.fn() };-- service.registerContextMenuHandler(handler);- expect(() => service.registerContextMenuHandler(handler)).toThrow();- });-- it('should clean up visibility when the handler is disposed', () => {- const service = new ContextMenuService();- const handler = {- visible: true,- handleContextMenu: vi.fn(),- hideContextMenu: vi.fn(),- };-- const disposable = service.registerContextMenuHandler(handler);- service.triggerContextMenu({ stopPropagation: vi.fn() } as any, 'main');- expect(service.visible).toBe(true);-- disposable.dispose();- expect(service.visible).toBe(false);- });-});--describe('context menu host service', () => {- it('should activate a registered menu and track it as the active menu', () => {- const service = new ContextMenuHostService();- const hide = vi.fn();-- service.registerMenu('menu-a', hide);- service.activateMenu('menu-a');-- expect(service.activeMenuId).toBe('menu-a');- });-- it('should hide the previous menu when activating a different one', () => {- const service = new ContextMenuHostService();- const hideA = vi.fn();- const hideB = vi.fn();-- service.registerMenu('menu-a', hideA);- service.registerMenu('menu-b', hideB);-- service.activateMenu('menu-a');- service.activateMenu('menu-b');-- expect(hideA).toHaveBeenCalledTimes(1);- expect(service.activeMenuId).toBe('menu-b');- });-- it('should hide the active menu when requested', () => {- const service = new ContextMenuHostService();- const hide = vi.fn();-- service.registerMenu('menu-a', hide);- service.activateMenu('menu-a');- service.hideActiveMenu();-- expect(hide).toHaveBeenCalledTimes(1);- expect(service.activeMenuId).toBeNull();- });-- it('should skip hiding when the active menu matches the excepted id', () => {- const service = new ContextMenuHostService();- const hide = vi.fn();-- service.registerMenu('menu-a', hide);- service.activateMenu('menu-a');- service.hideActiveMenu('menu-a');-- expect(hide).not.toHaveBeenCalled();- expect(service.activeMenuId).toBe('menu-a');- });-- it('should clear active state when a menu is deactivated', () => {- const service = new ContextMenuHostService();-- service.registerMenu('menu-a', vi.fn());- service.activateMenu('menu-a');- service.deactivateMenu('menu-a');-- expect(service.activeMenuId).toBeNull();- });-- it('should allow re-activating a menu after it was deactivated', () => {- const service = new ContextMenuHostService();-- service.registerMenu('menu-a', vi.fn());- service.activateMenu('menu-a');- service.deactivateMenu('menu-a');- service.activateMenu('menu-a');-- expect(service.activeMenuId).toBe('menu-a');- });-});--describe('canvas float DOM service', () => {- function createFloatDom(id: string): any {- return {- id,- componentKey: 'test-component',- unitId: 'unit-1',- onPointerMove: vi.fn(),- onPointerDown: vi.fn(),- onPointerUp: vi.fn(),- onWheel: vi.fn(),- position$: new BehaviorSubject({- left: 0,- top: 0,- rotate: 0,- width: 100,- height: 100,- absolute: { left: true, top: true },- }),- };- }-- it('should reflect newly added float DOM in the domLayers list', () => {- const service = new CanvasFloatDomService();- service.addFloatDom(createFloatDom('dom-1'));-- expect(service.domLayers).toHaveLength(1);- expect(service.domLayers[0][0]).toBe('dom-1');- });-- it('should update an existing float DOM by id', () => {- const service = new CanvasFloatDomService();- service.addFloatDom(createFloatDom('dom-1'));- service.updateFloatDom('dom-1', { componentKey: 'updated-component' } as any);-- expect(service.domLayers[0][1].componentKey).toBe('updated-component');- });-- it('should silently ignore updates to non-existent float DOM ids', () => {- const service = new CanvasFloatDomService();- service.addFloatDom(createFloatDom('dom-1'));-- expect(() => service.updateFloatDom('missing', { componentKey: 'x' } as any)).not.toThrow();- expect(service.domLayers).toHaveLength(1);- });-- it('should remove a float DOM by id', () => {- const service = new CanvasFloatDomService();- service.addFloatDom(createFloatDom('dom-1'));- service.addFloatDom(createFloatDom('dom-2'));- service.removeFloatDom('dom-1');-- expect(service.domLayers).toHaveLength(1);- expect(service.domLayers[0][0]).toBe('dom-2');- });-- it('should clear all float DOMs when removeAll is called', () => {- const service = new CanvasFloatDomService();- service.addFloatDom(createFloatDom('dom-1'));- service.addFloatDom(createFloatDom('dom-2'));- service.removeAll();-- expect(service.domLayers).toHaveLength(0);- });-- it('should emit domLayers changes through the observable', () => {- const service = new CanvasFloatDomService();- const emissions: any[] = [];- service.domLayers$.subscribe((layers) => emissions.push(layers.length));-- service.addFloatDom(createFloatDom('dom-1'));- service.addFloatDom(createFloatDom('dom-2'));- service.removeFloatDom('dom-1');-- expect(emissions.at(-1)).toBe(1);- });-});--describe('canvas popup service', () => {- function createPopup(overrides: Partial<any> = {}): any {- return {- componentKey: 'test-popup',- unitId: 'unit-1',- subUnitId: 'sheet-1',- canvasElement: document.createElement('canvas'),- anchorRect$: new BehaviorSubject({}),- ...overrides,- };- }-- it('should assign a unique id when adding a popup', () => {- const service = new CanvasPopupService();- const id = service.addPopup(createPopup());-- expect(id).toBeTruthy();- expect(service.popups).toHaveLength(1);- });-- it('should track the active popup id when onActiveChange is triggered', () => {- const service = new CanvasPopupService();- const id = service.addPopup(createPopup());-- const popup = service.popups[0][1];- popup.onActiveChange?.(true);- expect(service.activePopupId).toBe(id);-- popup.onActiveChange?.(false);- expect(service.activePopupId).toBeNull();- });-- it('should remove a popup by id and clear the activePopupId if it was active', () => {- const service = new CanvasPopupService();- const id = service.addPopup(createPopup());-- service.popups[0][1].onActiveChange?.(true);- expect(service.activePopupId).toBe(id);-- service.removePopup(id);- expect(service.popups).toHaveLength(0);- });-- it('should ignore removal of non-existent popup ids', () => {- const service = new CanvasPopupService();- service.addPopup(createPopup());-- expect(() => service.removePopup('non-existent')).not.toThrow();- expect(service.popups).toHaveLength(1);- });-- it('should remove all popups and reset state', () => {- const service = new CanvasPopupService();- service.addPopup(createPopup());- service.addPopup(createPopup());- service.removeAll();-- expect(service.popups).toHaveLength(0);- expect(service.activePopupId).toBeNull();- });-- it('should clear all popups on dispose', () => {- const service = new CanvasPopupService();- service.addPopup(createPopup());- service.dispose();-- expect(service.popups).toHaveLength(0);- });-});--describe('sidebar service', () => {- it('should become visible after opening a sidebar panel', () => {- const service = new DesktopSidebarService();- service.open({ id: 'panel-1' });-- expect(service.visible).toBe(true);- expect(service.options.id).toBe('panel-1');- });-- it('should ignore close requests with a mismatched panel id', () => {- const service = new DesktopSidebarService();- service.open({ id: 'panel-1' });- service.close('panel-2');-- expect(service.visible).toBe(true);- });-- it('should hide the sidebar and invoke onClose when the correct id is closed', () => {- const service = new DesktopSidebarService();- const onClose = vi.fn();- service.open({ id: 'panel-1', onClose });- service.close('panel-1');-- expect(service.visible).toBe(false);- expect(onClose).toHaveBeenCalledTimes(1);- });-- it('should invoke onClose when the open disposable is disposed', () => {- const service = new DesktopSidebarService();- const onClose = vi.fn();- const disposable = service.open({ id: 'panel-1', onClose });-- disposable.dispose();- expect(onClose).toHaveBeenCalledTimes(1);- expect(service.visible).toBe(false);- });-- it('should replace the current panel when opening a different one', () => {- const service = new DesktopSidebarService();- service.open({ id: 'panel-1' });- service.open({ id: 'panel-2' });-- expect(service.options.id).toBe('panel-2');- expect(service.visible).toBe(true);- });-- it('should allow setting and retrieving the sidebar container element', () => {- const service = new DesktopSidebarService();- const container = document.createElement('div');-- service.setContainer(container);- expect(service.getContainer()).toBe(container);- });-- it('should notify subscribers when the sidebar state changes', () => {- const service = new DesktopSidebarService();- const states: any[] = [];- service.sidebarOptions$.subscribe((opts) => states.push(opts));-- service.open({ id: 'panel-1' });- service.close('panel-1');-- expect(states.length).toBeGreaterThanOrEqual(2);- });-});--describe('theme switcher service', () => {- afterEach(() => {- const existing = document.getElementById('univer-theme-css-variables');- if (existing) {- existing.remove();- }- });-- it('should inject theme CSS variables into the document head', () => {- const service = new ThemeSwitcherService();- service.injectThemeToHead({- color: { primary: '#ffffff' },- spacing: 8,- } as any);-- const style = document.getElementById('univer-theme-css-variables');- expect(style).toBeTruthy();- expect(style?.textContent).toContain('--univer-color-primary: #ffffff');- expect(style?.textContent).toContain('--univer-spacing: 8');- });-- it('should replace the existing style element instead of creating duplicates', () => {- const service = new ThemeSwitcherService();- service.injectThemeToHead({ color: { primary: '#fff' } } as any);- service.injectThemeToHead({ color: { primary: '#000' } } as any);-- const styles = document.querySelectorAll('#univer-theme-css-variables');- expect(styles.length).toBe(1);- expect(styles[0]?.textContent).toContain('#000');- });-});diff --git a/packages/ui/src/services/before-close/__tests__/before-close.service.spec.ts b/packages/ui/src/services/before-close/__tests__/before-close.service.spec.tsnew file mode 100644index 0000000000..3a9ec09472--- /dev/null+++ b/packages/ui/src/services/before-close/__tests__/before-close.service.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 { Injector } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopNotificationService } from '../../notification/desktop-notification.service';+import { INotificationService } from '../../notification/notification.service';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';+import { DesktopBeforeCloseService, IBeforeCloseService } from '../before-close.service';++function createService(): IBeforeCloseService {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([INotificationService, { useClass: DesktopNotificationService }]);+ injector.add([IBeforeCloseService, { useClass: DesktopBeforeCloseService }]);+ return injector.get(IBeforeCloseService);+}++describe('DesktopBeforeCloseService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('runs close callbacks when the page unloads and stops after disposal', () => {+ const windowTarget = new EventTarget();+ vi.stubGlobal('window', windowTarget);+ const service = createService();+ const closed: string[] = [];+ const disposable = service.registerOnClose(() => closed.push('closed'));++ windowTarget.dispatchEvent(new Event('unload'));+ disposable.dispose();+ windowTarget.dispatchEvent(new Event('unload'));++ expect(closed).toEqual(['closed']);+ });++ it('registers the notification UI part used for blocked close messages', () => {+ const windowTarget = new EventTarget();+ vi.stubGlobal('window', windowTarget);+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([INotificationService, { useClass: DesktopNotificationService }]);+ injector.add([IBeforeCloseService, { useClass: DesktopBeforeCloseService }]);++ injector.get(IBeforeCloseService);+ expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);+ });+});diff --git a/packages/ui/src/services/confirm/__tests__/desktop-confirm.service.spec.ts b/packages/ui/src/services/confirm/__tests__/desktop-confirm.service.spec.tsnew file mode 100644index 0000000000..23f64e068e--- /dev/null+++ b/packages/ui/src/services/confirm/__tests__/desktop-confirm.service.spec.ts@@ -0,0 +1,52 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IConfirmPartMethodOptions } from '../../../views/components/confirm-part/interface';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';+import { DesktopConfirmService } from '../desktop-confirm.service';++function createService(): DesktopConfirmService {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([DesktopConfirmService]);+ return injector.get(DesktopConfirmService);+}++describe('DesktopConfirmService', () => {+ it('opens a confirm request and resolves it through the confirm callback', async () => {+ const service = createService();+ const opened: IConfirmPartMethodOptions[][] = [];+ const sub = service.confirmOptions$.subscribe((options) => opened.push(options));++ const promise = service.confirm({ id: 'save-confirm', children: 'Save changes?' });+ opened.at(-1)?.[0].onConfirm?.();++ await expect(promise).resolves.toBe(true);+ expect(opened.at(-1)).toEqual([]);+ sub.unsubscribe();+ });++ it('registers the global confirm UI part when constructed', () => {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([DesktopConfirmService]);++ injector.get(DesktopConfirmService);+ expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);+ });+});diff --git a/packages/ui/src/services/contextmenu/__tests__/contextmenu.service.spec.ts b/packages/ui/src/services/contextmenu/__tests__/contextmenu.service.spec.tsnew file mode 100644index 0000000000..18e08a8d67--- /dev/null+++ b/packages/ui/src/services/contextmenu/__tests__/contextmenu.service.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 { Injector } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';+import { ContextMenuService, IContextMenuService } from '../contextmenu.service';++function createService(): IContextMenuService {+ const injector = new Injector();+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);+ return injector.get(IContextMenuService);+}++describe('ContextMenuService', () => {+ it('routes context menu requests to the registered handler while enabled', () => {+ const service = createService();+ const handled: string[] = [];+ let visible = false;+ const event = { stopPropagation: vi.fn() };++ service.registerContextMenuHandler({+ get visible() {+ return visible;+ },+ handleContextMenu: (_event, menuType) => {+ visible = true;+ handled.push(menuType);+ },+ hideContextMenu: () => {+ visible = false;+ },+ });++ service.triggerContextMenu(event as never, 'cell');+ expect(handled).toEqual(['cell']);+ expect(event.stopPropagation).toHaveBeenCalledTimes(1);+ expect(service.visible).toBe(true);++ service.hideContextMenu();+ expect(service.visible).toBe(false);+ });++ it('suppresses handler execution while disabled and resumes after enable', () => {+ const service = createService();+ const handled: string[] = [];+ const event = { stopPropagation: vi.fn() };++ service.registerContextMenuHandler({+ visible: false,+ handleContextMenu: (_event, menuType) => handled.push(menuType),+ hideContextMenu: () => {},+ });++ service.disable();+ service.triggerContextMenu(event as never, 'row');+ service.enable();+ service.triggerContextMenu(event as never, 'column');++ expect(handled).toEqual(['column']);+ });+});diff --git a/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.spec.ts b/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.spec.tsnew file mode 100644index 0000000000..3db4bd500c--- /dev/null+++ b/packages/ui/src/services/dialog/__tests__/desktop-dialog.service.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 { IDialogPartMethodOptions } from '../../../views/components/dialog-part/interface';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';+import { DesktopDialogService } from '../desktop-dialog.service';+import { IDialogService } from '../dialog.service';++function createService(): IDialogService {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IDialogService, { useClass: DesktopDialogService }]);+ return injector.get(IDialogService);+}++describe('DesktopDialogService', () => {+ it('tracks opened dialogs and closes only the requested dialog', () => {+ const service = createService();+ const snapshots: IDialogPartMethodOptions[][] = [];+ const sub = service.getDialogs$().subscribe((options) => snapshots.push(options));++ service.open({ id: 'first' });+ service.open({ id: 'second' });+ service.close('first');++ expect(snapshots.at(-1)).toMatchObject([{ id: 'first', open: false }, { id: 'second', open: true }]);+ sub.unsubscribe();+ });++ it('keeps excepted dialogs open when closing all', () => {+ const service = createService();+ const snapshots: IDialogPartMethodOptions[][] = [];+ const sub = service.getDialogs$().subscribe((options) => snapshots.push(options));++ service.open({ id: 'first' });+ service.open({ id: 'second' });+ service.closeAll(['second']);++ expect(snapshots.at(-1)).toMatchObject([{ id: 'first', open: false }, { id: 'second', open: true }]);+ sub.unsubscribe();+ });++ it('registers the global dialog UI part when constructed', () => {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IDialogService, { useClass: DesktopDialogService }]);++ injector.get(IDialogService);+ expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);+ });+});diff --git a/packages/ui/src/services/dom/__tests__/canvas-dom-layer.service.spec.ts b/packages/ui/src/services/dom/__tests__/canvas-dom-layer.service.spec.tsnew file mode 100644index 0000000000..dddc03c43e--- /dev/null+++ b/packages/ui/src/services/dom/__tests__/canvas-dom-layer.service.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 type { IFloatDom, IFloatDomLayout } from '../canvas-dom-layer.service';+import { Injector } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { CanvasFloatDomService } from '../canvas-dom-layer.service';++function createService(): CanvasFloatDomService {+ const injector = new Injector();+ injector.add([CanvasFloatDomService]);+ return injector.get(CanvasFloatDomService);+}++function createFloatDom(id: string): IFloatDom {+ return {+ id,+ componentKey: 'shape',+ onPointerDown: () => {},+ onPointerMove: () => {},+ onPointerUp: () => {},+ onWheel: () => {},+ position$: new BehaviorSubject<IFloatDomLayout>({+ startX: 0,+ startY: 0,+ endX: 10,+ endY: 10,+ rotate: 0,+ width: 10,+ height: 10,+ absolute: { left: true, top: true },+ }),+ unitId: 'unit-1',+ };+}++describe('CanvasFloatDomService', () => {+ it('publishes floating DOM layer changes for canvas overlays', () => {+ const service = createService();+ const snapshots: Array<[string, IFloatDom][]> = [];+ const sub = service.domLayers$.subscribe((layers) => snapshots.push(layers));++ service.addFloatDom(createFloatDom('dom-1'));+ service.updateFloatDom('dom-1', { domId: 'runtime-dom-1' });+ service.removeFloatDom('dom-1');++ expect(snapshots.map((layers) => layers.length)).toEqual([0, 1, 1, 0]);+ expect(snapshots[2][0][1].domId).toBe('runtime-dom-1');+ sub.unsubscribe();+ });+});diff --git a/packages/ui/src/services/font.service.spec.ts b/packages/ui/src/services/font.service.spec.tsnew file mode 100644index 0000000000..cda7183447--- /dev/null+++ b/packages/ui/src/services/font.service.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 { ConfigService, IConfigService, Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { FontService, IFontService } from './font.service';++function createService(): IFontService {+ const injector = new Injector();+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IFontService, { useClass: FontService }]);+ return injector.get(IFontService);+}++describe('FontService', () => {+ it('maintains the font catalog used by font family pickers', () => {+ const service = createService();++ service.addFont({ value: 'Inter', label: 'Inter', category: 'sans-serif' });+ service.updateFont('Inter', { label: 'Inter UI' });++ expect(service.getFontByValue('Inter')).toMatchObject({ label: 'Inter UI' });+ expect(service.removeFont('Inter')).toBe(true);+ expect(service.getFontByValue('Inter')).toBeUndefined();+ });++ it('rejects duplicate font values to keep font selection stable', () => {+ const service = createService();+ const arial = service.getFontByValue('Arial')!;++ expect(() => service.addFont(arial)).toThrow('[FontService]: Font with value "Arial" already exists.');+ });+});diff --git a/packages/ui/src/services/gallery/__tests__/desktop-gallery.service.spec.ts b/packages/ui/src/services/gallery/__tests__/desktop-gallery.service.spec.tsnew file mode 100644index 0000000000..6d90360fab--- /dev/null+++ b/packages/ui/src/services/gallery/__tests__/desktop-gallery.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 type { IGalleryProps } from '@univerjs/design';+import { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';+import { DesktopGalleryService } from '../desktop-gallery.service';+import { IGalleryService } from '../gallery.service';++function createService(): IGalleryService {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IGalleryService, { useClass: DesktopGalleryService }]);+ return injector.get(IGalleryService);+}++describe('DesktopGalleryService', () => {+ it('publishes gallery open and close state for image preview workflows', () => {+ const service = createService();+ const snapshots: IGalleryProps[] = [];+ const sub = service.gallery$.subscribe((value) => snapshots.push(value));++ service.open({ images: ['a.png', 'b.png'] });+ service.close();++ expect(snapshots).toEqual([+ { open: true, images: ['a.png', 'b.png'] },+ { open: false, images: [] },+ ]);+ sub.unsubscribe();+ });++ it('registers the global gallery UI part when constructed', () => {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IGalleryService, { useClass: DesktopGalleryService }]);++ injector.get(IGalleryService);+ expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);+ });+});diff --git a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts b/packages/ui/src/services/layout/__tests__/layout.service.spec.tsnew file mode 100644index 0000000000..3c4a71fe5e--- /dev/null+++ b/packages/ui/src/services/layout/__tests__/layout.service.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 {+ ContextService,+ DesktopLogService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ UnitModel,+ UniverInstanceService,+ UniverInstanceType,+} from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopLayoutService, ILayoutService } from '../layout.service';++class TestSlideUnit extends UnitModel {+ override type = UniverInstanceType.UNIVER_SLIDE;+ private readonly _name$ = new BehaviorSubject('');+ override name$ = this._name$.asObservable();++ override getUnitId(): string {+ return 'slide-1';+ }++ override setName(name: string): void {+ this._name$.next(name);+ }++ override getSnapshot(): object {+ return { id: 'slide-1' };+ }++ override getRev(): number {+ return 1;+ }++ override incrementRev(): void {}++ override setRev(): void {}+}++function createElement(name: string, containsSelf = true) {+ return {+ dataset: { uComp: name },+ contains: (target: unknown) => containsSelf && target != null,+ } as unknown as HTMLElement;+}++function createService() {+ vi.stubGlobal('window', new EventTarget());+ vi.stubGlobal('document', { activeElement: null });+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);+ const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;+ const slide = injector.createInstance(TestSlideUnit);+ univerInstanceService.__addUnit(slide);+ univerInstanceService.focusUnit('slide-1');+ return {+ service: injector.get(ILayoutService),+ };+}++describe('DesktopLayoutService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('tracks registered containers and delegates focus to the focused Univer unit type', () => {+ const { service } = createService();+ const root = createElement('app-layout');+ const content = createElement('workbench-layout');+ const focused: string[] = [];++ const rootDisposable = service.registerRootContainerElement(root);+ const contentDisposable = service.registerContentElement(content);+ const focusDisposable = service.registerFocusHandler(UniverInstanceType.UNIVER_SLIDE, (unitId) => focused.push(unitId));++ expect(service.rootContainerElement).toBe(root);+ expect(service.getContentElement()).toBe(content);+ expect(service.checkElementInCurrentContainers(content)).toBe(true);++ service.focus();+ expect(focused).toEqual(['slide-1']);++ focusDisposable.dispose();+ contentDisposable.dispose();+ rootDisposable.dispose();+ expect(service.rootContainerElement).toBeNull();+ });+});diff --git a/packages/ui/src/services/local-file/__tests__/desktop-local-file.service.spec.ts b/packages/ui/src/services/local-file/__tests__/desktop-local-file.service.spec.tsnew file mode 100644index 0000000000..9603787dc5--- /dev/null+++ b/packages/ui/src/services/local-file/__tests__/desktop-local-file.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 { Injector } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopLocalFileService } from '../desktop-local-file.service';+import { ILocalFileService } from '../local-file.service';++function createService(): ILocalFileService {+ const injector = new Injector();+ injector.add([ILocalFileService, { useClass: DesktopLocalFileService }]);+ return injector.get(ILocalFileService);+}++describe('DesktopLocalFileService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('creates a file input with the requested picker options', async () => {+ const files = [new File(['a'], 'a.csv')];+ interface IInputStub {+ accept: string;+ click: ReturnType<typeof vi.fn>;+ multiple: boolean;+ onchange: (event: { target: { files: File[] } }) => void;+ type: string;+ }+ let input: IInputStub = {+ accept: '',+ click: vi.fn(),+ multiple: false,+ onchange: () => {},+ type: '',+ };+ vi.stubGlobal('document', {+ createElement: () => {+ input = {+ click: vi.fn(() => input.onchange({ target: { files } })),+ accept: '',+ multiple: false,+ onchange: () => {},+ type: '',+ };+ return input;+ },+ });+ const service = createService();++ await expect(service.openFile({ accept: '.csv', multiple: true })).resolves.toEqual(files);+ expect(input.type).toBe('file');+ expect(input.accept).toBe('.csv');+ expect(input.multiple).toBe(true);+ expect(input.click).toHaveBeenCalledTimes(1);+ });++ it('creates a download link for exported file data', () => {+ const link = { click: vi.fn(), download: '', href: '' };+ vi.stubGlobal('document', { createElement: () => link });+ vi.stubGlobal('window', { URL: { createObjectURL: () => 'blob:export' } });+ const service = createService();++ service.downloadFile(new Blob(['data']), 'report.csv');++ expect(link.download).toBe('report.csv');+ expect(link.href).toBe('blob:export');+ expect(link.click).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/ui/src/services/local-storage/__tests__/local-storage.service.spec.ts b/packages/ui/src/services/local-storage/__tests__/local-storage.service.spec.tsnew file mode 100644index 0000000000..efe8414bc0--- /dev/null+++ b/packages/ui/src/services/local-storage/__tests__/local-storage.service.spec.ts@@ -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 type { ILocalStorageService } from '@univerjs/core';+import { Injector } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopLocalStorageService } from '../local-storage.service';++function createMemoryLocalStorage() {+ const values = new Map<string, string>();+ return {+ get length() {+ return values.size;+ },+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => values.set(key, value),+ removeItem: (key: string) => values.delete(key),+ key: (index: number) => Array.from(values.keys())[index] ?? null,+ };+}++function createService(): ILocalStorageService {+ const injector = new Injector();+ injector.add([DesktopLocalStorageService]);+ return injector.get(DesktopLocalStorageService);+}++describe('DesktopLocalStorageService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('stores, lists, iterates, and removes persisted UI values', async () => {+ vi.stubGlobal('localStorage', createMemoryLocalStorage());+ const service = createService();++ await service.setItem('sidebar', { width: 320 });+ await service.setItem('theme', 'dark');++ await expect(service.getItem('sidebar')).resolves.toEqual({ width: 320 });+ await expect(service.keys()).resolves.toEqual(['sidebar', 'theme']);+ await expect(service.iterate((value, key) => key === 'theme' ? value : undefined)).resolves.toBe('dark');++ await service.removeItem('sidebar');+ await expect(service.getItem('sidebar')).resolves.toBeNull();+ });+});diff --git a/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts b/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.tsnew file mode 100644index 0000000000..a948db40bc--- /dev/null+++ b/packages/ui/src/services/menu/__tests__/menu-manager.service.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 type { MenuSchemaType } from '../menu-manager.service';+import { ConfigService, IConfigService, Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { IMenuManagerService, MenuManagerService } from '../menu-manager.service';++function createService(): IMenuManagerService {+ const injector = new Injector();+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);+ return injector.get(IMenuManagerService);+}++describe('MenuManagerService', () => {+ it('appends command menus and returns them in display order', () => {+ const service = createService();++ service.appendRootMenu({+ testPosition: {+ second: { order: 2, menuItemFactory: () => ({ id: 'second' }) },+ first: { order: 1, menuItemFactory: () => ({ id: 'first' }) },+ },+ } as MenuSchemaType);++ expect(service.getMenuByPositionKey('testPosition').map((item) => item.key)).toEqual(['first', 'second']);+ expect(service.getFlatMenuByPositionKey('testPosition').map((item) => item.item?.id)).toEqual(['first', 'second']);+ });++ it('merges menu contributions into existing positions and emits a change event', () => {+ const service = createService();+ const changes: void[] = [];+ const sub = service.menuChanged$.subscribe((value) => changes.push(value));++ service.appendRootMenu({ testMerge: { group: { order: 1 } } } as MenuSchemaType);+ service.mergeMenu({ group: { command: { order: 1, menuItemFactory: () => ({ id: 'command' }) } } } as MenuSchemaType);++ expect(service.getFlatMenuByPositionKey('testMerge').map((item) => item.key)).toEqual(['group', 'command']);+ expect(changes.length).toBeGreaterThanOrEqual(2);+ sub.unsubscribe();+ });+});diff --git a/packages/ui/src/services/message/__testing__/mock-message.service.spec.ts b/packages/ui/src/services/message/__testing__/mock-message.service.spec.tsnew file mode 100644index 0000000000..428eacb9c3--- /dev/null+++ b/packages/ui/src/services/message/__testing__/mock-message.service.spec.ts@@ -0,0 +1,38 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { describe, expect, it } from 'vitest';+import { IMessageService } from '../message.service';+import { MockMessageService } from './mock-message.service';++function createService(): IMessageService {+ const injector = new Injector();+ injector.add([IMessageService, { useClass: MockMessageService }]);+ return injector.get(IMessageService);+}++describe('MockMessageService', () => {+ it('acts as a no-op message channel for tests without a UI container', () => {+ const service = createService();+ const disposable = service.show({ content: 'Saved', type: MessageType.Success });++ expect(() => disposable.dispose()).not.toThrow();+ expect(() => service.remove('message-1')).not.toThrow();+ expect(() => service.removeAll()).not.toThrow();+ });+});diff --git a/packages/ui/src/services/message/__tests__/desktop-message.service.spec.ts b/packages/ui/src/services/message/__tests__/desktop-message.service.spec.tsnew file mode 100644index 0000000000..cb504c319b--- /dev/null+++ b/packages/ui/src/services/message/__tests__/desktop-message.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 { Injector } from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';+import { DesktopMessageService } from '../desktop-message.service';+import { IMessageService } from '../message.service';++function createService(): IMessageService {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IMessageService, { useClass: DesktopMessageService }]);+ return injector.get(IMessageService);+}++describe('DesktopMessageService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('shows a message and allows callers to close it through the returned disposable', () => {+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ callback(1);+ return 1;+ });+ const service = createService();++ const disposable = service.show({ id: 'save-message', content: 'Saved', type: MessageType.Success });++ expect(() => disposable.dispose()).not.toThrow();+ expect(() => service.removeAll()).not.toThrow();+ });++ it('registers the message container UI part when constructed', () => {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IMessageService, { useClass: DesktopMessageService }]);++ injector.get(IMessageService);+ expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);+ });+});diff --git a/packages/ui/src/services/notification/__tests__/desktop-notification.service.spec.ts b/packages/ui/src/services/notification/__tests__/desktop-notification.service.spec.tsnew file mode 100644index 0000000000..874b244abe--- /dev/null+++ b/packages/ui/src/services/notification/__tests__/desktop-notification.service.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 { Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';+import { DesktopNotificationService } from '../desktop-notification.service';+import { INotificationService } from '../notification.service';++function createService(): INotificationService {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([INotificationService, { useClass: DesktopNotificationService }]);+ return injector.get(INotificationService);+}++describe('DesktopNotificationService', () => {+ it('shows a notification and returns a disposable close handle', () => {+ const service = createService();++ const disposable = service.show({ title: 'Saved', content: 'Workbook saved', type: 'success' });++ expect(() => disposable.dispose()).not.toThrow();+ });++ it('registers the notification UI part when constructed', () => {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([INotificationService, { useClass: DesktopNotificationService }]);++ injector.get(INotificationService);+ expect(injector.get(IUIPartsService).getComponents(BuiltInUIPart.GLOBAL).size).toBe(1);+ });+});diff --git a/packages/ui/src/services/platform/__tests__/platform.service.spec.ts b/packages/ui/src/services/platform/__tests__/platform.service.spec.tsindex c7ebc1ffa7..27478b7aa3 100644--- a/packages/ui/src/services/platform/__tests__/platform.service.spec.ts+++ b/packages/ui/src/services/platform/__tests__/platform.service.spec.ts@@ -14,17 +14,25 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { afterEach, describe, expect, it, vi } from 'vitest';-import { PlatformService } from '../platform.service';+import { IPlatformService, PlatformService } from '../platform.service';++function createService(): IPlatformService {+ const injector = new Injector();+ injector.add([IPlatformService, { useClass: PlatformService }]);+ return injector.get(IPlatformService);+}describe('PlatformService', () => {afterEach(() => {vi.restoreAllMocks();+ vi.unstubAllGlobals();});it('should detect Mac platform by appVersion', () => {- vi.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Mac OS X');- const service = new PlatformService();+ vi.stubGlobal('navigator', { appVersion: 'Mac OS X' });+ const service = createService();expect(service.isMac).toBe(true);expect(service.isWindows).toBe(false);@@ -32,8 +40,8 @@ describe('PlatformService', () => {});it('should detect Windows platform by appVersion', () => {- vi.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Windows NT');- const service = new PlatformService();+ vi.stubGlobal('navigator', { appVersion: 'Windows NT' });+ const service = createService();expect(service.isMac).toBe(false);expect(service.isWindows).toBe(true);@@ -41,8 +49,8 @@ describe('PlatformService', () => {});it('should detect Linux platform by appVersion', () => {- vi.spyOn(window.navigator, 'appVersion', 'get').mockReturnValue('Linux x86_64');- const service = new PlatformService();+ vi.stubGlobal('navigator', { appVersion: 'Linux x86_64' });+ const service = createService();expect(service.isMac).toBe(false);expect(service.isWindows).toBe(false);diff --git a/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts b/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.tsnew file mode 100644index 0000000000..f0813b398d--- /dev/null+++ b/packages/ui/src/services/ribbon/__tests__/ribbon.service.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 type { MenuSchemaType } from '../../menu/menu-manager.service';+import {+ ConfigService,+ ContextService,+ DesktopLogService,+ IConfigService,+ IContextService,+ ILogService,+ Injector,+ IUniverInstanceService,+ UniverInstanceService,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { IMenuManagerService, MenuManagerService } from '../../menu/menu-manager.service';+import { MenuManagerPosition, RibbonPosition } from '../../menu/types';+import { DesktopRibbonService, IRibbonService } from '../ribbon.service';++function createService() {+ const injector = new Injector();+ injector.add([IConfigService, { useClass: ConfigService }]);+ injector.add([IContextService, { useClass: ContextService }]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);+ injector.add([IRibbonService, { useClass: DesktopRibbonService }]);+ return {+ service: injector.get(IRibbonService),+ menuManagerService: injector.get(IMenuManagerService),+ };+}++describe('DesktopRibbonService', () => {+ it('shows contextual ribbon tabs only when requested and restores the last regular tab when hidden', () => {+ const { service, menuManagerService } = createService();+ const ribbons: string[][] = [];+ const activated: string[] = [];+ const ribbonSub = service.ribbon$.subscribe((ribbon) => ribbons.push(ribbon.map((item) => item.key)));+ const activeSub = service.activatedTab$.subscribe((tab) => activated.push(tab));++ menuManagerService.appendRootMenu({+ [MenuManagerPosition.RIBBON]: {+ 'chart-tools': {+ order: 100,+ title: 'chart',+ contextual: true,+ group: { order: 0, command: { order: 0, menuItemFactory: () => ({ id: 'chart-command' }) } },+ },+ },+ } as MenuSchemaType);+ service.setActivatedTab(RibbonPosition.INSERT);+ service.showContextualTab('chart-tools', { activate: true });+ service.hideContextualTab('chart-tools');++ expect(ribbons.at(-2)).toContain('chart-tools');+ expect(ribbons.at(-1)).not.toContain('chart-tools');+ expect(activated).toContain('chart-tools');++ ribbonSub.unsubscribe();+ activeSub.unsubscribe();+ });++ it('publishes collapsed group ids and fake toolbar visibility changes', () => {+ const { service } = createService();+ const collapsed: string[][] = [];+ const fakeToolbarVisible: boolean[] = [];+ const collapsedSub = service.collapsedIds$.subscribe((ids) => collapsed.push(ids));+ const fakeToolbarSub = service.fakeToolbarVisible$.subscribe((visible) => fakeToolbarVisible.push(visible));++ service.setCollapsedIds(['format']);+ service.setFakeToolbarVisible(true);++ expect(collapsed).toEqual([[], ['format']]);+ expect(fakeToolbarVisible).toEqual([false, true]);+ collapsedSub.unsubscribe();+ fakeToolbarSub.unsubscribe();+ });+});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.tsindex 2eb411acda..f87b3171f2 100644--- a/packages/ui/src/services/shortcut/__tests__/shortcut-panel.service.spec.ts+++ b/packages/ui/src/services/shortcut/__tests__/shortcut-panel.service.spec.ts@@ -14,12 +14,19 @@* limitations under the License.*/+import { Injector } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { ShortcutPanelService } from '../shortcut-panel.service';+function createService(): ShortcutPanelService {+ const injector = new Injector();+ injector.add([ShortcutPanelService]);+ return injector.get(ShortcutPanelService);+}+describe('ShortcutPanelService', () => {it('should open and close panel state', () => {- const service = new ShortcutPanelService();+ const service = createService();expect(service.isOpen).toBe(false);@@ -31,7 +38,7 @@ describe('ShortcutPanelService', () => {});it('should emit distinct state values and complete on dispose', () => {- const service = new ShortcutPanelService();+ const service = createService();const values: boolean[] = [];let completed = false;diff --git a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.tsindex cc0cc458f8..66f672308e 100644--- a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts+++ b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts@@ -14,9 +14,10 @@* 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 { ICommandService, IContextService, Injector } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ILayoutService } from '../../layout/layout.service';+import { IPlatformService } from '../../platform/platform.service';import { KeyCode, MetaKeys } from '../keycode';import { ShortcutService } from '../shortcut.service';@@ -24,19 +25,23 @@ function createKeyboardEvent(keyCode: number,options?: { ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean; altKey?: boolean }): KeyboardEvent {- const event = new KeyboardEvent('keydown', {+ const event = new Event('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,- });+ }) as KeyboardEvent;++ for (const [key, value] of Object.entries({+ altKey: options?.altKey ?? false,+ ctrlKey: options?.ctrlKey ?? false,+ keyCode,+ metaKey: options?.metaKey ?? false,+ shiftKey: options?.shiftKey ?? false,+ })) {+ Object.defineProperty(event, key, {+ configurable: true,+ get: () => value,+ });+ }return event;}@@ -47,26 +52,60 @@ function createService(options?: {isLinux?: boolean;layoutAllowed?: boolean;}) {+ const eventTarget = new EventTarget();+ vi.stubGlobal('window', {+ addEventListener: eventTarget.addEventListener.bind(eventTarget),+ removeEventListener: eventTarget.removeEventListener.bind(eventTarget),+ dispatchEvent: eventTarget.dispatchEvent.bind(eventTarget),+ });+ vi.stubGlobal('document', {+ createElement: () => ({}),+ });+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 layoutService = {+ checkElementInCurrentContainers: vi.fn(() => options?.layoutAllowed),+ };++ class TestCommandService {+ executeCommand = executeCommand;+ }++ class TestPlatformService {+ isMac = platformService.isMac;+ isWindows = platformService.isWindows;+ isLinux = platformService.isLinux;+ }++ class TestContextService {}- const service = new ShortcutService(commandService as any, platformService as any, contextService, layoutService);+ class TestLayoutService {+ checkElementInCurrentContainers = layoutService.checkElementInCurrentContainers;+ }++ const injector = new Injector();+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([IPlatformService, { useClass: TestPlatformService }]);+ injector.add([IContextService, { useClass: TestContextService }]);+ if (options?.layoutAllowed !== undefined) {+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);+ }+ injector.add([ShortcutService]);+ const service = injector.get(ShortcutService);return { service, executeCommand, layoutService };}describe('ShortcutService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });+it('should register and unregister shortcuts', () => {const { service } = createService();const changed = vi.fn();diff --git a/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.spec.ts b/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.spec.tsnew file mode 100644index 0000000000..cfa401db37--- /dev/null+++ b/packages/ui/src/services/sidebar/__tests__/desktop-sidebar.service.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 { Injector } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { DesktopSidebarService } from '../desktop-sidebar.service';+import { ISidebarService } from '../sidebar.service';++function createService(): ISidebarService {+ const injector = new Injector();+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ return injector.get(ISidebarService);+}++describe('DesktopSidebarService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('opens and closes the requested sidebar panel', () => {+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ callback(1);+ return 1;+ });+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ const service = createService();+ const snapshots: unknown[] = [];+ const opened: string[] = [];+ const closed: string[] = [];+ const sub = service.sidebarOptions$.subscribe((value) => snapshots.push(value));++ service.open({ id: 'inspector', onOpen: () => opened.push('inspector'), onClose: (id) => closed.push(id ?? '') });+ service.close('inspector');++ expect(service.visible).toBe(false);+ expect(opened).toEqual(['inspector']);+ expect(closed).toEqual(['']);+ expect(snapshots).toMatchObject([{ id: 'inspector', visible: true }, { id: 'inspector', visible: false }]);+ sub.unsubscribe();+ });++ it('ignores close requests for a different sidebar id', () => {+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ callback(1);+ return 1;+ });+ vi.stubGlobal('cancelAnimationFrame', vi.fn());+ const service = createService();++ service.open({ id: 'inspector' });+ service.close('other');++ expect(service.visible).toBe(true);+ });+});diff --git a/packages/ui/src/services/theme-switcher/__tests__/theme-switcher.service.spec.ts b/packages/ui/src/services/theme-switcher/__tests__/theme-switcher.service.spec.tsnew file mode 100644index 0000000000..5b67b711c1--- /dev/null+++ b/packages/ui/src/services/theme-switcher/__tests__/theme-switcher.service.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 { Theme } from '@univerjs/themes';+import { Injector } from '@univerjs/core';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { ThemeSwitcherService } from '../theme-switcher.service';++function createService(): ThemeSwitcherService {+ const injector = new Injector();+ injector.add([ThemeSwitcherService]);+ return injector.get(ThemeSwitcherService);+}++describe('ThemeSwitcherService', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('injects theme tokens as CSS variables and replaces previous theme style', () => {+ interface IStyleElementStub {+ id?: string;+ textContent?: string;+ setAttribute: (key: string, value: string) => void;+ remove: () => void;+ }+ const appended: IStyleElementStub[] = [];+ const existing = { remove: vi.fn() };+ vi.stubGlobal('document', {+ getElementById: () => existing,+ createElement: () => ({+ setAttribute(key: string, value: string) {+ if (key === 'id') {+ this.id = value;+ }+ },+ remove: vi.fn(),+ textContent: '',+ } as IStyleElementStub),+ head: {+ appendChild: (element: IStyleElementStub) => appended.push(element),+ },+ });+ const service = createService();++ service.injectThemeToHead({ primary: { color: 'red' }, radius: 4 } as unknown as Theme);++ expect(existing.remove).toHaveBeenCalledTimes(1);+ expect(appended[0].id).toBe('univer-theme-css-variables');+ expect(appended[0].textContent).toContain('--univer-primary-color: red;');+ expect(appended[0].textContent).toContain('--univer-radius: 4;');+ });+});diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsxindex d0f6c96ab2..9d6d2c1bd2 100644--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx@@ -14,14 +14,18 @@* limitations under the License.*/-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';-import { LocaleService } from '@univerjs/core';-import React from 'react';-import { BehaviorSubject } from 'rxjs';+import type { ReactElement } from 'react';+import type { IValueOption } from '../../../../services/menu/menu';+import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { ILogService, Injector, LocaleService } from '@univerjs/core';+import { BehaviorSubject, Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';+import { ComponentManager, IconManager } from '../../../../common';import { ILayoutService } from '../../../../services/layout/layout.service';import { MenuItemType } from '../../../../services/menu/menu';import { IMenuManagerService } from '../../../../services/menu/menu-manager.service';+import { RediContext } from '../../../../utils/di';import {CONTEXT_MENU_SUBMENU_CLOSE_DELAY,CONTEXT_MENU_SUBMENU_PORTAL_ATTR,@@ -32,890 +36,456 @@ import {shouldShowContextMenuGroupSeparator,} from '../ContextMenuPanel';-const dependencyMap = new Map();-const tinyMenuGroupSpy = vi.fn();--afterEach(() => {- cleanup();- vi.useRealTimers();-});--vi.mock('../../../../utils/di', async () => {- const ReactModule = await import('react');+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++class TestMenuManagerService {+ readonly menuChanged$ = new Subject<void>();+ private readonly _menusByPosition = new Map<string, IMenuSchema[]>();++ setMenus(position: string, menus: IMenuSchema[]): void {+ this._menusByPosition.set(position, menus);+ this.menuChanged$.next();+ }++ getMenuByPositionKey(position: string): IMenuSchema[] {+ return this._menusByPosition.get(position) ?? [];+ }+}++class TestLocaleService {+ readonly direction$ = new BehaviorSubject<'ltr'>('ltr');++ t(key: string): string {+ return `translated:${key}`;+ }+}++class TestLayoutService {+ readonly rootContainerElement = document.body;+}++class TestLogService {+ warn(): void {}+}++class TestState {+ static selectedOptions: IValueOption[] = [];+ static cancels = 0;++ static reset(): void {+ this.selectedOptions = [];+ this.cancels = 0;+ }+}++function createContextMenuInjector() {+ const injector = new Injector();+ injector.add([IMenuManagerService, { useClass: TestMenuManagerService as never }]);+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([ILogService, { useClass: TestLogService as never }]);+ injector.add([ComponentManager]);+ injector.add([IconManager]);++ injector.get(IconManager).register({+ AlignLeftIcon: ({ className }: { className?: string }) => <span className={className} data-icon="align-left" />,+ AlignCenterIcon: ({ className }: { className?: string }) => <span className={className} data-icon="align-center" />,+ TextColorIcon: ({ className }: { className?: string }) => <span className={className} data-icon="text-color" />,+ ResetIcon: ({ className }: { className?: string }) => <span className={className} data-icon="reset" />,+ });+ return injector;+}++function renderWithDependencies(element: ReactElement, menuMap: Record<string, IMenuSchema[]>) {+ const injector = createContextMenuInjector();+ const menuManagerService = injector.get(IMenuManagerService) as unknown as TestMenuManagerService;++ Object.entries(menuMap).forEach(([position, menus]) => menuManagerService.setMenus(position, menus));++ return render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+}++function createButtonItem(+ key: string,+ options: {+ icon?: string;+ title?: string;+ tooltip?: string;+ params?: Record<string, unknown>;+ activated$?: BehaviorSubject<boolean>;+ hidden$?: BehaviorSubject<boolean>;+ } = {}+): IMenuSchema {return {- useDependency(token: unknown) {- return dependencyMap.get(token);- },- useObservable<T>(observable: any, defaultValue?: T) {- const [value, setValue] = ReactModule.useState(defaultValue);-- ReactModule.useEffect(() => {- if (!observable) {- return;- }-- const source = typeof observable === 'function' ? observable() : observable;- const sub = source.subscribe?.((nextValue: T) => setValue(nextValue));-- return () => sub?.unsubscribe?.();- }, [observable]);-- return value;+ key,+ order: 0,+ item: {+ id: key,+ type: MenuItemType.BUTTON,+ icon: options.icon,+ title: options.title,+ tooltip: options.tooltip,+ params: options.params,+ activated$: options.activated$,+ hidden$: options.hidden$,},};-});+}-vi.mock('../../../menu/desktop/TinyMenuGroup', () => ({- resolveMenuItemActiveState: () => false,- UITinyMenuGroup: (props: unknown) => {- tinyMenuGroupSpy(props);- return <div data-testid="tiny-menu-group" />;- },- UIQuickTileMenuGroup: () => <div data-testid="quick-tile-menu-group" />,-}));+function hasClassToken(element: HTMLElement, token: string): boolean {+ return element.className.split(/\s+/).includes(token);+}-vi.mock('../../../custom-label/CustomLabel', () => ({- CustomLabel: () => <span data-testid="custom-label" />,-}));--describe('ContextMenuPanel', () => {- it('applies the enlarged paragraph T size variant without affecting the shared defaults', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'quickTop',- order: 0,- title: 'docs-ui.paragraphMenu.align',- quickLayout: 'icon',- children: [{- key: 'quickItem',- order: 0,- item: {- id: 'quick-item',- type: MenuItemType.BUTTON,- },- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- const { container } = render(React.createElement(ContextMenuPanel as never, {- menuType: 'quick-layout-menu',- sizeVariant: 'paragraph-t',- }));-- const className = (container.firstChild as HTMLDivElement | null)?.className ?? '';- expect(className).toContain('univer-min-w-64');- expect(className).toContain('univer-text-base');- expect(className).toContain('univer-px-3');- expect(className).toContain('univer-py-2');- expect(tinyMenuGroupSpy.mock.calls[0][0]).toEqual(expect.objectContaining({- columns: 6,- sizeVariant: 'paragraph-t',- }));+async function nextFrame() {+ await act(async () => {+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));});+}- it('suppresses initial hover highlight until the pointer moves', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'insert',- order: 0,- children: [{- key: 'table',- order: 0,- item: {- id: 'insert-table',- type: MenuItemType.BUTTON,- },- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- const { container } = render(React.createElement(ContextMenuPanel as never, {- menuType: 'insert-menu',- suppressHoverUntilPointerMove: true,- }));- const panel = container.firstChild as HTMLDivElement;-- expect(panel.className).toContain('univer-context-menu-hover-suppressed');-- fireEvent.pointerMove(panel);-- expect(panel.className).not.toContain('univer-context-menu-hover-suppressed');- });-- it('keeps selector submenus closed while initial hover is suppressed', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'insert',- order: 0,- children: [{- key: 'table',- order: 0,- item: {- id: 'insert-table',- type: MenuItemType.BUTTON_SELECTOR,- title: 'insert table',- tooltip: 'insert table',- selections: [{- label: 'table picker',- value: 'table picker',- }],- },- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- const { container, unmount } = render(React.createElement(ContextMenuPanel as never, {- menuType: 'insert-menu',- suppressHoverUntilPointerMove: true,- }));- const panel = container.firstChild as HTMLDivElement;- const tableButton = document.querySelector('button[title="insert table"]') as HTMLButtonElement | null;- const tableWrapper = tableButton?.parentElement as HTMLDivElement | null;-- expect(tableWrapper).not.toBeNull();-- fireEvent.mouseEnter(tableWrapper!);- expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(0);-- fireEvent.pointerMove(panel);- fireEvent.mouseEnter(tableWrapper!);- expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(1);-- unmount();- });-- it('can focus the menu container without selecting an item initially', async () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'insert',- order: 0,- children: [{- key: 'table',- order: 0,- item: {- id: 'insert-table',- type: MenuItemType.BUTTON,- title: 'insert table',- tooltip: 'insert table',- },- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- const { container } = render(React.createElement(ContextMenuPanel as never, {- menuType: 'insert-menu',- autoFocus: true,- autoFocusTarget: 'container',- }));- const panel = container.firstChild as HTMLDivElement;- const tableButton = document.querySelector('button[title="insert table"]') as HTMLButtonElement | null;-- await act(async () => {- await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));- });-- expect(document.activeElement).toBe(panel);-- fireEvent.keyDown(panel, { key: 'ArrowDown' });-- expect(document.activeElement).toBe(tableButton);+describe('ContextMenuPanel', () => {+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ TestState.reset();});- it('does not render a separator between consecutive header quick rows', () => {- expect(shouldShowContextMenuGroupSeparator([+ it('keeps paragraph quick groups visually connected while separating the next normal group', () => {+ const schemas = [{ key: 'quickTop', order: 0, quickLayout: 'icon' },{ key: 'quickBottom', order: 1, quickLayout: 'icon' },{ key: 'layout', order: 2 },- ] as never, 0)).toBe(false);+ ] as IMenuSchema[];- expect(shouldShowContextMenuGroupSeparator([- { key: 'quickTop', order: 0, quickLayout: 'icon' },- { key: 'quickBottom', order: 1, quickLayout: 'icon' },- { key: 'layout', order: 2 },- ] as never, 1)).toBe(true);- });-- it('clusters consecutive paragraph T header quick rows into one shared container', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [- {- key: 'quickTop',- order: 0,- quickLayout: 'icon',- children: [{- key: 'quickItemTop',- order: 0,- item: {- id: 'quick-item-top',- type: MenuItemType.BUTTON,- },- }],- },- {- key: 'quickBottom',- order: 1,- quickLayout: 'icon',- children: [{- key: 'quickItemBottom',- order: 0,- item: {- id: 'quick-item-bottom',- type: MenuItemType.BUTTON,- },- }],- },- ]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- const { container } = render(React.createElement(ContextMenuPanel as never, {- menuType: 'quick-layout-menu',- sizeVariant: 'paragraph-t',- }));-- const sharedCluster = container.querySelector('.univer-gap-0') as HTMLDivElement | null;-- expect(sharedCluster).not.toBeNull();- expect(sharedCluster?.className ?? '').toContain('univer-py-2');- expect(sharedCluster?.querySelectorAll('[data-testid="tiny-menu-group"]').length).toBe(2);- expect(container.querySelectorAll('.univer-gap-0 [data-testid="tiny-menu-group"]').length).toBe(2);- });-- it('groups consecutive paragraph T header quick rows before rendering', () => {- expect(getContextMenuSchemaRenderGroups([- { key: 'quickTop', order: 0, quickLayout: 'icon' },- { key: 'quickBottom', order: 1, quickLayout: 'icon' },- { key: 'align', order: 2 },- ] as never, 'paragraph-t')).toEqual([+ expect(shouldShowContextMenuGroupSeparator(schemas, 0)).toBe(false);+ expect(shouldShowContextMenuGroupSeparator(schemas, 1)).toBe(true);+ expect(getContextMenuSchemaRenderGroups(schemas, 'paragraph-t')).toEqual([{startIndex: 0,endIndex: 1,- menuSchemas: [- { key: 'quickTop', order: 0, quickLayout: 'icon' },- { key: 'quickBottom', order: 1, quickLayout: 'icon' },- ],+ menuSchemas: [schemas[0], schemas[1]],},{startIndex: 2,endIndex: 2,- menuSchemas: [- { key: 'align', order: 2 },- ],+ menuSchemas: [schemas[2]],},]);+ expect(getContextMenuQuickGroupColumns(schemas[0])).toBe(6);});- it('uses a fixed six-column layout for header quick icon groups only', () => {- expect(getContextMenuQuickGroupColumns({- key: 'quickTop',- order: 0,- quickLayout: 'icon',- } as never)).toBe(6);-- expect(getContextMenuQuickGroupColumns({- key: 'quickBottom',- order: 1,- quickLayout: 'icon',- } as never)).toBe(6);-- expect(getContextMenuQuickGroupColumns({- key: 'align',- order: 0,- quickLayout: 'icon',- } as never)).toBeUndefined();- });-- it('passes compact quick layout metadata through to tiny menu groups', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'colors',- order: 0,- quickLayout: 'icon',- quickColumns: 8,- quickLayoutVariant: 'compact',- children: [{- key: 'quickItem',- order: 0,- item: {- id: 'quick-item',- type: MenuItemType.BUTTON,+ it('renders paragraph quick menus with real tiny groups and submits the clicked command', () => {+ renderWithDependencies(+ <ContextMenuPanel+ menuType="paragraph-menu"+ sizeVariant="paragraph-t"+ activeItemIds={['align-center']}+ hiddenItemIds={['reset-format']}+ onOptionSelect={(option) => TestState.selectedOptions.push(option)}+ />,+ {+ 'paragraph-menu': [+ {+ key: 'quickTop',+ order: 0,+ title: 'docs-ui.paragraphMenu.align',+ quickLayout: 'icon',+ children: [+ createButtonItem('align-left', {+ icon: 'AlignLeftIcon',+ tooltip: 'docs-ui.toolbar.alignLeft',+ }),+ createButtonItem('align-center', {+ icon: 'AlignCenterIcon',+ tooltip: 'docs-ui.toolbar.alignCenter',+ params: { horizontalAlign: 'center' },+ }),+ ],},- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(React.createElement(ContextMenuPanel as never, {- menuType: 'quick-layout-menu',- sizeVariant: 'paragraph-t',- }));-- expect(tinyMenuGroupSpy.mock.calls[0][0]).toEqual(expect.objectContaining({- columns: 8,- layoutVariant: 'compact',- }));- });-- it('renders a right-aligned header action for titled context menu groups', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'colors',- order: 0,- title: 'docs-ui.toolbar.textColor.main',- headerActionItem: {- id: 'header-action',- type: MenuItemType.BUTTON_SELECTOR,- icon: 'HeaderTextColorIcon',- tooltip: 'header-action',- selections: [],- },- children: [{- key: 'quickItem',- order: 0,- item: {- id: 'quick-item',- type: MenuItemType.BUTTON,+ {+ key: 'quickBottom',+ order: 1,+ quickLayout: 'icon',+ children: [+ createButtonItem('reset-format', {+ icon: 'ResetIcon',+ tooltip: 'docs-ui.toolbar.resetFormat',+ }),+ ],},- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(React.createElement(ContextMenuPanel as never, {- menuType: 'quick-layout-menu',- sizeVariant: 'paragraph-t',- }));-- expect(document.querySelector('button[title="header-action"]')).not.toBeNull();- });-- it('opens a header action selector submenu instead of immediately executing its current value', () => {- dependencyMap.clear();- tinyMenuGroupSpy.mockClear();- const onOptionSelect = vi.fn();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'colors',- order: 0,- title: 'docs-ui.toolbar.textColor.main',- headerActionItem: {- id: 'header-action',- type: MenuItemType.BUTTON_SELECTOR,- icon: 'HeaderTextColorIcon',- tooltip: 'header-action',- selections: [{- label: 'custom-option',- value: '#ff0000',- }],- },- children: [{- key: 'quickItem',- order: 0,- item: {- id: 'quick-item',- type: MenuItemType.BUTTON,+ {+ key: 'insert',+ order: 2,+ children: [+ createButtonItem('insert-link', {+ title: 'docs-ui.toolbar.link',+ tooltip: 'docs-ui.toolbar.link',+ }),+ ],},- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(React.createElement(ContextMenuPanel as never, {- menuType: 'quick-layout-menu',- sizeVariant: 'paragraph-t',- onOptionSelect,- }));+ ],+ }+ );- const headerActionButton = document.querySelector('button[title="header-action"]') as HTMLButtonElement | null;+ expect(screen.getByText('translated:docs-ui.paragraphMenu.align')).not.toBeNull();+ expect(screen.queryByRole('button', { name: 'translated:docs-ui.toolbar.resetFormat' })).toBeNull();- expect(headerActionButton).not.toBeNull();+ const alignCenterButton = screen.getByRole('button', { name: 'translated:docs-ui.toolbar.alignCenter' });+ expect(hasClassToken(alignCenterButton, 'univer-bg-gray-50')).toBe(true);- fireEvent.click(headerActionButton!);+ fireEvent.click(alignCenterButton);- expect(onOptionSelect).not.toHaveBeenCalled();+ expect(TestState.selectedOptions).toEqual([{+ id: 'align-center',+ label: 'align-center',+ commandId: undefined,+ params: { horizontalAlign: 'center' },+ value: undefined,+ tooltip: 'translated:docs-ui.toolbar.alignCenter',+ }]);});- it('renders quick layout group titles before icon rows', () => {- dependencyMap.clear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'quickGroup',- order: 0,- title: 'docs-ui.paragraphMenu.align',- quickLayout: 'icon',- children: [{- key: 'quickItem',- order: 0,- item: {- id: 'quick-item',- type: MenuItemType.BUTTON,- },- }],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(<ContextMenuPanel menuType="quick-layout-menu" />);-- expect(screen.getAllByText('docs-ui.paragraphMenu.align').length).toBeGreaterThan(0);- expect(screen.getAllByTestId('tiny-menu-group').length).toBeGreaterThan(0);- });+ it('removes a group when all of its children become hidden', async () => {+ const visible$ = new BehaviorSubject(false);+ const hidden$ = new BehaviorSubject(true);- it('supports keyboard focus, navigation, confirm, and cancel', async () => {- dependencyMap.clear();- const onOptionSelect = vi.fn();- const onCancel = vi.fn();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn(() => [{- key: 'insert',- order: 0,- children: [+ renderWithDependencies(+ <ContextMenuPanel menuType="context-menu" />,+ {+ 'context-menu': [{- key: 'heading-1',+ key: 'hidden-group',order: 0,- item: {- id: 'heading-1',- type: MenuItemType.BUTTON,- title: 'heading 1',- tooltip: 'heading 1',- },+ title: 'docs-ui.hiddenGroup',+ children: [+ createButtonItem('hidden-action', {+ title: 'docs-ui.hiddenAction',+ tooltip: 'docs-ui.hiddenAction',+ hidden$,+ }),+ ],},{- key: 'callout',+ key: 'visible-group',order: 1,- item: {- id: 'callout',- type: MenuItemType.BUTTON,- title: 'callout',- tooltip: 'callout',- },+ title: 'docs-ui.visibleGroup',+ children: [+ createButtonItem('visible-action', {+ title: 'docs-ui.visibleAction',+ tooltip: 'docs-ui.visibleAction',+ hidden$: visible$,+ }),+ ],},],- }]),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),+ }+ );++ await waitFor(() => {+ expect(screen.queryByText('translated:docs-ui.hiddenGroup')).toBeNull();});+ expect(screen.getByText('translated:docs-ui.visibleGroup')).not.toBeNull();+ expect(screen.getByRole('button', { name: 'translated:docs-ui.visibleAction' })).not.toBeNull();+ });- const { container } = render(+ it('supports keyboard navigation, confirm, and cancel from the real menu DOM', async () => {+ renderWithDependencies(<ContextMenuPanelmenuType="keyboard-menu"autoFocus- onCancel={onCancel}- onOptionSelect={onOptionSelect}- />+ onCancel={() => {+ TestState.cancels += 1;+ }}+ onOptionSelect={(option) => TestState.selectedOptions.push(option)}+ />,+ {+ 'keyboard-menu': [+ {+ key: 'insert',+ order: 0,+ children: [+ createButtonItem('heading-1', {+ title: 'docs-ui.heading1',+ tooltip: 'docs-ui.heading1',+ }),+ createButtonItem('callout', {+ title: 'docs-ui.callout',+ tooltip: 'docs-ui.callout',+ params: { block: 'callout' },+ }),+ ],+ },+ ],+ });- const panel = container.firstElementChild as HTMLDivElement;- const headingButton = document.querySelector('button[title="heading 1"]') as HTMLButtonElement | null;- const calloutButton = document.querySelector('button[title="callout"]') as HTMLButtonElement | null;+ await nextFrame();- await act(async () => {- await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));- });+ const panel = document.querySelector('[tabindex="-1"]') as HTMLDivElement;+ const headingButton = screen.getByRole('button', { name: 'translated:docs-ui.heading1' });+ const calloutButton = screen.getByRole('button', { name: 'translated:docs-ui.callout' });expect(document.activeElement).toBe(headingButton);fireEvent.keyDown(panel, { key: 'ArrowDown' });expect(document.activeElement).toBe(calloutButton);- fireEvent.keyDown(panel, { key: 'ArrowLeft' });- expect(document.activeElement).toBe(headingButton);-- fireEvent.keyDown(panel, { key: 'ArrowRight' });- expect(document.activeElement).toBe(calloutButton);-fireEvent.keyDown(panel, { key: 'Enter' });- expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({+ expect(TestState.selectedOptions).toEqual([{id: 'callout',label: 'callout',- }));+ commandId: undefined,+ params: { block: 'callout' },+ value: undefined,+ }]);fireEvent.keyDown(panel, { key: 'Escape' });- expect(onCancel).toHaveBeenCalledTimes(1);+ expect(TestState.cancels).toBe(1);});- it('keeps left and right navigation on the same visual row until the row boundary', () => {- const createButton = (left: number, top: number) => ({- getBoundingClientRect: () => ({- bottom: top + 32,- height: 32,- left,- right: left + 32,- top,- width: 32,- x: left,- y: top,- toJSON: () => ({}),- }),- }) as HTMLButtonElement;- const h2 = createButton(56, 0);- const h3 = createButton(112, 0);- const visuallyCloseSecondRowItem = createButton(60, 40);-- expect(getNextMenuButtonByDirection([- h2,- h3,- visuallyCloseSecondRowItem,- ], 0, 'ArrowRight')).toBe(h3);- expect(getNextMenuButtonByDirection([- h2,- h3,- visuallyCloseSecondRowItem,- ], 1, 'ArrowRight')).toBe(visuallyCloseSecondRowItem);+ it('selects an option from a selector submenu with the selector command id', () => {+ renderWithDependencies(+ <ContextMenuPanel+ menuType="format-menu"+ onOptionSelect={(option) => TestState.selectedOptions.push(option)}+ />,+ {+ 'format-menu': [+ {+ key: 'format',+ order: 0,+ children: [+ {+ key: 'color',+ order: 0,+ item: {+ id: 'text-color',+ type: MenuItemType.BUTTON_SELECTOR,+ icon: 'TextColorIcon',+ title: 'docs-ui.textColor',+ tooltip: 'docs-ui.textColor',+ selectionsCommandId: 'doc.command.setTextColor',+ selections: [+ {+ label: 'palette.red',+ value: '#ff0000',+ },+ {+ label: 'palette.blue',+ value: '#0000ff',+ },+ ],+ },+ },+ ],+ },+ ],+ }+ );++ const colorButton = screen.getByRole('button', { name: 'translated:docs-ui.textColor' });+ fireEvent.mouseEnter(colorButton.parentElement as HTMLElement);++ fireEvent.click(screen.getByText('translated:palette.red').closest('button') as HTMLButtonElement);++ expect(TestState.selectedOptions).toEqual([{+ id: 'text-color',+ label: 'color',+ commandId: 'doc.command.setTextColor',+ value: '#ff0000',+ }]);+ expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(0);});- it('keeps the newly hovered submenu open when switching quickly between sibling submenu items', () => {+ it('keeps the newly hovered submenu open when moving across sibling submenu items', () => {vi.useFakeTimers();- dependencyMap.clear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn((key: string) => {- if (key === 'submenu-root') {- return [- {- key: 'indent',- order: 0,- item: {- id: 'indent',- type: MenuItemType.SUBITEMS,- title: 'indent',- tooltip: 'indent',- },- },- {- key: 'colors',- order: 1,- item: {- id: 'colors',- type: MenuItemType.SUBITEMS,- title: 'colors',- tooltip: 'colors',- },- },- ];- }- if (key === 'indent') {- return [{- key: 'indent-option',+ renderWithDependencies(+ <ContextMenuPanel menuType="submenu-root" />,+ {+ 'submenu-root': [+ {+ key: 'indent',order: 0,item: {- id: 'indent-option',- type: MenuItemType.BUTTON,- title: 'indent option',+ id: 'indent',+ type: MenuItemType.SUBITEMS,+ title: 'docs-ui.indent',+ tooltip: 'docs-ui.indent',},- }];- }-- if (key === 'colors') {- return [{- key: 'colors-option',- order: 0,+ },+ {+ key: 'colors',+ order: 1,item: {- id: 'colors-option',- type: MenuItemType.BUTTON,- title: 'colors option',+ id: 'colors',+ type: MenuItemType.SUBITEMS,+ title: 'docs-ui.colors',+ tooltip: 'docs-ui.colors',},- }];- }-- return [];- }),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(<ContextMenuPanel menuType="submenu-root" />);-- const indentButton = document.querySelector('button[title="indent"]') as HTMLButtonElement | null;- const colorsButton = document.querySelector('button[title="colors"]') as HTMLButtonElement | null;- expect(indentButton).not.toBeNull();- expect(colorsButton).not.toBeNull();+ },+ ],+ indent: [+ createButtonItem('indent-more', {+ title: 'docs-ui.indentMore',+ tooltip: 'docs-ui.indentMore',+ }),+ ],+ colors: [+ createButtonItem('fill-color', {+ title: 'docs-ui.fillColor',+ tooltip: 'docs-ui.fillColor',+ }),+ ],+ }+ );- const indentWrapper = indentButton?.parentElement as HTMLDivElement | null;- const colorsWrapper = colorsButton?.parentElement as HTMLDivElement | null;- expect(indentWrapper).not.toBeNull();- expect(colorsWrapper).not.toBeNull();+ const indentButton = screen.getByRole('button', { name: 'translated:docs-ui.indent' });+ const colorsButton = screen.getByRole('button', { name: 'translated:docs-ui.colors' });+ const indentWrapper = indentButton.parentElement as HTMLElement;+ const colorsWrapper = colorsButton.parentElement as HTMLElement;act(() => {- fireEvent.mouseEnter(indentWrapper!);+ fireEvent.mouseEnter(indentWrapper);});- expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(1);+ expect(screen.getByText('translated:docs-ui.indentMore')).not.toBeNull();act(() => {- fireEvent.mouseLeave(indentWrapper!, { relatedTarget: colorsWrapper });- fireEvent.mouseEnter(colorsWrapper!);+ fireEvent.mouseLeave(indentWrapper, { relatedTarget: colorsWrapper });+ fireEvent.mouseEnter(colorsWrapper);});- expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(1);+ expect(screen.getByText('translated:docs-ui.fillColor')).not.toBeNull();+ expect(screen.queryByRole('button', { name: 'translated:docs-ui.indentMore' })).toBeNull();act(() => {vi.advanceTimersByTime(CONTEXT_MENU_SUBMENU_CLOSE_DELAY + 10);});- expect(document.querySelectorAll(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`)).toHaveLength(1);-- vi.useRealTimers();- });-- it('closes an open submenu immediately when hovering a plain root menu item', () => {- vi.useFakeTimers();- dependencyMap.clear();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn((key: string) => {- if (key === 'submenu-root') {- return [- {- key: 'insert',- order: 0,- item: {- id: 'insert',- type: MenuItemType.SUBITEMS,- title: 'insert',- tooltip: 'insert',- },- },- {- key: 'align',- order: 1,- item: {- id: 'align',- type: MenuItemType.BUTTON,- title: 'align',- tooltip: 'align',- },- },- ];- }-- if (key === 'insert') {- return [{- key: 'insert-option',- order: 0,- item: {- id: 'insert-option',- type: MenuItemType.BUTTON,- title: 'insert option',- tooltip: 'insert option',- },- }];- }-- return [];- }),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(<ContextMenuPanel menuType="submenu-root" />);-- const insertButton = document.querySelector('button[title="insert"]') as HTMLButtonElement | null;- const alignButton = document.querySelector('button[title="align"]') as HTMLButtonElement | null;- expect(insertButton).not.toBeNull();- expect(alignButton).not.toBeNull();-- act(() => {- fireEvent.mouseEnter(insertButton!.parentElement!);- });- expect(document.querySelector('button[title="insert option"]')).not.toBeNull();-- act(() => {- fireEvent.mouseLeave(insertButton!.parentElement!, { relatedTarget: alignButton });- fireEvent.mouseEnter(alignButton!.parentElement!);- });-- expect(document.querySelector('button[title="insert option"]')).toBeNull();-- vi.useRealTimers();+ expect(screen.getByText('translated:docs-ui.fillColor')).not.toBeNull();});- it('does not report a menu pointer leave when moving from a portal submenu back to the root menu', () => {- dependencyMap.clear();- const onMenuPointerLeave = vi.fn();-- dependencyMap.set(IMenuManagerService, {- menuChanged$: new BehaviorSubject<void>(undefined),- getMenuByPositionKey: vi.fn((key: string) => {- if (key === 'submenu-root') {- return [- {- key: 'insert',- order: 0,- item: {- id: 'insert',- type: MenuItemType.SUBITEMS,- title: 'insert',- tooltip: 'insert',- },- },- {- key: 'align',- order: 1,- item: {- id: 'align',- type: MenuItemType.BUTTON,- title: 'align',- tooltip: 'align',- },- },- ];- }-- if (key === 'insert') {- return [{- key: 'insert-option',- order: 0,- item: {- id: 'insert-option',- type: MenuItemType.BUTTON,- title: 'insert option',- tooltip: 'insert option',- },- }];- }-- return [];+ it('keeps row navigation on the same visual row until the row boundary', () => {+ const createButton = (left: number, top: number) => ({+ getBoundingClientRect: () => ({+ bottom: top + 32,+ height: 32,+ left,+ right: left + 32,+ top,+ width: 32,+ x: left,+ y: top,+ toJSON: () => ({}),}),- });- dependencyMap.set(ILayoutService, {- rootContainerElement: document.body,- });- dependencyMap.set(LocaleService, {- t: (key: string) => key,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });-- render(- <ContextMenuPanel- menuType="submenu-root"- onMenuPointerLeave={onMenuPointerLeave}- />- );-- const insertButton = document.querySelector('button[title="insert"]') as HTMLButtonElement | null;- const alignButton = document.querySelector('button[title="align"]') as HTMLButtonElement | null;- expect(insertButton).not.toBeNull();- expect(alignButton).not.toBeNull();-- act(() => {- fireEvent.mouseEnter(insertButton!.parentElement!);- });-- const optionButton = Array.from(document.querySelectorAll<HTMLButtonElement>('button[title="insert option"]')).pop() ?? null;- const submenu = optionButton?.closest(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}="true"]`) as HTMLDivElement | null;- expect(submenu).not.toBeNull();-- fireEvent.mouseLeave(submenu!, { relatedTarget: alignButton });+ }) as HTMLButtonElement;+ const first = createButton(0, 0);+ const second = createButton(56, 0);+ const nextRow = createButton(4, 40);- expect(onMenuPointerLeave).not.toHaveBeenCalled();+ expect(getNextMenuButtonByDirection([first, second, nextRow], 0, 'ArrowRight')).toBe(second);+ expect(getNextMenuButtonByDirection([first, second, nextRow], 1, 'ArrowRight')).toBe(nextRow);});});diff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsxindex a08d43e71d..e0260d4f09 100644--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx@@ -14,24 +14,42 @@* limitations under the License.*/-import { render, screen } from '@testing-library/react';-import React from 'react';-import { describe, expect, it, vi } from 'vitest';+import type { ReactElement } from 'react';+import { render } from '@testing-library/react';+import { ILogService, Injector, LocaleService } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { ComponentManager } from '../../../../common/component-manager';+import { IconManager } from '../../../../common/icon-manager';+import { RediContext } from '../../../../utils/di';import { DropdownMenuLabel } from '../TooltipButtonWrapper';-vi.mock('../../../custom-label/CustomLabel', () => ({- CustomLabel: (props: { label?: unknown }) => React.createElement(- 'span',- {- 'data-testid': 'custom-label',- },- typeof props.label === 'string' ? props.label : 'custom-label'- ),-}));+class TestLocaleService {+ t(key: string) {+ return key;+ }+}++class TestLogService {+ warn(): void {}+}++function renderWithDependencies(element: ReactElement) {+ const injector = new Injector();+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([ILogService, { useClass: TestLogService as never }]);+ injector.add([ComponentManager]);+ injector.add([IconManager]);++ return render(+ <RediContext.Provider value={{ injector }}>+ {element}+ </RediContext.Provider>+ );+}describe('DropdownMenuLabel', () => {it('keeps menu content left-aligned and renders the selected checkmark on the right', () => {- const { container } = render(+ const { container, getByText } = renderWithDependencies(<DropdownMenuLabelvalue="normal"option={{@@ -49,11 +67,11 @@ describe('DropdownMenuLabel', () => {expect(children[0].className).toContain('univer-gap-2');expect(children[1].className).toContain('univer-ml-auto');expect(children[1].querySelector('svg')).toBeTruthy();- expect(screen.getByTestId('custom-label').textContent).toBe('Normal');+ expect(getByText('Normal')).toBeTruthy();});it('reserves the right-side checkmark slot for selectable items even when not selected', () => {- const { container } = render(+ const { container } = renderWithDependencies(<DropdownMenuLabelvalue="normal"option={{diff --git a/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsx b/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsxnew file mode 100644index 0000000000..3509646743--- /dev/null+++ b/packages/ui/src/views/font-family/__tests__/FontInputs.spec.tsx@@ -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 { ICommand } from '@univerjs/core';+import type { ReactElement } from 'react';+import { fireEvent, render } from '@testing-library/react';+import { CommandType, ICommandService, LocaleService, LocaleType, Univer } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { afterEach, describe, expect, it } from 'vitest';+import { FontService, IFontService } from '../../../services/font.service';+import { RediProvider } from '../../../utils/di';+import { FontSize } from '../../font-size/FontSize';+import { FontFamily } from '../FontFamily';++class TestState {+ static commandParams: unknown[] = [];+ static familyChanges: string[] = [];+ static sizeChanges: number[] = [];++ static reset(): void {+ this.commandParams = [];+ this.familyChanges = [];+ this.sizeChanges = [];+ }+}++const SetFontFamilyCommand: ICommand<{ value: string }> = {+ id: 'test.command.set-font-family',+ type: CommandType.COMMAND,+ handler(_accessor, params) {+ TestState.commandParams.push(params);+ return true;+ },+};++function renderWithDependencies(element: ReactElement) {+ const univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([IFontService, { useClass: FontService }]);+ injector.get(LocaleService).load({+ [LocaleType.ZH_CN]: {+ ui: {+ fontFamily: {+ arial: 'Arial',+ 'times-new-roman': 'Times New Roman',+ tahoma: 'Tahoma',+ verdana: 'Verdana',+ },+ },+ },+ });+ injector.get(ICommandService).registerCommand(SetFontFamilyCommand);++ const result = render(+ <RediProvider value={{ injector }}>+ {element}+ </RediProvider>+ );++ return {+ ...result,+ dispose: () => {+ result.unmount();+ univer.dispose();+ },+ };+}++describe('font input views', () => {+ afterEach(() => {+ TestState.reset();+ });++ it('executes the font-family command when the typed text matches a known font', () => {+ const rendered = renderWithDependencies(+ <FontFamily+ id={SetFontFamilyCommand.id}+ value="Arial"+ onChange={(value) => TestState.familyChanges.push(value)}+ />+ );+ const input = rendered.container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: 'times' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(TestState.commandParams).toEqual([{ value: 'Times New Roman' }]);+ expect(TestState.familyChanges).toEqual([]);+ rendered.dispose();+ });++ it('restores the displayed font when the typed text does not match any font', () => {+ const rendered = renderWithDependencies(+ <FontFamily+ id={SetFontFamilyCommand.id}+ value="Arial"+ onChange={(value) => TestState.familyChanges.push(value)}+ />+ );+ const input = rendered.container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: 'Unknown Family' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(TestState.commandParams).toEqual([]);+ expect(TestState.familyChanges).toEqual([]);+ expect(input.value).toBe('Arial');+ rendered.dispose();+ });++ it('commits font size only when Enter is pressed', () => {+ const disabled$ = new BehaviorSubject(false);+ const rendered = render(+ <FontSize+ value={11}+ min={1}+ max={99}+ disabled$={disabled$}+ onChange={(value) => TestState.sizeChanges.push(value)}+ />+ );+ const input = rendered.container.querySelector('input') as HTMLInputElement;++ fireEvent.change(input, { target: { value: '16' } });+ expect(TestState.sizeChanges).toEqual([]);++ fireEvent.keyDown(input, { code: 'Enter' });++ expect(TestState.sizeChanges).toEqual([16]);+ });+});diff --git a/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsx b/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsxindex 1ef710dae1..d92b6b87a6 100644--- a/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsx+++ b/packages/ui/src/views/menu/desktop/__tests__/DesignTinyMenuGroup.spec.tsx@@ -16,12 +16,20 @@import { fireEvent, render, screen } from '@testing-library/react';import React from 'react';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it } from 'vitest';import { DesignTinyMenuGroup } from '../DesignTinyMenuGroup';+class TestState {+ static clickCount = 0;++ static recordClick(): void {+ this.clickCount += 1;+ }+}+describe('DesignTinyMenuGroup', () => {it('renders quick icon items as focusable menu buttons', () => {- const onClick = vi.fn();+ TestState.clickCount = 0;const Icon = () => <span data-testid="quick-icon" />;render(@@ -30,7 +38,7 @@ describe('DesignTinyMenuGroup', () => {key: 'h1',Icon,className: '',- onClick,+ onClick: () => TestState.recordClick(),tooltip: 'Heading 1',}]}columns={6}@@ -44,7 +52,7 @@ describe('DesignTinyMenuGroup', () => {expect(document.activeElement).toBe(button);expect(button.getAttribute('title')).toBeNull();- expect(onClick).toHaveBeenCalledTimes(1);+ expect(TestState.clickCount).toBe(1);});it('keeps native titles for default tiny menus', () => {@@ -56,7 +64,7 @@ describe('DesignTinyMenuGroup', () => {key: 'h1',Icon,className: '',- onClick: vi.fn(),+ onClick: () => undefined,tooltip: 'Heading 1',}]}/>@@ -88,8 +96,8 @@ describe('DesignTinyMenuGroup', () => {const { container } = render(<DesignTinyMenuGroupitems={[- { key: 'black', Icon, className: '', onClick: vi.fn() },- { key: 'red', Icon, className: '', onClick: vi.fn() },+ { key: 'black', Icon, className: '', onClick: () => undefined },+ { key: 'red', Icon, className: '', onClick: () => undefined },]}columns={8}layoutVariant="compact"diff --git a/packages/ui/src/views/menu/desktop/__tests__/TinyMenuGroup.spec.ts b/packages/ui/src/views/menu/desktop/__tests__/TinyMenuGroup.spec.tsdeleted file mode 100644index 436a111547..0000000000--- a/packages/ui/src/views/menu/desktop/__tests__/TinyMenuGroup.spec.ts+++ /dev/null@@ -1,223 +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 { render } from '@testing-library/react';-import { LocaleService } from '@univerjs/core';-import React from 'react';-import { BehaviorSubject, of } from 'rxjs';-import { beforeEach, describe, expect, it, vi } from 'vitest';-import { IconManager } from '../../../../common';-import { MenuItemType } from '../../../../services/menu/menu';-import { getVisibleTinyMenuChildren, resolveMenuItemActiveState, UITinyMenuGroup } from '../TinyMenuGroup';--const dependencyMap = new Map();-const designTinyMenuGroupSpy = vi.fn();--vi.mock('../../../../utils/di', async () => {- const ReactModule = await import('react');-- return {- useDependency(token: unknown) {- return dependencyMap.get(token);- },- useObservable<T>(observable: any, defaultValue?: T) {- const [value, setValue] = ReactModule.useState(defaultValue);-- ReactModule.useEffect(() => {- if (!observable) {- return;- }-- const source = typeof observable === 'function' ? observable() : observable;- const sub = source.subscribe?.((nextValue: T) => setValue(nextValue));-- return () => sub?.unsubscribe?.();- }, [observable]);-- return value;- },- };-});--vi.mock('../DesignTinyMenuGroup', () => ({- DesignTinyMenuGroup: (props: unknown) => {- designTinyMenuGroupSpy(props);- return React.createElement('div', { 'data-testid': 'design-tiny-menu-group' });- },-}));--describe('TinyMenuGroup', () => {- beforeEach(() => {- dependencyMap.clear();- designTinyMenuGroupSpy.mockClear();- dependencyMap.set(IconManager, {- get: () => () => React.createElement('span'),- });- dependencyMap.set(LocaleService, {- t: (key: string) => `translated:${key}`,- direction$: new BehaviorSubject<'ltr'>('ltr'),- });- });-- it('uses explicit active items as an override instead of merging with observable active state', () => {- expect(resolveMenuItemActiveState('h1', true, ['normal-text'])).toBe(false);- expect(resolveMenuItemActiveState('normal-text', false, ['normal-text'])).toBe(true);- expect(resolveMenuItemActiveState('h1', true)).toBe(true);- });-- it('filters hidden tiny menu children before rendering', () => {- const children = [- { key: 'h1', order: 0, item: { id: 'h1' } },- { key: 'title', order: 1, item: { id: 'title' } },- { key: 'subtitle', order: 2, item: { id: 'subtitle' } },- ] as never;-- expect(getVisibleTinyMenuChildren(children, ['title', 'subtitle']).map((item) => item.key)).toEqual(['h1']);- });-- it('passes translated tooltips and command params through tiny icon menu items', () => {- const onOptionSelect = vi.fn();- const item = {- key: 'quick',- order: 0,- children: [{- key: 'text-color',- order: 0,- item: {- id: 'doc.command.set-inline-format-text-color',- type: MenuItemType.BUTTON,- icon: 'TextTypeIcon',- tooltip: 'docs-ui.toolbar.textColor.main',- params: { value: '#FE4B4B' },- hidden$: of(false),- activated$: of(false),- },- }],- } as never;-- render(React.createElement(UITinyMenuGroup, { item, onOptionSelect }));-- const props = designTinyMenuGroupSpy.mock.calls[0][0] as {- items: Array<{ onClick: () => void; tooltip?: string }>;- };-- expect(props.items[0].tooltip).toBe('translated:docs-ui.toolbar.textColor.main');-- props.items[0].onClick();-- expect(onOptionSelect).toHaveBeenCalledWith(expect.objectContaining({- id: 'doc.command.set-inline-format-text-color',- label: 'doc.command.set-inline-format-text-color',- params: { value: '#FE4B4B' },- tooltip: 'translated:docs-ui.toolbar.textColor.main',- }));- });-- it('passes fixed column layout through to the tiny menu renderer', () => {- const item = {- key: 'quick',- order: 0,- children: [{- key: 'h1',- order: 0,- item: {- id: 'doc.command.h1-heading',- type: MenuItemType.BUTTON,- icon: 'H1Icon',- hidden$: of(false),- activated$: of(false),- },- }],- } as never;-- render(React.createElement(UITinyMenuGroup, { item, columns: 6 }));-- const props = designTinyMenuGroupSpy.mock.calls[0][0] as {- columns?: number;- };-- expect(props.columns).toBe(6);- });-- it('passes paragraph T size variant through to the tiny menu renderer', () => {- const item = {- key: 'quick',- order: 0,- children: [{- key: 'h1',- order: 0,- item: {- id: 'doc.command.h1-heading',- type: MenuItemType.BUTTON,- icon: 'H1Icon',- hidden$: of(false),- activated$: of(false),- },- }],- } as never;-- render(React.createElement(UITinyMenuGroup, { item, sizeVariant: 'paragraph-t' }));-- const props = designTinyMenuGroupSpy.mock.calls[0][0] as {- sizeVariant?: string;- };-- expect(props.sizeVariant).toBe('paragraph-t');- });-- it('skips tiny menu children whose icons are not registered', () => {- dependencyMap.set(IconManager, {- get: (key: string) => key === 'KnownIcon' ? () => React.createElement('span') : undefined,- });-- const item = {- key: 'quick',- order: 0,- children: [- {- key: 'known',- order: 0,- item: {- id: 'known',- type: MenuItemType.BUTTON,- icon: 'KnownIcon',- hidden$: of(false),- activated$: of(false),- },- },- {- key: 'missing',- order: 1,- item: {- id: 'missing',- type: MenuItemType.BUTTON,- icon: 'MissingIcon',- hidden$: of(false),- activated$: of(false),- },- },- ],- } as never;-- render(React.createElement(UITinyMenuGroup, { item }));-- const props = designTinyMenuGroupSpy.mock.calls[0][0] as {- items: Array<{ key: string }>;- };-- expect(props.items.map((menuItem) => menuItem.key)).toEqual(['known']);- });-});diff --git a/packages/ui/src/views/menu/desktop/__tests__/TinyMenuGroup.spec.tsx b/packages/ui/src/views/menu/desktop/__tests__/TinyMenuGroup.spec.tsxnew file mode 100644index 0000000000..3a57a586b0--- /dev/null+++ b/packages/ui/src/views/menu/desktop/__tests__/TinyMenuGroup.spec.tsx@@ -0,0 +1,202 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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 { ReactElement } from 'react';+import type { IValueOption } from '../../../../services/menu/menu';+import type { IMenuSchema } from '../../../../services/menu/menu-manager.service';+import { fireEvent, render, screen } from '@testing-library/react';+import { ILogService, Injector, LocaleService } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { describe, expect, it } from 'vitest';+import { IconManager } from '../../../../common/icon-manager';+import { MenuItemType } from '../../../../services/menu/menu';+import { RediContext } from '../../../../utils/di';+import { getVisibleTinyMenuChildren, resolveMenuItemActiveState, UITinyMenuGroup } from '../TinyMenuGroup';++class TestLocaleService {+ readonly direction$ = new BehaviorSubject<'ltr'>('ltr');++ t(key: string): string {+ return `translated:${key}`;+ }+}++class TestLogService {+ warn(): void {}+}++class TestState {+ static selectedOptions: IValueOption[] = [];++ static reset(): void {+ this.selectedOptions = [];+ }+}++function createTinyMenuInjector() {+ const injector = new Injector();+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);+ injector.add([ILogService, { useClass: TestLogService as never }]);+ injector.add([IconManager]);++ const iconManager = injector.get(IconManager);+ iconManager.register({+ TextTypeIcon: ({ className }: { className?: string }) => <span className={className} data-icon="text-type" />,+ H1Icon: ({ className }: { className?: string }) => <span className={className} data-icon="h1" />,+ ResetIcon: ({ className }: { className?: string }) => <span className={className} data-icon="reset" />,+ });++ return injector;+}++function renderWithDependencies(element: ReactElement) {+ return render(+ <RediContext.Provider value={{ injector: createTinyMenuInjector() }}>+ {element}+ </RediContext.Provider>+ );+}++function createChild(+ key: string,+ options: {+ icon?: string;+ tooltip?: string;+ params?: Record<string, unknown>;+ hidden$?: BehaviorSubject<boolean>;+ activated$?: BehaviorSubject<boolean>;+ } = {}+): IMenuSchema {+ return {+ key,+ order: 0,+ item: {+ id: key,+ type: MenuItemType.BUTTON,+ icon: options.icon ?? 'H1Icon',+ tooltip: options.tooltip,+ params: options.params,+ hidden$: options.hidden$,+ activated$: options.activated$,+ },+ };+}++function createGroup(children: IMenuSchema[]): IMenuSchema {+ return {+ key: 'quick',+ order: 0,+ children,+ };+}++function hasClassToken(element: HTMLElement, token: string): boolean {+ return element.className.split(/\s+/).includes(token);+}++describe('TinyMenuGroup', () => {+ it('uses explicit active items as an override instead of merging with observable active state', () => {+ expect(resolveMenuItemActiveState('h1', true, ['normal-text'])).toBe(false);+ expect(resolveMenuItemActiveState('normal-text', false, ['normal-text'])).toBe(true);+ expect(resolveMenuItemActiveState('h1', true)).toBe(true);+ });++ it('filters hidden tiny menu children by item id before rendering', () => {+ const children = [+ createChild('h1'),+ createChild('title'),+ createChild('subtitle'),+ ];++ expect(getVisibleTinyMenuChildren(children, ['title', 'subtitle']).map((item) => item.key)).toEqual(['h1']);+ });++ it('renders visible tiny menu children and submits translated option payloads from clicks', () => {+ TestState.reset();+ const item = createGroup([+ createChild('doc.command.set-inline-format-text-color', {+ icon: 'TextTypeIcon',+ tooltip: 'docs-ui.toolbar.textColor.main',+ params: { value: '#FE4B4B' },+ }),+ createChild('doc.command.hidden-heading', {+ icon: 'H1Icon',+ tooltip: 'docs-ui.toolbar.hidden',+ }),+ ]);++ renderWithDependencies(+ <UITinyMenuGroup+ item={item}+ columns={6}+ hiddenItemIds={['doc.command.hidden-heading']}+ onOptionSelect={(option) => TestState.selectedOptions.push(option)}+ />+ );++ const textColorButton = screen.getByRole('button', { name: 'translated:docs-ui.toolbar.textColor.main' });+ expect(screen.queryByRole('button', { name: 'translated:docs-ui.toolbar.hidden' })).toBeNull();+ expect((textColorButton.parentElement as HTMLElement).style.gridTemplateColumns).toBe('');++ fireEvent.click(textColorButton);++ expect(TestState.selectedOptions).toEqual([{+ id: 'doc.command.set-inline-format-text-color',+ label: 'doc.command.set-inline-format-text-color',+ commandId: undefined,+ params: { value: '#FE4B4B' },+ value: undefined,+ tooltip: 'translated:docs-ui.toolbar.textColor.main',+ }]);+ });++ it('reflects explicit active item overrides in the rendered tiny menu', () => {+ const item = createGroup([+ createChild('doc.command.h1-heading', {+ icon: 'H1Icon',+ tooltip: 'docs-ui.toolbar.heading.h1',+ }),+ createChild('doc.command.reset-heading', {+ icon: 'ResetIcon',+ tooltip: 'docs-ui.toolbar.heading.reset',+ }),+ ]);++ renderWithDependencies(+ <UITinyMenuGroup item={item} activeItemIds={['doc.command.reset-heading']} />+ );++ const h1Button = screen.getByRole('button', { name: 'translated:docs-ui.toolbar.heading.h1' });+ const resetButton = screen.getByRole('button', { name: 'translated:docs-ui.toolbar.heading.reset' });+ expect(hasClassToken(h1Button, 'univer-bg-gray-50')).toBe(false);+ expect(hasClassToken(resetButton, 'univer-bg-gray-50')).toBe(true);+ });++ it('uses compact paragraph layout dimensions for dense paragraph menus', () => {+ const item = createGroup([+ createChild('black', { icon: 'H1Icon' }),+ createChild('red', { icon: 'ResetIcon' }),+ ]);++ const { container } = renderWithDependencies(+ <UITinyMenuGroup item={item} columns={8} sizeVariant="paragraph-t" layoutVariant="compact" />+ );++ const group = container.querySelector('.univer-menu-item-group') as HTMLElement;+ expect(group.style.gridTemplateColumns).toBe('repeat(8, max-content)');+ expect(hasClassToken(screen.getByRole('button', { name: 'black' }), 'univer-rounded-sm')).toBe(true);+ });+});diff --git a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsxindex 7645bf0bfb..dfe1be5b6b 100644--- a/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx+++ b/packages/ui/src/views/mobile-workbench/MobileWorkbench.tsx@@ -14,13 +14,15 @@* limitations under the License.*/+import type { Injector } from '@univerjs/core';+import type { ComponentType } from 'react';import type { IWorkbenchOptions } from '../../controllers/ui/ui.controller';import { LocaleService, ThemeService } from '@univerjs/core';-import { borderBottomClassName, clsx, ConfigProvider } from '@univerjs/design';+import { borderBottomClassName, clsx, ConfigProvider, render as createRoot } from '@univerjs/design';import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { BuiltInUIPart } from '../../services/parts/parts.service';import { ThemeSwitcherService } from '../../services/theme-switcher/theme-switcher.service';-import { useDependency } from '../../utils/di';+import { connectInjector, useDependency } from '../../utils/di';import { ComponentContainer, useComponentsOfPart } from '../components/ComponentContainer';import { MobileContextMenu } from '../components/context-menu/MobileContextMenu';import { Sidebar } from '../components/sidebar/Sidebar';@@ -31,6 +33,24 @@ export interface IUniverAppProps extends IWorkbenchOptions {onRendered?: (container: HTMLElement) => void;}+export function mountMobileWorkbench(+ injector: Injector,+ options: IWorkbenchOptions,+ mountContainer: HTMLElement,+ onRendered: (contentElement: HTMLElement) => void+): void {+ const ConnectedApp = connectInjector(MobileWorkbench, injector) as ComponentType<IUniverAppProps>;++ createRoot(+ <ConnectedApp+ {...options}+ mountContainer={mountContainer}+ onRendered={onRendered}+ />,+ mountContainer+ );+}+export function MobileWorkbench(props: IUniverAppProps) {const {header = true,diff --git a/packages/ui/src/views/workbench/Workbench.tsx b/packages/ui/src/views/workbench/Workbench.tsxindex fa9019ed17..363c7ac1dc 100644--- a/packages/ui/src/views/workbench/Workbench.tsx+++ b/packages/ui/src/views/workbench/Workbench.tsx@@ -14,16 +14,18 @@* limitations under the License.*/+import type { Injector } from '@univerjs/core';+import type { ComponentType } from 'react';import type { IUniverUIConfig } from '../../config/config';import type { IWorkbenchOptions } from '../../controllers/ui/ui.controller';import { IConfigService, LocaleService, ThemeService } from '@univerjs/core';-import { borderBottomClassName, clsx, ConfigContext, ConfigProvider } from '@univerjs/design';+import { borderBottomClassName, clsx, ConfigContext, ConfigProvider, render as createRoot } from '@univerjs/design';import { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { UI_PLUGIN_CONFIG_KEY } from '../../config/config';import { BuiltInUIPart } from '../../services/parts/parts.service';import { ThemeSwitcherService } from '../../services/theme-switcher/theme-switcher.service';-import { useDependency } from '../../utils/di';+import { connectInjector, useDependency } from '../../utils/di';import { ComponentContainer, useComponentsOfPart } from '../components/ComponentContainer';import { DesktopContextMenu } from '../components/context-menu/ContextMenu';import { Sidebar } from '../components/sidebar/Sidebar';@@ -40,6 +42,24 @@ export function DesktopWorkbench(props: IUniverWorkbenchProps) {return <DesktopWorkbenchContent {...props} {...uiConfig} />;}+export function mountDesktopWorkbench(+ injector: Injector,+ options: IWorkbenchOptions,+ mountContainer: HTMLElement,+ onRendered: (contentElement: HTMLElement) => void+): void {+ const ConnectedApp = connectInjector(DesktopWorkbench, injector) as ComponentType<IUniverWorkbenchProps>;++ createRoot(+ <ConnectedApp+ {...options}+ mountContainer={mountContainer}+ onRendered={onRendered}+ />,+ mountContainer+ );+}+export function DesktopWorkbenchContent(props: IUniverWorkbenchProps) {const {header = true,diff --git a/packages/uniscript/src/commands/operations/__tests__/panel.operation.spec.ts b/packages/uniscript/src/commands/operations/__tests__/panel.operation.spec.tsnew file mode 100644index 0000000000..cbc3d07e3e--- /dev/null+++ b/packages/uniscript/src/commands/operations/__tests__/panel.operation.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 { ICommandService, Univer } from '@univerjs/core';+import { DesktopSidebarService, ISidebarService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { ScriptPanelService } from '../../../services/script-panel.service';+import { ScriptPanelComponentName, ToggleScriptPanelOperation } from '../panel.operation';++describe('ToggleScriptPanelOperation', () => {+ let univer: Univer;+ let commandService: ICommandService;+ let scriptPanelService: ScriptPanelService;+ let sidebarService: ISidebarService;++ beforeEach(() => {+ univer = new Univer();+ const injector = univer.__getInjector();+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);+ injector.add([ScriptPanelService]);++ commandService = injector.get(ICommandService);+ commandService.registerCommand(ToggleScriptPanelOperation);+ scriptPanelService = injector.get(ScriptPanelService);+ sidebarService = injector.get(ISidebarService);+ });++ afterEach(() => {+ univer.dispose();+ });++ it('opens the Uniscript sidebar when the panel is closed', async () => {+ const result = await commandService.executeCommand(ToggleScriptPanelOperation.id);++ expect(result).toBe(true);+ expect(scriptPanelService.isOpen).toBe(true);+ expect(sidebarService.visible).toBe(true);+ expect(sidebarService.options.children?.label).toBe(ScriptPanelComponentName);+ expect(sidebarService.width).toBeUndefined();+ });++ it('closes the Uniscript sidebar when the panel is already open', async () => {+ await commandService.executeCommand(ToggleScriptPanelOperation.id);++ const result = await commandService.executeCommand(ToggleScriptPanelOperation.id);++ expect(result).toBe(true);+ expect(scriptPanelService.isOpen).toBe(false);+ expect(sidebarService.visible).toBe(false);+ });+});diff --git a/packages/uniscript/src/services/__tests__/script-editor.service.spec.ts b/packages/uniscript/src/services/__tests__/script-editor.service.spec.tsindex bc496f617c..4e191113a2 100644--- a/packages/uniscript/src/services/__tests__/script-editor.service.spec.ts+++ b/packages/uniscript/src/services/__tests__/script-editor.service.spec.ts@@ -26,11 +26,11 @@ describe('ScriptEditorService', () => {vi.stubGlobal('window', globalThis);Reflect.deleteProperty(window, 'MonacoEnvironment');const injector = new Injector();- injector.add([IConfigService, {- useValue: {- getConfig: (key: string) => key === UNISCRIPT_PLUGIN_CONFIG_KEY ? { getWorkerUrl: () => 'worker.js' } : undefined,- } as unknown as IConfigService,- }]);+ class TestConfigService {+ getConfig = (key: string) => key === UNISCRIPT_PLUGIN_CONFIG_KEY ? { getWorkerUrl: () => 'worker.js' } : undefined;+ }++ injector.add([IConfigService, { useClass: TestConfigService as never }]);injector.add([ScriptEditorService]);service = injector.get(ScriptEditorService);});diff --git a/packages/uniscript/src/services/__tests__/script-execution.service.spec.ts b/packages/uniscript/src/services/__tests__/script-execution.service.spec.tsindex 56932edd0d..178afe99c0 100644--- a/packages/uniscript/src/services/__tests__/script-execution.service.spec.ts+++ b/packages/uniscript/src/services/__tests__/script-execution.service.spec.ts@@ -27,9 +27,13 @@ describe('UniscriptExecutionService', () => {beforeEach(() => {Reflect.deleteProperty(globalThis, '__uniscriptResult');const injector = new Injector();+ class TestCommandService {}++ class TestUniverInstanceService {}+injector.add([ILogService, { useClass: DesktopLogService }]);- injector.add([ICommandService, { useValue: {} as ICommandService }]);- injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);+ injector.add([ICommandService, { useClass: TestCommandService as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);injector.add([LifecycleService]);injector.add([IUniscriptExecutionService, { useClass: UniscriptExecutionService }]);service = injector.get(IUniscriptExecutionService);diff --git a/packages/watermark/src/services/watermark.service.spec.ts b/packages/watermark/src/services/watermark.service.spec.tsindex 01a9e5e4f3..3eab4debfe 100644--- a/packages/watermark/src/services/watermark.service.spec.ts+++ b/packages/watermark/src/services/watermark.service.spec.ts@@ -14,20 +14,30 @@* limitations under the License.*/+import { ILocalStorageService, Injector } from '@univerjs/core';import { UNIVER_WATERMARK_STORAGE_KEY } from '@univerjs/engine-render';import { describe, expect, it, vi } from 'vitest';import { WatermarkService } from './watermark.service';+const getItem = vi.fn(async () => ({ type: 'text' }));+const setItem = vi.fn();+const removeItem = vi.fn();++class TestLocalStorage {+ getItem = getItem;+ setItem = setItem;+ removeItem = removeItem;+}+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);+ getItem.mockClear();+ setItem.mockClear();+ removeItem.mockClear();+ const injector = new Injector();+ injector.add([ILocalStorageService, { useClass: TestLocalStorage as never }]);+ injector.add([WatermarkService]);+ const service = injector.get(WatermarkService);await expect(service.getWatermarkConfig()).resolves.toEqual({ type: 'text' });expect(getItem).toHaveBeenCalledWith(UNIVER_WATERMARK_STORAGE_KEY);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 261d40e77f..967389e3e7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -17,7 +17,7 @@ importers:devDependencies:'@antfu/eslint-config':specifier: ^9.0.0- version: 9.0.0(@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]))(@typescript-eslint/[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])+ version: 9.0.0(@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]))(@typescript-eslint/[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])'@commitlint/cli':specifier: ^21.0.2@@ -67,8 +67,8 @@ importers:specifier: ^7.1.1version: 7.1.1([email protected]([email protected]))eslint-plugin-react-refresh:- specifier: ^0.5.2- version: 0.5.2([email protected]([email protected]))+ specifier: ^0.5.3+ version: 0.5.3([email protected]([email protected]))husky:specifier: ^9.1.7version: 9.1.7@@ -76,8 +76,8 @@ importers:specifier: ^17.0.7version: 17.0.7posthog-node:- specifier: ^5.37.0- version: 5.37.0([email protected])+ specifier: ^5.38.0+ version: 5.38.0([email protected])react:specifier: 19.2.7version: 19.2.7@@ -984,6 +984,9 @@ importers:specifier: workspace:*version: link:../uidevDependencies:+ '@testing-library/react':+ specifier: ^16.3.2+ version: 16.3.2(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@univerjs-infra/shared':specifier: workspace:*version: link:../../common/shared@@ -2788,6 +2791,9 @@ importers:'@univerjs-infra/shared':specifier: workspace:*version: link:../../common/shared+ '@univerjs/engine-render':+ specifier: workspace:*+ version: link:../engine-renderpostcss:specifier: ^8.5.15version: 8.5.15@@ -5567,11 +5573,11 @@ packages:engines: {node: '>=18'}hasBin: true- '@posthog/[email protected]':- resolution: {integrity: sha512-vwOEMfZvGv5XxNWV7p9I52NSmvFNMhyW2IHpIoUHW5jLkgUrknzJW1H/qxVGSIrNNVQkfsoaDFzDhJdg10pgrA==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-hf+COAWSAG1UQHluPsfAOJDOR8tr8YY7cdf58ENGt20pEEWZ6sH3IbtvFDWkhp0ulSftA62x17w8R/f6IAwwEA==}- '@posthog/[email protected]':- resolution: {integrity: sha512-LqJoiQi2eyWn7rCUgnn+D+F3Efp6+04o72bjSX6kWHx0nFaYNC/nJuAIRliDTY/X7GPIUAaHAcSjbMI/9wfX1Q==}+ '@posthog/[email protected]':+ resolution: {integrity: sha512-XR0B1geABbnUlSNv4RuFWvk19D870B668C/XzcKDctAZ+xCH5gmGM0oltGbA9yj+2ia9Y65nOrDYKN6Whu1oBw==}'@protobufjs/[email protected]':resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}@@ -8568,8 +8574,8 @@ packages:eslint: '*'typescript: '*'- resolution: {integrity: sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==}+ resolution: {integrity: sha512-5EMmLCV98Pi4o/f/3DP/v/tNqLHMIc9I8LKClNDWhZ9JTho89/kQcitCXQBMG7sAfVRK0Ie3T2EDOzp1YXYiVA==}peerDependencies:eslint: ^9 || ^10@@ -10696,8 +10702,8 @@ packages:resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}engines: {node: ^10 || ^12 || >=14}- resolution: {integrity: sha512-wFwWGcqAqZ1WJRlNNYc92veV83d1lOQcP4Lq0q7Kar9GdZLPpiFYHeudyybYJnjZjkI9v06vLvY/Og5CZIfByg==}+ resolution: {integrity: sha512-xEojUWq7ajYfsMPZIexG9xtvhewpqrPWvL/qRhnm8W3KVZi6BlXHe29tjywZJglrDwEQpqdtYKbRXyg2zF9MWw==}engines: {node: ^20.20.0 || >=22.22.0}peerDependencies:rxjs: ^7.0.0@@ -12257,7 +12263,7 @@ snapshots:'@alloc/[email protected]': {}- '@antfu/[email protected](@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]))(@typescript-eslint/[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])':+ '@antfu/[email protected](@eslint-react/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))(@typescript-eslint/[email protected]([email protected]))(@typescript-eslint/[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])':dependencies:'@antfu/install-pkg': 1.1.0'@clack/prompts': 1.5.1@@ -12299,7 +12305,7 @@ snapshots:optionalDependencies:eslint-plugin-format: 2.0.1([email protected]([email protected]))- eslint-plugin-react-refresh: 0.5.2([email protected]([email protected]))+ eslint-plugin-react-refresh: 0.5.3([email protected]([email protected]))transitivePeerDependencies:- '@eslint/json'- '@typescript-eslint/rule-tester'@@ -14029,11 +14035,11 @@ snapshots:dependencies:playwright: 1.57.0- '@posthog/[email protected]':+ '@posthog/[email protected]':dependencies:- '@posthog/types': 1.386.3+ '@posthog/types': 1.387.0- '@posthog/[email protected]': {}+ '@posthog/[email protected]': {}'@protobufjs/[email protected]': {}@@ -15158,8 +15164,8 @@ snapshots:'@typescript-eslint/[email protected]([email protected])':dependencies:- '@typescript-eslint/tsconfig-utils': 8.56.1([email protected])- '@typescript-eslint/types': 8.56.1+ '@typescript-eslint/tsconfig-utils': 8.61.0([email protected])+ '@typescript-eslint/types': 8.61.0debug: 4.4.3typescript: 6.0.3transitivePeerDependencies:@@ -17177,7 +17183,7 @@ snapshots:transitivePeerDependencies:- supports-colordependencies:eslint: 10.5.0([email protected])@@ -19693,9 +19699,9 @@ snapshots:picocolors: 1.1.1source-map-js: 1.2.1dependencies:- '@posthog/core': 1.32.3+ '@posthog/core': 1.34.0optionalDependencies:rxjs: 7.8.2diff --git a/turbo.json b/turbo.jsonindex 443b4b4057..5b9087dc7b 100644--- a/turbo.json+++ b/turbo.json@@ -5,7 +5,7 @@},"coverage": {- "cache": false+ "outputs": ["coverage/**"]},"build": {