Skip to content

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

test: add unit tests (#7110)

白熱e5f7f2d33206
diff --git a/common/shared/vitest/index.ts b/common/shared/vitest/index.ts
index c6af59c2f4..5d0982fc9f 100644
--- a/common/shared/vitest/index.ts
+++ b/common/shared/vitest/index.ts
@@ -66,6 +66,7 @@ export default function createConfig(options?: any) {
'**/src/menu/**',
'**/src/plugin.ts',
'**/src/mobile-plugin.ts',
+ '**/src/facade/index.ts',
'**/src/config/config.ts',
],
},
diff --git a/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx b/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx
index 5ce7f87a73..b9793045da 100644
--- a/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx
+++ b/packages/action-recorder/src/views/components/RecorderPanel.spec.tsx
@@ -268,4 +268,50 @@ describe('RecorderPanel', () => {
expect(container.textContent).toBe('');
expect(TestState.downloads).toHaveLength(0);
});
+
+ it('completes an active recording from the panel cancel action using the stop command', 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(APPLY_CELL_VALUE_COMMAND_ID, {
+ unitId: 'focused-workbook',
+ subUnitId: 'sheet-1',
+ value: 'cancelled',
+ });
+ });
+
+ expect(container.textContent).toContain(`1: ${APPLY_CELL_VALUE_COMMAND_ID}`);
+
+ await act(async () => {
+ getButton(container!, 'Cancel').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(currentTestBed.recorderService.recording).toBe(false);
+ expect(container.textContent).toContain('Start Recording');
+ expect(TestState.downloads).toHaveLength(1);
+ expect(JSON.parse(await TestState.downloads[0].data.text())).toEqual([
+ {
+ id: APPLY_CELL_VALUE_COMMAND_ID,
+ type: CommandType.COMMAND,
+ params: {
+ unitId: 'focused-workbook',
+ subUnitId: 'sheet-1',
+ value: 'cancelled',
+ },
+ },
+ ]);
+ });
});
diff --git a/packages/core/src/facade/__tests__/f-base.spec.ts b/packages/core/src/facade/__tests__/f-base.spec.ts
new file mode 100644
index 0000000000..9202727b4c
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-base.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 type { Injector as IInjector } from '@univerjs/core';
+import { Inject, Injector } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { FBase, FBaseInitialable } from '../f-base';
+
+describe('FBase', () => {
+ it('should add facade extension methods and run initializers with the active injector', () => {
+ const initLog = new WeakMap<object, string[]>();
+
+ class BaseSource {
+ static sourceLabel = 'base-source';
+
+ greet(this: { prefix: string }, name: string) {
+ return `${this.prefix}:${name}`;
+ }
+ }
+
+ class InitSourceA {
+ static initSource = 'a';
+
+ _initialize(injector: IInjector) {
+ const current = initLog.get(this) ?? [];
+ current.push(`a:${Boolean(injector)}`);
+ initLog.set(this, current);
+ }
+
+ mark(this: { steps: string[] }, value: string) {
+ this.steps.push(`mark:${value}`);
+ }
+ }
+
+ class InitSourceB {
+ _initialize() {
+ const current = initLog.get(this) ?? [];
+ current.push('b');
+ initLog.set(this, current);
+ }
+ }
+
+ class BaseFacade extends FBase {
+ prefix = 'base';
+ }
+
+ class AutoInitialable extends FBaseInitialable {
+ steps: string[] = [];
+
+ constructor(@Inject(Injector) injector: IInjector) {
+ super(injector);
+ }
+ }
+
+ class ManualInitialable extends FBaseInitialable {
+ steps: string[] = [];
+
+ constructor(@Inject(Injector) injector: IInjector) {
+ super(injector);
+ }
+
+ static enableManualInitForTest() {
+ this._enableManualInit();
+ }
+
+ runManualInitializers(injector: IInjector) {
+ this._runInitializers(injector);
+ }
+ }
+
+ BaseFacade.extend(BaseSource);
+ AutoInitialable.extend(InitSourceA);
+ AutoInitialable.extend(InitSourceB);
+ ManualInitialable.extend(InitSourceA);
+ ManualInitialable.enableManualInitForTest();
+
+ const injector = new Injector();
+ const baseFacade = injector.createInstance(BaseFacade) as BaseFacade & { greet(name: string): string };
+ const auto = injector.createInstance(AutoInitialable) as AutoInitialable & { mark(value: string): void };
+ const manual = injector.createInstance(ManualInitialable) as ManualInitialable & { mark(value: string): void };
+
+ expect(baseFacade.greet('univer')).toBe('base:univer');
+ expect((BaseFacade as typeof BaseFacade & { sourceLabel: string }).sourceLabel).toBe('base-source');
+
+ expect(initLog.get(auto)).toEqual(['a:true', 'b']);
+ auto.mark('auto');
+ expect(auto.steps).toEqual(['mark:auto']);
+ expect((AutoInitialable as typeof AutoInitialable & { initSource: string }).initSource).toBe('a');
+
+ expect(initLog.get(manual)).toBeUndefined();
+ manual.runManualInitializers(injector);
+ manual.mark('manual');
+ expect(initLog.get(manual)).toEqual(['a:true']);
+ expect(manual.steps).toEqual(['mark:manual']);
+ });
+});
diff --git a/packages/core/src/facade/__tests__/f-core-facade.spec.ts b/packages/core/src/facade/__tests__/f-core-facade.spec.ts
deleted file mode 100644
index 28355eb571..0000000000
--- a/packages/core/src/facade/__tests__/f-core-facade.spec.ts
+++ /dev/null
@@ -1,277 +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 { describe, expect, it, vi } from 'vitest';
-import { Injector } from '../../common/di';
-import {
- AbsoluteRefType,
- AutoFillSeries,
- BaselineOffset,
- BooleanNumber,
- BorderStyleTypes,
- BorderType,
- ColorType,
- CommandType,
- CommonHideTypes,
- CopyPasteType,
- DataValidationErrorStyle,
- DataValidationOperator,
- DataValidationRenderMode,
- DataValidationStatus,
- DataValidationType,
- DeleteDirection,
- DeveloperMetadataVisibility,
- Dimension,
- Direction,
- HorizontalAlign,
- InterpolationPointType,
- LifecycleStages,
- LocaleType,
- MentionType,
- ProtectionType,
- RelativeDate,
- SheetTypes,
- TextDecoration,
- TextDirection,
- ThemeColorType,
- UniverInstanceType,
- VerticalAlign,
- WrapStrategy,
-} from '../../index';
-import { FBase, FBaseInitialable } from '../f-base';
-import { FEnum } from '../f-enum';
-import { FEventName } from '../f-event';
-import { FEventRegistry } from '../f-event-registry';
-
-describe('facade core primitives', () => {
- it('should extend FBase and FBaseInitialable with methods, statics and initializers', () => {
- const initLog = new WeakMap<object, string[]>();
-
- class BaseSource {
- static sourceLabel = 'base-source';
-
- greet(this: { prefix: string }, name: string) {
- return `${this.prefix}:${name}`;
- }
- }
-
- class InitSourceA {
- static initSource = 'a';
-
- _initialize(injector: Injector) {
- const current = initLog.get(this) ?? [];
- current.push(`a:${injector instanceof Injector}`);
- initLog.set(this, current);
- }
-
- mark(this: { steps: string[] }, value: string) {
- this.steps.push(`mark:${value}`);
- }
- }
-
- class InitSourceB {
- _initialize() {
- const current = initLog.get(this) ?? [];
- current.push('b');
- initLog.set(this, current);
- }
- }
-
- class BaseFacade extends FBase {
- prefix = 'base';
- }
-
- class AutoInitialable extends FBaseInitialable {
- steps: string[] = [];
- }
-
- class ManualInitialable extends FBaseInitialable {
- steps: string[] = [];
-
- static enableManualInitForTest() {
- this._enableManualInit();
- }
-
- runManualInitializers(injector: Injector) {
- this._runInitializers(injector);
- }
- }
-
- BaseFacade.extend(BaseSource);
- AutoInitialable.extend(InitSourceA);
- AutoInitialable.extend(InitSourceB);
- ManualInitialable.extend(InitSourceA);
- ManualInitialable.enableManualInitForTest();
-
- const injector = new Injector();
- const baseFacade = new BaseFacade() as BaseFacade & { greet(name: string): string };
- const auto = new AutoInitialable(injector) as AutoInitialable & { mark(value: string): void };
- const manual = new ManualInitialable(injector) as ManualInitialable & { mark(value: string): void };
-
- expect(baseFacade.greet('univer')).toBe('base:univer');
- expect((BaseFacade as typeof BaseFacade & { sourceLabel: string }).sourceLabel).toBe('base-source');
-
- expect(initLog.get(auto)).toEqual(['a:true', 'b']);
- auto.mark('auto');
- expect(auto.steps).toEqual(['mark:auto']);
- expect((AutoInitialable as typeof AutoInitialable & { initSource: string }).initSource).toBe('a');
-
- expect(initLog.get(manual)).toBeUndefined();
- manual.runManualInitializers(injector);
- manual.mark('manual');
- expect(initLog.get(manual)).toEqual(['a:true']);
- expect(manual.steps).toEqual(['mark:manual']);
- });
-
- it('should lazily register event handlers and dispose them when listeners are removed', () => {
- const registry = new FEventRegistry();
- const disposeSpy = vi.fn();
- const initSpy = vi.fn(() => ({ dispose: disposeSpy }));
- const listenerA = vi.fn((params: { stage: LifecycleStages; cancel?: boolean }) => {
- params.cancel = true;
- });
- const listenerB = vi.fn();
-
- const handlerDisposable = registry.registerEventHandler('LifeCycleChanged', initSpy);
- expect(initSpy).not.toHaveBeenCalled();
-
- const listenerADisposable = registry.addEvent('LifeCycleChanged', listenerA);
- expect(initSpy).toHaveBeenCalledTimes(1);
-
- const result = registry.fireEvent('LifeCycleChanged', { stage: LifecycleStages.Ready, cancel: false });
- expect(result).toBe(true);
- expect(listenerA).toHaveBeenCalledWith({ stage: LifecycleStages.Ready, cancel: true });
-
- const listenerBDisposable = registry.addEvent('LifeCycleChanged', listenerB);
- expect(initSpy).toHaveBeenCalledTimes(1);
-
- listenerADisposable.dispose();
- expect(disposeSpy).not.toHaveBeenCalled();
-
- listenerBDisposable.dispose();
- expect(disposeSpy).toHaveBeenCalledTimes(1);
-
- registry.addEvent('LifeCycleChanged', listenerA);
- expect(initSpy).toHaveBeenCalledTimes(2);
-
- handlerDisposable.dispose();
- expect(disposeSpy).toHaveBeenCalledTimes(2);
- });
-
- it('should expose facade enum and event name singletons and support extension', () => {
- class EnumSource {
- static label = 'enum-source';
-
- extraEnum(this: { marker: string }) {
- return `${this.marker}:enum`;
- }
- }
-
- class EventSource {
- static label = 'event-source';
-
- extraEvent(this: { marker: string }) {
- return `${this.marker}:event`;
- }
- }
-
- class ExtendedEnum extends FEnum {
- marker = 'extended';
- }
-
- class ExtendedEventName extends FEventName {
- marker = 'extended';
- }
-
- ExtendedEnum.extend(EnumSource);
- ExtendedEventName.extend(EventSource);
-
- FEnum._instance = null;
- FEventName._instance = null;
-
- const facadeEnum = FEnum.get();
- const sameFacadeEnum = FEnum.get();
- const facadeEvent = FEventName.get();
- const sameFacadeEvent = FEventName.get();
-
- expect(facadeEnum).toBe(sameFacadeEnum);
- expect(facadeEvent).toBe(sameFacadeEvent);
-
- const enumMap: Record<string, unknown> = {
- AbsoluteRefType,
- UniverInstanceType,
- LifecycleStages,
- DataValidationType,
- DataValidationErrorStyle,
- DataValidationRenderMode,
- DataValidationOperator,
- DataValidationStatus,
- CommandType,
- BaselineOffset,
- BooleanNumber,
- HorizontalAlign,
- TextDecoration,
- TextDirection,
- VerticalAlign,
- WrapStrategy,
- BorderType,
- BorderStyleTypes,
- AutoFillSeries,
- ColorType,
- CommonHideTypes,
- CopyPasteType,
- DeleteDirection,
- DeveloperMetadataVisibility,
- Dimension,
- Direction,
- InterpolationPointType,
- LocaleType,
- MentionType,
- ProtectionType,
- RelativeDate,
- SheetTypes,
- ThemeColorType,
- };
-
- Object.entries(enumMap).forEach(([key, value]) => {
- expect(((facadeEnum as unknown) as Record<string, unknown>)[key]).toBe(value);
- });
-
- const eventMap = {
- DocCreated: 'DocCreated',
- DocDisposed: 'DocDisposed',
- LifeCycleChanged: 'LifeCycleChanged',
- Redo: 'Redo',
- Undo: 'Undo',
- BeforeRedo: 'BeforeRedo',
- BeforeUndo: 'BeforeUndo',
- CommandExecuted: 'CommandExecuted',
- BeforeCommandExecute: 'BeforeCommandExecute',
- };
-
- Object.entries(eventMap).forEach(([key, value]) => {
- expect(((facadeEvent as unknown) as Record<string, unknown>)[key]).toBe(value);
- });
-
- const extendedEnum = new ExtendedEnum() as ExtendedEnum & { extraEnum(): string };
- const extendedEvent = new ExtendedEventName() as ExtendedEventName & { extraEvent(): string };
-
- expect(extendedEnum.extraEnum()).toBe('extended:enum');
- expect((ExtendedEnum as typeof ExtendedEnum & { label: string }).label).toBe('enum-source');
- expect(extendedEvent.extraEvent()).toBe('extended:event');
- expect((ExtendedEventName as typeof ExtendedEventName & { label: string }).label).toBe('event-source');
- });
-});
diff --git a/packages/core/src/facade/__tests__/f-doc.spec.ts b/packages/core/src/facade/__tests__/f-doc.spec.ts
new file mode 100644
index 0000000000..c741ca2076
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-doc.spec.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, IDocumentData, Injector } from '@univerjs/core';
+import { Univer, UniverInstanceType } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { FDoc } from '../f-doc';
+
+function createDocData(id: string): Partial<IDocumentData> {
+ return {
+ id,
+ body: {
+ dataStream: 'Document facade\r\n',
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
+describe('FDoc', () => {
+ let univer: Univer;
+
+ beforeEach(() => {
+ univer = new Univer();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should initialize document facade extensions with the active document model', () => {
+ class DocumentFacadeExtension {
+ _initialize(this: { initializedByInjector?: boolean }, injector: Injector) {
+ this.initializedByInjector = injector === univer.__getInjector();
+ }
+
+ getDocId(this: { doc: DocumentDataModel }) {
+ return this.doc.getUnitId();
+ }
+
+ getDataStream(this: { doc: DocumentDataModel }) {
+ return this.doc.getSnapshot().body?.dataStream;
+ }
+ }
+
+ FDoc.extend(DocumentFacadeExtension);
+
+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-facade-test')) as DocumentDataModel;
+ const facadeDoc = univer.__getInjector().createInstance(FDoc, doc) as FDoc & {
+ getDocId(): string;
+ getDataStream(): string | undefined;
+ initializedByInjector?: boolean;
+ };
+
+ expect(facadeDoc.getDocId()).toBe('doc-facade-test');
+ expect(facadeDoc.getDataStream()).toBe('Document facade\r\n');
+ expect(facadeDoc.initializedByInjector).toBe(true);
+ });
+});
diff --git a/packages/core/src/facade/__tests__/f-enum.spec.ts b/packages/core/src/facade/__tests__/f-enum.spec.ts
new file mode 100644
index 0000000000..9547136aad
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-enum.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 {
+ AbsoluteRefType,
+ AutoFillSeries,
+ BaselineOffset,
+ BooleanNumber,
+ BorderStyleTypes,
+ BorderType,
+ ColorType,
+ CommandType,
+ CommonHideTypes,
+ CopyPasteType,
+ DataValidationErrorStyle,
+ DataValidationOperator,
+ DataValidationRenderMode,
+ DataValidationStatus,
+ DataValidationType,
+ DeleteDirection,
+ DeveloperMetadataVisibility,
+ Dimension,
+ Direction,
+ HorizontalAlign,
+ InterpolationPointType,
+ LifecycleStages,
+ LocaleType,
+ MentionType,
+ ProtectionType,
+ RelativeDate,
+ SheetTypes,
+ TextDecoration,
+ TextDirection,
+ ThemeColorType,
+ UniverInstanceType,
+ VerticalAlign,
+ WrapStrategy,
+} from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { FEnum } from '../f-enum';
+
+describe('FEnum', () => {
+ it('should expose the enum values used by facade commands, units, styles and validations', () => {
+ FEnum._instance = null;
+
+ const facadeEnum = FEnum.get();
+
+ expect(facadeEnum).toBe(FEnum.get());
+
+ expect(facadeEnum.AbsoluteRefType).toBe(AbsoluteRefType);
+ expect(facadeEnum.UniverInstanceType).toBe(UniverInstanceType);
+ expect(facadeEnum.LifecycleStages).toBe(LifecycleStages);
+ expect(facadeEnum.DataValidationType).toBe(DataValidationType);
+ expect(facadeEnum.DataValidationErrorStyle).toBe(DataValidationErrorStyle);
+ expect(facadeEnum.DataValidationRenderMode).toBe(DataValidationRenderMode);
+ expect(facadeEnum.DataValidationOperator).toBe(DataValidationOperator);
+ expect(facadeEnum.DataValidationStatus).toBe(DataValidationStatus);
+ expect(facadeEnum.CommandType).toBe(CommandType);
+ expect(facadeEnum.BaselineOffset).toBe(BaselineOffset);
+ expect(facadeEnum.BooleanNumber).toBe(BooleanNumber);
+ expect(facadeEnum.HorizontalAlign).toBe(HorizontalAlign);
+ expect(facadeEnum.TextDecoration).toBe(TextDecoration);
+ expect(facadeEnum.TextDirection).toBe(TextDirection);
+ expect(facadeEnum.VerticalAlign).toBe(VerticalAlign);
+ expect(facadeEnum.WrapStrategy).toBe(WrapStrategy);
+ expect(facadeEnum.BorderType).toBe(BorderType);
+ expect(facadeEnum.BorderStyleTypes).toBe(BorderStyleTypes);
+ expect(facadeEnum.AutoFillSeries).toBe(AutoFillSeries);
+ expect(facadeEnum.ColorType).toBe(ColorType);
+ expect(facadeEnum.CommonHideTypes).toBe(CommonHideTypes);
+ expect(facadeEnum.CopyPasteType).toBe(CopyPasteType);
+ expect(facadeEnum.DeleteDirection).toBe(DeleteDirection);
+ expect(facadeEnum.DeveloperMetadataVisibility).toBe(DeveloperMetadataVisibility);
+ expect(facadeEnum.Dimension).toBe(Dimension);
+ expect(facadeEnum.Direction).toBe(Direction);
+ expect(facadeEnum.InterpolationPointType).toBe(InterpolationPointType);
+ expect(facadeEnum.LocaleType).toBe(LocaleType);
+ expect(facadeEnum.MentionType).toBe(MentionType);
+ expect(facadeEnum.ProtectionType).toBe(ProtectionType);
+ expect(facadeEnum.RelativeDate).toBe(RelativeDate);
+ expect(facadeEnum.SheetTypes).toBe(SheetTypes);
+ expect(facadeEnum.ThemeColorType).toBe(ThemeColorType);
+ });
+
+ it('should let plugins extend enum facade instances and static metadata', () => {
+ class EnumSource {
+ static label = 'enum-source';
+
+ extraEnum(this: { marker: string }) {
+ return `${this.marker}:enum`;
+ }
+ }
+
+ class ExtendedEnum extends FEnum {
+ marker = 'extended';
+ }
+
+ ExtendedEnum.extend(EnumSource);
+
+ const extendedEnum = new ExtendedEnum() as ExtendedEnum & { extraEnum(): string };
+
+ expect(extendedEnum.extraEnum()).toBe('extended:enum');
+ expect((ExtendedEnum as typeof ExtendedEnum & { label: string }).label).toBe('enum-source');
+ });
+});
diff --git a/packages/core/src/facade/__tests__/f-event-registry.spec.ts b/packages/core/src/facade/__tests__/f-event-registry.spec.ts
new file mode 100644
index 0000000000..23a106f202
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-event-registry.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, LifecycleStages } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { FEventRegistry } from '../f-event-registry';
+
+describe('FEventRegistry', () => {
+ it('should activate internal event bridges only while facade listeners are subscribed', () => {
+ const registry = new Injector().createInstance(FEventRegistry);
+ const disposeBridge = vi.fn();
+ const initBridge = vi.fn(() => ({ dispose: disposeBridge }));
+ const listenerA = vi.fn((params: { stage: LifecycleStages; cancel?: boolean }) => {
+ params.cancel = true;
+ });
+ const listenerB = vi.fn();
+
+ const bridgeDisposable = registry.registerEventHandler('LifeCycleChanged', initBridge);
+ expect(initBridge).not.toHaveBeenCalled();
+
+ const listenerADisposable = registry.addEvent('LifeCycleChanged', listenerA);
+ expect(initBridge).toHaveBeenCalledTimes(1);
+
+ const canceled = registry.fireEvent('LifeCycleChanged', { stage: LifecycleStages.Ready, cancel: false });
+ expect(canceled).toBe(true);
+ expect(listenerA).toHaveBeenCalledWith({ stage: LifecycleStages.Ready, cancel: true });
+
+ const listenerBDisposable = registry.addEvent('LifeCycleChanged', listenerB);
+ expect(initBridge).toHaveBeenCalledTimes(1);
+
+ listenerADisposable.dispose();
+ expect(disposeBridge).not.toHaveBeenCalled();
+
+ listenerBDisposable.dispose();
+ expect(disposeBridge).toHaveBeenCalledTimes(1);
+
+ registry.addEvent('LifeCycleChanged', listenerA);
+ expect(initBridge).toHaveBeenCalledTimes(2);
+
+ bridgeDisposable.dispose();
+ expect(disposeBridge).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/core/src/facade/__tests__/f-event.spec.ts b/packages/core/src/facade/__tests__/f-event.spec.ts
new file mode 100644
index 0000000000..69cc2df8a4
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-event.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { FEventName } from '../f-event';
+
+describe('FEventName', () => {
+ it('should expose the event names used by document, command and undo-redo facade flows', () => {
+ FEventName._instance = null;
+
+ const eventName = FEventName.get();
+
+ expect(eventName).toBe(FEventName.get());
+ expect(eventName.DocCreated).toBe('DocCreated');
+ expect(eventName.DocDisposed).toBe('DocDisposed');
+ expect(eventName.LifeCycleChanged).toBe('LifeCycleChanged');
+ expect(eventName.Redo).toBe('Redo');
+ expect(eventName.Undo).toBe('Undo');
+ expect(eventName.BeforeRedo).toBe('BeforeRedo');
+ expect(eventName.BeforeUndo).toBe('BeforeUndo');
+ expect(eventName.CommandExecuted).toBe('CommandExecuted');
+ expect(eventName.BeforeCommandExecute).toBe('BeforeCommandExecute');
+ });
+
+ it('should let plugins extend event facade instances and static metadata', () => {
+ class EventSource {
+ static label = 'event-source';
+
+ extraEvent(this: { marker: string }) {
+ return `${this.marker}:event`;
+ }
+ }
+
+ class ExtendedEventName extends FEventName {
+ marker = 'extended';
+ }
+
+ ExtendedEventName.extend(EventSource);
+
+ const extendedEvent = new ExtendedEventName() as ExtendedEventName & { extraEvent(): string };
+
+ expect(extendedEvent.extraEvent()).toBe('extended:event');
+ expect((ExtendedEventName as typeof ExtendedEventName & { label: string }).label).toBe('event-source');
+ });
+});
diff --git a/packages/core/src/facade/__tests__/f-hooks.spec.ts b/packages/core/src/facade/__tests__/f-hooks.spec.ts
index 911413e651..f08701c5c1 100644
--- a/packages/core/src/facade/__tests__/f-hooks.spec.ts
+++ b/packages/core/src/facade/__tests__/f-hooks.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICommand, IUniverInstanceService } from '../../index';
+import type { ICommand } from '../../index';
import { BehaviorSubject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { Injector } from '../../common/di';
@@ -29,6 +29,7 @@ import {
IContextService,
ILogService,
IUndoRedoService,
+ IUniverInstanceService,
LifecycleService,
LifecycleStages,
LocalUndoRedoService,
@@ -47,35 +48,38 @@ class FocusedUnit {
}
}
+class TestUniverInstanceService {
+ static focused$ = new BehaviorSubject<FocusedUnit | null>(new FocusedUnit('unit-1'));
+
+ readonly focused$ = TestUniverInstanceService.focused$.asObservable();
+
+ getFocusedUnit() {
+ return TestUniverInstanceService.focused$.value;
+ }
+}
+
describe('FHooks', () => {
let injector: Injector;
let commandService: ICommandService;
let lifecycleService: LifecycleService;
let undoRedoService: LocalUndoRedoService;
- let focused$: BehaviorSubject<FocusedUnit | null>;
let hooks: FHooks;
let mutationLog: string[];
beforeEach(() => {
+ TestUniverInstanceService.focused$ = new BehaviorSubject<FocusedUnit | null>(new FocusedUnit('unit-1'));
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([LifecycleService]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);
commandService = injector.get(ICommandService);
lifecycleService = injector.get(LifecycleService);
- const contextService = injector.get(IContextService);
-
- focused$ = new BehaviorSubject<FocusedUnit | null>(new FocusedUnit('unit-1'));
- const instanceService = {
- focused$: focused$.asObservable(),
- getFocusedUnit: () => focused$.value,
- } as IUniverInstanceService;
-
- undoRedoService = new LocalUndoRedoService(instanceService, commandService, contextService);
- injector.add([IUndoRedoService, { useValue: undoRedoService }]);
+ undoRedoService = injector.get(IUndoRedoService) as LocalUndoRedoService;
hooks = injector.createInstance(FHooks);
mutationLog = [];
@@ -91,7 +95,7 @@ describe('FHooks', () => {
afterEach(() => {
undoRedoService.dispose();
- focused$.complete();
+ TestUniverInstanceService.focused$.complete();
injector.dispose();
});
diff --git a/packages/core/src/facade/__tests__/f-univer.integration.spec.ts b/packages/core/src/facade/__tests__/f-univer.spec.ts
similarity index 66%
rename from packages/core/src/facade/__tests__/f-univer.integration.spec.ts
rename to packages/core/src/facade/__tests__/f-univer.spec.ts
index 4af9f1e0d8..708ed0f254 100644
--- a/packages/core/src/facade/__tests__/f-univer.integration.spec.ts
+++ b/packages/core/src/facade/__tests__/f-univer.spec.ts
@@ -14,8 +14,19 @@
* limitations under the License.
*/
-import type { ICommand, IDisposable, IDocumentData } from '@univerjs/core';
-import { CommandType, HorizontalAlign, ICommandService, IUndoRedoService, IUniverInstanceService, LocaleService, ThemeService, Univer, UniverInstanceType } from '@univerjs/core';
+import type { ICommand, IDisposable, IDocumentData, Injector } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CommandType,
+ HorizontalAlign,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LocaleService,
+ ThemeService,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { FUniver } from '../f-univer';
@@ -77,7 +88,7 @@ describe('FUniver integration', () => {
commandService.registerCommand({
id: TEST_COMMAND_ID,
type: CommandType.COMMAND,
- handler: (_accessor, params?: { value: string }) => params?.value === 'ok',
+ handler: (_accessor, params?: { value: string }) => params ? params.value === 'ok' : false,
} as ICommand<{ value: string }, boolean>);
disposables.push(
@@ -128,7 +139,11 @@ describe('FUniver integration', () => {
expect(textStyle.ff).toBe('Inter');
expect(paragraph.horizontalAlign).toBe(HorizontalAlign.CENTER);
expect(univerAPI.newTextDecoration({ s: univerAPI.Enum.BooleanNumber.TRUE }).build().s).toBe(univerAPI.Enum.BooleanNumber.TRUE);
- expect(univerAPI.newRichTextValue(createDocData('facade-rich-text') as IDocumentData).getData().body?.dataStream).toBe('Hello\r\n');
+ const richTextBody = univerAPI.newRichTextValue(createDocData('facade-rich-text') as IDocumentData).getData().body;
+ if (!richTextBody) {
+ throw new Error('Expected rich text value to keep the document body.');
+ }
+ expect(richTextBody.dataStream).toBe('Hello\r\n');
expect(univerAPI.Util.rectangle.intersects(
{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }
@@ -165,7 +180,7 @@ describe('FUniver integration', () => {
id: TEST_MUTATION_ID,
type: CommandType.MUTATION,
handler: (_accessor, params?: { label: string }) => {
- executed.push(params?.label ?? 'mutation');
+ executed.push(params ? params.label : 'mutation');
return true;
},
} as ICommand<{ label: string }, boolean>);
@@ -215,4 +230,69 @@ describe('FUniver integration', () => {
undoEvent.dispose();
redoEvent.dispose();
});
+
+ it('should expose extension hooks, locale getters, command hooks, and builder factories', async () => {
+ const injector = univer.__getInjector();
+ const commandService = injector.get(ICommandService);
+ const observed: string[] = [];
+
+ class FacadeExtension {
+ static staticValue = 'extended';
+
+ _initialize(_injector: Injector) {
+ observed.push('initialized');
+ }
+
+ extendedMethod() {
+ return 'method-result';
+ }
+ }
+
+ FUniver.extend(FacadeExtension);
+ const extendedAPI = FUniver.newAPI(injector) as FUniver & { extendedMethod: () => string };
+
+ expect((FUniver as unknown as { staticValue: string }).staticValue).toBe('extended');
+ expect(extendedAPI.extendedMethod()).toBe('method-result');
+ expect(observed).toContain('initialized');
+
+ commandService.registerCommand({
+ id: 'facade.hook.command',
+ type: CommandType.COMMAND,
+ handler: (_accessor, params?: { value: string }) => params ? params.value === 'ok' : false,
+ } as ICommand<{ value: string }, boolean>);
+
+ const hookEvents: string[] = [];
+ const beforeDisposable = extendedAPI.onBeforeCommandExecute((command, options) => hookEvents.push(`before:${command.id}:${options ? options.fromCollab : undefined}`));
+ const afterDisposable = extendedAPI.onCommandExecuted((command, options) => hookEvents.push(`after:${command.id}:${options ? options.fromCollab : undefined}`));
+
+ await expect(extendedAPI.executeCommand('facade.hook.command', { value: 'ok' }, { fromCollab: true })).resolves.toBe(true);
+ expect(extendedAPI.syncExecuteCommand('facade.hook.command', { value: 'ok' }, { fromCollab: false })).toBe(true);
+ expect(hookEvents).toEqual([
+ 'before:facade.hook.command:true',
+ 'after:facade.hook.command:true',
+ 'before:facade.hook.command:false',
+ 'after:facade.hook.command:false',
+ ]);
+
+ extendedAPI.loadLocales('frFR', { facade: { hello: 'Bonjour {0}' } } as never);
+ extendedAPI.setLocale('frFR');
+ expect(extendedAPI.getCurrentLocale()).toBe('frFR');
+ const locales = extendedAPI.getLocales();
+ if (!locales) {
+ throw new Error('Expected loaded facade locales to be available.');
+ }
+ expect((locales.facade as { hello: string }).hello).toBe('Bonjour {0}');
+
+ expect(() => extendedAPI.addEvent('' as never, () => {})).toThrow('Cannot add empty event');
+ expect(extendedAPI.fireEvent(extendedAPI.Event.CommandExecuted, { id: 'manual', type: CommandType.COMMAND, params: undefined })).toBeUndefined();
+
+ const documentData = createDocData('facade-builder') as IDocumentData;
+ expect(extendedAPI.newRichText(documentData).getData().id).toBe('facade-builder');
+ expect(extendedAPI.newParagraphStyleValue({ horizontalAlign: HorizontalAlign.RIGHT }).horizontalAlign).toBe(HorizontalAlign.RIGHT);
+ expect(extendedAPI.newTextStyleValue({ ff: 'Inter', fs: 14, bl: BooleanNumber.TRUE }).fontFamily).toBe('Inter');
+ expect(extendedAPI.newTextStyleValue({ ff: 'Inter', fs: 14, bl: BooleanNumber.TRUE }).bold).toBe(true);
+
+ beforeDisposable.dispose();
+ afterDisposable.dispose();
+ });
});
diff --git a/packages/core/src/facade/__tests__/f-usermanager.spec.ts b/packages/core/src/facade/__tests__/f-usermanager.spec.ts
new file mode 100644
index 0000000000..afd4886f0a
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-usermanager.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 { Univer, UserManagerService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { FUserManager } from '../f-usermanager';
+
+describe('FUserManager', () => {
+ let univer: Univer;
+
+ beforeEach(() => {
+ univer = new Univer();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should return the current collaborator from the shared user manager service', () => {
+ const injector = univer.__getInjector();
+ const userManagerService = injector.get(UserManagerService);
+ const userManagerFacade = injector.createInstance(FUserManager);
+ const observedUsers: string[] = [];
+ const subscription = userManagerService.currentUser$.subscribe((user) => {
+ observedUsers.push(user.userID);
+ });
+
+ userManagerService.setCurrentUser({ userID: 'u-1', name: 'Ada', avatar: 'ada.png' });
+ expect(userManagerFacade.getCurrentUser()).toEqual({ userID: 'u-1', name: 'Ada', avatar: 'ada.png' });
+
+ userManagerService.setCurrentUser({ userID: 'u-2', name: 'Grace' });
+ expect(userManagerFacade.getCurrentUser()).toEqual({ userID: 'u-2', name: 'Grace' });
+ expect(observedUsers).toEqual(expect.arrayContaining(['u-1', 'u-2']));
+
+ subscription.unsubscribe();
+ });
+});
diff --git a/packages/core/src/services/command/__tests__/command.service.spec.ts b/packages/core/src/services/command/__tests__/command.service.spec.ts
index b0a282c825..99989d703f 100644
--- a/packages/core/src/services/command/__tests__/command.service.spec.ts
+++ b/packages/core/src/services/command/__tests__/command.service.spec.ts
@@ -17,6 +17,7 @@
import type { IMultiCommand } from '../command.service';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Injector } from '../../../common/di';
+import { CustomCommandExecutionError } from '../../../common/error';
import { ConfigService, IConfigService } from '../../config/config.service';
import { ContextService, IContextService } from '../../context/context.service';
import { DesktopLogService, ILogService } from '../../log/log.service';
@@ -135,6 +136,14 @@ describe('Test CommandService', () => {
});
describe('Test registering command', () => {
+ it('Should report command registration state and execute the built-in nil command', () => {
+ expect(commandService.hasCommand('nil')).toBe(true);
+ expect(commandService.syncExecuteCommand('nil')).toBe(true);
+
+ commandService.unregisterCommand('nil');
+ expect(commandService.hasCommand('nil')).toBe(false);
+ });
+
it('Should throw error when registering a command with the same id', () => {
expect(() => {
commandService.registerCommand({
@@ -256,6 +265,89 @@ describe('Test CommandService', () => {
`command "${pushValCommandID}" skipped because CommandService is disposed.`
);
});
+
+ it('Should notify collaboration listeners for mutations and skip regular listeners for sync-only mutations', async () => {
+ const mutationID = 'mutation-for-collab-listener';
+ const regular = vi.fn();
+ const collab = vi.fn();
+ const regularDisposable = commandService.onCommandExecuted(regular);
+ const collabDisposable = commandService.onMutationExecutedForCollab(collab);
+
+ expect(() => commandService.onMutationExecutedForCollab(collab)).toThrow(
+ '[CommandService]: could not add a collab mutation listener twice.'
+ );
+
+ commandService.registerCommand({
+ id: mutationID,
+ type: CommandType.MUTATION,
+ handler: () => true,
+ });
+
+ await expect(commandService.executeCommand(mutationID, {}, { onlyLocal: true })).resolves.toBe(true);
+ expect(regular).toHaveBeenCalledTimes(1);
+ expect(collab).toHaveBeenCalledTimes(1);
+ expect(collab).toHaveBeenLastCalledWith(
+ { id: mutationID, type: CommandType.MUTATION, params: {} },
+ { onlyLocal: true }
+ );
+
+ regular.mockClear();
+ collab.mockClear();
+ await expect(commandService.executeCommand(mutationID, {}, { syncOnly: true })).resolves.toBe(true);
+ expect(regular).not.toHaveBeenCalled();
+ expect(collab).toHaveBeenCalledTimes(1);
+
+ regular.mockClear();
+ collab.mockClear();
+ expect(commandService.syncExecuteCommand(mutationID, {}, { syncOnly: true })).toBe(true);
+ expect(regular).not.toHaveBeenCalled();
+ expect(collab).toHaveBeenCalledTimes(1);
+
+ regularDisposable.dispose();
+ collabDisposable.dispose();
+ regular.mockClear();
+ collab.mockClear();
+ commandService.syncExecuteCommand(mutationID);
+ expect(regular).not.toHaveBeenCalled();
+ expect(collab).not.toHaveBeenCalled();
+ });
+
+ it('Should attach the triggering command id to nested synchronous mutations', () => {
+ const mutationID = 'nested-trigger-mutation';
+ const commandID = 'nested-trigger-command';
+ const params: { trigger?: string } = {};
+
+ commandService.registerCommand({
+ id: mutationID,
+ type: CommandType.MUTATION,
+ handler: (_accessor, mutationParams: { trigger?: string }) => {
+ expect(mutationParams.trigger).toBe(commandID);
+ return true;
+ },
+ });
+ commandService.registerCommand({
+ id: commandID,
+ type: CommandType.COMMAND,
+ handler: (accessor) => accessor.get(ICommandService).syncExecuteCommand(mutationID, params),
+ });
+
+ expect(commandService.syncExecuteCommand(commandID)).toBe(true);
+ expect(params.trigger).toBe(commandID);
+ });
+
+ it('Should convert custom command execution errors into a false result', async () => {
+ const customErrorCommandID = 'custom-error-command';
+ commandService.registerCommand({
+ id: customErrorCommandID,
+ type: CommandType.COMMAND,
+ handler: () => {
+ throw new CustomCommandExecutionError('canceled by test');
+ },
+ });
+
+ await expect(commandService.executeCommand(customErrorCommandID)).resolves.toBe(false);
+ expect(commandService.syncExecuteCommand(customErrorCommandID)).toBe(false);
+ });
});
describe('Test MultiCommand', () => {
@@ -307,5 +399,53 @@ describe('Test CommandService', () => {
`[CommandService]: command "${commandID}" is not registered.`
);
});
+
+ it('Should reject mixing single commands with multi command implementations', () => {
+ commandService.registerCommand({
+ id: anotherCommandID,
+ type: CommandType.COMMAND,
+ handler: () => true,
+ });
+
+ expect(() => commandService.registerMultipleCommand({
+ id: anotherCommandID,
+ type: CommandType.COMMAND,
+ name: 'multi',
+ multi: true,
+ priority: 1,
+ handler: () => true,
+ } as IMultiCommand)).toThrow('Command has registered as a single command.');
+ });
+
+ it('Should continue to lower priority implementations when a multi command returns false', async () => {
+ const commandID = 'fallback-multi-command';
+ const calls: string[] = [];
+
+ commandService.registerMultipleCommand({
+ id: commandID,
+ type: CommandType.COMMAND,
+ name: 'first',
+ multi: true,
+ priority: 10,
+ handler: () => {
+ calls.push('first');
+ return false;
+ },
+ } as IMultiCommand);
+ commandService.registerMultipleCommand({
+ id: commandID,
+ type: CommandType.COMMAND,
+ name: 'second',
+ multi: true,
+ priority: 1,
+ handler: () => {
+ calls.push('second');
+ return true;
+ },
+ } as IMultiCommand);
+
+ await expect(commandService.executeCommand(commandID)).resolves.toBe(true);
+ expect(calls).toEqual(['first', 'second']);
+ });
});
});
diff --git a/packages/core/src/services/lifecycle/__tests__/lifecycle.service.spec.ts b/packages/core/src/services/lifecycle/__tests__/lifecycle.service.spec.ts
index e35ae69e0d..2bf6e3ea6d 100644
--- a/packages/core/src/services/lifecycle/__tests__/lifecycle.service.spec.ts
+++ b/packages/core/src/services/lifecycle/__tests__/lifecycle.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { Injector } from '../../../common/di';
import { DesktopLogService, ILogService } from '../../log/log.service';
import { LifecycleStages } from '../lifecycle';
@@ -128,4 +128,51 @@ describe('Test LifecycleService', () => {
'[LifecycleService]: lifecycle stage "Rendered" will never be reached!'
);
});
+
+ it('Should resolve "onStage" when the requested lifecycle stage is reached', async () => {
+ injector = createLifecycleTestBed().injector;
+ lifecycleService = injector.get(LifecycleService);
+
+ const rendered = lifecycleService.onStage(LifecycleStages.Rendered);
+ lifecycleService.stage = LifecycleStages.Ready;
+ lifecycleService.stage = LifecycleStages.Rendered;
+
+ await expect(rendered).resolves.toBeUndefined();
+ await expect(lifecycleService.onStage(LifecycleStages.Ready)).resolves.toBeUndefined();
+ });
+
+ it('Should complete previous-stage subscriptions at steady and guard reentrant stage changes', () => {
+ injector = createLifecycleTestBed().injector;
+ lifecycleService = injector.get(LifecycleService);
+ const completed = vi.fn();
+ const stages: LifecycleStages[] = [];
+ let reentrantError: Error | undefined;
+
+ lifecycleService.lifecycle$.subscribe((stage) => {
+ if (stage === LifecycleStages.Ready) {
+ try {
+ lifecycleService.stage = LifecycleStages.Rendered;
+ } catch (error) {
+ reentrantError = error as Error;
+ }
+ }
+ });
+ lifecycleService.subscribeWithPrevious().subscribe({
+ next: (stage) => stages.push(stage),
+ complete: completed,
+ });
+
+ lifecycleService.stage = LifecycleStages.Ready;
+ lifecycleService.stage = LifecycleStages.Rendered;
+ lifecycleService.stage = LifecycleStages.Steady;
+
+ expect(reentrantError?.message).toBe('[LifecycleService]: cannot set new stage when related logic is all handled!');
+ expect(stages).toEqual([
+ LifecycleStages.Starting,
+ LifecycleStages.Ready,
+ LifecycleStages.Rendered,
+ LifecycleStages.Steady,
+ ]);
+ expect(completed).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/data-validation/src/commands/commands/__tests__/data-validation.command.spec.ts b/packages/data-validation/src/commands/commands/__tests__/data-validation.command.spec.ts
new file mode 100644
index 0000000000..3bf71c3000
--- /dev/null
+++ b/packages/data-validation/src/commands/commands/__tests__/data-validation.command.spec.ts
@@ -0,0 +1,232 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 {
+ DataValidatorRegistryScope,
+ DataValidatorRegistryService,
+} from '../../../services/data-validator-registry.service';
+import {
+ AddDataValidationMutation,
+ RemoveDataValidationMutation,
+ UpdateDataValidationMutation,
+} from '../../mutations/data-validation.mutation';
+import {
+ AddDataValidationCommand,
+ RemoveAllDataValidationCommand,
+ RemoveDataValidationCommand,
+ removeDataValidationUndoFactory,
+ UpdateDataValidationOptionsCommand,
+ UpdateDataValidationSettingCommand,
+} from '../data-validation.command';
+
+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('deprecated data validation commands', () => {
+ let univer: Univer;
+ let commandService: ICommandService;
+ let dataValidationModel: DataValidationModel;
+
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([DataValidationModel]);
+ injector.add([DataValidatorRegistryService]);
+
+ commandService = injector.get(ICommandService);
+ [
+ AddDataValidationMutation,
+ RemoveDataValidationMutation,
+ UpdateDataValidationMutation,
+ AddDataValidationCommand,
+ RemoveDataValidationCommand,
+ RemoveAllDataValidationCommand,
+ UpdateDataValidationOptionsCommand,
+ UpdateDataValidationSettingCommand,
+ ].forEach((command) => commandService.registerCommand(command));
+
+ injector.get(DataValidatorRegistryService).register({
+ id: DataValidationType.TEXT_LENGTH,
+ title: 'Text length',
+ operators: [DataValidationOperator.GREATER_THAN],
+ scopes: DataValidatorRegistryScope.SHEET,
+ order: 0,
+ validatorFormula: () => ({ success: true }),
+ normalizeFormula: (rule: ISheetDataValidationRule) => ({
+ formula1: rule.formula1,
+ formula2: rule.formula2,
+ }),
+ } as never);
+
+ dataValidationModel = injector.get(DataValidationModel);
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('adds a rule through the command and stores undo that removes it', async () => {
+ const result = await commandService.executeCommand(AddDataValidationCommand.id, {
+ unitId,
+ subUnitId,
+ rule: {
+ ...createRule('rule-1'),
+ range: { startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 },
+ },
+ index: 0,
+ });
+
+ expect(result).toBe(true);
+ expect(dataValidationModel.getRuleById(unitId, subUnitId, 'rule-1')?.ranges).toEqual([
+ { startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 },
+ ]);
+ });
+
+ it('updates rule options and criteria with reversible mutations', async () => {
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId,
+ subUnitId,
+ rule: createRule('rule-1'),
+ });
+
+ expect(await commandService.executeCommand(UpdateDataValidationOptionsCommand.id, {
+ unitId,
+ subUnitId,
+ ruleId: 'rule-1',
+ options: {
+ allowBlank: false,
+ showErrorMessage: false,
+ prompt: 'Use more text',
+ },
+ })).toBe(true);
+
+ expect(await commandService.executeCommand(UpdateDataValidationSettingCommand.id, {
+ unitId,
+ subUnitId,
+ ruleId: 'rule-1',
+ setting: {
+ type: DataValidationType.TEXT_LENGTH,
+ operator: DataValidationOperator.GREATER_THAN,
+ formula1: '3',
+ formula2: undefined,
+ allowBlank: true,
+ },
+ })).toBe(true);
+
+ expect(dataValidationModel.getRuleById(unitId, subUnitId, 'rule-1')).toMatchObject({
+ type: DataValidationType.TEXT_LENGTH,
+ operator: DataValidationOperator.GREATER_THAN,
+ formula1: '3',
+ formula2: undefined,
+ allowBlank: true,
+ showErrorMessage: false,
+ prompt: 'Use more text',
+ });
+ });
+
+ it('removes one rule or all rules and records add mutations for undo', async () => {
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId,
+ subUnitId,
+ rule: [createRule('rule-1'), createRule('rule-2')],
+ });
+
+ expect(await commandService.executeCommand(RemoveDataValidationCommand.id, {
+ unitId,
+ subUnitId,
+ ruleId: 'rule-1',
+ })).toBe(true);
+ expect(dataValidationModel.getRules(unitId, subUnitId).map((rule) => rule.uid)).toEqual(['rule-2']);
+
+ expect(await commandService.executeCommand(RemoveAllDataValidationCommand.id, { unitId, subUnitId })).toBe(true);
+ expect(dataValidationModel.getRules(unitId, subUnitId)).toEqual([]);
+ });
+
+ it('rebuilds batch remove undo mutations from the rules that existed before deletion', async () => {
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId,
+ subUnitId,
+ rule: [
+ createRule('rule-1', { formula1: '1' }),
+ createRule('rule-2', { formula1: '5' }),
+ ],
+ });
+
+ const [undo] = removeDataValidationUndoFactory(univer.__getInjector(), {
+ unitId,
+ subUnitId,
+ ruleId: ['rule-1', 'rule-2', 'missing-rule'],
+ source: 'command',
+ });
+
+ expect(undo).toMatchObject({
+ id: AddDataValidationMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ source: 'command',
+ rule: [
+ { uid: 'rule-1', formula1: '1' },
+ { uid: 'rule-2', formula1: '5' },
+ ],
+ },
+ });
+ });
+
+ it('does not mutate rules when parameters or target rules are missing', async () => {
+ expect(await commandService.executeCommand(AddDataValidationCommand.id)).toBe(false);
+ expect(await commandService.executeCommand(RemoveDataValidationCommand.id)).toBe(false);
+ expect(await commandService.executeCommand(RemoveAllDataValidationCommand.id)).toBe(false);
+ expect(await commandService.executeCommand(UpdateDataValidationOptionsCommand.id)).toBe(false);
+ expect(await commandService.executeCommand(UpdateDataValidationSettingCommand.id)).toBe(false);
+
+ expect(await commandService.executeCommand(UpdateDataValidationOptionsCommand.id, {
+ unitId,
+ subUnitId,
+ ruleId: 'missing',
+ options: { prompt: 'Ignored' },
+ })).toBe(false);
+ expect(await commandService.executeCommand(UpdateDataValidationSettingCommand.id, {
+ unitId,
+ subUnitId,
+ ruleId: 'missing',
+ setting: {
+ type: DataValidationType.TEXT_LENGTH,
+ operator: DataValidationOperator.GREATER_THAN,
+ formula1: '3',
+ },
+ })).toBe(false);
+ expect(dataValidationModel.getRules(unitId, subUnitId)).toEqual([]);
+ });
+});
diff --git a/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
new file mode 100644
index 0000000000..f259715590
--- /dev/null
+++ b/packages/docs-drawing-ui/src/views/doc-image-panel/__tests__/DocDrawingPosition.spec.tsx
@@ -0,0 +1,318 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 {
+ 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 { UpdateDrawingDocTransformCommand } from '../../../commands/commands/update-doc-drawing.command';
+import locale from '../../../locale/en-US';
+import { DocDrawingPosition } from '../DocDrawingPosition';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'doc-drawing-position-doc';
+const DRAWING_ID = 'image-1';
+
+class TestDocSkeletonManagerService {
+ private readonly _page = { marginTop: 72 };
+ private readonly _column = {
+ lines: [] as Array<{
+ top: number;
+ paragraphIndex: number;
+ paragraphStart?: boolean;
+ }>,
+ parent: {
+ parent: this._page,
+ },
+ };
+
+ private readonly _paragraphStartLine = {
+ top: 20,
+ paragraphIndex: 1,
+ paragraphStart: true,
+ };
+
+ private readonly _line = {
+ top: 44,
+ paragraphIndex: 1,
+ parent: this._column,
+ };
+
+ private readonly _glyph = {
+ parent: {
+ parent: this._line,
+ },
+ };
+
+ constructor() {
+ this._column.lines.push(this._paragraphStartLine, this._line);
+ }
+
+ getSkeleton() {
+ return {
+ findNodeByCharIndex: () => this._glyph,
+ 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 {
+ getSegment() {
+ return '';
+ }
+
+ getSegmentPage() {
+ return 0;
+ }
+
+ blur() {
+ return undefined;
+ }
+}
+
+class TestScene {
+ getTransformerByCreate() {
+ return {
+ refreshControls: () => undefined,
+ };
+ }
+}
+
+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,
+ docTransform: {
+ positionH: {
+ relativeFrom: ObjectRelativeFromH.PAGE,
+ posOffset: 0,
+ },
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PARAGRAPH,
+ posOffset: 12,
+ },
+ },
+ } as never,
+ },
+ drawingsOrder: [DRAWING_ID],
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function createPositionTestBed() {
+ 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);
+ [
+ UpdateDrawingDocTransformCommand,
+ 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 createPositionTestBed>) {
+ const drawing = testBed.doc.getSnapshot().drawings![DRAWING_ID];
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <DocDrawingPosition drawings={[drawing as never]} />
+ </RediContext.Provider>
+ );
+ });
+}
+
+function currentDrawing(testBed: ReturnType<typeof createPositionTestBed>) {
+ 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;
+}
+
+describe('DocDrawingPosition', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createPositionTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('anchors the focused drawing to the page when move-with-text is turned off', async () => {
+ currentTestBed = createPositionTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderPanel(root, currentTestBed);
+
+ const moveWithText = inputByLabelText('Move object with text');
+ expect(moveWithText.checked).toBe(true);
+
+ await act(async () => {
+ moveWithText.click();
+ await Promise.resolve();
+ });
+
+ expect(moveWithText.checked).toBe(false);
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ docTransform: {
+ positionV: {
+ relativeFrom: ObjectRelativeFromV.PAGE,
+ posOffset: 104,
+ },
+ },
+ });
+ });
+});
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.tsx
index 3372c0566a..2b1622590b 100644
--- 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.tsx
@@ -342,4 +342,22 @@ describe('DocDrawingTextWrap', () => {
distR: 4,
});
});
+
+ it('persists right-only 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('Right only').click();
+ await Promise.resolve();
+ });
+
+ expect(currentDrawing(currentTestBed)).toMatchObject({
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ wrapText: WrapTextType.RIGHT,
+ });
+ });
});
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.tsx
index ea78c66af1..3b99a4f23f 100644
--- a/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
+++ b/packages/docs-hyper-link-ui/src/views/__tests__/DocLinkPopup.spec.tsx
@@ -46,8 +46,12 @@ import { DocLinkPopup } from '../DocLinkPopup';
const UNIT_ID = 'doc-link-popup-doc';
class TestDocCanvasPopManagerService {
+ disposeCount = 0;
+
attachPopupToRange() {
- return toDisposable(() => undefined);
+ return toDisposable(() => {
+ this.disposeCount += 1;
+ });
}
}
@@ -300,4 +304,50 @@ describe('DocLinkPopup', () => {
});
expect(currentTestBed.popupService.editing).toBeNull();
});
+
+ it('adds a document hyperlink from selected text and normalizes a bare URL', async () => {
+ currentTestBed = createPopupTestBed();
+ const selectionManager = currentTestBed.injector.get(DocSelectionManagerService);
+ const popManager = currentTestBed.injector.get(DocCanvasPopManagerService) as unknown as TestDocCanvasPopManagerService;
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: UNIT_ID, subUnitId: UNIT_ID });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 5,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+ currentTestBed.popupService.showEditPopup(UNIT_ID, null);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ renderEditPopup(root, currentTestBed);
+
+ const [linkInput] = Array.from(container.querySelectorAll('input')) as HTMLInputElement[];
+ expect(linkInput.value).toBe('');
+
+ await act(async () => {
+ 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;
+
+ await act(async () => {
+ confirm.click();
+ await Promise.resolve();
+ });
+
+ const body = currentTestBed.doc.getBody();
+ const addedLink = body?.customRanges?.find((range) => range.properties?.url === 'https://docs.univer.ai');
+
+ expect(body?.dataStream).toBe('Hello world\r\n');
+ expect(addedLink?.startIndex).toBe(0);
+ expect(addedLink?.endIndex).toBe(4);
+ expect(currentTestBed.popupService.editing).toBeNull();
+ expect(popManager.disposeCount).toBe(1);
+ });
});
diff --git a/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.ts b/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.ts
index 1620f02264..a66356206b 100644
--- a/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.ts
+++ b/packages/docs-hyper-link/src/controllers/__tests__/resource.controller.spec.ts
@@ -17,12 +17,18 @@
import type { DocumentDataModel, ICustomRange, IDocumentData } from '@univerjs/core';
import {
CustomRangeType,
+ ICommandService,
IResourceManagerService,
LocaleType,
Univer,
UniverInstanceType,
} from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import {
+ AddHyperLinkMuatation,
+ DeleteHyperLinkMuatation,
+ UpdateHyperLinkMuatation,
+} from '../../commands/mutations/hyper-link.mutation';
import { DOC_HYPER_LINK_PLUGIN, DocHyperLinkResourceController } from '../resource.controller';
function createDocData(): IDocumentData {
@@ -106,6 +112,7 @@ function getRange(model: DocumentDataModel, rangeId: string, segment: 'body' | '
describe('DocHyperLinkResourceController', () => {
let univer: Univer;
+ let commandService: ICommandService;
let resourceManagerService: IResourceManagerService;
beforeEach(() => {
@@ -115,6 +122,11 @@ describe('DocHyperLinkResourceController', () => {
injector.add([DocHyperLinkResourceController]);
injector.get(DocHyperLinkResourceController);
+ commandService = injector.get(ICommandService);
+ commandService.registerCommand(AddHyperLinkMuatation);
+ commandService.registerCommand(UpdateHyperLinkMuatation);
+ commandService.registerCommand(DeleteHyperLinkMuatation);
+
resourceManagerService = injector.get(IResourceManagerService);
});
@@ -166,4 +178,10 @@ describe('DocHyperLinkResourceController', () => {
expect(resource).toBeDefined();
expect(resource?.data).toBe(JSON.stringify({ links: [] }));
});
+
+ it('should execute hyperlink resource mutations successfully', async () => {
+ await expect(commandService.executeCommand(AddHyperLinkMuatation.id)).resolves.toBe(true);
+ await expect(commandService.executeCommand(UpdateHyperLinkMuatation.id)).resolves.toBe(true);
+ await expect(commandService.executeCommand(DeleteHyperLinkMuatation.id)).resolves.toBe(true);
+ });
});
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.ts
index ac20f04342..e132a2ebaa 100644
--- 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.ts
@@ -17,7 +17,12 @@
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';
+import {
+ CloseMentionEditPopupOperation,
+ CloseMentionInfoPopupOperation,
+ ShowMentionEditPopupOperation,
+ ShowMentionInfoPopupOperation,
+} from '../mention-popup.operation';
describe('mention edit popup operations', () => {
let univer: Univer;
@@ -32,6 +37,8 @@ describe('mention edit popup operations', () => {
commandService = injector.get(ICommandService);
commandService.registerCommand(ShowMentionEditPopupOperation);
commandService.registerCommand(CloseMentionEditPopupOperation);
+ commandService.registerCommand(ShowMentionInfoPopupOperation);
+ commandService.registerCommand(CloseMentionInfoPopupOperation);
mentionService = injector.get(DocMentionService);
});
@@ -70,4 +77,12 @@ describe('mention edit popup operations', () => {
expect(result).toBe(false);
expect(mentionService.editing).toBeUndefined();
});
+
+ it('keeps info popup operations as event placeholders', async () => {
+ await expect(commandService.executeCommand(ShowMentionInfoPopupOperation.id, {
+ unitId: 'doc-1',
+ mentionId: 'mention-1',
+ })).resolves.toBe(false);
+ await expect(commandService.executeCommand(CloseMentionInfoPopupOperation.id)).resolves.toBe(false);
+ });
});
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.ts
index c222ca2a46..c6dda1ba37 100644
--- 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.ts
@@ -67,4 +67,37 @@ describe('DocMentionPopupService', () => {
sub.unsubscribe();
});
+
+ it('replaces an existing edit popup and closes when the popup reports outside clicks', () => {
+ const { service, mentionService, attached, popupDisposals } = createService();
+
+ mentionService.startEditing({ unitId: 'doc-1', index: 4 });
+ mentionService.startEditing({ unitId: 'doc-1', index: 7 });
+
+ expect(service.editPopup).toMatchObject({ anchor: 7, unitId: 'doc-1' });
+ expect(popupDisposals).toEqual([1]);
+ expect(attached).toMatchObject([
+ { range: { startOffset: 4, endOffset: 4, collapsed: true }, unitId: 'doc-1' },
+ { range: { startOffset: 7, endOffset: 7, collapsed: true }, unitId: 'doc-1' },
+ ]);
+
+ const latestPopup = attached.at(-1) as { popup: { onClickOutside: () => void } };
+ latestPopup.popup.onClickOutside();
+
+ expect(mentionService.editing).toBeUndefined();
+ expect(service.editPopup).toBeNull();
+ expect(popupDisposals).toEqual([1, 2]);
+ });
+
+ it('leaves empty popup states unchanged when there is nothing to close', () => {
+ const { service, popupDisposals } = createService();
+
+ service.closeEditPopup();
+ service.showInfoPopup();
+ service.closeInfoPopup();
+
+ expect(service.editPopup).toBeUndefined();
+ expect(service.infoPopup).toBeUndefined();
+ expect(popupDisposals).toEqual([]);
+ });
});
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.tsx
index a0c97c4960..a23fa76b6f 100644
--- a/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx
+++ b/packages/docs-mention-ui/src/views/__tests__/mention-views.spec.tsx
@@ -252,6 +252,7 @@ function createViewsTestBed() {
selectionManager,
mentionIOService: get(IMentionIOService) as TestMentionIOService,
editorService: get(IEditorService) as unknown as TestEditorService,
+ popupManagerService: get(DocCanvasPopManagerService) as unknown as TestDocCanvasPopManagerService,
popupService: get(DocMentionPopupService),
};
}
@@ -351,4 +352,26 @@ describe('mention views', () => {
expect(testBed.popupService.editPopup).toBeNull();
expect(testBed.editorService.focusedUnitIds).toEqual([unitId, unitId]);
});
+
+ it('dismisses the edit popup from the empty list area without inserting a mention', async () => {
+ const testBed = createViewsTestBed();
+ univer = testBed.univer;
+ testBed.popupService.showEditPopup(unitId, 6);
+ const rendered = renderIntoDocument(<MentionEditPopup />, testBed.injector);
+ disposable = disposeRender(rendered.root, rendered.container);
+
+ const popupRoot = rendered.container.querySelector<HTMLElement>(`[data-editorid="${unitId}"]`);
+ expect(popupRoot).toBeDefined();
+
+ await act(async () => {
+ popupRoot!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(testBed.doc.getBody()?.dataStream).toBe('Hello @al\r\n');
+ expect(testBed.doc.getBody()?.customRanges).toBeUndefined();
+ expect(testBed.popupService.editPopup).toBeNull();
+ expect(testBed.editorService.focusedUnitIds).toEqual([unitId]);
+ expect(testBed.popupManagerService.disposed).toHaveLength(1);
+ });
});
diff --git a/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts b/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts
index ce3a8e96e3..41cd1df130 100644
--- a/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts
+++ b/packages/docs-quick-insert-ui/src/commands/commands/__tests__/doc-quick-insert.command.spec.ts
@@ -19,27 +19,31 @@ import { CutContentCommand } from '@univerjs/docs-ui';
import { describe, expect, it, vi } from 'vitest';
import { DeleteSearchKeyCommand } from '../doc-quick-insert.command';
+class RecordingCommandService {
+ readonly syncExecuteCommand = vi.fn(() => true);
+}
+
function createAccessor(bindings: Array<[unknown, unknown]>) {
const injector = new Injector();
- bindings.forEach(([token, value]) => {
- injector.add([token as never, { useValue: value }]);
+ bindings.forEach(([token, useClass]) => {
+ injector.add([token as never, { useClass: useClass as never }]);
});
- return injector as never;
+ return injector;
}
describe('DeleteSearchKeyCommand', () => {
it('cuts the slash-triggered keyword range from the document', () => {
- const syncExecuteCommand = vi.fn(() => true);
const accessor = createAccessor([
- [ICommandService, { syncExecuteCommand }],
+ [ICommandService, RecordingCommandService],
]);
+ const commandService = accessor.get(ICommandService) as unknown as RecordingCommandService;
const result = DeleteSearchKeyCommand.handler(accessor, { start: 4, end: 9 });
expect(result).toBe(true);
- expect(syncExecuteCommand).toHaveBeenCalledWith(CutContentCommand.id, {
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(CutContentCommand.id, {
segmentId: '',
textRanges: [{
startOffset: 4,
diff --git a/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts b/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts
index 49b6fa763a..0979ecd98e 100644
--- a/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts
+++ b/packages/docs-quick-insert-ui/src/commands/operations/__tests__/quick-insert-popup.operation.spec.ts
@@ -19,22 +19,27 @@ import { describe, expect, it, vi } from 'vitest';
import { DocQuickInsertPopupService } from '../../../services/doc-quick-insert-popup.service';
import { CloseQuickInsertPopupOperation, ShowQuickInsertPopupOperation } from '../quick-insert-popup.operation';
+class RecordingQuickInsertPopupService {
+ readonly showPopup = vi.fn();
+ readonly closePopup = vi.fn();
+}
+
function createAccessor(bindings: Array<[unknown, unknown]>) {
const injector = new Injector();
- bindings.forEach(([token, value]) => {
- injector.add([token as never, { useValue: value }]);
+ bindings.forEach(([token, useClass]) => {
+ injector.add([token as never, { useClass: useClass as never }]);
});
- return injector as never;
+ return injector;
}
describe('quick insert popup operations', () => {
it('shows a popup only when parameters are provided', () => {
- const showPopup = vi.fn();
const accessor = createAccessor([
- [DocQuickInsertPopupService, { showPopup }],
+ [DocQuickInsertPopupService, RecordingQuickInsertPopupService],
]);
+ const popupService = accessor.get(DocQuickInsertPopupService) as unknown as RecordingQuickInsertPopupService;
const params = {
unitId: 'doc-1',
index: 3,
@@ -46,16 +51,16 @@ describe('quick insert popup operations', () => {
expect(ShowQuickInsertPopupOperation.handler(accessor, undefined)).toBe(false);
expect(ShowQuickInsertPopupOperation.handler(accessor, params)).toBe(true);
- expect(showPopup).toHaveBeenCalledWith(params);
+ expect(popupService.showPopup).toHaveBeenCalledWith(params);
});
it('closes the active popup session', () => {
- const closePopup = vi.fn();
const accessor = createAccessor([
- [DocQuickInsertPopupService, { closePopup }],
+ [DocQuickInsertPopupService, RecordingQuickInsertPopupService],
]);
+ const popupService = accessor.get(DocQuickInsertPopupService) as unknown as RecordingQuickInsertPopupService;
expect(CloseQuickInsertPopupOperation.handler(accessor)).toBe(true);
- expect(closePopup).toHaveBeenCalledTimes(1);
+ expect(popupService.closePopup).toHaveBeenCalledTimes(1);
});
});
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.tsx
index 43e16c98a0..845589bb7e 100644
--- a/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
+++ b/packages/docs-quick-insert-ui/src/views/__tests__/QuickInsertPopup.spec.tsx
@@ -34,7 +34,16 @@ import {
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 {
+ 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';
@@ -42,6 +51,7 @@ 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 { QuickInsertPlaceholder } from '../QuickInsertPlaceholder';
import { QuickInsertPopup } from '../QuickInsertPopup';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -164,6 +174,9 @@ function createQuickInsertPopupTestBed(options?: {
},
});
+ const componentManager = injector.get(ComponentManager);
+ componentManager.register(QuickInsertPlaceholder.componentKey, QuickInsertPlaceholder);
+
const commandService = injector.get(ICommandService);
commandService.registerCommand(CloseQuickInsertPopupOperation);
commandService.registerCommand(DeleteSearchKeyCommand);
@@ -385,4 +398,37 @@ describe('QuickInsertPopup', () => {
expect(documentArrowDownShortcut.preconditions()).toBe(true);
});
+
+ it('keeps the typed trigger intact when enter is pressed with no matching menu', async () => {
+ const { getCutContentParams, getSelectedMenu, injector, popupService } = createQuickInsertPopupTestBed({
+ dataStream: '/unknown\r\n',
+ inputOffset: { start: 0, end: 8 },
+ });
+ 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();
+ });
+
+ expect(container.textContent).toContain('No result');
+ expect(container.textContent).not.toContain('Table');
+
+ const enterShortcut = shortcutService.getAllShortcuts().find((shortcut) => shortcut.binding === KeyCode.ENTER);
+ expect(enterShortcut).toBeDefined();
+
+ await act(async () => {
+ await commandService.executeCommand(enterShortcut!.id);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+ expect(getSelectedMenu()).toBeUndefined();
+ expect(getCutContentParams()).toBeUndefined();
+ expect(popupService.editPopup).not.toBeNull();
+ });
});
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.ts
index a9fa0648eb..2c440ac159 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
@@ -51,7 +51,7 @@ import {
SetTextSelectionsOperation,
UpdateTextCommand,
} from '@univerjs/docs';
-import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
+import { DocumentEditArea, GlyphType, IRenderManagerService } from '@univerjs/engine-render';
import { ISidebarService } from '@univerjs/ui';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
@@ -356,6 +356,30 @@ function createMultiParagraphDoc(): IDocumentData {
};
}
+function createListParagraphDoc(): IDocumentData {
+ const doc = createMultiParagraphDoc();
+ return {
+ ...doc,
+ body: {
+ ...doc.body!,
+ paragraphs: [
+ doc.body!.paragraphs![0],
+ {
+ ...doc.body!.paragraphs![1],
+ bullet: {
+ listId: 'list-1',
+ listType: 'BULLET_LIST',
+ nestingLevel: 0,
+ },
+ paragraphStyle: {
+ hanging: { v: 18 },
+ },
+ },
+ ],
+ },
+ };
+}
+
function createHorizontalLineDoc(): IDocumentData {
const doc = createMultiParagraphDoc();
const body = doc.body!;
@@ -1022,6 +1046,48 @@ describe('misc document commands', () => {
expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toBeUndefined();
});
+ it('turns a list paragraph into an indented paragraph when Backspace is pressed at its first glyph', async () => {
+ ({ univer, get } = createCommandTestBed(createListParagraphDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DeleteLeftCommand);
+ commandService.registerCommand(UpdateTextCommand);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(6);
+
+ const skeletonManager = get(DocSkeletonManagerService) as unknown as { getSkeleton: () => unknown };
+ skeletonManager.getSkeleton = () => {
+ const listGlyph = { glyphType: GlyphType.LIST };
+ const textGlyph = { content: 'B', count: 1, streamType: 'B' };
+ const divide = {
+ glyphGroup: [listGlyph, textGlyph],
+ parent: undefined as unknown,
+ };
+ const line = {
+ divides: [divide],
+ paragraphIndex: 10,
+ };
+ divide.parent = line;
+ (textGlyph as { parent?: unknown }).parent = divide;
+
+ return {
+ findNodeByCharIndex(index: number) {
+ if (index === 6) {
+ return textGlyph;
+ }
+
+ return useLinearSkeleton('Title\rBody\r\n').findNodeByCharIndex(index);
+ },
+ };
+ };
+
+ expect(await commandService.executeCommand(DeleteLeftCommand.id)).toBe(true);
+ await awaitTime(0);
+
+ const paragraphStyle = getBody()?.paragraphs?.[1].paragraphStyle;
+ expect(paragraphStyle?.hanging).toBeUndefined();
+ expect(paragraphStyle?.indentStart).toEqual({ v: 18 });
+ });
+
it('removes the character after the cursor when Delete is pressed inside text', async () => {
({ univer, get } = createCommandTestBed(createBaseDoc('ABC\r\n')));
commandService = get(ICommandService);
@@ -1057,6 +1123,23 @@ describe('misc document commands', () => {
expect(getBody()?.paragraphs).toHaveLength(1);
});
+ it('cuts the selected content when Delete is pressed on a non-collapsed text range', async () => {
+ ({ univer, get } = createCommandTestBed(createBaseDoc('ABCD\r\n')));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DeleteRightCommand);
+ 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(DeleteRightCommand.id)).toBe(true);
+ await awaitTime(0);
+
+ expect(getBody()?.dataStream).toBe('AD\r\n');
+ });
+
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);
@@ -1106,6 +1189,38 @@ describe('misc document commands', () => {
expect(getDoc()?.getSnapshot().drawings?.['drawing-1']).toBeUndefined();
});
+ it('removes an inline drawing when Delete is pressed before its object marker', async () => {
+ ({ univer, get } = createCommandTestBed(createInlineDrawingDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DeleteRightCommand);
+ commandService.registerCommand(DeleteCustomBlockCommand);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(1);
+
+ 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(DeleteRightCommand.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);
diff --git a/packages/docs-ui/src/views/__tests__/PageSettings.spec.tsx b/packages/docs-ui/src/views/__tests__/PageSettings.spec.tsx
new file mode 100644
index 0000000000..7a855e6b0b
--- /dev/null
+++ b/packages/docs-ui/src/views/__tests__/PageSettings.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 { IConfirmChildrenProps } from '@univerjs/ui';
+import type { Root } from 'react-dom/client';
+import {
+ ContextService,
+ DocumentDataModel,
+ DocumentFlavor,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ ModernDocumentWidthMode,
+ PageOrientType,
+ UniverInstanceService,
+} 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 { PageSettings } from '../PageSettings';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestLogService {
+ debug(): void {}
+}
+
+function createPageSettingsTestBed() {
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: TestLogService as never }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([LocaleService, { useClass: LocaleService }]);
+
+ injector.get(LocaleService).load({
+ [LocaleType.ZH_CN]: {
+ 'docs-ui': {
+ 'page-settings': {
+ 'modern-mode': 'Modern',
+ 'classic-mode': 'Classic',
+ 'modern-width': 'Modern width',
+ 'modern-width-narrow': 'Narrow',
+ 'modern-width-medium': 'Medium',
+ 'modern-width-wide': 'Wide',
+ 'paper-size': 'Paper size',
+ 'custom-paper-size': 'Custom paper size',
+ top: 'Top',
+ bottom: 'Bottom',
+ left: 'Left',
+ right: 'Right',
+ 'page-size': {
+ a4: 'A4',
+ letter: 'Letter',
+ legal: 'Legal',
+ },
+ },
+ },
+ },
+ });
+
+ const doc = new DocumentDataModel({
+ id: 'page-settings-doc',
+ documentStyle: {
+ documentFlavor: DocumentFlavor.MODERN,
+ pageSize: { width: 720, height: 960 },
+ pageOrient: PageOrientType.PORTRAIT,
+ marginTop: 24,
+ marginBottom: 28,
+ marginLeft: 32,
+ marginRight: 36,
+ },
+ body: {
+ dataStream: '\r\n',
+ paragraphs: [],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ },
+ });
+ (injector.get(IUniverInstanceService) as UniverInstanceService).__addUnit(doc);
+
+ return { injector };
+}
+
+function renderPageSettings(hooks: IConfirmChildrenProps['hooks']) {
+ const { injector } = createPageSettingsTestBed();
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <PageSettings hooks={hooks} />
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, root };
+}
+
+function clickButton(container: HTMLElement, text: string) {
+ const button = Array.from(container.querySelectorAll('button')).find((button) => button.textContent?.includes(text));
+ if (!button) {
+ throw new Error(`Missing button: ${text}`);
+ }
+
+ button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
+describe('PageSettings', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('returns the selected page mode and modern width through confirm hooks', () => {
+ const hooks: IConfirmChildrenProps['hooks'] = {};
+ const rendered = renderPageSettings(hooks);
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => clickButton(container!, 'Wide'));
+ expect(hooks.beforeConfirm?.()).toMatchObject({
+ mode: DocumentFlavor.MODERN,
+ modernWidth: ModernDocumentWidthMode.WIDE,
+ pageSize: { width: 720, height: 960 },
+ margins: {
+ top: 24,
+ bottom: 28,
+ left: 32,
+ right: 36,
+ },
+ });
+
+ act(() => clickButton(container!, 'Classic'));
+ expect(hooks.beforeClose?.()).toMatchObject({
+ mode: DocumentFlavor.TRADITIONAL,
+ paperSize: 'A4',
+ pageSize: { width: 720, height: 960 },
+ });
+ });
+});
diff --git a/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx b/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx
new file mode 100644
index 0000000000..94811fbb6c
--- /dev/null
+++ b/packages/docs-ui/src/views/__tests__/SideMenu.spec.tsx
@@ -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 type { Root } from 'react-dom/client';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { SideMenu } from '../SideMenu';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const menus = [
+ { id: 'title', level: 1, text: 'Document outline', isTitle: true },
+ { id: 'intro', level: 1, text: 'Introduction' },
+ { id: 'details', level: 2, text: 'Details' },
+];
+
+function renderSideMenu(props: React.ComponentProps<typeof SideMenu>) {
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(<SideMenu {...props} />);
+ });
+
+ return { container, root };
+}
+
+describe('SideMenu', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('emits the clicked outline item with its document location metadata', () => {
+ const selectedItems: typeof menus = [];
+ const rendered = renderSideMenu({
+ menus,
+ maxHeight: 180,
+ open: true,
+ onClick: (menu) => {
+ selectedItems.push(menu);
+ },
+ });
+ root = rendered.root;
+ container = rendered.container;
+
+ const detailsItem = Array.from(container.querySelectorAll('div')).find((element) => element.textContent === 'Details');
+ if (!detailsItem) {
+ throw new Error('Missing Details menu item');
+ }
+
+ act(() => {
+ detailsItem.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(selectedItems).toEqual([{ id: 'details', level: 2, text: 'Details' }]);
+ });
+
+ it('requests an open state change and translates the panel from the controlled state', () => {
+ const openStates: boolean[] = [];
+ const rendered = renderSideMenu({
+ menus,
+ maxHeight: 180,
+ open: false,
+ mode: 'side-bar',
+ onOpenChange: (open) => {
+ openStates.push(open);
+ },
+ });
+ root = rendered.root;
+ container = rendered.container;
+
+ const toggle = container.firstElementChild?.firstElementChild;
+ const panel = container.firstElementChild?.children.item(1) as HTMLElement | null;
+ if (!toggle || !panel) {
+ throw new Error('Missing side menu toggle or panel');
+ }
+
+ expect(panel.style.transform).toBe('translateX(-100%)');
+
+ act(() => {
+ toggle.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(openStates).toEqual([true]);
+ expect(panel.style.transform).toBe('translateX(-100%)');
+ });
+});
diff --git a/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsx b/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsx
new file mode 100644
index 0000000000..ac9eb18d55
--- /dev/null
+++ b/packages/docs-ui/src/views/count-bar/__tests__/ZoomSlider.spec.tsx
@@ -0,0 +1,121 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { Root } from 'react-dom/client';
+import {
+ CommandService,
+ ConfigService,
+ ContextService,
+ DocumentDataModel,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { SetDocZoomRatioOperation } from '../../../commands/operations/set-doc-zoom-ratio.operation';
+import { ZoomSlider } from '../ZoomSlider';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestLogService {
+ debug(): void {}
+ warn(): void {}
+}
+
+function createZoomSliderTestBed() {
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: TestLogService as never }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+
+ const doc = new DocumentDataModel({
+ id: 'zoom-slider-doc',
+ body: {
+ dataStream: '\r\n',
+ paragraphs: [],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ },
+ });
+
+ (injector.get(IUniverInstanceService) as UniverInstanceService).__addUnit(doc);
+ injector.get(ICommandService).registerCommand(SetDocZoomRatioOperation);
+
+ return { injector, doc };
+}
+
+function renderZoomSlider() {
+ const { injector, doc } = createZoomSliderTestBed();
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <ZoomSlider />
+ </RediContext.Provider>
+ );
+ });
+
+ return { container, doc, root };
+}
+
+describe('ZoomSlider', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('applies toolbar zoom changes to the current document through the zoom operation', () => {
+ const rendered = renderZoomSlider();
+ root = rendered.root;
+ container = rendered.container;
+
+ const buttons = Array.from(container.querySelectorAll('button'));
+ const increaseButton = buttons[2];
+
+ act(() => {
+ increaseButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(rendered.doc.zoomRatio).toBe(1.1);
+ });
+});
diff --git a/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx b/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx
new file mode 100644
index 0000000000..df8b8488f8
--- /dev/null
+++ b/packages/docs-ui/src/views/header-footer/panel/__tests__/DocHeaderFooterOptions.spec.tsx
@@ -0,0 +1,367 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @vitest-environment jsdom
+ */
+
+import type { ICommand, IDisposable } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import type { ICoreHeaderFooterParams } from '../../../../commands/commands/doc-header-footer.command';
+import {
+ BooleanNumber,
+ CommandService,
+ CommandType,
+ ConfigService,
+ ContextService,
+ DocumentDataModel,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ toDisposable,
+ UniverInstanceService,
+} from '@univerjs/core';
+import { DocSkeletonManagerService } from '@univerjs/docs';
+import { DocumentEditArea, IRenderManagerService } from '@univerjs/engine-render';
+import { ILayoutService, 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 { CloseHeaderFooterCommand, CoreHeaderFooterCommandId } from '../../../../commands/commands/doc-header-footer.command';
+import { DocSelectionRenderService } from '../../../../services/selection/doc-selection-render.service';
+import { DocHeaderFooterOptions } from '../DocHeaderFooterOptions';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'header-footer-options-doc';
+
+interface IRecordedCommand {
+ id: string;
+ params: unknown;
+}
+
+class TestLogService {
+ debug(): void {}
+ warn(): void {}
+}
+
+class TestLocaleService {
+ t(key: string): string {
+ return key;
+ }
+}
+
+class TestLayoutService {
+ private _focusCount = 0;
+
+ get focusCount() {
+ return this._focusCount;
+ }
+
+ focus(): void {
+ this._focusCount += 1;
+ }
+
+ 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._focusCount > 0;
+ }
+}
+
+class TestSelectionRenderService {
+ private _segment = 'default-header';
+ private _segmentPage = 0;
+ private _removeRangeCount = 0;
+ private _blurCount = 0;
+
+ get segment() {
+ return this._segment;
+ }
+
+ get removeRangeCount() {
+ return this._removeRangeCount;
+ }
+
+ get blurCount() {
+ return this._blurCount;
+ }
+
+ getSegment(): string {
+ return this._segment;
+ }
+
+ setSegment(segmentId: string): void {
+ this._segment = segmentId;
+ }
+
+ getSegmentPage(): number {
+ return this._segmentPage;
+ }
+
+ setSegmentPage(page: number): void {
+ this._segmentPage = page;
+ }
+
+ removeAllRanges(): void {
+ this._removeRangeCount += 1;
+ }
+
+ blur(): void {
+ this._blurCount += 1;
+ }
+}
+
+class TestDocumentViewModel {
+ readonly editAreaChange$ = new Subject<DocumentEditArea | null>();
+ private _editArea = DocumentEditArea.HEADER;
+
+ getEditArea(): DocumentEditArea {
+ return this._editArea;
+ }
+
+ setEditArea(editArea: DocumentEditArea): void {
+ this._editArea = editArea;
+ this.editAreaChange$.next(editArea);
+ }
+}
+
+class TestDocSkeletonManagerService {
+ constructor(private readonly _viewModel: TestDocumentViewModel) {}
+
+ getViewModel(): TestDocumentViewModel {
+ return this._viewModel;
+ }
+}
+
+class TestRenderUnit {
+ constructor(
+ private readonly _selectionRenderService: TestSelectionRenderService,
+ private readonly _docSkeletonManagerService: TestDocSkeletonManagerService
+ ) {}
+
+ with(token: unknown) {
+ if (token === DocSelectionRenderService) {
+ return this._selectionRenderService;
+ }
+ if (token === DocSkeletonManagerService) {
+ return this._docSkeletonManagerService;
+ }
+ return null;
+ }
+}
+
+class TestRenderManagerService {
+ static renderUnit: TestRenderUnit;
+
+ getRenderById(): TestRenderUnit {
+ return TestRenderManagerService.renderUnit;
+ }
+}
+
+function createHeaderFooterOptionsTestBed() {
+ const injector = new Injector();
+ const records: IRecordedCommand[] = [];
+ const selectionRenderService = new TestSelectionRenderService();
+ const viewModel = new TestDocumentViewModel();
+
+ TestRenderManagerService.renderUnit = new TestRenderUnit(
+ selectionRenderService,
+ new TestDocSkeletonManagerService(viewModel)
+ );
+
+ injector.add([ILogService, { useClass: TestLogService as never }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
+
+ const doc = new DocumentDataModel({
+ id: UNIT_ID,
+ documentStyle: {
+ defaultHeaderId: 'default-header',
+ defaultFooterId: 'default-footer',
+ marginHeader: 12,
+ marginFooter: 18,
+ useFirstPageHeaderFooter: BooleanNumber.FALSE,
+ evenAndOddHeaders: BooleanNumber.FALSE,
+ },
+ body: {
+ dataStream: '\r\n',
+ paragraphs: [],
+ sectionBreaks: [],
+ customRanges: [],
+ tables: [],
+ textRuns: [],
+ },
+ });
+ (injector.get(IUniverInstanceService) as UniverInstanceService).__addUnit(doc);
+
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(createRecordingCommand(CoreHeaderFooterCommandId, records));
+ commandService.registerCommand(createRecordingCommand(CloseHeaderFooterCommand.id, records));
+
+ return {
+ injector,
+ records,
+ selectionRenderService,
+ viewModel,
+ layoutService: injector.get(ILayoutService) as unknown as TestLayoutService,
+ };
+}
+
+function createRecordingCommand(id: string, records: IRecordedCommand[]): ICommand {
+ return {
+ id,
+ type: CommandType.COMMAND,
+ handler: (_accessor, params) => {
+ records.push({ id, params });
+ return true;
+ },
+ };
+}
+
+function renderHeaderFooterOptions() {
+ const testBed = createHeaderFooterOptionsTestBed();
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <DocHeaderFooterOptions unitId={UNIT_ID} />
+ </RediContext.Provider>
+ );
+ });
+
+ return { ...testBed, container, root };
+}
+
+function clickCheckbox(input: HTMLInputElement) {
+ input.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
+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('DocHeaderFooterOptions', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('turns on first-page header/footer and focuses the newly created current-page segment', () => {
+ const rendered = renderHeaderFooterOptions();
+ root = rendered.root;
+ container = rendered.container;
+
+ const [firstPageCheckbox] = Array.from(container.querySelectorAll('input[type="checkbox"]')) as HTMLInputElement[];
+
+ act(() => clickCheckbox(firstPageCheckbox));
+
+ const [record] = rendered.records;
+ const params = record.params as ICoreHeaderFooterParams;
+
+ expect(record.id).toBe(CoreHeaderFooterCommandId);
+ expect(params.unitId).toBe(UNIT_ID);
+ expect(params.headerFooterProps).toEqual({
+ useFirstPageHeaderFooter: BooleanNumber.TRUE,
+ });
+ expect(params.segmentId).toHaveLength(6);
+ expect(rendered.selectionRenderService.segment).toBe(params.segmentId);
+ expect(rendered.layoutService.focusCount).toBe(1);
+ });
+
+ it('sends margin edits and close actions through header/footer commands', async () => {
+ const rendered = renderHeaderFooterOptions();
+ root = rendered.root;
+ container = rendered.container;
+
+ const [headerMarginInput] = Array.from(container.querySelectorAll('input[type="text"]')) as HTMLInputElement[];
+ const closeButton = Array.from(container.querySelectorAll('button')).find((button) => (
+ button.textContent?.includes('docs-ui.headerFooter.closeHeaderFooter')
+ ));
+
+ if (!closeButton) {
+ throw new Error('Missing close header footer button');
+ }
+
+ await act(async () => {
+ changeInput(headerMarginInput, '25.5');
+ });
+ act(() => {
+ closeButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+
+ expect(rendered.records.map((record) => record.id)).toEqual([
+ CoreHeaderFooterCommandId,
+ CloseHeaderFooterCommand.id,
+ ]);
+ expect((rendered.records[0].params as ICoreHeaderFooterParams).headerFooterProps).toEqual({
+ marginHeader: 25.5,
+ });
+ expect((rendered.records[1].params as { unitId: string })).toEqual({
+ unitId: UNIT_ID,
+ });
+ expect(rendered.selectionRenderService.removeRangeCount).toBe(1);
+ expect(rendered.selectionRenderService.blurCount).toBe(1);
+ });
+});
diff --git a/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
new file mode 100644
index 0000000000..f8fbbfee8b
--- /dev/null
+++ b/packages/docs/src/commands/commands/__tests__/core-editing.command.spec.ts
@@ -0,0 +1,133 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DeleteDirection, ICommandService } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createTestBed } from '../../../facade/__tests__/create-test-bed';
+import { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from '../core-editing.command';
+
+describe('core editing commands', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ testBed = createTestBed();
+ commandService = testBed.get(ICommandService);
+ });
+
+ afterEach(() => {
+ testBed.univer.dispose();
+ });
+
+ it('deletes text to the left of the collapsed range in the active document', () => {
+ const result = commandService.syncExecuteCommand(DeleteTextCommand.id, {
+ unitId: 'test',
+ range: {
+ startOffset: 6,
+ endOffset: 6,
+ collapsed: true,
+ },
+ direction: DeleteDirection.LEFT,
+ });
+
+ expect(result).toBe(true);
+ expect(testBed.univerAPI.getActiveDocument()?.save().body?.dataStream).toBe('Hello\r\n');
+ });
+
+ it('expands deletion to whole custom entities', () => {
+ testBed.univer.dispose();
+ testBed = createTestBed({
+ id: 'test',
+ body: {
+ dataStream: 'A@B\r\n',
+ paragraphs: [{ startIndex: 3, paragraphId: 'para_entity' }],
+ customRanges: [{
+ startIndex: 1,
+ endIndex: 2,
+ rangeId: 'mention-1',
+ rangeType: 0,
+ wholeEntity: true,
+ }],
+ },
+ documentStyle: {},
+ });
+ commandService = testBed.get(ICommandService);
+
+ const result = commandService.syncExecuteCommand(DeleteTextCommand.id, {
+ unitId: 'test',
+ range: {
+ startOffset: 2,
+ endOffset: 2,
+ collapsed: true,
+ },
+ direction: DeleteDirection.RIGHT,
+ len: 1,
+ });
+
+ expect(result).toBe(true);
+ expect(testBed.univerAPI.getActiveDocument()?.save().body?.dataStream).toBe('A\r\n');
+ });
+
+ it('updates text style over a range without changing the document text', () => {
+ const result = commandService.syncExecuteCommand(UpdateTextCommand.id, {
+ unitId: 'test',
+ range: {
+ startOffset: 0,
+ endOffset: 5,
+ collapsed: false,
+ },
+ updateBody: {
+ textRuns: [{
+ st: 0,
+ ed: 5,
+ ts: { bl: 1 },
+ }],
+ },
+ coverType: 0,
+ textRanges: [{
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ }],
+ });
+
+ const body = testBed.univerAPI.getActiveDocument()?.save().body;
+ expect(result).toBe(true);
+ expect(body?.dataStream).toBe('Hello,\r\n');
+ });
+
+ it('returns false when the target document or body cannot be resolved', () => {
+ expect(commandService.syncExecuteCommand(DeleteTextCommand.id, {
+ unitId: 'missing-doc',
+ range: {
+ startOffset: 1,
+ endOffset: 1,
+ collapsed: true,
+ },
+ direction: DeleteDirection.LEFT,
+ })).toBe(false);
+
+ expect(commandService.syncExecuteCommand(InsertTextCommand.id, {
+ unitId: 'missing-doc',
+ body: { dataStream: 'X' },
+ range: {
+ startOffset: 0,
+ endOffset: 0,
+ collapsed: true,
+ },
+ })).toBe(false);
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/create-test-bed.ts b/packages/docs/src/facade/__tests__/create-test-bed.ts
index 2d2639ef03..0267da4158 100644
--- a/packages/docs/src/facade/__tests__/create-test-bed.ts
+++ b/packages/docs/src/facade/__tests__/create-test-bed.ts
@@ -16,13 +16,44 @@
import type { DocumentDataModel, IDocumentData, Injector } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
-import { DisposableCollection, ILogService, IUniverInstanceService, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';
+import {
+ DisposableCollection,
+ DocumentBlockRangeType,
+ ILogService,
+ IUniverInstanceService,
+ LogLevel,
+ PresetListType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { FUniver as FUniverCtor } from '@univerjs/core/facade';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { BehaviorSubject } from 'rxjs';
import { UniverDocsPlugin } from '../../plugin';
import '../index';
+export const DOCUMENT_STYLE: IDocumentData['documentStyle'] = {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+};
+
+export function createDocumentData(id: string, body: NonNullable<IDocumentData['body']>): IDocumentData {
+ return {
+ id,
+ body: {
+ customBlocks: [],
+ ...body,
+ },
+ documentStyle: DOCUMENT_STYLE,
+ };
+}
+
function getTestDocumentDataDemo(): IDocumentData {
return {
id: 'test',
@@ -30,19 +61,104 @@ function getTestDocumentDataDemo(): IDocumentData {
dataStream: 'Hello,\r\n',
paragraphs: [{ startIndex: 6, paragraphId: 'para_fixture_19' }],
},
- documentStyle: {
- pageSize: {
- width: 594.3,
- height: 840.51,
- },
- marginTop: 72,
- marginBottom: 72,
- marginRight: 90,
- marginLeft: 90,
- },
+ documentStyle: DOCUMENT_STYLE,
};
}
+export function createSimpleDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Alpha\rBeta\rGamma\r\n',
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'para_alpha' },
+ { startIndex: 10, paragraphId: 'para_beta' },
+ { startIndex: 16, paragraphId: 'para_gamma' },
+ ],
+ sectionBreaks: [{ startIndex: 17 }],
+ });
+}
+
+export function createDuplicateDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Same\rSame\rTail\r\n',
+ paragraphs: [
+ { startIndex: 4, paragraphId: 'para_same_1' },
+ { startIndex: 9, paragraphId: 'para_same_2' },
+ { startIndex: 14, paragraphId: 'para_tail' },
+ ],
+ sectionBreaks: [{ startIndex: 15 }],
+ });
+}
+
+export function createTaskDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Todo\rDone\r\n',
+ paragraphs: [
+ {
+ startIndex: 4,
+ paragraphId: 'para_todo',
+ bullet: {
+ listId: 'task-list',
+ listType: PresetListType.CHECK_LIST,
+ nestingLevel: 0,
+ },
+ },
+ { startIndex: 9, paragraphId: 'para_done' },
+ ],
+ sectionBreaks: [{ startIndex: 10 }],
+ });
+}
+
+export function createBulletDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Bullet\rTail\r\n',
+ paragraphs: [
+ {
+ startIndex: 6,
+ paragraphId: 'para_bullet',
+ bullet: {
+ listId: 'bullet-list',
+ listType: PresetListType.BULLET_LIST,
+ nestingLevel: 0,
+ },
+ },
+ { startIndex: 11, paragraphId: 'para_bullet_tail' },
+ ],
+ sectionBreaks: [{ startIndex: 12 }],
+ });
+}
+
+export function createBlockRangeDocument(blockType = DocumentBlockRangeType.QUOTE, id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'Block\rAfter\r\n',
+ paragraphs: [{ startIndex: 5, paragraphId: 'para_fixture_20' }, { startIndex: 11, paragraphId: 'para_after_block' }],
+ blockRanges: [{
+ blockId: `${blockType}-1`,
+ blockType,
+ startIndex: 0,
+ endIndex: 5,
+ }],
+ sectionBreaks: [{ startIndex: 12 }],
+ });
+}
+
+export function createTableDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: 'TT\raa\r\n',
+ paragraphs: [{ startIndex: 2, paragraphId: 'para_fixture_21' }, { startIndex: 5, paragraphId: 'para_after_table' }],
+ tables: [{ tableId: 'table-1', startIndex: 0, endIndex: 2 }],
+ sectionBreaks: [{ startIndex: 6 }],
+ });
+}
+
+export function createCustomBlockDocument(id = 'test'): IDocumentData {
+ return createDocumentData(id, {
+ dataStream: '\b\raa\r\n',
+ paragraphs: [{ startIndex: 1, paragraphId: 'para_fixture_22' }, { startIndex: 4, paragraphId: 'para_after_custom_block' }],
+ customBlocks: [{ blockId: 'custom-1', blockType: 'custom' as never, startIndex: 0 }],
+ sectionBreaks: [{ startIndex: 5 }],
+ });
+}
+
function cloneDocumentData(documentData: IDocumentData): IDocumentData {
return JSON.parse(JSON.stringify(documentData)) as IDocumentData;
}
diff --git a/packages/docs/src/facade/__tests__/f-doc-block-range.spec.ts b/packages/docs/src/facade/__tests__/f-doc-block-range.spec.ts
new file mode 100644
index 0000000000..8aa763c8dd
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-doc-block-range.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { DocumentBlockRangeType } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createBlockRangeDocument, createTestBed } from './create-test-bed';
+
+describe('FDocBlockRange', () => {
+ let univer: Univer | null = null;
+ let document: FDocument;
+
+ function createDocumentFacade(blockType = DocumentBlockRangeType.QUOTE) {
+ univer?.dispose();
+ const testBed = createTestBed(createBlockRangeDocument(blockType));
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ }
+
+ afterEach(() => {
+ univer?.dispose();
+ univer = null;
+ });
+
+ it('should edit and remove block range content while preserving surrounding paragraphs', () => {
+ for (const blockType of [DocumentBlockRangeType.QUOTE, DocumentBlockRangeType.CALLOUT, DocumentBlockRangeType.CODE]) {
+ createDocumentFacade(blockType);
+
+ const body = document.getBody();
+ const block = body.getChild(0).asBlockRange();
+
+ expect(block.getType()).toBe('blockRange');
+ expect(block.getKey()).toBe(`${blockType}-1`);
+ expect(block.getParent()).toBe(body);
+ expect(block.getBlockType()).toBe(blockType);
+ expect(block.getText()).toBe('Block');
+ expect(body.getBlockRange(block.getKey()).blockType).toBe(blockType);
+ expect(body.getBlockRangeText(block.getKey())).toBe('Block');
+ expect(body.insertParagraph(0, 'Intro').getText()).toBe('Intro');
+ expect(block.getText()).toBe('Block');
+ expect(block.setText('Updated')).toBe(true);
+ expect(body.getBlockRangeText(block.getKey())).toBe('Updated');
+ expect(block.removeFromParent()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Intro\rAfter\r\n');
+ }
+ });
+
+ it('should unwrap a block range from the body', () => {
+ createDocumentFacade();
+
+ expect(document.getBody().getChild(0).asBlockRange().unwrap()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('After\r\n');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-doc-body.spec.ts b/packages/docs/src/facade/__tests__/f-doc-body.spec.ts
new file mode 100644
index 0000000000..ec4ecf4717
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-doc-body.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 type { Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DocElementStaleError } from '../doc-element-registry';
+import { createSimpleDocument, createTestBed } from './create-test-bed';
+
+describe('FDocBody', () => {
+ let univer: Univer;
+ let document: FDocument;
+
+ beforeEach(() => {
+ const testBed = createTestBed(createSimpleDocument());
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should read, insert, replace, style and remove paragraphs by stable paragraph ids', () => {
+ const body = document.getBody();
+ expect(body.getNumChildren()).toBe(3);
+
+ const first = body.getChild(0);
+ const second = body.getChild(1).asParagraph();
+ expect(first.getType()).toBe('paragraph');
+ expect(first.getKey()).toBe('para_alpha');
+ expect(first.asParagraph().getId()).toBe('para_alpha');
+ expect(second.getId()).toBe('para_beta');
+ expect(second.getKey()).toBe('para_beta');
+ expect(first.getParent()).toBe(body);
+ expect(first.getNextSibling()?.asParagraph().getText()).toBe('Beta');
+ expect(body.getChild(1).getPreviousSibling()?.asParagraph().getText()).toBe('Alpha');
+ expect(body.createSibling(first.getType(), first.getKey(), 1)?.asParagraph().getText()).toBe('Beta');
+
+ expect(body.getChildIndex(second)).toBe(1);
+ expect(body.insertText(0, 'Hello ')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\r\n');
+
+ const title = body.insertParagraph(0, 'Title');
+ expect(title.getId()).toMatch(/^para_/);
+ expect(title.getKey()).toBe(title.getId());
+ expect(title.getText()).toBe('Title');
+ expect(document.save().body?.paragraphs?.[0].paragraphId).toBe(title.getId());
+ expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\r\n');
+
+ const tail = body.appendParagraph('Tail');
+ expect(tail.getText()).toBe('Tail');
+ expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\rTail\r\n');
+
+ expect(body.deleteRange({ startOffset: 0, endOffset: 6 })).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\rTail\r\n');
+
+ expect(body.replaceRange({ startOffset: 0, endOffset: 5 }, 'Hi')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hi Alpha\rBeta\rGamma\rTail\r\n');
+
+ expect(body.setTextStyle({ startOffset: 0, endOffset: 2 }, { bl: 1 })).toBe(true);
+ expect(document.save().body?.textRuns).toContainEqual({
+ st: 0,
+ ed: 2,
+ ts: { bl: 1 },
+ });
+
+ const paragraph = body.getChild(0).asParagraph();
+ expect(body.setParagraphStyle(paragraph, { horizontalAlign: 2 })).toBe(true);
+ expect(document.save().body?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(2);
+
+ expect(body.getParagraphText(paragraph.getKey())).toBe('Hi Alpha');
+ expect(body.getParagraphRange(paragraph.getKey())).toMatchObject({ startOffset: 0, endOffset: 8 });
+ expect(body.resolveParagraph(paragraph.getKey()).paragraphIndex).toBe(0);
+ expect(body.resolveElement(paragraph.getType(), paragraph.getKey())).toMatchObject({ type: 'paragraph', position: 0 });
+
+ expect(body.setParagraphText(paragraph.getKey(), 'Updated')).toBe(true);
+ expect(paragraph.getText()).toBe('Updated');
+ expect(body.appendParagraphText(paragraph.getKey(), ' suffix')).toBe(true);
+ expect(paragraph.getText()).toBe('Updated suffix');
+ expect(body.removeParagraph(paragraph.getKey())).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Beta\rGamma\rTail\r\n');
+ });
+
+ it('should reject ambiguous or missing paragraph identities as stale elements', () => {
+ const body = document.getBody();
+ document.getDocumentDataModel().getBody()!.paragraphs![1].paragraphId = 'para_alpha';
+ expect(() => body.resolveParagraph('para_alpha')).toThrow(DocElementStaleError);
+
+ document.getDocumentDataModel().getBody()!.paragraphs![1].paragraphId = 'para_beta';
+ const invalidParagraph = document.getDocumentDataModel().getBody()!.paragraphs![0] as { paragraphId?: string };
+ delete invalidParagraph.paragraphId;
+
+ expect(() => body.getChild(0)).toThrow(DocElementStaleError);
+ expect(() => body.getChild(0)).toThrow('Paragraph at index 0 is missing paragraphId.');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-doc-custom-block.spec.ts b/packages/docs/src/facade/__tests__/f-doc-custom-block.spec.ts
new file mode 100644
index 0000000000..e331668d47
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-doc-custom-block.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createCustomBlockDocument, createTestBed } from './create-test-bed';
+
+describe('FDocCustomBlock', () => {
+ let univer: Univer;
+ let document: FDocument;
+
+ function createDocumentFacade() {
+ univer?.dispose();
+ const testBed = createTestBed(createCustomBlockDocument());
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ }
+
+ beforeEach(() => {
+ createDocumentFacade();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should expose custom block identity and remove the block from document body', () => {
+ const body = document.getBody();
+ const customBlock = body.getChild(0).asCustomBlock();
+
+ expect(customBlock.getType()).toBe('customBlock');
+ expect(customBlock.getKey()).toBe('custom-1');
+ expect(customBlock.getParent()).toBe(body);
+ expect(customBlock.getBlockId()).toBe('custom-1');
+ expect(body.getCustomBlock(customBlock.getBlockId()).blockId).toBe('custom-1');
+ expect(customBlock.removeFromParent()).toBe(true);
+ expect(document.save().body?.customBlocks).toEqual([]);
+
+ createDocumentFacade();
+ expect(document.getBody().removeCustomBlock('custom-1')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('\raa\r\n');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-doc-element.spec.ts b/packages/docs/src/facade/__tests__/f-doc-element.spec.ts
new file mode 100644
index 0000000000..4518ab9d33
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-doc-element.spec.ts
@@ -0,0 +1,83 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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, Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { DocumentBlockRangeType } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ createBlockRangeDocument,
+ createCustomBlockDocument,
+ createSimpleDocument,
+ createTableDocument,
+ createTestBed,
+} from './create-test-bed';
+
+describe('FDocElement', () => {
+ let univer: Univer | null = null;
+ let document: FDocument;
+
+ function createDocumentFacade(docData: IDocumentData) {
+ univer?.dispose();
+ const testBed = createTestBed(docData);
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ }
+
+ afterEach(() => {
+ univer?.dispose();
+ univer = null;
+ });
+
+ it('should cast body elements to their concrete facade types', () => {
+ createDocumentFacade(createSimpleDocument());
+ expect(document.getBody().getChild(0).asParagraph().getText()).toBe('Alpha');
+
+ createDocumentFacade(createBlockRangeDocument());
+ expect(document.getBody().getChild(0).asBlockRange().getBlockType()).toBe(DocumentBlockRangeType.QUOTE);
+
+ createDocumentFacade(createTableDocument());
+ expect(document.getBody().getChild(0).asTable().getTableId()).toBe('table-1');
+
+ createDocumentFacade(createCustomBlockDocument());
+ expect(document.getBody().getChild(0).asCustomBlock().getBlockId()).toBe('custom-1');
+ });
+
+ it('should remove a generic element from its parent', () => {
+ createDocumentFacade(createSimpleDocument());
+
+ expect(document.getBody().getChild(0).removeFromParent()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Beta\rGamma\r\n');
+ });
+
+ it('should navigate siblings and reject invalid casts', () => {
+ createDocumentFacade(createSimpleDocument());
+
+ const body = document.getBody();
+ const first = body.getChild(0);
+ const second = body.getChild(1);
+
+ expect(first.getPreviousSibling()).toBeNull();
+ expect(first.getNextSibling()?.getKey()).toBe(second.getKey());
+ expect(second.getPreviousSibling()?.getKey()).toBe(first.getKey());
+ expect(() => first.asTable()).toThrow('Cannot cast paragraph to table.');
+ expect(() => first.asBlockRange()).toThrow('Cannot cast paragraph to blockRange.');
+ expect(() => first.asCustomBlock()).toThrow('Cannot cast paragraph to customBlock.');
+
+ createDocumentFacade(createTableDocument());
+ expect(() => document.getBody().getChild(0).asParagraph()).toThrow('Cannot cast table to paragraph.');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-doc-paragraph.spec.ts b/packages/docs/src/facade/__tests__/f-doc-paragraph.spec.ts
new file mode 100644
index 0000000000..d67c663326
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-doc-paragraph.spec.ts
@@ -0,0 +1,92 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData, Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { PresetListType } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DocElementStaleError } from '../doc-element-registry';
+import {
+ createBulletDocument,
+ createDuplicateDocument,
+ createSimpleDocument,
+ createTaskDocument,
+ createTestBed,
+} from './create-test-bed';
+
+describe('FDocParagraph', () => {
+ let univer: Univer | null = null;
+ let document: FDocument;
+
+ function createDocumentFacade(docData: IDocumentData) {
+ univer?.dispose();
+ const testBed = createTestBed(docData);
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ }
+
+ afterEach(() => {
+ univer?.dispose();
+ univer = null;
+ });
+
+ it('should keep paragraph handles stable when text is duplicated or inserted before them', () => {
+ createDocumentFacade(createDuplicateDocument());
+
+ const body = document.getBody();
+ const secondSame = body.getChild(1).asParagraph();
+
+ expect(secondSame.getId()).toBe('para_same_2');
+ expect(body.insertParagraph(0, 'X').getText()).toBe('X');
+ expect(body.getChildIndex(secondSame)).toBe(2);
+ expect(secondSame.setText('Picked')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('X\rSame\rPicked\rTail\r\n');
+ expect(secondSame.removeFromParent()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('X\rSame\rTail\r\n');
+ });
+
+ it('should mark paragraph handles as stale after their backing paragraph is removed', () => {
+ createDocumentFacade(createSimpleDocument());
+
+ const paragraph = document.getBody().getChild(1).asParagraph();
+ expect(paragraph.removeFromParent()).toBe(true);
+ expect(() => paragraph.getText()).toThrow(DocElementStaleError);
+ expect(() => paragraph.removeFromParent()).toThrow(DocElementStaleError);
+ });
+
+ it('should update checklist paragraphs without changing non-task list items', () => {
+ createDocumentFacade(createBulletDocument());
+
+ const bulletBody = document.getBody();
+ const listItem = bulletBody.getChild(0).asParagraph();
+ expect(listItem.getType()).toBe('paragraph');
+ expect(listItem.getKey()).toMatch(/^para_/);
+ expect(listItem.getId()).toBe(listItem.getKey());
+ expect(listItem.getParent()).toBe(bulletBody);
+ expect(listItem.isListItem()).toBe(true);
+ expect(listItem.isTask()).toBe(false);
+
+ createDocumentFacade(createTaskDocument());
+
+ const task = document.getBody().getChild(0).asParagraph();
+ expect(task.isListItem()).toBe(true);
+ expect(task.isTask()).toBe(true);
+ expect(task.setTaskChecked(true)).toBe(true);
+ expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);
+ expect(document.getBody().setTaskChecked(task.getKey(), false)).toBe(true);
+ expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-doc-table.spec.ts b/packages/docs/src/facade/__tests__/f-doc-table.spec.ts
new file mode 100644
index 0000000000..146983002d
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-doc-table.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createTableDocument, createTestBed } from './create-test-bed';
+
+describe('FDocTable', () => {
+ let univer: Univer;
+ let document: FDocument;
+
+ function createDocumentFacade() {
+ univer?.dispose();
+ const testBed = createTestBed(createTableDocument());
+ univer = testBed.univer;
+ document = testBed.univerAPI.getActiveDocument()!;
+ }
+
+ beforeEach(() => {
+ createDocumentFacade();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should expose table identity and remove the table from document body', () => {
+ const body = document.getBody();
+ const table = body.getChild(0).asTable();
+
+ expect(table.getType()).toBe('table');
+ expect(table.getKey()).toBe('table-1');
+ expect(table.getParent()).toBe(body);
+ expect(table.getTableId()).toBe('table-1');
+ expect(body.getTable(table.getTableId()).tableId).toBe('table-1');
+ expect(table.removeFromParent()).toBe(true);
+ expect(document.save().body?.tables).toEqual([]);
+
+ createDocumentFacade();
+ expect(document.getBody().removeTable('table-1')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('aa\r\n');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-document-node.spec.ts b/packages/docs/src/facade/__tests__/f-document-node.spec.ts
deleted file mode 100644
index 867d5a8118..0000000000
--- a/packages/docs/src/facade/__tests__/f-document-node.spec.ts
+++ /dev/null
@@ -1,518 +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, Univer } from '@univerjs/core';
-import { DocumentBlockRangeType, IResourceManagerService, PresetListType, UniverInstanceType } from '@univerjs/core';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { DocElementStaleError } from '../doc-element-registry';
-import { FDocument } from '../f-document';
-import { createTestBed } from './create-test-bed';
-
-const DOCUMENT_STYLE: IDocumentData['documentStyle'] = {
- pageSize: {
- width: 594.3,
- height: 840.51,
- },
- marginTop: 72,
- marginBottom: 72,
- marginRight: 90,
- marginLeft: 90,
-};
-
-function createDocumentData(id: string, body: NonNullable<IDocumentData['body']>): IDocumentData {
- return {
- id,
- body: {
- customBlocks: [],
- ...body,
- },
- documentStyle: DOCUMENT_STYLE,
- };
-}
-
-function createSimpleDocument(id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: 'Alpha\rBeta\rGamma\r\n',
- paragraphs: [
- { startIndex: 5, paragraphId: 'para_alpha' },
- { startIndex: 10, paragraphId: 'para_beta' },
- { startIndex: 16, paragraphId: 'para_gamma' },
- ],
- sectionBreaks: [{ startIndex: 17 }],
- });
-}
-
-function createDuplicateDocument(id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: 'Same\rSame\rTail\r\n',
- paragraphs: [
- { startIndex: 4, paragraphId: 'para_same_1' },
- { startIndex: 9, paragraphId: 'para_same_2' },
- { startIndex: 14, paragraphId: 'para_tail' },
- ],
- sectionBreaks: [{ startIndex: 15 }],
- });
-}
-
-function createTaskDocument(id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: 'Todo\rDone\r\n',
- paragraphs: [
- {
- startIndex: 4,
- paragraphId: 'para_todo',
- bullet: {
- listId: 'task-list',
- listType: PresetListType.CHECK_LIST,
- nestingLevel: 0,
- },
- },
- { startIndex: 9, paragraphId: 'para_done' },
- ],
- sectionBreaks: [{ startIndex: 10 }],
- });
-}
-
-function createBulletDocument(id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: 'Bullet\rTail\r\n',
- paragraphs: [
- {
- startIndex: 6,
- paragraphId: 'para_bullet',
- bullet: {
- listId: 'bullet-list',
- listType: PresetListType.BULLET_LIST,
- nestingLevel: 0,
- },
- },
- { startIndex: 11, paragraphId: 'para_bullet_tail' },
- ],
- sectionBreaks: [{ startIndex: 12 }],
- });
-}
-
-function createBlockRangeDocument(blockType = DocumentBlockRangeType.QUOTE, id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: 'Block\rAfter\r\n',
- paragraphs: [{ startIndex: 5, paragraphId: 'para_fixture_20' }, { startIndex: 11, paragraphId: 'para_after_block' }],
- blockRanges: [{
- blockId: `${blockType}-1`,
- blockType,
- startIndex: 0,
- endIndex: 5,
- }],
- sectionBreaks: [{ startIndex: 12 }],
- });
-}
-
-function createTableDocument(id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: 'TT\raa\r\n',
- paragraphs: [{ startIndex: 2, paragraphId: 'para_fixture_21' }, { startIndex: 5, paragraphId: 'para_after_table' }],
- tables: [{ tableId: 'table-1', startIndex: 0, endIndex: 2 }],
- sectionBreaks: [{ startIndex: 6 }],
- });
-}
-
-function createCustomBlockDocument(id = 'test'): IDocumentData {
- return createDocumentData(id, {
- dataStream: '\b\raa\r\n',
- paragraphs: [{ startIndex: 1, paragraphId: 'para_fixture_22' }, { startIndex: 4, paragraphId: 'para_after_custom_block' }],
- customBlocks: [{ blockId: 'custom-1', blockType: 'custom' as never, startIndex: 0 }],
- sectionBreaks: [{ startIndex: 5 }],
- });
-}
-
-function expectParagraphIds(paragraphs: NonNullable<IDocumentData['body']>['paragraphs']): void {
- expect(paragraphs?.every((paragraph) => paragraph.paragraphId?.startsWith('para_'))).toBe(true);
- expect(new Set(paragraphs?.map((paragraph) => paragraph.paragraphId)).size).toBe(paragraphs?.length);
-}
-
-describe('FDocument facade in Node', () => {
- let univer: Univer;
- let document: FDocument;
- let get: ReturnType<typeof createTestBed>['get'];
-
- function createDocumentFacade(docData?: IDocumentData) {
- const testBed = createTestBed(docData);
- univer = testBed.univer;
- get = testBed.get;
- document = testBed.univerAPI.getActiveDocument()!;
- }
-
- beforeEach(() => {
- createDocumentFacade();
- });
-
- afterEach(() => {
- univer.dispose();
- });
-
- it('keeps existing FDocument methods in the docs package', () => {
- expect(document.appendText('Univer')).toBe(true);
- expect(document.save().body?.dataStream).toBe('Hello,Univer\r\n');
-
- univer.dispose();
- createDocumentFacade();
- expect(document.insertText('Docs', {
- endOffset: 4,
- segmentId: '',
- startOffset: 2,
- })).toBe(true);
- expect(document.save().body?.dataStream).toBe('HeDocso,\r\n');
-
- univer.dispose();
- createDocumentFacade();
- expect(document.insertParagraph('Line 1\nLine 2', {
- endOffset: 6,
- segmentId: '',
- startOffset: 6,
- })).toBe(true);
- expect(document.save().body?.dataStream).toBe('Hello,Line 1\rLine 2\r\r\n');
- });
-
- it('throws when appending text to a document without a body', () => {
- univer.dispose();
- createDocumentFacade({
- id: 'test',
- title: 'Test Document',
- documentStyle: {},
- });
-
- expect(() => document.appendText('Univer')).toThrowError('The document body is empty');
- });
-
- it('includes current document resources in snapshots', () => {
- const resourceManagerService = get(IResourceManagerService);
-
- resourceManagerService.registerPluginResource({
- pluginName: 'DOC_TEST_RESOURCE_PLUGIN',
- businesses: [UniverInstanceType.UNIVER_DOC],
- onLoad: () => undefined,
- onUnLoad: () => undefined,
- toJson: () => '{"value":1}',
- parseJson: (bytes) => JSON.parse(bytes),
- });
-
- expect(document.save().resources).toEqual([
- {
- name: 'DOC_TEST_RESOURCE_PLUGIN',
- data: '{"value":1}',
- },
- ]);
- });
-
- it('preserves required paragraph ids at test-bed and save snapshot boundaries', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
-
- const savedParagraphs = document.save().body?.paragraphs;
-
- expect(savedParagraphs?.map((paragraph) => paragraph.startIndex)).toEqual([5, 10, 16]);
- expectParagraphIds(savedParagraphs);
- });
-
- it('returns saved snapshots with required paragraph ids unchanged', () => {
- const snapshot = createDocumentData('doc-with-ids', {
- dataStream: 'Alpha\rBeta\rGamma\r\n',
- paragraphs: [
- { startIndex: 5, paragraphId: 'para_fixture_23' },
- { startIndex: 10, paragraphId: 'para_fixture_24' },
- { startIndex: 16, paragraphId: 'para_fixture_25' },
- ],
- sectionBreaks: [{ startIndex: 17 }],
- });
- const saveUnit = vi.fn(() => snapshot);
- const facadeDocument = new FDocument(
- {
- getSnapshot: () => ({ id: 'doc-with-ids', documentStyle: {} }),
- getUnitId: () => 'doc-with-ids',
- } as never,
- {} as never,
- {} as never,
- { saveUnit } as never,
- {} as never
- );
-
- const savedParagraphs = facadeDocument.save().body?.paragraphs;
-
- expect(saveUnit).toHaveBeenCalledWith('doc-with-ids');
- expect(savedParagraphs?.map((paragraph) => paragraph.startIndex)).toEqual([5, 10, 16]);
- expectParagraphIds(savedParagraphs);
- });
-
- it('uses existing paragraph ids when creating body facade wrappers', () => {
- const snapshot = createDocumentData('doc-with-ids', {
- dataStream: 'Legacy\r\n',
- paragraphs: [{ startIndex: 6, paragraphId: 'para_fixture_26' }],
- sectionBreaks: [{ startIndex: 7 }],
- });
- const model = {
- getUnitId: () => 'doc-with-ids',
- getSnapshot: () => snapshot,
- getSelfOrHeaderFooterModel: () => ({
- getBody: () => snapshot.body,
- }),
- };
- const facadeDocument = new FDocument(
- model as never,
- {} as never,
- {} as never,
- {} as never,
- {} as never
- );
-
- const paragraph = facadeDocument.getBody().getChild(0).asParagraph();
-
- expect(paragraph.getId()).toMatch(/^para_/);
- expect(snapshot.body?.paragraphs?.[0].paragraphId).toBe(paragraph.getId());
- });
-
- it('runs FDocBody paragraph and range APIs in Node', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
-
- const body = document.getBody();
- expect(body.getNumChildren()).toBe(3);
-
- const first = body.getChild(0);
- const second = body.getChild(1).asParagraph();
- expect(first.getType()).toBe('paragraph');
- expect(first.getKey()).toBe('para_alpha');
- expect(first.asParagraph().getId()).toBe('para_alpha');
- expect(second.getId()).toBe('para_beta');
- expect(second.getKey()).toBe('para_beta');
- expect(first.getParent()).toBe(body);
- expect(first.getNextSibling()?.asParagraph().getText()).toBe('Beta');
- expect(body.getChild(1).getPreviousSibling()?.asParagraph().getText()).toBe('Alpha');
- expect(body.createSibling(first.getType(), first.getKey(), 1)?.asParagraph().getText()).toBe('Beta');
-
- expect(body.getChildIndex(second)).toBe(1);
- expect(body.insertText(0, 'Hello ')).toBe(true);
- expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\r\n');
-
- const title = body.insertParagraph(0, 'Title');
- expect(title.getId()).toMatch(/^para_/);
- expect(title.getKey()).toBe(title.getId());
- expect(title.getText()).toBe('Title');
- expect(document.save().body?.paragraphs?.[0].paragraphId).toBe(title.getId());
- expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\r\n');
-
- const tail = body.appendParagraph('Tail');
- expect(tail.getText()).toBe('Tail');
- expect(document.save().body?.dataStream).toBe('Title\rHello Alpha\rBeta\rGamma\rTail\r\n');
-
- expect(body.deleteRange({ startOffset: 0, endOffset: 6 })).toBe(true);
- expect(document.save().body?.dataStream).toBe('Hello Alpha\rBeta\rGamma\rTail\r\n');
-
- expect(body.replaceRange({ startOffset: 0, endOffset: 5 }, 'Hi')).toBe(true);
- expect(document.save().body?.dataStream).toBe('Hi Alpha\rBeta\rGamma\rTail\r\n');
-
- expect(body.setTextStyle({ startOffset: 0, endOffset: 2 }, { bl: 1 })).toBe(true);
- expect(document.save().body?.textRuns).toContainEqual({
- st: 0,
- ed: 2,
- ts: { bl: 1 },
- });
-
- const paragraph = body.getChild(0).asParagraph();
- expect(body.setParagraphStyle(paragraph, { horizontalAlign: 2 })).toBe(true);
- expect(document.save().body?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(2);
-
- expect(body.getParagraphText(paragraph.getKey())).toBe('Hi Alpha');
- expect(body.getParagraphRange(paragraph.getKey())).toMatchObject({ startOffset: 0, endOffset: 8 });
- expect(body.resolveParagraph(paragraph.getKey()).paragraphIndex).toBe(0);
- expect(body.resolveElement(paragraph.getType(), paragraph.getKey())).toMatchObject({ type: 'paragraph', position: 0 });
-
- expect(body.setParagraphText(paragraph.getKey(), 'Updated')).toBe(true);
- expect(paragraph.getText()).toBe('Updated');
- expect(body.appendParagraphText(paragraph.getKey(), ' suffix')).toBe(true);
- expect(paragraph.getText()).toBe('Updated suffix');
- expect(body.removeParagraph(paragraph.getKey())).toBe(true);
- expect(document.save().body?.dataStream).toBe('Beta\rGamma\rTail\r\n');
- });
-
- it('keeps paragraph wrappers stable for insert-before and duplicate text', () => {
- univer.dispose();
- createDocumentFacade(createDuplicateDocument());
-
- const body = document.getBody();
- const secondSame = body.getChild(1).asParagraph();
-
- expect(secondSame.getId()).toBe('para_same_2');
- expect(body.insertParagraph(0, 'X').getText()).toBe('X');
- expect(body.getChildIndex(secondSame)).toBe(2);
- expect(secondSame.setText('Picked')).toBe(true);
- expect(document.save().body?.dataStream).toBe('X\rSame\rPicked\rTail\r\n');
- expect(secondSame.removeFromParent()).toBe(true);
- expect(document.save().body?.dataStream).toBe('X\rSame\rTail\r\n');
- });
-
- it('marks deleted paragraph wrappers as stale', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
-
- const paragraph = document.getBody().getChild(1).asParagraph();
- expect(paragraph.removeFromParent()).toBe(true);
- expect(() => paragraph.getText()).toThrow(DocElementStaleError);
- expect(() => paragraph.removeFromParent()).toThrow(DocElementStaleError);
- });
-
- it('throws stale errors for duplicate paragraph ids', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
-
- const body = document.getBody();
- document.getDocumentDataModel().getBody()!.paragraphs![1].paragraphId = 'para_alpha';
-
- expect(() => body.resolveParagraph('para_alpha')).toThrow(DocElementStaleError);
- });
-
- it('throws a stale error when a paragraph child is missing its id', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
-
- const body = document.getBody();
- const invalidParagraph = document.getDocumentDataModel().getBody()!.paragraphs![0] as { paragraphId?: string };
- delete invalidParagraph.paragraphId;
-
- expect(() => body.getChild(0)).toThrow(DocElementStaleError);
- expect(() => body.getChild(0)).toThrow('Paragraph at index 0 is missing paragraphId.');
- });
-
- it('runs FDocParagraph list and task APIs in Node', () => {
- univer.dispose();
- createDocumentFacade(createBulletDocument());
-
- const bulletBody = document.getBody();
- const listItem = bulletBody.getChild(0).asParagraph();
- expect(listItem.getType()).toBe('paragraph');
- expect(listItem.getKey()).toMatch(/^para_/);
- expect(listItem.getId()).toBe(listItem.getKey());
- expect(listItem.getParent()).toBe(bulletBody);
- expect(listItem.isListItem()).toBe(true);
- expect(listItem.isTask()).toBe(false);
-
- univer.dispose();
- createDocumentFacade(createTaskDocument());
-
- const task = document.getBody().getChild(0).asParagraph();
- expect(task.isListItem()).toBe(true);
- expect(task.isTask()).toBe(true);
- expect(task.setTaskChecked(true)).toBe(true);
- expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);
- expect(document.getBody().setTaskChecked(task.getKey(), false)).toBe(true);
- expect(document.save().body?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);
- });
-
- it('runs FDocElement cast APIs in Node', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
- expect(document.getBody().getChild(0).asParagraph().getText()).toBe('Alpha');
-
- univer.dispose();
- createDocumentFacade(createBlockRangeDocument());
- expect(document.getBody().getChild(0).asBlockRange().getBlockType()).toBe(DocumentBlockRangeType.QUOTE);
-
- univer.dispose();
- createDocumentFacade(createTableDocument());
- expect(document.getBody().getChild(0).asTable().getTableId()).toBe('table-1');
-
- univer.dispose();
- createDocumentFacade(createCustomBlockDocument());
- expect(document.getBody().getChild(0).asCustomBlock().getBlockId()).toBe('custom-1');
- });
-
- it('runs FDocBlockRange APIs in Node', () => {
- for (const blockType of [DocumentBlockRangeType.QUOTE, DocumentBlockRangeType.CALLOUT, DocumentBlockRangeType.CODE]) {
- univer.dispose();
- createDocumentFacade(createBlockRangeDocument(blockType));
-
- const body = document.getBody();
- const block = body.getChild(0).asBlockRange();
-
- expect(block.getType()).toBe('blockRange');
- expect(block.getKey()).toBe(`${blockType}-1`);
- expect(block.getParent()).toBe(body);
- expect(block.getBlockType()).toBe(blockType);
- expect(block.getText()).toBe('Block');
- expect(body.getBlockRange(block.getKey()).blockType).toBe(blockType);
- expect(body.getBlockRangeText(block.getKey())).toBe('Block');
- expect(body.insertParagraph(0, 'Intro').getText()).toBe('Intro');
- expect(block.getText()).toBe('Block');
- expect(block.setText('Updated')).toBe(true);
- expect(body.getBlockRangeText(block.getKey())).toBe('Updated');
- expect(block.removeFromParent()).toBe(true);
- expect(document.save().body?.dataStream).toBe('Intro\rAfter\r\n');
- }
-
- univer.dispose();
- createDocumentFacade(createBlockRangeDocument());
- expect(document.getBody().getChild(0).asBlockRange().unwrap()).toBe(true);
- expect(document.save().body?.dataStream).toBe('After\r\n');
- });
-
- it('runs FDocTable APIs in Node', () => {
- univer.dispose();
- createDocumentFacade(createTableDocument());
-
- const body = document.getBody();
- const table = body.getChild(0).asTable();
-
- expect(table.getType()).toBe('table');
- expect(table.getKey()).toBe('table-1');
- expect(table.getParent()).toBe(body);
- expect(table.getTableId()).toBe('table-1');
- expect(body.getTable(table.getTableId()).tableId).toBe('table-1');
- expect(table.removeFromParent()).toBe(true);
- expect(document.save().body?.tables).toEqual([]);
-
- univer.dispose();
- createDocumentFacade(createTableDocument());
- expect(document.getBody().removeTable('table-1')).toBe(true);
- expect(document.save().body?.dataStream).toBe('aa\r\n');
- });
-
- it('runs FDocCustomBlock APIs in Node', () => {
- univer.dispose();
- createDocumentFacade(createCustomBlockDocument());
-
- const body = document.getBody();
- const customBlock = body.getChild(0).asCustomBlock();
-
- expect(customBlock.getType()).toBe('customBlock');
- expect(customBlock.getKey()).toBe('custom-1');
- expect(customBlock.getParent()).toBe(body);
- expect(customBlock.getBlockId()).toBe('custom-1');
- expect(body.getCustomBlock(customBlock.getBlockId()).blockId).toBe('custom-1');
- expect(customBlock.removeFromParent()).toBe(true);
- expect(document.save().body?.customBlocks).toEqual([]);
-
- univer.dispose();
- createDocumentFacade(createCustomBlockDocument());
- expect(document.getBody().removeCustomBlock('custom-1')).toBe(true);
- expect(document.save().body?.dataStream).toBe('\raa\r\n');
- });
-
- it('removes a generic element from its parent in Node', () => {
- univer.dispose();
- createDocumentFacade(createSimpleDocument());
-
- expect(document.getBody().getChild(0).removeFromParent()).toBe(true);
- expect(document.save().body?.dataStream).toBe('Beta\rGamma\r\n');
- });
-});
diff --git a/packages/docs/src/facade/__tests__/f-document.spec.ts b/packages/docs/src/facade/__tests__/f-document.spec.ts
new file mode 100644
index 0000000000..c89a136100
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-document.spec.ts
@@ -0,0 +1,146 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData, Univer } from '@univerjs/core';
+import type { FDocument } from '../f-document';
+import { IResourceManagerService, IUndoRedoService, UniverInstanceType } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createDocumentData, createSimpleDocument, createTestBed } from './create-test-bed';
+
+describe('FDocument', () => {
+ let univer: Univer;
+ let document: FDocument;
+ let get: ReturnType<typeof createTestBed>['get'];
+ let univerAPI: ReturnType<typeof createTestBed>['univerAPI'];
+
+ function createDocumentFacade(docData?: IDocumentData) {
+ const testBed = createTestBed(docData);
+ univer = testBed.univer;
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+ document = univerAPI.getActiveDocument()!;
+ }
+
+ beforeEach(() => {
+ createDocumentFacade();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should edit document text through append, insert and paragraph operations', () => {
+ expect(document.appendText('Univer')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,Univer\r\n');
+
+ univer.dispose();
+ createDocumentFacade();
+ expect(document.insertText('Docs', {
+ endOffset: 4,
+ segmentId: '',
+ startOffset: 2,
+ })).toBe(true);
+ expect(document.save().body?.dataStream).toBe('HeDocso,\r\n');
+
+ univer.dispose();
+ createDocumentFacade();
+ expect(document.insertParagraph('Line 1\nLine 2', {
+ endOffset: 6,
+ segmentId: '',
+ startOffset: 6,
+ })).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,Line 1\rLine 2\r\r\n');
+ });
+
+ it('should reject text append when the document has no body', () => {
+ univer.dispose();
+ createDocumentFacade({
+ id: 'test',
+ title: 'Test Document',
+ documentStyle: {},
+ });
+
+ expect(() => document.appendText('Univer')).toThrowError('The document body is empty');
+ });
+
+ it('should include current document resources in saved snapshots', () => {
+ const resourceManagerService = get(IResourceManagerService);
+
+ resourceManagerService.registerPluginResource({
+ pluginName: 'DOC_TEST_RESOURCE_PLUGIN',
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ onLoad: () => undefined,
+ onUnLoad: () => undefined,
+ toJson: () => '{"value":1}',
+ parseJson: (bytes) => JSON.parse(bytes),
+ });
+
+ expect(document.save().resources).toEqual([
+ {
+ name: 'DOC_TEST_RESOURCE_PLUGIN',
+ data: '{"value":1}',
+ },
+ ]);
+ });
+
+ it('should expose document identity and snapshot data from the active model', () => {
+ expect(document.getId()).toBe('test');
+ expect(document.getName()).toBe('');
+ expect(document.getDocumentDataModel().getUnitId()).toBe('test');
+ expect(document.save().body?.dataStream).toBe('Hello,\r\n');
+ });
+
+ it('should run undo and redo against the active document', () => {
+ get(IUndoRedoService);
+
+ expect(document.appendText('One')).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,One\r\n');
+
+ expect(document.undo()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,\r\n');
+
+ expect(document.redo()).toBe(true);
+ expect(document.save().body?.dataStream).toBe('Hello,One\r\n');
+ });
+
+ it('should preserve paragraph ids in saved snapshots and body wrappers', () => {
+ univer.dispose();
+ createDocumentFacade(createSimpleDocument());
+
+ const savedParagraphs = document.save().body?.paragraphs;
+ const body = document.getBody();
+ const paragraph = body.getChild(0).asParagraph();
+
+ expect(savedParagraphs?.map((item) => item.paragraphId)).toEqual(['para_alpha', 'para_beta', 'para_gamma']);
+ expect(savedParagraphs?.map((item) => item.startIndex)).toEqual([5, 10, 16]);
+ expect(paragraph.getId()).toBe('para_alpha');
+ expect(paragraph.getText()).toBe('Alpha');
+ });
+
+ it('should keep caller-provided paragraph ids when creating a body facade', () => {
+ univer.dispose();
+ createDocumentFacade(createDocumentData('doc-with-ids', {
+ dataStream: 'Legacy\r\n',
+ paragraphs: [{ startIndex: 6, paragraphId: 'para_fixture_26' }],
+ sectionBreaks: [{ startIndex: 7 }],
+ }));
+
+ const paragraph = document.getBody().getChild(0).asParagraph();
+
+ expect(paragraph.getId()).toBe('para_fixture_26');
+ expect(document.save().body?.paragraphs?.[0].paragraphId).toBe('para_fixture_26');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/f-univer.spec.ts b/packages/docs/src/facade/__tests__/f-univer.spec.ts
new file mode 100644
index 0000000000..d85b17349a
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/f-univer.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 { Univer } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createTestBed, DOCUMENT_STYLE } from './create-test-bed';
+
+describe('FUniver docs facade', () => {
+ let univer: Univer;
+ let univerAPI: ReturnType<typeof createTestBed>['univerAPI'];
+
+ beforeEach(() => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ univerAPI = testBed.univerAPI;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should create, focus and resolve document facades by document id', () => {
+ expect(univerAPI.getActiveDocument()?.getId()).toBe('test');
+ expect(univerAPI.getDocument('test')?.getId()).toBe('test');
+ expect(univerAPI.getDocument('missing-doc')).toBeNull();
+
+ const created = univerAPI.createDocument({
+ id: 'created-doc',
+ title: 'Created',
+ body: {
+ dataStream: 'Created\r\n',
+ paragraphs: [{ startIndex: 7, paragraphId: 'para_created' }],
+ },
+ documentStyle: DOCUMENT_STYLE,
+ });
+
+ expect(created.getId()).toBe('created-doc');
+ expect(created.getName()).toBe('Created');
+ expect(univerAPI.getDocument('created-doc')?.save().body?.dataStream).toBe('Created\r\n');
+ });
+});
diff --git a/packages/docs/src/facade/__tests__/utils.spec.ts b/packages/docs/src/facade/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..2c18b7b801
--- /dev/null
+++ b/packages/docs/src/facade/__tests__/utils.spec.ts
@@ -0,0 +1,63 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import {
+ buildPlainTextInsertBody,
+ getNormalizedPlainTextCursorOffset,
+ getParagraphStyleAtOffset,
+ getRemovedLeadingParagraphBreakLength,
+} from '../utils';
+
+describe('doc facade utils', () => {
+ it('should build normalized paragraph insert bodies with independent paragraph styles', () => {
+ const paragraphStyle = { horizontalAlign: 2 };
+ const body = buildPlainTextInsertBody('\nTitle\nBody\r\n', {
+ paragraphStyle,
+ removeLeadingParagraphBreak: true,
+ });
+
+ paragraphStyle.horizontalAlign = 1;
+
+ expect(body.dataStream).toBe('Title\rBody\r');
+ expect(body.paragraphs?.map((paragraph) => paragraph.startIndex)).toEqual([5, 10]);
+ expect(body.paragraphs?.[0].paragraphId).toMatch(/^para_/);
+ expect(body.paragraphs?.[1].paragraphId).toMatch(/^para_/);
+ expect(body.paragraphs?.[0].paragraphId).not.toBe(body.paragraphs?.[1].paragraphId);
+ expect(body.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(2);
+ });
+
+ it('should calculate cursor offsets after line ending normalization and leading break removal', () => {
+ expect(getRemovedLeadingParagraphBreakLength('\nTitle', true)).toBe(1);
+ expect(getRemovedLeadingParagraphBreakLength('\nTitle', false)).toBe(0);
+ expect(getNormalizedPlainTextCursorOffset('\nA\r\nB', 4, true)).toBe(2);
+ });
+
+ it('should reuse the paragraph style surrounding an insertion offset', () => {
+ const body: IDocumentBody = {
+ dataStream: 'A\rB\r\n',
+ paragraphs: [
+ { startIndex: 1, paragraphId: 'para_a', paragraphStyle: { horizontalAlign: 1 } },
+ { startIndex: 3, paragraphId: 'para_b', paragraphStyle: { horizontalAlign: 2 } },
+ ],
+ };
+
+ expect(getParagraphStyleAtOffset(body, 0)?.horizontalAlign).toBe(1);
+ expect(getParagraphStyleAtOffset(body, 2)?.horizontalAlign).toBe(2);
+ expect(getParagraphStyleAtOffset({ dataStream: '' }, 0)).toBeUndefined();
+ });
+});
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.ts
index 35854949d8..d7700ad3ad 100644
--- a/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts
+++ b/packages/docs/src/services/__tests__/doc-selection-manager.service.spec.ts
@@ -14,8 +14,21 @@
* limitations under the License.
*/
-import { CommandService, ConfigService, ContextService, DesktopLogService, ICommandService, IConfigService, IContextService, ILogService, Injector, IUniverInstanceService, UniverInstanceService } from '@univerjs/core';
+import {
+ CommandService,
+ ConfigService,
+ ContextService,
+ DesktopLogService,
+ ICommandService,
+ IConfigService,
+ IContextService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ UniverInstanceService,
+} from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import { SetTextSelectionsOperation } from '../../commands/operations/text-selection.operation';
import { DocSelectionManagerService } from '../doc-selection-manager.service';
function createService() {
@@ -26,6 +39,7 @@ function createService() {
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([DocSelectionManagerService]);
+ injector.get(ICommandService).registerCommand(SetTextSelectionsOperation);
return injector.get(DocSelectionManagerService);
}
@@ -51,6 +65,22 @@ describe('DocSelectionManagerService', () => {
expect(service.getDocRanges().map((range) => range.startOffset)).toEqual([1, 5]);
});
+ it('keeps empty selections inert until a document selection is current', () => {
+ const service = createService();
+
+ service.__TEST_ONLY_add([{ startOffset: 1, endOffset: 1, collapsed: true }] as never);
+ service.refreshSelection();
+ service.replaceTextRanges([{ startOffset: 2, endOffset: 2 }]);
+
+ expect(service.__getCurrentSelection()).toBeNull();
+ expect(service.getSelectionInfo()).toBeUndefined();
+ expect(service.getTextRanges()).toBeUndefined();
+ expect(service.getRectRanges()).toBeUndefined();
+ expect(service.getActiveTextRange()).toBeUndefined();
+ expect(service.getActiveRectRange()).toBeUndefined();
+ expect(service.getDocRanges()).toEqual([]);
+ });
+
it('publishes refresh selection requests for current document ranges', () => {
const service = createService();
const refreshes: unknown[] = [];
@@ -68,4 +98,33 @@ describe('DocSelectionManagerService', () => {
});
sub.unsubscribe();
});
+
+ it('replaces render selections, publishes them, and sorts text and rect ranges together', async () => {
+ const service = createService();
+ const selections: unknown[] = [];
+ const sub = service.textSelection$.subscribe((value) => selections.push(value));
+ service.__TEST_ONLY_setCurrentSelection({ unitId: 'doc-1', subUnitId: 'doc-1' });
+
+ service.__replaceTextRangesWithNoRefresh({
+ textRanges: [{ startOffset: 8, endOffset: 9, collapsed: false, isActive: false }],
+ rectRanges: [{ startOffset: 2, endOffset: 4, isActive: true }],
+ segmentId: 'header-1',
+ segmentPage: 0,
+ isEditing: true,
+ style: { stroke: 'red' },
+ } as never, { unitId: 'doc-1', subUnitId: 'doc-1' });
+
+ expect(service.getTextRanges()?.map((range) => range.startOffset)).toEqual([8]);
+ expect(service.getRectRanges()?.map((range) => range.startOffset)).toEqual([2]);
+ expect(service.getActiveRectRange()?.startOffset).toBe(2);
+ expect(service.getDocRanges().map((range) => range.startOffset)).toEqual([2, 8]);
+ expect(selections.at(-1)).toMatchObject({
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ segmentId: 'header-1',
+ isEditing: true,
+ });
+
+ sub.unsubscribe();
+ });
});
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.ts
index b08794ea74..bc67f680bc 100644
--- 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.ts
@@ -30,11 +30,17 @@ import {
LocalUndoRedoService,
UniverInstanceService,
} from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { DocStateChangeManagerService } from '../doc-state-change-manager.service';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DocStateChangeManagerService, IDocStateChangeInterceptorService } from '../doc-state-change-manager.service';
import { DocStateEmitService } from '../doc-state-emit.service';
-function createService() {
+class DropDocStateChangeInterceptorService {
+ transformChangeStateInfo() {
+ return null;
+ }
+}
+
+function createService(intercept = false) {
const injector = new Injector();
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([IConfigService, { useClass: ConfigService }]);
@@ -43,6 +49,9 @@ function createService() {
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);
injector.add([DocStateEmitService]);
+ if (intercept) {
+ injector.add([IDocStateChangeInterceptorService, { useClass: DropDocStateChangeInterceptorService }]);
+ }
injector.add([DocStateChangeManagerService]);
return {
service: injector.get(DocStateChangeManagerService),
@@ -53,19 +62,28 @@ function createService() {
}
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 = {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function createChange(overrides = {}) {
+ return {
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 }] },
+ ...overrides,
};
+ }
+
+ 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 = createChange();
emitter.emitStateChangeInfo(change);
@@ -82,4 +100,58 @@ describe('DocStateChangeManagerService', () => {
sub.unsubscribe();
});
+
+ it('filters sync or intercepted state changes without changing caches', () => {
+ const synced = createService();
+ synced.emitter.emitStateChangeInfo(createChange({ isSync: true }));
+ expect(synced.service.getStateCache('doc-1')).toEqual({ history: [], collaboration: [] });
+
+ const intercepted = createService(true);
+ intercepted.emitter.emitStateChangeInfo(createChange());
+ expect(intercepted.service.getStateCache('doc-1')).toEqual({ history: [], collaboration: [] });
+ });
+
+ it('keeps no-history changes out of undo and collaboration streams', () => {
+ const { service, emitter, undoRedoService } = createService();
+ const changes: unknown[] = [];
+ const sub = service.docStateChange$.subscribe((value) => changes.push(value));
+
+ emitter.emitStateChangeInfo(createChange({ noHistory: true }));
+
+ expect(undoRedoService.pitchTopUndoElement()).toBeNull();
+ expect(changes.at(-1)).toBeNull();
+ sub.unsubscribe();
+ });
+
+ it('debounces history and collaboration flushing for composed edits', () => {
+ vi.useFakeTimers();
+ const { service, emitter, undoRedoService } = createService();
+ const changes: unknown[] = [];
+ const sub = service.docStateChange$.subscribe((value) => changes.push(value));
+
+ emitter.emitStateChangeInfo(createChange({ debounce: true }));
+ expect(service.getStateCache('doc-1').history).toHaveLength(1);
+ expect(changes.at(-1)).toBeNull();
+
+ vi.advanceTimersByTime(300);
+
+ expect(service.getStateCache('doc-1')).toEqual({ history: [], collaboration: [] });
+ expect(changes.at(-1)).toMatchObject({ unitId: 'doc-1', debounce: true });
+ sub.unsubscribe();
+ });
+
+ it('can restore pre-existing state caches for a document', () => {
+ const { service } = createService();
+ const state = createChange();
+
+ service.setStateCache('doc-1', {
+ history: [state],
+ collaboration: [state],
+ });
+
+ expect(service.getStateCache('doc-1')).toEqual({
+ history: [state],
+ collaboration: [state],
+ });
+ });
});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx
new file mode 100644
index 0000000000..a2a5120472
--- /dev/null
+++ b/packages/drawing-ui/src/views/__tests__/DrawingCommandBehavior.spec.tsx
@@ -0,0 +1,220 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, ICommandInfo, IDrawingParam } from '@univerjs/core';
+import type { ReactElement } from 'react';
+import type { Root } from 'react-dom/client';
+import { CommandType, DrawingTypeEnum, ICommandService, LocaleType, Univer } 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 { AlignType, SetDrawingAlignOperation } from '../../commands/operations/drawing-align.operation';
+import { ImagePopupMenu } from '../image-popup-menu/ImagePopupMenu';
+import { DrawingAlign } from '../panel/DrawingAlign';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const unitId = 'drawing-command-unit';
+const subUnitId = 'drawing-command-subunit';
+const drawingId = 'image-1';
+const wrappingStyleCommandId = 'doc.command.update-doc-drawing-wrapping-style';
+const editCommandId = 'drawing.command.open-image-setting';
+
+function createDrawing(id: string): IDrawingParam {
+ return {
+ unitId,
+ subUnitId,
+ drawingId: id,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: {
+ left: 10,
+ top: 20,
+ width: 120,
+ height: 80,
+ angle: 0,
+ },
+ };
+}
+
+function createOperation(id: string): ICommand {
+ return {
+ id,
+ type: CommandType.OPERATION,
+ handler: () => 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 }));
+ });
+}
+
+async function flushPendingCommands(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ });
+}
+
+function findByText<T extends HTMLElement>(selector: string, text: string): T {
+ const element = Array.from(document.querySelectorAll<T>(selector))
+ .find((item) => item.textContent?.includes(text));
+ if (!element) {
+ throw new Error(`Element with text "${text}" was not found.`);
+ }
+
+ return element;
+}
+
+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 command behavior', () => {
+ let univer: Univer;
+ let commandService: ICommandService;
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+ let executedCommands: ICommandInfo[];
+
+ beforeEach(() => {
+ univer = new Univer({ locales: { [LocaleType.ZH_CN]: {} } });
+ commandService = univer.__getInjector().get(ICommandService);
+ commandService.registerCommand(SetDrawingAlignOperation);
+ commandService.registerCommand(createOperation(wrappingStyleCommandId));
+ commandService.registerCommand(createOperation(editCommandId));
+ executedCommands = [];
+ commandService.onCommandExecuted((command) => executedCommands.push(command));
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ univer.dispose();
+ });
+
+ it('executes align operation with the selected alignment and drawings', async () => {
+ const drawings = [createDrawing(drawingId), createDrawing('image-2')];
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <DrawingAlign alignShow drawings={drawings} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(document.querySelector('[data-u-comp="select"]')!);
+ clickElement(findByText('[role="menuitemradio"]', 'drawing-ui.image-panel.align.right'));
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([{
+ id: SetDrawingAlignOperation.id,
+ type: SetDrawingAlignOperation.type,
+ params: {
+ alignType: AlignType.right,
+ drawings,
+ },
+ }]);
+ });
+
+ it('updates doc image wrapping style with the current drawing identity', async () => {
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImagePopupMenu
+ popup={{
+ extraProps: {
+ variant: 'doc-floating-toolbar',
+ unitId,
+ subUnitId,
+ drawingId,
+ menuItems: [],
+ },
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(document.querySelector('[data-u-comp="doc-image-floating-toolbar"] button')!);
+ clickElement(findByText('button', 'drawing-ui.image-text-wrap.square'));
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([{
+ id: wrappingStyleCommandId,
+ type: CommandType.OPERATION,
+ params: {
+ unitId,
+ subUnitId,
+ drawings: [{ unitId, subUnitId, drawingId }],
+ wrappingStyle: 'wrapSquare',
+ },
+ }]);
+ });
+
+ it('executes edit command and hides the doc image floating toolbar', async () => {
+ const editParams = { unitId, subUnitId, drawingId, source: 'toolbar' };
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <ImagePopupMenu
+ popup={{
+ extraProps: {
+ variant: 'doc-floating-toolbar',
+ unitId,
+ subUnitId,
+ drawingId,
+ menuItems: [{
+ label: 'drawing-ui.image-popup.edit',
+ index: 0,
+ commandId: editCommandId,
+ commandParams: editParams,
+ disable: false,
+ }],
+ },
+ }}
+ />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(document.querySelectorAll('[data-u-comp="doc-image-floating-toolbar"] button')[1]);
+ await flushPendingCommands();
+
+ expect(executedCommands).toEqual([{
+ id: editCommandId,
+ type: CommandType.OPERATION,
+ params: editParams,
+ }]);
+ expect(document.querySelector('[data-u-comp="doc-image-floating-toolbar"]')).toBeNull();
+ });
+});
diff --git a/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.spec.tsx b/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.spec.tsx
new file mode 100644
index 0000000000..8b82d02d10
--- /dev/null
+++ b/packages/drawing-ui/src/views/__tests__/DrawingGroupBehavior.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 { IDrawingParam } from '@univerjs/core';
+import type { IDrawingGroupUpdateParam } from '@univerjs/drawing';
+import type { ReactElement } from 'react';
+import type { Root } from 'react-dom/client';
+import { DrawingTypeEnum, ICommandService, LocaleType, Univer } from '@univerjs/core';
+import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { IconManager, 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 { CancelDrawingGroupOperation, SetDrawingGroupOperation } from '../../commands/operations/drawing-group.operation';
+import { DrawingGroup } from '../panel/DrawingGroup';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const unitId = 'drawing-group-unit';
+const subUnitId = 'drawing-group-subunit';
+
+function createDrawing(drawingId: string, left: number, groupId?: string): IDrawingParam {
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ groupId,
+ transform: {
+ left,
+ top: 10,
+ width: 20,
+ height: 30,
+ angle: 0,
+ },
+ };
+}
+
+function createGroup(drawingId: string): IDrawingParam {
+ return {
+ unitId,
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: {
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 100,
+ angle: 0,
+ },
+ groupBaseBound: {
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 100,
+ },
+ };
+}
+
+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$,
+ }),
+ },
+ };
+ }
+}
+
+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 findButtonByText(text: string): HTMLButtonElement {
+ const button = Array.from(document.querySelectorAll<HTMLButtonElement>('button'))
+ .find((item) => item.textContent?.includes(text));
+ if (!button) {
+ throw new Error(`Button with text "${text}" was not found.`);
+ }
+
+ return button;
+}
+
+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('DrawingGroup behavior', () => {
+ let univer: Univer;
+ 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([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IconManager]);
+
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(SetDrawingGroupOperation);
+ commandService.registerCommand(CancelDrawingGroupOperation);
+ drawingManagerService = injector.get(IDrawingManagerService);
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ univer.dispose();
+ });
+
+ it('emits a group update that links every selected drawing to the new group', () => {
+ const drawings = [createDrawing('image-1', 0), createDrawing('image-2', 30)];
+ const groupUpdates: IDrawingGroupUpdateParam[][] = [];
+ drawingManagerService.featurePluginGroupUpdate$.subscribe((update) => groupUpdates.push(update));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <DrawingGroup hasGroup drawings={drawings} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(findButtonByText('drawing-ui.image-panel.group.group'));
+
+ expect(groupUpdates).toHaveLength(1);
+ const update = groupUpdates[0][0];
+ expect(update.parent).toMatchObject({
+ unitId,
+ subUnitId,
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: {
+ left: 0,
+ top: 10,
+ width: 50,
+ height: 30,
+ },
+ });
+ expect(update.children.map((drawing) => ({
+ drawingId: drawing.drawingId,
+ groupId: drawing.groupId,
+ }))).toEqual([
+ { drawingId: 'image-1', groupId: update.parent.drawingId },
+ { drawingId: 'image-2', groupId: update.parent.drawingId },
+ ]);
+ });
+
+ it('emits an ungroup update that detaches every child from the selected group', () => {
+ const group = createGroup('group-1');
+ const childA = createDrawing('image-1', 0, group.drawingId);
+ const childB = createDrawing('image-2', 30, group.drawingId);
+ const ungroupUpdates: IDrawingGroupUpdateParam[][] = [];
+ drawingManagerService.registerDrawingData(unitId, {
+ [subUnitId]: {
+ data: {
+ [group.drawingId]: group,
+ [childA.drawingId]: childA,
+ [childB.drawingId]: childB,
+ },
+ order: [group.drawingId, childA.drawingId, childB.drawingId],
+ },
+ });
+ drawingManagerService.featurePluginUngroupUpdate$.subscribe((update) => ungroupUpdates.push(update));
+
+ const rendered = renderWithRediContext(
+ univer.__getInjector(),
+ <DrawingGroup hasGroup drawings={[group]} />
+ );
+ root = rendered.root;
+ container = rendered.container;
+
+ clickElement(findButtonByText('drawing-ui.image-panel.group.unGroup'));
+
+ expect(ungroupUpdates).toHaveLength(1);
+ const update = ungroupUpdates[0][0];
+ expect(update.parent).toBe(group);
+ expect(update.children.map((drawing) => ({
+ drawingId: drawing.drawingId,
+ groupId: drawing.groupId,
+ }))).toEqual([
+ { drawingId: 'image-1', groupId: undefined },
+ { drawingId: 'image-2', groupId: undefined },
+ ]);
+ });
+});
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.ts
index f21fa1c871..b636d9998e 100644
--- 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.ts
@@ -19,7 +19,29 @@ 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 { RegisterFunctionMutation } from '../register-function.mutation';
+import { SetArrayFormulaDataMutation } from '../set-array-formula-data.mutation';
+import { RemoveDefinedNameMutation, SetDefinedNameMutation, SetDefinedNameMutationFactory } from '../set-defined-name.mutation';
+import { RemoveFeatureCalculationMutation, SetFeatureCalculationMutation } from '../set-feature-calculation.mutation';
+import {
+ SetCellFormulaDependencyCalculationMutation,
+ SetCellFormulaDependencyCalculationResultMutation,
+ SetFormulaCalculationNotificationMutation,
+ SetFormulaCalculationResultMutation,
+ SetFormulaCalculationStartMutation,
+ SetFormulaCalculationStopMutation,
+ SetFormulaDependencyCalculationMutation,
+ SetFormulaDependencyCalculationResultMutation,
+ SetFormulaStringBatchCalculationMutation,
+ SetFormulaStringBatchCalculationResultMutation,
+ SetQueryFormulaDependencyAllMutation,
+ SetQueryFormulaDependencyAllResultMutation,
+ SetQueryFormulaDependencyMutation,
+ SetQueryFormulaDependencyResultMutation,
+ SetTriggerFormulaCalculationStartMutation,
+} from '../set-formula-calculation.mutation';
+import { SetFormulaDataMutation } from '../set-formula-data.mutation';
+import { SetImageFormulaDataMutation } from '../set-image-formula-data.mutation';
import { RemoveSuperTableMutation, SetSuperTableMutation, SetSuperTableOptionMutation } from '../set-super-table.mutation';
describe('formula reference mutations', () => {
@@ -115,4 +137,68 @@ describe('formula reference mutations', () => {
expect(result).toBe(true);
expect(superTableService.getTableOptionMap().get('数据')).toBe(TableOptionType.DATA);
});
+
+ it('returns false for malformed defined-name mutations and restores existing values through undo factory', async () => {
+ await commandService.executeCommand(SetDefinedNameMutation.id, {
+ unitId: 'book-1',
+ id: 'name-1',
+ name: 'Original',
+ formulaOrRefString: 'Sheet1!A1',
+ hidden: true,
+ localSheetId: 'sheet-1',
+ formulaOrRefStringWithPrefix: '=Sheet1!A1',
+ });
+
+ const factoryAccessor = { get: () => definedNamesService };
+
+ expect(SetDefinedNameMutationFactory(factoryAccessor as never, { unitId: 'book-1', id: 'name-1' } as never)).toEqual({
+ id: 'name-1',
+ unitId: 'book-1',
+ name: 'Original',
+ formulaOrRefString: 'Sheet1!A1',
+ comment: undefined,
+ hidden: true,
+ localSheetId: 'sheet-1',
+ formulaOrRefStringWithPrefix: '=Sheet1!A1',
+ });
+ expect(SetDefinedNameMutationFactory(factoryAccessor as never, { unitId: 'book-1', id: 'missing' } as never)).toBeNull();
+ expect(SetDefinedNameMutation.handler(commandService as never, null as never)).toBe(false);
+ expect(RemoveDefinedNameMutation.handler(commandService as never, null as never)).toBe(false);
+ expect(definedNamesService.getValueById('book-1', 'name-1')).toMatchObject({
+ name: 'Original',
+ formulaOrRefString: 'Sheet1!A1',
+ hidden: true,
+ });
+ });
+
+ it('keeps RPC-only formula mutations as successful command messages', () => {
+ const accessor = {} as never;
+ const statelessMutations = [
+ RegisterFunctionMutation,
+ SetArrayFormulaDataMutation,
+ SetFormulaDataMutation,
+ SetImageFormulaDataMutation,
+ SetFeatureCalculationMutation,
+ RemoveFeatureCalculationMutation,
+ SetFormulaCalculationStartMutation,
+ SetTriggerFormulaCalculationStartMutation,
+ SetFormulaStringBatchCalculationMutation,
+ SetFormulaStringBatchCalculationResultMutation,
+ SetFormulaCalculationStopMutation,
+ SetFormulaCalculationNotificationMutation,
+ SetFormulaCalculationResultMutation,
+ SetFormulaDependencyCalculationMutation,
+ SetFormulaDependencyCalculationResultMutation,
+ SetCellFormulaDependencyCalculationMutation,
+ SetCellFormulaDependencyCalculationResultMutation,
+ SetQueryFormulaDependencyMutation,
+ SetQueryFormulaDependencyResultMutation,
+ SetQueryFormulaDependencyAllMutation,
+ SetQueryFormulaDependencyAllResultMutation,
+ ];
+
+ expect(statelessMutations.map((mutation) => mutation.handler(accessor, {} as never))).toEqual(
+ statelessMutations.map(() => true)
+ );
+ });
});
diff --git a/packages/engine-formula/src/services/__tests__/active-dirty-manager.service.spec.ts b/packages/engine-formula/src/services/__tests__/active-dirty-manager.service.spec.ts
index c0a6c8a6b1..e39ed7dace 100644
--- a/packages/engine-formula/src/services/__tests__/active-dirty-manager.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/active-dirty-manager.service.spec.ts
@@ -43,4 +43,26 @@ describe('ActiveDirtyManagerService', () => {
service.remove(converter.commandId);
expect(service.has(converter.commandId)).toBe(false);
});
+
+ it('exposes and clears the registered converter map on dispose', () => {
+ const converter = {
+ commandId: 'sheet.command.insert-row',
+ getDirtyData: () => ({
+ dirtyRanges: [{
+ unitId: 'book-1',
+ sheetId: 'sheet-1',
+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 9 },
+ }],
+ }),
+ };
+
+ expect(service.get('missing')).toBeUndefined();
+ service.register(converter.commandId, converter);
+
+ expect(service.getDirtyConversionMap().get(converter.commandId)).toBe(converter);
+
+ service.dispose();
+ expect(service.getDirtyConversionMap().size).toBe(0);
+ expect(service.has(converter.commandId)).toBe(false);
+ });
});
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.ts
index d9d317824b..af8ece9c96 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
@@ -26,6 +26,25 @@ class TestDependencyManagerBaseService extends DependencyManagerBaseService {
}
}
+class TestBuildDependencyManagerService extends DependencyManagerService {
+ trees: FormulaDependencyTree[] = [];
+
+ override getAllTree() {
+ return this.trees;
+ }
+
+ override getTreeById(treeId: number) {
+ return this.trees.find((tree) => tree.treeId === treeId);
+ }
+
+ override updateDependencyTreeDirtyState(treeId: number, isDirty: boolean): void {
+ const tree = this.getTreeById(treeId);
+ if (tree) {
+ tree.isDirty = isDirty;
+ }
+ }
+}
+
function createTree(treeId: number, row: number, column: number) {
const tree = new FormulaDependencyTree(treeId);
tree.unitId = 'unit-1';
@@ -64,6 +83,22 @@ describe('DependencyManagerService', () => {
expect(service.hasOtherFormulaDataMainData('feature-formula')).toBe(true);
expect(service.getLastTreeId()).toBe(0);
expect(service.getLastTreeId()).toBe(1);
+ expect(service.getOtherFormulaDependency('missing', 'sheet-1', 'f-1')).toBeUndefined();
+ expect(service.getFeatureFormulaDependency('missing', 'sheet-1', 'feature-1')).toBeUndefined();
+ expect(service.getFormulaDependency('missing', 'sheet-1', 0, 0)).toBeUndefined();
+ expect(() => service.reset()).toThrow('Method not implemented.');
+ expect(() => service.getTreeById(1)).toThrow('Method not implemented.');
+ expect(() => service.getAllTree()).toThrow('Method not implemented.');
+ expect(() => service.addOtherFormulaDependency('u', 's', 'f', createTree(1, 0, 0))).toThrow('Method not implemented.');
+ expect(() => service.removeOtherFormulaDependency('u', 's', ['f'])).toThrow('Method not implemented.');
+ expect(() => service.clearOtherFormulaDependency('u')).toThrow('Method not implemented.');
+ expect(() => service.addFeatureFormulaDependency('u', 's', 'f', createTree(2, 0, 0))).toThrow('Method not implemented.');
+ expect(() => service.removeFeatureFormulaDependency('u', 's', ['f'])).toThrow('Method not implemented.');
+ expect(() => service.clearFeatureFormulaDependency('u')).toThrow('Method not implemented.');
+ expect(() => service.addFormulaDependency('u', 's', 0, 0, createTree(3, 0, 0))).toThrow('Method not implemented.');
+ expect(() => service.removeFormulaDependency('u', 's', 0, 0)).toThrow('Method not implemented.');
+ expect(() => service.clearFormulaDependency('u')).toThrow('Method not implemented.');
+ expect(() => service.updateDependencyTreeDirtyState(1, true)).toThrow('Method not implemented.');
});
it('should track formula dependencies and remove their search cache by location', () => {
@@ -132,6 +167,32 @@ describe('DependencyManagerService', () => {
expect(service.hasOtherFormulaDataMainData('f-1')).toBe(false);
});
+ it('should clear other-formula dependencies for a sheet or an entire workbook', () => {
+ const service = createService();
+ const treeA = createTree(11, 0, 0);
+ const treeB = createTree(12, 1, 1);
+ treeA.refOffsetX = 0;
+ treeA.refOffsetY = 0;
+ treeB.refOffsetX = 1;
+ treeB.refOffsetY = 1;
+
+ service.addOtherFormulaDependency('unit-1', 'sheet-1', 'f-1', treeA);
+ service.addOtherFormulaDependency('unit-1', 'sheet-2', 'f-2', treeB);
+ service.addDependencyRTreeCache(treeA);
+ service.addDependencyRTreeCache(treeB);
+ service.addOtherFormulaDependencyMainData('f-1');
+ service.addOtherFormulaDependencyMainData('f-2');
+
+ service.clearOtherFormulaDependency('unit-1', 'sheet-1');
+ expect(service.getOtherFormulaDependency('unit-1', 'sheet-1', 'f-1')?.getValue(0, 0)).toBeUndefined();
+ expect(service.getOtherFormulaDependency('unit-1', 'sheet-2', 'f-2')?.getValue(1, 1)).toBe(12);
+ expect(service.hasOtherFormulaDataMainData('f-1')).toBe(false);
+
+ service.clearOtherFormulaDependency('unit-1');
+ expect(service.getOtherFormulaDependency('unit-1', 'sheet-2', 'f-2')).toBeUndefined();
+ expect(service.hasOtherFormulaDataMainData('f-2')).toBe(false);
+ });
+
it('should manage feature formula dependencies', () => {
const service = createService();
const tree = createTree(20, 2, 2);
@@ -143,6 +204,24 @@ describe('DependencyManagerService', () => {
expect(service.getFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a')).toBeUndefined();
});
+ it('should clear feature dependencies by sheet or workbook', () => {
+ const service = createService();
+ const treeA = createTree(21, 2, 2);
+ const treeB = createTree(22, 3, 3);
+
+ service.addFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a', treeA);
+ service.addFeatureFormulaDependency('unit-1', 'sheet-2', 'feature-b', treeB);
+ service.addDependencyRTreeCache(treeA);
+ service.addDependencyRTreeCache(treeB);
+
+ service.clearFeatureFormulaDependency('unit-1', 'sheet-1');
+ expect(service.getFeatureFormulaDependency('unit-1', 'sheet-1', 'feature-a')).toBeUndefined();
+ expect(service.getFeatureFormulaDependency('unit-1', 'sheet-2', 'feature-b')).toBe(22);
+
+ service.clearFeatureFormulaDependency('unit-1');
+ expect(service.getFeatureFormulaDependency('unit-1', 'sheet-2', 'feature-b')).toBeUndefined();
+ });
+
it('should clear dependencies by defined name', () => {
const service = createService();
const tree = createTree(30, 3, 3);
@@ -195,4 +274,71 @@ describe('DependencyManagerService', () => {
])).toEqual(new Set());
expect(service.getLastTreeId()).toBe(0);
});
+
+ it('should clear formula dependencies across the whole workbook and dispose cached state', () => {
+ const service = createService();
+ const treeA = createTree(70, 7, 7);
+ const treeB = createTree(71, 8, 8);
+
+ service.addFormulaDependency('unit-1', 'sheet-1', 7, 7, treeA);
+ service.addFormulaDependency('unit-1', 'sheet-2', 8, 8, treeB);
+ service.addDependencyRTreeCache(treeA);
+ service.addDependencyRTreeCache(treeB);
+
+ service.clearFormulaDependency('unit-1');
+ expect(service.getFormulaDependency('unit-1', 'sheet-1', 7, 7)).toBeUndefined();
+ expect(service.getFormulaDependency('unit-1', 'sheet-2', 8, 8)).toBeUndefined();
+
+ service.addDependencyRTreeCache(treeA);
+ service.openKdTree();
+ service.closeKdTree();
+ service.dispose();
+ expect(service.searchDependency([{
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ range: {
+ startRow: 7,
+ startColumn: 7,
+ endRow: 7,
+ endColumn: 8,
+ },
+ }])).toEqual(new Set());
+ });
+
+ it('should build dependency relationships for selected trees and reverse dependencies for all trees', () => {
+ const injector = new Injector();
+ injector.add([TestBuildDependencyManagerService]);
+ const service = injector.get(TestBuildDependencyManagerService);
+ const parent = createTree(80, 1, 1);
+ const child = createTree(81, 0, 0);
+ parent.rangeList = [{
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ }];
+ service.trees = [parent, child];
+ service.addDependencyRTreeCache(parent);
+
+ expect(service.buildDependencyTree([parent])).toEqual([parent, child]);
+
+ service.updateDependencyTreeDirtyState(parent.treeId, true);
+ expect(service.getTreeById(parent.treeId)?.isDirty).toBe(true);
+ });
+
+ it('should build reverse dependencies when no selected trees are provided', () => {
+ const injector = new Injector();
+ injector.add([TestBuildDependencyManagerService]);
+ const service = injector.get(TestBuildDependencyManagerService);
+ const parent = createTree(90, 1, 1);
+ const child = createTree(91, 0, 0);
+ parent.rangeList = [{
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ }];
+ service.trees = [parent, child];
+ service.addDependencyRTreeCache(parent);
+
+ expect(service.buildDependencyTree([], [child])).toEqual([parent, child]);
+ });
});
diff --git a/packages/engine-formula/src/services/__tests__/feature-calculation-manager.service.spec.ts b/packages/engine-formula/src/services/__tests__/feature-calculation-manager.service.spec.ts
index b6fc746f0a..55c2e57f36 100644
--- a/packages/engine-formula/src/services/__tests__/feature-calculation-manager.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/feature-calculation-manager.service.spec.ts
@@ -38,12 +38,49 @@ describe('FeatureCalculationManagerService', () => {
};
service.register('book-1', 'sheet-1', 'sparkline-1', executor as never);
+ expect(service.has('book-1', 'sheet-1', 'sparkline-1')).toBe(true);
+ expect(service.get('book-1', 'sheet-1', 'sparkline-1')).toBe(executor);
+ expect(service.getReferenceExecutorMap().get('book-1')?.get('sheet-1')?.get('sparkline-1')).toBe(executor);
+
service.remove('book-1', 'sheet-1', ['sparkline-1']);
expect(service.get('book-1', 'sheet-1', 'sparkline-1')).toBeUndefined();
+ expect(service.has('book-1', 'sheet-1', 'sparkline-1')).toBe(false);
+ expect(service.has('missing', 'sheet-1', 'sparkline-1')).toBe(false);
+ expect(service.has('book-1', 'missing', 'sparkline-1')).toBe(false);
expect(changes).toEqual([
{ unitId: 'book-1', subUnitId: 'sheet-1', featureIds: ['sparkline-1'] },
{ unitId: 'book-1', subUnitId: 'sheet-1', featureIds: ['sparkline-1'] },
]);
});
+
+ it('keeps feature maps isolated per sheet and releases them on dispose', () => {
+ const executorA = {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ dependencyRanges: [],
+ getDirtyData: () => ({ runtimeCellData: {}, dirtyRanges: {} }),
+ };
+ const executorB = {
+ unitId: 'book-1',
+ subUnitId: 'sheet-2',
+ dependencyRanges: [],
+ getDirtyData: () => ({ runtimeCellData: {}, dirtyRanges: {} }),
+ };
+ const changes: unknown[] = [];
+
+ service.onChanged$.subscribe((change) => changes.push(change));
+ service.register('book-1', 'sheet-1', 'feature-1', executorA as never);
+ service.register('book-1', 'sheet-2', 'feature-1', executorB as never);
+
+ expect(service.get('book-1', 'sheet-1', 'feature-1')).toBe(executorA);
+ expect(service.get('book-1', 'sheet-2', 'feature-1')).toBe(executorB);
+
+ service.dispose();
+ expect(service.getReferenceExecutorMap().size).toBe(0);
+ expect(changes).toEqual([
+ { unitId: 'book-1', subUnitId: 'sheet-1', featureIds: ['feature-1'] },
+ { unitId: 'book-1', subUnitId: 'sheet-2', featureIds: ['feature-1'] },
+ ]);
+ });
});
diff --git a/packages/engine-formula/src/services/__tests__/hyperlink-engine-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/hyperlink-engine-formula.service.spec.ts
index 68f3ebb8ed..c37ecbdf3a 100644
--- a/packages/engine-formula/src/services/__tests__/hyperlink-engine-formula.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/hyperlink-engine-formula.service.spec.ts
@@ -23,7 +23,9 @@ describe('HyperlinkEngineFormulaService', () => {
beforeEach(() => {
const injector = new Injector();
- injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);
+ class TestUniverInstanceService {}
+
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);
service = injector.get(IHyperlinkEngineFormulaService);
});
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.ts
index db9117b304..999b599a6c 100644
--- a/packages/engine-render/src/services/__tests__/canvas-color.service.spec.ts
+++ b/packages/engine-render/src/services/__tests__/canvas-color.service.spec.ts
@@ -16,7 +16,14 @@
import { Injector, ThemeService } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import { CanvasColorService, DumbCanvasColorService, ICanvasColorService } from '../canvas-color.service';
+import {
+ CanvasColorService,
+ DumbCanvasColorService,
+ getDarkRenderColorOverride,
+ hexToRgb,
+ ICanvasColorService,
+ rgbToHex,
+} from '../canvas-color.service';
describe('CanvasColorService', () => {
it('keeps render colors unchanged in light mode', () => {
@@ -37,6 +44,42 @@ describe('CanvasColorService', () => {
expect(injector.get(ICanvasColorService).getRenderColor('rgba(37, 99, 235, 0.08)')).toBe('rgba(96,165,250,0.22)');
});
+ it('inverts supported color syntaxes in dark mode and caches the render result', () => {
+ const injector = new Injector();
+ injector.add([ThemeService]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.get(ThemeService).setDarkMode(true);
+ const service = injector.get(ICanvasColorService);
+
+ const shortHex = service.getRenderColor('#abc');
+ expect(shortHex).toMatch(/^#[0-9a-f]{6}$/);
+ expect(service.getRenderColor('#abcd')).toMatch(/^#[0-9a-f]{8}$/);
+ expect(service.getRenderColor('#abcdef99')).toMatch(/^#[0-9a-f]{8}$/);
+ expect(service.getRenderColor('rgb(1, 2, 3)')).toMatch(/^rgb\(\d+,\d+,\d+\)$/);
+ expect(service.getRenderColor('rgba(1, 2, 3, 0.5)')).toMatch(/^rgba\(\d+,\d+,\d+, 0.5\)$/);
+ expect(service.getRenderColor('transparent')).toBe('transparent');
+ expect(service.getRenderColor('transparent')).toBe('transparent');
+ expect(service.getRenderColor('red')).toEqual(expect.anything());
+ expect(service.getRenderColor('#abc')).toBe(shortHex);
+ });
+
+ it('reports dark overrides and color conversion helpers used by renderers', () => {
+ expect(getDarkRenderColorOverride(' RGBA(37, 99, 235, 0.08) ')).toBe('rgba(96,165,250,0.22)');
+ expect(getDarkRenderColorOverride('#ffffff')).toBeNull();
+ expect(hexToRgb('#abc')).toEqual([170, 187, 204]);
+ expect(hexToRgb('#abcdef')).toEqual([171, 205, 239]);
+ expect(rgbToHex([1.2, 15.5, 255])).toBe('#0110ff');
+ });
+
+ it('throws for colors that renderers cannot parse in dark mode', () => {
+ const injector = new Injector();
+ injector.add([ThemeService]);
+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);
+ injector.get(ThemeService).setDarkMode(true);
+
+ expect(() => injector.get(ICanvasColorService).getRenderColor('not-a-color-token')).toThrow('[CanvasColorService]: illegal color');
+ });
+
it('provides a dumb color service for render contexts that should not transform colors', () => {
const injector = new Injector();
injector.add([ICanvasColorService, { useClass: DumbCanvasColorService }]);
diff --git a/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx b/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx
index e4a0f875fe..231979c4d0 100644
--- a/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx
+++ b/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx
@@ -488,6 +488,36 @@ describe('FindReplaceDialog', () => {
expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 1, matchesPosition: 1 });
expect(readCurrentMatch(testBed.findReplaceService)?.range).toEqual({ id: 'A3' });
});
+
+ it('warns and keeps replace actions disabled when a replace dialog search has no 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], 'kiwi');
+ setInputValue(inputs[1], 'orange');
+ getButton(container!, FIND_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ });
+ await flushSearch();
+
+ expect(testBed.provider.queries.at(-1)).toMatchObject({
+ findString: 'kiwi',
+ replaceRevealed: true,
+ });
+ expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 0, matchesPosition: 0 });
+ expect(readCurrentMatch(testBed.findReplaceService)).toBeNull();
+ expect((testBed.get(IMessageService) as TestMessageService).messages.at(-1)?.content).toBe('find-replace.dialog.no-match');
+ expect(getButton(container!, REPLACE_LABEL).disabled).toBe(true);
+ expect(getButton(container!, REPLACE_ALL_LABEL).disabled).toBe(true);
+ expect(testBed.provider.rows.map((row) => row.text)).toEqual(INITIAL_ROWS.map((row) => row.text));
+ });
});
function readState(findReplaceService: IFindReplaceService): IFindReplaceState {
diff --git a/packages/network/src/services/http/__testing__/headers.spec.ts b/packages/network/src/services/http/__testing__/headers.spec.ts
new file mode 100644
index 0000000000..f6721b3ddd
--- /dev/null
+++ b/packages/network/src/services/http/__testing__/headers.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 { describe, expect, it } from 'vitest';
+import { HTTPHeaders, isApplicationJSONType } from '../headers';
+
+describe('HTTPHeaders', () => {
+ it('normalizes constructor headers and keeps repeated values', () => {
+ const headers = new HTTPHeaders({
+ Accept: 'text/plain',
+ 'X-Retry': 1,
+ 'X-Enabled': true,
+ });
+
+ headers.set('x-retry', 2);
+
+ expect(headers.has('ACCEPT')).toBe(true);
+ expect(headers.get('accept')).toEqual(['text/plain']);
+ expect(headers.get('x-retry')).toEqual(['1', '2']);
+ expect(headers.get('missing')).toBeNull();
+ });
+
+ it('parses browser Headers and raw header strings into fetch init values', () => {
+ const browserHeaders = new Headers();
+ browserHeaders.set('X-Token', 'abc');
+ const fromBrowser = new HTTPHeaders(browserHeaders);
+ const fromString = new HTTPHeaders('Content-Type: text/plain\nX-Trace: trace-1\nBroken');
+ const seen: Array<[string, string[]]> = [];
+
+ fromBrowser.forEach((name, value) => seen.push([name, value]));
+
+ expect(seen).toEqual([['x-token', ['abc']]]);
+ expect(fromString.toHeadersInit()).toEqual({
+ 'content-type': ' text/plain',
+ 'x-trace': ' trace-1',
+ accept: 'application/json, text/plain, */*',
+ });
+ });
+
+ it('adds default JSON headers except for FormData bodies', () => {
+ expect(new HTTPHeaders().toHeadersInit()).toEqual({
+ accept: 'application/json, text/plain, */*',
+ 'content-type': 'application/json;charset=UTF-8',
+ });
+ expect(new HTTPHeaders().toHeadersInit(new FormData())).toEqual({
+ accept: 'application/json, text/plain, */*',
+ });
+ });
+
+ it('detects JSON content types in string or array forms', () => {
+ expect(isApplicationJSONType('application/json; charset=utf-8')).toBe(true);
+ expect(isApplicationJSONType(['text/plain', 'application/json'])).toBe(true);
+ expect(isApplicationJSONType('text/plain')).toBe(false);
+ });
+});
diff --git a/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts b/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts
index 7d1f4a6d86..17e1bd8217 100644
--- a/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts
+++ b/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts
@@ -25,6 +25,15 @@ afterEach(() => {
});
describe('FetchHTTPImplementation', () => {
+ function createRequest(responseType: string, extra: Record<string, unknown> = {}) {
+ return new HTTPRequest('GET', 'https://example.com', {
+ responseType,
+ headers: new HTTPHeaders(),
+ withCredentials: false,
+ ...extra,
+ } as any);
+ }
+
it('should emit HTTPResponse for json response', async () => {
const body = new ReadableStream({
start(controller) {
@@ -93,4 +102,99 @@ describe('FetchHTTPImplementation', () => {
expect(events.some((e) => e.type === 0)).toBe(true);
expect(events.at(-1).body).toBe('ab');
});
+
+ it('should deserialize text, blob, and arraybuffer bodies', async () => {
+ const impl = new FetchHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('plain', {
+ status: 200,
+ headers: { 'content-type': 'text/plain' },
+ })));
+ await expect(new Promise<any>((resolve, reject) => {
+ impl.send(createRequest('text')).subscribe({ next: resolve, error: reject });
+ })).resolves.toMatchObject({ body: 'plain' });
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('blob-body', {
+ status: 200,
+ headers: { 'content-type': 'text/plain' },
+ })));
+ const blobResponse = await new Promise<any>((resolve, reject) => {
+ impl.send(createRequest('blob')).subscribe({ next: resolve, error: reject });
+ });
+ expect(blobResponse.body).toBeInstanceOf(Blob);
+ expect(await blobResponse.body.text()).toBe('blob-body');
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(new Uint8Array([1, 2, 3]), {
+ status: 200,
+ headers: { 'content-type': 'application/octet-stream' },
+ })));
+ const arrayBufferResponse = await new Promise<any>((resolve, reject) => {
+ impl.send(createRequest('arraybuffer')).subscribe({ next: resolve, error: reject });
+ });
+ expect(Array.from(new Uint8Array(arrayBufferResponse.body))).toEqual([1, 2, 3]);
+ });
+
+ it('should emit a null body when the response has no stream', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(null, { status: 204, statusText: 'No Content' })));
+
+ const impl = new FetchHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+
+ await expect(new Promise<any>((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ })).resolves.toMatchObject({ status: 204, statusText: 'No Content', body: null });
+ });
+
+ it('should emit HTTPResponseError for failed status, bad JSON, unknown response type, and fetch rejection', async () => {
+ const logService = { debug: vi.fn(), error: vi.fn() };
+ const impl = new FetchHTTPImplementation(logService as any);
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ message: 'bad' }), {
+ status: 500,
+ statusText: 'Server Error',
+ headers: { 'content-type': 'application/json' },
+ })));
+ await expect(new Promise((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ })).rejects.toMatchObject({ status: 500, statusText: 'Server Error' });
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('{bad', {
+ status: 200,
+ statusText: 'OK',
+ headers: { 'content-type': 'application/json' },
+ })));
+ await expect(new Promise((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ })).rejects.toMatchObject({ status: 200, statusText: 'OK' });
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response('body', {
+ status: 200,
+ statusText: 'OK',
+ })));
+ await expect(new Promise((resolve, reject) => {
+ impl.send(createRequest('document')).subscribe({ next: resolve, error: reject });
+ })).rejects.toMatchObject({ status: 200, statusText: 'OK' });
+
+ vi.stubGlobal('fetch', vi.fn(async () => {
+ throw Object.assign(new Error('offline'), { status: 0, statusText: 'Offline' });
+ }));
+ await expect(new Promise((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ })).rejects.toMatchObject({ status: 0, statusText: 'Offline' });
+ expect(logService.error).toHaveBeenCalled();
+ });
+
+ it('should abort the fetch request when unsubscribed', () => {
+ let capturedSignal: AbortSignal | undefined;
+ vi.stubGlobal('fetch', vi.fn((_url: string, init: RequestInit) => {
+ capturedSignal = init.signal as AbortSignal;
+ return new Promise(() => {});
+ }));
+
+ const impl = new FetchHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+ const subscription = impl.send(createRequest('json')).subscribe();
+
+ expect(capturedSignal?.aborted).toBe(false);
+ subscription.unsubscribe();
+ expect(capturedSignal?.aborted).toBe(true);
+ });
});
diff --git a/packages/network/src/services/http/implementations/__tests__/xhr.spec.ts b/packages/network/src/services/http/implementations/__tests__/xhr.spec.ts
new file mode 100644
index 0000000000..f291aabb9b
--- /dev/null
+++ b/packages/network/src/services/http/implementations/__tests__/xhr.spec.ts
@@ -0,0 +1,201 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { HTTPHeaders } from '../../headers';
+import { HTTPParams } from '../../params';
+import { HTTPRequest } from '../../request';
+import { XHRHTTPImplementation } from '../xhr';
+
+type Listener = (event: ProgressEvent) => void;
+
+const xhrInstances: FakeXMLHttpRequest[] = [];
+
+class FakeXMLHttpRequest {
+ DONE = 4;
+ readyState = 1;
+ status = 200;
+ statusText = 'OK';
+ responseType = '';
+ response: unknown;
+ responseText = '';
+ withCredentials = false;
+ method = '';
+ url = '';
+ sentBody: unknown;
+ aborted = false;
+ headers = new Map<string, string>();
+ removed: Array<[string, Listener]> = [];
+ private _listeners = new Map<string, Listener[]>();
+
+ constructor() {
+ xhrInstances.push(this);
+ }
+
+ open(method: string, url: string): void {
+ this.method = method;
+ this.url = url;
+ }
+
+ setRequestHeader(key: string, value: string): void {
+ this.headers.set(key, value);
+ }
+
+ getAllResponseHeaders(): string {
+ return 'Content-Type: application/json\nX-Trace: trace-1';
+ }
+
+ addEventListener(type: string, listener: Listener): void {
+ const listeners = this._listeners.get(type) ?? [];
+ listeners.push(listener);
+ this._listeners.set(type, listeners);
+ }
+
+ removeEventListener(type: string, listener: Listener): void {
+ this.removed.push([type, listener]);
+ this._listeners.set(type, (this._listeners.get(type) ?? []).filter((item) => item !== listener));
+ }
+
+ send(body: unknown): void {
+ this.sentBody = body;
+ }
+
+ abort(): void {
+ this.aborted = true;
+ this.readyState = this.DONE;
+ this.emit('abort');
+ }
+
+ emit(type: string): void {
+ (this._listeners.get(type) ?? []).forEach((listener) => listener(new ProgressEvent(type)));
+ }
+}
+
+function createRequest(responseType: string, extra: Record<string, unknown> = {}) {
+ return new HTTPRequest('POST', 'https://example.com/api', {
+ responseType,
+ withCredentials: true,
+ headers: new HTTPHeaders({ 'X-Test': 'yes' }),
+ params: new HTTPParams({ q: 'search' }),
+ body: { ok: true },
+ ...extra,
+ } as any);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ xhrInstances.length = 0;
+});
+
+describe('XHRHTTPImplementation', () => {
+ it('sends requests with headers, credentials and JSON body, then parses JSON responses', async () => {
+ vi.stubGlobal('XMLHttpRequest', FakeXMLHttpRequest as never);
+ const impl = new XHRHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+ const events: any[] = [];
+ const promise = new Promise<void>((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({
+ next: (event) => {
+ events.push(event);
+ resolve();
+ },
+ error: reject,
+ });
+ });
+ const xhr = xhrInstances[0];
+
+ xhr.responseText = '{"ok":true}';
+ xhr.emit('load');
+ await promise;
+
+ expect(xhr.method).toBe('POST');
+ expect(xhr.url).toBe('https://example.com/api?q=search');
+ expect(xhr.withCredentials).toBe(true);
+ expect(xhr.headers.get('x-test')).toBe('yes');
+ expect(xhr.headers.get('content-type')).toBe('application/json;charset=UTF-8');
+ expect(xhr.sentBody).toBe('{"ok":true}');
+ expect(events.at(-1).body).toEqual({ ok: true });
+ });
+
+ it('returns null for no-content responses and raw text for text responses', async () => {
+ vi.stubGlobal('XMLHttpRequest', FakeXMLHttpRequest as never);
+ const impl = new XHRHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+
+ const noContentPromise = new Promise<any>((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ });
+ xhrInstances[0].status = 204;
+ xhrInstances[0].responseText = '{"ignored":true}';
+ xhrInstances[0].emit('load');
+ await expect(noContentPromise).resolves.toMatchObject({ body: null });
+
+ const textPromise = new Promise<any>((resolve, reject) => {
+ impl.send(createRequest('text')).subscribe({ next: resolve, error: reject });
+ });
+ xhrInstances[1].responseText = 'plain';
+ xhrInstances[1].emit('load');
+ await expect(textPromise).resolves.toMatchObject({ body: 'plain' });
+ });
+
+ it('emits response errors for status errors, invalid JSON, blob mismatches, and network failures', async () => {
+ const logService = { debug: vi.fn(), error: vi.fn() };
+ vi.stubGlobal('XMLHttpRequest', FakeXMLHttpRequest as never);
+ const impl = new XHRHTTPImplementation(logService as any);
+
+ const statusError = new Promise((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ });
+ xhrInstances[0].status = 500;
+ xhrInstances[0].statusText = 'Server Error';
+ xhrInstances[0].responseText = '{"ok":false}';
+ xhrInstances[0].emit('load');
+ await expect(statusError).rejects.toMatchObject({ status: 500, statusText: 'Server Error' });
+
+ const jsonError = new Promise((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ });
+ xhrInstances[1].responseText = '{bad';
+ xhrInstances[1].emit('load');
+ await expect(jsonError).rejects.toMatchObject({ status: 200, statusText: 'OK' });
+
+ const blobError = new Promise((resolve, reject) => {
+ impl.send(createRequest('blob')).subscribe({ next: resolve, error: reject });
+ });
+ xhrInstances[2].response = 'not-a-blob';
+ xhrInstances[2].emit('load');
+ await expect(blobError).rejects.toMatchObject({ status: 200, statusText: 'OK' });
+
+ const networkError = new Promise((resolve, reject) => {
+ impl.send(createRequest('json')).subscribe({ next: resolve, error: reject });
+ });
+ xhrInstances[3].status = 0;
+ xhrInstances[3].statusText = '';
+ xhrInstances[3].emit('error');
+ await expect(networkError).rejects.toMatchObject({ status: 0, statusText: 'Unknown Error' });
+ expect(logService.error).toHaveBeenCalled();
+ });
+
+ it('aborts pending requests and removes event listeners when unsubscribed', () => {
+ vi.stubGlobal('XMLHttpRequest', FakeXMLHttpRequest as never);
+ const impl = new XHRHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+ const subscription = impl.send(createRequest('json')).subscribe({ error: () => undefined });
+ const xhr = xhrInstances[0];
+
+ subscription.unsubscribe();
+
+ expect(xhr.aborted).toBe(true);
+ expect(xhr.removed.map(([type]) => type)).toEqual(['load', 'error', 'abort', 'timeout']);
+ });
+});
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.tsx
index 68a31d8859..002a40a4b1 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionalStyleEditor.spec.tsx
@@ -67,4 +67,46 @@ describe('ConditionalStyleEditor', () => {
it: BooleanNumber.TRUE,
});
});
+
+ it('emits font color changes when a user picks a preset color', 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 styleControls = Array.from(container.firstElementChild!.children) as HTMLElement[];
+
+ await act(async () => {
+ styleControls[4].click();
+ await Promise.resolve();
+ });
+
+ const firstPresetColor = document.querySelector('[data-u-comp="color-picker-presets"] button') as HTMLButtonElement;
+
+ if (!firstPresetColor) {
+ throw new Error('Preset colors were not rendered');
+ }
+
+ await act(async () => {
+ firstPresetColor.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(latestStyle).toMatchObject({
+ cl: {
+ rgb: '#ffffff',
+ },
+ });
+ });
});
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.tsx
index 2d1cca3f40..1b098ad2ff 100644
--- 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.tsx
@@ -233,6 +233,42 @@ describe('RuleList', () => {
expect(container.textContent).not.toContain('A1');
});
+ it('deletes only the clicked conditional formatting rule', 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();
+ });
+
+ const activeRangeText = Array.from(container.querySelectorAll('div'))
+ .find((element) => element.textContent === 'A1');
+ const activeRuleRow = activeRangeText?.parentElement?.parentElement as HTMLElement | undefined;
+ const activeRuleDeleteButton = activeRuleRow?.lastElementChild as HTMLElement | undefined;
+
+ if (!activeRuleDeleteButton) {
+ throw new Error('Rule delete control was not rendered');
+ }
+
+ await act(async () => {
+ activeRuleDeleteButton.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');
+ expect(container.textContent).toContain('F6');
+ });
+
it('clears all worksheet conditional formatting rules in worksheet mode', async () => {
currentTestBed = await createRuleListTestBed();
container = document.createElement('div');
diff --git a/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts b/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
index 2a0e37d5cd..2b6f27927d 100644
--- a/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
+++ b/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
+import type { IAccessor, Workbook, Worksheet } from '@univerjs/core';
import { ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
-import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetsSelectionsService } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { ConditionalFormattingRangeIndexModel } from '../../../models/conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from '../../../models/conditional-formatting-rule-model';
@@ -26,16 +26,52 @@ import { SetConditionalRuleMutation } from '../../mutations/set-conditional-rule
import { ClearRangeCfCommand } from '../clear-range-cf.command';
import { ClearWorksheetCfCommand } from '../clear-worksheet-cf.command';
-vi.mock('@univerjs/sheets', async (importActual) => {
- const actual = await importActual<typeof import('@univerjs/sheets')>();
+class TestWorksheet {
+ constructor(private readonly _sheetId = 'sheet-1') {}
- return {
- ...actual,
- getSheetCommandTarget: vi.fn(),
- };
-});
+ getSheetId() {
+ return this._sheetId;
+ }
+}
+
+class TestWorkbook {
+ constructor(
+ private readonly _unitId = 'unit-1',
+ private readonly _worksheet: TestWorksheet | null = new TestWorksheet()
+ ) {}
+
+ getUnitId() {
+ return this._unitId;
+ }
+
+ getSheetBySheetId(sheetId: string) {
+ if (this._worksheet?.getSheetId() === sheetId) {
+ return this._worksheet as unknown as Worksheet;
+ }
+
+ return null;
+ }
+
+ getActiveSheet() {
+ return this._worksheet as unknown as Worksheet;
+ }
+}
-const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
+class TestUniverInstanceService {
+ constructor(private readonly _workbook: TestWorkbook | null = new TestWorkbook()) {}
+
+ getUnit(unitId: string) {
+ if (this._workbook?.getUnitId() === unitId) {
+ return this._workbook as unknown as Workbook;
+ }
+
+ return null;
+ }
+
+ getCurrentUnitOfType() {
+ return this._workbook as unknown as Workbook;
+ }
+}
function createRuleModel() {
const ruleModel = new ConditionalFormattingRuleModel();
@@ -69,7 +105,7 @@ function createRuleModel() {
return ruleModel;
}
-function createAccessor(ruleModel: ConditionalFormattingRuleModel) {
+function createAccessor(ruleModel: ConditionalFormattingRuleModel, univerInstanceService = new TestUniverInstanceService()) {
const rangeIndexModel = new ConditionalFormattingRangeIndexModel(ruleModel);
const rangeTransformService = new ConditionalFormattingRangeTransformService();
const commandService = {
@@ -83,8 +119,6 @@ function createAccessor(ruleModel: ConditionalFormattingRuleModel) {
range: { startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 },
}]),
};
- const univerInstanceService = {};
-
const accessor = {
get(token: unknown) {
if (token === ConditionalFormattingRuleModel) {
@@ -129,8 +163,6 @@ function createAccessor(ruleModel: ConditionalFormattingRuleModel) {
describe('clear conditional formatting commands', () => {
it('clears the selected range, updates overlapping rules, and records undo/redo', () => {
- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
-
const ruleModel = createRuleModel();
const { accessor, commandService, undoRedoService } = createAccessor(ruleModel);
@@ -167,9 +199,26 @@ describe('clear conditional formatting commands', () => {
}));
});
- it('clears every rule on the worksheet and records one delete per rule', () => {
- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
+ it('clears conditional formatting from the current selection when ranges are omitted', () => {
+ const ruleModel = createRuleModel();
+ const { accessor, commandService, undoRedoService } = createAccessor(ruleModel);
+
+ expect(ClearRangeCfCommand.handler(accessor, {})).toBe(true);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(DeleteConditionalRuleMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cfId: 'rule-delete',
+ }, undefined);
+ expect(undoRedoService.pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'unit-1',
+ redoMutations: expect.arrayContaining([
+ expect.objectContaining({ id: DeleteConditionalRuleMutation.id }),
+ ]),
+ }));
+ });
+
+ it('clears every rule on the worksheet and records one delete per rule', () => {
const ruleModel = createRuleModel();
const { accessor, commandService, undoRedoService } = createAccessor(ruleModel);
@@ -196,14 +245,24 @@ describe('clear conditional formatting commands', () => {
it('returns false when the target, selection, or rules are missing', () => {
const ruleModel = new ConditionalFormattingRuleModel();
const { accessor, commandService, selectionManagerService } = createAccessor(ruleModel);
+ const missingTarget = createAccessor(ruleModel, new TestUniverInstanceService(null));
- mockedGetSheetCommandTarget.mockReturnValue(null as never);
- expect(ClearRangeCfCommand.handler(accessor, { ranges: [] })).toBe(false);
- expect(ClearWorksheetCfCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
+ expect(ClearRangeCfCommand.handler(accessor, undefined as never)).toBe(false);
+
+ expect(ClearRangeCfCommand.handler(missingTarget.accessor, { ranges: [] })).toBe(false);
+ expect(ClearWorksheetCfCommand.handler(missingTarget.accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
selectionManagerService.getCurrentSelections.mockReturnValue([]);
- expect(ClearRangeCfCommand.handler(accessor, { ranges: [] })).toBe(false);
+ expect(ClearRangeCfCommand.handler(accessor, {})).toBe(false);
expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();
});
+
+ it('does not record undo redo when clearing rules fails during mutation sequence', () => {
+ const ruleModel = createRuleModel();
+ const { accessor, commandService, undoRedoService } = createAccessor(ruleModel);
+ commandService.syncExecuteCommand.mockReturnValue(false);
+
+ expect(ClearRangeCfCommand.handler(accessor, { ranges: [{ startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 }] })).toBe(false);
+ expect(undoRedoService.pushUndoRedo).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/sheets-conditional-formatting/src/commands/mutations/__tests__/formula-mark-dirty.mutation.spec.ts b/packages/sheets-conditional-formatting/src/commands/mutations/__tests__/formula-mark-dirty.mutation.spec.ts
new file mode 100644
index 0000000000..04a608b6ac
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/commands/mutations/__tests__/formula-mark-dirty.mutation.spec.ts
@@ -0,0 +1,30 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ConditionalFormattingFormulaMarkDirty } from '../formula-mark-dirty.mutation';
+
+describe('ConditionalFormattingFormulaMarkDirty', () => {
+ it('accepts dirty formula maps as a command message', () => {
+ expect(ConditionalFormattingFormulaMarkDirty.handler({} as never, {
+ 'book-1': {
+ 'sheet-1': {
+ 'cf-1_=A1>0': true,
+ },
+ },
+ })).toBe(true);
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts
index 6f8352aee9..6feb06b3aa 100644
--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts
@@ -18,25 +18,38 @@ import { CellValueType, Injector } from '@univerjs/core';
import { FormulaResultStatus, RegisterOtherFormulaService } from '@univerjs/engine-formula';
import { Subject } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { CFRuleType, CFSubRuleType, CFValueType } from '../../base/const';
import { ConditionalFormattingRuleModel } from '../../models/conditional-formatting-rule-model';
import { ConditionalFormattingFormulaService } from '../conditional-formatting-formula.service';
describe('ConditionalFormattingFormulaService', () => {
let service: ConditionalFormattingFormulaService;
let registerFormulaWithRange: ReturnType<typeof vi.fn>;
+ let deleteFormula: ReturnType<typeof vi.fn>;
let formulaResults: Map<string, unknown>;
+ let formulaResult$: Subject<Record<string, Record<string, unknown[]>>>;
+ let ruleChange$: Subject<any>;
+
+ class TestRegisterOtherFormulaService {
+ formulaResult$ = formulaResult$;
+ registerFormulaWithRange = registerFormulaWithRange;
+ getFormulaValueSync = (_unitId: string, _subUnitId: string, formulaId: string) => formulaResults.get(formulaId);
+ deleteFormula = deleteFormula;
+ }
+
+ class TestConditionalFormattingRuleModel {
+ $ruleChange = ruleChange$;
+ }
beforeEach(() => {
formulaResults = new Map();
registerFormulaWithRange = vi.fn(() => 'formula-1');
+ deleteFormula = vi.fn();
+ formulaResult$ = new Subject();
+ ruleChange$ = new Subject();
const injector = new Injector();
- injector.add([RegisterOtherFormulaService, { useValue: {
- formulaResult$: new Subject(),
- registerFormulaWithRange,
- getFormulaValueSync: (_unitId: string, _subUnitId: string, formulaId: string) => formulaResults.get(formulaId),
- deleteFormula: vi.fn(),
- } as unknown as RegisterOtherFormulaService }]);
- injector.add([ConditionalFormattingRuleModel, { useValue: { $ruleChange: new Subject() } as unknown as ConditionalFormattingRuleModel }]);
+ injector.add([RegisterOtherFormulaService, { useClass: TestRegisterOtherFormulaService as never }]);
+ injector.add([ConditionalFormattingRuleModel, { useClass: TestConditionalFormattingRuleModel as never }]);
injector.add([ConditionalFormattingFormulaService]);
service = injector.get(ConditionalFormattingFormulaService);
});
@@ -73,4 +86,134 @@ describe('ConditionalFormattingFormulaService', () => {
result: true,
});
});
+
+ it('returns not-register and pending statuses when formula results are unavailable', () => {
+ expect(service.getFormulaResultWithCoords('book-1', 'sheet-1', 'cf-1', '=A1>0')).toEqual({
+ status: FormulaResultStatus.NOT_REGISTER,
+ });
+
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0');
+ expect(service.getFormulaResultWithCoords('book-1', 'sheet-1', 'cf-1', '=A1>0')).toEqual({
+ status: FormulaResultStatus.NOT_REGISTER,
+ });
+
+ formulaResults.set('formula-1', { status: FormulaResultStatus.WAIT });
+ expect(service.getFormulaResultWithCoords('book-1', 'sheet-1', 'cf-1', '=A1>0')).toEqual({
+ status: FormulaResultStatus.WAIT,
+ });
+ });
+
+ it('returns formula matrices with extracted scalar cell values', () => {
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1:B2');
+ formulaResults.set('formula-1', {
+ status: FormulaResultStatus.SUCCESS,
+ result: {
+ 0: {
+ 0: [[{ t: CellValueType.BOOLEAN, v: 0 }]],
+ 1: [[{ v: 12 }]],
+ },
+ 1: {
+ 0: [[null]],
+ 1: [[{ v: 'done' }]],
+ },
+ },
+ });
+
+ const matrix = service.getFormulaMatrix('book-1', 'sheet-1', 'cf-1', '=A1:B2');
+
+ expect(matrix.status).toBe(FormulaResultStatus.SUCCESS);
+ expect(matrix.result?.getValue(0, 0)).toBe(false);
+ expect(matrix.result?.getValue(0, 1)).toBe(12);
+ expect(matrix.result?.getValue(1, 0)).toBe(false);
+ expect(matrix.result?.getValue(1, 1)).toBe('done');
+ });
+
+ it('registers and removes formulas in response to rule changes', () => {
+ ruleChange$.next({
+ type: 'add',
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ rule: {
+ cfId: 'cf-1',
+ ranges: [{ startRow: 3, endRow: 3, startColumn: 1, endColumn: 1 }],
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.formula,
+ value: '=A1>0',
+ },
+ },
+ });
+ ruleChange$.next({
+ type: 'delete',
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ rule: { cfId: 'cf-1' },
+ });
+
+ expect(registerFormulaWithRange).toHaveBeenCalledWith(
+ 'book-1',
+ 'sheet-1',
+ '=A1>0',
+ [{ startRow: 3, endRow: 3, startColumn: 1, endColumn: 1 }],
+ undefined,
+ expect.any(String),
+ 'cf-1'
+ );
+ expect(deleteFormula).toHaveBeenCalledWith('book-1', 'sheet-1', ['formula-1']);
+ });
+
+ it('removes formula caches when formula-backed scale rules are replaced', () => {
+ registerFormulaWithRange.mockReturnValueOnce('formula-1').mockReturnValueOnce('formula-2');
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=MIN(A:A)');
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=MAX(A:A)');
+
+ ruleChange$.next({
+ type: 'set',
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ rule: {
+ cfId: 'cf-1',
+ rule: {
+ type: CFRuleType.colorScale,
+ config: [{ value: { type: CFValueType.formula } }],
+ },
+ },
+ });
+
+ expect(deleteFormula).toHaveBeenCalledWith('book-1', 'sheet-1', ['formula-1', 'formula-2']);
+ expect(service.getSubUnitFormulaMap('book-1', 'sheet-1')?.getValues()).toEqual([]);
+ });
+
+ it('publishes result changes and reports whether every formula for the rule finished', () => {
+ registerFormulaWithRange.mockReturnValueOnce('formula-1').mockReturnValueOnce('formula-2');
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0');
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=B1>0');
+ const results: unknown[] = [];
+ service.result$.subscribe((result) => results.push(result));
+
+ formulaResults.set('formula-1', { status: FormulaResultStatus.SUCCESS, result: {} });
+ formulaResults.set('formula-2', { status: FormulaResultStatus.WAIT });
+ formulaResult$.next({ 'book-1': { 'sheet-1': [{ formulaId: 'formula-1' }] } });
+
+ formulaResults.set('formula-2', { status: FormulaResultStatus.SUCCESS, result: {} });
+ formulaResult$.next({ 'book-1': { 'sheet-1': [{ formulaId: 'formula-2' }, { formulaId: 'unknown' }] } });
+
+ expect(results).toEqual([
+ expect.objectContaining({ formulaId: 'formula-1', isAllFinished: false }),
+ expect.objectContaining({ formulaId: 'formula-2', isAllFinished: true }),
+ ]);
+ });
+
+ it('deletes one formula cache by text without unregistering other cached formulas', () => {
+ registerFormulaWithRange.mockReturnValueOnce('formula-1').mockReturnValueOnce('formula-2');
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0');
+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=B1>0');
+
+ expect(service.deleteCache('book-1', 'sheet-1', 'cf-1', '=A1>0')).toEqual([]);
+ expect(service.getSubUnitFormulaMap('book-1', 'sheet-1')?.getValue('cf-1_=A1>0', ['id'])).toBeNull();
+ expect(service.getSubUnitFormulaMap('book-1', 'sheet-1')?.getValue('cf-1_=B1>0', ['id'])).toMatchObject({
+ formulaId: 'formula-2',
+ });
+ expect(service.createCFormulaId('cf-1', '=B1>0')).toBe('cf-1_=B1>0');
+ });
});
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts
index 55938d7624..c8a5824418 100644
--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts
@@ -26,12 +26,24 @@ describe('ConditionalFormattingStyleComposer', () => {
const rules = new Map<string, unknown>();
let cellCfs: Array<{ cfId: string; result: unknown; priority: number }>;
+ class TestConditionalFormattingRuleModel {
+ getRule(_unitId: string, _subUnitId: string, cfId: string) {
+ return rules.get(cfId);
+ }
+ }
+
+ class TestConditionalFormattingViewModel {
+ getCellCfs() {
+ return cellCfs;
+ }
+ }
+
beforeEach(() => {
rules.clear();
cellCfs = [];
const injector = new Injector();
- injector.add([ConditionalFormattingRuleModel, { useValue: { getRule: (_unitId: string, _subUnitId: string, cfId: string) => rules.get(cfId) } as unknown as ConditionalFormattingRuleModel }]);
- injector.add([ConditionalFormattingViewModel, { useValue: { getCellCfs: () => cellCfs } as unknown as ConditionalFormattingViewModel }]);
+ injector.add([ConditionalFormattingRuleModel, { useClass: TestConditionalFormattingRuleModel as never }]);
+ injector.add([ConditionalFormattingViewModel, { useClass: TestConditionalFormattingViewModel as never }]);
injector.add([ConditionalFormattingStyleComposer]);
service = injector.get(ConditionalFormattingStyleComposer);
});
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts
index 78261df49a..a86f671322 100644
--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts
@@ -15,7 +15,18 @@
*/
import { ICommandService, Injector, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';
-import { SheetInterceptorService } from '@univerjs/sheets';
+import {
+ CopySheetCommand,
+ InsertColMutation,
+ InsertRowMutation,
+ MoveColsMutation,
+ MoveRangeMutation,
+ MoveRowsMutation,
+ RemoveSheetCommand,
+ ReorderRangeMutation,
+ SetRangeValuesMutation,
+ SheetInterceptorService,
+} from '@univerjs/sheets';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConditionalFormattingRangeIndexModel } from '../../models/conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from '../../models/conditional-formatting-rule-model';
@@ -26,18 +37,98 @@ import { ConditionalFormattingService } from '../conditional-formatting.service'
describe('ConditionalFormattingService', () => {
let service: ConditionalFormattingService;
let composeStyle: ReturnType<typeof vi.fn>;
+ let resourceConfig: any;
+ let sheetInterceptorConfig: any;
+ let commandListener: (commandInfo: any) => void;
+ let unitRules: Map<string, unknown[]> | null;
+ let deleteUnitId: ReturnType<typeof vi.fn>;
+ let addRule: ReturnType<typeof vi.fn>;
+ let rebuild: ReturnType<typeof vi.fn>;
+ let clearCache: ReturnType<typeof vi.fn>;
+ let markRuleDirty: ReturnType<typeof vi.fn>;
+
+ class TestConditionalFormattingRuleModel {
+ getUnitRules = () => unitRules;
+ getSubunitRules = (_unitId: string, subUnitId: string) => unitRules?.get(subUnitId);
+ deleteUnitId = deleteUnitId;
+ addRule = addRule;
+ createCfId = (_unitId: string, subUnitId: string) => `${subUnitId}-new-cf`;
+ }
+
+ class TestConditionalFormattingRangeIndexModel {
+ rebuild = rebuild;
+ getRulesByRanges = (_unitId: string, _subUnitId: string, ranges: unknown[]) => ranges.length ? [{ cfId: 'cf-1' }] : [];
+ remove = vi.fn();
+ add = vi.fn();
+ }
+
+ class TestConditionalFormattingStyleComposer {
+ composeStyle = composeStyle;
+ }
+
+ class TestConditionalFormattingViewModel {
+ clearCache = clearCache;
+ markRuleDirty = markRuleDirty;
+ markCellDirty = vi.fn();
+ }
+
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getRowCount: () => 100,
+ getColumnCount: () => 50,
+ };
+ const workbook = {
+ getUnitId: () => 'book-1',
+ getSheetBySheetId: (sheetId: string) => (sheetId === 'sheet-1' || sheetId === 'sheet-2' ? { ...worksheet, getSheetId: () => sheetId } : null),
+ getActiveSheet: () => worksheet,
+ };
+
+ class TestUniverInstanceService {
+ getUnit = (unitId: string) => (unitId === 'book-1' ? workbook : null);
+ getCurrentUnitOfType = () => workbook;
+ }
+
+ class TestResourceManagerService {
+ registerPluginResource(config: unknown) {
+ resourceConfig = config;
+ return { dispose: vi.fn() };
+ }
+ }
+
+ class TestSheetInterceptorService {
+ interceptCommand = vi.fn((config: unknown) => {
+ sheetInterceptorConfig = config;
+ return { dispose: vi.fn() };
+ });
+ }
+
+ class TestCommandService {
+ onCommandExecuted(listener: (commandInfo: any) => void) {
+ commandListener = listener;
+ return { dispose: vi.fn() };
+ }
+ }
beforeEach(() => {
composeStyle = vi.fn(() => ({ style: { bg: { rgb: '#fff000' } } }));
+ resourceConfig = null;
+ sheetInterceptorConfig = null;
+ commandListener = () => undefined;
+ unitRules = null;
+ deleteUnitId = vi.fn();
+ addRule = vi.fn();
+ rebuild = vi.fn();
+ clearCache = vi.fn();
+ markRuleDirty = vi.fn();
const injector = new Injector();
- injector.add([ConditionalFormattingRuleModel, { useValue: { getUnitRules: () => null, deleteUnitId: vi.fn() } as unknown as ConditionalFormattingRuleModel }]);
- injector.add([ConditionalFormattingRangeIndexModel, { useValue: { rebuild: vi.fn(), getCellRanges: () => [], remove: vi.fn(), add: vi.fn() } as unknown as ConditionalFormattingRangeIndexModel }]);
- injector.add([ConditionalFormattingStyleComposer, { useValue: { composeStyle } as unknown as ConditionalFormattingStyleComposer }]);
- injector.add([ConditionalFormattingViewModel, { useValue: { clearCache: vi.fn(), markCellDirty: vi.fn() } as unknown as ConditionalFormattingViewModel }]);
- injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);
- injector.add([IResourceManagerService, { useValue: { registerPluginResource: vi.fn(() => ({ dispose: vi.fn() })) } as unknown as IResourceManagerService }]);
- injector.add([SheetInterceptorService, { useValue: { interceptCommand: vi.fn(() => ({ dispose: vi.fn() })) } as unknown as SheetInterceptorService }]);
- injector.add([ICommandService, { useValue: { onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })) } as unknown as ICommandService }]);
+ injector.add([ConditionalFormattingRuleModel, { useClass: TestConditionalFormattingRuleModel as never }]);
+ injector.add([ConditionalFormattingRangeIndexModel, { useClass: TestConditionalFormattingRangeIndexModel as never }]);
+ injector.add([ConditionalFormattingStyleComposer, { useClass: TestConditionalFormattingStyleComposer as never }]);
+ injector.add([ConditionalFormattingViewModel, { useClass: TestConditionalFormattingViewModel as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IResourceManagerService, { useClass: TestResourceManagerService as never }]);
+ injector.add([SheetInterceptorService, { useClass: TestSheetInterceptorService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
injector.add([ConditionalFormattingService]);
service = injector.get(ConditionalFormattingService);
});
@@ -46,4 +137,118 @@ describe('ConditionalFormattingService', () => {
expect(service.composeStyle('book-1', 'sheet-1', 2, 3)).toEqual({ style: { bg: { rgb: '#fff000' } } });
expect(composeStyle).toHaveBeenCalledWith('book-1', 'sheet-1', 2, 3);
});
+
+ it('serializes, loads, and unloads conditional-formatting snapshot resources', () => {
+ const firstRule = { cfId: 'cf-1', ranges: [] };
+ const secondRule = { cfId: 'cf-2', ranges: [] };
+ unitRules = new Map([['sheet-1', [firstRule, secondRule]]]);
+
+ expect(resourceConfig.toJson('book-1')).toBe(JSON.stringify({ 'sheet-1': [firstRule, secondRule] }));
+ expect(resourceConfig.parseJson('')).toEqual({});
+ expect(resourceConfig.parseJson('{bad')).toEqual({});
+ expect(resourceConfig.parseJson('{"sheet-1":[]}')).toEqual({ 'sheet-1': [] });
+
+ resourceConfig.onLoad('book-2', { 'sheet-2': [firstRule, secondRule] });
+ expect(addRule).toHaveBeenNthCalledWith(1, 'book-2', 'sheet-2', secondRule);
+ expect(addRule).toHaveBeenNthCalledWith(2, 'book-2', 'sheet-2', firstRule);
+
+ resourceConfig.onUnLoad('book-1');
+ expect(deleteUnitId).toHaveBeenCalledWith('book-1');
+ expect(rebuild).toHaveBeenCalled();
+ expect(clearCache).toHaveBeenCalled();
+ });
+
+ it('marks affected conditional-formatting rules dirty after cell value and reorder mutations', () => {
+ commandListener({
+ id: SetRangeValuesMutation.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ cellValue: {
+ 1: { 2: { v: 10 } },
+ 3: { 4: { s: 'style-only' } },
+ },
+ },
+ });
+ commandListener({
+ id: ReorderRangeMutation.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 2 },
+ },
+ });
+ commandListener({ id: 'unrelated.command', params: {} });
+
+ expect(markRuleDirty).toHaveBeenCalledTimes(2);
+ expect(markRuleDirty).toHaveBeenCalledWith('book-1', 'sheet-1', 'cf-1');
+ });
+
+ it('creates conditional-formatting undo redo mutations for sheet remove and copy commands', () => {
+ const firstRule = { cfId: 'cf-1', ranges: [] };
+ const secondRule = { cfId: 'cf-2', ranges: [] };
+ unitRules = new Map([['sheet-1', [firstRule, secondRule]]]);
+
+ const removeResult = sheetInterceptorConfig.getMutations({
+ id: RemoveSheetCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1' },
+ });
+ expect(removeResult.redos).toEqual([
+ { id: 'sheet.mutation.delete-conditional-rule', params: { unitId: 'book-1', subUnitId: 'sheet-1', cfId: 'cf-1' } },
+ { id: 'sheet.mutation.delete-conditional-rule', params: { unitId: 'book-1', subUnitId: 'sheet-1', cfId: 'cf-2' } },
+ ]);
+ expect(removeResult.undos.length).toBeGreaterThan(0);
+
+ const copyResult = sheetInterceptorConfig.getMutations({
+ id: CopySheetCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', targetSubUnitId: 'sheet-2' },
+ });
+ expect(copyResult.redos).toEqual([
+ {
+ id: 'sheet.mutation.add-conditional-rule',
+ params: { unitId: 'book-1', subUnitId: 'sheet-2', rule: { cfId: 'sheet-2-new-cf', ranges: [] } },
+ },
+ {
+ id: 'sheet.mutation.add-conditional-rule',
+ params: { unitId: 'book-1', subUnitId: 'sheet-2', rule: { cfId: 'sheet-2-new-cf', ranges: [] } },
+ },
+ ]);
+ expect(sheetInterceptorConfig.getMutations({ id: 'unrelated.command', params: {} })).toEqual({ redos: [], undos: [] });
+ expect(sheetInterceptorConfig.getMutations({ id: RemoveSheetCommand.id, params: { unitId: 'missing', subUnitId: 'sheet-1' } })).toEqual({ redos: [], undos: [] });
+ });
+
+ it('marks conditional-formatting rules dirty after row and column structure changes', () => {
+ const range = { startRow: 2, endRow: 3, startColumn: 4, endColumn: 5 };
+ commandListener({ id: InsertColMutation.id, params: { unitId: 'book-1', subUnitId: 'sheet-1', range } });
+ commandListener({ id: InsertRowMutation.id, params: { unitId: 'book-1', subUnitId: 'sheet-1', range } });
+ commandListener({
+ id: MoveRowsMutation.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ sourceRange: { startRow: 5, endRow: 6, startColumn: 0, endColumn: 10 },
+ targetRange: { startRow: 1, endRow: 2, startColumn: 0, endColumn: 10 },
+ },
+ });
+ commandListener({
+ id: MoveColsMutation.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ sourceRange: { startRow: 0, endRow: 10, startColumn: 5, endColumn: 6 },
+ targetRange: { startRow: 0, endRow: 10, startColumn: 1, endColumn: 2 },
+ },
+ });
+ commandListener({
+ id: MoveRangeMutation.id,
+ params: {
+ unitId: 'book-1',
+ from: { subUnitId: 'sheet-1', value: { 0: { 0: { v: 1 } } } },
+ to: { subUnitId: 'sheet-1', value: { 2: { 2: { v: 1 } } } },
+ },
+ });
+
+ expect(markRuleDirty).toHaveBeenCalledWith('book-1', 'sheet-1', 'cf-1');
+ expect(markRuleDirty.mock.calls.length).toBeGreaterThanOrEqual(6);
+ });
});
diff --git a/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.ts b/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.ts
index 85786ed459..9c7fdf6479 100644
--- a/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.ts
+++ b/packages/sheets-crosshair-highlight/src/facade/f-univer.spec.ts
@@ -14,106 +14,99 @@
* limitations under the License.
*/
+import type { IDisposable } from '@univerjs/core';
+import { ICommandService, Injector } from '@univerjs/core';
+import { FEventName, FUniver } from '@univerjs/core/facade';
+import {
+ DisableCrosshairHighlightOperation,
+ EnableCrosshairHighlightOperation,
+ SheetsCrosshairHighlightService,
+ ToggleCrosshairHighlightOperation,
+} from '@univerjs/sheets-crosshair-highlight';
import { describe, expect, it, vi } from 'vitest';
+import { FSheetsCrosshairHighlightEventNameMixin } from './f-event';
+import { FUniverSheetsCrosshairHighlightMixin } from './f-univer';
-const mocked = vi.hoisted(() => ({
- extendUniver: vi.fn(),
- extendEvent: vi.fn(),
- colors: ['c1', 'c2'],
- enableId: 'enable',
- disableId: 'disable',
- toggleId: 'toggle',
-}));
+class TestCommandService {
+ readonly callbacks: Array<(commandInfo: { id: string }) => void> = [];
+ readonly executedCommandIds: string[] = [];
-vi.mock('@univerjs/core/facade', () => {
- class FUniver {
- static extend = mocked.extendUniver;
- }
- class FEventName {
- static extend = mocked.extendEvent;
+ onCommandExecuted(callback: (commandInfo: { id: string }) => void): IDisposable {
+ this.callbacks.push(callback);
+ return { dispose: () => undefined };
}
- return {
- FUniver,
- FEventName,
- };
-});
+ syncExecuteCommand(id: string): boolean {
+ this.executedCommandIds.push(id);
+ return true;
+ }
+}
-vi.mock('@univerjs/sheets-crosshair-highlight', () => ({
- DisableCrosshairHighlightOperation: { id: mocked.disableId },
- EnableCrosshairHighlightOperation: { id: mocked.enableId },
- ToggleCrosshairHighlightOperation: { id: mocked.toggleId },
- SheetsCrosshairHighlightService: class {},
-}));
+class TestCrosshairHighlightService {
+ enabled = true;
+}
describe('crosshair facade', () => {
- it('should register mixins and cover event wiring + APIs', async () => {
- const module1 = await import('./f-univer');
- const module2 = await import('./f-event');
-
- expect(mocked.extendEvent).toHaveBeenCalledWith(module2.FSheetsCrosshairHighlightEventNameMixin);
- expect(mocked.extendUniver).toHaveBeenCalledWith(module1.FUniverSheetsCrosshairHighlightMixin);
-
- const callbacks: Array<(commandInfo: { id: string }) => void> = [];
- const commandService = {
- onCommandExecuted: vi.fn((cb: (commandInfo: { id: string }) => void) => {
- callbacks.push(cb);
- return { dispose: vi.fn() };
- }),
- };
+ it('emits the enabled-change event for crosshair commands on the active sheet', () => {
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([SheetsCrosshairHighlightService, { useClass: TestCrosshairHighlightService as never }]);
+ const commandService = injector.get(ICommandService) as unknown as TestCommandService;
const fireEvent = vi.fn();
const registerEventHandler = vi.fn((_eventName: string, setup: () => unknown) => setup());
const thisArg = {
- Event: {
- CrosshairHighlightEnabledChanged: 'CrosshairHighlightEnabledChanged',
- },
- _injector: {
- get: vi.fn(() => ({
- enabled: true,
- })),
- },
- _commandService: {
- syncExecuteCommand: vi.fn(),
- },
+ Event: FEventName.get(),
+ _injector: injector,
+ _commandService: commandService,
getActiveSheet: vi.fn(() => ({
- workbook: { id: 'wb' },
- worksheet: { id: 'ws' },
+ workbook: { id: 'workbook-1' },
+ worksheet: { id: 'sheet-1' },
})),
- getCrosshairHighlightEnabled: vi.fn(() => true),
+ getCrosshairHighlightEnabled: () => FUniverSheetsCrosshairHighlightMixin.prototype.getCrosshairHighlightEnabled.call(thisArg as never),
fireEvent,
registerEventHandler,
disposeWithMe: vi.fn(),
};
- module1.FUniverSheetsCrosshairHighlightMixin.prototype._initialize.call(
- thisArg,
- { get: vi.fn(() => commandService) } as never
- );
- expect(registerEventHandler).toHaveBeenCalledTimes(1);
+ FUniverSheetsCrosshairHighlightMixin.prototype._initialize.call(thisArg as never, injector);
+ expect(registerEventHandler).toHaveBeenCalledWith('CrosshairHighlightEnabledChanged', expect.any(Function));
- callbacks[0]({ id: mocked.enableId });
- callbacks[0]({ id: mocked.disableId });
- callbacks[0]({ id: mocked.toggleId });
- callbacks[0]({ id: 'other-command' });
- expect(fireEvent).toHaveBeenCalled();
+ commandService.callbacks[0]({ id: EnableCrosshairHighlightOperation.id });
+ commandService.callbacks[0]({ id: DisableCrosshairHighlightOperation.id });
+ commandService.callbacks[0]({ id: ToggleCrosshairHighlightOperation.id });
+ commandService.callbacks[0]({ id: 'unrelated-command' });
- thisArg.getActiveSheet.mockReturnValue(undefined as never);
- callbacks[0]({ id: mocked.enableId });
+ expect(fireEvent).toHaveBeenCalledTimes(3);
+ expect(fireEvent).toHaveBeenLastCalledWith('CrosshairHighlightEnabledChanged', {
+ enabled: true,
+ workbook: { id: 'workbook-1' },
+ worksheet: { id: 'sheet-1' },
+ });
- const enabledResult = module1.FUniverSheetsCrosshairHighlightMixin.prototype.setCrosshairHighlightEnabled.call(thisArg, true);
- const disabledResult = module1.FUniverSheetsCrosshairHighlightMixin.prototype.setCrosshairHighlightEnabled.call(thisArg, false);
- expect(enabledResult).toBe(thisArg);
- expect(disabledResult).toBe(thisArg);
- expect(thisArg._commandService.syncExecuteCommand).toHaveBeenCalledWith(mocked.enableId);
- expect(thisArg._commandService.syncExecuteCommand).toHaveBeenCalledWith(mocked.disableId);
-
- expect(module1.FUniverSheetsCrosshairHighlightMixin.prototype.getCrosshairHighlightEnabled.call(thisArg)).toBe(true);
-
- const eventEnum = new module2.FSheetsCrosshairHighlightEventNameMixin();
- expect(eventEnum.CrosshairHighlightEnabledChanged).toBe('CrosshairHighlightEnabledChanged');
+ thisArg.getActiveSheet.mockReturnValue(undefined as never);
+ commandService.callbacks[0]({ id: EnableCrosshairHighlightOperation.id });
+ expect(fireEvent).toHaveBeenCalledTimes(3);
});
- it('should run facade entry export', async () => {
- await expect(import('./index')).resolves.toBeDefined();
+ it('updates crosshair state through commands and exposes the event name on real facade classes', () => {
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([SheetsCrosshairHighlightService, { useClass: TestCrosshairHighlightService as never }]);
+ const commandService = injector.get(ICommandService) as unknown as TestCommandService;
+ const thisArg = {
+ _injector: injector,
+ _commandService: commandService,
+ };
+
+ expect(FUniverSheetsCrosshairHighlightMixin.prototype.setCrosshairHighlightEnabled.call(thisArg as never, true)).toBe(thisArg);
+ expect(FUniverSheetsCrosshairHighlightMixin.prototype.setCrosshairHighlightEnabled.call(thisArg as never, false)).toBe(thisArg);
+ expect(commandService.executedCommandIds).toEqual([
+ EnableCrosshairHighlightOperation.id,
+ DisableCrosshairHighlightOperation.id,
+ ]);
+ expect(FUniverSheetsCrosshairHighlightMixin.prototype.getCrosshairHighlightEnabled.call(thisArg as never)).toBe(true);
+ expect(FEventName.get().CrosshairHighlightEnabledChanged).toBe('CrosshairHighlightEnabledChanged');
+ expect(Object.create(FSheetsCrosshairHighlightEventNameMixin.prototype).CrosshairHighlightEnabledChanged).toBe('CrosshairHighlightEnabledChanged');
+ expect(typeof FUniver.prototype.setCrosshairHighlightEnabled).toBe('function');
});
});
diff --git a/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx b/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx
index 0d800fca3f..7ed967e1f8 100644
--- a/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx
+++ b/packages/sheets-crosshair-highlight/src/views/components/CrosshairHighlight.spec.tsx
@@ -46,7 +46,7 @@ function createOverlayTestBed() {
const highlightBackground = Object.fromEntries(CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS.map((path, index) => [
path.replace('highlight.background.', ''),
{
- color: index === 1 ? '#040506' : '#010203',
+ color: index === 0 ? '#010203' : index === 1 ? '#040506' : `#${String(index + 10).padStart(2, '0')}0a0b`,
alpha: index === 1 ? 0.15 : 0.3,
},
]));
@@ -137,4 +137,22 @@ describe('CrosshairOverlay', () => {
expect(hasClassToken(cells[1], 'univer-ring-primary-600')).toBe(true);
expect(hasClassToken(cells[0], 'univer-ring-primary-600')).toBe(false);
});
+
+ it('moves the active swatch when the service color changes after render', () => {
+ const testBed = createOverlayTestBed();
+ const rendered = renderOverlay(testBed.injector);
+ disposable = teardown(rendered.root, rendered.container);
+
+ let cells = getColorCells(rendered.container);
+ expect(hasClassToken(cells[0], 'univer-ring-primary-600')).toBe(true);
+ expect(hasClassToken(cells[2], 'univer-ring-primary-600')).toBe(false);
+
+ act(() => {
+ testBed.service.setColor(CROSSHAIR_HIGHLIGHT_COLOR_THEME_PATHS[2]);
+ });
+
+ cells = getColorCells(rendered.container);
+ expect(hasClassToken(cells[0], 'univer-ring-primary-600')).toBe(false);
+ expect(hasClassToken(cells[2], 'univer-ring-primary-600')).toBe(true);
+ });
});
diff --git a/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts b/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts
index fc29cc1b3a..82d5c59256 100644
--- a/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts
+++ b/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts
@@ -14,80 +14,224 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService } from '@univerjs/core';
-import { getSheetCommandTarget } from '@univerjs/sheets';
-import { AddSheetDataValidationCommand, createDefaultNewRule } from '@univerjs/sheets-data-validation';
-import { describe, expect, it, vi } from 'vitest';
-import { OpenValidationPanelOperation } from '../../operations/data-validation.operation';
+import type {
+ Dependency,
+ ICommand,
+ ICommandInfo,
+ IDataValidationRule,
+ IDisposable,
+ IWorkbookData,
+ Workbook,
+} from '@univerjs/core';
+import type { ISidebarMethodOptions } from '@univerjs/ui';
+import {
+ CommandType,
+ DataValidationOperator,
+ DataValidationType,
+ ICommandService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleType,
+ Plugin,
+ toDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DataValidationModel } from '@univerjs/data-validation';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { AddSheetDataValidationCommand } from '@univerjs/sheets-data-validation';
+import { ISidebarService } from '@univerjs/ui';
+import { BehaviorSubject } from 'rxjs';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
+import { DATA_VALIDATION_PANEL, OpenValidationPanelOperation } from '../../operations/data-validation.operation';
import { AddSheetDataValidationAndOpenCommand } from '../data-validation-ui.command';
-vi.mock('@univerjs/sheets', async (importActual) => {
- const actual = await importActual<typeof import('@univerjs/sheets')>();
- return { ...actual, getSheetCommandTarget: vi.fn() };
-});
+interface ITestBed {
+ univer: Univer;
+ get: Injector['get'];
+ workbook?: Workbook;
+ executedCommands: ICommandInfo[];
+}
-vi.mock('@univerjs/sheets-data-validation', async (importActual) => {
- const actual = await importActual<typeof import('@univerjs/sheets-data-validation')>();
- return { ...actual, createDefaultNewRule: vi.fn() };
-});
+class TestDataValidationModel {
+ rejectAdd = false;
+ readonly rules = new Map<string, IDataValidationRule>();
-const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
-const mockedCreateDefaultNewRule = vi.mocked(createDefaultNewRule);
+ addRule(unitId: string, subUnitId: string, rule: IDataValidationRule): void {
+ this.rules.set(`${unitId}:${subUnitId}:${rule.uid}`, rule);
+ }
-function createAccessor() {
- const commandService = { syncExecuteCommand: vi.fn(() => true) };
- const accessor = {
- get(token: unknown) {
- if (token === IUniverInstanceService) {
- return {};
- }
+ getRuleById(unitId: string, subUnitId: string, ruleId: string): IDataValidationRule | undefined {
+ return this.rules.get(`${unitId}:${subUnitId}:${ruleId}`);
+ }
+}
+
+class TestSidebarService {
+ readonly sidebarOptions$ = new BehaviorSubject<ISidebarMethodOptions>({ visible: true });
+ readonly openedPanels: ISidebarMethodOptions[] = [];
+ disposeCount = 0;
+
+ open(options: ISidebarMethodOptions): IDisposable {
+ this.openedPanels.push(options);
+ return toDisposable(() => {
+ this.disposeCount++;
+ });
+ }
+}
+
+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',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {},
+ },
+ },
+ styles: {},
+ };
+}
+
+function registerDependencies(injector: Injector): void {
+ const dependencies: Dependency[] = [
+ [SheetsSelectionsService],
+ [DataValidationModel, { useClass: TestDataValidationModel }],
+ [ISidebarService, { useClass: TestSidebarService }],
+ [DataValidationPanelService],
+ ];
+ dependencies.forEach((dependency) => injector.add(dependency));
+}
+
+function createTestBed(createWorkbook = true): 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;
- if (token === ICommandService) {
- return commandService;
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ registerDependencies(this._injector);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ if (!createWorkbook) {
+ registerDependencies(injector);
+ }
+
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(AddSheetDataValidationAndOpenCommand);
+ commandService.registerCommand(OpenValidationPanelOperation);
+ commandService.registerCommand({
+ id: AddSheetDataValidationCommand.id,
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ const model = accessor.get(DataValidationModel) as unknown as TestDataValidationModel;
+ executedCommands.push({ id: AddSheetDataValidationCommand.id, params });
+
+ const addParams = params as { unitId: string; subUnitId: string; rule: IDataValidationRule } | undefined;
+ if (model.rejectAdd || !addParams) {
+ return false;
}
- throw new Error(`Unknown dependency: ${String(token)}`);
+ model.addRule(addParams.unitId, addParams.subUnitId, addParams.rule);
+ return true;
},
- } as IAccessor;
+ } as ICommand);
- return { accessor, commandService };
+ 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,
+ executedCommands,
+ };
}
describe('AddSheetDataValidationAndOpenCommand', () => {
- it('adds a default rule for the current sheet and opens the panel for that rule', () => {
- mockedCreateDefaultNewRule.mockReturnValue({ uid: 'rule-1' } as never);
- mockedGetSheetCommandTarget.mockReturnValue({
- workbook: { getUnitId: () => 'book-1' },
- worksheet: { getSheetId: () => 'sheet-1' },
- } as never);
- const { accessor, commandService } = createAccessor();
-
- expect(AddSheetDataValidationAndOpenCommand.handler(accessor)).toBe(true);
- expect(mockedCreateDefaultNewRule).toHaveBeenCalledWith(accessor);
- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, AddSheetDataValidationCommand.id, {
- rule: { uid: 'rule-1' },
+ let testBed: ITestBed | undefined;
+
+ afterEach(() => {
+ testBed?.univer.dispose();
+ testBed = undefined;
+ });
+
+ it('adds a default rule to the active sheet and opens the panel for that rule', () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ const panelService = testBed.get(DataValidationPanelService);
+ const sidebarService = testBed.get(ISidebarService) as unknown as TestSidebarService;
+
+ expect(commandService.syncExecuteCommand(AddSheetDataValidationAndOpenCommand.id)).toBe(true);
+
+ const addParams = testBed.executedCommands[0].params as { unitId: string; subUnitId: string; rule: IDataValidationRule };
+ expect(addParams.unitId).toBe('book-1');
+ expect(addParams.subUnitId).toBe('sheet-1');
+ expect(addParams.rule).toMatchObject({
+ type: DataValidationType.DECIMAL,
+ operator: DataValidationOperator.EQUAL,
+ formula1: '100',
+ });
+ expect(panelService.activeRule).toEqual({
unitId: 'book-1',
subUnitId: 'sheet-1',
+ rule: addParams.rule,
});
- expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, OpenValidationPanelOperation.id, {
- ruleId: 'rule-1',
- isAdd: true,
+ expect(panelService.isOpen).toBe(true);
+ expect(sidebarService.openedPanels.at(-1)).toMatchObject({
+ id: DATA_VALIDATION_PANEL,
+ header: { title: 'sheets-data-validation-ui.panel.addTitle' },
+ width: 312,
});
});
- it('returns false when there is no active target or adding the rule fails', () => {
- const { accessor, commandService } = createAccessor();
- mockedCreateDefaultNewRule.mockReturnValue({ uid: 'rule-2' } as never);
- mockedGetSheetCommandTarget.mockReturnValue(null as never);
- expect(AddSheetDataValidationAndOpenCommand.handler(accessor)).toBe(false);
-
- mockedGetSheetCommandTarget.mockReturnValue({
- workbook: { getUnitId: () => 'book-1' },
- worksheet: { getSheetId: () => 'sheet-1' },
- } as never);
- commandService.syncExecuteCommand.mockReturnValue(false);
- expect(AddSheetDataValidationAndOpenCommand.handler(accessor)).toBe(false);
- expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(1);
+ it('does not add or open when there is no active sheet target', () => {
+ testBed = createTestBed(false);
+ const commandService = testBed.get(ICommandService);
+ const panelService = testBed.get(DataValidationPanelService);
+ const sidebarService = testBed.get(ISidebarService) as unknown as TestSidebarService;
+
+ expect(commandService.syncExecuteCommand(AddSheetDataValidationAndOpenCommand.id)).toBe(false);
+ expect(testBed.executedCommands).toEqual([]);
+ expect(panelService.isOpen).toBe(false);
+ expect(sidebarService.openedPanels).toEqual([]);
+ });
+
+ it('does not open the panel when the rule add command rejects the new rule', () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ const panelService = testBed.get(DataValidationPanelService);
+ const model = testBed.get(DataValidationModel) as unknown as TestDataValidationModel;
+
+ model.rejectAdd = true;
+
+ expect(commandService.syncExecuteCommand(AddSheetDataValidationAndOpenCommand.id)).toBe(false);
+ expect(testBed.executedCommands).toHaveLength(1);
+ expect(panelService.isOpen).toBe(false);
+ expect(panelService.activeRule).toBeUndefined();
});
});
diff --git a/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts b/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts
index 639e5ba5ee..14a1e6a289 100644
--- a/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts
+++ b/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts
@@ -14,13 +14,26 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
+import type { Dependency, IDataValidationRule, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISidebarMethodOptions } from '@univerjs/ui';
import type { IDataValidationDropdownParam } from '../../../services/dropdown-manager.service';
-import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import {
+ DataValidationOperator,
+ DataValidationType,
+ ICommandService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleType,
+ Plugin,
+ toDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
import { DataValidationModel } from '@univerjs/data-validation';
-import { getSheetCommandTarget } from '@univerjs/sheets';
import { ISidebarService } from '@univerjs/ui';
-import { describe, expect, it, vi } from 'vitest';
+import { BehaviorSubject } from 'rxjs';
+import { afterEach, describe, expect, it } from 'vitest';
import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
import { DataValidationDropdownManagerService } from '../../../services/dropdown-manager.service';
import {
@@ -32,115 +45,235 @@ import {
ToggleValidationPanelOperation,
} from '../data-validation.operation';
-vi.mock('@univerjs/sheets', async (importActual) => {
- const actual = await importActual<typeof import('@univerjs/sheets')>();
- return { ...actual, getSheetCommandTarget: vi.fn() };
-});
+interface ITestBed {
+ univer: Univer;
+ get: Injector['get'];
+ workbook?: Workbook;
+}
-const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
+const RULE: IDataValidationRule = {
+ uid: 'rule-1',
+ type: DataValidationType.DECIMAL,
+ operator: DataValidationOperator.EQUAL,
+ formula1: '100',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+};
-function createAccessor() {
- const commandService = { executeCommand: vi.fn() };
- const panelService = {
- open: vi.fn(),
- close: vi.fn(),
- setActiveRule: vi.fn(),
- setCloseDisposable: vi.fn(),
- isOpen: false,
- };
- const rule = { uid: 'rule-1' };
- const dropdownService: {
- activeDropdown: IDataValidationDropdownParam | null;
- showDataValidationDropdown: ReturnType<typeof vi.fn>;
- hideDropdown: ReturnType<typeof vi.fn>;
- } = {
- activeDropdown: null,
- showDataValidationDropdown: vi.fn(),
- hideDropdown: vi.fn(),
- };
- const sidebarService = {
- open: vi.fn(() => ({ dispose: vi.fn() })),
- };
- const accessor = {
- get(token: unknown) {
- if (token === ICommandService) return commandService;
- if (token === DataValidationPanelService) return panelService;
- if (token === DataValidationModel) return { getRuleById: vi.fn(() => rule) };
- if (token === IUniverInstanceService) return {};
- if (token === ISidebarService) return sidebarService;
- if (token === DataValidationDropdownManagerService) return dropdownService;
- throw new Error(`Unknown dependency: ${String(token)}`);
+class TestDataValidationModel {
+ getRuleById(unitId: string, subUnitId: string, ruleId: string): IDataValidationRule | undefined {
+ return unitId === 'book-1' && subUnitId === 'sheet-1' && ruleId === RULE.uid ? RULE : undefined;
+ }
+}
+
+class TestSidebarService {
+ readonly sidebarOptions$ = new BehaviorSubject<ISidebarMethodOptions>({ visible: true });
+ readonly openedPanels: ISidebarMethodOptions[] = [];
+ disposeCount = 0;
+
+ open(options: ISidebarMethodOptions): IDisposable {
+ this.openedPanels.push(options);
+ return toDisposable(() => {
+ this.disposeCount++;
+ });
+ }
+}
+
+class TestDropdownManagerService {
+ activeDropdown: IDataValidationDropdownParam | null = null;
+ readonly shownLocations: Array<{ unitId: string; subUnitId: string; row: number; column: number }> = [];
+ hideCount = 0;
+
+ showDataValidationDropdown(unitId: string, subUnitId: string, row: number, column: number): void {
+ this.shownLocations.push({ unitId, subUnitId, row, column });
+ this.activeDropdown = {
+ location: {
+ unitId,
+ subUnitId,
+ row,
+ col: column,
+ },
+ } as IDataValidationDropdownParam;
+ }
+
+ hideDropdown(): void {
+ this.hideCount++;
+ this.activeDropdown = null;
+ }
+}
+
+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',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {},
+ },
},
- } as IAccessor;
+ styles: {},
+ };
+}
- return { accessor, commandService, panelService, dropdownService, sidebarService, rule };
+function registerDependencies(injector: Injector): void {
+ const dependencies: Dependency[] = [
+ [DataValidationModel, { useClass: TestDataValidationModel }],
+ [ISidebarService, { useClass: TestSidebarService }],
+ [DataValidationPanelService],
+ [DataValidationDropdownManagerService, { useClass: TestDropdownManagerService }],
+ ];
+ dependencies.forEach((dependency) => injector.add(dependency));
+}
+
+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 {
+ registerDependencies(this._injector);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ if (!createWorkbook) {
+ registerDependencies(injector);
+ }
+
+ const commandService = injector.get(ICommandService);
+ [
+ OpenValidationPanelOperation,
+ CloseValidationPanelOperation,
+ ToggleValidationPanelOperation,
+ ShowDataValidationDropdown,
+ HideDataValidationDropdown,
+ ].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('data validation operations', () => {
- it('opens the validation panel for the active sheet rule and wires close disposal', () => {
- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'book-1', subUnitId: 'sheet-1' } as never);
- const { accessor, panelService, sidebarService, rule } = createAccessor();
-
- expect(OpenValidationPanelOperation.handler(accessor, { ruleId: 'rule-1', isAdd: true })).toBe(true);
- expect(panelService.open).toHaveBeenCalledTimes(1);
- expect(panelService.setActiveRule).toHaveBeenCalledWith({ unitId: 'book-1', subUnitId: 'sheet-1', rule });
- expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ let testBed: ITestBed | undefined;
+
+ afterEach(() => {
+ testBed?.univer.dispose();
+ testBed = undefined;
+ });
+
+ it('opens the panel for an active sheet rule and closes it from the sidebar callback', async () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ const panelService = testBed.get(DataValidationPanelService);
+ const sidebarService = testBed.get(ISidebarService) as unknown as TestSidebarService;
+
+ await expect(commandService.executeCommand(OpenValidationPanelOperation.id, { ruleId: RULE.uid, isAdd: true })).resolves.toBe(true);
+
+ expect(panelService.isOpen).toBe(true);
+ expect(panelService.activeRule).toEqual({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ rule: RULE,
+ });
+ expect(sidebarService.openedPanels.at(-1)).toMatchObject({
id: DATA_VALIDATION_PANEL,
header: { title: 'sheets-data-validation-ui.panel.addTitle' },
children: { label: DATA_VALIDATION_PANEL },
width: 312,
- }));
- expect(panelService.setCloseDisposable).toHaveBeenCalledTimes(1);
+ });
+
+ sidebarService.openedPanels.at(-1)!.onClose?.();
+
+ expect(panelService.isOpen).toBe(false);
});
- it('closes and toggles the panel through the command service', () => {
- const { accessor, panelService, commandService } = createAccessor();
+ it('opens the rule list with empty params and returns false when no sheet is active', async () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ const panelService = testBed.get(DataValidationPanelService);
- expect(CloseValidationPanelOperation.handler(accessor)).toBe(true);
- expect(panelService.close).toHaveBeenCalledTimes(1);
+ await expect(commandService.executeCommand(OpenValidationPanelOperation.id)).resolves.toBe(false);
+ expect(panelService.isOpen).toBe(false);
- panelService.isOpen = true;
- expect(ToggleValidationPanelOperation.handler(accessor)).toBe(true);
- expect(commandService.executeCommand).toHaveBeenCalledWith(CloseValidationPanelOperation.id);
+ await expect(commandService.executeCommand(OpenValidationPanelOperation.id, {})).resolves.toBe(true);
+ expect(panelService.isOpen).toBe(true);
+ expect(panelService.activeRule).toBeUndefined();
- panelService.isOpen = false;
- ToggleValidationPanelOperation.handler(accessor);
- expect(commandService.executeCommand).toHaveBeenCalledWith(OpenValidationPanelOperation.id);
+ testBed.univer.dispose();
+ testBed = createTestBed(false);
+
+ await expect(testBed.get(ICommandService).executeCommand(OpenValidationPanelOperation.id, {})).resolves.toBe(false);
});
- it('shows and hides dropdowns only when location changes, and guards invalid params', () => {
- const { accessor, dropdownService } = createAccessor();
+ it('toggles an opened validation panel closed through the command service', async () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ const panelService = testBed.get(DataValidationPanelService);
+ const sidebarService = testBed.get(ISidebarService) as unknown as TestSidebarService;
+
+ await expect(commandService.executeCommand(OpenValidationPanelOperation.id, {})).resolves.toBe(true);
+ expect(panelService.isOpen).toBe(true);
+ expect(sidebarService.openedPanels).toHaveLength(1);
- expect(ShowDataValidationDropdown.handler(accessor, null as never)).toBe(false);
- expect(HideDataValidationDropdown.handler(accessor, null as never)).toBe(false);
+ await expect(commandService.executeCommand(ToggleValidationPanelOperation.id)).resolves.toBe(true);
+ expect(panelService.isOpen).toBe(false);
+ expect(sidebarService.disposeCount).toBe(1);
+ });
- expect(ShowDataValidationDropdown.handler(accessor, {
+ it('does not recreate dropdowns for the same cell and hides an active dropdown on demand', async () => {
+ testBed = createTestBed();
+ const commandService = testBed.get(ICommandService);
+ const dropdownService = testBed.get(DataValidationDropdownManagerService) as unknown as TestDropdownManagerService;
+
+ await expect(commandService.executeCommand(ShowDataValidationDropdown.id)).resolves.toBe(false);
+ await expect(commandService.executeCommand(HideDataValidationDropdown.id)).resolves.toBe(false);
+
+ await expect(commandService.executeCommand(ShowDataValidationDropdown.id, {
unitId: 'book-1',
subUnitId: 'sheet-1',
row: 1,
column: 2,
- })).toBe(true);
- expect(dropdownService.showDataValidationDropdown).toHaveBeenCalledWith('book-1', 'sheet-1', 1, 2);
-
- dropdownService.activeDropdown = { location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2 } } as unknown as IDataValidationDropdownParam;
- ShowDataValidationDropdown.handler(accessor, {
+ })).resolves.toBe(true);
+ await expect(commandService.executeCommand(ShowDataValidationDropdown.id, {
unitId: 'book-1',
subUnitId: 'sheet-1',
row: 1,
column: 2,
- });
- expect(dropdownService.showDataValidationDropdown).toHaveBeenCalledTimes(1);
+ })).resolves.toBe(true);
- expect(HideDataValidationDropdown.handler(accessor, { ok: true } as never)).toBe(true);
- expect(dropdownService.hideDropdown).toHaveBeenCalledTimes(1);
- });
+ expect(dropdownService.shownLocations).toEqual([
+ { unitId: 'book-1', subUnitId: 'sheet-1', row: 1, column: 2 },
+ ]);
- it('returns false when there is no active sheet target or no params', () => {
- const { accessor, panelService } = createAccessor();
- mockedGetSheetCommandTarget.mockReturnValue(null as never);
+ await expect(commandService.executeCommand(HideDataValidationDropdown.id, { reason: 'selection-change' })).resolves.toBe(true);
- expect(OpenValidationPanelOperation.handler(accessor, { ruleId: 'rule-1' })).toBe(false);
- expect(OpenValidationPanelOperation.handler(accessor, null as never)).toBe(false);
- expect(panelService.open).not.toHaveBeenCalled();
+ expect(dropdownService.hideCount).toBe(1);
+ expect(dropdownService.activeDropdown).toBeNull();
});
});
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.behavior.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.behavior.spec.tsx
new file mode 100644
index 0000000000..f004b6c6f9
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.behavior.spec.tsx
@@ -0,0 +1,561 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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,
+ 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,
+ WorkbookPermissionService,
+ WorksheetPermissionService,
+ WorksheetProtectionPointModel,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
+import {
+ DataValidationCacheService,
+ DataValidationCustomFormulaService,
+ DataValidationFormulaService,
+ DataValidationListCacheService,
+ DateValidator,
+ SheetDataValidationModel,
+ SheetsDataValidationValidatorService,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationSettingCommand,
+} 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 { DateShowTimeOption } from '../DateShowTimeOption';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'test';
+const SUB_UNIT_ID = 'sheet1';
+
+const FIRST_RANGE: IRange = {
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 0,
+};
+
+class TestMarkSelectionService {
+ addShape(selection: ISelectionWithStyle) {
+ return `shape-${selection.range.startRow}`;
+ }
+
+ addShapeWithNoFresh(selection: ISelectionWithStyle) {
+ return this.addShape(selection);
+ }
+
+ removeShape() {
+ // The detail tests do not need selection shape state.
+ }
+
+ removeAllShapes() {
+ // The detail tests do not need selection shape state.
+ }
+
+ refreshShapes() {
+ // The detail tests do not need selection shape state.
+ }
+
+ 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,
+ with: () => ({
+ getViewModel: () => ({
+ getDataModel: () => ({
+ updateDocumentDataPageSize: () => undefined,
+ }),
+ }),
+ getSkeleton: () => ({
+ getActualSize: () => ({ actualWidth: 0, actualHeight: 0 }),
+ }),
+ }),
+ scene: {
+ transformByState: () => undefined,
+ getViewport: () => undefined,
+ },
+ mainComponent: {
+ resize: () => undefined,
+ translate: () => undefined,
+ },
+ components: {
+ get: () => undefined,
+ },
+ };
+
+ 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,
+ },
+ },
+ locale: LocaleType.EN_US,
+ name: 'test workbook',
+ sheetOrder: [SUB_UNIT_ID],
+ styles: {},
+ };
+}
+
+function createDateRule(uid = 'rule-date'): ISheetDataValidationRule {
+ return {
+ uid,
+ type: DataValidationType.DATE,
+ ranges: [FIRST_RANGE],
+ allowBlank: true,
+ bizInfo: {
+ showTime: false,
+ },
+ };
+}
+
+function createDetailTestBed(rule: ISheetDataValidationRule) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'sheets-data-validation-ui-detail-behavior-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);
+ }
+ }
+
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'sheets-data-validation': {
+ date: {
+ title: 'Date',
+ },
+ validFail: {
+ date: 'Enter a valid date',
+ number: 'Enter a valid number',
+ },
+ },
+ 'sheets-data-validation-ui': {
+ operators: {
+ legal: 'Is valid',
+ },
+ panel: {
+ allowBlank: 'Allow blank',
+ done: 'Done',
+ formulaAnd: 'and',
+ formulaPlaceholder: 'Value or formula',
+ invalid: 'Invalid data',
+ messageInfo: 'Message',
+ options: 'Options',
+ range: 'Apply to range',
+ rangeError: 'Select a range',
+ rejectInput: 'Reject input',
+ removeRule: 'Remove rule',
+ showInfo: 'Show message',
+ showWarning: 'Show warning',
+ type: 'Criteria',
+ operator: 'Condition',
+ },
+ showTime: {
+ label: 'Show time',
+ },
+ },
+ },
+ });
+
+ 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(ILogService).setLogLevel(LogLevel.SILENT);
+ injector.get(ComponentManager).register(DateShowTimeOption.componentKey, DateShowTimeOption);
+
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand(UpdateSheetDataValidationSettingCommand);
+ commandService.registerCommand(UpdateSheetDataValidationOptionsCommand);
+
+ const localeService = injector.get(LocaleService);
+ const validatorRegistry = injector.get(DataValidatorRegistryService);
+ const dateValidator = new DateValidator(localeService, injector);
+ dateValidator.optionsInput = DateShowTimeOption.componentKey;
+ validatorRegistry.register(dateValidator);
+
+ const sheetDataValidationModel = injector.get(SheetDataValidationModel);
+ commandService.syncExecuteCommand(AddDataValidationMutation.id, {
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ rule,
+ });
+
+ injector.get(DataValidationPanelService).setActiveRule({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ rule,
+ });
+
+ return {
+ univer,
+ injector,
+ commandService,
+ workbook,
+ rule,
+ dataValidationModel: injector.get(DataValidationModel),
+ panelService: injector.get(DataValidationPanelService),
+ sheetDataValidationModel,
+ };
+}
+
+async function renderDetail(root: Root, testBed: ReturnType<typeof createDetailTestBed>) {
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <DataValidationDetail />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+}
+
+async function clickElement(element: HTMLElement) {
+ await act(async () => {
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+async function waitForDebounce() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 1100));
+ });
+}
+
+function findElementByText(container: HTMLElement, text: string) {
+ return Array.from(container.querySelectorAll<HTMLElement>('div'))
+ .filter((element) => element.textContent?.includes(text))
+ .sort((a, b) => (a.textContent?.length ?? 0) - (b.textContent?.length ?? 0))[0];
+}
+
+describe('DataValidationDetail rule editing', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createDetailTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('persists the allow-blank checkbox into the active rule setting command', async () => {
+ currentTestBed = createDetailTestBed(createDateRule('rule-date-allow-blank'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)?.allowBlank).toBe(true);
+
+ const allowBlankInput = container.querySelector<HTMLInputElement>('[data-u-comp="checkbox"] input')!;
+
+ await clickElement(allowBlankInput);
+ await waitForDebounce();
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)?.allowBlank).toBe(false);
+ });
+
+ it('persists date show-time options through the detail options command', async () => {
+ currentTestBed = createDetailTestBed(createDateRule());
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderDetail(root, currentTestBed);
+ await clickElement(findElementByText(container, 'panel.options'));
+
+ const showTimeInput = container.querySelectorAll<HTMLInputElement>('[data-u-comp="checkbox"] input')[1];
+
+ await clickElement(showTimeInput);
+ await waitForDebounce();
+
+ expect(currentTestBed.sheetDataValidationModel.getRuleById(UNIT_ID, SUB_UNIT_ID, currentTestBed.rule.uid)?.bizInfo).toEqual({
+ showTime: true,
+ });
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.spec.tsx
new file mode 100644
index 0000000000..9432f93731
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationOptions.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 { IDataValidationRuleOptions } from '@univerjs/core';
+import { DataValidationErrorStyle, LocaleService, LocaleType, Univer } from '@univerjs/core';
+import { ComponentManager, RediContext } from '@univerjs/ui';
+import { act, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DataValidationOptions } from '../DataValidationOptions';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function createOptionsTestBed() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([ComponentManager]);
+
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {
+ 'sheets-data-validation-ui': {
+ panel: {
+ invalid: 'Invalid data',
+ messageInfo: 'Message',
+ options: 'Options',
+ rejectInput: 'Reject input',
+ showInfo: 'Show message',
+ showWarning: 'Show warning',
+ },
+ },
+ },
+ });
+
+ return {
+ injector,
+ univer,
+ };
+}
+
+function OptionsHarness(props: {
+ initialValue: IDataValidationRuleOptions;
+ changes: IDataValidationRuleOptions[];
+}) {
+ const [value, setValue] = useState(props.initialValue);
+
+ return (
+ <DataValidationOptions
+ value={value}
+ onChange={(nextValue) => {
+ props.changes.push(nextValue);
+ setValue(nextValue);
+ }}
+ />
+ );
+}
+
+async function clickElement(element: HTMLElement) {
+ await act(async () => {
+ element.click();
+ await Promise.resolve();
+ });
+}
+
+async function changeInputValue(input: HTMLInputElement, value: string) {
+ await act(async () => {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+describe('DataValidationOptions', () => {
+ let root: ReturnType<typeof createRoot> | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentTestBed: ReturnType<typeof createOptionsTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentTestBed?.univer.dispose();
+ root = undefined;
+ container = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('saves invalid-data handling and custom error message options through change parameters', async () => {
+ currentTestBed = createOptionsTestBed();
+ const changes: IDataValidationRuleOptions[] = [];
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <OptionsHarness
+ initialValue={{
+ errorStyle: DataValidationErrorStyle.WARNING,
+ showErrorMessage: false,
+ error: 'old message',
+ }}
+ changes={changes}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await clickElement(container.firstElementChild as HTMLElement);
+ await clickElement(container.querySelectorAll<HTMLInputElement>('[data-u-comp="radio"] input')[1]);
+
+ expect(changes.at(-1)).toEqual({
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: false,
+ error: 'old message',
+ });
+
+ await clickElement(container.querySelector<HTMLInputElement>('[data-u-comp="checkbox"] input')!);
+
+ expect(changes.at(-1)).toEqual({
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: true,
+ error: 'old message',
+ });
+
+ await changeInputValue(container.querySelector<HTMLInputElement>('[data-u-comp="input"] input')!, 'Only choose approved values');
+
+ expect(changes.at(-1)).toEqual({
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: true,
+ error: 'Only choose approved values',
+ });
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts b/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts
new file mode 100644
index 0000000000..0273ca447c
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/views/widgets/__tests__/data-validation-widgets.spec.ts
@@ -0,0 +1,223 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ICellRenderContext, IDataValidationRule } from '@univerjs/core';
+import type { IFormulaResult } from '@univerjs/data-validation';
+import type { ISetRangeValuesCommandParams } from '@univerjs/sheets';
+import { DataValidationType, ICommandService, Injector, IUniverInstanceService, LocaleService, ThemeService } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SetRangeValuesCommand } from '@univerjs/sheets';
+import { DataValidationFormulaService, SheetDataValidationModel } from '@univerjs/sheets-data-validation';
+import { describe, expect, it } from 'vitest';
+import { ShowDataValidationDropdown } from '../../../commands/operations/data-validation.operation';
+
+class TestPath2D {
+ constructor(_path?: string) {
+ // Path details are not used by these pointer behavior tests.
+ }
+}
+
+Object.assign(globalThis, { Path2D: TestPath2D });
+
+interface IExecutedCommand {
+ id: string;
+ params?: unknown;
+}
+
+class RecordingCommandService {
+ readonly commands: IExecutedCommand[] = [];
+
+ executeCommand(id: string, params?: unknown): Promise<boolean> {
+ this.commands.push({ id, params });
+ return Promise.resolve(true);
+ }
+}
+
+class TestUniverInstanceService {
+}
+
+class TestRenderManagerService {
+}
+
+class TestLocaleService {
+}
+
+class TestThemeService {
+ getColorFromTheme(): string {
+ return '#155eef';
+ }
+}
+
+class TestFormulaService {
+ getRuleFormulaResult(): Promise<IFormulaResult[] | undefined> {
+ return Promise.resolve(undefined);
+ }
+
+ getRuleFormulaResultSync(): IFormulaResult[] | undefined {
+ return undefined;
+ }
+}
+
+class TestCheckboxValidator {
+ skipDefaultFontRender(): boolean {
+ return true;
+ }
+}
+
+class TestSheetDataValidationModel {
+ readonly rule: IDataValidationRule = {
+ uid: 'rule-checkbox',
+ type: DataValidationType.CHECKBOX,
+ ranges: [{ startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 }],
+ formula1: 'DONE',
+ formula2: 'TODO',
+ };
+
+ readonly validator = new TestCheckboxValidator();
+
+ getRuleByLocation(): IDataValidationRule {
+ return this.rule;
+ }
+
+ getValidator(): TestCheckboxValidator {
+ return this.validator;
+ }
+}
+
+function createInjector(): Injector {
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: RecordingCommandService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([SheetDataValidationModel, { useClass: TestSheetDataValidationModel as never }]);
+ injector.add([DataValidationFormulaService, { useClass: TestFormulaService as never }]);
+ injector.add([ThemeService, { useClass: TestThemeService as never }]);
+ return injector;
+}
+
+function createCellContext(value = 'DONE'): ICellRenderContext {
+ return {
+ data: { v: value },
+ style: null,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 3,
+ col: 4,
+ primaryWithCoord: {
+ startX: 20,
+ startY: 30,
+ endX: 140,
+ endY: 70,
+ actualRow: 8,
+ actualColumn: 9,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ startX: 20,
+ startY: 30,
+ endX: 140,
+ endY: 70,
+ startRow: 3,
+ endRow: 3,
+ startColumn: 4,
+ endColumn: 4,
+ },
+ },
+ worksheet: {
+ getCellRaw: () => ({ v: value }),
+ },
+ } as unknown as ICellRenderContext;
+}
+
+function getCommandService(injector: Injector): RecordingCommandService {
+ return injector.get(ICommandService) as unknown as RecordingCommandService;
+}
+
+describe('data validation canvas widgets', () => {
+ it('opens the single-select dropdown for the clicked cell and ignores secondary clicks', async () => {
+ const injector = createInjector();
+ const { DropdownWidget } = await import('../dropdown-widget');
+ const widget = injector.createInstance(DropdownWidget);
+ const cellContext = createCellContext();
+ const commandService = getCommandService(injector);
+
+ widget.onPointerDown(cellContext, { button: 0 } as never);
+ widget.onPointerDown(cellContext, { button: 2 } as never);
+
+ expect(commandService.commands).toEqual([
+ {
+ id: ShowDataValidationDropdown.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 3,
+ column: 4,
+ },
+ },
+ ]);
+ });
+
+ it('limits multi-select dropdown hit testing to the arrow affordance before opening it', async () => {
+ const injector = createInjector();
+ const { DropdownMultipleWidget } = await import('../dropdown-multiple-widget');
+ const widget = injector.createInstance(DropdownMultipleWidget);
+ const cellContext = createCellContext();
+
+ expect(widget.isHit({ x: 132, y: 45 }, cellContext)).toBe(true);
+ expect(widget.isHit({ x: 120, y: 45 }, cellContext)).toBe(false);
+
+ widget.onPointerDown(cellContext, { button: 0 } as never);
+
+ expect(getCommandService(injector).commands).toEqual([
+ {
+ id: ShowDataValidationDropdown.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 3,
+ column: 4,
+ },
+ },
+ ]);
+ });
+
+ it('toggles checkbox cells from the checked formula value to the unchecked formula value', async () => {
+ const injector = createInjector();
+ const { CheckboxRender } = await import('../checkbox-widget');
+ const widget = injector.createInstance(CheckboxRender);
+
+ await widget.onPointerDown(createCellContext('DONE'), { button: 0 } as never);
+
+ expect(getCommandService(injector).commands).toEqual([
+ {
+ id: SetRangeValuesCommand.id,
+ params: {
+ range: {
+ startColumn: 9,
+ endColumn: 9,
+ startRow: 8,
+ endRow: 8,
+ },
+ value: {
+ v: 'TODO',
+ p: null,
+ },
+ } satisfies ISetRangeValuesCommandParams,
+ },
+ ]);
+ });
+});
diff --git a/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts b/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts
index 8832d39b37..a4d4805643 100644
--- a/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts
+++ b/packages/sheets-data-validation/src/facade/__tests__/f-data-validation-builder.spec.ts
@@ -15,7 +15,7 @@
*/
import type { FUniver } from '@univerjs/core/facade';
-import { DataValidationOperator, DataValidationType } from '@univerjs/core';
+import { DataValidationErrorStyle, DataValidationOperator, DataValidationType } from '@univerjs/core';
import { deserializeListOptions } from '@univerjs/sheets';
import { FDataValidationBuilder } from '@univerjs/sheets-data-validation/facade/f-data-validation-builder.js';
import { beforeEach, describe, expect, it } from 'vitest';
@@ -135,6 +135,20 @@ describe('Test FDataValidationBuilder', () => {
expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.NOT_BETWEEN, '1', '2']);
});
+ it('should build decimal and whole number not equal rules', () => {
+ const decimalBuilder = new FDataValidationBuilder();
+ decimalBuilder.requireNumberNotEqualTo(10);
+
+ expect(decimalBuilder.getCriteriaType()).toBe(DataValidationType.DECIMAL);
+ expect(decimalBuilder.getCriteriaValues()).toEqual([DataValidationOperator.NOT_EQUAL, '10', undefined]);
+
+ const wholeBuilder = new FDataValidationBuilder();
+ wholeBuilder.requireNumberNotEqualTo(7, true);
+
+ expect(wholeBuilder.getCriteriaType()).toBe(DataValidationType.WHOLE);
+ expect(wholeBuilder.getCriteriaValues()).toEqual([DataValidationOperator.NOT_EQUAL, '7', undefined]);
+ });
+
it('should build date equal', () => {
const builder = new FDataValidationBuilder();
builder.requireDateEqualTo(new Date('2020-01-01'));
@@ -221,4 +235,38 @@ describe('Test FDataValidationBuilder', () => {
expect(builder.build().getCriteriaType()).toEqual(DataValidationType.LIST);
expect(builder.getCriteriaValues()).toEqual([undefined, '=[test]sheet1!A1', undefined]);
});
+
+ it('copies configured rules and keeps user-facing validation options', () => {
+ const builder = new FDataValidationBuilder();
+ builder
+ .requireValueInList(['Approved', 'Rejected'])
+ .setAllowInvalid(false)
+ .setAllowBlank(false)
+ .setOptions({
+ error: 'Choose an approval state',
+ showErrorMessage: true,
+ });
+
+ expect(builder.getCriteriaType()).toBe(DataValidationType.LIST);
+ expect(builder.getHelpText()).toBe('Choose an approval state');
+ expect(builder.getAllowInvalid()).toBe(false);
+
+ const rule = builder.build().rule;
+ expect(rule).toMatchObject({
+ errorStyle: DataValidationErrorStyle.STOP,
+ allowBlank: false,
+ error: 'Choose an approval state',
+ showErrorMessage: true,
+ });
+
+ const copiedRule = builder.copy().build().rule;
+ expect(copiedRule).toMatchObject({
+ type: rule.type,
+ formula1: rule.formula1,
+ errorStyle: DataValidationErrorStyle.STOP,
+ allowBlank: false,
+ error: 'Choose an approval state',
+ });
+ expect(copiedRule.uid).not.toBe(rule.uid);
+ });
});
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.ts
index d977f537e4..3a98d91ec0 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
@@ -14,18 +14,30 @@
* limitations under the License.
*/
-/* eslint-disable ts/no-non-null-asserted-optional-chain */
-
import type { Injector } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
-import { DataValidationType, ICommandService } from '@univerjs/core';
+import {
+ DataValidationErrorStyle,
+ DataValidationOperator,
+ DataValidationStatus,
+ DataValidationType,
+ ICommandService,
+} from '@univerjs/core';
import {
FormulaExecuteStageType,
SetFormulaCalculationNotificationMutation,
SetFormulaCalculationResultMutation,
SetFormulaCalculationStartMutation,
} from '@univerjs/engine-formula';
-import { AddSheetDataValidationCommand, DataValidationCustomFormulaService } from '@univerjs/sheets-data-validation';
+import {
+ AddSheetDataValidationCommand,
+ ClearRangeDataValidationCommand,
+ DataValidationCustomFormulaService,
+ RemoveSheetDataValidationCommand,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
+ UpdateSheetDataValidationSettingCommand,
+} from '@univerjs/sheets-data-validation';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createFacadeTestBed } from './create-test-bed';
@@ -43,7 +55,14 @@ describe('Test FRange', () => {
univerAPI = testBed.univerAPI;
commandService = get(ICommandService);
- commandService.registerCommand(AddSheetDataValidationCommand);
+ [
+ AddSheetDataValidationCommand,
+ ClearRangeDataValidationCommand,
+ RemoveSheetDataValidationCommand,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
+ UpdateSheetDataValidationSettingCommand,
+ ].forEach((command) => commandService.registerCommand(command));
commandService.registerCommand(SetFormulaCalculationStartMutation);
commandService.registerCommand(SetFormulaCalculationNotificationMutation);
commandService.registerCommand(SetFormulaCalculationResultMutation);
@@ -55,7 +74,10 @@ describe('Test FRange', () => {
});
it('Range set data validation', async () => {
- const activeSheet = univerAPI.getActiveWorkbook()?.getActiveSheet()!;
+ const activeSheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
+ if (!activeSheet) {
+ throw new Error('Active sheet not found');
+ }
const range = activeSheet.getRange(0, 0, 10, 10);
const range2 = activeSheet.getRange(11, 11, 2, 2);
await range.setDataValidation(univerAPI.newDataValidation().requireCheckbox().build());
@@ -78,6 +100,58 @@ describe('Test FRange', () => {
expect(activeSheet?.getDataValidations().length).toEqual(2);
});
+ it('manages an applied validation rule from a range facade', async () => {
+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ const sourceRange = activeSheet.getRange(0, 0, 2, 1);
+ const targetRange = activeSheet.getRange(3, 0, 2, 1);
+
+ const rule = univerAPI.newDataValidation()
+ .requireNumberBetween(1, 10)
+ .setOptions({
+ errorStyle: DataValidationErrorStyle.STOP,
+ showErrorMessage: true,
+ error: 'Use a number from 1 to 10',
+ })
+ .build();
+
+ sourceRange.setDataValidation(rule);
+ const appliedRule = sourceRange.getDataValidation()!;
+
+ expect(appliedRule.getApplied()).toBe(true);
+ expect(appliedRule.getAllowInvalid()).toBe(false);
+ expect(appliedRule.getCriteriaType()).toBe(DataValidationType.DECIMAL);
+ expect(appliedRule.getCriteriaValues()).toEqual([DataValidationOperator.BETWEEN, '1', '10']);
+ expect(appliedRule.getHelpText()).toBe('Use a number from 1 to 10');
+ expect(appliedRule.getUnitId()).toBe(univerAPI.getActiveWorkbook()!.getId());
+ expect(appliedRule.getSheetId()).toBe(activeSheet.getSheetId());
+ expect(appliedRule.getRanges().map((range) => range.getA1Notation())).toEqual(['A1:A2']);
+ expect(appliedRule.copy().getCriteriaValues()).toEqual([DataValidationOperator.BETWEEN, '1', '10']);
+
+ appliedRule
+ .setCriteria(DataValidationType.DECIMAL, [DataValidationOperator.GREATER_THAN, '2', undefined as never], false)
+ .setOptions({ error: 'Use a whole number greater than 2', showErrorMessage: false })
+ .setRanges([targetRange]);
+
+ const movedRule = targetRange.getDataValidation()!;
+ expect(sourceRange.getDataValidation()).toBeUndefined();
+ expect(movedRule.getCriteriaType()).toBe(DataValidationType.DECIMAL);
+ expect(movedRule.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN, '2', undefined]);
+ expect(movedRule.getHelpText()).toBe('Use a whole number greater than 2');
+ expect(movedRule.getRanges().map((range) => range.getA1Notation())).toEqual(['A4:A5']);
+
+ expect(await targetRange.getValidatorStatus()).toEqual([
+ [DataValidationStatus.INVALID, DataValidationStatus.INVALID],
+ ]);
+
+ expect(movedRule.delete()).toBe(true);
+ expect(targetRange.getDataValidation()).toBeUndefined();
+
+ targetRange.setDataValidation(rule);
+ expect(targetRange.getDataValidations()).toHaveLength(1);
+ targetRange.setDataValidation(null);
+ expect(targetRange.getDataValidations()).toEqual([]);
+ });
+
it('resolves onCalculationResultApplied after data-validation custom formula results are emitted', async () => {
const workbook = univerAPI.getActiveWorkbook()!;
const activeSheet = workbook.getActiveSheet();
diff --git a/packages/sheets-data-validation/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-data-validation/src/facade/__tests__/f-univer.spec.ts
new file mode 100644
index 0000000000..0cf6cb65b1
--- /dev/null
+++ b/packages/sheets-data-validation/src/facade/__tests__/f-univer.spec.ts
@@ -0,0 +1,159 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DataValidationOperator, DataValidationStatus, DataValidationType, ICommandService } from '@univerjs/core';
+import {
+ AddSheetDataValidationCommand,
+ ClearRangeDataValidationCommand,
+ RemoveSheetAllDataValidationCommand,
+ RemoveSheetDataValidationCommand,
+ SheetDataValidationModel,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
+ UpdateSheetDataValidationSettingCommand,
+} from '@univerjs/sheets-data-validation';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createFacadeTestBed } from './create-test-bed';
+
+describe('FUniver sheets data validation events', () => {
+ let testBed: ReturnType<typeof createFacadeTestBed>;
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ testBed = createFacadeTestBed();
+ commandService = testBed.get(ICommandService);
+ [
+ AddSheetDataValidationCommand,
+ ClearRangeDataValidationCommand,
+ RemoveSheetAllDataValidationCommand,
+ RemoveSheetDataValidationCommand,
+ UpdateSheetDataValidationOptionsCommand,
+ UpdateSheetDataValidationRangeCommand,
+ UpdateSheetDataValidationSettingCommand,
+ ].forEach((command) => commandService.registerCommand(command));
+ });
+
+ afterEach(() => {
+ testBed.univer.dispose();
+ });
+
+ it('fires before and changed events around validation rule lifecycle commands', () => {
+ const { univerAPI } = testBed;
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet();
+ const range = worksheet.getRange(0, 0, 1, 1);
+ const movedRange = worksheet.getRange(2, 0, 1, 1);
+ const logs: string[] = [];
+
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationAdd, ({ rule, worksheet }) => {
+ logs.push(`before-add:${worksheet.getSheetId()}:${rule.type}`);
+ });
+ univerAPI.addEvent(univerAPI.Event.SheetDataValidationChanged, ({ changeType, rule }) => {
+ logs.push(`changed:${changeType}:${rule.getCriteriaType()}`);
+ });
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationCriteriaUpdate, ({ newCriteria }) => {
+ logs.push(`before-criteria:${newCriteria.type}:${newCriteria.formula1}`);
+ });
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationOptionsUpdate, ({ newOptions }) => {
+ logs.push(`before-options:${newOptions.error}`);
+ });
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationRangeUpdate, ({ newRanges }) => {
+ logs.push(`before-range:${newRanges[0].startRow}`);
+ });
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationDelete, ({ ruleId }) => {
+ logs.push(`before-delete:${ruleId}`);
+ });
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationDeleteAll, ({ rules }) => {
+ logs.push(`before-delete-all:${rules.length}`);
+ });
+
+ const rule = univerAPI.newDataValidation()
+ .requireNumberBetween(1, 5)
+ .build();
+
+ range.setDataValidation(rule);
+ const appliedRule = range.getDataValidation()!;
+ const ruleId = appliedRule.rule.uid;
+
+ appliedRule.setCriteria(DataValidationType.DECIMAL, [DataValidationOperator.GREATER_THAN, '2', undefined as never]);
+ appliedRule.setOptions({ error: 'Use a whole number greater than 2' });
+ appliedRule.setRanges([movedRange]);
+ expect(movedRange.getDataValidation()?.delete()).toBe(true);
+
+ movedRange.setDataValidation(univerAPI.newDataValidation().requireCheckbox().build());
+ expect(commandService.syncExecuteCommand(RemoveSheetAllDataValidationCommand.id, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ })).toBe(true);
+
+ expect(logs).toEqual([
+ `before-add:${worksheet.getSheetId()}:${DataValidationType.DECIMAL}`,
+ `changed:add:${DataValidationType.DECIMAL}`,
+ `before-criteria:${DataValidationType.DECIMAL}:2`,
+ `changed:update:${DataValidationType.DECIMAL}`,
+ 'before-options:Use a whole number greater than 2',
+ `changed:update:${DataValidationType.DECIMAL}`,
+ 'before-range:2',
+ `changed:update:${DataValidationType.DECIMAL}`,
+ `before-delete:${ruleId}`,
+ `changed:remove:${DataValidationType.DECIMAL}`,
+ `before-add:${worksheet.getSheetId()}:${DataValidationType.CHECKBOX}`,
+ `changed:add:${DataValidationType.CHECKBOX}`,
+ 'before-delete-all:1',
+ `changed:remove:${DataValidationType.CHECKBOX}`,
+ ]);
+ });
+
+ it('cancels validation commands from before events', () => {
+ const { univerAPI } = testBed;
+ const range = univerAPI.getActiveWorkbook()!.getActiveSheet().getRange(0, 0, 1, 1);
+ univerAPI.addEvent(univerAPI.Event.BeforeSheetDataValidationAdd, (event) => {
+ event.cancel = true;
+ });
+
+ range.setDataValidation(univerAPI.newDataValidation().requireCheckbox().build());
+
+ expect(range.getDataValidation()).toBeUndefined();
+ });
+
+ it('fires validator status changes for cells whose validation result changes', async () => {
+ const { get, univerAPI } = testBed;
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet();
+ const range = worksheet.getRange(0, 0, 1, 1);
+ const statuses: string[] = [];
+
+ range.setDataValidation(univerAPI.newDataValidation().requireNumberBetween(1, 5).build());
+ const rule = range.getDataValidation()!;
+
+ univerAPI.addEvent(univerAPI.Event.SheetDataValidatorStatusChanged, ({ column, row, rule, status }) => {
+ statuses.push(`${row}:${column}:${rule.getCriteriaType()}:${status}`);
+ });
+
+ get(SheetDataValidationModel).validator(rule.rule, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ workbook: workbook.getWorkbook(),
+ worksheet: worksheet.getSheet(),
+ row: 0,
+ col: 0,
+ });
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(statuses).toEqual([`0:0:${DataValidationType.DECIMAL}:${DataValidationStatus.VALID}`]);
+ });
+});
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.ts
index 78901ad77a..b6bce1c4c8 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
@@ -17,6 +17,7 @@
import type { Injector, IWorkbookData } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
import {
+ DataValidationStatus,
ICommandService,
LocaleType,
} from '@univerjs/core';
@@ -29,7 +30,7 @@ import {
UpdateSheetDataValidationRangeCommand,
UpdateSheetDataValidationSettingCommand,
} from '@univerjs/sheets-data-validation';
-import { beforeEach, describe } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createFacadeTestBed } from './create-test-bed';
function createWorkbookData(): IWorkbookData {
@@ -60,9 +61,11 @@ function createWorkbookData(): IWorkbookData {
describe('Test FWorksheet data validation facade', () => {
let get: Injector['get'];
let univerAPI: FUniver;
+ let univer: ReturnType<typeof createFacadeTestBed>['univer'];
beforeEach(() => {
const testBed = createFacadeTestBed(createWorkbookData());
+ univer = testBed.univer;
get = testBed.get;
univerAPI = testBed.univerAPI;
@@ -77,4 +80,104 @@ describe('Test FWorksheet data validation facade', () => {
UpdateSheetDataValidationSettingCommand,
].forEach((command) => commandService.registerCommand(command));
});
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('reads worksheet rules, validator status, and validation errors', async () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet();
+ const range = worksheet.getRange(0, 0, 4, 1);
+ const rule = univerAPI.newDataValidation()
+ .requireNumberBetween(1, 2)
+ .setOptions({
+ showErrorMessage: true,
+ error: 'Only values from 1 to 2 are valid',
+ })
+ .build();
+
+ range.setDataValidation(rule);
+
+ const rules = worksheet.getDataValidations();
+ expect(rules).toHaveLength(1);
+ expect(worksheet.getDataValidation(rules[0].rule.uid)?.getCriteriaValues()).toEqual(
+ rules[0].getCriteriaValues()
+ );
+ expect(worksheet.getDataValidation('missing-rule')).toBeNull();
+
+ const worksheetStatus = await worksheet.getValidatorStatusAsync();
+ expect(worksheetStatus.getValue(2, 0)).toBe(DataValidationStatus.INVALID);
+ expect(worksheetStatus.getValue(3, 0)).toBe(DataValidationStatus.INVALID);
+
+ await expect(range.getDataValidationErrorAsync()).resolves.toMatchObject([
+ {
+ sheetName: 'sheet1',
+ row: 2,
+ column: 0,
+ ruleId: rules[0].rule.uid,
+ inputValue: 3,
+ },
+ {
+ sheetName: 'sheet1',
+ row: 3,
+ column: 0,
+ ruleId: rules[0].rule.uid,
+ inputValue: 4,
+ },
+ ]);
+
+ await expect(worksheet.getAllDataValidationErrorAsync()).resolves.toMatchObject([
+ {
+ sheetName: 'sheet1',
+ row: 2,
+ column: 0,
+ inputValue: 3,
+ },
+ {
+ sheetName: 'sheet1',
+ row: 3,
+ column: 0,
+ inputValue: 4,
+ },
+ ]);
+ });
+
+ it('aggregates validation status and errors at workbook level', async () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet();
+ const rule = univerAPI.newDataValidation()
+ .requireNumberLessThanOrEqualTo(2)
+ .build();
+
+ worksheet.getRange(0, 0, 4, 1).setDataValidation(rule);
+
+ const status = await workbook.getValidatorStatus();
+ expect(status.sheet1.getValue(2, 0)).toBe(DataValidationStatus.INVALID);
+ expect(status.sheet1.getValue(3, 0)).toBe(DataValidationStatus.INVALID);
+
+ await expect(workbook.getAllDataValidationErrorAsync()).resolves.toMatchObject([
+ {
+ sheetName: 'sheet1',
+ row: 2,
+ column: 0,
+ inputValue: 3,
+ },
+ {
+ sheetName: 'sheet1',
+ row: 3,
+ column: 0,
+ inputValue: 4,
+ },
+ ]);
+ });
+
+ it('returns empty error lists when no rule is applied', async () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet();
+
+ await expect(worksheet.getAllDataValidationErrorAsync()).resolves.toEqual([]);
+ await expect(workbook.getAllDataValidationErrorAsync()).resolves.toEqual([]);
+ await expect(worksheet.getRange(0, 0, 1, 1).getDataValidationErrorAsync()).resolves.toEqual([]);
+ });
});
diff --git a/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx b/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx
new file mode 100644
index 0000000000..e62f411978
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/batch-save-images/__tests__/BatchSaveImagesDialog.spec.tsx
@@ -0,0 +1,341 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ISelectionWithStyle } from '@univerjs/sheets';
+import type { Root } from 'react-dom/client';
+import type { IBatchSaveImagesConfig, ICellImageInfo } from '../../../services/batch-save-images.service';
+import { Disposable, ImageSourceType, toDisposable } from '@univerjs/core';
+import { IMarkSelectionService } from '@univerjs/sheets-ui';
+import { IDialogService, RediContext } 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 { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+import { FileNamePart, IBatchSaveImagesService } from '../../../services/batch-save-images.service';
+import { BatchSaveImagesDialog } from '../BatchSaveImagesDialog';
+import { BATCH_SAVE_IMAGES_DIALOG_ID } from '../component-name';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestDialogService extends Disposable implements IDialogService {
+ private readonly _closedIds: string[] = [];
+ private readonly _dialogs$ = new BehaviorSubject<any[]>([]);
+
+ open(): IDisposable {
+ return toDisposable(() => undefined);
+ }
+
+ close(id: string): void {
+ this._closedIds.push(id);
+ }
+
+ closeAll(): void {
+ this._closedIds.push('*');
+ }
+
+ getDialogs$() {
+ return this._dialogs$.asObservable();
+ }
+
+ get closedIds(): string[] {
+ return this._closedIds;
+ }
+
+ override dispose(): void {
+ super.dispose();
+ this._dialogs$.complete();
+ }
+}
+
+class TestMarkSelectionService implements IMarkSelectionService {
+ private _nextId = 1;
+ private readonly _shapeMap = new Map<string, ISelectionWithStyle>();
+ private readonly _addedRanges: IRange[] = [];
+ private readonly _removedIds: string[] = [];
+
+ addShape(selection: ISelectionWithStyle): string {
+ const id = `shape-${this._nextId++}`;
+ this._shapeMap.set(id, selection);
+ this._addedRanges.push(selection.range);
+ return id;
+ }
+
+ addShapeWithNoFresh(selection: ISelectionWithStyle): string {
+ return this.addShape(selection);
+ }
+
+ removeShape(id: string): void {
+ this._shapeMap.delete(id);
+ this._removedIds.push(id);
+ }
+
+ removeAllShapes(): void {
+ this._shapeMap.clear();
+ }
+
+ refreshShapes(): void {
+ return undefined;
+ }
+
+ getShapeMap(): ReturnType<IMarkSelectionService['getShapeMap']> {
+ return this._shapeMap as unknown as ReturnType<IMarkSelectionService['getShapeMap']>;
+ }
+
+ get addedRanges(): IRange[] {
+ return this._addedRanges;
+ }
+
+ get activeRanges(): IRange[] {
+ return Array.from(this._shapeMap.values()).map((selection) => selection.range);
+ }
+
+ get removedIds(): string[] {
+ return this._removedIds;
+ }
+}
+
+class TestBatchSaveImagesService implements IBatchSaveImagesService {
+ private readonly _images = [
+ createImage('image-a', 'B3', 2, 1),
+ createImage('image-b', 'B4', 3, 1),
+ ];
+
+ private readonly _dataColumns = [
+ { index: 4, label: 'Name' },
+ { index: 6, label: 'SKU' },
+ ];
+
+ private _failSaving = false;
+ private _savedImages: ICellImageInfo[] = [];
+ private _savedConfig: IBatchSaveImagesConfig | null = null;
+
+ failSaving(): void {
+ this._failSaving = true;
+ }
+
+ get savedImages(): ICellImageInfo[] {
+ return this._savedImages;
+ }
+
+ get savedConfig(): IBatchSaveImagesConfig | null {
+ return this._savedConfig;
+ }
+
+ getCellImagesInSelection(): ICellImageInfo[] {
+ return this._images;
+ }
+
+ getCellImagesFromRanges(): ICellImageInfo[] {
+ return this._images;
+ }
+
+ getDataColumns(): Array<{ index: number; label: string }> {
+ return this._dataColumns;
+ }
+
+ getDataColumnsForRanges(): Array<{ index: number; label: string }> {
+ return this._dataColumns;
+ }
+
+ getSelectionRangeNotation(): string {
+ return 'B3:B4';
+ }
+
+ generateFileName(imageInfo: ICellImageInfo): string {
+ return imageInfo.cellAddress;
+ }
+
+ generateFileNameWithContext(imageInfo: ICellImageInfo): string {
+ return imageInfo.cellAddress;
+ }
+
+ async saveImages(images: ICellImageInfo[], config: IBatchSaveImagesConfig): Promise<void> {
+ if (this._failSaving) {
+ throw new Error('save failed');
+ }
+
+ this._savedImages = images;
+ this._savedConfig = config;
+ }
+
+ async saveImagesWithContext(images: ICellImageInfo[], config: IBatchSaveImagesConfig): Promise<void> {
+ await this.saveImages(images, config);
+ }
+
+ async downloadSingleImage(): Promise<void> {
+ return undefined;
+ }
+
+ getSelectionRowRange(): { startRow: number; endRow: number } {
+ return { startRow: 2, endRow: 3 };
+ }
+
+ getSelectionColumnIndices(): Set<number> {
+ return new Set([1]);
+ }
+
+ registerURLImageDownloader(): IDisposable {
+ return toDisposable(() => undefined);
+ }
+}
+
+function createImage(imageId: string, cellAddress: string, row: number, col: number): ICellImageInfo {
+ return {
+ row,
+ col,
+ cellAddress,
+ imageId,
+ source: `https://example.com/${imageId}.png`,
+ imageSourceType: ImageSourceType.URL,
+ };
+}
+
+function getButton(container: HTMLElement, text: string): HTMLButtonElement {
+ const button = Array.from(container.querySelectorAll('button')).find((button) => button.textContent === text);
+ if (!button) {
+ throw new Error(`Button ${text} was not rendered`);
+ }
+
+ return button;
+}
+
+function getCheckbox(container: HTMLElement, index: number): HTMLInputElement {
+ const checkbox = container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]')[index];
+ if (!checkbox) {
+ throw new Error(`Checkbox ${index} was not rendered`);
+ }
+
+ return checkbox;
+}
+
+function openSelect(select: HTMLElement): void {
+ select.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+}
+
+describe('BatchSaveImagesDialog', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ async function renderDialog() {
+ const testBed = createSheetsDrawingUiTestBed(undefined, [
+ [IDialogService, { useClass: TestDialogService }],
+ [IMarkSelectionService, { useClass: TestMarkSelectionService }],
+ [IBatchSaveImagesService, { useClass: TestBatchSaveImagesService }],
+ ]);
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <BatchSaveImagesDialog />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ return {
+ testBed,
+ batchSaveService: testBed.get(IBatchSaveImagesService) as TestBatchSaveImagesService,
+ dialogService: testBed.get(IDialogService) as unknown as TestDialogService,
+ markSelectionService: testBed.get(IMarkSelectionService) as TestMarkSelectionService,
+ };
+ }
+
+ it('saves selected images with the chosen column value in file names', async () => {
+ const { testBed, batchSaveService, dialogService, markSelectionService } = await renderDialog();
+ const columnValueCheckbox = getCheckbox(container!, 1);
+
+ await act(async () => {
+ columnValueCheckbox.click();
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([{
+ startRow: 2,
+ endRow: 3,
+ startColumn: 4,
+ endColumn: 4,
+ }]);
+
+ await act(async () => {
+ openSelect(container!.querySelector<HTMLElement>('[data-u-comp="select"]')!);
+ await Promise.resolve();
+ });
+
+ const skuOption = Array.from(document.body.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"]'))
+ .find((item) => item.textContent === 'SKU');
+ if (!skuOption) {
+ throw new Error('SKU column option was not rendered');
+ }
+
+ await act(async () => {
+ skuOption.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(markSelectionService.activeRanges).toEqual([{
+ startRow: 2,
+ endRow: 3,
+ startColumn: 6,
+ endColumn: 6,
+ }]);
+ expect(markSelectionService.removedIds).toEqual(['shape-1']);
+
+ await act(async () => {
+ getButton(container!, 'sheets-drawing-ui.save.confirm').click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedImages.map((image) => image.imageId)).toEqual(['image-a', 'image-b']);
+ expect(batchSaveService.savedConfig).toEqual({
+ fileNameParts: [FileNamePart.CELL_ADDRESS, FileNamePart.COLUMN_VALUE],
+ columnIndex: 6,
+ });
+ expect(dialogService.closedIds).toEqual([BATCH_SAVE_IMAGES_DIALOG_ID]);
+
+ testBed.univer.dispose();
+ });
+
+ it('keeps the dialog open and shows the save error when saving fails', async () => {
+ const { testBed, batchSaveService, dialogService } = await renderDialog();
+ batchSaveService.failSaving();
+
+ await act(async () => {
+ getButton(container!, 'sheets-drawing-ui.save.confirm').click();
+ await Promise.resolve();
+ });
+
+ expect(batchSaveService.savedConfig).toBeNull();
+ expect(dialogService.closedIds).toEqual([]);
+ expect(container!.textContent).toContain('sheets-drawing-ui.save.error');
+
+ testBed.univer.dispose();
+ });
+});
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.ts
index 4962e9841f..33964169ea 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
@@ -16,10 +16,12 @@
import type { Injector, Univer } from '@univerjs/core';
import type { ISheetImage } from '@univerjs/sheets-drawing';
-import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
+import { DrawingTypeEnum, ICommandService, ImageSourceType } from '@univerjs/core';
import { SheetSkeletonService } from '@univerjs/sheets';
+import { ISheetDrawingService } from '@univerjs/sheets-drawing';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';
+import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-drawing.command';
import { FOverGridImage } from '../f-over-grid-image';
describe('FOverGridImage', () => {
@@ -85,4 +87,103 @@ describe('FOverGridImage', () => {
warnSpy.mockRestore();
});
+
+ it('updates image data and removes the image through facade methods', async () => {
+ const image = createImage();
+ const commandService = injector.get(ICommandService);
+ const sheetDrawingService = injector.get(ISheetDrawingService);
+ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, { unitId: 'test', drawings: [image] })).toBe(true);
+
+ const fImage = injector.createInstance(FOverGridImage, image);
+
+ expect(fImage.setSource('https://example.com/updated.png', ImageSourceType.URL)).toBe(true);
+ expect(getStoredImage('drawing-1').source).toBe('https://example.com/updated.png');
+
+ expect(await fImage.setPositionAsync(4, 5, 6, 7)).toBe(true);
+ expect(getStoredImage('drawing-1').sheetTransform.from).toEqual(expect.objectContaining({
+ row: 4,
+ column: 5,
+ rowOffset: 6,
+ columnOffset: 7,
+ }));
+
+ expect(await fImage.setSizeAsync(160, 90)).toBe(true);
+ expect(getStoredImage('drawing-1').transform).toEqual(expect.objectContaining({
+ width: 160,
+ height: 90,
+ }));
+
+ expect(fImage.setCrop(1, 2, 3, 4)).toBe(true);
+ expect(getStoredImage('drawing-1').srcRect).toEqual({ top: 1, left: 2, bottom: 3, right: 4 });
+
+ expect(fImage.setRotate(30)).toBe(true);
+ expect(getStoredImage('drawing-1').sheetTransform.angle).toBe(30);
+
+ expect(fImage.setForward()).toBe(true);
+ expect(fImage.setBackward()).toBe(true);
+ expect(fImage.setFront()).toBe(true);
+ expect(fImage.setBack()).toBe(true);
+
+ expect(fImage.remove()).toBe(true);
+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-1' })).toBeUndefined();
+ });
+
+ function getStoredImage(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;
+ }
});
+
+function createImage(): ISheetImage {
+ return {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: 'drawing-1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType: ImageSourceType.URL,
+ source: 'https://example.com/drawing-1.png',
+ transform: {
+ left: 20,
+ top: 30,
+ width: 100,
+ height: 60,
+ },
+ sheetTransform: {
+ from: {
+ row: 1,
+ rowOffset: 0,
+ column: 1,
+ columnOffset: 0,
+ },
+ to: {
+ row: 4,
+ rowOffset: 0,
+ column: 3,
+ columnOffset: 0,
+ },
+ },
+ axisAlignSheetTransform: {
+ from: {
+ row: 1,
+ rowOffset: 0,
+ column: 1,
+ columnOffset: 0,
+ },
+ to: {
+ row: 4,
+ rowOffset: 0,
+ column: 3,
+ columnOffset: 0,
+ },
+ },
+ };
+}
diff --git a/packages/sheets-drawing/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-univer.spec.ts
index 44c8ffd576..622e1ad237 100644
--- a/packages/sheets-drawing/src/facade/__tests__/f-univer.spec.ts
+++ b/packages/sheets-drawing/src/facade/__tests__/f-univer.spec.ts
@@ -16,7 +16,9 @@
import type { Injector, Univer } from '@univerjs/core';
import type { ISheetImage } from '@univerjs/sheets-drawing';
+import { ICommandService } from '@univerjs/core';
import { FUniver } from '@univerjs/core/facade';
+import { SetDrawingSelectedOperation } from '@univerjs/drawing';
import { ISheetDrawingService } from '@univerjs/sheets-drawing';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';
@@ -57,6 +59,73 @@ describe('sheets drawing facade image lifecycle', () => {
disposable.dispose();
});
+
+ it('emits image lifecycle events around insert, change, select, and remove operations', async () => {
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ const commandService = injector.get(ICommandService);
+ const events: string[] = [];
+ const disposables = [
+ univerAPI.addEvent(univerAPI.Event.BeforeOverGridImageInsert, (event) => {
+ events.push(`before-insert:${event.insertImageParams[0].source}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.OverGridImageInserted, (event) => {
+ events.push(`inserted:${event.images[0].getId()}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.BeforeOverGridImageChange, (event) => {
+ events.push(`before-change:${event.images[0].changeParam.source}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.OverGridImageChanged, (event) => {
+ events.push(`changed:${event.images[0].toBuilder().getSource()}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.BeforeOverGridImageSelect, (event) => {
+ events.push(`before-select:${event.selectedImages[0].getId()}:${event.oldSelectedImages.length}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.OverGridImageSelected, (event) => {
+ events.push(`selected:${event.selectedImages[0].getId()}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.BeforeOverGridImageRemove, (event) => {
+ events.push(`before-remove:${event.images[0].getId()}`);
+ }),
+ univerAPI.addEvent(univerAPI.Event.OverGridImageRemoved, (event) => {
+ events.push(`removed:${event.removeImageParams[0].drawingId}`);
+ }),
+ ];
+ const image = await worksheet.newOverGridImage()
+ .setSource('https://example.com/image.png', univerAPI.Enum.ImageSourceType.URL)
+ .setWidth(40)
+ .setHeight(30)
+ .buildAsync();
+
+ expect(worksheet.insertImages([image])).toBe(worksheet);
+ expect(getStoredImage(injector, image.drawingId).source).toBe('https://example.com/image.png');
+
+ const imageFacade = worksheet.getImageById(image.drawingId)!;
+ expect(imageFacade.setSource('https://example.com/updated.png', univerAPI.Enum.ImageSourceType.URL)).toBe(true);
+
+ expect(commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, [{
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: image.drawingId,
+ drawingType: image.drawingType,
+ }])).toBe(true);
+
+ expect(imageFacade.remove()).toBe(true);
+
+ expect(events).toEqual([
+ 'before-insert:https://example.com/image.png',
+ `inserted:${image.drawingId}`,
+ 'before-change:https://example.com/updated.png',
+ 'changed:https://example.com/updated.png',
+ `before-select:${image.drawingId}:0`,
+ `selected:${image.drawingId}`,
+ `before-remove:${image.drawingId}`,
+ `removed:${image.drawingId}`,
+ ]);
+
+ for (const disposable of disposables) {
+ disposable.dispose();
+ }
+ });
});
function getStoredImage(injector: Injector, drawingId: string): ISheetImage {
diff --git a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
index 11f952d984..e9d0280217 100644
--- a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
+++ b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
@@ -20,6 +20,7 @@ import type { ISheetDrawing } from '../../services/sheet-drawing.service';
import {
DrawingTypeEnum,
ICommandService,
+ ImageSourceType,
IUniverInstanceService,
RedoCommand,
UndoCommand,
@@ -168,6 +169,78 @@ describe('FWorksheetDrawingMixin group drawings', () => {
expect(recursiveChildren).toHaveLength(4);
expect(recursiveChildren).toEqual(expect.arrayContaining(['drawing-1', 'drawing-2', 'drawing-3', 'group-1']));
});
+
+ it('inserts, reads, updates, and deletes over-grid images through the worksheet facade', async () => {
+ const sheetDrawingService = injector.get(ISheetDrawingService);
+ const fWorksheet = createFacade(injector);
+ const image = await fWorksheet.newOverGridImage()
+ .setSource('https://example.com/image.png', ImageSourceType.URL)
+ .setColumn(2)
+ .setRow(3)
+ .setColumnOffset(4)
+ .setRowOffset(5)
+ .setWidth(120)
+ .setHeight(80)
+ .setCropTop(1)
+ .setCropLeft(2)
+ .setCropBottom(3)
+ .setCropRight(4)
+ .setRotate(15)
+ .buildAsync();
+
+ expect(fWorksheet.insertImages([image])).toBe(fWorksheet);
+
+ const images = fWorksheet.getImages();
+ expect(images).toHaveLength(1);
+ expect(images[0].getId()).toBe(image.drawingId);
+ expect(fWorksheet.getImageById(image.drawingId)?.toBuilder().getSource()).toBe('https://example.com/image.png');
+
+ const updatedImage = {
+ ...image,
+ source: 'https://example.com/updated.png',
+ };
+ expect(fWorksheet.updateImages([updatedImage])).toBe(fWorksheet);
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: image.drawingId,
+ }) as { source: string }).source).toBe('https://example.com/updated.png');
+
+ expect(fWorksheet.deleteImages(images)).toBe(fWorksheet);
+ expect(fWorksheet.getImageById(image.drawingId)).toBeNull();
+ expect(fWorksheet.getImages()).toEqual([]);
+ });
+
+ it('returns only images from sheet drawing data and exposes active images from the drawing selection', () => {
+ const commandService = injector.get(ICommandService);
+ const fWorksheet = createFacade(injector);
+ const image = createDrawing('image-1', 10, DrawingTypeEnum.DRAWING_IMAGE);
+ const shape = createDrawing('shape-1', 80, DrawingTypeEnum.DRAWING_SHAPE);
+
+ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, { unitId: 'test', drawings: [image, shape] })).toBe(true);
+ expect(fWorksheet.getImages().map((drawing) => drawing.getId())).toEqual(['image-1']);
+
+ injector.get(ISheetDrawingService).focusDrawing([{
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: 'image-1',
+ }]);
+
+ expect(fWorksheet.getActiveImages().map((drawing) => drawing.getId())).toEqual(['image-1']);
+ });
+
+ it('keeps grouping APIs inert when requested drawings or groups do not exist', () => {
+ const commandService = injector.get(ICommandService);
+ const fWorksheet = createFacade(injector);
+ const image = createDrawing('drawing-1', 10);
+
+ expect(commandService.syncExecuteCommand(InsertSheetDrawingCommand.id, { unitId: 'test', drawings: [image] })).toBe(true);
+
+ expect(fWorksheet.groupDrawings(['drawing-1', 'missing-drawing'], 'group-1')).toBeNull();
+ expect(fWorksheet.ungroupDrawings(['missing-group'])).toBe(false);
+ expect(fWorksheet.getDrawingGroupChildren('missing-group', true)).toEqual([]);
+ expect(fWorksheet.getDrawingParentGroup('drawing-1')).toBeNull();
+ });
});
function createFacade(injector: Injector): FWorksheetDrawingMixin {
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.tsx
index 7111f891fd..c97282c909 100644
--- a/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx
+++ b/packages/sheets-filter-ui/src/views/components/__tests__/SheetsFilterPanel.spec.tsx
@@ -223,10 +223,20 @@ function clickElement(element: Element) {
element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
}
+function openSelect(element: Element) {
+ element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+}
+
function changeCheckbox(input: HTMLInputElement) {
input.dispatchEvent(new MouseEvent('click', { bubbles: true }));
}
+function changeInput(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
function getButton(container: HTMLElement, text: string): HTMLElement {
const button = Array.from(container.querySelectorAll('[data-u-comp="button"]'))
.find((button) => button.textContent === text);
@@ -238,6 +248,28 @@ function getButton(container: HTMLElement, text: string): HTMLElement {
return button as HTMLElement;
}
+function getSelect(container: HTMLElement, index = 0): HTMLElement {
+ const select = container.querySelectorAll<HTMLElement>('[data-u-comp="select"]').item(index);
+ if (!select) {
+ throw new Error(`Select at index "${index}" was not rendered.`);
+ }
+
+ return select;
+}
+
+function getDropdownOption(text: string): HTMLElement {
+ const option = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"]'))
+ .find((item) => item.textContent === text);
+ if (!option) {
+ const renderedOptions = Array.from(document.querySelectorAll<HTMLElement>('[data-slot="dropdown-menu-radio-item"]'))
+ .map((item) => item.textContent)
+ .join(', ');
+ throw new Error(`Dropdown option "${text}" was not rendered. Options: ${renderedOptions}`);
+ }
+
+ return option;
+}
+
function getValueItemCheckbox(container: HTMLElement, title: string): HTMLInputElement {
const titleElement = Array.from(container.querySelectorAll('span'))
.find((element) => element.textContent === title);
@@ -424,6 +456,87 @@ describe('FilterPanel', () => {
expect(currentTestBed.contextService.getContextValue(FILTER_PANEL_OPENED_KEY)).toBe(false);
});
+ it('keeps value criteria unchanged when a changed candidate is cancelled', async () => {
+ currentTestBed = createFilterPanelViewTestBed(WithValuesAndEmptyFilterModelFactory());
+ await openPanel(currentTestBed);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderPanel(root, currentTestBed);
+
+ const michaelCheckbox = getValueItemCheckbox(container, 'Michael');
+ expect(michaelCheckbox.checked).toBe(false);
+
+ await act(async () => {
+ changeCheckbox(michaelCheckbox);
+ await awaitTime(20);
+ });
+
+ expect(getValueItemCheckbox(container, 'Michael').checked).toBe(true);
+
+ await act(async () => {
+ clickElement(getButton(container!, 'Cancel'));
+ await awaitTime(20);
+ });
+
+ expect(currentTestBed.filterService.activeFilterModel?.getFilterColumn(0)?.getColumnData().filters).toEqual({
+ blank: true,
+ filters: ['1'],
+ });
+ expect(currentTestBed.contextService.getContextValue(FILTER_PANEL_OPENED_KEY)).toBe(false);
+ });
+
+ it('applies text contains criteria from the conditions panel', async () => {
+ currentTestBed = createFilterPanelViewTestBed(WithValuesFilterModelFactory());
+ await openPanel(currentTestBed);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderPanel(root, currentTestBed);
+
+ const conditionButton = Array.from(container.querySelectorAll('[data-u-comp="segmented"] button'))
+ .find((button) => button.textContent === 'By Conditions') as HTMLElement;
+
+ await act(async () => {
+ clickElement(conditionButton);
+ await awaitTime(20);
+ });
+
+ await act(async () => {
+ openSelect(getSelect(container!));
+ await awaitTime(20);
+ });
+
+ await act(async () => {
+ clickElement(getDropdownOption('Text Contains'));
+ await awaitTime(20);
+ });
+
+ const input = container.querySelector<HTMLInputElement>('[data-u-comp="sheets-filter-panel-conditions-container-inner"] input');
+ if (!input) {
+ throw new Error('Condition value input was not rendered.');
+ }
+
+ await act(async () => {
+ changeInput(input, 'Michael');
+ await awaitTime(20);
+ });
+
+ await act(async () => {
+ clickElement(getButton(container!, 'Confirm'));
+ await awaitTime(20);
+ });
+
+ const columnData = currentTestBed.filterService.activeFilterModel?.getFilterColumn(0)?.getColumnData();
+ expect(columnData?.customFilters).toEqual({
+ customFilters: [{ val: '*Michael*' }],
+ });
+ expect(columnData?.filters).toBeUndefined();
+ 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);
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.ts
index 7f0375a03a..f36e3c9170 100644
--- a/packages/sheets-filter/src/services/__tests__/sheet-filter.service.spec.ts
+++ b/packages/sheets-filter/src/services/__tests__/sheet-filter.service.spec.ts
@@ -30,6 +30,7 @@ import {
UniverInstanceService,
Workbook,
} from '@univerjs/core';
+import { of } from 'rxjs';
import { describe, expect, it } from 'vitest';
import { SheetsFilterService } from '../sheet-filter.service';
@@ -54,6 +55,45 @@ function createService() {
return injector.get(SheetsFilterService);
}
+function createServiceWithCapturedResource() {
+ let resourceConfig: any;
+ const sheet = {
+ getUnitId: () => 'unit-1',
+ getSheetId: () => 'sheet-1',
+ };
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: (sheetId: string) => (sheetId === 'sheet-1' ? sheet : null),
+ getActiveSheet: () => sheet,
+ activeSheet$: of(sheet),
+ };
+
+ class TestResourceManagerService {
+ registerPluginResource(config: unknown) {
+ resourceConfig = config;
+ return { dispose: () => undefined };
+ }
+ }
+
+ class TestUniverInstanceService {
+ getUniverSheetInstance = (unitId: string) => (unitId === 'unit-1' ? workbook : null);
+ getCurrentUnitOfType = () => workbook;
+ getCurrentTypeOfUnit$ = () => of(workbook);
+ }
+
+ class TestCommandService {
+ onCommandExecuted = () => ({ dispose: () => undefined });
+ }
+
+ const injector = new Injector();
+ injector.add([IResourceManagerService, { useClass: TestResourceManagerService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([SheetsFilterService]);
+
+ return { service: injector.get(SheetsFilterService), getResourceConfig: () => resourceConfig };
+}
+
describe('SheetsFilterService', () => {
it('creates and removes filter models for workbook sheets', () => {
const service = createService();
@@ -63,6 +103,14 @@ describe('SheetsFilterService', () => {
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();
+ expect(service.removeFilterModel('unit-1', 'sheet-1')).toBe(false);
+ });
+
+ it('throws when creating filter models for missing workbook or worksheet', () => {
+ const service = createService();
+
+ expect(() => service.ensureFilterModel('missing', 'sheet-1')).toThrow('non-existing workbook missing');
+ expect(() => service.ensureFilterModel('unit-1', 'missing')).toThrow('non-existing worksheet missing');
});
it('publishes filter error messages for UI consumers', () => {
@@ -75,4 +123,48 @@ describe('SheetsFilterService', () => {
expect(messages).toEqual([null, 'Invalid filter range']);
sub.unsubscribe();
});
+
+ it('disposes cached filter models and completes state streams', () => {
+ const service = createService();
+ const model = service.ensureFilterModel('unit-1', 'sheet-1');
+ const completions: string[] = [];
+
+ service.loadedUnitId$.subscribe({ complete: () => completions.push('loaded') });
+ service.errorMsg$.subscribe({ complete: () => completions.push('error') });
+ service.activeFilterModel$.subscribe({ complete: () => completions.push('active') });
+
+ service.dispose();
+
+ expect(service.getFilterModel('unit-1', 'sheet-1')).toBeNull();
+ expect((model as never as { _disposed: boolean })._disposed).toBe(true);
+ expect(completions).toEqual(['loaded', 'error', 'active']);
+ });
+
+ it('loads and unloads filter models from snapshot resources and updates active model', () => {
+ const { service, getResourceConfig } = createServiceWithCapturedResource();
+ const loaded: unknown[] = [];
+ const active: unknown[] = [];
+ service.loadedUnitId$.subscribe((unitId) => loaded.push(unitId));
+ service.activeFilterModel$.subscribe((model) => active.push(model));
+
+ expect(getResourceConfig().toJson('unit-1')).toBe('{}');
+
+ getResourceConfig().onLoad('unit-1', {
+ 'sheet-1': {
+ ref: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ filterColumns: [],
+ },
+ });
+
+ expect(loaded).toEqual([null, 'unit-1']);
+ expect(service.getFilterModel('unit-1', 'sheet-1')).toBe(service.activeFilterModel);
+ expect(active.at(-1)).toBe(service.activeFilterModel);
+ expect(JSON.parse(getResourceConfig().toJson('unit-1'))['sheet-1']).toMatchObject({
+ ref: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ });
+
+ getResourceConfig().onUnLoad('unit-1');
+ expect(service.getFilterModel('unit-1', 'sheet-1')).toBeNull();
+ expect(JSON.stringify(getResourceConfig().parseJson('{"sheet-1":{"filterColumns":[]}}'))).toBe('{"sheet-1":{"filterColumns":[]}}');
+ });
});
diff --git a/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts b/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts
index efca75476d..0323e07791 100644
--- a/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts
+++ b/packages/sheets-formula-ui/src/commands/operations/__tests__/insert-function.operation.spec.ts
@@ -42,22 +42,22 @@ describe('Test insert function operation', () => {
let commandService: ICommandService;
let editorService: IEditorService;
+ class TestEditorService {
+ getEditor = vi.fn(() => null);
+ register = vi.fn();
+ getAllEditor = vi.fn(() => new Map());
+ isEditor = vi.fn(() => false);
+ isSheetEditor = vi.fn(() => false);
+ blur$ = { subscribe: vi.fn() };
+ blur = vi.fn();
+ focus$ = { subscribe: vi.fn() };
+ focus = vi.fn();
+ getFocusId = vi.fn(() => null);
+ getFocusEditor = vi.fn(() => null);
+ }
+
beforeEach(() => {
- const fakeEditorService = {
- getEditor: vi.fn(() => null),
- register: vi.fn(),
- getAllEditor: vi.fn(() => new Map()),
- isEditor: vi.fn(() => false),
- isSheetEditor: vi.fn(() => false),
- blur$: { subscribe: vi.fn() },
- blur: vi.fn(),
- focus$: { subscribe: vi.fn() },
- focus: vi.fn(),
- getFocusId: vi.fn(() => null),
- getFocusEditor: vi.fn(() => null),
- } as unknown as IEditorService;
-
- const testBed = createCommandTestBed(undefined, [[IEditorServiceToken, { useValue: fakeEditorService }]]);
+ const testBed = createCommandTestBed(undefined, [[IEditorServiceToken, { useClass: TestEditorService as never }]]);
univer = testBed.univer;
get = testBed.get;
editorService = get(IEditorServiceToken);
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx b/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx
new file mode 100644
index 0000000000..9b6fd06fb2
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/search-function/__tests__/SearchFunction.spec.tsx
@@ -0,0 +1,276 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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, IDisposable } from '@univerjs/core';
+import type { Editor } from '@univerjs/docs-ui';
+import type { IFunctionInfo } from '@univerjs/engine-formula';
+import type { IShortcutItem } from '@univerjs/ui';
+import type { Root } from 'react-dom/client';
+import {
+ CommandType,
+ ConfigService,
+ ICommandService,
+ IConfigService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+} from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { FunctionType, sequenceNodeType } from '@univerjs/engine-formula';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { IShortcutService, 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 { SearchFunction } from '../SearchFunction';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const sumInfo: IFunctionInfo = {
+ functionName: 'SUM',
+ functionType: FunctionType.Math,
+ description: 'Adds selected values.',
+ abstract: 'Adds values.',
+ functionParameter: [],
+};
+
+class TestDescriptionService {
+ getSearchListByNameFirstLetter(searchText: string) {
+ if (!sumInfo.functionName.startsWith(searchText.toUpperCase())) {
+ return [];
+ }
+ return [{
+ name: sumInfo.functionName,
+ desc: sumInfo.description,
+ functionType: sumInfo.functionType,
+ }];
+ }
+}
+
+class TestCommandService {
+ readonly registered: ICommandInfo[] = [];
+
+ executeCommand(): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ registerCommand(command: ICommandInfo): IDisposable {
+ this.registered.push(command);
+ return { dispose: () => {} };
+ }
+
+ registerMultipleCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ beforeCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ onCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ syncExecuteCommand(): boolean {
+ return true;
+ }
+
+ setCommandExecutedListener(): void {}
+
+ getCommands(): Map<string, ICommandInfo> {
+ return new Map(this.registered.map((command) => [command.id, command]));
+ }
+
+ getCommand(): ICommandInfo {
+ return { id: 'test.command', type: CommandType.OPERATION };
+ }
+}
+
+class TestShortcutService {
+ readonly shortcutChanged$ = new Subject<void>();
+ readonly shortcuts: IShortcutItem[] = [];
+
+ forceEscape(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ forceDisable(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ dispatch(): IShortcutItem<object> | undefined {
+ return undefined;
+ }
+
+ registerShortcut(shortcut: IShortcutItem): IDisposable {
+ this.shortcuts.push(shortcut);
+ return { dispose: () => {} };
+ }
+
+ getShortcutDisplay(): string | null {
+ return null;
+ }
+
+ getShortcutDisplayOfCommand(): string | null {
+ return null;
+ }
+
+ getAllShortcuts(): IShortcutItem[] {
+ return this.shortcuts;
+ }
+}
+
+class TestSidebarService {
+ readonly scrollEvent$ = new Subject<Event>();
+}
+
+class TestUniverInstanceService {
+ readonly unitAdded$ = new Subject();
+}
+
+class TestEditorService {
+ getEditor(): unknown {
+ return SearchFunctionState.editor;
+ }
+}
+
+class TestResizeObserver {
+ observe(): void {}
+ disconnect(): void {}
+ unobserve(): void {}
+}
+
+class SearchFunctionState {
+ static editor: unknown;
+ static selected: Array<{ text: string; offset: number }> = [];
+ static focused = 0;
+
+ static reset(): void {
+ this.editor = undefined;
+ this.selected = [];
+ this.focused = 0;
+ }
+}
+
+function createEditor(): Editor {
+ const input$ = new Subject<void>();
+ const selectionRanges = [{ startOffset: 2, endOffset: 2, collapsed: true }];
+ return {
+ input$,
+ getEditorId: () => 'formula-editor-test',
+ getSelectionRanges: () => selectionRanges,
+ focus: () => {
+ SearchFunctionState.focused += 1;
+ },
+ getBoundingClientRect: () => ({ left: 10, top: 20, right: 130, bottom: 44 }),
+ getDocumentData: () => ({ documentStyle: { marginTop: 0, marginBottom: 0 } }),
+ getSkeleton: () => ({
+ getSkeletonData: () => ({
+ pages: [{ height: 24 }],
+ }),
+ }),
+ } as unknown as Editor;
+}
+
+function createSearchFunctionTestBed() {
+ const injector = new Injector();
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.add([IDescriptionService, { useClass: TestDescriptionService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IShortcutService, { useClass: TestShortcutService as never }]);
+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+
+ const editor = createEditor();
+ SearchFunctionState.editor = editor;
+
+ return { injector, editor };
+}
+
+async function waitForSearchList(editor: Editor): Promise<void> {
+ await act(async () => {
+ (editor.input$ as unknown as Subject<void>).next();
+ await new Promise((resolve) => setTimeout(resolve, 350));
+ });
+}
+
+describe('SearchFunction', () => {
+ let container: HTMLDivElement;
+ let popupRoot: HTMLDivElement;
+ let root: Root;
+ let resizeObserver: typeof ResizeObserver | undefined;
+
+ beforeEach(() => {
+ SearchFunctionState.reset();
+ resizeObserver = globalThis.ResizeObserver;
+ globalThis.ResizeObserver = TestResizeObserver as typeof ResizeObserver;
+ container = document.createElement('div');
+ popupRoot = document.createElement('div');
+ popupRoot.id = 'univer-popup-portal';
+ document.body.appendChild(container);
+ document.body.appendChild(popupRoot);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ popupRoot.remove();
+ if (resizeObserver) {
+ globalThis.ResizeObserver = resizeObserver;
+ } else {
+ delete (globalThis as { ResizeObserver?: unknown }).ResizeObserver;
+ }
+ });
+
+ it('replaces the typed function token and refocuses the editor when a search result is selected', async () => {
+ const { injector, editor } = createSearchFunctionTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SearchFunction
+ isFocus
+ editor={editor}
+ sequenceNodes={[{ nodeType: sequenceNodeType.FUNCTION, token: 'SU' } as never]}
+ onSelect={(result) => SearchFunctionState.selected.push(result)}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await waitForSearchList(editor);
+
+ const sumItem = Array.from(document.body.querySelectorAll('li'))
+ .find((node) => node.textContent?.includes('SUM')) as HTMLElement | undefined;
+ expect(sumItem).toBeDefined();
+
+ await act(async () => {
+ sumItem!.click();
+ await Promise.resolve();
+ });
+
+ expect(SearchFunctionState.selected).toEqual([{ text: 'SUM(', offset: -2 }]);
+ expect(SearchFunctionState.focused).toBe(1);
+ expect(document.body.textContent).not.toContain('Adds selected values.');
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx b/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx
new file mode 100644
index 0000000000..f3d696e39b
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-progress/__tests__/FormulaProgress.spec.tsx
@@ -0,0 +1,183 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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, IDisposable } from '@univerjs/core';
+import type { Root } from 'react-dom/client';
+import { CommandType, ICommandService, Injector } from '@univerjs/core';
+import { SetFormulaCalculationStopMutation } from '@univerjs/engine-formula';
+import { TriggerCalculationController } from '@univerjs/sheets-formula';
+import { RediContext } 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 { FormulaProgressBar } from '../FormulaProgress';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+interface ITestProgress {
+ done: number;
+ count: number;
+ label?: string;
+}
+
+class TestCommandService {
+ readonly executed: Array<{ id: string; params?: unknown }> = [];
+
+ executeCommand(id: string, params?: unknown): Promise<boolean> {
+ this.executed.push({ id, params });
+ return Promise.resolve(true);
+ }
+
+ registerCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ registerMultipleCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ beforeCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ onCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ syncExecuteCommand(): boolean {
+ return true;
+ }
+
+ setCommandExecutedListener(): void {}
+
+ getCommands(): Map<string, ICommandInfo> {
+ return new Map();
+ }
+
+ getCommand(): ICommandInfo {
+ return { id: 'test.command', type: CommandType.OPERATION };
+ }
+}
+
+class TestTriggerCalculationController {
+ private readonly _progress$ = new BehaviorSubject<ITestProgress>({ done: 2, count: 5, label: 'Calculating' });
+ readonly progress$ = this._progress$.asObservable();
+ cleared = 0;
+
+ setProgress(progress: ITestProgress): void {
+ this._progress$.next(progress);
+ }
+
+ clearProgress(): void {
+ this.cleared += 1;
+ this._progress$.next({ done: 0, count: 0 });
+ }
+}
+
+function createProgressTestBed() {
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([TriggerCalculationController, { useClass: TestTriggerCalculationController as never }]);
+
+ return {
+ injector,
+ commandService: injector.get(ICommandService) as unknown as TestCommandService,
+ controller: injector.get(TriggerCalculationController) as unknown as TestTriggerCalculationController,
+ };
+}
+
+describe('FormulaProgressBar', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let requestAnimationFrameDescriptor: PropertyDescriptor | undefined;
+
+ beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ requestAnimationFrameDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'requestAnimationFrame');
+ Object.defineProperty(globalThis, 'requestAnimationFrame', {
+ configurable: true,
+ value: (callback: FrameRequestCallback) => {
+ callback(0);
+ return 1;
+ },
+ });
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ if (requestAnimationFrameDescriptor) {
+ Object.defineProperty(globalThis, 'requestAnimationFrame', requestAnimationFrameDescriptor);
+ } else {
+ delete (globalThis as { requestAnimationFrame?: unknown }).requestAnimationFrame;
+ }
+ });
+
+ function renderProgress(injector: Injector) {
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <FormulaProgressBar />
+ </RediContext.Provider>
+ );
+ });
+ }
+
+ it('sends the stop-calculation command when the user terminates progress', async () => {
+ const { commandService, injector } = createProgressTestBed();
+
+ renderProgress(injector);
+
+ const closeButton = container.querySelector('button') as HTMLButtonElement;
+ expect(closeButton).toBeDefined();
+
+ await act(async () => {
+ closeButton.click();
+ await Promise.resolve();
+ });
+
+ expect(commandService.executed).toEqual([
+ { id: SetFormulaCalculationStopMutation.id, params: undefined },
+ ]);
+ });
+
+ it('clears progress after a completed progress transition ends', async () => {
+ const { controller, injector } = createProgressTestBed();
+
+ renderProgress(injector);
+
+ await act(async () => {
+ controller.setProgress({ done: 3, count: 3, label: 'Done' });
+ await Promise.resolve();
+ });
+
+ const progressBarInner = Array.from(container.querySelectorAll('div'))
+ .find((node) => node.style.width === '100%') as HTMLDivElement | undefined;
+ expect(progressBarInner).toBeDefined();
+
+ await act(async () => {
+ progressBarInner!.dispatchEvent(new Event('transitionend', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(controller.cleared).toBe(1);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx b/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
new file mode 100644
index 0000000000..38e1a4eb90
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/more-functions/__tests__/MoreFunctions.spec.tsx
@@ -0,0 +1,451 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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, IDisposable } from '@univerjs/core';
+import type { IFunctionInfo } from '@univerjs/engine-formula';
+import type { ISearchItem } from '@univerjs/sheets-formula';
+import type { Root } from 'react-dom/client';
+import {
+ CommandType,
+ ConfigService,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ICommandService,
+ IConfigService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { FunctionType } from '@univerjs/engine-formula';
+import { IDescriptionService } from '@univerjs/sheets-formula';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { ISidebarService, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { BehaviorSubject, of, Subject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { MoreFunctions } from '../MoreFunctions';
+import { SelectFunction } from '../select-function/SelectFunction';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const sumInfo: IFunctionInfo = {
+ functionName: 'SUM',
+ functionType: FunctionType.Math,
+ description: 'Adds values together.',
+ abstract: 'Adds values.',
+ functionParameter: [
+ {
+ name: 'number1',
+ detail: 'First value.',
+ example: 'A1',
+ require: 1,
+ repeat: 1,
+ },
+ ],
+};
+
+const averageInfo: IFunctionInfo = {
+ functionName: 'AVERAGE',
+ functionType: FunctionType.Statistical,
+ description: 'Returns the average value.',
+ abstract: 'Average value.',
+ functionParameter: [
+ {
+ name: 'value1',
+ detail: 'First value.',
+ example: 'A1:A3',
+ require: 1,
+ repeat: 1,
+ },
+ ],
+};
+
+class TestDescriptionService {
+ private readonly _items = [sumInfo, averageInfo];
+
+ getDescriptions() {
+ return new Map(this._items.map((item) => [item.functionName, item]));
+ }
+
+ hasFunction(searchText: string) {
+ return this._items.some((item) => item.functionName === searchText.toUpperCase());
+ }
+
+ getFunctionInfo(searchText: string) {
+ return this._items.find((item) => item.functionName === searchText.toUpperCase());
+ }
+
+ getSearchListByName(searchText: string): ISearchItem[] {
+ const normalized = searchText.toUpperCase();
+ return this._items
+ .filter((item) => item.functionName.includes(normalized))
+ .map((item) => ({ name: item.functionName, desc: item.description }));
+ }
+
+ getSearchListByNameFirstLetter(searchText: string) {
+ return this.getSearchListByName(searchText).map((item) => ({
+ ...item,
+ functionType: this.getFunctionInfo(item.name)!.functionType,
+ }));
+ }
+
+ getSearchListByType(type: number): ISearchItem[] {
+ return this._items
+ .filter((item) => type === -1 || item.functionType === type)
+ .map((item) => ({ name: item.functionName, desc: item.description }));
+ }
+
+ registerDescriptions(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ unregisterDescriptions(): void {}
+
+ hasDescription(name: string) {
+ return this.hasFunction(name);
+ }
+
+ hasDefinedNameDescription() {
+ return false;
+ }
+
+ isFormulaDefinedName() {
+ return false;
+ }
+}
+
+class TestSidebarService {
+ readonly sidebarOptions$ = new Subject<unknown>();
+ readonly scrollEvent$ = new Subject<Event>();
+ visible = false;
+ options = {};
+ width = undefined;
+
+ open(): IDisposable {
+ this.visible = true;
+ return { dispose: () => this.close() };
+ }
+
+ close(): void {
+ this.visible = false;
+ }
+
+ getContainer(): HTMLElement | undefined {
+ return undefined;
+ }
+
+ setContainer(): void {}
+
+ setWidth(value: number): void {
+ this.width = value as never;
+ }
+}
+
+class TestCommandService {
+ readonly executed: Array<{ id: string; params?: unknown }> = [];
+
+ executeCommand(id: string, params?: unknown): Promise<boolean> {
+ this.executed.push({ id, params });
+ return Promise.resolve(true);
+ }
+
+ registerCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ registerMultipleCommand(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ beforeCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ onCommandExecuted() {
+ return { dispose: () => {} };
+ }
+
+ syncExecuteCommand(): boolean {
+ return true;
+ }
+
+ setCommandExecutedListener(): void {}
+
+ getCommands(): Map<string, ICommandInfo> {
+ return new Map();
+ }
+
+ getCommand(): ICommandInfo {
+ return { id: 'test.command', type: CommandType.OPERATION };
+ }
+}
+
+class TestEditorService {
+ readonly replaced = new Map<string, Array<{ text: string; cover?: boolean }>>();
+
+ getEditor(id: string) {
+ return {
+ replaceText: (text: string, cover?: boolean) => {
+ const list = this.replaced.get(id) ?? [];
+ list.push({ text, cover });
+ this.replaced.set(id, list);
+ },
+ };
+ }
+}
+
+class TestEditorBridgeService {}
+
+class TestUniverInstanceService {
+ private readonly _workbook = {
+ getUnitId: () => 'formula-book',
+ getActiveSheet: () => ({
+ getSheetId: () => 'sheet-1',
+ }),
+ getSheetBySheetId: () => ({
+ getSheetId: () => 'sheet-1',
+ }),
+ };
+
+ readonly unitAdded$ = new Subject();
+ readonly unitDisposed$ = new Subject();
+ readonly focused$ = new BehaviorSubject<string | null>(null);
+
+ getTypeOfUnitAdded$() {
+ return this.unitAdded$.asObservable();
+ }
+
+ getTypeOfUnitDisposed$() {
+ return this.unitDisposed$.asObservable();
+ }
+
+ getCurrentUnitOfType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this._workbook : null;
+ }
+
+ getCurrentTypeOfUnit$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? of(this._workbook) : of(null);
+ }
+
+ getUnit() {
+ return this._workbook;
+ }
+
+ getAllUnitsForType() {
+ return [this._workbook];
+ }
+
+ focusUnit(): void {}
+
+ getFocusedUnit() {
+ return null;
+ }
+
+ setCurrentUnitForType(): void {}
+
+ createUnit() {
+ return this._workbook;
+ }
+
+ disposeUnit() {
+ return true;
+ }
+
+ registerCtorForType(): IDisposable {
+ return { dispose: () => {} };
+ }
+
+ changeDoc(): void {}
+
+ getUnitType() {
+ return UniverInstanceType.UNIVER_SHEET;
+ }
+
+ getUniverSheetInstance() {
+ return this._workbook;
+ }
+
+ getUniverDocInstance() {
+ return null;
+ }
+
+ getCurrentUniverDocInstance() {
+ return null;
+ }
+}
+
+class SelectionState {
+ static values: Array<IFunctionInfo | null> = [];
+
+ static reset(): void {
+ this.values = [];
+ }
+}
+
+function createFormulaViewTestBed() {
+ const injector = new Injector();
+
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.add([IDescriptionService, { useClass: TestDescriptionService as never }]);
+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+
+ injector.get(LocaleService).load({
+ [LocaleType.ZH_CN]: {
+ 'sheets-formula-ui': {
+ moreFunctions: {
+ allFunctions: 'All functions',
+ searchFunctionPlaceholder: 'Search functions',
+ confirm: 'Confirm',
+ next: 'Next',
+ prev: 'Previous',
+ syntax: 'Syntax',
+ },
+ prompt: {
+ required: 'Required.',
+ optional: 'Optional.',
+ helpExample: 'Example',
+ },
+ },
+ },
+ });
+
+ return {
+ injector,
+ commandService: injector.get(ICommandService) as unknown as TestCommandService,
+ editorService: injector.get(IEditorService) as unknown as TestEditorService,
+ };
+}
+
+function renderWithInjector(root: Root, injector: Injector, element: React.ReactNode) {
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ {element}
+ </RediContext.Provider>
+ );
+ });
+}
+
+function writeInput(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+describe('formula function picker views', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ SelectionState.reset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it('filters functions by typed text and reports the selected function info', async () => {
+ const { injector } = createFormulaViewTestBed();
+
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <SelectFunction onChange={(value) => SelectionState.values.push(value)} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ expect(input).toBeDefined();
+
+ await act(async () => {
+ writeInput(input, 'AVE');
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain('AVERAGE');
+ expect(container.textContent).not.toContain('SUM');
+
+ const item = Array.from(container.querySelectorAll('li'))
+ .find((node) => node.textContent?.includes('AVERAGE')) as HTMLElement | undefined;
+ expect(item).toBeDefined();
+
+ await act(async () => {
+ item!.click();
+ await Promise.resolve();
+ });
+
+ expect(SelectionState.values.at(-1)?.functionName).toBe('AVERAGE');
+ expect(container.textContent).toContain('Returns the average value.');
+ expect(container.textContent).toContain('AVERAGE(A1:A3)');
+ });
+
+ it('inserts the selected function call into both sheet editors after confirmation', async () => {
+ const { commandService, editorService, injector } = createFormulaViewTestBed();
+
+ await act(async () => {
+ renderWithInjector(root, injector, <MoreFunctions />);
+ await Promise.resolve();
+ });
+
+ const averageItem = Array.from(container.querySelectorAll('li'))
+ .find((node) => node.textContent?.includes('AVERAGE')) as HTMLElement | undefined;
+ expect(averageItem).toBeDefined();
+
+ await act(async () => {
+ averageItem!.click();
+ await Promise.resolve();
+ });
+
+ const confirmButton = Array.from(container.querySelectorAll('button'))
+ .find((node) => node.textContent === 'Confirm') as HTMLButtonElement | undefined;
+ expect(confirmButton).toBeDefined();
+ expect(confirmButton!.disabled).toBe(false);
+
+ await act(async () => {
+ confirmButton!.click();
+ await Promise.resolve();
+ });
+
+ expect(commandService.executed).toEqual([
+ {
+ id: 'sheet.operation.set-cell-edit-visible',
+ params: expect.objectContaining({
+ visible: true,
+ unitId: 'formula-book',
+ }),
+ },
+ ]);
+ expect(editorService.replaced.get(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=AVERAGE(', cover: undefined }]);
+ expect(editorService.replaced.get(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)).toEqual([{ text: '=AVERAGE(', cover: false }]);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx b/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
new file mode 100644
index 0000000000..29f40b0b8b
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/__tests__/RangeSelectorDialog.spec.tsx
@@ -0,0 +1,182 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 type { ISelectionWithStyle } from '@univerjs/sheets';
+import type { Root } from 'react-dom/client';
+import { Injector, IUniverInstanceService, LocaleService, LocaleType, UniverInstanceType } from '@univerjs/core';
+import { LexerTreeBuilder } from '@univerjs/engine-formula';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+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 { RangeSelectorDialog } from '../index';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestSheetsSelectionsService {
+ readonly selectionMoveStart$ = new Subject<ISelectionWithStyle[]>();
+ readonly selectionMoving$ = new Subject<ISelectionWithStyle[]>();
+ readonly selectionMoveEnd$ = new Subject<ISelectionWithStyle[]>();
+}
+
+class TestUniverInstanceService {
+ private readonly _workbook = {
+ getActiveSheet: () => ({
+ getSheetId: () => 'sheet-1',
+ getName: () => 'Sheet1',
+ }),
+ };
+
+ readonly unitAdded$ = new Subject();
+ readonly unitDisposed$ = new Subject();
+
+ getUnit(_unitId: string, type?: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this._workbook : null;
+ }
+
+ getCurrentUnitOfType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this._workbook : null;
+ }
+}
+
+class RangeDialogState {
+ static confirmed: IUnitRangeName[][] = [];
+ static closed = 0;
+
+ static reset(): void {
+ this.confirmed = [];
+ this.closed = 0;
+ }
+}
+
+function createRangeDialogTestBed() {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);
+ injector.add([SheetsSelectionsService, { useClass: TestSheetsSelectionsService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ const localeService = injector.get(LocaleService);
+ localeService.load({
+ [LocaleType.EN_US]: {
+ 'sheets-formula-ui': {
+ rangeSelector: {
+ title: 'Select a data range',
+ addAnotherRange: 'Add range',
+ placeHolder: 'Select range or enter.',
+ confirm: 'Confirm',
+ cancel: 'Cancel',
+ },
+ },
+ },
+ });
+ localeService.setLocale(LocaleType.EN_US);
+ return injector;
+}
+
+function renderRangeDialog(root: Root, injector: Injector) {
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <RangeSelectorDialog
+ visible
+ initialValue={[]}
+ unitId="book-1"
+ subUnitId="sheet-1"
+ onConfirm={(ranges) => RangeDialogState.confirmed.push(ranges)}
+ onClose={() => {
+ RangeDialogState.closed += 1;
+ }}
+ />
+ </RediContext.Provider>
+ );
+ });
+}
+
+function writeInput(input: HTMLInputElement, value: string) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ valueSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
+
+async function clickButton(text: string): Promise<void> {
+ const button = Array.from(document.body.querySelectorAll('button'))
+ .find((node) => node.textContent === text) as HTMLButtonElement | undefined;
+ expect(button).toBeDefined();
+ await act(async () => {
+ button!.click();
+ await Promise.resolve();
+ });
+}
+
+describe('RangeSelectorDialog', () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ RangeDialogState.reset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ });
+
+ it('confirms only valid range inputs and normalizes reversed coordinates', async () => {
+ renderRangeDialog(root, createRangeDialogTestBed());
+
+ const firstInput = document.body.querySelector('input') as HTMLInputElement;
+ expect(firstInput).toBeDefined();
+
+ await act(async () => {
+ writeInput(firstInput, 'B2:A1');
+ await Promise.resolve();
+ });
+
+ await clickButton('Add range');
+
+ const inputs = Array.from(document.body.querySelectorAll('input')) as HTMLInputElement[];
+ expect(inputs.length).toBe(2);
+
+ await act(async () => {
+ writeInput(inputs[1], 'SUM(A1)');
+ await Promise.resolve();
+ });
+
+ await clickButton('Confirm');
+
+ expect(RangeDialogState.confirmed).toEqual([[
+ expect.objectContaining({
+ unitId: '',
+ sheetName: '',
+ range: expect.objectContaining({
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 1,
+ }),
+ }),
+ ]]);
+ expect(RangeDialogState.closed).toBe(0);
+ });
+});
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.tsx
index 43b7d42b95..e5ae3b5bef 100644
--- a/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/__tests__/CellLinkPopup.spec.tsx
@@ -42,6 +42,7 @@ import {
CancelHyperLinkCommand,
HyperLinkModel,
RemoveHyperLinkMutation,
+ SheetHyperLinkType,
SheetsHyperLinkParserService,
UpdateHyperLinkMutation,
} from '@univerjs/sheets-hyper-link';
@@ -317,6 +318,20 @@ function inputText(input: HTMLInputElement, value: string) {
input.dispatchEvent(new Event('input', { bubbles: true }));
}
+async function selectOption(trigger: Element, optionText: string) {
+ trigger.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ trigger.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+
+ const option = Array.from(document.querySelectorAll('button, [data-slot="dropdown-menu-radio-item"]')).find((item) => item.textContent === optionText);
+
+ if (!option) {
+ throw new Error(`Option ${optionText} was not rendered`);
+ }
+
+ option.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
function renderPopup(
root: Root,
container: HTMLDivElement,
@@ -475,4 +490,61 @@ describe('CellLinkEdit', () => {
expect(linkRange?.properties?.url).toBe('http://docs.univer.ai');
expect(popupService.currentEditing).toBeNull();
});
+
+ it('switches from URL to worksheet link and saves the selected sheet target', 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 typeSelect = container.querySelector('[data-u-comp="select"]');
+ expect(typeSelect?.textContent).toContain('sheets-hyper-link-ui.form.link');
+
+ await act(async () => {
+ await selectOption(typeSelect!, 'sheets-hyper-link-ui.form.worksheet');
+ await Promise.resolve();
+ });
+
+ const selects = Array.from(container.querySelectorAll('[data-u-comp="select"]'));
+ expect(selects).toHaveLength(2);
+
+ await act(async () => {
+ await selectOption(selects[1], 'Sheet 1');
+ await Promise.resolve();
+ });
+ renderManagerService.enableScrollRender = true;
+
+ const formButtons = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'));
+ const okButton = formButtons[formButtons.length - 1];
+
+ 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 sheetLink = body?.customRanges?.find((range) => range.properties?.url === `#${SheetHyperLinkType.SHEET}=${SUB_UNIT_ID}`);
+
+ expect(body?.dataStream).toBe('Univer\r\n');
+ expect(sheetLink?.rangeType).toBe(CustomRangeType.HYPERLINK);
+ expect(popupService.currentEditing).toBeNull();
+ });
});
diff --git a/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsx b/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsx
index f059ee01e4..36fee9dd47 100644
--- a/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsx
+++ b/packages/sheets-note-ui/src/views/__tests__/Note.spec.tsx
@@ -19,6 +19,7 @@ import type { IPopup } from '@univerjs/ui';
import type { Root } from 'react-dom/client';
import {
awaitTime,
+ CommandType,
ICommandService,
IConfigService,
ILogService,
@@ -52,6 +53,12 @@ import { SheetsNote } from '../Note';
const UNIT_ID = 'note-view-workbook';
const SUB_UNIT_ID = 'sheet-1';
+const FailingUpdateNoteMutation = {
+ id: UpdateNoteMutation.id,
+ type: CommandType.MUTATION,
+ handler: () => false,
+};
+
class TestRenderManagerService {
getRenderById() {
return {
@@ -96,16 +103,20 @@ function createWorkbookData(): IWorkbookData {
};
}
+function createNoteLocation(row: number, col: number) {
+ return {
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ row,
+ col,
+ trigger: 'context-menu',
+ };
+}
+
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',
- },
+ location: createNoteLocation(row, col),
},
} as IPopup<{ location: { unitId: string; subUnitId: string; row: number; col: number; trigger: string } }>;
}
@@ -150,6 +161,8 @@ function createNoteViewTestBed() {
injector,
workbook,
noteModel: injector.get(SheetsNoteModel),
+ commandService,
+ notePopupService: injector.get(SheetsNotePopupService),
};
}
@@ -242,4 +255,54 @@ describe('SheetsNote', () => {
expect(note?.width).toBe(180);
expect(note?.height).toBe(96);
});
+
+ it('closes the popup when creating the initial note cannot be saved', async () => {
+ const testBed = createMountedNote();
+ testBed.commandService.unregisterCommand(UpdateNoteMutation.id);
+ testBed.commandService.registerCommand(FailingUpdateNoteMutation);
+ testBed.notePopupService.showPopup(createNoteLocation(2, 3));
+
+ await renderNote(root!, testBed);
+ await act(async () => {
+ await awaitTime(350);
+ });
+
+ expect(testBed.noteModel.getNote(UNIT_ID, SUB_UNIT_ID, { row: 2, col: 3 })).toBeUndefined();
+ expect(testBed.notePopupService.activePopup).toBeNull();
+ });
+
+ it('restores the previous note text when an edit cannot be saved', async () => {
+ const testBed = createMountedNote();
+
+ testBed.commandService.syncExecuteCommand(SheetUpdateNoteCommand.id, {
+ unitId: UNIT_ID,
+ sheetId: SUB_UNIT_ID,
+ row: 2,
+ col: 3,
+ note: {
+ id: 'existing-note',
+ width: 180,
+ height: 96,
+ note: 'Original note',
+ },
+ });
+ testBed.commandService.unregisterCommand(UpdateNoteMutation.id);
+ testBed.commandService.registerCommand(FailingUpdateNoteMutation);
+
+ await renderNote(root!, testBed);
+ await act(async () => {
+ await awaitTime(350);
+ });
+
+ const textarea = container!.querySelector('textarea') as HTMLTextAreaElement;
+
+ await act(async () => {
+ inputText(textarea, 'Unsaved edit');
+ await awaitTime(350);
+ });
+
+ const note = testBed.noteModel.getNote(UNIT_ID, SUB_UNIT_ID, { row: 2, col: 3 });
+ expect(note?.note).toBe('Original note');
+ expect(textarea.value).toBe('Original note');
+ });
});
diff --git a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx
index eb1286b1cf..7e725d57d0 100644
--- a/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx
+++ b/packages/sheets-numfmt-ui/src/views/__tests__/SheetNumfmtViews.spec.tsx
@@ -42,7 +42,7 @@ import {
SheetInterceptorService,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { SetNumfmtCommand, SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';
+import { getPatternType, SetNumfmtCommand, SheetsNumfmtCellContentController } from '@univerjs/sheets-numfmt';
import { ILayoutService, RediContext } from '@univerjs/ui';
import { act } from 'react';
import { createRoot } from 'react-dom/client';
@@ -423,6 +423,45 @@ describe('SheetNumfmtPanel', () => {
let container: HTMLDivElement | undefined;
let currentTestBed: ReturnType<typeof createNumfmtViewTestBed> | undefined;
+ async function selectPanelType(label: string) {
+ await act(async () => {
+ container!.querySelector('[data-u-comp="select"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+
+ const option = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((button) => button.textContent === label) as HTMLElement | undefined;
+
+ expect(option).toBeDefined();
+
+ await act(async () => {
+ option!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ }
+
+ async function selectPanelListOption(label: string) {
+ const option = Array.from(container!.querySelectorAll('a'))
+ .find((item) => item.textContent === label) as HTMLElement | undefined;
+
+ expect(option).toBeDefined();
+
+ await act(async () => {
+ option!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+ }
+
+ async function confirmPanel() {
+ 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();
+ });
+ }
+
afterEach(() => {
act(() => {
root?.unmount();
@@ -529,4 +568,48 @@ describe('SheetNumfmtPanel', () => {
{ type: 'confirm', value: '' },
]);
});
+
+ it('applies the selected date format through the real SetNumfmtCommand when confirmed', async () => {
+ currentTestBed = createNumfmtViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const commandResults: Array<Promise<unknown>> = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetNumfmtPanel
+ value={{
+ defaultValue: 1234.5,
+ defaultPattern: '',
+ row: 0,
+ col: 0,
+ }}
+ onChange={(event) => {
+ if (event.type === 'confirm') {
+ commandResults.push(currentTestBed!.commandService.executeCommand(SetNumfmtCommand.id, {
+ values: [{
+ row: 0,
+ col: 0,
+ pattern: event.value,
+ type: getPatternType(event.value),
+ }],
+ }) as Promise<unknown>);
+ }
+ }}
+ />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await selectPanelType('Date');
+ await selectPanelListOption('1930/08/05');
+ await confirmPanel();
+ const results = await Promise.all(commandResults);
+
+ expect(results).toEqual([true]);
+ expect(currentTestBed.numfmtService.getValue(UNIT_ID, SUB_UNIT_ID, 0, 0)).toEqual({ pattern: 'yyyy/MM/dd' });
+ });
});
diff --git a/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts b/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts
index 01f51546fa..8f4b4aa389 100644
--- a/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts
+++ b/packages/sheets-numfmt/src/commands/commands/__tests__/numfmt.command.spec.ts
@@ -219,6 +219,20 @@ describe('Sheets numfmt commands', () => {
expect(numfmtService.getValue('test', 'sheet1', 1, 0)).toEqual({ pattern: '0.00' });
});
+ it('subtracts decimals from raw numeric cells when no number format exists yet', async () => {
+ selectionService.addSelections([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(SubtractDecimalCommand.id)).resolves.toBe(true);
+
+ expect(numfmtService.getValue('test', 'sheet1', 0, 0)).toEqual({ pattern: '0' });
+ });
+
it('applies percent and currency formats to current selections', async () => {
selectionService.addSelections([
{
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.ts
index 935f129593..a3a70798f3 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
@@ -18,11 +18,14 @@ import type { ICellData, Injector, Nullable, Univer } from '@univerjs/core';
import { ICommandService, IConfirmService, RANGE_TYPE, TestConfirmService } from '@univerjs/core';
import { ReorderRangeCommand, ReorderRangeMutation, SetRangeValuesMutation, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SheetsSortUIService } from '../../../services/sheets-sort-ui.service';
import {
SortRangeAscCommand,
SortRangeAscExtCommand,
SortRangeAscExtInCtxMenuCommand,
SortRangeAscInCtxMenuCommand,
+ SortRangeCustomCommand,
+ SortRangeCustomInCtxMenuCommand,
SortRangeDescCommand,
SortRangeDescExtCommand,
SortRangeDescExtInCtxMenuCommand,
@@ -59,10 +62,12 @@ describe('Sheets sort commands integration', () => {
SortRangeAscExtCommand,
SortRangeAscInCtxMenuCommand,
SortRangeAscExtInCtxMenuCommand,
+ SortRangeCustomCommand,
SortRangeDescCommand,
SortRangeDescExtCommand,
SortRangeDescInCtxMenuCommand,
SortRangeDescExtInCtxMenuCommand,
+ SortRangeCustomInCtxMenuCommand,
].forEach((command) => commandService.registerCommand(command));
getValues = (startRow, startColumn, endRow, endColumn) =>
@@ -192,4 +197,39 @@ describe('Sheets sort commands integration', () => {
expect(await commandService.executeCommand(SortRangeDescExtInCtxMenuCommand.id)).toBe(true);
expectDescendingExtendedSortResult();
});
+
+ it('opens custom sort panel for the selected range', async () => {
+ selectSortRange();
+
+ expect(await commandService.executeCommand(SortRangeCustomCommand.id)).toBe(true);
+
+ const customSortState = get(SheetsSortUIService).customSortState();
+ expect(customSortState?.show).toBe(true);
+ expect(customSortState?.location).toMatchObject({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ colIndex: 9,
+ range: {
+ startRow: 0,
+ startColumn: 9,
+ endRow: 6,
+ endColumn: 11,
+ },
+ });
+ });
+
+ it('opens custom sort panel from the context menu command', async () => {
+ selectSortRange();
+
+ expect(await commandService.executeCommand(SortRangeCustomInCtxMenuCommand.id)).toBe(true);
+
+ const customSortState = get(SheetsSortUIService).customSortState();
+ expect(customSortState?.show).toBe(true);
+ expect(customSortState?.location?.range).toMatchObject({
+ startRow: 0,
+ startColumn: 9,
+ endRow: 6,
+ endColumn: 11,
+ });
+ });
});
diff --git a/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsx b/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsx
index 7954c8ba30..07c979de48 100644
--- a/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsx
+++ b/packages/sheets-sort-ui/src/views/__tests__/SheetsSortViews.spec.tsx
@@ -51,6 +51,7 @@ import enUS from '../../locale/en-US';
import { SheetsSortUIService } from '../../services/sheets-sort-ui.service';
import { CustomSortPanel } from '../CustomSortPanel';
import EmbedSortBtn from '../EmbedSortBtn';
+import { ExtendConfirm } from '../ExtendConfirm';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -190,6 +191,33 @@ function getButton(container: HTMLElement, text: string) {
return button as HTMLElement;
}
+function getRadio(container: HTMLElement, text: string, position = 0) {
+ const radios = Array.from(container.querySelectorAll('[data-u-comp="radio"]'))
+ .filter((item) => item.textContent === text);
+ expect(radios[position]).toBeTruthy();
+ return radios[position].querySelector('input') as HTMLInputElement;
+}
+
+function getAddCondition(container: HTMLElement) {
+ const trigger = Array.from(container.querySelectorAll('div'))
+ .find((item) => item.textContent === 'Add condition');
+ expect(trigger).toBeTruthy();
+ return trigger as HTMLElement;
+}
+
+function setCellValue(worksheet: Worksheet, row: number, col: number, value: string | number) {
+ worksheet.getCellMatrix().setValue(row, col, { v: value, t: typeof value === 'number' ? 2 : 1 });
+}
+
+function setDuplicateNamesForConditionTests(worksheet: Worksheet) {
+ setCellValue(worksheet, 1, 0, 'Sam');
+ setCellValue(worksheet, 1, 1, 20);
+ setCellValue(worksheet, 2, 0, 'Amy');
+ setCellValue(worksheet, 2, 1, 10);
+ setCellValue(worksheet, 3, 0, 'Sam');
+ setCellValue(worksheet, 3, 1, 30);
+}
+
describe('Sheets sort views', () => {
let root: Root | undefined;
let container: HTMLDivElement | undefined;
@@ -266,4 +294,111 @@ describe('Sheets sort views', () => {
expect(getColumnValues(currentTestBed.worksheet, 1, [0, 1, 2, 3])).toEqual(['Score', 10, 30, 20]);
expect(currentTestBed.sortUIService.customSortState()).toEqual({ show: false });
});
+
+ it('reports the selected extend range option through the rendered confirmation body', async () => {
+ currentTestBed = createSortViewTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const selectedOptions: string[] = [];
+
+ await renderWithInjector(
+ root,
+ currentTestBed,
+ <ExtendConfirm onChange={(value) => selectedOptions.push(value)} />
+ );
+
+ await act(async () => {
+ getRadio(container!, 'Extend range sorting').click();
+ await awaitTime(20);
+ });
+
+ await act(async () => {
+ getRadio(container!, 'Keep range sorting').click();
+ await awaitTime(20);
+ });
+
+ expect(selectedOptions).toEqual(['1', '0']);
+ });
+
+ it('applies an added custom sort condition as a secondary rule', async () => {
+ currentTestBed = createSortViewTestBed();
+ setDuplicateNamesForConditionTests(currentTestBed.worksheet);
+ currentTestBed.sortUIService.showCustomSortPanel({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 1 },
+ colIndex: 0,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderWithInjector(root, currentTestBed, <CustomSortPanel />);
+
+ await act(async () => {
+ getAddCondition(container!).click();
+ await awaitTime(260);
+ });
+
+ await act(async () => {
+ getRadio(container!, 'Descending', 1).click();
+ await awaitTime(20);
+ });
+
+ await act(async () => {
+ getButton(container!, 'Confirm').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await awaitTime(20);
+ });
+
+ expect(getColumnValues(currentTestBed.worksheet, 0, [1, 2, 3])).toEqual(['Amy', 'Sam', 'Sam']);
+ expect(getColumnValues(currentTestBed.worksheet, 1, [1, 2, 3])).toEqual([10, 30, 20]);
+ expect(currentTestBed.sortUIService.customSortState()).toEqual({ show: false });
+ });
+
+ it('removes an added custom sort condition before confirming', async () => {
+ currentTestBed = createSortViewTestBed();
+ setDuplicateNamesForConditionTests(currentTestBed.worksheet);
+ currentTestBed.sortUIService.showCustomSortPanel({
+ unitId: UNIT_ID,
+ subUnitId: SUB_UNIT_ID,
+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 1 },
+ colIndex: 0,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderWithInjector(root, currentTestBed, <CustomSortPanel />);
+
+ await act(async () => {
+ getAddCondition(container!).click();
+ await awaitTime(260);
+ });
+
+ await act(async () => {
+ getRadio(container!, 'Descending', 1).click();
+ await awaitTime(20);
+ });
+
+ const removeLinks = Array.from(container.querySelectorAll('a'));
+ expect(removeLinks[1]).toBeTruthy();
+
+ await act(async () => {
+ removeLinks[1].dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await awaitTime(20);
+ });
+
+ expect(Array.from(container.querySelectorAll('[data-u-comp="radio"]'))
+ .filter((item) => item.textContent === 'Descending')).toHaveLength(1);
+
+ await act(async () => {
+ getButton(container!, 'Confirm').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await awaitTime(20);
+ });
+
+ expect(getColumnValues(currentTestBed.worksheet, 0, [1, 2, 3])).toEqual(['Amy', 'Sam', 'Sam']);
+ expect(getColumnValues(currentTestBed.worksheet, 1, [1, 2, 3])).toEqual([10, 20, 30]);
+ expect(currentTestBed.sortUIService.customSortState()).toEqual({ show: false });
+ });
});
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.ts
index aa876ec756..038f4d7f2a 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
@@ -17,22 +17,43 @@
import type { ICellValueCompareFn } from '../../commands/commands/sheets-sort.command';
import { ICommandService, Injector, IUniverInstanceService } from '@univerjs/core';
import { FormulaDataModel } from '@univerjs/engine-formula';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SortRangeCommand } from '../../commands/commands/sheets-sort.command';
import { SheetsSortService } from '../sheets-sort.service';
describe('SheetsSortService', () => {
let service: SheetsSortService;
+ let sheet: any;
+ let arrayFormulaRange: any;
+ let executeCommand: ReturnType<typeof vi.fn>;
beforeEach(() => {
const injector = new Injector();
- class TestUniverInstanceService {}
+ sheet = {
+ getSheetId: () => 'sheet-1',
+ getMergeData: () => [],
+ getCellRaw: () => null,
+ };
+ arrayFormulaRange = {};
+ executeCommand = vi.fn(async () => true);
+
+ const workbook = {
+ getUnitId: () => 'book-1',
+ getSheetBySheetId: (sheetId: string) => (sheetId === 'sheet-1' ? sheet : null),
+ getActiveSheet: () => sheet,
+ };
+
+ class TestUniverInstanceService {
+ getUnit = (unitId: string) => (unitId === 'book-1' ? workbook : null);
+ getCurrentUnitOfType = () => workbook;
+ }
class TestCommandService {
- executeCommand = async () => true;
+ executeCommand = executeCommand;
}
class TestFormulaDataModel {
- getArrayFormulaRange = () => ({});
+ getArrayFormulaRange = () => arrayFormulaRange;
}
injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
@@ -56,4 +77,69 @@ describe('SheetsSortService', () => {
expect(service.getAllCompareFns()).toEqual([second, first]);
});
+
+ it('validates sort ranges against merge layout and non-empty cells', () => {
+ const location = { unitId: 'book-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } };
+
+ expect(service.mergeCheck(location)).toBe(true);
+ sheet.getMergeData = () => [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }];
+ expect(service.mergeCheck(location)).toBe(true);
+ sheet.getMergeData = () => [
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ ];
+ expect(service.mergeCheck(location)).toBe(false);
+
+ sheet.getCellRaw = (row: number, col: number) => (row === 1 && col === 1 ? { v: 'value' } : null);
+ expect(service.emptyCheck(location)).toBe(true);
+ sheet.getCellRaw = () => null;
+ expect(service.emptyCheck(location)).toBe(false);
+
+ expect(service.mergeCheck({ ...location, unitId: 'missing' })).toBe(false);
+ expect(service.emptyCheck({ ...location, unitId: 'missing' })).toBe(false);
+ });
+
+ it('rejects sort ranges that intersect array formulas', () => {
+ const location = { unitId: 'book-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 } };
+
+ expect(service.formulaCheck(location)).toBe(true);
+
+ arrayFormulaRange = {
+ 'book-1': {
+ 'sheet-1': {
+ 1: {
+ 1: { startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 },
+ },
+ },
+ },
+ };
+ expect(service.formulaCheck(location)).toBe(false);
+ });
+
+ it('applies sort options through the command service with explicit or active sheet targets', async () => {
+ service.applySort({
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ orderRules: [{ colIndex: 1, type: 'asc' }] as never,
+ hasTitle: true,
+ });
+ service.applySort({
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ orderRules: [] as never,
+ }, 'book-2', 'sheet-2');
+
+ expect(executeCommand).toHaveBeenNthCalledWith(1, SortRangeCommand.id, {
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ orderRules: [{ colIndex: 1, type: 'asc' }],
+ hasTitle: true,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ });
+ expect(executeCommand).toHaveBeenNthCalledWith(2, SortRangeCommand.id, {
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 },
+ orderRules: [],
+ hasTitle: false,
+ unitId: 'book-2',
+ subUnitId: 'sheet-2',
+ });
+ });
});
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.tsx
index fcadaf05d0..478c89406d 100644
--- 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.tsx
@@ -16,7 +16,17 @@
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 {
+ 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 {
@@ -27,7 +37,9 @@ import {
SheetTableService,
TABLE_FILTER_EMPTY_VALUE,
TableColumnFilterTypeEnum,
+ TableConditionTypeEnum,
TableManager,
+ TableStringCompareTypeEnum,
} from '@univerjs/sheets-table';
import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
import { IDialogService, RediContext } from '@univerjs/ui';
@@ -231,6 +243,9 @@ function renderWithRediContext(testBed: ITestBed, element: React.ReactElement) {
function changeInput(input: HTMLInputElement, value: string): void {
act(() => {
+ if (!input.getAttribute('type')) {
+ input.setAttribute('type', 'text');
+ }
const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
valueSetter?.call(input, value);
input.dispatchEvent(new Event('input', { bubbles: true }));
@@ -367,4 +382,46 @@ describe('sheet table view components', () => {
});
expect(componentController.closeCount).toBe(1);
});
+
+ it('applies a condition filter from the condition tab input', async () => {
+ testBed = createTestBed();
+ const componentController = testBed.injector.get(SheetsTableComponentController) as TestComponentController;
+ const table = testBed.injector.get(TableManager).getTable(testBed.workbook.getUnitId(), 'table-orders')!;
+ table.setTableFilterColumn(0, {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ expectedValue: 'pen',
+ },
+ });
+ 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;
+
+ const conditionInput = container.querySelector('input') as HTMLInputElement | null;
+ if (!conditionInput) {
+ throw new Error('Condition input was not found.');
+ }
+ changeInput(conditionInput, 'book');
+ clickButtonByText(container, 'Confirm');
+ await flushCommands();
+
+ expect(table.getTableFilterColumn(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ expectedValue: 'book',
+ },
+ });
+ expect(componentController.closeCount).toBe(1);
+ });
});
diff --git a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
index 7c085d9fd7..32fe83460a 100644
--- a/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
+++ b/packages/sheets-table/src/commands/commands/__tests__/sheet-table-row-col.command.spec.ts
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-import { ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
-import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import { ICommandService, IUndoRedoService, IUniverInstanceService, ObjectMatrix } from '@univerjs/core';
+import { MoveRangeMutation, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
import { SheetsTableController } from '../../../controllers/sheets-table.controller';
@@ -30,22 +30,6 @@ import {
SheetTableRemoveRowCommand,
} from '../sheet-table-row-col.command';
-const sheetsMocks = vi.hoisted(() => ({
- getSheetCommandTarget: vi.fn(),
- getMoveRangeUndoRedoMutations: vi.fn(),
- SheetsSelectionsService: Symbol('SheetsSelectionsService'),
-}));
-
-vi.mock('@univerjs/sheets', async () => {
- const actual = await vi.importActual('@univerjs/sheets');
- return {
- ...actual,
- getSheetCommandTarget: sheetsMocks.getSheetCommandTarget,
- getMoveRangeUndoRedoMutations: sheetsMocks.getMoveRangeUndoRedoMutations,
- SheetsSelectionsService: sheetsMocks.SheetsSelectionsService,
- };
-});
-
function createAccessor(pairs: Array<[unknown, unknown]>) {
const map = new Map<unknown, unknown>(pairs);
return {
@@ -58,12 +42,136 @@ function createAccessor(pairs: Array<[unknown, unknown]>) {
} as any;
}
+interface ICreateSheetContextOptions {
+ unitId?: string;
+ subUnitId?: string;
+ rowCount?: number;
+ columnCount?: number;
+ dataRange?: { endRow: number; endColumn: number };
+ cells?: Array<[number, number, unknown]>;
+}
+
+class TestCellMatrix {
+ private readonly _matrix = new ObjectMatrix<unknown>();
+
+ constructor(private readonly _dataRange: { endRow: number; endColumn: number }) {}
+
+ getDataRange() {
+ return this._dataRange;
+ }
+
+ getValue(row: number, column: number) {
+ return this._matrix.getValue(row, column);
+ }
+
+ setValue(row: number, column: number, value: unknown) {
+ this._matrix.setValue(row, column, value);
+ }
+}
+
+class TestWorksheet {
+ private readonly _cellMatrix: TestCellMatrix;
+
+ constructor(
+ private readonly _sheetId: string,
+ private readonly _rowCount: number,
+ private readonly _columnCount: number,
+ dataRange: { endRow: number; endColumn: number },
+ cells: Array<[number, number, unknown]>
+ ) {
+ this._cellMatrix = new TestCellMatrix(dataRange);
+ cells.forEach(([row, column, value]) => this._cellMatrix.setValue(row, column, value));
+ }
+
+ getSheetId() {
+ return this._sheetId;
+ }
+
+ getRowCount() {
+ return this._rowCount;
+ }
+
+ getColumnCount() {
+ return this._columnCount;
+ }
+
+ getCellMatrix() {
+ return this._cellMatrix;
+ }
+
+ getMatrixWithMergedCells() {
+ return new ObjectMatrix<{ rowSpan?: number; colSpan?: number }>();
+ }
+
+ getMergedCell() {
+ return null;
+ }
+}
+
+class TestWorkbook {
+ constructor(
+ private readonly _unitId: string,
+ private readonly _worksheet: TestWorksheet
+ ) {}
+
+ getUnitId() {
+ return this._unitId;
+ }
+
+ getActiveSheet() {
+ return this._worksheet;
+ }
+
+ getSheetBySheetId(sheetId: string) {
+ return sheetId === this._worksheet.getSheetId() ? this._worksheet : null;
+ }
+
+ getStyles() {
+ return {
+ get: (styleId: string) => styleId,
+ };
+ }
+}
+
+class TestUniverInstanceService {
+ constructor(private readonly _workbook: TestWorkbook | null = null) {}
+
+ getUnit(unitId: string) {
+ return this._workbook?.getUnitId() === unitId ? this._workbook : null;
+ }
+
+ getCurrentUnitOfType() {
+ return this._workbook;
+ }
+
+ getUniverSheetInstance(unitId: string) {
+ return this.getUnit(unitId);
+ }
+}
+
+function createSheetContext(options: ICreateSheetContextOptions = {}) {
+ const {
+ unitId = 'u1',
+ subUnitId = 's1',
+ rowCount = 100,
+ columnCount = 100,
+ dataRange = { endRow: 10, endColumn: 10 },
+ cells = [],
+ } = options;
+ const worksheet = new TestWorksheet(subUnitId, rowCount, columnCount, dataRange, cells);
+ const workbook = new TestWorkbook(unitId, worksheet);
+
+ return {
+ workbook,
+ worksheet,
+ univerInstanceService: new TestUniverInstanceService(workbook),
+ };
+}
+
describe('sheet-table-row-col commands', () => {
it('insert commands should return false when there is no sheet target', () => {
- sheetsMocks.getSheetCommandTarget.mockReturnValue(null);
-
const accessor = createAccessor([
- [IUniverInstanceService, {}],
+ [IUniverInstanceService, new TestUniverInstanceService()],
]);
expect(SheetTableInsertRowCommand.handler(accessor)).toBe(false);
@@ -72,7 +180,7 @@ describe('sheet-table-row-col commands', () => {
it('remove commands should return false for invalid params', () => {
const accessor = createAccessor([
- [IUniverInstanceService, {}],
+ [IUniverInstanceService, new TestUniverInstanceService()],
]);
expect(SheetTableRemoveRowCommand.handler(accessor, undefined as any)).toBe(false);
@@ -80,19 +188,10 @@ describe('sheet-table-row-col commands', () => {
});
it('commands should stop when current selection is invalid or table is missing', () => {
- sheetsMocks.getSheetCommandTarget.mockReturnValue({
- unitId: 'u1',
- subUnitId: 's1',
- worksheet: {
- getRowCount: () => 100,
- getColumnCount: () => 100,
- getCellMatrix: () => ({ getDataRange: () => ({ endRow: 10, endColumn: 10 }) }),
- },
- workbook: {},
- });
+ const { univerInstanceService } = createSheetContext();
const accessor = createAccessor([
- [IUniverInstanceService, {}],
+ [IUniverInstanceService, univerInstanceService],
[SheetsSelectionsService, { getCurrentSelections: () => [] }],
[SheetsTableController, { getContainerTableWithRange: () => null }],
[TableManager, {}],
@@ -107,20 +206,127 @@ describe('sheet-table-row-col commands', () => {
expect(SheetTableRemoveColCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' } as any)).toBe(false);
});
- it('direct row insert should update table range and move trailing table rows', () => {
- sheetsMocks.getSheetCommandTarget.mockReturnValue({
+ it('toolbar insert row should insert worksheet rows when there is not enough trailing space', () => {
+ const range = { startRow: 4, endRow: 5, startColumn: 1, endColumn: 3 };
+ const { univerInstanceService } = createSheetContext({
+ rowCount: 10,
+ columnCount: 20,
+ dataRange: { endRow: 9, endColumn: 8 },
+ });
+
+ const syncExecuteCommand = vi.fn(() => true);
+ const pushUndoRedo = vi.fn();
+ const table = {
+ getId: () => 't1',
+ getRange: () => ({ startRow: 0, endRow: 5, startColumn: 1, endColumn: 3 }),
+ };
+ const accessor = createAccessor([
+ [IUniverInstanceService, univerInstanceService],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range }] }],
+ [SheetsTableController, { getContainerTableWithRange: () => table }],
+ [TableManager, {}],
+ [ICommandService, { syncExecuteCommand }],
+ [IUndoRedoService, { pushUndoRedo }],
+ ]);
+
+ expect(SheetTableInsertRowCommand.handler(accessor)).toBe(true);
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string]>).map(([id]) => id)).toEqual([
+ 'sheet.mutation.insert-row',
+ 'sheet.mutation.set-sheet-table',
+ ]);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'u1',
+ undoMutations: expect.arrayContaining([expect.objectContaining({ id: 'sheet.mutation.remove-rows' })]),
+ }));
+ });
+
+ it('toolbar insert column should insert worksheet columns when there is not enough trailing space', () => {
+ const range = { startRow: 1, endRow: 4, startColumn: 4, endColumn: 5 };
+ const { univerInstanceService } = createSheetContext({
+ rowCount: 20,
+ columnCount: 10,
+ dataRange: { endRow: 8, endColumn: 9 },
+ });
+
+ const syncExecuteCommand = vi.fn(() => true);
+ const pushUndoRedo = vi.fn();
+ const table = {
+ getId: () => 't1',
+ getRange: () => ({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 5 }),
+ };
+ const accessor = createAccessor([
+ [IUniverInstanceService, univerInstanceService],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range }] }],
+ [SheetsTableController, { getContainerTableWithRange: () => table }],
+ [ICommandService, { syncExecuteCommand }],
+ [IUndoRedoService, { pushUndoRedo }],
+ ]);
+
+ expect(SheetTableInsertColCommand.handler(accessor)).toBe(true);
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string]>).map(([id]) => id)).toEqual([
+ 'sheet.mutation.insert-col',
+ 'sheet.mutation.set-sheet-table',
+ ]);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'u1',
+ undoMutations: expect.arrayContaining([expect.objectContaining({ id: 'sheet.mutation.remove-col' })]),
+ }));
+ });
+
+ it('direct insert commands should reject invalid count, table and index inputs', () => {
+ const { univerInstanceService } = createSheetContext();
+ const table = {
+ getSubunitId: () => 's1',
+ getRange: () => ({ startRow: 1, endRow: 4, startColumn: 1, endColumn: 4 }),
+ };
+ const accessor = createAccessor([
+ [IUniverInstanceService, univerInstanceService],
+ [TableManager, { getTableById: (_unitId: string, tableId: string) => (tableId === 't1' ? table : null) }],
+ [ICommandService, { syncExecuteCommand: vi.fn(() => true) }],
+ [IUndoRedoService, { pushUndoRedo: vi.fn() }],
+ ]);
+
+ expect(SheetTableInsertRowAtCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1', index: 2, count: 0 })).toBe(false);
+ expect(SheetTableInsertColumnAtCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 'missing', index: 2, count: 1 })).toBe(false);
+ expect(SheetTableInsertRowAtCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1', index: 1, count: 1 })).toBe(false);
+ expect(SheetTableInsertColumnAtCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1', index: 6, count: 1 })).toBe(false);
+ });
+
+ it('direct row insert should not push undo records when command sequence fails', () => {
+ const { univerInstanceService } = createSheetContext();
+ const syncExecuteCommand = vi.fn(() => false);
+ const pushUndoRedo = vi.fn();
+ const table = {
+ getId: () => 't1',
+ getSubunitId: () => 's1',
+ getRange: () => ({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 }),
+ };
+ const accessor = createAccessor([
+ [IUniverInstanceService, univerInstanceService],
+ [TableManager, { getTableById: () => table }],
+ [ICommandService, { syncExecuteCommand }],
+ [IUndoRedoService, { pushUndoRedo }],
+ ]);
+
+ expect(SheetTableInsertRowAtCommand.handler(accessor, {
unitId: 'u1',
subUnitId: 's1',
- worksheet: {
- getRowCount: () => 100,
- getColumnCount: () => 100,
- getCellMatrix: () => ({ getDataRange: () => ({ endRow: 10, endColumn: 10 }) }),
- },
- workbook: {},
- });
- sheetsMocks.getMoveRangeUndoRedoMutations.mockReturnValue({
- redos: [{ id: 'move-redo', params: {} }],
- undos: [{ id: 'move-undo', params: {} }],
+ tableId: 't1',
+ index: 2,
+ count: 1,
+ })).toBe(false);
+ expect(pushUndoRedo).not.toHaveBeenCalled();
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string]>).map(([id]) => id)).toEqual([
+ 'sheet.mutation.set-sheet-table',
+ ]);
+ });
+
+ it('direct row insert should update table range and move trailing table rows', () => {
+ const { univerInstanceService } = createSheetContext({
+ cells: [
+ [2, 1, { v: 'body-1' }],
+ [10, 3, { v: 'tail' }],
+ ],
});
const syncExecuteCommand = vi.fn(() => true);
@@ -131,7 +337,7 @@ describe('sheet-table-row-col commands', () => {
getRange: () => ({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 }),
};
const accessor = createAccessor([
- [IUniverInstanceService, {}],
+ [IUniverInstanceService, univerInstanceService],
[TableManager, { getTableById: () => table }],
[ICommandService, { syncExecuteCommand }],
[IUndoRedoService, { pushUndoRedo }],
@@ -144,24 +350,46 @@ describe('sheet-table-row-col commands', () => {
index: 2,
count: 1,
})).toBe(true);
- expect(syncExecuteCommand).toHaveBeenCalled();
- expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({ unitID: 'u1' }));
+ const calls = syncExecuteCommand.mock.calls as unknown as Array<[string, any]>;
+ expect(calls.map(([id]) => id)).toEqual([
+ 'sheet.mutation.set-sheet-table',
+ MoveRangeMutation.id,
+ ]);
+ expect(calls[0][1].config.updateRange.newRange).toEqual({ startRow: 0, endRow: 5, startColumn: 1, endColumn: 3 });
+ expect(calls[1][1]).toEqual(expect.objectContaining({
+ fromRange: { startRow: 2, endRow: 10, startColumn: 1, endColumn: 3 },
+ toRange: { startRow: 3, endRow: 11, startColumn: 1, endColumn: 3 },
+ }));
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'u1',
+ undoMutations: expect.arrayContaining([
+ expect.objectContaining({
+ id: 'sheet.mutation.set-sheet-table',
+ params: expect.objectContaining({
+ config: expect.objectContaining({
+ updateRange: expect.objectContaining({
+ newRange: { startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 },
+ }),
+ }),
+ }),
+ }),
+ expect.objectContaining({
+ id: MoveRangeMutation.id,
+ params: expect.objectContaining({
+ fromRange: { startRow: 3, endRow: 11, startColumn: 1, endColumn: 3 },
+ toRange: { startRow: 2, endRow: 10, startColumn: 1, endColumn: 3 },
+ }),
+ }),
+ ]),
+ }));
});
it('direct column insert should update table columns and move trailing table columns', () => {
- sheetsMocks.getSheetCommandTarget.mockReturnValue({
- unitId: 'u1',
- subUnitId: 's1',
- worksheet: {
- getRowCount: () => 100,
- getColumnCount: () => 100,
- getCellMatrix: () => ({ getDataRange: () => ({ endRow: 10, endColumn: 10 }) }),
- },
- workbook: {},
- });
- sheetsMocks.getMoveRangeUndoRedoMutations.mockReturnValue({
- redos: [{ id: 'move-redo', params: {} }],
- undos: [{ id: 'move-undo', params: {} }],
+ const { univerInstanceService } = createSheetContext({
+ cells: [
+ [0, 2, { v: 'middle-col' }],
+ [4, 10, { v: 'tail-col' }],
+ ],
});
const syncExecuteCommand = vi.fn(() => true);
@@ -172,7 +400,7 @@ describe('sheet-table-row-col commands', () => {
getRange: () => ({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 }),
};
const accessor = createAccessor([
- [IUniverInstanceService, {}],
+ [IUniverInstanceService, univerInstanceService],
[TableManager, { getTableById: () => table }],
[ICommandService, { syncExecuteCommand }],
[IUndoRedoService, { pushUndoRedo }],
@@ -185,24 +413,40 @@ describe('sheet-table-row-col commands', () => {
index: 2,
count: 1,
})).toBe(true);
- expect(syncExecuteCommand).toHaveBeenCalled();
- expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({ unitID: 'u1' }));
+ const calls = syncExecuteCommand.mock.calls as unknown as Array<[string, any]>;
+ expect(calls.map(([id]) => id)).toEqual([
+ 'sheet.mutation.set-sheet-table',
+ MoveRangeMutation.id,
+ ]);
+ expect(calls[0][1].config.rowColOperation).toEqual({
+ operationType: 'insert',
+ rowColType: 'column',
+ index: 2,
+ count: 1,
+ });
+ expect(calls[1][1]).toEqual(expect.objectContaining({
+ fromRange: { startRow: 0, endRow: 4, startColumn: 2, endColumn: 10 },
+ toRange: { startRow: 0, endRow: 4, startColumn: 3, endColumn: 11 },
+ }));
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'u1',
+ redoMutations: expect.arrayContaining([
+ expect.objectContaining({
+ id: MoveRangeMutation.id,
+ params: expect.objectContaining({
+ toRange: { startRow: 0, endRow: 4, startColumn: 3, endColumn: 11 },
+ }),
+ }),
+ ]),
+ }));
});
it('direct column remove should update table columns and move trailing table columns', () => {
- sheetsMocks.getSheetCommandTarget.mockReturnValue({
- unitId: 'u1',
- subUnitId: 's1',
- worksheet: {
- getRowCount: () => 100,
- getColumnCount: () => 100,
- getCellMatrix: () => ({ getDataRange: () => ({ endRow: 10, endColumn: 10 }) }),
- },
- workbook: {},
- });
- sheetsMocks.getMoveRangeUndoRedoMutations.mockReturnValue({
- redos: [{ id: 'move-redo', params: {} }],
- undos: [{ id: 'move-undo', params: {} }],
+ const { univerInstanceService } = createSheetContext({
+ cells: [
+ [0, 3, { v: 'right-col' }],
+ [4, 10, { v: 'tail-col' }],
+ ],
});
const syncExecuteCommand = vi.fn(() => true);
@@ -227,7 +471,7 @@ describe('sheet-table-row-col commands', () => {
}),
};
const accessor = createAccessor([
- [IUniverInstanceService, {}],
+ [IUniverInstanceService, univerInstanceService],
[TableManager, { getTableById: () => table }],
[ICommandService, { syncExecuteCommand }],
[IUndoRedoService, { pushUndoRedo }],
@@ -255,13 +499,24 @@ describe('sheet-table-row-col commands', () => {
'formula.redo.before',
'sheet.mutation.set-sheet-table',
'formula.redo.after',
- 'move-redo',
+ MoveRangeMutation.id,
]);
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string, any]>)[3][1]).toEqual(expect.objectContaining({
+ fromRange: { startRow: 0, endRow: 4, startColumn: 3, endColumn: 10 },
+ toRange: { startRow: 0, endRow: 4, startColumn: 2, endColumn: 9 },
+ }));
expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
unitID: 'u1',
undoMutations: expect.arrayContaining([
expect.objectContaining({ id: 'formula.undo.before' }),
expect.objectContaining({ id: 'formula.undo.after' }),
+ expect.objectContaining({
+ id: MoveRangeMutation.id,
+ params: expect.objectContaining({
+ fromRange: { startRow: 0, endRow: 4, startColumn: 2, endColumn: 9 },
+ toRange: { startRow: 0, endRow: 4, startColumn: 3, endColumn: 10 },
+ }),
+ }),
]),
redoMutations: expect.arrayContaining([
expect.objectContaining({ id: 'formula.redo.before' }),
@@ -269,4 +524,130 @@ describe('sheet-table-row-col commands', () => {
]),
}));
});
+
+ it('toolbar remove row should shrink the table and move trailing rows', () => {
+ const range = { startRow: 2, endRow: 3, startColumn: 1, endColumn: 3 };
+ const { univerInstanceService } = createSheetContext({
+ cells: [
+ [4, 1, { v: 'after-removed-row' }],
+ [10, 3, { v: 'tail-row' }],
+ ],
+ });
+
+ const syncExecuteCommand = vi.fn(() => true);
+ const pushUndoRedo = vi.fn();
+ const table = {
+ getId: () => 't1',
+ getRange: () => ({ startRow: 0, endRow: 5, startColumn: 1, endColumn: 3 }),
+ };
+ const accessor = createAccessor([
+ [IUniverInstanceService, univerInstanceService],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range }] }],
+ [SheetsTableController, { getContainerTableWithRange: () => table }],
+ [ICommandService, { syncExecuteCommand }],
+ [IUndoRedoService, { pushUndoRedo }],
+ ]);
+
+ expect(SheetTableRemoveRowCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' })).toBe(true);
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string]>).map(([id]) => id)).toEqual([
+ 'sheet.mutation.set-sheet-table',
+ MoveRangeMutation.id,
+ ]);
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string, any]>)[0][1].config.updateRange.newRange).toEqual({
+ startRow: 0,
+ endRow: 3,
+ startColumn: 1,
+ endColumn: 3,
+ });
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string, any]>)[1][1]).toEqual(expect.objectContaining({
+ fromRange: { startRow: 4, endRow: 10, startColumn: 1, endColumn: 3 },
+ toRange: { startRow: 2, endRow: 8, startColumn: 1, endColumn: 3 },
+ }));
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'u1',
+ redoMutations: expect.arrayContaining([expect.objectContaining({ id: MoveRangeMutation.id })]),
+ }));
+ });
+
+ it('toolbar remove column should notify interceptors, restore removed column metadata, and move trailing columns', () => {
+ const range = { startRow: 0, endRow: 4, startColumn: 2, endColumn: 2 };
+ const { univerInstanceService } = createSheetContext({
+ dataRange: { endRow: 10, endColumn: 8 },
+ cells: [
+ [0, 3, { v: 'after-removed-col' }],
+ [4, 8, { v: 'tail-col' }],
+ ],
+ });
+
+ const syncExecuteCommand = vi.fn(() => true);
+ const pushUndoRedo = vi.fn();
+ const onCommandExecute = vi.fn(() => ({
+ preRedos: [{ id: 'pre-redo', params: {} }],
+ redos: [{ id: 'post-redo', params: {} }],
+ preUndos: [{ id: 'pre-undo', params: {} }],
+ undos: [{ id: 'post-undo', params: {} }],
+ }));
+ const table = {
+ getId: () => 't1',
+ getRange: () => ({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 4 }),
+ getTableInfo: () => ({
+ name: 'Table',
+ columns: [
+ { id: 'c1', displayName: 'A' },
+ { id: 'c2', displayName: 'B' },
+ { id: 'c3', displayName: 'C' },
+ ],
+ }),
+ };
+ const accessor = createAccessor([
+ [IUniverInstanceService, univerInstanceService],
+ [TableManager, {}],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range }] }],
+ [SheetsTableController, { getContainerTableWithRange: () => table }],
+ [ICommandService, { syncExecuteCommand }],
+ [IUndoRedoService, { pushUndoRedo }],
+ [SheetInterceptorService, { onCommandExecute }],
+ ]);
+
+ expect(SheetTableRemoveColCommand.handler(accessor, { unitId: 'u1', subUnitId: 's1', tableId: 't1' })).toBe(true);
+ expect(onCommandExecute).toHaveBeenCalledWith({
+ id: SheetTableRemoveColCommand.id,
+ params: expect.objectContaining({
+ tableName: 'Table',
+ removedColumnNames: ['B'],
+ }),
+ });
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string]>).map(([id]) => id)).toEqual([
+ 'pre-redo',
+ 'sheet.mutation.set-sheet-table',
+ 'post-redo',
+ MoveRangeMutation.id,
+ ]);
+ expect((syncExecuteCommand.mock.calls as unknown as Array<[string, any]>)[3][1]).toEqual(expect.objectContaining({
+ fromRange: { startRow: 0, endRow: 4, startColumn: 3, endColumn: 8 },
+ toRange: { startRow: 0, endRow: 4, startColumn: 2, endColumn: 7 },
+ }));
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ undoMutations: expect.arrayContaining([
+ expect.objectContaining({ id: 'pre-undo' }),
+ expect.objectContaining({
+ id: 'sheet.mutation.set-sheet-table',
+ params: expect.objectContaining({
+ config: expect.objectContaining({
+ rowColOperation: expect.objectContaining({
+ columnsJson: [{ id: 'c2', displayName: 'B' }],
+ }),
+ }),
+ }),
+ }),
+ expect.objectContaining({
+ id: MoveRangeMutation.id,
+ params: expect.objectContaining({
+ fromRange: { startRow: 0, endRow: 4, startColumn: 2, endColumn: 7 },
+ toRange: { startRow: 0, endRow: 4, startColumn: 3, endColumn: 8 },
+ }),
+ }),
+ ]),
+ }));
+ });
});
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.tsx
index f4c92c75da..eb7570f5b8 100644
--- a/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
+++ b/packages/sheets-thread-comment-ui/src/views/__tests__/SheetsThreadCommentPanel.spec.tsx
@@ -257,6 +257,7 @@ function createTestBed() {
commandService,
threadCommentModel: get(ThreadCommentModel),
popupService: get(SheetsThreadCommentPopupService),
+ panelService: get(ThreadCommentPanelService),
};
}
@@ -402,4 +403,28 @@ describe('SheetsThreadCommentPanel', () => {
expect(testBed.popupService.activePopup).toBeNull();
expect(TestState.popupDisposeCount).toBe(1);
});
+
+ it('removes the hover highlight when the panel is hidden by service state', () => {
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ testBed.panelService.setPanelVisible(true);
+ testBed.threadCommentModel.addComment(unitId, sheet1, createComment('current-sheet-thread', sheet1, 'B2', 'Current sheet B2'));
+
+ const rendered = renderPanel(testBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ const currentThread = container.querySelector(`#PANEL-${unitId}-${sheet1}-current-sheet-thread`);
+ expect(currentThread).toBeInstanceOf(HTMLElement);
+
+ dispatchMouseEvent(currentThread!, 'mouseover');
+ expect(TestState.shapes).toHaveLength(1);
+
+ act(() => {
+ testBed.panelService.setPanelVisible(false);
+ });
+
+ expect(TestState.shapes).toHaveLength(0);
+ expect(TestState.removedShapeIds).toEqual(['shape-1']);
+ });
});
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-event.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-event.spec.ts
new file mode 100644
index 0000000000..32602a6c15
--- /dev/null
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-event.spec.ts
@@ -0,0 +1,37 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { FEventName } from '@univerjs/core/facade';
+import { describe, expect, it } from 'vitest';
+import { FSheetsThreadCommentEventNameMixin } from '../f-event';
+
+describe('FSheetsThreadCommentEventNameMixin', () => {
+ it('adds thread-comment event names to facade event names', () => {
+ const eventName = Object.create(FSheetsThreadCommentEventNameMixin.prototype) as FSheetsThreadCommentEventNameMixin;
+ const extended = new FEventName();
+
+ expect(eventName.CommentAdded).toBe('CommentAdded');
+ expect(eventName.BeforeCommentAdd).toBe('BeforeCommentAdd');
+ expect(eventName.CommentUpdated).toBe('CommentUpdated');
+ expect(eventName.BeforeCommentUpdate).toBe('BeforeCommentUpdate');
+ expect(eventName.CommentDeleted).toBe('CommentDeleted');
+ expect(eventName.BeforeCommentDelete).toBe('BeforeCommentDelete');
+ expect(eventName.CommentResolved).toBe('CommentResolved');
+ expect(eventName.BeforeCommentResolve).toBe('BeforeCommentResolve');
+ expect(extended.CommentAdded).toBe('CommentAdded');
+ expect(extended.BeforeCommentResolve).toBe('BeforeCommentResolve');
+ });
+});
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts
new file mode 100644
index 0000000000..8620784f1f
--- /dev/null
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-range.spec.ts
@@ -0,0 +1,156 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import {
+ ICommandService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ RichTextBuilder,
+ UniverInstanceType,
+ UserManagerService,
+} from '@univerjs/core';
+import { FormulaDataModel } from '@univerjs/engine-formula';
+import { AddCommentCommand, DeleteCommentTreeCommand, ThreadCommentModel } from '@univerjs/thread-comment';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsThreadCommentModel } from '../../models/sheets-thread-comment.model';
+import { FRangeSheetsThreadCommentMixin } from '../f-range';
+import { FTheadCommentBuilder } from '../f-thread-comment';
+
+function createComment(id: string, ref: string) {
+ return {
+ id,
+ threadId: `thread-${id}`,
+ ref,
+ dT: '2025-01-01T00:00:00.000Z',
+ personId: 'user-1',
+ text: RichTextBuilder.newEmptyData().body!,
+ attachments: [],
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ children: [],
+ };
+}
+
+describe('FRangeSheetsThreadCommentMixin', () => {
+ it('gets, adds, and clears comments through injected services', async () => {
+ const commandService = { executeCommand: vi.fn(async () => true) };
+ const comments = new Map([
+ ['comment-1', createComment('comment-1', 'A1')],
+ ['comment-2', createComment('comment-2', 'B1')],
+ ]);
+ const locations = new Map([
+ ['0:0', 'comment-1'],
+ ['0:1', 'comment-2'],
+ ]);
+
+ class TestSheetsThreadCommentModel {
+ getByLocation = (_unitId: string, _sheetId: string, row: number, col: number) => locations.get(`${row}:${col}`);
+ getComment = (_unitId: string, _sheetId: string, commentId: string) => comments.get(commentId);
+ getCommentWithChildren = (_unitId: string, _sheetId: string, commentId: string) => comments.get(commentId);
+ }
+
+ class TestUserManagerService {
+ getCurrentUser = () => ({ userID: 'current-user' });
+ }
+
+ class TestUniverInstanceService {
+ getUnit = (_unitId: string, type: UniverInstanceType) => (type === UniverInstanceType.UNIVER_SHEET ? workbook : null);
+ }
+
+ class TestThreadCommentModel {
+ getCommentWithChildren = (_unitId: string, _subUnitId: string, commentId: string) => comments.get(commentId);
+ }
+
+ class TestFormulaDataModel {}
+ class TestLogService {}
+
+ const injector = new Injector();
+ injector.add([SheetsThreadCommentModel, { useClass: TestSheetsThreadCommentModel as never }]);
+ injector.add([ICommandService, { useClass: class { executeCommand = commandService.executeCommand; } as never }]);
+ injector.add([UserManagerService, { useClass: TestUserManagerService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([ThreadCommentModel, { useClass: TestThreadCommentModel as never }]);
+ injector.add([FormulaDataModel, { useClass: TestFormulaDataModel as never }]);
+ injector.add([ILogService, { useClass: TestLogService as never }]);
+
+ const workbook = { getUnitId: () => 'book-1', getSheetBySheetId: () => worksheet };
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getRowCount: () => 100,
+ getColumnCount: () => 100,
+ };
+ const range = injector.createInstance(
+ FRangeSheetsThreadCommentMixin,
+ workbook as never,
+ worksheet as never,
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }
+ );
+
+ expect(range.getComment()?.getCommentData().id).toBe('comment-1');
+ expect(range.getComments().map((comment) => comment.getCommentData().id)).toEqual(['comment-1', 'comment-2']);
+
+ await expect(range.addCommentAsync(FTheadCommentBuilder.create().setId('new-comment'))).resolves.toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(AddCommentCommand.id, expect.objectContaining({
+ comment: expect.objectContaining({
+ id: 'new-comment',
+ ref: 'A1',
+ personId: 'current-user',
+ parentId: 'comment-1',
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ }),
+ }));
+
+ await expect(range.clearCommentAsync()).resolves.toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(DeleteCommentTreeCommand.id, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ threadId: 'thread-comment-1',
+ commentId: 'comment-1',
+ });
+
+ await expect(range.clearCommentsAsync()).resolves.toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(DeleteCommentTreeCommand.id, expect.objectContaining({ commentId: 'comment-2' }));
+ });
+
+ it('returns empty comment results and treats clearing an empty cell as successful', async () => {
+ class TestSheetsThreadCommentModel {
+ getByLocation = () => 'missing-comment';
+ getComment = () => null;
+ }
+
+ const injector = new Injector();
+ injector.add([SheetsThreadCommentModel, { useClass: TestSheetsThreadCommentModel as never }]);
+ injector.add([ICommandService, { useClass: class { executeCommand = vi.fn(async () => true); } as never }]);
+ injector.add([UserManagerService, { useClass: class { getCurrentUser = () => ({ userID: 'user' }); } as never }]);
+ injector.add([IUniverInstanceService, { useClass: class { getUnit = () => null; } as never }]);
+ injector.add([ThreadCommentModel, { useClass: class { getCommentWithChildren = () => null; } as never }]);
+ injector.add([FormulaDataModel, { useClass: class {} as never }]);
+ injector.add([ILogService, { useClass: class {} as never }]);
+
+ const range = injector.createInstance(
+ FRangeSheetsThreadCommentMixin,
+ { getUnitId: () => 'book-1' } as never,
+ { getSheetId: () => 'sheet-1', getRowCount: () => 10, getColumnCount: () => 10 } as never,
+ { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }
+ );
+
+ expect(range.getComment()).toBeNull();
+ expect(range.getComments()).toEqual([]);
+ await expect(range.clearComment()).resolves.toBe(true);
+ });
+});
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-univer.spec.ts
new file mode 100644
index 0000000000..99f6c72cf2
--- /dev/null
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-univer.spec.ts
@@ -0,0 +1,193 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ICommandService, Injector, RichTextBuilder } from '@univerjs/core';
+import {
+ AddCommentCommand,
+ DeleteCommentCommand,
+ DeleteCommentTreeCommand,
+ ResolveCommentCommand,
+ UpdateCommentCommand,
+} from '@univerjs/thread-comment';
+import { describe, expect, it, vi } from 'vitest';
+import { FUniverSheetsThreadCommentMixin } from '../f-univer';
+import '../f-event';
+
+function createApi(cancelEvents = new Set<string>()) {
+ const afterListeners: Array<(commandInfo: any) => void> = [];
+ const beforeListeners: Array<(commandInfo: any) => void> = [];
+ const commandService = {
+ onCommandExecuted: (listener: (commandInfo: any) => void) => {
+ afterListeners.push(listener);
+ return { dispose: vi.fn() };
+ },
+ beforeCommandExecuted: (listener: (commandInfo: any) => void) => {
+ beforeListeners.push(listener);
+ return { dispose: vi.fn() };
+ },
+ };
+ class TestCommandService {
+ onCommandExecuted = commandService.onCommandExecuted;
+ beforeCommandExecuted = commandService.beforeCommandExecuted;
+ }
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+
+ const fired: Array<{ name: string; params: any }> = [];
+ const range = { getRow: () => 2, getColumn: () => 3 };
+ const threadComment = {
+ getRange: () => range,
+ };
+ const workbook = {};
+ const worksheet = {
+ getCommentById: (commentId: string) => (commentId === 'missing' ? null : threadComment),
+ };
+ const api = Object.create(FUniverSheetsThreadCommentMixin.prototype) as any;
+ Object.defineProperty(api, 'Event', {
+ value: {
+ CommentAdded: 'CommentAdded',
+ BeforeCommentAdd: 'BeforeCommentAdd',
+ CommentUpdated: 'CommentUpdated',
+ BeforeCommentUpdate: 'BeforeCommentUpdate',
+ CommentDeleted: 'CommentDeleted',
+ BeforeCommentDelete: 'BeforeCommentDelete',
+ CommentResolved: 'CommentResolved',
+ BeforeCommentResolve: 'BeforeCommentResolve',
+ },
+ });
+ api.disposeWithMe = vi.fn((disposable) => disposable);
+ api.registerEventHandler = vi.fn((_name: string, register: () => unknown) => register());
+ api.getSheetCommandTarget = vi.fn(() => ({ workbook, worksheet }));
+ api.fireEvent = vi.fn((name: string, params: any) => {
+ if (cancelEvents.has(name)) {
+ params.cancel = true;
+ }
+ fired.push({ name, params });
+ });
+ api._initialize(injector);
+
+ return { api, fired, afterListeners, beforeListeners, workbook, worksheet, threadComment };
+}
+
+describe('FUniverSheetsThreadCommentMixin', () => {
+ it('creates thread comment builders', () => {
+ const { api } = createApi();
+ const builder = api.newTheadComment().setId('comment-1');
+
+ expect(builder.id).toBe('comment-1');
+ });
+
+ it('fires public comment events from executed comment commands', () => {
+ const { api, fired, afterListeners, workbook, worksheet, threadComment } = createApi();
+
+ afterListeners.forEach((listener) => listener({ id: 'unrelated.command', params: {} }));
+ api.getSheetCommandTarget.mockReturnValueOnce(null);
+ afterListeners.forEach((listener) => listener({
+ id: AddCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', comment: { id: 'comment-1' } },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: AddCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', comment: { id: 'comment-1' } },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: UpdateCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', payload: { commentId: 'comment-1' } },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: DeleteCommentTreeCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'comment-1' },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: ResolveCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'comment-1', resolved: true },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: AddCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', comment: { id: 'missing' } },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: UpdateCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', payload: { commentId: 'missing' } },
+ }));
+ afterListeners.forEach((listener) => listener({
+ id: ResolveCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'missing', resolved: true },
+ }));
+
+ expect(fired).toEqual([
+ { name: 'CommentAdded', params: { workbook, worksheet, row: 2, col: 3, comment: threadComment } },
+ { name: 'CommentUpdated', params: { workbook, worksheet, row: 2, col: 3, comment: threadComment } },
+ { name: 'CommentDeleted', params: { workbook, worksheet, commentId: 'comment-1' } },
+ { name: 'CommentResolved', params: { workbook, worksheet, row: 2, col: 3, comment: threadComment, resolved: true } },
+ ]);
+ });
+
+ it('fires before comment events and cancels commands when listeners request it', () => {
+ const body = RichTextBuilder.newEmptyData().body!;
+ const { api, fired, beforeListeners } = createApi();
+
+ beforeListeners.forEach((listener) => listener({ id: 'unrelated.command', params: {} }));
+ api.getSheetCommandTarget.mockReturnValueOnce(null);
+ beforeListeners.forEach((listener) => listener({
+ id: AddCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', comment: { id: 'comment-1', ref: 'B2', text: body } },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: AddCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', comment: { id: 'comment-1', ref: 'B2', text: body } },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: UpdateCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', payload: { commentId: 'comment-1', text: body } },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: DeleteCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'comment-1' },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: ResolveCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'comment-1', resolved: false },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: UpdateCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', payload: { commentId: 'missing', text: body } },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: DeleteCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'missing' },
+ }));
+ beforeListeners.forEach((listener) => listener({
+ id: ResolveCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'missing', resolved: false },
+ }));
+
+ expect(fired.map((event) => event.name)).toEqual([
+ 'BeforeCommentAdd',
+ 'BeforeCommentUpdate',
+ 'BeforeCommentDelete',
+ 'BeforeCommentResolve',
+ ]);
+
+ const canceled = createApi(new Set(['BeforeCommentAdd']));
+ expect(() => {
+ canceled.beforeListeners.forEach((listener) => listener({
+ id: AddCommentCommand.id,
+ params: { unitId: 'book-1', subUnitId: 'sheet-1', comment: { id: 'comment-1', ref: 'A1', text: body } },
+ }));
+ }).toThrow();
+ });
+});
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts
index f75c8e1b5f..3b8f3d9ebd 100644
--- a/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import { AddCommentCommand, DeleteCommentCommand, UpdateCommentCommand } from '@univerjs/thread-comment';
+import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { FWorkbookSheetsThreadCommentMixin } from '../f-workbook';
@@ -37,4 +39,64 @@ describe('FWorkbookSheetsThreadCommentMixin', () => {
expect(deleteAsync).toHaveBeenCalledTimes(1);
expect(createInstance).toHaveBeenCalledTimes(2);
});
+
+ it('should filter workbook comment update subscriptions to the current workbook', () => {
+ const commentUpdate$ = new Subject<any>();
+ const callback = vi.fn();
+ const instance = Object.create(FWorkbookSheetsThreadCommentMixin.prototype) as any;
+ instance._workbook = { getUnitId: () => 'unit-1' };
+ instance._threadCommentModel = { commentUpdate$ };
+
+ const disposable = instance.onThreadCommentChange(callback);
+
+ commentUpdate$.next({ unitId: 'other', payload: 1 });
+ commentUpdate$.next({ unitId: 'unit-1', payload: 2 });
+
+ expect(callback).toHaveBeenCalledWith({ unitId: 'unit-1', payload: 2 });
+ disposable.dispose();
+ commentUpdate$.next({ unitId: 'unit-1', payload: 3 });
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it('should run deprecated before-command hooks for current workbook comments', () => {
+ const beforeListeners: Array<(commandInfo: any, options?: any) => void> = [];
+ const instance = Object.create(FWorkbookSheetsThreadCommentMixin.prototype) as any;
+ instance._workbook = { getUnitId: () => 'unit-1' };
+ instance._commandService = {
+ beforeCommandExecuted: (listener: (commandInfo: any, options?: any) => void) => {
+ beforeListeners.push(listener);
+ return { dispose: vi.fn() };
+ },
+ };
+ const beforeAdd = vi.fn();
+ const beforeUpdate = vi.fn();
+ const beforeDelete = vi.fn();
+
+ instance.onBeforeAddThreadComment(beforeAdd);
+ instance.onBeforeUpdateThreadComment(beforeUpdate);
+ instance.onBeforeDeleteThreadComment(beforeDelete);
+
+ beforeListeners.forEach((listener) => listener({ id: AddCommentCommand.id, params: { unitId: 'other' } }, { local: true }));
+ beforeListeners.forEach((listener) => listener({ id: AddCommentCommand.id, params: { unitId: 'unit-1', comment: { id: 'comment-1' } } }, { local: true }));
+ beforeListeners.forEach((listener) => listener({ id: UpdateCommentCommand.id, params: { unitId: 'unit-1', payload: { commentId: 'comment-1' } } }));
+ beforeListeners.forEach((listener) => listener({ id: DeleteCommentCommand.id, params: { unitId: 'unit-1', commentId: 'comment-1' } }));
+
+ expect(beforeAdd).toHaveBeenCalledTimes(1);
+ expect(beforeAdd).toHaveBeenCalledWith({ unitId: 'unit-1', comment: { id: 'comment-1' } }, { local: true });
+ expect(beforeUpdate).toHaveBeenCalledWith({ unitId: 'unit-1', payload: { commentId: 'comment-1' } }, undefined);
+ expect(beforeDelete).toHaveBeenCalledWith({ unitId: 'unit-1', commentId: 'comment-1' }, undefined);
+
+ const blocked = Object.create(FWorkbookSheetsThreadCommentMixin.prototype) as any;
+ const blockedListeners: Array<(commandInfo: any) => void> = [];
+ blocked._workbook = { getUnitId: () => 'unit-1' };
+ blocked._commandService = {
+ beforeCommandExecuted: (listener: (commandInfo: any) => void) => {
+ blockedListeners.push(listener);
+ return { dispose: vi.fn() };
+ },
+ };
+ blocked.onBeforeAddThreadComment(() => false);
+
+ expect(() => blockedListeners[0]({ id: AddCommentCommand.id, params: { unitId: 'unit-1' } })).toThrow('Command is stopped by the hook onBeforeAddThreadComment');
+ });
});
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts
index 24a1d0b4db..79df3ccadc 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/selection-utils.spec.ts
@@ -15,7 +15,7 @@
*/
import { Direction, RANGE_TYPE } from '@univerjs/core';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import {
checkIfShrink,
expandToNextCell,
@@ -30,14 +30,6 @@ import {
shrinkToNextCell,
} from '../utils/selection-utils';
-vi.mock('@univerjs/sheets', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@univerjs/sheets')>();
- return {
- ...actual,
- alignToMergedCellsBorders: (range: any) => range,
- };
-});
-
function createMatrix(hasValue = false) {
return {
forValue: (cb: (...args: any[]) => void) => {
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
index 8e11621510..2a54192c93 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-format-painter.command.spec.ts
@@ -38,7 +38,11 @@ import {
import { BehaviorSubject } from 'rxjs';
import { beforeEach, describe, expect, it } from 'vitest';
import { FormatPainterController } from '../../../controllers/format-painter/format-painter.controller';
-import { FormatPainterService, IFormatPainterService } from '../../../services/format-painter/format-painter.service';
+import {
+ FormatPainterService,
+ FormatPainterStatus,
+ IFormatPainterService,
+} from '../../../services/format-painter/format-painter.service';
import { IMarkSelectionService } from '../../../services/mark-selection/mark-selection.service';
import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
import { SetFormatPainterOperation } from '../../operations/set-format-painter.operation';
@@ -234,6 +238,24 @@ describe('Test format painter rules in controller', () => {
});
describe('format painter', () => {
+ it('toggles toolbar commands between active mode and off', async () => {
+ const formatPainterService = get(IFormatPainterService);
+
+ expect(formatPainterService.getStatus()).toBe(FormatPainterStatus.OFF);
+
+ expect(await commandService.executeCommand(SetInfiniteFormatPainterCommand.id)).toBeTruthy();
+ expect(formatPainterService.getStatus()).toBe(FormatPainterStatus.INFINITE);
+
+ expect(await commandService.executeCommand(SetInfiniteFormatPainterCommand.id)).toBeTruthy();
+ expect(formatPainterService.getStatus()).toBe(FormatPainterStatus.OFF);
+
+ expect(await commandService.executeCommand(SetOnceFormatPainterCommand.id)).toBeTruthy();
+ expect(formatPainterService.getStatus()).toBe(FormatPainterStatus.ONCE);
+
+ expect(await commandService.executeCommand(SetOnceFormatPainterCommand.id)).toBeTruthy();
+ expect(formatPainterService.getStatus()).toBe(FormatPainterStatus.OFF);
+ });
+
describe('format painter the numbers', async () => {
it('correct situation', async () => {
const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
diff --git a/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.ts b/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.ts
index b5f8327e48..64042b523d 100644
--- a/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.ts
+++ b/packages/sheets-ui/src/commands/operations/__tests__/sidebar-defined-name.operation.spec.ts
@@ -14,82 +14,220 @@
* limitations under the License.
*/
-import { IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { Injector, IUniverInstanceService, LocaleService } from '@univerjs/core';
import { IEditorService } from '@univerjs/docs-ui';
-import { getSheetCommandTarget } from '@univerjs/sheets';
-import { ISidebarService } from '@univerjs/ui';
-import { describe, expect, it, vi } from 'vitest';
+import { EditStateEnum, UnitObject, ViewStateEnum } from '@univerjs/sheets';
+import { IDialogService, ISidebarService } from '@univerjs/ui';
+import { describe, expect, it } from 'vitest';
+import {
+ UNIVER_SHEET_PERMISSION_DIALOG,
+ UNIVER_SHEET_PERMISSION_DIALOG_ID,
+ UNIVER_SHEET_PERMISSION_PANEL,
+} from '../../../consts/permission';
+import { SheetPermissionPanelModel } from '../../../services/permission/sheet-permission-panel.model';
+import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';
+import { ISheetBarService } from '../../../services/sheet-bar/sheet-bar.service';
import { DEFINED_NAME_CONTAINER } from '../../../views/defined-name/component-name';
+import { RenameSheetOperation } from '../rename-sheet.operation';
+import { SheetPermissionOpenDialogOperation } from '../sheet-permission-open-dialog.operation';
+import { SheetPermissionOpenPanelOperation } from '../sheet-permission-open-panel.operation';
import { SidebarDefinedNameOperation } from '../sidebar-defined-name.operation';
-vi.mock('@univerjs/sheets', () => ({
- getSheetCommandTarget: vi.fn(),
-}));
-
-function createAccessor(pairs: Array<[unknown, unknown]>) {
- const map = new Map<unknown, unknown>(pairs);
- return {
- get(token: unknown) {
- if (!map.has(token)) {
- throw new Error(`Unknown token: ${String(token)}`);
- }
- return map.get(token);
- },
- } as any;
+class SidebarServiceForTest {
+ readonly openCalls: unknown[] = [];
+ closeCount = 0;
+
+ open(props: unknown) {
+ this.openCalls.push(props);
+ }
+
+ close() {
+ this.closeCount += 1;
+ }
+}
+
+class DialogServiceForTest {
+ readonly openCalls: unknown[] = [];
+ readonly closeIds: string[] = [];
+
+ open(props: unknown) {
+ this.openCalls.push(props);
+ }
+
+ close(id: string) {
+ this.closeIds.push(id);
+ }
+}
+
+class SheetBarServiceForTest {
+ readonly renameIds: string[] = [];
+
+ setRenameId(subUnitId: string) {
+ this.renameIds.push(subUnitId);
+ }
+}
+
+class EditorServiceForTest {
+}
+
+class LocaleServiceForTest {
+ t(key: string) {
+ return `localized:${key}`;
+ }
+}
+
+class WorkbookForTest {
+ getUnitId() {
+ return 'unit-1';
+ }
+
+ getActiveSheet() {
+ return {
+ getSheetId: () => 'sheet-1',
+ };
+ }
+}
+
+class UniverInstanceWithSheet {
+ getCurrentUnitOfType() {
+ return new WorkbookForTest();
+ }
+}
+
+class UniverInstanceWithoutSheet {
+ getCurrentUnitOfType() {
+ return null;
+ }
+}
+
+function addUseClass(injector: Injector, token: unknown, useClass: unknown) {
+ injector.add([token, { useClass }] as any);
+}
+
+function createOperationInjector(univerClass: typeof UniverInstanceWithSheet | typeof UniverInstanceWithoutSheet = UniverInstanceWithSheet) {
+ const injector = new Injector();
+ addUseClass(injector, ISidebarService, SidebarServiceForTest);
+ addUseClass(injector, IDialogService, DialogServiceForTest);
+ addUseClass(injector, ISheetBarService, SheetBarServiceForTest);
+ addUseClass(injector, IEditorService, EditorServiceForTest);
+ addUseClass(injector, LocaleService, LocaleServiceForTest);
+ addUseClass(injector, IUniverInstanceService, univerClass);
+ injector.add([SheetPermissionPanelModel]);
+ injector.add([SheetPermissionUserManagerService]);
+ return injector;
}
describe('SidebarDefinedNameOperation', () => {
it('returns false when there is no sheet command target', async () => {
- vi.mocked(getSheetCommandTarget).mockReturnValue(null as any);
- const open = vi.fn();
- const close = vi.fn();
- const accessor = createAccessor([
- [ISidebarService, { open, close }],
- [IEditorService, {}],
- [LocaleService, { t: vi.fn(() => 'Defined Name') }],
- [IUniverInstanceService, {}],
- ]);
-
- await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'open' } as any)).resolves.toBe(false);
- expect(open).not.toHaveBeenCalled();
- expect(close).not.toHaveBeenCalled();
+ const injector = createOperationInjector(UniverInstanceWithoutSheet);
+
+ await expect(SidebarDefinedNameOperation.handler(injector, { value: 'open' })).resolves.toBe(false);
+
+ const sidebarService = injector.get(ISidebarService) as unknown as SidebarServiceForTest;
+ expect(sidebarService.openCalls).toEqual([]);
+ expect(sidebarService.closeCount).toBe(0);
});
it('opens sidebar with localized title when value is open', async () => {
- vi.mocked(getSheetCommandTarget).mockReturnValue({ unitId: 'u1', subUnitId: 's1' } as any);
- const open = vi.fn();
- const close = vi.fn();
- const accessor = createAccessor([
- [ISidebarService, { open, close }],
- [IEditorService, {}],
- [LocaleService, { t: vi.fn(() => 'Defined Name') }],
- [IUniverInstanceService, {}],
- ]);
-
- await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'open' } as any)).resolves.toBe(true);
- expect(open).toHaveBeenCalledWith(expect.objectContaining({
+ const injector = createOperationInjector();
+
+ await expect(SidebarDefinedNameOperation.handler(injector, { value: 'open' })).resolves.toBe(true);
+
+ const sidebarService = injector.get(ISidebarService) as unknown as SidebarServiceForTest;
+ expect(sidebarService.openCalls).toEqual([expect.objectContaining({
id: DEFINED_NAME_CONTAINER,
width: 333,
- header: { title: 'Defined Name' },
+ header: { title: 'localized:sheets-ui.definedName.featureTitle' },
children: { label: DEFINED_NAME_CONTAINER },
- }));
- expect(close).not.toHaveBeenCalled();
+ bodyStyle: {
+ height: '100%',
+ overflow: 'hidden',
+ },
+ })]);
+ (sidebarService.openCalls[0] as { onClose: () => void }).onClose();
+ expect(sidebarService.closeCount).toBe(0);
});
it('closes sidebar for close/default action', async () => {
- vi.mocked(getSheetCommandTarget).mockReturnValue({ unitId: 'u1', subUnitId: 's1' } as any);
- const close = vi.fn();
- const accessor = createAccessor([
- [ISidebarService, { open: vi.fn(), close }],
- [IEditorService, {}],
- [LocaleService, { t: vi.fn(() => 'Defined Name') }],
- [IUniverInstanceService, {}],
- ]);
-
- await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'close' } as any)).resolves.toBe(true);
- expect(close).toHaveBeenCalledTimes(1);
-
- await expect(SidebarDefinedNameOperation.handler(accessor, { value: 'other' } as any)).resolves.toBe(true);
- expect(close).toHaveBeenCalledTimes(2);
+ const injector = createOperationInjector();
+
+ await expect(SidebarDefinedNameOperation.handler(injector, { value: 'close' })).resolves.toBe(true);
+ await expect(SidebarDefinedNameOperation.handler(injector, { value: 'other' })).resolves.toBe(true);
+
+ expect((injector.get(ISidebarService) as unknown as SidebarServiceForTest).closeCount).toBe(2);
+ });
+});
+
+describe('sheet bar and permission operations', () => {
+ it('marks the requested sheet as being renamed from the sheet bar', async () => {
+ const injector = createOperationInjector();
+
+ await expect(RenameSheetOperation.handler(injector, { subUnitId: 'sheet-2' })).resolves.toBe(true);
+ await expect(RenameSheetOperation.handler(injector)).resolves.toBe(true);
+
+ expect((injector.get(ISheetBarService) as unknown as SheetBarServiceForTest).renameIds).toEqual(['sheet-2']);
+ });
+
+ it('opens the permission dialog after closing find and replace', async () => {
+ const injector = createOperationInjector();
+
+ await expect(SheetPermissionOpenDialogOperation.handler(injector)).resolves.toBe(true);
+
+ const dialogService = injector.get(IDialogService) as unknown as DialogServiceForTest;
+ expect(dialogService.closeIds).toEqual(['DESKTOP_FIND_REPLACE_DIALOG']);
+ expect(dialogService.openCalls).toEqual([expect.objectContaining({
+ id: UNIVER_SHEET_PERMISSION_DIALOG_ID,
+ title: { title: 'sheets-ui.permission.dialog.allowedPermissionType' },
+ children: { label: UNIVER_SHEET_PERMISSION_DIALOG },
+ width: 393,
+ destroyOnClose: true,
+ })]);
+
+ (dialogService.openCalls[0] as { onClose: () => void }).onClose();
+ expect(dialogService.closeIds).toEqual(['DESKTOP_FIND_REPLACE_DIALOG', UNIVER_SHEET_PERMISSION_DIALOG_ID]);
+ });
+
+ it('opens the permission panel with rule context and resets panel state on close', async () => {
+ const injector = createOperationInjector();
+ const model = injector.get(SheetPermissionPanelModel);
+ const userManager = injector.get(SheetPermissionUserManagerService);
+ const rule = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ permissionId: 'permission-1',
+ unitType: UnitObject.SelectRange,
+ id: 'rule-1',
+ ranges: [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }],
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
+ userManager.setCanEditUserList([{ id: 'user-1', role: 1, subject: undefined }]);
+ userManager.setSelectUserList([{ id: 'user-1', role: 1, subject: undefined }]);
+
+ await expect(SheetPermissionOpenPanelOperation.handler(injector, {
+ fromSheetBar: true,
+ showDetail: false,
+ rule,
+ oldRule: rule,
+ })).resolves.toBe(true);
+
+ const sidebarService = injector.get(ISidebarService) as unknown as SidebarServiceForTest;
+ expect(model.getVisible()).toBe(true);
+ expect(sidebarService.openCalls).toEqual([expect.objectContaining({
+ header: { title: 'sheets-ui.permission.panel.title' },
+ width: 330,
+ children: {
+ label: UNIVER_SHEET_PERMISSION_PANEL,
+ showDetail: false,
+ fromSheetBar: true,
+ rule,
+ oldRule: rule,
+ },
+ })]);
+
+ (sidebarService.openCalls[0] as { onClose: () => void }).onClose();
+ expect(model.getVisible()).toBe(false);
+ expect(userManager.userList).toEqual([]);
+ expect(userManager.selectUserList).toEqual([]);
});
});
diff --git a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts
index 138487274b..d8b7cd79ad 100644
--- a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts
+++ b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts
@@ -130,6 +130,119 @@ class PasteRecorderService {
}
}
+class TestSheetClipboardService {
+ readonly showMenu$ = new Subject<boolean>();
+ readonly pasteOptionsCache$ = new Subject<unknown>();
+
+ private _showMenu = false;
+ private _pasteOptionsCache: unknown = null;
+
+ setShowMenu(show: boolean): void {
+ this._showMenu = show;
+ this.showMenu$.next(show);
+ }
+
+ getPasteMenuVisible(): boolean {
+ return this._showMenu;
+ }
+
+ getPasteOptionsCache(): unknown {
+ return this._pasteOptionsCache;
+ }
+
+ updatePasteOptionsCache(cache: unknown): void {
+ this._pasteOptionsCache = cache;
+ this.pasteOptionsCache$.next(cache);
+ }
+
+ disposePasteOptionsCache(): void {
+ this.updatePasteOptionsCache(null);
+ }
+
+ generateCopyContent(): { html: string; plain: string } {
+ return { html: '<b>a</b>', plain: 'a' };
+ }
+
+ copy(): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ cut(): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ paste(): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ pasteByCopyId(): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ legacyPaste(): Promise<boolean> {
+ return Promise.resolve(true);
+ }
+
+ rePasteWithPasteType(): boolean {
+ return true;
+ }
+
+ copyContentCache(): never {
+ throw new Error('copyContentCache is not used in this facade spec.');
+ }
+
+ addClipboardHook(): never {
+ throw new Error('addClipboardHook is not used in this facade spec.');
+ }
+
+ getClipboardHooks(): never {
+ throw new Error('getClipboardHooks is not used in this facade spec.');
+ }
+
+ removeMarkSelection(): void { }
+}
+
+class TestClipboardInterfaceService {
+ readonly supportClipboard = true;
+
+ writeText(): Promise<void> {
+ return Promise.resolve();
+ }
+
+ write(): Promise<void> {
+ return Promise.resolve();
+ }
+
+ readText(): Promise<string> {
+ return Promise.resolve('');
+ }
+
+ read(): Promise<ClipboardItem[]> {
+ return Promise.resolve([]);
+ }
+}
+
+class TestHoverManagerService {
+ readonly currentClickedCell$ = new Subject<ITestHoverCell>();
+ readonly currentRichText$ = new Subject<ITestHoverCell['location']>();
+ readonly currentPointerDownCell$ = new Subject<ITestHoverCell['location']>();
+ readonly currentPointerUpCell$ = new Subject<ITestHoverCell['location']>();
+ readonly currentCellPosWithEvent$ = new Subject<ITestHoverCell['location']>();
+ readonly currentRowHeaderClick$ = new Subject<ITestHeaderEvent>();
+ readonly currentRowHeaderPointerDown$ = new Subject<ITestHeaderEvent>();
+ readonly currentRowHeaderPointerUp$ = new Subject<ITestHeaderEvent>();
+ readonly currentHoveredRowHeader$ = new Subject<ITestHeaderEvent>();
+ readonly currentColHeaderClick$ = new Subject<ITestHeaderEvent>();
+ readonly currentColHeaderPointerDown$ = new Subject<ITestHeaderEvent>();
+ readonly currentColHeaderPointerUp$ = new Subject<ITestHeaderEvent>();
+ readonly currentHoveredColHeader$ = new Subject<ITestHeaderEvent>();
+}
+
+class TestDragManagerService {
+ readonly currentCell$ = new Subject<ITestDragCell>();
+ readonly endCell$ = new Subject<ITestDragCell>();
+}
+
const TestPasteCommand: ICommand<ISheetPasteByShortKeyParams> = {
id: SheetPasteShortKeyCommand.id,
type: CommandType.COMMAND,
@@ -165,20 +278,6 @@ const TestZoomCommand: ICommand<{ unitId: string; subUnitId: string; zoomRatio:
};
describe('Test FUniver UI mixin', () => {
- const clipboardService = {
- generateCopyContent: vi.fn(() => ({ html: '<b>a</b>', plain: 'a' })),
- };
-
- const renderPermissionService = {
- setProtectedRangeShadowStrategy: vi.fn(),
- getProtectedRangeShadowStrategy: vi.fn(() => 'always' as const),
- getProtectedRangeShadowStrategy$: vi.fn(() => ({ subscribe: vi.fn() })),
- };
-
- const clipboardInterfaceService = {
- read: vi.fn(async () => []),
- };
-
beforeEach(() => {
vi.clearAllMocks();
});
@@ -400,9 +499,9 @@ describe('Test FUniver UI mixin', () => {
it('should handle common facade methods and clipboard internals', async () => {
const testBed = createFacadeTestBed(undefined, [
- [ISheetClipboardService, { useValue: clipboardService }],
- [SheetPermissionRenderManagerService, { useValue: renderPermissionService }],
- [IClipboardInterfaceService, { useValue: clipboardInterfaceService }],
+ [ISheetClipboardService, { useClass: TestSheetClipboardService as never }],
+ [SheetPermissionRenderManagerService],
+ [IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }],
[IEditorBridgeService, { useClass: EditorBridgeService }],
[IEditorService, { useClass: EditorService }],
[DocSelectionManagerService],
@@ -430,14 +529,19 @@ describe('Test FUniver UI mixin', () => {
});
testBed.univerAPI.setProtectedRangeShadowStrategy('none');
- expect(renderPermissionService.setProtectedRangeShadowStrategy).toHaveBeenCalledWith('none');
- expect(testBed.univerAPI.getProtectedRangeShadowStrategy()).toBe('always');
- expect(testBed.univerAPI.getProtectedRangeShadowStrategy$()).toBeTruthy();
+ expect(testBed.get(SheetPermissionRenderManagerService).getProtectedRangeShadowStrategy()).toBe('none');
+ expect(testBed.univerAPI.getProtectedRangeShadowStrategy()).toBe('none');
+ const strategies: string[] = [];
+ const subscription = testBed.univerAPI.getProtectedRangeShadowStrategy$().subscribe((strategy) => {
+ strategies.push(strategy);
+ });
+ testBed.univerAPI.setProtectedRangeShadowStrategy('non-editable');
+ expect(strategies).toEqual(['none', 'non-editable']);
+ subscription.unsubscribe();
const permissionService = testBed.get(IPermissionService);
- const setShowComponentsSpy = vi.spyOn(permissionService, 'setShowComponents');
testBed.univerAPI.setPermissionDialogVisible(false);
- expect(setShowComponentsSpy).toHaveBeenCalledWith(false);
+ expect(permissionService.getShowComponents()).toBe(false);
const copyParams = univerAPI._generateClipboardCopyParam();
expect(copyParams?.text).toBe('a');
@@ -524,46 +628,9 @@ 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$,
- currentPointerDownCell$,
- currentPointerUpCell$,
- currentCellPosWithEvent$,
- currentRowHeaderClick$,
- currentRowHeaderPointerDown$,
- currentRowHeaderPointerUp$,
- currentHoveredRowHeader$,
- currentColHeaderClick$,
- currentColHeaderPointerDown$,
- currentColHeaderPointerUp$,
- currentHoveredColHeader$,
- };
-
- const dragManagerService = {
- currentCell$: currentDragCell$,
- endCell$: endDragCell$,
- };
-
const testBed = createFacadeTestBed(undefined, [
- [HoverManagerService, { useValue: hoverManagerService }],
- [DragManagerService, { useValue: dragManagerService }],
+ [HoverManagerService, { useClass: TestHoverManagerService as never }],
+ [DragManagerService, { useClass: TestDragManagerService as never }],
[IEditorBridgeService, { useClass: EditorBridgeService }],
[IEditorService, { useClass: EditorService }],
[DocSelectionManagerService],
@@ -574,6 +641,8 @@ describe('Test FUniver UI mixin', () => {
const workbook = testBed.univerAPI.getActiveWorkbook()!;
const worksheet = workbook.getActiveSheet()!;
+ const hoverManagerService = testBed.get(HoverManagerService) as unknown as TestHoverManagerService;
+ const dragManagerService = testBed.get(DragManagerService) as unknown as TestDragManagerService;
const logs: string[] = [];
const disposables = [
testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellClicked, ({ row, column }) => logs.push(`cell:${row},${column}`)),
@@ -596,28 +665,28 @@ describe('Test FUniver UI mixin', () => {
const lifecycleService = testBed.get(LifecycleService);
lifecycleService.stage = LifecycleStages.Rendered;
- currentClickedCell$.next({
+ hoverManagerService.currentClickedCell$.next({
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({
+ hoverManagerService.currentRichText$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 2, col: 3 });
+ hoverManagerService.currentPointerDownCell$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 3, col: 4 });
+ hoverManagerService.currentPointerUpCell$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 4, col: 5 });
+ hoverManagerService.currentCellPosWithEvent$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 5, col: 6 });
+ hoverManagerService.currentRowHeaderClick$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 3 });
+ hoverManagerService.currentRowHeaderPointerDown$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 4 });
+ hoverManagerService.currentRowHeaderPointerUp$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 6 });
+ hoverManagerService.currentHoveredRowHeader$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 5 });
+ hoverManagerService.currentColHeaderClick$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 4 });
+ hoverManagerService.currentColHeaderPointerDown$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 6 });
+ hoverManagerService.currentColHeaderPointerUp$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 7 });
+ hoverManagerService.currentHoveredColHeader$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 8 });
+ dragManagerService.currentCell$.next({
location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 3, col: 4 },
position: { startX: 0, startY: 0, endX: 10, endY: 10 },
dataTransfer: {} as DataTransfer,
});
- endDragCell$.next({
+ dragManagerService.endCell$.next({
location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 7, col: 8 },
position: { startX: 0, startY: 0, endX: 10, endY: 10 },
dataTransfer: {} as DataTransfer,
diff --git a/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts b/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts
index a6fc1a883a..af576056b7 100644
--- a/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts
@@ -14,10 +14,14 @@
* limitations under the License.
*/
-import type { ICommandInfo, ICommandService as ICommandServiceType, Workbook } from '@univerjs/core';
+import type { ICommandInfo, Workbook } from '@univerjs/core';
import type { Engine, IRenderContext, Scene } from '@univerjs/engine-render';
import { ICommandService, Injector, UniverInstanceType } from '@univerjs/core';
-import { MarkDirtyRowAutoHeightOperation, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';
+import {
+ CancelMarkDirtyRowAutoHeightOperation,
+ MarkDirtyRowAutoHeightOperation,
+ SetWorksheetRowAutoHeightMutation,
+} from '@univerjs/sheets';
import { BehaviorSubject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { AutoHeightService, taskRowsFromRanges } from '../auto-height.service';
@@ -49,6 +53,44 @@ function createRenderContext(unitId: string): IRenderContext<Workbook> {
};
}
+class TestSheetSkeletonManagerService {
+ static skeleton: unknown = null;
+
+ getSkeleton() {
+ return TestSheetSkeletonManagerService.skeleton;
+ }
+}
+
+class TestCommandService {
+ static executed: Array<{ id: string; params?: unknown }> = [];
+ static listeners: Array<(info: ICommandInfo) => void> = [];
+
+ syncExecuteCommand(id: string, params?: unknown) {
+ TestCommandService.executed.push({ id, params });
+ }
+
+ onCommandExecuted(cb: (info: ICommandInfo) => void) {
+ TestCommandService.listeners.push(cb);
+ return {
+ dispose: () => {
+ TestCommandService.listeners = TestCommandService.listeners.filter((listener) => listener !== cb);
+ },
+ };
+ }
+}
+
+function createAutoHeightService(skeleton: unknown, unitId = 'u-1') {
+ TestSheetSkeletonManagerService.skeleton = skeleton;
+ TestCommandService.executed = [];
+ TestCommandService.listeners = [];
+
+ const injector = new Injector();
+ injector.add([SheetSkeletonManagerService, { useClass: TestSheetSkeletonManagerService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([AutoHeightService, { useFactory: () => injector.createInstance(AutoHeightService, createRenderContext(unitId)) }]);
+ return injector.get(AutoHeightService);
+}
+
describe('taskRowsFromRanges', () => {
it('splits ranges by max rows and keeps remains', () => {
const { result, lasts } = taskRowsFromRanges(
@@ -87,17 +129,6 @@ describe('AutoHeightService', () => {
getRowHeight,
} as unknown;
- const sheetSkeletonManagerService = {
- getSkeleton: () => skeleton,
- } as unknown;
-
- const syncExecuteCommand = vi.fn();
- const onCommandExecuted = vi.fn(() => ({ dispose: () => { } }));
- const commandService = {
- syncExecuteCommand,
- onCommandExecuted,
- } as unknown;
-
// Make requestIdleCallback run "once" synchronously.
// `AutoHeightService` schedules another idle callback after processing; if we
// call callbacks immediately every time, it becomes infinite recursion.
@@ -113,11 +144,7 @@ describe('AutoHeightService', () => {
return 1;
});
- const context = createRenderContext('u-1');
- const injector = new Injector();
- injector.add([SheetSkeletonManagerService, { useValue: sheetSkeletonManagerService as unknown as SheetSkeletonManagerService }]);
- injector.add([ICommandService, { useValue: commandService as unknown as ICommandServiceType }]);
- const service = injector.createInstance(AutoHeightService, context);
+ const service = createAutoHeightService(skeleton);
service.startAutoHeightTask({
id: 't-1',
@@ -126,11 +153,14 @@ describe('AutoHeightService', () => {
});
// Only rows with changed autoHeight should be synced.
- expect(syncExecuteCommand).toHaveBeenCalledWith(SetWorksheetRowAutoHeightMutation.id, {
- unitId: 'u-1',
- subUnitId: 's-1',
- rowsAutoHeightInfo: [{ row: 0, autoHeight: 30 }],
- });
+ expect(TestCommandService.executed).toEqual([{
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ rowsAutoHeightInfo: [{ row: 0, autoHeight: 30 }],
+ },
+ }]);
// Ensures it "normalizes" ranges to column 0 in the task.
expect(calculateAutoHeightInRange).toHaveBeenCalledWith([
@@ -142,22 +172,6 @@ describe('AutoHeightService', () => {
});
it('wires command executed listener for mark-dirty mutation', () => {
- const sheetSkeletonManagerService = {
- getSkeleton: () => ({
- calculateAutoHeightInRange: () => [],
- getRowHeight: () => 10,
- }),
- } as unknown;
-
- const commandHandlers: Array<(info: ICommandInfo) => void> = [];
- const commandService = {
- syncExecuteCommand: vi.fn(),
- onCommandExecuted: (cb: (info: ICommandInfo) => void) => {
- commandHandlers.push(cb);
- return { dispose: () => { } };
- },
- } as unknown;
-
let ran = false;
const idleGlobals = globalThis as unknown as IIdleGlobals;
const requestIdleCallbackSpy = vi
@@ -170,14 +184,13 @@ describe('AutoHeightService', () => {
return 1;
});
- const context = createRenderContext('u-1');
- const injector = new Injector();
- injector.add([SheetSkeletonManagerService, { useValue: sheetSkeletonManagerService as unknown as SheetSkeletonManagerService }]);
- injector.add([ICommandService, { useValue: commandService as unknown as ICommandServiceType }]);
- const service = injector.createInstance(AutoHeightService, context);
+ const service = createAutoHeightService({
+ calculateAutoHeightInRange: () => [],
+ getRowHeight: () => 10,
+ });
- expect(commandHandlers).toHaveLength(1);
- commandHandlers[0]({
+ expect(TestCommandService.listeners).toHaveLength(1);
+ TestCommandService.listeners[0]({
id: MarkDirtyRowAutoHeightOperation.id,
params: {
unitId: 'u-1',
@@ -193,4 +206,137 @@ describe('AutoHeightService', () => {
service.dispose();
requestIdleCallbackSpy.mockRestore();
});
+
+ it('cancels queued dirty-row work through the command listener', () => {
+ const skeleton = {
+ calculateAutoHeightInRange: () => [{ row: 1, autoHeight: 24 }],
+ getRowHeight: () => 12,
+ };
+
+ const idleGlobals = globalThis as unknown as IIdleGlobals;
+ const requestIdleCallbackSpy = vi
+ .spyOn(idleGlobals, 'requestIdleCallback')
+ .mockImplementation(() => 1);
+ const service = createAutoHeightService(skeleton);
+
+ TestCommandService.listeners[0]({
+ id: MarkDirtyRowAutoHeightOperation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ ranges: [{ startRow: 1, endRow: 1, startColumn: 5, endColumn: 8 }],
+ id: 'task-to-cancel',
+ },
+ });
+ TestCommandService.listeners[0]({
+ id: CancelMarkDirtyRowAutoHeightOperation.id,
+ params: {
+ unitId: 'u-1',
+ id: 'task-to-cancel',
+ },
+ });
+
+ (service as unknown as { _calculateLoop: (deadline: IdleDeadline) => void })._calculateLoop({
+ timeRemaining: () => 100,
+ didTimeout: false,
+ } as IdleDeadline);
+
+ expect(TestCommandService.executed).toEqual([]);
+
+ service.dispose();
+ requestIdleCallbackSpy.mockRestore();
+ });
+
+ it('keeps large auto-height work in batches and skips already queued ranges', () => {
+ const calculatedRanges: unknown[] = [];
+ const skeleton = {
+ calculateAutoHeightInRange: (ranges: unknown[]) => {
+ calculatedRanges.push(ranges);
+ return [{ row: 0, autoHeight: 24 }];
+ },
+ getRowHeight: () => 12,
+ };
+
+ let callbacks = 0;
+ let timeRemainingCalls = 0;
+ const idleGlobals = globalThis as unknown as IIdleGlobals;
+ const requestIdleCallbackSpy = vi
+ .spyOn(idleGlobals, 'requestIdleCallback')
+ .mockImplementation((cb) => {
+ callbacks++;
+ if (callbacks === 1) {
+ cb({
+ timeRemaining: () => {
+ timeRemainingCalls++;
+ return timeRemainingCalls === 1 ? 100 : 0;
+ },
+ didTimeout: false,
+ } as IdleDeadline);
+ }
+ return callbacks;
+ });
+ const service = createAutoHeightService(skeleton);
+
+ service.startAutoHeightTask({
+ id: 'large',
+ sheetId: 's-1',
+ ranges: [{ startRow: 0, endRow: 600, startColumn: 2, endColumn: 4 }],
+ });
+ service.startAutoHeightTask({
+ id: 'already-queued',
+ sheetId: 's-1',
+ ranges: [{ startRow: 500, endRow: 600, startColumn: 9, endColumn: 9 }],
+ });
+
+ expect(calculatedRanges[0]).toEqual([{ startRow: 0, endRow: 499, startColumn: 0, endColumn: 0 }]);
+ expect(TestCommandService.executed).toEqual([{
+ id: SetWorksheetRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ rowsAutoHeightInfo: [{ row: 0, autoHeight: 24 }],
+ },
+ }]);
+
+ service.dispose();
+ requestIdleCallbackSpy.mockRestore();
+ });
+
+ it('calculates the full remaining range after task timeout', () => {
+ const calculatedRanges: unknown[] = [];
+ const skeleton = {
+ calculateAutoHeightInRange: (ranges: unknown[]) => {
+ calculatedRanges.push(ranges);
+ return [];
+ },
+ getRowHeight: () => 12,
+ };
+
+ const dateNowSpy = vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValue(20_000);
+ let ran = false;
+ const idleGlobals = globalThis as unknown as IIdleGlobals;
+ const requestIdleCallbackSpy = vi
+ .spyOn(idleGlobals, 'requestIdleCallback')
+ .mockImplementation((cb) => {
+ if (!ran) {
+ ran = true;
+ cb({ timeRemaining: () => 100, didTimeout: false } as IdleDeadline);
+ }
+ return 1;
+ });
+ const service = createAutoHeightService(skeleton);
+
+ service.startAutoHeightTask({
+ id: 'expired',
+ sheetId: 's-1',
+ maxTime: 1,
+ ranges: [{ startRow: 0, endRow: 600, startColumn: 1, endColumn: 1 }],
+ });
+
+ expect(calculatedRanges[0]).toEqual([{ startRow: 0, endRow: 600, startColumn: 0, endColumn: 0 }]);
+
+ service.dispose();
+ requestIdleCallbackSpy.mockRestore();
+ dateNowSpy.mockRestore();
+ });
});
diff --git a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts
index fee8650eab..8e3e020768 100644
--- a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts
@@ -14,32 +14,157 @@
* limitations under the License.
*/
+import type { ICommandInfo, IRange } from '@univerjs/core';
+import type { IPopup } from '@univerjs/ui';
+import { ICommandService, Injector, IUniverInstanceService } from '@univerjs/core';
+import { IRenderManagerService, RENDER_CLASS_TYPE } from '@univerjs/engine-render';
+import {
+ IRefSelectionsService,
+ RefRangeService,
+ SetFrozenMutation,
+ SetWorksheetRowAutoHeightMutation,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
+import { ICanvasPopupService } from '@univerjs/ui';
import { BehaviorSubject, Subject } from 'rxjs';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import * as commonUtils from '../../common/utils';
+import { describe, expect, it, vi } from 'vitest';
+import { SetScrollOperation } from '../../commands/operations/scroll.operation';
import { SheetCanvasPopManagerService } from '../canvas-pop-manager.service';
+import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
function createEventSubject<T>() {
const listeners = new Set<(event: T) => void>();
return {
- subscribeEvent(cb: (event: T) => void) {
- listeners.add(cb);
+ subscribeEvent(listener: (event: T) => void) {
+ listeners.add(listener);
return {
- dispose() {
- listeners.delete(cb);
- },
- unsubscribe() {
- listeners.delete(cb);
- },
+ dispose: () => listeners.delete(listener),
+ unsubscribe: () => listeners.delete(listener),
};
},
emit(event: T) {
- listeners.forEach((cb) => cb(event));
+ for (const listener of listeners) {
+ listener(event);
+ }
},
};
}
-function createService() {
+class TestCanvasPopupService {
+ activePopupId = '';
+ readonly popups = new Map<string, IPopup>();
+ readonly removedIds: string[] = [];
+ private _nextId = 1;
+
+ addPopup(popup: IPopup) {
+ const id = `popup-${this._nextId}`;
+ this._nextId++;
+ this.activePopupId = id;
+ this.popups.set(id, popup);
+ return id;
+ }
+
+ removePopup(id: string) {
+ this.removedIds.push(id);
+ this.popups.delete(id);
+ if (this.activePopupId === id) {
+ this.activePopupId = '';
+ }
+ }
+
+ lastPopup() {
+ const values = Array.from(this.popups.values());
+ return values[values.length - 1];
+ }
+}
+
+class TestCommandService {
+ private readonly _listeners: Array<(info: ICommandInfo) => void> = [];
+
+ onCommandExecuted(listener: (info: ICommandInfo) => void) {
+ this._listeners.push(listener);
+ return {
+ dispose: () => {
+ const index = this._listeners.indexOf(listener);
+ if (index > -1) {
+ this._listeners.splice(index, 1);
+ }
+ },
+ };
+ }
+
+ emit(id: string, params?: ICommandInfo['params']) {
+ for (const listener of this._listeners) {
+ listener({ id, params });
+ }
+ }
+}
+
+class TestUniverInstanceService {
+ workbook: any;
+
+ getCurrentUnitOfType() {
+ return this.workbook;
+ }
+
+ getUnit(unitId: string) {
+ return this.workbook?.getUnitId() === unitId ? this.workbook : null;
+ }
+}
+
+class TestRenderManagerService {
+ render: any;
+
+ getRenderById() {
+ return this.render;
+ }
+}
+
+class TestRefRangeService {
+ readonly watchedRanges: Array<{
+ unitId: string;
+ subUnitId: string;
+ range: IRange;
+ callback: (before: IRange, after: IRange | null) => void;
+ disposed: boolean;
+ }> = [];
+
+ watchRange(unitId: string, subUnitId: string, range: IRange, callback: (before: IRange, after: IRange | null) => void) {
+ const record = { unitId, subUnitId, range, callback, disposed: false };
+ this.watchedRanges.push(record);
+ return {
+ dispose: () => {
+ record.disposed = true;
+ },
+ };
+ }
+}
+
+class TestSelectionMovingService {
+ readonly selectionMoving$ = new Subject<void>();
+ readonly selectionMoveEnd$ = new Subject<void>();
+}
+
+function createWorkbook(worksheet: any) {
+ return {
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: (sheetId: string) => sheetId === worksheet.getSheetId() ? worksheet : null,
+ };
+}
+
+function createSheetHarness() {
+ 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([RefRangeService, { useClass: TestRefRangeService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IRefSelectionsService, { useClass: TestSelectionMovingService as never }]);
+ injector.add([SheetsSelectionsService, { useClass: TestSelectionMovingService as never }]);
+ injector.add([SheetCanvasPopManagerService]);
+
const canvas = document.createElement('canvas');
canvas.style.width = '100px';
vi.spyOn(canvas, 'getBoundingClientRect').mockReturnValue({
@@ -54,22 +179,24 @@ function createService() {
toJSON: () => ({}),
} as DOMRect);
- const commandListeners: Array<(info: { id: string; params?: any }) => void> = [];
- const onTransformChange$ = createEventSubject<unknown>();
+ const transformChange$ = createEventSubject<unknown>();
+ const clientRect$ = new BehaviorSubject({});
const worksheet = {
getSheetId: () => 'sheet-1',
getFreeze: () => ({ startRow: 1, startColumn: 1, xSplit: 0, ySplit: 0 }),
};
- const workbook = {
- getUnitId: () => 'unit-1',
- getActiveSheet: () => worksheet,
- getSheetBySheetId: () => worksheet,
- };
+ const workbook = createWorkbook(worksheet);
const skeleton = {
rowHeightAccumulation: [20, 40, 60],
columnWidthAccumulation: [30, 60, 90],
rowHeaderWidth: 20,
columnHeaderHeight: 20,
+ getNoMergeCellWithCoordByIndex: (row: number, col: number) => ({
+ startX: col * 30,
+ endX: col * 30 + 30,
+ startY: row * 20,
+ endY: row * 20 + 20,
+ }),
getCellWithCoordByIndex: (row: number, col: number) => ({
startX: col * 30,
endX: col * 30 + 30,
@@ -84,160 +211,270 @@ function createService() {
},
}),
};
- const viewport = { viewportScrollX: 0, viewportScrollY: 0 };
- const currentRender = {
+ const sheetSelectionRenderService = { selectionMoving: false };
+ const render = {
scene: {
getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),
+ getViewport: () => ({
+ left: 0,
+ top: 0,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ }),
},
engine: {
- clientRect$: new BehaviorSubject({}),
- onTransformChange$,
+ clientRect$,
+ onTransformChange$: transformChange$,
getCanvasElement: () => canvas,
},
- with(_token: unknown) {
- return {
- ensureSkeleton: () => skeleton,
- getOrCreateSkeleton: () => skeleton,
- getSkeletonParam: () => ({ skeleton }),
- selectionMoving: false,
- };
+ with(token: unknown) {
+ if (token === SheetSkeletonManagerService) {
+ return {
+ ensureSkeleton: () => skeleton,
+ getOrCreateSkeleton: () => skeleton,
+ getSkeletonParam: () => ({ skeleton }),
+ };
+ }
+ if (token === ISheetSelectionRenderService) {
+ return sheetSelectionRenderService;
+ }
+ throw new Error(`Unexpected render dependency: ${String(token)}`);
},
};
- const popupService = {
- activePopupId: 'active',
- addPopup: vi.fn(() => 'popup-1'),
- removePopup: vi.fn(),
- };
-
- const service = new SheetCanvasPopManagerService(
- popupService as any,
- { getRenderById: () => currentRender } as any,
- {
- getCurrentUnitOfType: () => workbook,
- getUnit: () => workbook,
- } as any,
- {
- watchRange: vi.fn((_unitId: string, _subUnitId: string, _range: any, _cb: any) => ({
- dispose: vi.fn(),
- })),
- } as any,
- {
- onCommandExecuted: (cb: (info: { id: string; params?: any }) => void) => {
- commandListeners.push(cb);
- return { dispose: vi.fn() };
- },
- emit(id: string, params?: any) {
- commandListeners.forEach((cb) => cb({ id, params }));
- },
- } as any,
- {
- selectionMoving$: new Subject<void>(),
- selectionMoveEnd$: new Subject<void>(),
- } as any,
- {
- selectionMoving$: new Subject<void>(),
- selectionMoveEnd$: new Subject<void>(),
- } as any
- );
+ const univerInstanceService = injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService;
+ const renderManagerService = injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ univerInstanceService.workbook = workbook;
+ renderManagerService.render = render;
return {
- service,
- popupService,
- currentRender,
+ service: injector.get(SheetCanvasPopManagerService),
+ popupService: injector.get(ICanvasPopupService) as unknown as TestCanvasPopupService,
+ commandService: injector.get(ICommandService) as unknown as TestCommandService,
+ refRangeService: injector.get(RefRangeService) as unknown as TestRefRangeService,
+ refSelectionService: injector.get(IRefSelectionsService) as unknown as TestSelectionMovingService,
+ sheetSelectionService: injector.get(SheetsSelectionsService) as unknown as TestSelectionMovingService,
+ univerInstanceService,
+ renderManagerService,
workbook,
worksheet,
skeleton,
- viewport,
+ render,
+ canvas,
+ clientRect$,
+ transformChange$,
+ sheetSelectionRenderService,
+ viewport: { viewportScrollX: 0, viewportScrollY: 0 },
};
}
describe('SheetCanvasPopManagerService', () => {
- beforeEach(() => {
- vi.spyOn(commonUtils, 'getViewportByCell').mockReturnValue({ viewportScrollX: 0, viewportScrollY: 0 } as any);
- });
+ it('resolves registered feature menus for the drawing that opened the menu', () => {
+ const { service } = createSheetHarness();
+ const callback = vi.fn((unitId: string, subUnitId: string, drawingId: string, drawingType: unknown) => [{
+ label: `${unitId}/${subUnitId}/${drawingId}/${drawingType}`,
+ index: 0,
+ commandId: 'open',
+ commandParams: { drawingId },
+ disable: false,
+ }]);
+
+ service.registerFeatureMenu('image' as never, callback);
+
+ expect(service.getFeatureMenu('unit-1', 'sheet-1', 'drawing-1', 'image' as never)).toEqual([
+ { label: 'unit-1/sheet-1/drawing-1/image', index: 0, commandId: 'open', commandParams: { drawingId: 'drawing-1' }, disable: false },
+ ]);
+ expect(service.getFeatureMenu('unit-1', 'sheet-1', 'drawing-1', 'chart' as never)).toBeUndefined();
- afterEach(() => {
- vi.restoreAllMocks();
+ service.dispose();
+ expect(service.getFeatureMenu('unit-1', 'sheet-1', 'drawing-1', 'image' as never)).toBeUndefined();
});
- it('registers and resolves feature menus', () => {
- const { service } = createService();
- const callback = vi.fn(() => [{ label: 'menu', index: 0, commandId: 'cmd', commandParams: {}, disable: false }]);
+ it('anchors a drawing popup with the registered menu offset and removes it when closed', () => {
+ const { service, popupService, canvas } = createSheetHarness();
+ const targetObject = {
+ left: 20,
+ top: 10,
+ width: 40,
+ height: 30,
+ classType: RENDER_CLASS_TYPE.SHAPE,
+ getPropByKey: () => 'image',
+ };
- service.registerFeatureMenu('image' as any, callback);
- service.registerFeatureMenuOffset('image' as any, 12, 8);
+ service.registerFeatureMenuOffset('image' as never, 12, 8);
+ const disposable = service.attachPopupToObject(targetObject as never, { componentKey: 'drawing-toolbar' } as never);
- expect(service.getFeatureMenu('u', 's', 'd', 'image' as any)).toEqual([
- { label: 'menu', index: 0, commandId: 'cmd', commandParams: {}, disable: false },
- ]);
- expect(service.getFeatureMenu('u', 's', 'd', 'chart' as any)).toBeUndefined();
- });
+ expect(popupService.lastPopup()).toMatchObject({
+ componentKey: 'drawing-toolbar',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ canvasElement: canvas,
+ anchorRect: { left: 50, right: 154, top: 56, bottom: 100 },
+ });
+ expect(disposable.canDispose()).toBe(false);
- it('attaches popup to absolute position and disposes correctly', () => {
- const { service, popupService } = createService();
+ disposable.dispose();
+ expect(popupService.removedIds).toEqual(['popup-1']);
+ expect(popupService.popups.size).toBe(0);
+ });
+ it('keeps absolute-position popups hidden while a selection is being dragged unless the popup opts in', () => {
+ const { service, popupService, refSelectionService, sheetSelectionService } = createSheetHarness();
const bound = { top: 10, left: 20, right: 30, bottom: 40 };
- const disposable = service.attachPopupToAbsolutePosition(bound, { componentKey: 'comp' } as any, 'unit-1', 'sheet-1');
- expect(disposable).not.toBeNull();
- expect(popupService.addPopup).toHaveBeenCalled();
- expect(disposable?.canDispose()).toBe(true);
+
+ refSelectionService.selectionMoving$.next();
+ expect(service.attachPopupToAbsolutePosition(bound, { componentKey: 'tooltip' } as never, 'unit-1', 'sheet-1')).toBeUndefined();
+ refSelectionService.selectionMoveEnd$.next();
+
+ sheetSelectionService.selectionMoving$.next();
+ expect(service.attachPopupToAbsolutePosition(bound, { componentKey: 'sheet-tooltip' } as never, 'unit-1', 'sheet-1')).toBeUndefined();
+ sheetSelectionService.selectionMoveEnd$.next();
+
+ const disposable = service.attachPopupToAbsolutePosition(
+ bound,
+ { componentKey: 'drag-tooltip', showOnSelectionMoving: true } as never,
+ 'unit-1',
+ 'sheet-1'
+ );
+
+ expect(popupService.lastPopup()).toMatchObject({
+ componentKey: 'drag-tooltip',
+ anchorRect: bound,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ });
+ expect(disposable?.canDispose()).toBe(false);
disposable?.dispose();
- expect(popupService.removePopup).toHaveBeenCalledWith('popup-1');
+ expect(popupService.removedIds).toEqual(['popup-1']);
+ });
+
+ it('anchors a popup to a sheet position and refreshes its hidden freeze area on viewport changes', () => {
+ const { service, popupService, commandService, transformChange$ } = createSheetHarness();
+
+ const disposable = service.attachPopupByPosition(
+ { left: 20, top: 10, right: 30, bottom: 40 },
+ { componentKey: 'position-menu' } as never,
+ { unitId: 'unit-1', subUnitId: 'sheet-1', row: 1, col: 1 }
+ );
+ const popup = popupService.lastPopup()!;
+ const hiddenRects: unknown[] = [];
+ popup.hiddenRects$!.subscribe((rects) => hiddenRects.push(rects));
+
+ expect(popup).toMatchObject({
+ componentKey: 'position-menu',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ anchorRect: { left: 50, right: 70, top: 40, bottom: 100 },
+ });
+
+ commandService.emit(SetFrozenMutation.id);
+ transformChange$.emit({});
+ expect(hiddenRects[hiddenRects.length - 1]).toEqual([
+ { left: -Infinity, top: -Infinity, right: 50, bottom: 20 },
+ { left: 50, top: -Infinity, right: Infinity, bottom: 20 },
+ { left: -Infinity, top: 20, right: 50, bottom: Infinity },
+ ]);
- expect(service.attachPopupToAbsolutePosition(bound, { componentKey: 'comp' } as any, 'other', 'sheet-1')).toBeNull();
+ disposable?.dispose();
+ expect(popupService.removedIds).toEqual(['popup-1']);
});
- it('attaches popup to cell and range with watchers', () => {
- const { service, popupService } = createService();
+ it('moves a cell popup when its watched range is remapped and removes it when the cell disappears', () => {
+ const { service, popupService, refRangeService, viewport } = createSheetHarness();
+
+ const disposable = service.attachPopupToCell(1, 1, { componentKey: 'cell-action' } as never, 'unit-1', 'sheet-1', viewport as never);
+ const popup = popupService.lastPopup()!;
+ const positions: unknown[] = [];
+ popup.anchorRect$!.subscribe((position) => positions.push(position));
- const cellPopup = service.attachPopupToCell(1, 1, { componentKey: 'comp' } as any);
- expect(cellPopup).not.toBeNull();
- expect(popupService.addPopup).toHaveBeenCalled();
- expect(cellPopup?.canDispose()).toBe(true);
- cellPopup?.dispose();
+ expect(popup.anchorRect).toEqual({ left: 70, right: 130, top: 60, bottom: 100 });
+ expect(refRangeService.watchedRanges[0]).toMatchObject({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ });
+
+ refRangeService.watchedRanges[0].callback(
+ { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 }
+ );
+ expect(positions[positions.length - 1]).toEqual({ left: 130, right: 190, top: 100, bottom: 140 });
- const rangePopup = service.attachRangePopup(
- { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } as any,
- { componentKey: 'comp' } as any
+ refRangeService.watchedRanges[0].callback(
+ { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 },
+ null
);
- expect(rangePopup).not.toBeNull();
- rangePopup?.dispose();
- expect(popupService.removePopup).toHaveBeenCalled();
+ expect(popupService.removedIds).toEqual(['popup-1']);
+ expect(refRangeService.watchedRanges[0].disposed).toBe(true);
+ expect(disposable?.canDispose()).toBe(true);
});
- it('calculates cell position and handles disposed skeleton/scene', () => {
- const { service, currentRender, skeleton, viewport } = createService();
+ it('updates cell and range anchors when sheet geometry changes', () => {
+ const { service, popupService, commandService, clientRect$, transformChange$, refRangeService, viewport } = createSheetHarness();
- const calc = (service as any)._calcCellPositionByCell.bind(service);
- const normal = calc(1, 1, currentRender, skeleton, viewport);
- expect(normal.left).toBeGreaterThan(0);
- expect(normal.bottom).toBeGreaterThan(normal.top);
+ service.attachPopupToCell(1, 1, { componentKey: 'cell-action' } as never, 'unit-1', 'sheet-1', viewport as never);
+ const cellPopup = popupService.lastPopup()!;
+ const cellPositions: unknown[] = [];
+ cellPopup.anchorRect$!.subscribe((position) => cellPositions.push(position));
- const disposedSkeleton = { ...skeleton, _disposed: true };
- const disposedSceneRender = {
- ...currentRender,
- scene: {
- ...currentRender.scene,
- _disposed: true,
- },
- };
- expect(calc(1, 1, disposedSceneRender, disposedSkeleton, viewport)).toEqual({
- left: 0,
- right: 0,
- top: 0,
- bottom: 0,
- });
+ clientRect$.next({ width: 300 });
+ commandService.emit(SetWorksheetRowAutoHeightMutation.id, { rowsAutoHeightInfo: [{ row: 1 }] });
+ transformChange$.emit({});
+ expect(cellPositions).toContainEqual({ left: 70, right: 130, top: 60, bottom: 100 });
+
+ service.attachRangePopup(
+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ { componentKey: 'range-toolbar' } as never,
+ 'unit-1',
+ 'sheet-1',
+ viewport as never
+ );
+ const rangePopup = popupService.lastPopup()!;
+ const rangePositions: unknown[] = [];
+ rangePopup.anchorRect$!.subscribe((position) => rangePositions.push(position));
+
+ commandService.emit(SetScrollOperation.id);
+ commandService.emit(SetFrozenMutation.id);
+ expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 10, right: 130, top: 20, bottom: 100 });
+
+ const rangeWatch = refRangeService.watchedRanges[1];
+ rangeWatch.callback(
+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }
+ );
+ expect(rangePositions[rangePositions.length - 1]).toEqual({ left: 70, right: 190, top: 60, bottom: 140 });
+
+ rangeWatch.callback(
+ { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 },
+ null
+ );
+ expect(popupService.removedIds).toContain('popup-2');
});
- it('returns null for missing workbook/sheet in attachPopupToCell', () => {
- const { service } = createService();
- const mock = service as any;
- mock._univerInstanceService.getUnit = () => null;
- expect(service.attachPopupToCell(0, 0, { componentKey: 'comp' } as any, 'unit-x', 'sheet-1')).toBeNull();
+ it('does not open popups for a different sheet location or unavailable workbook data', () => {
+ const { service, popupService, univerInstanceService, renderManagerService } = createSheetHarness();
+ const bound = { top: 10, left: 20, right: 30, bottom: 40 };
+
+ expect(service.attachPopupByPosition(bound, { componentKey: 'mismatch' } as never, {
+ unitId: 'unit-2',
+ subUnitId: 'sheet-1',
+ row: 0,
+ col: 0,
+ })).toBeNull();
+
+ expect(service.attachPopupToAbsolutePosition(bound, { componentKey: 'mismatch' } as never, 'unit-2', 'sheet-1')).toBeNull();
+
+ univerInstanceService.workbook = null;
+ expect(service.attachPopupToCell(0, 0, { componentKey: 'missing-workbook' } as never, 'unit-1', 'sheet-1')).toBeNull();
+
+ univerInstanceService.workbook = createWorkbook({ getSheetId: () => 'sheet-2', getFreeze: () => ({ startRow: 0, startColumn: 0, xSplit: 0, ySplit: 0 }) });
+ expect(service.attachPopupToCell(0, 0, { componentKey: 'missing-sheet' } as never, 'unit-1', 'sheet-1')).toBeNull();
+
+ univerInstanceService.workbook = createWorkbook({ getSheetId: () => 'sheet-1', getFreeze: () => ({ startRow: 0, startColumn: 0, xSplit: 0, ySplit: 0 }) });
+ renderManagerService.render = null;
+ expect(service.attachPopupToCell(0, 0, { componentKey: 'missing-render' } as never, 'unit-1', 'sheet-1')).toBeNull();
- mock._univerInstanceService.getUnit = () => ({ getSheetBySheetId: () => null });
- expect(service.attachPopupToCell(0, 0, { componentKey: 'comp' } as any, 'unit-x', 'sheet-1')).toBeNull();
+ expect(popupService.popups.size).toBe(0);
});
});
diff --git a/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts b/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts
index e6a58f2bff..6cd6f11285 100644
--- a/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/editor-bridge.service.spec.ts
@@ -14,11 +14,19 @@
* limitations under the License.
*/
-import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';
-import { DeviceInputEventType } from '@univerjs/engine-render';
+import {
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ IContextService,
+ Injector,
+ IUniverInstanceService,
+ ThemeService,
+} from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
+import { SheetInterceptorService, SheetSkeletonService } from '@univerjs/sheets';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
-import { EditorBridgeService } from '../editor-bridge.service';
+import { EditorBridgeService, IEditorBridgeService } from '../editor-bridge.service';
function createService(options?: { hasFocusEditor?: boolean }) {
const unitDisposed$ = new Subject<any>();
@@ -55,15 +63,46 @@ function createService(options?: { hasFocusEditor?: boolean }) {
},
};
- const service = new EditorBridgeService(
- mocks.sheetInterceptorService as any,
- mocks.sheetSkeletonService as any,
- mocks.renderManagerService as any,
- mocks.themeService as any,
- mocks.univerInstanceService as any,
- mocks.editorService as any,
- mocks.contextService as any
- );
+ class TestSheetInterceptorService {
+ writeCellInterceptor = mocks.sheetInterceptorService.writeCellInterceptor;
+ }
+
+ class TestSheetSkeletonService {
+ getSkeleton = mocks.sheetSkeletonService.getSkeleton;
+ }
+
+ class TestRenderManagerService {
+ getRenderUnitById = mocks.renderManagerService.getRenderUnitById;
+ }
+
+ class TestThemeService {
+ getColorFromTheme = mocks.themeService.getColorFromTheme;
+ }
+
+ class TestUniverInstanceService {
+ getTypeOfUnitDisposed$ = mocks.univerInstanceService.getTypeOfUnitDisposed$;
+ getCurrentUnitOfType = mocks.univerInstanceService.getCurrentUnitOfType;
+ }
+
+ class TestEditorService {
+ getFocusEditor = mocks.editorService.getFocusEditor;
+ focus = mocks.editorService.focus;
+ }
+
+ class TestContextService {
+ setContextValue = mocks.contextService.setContextValue;
+ }
+
+ const injector = new Injector();
+ injector.add([SheetInterceptorService, { useClass: TestSheetInterceptorService as never }]);
+ injector.add([SheetSkeletonService, { useClass: TestSheetSkeletonService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([ThemeService, { useClass: TestThemeService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ injector.add([IContextService, { useClass: TestContextService as never }]);
+ injector.add([IEditorBridgeService, { useClass: EditorBridgeService }]);
+ const service = injector.get(IEditorBridgeService) as EditorBridgeService;
return { service, mocks };
}
@@ -110,6 +149,21 @@ function createEditCellParam() {
} as any;
}
+function createPositionedEditCellParam() {
+ return {
+ ...createEditCellParam(),
+ scene: {
+ getAncestorScale: () => ({ scaleX: 2, scaleY: 1.5 }),
+ getViewportScrollXY: () => ({ x: 5, y: 10 }),
+ },
+ engine: {
+ getCanvasElement: () => ({
+ getBoundingClientRect: () => ({ left: 12, top: 18 }),
+ }),
+ },
+ } as any;
+}
+
describe('EditorBridgeService', () => {
it('syncs edit state/layout from latest state and reacts to disposed unit', () => {
const { service, mocks } = createService();
@@ -204,4 +258,63 @@ describe('EditorBridgeService', () => {
expect(getLatestSpy).toHaveBeenCalled();
expect(mocks.editorService.focus).not.toHaveBeenCalled();
});
+
+ it('builds the edit cell state from workbook, skeleton, render and intercepted cell data', () => {
+ const { service, mocks } = createService();
+ const body: any = {
+ dataStream: '=SUM(A1:A2)\r\n',
+ textRuns: [],
+ };
+ const documentModel = {
+ documentStyle: {
+ renderConfig: {},
+ },
+ getBody: () => body,
+ setZoomRatio: vi.fn(),
+ };
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellRaw: vi.fn(() => ({ v: '=SUM(A1:A2)' })),
+ getCell: vi.fn(() => ({ isInArrayFormulaRange: true })),
+ getCellDocumentModelWithFormula: vi.fn(() => ({ documentModel })),
+ getBlankCellDocumentModel: vi.fn(() => ({ documentModel })),
+ };
+ mocks.univerInstanceService.getCurrentUnitOfType.mockReturnValue({
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => worksheet,
+ } as never);
+ mocks.sheetSkeletonService.getSkeleton.mockReturnValue({
+ getNoMergeCellWithCoordByIndex: (row: number, column: number) => ({
+ startX: column * 100,
+ startY: row * 20,
+ endX: column * 100 + 100,
+ endY: row * 20 + 20,
+ }),
+ } as never);
+ mocks.renderManagerService.getRenderUnitById.mockReturnValue({
+ with: () => ({
+ getViewPort: () => ({ viewportKey: 'main' }),
+ }),
+ } as never);
+
+ service.setEditCell(createPositionedEditCellParam());
+
+ expect(service.getEditLocation()).toEqual(expect.objectContaining({
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ row: 1,
+ column: 2,
+ editorUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ }));
+ expect(service.getEditCellLayout()).toEqual(expect.objectContaining({
+ scaleX: 2,
+ scaleY: 1.5,
+ canvasOffset: { left: 12, top: 18 },
+ }));
+ expect(documentModel.setZoomRatio).toHaveBeenCalledWith(2);
+ expect(body.textRuns[0].ts.cl.rgb).toBe('#d0d0d0');
+
+ service.refreshEditCellPosition(true);
+ expect(service.getEditCellLayout()?.position.startX).toBeGreaterThan(0);
+ });
});
diff --git a/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts
index b68d697d5c..e4628f18d1 100644
--- a/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts
@@ -14,15 +14,49 @@
* limitations under the License.
*/
-import type { IUniverInstanceService } from '@univerjs/core';
-import type { IRenderManagerService } from '@univerjs/engine-render';
-import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { Injector, IUniverInstanceService } from '@univerjs/core';
+import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
import { BehaviorSubject, Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
import { HoverManagerService } from '../hover-manager.service';
import { SheetScrollManagerService } from '../scroll-manager.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+class TestUniverInstanceService {
+ static service: Partial<IUniverInstanceService>;
+
+ getUnit(...args: Parameters<IUniverInstanceService['getUnit']>) {
+ return TestUniverInstanceService.service.getUnit!(...args);
+ }
+
+ getCurrentTypeOfUnit$(...args: Parameters<IUniverInstanceService['getCurrentTypeOfUnit$']>) {
+ return TestUniverInstanceService.service.getCurrentTypeOfUnit$!(...args);
+ }
+
+ get unitDisposed$() {
+ return TestUniverInstanceService.service.unitDisposed$!;
+ }
+}
+
+class TestRenderManagerService {
+ static service: Partial<IRenderManagerService>;
+
+ getRenderById(...args: Parameters<IRenderManagerService['getRenderById']>) {
+ return TestRenderManagerService.service.getRenderById!(...args);
+ }
+}
+
+function createHoverManagerService(univerInstanceService: Partial<IUniverInstanceService>, renderManagerService: Partial<IRenderManagerService>) {
+ TestUniverInstanceService.service = univerInstanceService;
+ TestRenderManagerService.service = renderManagerService;
+
+ const injector = new Injector();
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([HoverManagerService]);
+ return injector.get(HoverManagerService);
+}
+
describe('HoverManagerService', () => {
it('emits row/col header hover and click positions based on active viewport', () => {
const workbook = {
@@ -84,7 +118,7 @@ describe('HoverManagerService', () => {
getRenderById: () => render as any,
};
- const service = new HoverManagerService(univerInstanceService as IUniverInstanceService, renderManagerService as IRenderManagerService);
+ const service = createHoverManagerService(univerInstanceService, renderManagerService);
let hoveredRow: any = null;
service.currentHoveredRowHeader$.subscribe((v) => {
@@ -210,7 +244,14 @@ describe('HoverManagerService', () => {
getRenderById: () => render as any,
};
- const service = new HoverManagerService(univerInstanceService as IUniverInstanceService, renderManagerService as IRenderManagerService);
+ const service = createHoverManagerService(univerInstanceService, renderManagerService);
+
+ const currentCells: any[] = [];
+ service.currentCell$.subscribe((v) => currentCells.push(v));
+ const richTextNoDistinct: any[] = [];
+ service.currentRichTextNoDistinct$.subscribe((v) => richTextNoDistinct.push(v));
+ const richTextDistinct: any[] = [];
+ service.currentRichText$.subscribe((v) => richTextDistinct.push(v));
let currentCellWithEvent: any = null;
service.currentCellPosWithEvent$.subscribe((v) => {
@@ -245,6 +286,7 @@ describe('HoverManagerService', () => {
service.triggerPointerUp('u-1', event);
service.triggerClick('u-1', 150, 30);
service.triggerDbClick('u-1', 150, 30);
+ service.triggerMouseMove('u-1', event);
expect(currentCellWithEvent).toEqual(
expect.objectContaining({
@@ -255,6 +297,9 @@ describe('HoverManagerService', () => {
event,
})
);
+ expect(currentCells.at(-1)).toEqual(expect.objectContaining({ location: expect.objectContaining({ row: 1, col: 1 }) }));
+ expect(richTextNoDistinct.at(-1)).toEqual(expect.objectContaining({ unitId: 'u-1', row: 1, col: 1 }));
+ expect(richTextDistinct.at(-1)).toEqual(expect.objectContaining({ unitId: 'u-1', row: 1, col: 1 }));
expect(pointerDowns.at(-1)).toEqual(expect.objectContaining({ unitId: 'u-1', row: 1, col: 1 }));
expect(pointerUps.at(-1)).toEqual(expect.objectContaining({ unitId: 'u-1', row: 1, col: 1 }));
expect(clicks.at(-1)).toEqual(expect.objectContaining({ location: expect.objectContaining({ row: 1, col: 1 }) }));
@@ -281,6 +326,10 @@ describe('HoverManagerService', () => {
});
expect(currentPos).toBeNull();
+ currentSheet$.next(null);
+ unitDisposed$.next(workbook);
+ expect(currentCells.at(-1)).toBeNull();
+
service.dispose();
});
});
diff --git a/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts b/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts
index 6490ffe5b7..c9c3af1854 100644
--- a/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts
@@ -28,9 +28,15 @@ describe('SheetPrintInterceptorService', () => {
});
it('maps runtime components to printable component implementations', () => {
+ const interceptPoints = service.interceptor.getInterceptPoints();
+ const domCollection = { dispose: () => {} };
+
service.registerPrintComponent('sheet-chart', 'print-sheet-chart');
expect(service.getPrintComponent('sheet-chart')).toBe('print-sheet-chart');
expect(service.getPrintComponent('unknown-component')).toBeUndefined();
+ expect(service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_RANGE)({ startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 }, { unitId: 'u-1', subUnitId: 's-1' })).toEqual({ startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 });
+ expect(service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_COMPONENT_COLLECT)(undefined, {} as never)).toBeUndefined();
+ expect(service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_DOM_COLLECT)(domCollection as never, {} as never)).toBe(domCollection);
});
});
diff --git a/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts b/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts
index 4f0e986e57..71057cbbe2 100644
--- a/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts
@@ -14,18 +14,122 @@
* limitations under the License.
*/
-import { ICommandService, Injector } from '@univerjs/core';
+import type { IRange } from '@univerjs/core';
+import { ICommandService, Injector, LocaleService } from '@univerjs/core';
+import {
+ AddWorksheetMergeCommand,
+ ClearSelectionAllCommand,
+ ClearSelectionContentCommand,
+ ClearSelectionFormatCommand,
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveUpCommand,
+ InsertColCommand,
+ InsertRangeMoveDownCommand,
+ InsertRangeMoveRightCommand,
+ InsertRowCommand,
+ RemoveColCommand,
+ RemoveRowCommand,
+ RemoveWorksheetMergeCommand,
+ SetBorderCommand,
+ SetColWidthCommand,
+ SetRowHeightCommand,
+ SetStyleCommand,
+ SheetPermissionCheckController,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
import { beforeEach, describe, expect, it } from 'vitest';
+import { RepeatLastActionCommand } from '../../commands/commands/repeat-last-action.command';
import { IRepeatLastActionService, RepeatLastActionPermission, RepeatLastActionService } from '../repeat-last-action.service';
+const FIRST_RANGE: IRange = { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 };
+const LAST_RANGE: IRange = { startRow: 4, endRow: 6, startColumn: 2, endColumn: 3 };
+const SELECTIONS = [FIRST_RANGE, LAST_RANGE];
+
+class RecordingCommandService {
+ readonly executions: Array<{ id: string; params?: unknown }> = [];
+ onExecute?: () => void;
+ failNext = false;
+
+ async executeCommand(id: string, params?: unknown): Promise<boolean> {
+ this.executions.push({ id, params });
+ this.onExecute?.();
+
+ if (this.failNext) {
+ this.failNext = false;
+ throw new Error('command failed');
+ }
+
+ return true;
+ }
+}
+
+class CommandSelectionsService {
+ selections: Array<{ range: IRange }> | null = SELECTIONS.map((range) => ({ range }));
+
+ getCurrentSelections() {
+ return this.selections;
+ }
+}
+
+class CommandRepeatLastActionService {
+ permission: RepeatLastActionPermission | RepeatLastActionPermission[] = RepeatLastActionPermission.None;
+ readonly repeatedSelections: IRange[][] = [];
+ result = true;
+
+ getActionPermission() {
+ return this.permission;
+ }
+
+ async runWithoutRecording(selections: IRange[]) {
+ this.repeatedSelections.push(selections);
+ return this.result;
+ }
+}
+
+class CommandPermissionCheckController {
+ permissions: boolean[] = [true];
+ readonly checks: unknown[] = [];
+ readonly blockedMessages: string[] = [];
+
+ permissionCheckWithRanges(permissionTypes: unknown) {
+ this.checks.push(permissionTypes);
+ return this.permissions.shift() ?? true;
+ }
+
+ blockExecuteWithoutPermission(message: string) {
+ this.blockedMessages.push(message);
+ }
+}
+
+class CommandLocaleService {
+ t(key: string) {
+ return `translated:${key}`;
+ }
+}
+
+function addUseClass(injector: Injector, token: unknown, useClass: unknown) {
+ injector.add([token, { useClass }] as any);
+}
+
+function createRepeatCommandInjector(): Injector {
+ const injector = new Injector();
+ addUseClass(injector, SheetsSelectionsService, CommandSelectionsService);
+ addUseClass(injector, IRepeatLastActionService, CommandRepeatLastActionService);
+ addUseClass(injector, SheetPermissionCheckController, CommandPermissionCheckController);
+ addUseClass(injector, LocaleService, CommandLocaleService);
+ return injector;
+}
+
describe('RepeatLastActionService', () => {
let service: IRepeatLastActionService;
+ let commandService: RecordingCommandService;
beforeEach(() => {
const injector = new Injector();
- injector.add([ICommandService, { useValue: { executeCommand: async () => true } as unknown as ICommandService }]);
+ addUseClass(injector, ICommandService, RecordingCommandService);
injector.add([IRepeatLastActionService, { useClass: RepeatLastActionService }]);
service = injector.get(IRepeatLastActionService);
+ commandService = injector.get(ICommandService) as unknown as RecordingCommandService;
});
it('records repeatable commands with the permission type needed by the current selection', () => {
@@ -42,5 +146,186 @@ describe('RepeatLastActionService', () => {
disposable.dispose();
expect(service.getRepeatableCommands().has('sheet.command.fill-series')).toBe(false);
+ service.setAction({ id: 'sheet.command.fill-series' });
+ expect(service.getActionPermission()).toBe(RepeatLastActionPermission.None);
+ });
+
+ it('maps built-in repeatable commands to the permissions they need', () => {
+ service.setAction({ id: SetStyleCommand.id });
+ expect(service.getActionPermission()).toBe(RepeatLastActionPermission.CellStyle);
+
+ service.setAction({ id: SetRowHeightCommand.id });
+ expect(service.getActionPermission()).toBe(RepeatLastActionPermission.RowStyle);
+
+ service.setAction({ id: SetColWidthCommand.id });
+ expect(service.getActionPermission()).toBe(RepeatLastActionPermission.ColumnStyle);
+
+ service.setAction({ id: ClearSelectionAllCommand.id });
+ expect(service.getActionPermission()).toEqual([
+ RepeatLastActionPermission.CellStyle,
+ RepeatLastActionPermission.CellValue,
+ ]);
+
+ service.setAction({ id: 'sheet.command.not-repeatable' });
+ expect(service.getActionPermission()).toBe(RepeatLastActionPermission.None);
+ });
+
+ it('replays commands with the current selection shape expected by each command family', async () => {
+ service.setAction({ id: SetStyleCommand.id, params: { style: { bl: 1 }, range: FIRST_RANGE } });
+ await expect(service.runWithoutRecording(SELECTIONS)).resolves.toBe(true);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: SetStyleCommand.id,
+ params: { style: { bl: 1 }, range: LAST_RANGE },
+ });
+
+ service.setAction({ id: AddWorksheetMergeCommand.id, params: { type: 1 } });
+ await service.runWithoutRecording(SELECTIONS);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: AddWorksheetMergeCommand.id,
+ params: { type: 1, selections: SELECTIONS },
+ });
+
+ for (const [sourceCommand, replayCommand] of [
+ [InsertRowCommand.id, InsertRangeMoveDownCommand.id],
+ [InsertColCommand.id, InsertRangeMoveRightCommand.id],
+ [RemoveRowCommand.id, DeleteRangeMoveUpCommand.id],
+ [RemoveColCommand.id, DeleteRangeMoveLeftCommand.id],
+ ]) {
+ service.setAction({ id: sourceCommand });
+ await service.runWithoutRecording(SELECTIONS);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: replayCommand,
+ params: { range: LAST_RANGE },
+ });
+ }
+
+ for (const commandId of [
+ SetBorderCommand.id,
+ SetRowHeightCommand.id,
+ SetColWidthCommand.id,
+ ClearSelectionContentCommand.id,
+ ClearSelectionFormatCommand.id,
+ ClearSelectionAllCommand.id,
+ RemoveWorksheetMergeCommand.id,
+ ]) {
+ service.setAction({ id: commandId, params: { unitId: 'unit-1' } });
+ await service.runWithoutRecording(SELECTIONS);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: commandId,
+ params: { unitId: 'unit-1', ranges: SELECTIONS },
+ });
+ }
+ });
+
+ it('uses registered command handlers and falls back to original params for custom replay', async () => {
+ const customParams = { fillType: 'series' };
+ service.registerRepeatableCommand(
+ 'sheet.command.fill-series',
+ (selections, params) => ({ ...params, anchor: selections.at(-1) }),
+ RepeatLastActionPermission.CellValue
+ );
+
+ service.setAction({ id: 'sheet.command.fill-series', params: customParams });
+ await service.runWithoutRecording(SELECTIONS);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: 'sheet.command.fill-series',
+ params: { fillType: 'series', anchor: LAST_RANGE },
+ });
+
+ service.setAction({ id: 'sheet.command.other', params: { keep: true } });
+ await service.runWithoutRecording(SELECTIONS);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: 'sheet.command.other',
+ params: { keep: true },
+ });
+ });
+
+ it('does not record nested actions while a repeat is running', async () => {
+ service.setAction({ id: SetStyleCommand.id, params: { style: { it: 1 } } });
+ commandService.onExecute = () => service.setAction({ id: SetBorderCommand.id });
+
+ await service.runWithoutRecording(SELECTIONS);
+
+ expect(service.getAction()).toEqual({ id: SetStyleCommand.id, params: { style: { it: 1 } } });
+ });
+
+ it('stops recording depth after failed replay and can repeat again', async () => {
+ service.setAction({ id: SetStyleCommand.id, params: { style: { ul: { s: 1 } } } });
+ commandService.failNext = true;
+
+ await expect(service.runWithoutRecording(SELECTIONS)).rejects.toThrow('command failed');
+
+ service.setAction({ id: SetBorderCommand.id, params: { unitId: 'unit-1' } });
+ await expect(service.runWithoutRecording(SELECTIONS)).resolves.toBe(true);
+ expect(commandService.executions.at(-1)).toEqual({
+ id: SetBorderCommand.id,
+ params: { unitId: 'unit-1', ranges: SELECTIONS },
+ });
+ });
+
+ it('returns false when there is no action to replay', async () => {
+ await expect(service.runWithoutRecording(SELECTIONS)).resolves.toBe(false);
+ expect(commandService.executions).toEqual([]);
+ });
+});
+
+describe('RepeatLastActionCommand', () => {
+ it('does not repeat when the sheet has no current selection', async () => {
+ const injector = createRepeatCommandInjector();
+ (injector.get(SheetsSelectionsService) as unknown as CommandSelectionsService).selections = [];
+
+ await expect(RepeatLastActionCommand.handler(injector)).resolves.toBe(false);
+ expect((injector.get(IRepeatLastActionService) as unknown as CommandRepeatLastActionService).repeatedSelections).toEqual([]);
+ });
+
+ it('repeats the last action without permission checks for actions that do not need them', async () => {
+ const injector = createRepeatCommandInjector();
+ const repeatService = injector.get(IRepeatLastActionService) as unknown as CommandRepeatLastActionService;
+
+ await expect(RepeatLastActionCommand.handler(injector)).resolves.toBe(true);
+
+ expect(repeatService.repeatedSelections).toEqual([SELECTIONS]);
+ expect((injector.get(SheetPermissionCheckController) as unknown as CommandPermissionCheckController).checks).toEqual([]);
+ });
+
+ it('blocks a single-permission repeat when the current range cannot be edited', async () => {
+ const injector = createRepeatCommandInjector();
+ const repeatService = injector.get(IRepeatLastActionService) as unknown as CommandRepeatLastActionService;
+ const permissionController = injector.get(SheetPermissionCheckController) as unknown as CommandPermissionCheckController;
+ repeatService.permission = RepeatLastActionPermission.CellStyle;
+ permissionController.permissions = [false];
+
+ await expect(RepeatLastActionCommand.handler(injector)).resolves.toBe(false);
+
+ expect(repeatService.repeatedSelections).toEqual([]);
+ expect(permissionController.blockedMessages).toEqual(['translated:sheets-ui.permission.dialog.setStyleErr']);
+ });
+
+ it('checks every required permission and stops at the first failed range rule', async () => {
+ const injector = createRepeatCommandInjector();
+ const repeatService = injector.get(IRepeatLastActionService) as unknown as CommandRepeatLastActionService;
+ const permissionController = injector.get(SheetPermissionCheckController) as unknown as CommandPermissionCheckController;
+ repeatService.permission = [
+ RepeatLastActionPermission.None,
+ RepeatLastActionPermission.CellStyle,
+ RepeatLastActionPermission.CellValue,
+ ];
+ permissionController.permissions = [true, false];
+
+ await expect(RepeatLastActionCommand.handler(injector)).resolves.toBe(false);
+
+ expect(permissionController.checks.length).toBe(2);
+ expect(permissionController.blockedMessages).toEqual(['translated:sheets-ui.permission.dialog.editErr']);
+ expect(repeatService.repeatedSelections).toEqual([]);
+ });
+
+ it('returns the replay result after all required permissions pass', async () => {
+ const injector = createRepeatCommandInjector();
+ const repeatService = injector.get(IRepeatLastActionService) as unknown as CommandRepeatLastActionService;
+ repeatService.permission = RepeatLastActionPermission.Editable;
+ repeatService.result = false;
+
+ await expect(RepeatLastActionCommand.handler(injector)).resolves.toBe(false);
+ expect(repeatService.repeatedSelections).toEqual([SELECTIONS]);
});
});
diff --git a/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts
index ba751403f9..ecee5a46f8 100644
--- a/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts
@@ -22,6 +22,19 @@ import { describe, expect, it } from 'vitest';
import { SheetScrollManagerService } from '../scroll-manager.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+class TestSheetSkeletonManagerService {
+ static currentSkeleton: any = null;
+ static skeletons = new Map<string, any>();
+
+ getCurrentSkeleton() {
+ return TestSheetSkeletonManagerService.currentSkeleton;
+ }
+
+ getSkeleton(sheetId: string) {
+ return TestSheetSkeletonManagerService.skeletons.get(sheetId) ?? null;
+ }
+}
+
function createRenderContext(unitId: string): IRenderContext<Workbook> {
const activated$ = new BehaviorSubject(true);
const unit = {
@@ -45,10 +58,18 @@ function createRenderContext(unitId: string): IRenderContext<Workbook> {
}
describe('SheetScrollManagerService', () => {
- it('returns an empty scroll state when no search param is set', () => {
+ function createService(skeleton: any = null, skeletons: Record<string, any> = {}) {
+ TestSheetSkeletonManagerService.currentSkeleton = skeleton;
+ TestSheetSkeletonManagerService.skeletons = new Map(Object.entries(skeletons));
+
const injector = new Injector();
- injector.add([SheetSkeletonManagerService, { useValue: { getCurrentSkeleton: () => null } as unknown as SheetSkeletonManagerService }]);
- const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+ injector.add([SheetSkeletonManagerService, { useClass: TestSheetSkeletonManagerService as never }]);
+ injector.add([SheetScrollManagerService, { useFactory: () => injector.createInstance(SheetScrollManagerService, createRenderContext('u-1')) }]);
+ return injector.get(SheetScrollManagerService);
+ }
+
+ it('returns an empty scroll state when no search param is set', () => {
+ const service = createService();
expect(service.getCurrentScrollState()).toEqual({
sheetViewStartRow: 0,
@@ -59,9 +80,7 @@ describe('SheetScrollManagerService', () => {
});
it('stores and retrieves scroll state by sheet', () => {
- const injector = new Injector();
- injector.add([SheetSkeletonManagerService, { useValue: { getCurrentSkeleton: () => null } as unknown as SheetSkeletonManagerService }]);
- const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+ const service = createService();
service.setSearchParam({ unitId: 'u-1', sheetId: 's-1' });
service.setValidScrollState({
@@ -96,19 +115,10 @@ describe('SheetScrollManagerService', () => {
});
it('calculates viewport scroll based on skeleton accumulations', () => {
- const injector = new Injector();
- injector.add([
- SheetSkeletonManagerService,
- {
- useValue: {
- getCurrentSkeleton: () => ({
- rowHeightAccumulation: [10, 25, 45],
- columnWidthAccumulation: [100, 210, 330],
- }),
- } as unknown as SheetSkeletonManagerService,
- },
- ]);
- const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+ const service = createService({
+ rowHeightAccumulation: [10, 25, 45],
+ columnWidthAccumulation: [100, 210, 330],
+ });
expect(service.calcViewportScrollFromRowColOffset(null)).toEqual({
viewportScrollX: 0,
@@ -133,29 +143,20 @@ describe('SheetScrollManagerService', () => {
});
it('calculates viewport scroll from the actual cell start when gaps shift the origin', () => {
- const injector = new Injector();
- injector.add([
- SheetSkeletonManagerService,
- {
- useValue: {
- getCurrentSkeleton: () => ({
- rowHeightAccumulation: [28, 57, 81],
- columnWidthAccumulation: [72, 192, 271],
- getCellWithCoordByIndex: (row: number, column: number, header?: boolean) => {
- expect(header).toBe(false);
- expect(row).toBe(1);
- expect(column).toBe(2);
-
- return {
- startY: 33,
- startX: 199,
- };
- },
- }),
- } as unknown as SheetSkeletonManagerService,
+ const service = createService({
+ rowHeightAccumulation: [28, 57, 81],
+ columnWidthAccumulation: [72, 192, 271],
+ getCellWithCoordByIndex: (row: number, column: number, header?: boolean) => {
+ expect(header).toBe(false);
+ expect(row).toBe(1);
+ expect(column).toBe(2);
+
+ return {
+ startY: 33,
+ startX: 199,
+ };
},
- ]);
- const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+ });
expect(service.calcViewportScrollFromRowColOffset({
sheetViewStartRow: 1,
@@ -173,33 +174,21 @@ describe('SheetScrollManagerService', () => {
});
it('keeps the initial viewport at origin when gap 0 exists but no scroll has been applied', () => {
- const injector = new Injector();
- injector.add([
- SheetSkeletonManagerService,
- {
- useValue: {
- getCurrentSkeleton: () => ({
- getCellWithCoordByIndex: (row: number, column: number, header?: boolean) => {
- expect(header).toBe(false);
- expect(row).toBe(0);
- expect(column).toBe(0);
-
- return {
- startY: 10,
- startX: 7,
- };
- },
- getRowGapSize: (row: number) => (row === 0 ? 10 : 0),
- getColGapSize: (column: number) => (column === 0 ? 7 : 0),
- }),
- getSkeleton: () => ({
- getRowGapSize: (row: number) => (row === 0 ? 10 : 0),
- getColGapSize: (column: number) => (column === 0 ? 7 : 0),
- }),
- } as unknown as SheetSkeletonManagerService,
+ const gapSkeleton = {
+ getCellWithCoordByIndex: (row: number, column: number, header?: boolean) => {
+ expect(header).toBe(false);
+ expect(row).toBe(0);
+ expect(column).toBe(0);
+
+ return {
+ startY: 10,
+ startX: 7,
+ };
},
- ]);
- const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+ getRowGapSize: (row: number) => (row === 0 ? 10 : 0),
+ getColGapSize: (column: number) => (column === 0 ? 7 : 0),
+ };
+ const service = createService(gapSkeleton, { 's-1': gapSkeleton });
service.setSearchParam({ unitId: 'u-1', sheetId: 's-1' });
@@ -222,19 +211,10 @@ describe('SheetScrollManagerService', () => {
});
it('falls back to current skeleton when a mock does not provide getSkeleton', () => {
- const injector = new Injector();
- injector.add([
- SheetSkeletonManagerService,
- {
- useValue: {
- getCurrentSkeleton: () => ({
- getRowGapSize: (row: number) => (row === 0 ? 9 : 0),
- getColGapSize: (column: number) => (column === 0 ? 6 : 0),
- }),
- } as unknown as SheetSkeletonManagerService,
- },
- ]);
- const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+ const service = createService({
+ getRowGapSize: (row: number) => (row === 0 ? 9 : 0),
+ getColGapSize: (column: number) => (column === 0 ? 6 : 0),
+ });
expect(service.getScrollStateByParam({ unitId: 'u-1', sheetId: 's-2' })).toEqual({
sheetViewStartRow: 0,
@@ -243,4 +223,80 @@ describe('SheetScrollManagerService', () => {
offsetY: -9,
});
});
+
+ it('publishes raw scroll info, persists current-sheet scroll and clears to the sheet default', () => {
+ const appliedScrolls: Array<[number, number]> = [];
+ const sheetSkeleton = {
+ getRowGapSize: (row: number) => (row === 0 ? 8 : 0),
+ getColGapSize: (column: number) => (column === 0 ? 5 : 0),
+ setScroll: (x: number, y: number) => appliedScrolls.push([x, y]),
+ };
+ const service = createService(sheetSkeleton, { 's-1': sheetSkeleton });
+ const rawStates: unknown[] = [];
+ service.rawScrollInfo$.subscribe((state) => rawStates.push(state));
+
+ service.emitRawScrollParam({
+ unitId: 'u-1',
+ sheetId: 's-1',
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 2,
+ offsetX: 11,
+ offsetY: 12,
+ });
+ expect(rawStates.at(-1)).toEqual({
+ unitId: 'u-1',
+ sheetId: 's-1',
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 2,
+ offsetX: 11,
+ offsetY: 12,
+ });
+
+ service.setValidScrollStateToCurrSheet({
+ sheetViewStartRow: 1,
+ sheetViewStartColumn: 1,
+ offsetX: 1,
+ offsetY: 2,
+ scrollX: 30,
+ scrollY: 40,
+ viewportScrollX: 300,
+ viewportScrollY: 400,
+ });
+ expect(appliedScrolls).toEqual([]);
+
+ service.setSearchParam({ unitId: 'u-1', sheetId: 's-1' });
+ service.setValidScrollStateToCurrSheet({
+ sheetViewStartRow: 1,
+ sheetViewStartColumn: 1,
+ offsetX: 1,
+ offsetY: 2,
+ scrollX: 30,
+ scrollY: 40,
+ viewportScrollX: 300,
+ viewportScrollY: 400,
+ });
+ expect(service.getCurrentScrollState()).toEqual({
+ sheetViewStartRow: 1,
+ sheetViewStartColumn: 1,
+ offsetX: 1,
+ offsetY: 2,
+ });
+ expect(appliedScrolls).toEqual([[300, 400]]);
+
+ service.clear();
+ expect(service.getCurrentScrollState()).toEqual({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: -5,
+ offsetY: -8,
+ });
+ expect(rawStates.at(-1)).toEqual({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: -5,
+ offsetY: -8,
+ });
+
+ service.dispose();
+ });
});
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.ts
index 60841abe4a..620c796c97 100644
--- 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.ts
@@ -28,10 +28,40 @@ import {
UniverInstanceType,
Workbook,
} from '@univerjs/core';
-import { SheetSkeletonService } from '@univerjs/sheets';
+import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
+import { Subject } from 'rxjs';
import { describe, expect, it } from 'vitest';
+import { ISheetSelectionRenderService } from '../selection/base-selection-render.service';
import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+class TestSheetSkeletonService {
+ static skeleton: any;
+ static param: any;
+ static scene: unknown;
+ buildSkeleton$ = new Subject<any>();
+
+ setScene(_unitId: string, scene: unknown) {
+ TestSheetSkeletonService.scene = scene;
+ }
+
+ getSkeletonsByUnitId() {
+ return [TestSheetSkeletonService.skeleton];
+ }
+
+ getSkeleton() {
+ return TestSheetSkeletonService.skeleton;
+ }
+
+ getSkeletonParam() {
+ return TestSheetSkeletonService.param;
+ }
+
+ ensureSkeleton() {
+ return TestSheetSkeletonService.skeleton;
+ }
+}
+
describe('SheetSkeletonManagerService', () => {
it('sets the current worksheet skeleton and marks it dirty for recalculation', () => {
const injector = new Injector();
@@ -67,4 +97,68 @@ describe('SheetSkeletonManagerService', () => {
expect(service.getCurrentParam()).toMatchObject({ unitId: 'unit-1', sheetId: 'sheet-1', dirty: true });
expect(service.ensureSkeleton('sheet-1')).toBe(service.getCurrentSkeleton());
});
+
+ it('updates sheet header sizes, viewport bounds and selection render state', () => {
+ const registeredSkeletons: string[] = [];
+ const skeleton = {
+ columnHeaderHeight: 20,
+ rowHeaderWidth: 46,
+ registerGetCellHeight: () => registeredSkeletons.push('registered'),
+ };
+ const param = { unitId: 'unit-1', sheetId: 'sheet-1', skeleton, dirty: false };
+ TestSheetSkeletonService.skeleton = skeleton;
+ TestSheetSkeletonService.param = param;
+
+ const injector = new Injector();
+ injector.add([SheetSkeletonService, { useClass: TestSheetSkeletonService as never }]);
+ const workbook = {
+ getSheetBySheetId: () => ({ getSheetId: () => 'sheet-1' }),
+ getStyles: () => ({}),
+ };
+ const service = injector.createInstance(SheetSkeletonManagerService, {
+ unit: workbook,
+ unitId: 'unit-1',
+ type: UniverInstanceType.UNIVER_SHEET,
+ scene: {},
+ } as never);
+
+ const viewportState = new Map<string, any>([
+ [SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT, { left: 100, setViewportSize(params: object) { Object.assign(this, params); } }],
+ [SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT, { setViewportSize(params: object) { Object.assign(this, params); } }],
+ [SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM, { setViewportSize(params: object) { Object.assign(this, params); } }],
+ [SHEET_VIEWPORT_KEY.VIEW_ROW_TOP, { setViewportSize(params: object) { Object.assign(this, params); } }],
+ [SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP, { width: 46, setViewportSize(params: object) { Object.assign(this, params); } }],
+ ]);
+ const mainViewport = { top: 0, left: 46 };
+ const selections = [{ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }];
+ const resetSelections: unknown[] = [];
+ const render = {
+ unitId: 'unit-1',
+ scene: {
+ getViewports: () => [mainViewport],
+ getViewport: (key: string) => viewportState.get(key),
+ },
+ with: (token: unknown) => {
+ if (token === SheetsSelectionsService) {
+ return { getCurrentSelections: () => selections };
+ }
+ if (token === ISheetSelectionRenderService) {
+ return { resetSelectionsByModelData: (value: unknown) => resetSelections.push(value) };
+ }
+ return null;
+ },
+ };
+
+ service.setColumnHeaderSize(render as never, 'sheet-1', 32);
+ service.setRowHeaderSize(render as never, 'sheet-1', 60);
+
+ expect(registeredSkeletons).toEqual(['registered']);
+ expect(skeleton.columnHeaderHeight).toBe(32);
+ expect(skeleton.rowHeaderWidth).toBe(60);
+ expect(mainViewport).toEqual({ top: 32, left: 60 });
+ expect(viewportState.get(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT)).toMatchObject({ height: 32, left: 114 });
+ expect(viewportState.get(SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP)).toMatchObject({ height: 32, width: 60 });
+ expect(resetSelections).toEqual([selections, selections]);
+ expect((param as { commandId?: string }).commandId).toBe('sheet.command.set-row-header-width');
+ });
});
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.ts
index ed85540627..13b05e3c8a 100644
--- a/packages/sheets-ui/src/services/__tests__/sheets-render.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/sheets-render.service.spec.ts
@@ -23,9 +23,11 @@ import {
IUniverInstanceService,
ThemeService,
UniverInstanceService,
+ UniverInstanceType,
} from '@univerjs/core';
-import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import { describe, expect, it } from 'vitest';
+import { IRenderManagerService, RenderManagerService, Spreadsheet } from '@univerjs/engine-render';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
import { SheetsRenderService } from '../sheets-render.service';
function createService(): SheetsRenderService {
@@ -39,6 +41,78 @@ function createService(): SheetsRenderService {
return injector.get(SheetsRenderService);
}
+function createWorkbook(unitId: string) {
+ return {
+ getUnitId: () => unitId,
+ };
+}
+
+function createLifecycleService() {
+ const added$ = new Subject<{ unit: ReturnType<typeof createWorkbook>; options?: Record<string, unknown> }>();
+ const disposed$ = new Subject<ReturnType<typeof createWorkbook>>();
+ const rawFormula$ = new BehaviorSubject(false);
+ const initialWorkbook = createWorkbook('book-1');
+ const created$ = new Subject<any>();
+ const createdRenderers: Array<{ unitId: string; options?: unknown }> = [];
+ const removedRenderers: string[] = [];
+ const spreadsheet = Object.create(Spreadsheet.prototype) as Spreadsheet & { makeForceDirty: any };
+ spreadsheet.makeForceDirty = vi.fn();
+
+ class TestContextService {
+ subscribeContextValue$() {
+ return rawFormula$.asObservable();
+ }
+ }
+
+ class TestUniverInstanceService {
+ getTypeOfUnitAdded$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? added$.asObservable() : new Subject().asObservable();
+ }
+
+ getAllUnitsForType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? [initialWorkbook] : [];
+ }
+
+ getTypeOfUnitDisposed$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? disposed$.asObservable() : new Subject().asObservable();
+ }
+ }
+
+ class TestRenderManagerService {
+ readonly created$ = created$.asObservable();
+
+ createRender(unitId: string, options?: unknown) {
+ createdRenderers.push({ unitId, options });
+ }
+
+ removeRender(unitId: string) {
+ removedRenderers.push(unitId);
+ }
+
+ getRenderAll() {
+ return [{ mainComponent: spreadsheet }];
+ }
+ }
+
+ const injector = new Injector();
+ injector.add([IContextService, { useClass: TestContextService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([ThemeService]);
+ injector.add([SheetsRenderService]);
+
+ return {
+ service: injector.get(SheetsRenderService),
+ added$,
+ disposed$,
+ rawFormula$,
+ created$,
+ createdRenderers,
+ removedRenderers,
+ spreadsheet,
+ };
+}
+
describe('SheetsRenderService', () => {
it('tracks mutations that require rebuilding the sheet skeleton and unregisters them by disposable', () => {
const service = createService();
@@ -47,7 +121,50 @@ describe('SheetsRenderService', () => {
expect(service.checkMutationShouldTriggerRerender('sheet.mutation.resize-row')).toBe(true);
expect(service.checkMutationShouldTriggerRerender('sheet.mutation.set-value')).toBe(false);
+ const duplicateDisposable = service.registerSkeletonChangingMutations('sheet.mutation.resize-row');
+ duplicateDisposable.dispose();
+ expect(service.checkMutationShouldTriggerRerender('sheet.mutation.resize-row')).toBe(true);
+
disposable.dispose();
expect(service.checkMutationShouldTriggerRerender('sheet.mutation.resize-row')).toBe(false);
});
+
+ it('creates and disposes sheet renderers as workbooks enter and leave the instance service', async () => {
+ const { added$, disposed$, created$, createdRenderers, removedRenderers } = createLifecycleService();
+
+ await Promise.resolve();
+ expect(createdRenderers.map(({ unitId }) => unitId)).toEqual(['book-1']);
+
+ added$.next({ unit: createWorkbook('book-2'), options: { mountContainer: 'container' } });
+ expect(createdRenderers.at(-1)).toEqual({
+ unitId: 'book-2',
+ options: { mountContainer: 'container' },
+ });
+
+ const canvas = { setId: vi.fn() };
+ const context = { setId: vi.fn() };
+ created$.next({
+ unitId: 'book-2',
+ engine: {
+ getCanvas: () => ({
+ setId: canvas.setId,
+ getContext: () => context,
+ }),
+ },
+ });
+ expect(canvas.setId).toHaveBeenCalledWith('univer-sheet-main-canvas_book-2');
+ expect(context.setId).toHaveBeenCalledWith('univer-sheet-main-canvas_book-2');
+
+ disposed$.next(createWorkbook('book-1'));
+ expect(removedRenderers).toEqual(['book-1']);
+ });
+
+ it('marks spreadsheet renderers dirty when raw formula display changes', async () => {
+ const { rawFormula$, spreadsheet } = createLifecycleService();
+
+ await Promise.resolve();
+ rawFormula$.next(true);
+
+ expect(spreadsheet.makeForceDirty).toHaveBeenCalledWith(true);
+ });
});
diff --git a/packages/sheets-ui/src/services/__tests__/shortcut-experience.service.spec.ts b/packages/sheets-ui/src/services/__tests__/shortcut-experience.service.spec.ts
index 3e74899b43..9dc8703751 100644
--- a/packages/sheets-ui/src/services/__tests__/shortcut-experience.service.spec.ts
+++ b/packages/sheets-ui/src/services/__tests__/shortcut-experience.service.spec.ts
@@ -23,8 +23,10 @@ describe('ShortcutExperienceService', () => {
beforeEach(() => {
const injector = new Injector();
- injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);
- injector.add([LocaleService, { useValue: {} as LocaleService }]);
+ class TestUniverInstanceService {}
+
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([LocaleService]);
injector.add([ShortcutExperienceService]);
service = injector.get(ShortcutExperienceService);
});
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.ts
index 98ac2893fd..17e4d91f40 100644
--- 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.ts
@@ -29,6 +29,8 @@ import {
IUniverInstanceService,
LocaleService,
LocalUndoRedoService,
+ ObjectMatrix,
+ RANGE_TYPE,
ThemeService,
UniverInstanceService,
Workbook,
@@ -36,7 +38,6 @@ import {
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import { SheetSkeletonService, SheetsSelectionsService } from '@univerjs/sheets';
import {
- BrowserClipboardService,
IClipboardInterfaceService,
INotificationService,
IPlatformService,
@@ -44,7 +45,14 @@ import {
} 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';
+import {
+ ISheetClipboardService,
+ PREDEFINED_HOOK_NAME_COPY,
+ PREDEFINED_HOOK_NAME_PASTE,
+ SheetClipboardService,
+} from '../clipboard.service';
+import { COPY_TYPE } from '../type';
+import { MockClipboardItem } from './mock-clipboard';
class NoopNotificationService {
show() {
@@ -52,7 +60,84 @@ class NoopNotificationService {
}
}
-function createService(): ISheetClipboardService {
+class TestClipboardInterfaceService {
+ readonly writes: Array<{ text: string; html: string }> = [];
+
+ get supportClipboard(): boolean {
+ return true;
+ }
+
+ async writeText(text: string): Promise<void> {
+ this.writes.push({ text, html: '' });
+ }
+
+ async write(text: string, html: string): Promise<void> {
+ this.writes.push({ text, html });
+ }
+
+ async readText(): Promise<string> {
+ return '';
+ }
+
+ async read(): Promise<ClipboardItem[]> {
+ return [];
+ }
+}
+
+interface ITestCell {
+ v?: string;
+ s?: unknown;
+ rowSpan?: number;
+ colSpan?: number;
+}
+
+interface ITestDiscreteRange {
+ rows: number[];
+ cols: number[];
+}
+
+interface IPrivateClipboardServiceAccess {
+ _pasteUSM(
+ data: { cellMatrix: ObjectMatrix<ITestCell>; rowProperties: unknown[]; colProperties: unknown[] },
+ target: { unitId: string; subUnitId: string; pastedRange: ITestDiscreteRange },
+ pasteType: string
+ ): boolean;
+ _transformPastedData(
+ rowCount: number,
+ colCount: number,
+ cellMatrix: ObjectMatrix<ITestCell>
+ ): { unitId: string; subUnitId: string; pastedRange: ITestDiscreteRange } | null;
+ _expandOrShrinkRowsCols(
+ unitId: string,
+ subUnitId: string,
+ range: ITestDiscreteRange,
+ colCount: number,
+ rowCount: number
+ ): ITestDiscreteRange;
+ _getSetSelectionOperation(
+ unitId: string,
+ subUnitId: string,
+ range: ITestDiscreteRange,
+ cellMatrix: ObjectMatrix<ITestCell>,
+ pasteType: string
+ ): {
+ params: {
+ selections: Array<{
+ primary: {
+ startRow: number;
+ endRow: number;
+ startColumn: number;
+ endColumn: number;
+ isMerged?: boolean;
+ isMergedMainCell?: boolean;
+ };
+ }>;
+ };
+ };
+ _topLeftCellsMatch(rowCount: number, colCount: number, range: { topRow: number; leftCol: number }): boolean;
+}
+
+function createTestContext() {
vi.stubGlobal('navigator', { appVersion: 'Linux' });
const injector = new Injector();
injector.add([ILogService, { useClass: DesktopLogService }]);
@@ -60,7 +145,7 @@ function createService(): ISheetClipboardService {
injector.add([IContextService, { useClass: ContextService }]);
injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);
injector.add([SheetsSelectionsService]);
- injector.add([IClipboardInterfaceService, { useClass: BrowserClipboardService }]);
+ injector.add([IClipboardInterfaceService, { useClass: TestClipboardInterfaceService }]);
injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);
injector.add([ICommandService, { useClass: CommandService }]);
injector.add([SheetSkeletonService]);
@@ -75,12 +160,59 @@ function createService(): ISheetClipboardService {
const univerInstanceService = injector.get(IUniverInstanceService) as UniverInstanceService;
const workbook = injector.createInstance(Workbook, {
id: 'unit-1',
- sheets: { 'sheet-1': { id: 'sheet-1' } },
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 'Quarterly revenue',
+ },
+ },
+ },
+ mergeData: [
+ {
+ startRow: 1,
+ startColumn: 1,
+ endRow: 2,
+ endColumn: 2,
+ },
+ ],
+ },
+ },
sheetOrder: ['sheet-1'],
});
univerInstanceService.__addUnit(workbook);
univerInstanceService.focusUnit('unit-1');
- return injector.get(ISheetClipboardService);
+ return {
+ injector,
+ service: injector.get(ISheetClipboardService),
+ };
+}
+
+function createService(): ISheetClipboardService {
+ return createTestContext().service;
+}
+
+function selectCell(injector: Injector, row = 0, column = 0) {
+ selectRange(injector, row, column, row, column);
+}
+
+function selectRange(injector: Injector, startRow: number, startColumn: number, endRow: number, endColumn: number) {
+ const selectionManager = injector.get(SheetsSelectionsService);
+ selectionManager.addSelections([
+ {
+ range: {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: null,
+ style: null,
+ },
+ ]);
}
describe('SheetClipboardService', () => {
@@ -107,4 +239,269 @@ describe('SheetClipboardService', () => {
expect(service.getPasteMenuVisible()).toBe(false);
expect(service.getPasteOptionsCache()).toBeNull();
});
+
+ it('keeps clipboard hooks in priority order and ignores duplicate hook ids', () => {
+ const service = createService();
+ const lowPriority = { id: 'after-default', priority: 20 };
+ const highPriority = { id: 'before-default', priority: 1 };
+ const duplicateHighPriority = { id: 'before-default', priority: 0 };
+
+ service.addClipboardHook(lowPriority as never);
+ service.addClipboardHook(highPriority as never);
+ service.addClipboardHook(duplicateHighPriority as never);
+
+ expect(service.getClipboardHooks().map((hook) => hook.id)).toEqual(['before-default', 'after-default']);
+ });
+
+ it('copies the current sheet selection into clipboard text/html and internal paste cache', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector);
+
+ const copied = await service.copy();
+ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ const copyId = clipboard.writes[0].html.match(/data-copy-id="([^"]+)"/)?.[1];
+
+ expect(copied).toBe(true);
+ expect(clipboard.writes[0].text).toBe('Quarterly revenue');
+ expect(clipboard.writes[0].html).toContain('data-copy-id=');
+ expect(copyId && service.copyContentCache().get(copyId)?.copyType).toBe(COPY_TYPE.COPY);
+ });
+
+ it('records cut selections as cut copy cache entries', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector);
+
+ const cut = await service.cut();
+ const clipboard = injector.get(IClipboardInterfaceService) as unknown as TestClipboardInterfaceService;
+ const copyId = clipboard.writes[0].html.match(/data-copy-id="([^"]+)"/)?.[1];
+
+ expect(cut).toBe(true);
+ expect(service.copyContentCache().get(copyId!)?.copyType).toBe(COPY_TYPE.CUT);
+ });
+
+ it('routes plain text and image clipboard items to paste hooks with the requested paste type', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector);
+ const pastedTexts: Array<{ text: string; pasteType: string }> = [];
+ const pastedFiles: Array<{ name: string; pasteType: string }> = [];
+
+ service.addClipboardHook({
+ id: 'plain-and-image-paste',
+ onPastePlainText(_payload: unknown, text: string, options: { pasteType: string }) {
+ pastedTexts.push({ text, pasteType: options.pasteType });
+ return { redos: [], undos: [] };
+ },
+ onPasteFiles(_payload: unknown, files: File[], options: { pasteType: string }) {
+ pastedFiles.push({ name: files[0].name, pasteType: options.pasteType });
+ return { redos: [], undos: [] };
+ },
+ } as never);
+
+ const textItem = new MockClipboardItem({ 'text/plain': 'North\tSouth' });
+ const imageItem = new MockClipboardItem({ 'image/png': 'image-bytes' });
+
+ expect(await service.paste(textItem as unknown as ClipboardItem, PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE)).toBe(true);
+ expect(await service.paste(imageItem as unknown as ClipboardItem, PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT)).toBe(true);
+ expect(pastedTexts).toEqual([{ text: 'North\tSouth', pasteType: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE }]);
+ expect(pastedFiles).toEqual([{ name: 'clipboard-image.png', pasteType: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT }]);
+ });
+
+ it('returns false when a clipboard item has no usable sheet content', async () => {
+ const service = createService();
+ const emptyItem = new MockClipboardItem({});
+
+ expect(await service.paste(emptyItem as unknown as ClipboardItem)).toBe(false);
+ });
+
+ it('returns false when internal paste and repaste have no cached business content', async () => {
+ const service = createService();
+
+ expect(await service.pasteByCopyId('missing-copy-id')).toBe(false);
+ expect(service.rePasteWithPasteType('SPECIAL_PASTE_VALUE')).toBe(false);
+ });
+
+ it('lets a special copy hook provide business-only cell values', () => {
+ const service = createService();
+ const lifecycle: string[] = [];
+
+ service.addClipboardHook({
+ id: PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY,
+ onBeforeCopy() {
+ lifecycle.push('before');
+ },
+ getCellValueBySpecialMatrix() {
+ return {
+ v: '=SUM(A1:A4)',
+ displayV: 'Projected revenue',
+ };
+ },
+ onAfterCopy() {
+ lifecycle.push('after');
+ },
+ } as never);
+
+ const copyContent = service.generateCopyContent('unit-1', 'sheet-1', {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ }, { copyHookType: PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY });
+
+ expect(copyContent?.plain).toBe('Projected revenue');
+ expect(copyContent?.matrixFragment.getValue(0, 0)?.v).toBe('=SUM(A1:A4)');
+ expect(lifecycle).toEqual(['before', 'after']);
+ });
+
+ it('stops paste execution when a hook blocks the target range', async () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector);
+ const pasteResults: boolean[] = [];
+
+ service.addClipboardHook({
+ id: 'protected-range-paste',
+ onBeforePaste() {
+ return false;
+ },
+ onAfterPaste(result: boolean) {
+ pasteResults.push(result);
+ },
+ onPastePlainText() {
+ return { redos: [], undos: [] };
+ },
+ } as never);
+
+ const textItem = new MockClipboardItem({ 'text/plain': 'Blocked update' });
+
+ expect(await service.paste(textItem as unknown as ClipboardItem)).toBe(false);
+ expect(pasteResults).toEqual([false]);
+ });
+
+ it('stops structured sheet paste when a hook blocks the computed range', () => {
+ const service = createService();
+ const matrix = new ObjectMatrix<ITestCell>();
+ const pasteResults: boolean[] = [];
+ matrix.setValue(0, 0, { v: 'Blocked matrix' });
+
+ service.addClipboardHook({
+ id: 'structured-protection',
+ onBeforePaste() {
+ return false;
+ },
+ onAfterPaste(result: boolean) {
+ pasteResults.push(result);
+ },
+ } as never);
+
+ const pasted = (service as unknown as IPrivateClipboardServiceAccess)._pasteUSM(
+ {
+ cellMatrix: matrix,
+ rowProperties: [],
+ colProperties: [],
+ },
+ {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ pastedRange: {
+ rows: [0],
+ cols: [0],
+ },
+ },
+ PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE
+ );
+
+ expect(pasted).toBe(false);
+ expect(pasteResults).toEqual([false]);
+ });
+
+ it('computes pasted target ranges when a one-cell source fills a business selection', () => {
+ const { injector, service } = createTestContext();
+ selectCell(injector, 3, 3);
+ const matrix = new ObjectMatrix<ITestCell>();
+ matrix.setValue(0, 0, { v: 'Region total' });
+
+ const target = (service as unknown as IPrivateClipboardServiceAccess)._transformPastedData(1, 1, matrix);
+
+ expect(target).toMatchObject({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ pastedRange: {
+ rows: [3],
+ cols: [3],
+ },
+ });
+ expect(matrix.getValue(0, 0)?.v).toBe('Region total');
+ });
+
+ it('keeps a single pasted cell inside an existing merged target and strips source span styling', () => {
+ const { injector, service } = createTestContext();
+ selectRange(injector, 1, 1, 2, 2);
+ const matrix = new ObjectMatrix<ITestCell>();
+ matrix.setValue(0, 0, {
+ v: 'Merged-region note',
+ s: { bl: 1 },
+ rowSpan: 2,
+ colSpan: 2,
+ });
+
+ const target = (service as unknown as IPrivateClipboardServiceAccess)._transformPastedData(1, 1, matrix);
+
+ expect(target?.pastedRange).toEqual({
+ rows: [1, 2],
+ cols: [1, 2],
+ });
+ expect(matrix.getValue(0, 0)).toMatchObject({
+ v: 'Merged-region note',
+ s: null,
+ });
+ expect(matrix.getValue(0, 0)?.rowSpan).toBeUndefined();
+ expect(matrix.getValue(0, 0)?.colSpan).toBeUndefined();
+ });
+
+ it('expands paste rows and columns beyond the current selection when pasted data is larger', () => {
+ const service = createService();
+
+ const range = (service as unknown as IPrivateClipboardServiceAccess)._expandOrShrinkRowsCols(
+ 'unit-1',
+ 'sheet-1',
+ { rows: [4], cols: [2] },
+ 3,
+ 2
+ );
+
+ expect(range).toEqual({
+ rows: [4, 5],
+ cols: [2, 3, 4],
+ });
+ });
+
+ it('expands the primary selection when default paste creates a merged cell', () => {
+ const service = createService();
+ const matrix = new ObjectMatrix<ITestCell>();
+ matrix.setValue(0, 0, { v: 'Merged header', rowSpan: 2, colSpan: 2 });
+
+ const operation = (service as unknown as IPrivateClipboardServiceAccess)._getSetSelectionOperation(
+ 'unit-1',
+ 'sheet-1',
+ { rows: [6, 7], cols: [1, 2] },
+ matrix,
+ PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE
+ );
+
+ expect(operation.params.selections[0].primary).toMatchObject({
+ startRow: 6,
+ endRow: 7,
+ startColumn: 1,
+ endColumn: 2,
+ isMerged: true,
+ isMergedMainCell: true,
+ });
+ });
+
+ it('detects whether the top-left paste target crosses existing merged cells', () => {
+ const service = createService();
+ const access = service as unknown as IPrivateClipboardServiceAccess;
+
+ expect(access._topLeftCellsMatch(1, 2, { topRow: 1, leftCol: 1 })).toBe(false);
+ expect(access._topLeftCellsMatch(1, 1, { topRow: 5, leftCol: 5 })).toBe(true);
+ });
});
diff --git a/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/utils.spec.ts b/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/utils.spec.ts
index dc16c5d4ac..29119ee8bb 100644
--- a/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/utils.spec.ts
+++ b/packages/sheets-ui/src/services/clipboard/html-to-usm/__tests__/utils.spec.ts
@@ -14,8 +14,33 @@
* limitations under the License.
*/
+import type { IDocumentBody, IDocumentData, IParagraph } from '@univerjs/core';
+import { BaselineOffset, BooleanNumber, DataStreamTreeTokenType } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
-import parseToDom from '../utils';
+import { extractNodeStyle } from '../parse-node-style';
+import { LarkPastePlugin } from '../paste-plugins/plugin-lark';
+import { UniverPastePlugin } from '../paste-plugins/plugin-univer';
+import { WordPastePlugin } from '../paste-plugins/plugin-word';
+import parseToDom, { convertToCellStyle, generateParagraphs, getParagraphStyle } from '../utils';
+
+function createCellDocument(dataStream: string, textRuns: IDocumentBody['textRuns']): IDocumentData {
+ return {
+ id: 'paste-cell-doc',
+ body: {
+ dataStream,
+ textRuns,
+ },
+ documentStyle: {},
+ };
+}
+
+function checkElementFilter(filter: string | string[] | ((node: HTMLElement) => boolean), node: HTMLElement): boolean {
+ if (typeof filter !== 'function') {
+ throw new TypeError('Expected paste plugin filter to be a function');
+ }
+
+ return filter(node);
+}
describe('parseToDom', () => {
it('parses clipboard html without retaining active content sinks', () => {
@@ -34,4 +59,250 @@ describe('parseToDom', () => {
expect(dom.querySelector('iframe')).toBeNull();
expect(dom.querySelector('table td')?.textContent).toBe('1');
});
+
+ it('keeps plain pasted rows readable by normalizing multiline text nodes', () => {
+ const dom = parseToDom('<table><tbody><tr><td>North\r\n\tEast</td><td>South\n West</td></tr></tbody></table>');
+
+ expect([...dom.querySelectorAll('td')].map((td) => td.textContent)).toEqual(['North East', 'South West']);
+ });
+});
+
+describe('extractNodeStyle', () => {
+ it('maps semantic rich text tags and inline styles into document text style', () => {
+ const bold = document.createElement('strong');
+ bold.setAttribute('style', [
+ 'font-family: Arial',
+ 'font-size: 20px',
+ 'font-style: italic',
+ 'font-weight: 700',
+ 'text-decoration: underline',
+ 'color: rgb(12, 34, 56)',
+ 'background-color: #ffeecc',
+ ].join(';'));
+
+ expect(extractNodeStyle(bold)).toEqual({
+ bl: BooleanNumber.TRUE,
+ ff: 'Arial',
+ fs: 15,
+ it: BooleanNumber.TRUE,
+ ul: { s: BooleanNumber.TRUE },
+ cl: { rgb: 'rgb(12,34,56)' },
+ bg: { rgb: 'rgb(255,238,204)' },
+ });
+ });
+
+ it('honors predefined style records from paste plugins', () => {
+ const node = document.createElement('span');
+
+ expect(extractNodeStyle(node, {
+ 'font-size': '11pt',
+ 'font-weight': 'bold',
+ 'text-decoration': 'line-through',
+ color: 'not-a-color',
+ })).toEqual({
+ fs: 11,
+ bl: BooleanNumber.TRUE,
+ st: { s: BooleanNumber.TRUE },
+ });
+ });
+
+ it.each([
+ ['s', { st: { s: BooleanNumber.TRUE } }],
+ ['u', { ul: { s: BooleanNumber.TRUE } }],
+ ['i', { it: BooleanNumber.TRUE }],
+ ['sup', { va: BaselineOffset.SUPERSCRIPT }],
+ ['sub', { va: BaselineOffset.SUBSCRIPT }],
+ ])('maps <%s> to spreadsheet text style', (tag, expected) => {
+ expect(extractNodeStyle(document.createElement(tag))).toEqual(expected);
+ });
+
+ it('prefers overline when pasted text decoration asks for it', () => {
+ const node = document.createElement('span');
+
+ expect(extractNodeStyle(node, {
+ 'text-decoration': 'overline',
+ })).toEqual({
+ ol: { s: BooleanNumber.TRUE },
+ });
+ });
+});
+
+describe('html-to-usm text body helpers', () => {
+ it('extracts paragraph spacing from pasted document blocks', () => {
+ const paragraph = document.createElement('p');
+ paragraph.setAttribute('style', 'margin-top: 6pt; margin-bottom: 8px; line-height: 1.4');
+
+ expect(getParagraphStyle(paragraph)).toEqual({
+ spaceAbove: { v: 8 },
+ spaceBelow: { v: 8 },
+ lineSpacing: 1.4,
+ });
+ });
+
+ it('returns no paragraph style when pasted blocks carry no supported paragraph CSS', () => {
+ const paragraph = document.createElement('p');
+ paragraph.setAttribute('style', 'color: red');
+
+ expect(getParagraphStyle(paragraph)).toBeNull();
+ });
+
+ it('creates paragraphs for every paragraph token and copies previous paragraph formatting', () => {
+ const previous: IParagraph = {
+ startIndex: 0,
+ paragraphId: 'previous',
+ bullet: { listId: 'list-1', listType: 'BULLET_LIST', nestingLevel: 0 },
+ paragraphStyle: { lineSpacing: 1.25 },
+ };
+
+ const paragraphs = generateParagraphs(`A${DataStreamTreeTokenType.PARAGRAPH}B${DataStreamTreeTokenType.PARAGRAPH}`, previous);
+
+ expect(paragraphs.map((paragraph) => ({
+ startIndex: paragraph.startIndex,
+ bullet: paragraph.bullet,
+ paragraphStyle: paragraph.paragraphStyle,
+ }))).toEqual([
+ {
+ startIndex: 1,
+ bullet: previous.bullet,
+ paragraphStyle: previous.paragraphStyle,
+ },
+ {
+ startIndex: 3,
+ bullet: previous.bullet,
+ paragraphStyle: previous.paragraphStyle,
+ },
+ ]);
+ expect(paragraphs[0].bullet).not.toBe(previous.bullet);
+ expect(paragraphs[0].paragraphStyle).not.toBe(previous.paragraphStyle);
+ });
+
+ it('promotes single full-length rich text run to cell style', () => {
+ const cell = {
+ p: createCellDocument('Total\r', [{ st: 0, ed: 6, ts: { bl: BooleanNumber.TRUE } }]),
+ };
+
+ expect(convertToCellStyle(cell, 'Total\r', cell.p!.body!.textRuns!)).toEqual({
+ p: {
+ id: 'paste-cell-doc',
+ body: {
+ dataStream: 'Total\r',
+ textRuns: [],
+ },
+ documentStyle: {},
+ },
+ s: { bl: BooleanNumber.TRUE },
+ });
+ });
+
+ it('keeps partial rich text runs inside the document body', () => {
+ const cell = {
+ p: createCellDocument('Total\r', [{ st: 0, ed: 5, ts: { bl: BooleanNumber.TRUE } }]),
+ };
+
+ expect(convertToCellStyle(cell, 'Total\r', cell.p!.body!.textRuns!)).toBe(cell);
+ });
+});
+
+describe('paste plugins for rich external HTML', () => {
+ it('recognizes Word HTML and carries bold block paragraph spacing into the document body', () => {
+ const bold = document.createElement('b');
+ bold.setAttribute('style', 'font-size: 10pt; color: #336699');
+ const paragraph = document.createElement('p');
+ paragraph.className = 'MsoNormal';
+ paragraph.setAttribute('style', 'margin-top: 3pt; margin-bottom: 5pt');
+ const plainParagraph = document.createElement('p');
+ plainParagraph.className = 'Normal';
+ const doc: IDocumentBody = {
+ dataStream: 'Heading',
+ textRuns: [],
+ paragraphs: [{ startIndex: 0, paragraphId: 'existing-word-paragraph' }],
+ };
+
+ WordPastePlugin.afterProcessRules[0].handler(doc, paragraph);
+
+ expect(WordPastePlugin.checkPasteType('<!-- copied from word -->')).toBe(true);
+ expect(WordPastePlugin.checkPasteType('<table><td>plain</td></table>')).toBe(false);
+ expect(checkElementFilter(WordPastePlugin.afterProcessRules[0].filter, paragraph)).toBe(true);
+ expect(checkElementFilter(WordPastePlugin.afterProcessRules[0].filter, plainParagraph)).toBe(false);
+ expect(WordPastePlugin.stylesRules[0].getStyle(bold)).toEqual({
+ bl: BooleanNumber.TRUE,
+ fs: 10,
+ cl: { rgb: 'rgb(51,102,153)' },
+ });
+ expect(doc.dataStream).toBe('Heading\r');
+ expect(doc.paragraphs?.map(({ startIndex, paragraphStyle }) => ({ startIndex, paragraphStyle }))).toEqual([
+ {
+ startIndex: 0,
+ paragraphStyle: undefined,
+ },
+ {
+ startIndex: 7,
+ paragraphStyle: {
+ spaceAbove: { v: 4 },
+ spaceBelow: { v: 6.666666666666667 },
+ },
+ },
+ ]);
+ });
+
+ it('recognizes Lark HTML and treats deleted text plus ace lines as rich document content', () => {
+ const deleted = document.createElement('s');
+ deleted.setAttribute('style', 'font-weight: 700; background-color: rgb(250, 240, 230)');
+ const line = document.createElement('div');
+ line.className = 'ace-line';
+ const plainLine = document.createElement('div');
+ plainLine.className = 'plain-line';
+ const doc: IDocumentBody = {
+ dataStream: 'First line',
+ textRuns: [],
+ paragraphs: [{ startIndex: 0, paragraphId: 'existing-lark-paragraph' }],
+ };
+
+ LarkPastePlugin.afterProcessRules[0].handler(doc, line);
+
+ expect(LarkPastePlugin.checkPasteType('<meta name="lark-record-clipboard">')).toBe(true);
+ expect(LarkPastePlugin.checkPasteType('<p>plain</p>')).toBe(false);
+ expect(checkElementFilter(LarkPastePlugin.afterProcessRules[0].filter, line)).toBe(true);
+ expect(checkElementFilter(LarkPastePlugin.afterProcessRules[0].filter, plainLine)).toBe(false);
+ expect(LarkPastePlugin.stylesRules[0].getStyle(deleted)).toEqual({
+ st: { s: BooleanNumber.TRUE },
+ bl: BooleanNumber.TRUE,
+ bg: { rgb: 'rgb(250,240,230)' },
+ });
+ expect(doc.dataStream).toBe('First line\r');
+ expect(doc.paragraphs?.map(({ startIndex }) => startIndex)).toEqual([0, 10]);
+ });
+
+ it('recognizes Univer HTML and preserves paragraph style on UniverNormal paragraphs', () => {
+ const paragraph = document.createElement('p');
+ paragraph.className = 'UniverNormal';
+ paragraph.setAttribute('style', 'line-height: 1.6');
+ const wordParagraph = document.createElement('p');
+ wordParagraph.className = 'MsoNormal';
+ const doc: IDocumentBody = {
+ dataStream: 'Sheet note',
+ textRuns: [],
+ paragraphs: [{ startIndex: 0, paragraphId: 'existing-univer-paragraph' }],
+ };
+
+ UniverPastePlugin.afterProcessRules[0].handler(doc, paragraph);
+
+ expect(UniverPastePlugin.checkPasteType('<p class="UniverNormal">value</p>')).toBe(true);
+ expect(UniverPastePlugin.checkPasteType('<p class="MsoNormal">value</p>')).toBe(false);
+ expect(checkElementFilter(UniverPastePlugin.afterProcessRules[0].filter, paragraph)).toBe(true);
+ expect(checkElementFilter(UniverPastePlugin.afterProcessRules[0].filter, wordParagraph)).toBe(false);
+ expect(doc.dataStream).toBe('Sheet note\r');
+ expect(doc.paragraphs?.map(({ startIndex, paragraphStyle }) => ({ startIndex, paragraphStyle }))).toEqual([
+ {
+ startIndex: 0,
+ paragraphStyle: undefined,
+ },
+ {
+ startIndex: 10,
+ paragraphStyle: {
+ lineSpacing: 1.6,
+ },
+ },
+ ]);
+ });
});
diff --git a/packages/sheets-ui/src/services/editor/__tests__/cell-editor-manager.service.spec.ts b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-manager.service.spec.ts
index c045c67fc3..b8e7103880 100644
--- a/packages/sheets-ui/src/services/editor/__tests__/cell-editor-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-manager.service.spec.ts
@@ -42,5 +42,11 @@ describe('CellEditorManagerService', () => {
expect(states.at(-1)).toEqual({ show: true, startX: 20, startY: 40, endX: 100, endY: 70 });
expect(rects.at(-1)).toEqual({ left: 10, top: 20, width: 100, height: 30 });
expect(focus).toEqual([false, true]);
+ expect(service.getState()).toEqual({ show: true, startX: 20, startY: 40, endX: 100, endY: 70 });
+ expect(service.getRect()).toEqual({ left: 10, top: 20, width: 100, height: 30 });
+
+ service.dispose();
+ expect(service.getState()).toBeNull();
+ expect(service.getRect()).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.ts
index a0ae500945..36ddd9a1b3 100644
--- 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.ts
@@ -19,6 +19,8 @@ import {
ConfigService,
ContextService,
DesktopLogService,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ HorizontalAlign,
ICommandService,
IConfigService,
IContextService,
@@ -29,17 +31,210 @@ import {
LocalUndoRedoService,
ThemeService,
UniverInstanceService,
+ UniverInstanceType,
+ VerticalAlign,
+ WrapStrategy,
} from '@univerjs/core';
-import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocSelectionManagerService, DocSkeletonManagerService } 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 { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
import { CellEditorManagerService, ICellEditorManagerService } from '../cell-editor-manager.service';
import { SheetCellEditorResizeService } from '../cell-editor-resize.service';
+class TestLayoutService {
+ getContentElement() {
+ return {
+ getBoundingClientRect: () => ({ left: 10, top: 20 }),
+ };
+ }
+}
+
+class TestCellEditorManagerService {
+ private _state: Record<string, number | boolean> | null = null;
+
+ setState(state: Record<string, number | boolean>) {
+ this._state = state;
+ }
+
+ getState() {
+ return this._state;
+ }
+}
+
+class TestEditorBridgeService {
+ refreshCount = 0;
+
+ readonly editCellState = {
+ unitId: 'unit-1',
+ sheetId: 'sheet-1',
+ row: 1,
+ column: 1,
+ position: {
+ startX: 100,
+ startY: 60,
+ endX: 160,
+ endY: 84,
+ },
+ canvasOffset: {
+ left: 0,
+ top: 0,
+ },
+ scaleX: 1,
+ scaleY: 1,
+ documentLayoutObject: {
+ textRotation: undefined,
+ wrapStrategy: WrapStrategy.UNSPECIFIED,
+ verticalAlign: VerticalAlign.TOP,
+ horizontalAlign: HorizontalAlign.LEFT,
+ paddingData: {
+ l: 4,
+ r: 6,
+ t: 3,
+ b: 5,
+ },
+ fill: '#fff',
+ },
+ };
+
+ getEditCellState() {
+ return this.editCellState;
+ }
+
+ isVisible() {
+ return { visible: true };
+ }
+
+ refreshEditCellPosition() {
+ this.refreshCount += 1;
+ }
+
+ getCurrentEditorId() {
+ return DOCS_NORMAL_EDITOR_UNIT_ID_KEY;
+ }
+}
+
+class TestUniverInstanceService {
+ readonly documentModel = {
+ pageSize: 0,
+ margin: {},
+ renderConfig: {},
+ updateDocumentDataPageSize: (pageSize: number) => {
+ this.documentModel.pageSize = pageSize;
+ },
+ updateDocumentDataMargin: (margin: Record<string, number | undefined>) => {
+ this.documentModel.margin = margin;
+ },
+ updateDocumentRenderConfig: (renderConfig: Record<string, unknown>) => {
+ this.documentModel.renderConfig = renderConfig;
+ },
+ };
+
+ getUnit(unitId: string) {
+ return unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY ? this.documentModel : null;
+ }
+
+ getCurrentUnitOfType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET
+ ? { getUnitId: () => 'unit-1' }
+ : null;
+ }
+}
+
+class TestRenderManagerService {
+ readonly sheetCanvasElement = {
+ style: { width: '800px' },
+ getBoundingClientRect: () => ({ left: 30, top: 50, width: 800, height: 600 }),
+ };
+
+ readonly sheetEngine = {
+ width: 800,
+ getCanvasElement: () => this.sheetCanvasElement,
+ };
+
+ readonly editorEngine = {
+ resized: null as null | { width: number; height: number },
+ resizeBySize: (width: number, height: number) => {
+ this.editorEngine.resized = { width, height };
+ },
+ };
+
+ readonly editorDocument = {
+ resized: null as null | { width: number; height: number },
+ resize: (width: number, height: number) => {
+ this.editorDocument.resized = { width, height };
+ },
+ };
+
+ readonly editorScene = {
+ transformed: null as null | Record<string, number>,
+ background: null as null | unknown,
+ getViewport: () => ({
+ getScrollBar: () => null,
+ scrollToViewportPos: () => { },
+ }),
+ getObject: () => null,
+ addObjects: (objects: unknown[]) => {
+ this.editorScene.background = objects[0];
+ },
+ getPrecisionScale: () => ({ scaleX: 1, scaleY: 1 }),
+ transformByState: (state: Record<string, number>) => {
+ this.editorScene.transformed = state;
+ },
+ };
+
+ readonly docSkeleton = {
+ calculate: () => { },
+ getActualSize: () => ({ actualWidth: 120, actualHeight: 36 }),
+ };
+
+ getRenderById(unitId: string) {
+ if (unitId === 'unit-1') {
+ return {
+ engine: this.sheetEngine,
+ with: (dependency: unknown) => {
+ if (dependency === SheetSkeletonManagerService) {
+ return {
+ getSkeletonParam: () => ({
+ skeleton: {
+ getCellWithCoordByIndex: () => ({
+ mergeInfo: {
+ startX: 100,
+ startY: 60,
+ endX: 160,
+ endY: 84,
+ },
+ }),
+ },
+ }),
+ };
+ }
+ },
+ };
+ }
+
+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return {
+ mainComponent: this.editorDocument,
+ scene: this.editorScene,
+ engine: this.editorEngine,
+ components: new Map(),
+ with: (dependency: unknown) => {
+ if (dependency === DocSkeletonManagerService) {
+ return {
+ getSkeleton: () => this.docSkeleton,
+ };
+ }
+ },
+ };
+ }
+ }
+}
+
describe('SheetCellEditorResizeService', () => {
afterEach(() => {
vi.unstubAllGlobals();
@@ -73,4 +268,126 @@ describe('SheetCellEditorResizeService', () => {
expect(callbackCalled).toBe(false);
});
+
+ it('expands the active cell editor to fit rendered text content', async () => {
+ vi.stubGlobal('window', new EventTarget());
+ vi.stubGlobal('document', { activeElement: { dataset: {} } });
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);
+ injector.add([ThemeService]);
+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetSkeletonService]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([ICellEditorManagerService, { useClass: TestCellEditorManagerService as never }]);
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([SheetCellEditorResizeService]);
+
+ let callbackCalled = false;
+ injector.get(SheetCellEditorResizeService).fitTextSize(() => {
+ callbackCalled = true;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const editorManager = injector.get(ICellEditorManagerService) as unknown as TestCellEditorManagerService;
+ const renderManager = injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ expect(editorManager.getState()).toEqual(expect.objectContaining({
+ startX: 120,
+ startY: 90,
+ endX: 250,
+ endY: 134,
+ show: true,
+ }));
+ expect(renderManager.editorDocument.resized).toEqual({ width: 130, height: 44 });
+ expect(renderManager.editorEngine.resized).toEqual({ width: 130, height: 44 });
+ expect(callbackCalled).toBe(true);
+ });
+
+ it('refits the editor when its container size drifts from the edited cell', async () => {
+ vi.stubGlobal('window', new EventTarget());
+ vi.stubGlobal('document', { activeElement: { dataset: {} } });
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);
+ injector.add([ThemeService]);
+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetSkeletonService]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([ICellEditorManagerService, { useClass: TestCellEditorManagerService as never }]);
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([SheetCellEditorResizeService]);
+ const editorManager = injector.get(ICellEditorManagerService) as unknown as TestCellEditorManagerService;
+ editorManager.setState({
+ startX: 100,
+ startY: 60,
+ endX: 120,
+ endY: 70,
+ show: true,
+ });
+
+ let callbackCalled = false;
+ injector.get(SheetCellEditorResizeService).resizeCellEditor(() => {
+ callbackCalled = true;
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const editorBridgeService = injector.get(IEditorBridgeService) as unknown as TestEditorBridgeService;
+ expect(editorBridgeService.refreshCount).toBeGreaterThanOrEqual(2);
+ expect(editorManager.getState()).toEqual(expect.objectContaining({
+ endX: 250,
+ endY: 134,
+ show: true,
+ }));
+ expect(callbackCalled).toBe(true);
+ });
+
+ it('positions expanded editor content according to cell alignment', async () => {
+ vi.stubGlobal('window', new EventTarget());
+ vi.stubGlobal('document', { activeElement: { dataset: {} } });
+ const injector = new Injector();
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([ICommandService, { useClass: CommandService }]);
+ injector.add([IUndoRedoService, { useClass: LocalUndoRedoService }]);
+ injector.add([ThemeService]);
+ injector.add([ILayoutService, { useClass: TestLayoutService as never }]);
+ injector.add([DocSelectionManagerService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetSkeletonService]);
+ injector.add([IEditorService, { useClass: EditorService }]);
+ injector.add([ICellEditorManagerService, { useClass: TestCellEditorManagerService as never }]);
+ injector.add([IEditorBridgeService, { useClass: TestEditorBridgeService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([SheetCellEditorResizeService]);
+ const editorBridge = injector.get(IEditorBridgeService) as unknown as TestEditorBridgeService;
+ editorBridge.editCellState.documentLayoutObject.verticalAlign = VerticalAlign.MIDDLE;
+ editorBridge.editCellState.documentLayoutObject.horizontalAlign = HorizontalAlign.RIGHT;
+
+ injector.get(SheetCellEditorResizeService).fitTextSize();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ const editorManager = injector.get(ICellEditorManagerService) as unknown as TestCellEditorManagerService;
+ expect(editorManager.getState()).toEqual(expect.objectContaining({
+ startX: 50,
+ startY: 90,
+ endX: 180,
+ show: true,
+ }));
+ });
});
diff --git a/packages/sheets-ui/src/services/editor/__tests__/formula-editor-manager.service.spec.ts b/packages/sheets-ui/src/services/editor/__tests__/formula-editor-manager.service.spec.ts
index 15b199f76b..e16cea61b3 100644
--- a/packages/sheets-ui/src/services/editor/__tests__/formula-editor-manager.service.spec.ts
+++ b/packages/sheets-ui/src/services/editor/__tests__/formula-editor-manager.service.spec.ts
@@ -19,12 +19,12 @@ import { beforeEach, describe, expect, it } from 'vitest';
import { FormulaEditorManagerService, IFormulaEditorManagerService } from '../formula-editor-manager.service';
describe('FormulaEditorManagerService', () => {
- let service: IFormulaEditorManagerService;
+ let service: FormulaEditorManagerService;
beforeEach(() => {
const injector = new Injector();
injector.add([IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }]);
- service = injector.get(IFormulaEditorManagerService);
+ service = injector.get(IFormulaEditorManagerService) as FormulaEditorManagerService;
});
it('publishes formula editor position and toolbar button interactions', () => {
@@ -47,5 +47,9 @@ describe('FormulaEditorManagerService', () => {
expect(focus).toEqual([false, true]);
expect(fxClicks).toEqual([true]);
expect(foldClicks).toEqual([false]);
+ expect(service.getPosition()).toBe(rect);
+
+ service.dispose();
+ expect(service.getPosition()).toBeNull();
});
});
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.ts
index 4aa6549473..aaeee34d9a 100644
--- 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.ts
@@ -25,32 +25,49 @@ import {
UniverInstanceService,
Workbook,
} from '@univerjs/core';
-import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
import { SheetSkeletonService } from '@univerjs/sheets';
import { describe, expect, it } from 'vitest';
+import { createFakeScene, createFakeSkeleton, createFakeViewport } from '../../../controllers/render-controllers/__tests__/render-test-bed';
import { IMarkSelectionService, MarkSelectionService } from '../mark-selection.service';
-function createService(): IMarkSelectionService {
+class TestSheetSkeletonService {
+ readonly skeleton = createFakeSkeleton();
+
+ getSkeleton() {
+ return this.skeleton;
+ }
+}
+
+class TestRenderManagerService {
+ readonly scene = createFakeScene(new Map([[SHEET_VIEWPORT_KEY.VIEW_MAIN, createFakeViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)]]));
+
+ getRenderById() {
+ return { scene: this.scene };
+ }
+}
+
+function createService(workbookData = {
+ id: 'unit-1',
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ },
+ },
+ sheetOrder: ['sheet-1'],
+}): 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([SheetSkeletonService, { useClass: TestSheetSkeletonService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
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'],
- });
+ const workbook = injector.createInstance(Workbook, workbookData);
univerInstanceService.__addUnit(workbook);
- univerInstanceService.focusUnit('unit-1');
+ univerInstanceService.focusUnit(workbookData.id);
return injector.get(IMarkSelectionService);
}
@@ -74,4 +91,40 @@ describe('MarkSelectionService', () => {
service.removeShape(id!);
expect(service.getShapeMap().size).toBe(0);
});
+
+ it('refreshes marked selections for the active sheet and clears rendered controls', () => {
+ const service = createService();
+ const selection = {
+ range: { startRow: 1, endRow: 2, startColumn: 3, endColumn: 4 },
+ primary: null,
+ };
+
+ const firstId = service.addShape(selection as never);
+ const secondId = service.addShapeWithNoFresh({
+ range: { startRow: 4, endRow: 4, startColumn: 1, endColumn: 1 },
+ primary: null,
+ } as never);
+
+ expect(service.getShapeMap().get(firstId!)?.control?.getRange()).toMatchObject({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+ });
+ expect(service.getShapeMap().get(secondId!)?.control).toBeNull();
+
+ service.refreshShapes();
+ expect(service.getShapeMap().get(secondId!)?.control?.getRange()).toMatchObject({
+ startRow: 4,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 1,
+ });
+
+ service.removeShape('missing');
+ expect(service.getShapeMap().size).toBe(2);
+
+ service.removeAllShapes();
+ 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.ts
index 3be2e73809..08dcca37dc 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
@@ -18,6 +18,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 { SheetPermissionPanelModel } from '../sheet-permission-panel.model';
import { SheetPermissionUserManagerService } from '../sheet-permission-user-list.service';
const OWNER: ICollaborator = {
@@ -77,3 +78,19 @@ describe('SheetPermissionUserManagerService', () => {
expect(await resetSelectedUsers).toEqual([]);
});
});
+
+describe('SheetPermissionPanelModel', () => {
+ it('tracks whether the permission panel should be visible', () => {
+ const injector = new Injector();
+ injector.add([SheetPermissionPanelModel]);
+ const model = injector.get(SheetPermissionPanelModel);
+
+ expect(model.getVisible()).toBe(false);
+
+ model.setVisible(true);
+ expect(model.getVisible()).toBe(true);
+
+ model.reset();
+ expect(model.getVisible()).toBe(false);
+ });
+});
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.ts
index 9d2d5c6097..7980aa84f9 100644
--- 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.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
import {
CommandService,
ConfigService,
@@ -25,11 +25,22 @@ import {
IContextService,
ILogService,
Injector,
+ RANGE_TYPE,
ThemeService,
} from '@univerjs/core';
+import { ScrollTimerType, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { REF_SELECTIONS_ENABLED, SELECTIONS_ENABLED } from '@univerjs/sheets';
import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ createFakeEngine,
+ createFakeScene,
+ createFakeSkeleton,
+ createFakeViewport,
+} from '../../../controllers/render-controllers/__tests__/render-test-bed';
+import { SheetSkeletonManagerService } from '../../sheet-skeleton-manager.service';
import { BaseSelectionRenderService } from '../base-selection-render.service';
+import { SelectionLayer } from '../selection-layer';
class TestSelectionRenderService extends BaseSelectionRenderService {
emitMoving() {
@@ -39,31 +50,210 @@ class TestSelectionRenderService extends BaseSelectionRenderService {
emitMoveEnd() {
this._selectionMoveEnd$.next([]);
}
+
+ changeRuntimeForTest(options?: { freeze?: { startRow: number; startColumn: number; xSplit: number; ySplit: number } }) {
+ const skeleton = createSelectionSkeleton(options?.freeze);
+ TestSheetSkeletonManagerService.skeleton = skeleton;
+ const scene = createFakeScene(new Map([
+ [SHEET_VIEWPORT_KEY.VIEW_MAIN, createFakeViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN)],
+ [SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP, createFakeViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP)],
+ [SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP, createFakeViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)],
+ [SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT, createFakeViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)],
+ ]));
+ this._changeRuntime(skeleton as never, scene as never);
+ return { skeleton, scene };
+ }
+
+ getViewportByCellForTest(row?: number, column?: number) {
+ return this._getViewportByCell(row, column);
+ }
+
+ getSelectionByOffsetForTest(offsetX: number, offsetY: number, rangeType = RANGE_TYPE.NORMAL) {
+ this._rangeType = rangeType;
+ return this._getSelectionWithCoordByOffset(offsetX, offsetY, 1, 1, { x: 0, y: 0 });
+ }
+
+ moveSelectionForTest(offsetX: number, offsetY: number, rangeType = RANGE_TYPE.NORMAL) {
+ const activeControl = this.getActiveSelectionControl();
+ this._startRangeWhenPointerDown = activeControl!.model as never;
+ this._startViewportPosX = 0;
+ this._startViewportPosY = 0;
+ this._movingHandler(offsetX, offsetY, activeControl, rangeType);
+ }
+
+ listenPointerMoveForTest(rangeType = RANGE_TYPE.NORMAL) {
+ const activeControl = this.getActiveSelectionControl()!;
+ this._startRangeWhenPointerDown = activeControl.model as never;
+ this._startViewportPosX = 0;
+ this._startViewportPosY = 0;
+ this._setupPointerMoveListener(
+ this._scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN),
+ activeControl,
+ rangeType,
+ ScrollTimerType.ALL,
+ 0,
+ 0
+ );
+ }
+
+ checkClearPreviousControlsForTest(evt: { ctrlKey?: boolean; shiftKey?: boolean }) {
+ this._checkClearPreviousControls(evt as never);
+ }
+
+ setSingleModeForTest(enabled: boolean) {
+ this.setSingleSelectionEnabled(enabled);
+ }
+
+ extendSelectionFromActiveToTest(row: number, column: number) {
+ const activeControl = this.getActiveSelectionControl()!;
+ const currentCell = (this._skeleton as never as {
+ getCellWithCoordByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ }).getCellWithCoordByOffset(column * 100, row * 20, 1, 1, { x: 0, y: 0 });
+ this._makeSelectionByTwoCells(currentCell as never, activeControl.model as never, this._skeleton, RANGE_TYPE.NORMAL, activeControl);
+ }
+
+ addExternalEndingListenersForTest(activeScene: { onPointerDown$: unknown; onPointerUp$: unknown }) {
+ (this._scene as never as { getEngine: () => { activeScene: unknown } }).getEngine = () => ({ activeScene });
+ this._addEndingListeners();
+ }
}
+class TestSheetSkeletonManagerService {
+ static skeleton = createSelectionSkeleton();
+
+ getCurrentParam() {
+ return {
+ unitId: 'test',
+ sheetId: 'sheet1',
+ skeleton: TestSheetSkeletonManagerService.skeleton,
+ };
+ }
+}
+
+function createSelectionSkeleton(freeze = { startRow: 0, startColumn: 0, xSplit: 0, ySplit: 0 }) {
+ const skeleton = createFakeSkeleton({
+ getWorksheetConfig: () => ({ freeze }),
+ });
+ const withCellMeta = (row: number, column: number) => {
+ const coord = skeleton.getNoMergeCellWithCoordByIndex(row, column);
+ return {
+ ...coord,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ ...coord,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ },
+ };
+ };
+
+ (skeleton as never as {
+ getCellWithCoordByOffset: (
+ x: number,
+ y: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ) => unknown;
+ getCellByOffset: (
+ x: number,
+ y: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ) => unknown;
+ expandRangeByMerge: <T>(range: T) => T;
+ }).getCellWithCoordByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ return withCellMeta(row, column);
+ };
+ (skeleton as never as {
+ getCellByOffset: (
+ x: number,
+ y: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number }
+ ) => unknown;
+ }).getCellByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ return withCellMeta(row, column);
+ };
+ (skeleton as never as { expandRangeByMerge: <T>(range: T) => T }).expandRangeByMerge = (range) => range;
+
+ return skeleton;
+}
+
+function createSelectionRenderService() {
+ 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]);
+ injector.add([SheetSkeletonManagerService, { useClass: TestSheetSkeletonManagerService as never }]);
+
+ const contextService = injector.get(IContextService);
+ contextService.setContextValue(SELECTIONS_ENABLED, true);
+ contextService.setContextValue(REF_SELECTIONS_ENABLED, false);
+
+ const service = injector.createInstance(
+ TestSelectionRenderService,
+ injector,
+ injector.get(ThemeService),
+ injector.get(IShortcutService),
+ injector.get(SheetSkeletonManagerService),
+ contextService
+ );
+
+ return { injector, contextService, service };
+}
+
+function createSelection(range: ISelectionWithStyle['range']): ISelectionWithStyle {
+ return {
+ range,
+ primary: {
+ actualRow: range.startRow,
+ actualColumn: range.startColumn,
+ startRow: range.startRow,
+ endRow: range.startRow,
+ startColumn: range.startColumn,
+ endColumn: range.startColumn,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ };
+}
+
+function viewportKey(viewport: unknown) {
+ return (viewport as { viewportKey?: string } | null)?.viewportKey;
+}
+
+const selections: ISelectionWithStyle[] = [
+ createSelection({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL }),
+ createSelection({ startRow: 2, endRow: 3, startColumn: 2, endColumn: 4, rangeType: RANGE_TYPE.NORMAL }),
+];
+
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)
- );
+ const { service } = createSelectionRenderService();
service.emitMoving();
expect(service.selectionMoving).toBe(true);
@@ -71,4 +261,218 @@ describe('BaseSelectionRenderService', () => {
service.emitMoveEnd();
expect(service.selectionMoving).toBe(false);
});
+
+ it('resets rendered selection controls from workbook selection data', () => {
+ const { contextService, service } = createSelectionRenderService();
+ service.changeRuntimeForTest();
+
+ service.resetSelectionsByModelData(selections);
+ expect(service.getSelectionControls()).toHaveLength(2);
+ expect(service.getActiveRange()).toEqual({
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ });
+
+ service.setActiveSelectionIndex(0);
+ expect(service.getActiveSelectionControl()?.getRange()).toMatchObject({
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ });
+
+ service.resetActiveSelectionIndex();
+ service.resetSelectionsByModelData([selections[0]]);
+ expect(service.getSelectionControls()).toHaveLength(1);
+ expect(service.getSelectionDataWithStyle()[0].rangeWithCoord).toMatchObject({
+ unitId: 'test',
+ sheetId: 'sheet1',
+ startRow: 1,
+ startColumn: 1,
+ });
+
+ contextService.setContextValue(SELECTIONS_ENABLED, false);
+ service.resetSelectionsByModelData(selections);
+ expect(service.getSelectionControls()).toHaveLength(1);
+ expect(service.isSelectionDisabled()).toBe(true);
+ expect(service.inRefSelectionMode()).toBe(false);
+ });
+
+ it('chooses the visible viewport for frozen row and column selections', () => {
+ const { service } = createSelectionRenderService();
+ service.changeRuntimeForTest({
+ freeze: { startRow: 2, startColumn: 2, xSplit: 0, ySplit: 0 },
+ });
+
+ expect(service.getViewportByCellForTest()).toBeNull();
+ expect(viewportKey(service.getViewportByCellForTest(3, 3))).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ expect(viewportKey(service.getViewportByCellForTest(1, 1))).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);
+ expect(viewportKey(service.getViewportByCellForTest(1, 3))).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);
+ expect(viewportKey(service.getViewportByCellForTest(3, 1))).toBe(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT);
+ });
+
+ it('converts pointer offsets into sheet cells and expands an active selection while dragging', () => {
+ const { service } = createSelectionRenderService();
+ service.changeRuntimeForTest();
+ service.resetSelectionsByModelData([selections[0]]);
+
+ expect(service.getCellWithCoordByOffset(250, 45)).toMatchObject({
+ actualRow: 2,
+ actualColumn: 2,
+ startRow: 2,
+ startColumn: 2,
+ });
+ expect(service.getSelectionByOffsetForTest(250, 45)).toMatchObject({
+ rangeWithCoord: {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 2,
+ endColumn: 2,
+ },
+ });
+ expect(service.getSelectionByOffsetForTest(250, 45, RANGE_TYPE.ROW)).toMatchObject({
+ rangeWithCoord: {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 2,
+ endColumn: 2,
+ },
+ });
+
+ const movingSelections: unknown[] = [];
+ service.selectionMoving$.subscribe((selection) => movingSelections.push(selection));
+ service.moveSelectionForTest(350, 65);
+
+ expect(service.getActiveRange()).toEqual({
+ startRow: 1,
+ startColumn: 1,
+ endRow: 3,
+ endColumn: 3,
+ });
+ expect(movingSelections).toHaveLength(1);
+ });
+
+ it('emits finalized selection data and clears active drag listeners when selection ends', () => {
+ const { service } = createSelectionRenderService();
+ service.changeRuntimeForTest();
+ service.resetSelectionsByModelData([selections[0]]);
+
+ const finalizedSelections: unknown[] = [];
+ service.selectionMoveEnd$.subscribe((selection) => finalizedSelections.push(selection));
+ service.moveSelectionForTest(250, 45);
+ service.endSelection();
+
+ expect(finalizedSelections[finalizedSelections.length - 1]).toMatchObject([{
+ rangeWithCoord: {
+ unitId: 'test',
+ sheetId: 'sheet1',
+ startRow: 1,
+ startColumn: 1,
+ endRow: 2,
+ endColumn: 2,
+ },
+ }]);
+ expect(service.selectionMoving).toBe(false);
+ });
+
+ it('preserves existing selections for additive selection gestures and clears them for single-selection gestures', () => {
+ const { service } = createSelectionRenderService();
+ service.changeRuntimeForTest();
+ service.resetSelectionsByModelData(selections);
+
+ service.checkClearPreviousControlsForTest({ ctrlKey: true });
+ expect(service.getSelectionControls()).toHaveLength(2);
+
+ service.checkClearPreviousControlsForTest({ shiftKey: true });
+ expect(service.getSelectionControls()).toHaveLength(2);
+
+ service.setSingleModeForTest(true);
+ service.checkClearPreviousControlsForTest({ ctrlKey: true });
+ expect(service.getSelectionControls()).toHaveLength(0);
+ });
+
+ it('expands the active selection between the anchor cell and the current pointer cell', () => {
+ const { service } = createSelectionRenderService();
+ service.changeRuntimeForTest();
+ service.resetSelectionsByModelData([selections[0]]);
+
+ service.extendSelectionFromActiveToTest(4, 5);
+
+ expect(service.getActiveRange()).toEqual({
+ startRow: 1,
+ startColumn: 1,
+ endRow: 4,
+ endColumn: 5,
+ });
+ });
+
+ it('updates the active selection through the pointer-move listener during drag', () => {
+ const { service } = createSelectionRenderService();
+ const { scene } = service.changeRuntimeForTest();
+ service.resetSelectionsByModelData([selections[0]]);
+ const movingSelections: unknown[] = [];
+ service.selectionMoving$.subscribe((selection) => movingSelections.push(selection));
+
+ service.listenPointerMoveForTest();
+ (scene.onPointerMove$ as unknown as { emit: (evt: unknown, state?: unknown) => void }).emit({
+ offsetX: 350,
+ offsetY: 65,
+ });
+
+ expect(service.getActiveRange()).toEqual({
+ startRow: 1,
+ startColumn: 1,
+ endRow: 3,
+ endColumn: 3,
+ });
+ expect(movingSelections.length).toBeGreaterThan(0);
+ });
+
+ it('cancels an in-progress selection when another scene receives a pointer event', () => {
+ const { service } = createSelectionRenderService();
+ const { scene } = service.changeRuntimeForTest();
+ const activeScene = {
+ onPointerDown$: {
+ subscribeEvent: (listener: () => void) => {
+ (activeScene as never as { pointerDown: () => void }).pointerDown = listener;
+ return { unsubscribe: () => { }, dispose: () => { } };
+ },
+ },
+ onPointerUp$: {
+ subscribeEvent: (listener: () => void) => {
+ (activeScene as never as { pointerUp: () => void }).pointerUp = listener;
+ return { unsubscribe: () => { }, dispose: () => { } };
+ },
+ },
+ };
+ let objectsEventEnabled = false;
+ (scene as never as { enableObjectsEvent: () => void }).enableObjectsEvent = () => {
+ objectsEventEnabled = true;
+ };
+
+ service.addExternalEndingListenersForTest(activeScene);
+ (activeScene as never as { pointerDown: () => void }).pointerDown();
+
+ expect(objectsEventEnabled).toBe(true);
+ });
+
+ it('reports selection layer render timing after a render pass', () => {
+ const injector = new Injector();
+ const engine = createFakeEngine();
+ const scene = createFakeScene(new Map(), { engine });
+ const metrics: Array<[string, number]> = [];
+ engine.renderFrameTimeMetric$.subscribe((metric) => metrics.push(metric));
+ const layer = injector.createInstance(SelectionLayer, scene as never, [], 7);
+ const ctx = {
+ save: () => { },
+ restore: () => { },
+ };
+
+ expect(layer.render(ctx as never)).toBe(layer);
+
+ expect(metrics[0][0]).toBe('selectionLayer');
+ expect(metrics[0][1]).toBeGreaterThanOrEqual(0);
+ });
});
diff --git a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
index 813a3fa638..a82f9dc450 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/mobile-selection-render.service.spec.ts
@@ -14,11 +14,149 @@
* limitations under the License.
*/
-import { RANGE_TYPE } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
-import { shouldKeepCurrentSelectionOnMobileLongPress } from '../mobile-selection-render.service';
+import { Injector, RANGE_TYPE, ThemeService } from '@univerjs/core';
+import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { SetSelectionsOperation } from '@univerjs/sheets';
+import { IShortcutService } from '@univerjs/ui';
+import { BehaviorSubject } from 'rxjs';
+import { beforeAll, describe, expect, it } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import {
+ createFakeScene,
+ createFakeSkeleton,
+ createFakeViewport,
+ createRenderTestBed,
+ createTestEvent,
+} from '../../../controllers/render-controllers/__tests__/render-test-bed';
+import { SheetScrollManagerService } from '../../scroll-manager.service';
+import { MobileSheetsSelectionRenderService, shouldKeepCurrentSelectionOnMobileLongPress } from '../mobile-selection-render.service';
+import { MobileSelectionControl } from '../mobile-selection-shape';
+
+class TestThemeService {
+ getColorFromTheme(key: string) {
+ return key === 'white' ? '#ffffff' : '#3b82f6';
+ }
+}
+
+class TestShortcutService {
+ forceEscape() {
+ return { dispose: () => { } };
+ }
+}
+
+class TestSheetScrollManagerService {
+ readonly validViewportScrollInfo$ = new BehaviorSubject<{ viewportScrollX: number; viewportScrollY: number } | null>(null);
+}
+
+function createMobileControl(rangeType: RANGE_TYPE) {
+ const injector = new Injector();
+ injector.add([ThemeService, { useClass: TestThemeService }]);
+ const viewport = createFakeViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ const scene = createFakeScene(new Map([[SHEET_VIEWPORT_KEY.VIEW_MAIN, viewport]]));
+ const skeleton = createFakeSkeleton();
+ const control = injector.createInstance(
+ MobileSelectionControl,
+ scene as never,
+ 1,
+ injector.get(ThemeService),
+ {
+ rowHeaderWidth: skeleton.rowHeaderWidth,
+ columnHeaderHeight: skeleton.columnHeaderHeight,
+ rangeType,
+ }
+ );
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 3,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ startY: 20,
+ endX: 300,
+ endY: 80,
+ rangeType,
+ },
+ primaryWithCoord: {
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ },
+ },
+ style: null,
+ }, skeleton as never);
+
+ return control;
+}
+
+function installCellLookupForMobileSelection(skeleton: ReturnType<typeof createFakeSkeleton>) {
+ const cellWithMeta = (row: number, column: number) => {
+ const cell = skeleton.getNoMergeCellWithCoordByIndex(row, column);
+ return {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ },
+ };
+ };
+ (skeleton as never as {
+ getCellByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ getCellWithCoordByIndex: (row: number, column: number) => unknown;
+ getCellWithCoordByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ getColumnCount: () => number;
+ getRowCount: () => number;
+ expandRangeByMerge: <T>(range: T) => T;
+ }).getCellByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ return cellWithMeta(row, column);
+ };
+ (skeleton as never as { getCellWithCoordByIndex: (row: number, column: number) => unknown }).getCellWithCoordByIndex = cellWithMeta;
+ (skeleton as never as {
+ getCellWithCoordByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ }).getCellWithCoordByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ return cellWithMeta(row, column);
+ };
+ (skeleton as never as { getColumnCount: () => number }).getColumnCount = () => skeleton.worksheet.getColumnCount();
+ (skeleton as never as { getRowCount: () => number }).getRowCount = () => skeleton.worksheet.getRowCount();
+ (skeleton as never as { expandRangeByMerge: <T>(range: T) => T }).expandRangeByMerge = (range) => range;
+}
describe('shouldKeepCurrentSelectionOnMobileLongPress', () => {
+ beforeAll(() => {
+ globalThis.window = {
+ cancelAnimationFrame: () => { },
+ requestAnimationFrame: () => 1,
+ } as unknown as Window & typeof globalThis;
+ });
+
it('keeps the existing selection when long press is inside it', () => {
expect(shouldKeepCurrentSelectionOnMobileLongPress([
{
@@ -79,4 +217,288 @@ describe('shouldKeepCurrentSelectionOnMobileLongPress', () => {
rangeType: RANGE_TYPE.NORMAL,
})).toBe(true);
});
+
+ it('positions mobile expand handles on normal selections', () => {
+ const control = createMobileControl(RANGE_TYPE.NORMAL);
+
+ expect(control.fillControlTopLeft?.visible).toBe(true);
+ expect(control.fillControlBottomRight?.visible).toBe(true);
+ expect(control.fillControlTopLeft?.left).toBeLessThan(0);
+ expect(control.fillControlBottomRight?.left).toBeGreaterThan(0);
+ expect(control.getViewportMainScrollInfo()).toMatchObject({
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ width: 800,
+ height: 600,
+ });
+ });
+
+ it('keeps row and column expand handles inside the visible sheet body', () => {
+ const rowControl = createMobileControl(RANGE_TYPE.ROW);
+ rowControl.transformControlPoint(900, 0, 500, 500);
+ expect(rowControl.rangeType).toBe(RANGE_TYPE.ROW);
+ expect(rowControl.fillControlTopLeft?.left).toBeLessThanOrEqual(500);
+ expect(rowControl.fillControlBottomRight?.top).toBeGreaterThan(rowControl.fillControlTopLeft?.top ?? 0);
+
+ const columnControl = createMobileControl(RANGE_TYPE.COLUMN);
+ columnControl.transformControlPoint(0, 900, 500, 300);
+ expect(columnControl.rangeType).toBe(RANGE_TYPE.COLUMN);
+ expect(columnControl.fillControlTopLeft?.top).toBeLessThanOrEqual(300);
+ expect(columnControl.fillControlBottomRight?.left).toBeGreaterThan(columnControl.fillControlTopLeft?.left ?? 0);
+ });
+
+ it('keeps replacement mobile handles wired through disposal', () => {
+ const control = createMobileControl(RANGE_TYPE.NORMAL);
+ const topLeft = control.fillControlTopLeft!;
+ const bottomRight = control.fillControlBottomRight!;
+
+ control.fillControlTopLeft = topLeft;
+ control.fillControlBottomRight = bottomRight;
+ control.rangeType = RANGE_TYPE.ALL;
+
+ expect(control.fillControlTopLeft).toBe(topLeft);
+ expect(control.fillControlBottomRight).toBe(bottomRight);
+ expect(control.rangeType).toBe(RANGE_TYPE.ALL);
+
+ control.dispose();
+ });
+
+ it('creates mobile selections from pointer positions after the sheet skeleton is ready', () => {
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [IShortcutService, { useClass: TestShortcutService }],
+ [SheetScrollManagerService, { useClass: TestSheetScrollManagerService }],
+ ],
+ });
+ const { injector, sheet, commandService, sheetSkeletonManagerService, skeleton, context } = testBed;
+ (context.mainComponent as never as { onPointerUp$: unknown }).onPointerUp$ = createTestEvent();
+ (skeleton as never as {
+ getCellByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ getColumnCount: () => number;
+ getRowCount: () => number;
+ }).getCellByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ const cell = skeleton.getNoMergeCellWithCoordByIndex(row, column);
+ return {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ };
+ };
+ (skeleton as never as { getColumnCount: () => number }).getColumnCount = () => skeleton.worksheet.getColumnCount();
+ (skeleton as never as { getRowCount: () => number }).getRowCount = () => skeleton.worksheet.getRowCount();
+ commandService.registerCommand(SetSelectionsOperation);
+ const service = injector.createInstance(MobileSheetsSelectionRenderService, context as never);
+
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ unitId: sheet.getUnitId(),
+ sheetId: 'sheet1',
+ skeleton: skeleton as never,
+ });
+
+ service.createNewSelection({ offsetX: 150, offsetY: 45 } as never, 0, RANGE_TYPE.NORMAL);
+ expect(service.getSelectionControls()).toHaveLength(1);
+ expect(service.getActiveRange()).toEqual({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 1,
+ });
+
+ service.createNewSelection({ offsetX: 150, offsetY: 45 } as never, 0, RANGE_TYPE.ROW);
+ expect(service.getActiveRange()).toMatchObject({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 0,
+ endColumn: 49,
+ });
+
+ const scrollManager = injector.get(SheetScrollManagerService) as never as TestSheetScrollManagerService;
+ scrollManager.validViewportScrollInfo$.next({ viewportScrollX: 240, viewportScrollY: 180 });
+ expect(service.getActiveSelectionControl<MobileSelectionControl>()?.fillControlTopLeft?.left).toBeGreaterThan(0);
+
+ const leftTopPlaceholder = context.components.get(SHEET_VIEW_KEY.LEFT_TOP)!;
+ let stopped = false;
+ (leftTopPlaceholder.onPointerDown$ as unknown as { emit: (evt: unknown, state: { stopPropagation: () => void }) => void }).emit({ button: 0 }, {
+ stopPropagation: () => {
+ stopped = true;
+ },
+ });
+ expect(stopped).toBe(true);
+ expect(service.getActiveRange()).toMatchObject({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 199,
+ endColumn: 49,
+ });
+
+ service.dispose();
+ testBed.univer.dispose();
+ });
+
+ it('expands a mobile selection by dragging the bottom-right handle', () => {
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [IShortcutService, { useClass: TestShortcutService }],
+ [SheetScrollManagerService, { useClass: TestSheetScrollManagerService }],
+ ],
+ });
+ const { injector, sheet, commandService, sheetSkeletonManagerService, skeleton, context, scene, contextService } = testBed;
+ (context.mainComponent as never as { onPointerUp$: unknown }).onPointerUp$ = createTestEvent();
+ installCellLookupForMobileSelection(skeleton);
+ (scene as never as { getTransformer: () => { clearSelectedObjects: () => void } }).getTransformer = () => ({ clearSelectedObjects: () => { } });
+ commandService.registerCommand(SetSelectionsOperation);
+ const service = injector.createInstance(MobileSheetsSelectionRenderService, context as never);
+
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ unitId: sheet.getUnitId(),
+ sheetId: 'sheet1',
+ skeleton: skeleton as never,
+ });
+
+ service.createNewSelection({ offsetX: 150, offsetY: 45 } as never, 0, RANGE_TYPE.NORMAL);
+ const movingSelections: unknown[] = [];
+ service.selectionMoving$.subscribe((selection) => movingSelections.push(selection));
+ const activeControl = service.getActiveSelectionControl<MobileSelectionControl>()!;
+
+ activeControl.fillControlBottomRight!.onPointerDown$.emitEvent({ offsetX: 150, offsetY: 45 } as never);
+ expect(contextService.getContextValue('MOBILE_EXPANDING_SELECTION')).toBe(true);
+
+ (scene.onPointerMove$ as unknown as { emit: (evt: unknown, state?: unknown) => void }).emit({ offsetX: 360, offsetY: 90 });
+ expect(service.getActiveRange()).toEqual({
+ startRow: 2,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 3,
+ });
+ expect(movingSelections.length).toBeGreaterThan(0);
+
+ (scene.onPointerUp$ as unknown as { emit: (evt: unknown, state?: unknown) => void }).emit({ offsetX: 360, offsetY: 90 });
+ expect(contextService.getContextValue('MOBILE_EXPANDING_SELECTION')).toBe(false);
+
+ service.dispose();
+ testBed.univer.dispose();
+ });
+
+ it('creates mobile selections from tap and header gestures while respecting pinch zoom state', () => {
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [IShortcutService, { useClass: TestShortcutService }],
+ [SheetScrollManagerService, { useClass: TestSheetScrollManagerService }],
+ ],
+ });
+ const { injector, sheet, commandService, sheetSkeletonManagerService, skeleton, context, contextService } = testBed;
+ (context.mainComponent as never as { onPointerUp$: unknown }).onPointerUp$ = createTestEvent();
+ (skeleton as never as {
+ getCellByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ getColumnCount: () => number;
+ getRowCount: () => number;
+ expandRangeByMerge: <T>(range: T) => T;
+ }).getCellByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ const cell = skeleton.getNoMergeCellWithCoordByIndex(row, column);
+ return {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ },
+ };
+ };
+ (skeleton as never as { getColumnCount: () => number }).getColumnCount = () => skeleton.worksheet.getColumnCount();
+ (skeleton as never as { getRowCount: () => number }).getRowCount = () => skeleton.worksheet.getRowCount();
+ (skeleton as never as { expandRangeByMerge: <T>(range: T) => T }).expandRangeByMerge = (range) => range;
+ commandService.registerCommand(SetSelectionsOperation);
+ const service = injector.createInstance(MobileSheetsSelectionRenderService, context as never);
+
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ unitId: sheet.getUnitId(),
+ sheetId: 'sheet1',
+ skeleton: skeleton as never,
+ });
+
+ const spreadsheet = context.mainComponent as never as {
+ onPointerDown$: { emit: (evt: unknown, state: unknown) => void };
+ onPointerUp$: { emit: (evt: unknown, state: unknown) => void };
+ };
+ let stopped = false;
+ spreadsheet.onPointerDown$.emit({ offsetX: 150, offsetY: 45, button: 0 }, {
+ stopPropagation: () => {
+ stopped = true;
+ },
+ });
+ spreadsheet.onPointerUp$.emit({ offsetX: 154, offsetY: 49, button: 0 }, {
+ stopPropagation: () => {
+ stopped = true;
+ },
+ });
+ expect(stopped).toBe(true);
+ expect(service.getActiveRange()).toEqual({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 1,
+ });
+
+ contextService.setContextValue('MOBILE_PINCH_ZOOMING', true);
+ spreadsheet.onPointerDown$.emit({ offsetX: 250, offsetY: 65, button: 0 }, {
+ stopPropagation: () => {
+ throw new Error('pinch zoom should not start a tap selection');
+ },
+ });
+ spreadsheet.onPointerUp$.emit({ offsetX: 250, offsetY: 65, button: 0 }, {
+ stopPropagation: () => {
+ throw new Error('pinch zoom should not finish a tap selection');
+ },
+ });
+ expect(service.getActiveRange()).toEqual({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 1,
+ });
+ contextService.setContextValue('MOBILE_PINCH_ZOOMING', false);
+
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW)!;
+ (rowHeader.onPointerDown$ as unknown as { emit: (evt: unknown, state: unknown) => void }).emit({
+ offsetX: 10,
+ offsetY: 65,
+ button: 0,
+ }, {});
+ expect(service.getActiveRange()).toEqual({
+ startRow: 3,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 49,
+ });
+
+ const columnHeader = context.components.get(SHEET_VIEW_KEY.COLUMN)!;
+ (columnHeader.onPointerDown$ as unknown as { emit: (evt: unknown, state: unknown) => void }).emit({
+ offsetX: 350,
+ offsetY: 5,
+ button: 0,
+ }, {});
+ expect(service.getActiveRange()).toEqual({
+ startRow: 0,
+ endRow: 199,
+ startColumn: 3,
+ endColumn: 3,
+ });
+
+ service.dispose();
+ testBed.univer.dispose();
+ });
});
diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts
index 791aca0fb0..aed36793a9 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts
@@ -14,41 +14,232 @@
* limitations under the License.
*/
-import type { ThemeService } from '@univerjs/core';
-import { beforeAll, describe, expect, it, vi } from 'vitest';
+import type { IRangeWithCoord, ThemeService } from '@univerjs/core';
+import type { Vector2 } from '@univerjs/engine-render';
+import { Injector, IUniverInstanceService } from '@univerjs/core';
+import { CURSOR_TYPE, IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { beforeAll, describe, expect, it } from 'vitest';
+import { ISheetSelectionRenderService } from '../base-selection-render.service';
import { SelectionControl } from '../selection-control';
+function createTestEvent<T>() {
+ const listeners: Array<(event: T) => void> = [];
+ return {
+ subscribeEvent(listener: (event: T) => void) {
+ listeners.push(listener);
+ return {
+ unsubscribe: () => {
+ const index = listeners.indexOf(listener);
+ if (index >= 0) {
+ listeners.splice(index, 1);
+ }
+ },
+ dispose: () => {
+ const index = listeners.indexOf(listener);
+ if (index >= 0) {
+ listeners.splice(index, 1);
+ }
+ },
+ };
+ },
+ emit(event: T) {
+ for (let i = 0, len = listeners.length; i < len; i++) {
+ listeners[i](event);
+ }
+ },
+ };
+}
+
function createFakeScene() {
+ const pointerMove$ = createTestEvent<{ offsetX: number; offsetY: number }>();
+ const pointerUp$ = createTestEvent<{ offsetX?: number; offsetY?: number }>();
+ const viewports = new Map<string, unknown>();
+ const mainViewport = {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_MAIN,
+ left: 0,
+ top: 0,
+ width: 1000,
+ height: 800,
+ scrollToBarPos: () => { },
+ scrollByViewportDeltaVal: () => false,
+ transScroll2ViewportScrollValue: () => ({ x: 0, y: 0 }),
+ };
+ viewports.set(SHEET_VIEWPORT_KEY.VIEW_MAIN, mainViewport);
+
return {
- addObject: vi.fn(),
- addObjects: vi.fn(),
+ pointerMove$,
+ pointerUp$,
+ addedObjects: [] as unknown[],
+ disabledObjectsEventCount: 0,
+ enabledObjectsEventCount: 0,
+ cursor: '',
+ addObject: (obj: { parent?: unknown }) => {
+ obj.parent = null;
+ (obj as { scene?: unknown }).scene = null;
+ },
+ addObjects: (objs: Array<{ parent?: unknown }>) => {
+ objs.forEach((obj) => {
+ obj.parent = null;
+ (obj as { scene?: unknown }).scene = null;
+ });
+ },
+ getCoordRelativeToViewport: (coord: Vector2) => coord,
+ getScrollXYInfoByViewport: () => ({ x: 0, y: 0 }),
+ getViewportScrollXY: () => ({ x: 0, y: 0 }),
getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),
- onTransformChange$: { subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })) },
+ getViewport: (key: string) => viewports.get(key),
+ getActiveViewportByCoord: () => mainViewport,
+ disableObjectsEvent() {
+ this.disabledObjectsEventCount += 1;
+ },
+ enableObjectsEvent() {
+ this.enabledObjectsEventCount += 1;
+ },
+ setCursor(cursor: string) {
+ this.cursor = cursor;
+ },
+ resetCursor() {
+ this.cursor = '';
+ },
+ onPointerMove$: pointerMove$,
+ onPointerUp$: pointerUp$,
+ onTransformChange$: { subscribeEvent: () => ({ dispose: () => { } }) },
} as any;
}
function createFakeThemeService() {
return {
- getColorFromTheme: vi.fn((key: string) => (key === 'white' ? '#ffffff' : '#3b82f6')),
+ getColorFromTheme: (key: string) => (key === 'white' ? '#ffffff' : '#3b82f6'),
} as unknown as ThemeService;
}
+function createWidgetStyle(widgets: Record<string, boolean>) {
+ return {
+ strokeWidth: 1,
+ stroke: '#3b82f6',
+ fill: 'rgba(59, 130, 246, 0.12)',
+ widgetSize: 6,
+ widgets,
+ };
+}
+
+function createControl(options?: {
+ highlightHeader?: boolean;
+ enableAutoFill?: boolean;
+ rowHeaderWidth: number;
+ columnHeaderHeight: number;
+ rowHeaderOffsetX?: number;
+ columnHeaderOffsetY?: number;
+}, scene = createFakeScene()) {
+ const injector = new Injector();
+ return injector.createInstance(
+ SelectionControl,
+ scene,
+ 1,
+ createFakeThemeService(),
+ options ?? {
+ rowHeaderWidth: 46,
+ columnHeaderHeight: 20,
+ }
+ );
+}
+
+function createFakeSkeleton(options?: { merged?: boolean }) {
+ const cellWidth = 100;
+ const cellHeight = 20;
+ const toRange = (startRow: number, startColumn: number, endRow = startRow, endColumn = startColumn) => ({
+ startRow,
+ endRow,
+ startColumn,
+ endColumn,
+ startX: startColumn * cellWidth,
+ endX: (endColumn + 1) * cellWidth,
+ startY: startRow * cellHeight,
+ endY: (endRow + 1) * cellHeight,
+ });
+
+ return {
+ rowHeaderWidth: 46,
+ columnHeaderHeight: 20,
+ rowHeaderWidthAndMarginLeft: 46,
+ columnHeaderHeightAndMarginTop: 20,
+ worksheet: {
+ getCellInfoInMergeData: (row: number, column: number) => ({
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ ...toRange(row, column),
+ mergeInfo: toRange(row, column),
+ }),
+ getMergedCellRange: () => options?.merged ? [toRange(1, 1, 2, 1)] : [],
+ },
+ getWorksheetConfig: () => ({
+ freeze: {
+ startRow: 2,
+ startColumn: 2,
+ xSplit: 0,
+ ySplit: 0,
+ },
+ }),
+ getRowCount: () => 20,
+ getColumnCount: () => 20,
+ getCellIndexByOffset: (offsetX: number, offsetY: number) => ({
+ row: Math.max(0, Math.floor(offsetY / cellHeight)),
+ column: Math.max(0, Math.floor(offsetX / cellWidth)),
+ }),
+ getNoMergeCellWithCoordByIndex: (row: number, column: number) => toRange(row, column),
+ getCellWithMergeInfoByIndex: (row: number, column: number) => ({
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ ...toRange(row, column),
+ mergeInfo: toRange(row, column),
+ }),
+ };
+}
+
+class TestUniverInstanceService {}
+
+class TestRenderManagerService {}
+
+class TestSheetSelectionRenderService {
+ interceptor = {
+ fetchThroughInterceptors: () => () => true,
+ };
+}
+
+function attachExtension(control: SelectionControl, scene: ReturnType<typeof createFakeScene>, skeleton = createFakeSkeleton()) {
+ const injector = new Injector();
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([ISheetSelectionRenderService, { useClass: TestSheetSelectionRenderService as never }]);
+
+ const hooks = { selectionMoveEnd: () => {
+ hooks.moveEndCount += 1;
+ }, moveEndCount: 0 };
+ control.setControlExtension({
+ skeleton: skeleton as never,
+ scene,
+ themeService: createFakeThemeService(),
+ injector,
+ selectionHooks: hooks as never,
+ });
+
+ return hooks;
+}
+
describe('SelectionControl', () => {
beforeAll(() => {
- vi.stubGlobal('window', {
- cancelAnimationFrame: vi.fn(),
- requestAnimationFrame: vi.fn(() => 1),
- });
+ globalThis.window = {
+ cancelAnimationFrame: () => { },
+ requestAnimationFrame: () => 1,
+ } as unknown as Window & typeof globalThis;
});
it('updates range and shows/hides autofill based on primary', () => {
- const scene = createFakeScene();
- const themeService = createFakeThemeService();
-
- const control = new SelectionControl(scene, 1, themeService, {
- rowHeaderWidth: 46,
- columnHeaderHeight: 20,
- });
+ const control = createControl();
// No primary: should hide autofill.
control.updateRange(
@@ -95,12 +286,7 @@ describe('SelectionControl', () => {
});
it('keeps header highlights aligned with outline header padding', () => {
- const scene = createFakeScene();
- const themeService = createFakeThemeService();
- const control = new SelectionControl(scene, 1, themeService, {
- rowHeaderWidth: 46,
- columnHeaderHeight: 20,
- });
+ const control = createControl();
control.updateRangeBySelectionWithCoord({
rangeWithCoord: {
@@ -127,4 +313,661 @@ describe('SelectionControl', () => {
expect((control as any)._columnHeaderGroup.left).toBe(126);
expect((control as any)._columnHeaderGroup.top).toBe(40);
});
+
+ it('uses widgets instead of autofill when a selection style exposes resize handles', () => {
+ const control = createControl();
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 1,
+ startX: 0,
+ startY: 0,
+ endX: 120,
+ endY: 40,
+ },
+ primaryWithCoord: {
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ mergeInfo: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ },
+ },
+ style: {
+ strokeWidth: 1,
+ stroke: '#3b82f6',
+ fill: 'rgba(59, 130, 246, 0.12)',
+ widgetSize: 6,
+ widgets: { tl: true, br: true },
+ },
+ });
+
+ expect(control.fillControl.visible).toBe(false);
+ expect(control.topLeftWidget.visible).toBe(true);
+ expect(control.bottomRightWidget.visible).toBe(true);
+ expect(control.topCenterWidget.visible).toBe(false);
+
+ control.updateStyle({
+ widgets: {},
+ });
+ expect(control.topLeftWidget.visible).toBe(false);
+ });
+
+ it('returns the highlighted cell range and clears it without changing the selected range', () => {
+ const control = createControl();
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ startX: 200,
+ startY: 20,
+ endX: 500,
+ endY: 80,
+ },
+ primaryWithCoord: {
+ actualRow: 2,
+ actualColumn: 3,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 300,
+ startY: 40,
+ endX: 400,
+ endY: 60,
+ mergeInfo: {
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 3,
+ startX: 300,
+ startY: 40,
+ endX: 400,
+ endY: 60,
+ },
+ },
+ style: null,
+ });
+
+ expect(control.getCurrentCellInfo()).toEqual({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 3,
+ startX: 300,
+ startY: 40,
+ endX: 400,
+ endY: 60,
+ });
+ expect(control.getValue().rangeWithCoord).toMatchObject({
+ startRow: 1,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 4,
+ });
+
+ control.clearHighlight();
+ expect(control.getCurrentCellInfo()).toBeUndefined();
+
+ control.disableHelperSelection();
+ expect(control.isHelperSelection).toBe(false);
+ control.enableHelperSelection();
+ expect(control.isHelperSelection).toBe(true);
+ });
+
+ it('updates public interaction state without changing the selected range', () => {
+ const control = createControl();
+ const selectedRange = {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ };
+ control.updateRange(selectedRange, null);
+
+ control.setEvent(false);
+ expect(control.leftControl.evented).toBe(false);
+ expect(control.rightControl.evented).toBe(false);
+ control.setEvent(true);
+ expect(control.topControl.evented).toBe(true);
+ expect(control.bottomControl.evented).toBe(true);
+
+ let filledRange: typeof selectedRange | undefined;
+ control.selectionFilled$.subscribe((range) => {
+ filledRange = range as typeof selectedRange;
+ });
+ control.refreshSelectionFilled(selectedRange);
+ expect(filledRange).toEqual(selectedRange);
+
+ control.updateCurrCell({
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ mergeInfo: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ },
+ });
+ expect(control.getCurrentCellInfo()).toMatchObject({
+ startRow: 0,
+ startColumn: 0,
+ });
+
+ control.rowHeaderWidth = 72;
+ control.columnHeaderHeight = 28;
+ expect(control.rowHeaderWidth).toBe(72);
+ expect(control.columnHeaderHeight).toBe(28);
+ expect(control.getScene()).toBeDefined();
+
+ const model = control.selectionModel;
+ control.selectionModel = model;
+ expect(control.model).toBe(model);
+
+ control.setControlExtensionDisable(true);
+ expect(control.getRange()).toMatchObject({
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ });
+ });
+
+ it('moves the selected range by dragging the selection border', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ const hooks = attachExtension(control, scene);
+ const movingRanges: IRangeWithCoord[] = [];
+ const endedRanges: IRangeWithCoord[] = [];
+ control.selectionMoving$.subscribe((range) => movingRanges.push(range));
+ control.selectionMoveEnd$.subscribe((range) => endedRanges.push(range));
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ startY: 20,
+ endX: 300,
+ endY: 60,
+ },
+ primaryWithCoord: null,
+ style: null,
+ });
+
+ control.leftControl.onPointerDown$.emitEvent({ offsetX: 120, offsetY: 30 } as never);
+ scene.pointerMove$.emit({ offsetX: 320, offsetY: 80 });
+ scene.pointerUp$.emit({});
+
+ expect(movingRanges.at(-1)).toMatchObject({
+ startRow: 4,
+ endRow: 5,
+ startColumn: 3,
+ endColumn: 4,
+ startX: 300,
+ endX: 500,
+ startY: 80,
+ endY: 120,
+ });
+ expect(endedRanges.at(-1)).toEqual(movingRanges.at(-1));
+ expect(scene.disabledObjectsEventCount).toBe(1);
+ expect(scene.enabledObjectsEventCount).toBe(1);
+ expect(hooks.moveEndCount).toBe(1);
+ });
+
+ it('does not move the range while the selection extension is disabled', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene);
+ const movingRanges: IRangeWithCoord[] = [];
+ control.selectionMoving$.subscribe((range) => movingRanges.push(range));
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ startY: 20,
+ endX: 300,
+ endY: 60,
+ },
+ primaryWithCoord: null,
+ style: null,
+ });
+ control.setControlExtensionDisable(true);
+
+ control.leftControl.onPointerDown$.emitEvent({ offsetX: 120, offsetY: 30 } as never);
+ scene.pointerMove$.emit({ offsetX: 320, offsetY: 80 });
+ scene.pointerUp$.emit({});
+
+ expect(movingRanges).toEqual([]);
+ });
+
+ it('shows the expected cursors for move, resize and autofill affordances', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene);
+
+ control.leftControl.onPointerEnter$.emitEvent({ offsetX: 120, offsetY: 30 } as never);
+ expect((control.leftControl as never as { _cursor: CURSOR_TYPE })._cursor).toBe(CURSOR_TYPE.MOVE);
+ control.leftControl.onPointerLeave$.emitEvent({ offsetX: 120, offsetY: 30 } as never);
+
+ control.topLeftWidget.onPointerEnter$.emitEvent({ offsetX: 100, offsetY: 20 } as never);
+ expect((control.topLeftWidget as never as { _cursor: CURSOR_TYPE })._cursor).toBe(CURSOR_TYPE.NORTH_WEST_RESIZE);
+ control.topLeftWidget.onPointerLeave$.emitEvent({ offsetX: 100, offsetY: 20 } as never);
+
+ control.fillControl.onPointerEnter$.emitEvent({ offsetX: 300, offsetY: 60 } as never);
+ expect((control.fillControl as never as { _cursor: CURSOR_TYPE })._cursor).toBe(CURSOR_TYPE.CROSSHAIR);
+ control.fillControl.onPointerLeave$.emitEvent({ offsetX: 300, offsetY: 60 } as never);
+ });
+
+ it('resizes the selected range by dragging a selection widget', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ const hooks = attachExtension(control, scene);
+ const scalingRanges: IRangeWithCoord[] = [];
+ const scaledRanges: IRangeWithCoord[] = [];
+ control.selectionScaling$.subscribe((range) => scalingRanges.push(range));
+ control.selectionScaled$.subscribe((range) => {
+ if (range) {
+ scaledRanges.push(range);
+ }
+ });
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ startY: 20,
+ endX: 300,
+ endY: 60,
+ },
+ primaryWithCoord: {
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ },
+ },
+ style: createWidgetStyle({ br: true }),
+ });
+
+ control.bottomRightWidget.onPointerDown$.emitEvent({ offsetX: 300, offsetY: 60 } as never);
+ scene.pointerMove$.emit({ offsetX: 420, offsetY: 90 });
+ scene.pointerUp$.emit({});
+
+ expect(scalingRanges.at(-1)).toMatchObject({
+ startRow: 1,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 4,
+ startX: 100,
+ endX: 500,
+ startY: 20,
+ endY: 100,
+ });
+ expect(scaledRanges.at(-1)).toEqual(scalingRanges.at(-1));
+ expect(control.getRange()).toMatchObject({
+ startRow: 1,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 4,
+ });
+ expect(hooks.moveEndCount).toBe(1);
+ });
+
+ it('keeps the opposite corner fixed when resizing from the top-left widget', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene);
+ const scalingRanges: IRangeWithCoord[] = [];
+ control.selectionScaling$.subscribe((range) => scalingRanges.push(range));
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 3,
+ endRow: 5,
+ startColumn: 3,
+ endColumn: 5,
+ startX: 300,
+ startY: 60,
+ endX: 600,
+ endY: 120,
+ },
+ primaryWithCoord: null,
+ style: createWidgetStyle({ tl: true }),
+ });
+
+ control.topLeftWidget.onPointerDown$.emitEvent({ offsetX: 300, offsetY: 60 } as never);
+ scene.pointerMove$.emit({ offsetX: 120, offsetY: 25 });
+ scene.pointerUp$.emit({});
+
+ expect(scalingRanges.at(-1)).toMatchObject({
+ startRow: 1,
+ endRow: 5,
+ startColumn: 1,
+ endColumn: 5,
+ startX: 100,
+ endX: 600,
+ startY: 20,
+ endY: 120,
+ });
+ });
+
+ it('resizes from each edge handle while keeping the opposite edge anchored', () => {
+ const cases = [
+ {
+ widget: 'topCenterWidget',
+ enabledWidget: 'tc',
+ down: { offsetX: 400, offsetY: 60 },
+ move: { offsetX: 350, offsetY: 25 },
+ expected: { startRow: 1, endRow: 5, startColumn: 3, endColumn: 5 },
+ },
+ {
+ widget: 'topRightWidget',
+ enabledWidget: 'tr',
+ down: { offsetX: 600, offsetY: 60 },
+ move: { offsetX: 720, offsetY: 25 },
+ expected: { startRow: 1, endRow: 5, startColumn: 3, endColumn: 7 },
+ },
+ {
+ widget: 'middleLeftWidget',
+ enabledWidget: 'ml',
+ down: { offsetX: 300, offsetY: 90 },
+ move: { offsetX: 120, offsetY: 80 },
+ expected: { startRow: 3, endRow: 5, startColumn: 1, endColumn: 5 },
+ },
+ {
+ widget: 'middleRightWidget',
+ enabledWidget: 'mr',
+ down: { offsetX: 600, offsetY: 90 },
+ move: { offsetX: 720, offsetY: 80 },
+ expected: { startRow: 3, endRow: 5, startColumn: 3, endColumn: 7 },
+ },
+ {
+ widget: 'bottomLeftWidget',
+ enabledWidget: 'bl',
+ down: { offsetX: 300, offsetY: 120 },
+ move: { offsetX: 120, offsetY: 165 },
+ expected: { startRow: 3, endRow: 8, startColumn: 1, endColumn: 5 },
+ },
+ {
+ widget: 'bottomCenterWidget',
+ enabledWidget: 'bc',
+ down: { offsetX: 400, offsetY: 120 },
+ move: { offsetX: 350, offsetY: 165 },
+ expected: { startRow: 3, endRow: 8, startColumn: 3, endColumn: 5 },
+ },
+ ] as const;
+
+ for (let i = 0, len = cases.length; i < len; i++) {
+ const item = cases[i];
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene);
+ const scalingRanges: IRangeWithCoord[] = [];
+ control.selectionScaling$.subscribe((range) => scalingRanges.push(range));
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 3,
+ endRow: 5,
+ startColumn: 3,
+ endColumn: 5,
+ startX: 300,
+ startY: 60,
+ endX: 600,
+ endY: 120,
+ },
+ primaryWithCoord: null,
+ style: createWidgetStyle({ [item.enabledWidget]: true }),
+ });
+
+ control[item.widget].onPointerDown$.emitEvent(item.down as never);
+ scene.pointerMove$.emit(item.move);
+ scene.pointerUp$.emit({});
+
+ expect(scalingRanges.at(-1)).toMatchObject(item.expected);
+ }
+ });
+
+ it('extends the autofill range by dragging the fill handle and commits it on pointer up', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene);
+ const fillingRanges: IRangeWithCoord[] = [];
+ const filledRanges: IRangeWithCoord[] = [];
+ control.selectionFilling$.subscribe((range) => {
+ if (range) {
+ fillingRanges.push(range);
+ }
+ });
+ control.selectionFilled$.subscribe((range) => {
+ if (range) {
+ filledRanges.push(range);
+ }
+ });
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ startY: 20,
+ endX: 300,
+ endY: 60,
+ },
+ primaryWithCoord: {
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ },
+ },
+ style: null,
+ });
+
+ control.fillControl.onPointerDown$.emitEvent({ offsetX: 300, offsetY: 60 } as never);
+ scene.pointerMove$.emit({ offsetX: 150, offsetY: 95 });
+ scene.pointerUp$.emit({});
+
+ expect(fillingRanges.at(-1)).toMatchObject({
+ startRow: 1,
+ endRow: 4,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ endX: 300,
+ startY: 20,
+ endY: 100,
+ });
+ expect(filledRanges.at(-1)).toEqual(fillingRanges.at(-1));
+ });
+
+ it('autofills horizontally when the fill handle is dragged beyond the selected columns', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene);
+ const fillingRanges: IRangeWithCoord[] = [];
+ control.selectionFilling$.subscribe((range) => {
+ if (range) {
+ fillingRanges.push(range);
+ }
+ });
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ startX: 100,
+ startY: 20,
+ endX: 300,
+ endY: 60,
+ },
+ primaryWithCoord: {
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 40,
+ },
+ },
+ style: null,
+ });
+
+ control.fillControl.onPointerDown$.emitEvent({ offsetX: 300, offsetY: 60 } as never);
+ scene.pointerMove$.emit({ offsetX: 460, offsetY: 45 });
+ scene.pointerUp$.emit({});
+
+ expect(fillingRanges.at(-1)).toMatchObject({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 4,
+ startX: 100,
+ endX: 500,
+ startY: 20,
+ endY: 60,
+ });
+ });
+
+ it('keeps merged autofill ranges aligned to the original merged block size', () => {
+ const scene = createFakeScene();
+ const control = createControl(undefined, scene);
+ attachExtension(control, scene, createFakeSkeleton({ merged: true }));
+ const fillingRanges: IRangeWithCoord[] = [];
+ control.selectionFilling$.subscribe((range) => {
+ if (range) {
+ fillingRanges.push(range);
+ }
+ });
+
+ control.updateRangeBySelectionWithCoord({
+ rangeWithCoord: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 60,
+ },
+ primaryWithCoord: {
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: true,
+ isMergedMainCell: true,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 60,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ startY: 20,
+ endX: 200,
+ endY: 60,
+ },
+ },
+ style: null,
+ });
+
+ control.fillControl.onPointerDown$.emitEvent({ offsetX: 200, offsetY: 60 } as never);
+ scene.pointerMove$.emit({ offsetX: 150, offsetY: 125 });
+ scene.pointerUp$.emit({});
+
+ expect(fillingRanges.at(-1)).toMatchObject({
+ startRow: 1,
+ endRow: 6,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ endX: 200,
+ startY: 20,
+ endY: 140,
+ });
+ });
});
diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts
index 76877c359e..30c0bc8e30 100644
--- a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts
+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts
@@ -20,18 +20,78 @@ import { RANGE_TYPE } from '@univerjs/core';
import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { IShortcutService } from '@univerjs/ui';
import { describe, expect, it } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
import { createRenderTestBed } from '../../../controllers/render-controllers/__tests__/render-test-bed';
import { SheetSelectionRenderService } from '../selection-render.service';
+class TestShortcutService {
+ forceEscape() {
+ return { dispose: () => { } };
+ }
+}
+
describe('SheetSelectionRenderService', () => {
+ function preparePointerSelectionTestBed() {
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [IShortcutService, { useClass: TestShortcutService }],
+ ],
+ });
+ const { commandService, skeleton, context, scene, engine } = testBed;
+ (skeleton as never as {
+ getCellByOffset: (x: number, y: number, scaleX: number, scaleY: number, scrollXY: { x: number; y: number }) => unknown;
+ getColumnCount: () => number;
+ getRowCount: () => number;
+ expandRangeByMerge: <T>(range: T) => T;
+ }).getCellByOffset = (x, y, scaleX, scaleY, scrollXY) => {
+ const { row, column } = skeleton.getCellIndexByOffset(x, y, scaleX, scaleY, scrollXY);
+ const cell = skeleton.getNoMergeCellWithCoordByIndex(row, column);
+ return {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ actualRow: row,
+ actualColumn: column,
+ isMerged: false,
+ isMergedMainCell: false,
+ mergeInfo: {
+ ...cell,
+ startRow: row,
+ endRow: row,
+ startColumn: column,
+ endColumn: column,
+ },
+ };
+ };
+ (skeleton as never as { getColumnCount: () => number }).getColumnCount = () => skeleton.worksheet.getColumnCount();
+ (skeleton as never as { getRowCount: () => number }).getRowCount = () => skeleton.worksheet.getRowCount();
+ (skeleton as never as { expandRangeByMerge: <T>(range: T) => T }).expandRangeByMerge = (range) => range;
+ (scene as never as { getTransformer: () => { clearSelectedObjects: () => void } }).getTransformer = () => ({ clearSelectedObjects: () => { } });
+ (engine as never as { setCapture: () => void }).setCapture = () => { };
+ commandService.registerCommand(SetSelectionsOperation);
+
+ const service = testBed.injector.createInstance(SheetSelectionRenderService, context as any);
+ testBed.sheetSkeletonManagerService.emitCurrentSkeleton({
+ unitId: testBed.sheet.getUnitId(),
+ sheetId: 'sheet1',
+ skeleton: skeleton as any,
+ });
+
+ return { ...testBed, service };
+ }
+
it('renders selections from model changes and respects SELECTIONS_ENABLED', () => {
const testBed = createRenderTestBed({
dependencies: [
- [IShortcutService, { useValue: {} }],
+ [IShortcutService, { useClass: TestShortcutService }],
],
});
const { injector, sheet, commandService, sheetSkeletonManagerService, skeleton, context } = testBed;
+ (skeleton as never as { getColumnCount: () => number }).getColumnCount = () => skeleton.worksheet.getColumnCount();
+ (skeleton as never as { getRowCount: () => number }).getRowCount = () => skeleton.worksheet.getRowCount();
commandService.registerCommand(SetSelectionsOperation);
const renderService = injector.createInstance(SheetSelectionRenderService, context as any);
@@ -101,6 +161,79 @@ describe('SheetSelectionRenderService', () => {
})).toBeTruthy();
expect(renderService.getSelectionControls().length).toBe(1);
+ renderService.transparentSelection();
+ expect(renderService.getSelectionControls()[0].currentStyle.stroke).toBe('transparent');
+
+ renderService.showSelection();
+ expect(renderService.getSelectionControls()[0].getRange()).toMatchObject(range);
+
+ const leftTopPlaceholder = context.components.get(SHEET_VIEW_KEY.LEFT_TOP)!;
+ let stopped = false;
+ (leftTopPlaceholder.onPointerDown$ as unknown as { emit: (evt: unknown, state: { stopPropagation: () => void }) => void }).emit({ button: 0 }, {
+ stopPropagation: () => {
+ stopped = true;
+ },
+ });
+ expect(stopped).toBe(true);
+ expect(renderService.getActiveRange()).toMatchObject({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 199,
+ endColumn: 49,
+ });
+
+ renderService.dispose();
testBed.univer.dispose();
});
+
+ it('creates normal row and column selections from pointer gestures', () => {
+ const { context, scene, service, univer } = preparePointerSelectionTestBed();
+ const stopCalls: string[] = [];
+ const state = { stopPropagation: () => stopCalls.push('stop') };
+
+ const spreadsheet = context.mainComponent!;
+ (spreadsheet.onPointerDown$ as unknown as { emit: (evt: unknown, state: unknown) => void }).emit({
+ offsetX: 250,
+ offsetY: 45,
+ button: 0,
+ }, state);
+ expect(service.getActiveRange()).toEqual({
+ startRow: 2,
+ endRow: 2,
+ startColumn: 2,
+ endColumn: 2,
+ });
+
+ (scene.onPointerUp$ as unknown as { emit: (evt: unknown, state: unknown) => void }).emit({}, {});
+
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW)!;
+ (rowHeader.onPointerDown$ as unknown as { emit: (evt: unknown, state: unknown) => void }).emit({
+ offsetX: 10,
+ offsetY: 65,
+ button: 0,
+ }, state);
+ expect(service.getActiveRange()).toEqual({
+ startRow: 3,
+ endRow: 3,
+ startColumn: 0,
+ endColumn: 49,
+ });
+
+ const columnHeader = context.components.get(SHEET_VIEW_KEY.COLUMN)!;
+ (columnHeader.onPointerDown$ as unknown as { emit: (evt: unknown, state: unknown) => void }).emit({
+ offsetX: 350,
+ offsetY: 5,
+ button: 0,
+ }, state);
+ expect(service.getActiveRange()).toEqual({
+ startRow: 0,
+ endRow: 199,
+ startColumn: 3,
+ endColumn: 3,
+ });
+ expect(stopCalls.length).toBeGreaterThanOrEqual(3);
+
+ service.dispose();
+ univer.dispose();
+ });
});
diff --git a/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.ts b/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.ts
index b5f34d1499..93d4178988 100644
--- a/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.ts
+++ b/packages/sheets-ui/src/services/utils/__tests__/doc-skeleton-util.spec.ts
@@ -15,25 +15,23 @@
*/
import type { DocumentSkeleton } from '@univerjs/engine-render';
-import { HorizontalAlign, IUniverInstanceService, VerticalAlign } from '@univerjs/core';
+import {
+ CustomRangeType,
+ HorizontalAlign,
+ IUniverInstanceService,
+ PresetListType,
+ VerticalAlign,
+} from '@univerjs/core';
+import { NodePositionConvertToCursor } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { describe, expect, it, vi } from 'vitest';
import { IEditorBridgeService } from '../../editor-bridge.service';
-import { calcPadding, calculateDocSkeletonRects, getCustomRangePosition, getEditingCustomRangePosition } from '../doc-skeleton-util';
-
-vi.mock('@univerjs/docs-ui', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@univerjs/docs-ui')>();
- return {
- ...actual,
- DOC_VERTICAL_PADDING: 2,
- getLineBounding: () => [{ top: 1, bottom: 3, left: 2, right: 4 }],
- NodePositionConvertToCursor: class {
- getRangePointData() {
- return { borderBoxPointGroup: [{}] };
- }
- },
- };
-});
+import {
+ calcPadding,
+ calculateDocSkeletonRects,
+ getCustomRangePosition,
+ getEditingCustomRangePosition,
+} from '../doc-skeleton-util';
function createAccessor(pairs: Array<[unknown, unknown]>) {
const map = new Map<unknown, unknown>(pairs);
@@ -62,6 +60,19 @@ function createDocSkeleton(customRangeId = 'range-1') {
} as any;
}
+function spyCursorRange() {
+ return vi.spyOn(NodePositionConvertToCursor.prototype, 'getRangePointData').mockReturnValue({
+ borderBoxPointGroup: [[
+ { x: 2, y: 1 },
+ { x: 4, y: 1 },
+ { x: 4, y: 3 },
+ { x: 2, y: 3 },
+ ]],
+ contentBoxPointGroup: [],
+ cursorList: [],
+ } as never);
+}
+
describe('doc-skeleton-util', () => {
it('calcPadding handles vertical and horizontal alignment branches', () => {
const cell = {
@@ -131,7 +142,65 @@ describe('doc-skeleton-util', () => {
});
});
+ it('collects hyperlink and checklist hit rects with cell padding applied', () => {
+ const cursorSpy = spyCursorRange();
+ const bulletGlyph = { glyphType: 'list-mark' };
+ const docSkeleton = {
+ findNodePositionByCharIndex: () => ({ segmentPage: 0, left: 0, top: 0 }),
+ findPositionByGlyph: (glyph: unknown) => glyph === bulletGlyph ? { segmentPage: 0, left: 0, top: 0 } : null,
+ findNodeByCharIndex: () => ({
+ parent: {
+ parent: {
+ parent: {
+ lines: [{
+ paragraphStart: true,
+ paragraphIndex: 4,
+ divides: [{ glyphGroup: [bulletGlyph] }],
+ }],
+ },
+ },
+ },
+ }),
+ getSkeletonData: () => ({
+ pages: [{
+ height: 4,
+ width: 6,
+ skeDrawings: new Map(),
+ }],
+ }),
+ getViewModel: () => ({
+ getDataModel: () => ({
+ getBody: () => ({
+ customRanges: [{
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ startIndex: 0,
+ endIndex: 2,
+ }],
+ paragraphs: [{
+ startIndex: 4,
+ bullet: { listType: PresetListType.CHECK_LIST_CHECKED },
+ }],
+ }),
+ }),
+ }),
+ } as any;
+
+ const rects = calculateDocSkeletonRects(docSkeleton, 10, 20);
+
+ expect(rects.links[0]).toMatchObject({
+ range: { rangeId: 'link-1' },
+ rects: [{ top: 21, bottom: 23, left: 12, right: 14 }],
+ });
+ expect(rects.checkLists[0]).toMatchObject({
+ paragraph: { startIndex: 4 },
+ rect: { top: 21, bottom: 23, left: 12, right: 14 },
+ });
+ cursorSpy.mockRestore();
+ });
+
it('getCustomRangePosition returns transformed rects and label', () => {
+ const cursorSpy = spyCursorRange();
const docSkeleton = createDocSkeleton();
const font = {
documentSkeleton: docSkeleton,
@@ -180,7 +249,8 @@ describe('doc-skeleton-util', () => {
const result = getCustomRangePosition(injector, 'unit-1', 'sheet-1', 1, 2, 'range-1');
expect(result?.label).toBe('abcd');
- expect(result?.rects).toEqual([{ top: 30, bottom: 32, left: 58, right: 60 }]);
+ expect(result?.rects).toEqual([{ top: 32, bottom: 34, left: 58, right: 60 }]);
+ cursorSpy.mockRestore();
});
it('getCustomRangePosition returns null for missing workbook/worksheet/customRange', () => {
@@ -217,9 +287,32 @@ describe('doc-skeleton-util', () => {
[IRenderManagerService, { getRenderById: () => ({ with: () => ({ getSkeletonParam: () => ({ skeleton }) }) }) }],
]);
expect(getCustomRangePosition(noRangeInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();
+
+ const noSkeletonInjector = createAccessor([
+ [IUniverInstanceService, { getUnit: () => ({ getUnitId: () => 'unit-1', getSheetBySheetId: () => worksheet }) }],
+ [IRenderManagerService, { getRenderById: () => ({ with: () => ({ getSkeletonParam: () => null }) }) }],
+ ]);
+ expect(getCustomRangePosition(noSkeletonInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeUndefined();
+
+ const noDocSkeletonInjector = createAccessor([
+ [IUniverInstanceService, { getUnit: () => ({ getUnitId: () => 'unit-1', getSheetBySheetId: () => worksheet }) }],
+ [IRenderManagerService, {
+ getRenderById: () => ({
+ with: () => ({
+ getSkeletonParam: () => ({
+ skeleton: {
+ getFont: () => null,
+ },
+ }),
+ }),
+ }),
+ }],
+ ]);
+ expect(getCustomRangePosition(noDocSkeletonInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();
});
it('getEditingCustomRangePosition handles guards and success path', () => {
+ const cursorSpy = spyCursorRange();
const docSkeleton = createDocSkeleton();
const editorBridgeService = {
getEditCellState: () => ({ editorUnitId: 'doc-1', unitId: 'unit-1', sheetId: 'sheet-1', row: 1, column: 2 }),
@@ -265,5 +358,40 @@ describe('doc-skeleton-util', () => {
[IRenderManagerService, renderManagerService],
]);
expect(getEditingCustomRangePosition(hiddenInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();
+
+ const mismatchedCellInjector = createAccessor([
+ [IEditorBridgeService, { getEditCellState: () => ({ editorUnitId: 'doc-1', unitId: 'unit-1', sheetId: 'sheet-1', row: 9, column: 2 }), isVisible: () => ({ visible: true }) }],
+ [IRenderManagerService, renderManagerService],
+ ]);
+ expect(getEditingCustomRangePosition(mismatchedCellInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();
+
+ const missingRendererInjector = createAccessor([
+ [IEditorBridgeService, editorBridgeService],
+ [IRenderManagerService, { getRenderById: () => null }],
+ ]);
+ expect(getEditingCustomRangePosition(missingRendererInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();
+
+ const noEditingRangeInjector = createAccessor([
+ [IEditorBridgeService, editorBridgeService],
+ [IRenderManagerService, {
+ getRenderById: (id: string) => {
+ if (id === 'doc-1') {
+ return {
+ with: () => ({ getSkeleton: () => createDocSkeleton('other-id') }),
+ engine: {
+ getCanvasElement: () => ({
+ getBoundingClientRect: () => ({ top: 100, left: 200 }),
+ }),
+ },
+ };
+ }
+ return {
+ with: () => ({ getSkeletonParam: () => ({ skeleton: {} }) }),
+ };
+ },
+ }],
+ ]);
+ expect(getEditingCustomRangePosition(noEditingRangeInjector, 'unit-1', 'sheet-1', 1, 2, 'range-1')).toBeNull();
+ cursorSpy.mockRestore();
});
});
diff --git a/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx b/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.spec.tsx
new file mode 100644
index 0000000000..f8cf6e8d45
--- /dev/null
+++ b/packages/sheets-ui/src/views/auto-fill-popup-menu/__tests__/AutoFillPopupMenu.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 { IWorkbookData, Workbook } from '@univerjs/core';
+import type { ReactElement } from 'react';
+import type { Root } from 'react-dom/client';
+import {
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { AUTO_FILL_APPLY_TYPE, IAutoFillService, RefillCommand } from '@univerjs/sheets';
+import { RediContext } 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 { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
+import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
+import { AutoFillPopupMenu } from '../AutoFillPopupMenu';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'auto-fill-popup-unit';
+const SHEET_ID = 'sheet-1';
+
+class TestAutoFillService {
+ private readonly _menu$ = new BehaviorSubject([
+ { label: 'sheets.autoFill.copy', value: AUTO_FILL_APPLY_TYPE.COPY, disable: false },
+ { label: 'sheets.autoFill.series', value: AUTO_FILL_APPLY_TYPE.SERIES, disable: true },
+ ]);
+
+ readonly menu$ = this._menu$.asObservable();
+
+ private readonly _showMenu$ = new BehaviorSubject(false);
+ readonly showMenu$ = this._showMenu$.asObservable();
+
+ private readonly _applyType$ = new BehaviorSubject(AUTO_FILL_APPLY_TYPE.SERIES);
+ readonly applyType$ = this._applyType$.asObservable();
+
+ autoFillLocation = {
+ source: { rows: [0], cols: [0] },
+ target: { rows: [0, 1], cols: [0, 1] },
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ };
+
+ readonly refillTypes: AUTO_FILL_APPLY_TYPE[] = [];
+
+ setShowMenu(show: boolean): void {
+ this._showMenu$.next(show);
+ }
+
+ fillData(type: AUTO_FILL_APPLY_TYPE): boolean {
+ this.refillTypes.push(type);
+ this._applyType$.next(type);
+ return true;
+ }
+}
+
+class TestSheetSkeletonManagerService {
+ readonly currentSkeleton$ = new BehaviorSubject({});
+
+ getCurrentSkeleton() {
+ return {
+ getNoMergeCellWithCoordByIndex: () => ({ endX: 80, endY: 40 }),
+ };
+ }
+}
+
+class TestSheetSelectionRenderService {
+ getViewPort(): object {
+ return {};
+ }
+}
+
+class TestRenderUnit {
+ readonly components = new Map();
+ readonly mainComponent = {};
+ readonly engine = {};
+ readonly sheetSkeletonManagerService = new TestSheetSkeletonManagerService();
+ readonly selectionRenderService = new TestSheetSelectionRenderService();
+ readonly scene = {
+ scaleX: 1,
+ scaleY: 1,
+ getViewportScrollXY: () => ({ x: 0, y: 0 }),
+ getEngine: () => ({
+ getCanvas: () => ({
+ getWidth: () => 400,
+ getHeight: () => 300,
+ }),
+ }),
+ };
+
+ with(token: unknown): unknown {
+ if (token === SheetSkeletonManagerService) {
+ return this.sheetSkeletonManagerService;
+ }
+
+ if (token === ISheetSelectionRenderService) {
+ return this.selectionRenderService;
+ }
+
+ return null;
+ }
+}
+
+class TestRenderManagerService {
+ readonly renderUnit = new TestRenderUnit();
+
+ getRenderById(): TestRenderUnit {
+ return this.renderUnit;
+ }
+}
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: UNIT_ID,
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'Auto Fill Popup',
+ sheetOrder: [SHEET_ID],
+ styles: {},
+ sheets: {
+ [SHEET_ID]: {
+ id: SHEET_ID,
+ name: 'Sheet1',
+ cellData: {},
+ },
+ },
+ };
+}
+
+function createAutoFillPopupTestBed() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([IAutoFillService, { useClass: TestAutoFillService as never }]);
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);
+ injector.get(LocaleService).load({ [LocaleType.EN_US]: {} });
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ injector.get(ICommandService).registerCommand(RefillCommand);
+
+ return { univer, injector, workbook };
+}
+
+function renderWithDependencies(element: ReactElement, injector: ReturnType<typeof createAutoFillPopupTestBed>['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 };
+}
+
+async function clickElement(element: HTMLElement): Promise<void> {
+ await act(async () => {
+ element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+function getByText(text: string): HTMLElement {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node) {
+ if (node.textContent === text) {
+ const element = node.parentElement;
+ if (element) {
+ return element;
+ }
+ }
+ node = walker.nextNode();
+ }
+
+ throw new Error(`Text not found: ${text}`);
+}
+
+describe('AutoFillPopupMenu', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentBed: ReturnType<typeof createAutoFillPopupTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentBed?.univer.dispose();
+ document.body.innerHTML = '';
+ root = undefined;
+ container = undefined;
+ currentBed = undefined;
+ });
+
+ it('runs refill through the command service for the selected enabled apply type', async () => {
+ currentBed = createAutoFillPopupTestBed();
+ const autoFillService = currentBed.injector.get(IAutoFillService) as unknown as TestAutoFillService;
+ const rendered = renderWithDependencies(<AutoFillPopupMenu />, currentBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => {
+ autoFillService.setShowMenu(true);
+ });
+
+ const trigger = rendered.container.querySelector('[data-slot="dropdown-menu-trigger"]');
+ if (!(trigger instanceof HTMLElement)) {
+ throw new TypeError('Auto fill menu trigger not found');
+ }
+
+ await clickElement(trigger);
+ await clickElement(getByText('sheets.autoFill.copy'));
+
+ expect(autoFillService.refillTypes).toEqual([AUTO_FILL_APPLY_TYPE.COPY]);
+ });
+});
diff --git a/packages/sheets-ui/src/views/border-panel/__tests__/BorderPanel.spec.tsx b/packages/sheets-ui/src/views/border-panel/__tests__/BorderPanel.spec.tsx
new file mode 100644
index 0000000000..f89d156893
--- /dev/null
+++ b/packages/sheets-ui/src/views/border-panel/__tests__/BorderPanel.spec.tsx
@@ -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 type { IBorderInfo } from '@univerjs/sheets';
+import type { Root } from 'react-dom/client';
+import { BorderStyleTypes, BorderType, Univer } from '@univerjs/core';
+import { BorderStyleManagerService, SheetsSelectionsService } from '@univerjs/sheets';
+import { IconManager, RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { BorderPanel } from '../BorderPanel';
+
+class TestSheetsSelectionsService {
+ getCellStylesProperty() {
+ return {
+ isAllValuesSame: true,
+ value: {
+ t: {
+ s: BorderStyleTypes.THIN,
+ cl: { rgb: '#123456' },
+ },
+ },
+ };
+ }
+}
+
+class TestState {
+ static changes: IBorderInfo[] = [];
+
+ static reset(): void {
+ this.changes = [];
+ }
+}
+
+function renderPanel(value: IBorderInfo) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ injector.add([BorderStyleManagerService]);
+ injector.add([IconManager]);
+ injector.add([SheetsSelectionsService, { useClass: TestSheetsSelectionsService as never }]);
+
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+ const root: Root = createRoot(container);
+
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <BorderPanel
+ value={value}
+ onChange={(nextValue) => TestState.changes.push(nextValue)}
+ />
+ </RediContext.Provider>
+ );
+ });
+
+ return {
+ container,
+ dispose: () => {
+ act(() => root.unmount());
+ container.remove();
+ univer.dispose();
+ },
+ };
+}
+
+describe('BorderPanel', () => {
+ afterEach(() => {
+ TestState.reset();
+ });
+
+ it('keeps the current border color and style when selecting a new border type', () => {
+ const rendered = renderPanel({
+ type: BorderType.ALL,
+ color: '#123456',
+ style: BorderStyleTypes.THIN,
+ activeBorderType: true,
+ });
+
+ const borderTypeItems = rendered.container.querySelectorAll('a');
+ act(() => {
+ (borderTypeItems[0] as HTMLElement).click();
+ });
+
+ expect(TestState.changes).toEqual([
+ {
+ type: BorderType.TOP,
+ color: '#123456',
+ style: BorderStyleTypes.THIN,
+ activeBorderType: true,
+ },
+ ]);
+ rendered.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/views/clipboard/__tests__/ClipboardPopupMenu.spec.tsx b/packages/sheets-ui/src/views/clipboard/__tests__/ClipboardPopupMenu.spec.tsx
new file mode 100644
index 0000000000..10334ded9d
--- /dev/null
+++ b/packages/sheets-ui/src/views/clipboard/__tests__/ClipboardPopupMenu.spec.tsx
@@ -0,0 +1,250 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ReactElement } from 'react';
+import type { Root } from 'react-dom/client';
+import {
+ ICommandService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ ObjectMatrix,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { RediContext } 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 { SheetOptionalPasteCommand } from '../../../commands/commands/clipboard.command';
+import { ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '../../../services/clipboard/clipboard.service';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
+import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
+import { ClipboardPopupMenu } from '../ClipboardPopupMenu';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'clipboard-popup-unit';
+const SHEET_ID = 'sheet-1';
+
+class TestSheetClipboardService {
+ private readonly _showMenu$ = new BehaviorSubject(false);
+ readonly showMenu$ = this._showMenu$.asObservable();
+
+ private readonly _pasteOptionsCache$ = new BehaviorSubject({
+ target: {
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ pastedRange: { rows: [0, 1], cols: [0, 1] },
+ },
+ cellMatrix: new ObjectMatrix(),
+ pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE,
+ });
+
+ readonly pasteOptionsCache$ = this._pasteOptionsCache$.asObservable();
+ readonly selectedPasteTypes: string[] = [];
+
+ setShowMenu(show: boolean): void {
+ this._showMenu$.next(show);
+ }
+
+ getPasteMenuVisible(): boolean {
+ return this._showMenu$.getValue();
+ }
+
+ getPasteOptionsCache(): unknown {
+ return this._pasteOptionsCache$.getValue();
+ }
+
+ updatePasteOptionsCache(cache: unknown): void {
+ this._pasteOptionsCache$.next(cache as never);
+ }
+
+ rePasteWithPasteType(type: string): boolean {
+ this.selectedPasteTypes.push(type);
+ return true;
+ }
+}
+
+class TestSheetSkeletonManagerService {
+ getCurrentSkeleton() {
+ return {
+ getNoMergeCellWithCoordByIndex: () => ({ endX: 80, endY: 40 }),
+ };
+ }
+}
+
+class TestSheetSelectionRenderService {
+ getViewPort(): object {
+ return {};
+ }
+}
+
+class TestRenderUnit {
+ readonly components = new Map();
+ readonly mainComponent = {};
+ readonly engine = {};
+ readonly sheetSkeletonManagerService = new TestSheetSkeletonManagerService();
+ readonly selectionRenderService = new TestSheetSelectionRenderService();
+ readonly scene = {
+ scaleX: 1,
+ scaleY: 1,
+ getViewportScrollXY: () => ({ x: 0, y: 0 }),
+ getEngine: () => ({
+ getCanvas: () => ({
+ getWidth: () => 400,
+ getHeight: () => 300,
+ }),
+ }),
+ };
+
+ with(token: unknown): unknown {
+ if (token === SheetSkeletonManagerService) {
+ return this.sheetSkeletonManagerService;
+ }
+
+ if (token === ISheetSelectionRenderService) {
+ return this.selectionRenderService;
+ }
+
+ return null;
+ }
+}
+
+class TestRenderManagerService {
+ readonly renderUnit = new TestRenderUnit();
+
+ getRenderById(): TestRenderUnit {
+ return this.renderUnit;
+ }
+}
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: UNIT_ID,
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'Clipboard Popup',
+ sheetOrder: [SHEET_ID],
+ styles: {},
+ sheets: {
+ [SHEET_ID]: {
+ id: SHEET_ID,
+ name: 'Sheet1',
+ cellData: {},
+ },
+ },
+ };
+}
+
+function createClipboardPopupTestBed() {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
+ injector.add([ISheetClipboardService, { useClass: TestSheetClipboardService as never }]);
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
+ injector.get(IUniverInstanceService).focusUnit(UNIT_ID);
+ injector.get(LocaleService).load({ [LocaleType.EN_US]: {} });
+ injector.get(LocaleService).setLocale(LocaleType.EN_US);
+ injector.get(ICommandService).registerCommand(SheetOptionalPasteCommand);
+
+ return { univer, injector, workbook };
+}
+
+function renderWithDependencies(element: ReactElement, injector: ReturnType<typeof createClipboardPopupTestBed>['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 };
+}
+
+async function clickElement(element: HTMLElement): Promise<void> {
+ await act(async () => {
+ element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+function getByText(text: string): HTMLElement {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node) {
+ if (node.textContent === text) {
+ const element = node.parentElement;
+ if (element) {
+ return element;
+ }
+ }
+ node = walker.nextNode();
+ }
+
+ throw new Error(`Text not found: ${text}`);
+}
+
+describe('ClipboardPopupMenu', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let currentBed: ReturnType<typeof createClipboardPopupTestBed> | undefined;
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ container?.remove();
+ currentBed?.univer.dispose();
+ document.body.innerHTML = '';
+ root = undefined;
+ container = undefined;
+ currentBed = undefined;
+ });
+
+ it('runs optional paste through the command service with the selected paste option', async () => {
+ currentBed = createClipboardPopupTestBed();
+ const clipboardService = currentBed.injector.get(ISheetClipboardService) as unknown as TestSheetClipboardService;
+ const rendered = renderWithDependencies(<ClipboardPopupMenu />, currentBed.injector);
+ root = rendered.root;
+ container = rendered.container;
+
+ act(() => {
+ clipboardService.setShowMenu(true);
+ });
+
+ const trigger = rendered.container.querySelector('[data-slot="dropdown-menu-trigger"]');
+ if (!(trigger instanceof HTMLElement)) {
+ throw new TypeError('Clipboard menu trigger not found');
+ }
+
+ await clickElement(trigger);
+ await clickElement(getByText('sheets-ui.rightClick.pasteValue'));
+
+ expect(clipboardService.selectedPasteTypes).toEqual(['SPECIAL_PASTE_VALUE']);
+ });
+});
diff --git a/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsx b/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsx
new file mode 100644
index 0000000000..2dc81c44de
--- /dev/null
+++ b/packages/sheets-ui/src/views/dropdown/__tests__/ListDropDown.spec.tsx
@@ -0,0 +1,239 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ISheetLocation } from '@univerjs/sheets';
+import type { IPopup } from '@univerjs/ui';
+import type { ReactElement } from 'react';
+import type { IListDropdownProps } from '../ListDropDown';
+import type { IBaseDropdownProps } from '../type';
+import { Injector, LocaleService } from '@univerjs/core';
+import { serializeListOptions, SheetPermissionCheckController } from '@univerjs/sheets';
+import { RediContext } from '@univerjs/ui';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ListDropDown } from '../ListDropDown';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'list-dropdown-unit';
+const SHEET_ID = 'sheet-1';
+type IListPopupProps = IListDropdownProps & IBaseDropdownProps;
+
+class TestLocaleService {
+ t(key: string): string {
+ return key;
+ }
+}
+
+class PermissionDecision {
+ static allowed = true;
+ static checks: Array<{ ranges: unknown; unitId: string | undefined; subUnitId: string | undefined }> = [];
+
+ static reset(): void {
+ this.allowed = true;
+ this.checks = [];
+ }
+}
+
+class TestSheetPermissionCheckController {
+ permissionCheckWithRanges(permissionTypes: unknown, ranges: unknown, unitId?: string, subUnitId?: string): boolean {
+ PermissionDecision.checks.push({ ranges, unitId, subUnitId });
+ return PermissionDecision.allowed;
+ }
+}
+
+class InteractionLog {
+ static selectedValues: string[][] = [];
+ static hideCount = 0;
+ static editCount = 0;
+ static allowClose = true;
+
+ static reset(): void {
+ this.selectedValues = [];
+ this.hideCount = 0;
+ this.editCount = 0;
+ this.allowClose = true;
+ }
+
+ static async changeSelectedValues(values: string[]): Promise<boolean> {
+ this.selectedValues.push(values);
+ return this.allowClose;
+ }
+
+ static hide(): void {
+ this.hideCount += 1;
+ }
+
+ static edit(): void {
+ this.editCount += 1;
+ }
+}
+
+function createInjector() {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([SheetPermissionCheckController, { useClass: TestSheetPermissionCheckController as never }]);
+
+ return injector;
+}
+
+function createLocation(): ISheetLocation {
+ return {
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ row: 2,
+ col: 3,
+ workbook: {},
+ worksheet: {},
+ } as ISheetLocation;
+}
+
+function createPopup(extraProps: Partial<IListPopupProps> = {}): IPopup<IListPopupProps> {
+ return {
+ componentKey: ListDropDown.componentKey,
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ anchorRect: { left: 10, top: 10, right: 90, bottom: 30 },
+ extraProps: {
+ location: createLocation(),
+ hideFn: () => InteractionLog.hide(),
+ onChange: (values: string[]) => InteractionLog.changeSelectedValues(values),
+ onEdit: () => InteractionLog.edit(),
+ options: [
+ { label: 'Alpha', value: 'alpha', color: '#ffffff' },
+ { label: 'Beta', value: 'beta', color: '#2b68ff' },
+ { label: 'Gamma', value: 'gamma', color: '#f4d35e' },
+ ],
+ ...extraProps,
+ },
+ } as IPopup<IListPopupProps>;
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = createInjector();
+ 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 getByText(container: HTMLElement, text: string): HTMLElement {
+ const walker = document.createTreeWalker(container, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node) {
+ if (node.textContent === text) {
+ const element = node.parentElement;
+ if (!element) {
+ break;
+ }
+
+ return element;
+ }
+ node = walker.nextNode();
+ }
+
+ throw new Error(`Text not found: ${text}`);
+}
+
+async function clickText(container: HTMLElement, text: string) {
+ await act(async () => {
+ getByText(container, text).dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+}
+
+describe('ListDropDown', () => {
+ const disposals: Array<() => void> = [];
+
+ afterEach(() => {
+ disposals.splice(0).forEach((dispose) => dispose());
+ InteractionLog.reset();
+ PermissionDecision.reset();
+ });
+
+ it('reports multiple selections in option order and keeps the popup open when change is rejected', async () => {
+ InteractionLog.allowClose = false;
+ const { container, unmount } = renderWithDependencies(
+ <ListDropDown
+ popup={createPopup({
+ multiple: true,
+ defaultValue: serializeListOptions(['gamma']),
+ })}
+ />
+ );
+ disposals.push(unmount);
+
+ await clickText(container, 'Beta');
+
+ expect(InteractionLog.selectedValues).toEqual([['beta', 'gamma']]);
+ expect(InteractionLog.hideCount).toBe(0);
+ });
+
+ it('hides the popup after a successful single selection', async () => {
+ const { container, unmount } = renderWithDependencies(
+ <ListDropDown
+ popup={createPopup({
+ defaultValue: 'alpha',
+ })}
+ />
+ );
+ disposals.push(unmount);
+
+ await clickText(container, 'Gamma');
+
+ expect(InteractionLog.selectedValues).toEqual([['gamma']]);
+ expect(InteractionLog.hideCount).toBe(1);
+ });
+
+ it('opens the list editor only when cell edit permission allows it', async () => {
+ const { container, unmount } = renderWithDependencies(
+ <ListDropDown
+ popup={createPopup({
+ showEdit: true,
+ })}
+ />
+ );
+ disposals.push(unmount);
+
+ await clickText(container, 'sheets-ui.data-validation.list.edit');
+
+ expect(InteractionLog.editCount).toBe(1);
+ expect(PermissionDecision.checks).toEqual([
+ {
+ ranges: [{ startColumn: 3, startRow: 2, endColumn: 3, endRow: 2 }],
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ },
+ ]);
+ });
+});
diff --git a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
new file mode 100644
index 0000000000..5bd1ab2893
--- /dev/null
+++ b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
@@ -0,0 +1,166 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Injector, LocaleService } from '@univerjs/core';
+import { ContextMenuService, IContextMenuService, RediContext } 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 { MenuItemInput } from '../MenuItemInput';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestLocaleService {
+ t(key: string): string {
+ return key;
+ }
+}
+
+class ChangeRecords {
+ static values: string[] = [];
+
+ static reset(): void {
+ this.values = [];
+ }
+
+ static push(value: string): void {
+ this.values.push(value);
+ }
+}
+
+function createInjector() {
+ const injector = new Injector();
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([IContextMenuService, { useClass: ContextMenuService }]);
+
+ return injector;
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = createInjector();
+ 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 getInput(container: HTMLElement): HTMLInputElement {
+ const input = container.querySelector('input');
+ if (!(input instanceof HTMLInputElement)) {
+ throw new TypeError('Input not found');
+ }
+
+ return input;
+}
+
+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 clickIncrement(container: HTMLElement) {
+ const incrementButton = container.querySelector('[aria-label="increment"]');
+ if (!(incrementButton instanceof HTMLElement)) {
+ throw new TypeError('Increment button not found');
+ }
+
+ incrementButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
+describe('MenuItemInput', () => {
+ const disposals: Array<() => void> = [];
+
+ afterEach(() => {
+ disposals.splice(0).forEach((dispose) => dispose());
+ ChangeRecords.reset();
+ });
+
+ it('clamps typed values to the configured maximum before reporting the command value', () => {
+ const { container, unmount } = renderWithDependencies(
+ <MenuItemInput
+ prefix="sheet.menu.before"
+ suffix="sheet.menu.after"
+ value="12"
+ min={5}
+ max={20}
+ onChange={(value) => ChangeRecords.push(value)}
+ />
+ );
+ disposals.push(unmount);
+
+ act(() => {
+ setInputText(getInput(container), '38');
+ });
+
+ expect(getInput(container).value).toBe('20');
+ expect(ChangeRecords.values).toEqual(['20']);
+ });
+
+ it('uses disabled stream updates to block input changes and resumes reporting after re-enabled', () => {
+ const disabled$ = new BehaviorSubject(false);
+ const { container, unmount } = renderWithDependencies(
+ <MenuItemInput
+ prefix="sheet.menu.before"
+ suffix="sheet.menu.after"
+ value="10"
+ min={1}
+ max={20}
+ disabled$={disabled$}
+ onChange={(value) => ChangeRecords.push(value)}
+ />
+ );
+ disposals.push(unmount);
+
+ act(() => {
+ disabled$.next(true);
+ });
+ act(() => {
+ clickIncrement(container);
+ });
+
+ expect(getInput(container).value).toBe('10');
+ expect(ChangeRecords.values).toEqual([]);
+
+ act(() => {
+ disabled$.next(false);
+ });
+ act(() => {
+ clickIncrement(container);
+ });
+
+ expect(getInput(container).value).toBe('11');
+ expect(ChangeRecords.values).toEqual(['11']);
+ });
+});
diff --git a/packages/sheets-ui/src/views/permission/__tests__/PermissionDetailFooterPart.spec.tsx b/packages/sheets-ui/src/views/permission/__tests__/PermissionDetailFooterPart.spec.tsx
new file mode 100644
index 0000000000..16d5871c2f
--- /dev/null
+++ b/packages/sheets-ui/src/views/permission/__tests__/PermissionDetailFooterPart.spec.tsx
@@ -0,0 +1,349 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ReactElement } from 'react';
+import {
+ IAuthzIoService,
+ ICommandService,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { ObjectScope, UnitAction, UnitRole } from '@univerjs/protocol';
+import {
+ AddRangeProtectionCommand,
+ AddWorksheetProtectionCommand,
+ EditStateEnum,
+ UnitObject,
+ ViewStateEnum,
+} from '@univerjs/sheets';
+import { ISidebarService, 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 { UNIVER_SHEET_PERMISSION_PANEL } from '../../../consts/permission';
+import { SheetPermissionPanelModel } from '../../../services/permission/sheet-permission-panel.model';
+import { SheetPermissionUserManagerService } from '../../../services/permission/sheet-permission-user-list.service';
+import { PermissionDetailFooterPart } from '../panel-detail/PermissionDetailFooterPart';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'permission-footer-unit';
+const SHEET_ID = 'sheet-1';
+const CREATED_PERMISSION_ID = 'created-permission-id';
+
+class TestWorksheet {
+ getSheetId(): string {
+ return SHEET_ID;
+ }
+
+ getRowCount(): number {
+ return 20;
+ }
+
+ getColumnCount(): number {
+ return 10;
+ }
+}
+
+class TestWorkbook {
+ private readonly _worksheet = new TestWorksheet();
+
+ getUnitId(): string {
+ return UNIT_ID;
+ }
+
+ getActiveSheet(): TestWorksheet {
+ return this._worksheet;
+ }
+}
+
+class TestUniverInstanceService {
+ private readonly _workbook = new TestWorkbook();
+
+ getCurrentUnitOfType(unitType: UniverInstanceType): TestWorkbook | null {
+ return unitType === UniverInstanceType.UNIVER_SHEET ? this._workbook : null;
+ }
+}
+
+class TestLocaleService {
+ t(key: string): string {
+ return key;
+ }
+}
+
+class TestCommandService {
+ readonly commands: Array<{ id: string; params?: unknown }> = [];
+
+ async executeCommand(id: string, params?: unknown): Promise<boolean> {
+ this.commands.push({ id, params });
+ return true;
+ }
+}
+
+class TestAuthzIoService {
+ readonly creates: unknown[] = [];
+ readonly updates: unknown[] = [];
+
+ async create(config: unknown): Promise<string> {
+ this.creates.push(config);
+ return CREATED_PERMISSION_ID;
+ }
+
+ async update(config: unknown): Promise<void> {
+ this.updates.push(config);
+ }
+}
+
+class TestSidebarService {
+ readonly sidebarOptions$ = new Subject();
+ readonly scrollEvent$ = new Subject<Event>();
+ readonly openHistory: unknown[] = [];
+ private _container: HTMLElement = document.createElement('div');
+
+ open(params: unknown) {
+ this.openHistory.push(params);
+ return { dispose(): void {} };
+ }
+
+ close(): void {}
+
+ get visible(): boolean {
+ return this.openHistory.length > 0;
+ }
+
+ get options(): unknown {
+ return this.openHistory[this.openHistory.length - 1];
+ }
+
+ 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 createPermissionFooterTestBed() {
+ const injector = new Injector();
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([LocaleService, { useClass: TestLocaleService as never }]);
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([ISidebarService, { useClass: TestSidebarService as never }]);
+ injector.add([SheetPermissionPanelModel, { useClass: SheetPermissionPanelModel }]);
+ injector.add([SheetPermissionUserManagerService, { useClass: SheetPermissionUserManagerService }]);
+ injector.add([IAuthzIoService, { useClass: TestAuthzIoService as never }]);
+
+ return injector;
+}
+
+function renderWithDependencies(element: ReactElement, injector: 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,
+ 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 clickConfirm(container: HTMLElement) {
+ const confirmText = getByText(container, 'sheets-ui.permission.button.confirm');
+ const button = confirmText.closest('button');
+ if (!(button instanceof HTMLButtonElement)) {
+ throw new TypeError('Confirm button not found');
+ }
+
+ button.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+}
+
+describe('PermissionDetailFooterPart', () => {
+ const disposals: Array<() => void> = [];
+
+ afterEach(() => {
+ disposals.splice(0).forEach((dispose) => dispose());
+ });
+
+ it('creates range protection with selected editors and returns the sidebar to the list', async () => {
+ const injector = createPermissionFooterTestBed();
+ const userManager = injector.get(SheetPermissionUserManagerService);
+ userManager.setSelectUserList([{ id: 'user-1', subject: undefined, role: UnitRole.Reader }]);
+ const range: IRange = { startRow: 1, endRow: 3, startColumn: 2, endColumn: 4 };
+ const { container, unmount } = renderWithDependencies(
+ <PermissionDetailFooterPart
+ permissionId=""
+ id="range-rule"
+ ranges={[range]}
+ desc="Quarterly inputs"
+ editState={EditStateEnum.DesignedUserCanEdit}
+ viewState={ViewStateEnum.OthersCanView}
+ />,
+ injector
+ );
+ disposals.push(unmount);
+
+ await act(async () => {
+ clickConfirm(container);
+ await Promise.resolve();
+ });
+
+ const authzIoService = injector.get(IAuthzIoService) as unknown as TestAuthzIoService;
+ expect(authzIoService.creates).toEqual([{
+ selectRangeObject: {
+ collaborators: [{ id: 'user-1', subject: undefined, role: UnitRole.Editor }],
+ unitID: UNIT_ID,
+ name: '',
+ scope: {
+ read: ObjectScope.AllCollaborator,
+ edit: ObjectScope.SomeCollaborator,
+ },
+ },
+ objectType: UnitObject.SelectRange,
+ }]);
+
+ const commandService = injector.get(ICommandService) as unknown as TestCommandService;
+ expect(commandService.commands).toEqual([{
+ id: AddRangeProtectionCommand.id,
+ params: {
+ rule: {
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ permissionId: '',
+ id: 'range-rule',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.DesignedUserCanEdit,
+ unitType: UnitObject.SelectRange,
+ ranges: [range],
+ description: 'Quarterly inputs',
+ },
+ permissionId: CREATED_PERMISSION_ID,
+ },
+ }]);
+
+ const sidebarService = injector.get(ISidebarService) as unknown as TestSidebarService;
+ expect(sidebarService.openHistory).toEqual([{
+ header: { title: 'sheets-ui.permission.panel.title' },
+ children: {
+ label: UNIVER_SHEET_PERMISSION_PANEL,
+ showDetail: false,
+ },
+ width: 330,
+ }]);
+ });
+
+ it('converts a full-sheet range into worksheet protection before executing the add command', async () => {
+ const injector = createPermissionFooterTestBed();
+ const wholeSheetRange: IRange = { startRow: 0, endRow: 19, startColumn: 0, endColumn: 9 };
+ const { container, unmount } = renderWithDependencies(
+ <PermissionDetailFooterPart
+ permissionId=""
+ id="sheet-rule"
+ ranges={[wholeSheetRange]}
+ desc="Whole sheet locked"
+ editState={EditStateEnum.OnlyMe}
+ viewState={ViewStateEnum.OthersCanView}
+ />,
+ injector
+ );
+ disposals.push(unmount);
+
+ await act(async () => {
+ clickConfirm(container);
+ await Promise.resolve();
+ });
+
+ const authzIoService = injector.get(IAuthzIoService) as unknown as TestAuthzIoService;
+ expect(authzIoService.creates).toEqual([{
+ worksheetObject: {
+ collaborators: [],
+ unitID: UNIT_ID,
+ name: '',
+ strategies: [
+ { role: UnitRole.Editor, action: UnitAction.Edit },
+ { role: UnitRole.Reader, action: UnitAction.View },
+ ],
+ scope: {
+ read: ObjectScope.AllCollaborator,
+ edit: ObjectScope.OneSelf,
+ },
+ },
+ objectType: UnitObject.Worksheet,
+ }]);
+
+ const commandService = injector.get(ICommandService) as unknown as TestCommandService;
+ expect(commandService.commands).toEqual([{
+ id: AddWorksheetProtectionCommand.id,
+ params: {
+ rule: {
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ permissionId: CREATED_PERMISSION_ID,
+ id: 'sheet-rule',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ unitType: UnitObject.Worksheet,
+ description: 'Whole sheet locked',
+ },
+ unitId: UNIT_ID,
+ },
+ }]);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/add-merge.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/add-merge.command.spec.ts
index 8c9f257468..3365d725ce 100644
--- a/packages/sheets/src/commands/commands/__tests__/add-merge.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/add-merge.command.spec.ts
@@ -15,17 +15,41 @@
*/
import type { Injector, IWorkbookData } from '@univerjs/core';
-import { ICommandService, IConfirmService, IUniverInstanceService, LocaleService, LocaleType, RANGE_TYPE, TestConfirmService } from '@univerjs/core';
+import {
+ ICommandService,
+ IConfirmService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ RANGE_TYPE,
+ TestConfirmService,
+} from '@univerjs/core';
import { beforeEach, describe, expect, it } from 'vitest';
import enUS from '../../../locale/en-US';
import zhCN from '../../../locale/zh-CN';
+import { SheetsSelectionsService } from '../../../services/selections/selection.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { RemoveWorksheetMergeMutation } from '../../mutations/remove-worksheet-merge.mutation';
import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
import { SetSelectionsOperation } from '../../operations/selection.operation';
-import { AddWorksheetMergeCommand } from '../add-worksheet-merge.command';
+import {
+ addMergeCellsUtil,
+ AddWorksheetMergeAllCommand,
+ AddWorksheetMergeCommand,
+ AddWorksheetMergeHorizontalCommand,
+ AddWorksheetMergeVerticalCommand,
+ getMergeableSelectionsByType,
+ MergeType,
+} from '../add-worksheet-merge.command';
+import { RemoveWorksheetMergeCommand } from '../remove-worksheet-merge.command';
import { createCommandTestBed } from './create-command-test-bed';
+class DeclineConfirmService extends TestConfirmService<unknown> {
+ override confirm(): Promise<boolean> {
+ return Promise.resolve(false);
+ }
+}
+
const WORKBOOK_DATA_DEMO: IWorkbookData = {
id: 'test',
appVersion: '3.0.0-alpha',
@@ -126,16 +150,36 @@ const WORKBOOK_DATA_DEMO: IWorkbookData = {
describe('add-merge-command', () => {
let get: Injector['get'];
+ let injector: Injector;
let commandService: ICommandService;
+ function getWorksheet(getter: Injector['get'] = get) {
+ const workbook = getter(IUniverInstanceService).getUniverSheetInstance('test');
+ if (!workbook) {
+ throw new Error('Expected workbook test to exist.');
+ }
+
+ const worksheet = workbook.getSheetBySheetId('sheet1');
+ if (!worksheet) {
+ throw new Error('Expected worksheet sheet1 to exist.');
+ }
+
+ return worksheet;
+ }
+
beforeEach(() => {
const testBed = createCommandTestBed(WORKBOOK_DATA_DEMO, [
[IConfirmService, { useClass: TestConfirmService }],
]);
get = testBed.get;
+ injector = testBed.injector;
commandService = get(ICommandService);
commandService.registerCommand(AddWorksheetMergeCommand);
+ commandService.registerCommand(AddWorksheetMergeAllCommand);
+ commandService.registerCommand(AddWorksheetMergeVerticalCommand);
+ commandService.registerCommand(AddWorksheetMergeHorizontalCommand);
+ commandService.registerCommand(RemoveWorksheetMergeCommand);
commandService.registerCommand(SetRangeValuesMutation);
commandService.registerCommand(RemoveWorksheetMergeMutation);
commandService.registerCommand(AddWorksheetMergeMutation);
@@ -167,8 +211,8 @@ describe('add-merge-command', () => {
})
).toBeTruthy();
- const worksheet = get(IUniverInstanceService)?.getUniverSheetInstance('test')?.getSheetBySheetId('sheet1');
- const mergeData = worksheet?.getConfig().mergeData;
+ const worksheet = getWorksheet();
+ const mergeData = worksheet.getConfig().mergeData;
const { startRow, startColumn, endColumn, endRow } = mergeData![0];
expect({
startRow,
@@ -193,5 +237,99 @@ describe('add-merge-command', () => {
endRow: 3,
endColumn: 5,
});
+ const keptCell = worksheet.getCell(1, 5);
+ const clearedCell = worksheet.getCell(2, 5);
+ expect(keptCell && keptCell.v).toBe(3);
+ expect(clearedCell && clearedCell.v ? clearedCell.v : null).toBeNull();
+ });
+
+ it('keeps existing cells unchanged when the user cancels merging cells with content', async () => {
+ const testBed = createCommandTestBed(WORKBOOK_DATA_DEMO, [
+ [IConfirmService, { useClass: DeclineConfirmService }],
+ ]);
+ const localGet = testBed.get;
+ const localCommandService = localGet(ICommandService);
+ localCommandService.registerCommand(AddWorksheetMergeCommand);
+ localCommandService.registerCommand(SetRangeValuesMutation);
+ localCommandService.registerCommand(RemoveWorksheetMergeMutation);
+ localCommandService.registerCommand(AddWorksheetMergeMutation);
+ localCommandService.registerCommand(SetSelectionsOperation);
+ localGet(LocaleService).load({ zhCN, enUS });
+
+ await expect(localCommandService.executeCommand(AddWorksheetMergeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ selections: [{ startRow: 1, startColumn: 5, endRow: 2, endColumn: 5 }],
+ defaultMerge: false,
+ })).resolves.toBe(false);
+
+ const worksheet = getWorksheet(localGet);
+ const firstCell = worksheet.getCell(1, 5);
+ const secondCell = worksheet.getCell(2, 5);
+ expect(firstCell && firstCell.v).toBe(3);
+ expect(secondCell && secondCell.v).toBe(1);
+
+ testBed.univer.dispose();
+ });
+
+ it('filters mergeable selections by requested merge type', () => {
+ const singleCell = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 };
+ const oneRow = { startRow: 1, endRow: 1, startColumn: 1, endColumn: 3 };
+ const oneColumn = { startRow: 2, endRow: 4, startColumn: 2, endColumn: 2 };
+ const block = { startRow: 5, endRow: 6, startColumn: 5, endColumn: 6 };
+
+ expect(getMergeableSelectionsByType(MergeType.MergeAll, null)).toBeNull();
+ expect(getMergeableSelectionsByType(MergeType.MergeAll, [singleCell, oneRow, oneColumn, block])).toEqual([oneRow, oneColumn, block]);
+ expect(getMergeableSelectionsByType(MergeType.MergeVertical, [singleCell, oneRow, oneColumn, block])).toEqual([oneColumn, block]);
+ expect(getMergeableSelectionsByType(MergeType.MergeHorizontal, [singleCell, oneRow, oneColumn, block])).toEqual([oneRow, block]);
+ });
+
+ it('merges current selections through all, vertical, and horizontal commands', async () => {
+ const selectionManagerService = get(SheetsSelectionsService);
+ const worksheet = getWorksheet();
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 5, endRow: 6, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+ await expect(commandService.executeCommand(AddWorksheetMergeAllCommand.id)).resolves.toBe(true);
+ expect(worksheet.getMergeData().some((range) => range.startRow === 5 && range.endRow === 6 && range.startColumn === 0 && range.endColumn === 1)).toBe(true);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 7, endRow: 8, startColumn: 2, endColumn: 3, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+ await expect(commandService.executeCommand(AddWorksheetMergeVerticalCommand.id)).resolves.toBe(true);
+ expect(worksheet.getMergeData().some((range) => range.startRow === 7 && range.endRow === 8 && range.startColumn === 2 && range.endColumn === 2)).toBe(true);
+ expect(worksheet.getMergeData().some((range) => range.startRow === 7 && range.endRow === 8 && range.startColumn === 3 && range.endColumn === 3)).toBe(true);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 9, endRow: 10, startColumn: 4, endColumn: 5, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+ await expect(commandService.executeCommand(AddWorksheetMergeHorizontalCommand.id)).resolves.toBe(true);
+ expect(worksheet.getMergeData().some((range) => range.startRow === 9 && range.endRow === 9 && range.startColumn === 4 && range.endColumn === 5)).toBe(true);
+ expect(worksheet.getMergeData().some((range) => range.startRow === 10 && range.endRow === 10 && range.startColumn === 4 && range.endColumn === 5)).toBe(true);
+ });
+
+ it('force merges through facade utility after removing overlapping merged cells', async () => {
+ const worksheet = getWorksheet();
+ const ranges = [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 8 }];
+
+ expect(() => addMergeCellsUtil(injector, 'test', 'sheet1', ranges)).toThrow(/overlap/);
+
+ addMergeCellsUtil(injector, 'test', 'sheet1', ranges, { isForceMerge: true });
+ await Promise.resolve();
+
+ expect(worksheet.getMergeData().some((range) => range.startRow === 0 && range.endRow === 1 && range.startColumn === 0 && range.endColumn === 8)).toBe(true);
});
});
diff --git a/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts
index 702bd1d530..690dd0c5a1 100644
--- a/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/insert-range.command.spec.ts
@@ -498,6 +498,58 @@ describe('Test insert range commands', () => {
// reset data for next test
expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
});
+
+ it('will append rows with anchor height when moving data below the current data range', async () => {
+ const localTestBed = createCommandTestBed({
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ 1: {
+ 0: { v: 'A2', s: 's1' },
+ },
+ },
+ rowData: {
+ 0: { h: 40 },
+ },
+ rowCount: 10,
+ columnCount: 10,
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {
+ s1: { bg: { rgb: '#ff0000' } },
+ },
+ }, [[MergeCellController], [RefRangeService]]);
+ const localGet = localTestBed.get;
+ localGet(MergeCellController);
+ const localCommandService = localGet(ICommandService);
+ [
+ InsertRangeMoveDownCommand,
+ AddWorksheetMergeMutation,
+ RemoveWorksheetMergeMutation,
+ InsertRowMutation,
+ RemoveRowMutation,
+ SetSelectionsOperation,
+ SetRangeValuesMutation,
+ MoveRangeMutation,
+ ].forEach((c) => localCommandService.registerCommand(c));
+
+ await expect(localCommandService.executeCommand(InsertRangeMoveDownCommand.id, {
+ range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 0 },
+ })).resolves.toBe(true);
+
+ const worksheet = localGet(IUniverInstanceService).getUniverSheetInstance('test')!.getSheetBySheetId('sheet1')!;
+ expect(worksheet.getRowCount()).toBe(13);
+ expect(worksheet.getRowHeight(2)).toBe(40);
+ expect(worksheet.getCell(4, 0)?.v).toBe('A2');
+
+ localTestBed.univer.dispose();
+ });
});
describe('fault situations', () => {
diff --git a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
index 934c72bf88..e2c3487608 100644
--- a/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/insert-remove-rows-cols.command.spec.ts
@@ -17,6 +17,7 @@
import type { ICellData, Injector, IRange, IStyleData, IWorkbookData, Nullable, Univer, Workbook } from '@univerjs/core';
import type { IRemoveRowColCommandParams } from '../remove-row-col.command';
import {
+ Direction,
ICommandService,
IUniverInstanceService,
LocaleType,
@@ -30,6 +31,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MergeCellController } from '../../../controllers/merge-cell.controller';
import { RefRangeService } from '../../../services/ref-range/ref-range.service';
import { SheetsSelectionsService } from '../../../services/selections/selection.service';
+import { SheetInterceptorService } from '../../../services/sheet-interceptor/sheet-interceptor.service';
import { AddWorksheetMergeMutation } from '../../mutations/add-worksheet-merge.mutation';
import { InsertColMutation, InsertRowMutation } from '../../mutations/insert-row-col.mutation';
import { MoveRangeMutation } from '../../mutations/move-range.mutation';
@@ -102,7 +104,7 @@ describe('Test insert and remove rows cols commands', () => {
function selectRow(rowStart: number, rowEnd: number): void {
const selectionManagerService = get(SheetsSelectionsService);
const endColumn = getColCount() - 1;
- selectionManagerService.addSelections([
+ selectionManagerService.setSelections([
{
range: { startRow: rowStart, startColumn: 0, endColumn, endRow: rowEnd, rangeType: RANGE_TYPE.ROW },
primary: {
@@ -123,7 +125,7 @@ describe('Test insert and remove rows cols commands', () => {
function selectColumn(columnStart: number, columnEnd: number): void {
const selectionManagerService = get(SheetsSelectionsService);
const endRow = getRowCount() - 1;
- selectionManagerService.addSelections([
+ selectionManagerService.setSelections([
{
range: {
startRow: 0,
@@ -243,6 +245,64 @@ describe('Test insert and remove rows cols commands', () => {
// Insert row style
expect(getCellStyle(1, 0)).toBe('s1');
});
+
+ it('does not insert rows when a before-command interceptor denies the operation', async () => {
+ const sheetInterceptorService = get(SheetInterceptorService);
+ const disposable = sheetInterceptorService.interceptBeforeCommand({
+ performCheck: async (info) => info.id !== InsertRowCommand.id,
+ });
+
+ selectRow(0, 0);
+ await expect(commandService.executeCommand(InsertRowCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction: Direction.DOWN,
+ range: { startRow: 1, endRow: 1, startColumn: 0, endColumn: getColCount() - 1 },
+ })).resolves.toBe(false);
+ expect(getRowCount()).toBe(20);
+
+ disposable.dispose();
+ });
+
+ it('copies non-default row height when inserting through the row range command', async () => {
+ const result = await commandService.executeCommand(InsertRowByRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction: Direction.DOWN,
+ range: { startRow: 1, endRow: 2, startColumn: 0, endColumn: getColCount() - 1 },
+ cellValue: { 1: { 0: { s: 's1' } } },
+ });
+
+ expect(result).toBeTruthy();
+ const worksheet = get(IUniverInstanceService).getUniverSheetInstance('test')!.getSheetBySheetId('sheet1')!;
+ expect(worksheet.getRowHeight(1)).toBe(36);
+ expect(getCellStyle(1, 0)).toBe('s1');
+ });
+
+ it('inserts multiple rows above and below the selected planning rows', async () => {
+ selectRow(1, 1);
+
+ await expect(commandService.executeCommand(InsertMultiRowsAboveCommand.id, { value: 2 })).resolves.toBe(true);
+ expect(getRowCount()).toBe(22);
+ expect(getCellStyle(1, 0)).toBe('s1');
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getRowCount()).toBe(20);
+
+ selectRow(1, 2);
+ await expect(commandService.executeCommand(InsertMultiRowsAfterCommand.id, { value: 3 })).resolves.toBe(true);
+ expect(getRowCount()).toBe(23);
+ expect(getMergedInfo(5, 2)).toMatchObject({ startRow: 2, endRow: 6, startColumn: 2, endColumn: 2 });
+ });
+
+ it('rejects row insertion when the requested anchor is outside the worksheet', async () => {
+ await expect(commandService.executeCommand(InsertRowByRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction: Direction.DOWN,
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: getColCount() - 1 },
+ })).rejects.toThrow('Anchor row is out of bounds');
+ });
});
describe('Insert columns', () => {
@@ -285,6 +345,63 @@ describe('Test insert and remove rows cols commands', () => {
// Insert column style
expect(getCellStyle(0, 1)).toBe('s1');
});
+
+ it('does not insert columns when a before-command interceptor denies the operation', async () => {
+ const sheetInterceptorService = get(SheetInterceptorService);
+ const disposable = sheetInterceptorService.interceptBeforeCommand({
+ performCheck: async (info) => info.id !== InsertColCommand.id,
+ });
+
+ await expect(commandService.executeCommand(InsertColCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction: Direction.RIGHT,
+ range: { startRow: 0, endRow: getRowCount() - 1, startColumn: 1, endColumn: 1 },
+ })).resolves.toBe(false);
+ expect(getColCount()).toBe(20);
+
+ disposable.dispose();
+ });
+
+ it('copies non-default column width when inserting through the column range command', async () => {
+ const result = await commandService.executeCommand(InsertColByRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction: Direction.RIGHT,
+ range: { startRow: 0, endRow: getRowCount() - 1, startColumn: 1, endColumn: 2 },
+ cellValue: { 0: { 1: { s: 's1' } } },
+ });
+
+ expect(result).toBeTruthy();
+ const worksheet = get(IUniverInstanceService).getUniverSheetInstance('test')!.getSheetBySheetId('sheet1')!;
+ expect(worksheet.getColumnWidth(1)).toBe(112);
+ expect(getCellStyle(0, 1)).toBe('s1');
+ });
+
+ it('inserts multiple columns on both sides of a selected report block', async () => {
+ selectColumn(1, 1);
+
+ await expect(commandService.executeCommand(InsertMultiColsLeftCommand.id, { value: 2 })).resolves.toBe(true);
+ expect(getColCount()).toBe(22);
+ expect(getCellStyle(0, 1)).toBe('s1');
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getColCount()).toBe(20);
+
+ selectColumn(1, 2);
+ await expect(commandService.executeCommand(InsertMultiColsRightCommand.id, { value: 3 })).resolves.toBe(true);
+ expect(getColCount()).toBe(23);
+ expect(getMergedInfo(1, 6)).toMatchObject({ startRow: 1, endRow: 1, startColumn: 2, endColumn: 6 });
+ });
+
+ it('rejects column insertion when the requested anchor is outside the worksheet', async () => {
+ await expect(commandService.executeCommand(InsertColByRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction: Direction.RIGHT,
+ range: { startRow: 0, endRow: getRowCount() - 1, startColumn: 0, endColumn: 0 },
+ })).rejects.toThrow('Anchor column is out of bounds');
+ });
});
describe('Remove rows', () => {
@@ -406,6 +523,12 @@ const TEST_ROW_COL_INSERTION_DEMO: IWorkbookData = {
],
rowCount: 20,
columnCount: 20,
+ rowData: {
+ 0: { h: 36 },
+ },
+ columnData: {
+ 0: { w: 112 },
+ },
},
},
locale: LocaleType.ZH_CN,
diff --git a/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
new file mode 100644
index 0000000000..1a46562a5b
--- /dev/null
+++ b/packages/sheets/src/commands/commands/__tests__/permission-and-worksheet-meta.command.spec.ts
@@ -0,0 +1,546 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, IRange } from '@univerjs/core';
+import type { IRangeProtectionRule } from '../../../models/range-protection-rule.model';
+import type { IWorksheetProtectionRule } from '../../../services/permission/type';
+import { BooleanNumber, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
+import { UnitObject } from '@univerjs/protocol';
+import { describe, expect, it } from 'vitest';
+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../models/range-protection-rule.model';
+import { AddRangeProtectionMutation } from '../../mutations/add-range-protection.mutation';
+import { AddWorksheetProtectionMutation } from '../../mutations/add-worksheet-protection.mutation';
+import { DeleteRangeProtectionMutation } from '../../mutations/delete-range-protection.mutation';
+import { DeleteWorksheetProtectionMutation } from '../../mutations/delete-worksheet-protection.mutation';
+import { SetRangeProtectionMutation } from '../../mutations/set-range-protection.mutation';
+import { SetWorksheetColumnCountMutation } from '../../mutations/set-worksheet-column-count.mutation';
+import { SetWorksheetHideMutation } from '../../mutations/set-worksheet-hide.mutation';
+import { SetWorksheetPermissionPointsMutation } from '../../mutations/set-worksheet-permission-points.mutation';
+import { SetWorksheetProtectionMutation } from '../../mutations/set-worksheet-protection.mutation';
+import { SetWorksheetRightToLeftMutation } from '../../mutations/set-worksheet-right-to-left.mutation';
+import { SetWorksheetRowCountMutation } from '../../mutations/set-worksheet-row-count.mutation';
+import { SetWorksheetActiveOperation } from '../../operations/set-worksheet-active.operation';
+import { AddRangeProtectionCommand } from '../add-range-protection.command';
+import { AddWorksheetProtectionCommand } from '../add-worksheet-protection.command';
+import { DeleteRangeProtectionCommand } from '../delete-range-protection.command';
+import { DeleteWorksheetProtectionCommand } from '../delete-worksheet-protection.command';
+import { SetProtectionCommand } from '../set-protection.command';
+import { SetWorksheetColumnCountCommand } from '../set-worksheet-column-count.command';
+import { SetWorksheetPermissionPointsCommand } from '../set-worksheet-permission-points.command';
+import { SetWorksheetProtectionCommand } from '../set-worksheet-protection.command';
+import { SetWorksheetRightToLeftCommand } from '../set-worksheet-right-to-left.command';
+import { SetWorksheetRowCountCommand } from '../set-worksheet-row-count.command';
+import { SetWorksheetShowCommand } from '../set-worksheet-show.command';
+
+function createAccessor(records: Map<unknown, unknown>): IAccessor {
+ return {
+ get: (token: unknown) => records.get(token) as never,
+ has: (token: unknown) => records.has(token),
+ } as IAccessor;
+}
+
+function createCommandService(results: Record<string, boolean> = {}) {
+ const calls: Array<{ id: string; params: unknown; async: boolean }> = [];
+ return {
+ calls,
+ executeCommand: async (id: string, params: unknown) => {
+ calls.push({ id, params, async: true });
+ return results[id] ?? true;
+ },
+ syncExecuteCommand: (id: string, params: unknown) => {
+ calls.push({ id, params, async: false });
+ return results[id] ?? true;
+ },
+ };
+}
+
+function createUndoRedoService() {
+ const records: unknown[] = [];
+ return {
+ records,
+ pushUndoRedo: (record: unknown) => records.push(record),
+ };
+}
+
+function createRangeRule(id: string, range: IRange = { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }): IRangeProtectionRule {
+ return {
+ id,
+ permissionId: `permission-${id}`,
+ ranges: [range],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ unitType: UnitObject.SelectRange,
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ description: 'financial input cells',
+ };
+}
+
+function createWorksheetRule(permissionId = 'permission-sheet-1'): IWorksheetProtectionRule {
+ return {
+ permissionId,
+ unitType: UnitObject.Worksheet,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
+}
+
+function createWorkbookTarget() {
+ const config = { hidden: BooleanNumber.TRUE, rightToLeft: BooleanNumber.FALSE };
+ const worksheet = {
+ rowCount: 100,
+ columnCount: 20,
+ config,
+ getSheetId: () => 'sheet-1',
+ getConfig: () => config,
+ isSheetHidden: () => config.hidden,
+ getRowCount() { return this.rowCount; },
+ getColumnCount() { return this.columnCount; },
+ };
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: (subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null,
+ getActiveSheet: () => worksheet,
+ };
+ const univerInstanceService = {
+ getUnit: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ getCurrentUnitOfType: () => workbook,
+ getUniverSheetInstance: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ };
+ return { worksheet, workbook, univerInstanceService };
+}
+
+describe('range protection commands', () => {
+ it('adds a range protection rule and records undo/redo mutations when the mutation succeeds', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const ruleModel = new RangeProtectionRuleModel();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, ruleModel],
+ ]));
+ const sourceRule = createRangeRule('source-rule');
+
+ await expect(AddRangeProtectionCommand.handler(accessor, { permissionId: 'permission-new', rule: sourceRule })).resolves.toBe(true);
+
+ const addCall = commandService.calls[0];
+ expect(addCall.id).toBe(AddRangeProtectionMutation.id);
+ expect(addCall.params).toMatchObject({ unitId: 'unit-1', subUnitId: 'sheet-1' });
+ expect((addCall.params as { rules: IRangeProtectionRule[] }).rules[0]).toMatchObject({
+ ranges: sourceRule.ranges,
+ permissionId: 'permission-new',
+ description: sourceRule.description,
+ unitType: sourceRule.unitType,
+ unitId: sourceRule.unitId,
+ subUnitId: sourceRule.subUnitId,
+ viewState: sourceRule.viewState,
+ editState: sourceRule.editState,
+ });
+ expect(undoRedoService.records).toHaveLength(1);
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ redoMutations: [{ id: AddRangeProtectionMutation.id }],
+ undoMutations: [{ id: DeleteRangeProtectionMutation.id }],
+ });
+
+ await expect(AddRangeProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
+ });
+
+ it('does not record undo when adding range protection fails', async () => {
+ const commandService = createCommandService({ [AddRangeProtectionMutation.id]: false });
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, new RangeProtectionRuleModel()],
+ ]));
+
+ await expect(AddRangeProtectionCommand.handler(accessor, { permissionId: 'permission-new', rule: createRangeRule('source-rule') })).resolves.toBe(true);
+ expect(undoRedoService.records).toEqual([]);
+ });
+
+ it('deletes a range protection rule and keeps the deleted rule for undo', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ ]));
+ const rule = createRangeRule('rule-1');
+
+ await expect(DeleteRangeProtectionCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rule })).resolves.toBe(true);
+ expect(commandService.calls).toEqual([{ id: DeleteRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: ['rule-1'] }, async: true }]);
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ redoMutations: [{ id: DeleteRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: ['rule-1'] } }],
+ undoMutations: [{ id: AddRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [rule] } }],
+ });
+ await expect(DeleteRangeProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
+ });
+});
+
+describe('worksheet protection commands', () => {
+ it('adds, deletes, and updates worksheet protection through command mutations', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ ]));
+ const rule = createWorksheetRule('permission-new');
+ const oldRule = createWorksheetRule('permission-old');
+
+ await expect(AddWorksheetProtectionCommand.handler(accessor, { unitId: 'unit-1', rule })).resolves.toBe(true);
+ expect(commandService.calls[0]).toEqual({
+ id: AddWorksheetProtectionMutation.id,
+ params: { unitId: 'unit-1', rule, subUnitId: 'sheet-1' },
+ async: true,
+ });
+
+ expect(DeleteWorksheetProtectionCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rule })).toBe(true);
+ expect(commandService.calls[1]).toEqual({
+ id: DeleteWorksheetProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1' },
+ async: true,
+ });
+
+ await expect(SetWorksheetProtectionCommand.handler(accessor, { permissionId: 'permission-updated', rule, oldRule })).resolves.toBe(true);
+ expect(commandService.calls[2]).toEqual({
+ id: SetWorksheetProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', newRule: { ...rule, permissionId: 'permission-updated' } },
+ async: true,
+ });
+ expect(undoRedoService.records).toHaveLength(3);
+
+ await expect(AddWorksheetProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
+ expect(DeleteWorksheetProtectionCommand.handler(accessor, undefined as never)).toBe(false);
+ await expect(SetWorksheetProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
+ });
+
+ it('does not record undo when worksheet protection add or set mutations fail', async () => {
+ const commandService = createCommandService({
+ [AddWorksheetProtectionMutation.id]: false,
+ [SetWorksheetProtectionMutation.id]: false,
+ });
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ ]));
+ const rule = createWorksheetRule('permission-new');
+
+ await expect(AddWorksheetProtectionCommand.handler(accessor, { unitId: 'unit-1', rule })).resolves.toBe(true);
+ await expect(SetWorksheetProtectionCommand.handler(accessor, { permissionId: 'permission-updated', rule, oldRule: createWorksheetRule('permission-old') })).resolves.toBe(true);
+ expect(undoRedoService.records).toEqual([]);
+ });
+
+ it('sets worksheet point permissions with the target unit and sheet ids', async () => {
+ const commandService = createCommandService();
+ const accessor = createAccessor(new Map<unknown, unknown>([[ICommandService, commandService]]));
+ const rule = { unitId: 'unit-1', subUnitId: 'sheet-1', permissionId: 'permission-point-1' };
+
+ await expect(SetWorksheetPermissionPointsCommand.handler(accessor, { rule })).resolves.toBe(true);
+ expect(commandService.calls).toEqual([{ id: SetWorksheetPermissionPointsMutation.id, params: { rule, unitId: 'unit-1', subUnitId: 'sheet-1' }, async: true }]);
+ await expect(SetWorksheetPermissionPointsCommand.handler(accessor, undefined as never)).resolves.toBe(false);
+ });
+});
+
+describe('mixed protection command', () => {
+ it('updates a range protection rule in place and records the previous rule for undo', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, new RangeProtectionRuleModel()],
+ ]));
+ const oldRule = createRangeRule('rule-1', { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 });
+ const rule = {
+ ...oldRule,
+ ranges: [{ startRow: 2, endRow: 3, startColumn: 1, endColumn: 2 }],
+ description: 'approved input cells',
+ };
+
+ await expect(SetProtectionCommand.handler(accessor, { rule, oldRule } as never)).resolves.toBe(true);
+
+ expect(commandService.calls).toEqual([{
+ id: SetRangeProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', rule, ruleId: 'rule-1' },
+ async: false,
+ }]);
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleId: 'rule-1', rule: oldRule } }],
+ redoMutations: [{ id: SetRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rule, ruleId: 'rule-1' } }],
+ });
+ });
+
+ it('updates a worksheet protection rule in place and records the previous rule for undo', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, new RangeProtectionRuleModel()],
+ ]));
+ const oldRule = createWorksheetRule('worksheet-permission-old');
+ const rule = { ...oldRule, permissionId: 'worksheet-permission-new' };
+
+ await expect(SetProtectionCommand.handler(accessor, { rule, oldRule } as never)).resolves.toBe(true);
+
+ expect(commandService.calls).toEqual([{
+ id: SetWorksheetProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', rule },
+ async: false,
+ }]);
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetWorksheetProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rule: oldRule } }],
+ redoMutations: [{ id: SetWorksheetProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rule } }],
+ });
+ });
+
+ it('switches worksheet protection to range protection with reversible mutations', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const ruleModel = new RangeProtectionRuleModel();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, ruleModel],
+ ]));
+ const oldRule = createWorksheetRule('worksheet-permission');
+ const rule = createRangeRule('', { startRow: 4, endRow: 4, startColumn: 2, endColumn: 2 });
+
+ await expect(SetProtectionCommand.handler(accessor, { rule, oldRule } as never)).resolves.toBe(true);
+
+ expect(commandService.calls[0]).toMatchObject({
+ id: DeleteWorksheetProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1' },
+ });
+ expect(commandService.calls[1]).toMatchObject({
+ id: AddRangeProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [rule] },
+ });
+ expect(rule.id).not.toBe('');
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [
+ { id: DeleteRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: [rule.id] } },
+ { id: AddWorksheetProtectionMutation.id, params: { unitId: 'unit-1', rule: oldRule, subUnitId: 'sheet-1' } },
+ ],
+ redoMutations: [
+ { id: DeleteWorksheetProtectionMutation.id },
+ { id: AddRangeProtectionMutation.id },
+ ],
+ });
+
+ await expect(SetProtectionCommand.handler(accessor, undefined as never)).resolves.toBe(false);
+ });
+
+ it('switches range protection to worksheet protection with reversible mutations', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, new RangeProtectionRuleModel()],
+ ]));
+ const oldRule = createRangeRule('range-permission');
+ const rule = createWorksheetRule('worksheet-permission');
+
+ await expect(SetProtectionCommand.handler(accessor, { rule, oldRule } as never)).resolves.toBe(true);
+
+ expect(commandService.calls).toEqual([
+ {
+ id: DeleteRangeProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: ['range-permission'] },
+ async: false,
+ },
+ {
+ id: AddWorksheetProtectionMutation.id,
+ params: { unitId: 'unit-1', rule, subUnitId: 'sheet-1' },
+ async: false,
+ },
+ ]);
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [
+ { id: DeleteWorksheetProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1' } },
+ { id: AddRangeProtectionMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [oldRule] } },
+ ],
+ redoMutations: [
+ { id: DeleteRangeProtectionMutation.id },
+ { id: AddWorksheetProtectionMutation.id },
+ ],
+ });
+ });
+
+ it('does not create an undo item when protection update mutations fail', async () => {
+ const commandService = createCommandService({ [SetRangeProtectionMutation.id]: false });
+ const undoRedoService = createUndoRedoService();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [RangeProtectionRuleModel, new RangeProtectionRuleModel()],
+ ]));
+ const oldRule = createRangeRule('rule-1');
+ const rule = { ...oldRule, description: 'changed description' };
+
+ await expect(SetProtectionCommand.handler(accessor, { rule, oldRule } as never)).resolves.toBe(true);
+
+ expect(undoRedoService.records).toEqual([]);
+ });
+});
+
+describe('worksheet row, column, rtl and show commands', () => {
+ it('sets row and column counts and records previous dimensions for undo', () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const { univerInstanceService } = createWorkbookTarget();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+
+ expect(SetWorksheetRowCountCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 120 })).toBe(true);
+ expect(SetWorksheetColumnCountCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 40 })).toBe(true);
+ expect(commandService.calls).toEqual([
+ { id: SetWorksheetRowCountMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 120 }, async: false },
+ { id: SetWorksheetColumnCountMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 40 }, async: false },
+ ]);
+ expect(undoRedoService.records).toMatchObject([
+ {
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetWorksheetRowCountMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 100 } }],
+ redoMutations: [{ id: SetWorksheetRowCountMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 120 } }],
+ },
+ {
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetWorksheetColumnCountMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 20 } }],
+ redoMutations: [{ id: SetWorksheetColumnCountMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 40 } }],
+ },
+ ]);
+ });
+
+ it('returns false when worksheet count mutations cannot target or apply the sheet', () => {
+ const { univerInstanceService } = createWorkbookTarget();
+ const falseCommandService = createCommandService({
+ [SetWorksheetRowCountMutation.id]: false,
+ [SetWorksheetColumnCountMutation.id]: false,
+ });
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, falseCommandService],
+ [IUndoRedoService, createUndoRedoService()],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+
+ expect(SetWorksheetRowCountCommand.handler(accessor, { unitId: 'missing', subUnitId: 'sheet-1', rowCount: 120 })).toBe(false);
+ expect(SetWorksheetColumnCountCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'missing', columnCount: 40 })).toBe(false);
+ expect(SetWorksheetRowCountCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 120 })).toBe(false);
+ expect(SetWorksheetColumnCountCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 40 })).toBe(false);
+ });
+
+ it('sets worksheet right-to-left mode from explicit params or defaults to false', async () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const { univerInstanceService } = createWorkbookTarget();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+
+ await expect(SetWorksheetRightToLeftCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.TRUE })).resolves.toBe(true);
+ await expect(SetWorksheetRightToLeftCommand.handler(accessor)).resolves.toBe(true);
+ expect(commandService.calls).toEqual([
+ { id: SetWorksheetRightToLeftMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.TRUE }, async: false },
+ { id: SetWorksheetRightToLeftMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.FALSE }, async: false },
+ ]);
+ expect(undoRedoService.records).toHaveLength(2);
+ });
+
+ it('returns false when worksheet right-to-left cannot target or apply the sheet', async () => {
+ const { univerInstanceService } = createWorkbookTarget();
+ const accessorWithoutTarget = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, createCommandService()],
+ [IUndoRedoService, createUndoRedoService()],
+ [IUniverInstanceService, { ...univerInstanceService, getUnit: () => null, getCurrentUnitOfType: () => null }],
+ ]));
+ await expect(SetWorksheetRightToLeftCommand.handler(accessorWithoutTarget, { unitId: 'missing', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.TRUE })).resolves.toBe(false);
+
+ const falseCommandService = createCommandService({ [SetWorksheetRightToLeftMutation.id]: false });
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, falseCommandService],
+ [IUndoRedoService, createUndoRedoService()],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+ await expect(SetWorksheetRightToLeftCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.TRUE })).resolves.toBe(false);
+ });
+
+ it('shows a hidden worksheet, activates it, and records undo for the hide state', () => {
+ const commandService = createCommandService();
+ const undoRedoService = createUndoRedoService();
+ const { univerInstanceService, worksheet } = createWorkbookTarget();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+
+ expect(SetWorksheetShowCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(true);
+ expect(commandService.calls).toEqual([
+ { id: SetWorksheetHideMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', hidden: BooleanNumber.FALSE }, async: false },
+ { id: SetWorksheetActiveOperation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1' }, async: false },
+ ]);
+ expect(undoRedoService.records[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetWorksheetHideMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', hidden: BooleanNumber.TRUE } }],
+ redoMutations: [{ id: SetWorksheetHideMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', hidden: BooleanNumber.FALSE } }],
+ });
+
+ worksheet.config.hidden = BooleanNumber.FALSE;
+ expect(SetWorksheetShowCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
+ });
+
+ it('does not show a worksheet when targeting, hide mutation, or activation fails', () => {
+ const { univerInstanceService } = createWorkbookTarget();
+ const noTargetAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, createCommandService()],
+ [IUndoRedoService, createUndoRedoService()],
+ [IUniverInstanceService, { ...univerInstanceService, getUnit: () => null }],
+ ]));
+ expect(SetWorksheetShowCommand.handler(noTargetAccessor, { unitId: 'missing', subUnitId: 'sheet-1' })).toBe(false);
+
+ const failedHideAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, createCommandService({ [SetWorksheetHideMutation.id]: false })],
+ [IUndoRedoService, createUndoRedoService()],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+ expect(SetWorksheetShowCommand.handler(failedHideAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
+
+ const failedActiveAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, createCommandService({ [SetWorksheetActiveOperation.id]: false })],
+ [IUndoRedoService, createUndoRedoService()],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+ expect(SetWorksheetShowCommand.handler(failedActiveAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts
index 22274cc9f5..dd5f6d326a 100644
--- a/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/set-col-width.command.spec.ts
@@ -20,7 +20,7 @@ import { ICommandService, IUniverInstanceService, RANGE_TYPE, RedoCommand, UndoC
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SheetsSelectionsService } from '../../../services/selections/selection.service';
import { SetWorksheetColWidthMutation } from '../../mutations/set-worksheet-col-width.mutation';
-import { DeltaColumnWidthCommand, SetColWidthCommand } from '../set-worksheet-col-width.command';
+import { DeltaColumnWidthCommand, SetColWidthCommand, SetWorksheetColIsAutoWidthCommand } from '../set-worksheet-col-width.command';
import { createCommandTestBed } from './create-command-test-bed';
describe('Test set col width commands', () => {
@@ -70,6 +70,23 @@ describe('Test set col width commands', () => {
]);
}
+ function selectWholeSheet(): void {
+ const worksheet = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;
+ selectionsService.setSelections([
+ {
+ range: {
+ startRow: 0,
+ endRow: worksheet.getMaxRows() - 1,
+ startColumn: 0,
+ endColumn: worksheet.getMaxColumns() - 1,
+ rangeType: RANGE_TYPE.ALL,
+ },
+ primary: null,
+ style: null,
+ },
+ ]);
+ }
+
beforeEach(() => {
const testBed = createCommandTestBed();
univer = testBed.univer;
@@ -78,6 +95,7 @@ describe('Test set col width commands', () => {
commandService = get(ICommandService);
commandService.registerCommand(DeltaColumnWidthCommand);
commandService.registerCommand(SetColWidthCommand);
+ commandService.registerCommand(SetWorksheetColIsAutoWidthCommand);
commandService.registerCommand(SetWorksheetColWidthMutation);
const worksheet = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet()!;
@@ -151,6 +169,22 @@ describe('Test set col width commands', () => {
expect(getColumnWidth(5)).toBe(88);
expect(getColumnWidth(7)).toBe(65);
});
+
+ it('resizes every column when the whole sheet is selected', async () => {
+ selectWholeSheet();
+
+ await commandService.executeCommand<IDeltaColumnWidthCommandParams>(DeltaColumnWidthCommand.id, {
+ deltaX: 12,
+ anchorCol: 0,
+ });
+
+ expect(getColumnWidth(0)).toBe(100);
+ expect(getColumnWidth(3)).toBe(100);
+
+ await commandService.executeCommand(UndoCommand.id);
+ expect(getColumnWidth(0)).toBe(88);
+ expect(getColumnWidth(3)).toBe(88);
+ });
});
it('Direct change col widths', async () => {
@@ -181,4 +215,9 @@ describe('Test set col width commands', () => {
});
expect(getColumnWidth(1)).toBe(50);
});
+
+ it('records auto-width work for the selected columns', async () => {
+ expect(await commandService.executeCommand(SetWorksheetColIsAutoWidthCommand.id)).toBe(true);
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ });
});
diff --git a/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts b/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts
new file mode 100644
index 0000000000..95ee8a49aa
--- /dev/null
+++ b/packages/sheets/src/commands/commands/__tests__/simple-command-handlers.spec.ts
@@ -0,0 +1,808 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import {
+ CellValueType,
+ ICommandService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ ObjectMatrix,
+ PresetListType,
+} from '@univerjs/core';
+import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { SplitDelimiterEnum } from '../../../basics/split-range-text';
+import { IAutoFillService } from '../../../services/auto-fill/auto-fill.service';
+import { AUTO_FILL_APPLY_TYPE } from '../../../services/auto-fill/type';
+import { INumfmtService } from '../../../services/numfmt/type';
+import { SheetsSelectionsService } from '../../../services/selections/selection.service';
+import { SheetInterceptorService } from '../../../services/sheet-interceptor/sheet-interceptor.service';
+import { SheetSkeletonService } from '../../../skeleton/skeleton.service';
+import { InsertColMutation, InsertRowMutation } from '../../mutations/insert-row-col.mutation';
+import { RemoveNumfmtMutation, SetNumfmtMutation } from '../../mutations/numfmt.mutation';
+import { RemoveColMutation, RemoveRowMutation } from '../../mutations/remove-row-col.mutation';
+import { ReorderRangeMutation } from '../../mutations/reorder-range.mutation';
+import { SetRangeValuesMutation } from '../../mutations/set-range-values.mutation';
+import { SetSelectionsOperation } from '../../operations/selection.operation';
+import { AppendRowCommand } from '../append-row.command';
+import {
+ AutoClearContentCommand,
+ AutoFillCommand,
+ SheetCopyDownCommand,
+ SheetCopyRightCommand,
+} from '../auto-fill.command';
+import { InsertDefinedNameCommand } from '../insert-defined-name.command';
+import { RefillCommand } from '../refill.command';
+import { ReorderRangeCommand } from '../reorder-range.command';
+import { SetRangeValuesCommand } from '../set-range-values.command';
+import { SplitTextToColumnsCommand } from '../split-text-to-columns.command';
+import { TextToNumberCommand } from '../text-to-number.command';
+import { ToggleCellCheckboxCommand } from '../toggle-checkbox.command';
+
+function createAccessor(records: Map<unknown, unknown>): IAccessor {
+ return {
+ get: (token: unknown) => records.get(token) as never,
+ has: (token: unknown) => records.has(token),
+ } as IAccessor;
+}
+
+function createStyles() {
+ return {
+ getStyleByCell: (cell?: { s?: unknown }) => typeof cell?.s === 'object' ? cell.s : null,
+ get: (id: string) => id === 'text-style' ? { n: { pattern: '@' } } : null,
+ };
+}
+
+function createWorkbook(worksheet: unknown) {
+ return {
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: (subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null,
+ getActiveSheet: () => worksheet,
+ getStyles: createStyles,
+ };
+}
+
+function createUniverInstanceService(worksheet: unknown) {
+ const workbook = createWorkbook(worksheet);
+ return {
+ getUnit: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ getUniverSheetInstance: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ getCurrentUnitOfType: () => workbook,
+ };
+}
+
+describe('InsertDefinedNameCommand', () => {
+ it('creates a defined name and records the remove mutation as undo', () => {
+ const calls: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const commandService = {
+ syncExecuteCommand: (id: string, params: unknown) => {
+ calls.push({ id, params });
+ return true;
+ },
+ };
+ const undoRedoService = {
+ pushUndoRedo: (record: unknown) => undoRecords.push(record),
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, undoRedoService],
+ ]));
+ const params = {
+ unitId: 'unit-1',
+ id: 'name-1',
+ name: 'RevenueTotal',
+ formulaOrRefString: '=SUM(Sheet1!A:A)',
+ };
+
+ expect(InsertDefinedNameCommand.handler(accessor, params)).toBe(true);
+ expect(calls).toEqual([{ id: SetDefinedNameMutation.id, params }]);
+ expect(undoRecords).toEqual([{
+ unitID: 'unit-1',
+ undoMutations: [{ id: RemoveDefinedNameMutation.id, params }],
+ redoMutations: [{ id: SetDefinedNameMutation.id, params }],
+ }]);
+ });
+
+ it('does not create undo records without params or when the mutation fails', () => {
+ const undoRecords: unknown[] = [];
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => false }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ ]));
+
+ expect(InsertDefinedNameCommand.handler(accessor, undefined)).toBe(false);
+ expect(InsertDefinedNameCommand.handler(accessor, {
+ unitId: 'unit-1',
+ id: 'name-1',
+ name: 'RevenueTotal',
+ formulaOrRefString: '=SUM(Sheet1!A:A)',
+ })).toBe(false);
+ expect(undoRecords).toEqual([]);
+ });
+});
+
+describe('AppendRowCommand', () => {
+ it('inserts missing sheet rows and columns before appending cell values', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const cellMatrix = new ObjectMatrix({ 5: { 0: { v: 'old' } } });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellMatrix: () => cellMatrix,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ ]));
+ const cellValue = { 5: { 0: { v: 'new' }, 3: { v: 'overflow column' } } };
+
+ expect(AppendRowCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cellValue,
+ insertRowNums: 1,
+ insertColumnNums: 2,
+ maxRows: 5,
+ maxColumns: 3,
+ })).toBe(true);
+ expect(executed.map((call) => call.id)).toEqual([InsertColMutation.id, InsertRowMutation.id, SetRangeValuesMutation.id]);
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [
+ { id: SetRangeValuesMutation.id },
+ { id: RemoveRowMutation.id },
+ { id: RemoveColMutation.id },
+ ],
+ redoMutations: [
+ { id: InsertColMutation.id },
+ { id: InsertRowMutation.id },
+ { id: SetRangeValuesMutation.id },
+ ],
+ });
+ });
+
+ it('returns false when append mutations do not complete', () => {
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => false }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService({ getSheetId: () => 'sheet-1', getCellMatrix: () => new ObjectMatrix() })],
+ ]));
+
+ expect(AppendRowCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cellValue: { 0: { 0: { v: 'new' } } },
+ })).toBe(false);
+ });
+});
+
+describe('SetRangeValuesCommand', () => {
+ it('sets a two-dimensional value array over the current selection and follows the target range', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const cellMatrix = new ObjectMatrix({
+ 1: { 1: { v: 'old-1' }, 2: { v: 'old-2' } },
+ 2: { 1: { v: 'old-3' }, 2: { v: 'old-4' } },
+ });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellMatrix: () => cellMatrix,
+ getCellHeight: () => 24,
+ getMergedCell: () => null,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 } }] }],
+ [SheetInterceptorService, {
+ onCommandExecute: () => ({ redos: [{ id: 'interceptor-redo', params: {} }], undos: [{ id: 'interceptor-undo', params: {} }] }),
+ generateMutationsOfAutoHeight: () => ({ redos: [{ id: 'auto-height-redo', params: {} }], undos: [{ id: 'auto-height-undo', params: {} }] }),
+ }],
+ ]));
+
+ expect(SetRangeValuesCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ value: [[{ v: 'A' }, { v: 'B' }], [{ v: 'C' }, { v: 'D' }]],
+ redoUndoId: 'set-range-values-test',
+ })).toBe(true);
+ expect(executed.map((call) => call.id)).toEqual([SetRangeValuesMutation.id, 'interceptor-redo', 'auto-height-redo']);
+ expect(executed[0].params).toMatchObject({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cellValue: { 1: { 1: { v: 'A' }, 2: { v: 'B' } }, 2: { 1: { v: 'C' }, 2: { v: 'D' } } },
+ });
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ id: 'set-range-values-test',
+ undoMutations: [{ id: SetRangeValuesMutation.id }, { id: 'interceptor-undo' }, { id: 'auto-height-undo' }, { id: SetSelectionsOperation.id }],
+ redoMutations: [{ id: SetRangeValuesMutation.id }, { id: 'interceptor-redo' }, { id: 'auto-height-redo' }, { id: SetSelectionsOperation.id }],
+ });
+ });
+
+ it('returns false when no range can be resolved or post mutations fail', () => {
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellMatrix: () => new ObjectMatrix(),
+ getCellHeight: () => undefined,
+ getMergedCell: () => null,
+ };
+ const noRangeAccessor = createAccessor(new Map<unknown, unknown>([
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [SheetsSelectionsService, { getCurrentSelections: () => [] }],
+ ]));
+ expect(SetRangeValuesCommand.handler(noRangeAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1', value: { v: 'A' } })).toBe(false);
+
+ const failedAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string) => id !== 'interceptor-redo' }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }] }],
+ [SheetInterceptorService, {
+ onCommandExecute: () => ({ redos: [{ id: 'interceptor-redo', params: {} }], undos: [] }),
+ generateMutationsOfAutoHeight: () => ({ redos: [], undos: [] }),
+ }],
+ ]));
+ expect(SetRangeValuesCommand.handler(failedAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1', value: { v: 'A' } })).toBe(false);
+ });
+});
+
+describe('RefillCommand', () => {
+ it('delegates the selected auto-fill apply type to the auto-fill service', async () => {
+ const filledTypes: AUTO_FILL_APPLY_TYPE[] = [];
+ const autoFillService = {
+ fillData: (type: AUTO_FILL_APPLY_TYPE) => {
+ filledTypes.push(type);
+ return type === AUTO_FILL_APPLY_TYPE.COPY;
+ },
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([[IAutoFillService, autoFillService]]));
+
+ await expect(RefillCommand.handler(accessor, { type: AUTO_FILL_APPLY_TYPE.COPY })).resolves.toBe(true);
+ await expect(RefillCommand.handler(accessor, { type: AUTO_FILL_APPLY_TYPE.NO_FORMAT })).resolves.toBe(false);
+ expect(filledTypes).toEqual([AUTO_FILL_APPLY_TYPE.COPY, AUTO_FILL_APPLY_TYPE.NO_FORMAT]);
+ });
+});
+
+describe('AutoFillCommand family', () => {
+ it('delegates explicit auto-fill ranges to the auto-fill service target', async () => {
+ const calls: unknown[] = [];
+ const worksheet = { getSheetId: () => 'sheet-1' };
+ const autoFillService = {
+ triggerAutoFill: (...args: unknown[]) => {
+ calls.push(args);
+ return Promise.resolve(true);
+ },
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [IAutoFillService, autoFillService],
+ ]));
+ const sourceRange = { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 };
+ const targetRange = { startRow: 0, endRow: 4, startColumn: 0, endColumn: 1 };
+
+ await expect(AutoFillCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', sourceRange, targetRange, applyType: AUTO_FILL_APPLY_TYPE.SERIES })).resolves.toBe(true);
+ expect(calls).toEqual([['unit-1', 'sheet-1', sourceRange, targetRange, AUTO_FILL_APPLY_TYPE.SERIES]]);
+
+ const noTargetAccessor = createAccessor(new Map<unknown, unknown>([
+ [IUniverInstanceService, { getUnit: () => null }],
+ [IAutoFillService, autoFillService],
+ ]));
+ await expect(AutoFillCommand.handler(noTargetAccessor, { unitId: 'missing', subUnitId: 'sheet-1', sourceRange, targetRange })).resolves.toBe(false);
+ });
+
+ it('copy-fills down and right from the current selection and hides the apply menu after success', async () => {
+ const commandCalls: unknown[] = [];
+ const shownStates: boolean[] = [];
+ const worksheet = { getSheetId: () => 'sheet-1' };
+ const commandService = {
+ executeCommand: async (id: string, params: unknown) => {
+ commandCalls.push({ id, params });
+ return true;
+ },
+ };
+ const autoFillService = {
+ setShowMenu: (show: boolean) => shownStates.push(show),
+ };
+ const selections = [
+ { range: { startRow: 3, endRow: 3, startColumn: 0, endColumn: 2 } },
+ { range: { startRow: 1, endRow: 3, startColumn: 4, endColumn: 4 } },
+ ];
+ let selectionIndex = 0;
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [IAutoFillService, autoFillService],
+ [SheetsSelectionsService, { getCurrentLastSelection: () => selections[selectionIndex++] }],
+ ]));
+
+ await expect(SheetCopyDownCommand.handler(accessor)).resolves.toBe(true);
+ await expect(SheetCopyRightCommand.handler(accessor)).resolves.toBe(true);
+ expect(commandCalls).toEqual([
+ {
+ id: AutoFillCommand.id,
+ params: {
+ sourceRange: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 2 },
+ targetRange: { startRow: 2, endRow: 3, startColumn: 0, endColumn: 2 },
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ applyType: AUTO_FILL_APPLY_TYPE.COPY,
+ },
+ },
+ {
+ id: AutoFillCommand.id,
+ params: {
+ sourceRange: { startRow: 1, endRow: 3, startColumn: 3, endColumn: 3 },
+ targetRange: { startRow: 1, endRow: 3, startColumn: 3, endColumn: 4 },
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ applyType: AUTO_FILL_APPLY_TYPE.COPY,
+ },
+ },
+ ]);
+ expect(shownStates).toEqual([false, false]);
+ });
+
+ it('does not copy-fill when the selection cannot produce a source range or the command fails', async () => {
+ const worksheet = { getSheetId: () => 'sheet-1' };
+ const accessorAtTopLeft = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { executeCommand: async () => true }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [IAutoFillService, { setShowMenu: () => undefined }],
+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }) }],
+ ]));
+ await expect(SheetCopyDownCommand.handler(accessorAtTopLeft)).resolves.toBe(false);
+ await expect(SheetCopyRightCommand.handler(accessorAtTopLeft)).resolves.toBe(false);
+
+ const shownStates: boolean[] = [];
+ const failedAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { executeCommand: async () => false }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [IAutoFillService, { setShowMenu: (show: boolean) => shownStates.push(show) }],
+ [SheetsSelectionsService, { getCurrentLastSelection: () => ({ range: { startRow: 2, endRow: 4, startColumn: 0, endColumn: 1 } }) }],
+ ]));
+ await expect(SheetCopyDownCommand.handler(failedAccessor)).resolves.toBe(false);
+ expect(shownStates).toEqual([]);
+ });
+
+ it('clears dragged content, restores selection on undo, and runs after-interceptor mutations', async () => {
+ const executed: unknown[] = [];
+ const undoRecords: unknown[] = [];
+ const oldSelection = { range: { startRow: 9, endRow: 9, startColumn: 9, endColumn: 9 } };
+ const cellMatrix = new ObjectMatrix({ 2: { 2: { v: 'old' } } });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellMatrix: () => cellMatrix,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [SheetsSelectionsService, { getCurrentLastSelection: () => oldSelection }],
+ [SheetInterceptorService, { afterCommandExecute: () => ({ redos: [{ id: 'after-redo', params: {} }], undos: [{ id: 'after-undo', params: {} }] }) }],
+ ]));
+
+ await expect(AutoClearContentCommand.handler(accessor, {
+ clearRange: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 3 },
+ selectionRange: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 3 },
+ })).resolves.toBe(true);
+ expect((executed[0] as { id: string }).id).toBe(SetRangeValuesMutation.id);
+ expect((executed[1] as { id: string }).id).toBe(SetSelectionsOperation.id);
+ expect((executed[2] as { id: string }).id).toBe('after-redo');
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [
+ { id: SetRangeValuesMutation.id },
+ { id: SetSelectionsOperation.id, params: { selections: [oldSelection], unitId: 'unit-1', subUnitId: 'sheet-1' } },
+ { id: 'after-undo' },
+ ],
+ });
+ });
+});
+
+describe('TextToNumberCommand', () => {
+ it('converts numeric text cells and removes text number format where needed', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const cellMatrix = new ObjectMatrix({
+ 0: {
+ 0: { v: '42', t: CellValueType.STRING },
+ 1: { v: '003', t: CellValueType.NUMBER, s: 'text-style' },
+ 2: { v: 'abc', t: CellValueType.STRING },
+ },
+ });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellRaw: (row: number, col: number) => cellMatrix.getValue(row, col),
+ getCellMatrix: () => cellMatrix,
+ getStyleDataByHash: (id: string) => id === 'text-style' ? { n: { pattern: '@' } } : null,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [INumfmtService, { getValue: (_unitId: string, _subUnitId: string, row: number, col: number) => row === 0 && col === 1 ? { pattern: '@' } : null }],
+ ]));
+
+ expect(TextToNumberCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }],
+ })).toBe(true);
+ expect(executed.map((call) => call.id)).toEqual([SetRangeValuesMutation.id, RemoveNumfmtMutation.id]);
+ expect(executed[0].params).toMatchObject({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cellValue: {
+ 0: {
+ 0: { v: 42, t: CellValueType.NUMBER },
+ 1: { v: 3, t: CellValueType.NUMBER },
+ },
+ },
+ });
+ expect(executed[1].params).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }],
+ });
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetRangeValuesMutation.id }, { id: SetNumfmtMutation.id }],
+ });
+ });
+
+ it('returns false without a target, without ranges, or when mutation execution fails', () => {
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellRaw: () => ({ v: '42', t: CellValueType.STRING }),
+ getCellMatrix: () => new ObjectMatrix(),
+ getStyleDataByHash: () => null,
+ };
+ const noTargetAccessor = createAccessor(new Map<unknown, unknown>([
+ [IUniverInstanceService, { getUnit: () => null }],
+ ]));
+ expect(TextToNumberCommand.handler(noTargetAccessor, { unitId: 'missing', subUnitId: 'sheet-1', ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] })).toBe(false);
+
+ const noRangesAccessor = createAccessor(new Map<unknown, unknown>([
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [SheetsSelectionsService, { getCurrentSelections: () => [] }],
+ ]));
+ expect(TextToNumberCommand.handler(noRangesAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
+
+ const failedAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => false }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ ]));
+ expect(TextToNumberCommand.handler(failedAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }] })).toBe(false);
+ });
+
+ it('uses current selections when ranges are omitted', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const cellMatrix = new ObjectMatrix({ 2: { 2: { v: '56', t: CellValueType.STRING } } });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellRaw: (row: number, col: number) => cellMatrix.getValue(row, col),
+ getCellMatrix: () => cellMatrix,
+ getStyleDataByHash: () => null,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 } }] }],
+ ]));
+
+ expect(TextToNumberCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(true);
+ expect(executed[0]).toMatchObject({
+ id: SetRangeValuesMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cellValue: { 2: { 2: { v: 56, t: CellValueType.NUMBER } } },
+ },
+ });
+ expect(undoRecords).toHaveLength(1);
+ });
+});
+
+describe('ToggleCellCheckboxCommand', () => {
+ function createChecklistCell() {
+ return {
+ p: {
+ id: 'doc-1',
+ body: {
+ dataStream: 'Alpha\rBeta\r\n',
+ paragraphs: [
+ { startIndex: 5, paragraphId: 'para-1' },
+ {
+ startIndex: 10,
+ paragraphId: 'para-2',
+ bullet: {
+ listId: 'check-1',
+ listType: PresetListType.CHECK_LIST,
+ nestingLevel: 0,
+ },
+ },
+ ],
+ },
+ },
+ };
+ }
+
+ it('toggles a rich-text checklist paragraph and records undo from the old cell value', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const cell = createChecklistCell();
+ const cellMatrix = new ObjectMatrix({ 4: { 3: cell } });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCell: (row: number, col: number) => cellMatrix.getValue(row, col),
+ getCellMatrix: () => cellMatrix,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ ]));
+
+ expect(ToggleCellCheckboxCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 4,
+ col: 3,
+ paragraphIndex: 10,
+ })).toBe(true);
+
+ const redoCell = (executed[0].params as { cellValue: Record<number, Record<number, { t: CellValueType; p: { body: { paragraphs: Array<{ bullet?: { listType: string } }> } } }>> }).cellValue[4][3];
+ expect(executed[0].id).toBe(SetRangeValuesMutation.id);
+ expect(redoCell.t).toBe(CellValueType.STRING);
+ expect(redoCell.p.body.paragraphs[1].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ redoMutations: [{ id: SetRangeValuesMutation.id }],
+ undoMutations: [{ id: SetRangeValuesMutation.id }],
+ });
+ });
+
+ it('returns false when checkbox toggle has no target rich text or paragraph', () => {
+ const worksheetWithoutRichText = {
+ getSheetId: () => 'sheet-1',
+ getCell: () => ({ v: 'plain' }),
+ getCellMatrix: () => new ObjectMatrix(),
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => true }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService(worksheetWithoutRichText)],
+ ]));
+
+ expect(ToggleCellCheckboxCommand.handler(accessor, undefined as never)).toBe(false);
+ expect(ToggleCellCheckboxCommand.handler(accessor, { unitId: 'missing', subUnitId: 'sheet-1', row: 0, col: 0, paragraphIndex: 0 })).toBe(false);
+ expect(ToggleCellCheckboxCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', row: 0, col: 0, paragraphIndex: 0 })).toBe(false);
+
+ const cell = createChecklistCell();
+ const cellMatrix = new ObjectMatrix({ 4: { 3: cell } });
+ const invalidParagraphAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => true }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService({
+ getSheetId: () => 'sheet-1',
+ getCell: (row: number, col: number) => cellMatrix.getValue(row, col),
+ getCellMatrix: () => cellMatrix,
+ })],
+ ]));
+ expect(ToggleCellCheckboxCommand.handler(invalidParagraphAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1', row: 4, col: 3, paragraphIndex: 999 })).toBe(false);
+ });
+});
+
+describe('SplitTextToColumnsCommand', () => {
+ it('splits single-column text into adjacent columns and inserts columns when output exceeds sheet width', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const cellMatrix = new ObjectMatrix({
+ 0: { 1: { v: 'North,West,East', t: CellValueType.STRING } },
+ 1: { 1: { v: '1,2,3', t: CellValueType.STRING } },
+ });
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getColumnCount: () => 3,
+ getRowCount: () => 10,
+ getMaxColumns: () => 3,
+ getMaxRows: () => 10,
+ getCell: (row: number, col: number) => cellMatrix.getValue(row, col),
+ getCellMatrix: () => cellMatrix,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ } }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ ]));
+
+ expect(SplitTextToColumnsCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 0, endRow: 1, startColumn: 1, endColumn: 1 },
+ delimiter: SplitDelimiterEnum.Comma,
+ })).toBe(true);
+
+ expect(executed.map((call) => call.id)).toEqual(['sheet.mutation.insert-col', SetRangeValuesMutation.id]);
+ expect(executed[1].params).toMatchObject({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cellValue: {
+ 0: {
+ 1: { v: 'North' },
+ 2: { v: 'West' },
+ 3: { v: 'East' },
+ },
+ 1: {
+ 1: { v: '1' },
+ 2: { v: '2' },
+ 3: { v: '3' },
+ },
+ },
+ });
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [{ id: SetRangeValuesMutation.id }, { id: 'sheet.mutation.remove-col' }],
+ });
+ });
+
+ it('returns false for multi-column source ranges, missing targets, or failed mutation sequence', () => {
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getColumnCount: () => 5,
+ getRowCount: () => 10,
+ getMaxColumns: () => 5,
+ getMaxRows: () => 10,
+ getCell: () => ({ v: 'A,B', t: CellValueType.STRING }),
+ getCellMatrix: () => new ObjectMatrix(),
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => true }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ ]));
+ expect(() => SplitTextToColumnsCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 } })).toThrowError('The range must be in the same column.');
+
+ const noTargetAccessor = createAccessor(new Map<unknown, unknown>([[IUniverInstanceService, { getUnit: () => null }]]));
+ expect(SplitTextToColumnsCommand.handler(noTargetAccessor, { unitId: 'missing', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } })).toBe(false);
+
+ const failedAccessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => false }],
+ [IUndoRedoService, { pushUndoRedo: () => undefined }],
+ [IUniverInstanceService, createUniverInstanceService(worksheet)],
+ ]));
+ expect(SplitTextToColumnsCommand.handler(failedAccessor, { unitId: 'unit-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } })).toBe(false);
+ });
+});
+
+describe('ReorderRangeCommand', () => {
+ it('executes reorder with interceptor and auto-height mutations and records undo/redo', () => {
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const undoRecords: unknown[] = [];
+ const commandService = {
+ syncExecuteCommand: (id: string, params: unknown) => {
+ executed.push({ id, params });
+ return true;
+ },
+ };
+ const sheetInterceptorService = {
+ onCommandExecute: () => ({
+ preRedos: [{ id: 'pre-redo', params: { stage: 'before' } }],
+ redos: [{ id: 'redo-after-reorder', params: { stage: 'during' } }],
+ preUndos: [{ id: 'pre-undo', params: { stage: 'before' } }],
+ undos: [{ id: 'undo-after-reorder', params: { stage: 'during' } }],
+ }),
+ afterCommandExecute: () => ({
+ redos: [{ id: 'post-redo', params: { stage: 'after' } }],
+ undos: [{ id: 'post-undo', params: { stage: 'after' } }],
+ }),
+ generateMutationsOfAutoHeight: () => ({
+ redos: [{ id: 'auto-height-redo', params: { stage: 'height' } }],
+ undos: [{ id: 'auto-height-undo', params: { stage: 'height' } }],
+ }),
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, commandService],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [SheetInterceptorService, sheetInterceptorService],
+ [SheetSkeletonService, { getSkeleton: () => null }],
+ ]));
+ const range = { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 };
+
+ expect(ReorderRangeCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range,
+ order: { 0: 2, 1: 0, 2: 1 },
+ })).toBe(true);
+
+ expect(executed).toEqual([
+ { id: 'pre-redo', params: { stage: 'before' } },
+ { id: ReorderRangeMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', range, order: { 0: 2, 1: 0, 2: 1 } } },
+ { id: 'redo-after-reorder', params: { stage: 'during' } },
+ { id: 'post-redo', params: { stage: 'after' } },
+ { id: 'auto-height-redo', params: { stage: 'height' } },
+ ]);
+ expect(undoRecords[0]).toMatchObject({
+ unitID: 'unit-1',
+ undoMutations: [
+ { id: 'pre-undo' },
+ { id: ReorderRangeMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', range, order: { 0: 1, 1: 2, 2: 0 } } },
+ { id: 'undo-after-reorder' },
+ { id: 'post-undo' },
+ { id: 'auto-height-undo' },
+ ],
+ redoMutations: [
+ { id: 'pre-redo' },
+ { id: ReorderRangeMutation.id },
+ { id: 'redo-after-reorder' },
+ { id: 'post-redo' },
+ { id: 'auto-height-redo' },
+ ],
+ });
+ });
+
+ it('returns false and skips undo records when the reorder sequence fails', () => {
+ const undoRecords: unknown[] = [];
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [ICommandService, { syncExecuteCommand: () => false }],
+ [IUndoRedoService, { pushUndoRedo: (record: unknown) => undoRecords.push(record) }],
+ [SheetInterceptorService, {
+ onCommandExecute: () => ({ preRedos: [], redos: [], preUndos: [], undos: [] }),
+ afterCommandExecute: () => ({ redos: [], undos: [] }),
+ generateMutationsOfAutoHeight: () => ({ redos: [], undos: [] }),
+ }],
+ [SheetSkeletonService, { getSkeleton: () => null }],
+ ]));
+
+ expect(ReorderRangeCommand.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ order: { 0: 1, 1: 0 },
+ })).toBe(false);
+ expect(undoRecords).toEqual([]);
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/util-extra.spec.ts b/packages/sheets/src/commands/commands/__tests__/util-extra.spec.ts
index 61e4c98ec1..dbd3280f68 100644
--- a/packages/sheets/src/commands/commands/__tests__/util-extra.spec.ts
+++ b/packages/sheets/src/commands/commands/__tests__/util-extra.spec.ts
@@ -14,9 +14,31 @@
* limitations under the License.
*/
-import { ObjectMatrix } from '@univerjs/core';
+import { Dimension, ObjectMatrix, RANGE_TYPE } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import { SheetsSelectionsService } from '../../../services/selections/selection.service';
+import { SelectionMoveType } from '../../../services/selections/type';
+import { SetSelectionsOperation } from '../../operations/selection.operation';
+import { AddMergeRedoSelectionsOperationFactory, AddMergeUndoSelectionsOperationFactory } from '../../utils/handle-merge-operation';
+import {
+ DeleteRangeUndoMutationFactory,
+ handleDeleteRangeMutation,
+ handleInsertRangeMutation,
+ InsertRangeUndoMutationFactory,
+} from '../../utils/handle-range.mutation';
import { countCells, getSuitableRangesInView } from '../util';
+import {
+ alignToMergedCellsBorders,
+ calculateTotalLength,
+ copyRangeStyles,
+ copyRangeStylesWithoutBorder,
+ createRangeIteratorWithSkipFilteredRows,
+ followSelectionOperation,
+ getCellAtRowCol,
+ getPrimaryForRange,
+ isSingleCellSelection,
+ setEndForRange,
+} from '../utils/selection-utils';
describe('sheets command util', () => {
it('should select nearest ranges and split overflow range by max visible row quota', () => {
@@ -54,4 +76,180 @@ describe('sheets command util', () => {
expect(countCells(matrix)).toBe(3);
});
+
+ it('should generate merge selection redo and undo operations from the current primary cell', () => {
+ const currentSelections = [
+ {
+ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ primary: { actualRow: 1, actualColumn: 1 },
+ },
+ ];
+ const accessor = {
+ get: (token: unknown) => token === SheetsSelectionsService ? { getCurrentSelections: () => currentSelections } : null,
+ } as any;
+ const params = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ value: Dimension.ROWS,
+ selections: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }],
+ };
+
+ expect(AddMergeRedoSelectionsOperationFactory(accessor, params as any, [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 4 }])).toEqual({
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ type: SelectionMoveType.ONLY_SET,
+ selections: [{
+ range: currentSelections[0].range,
+ style: null,
+ primary: {
+ startRow: 1,
+ startColumn: 1,
+ endRow: 1,
+ endColumn: 4,
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: true,
+ isMergedMainCell: true,
+ },
+ }],
+ },
+ });
+ expect(AddMergeUndoSelectionsOperationFactory(accessor, params as any)).toEqual({
+ id: SetSelectionsOperation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ type: SelectionMoveType.ONLY_SET,
+ selections: currentSelections,
+ },
+ });
+ expect(AddMergeRedoSelectionsOperationFactory({ get: () => ({ getCurrentSelections: () => [] }) } as any, params as any, [])).toBeNull();
+ expect(AddMergeUndoSelectionsOperationFactory({ get: () => ({ getCurrentSelections: () => [{ range: {}, primary: null }] }) } as any, params as any)).toBeNull();
+ });
+
+ it('should shift object matrix cells when inserting or deleting ranges', () => {
+ const rowMatrix = new ObjectMatrix<string>({
+ 0: { 0: 'A0' },
+ 1: { 0: 'A1' },
+ 2: { 0: 'A2' },
+ });
+ handleInsertRangeMutation(rowMatrix, { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 }, 2, 0, Dimension.ROWS, { 1: { 0: 'inserted' } });
+ expect(rowMatrix.getValue(1, 0)).toBe('inserted');
+ expect(rowMatrix.getValue(2, 0)).toBe('A1');
+ expect(rowMatrix.getValue(3, 0)).toBe('A2');
+
+ handleDeleteRangeMutation(rowMatrix, { startRow: 1, endRow: 1, startColumn: 0, endColumn: 0 }, 3, 0, Dimension.ROWS);
+ expect(rowMatrix.getValue(1, 0)).toBe('A1');
+ expect(rowMatrix.getValue(2, 0)).toBe('A2');
+
+ const colMatrix = new ObjectMatrix<string>({
+ 0: { 0: 'A', 1: 'B', 2: 'C' },
+ });
+ handleInsertRangeMutation(colMatrix, { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }, 0, 2, Dimension.COLUMNS, { 0: { 1: 'inserted' } });
+ expect(colMatrix.getValue(0, 1)).toBe('inserted');
+ expect(colMatrix.getValue(0, 2)).toBe('B');
+ expect(colMatrix.getValue(0, 3)).toBe('C');
+
+ handleDeleteRangeMutation(colMatrix, { startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }, 0, 3, Dimension.COLUMNS);
+ expect(colMatrix.getValue(0, 1)).toBe('B');
+ expect(colMatrix.getValue(0, 2)).toBe('C');
+ });
+
+ it('should build range mutation undo params from worksheet state', () => {
+ const cellMatrix = new ObjectMatrix({ 0: { 0: { v: 'A' }, 1: { v: 'B' } } });
+ const worksheet = {
+ getCellMatrix: () => cellMatrix,
+ getConfig: () => ({ rowCount: 2, columnCount: 2 }),
+ };
+ const accessor = {
+ get: () => ({
+ getUnit: () => ({ getSheetBySheetId: () => worksheet }),
+ }),
+ } as any;
+ const params = { unitId: 'unit-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, shiftDimension: Dimension.ROWS };
+
+ expect(InsertRangeUndoMutationFactory(accessor, params)).toEqual(params);
+ expect(DeleteRangeUndoMutationFactory(accessor, params)).toMatchObject({
+ ...params,
+ cellValue: { 0: { 0: { v: 'A' } } },
+ });
+ expect(DeleteRangeUndoMutationFactory({ get: () => ({ getUnit: () => null }) } as any, params)).toBeNull();
+ });
+
+ it('should align selection helpers to merged cells and worksheet bounds', () => {
+ const mergedMatrix = new ObjectMatrix({ 0: { 0: { rowSpan: 2, colSpan: 2 } } });
+ const worksheet = {
+ getMatrixWithMergedCells: () => mergedMatrix,
+ getMergedCell: () => ({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }),
+ };
+
+ expect(alignToMergedCellsBorders({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, worksheet as any)).toMatchObject({
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 1,
+ });
+ expect(getCellAtRowCol(0, 0, worksheet as any)).toEqual({
+ actualRow: 0,
+ actualColumn: 0,
+ startRow: 0,
+ startColumn: 0,
+ endRow: 1,
+ endColumn: 1,
+ isMerged: true,
+ isMergedMainCell: true,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+ expect(getPrimaryForRange({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, worksheet as any)).toMatchObject({
+ startRow: 0,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 1,
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: true,
+ isMergedMainCell: true,
+ });
+
+ expect(setEndForRange({ startRow: Number.NaN, endRow: Number.NaN, startColumn: Number.NaN, endColumn: Number.NaN }, 10, 5)).toEqual({
+ startRow: 0,
+ endRow: 9,
+ startColumn: 0,
+ endColumn: 4,
+ });
+ expect(calculateTotalLength({ a: [0, 2], b: [5, 7] })).toBe(8);
+ expect(isSingleCellSelection({ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }, primary: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 } } as any)).toBe(true);
+ expect(isSingleCellSelection(null)).toBe(false);
+ expect(followSelectionOperation({ startRow: 2, endRow: 2, startColumn: 3, endColumn: 3 }, { getUnitId: () => 'unit-1' } as any, { getSheetId: () => 'sheet-1', getMergedCell: () => null } as any)).toMatchObject({
+ id: SetSelectionsOperation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', reveal: true },
+ });
+ });
+
+ it('should iterate only operable cells and copy reusable range styles', () => {
+ const visited: Array<[number, number]> = [];
+ const iterator = createRangeIteratorWithSkipFilteredRows({
+ getRowFiltered: (row: number) => row === 1,
+ } as any);
+ iterator.forOperableEach({ startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 }, (row, col) => visited.push([row, col]));
+ expect(visited).toEqual([[0, 0], [0, 1], [2, 0], [2, 1]]);
+
+ const worksheet = {
+ getCellWithFilteredInterceptors: (row: number, col: number) => {
+ if (row === 0 && col === 0) return { s: { bg: { rgb: '#fff' } } };
+ if (row === 0 && col === 1) return { s: {} };
+ return null;
+ },
+ getStyleDataByHash: () => ({ bg: { rgb: '#000' }, bd: { t: { s: 1 } } }),
+ setStyleData: (style: unknown) => `style:${JSON.stringify(style)}`,
+ };
+ expect(copyRangeStyles(worksheet as any, 1, 1, 0, 1, true, 0)).toEqual({
+ 1: { 0: { s: { bg: { rgb: '#fff' } } } },
+ });
+ expect(copyRangeStylesWithoutBorder({ ...worksheet, getCellWithFilteredInterceptors: () => ({ s: 'style-hash' }) } as any, 1, 1, 0, 0, true, 0)).toEqual({
+ 1: { 0: { s: 'style:{"bg":{"rgb":"#000"}}' } },
+ });
+ });
});
diff --git a/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts
index 65208196fd..561692f80a 100644
--- a/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts
+++ b/packages/sheets/src/commands/mutations/__tests__/worksheet-meta.mutation.spec.ts
@@ -15,7 +15,7 @@
*/
import type { IAccessor } from '@univerjs/core';
-import { IUniverInstanceService } from '@univerjs/core';
+import { BooleanNumber, IUniverInstanceService } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import {
SetGridlinesColorMutation,
@@ -23,6 +23,14 @@ import {
} from '../set-gridlines-color.mutation';
import { SetWorksheetHideMutation, SetWorksheetHideMutationFactory } from '../set-worksheet-hide.mutation';
import { SetWorksheetNameMutation, SetWorksheetNameMutationFactory } from '../set-worksheet-name.mutation';
+import {
+ SetWorksheetRowAutoHeightMutation,
+ SetWorksheetRowAutoHeightMutationFactory,
+ SetWorksheetRowHeightMutation,
+ SetWorksheetRowHeightMutationFactory,
+ SetWorksheetRowIsAutoHeightMutation,
+ SetWorksheetRowIsAutoHeightMutationFactory,
+} from '../set-worksheet-row-height.mutation';
function createAccessor(instanceService: unknown): IAccessor {
return {
@@ -244,4 +252,75 @@ describe('worksheet meta mutations', () => {
})
).toThrowError('[SetWorksheetNameMutationFactory]: worksheet is null error!');
});
+
+ it('row height mutations should update height, auto-height flag, and measured auto height', () => {
+ const rows: Record<number, { h?: number; ia?: BooleanNumber; ah?: number }> = {
+ 1: { h: 24, ia: BooleanNumber.TRUE, ah: 28 },
+ 2: {},
+ };
+ const manager = {
+ getRow: (row: number) => rows[row],
+ getRowOrCreate: (row: number) => {
+ rows[row] ??= {};
+ return rows[row];
+ },
+ setRowHeight: (row: number, height: number) => {
+ rows[row] ??= {};
+ rows[row].h = height;
+ },
+ };
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getConfig: () => ({ defaultRowHeight: 19 }),
+ getRowManager: () => manager,
+ };
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: vi.fn((subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null),
+ };
+ const accessor = createAccessor({
+ getUnit: vi.fn((unitId: string) => unitId === 'unit-1' ? workbook : null),
+ getCurrentUnitOfType: vi.fn(() => workbook),
+ });
+ const ranges = [{ startRow: 1, endRow: 2, startColumn: 0, endColumn: 3 }];
+
+ expect(SetWorksheetRowHeightMutationFactory({ unitId: 'unit-1', subUnitId: 'sheet-1', ranges, rowHeight: 40 }, worksheet as never)).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges,
+ rowHeight: { 1: 24, 2: 19 },
+ });
+ expect(SetWorksheetRowHeightMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ranges, rowHeight: { 1: 31, 2: null } })).toBe(true);
+ expect(rows[1].h).toBe(31);
+ expect(rows[2].h).toBeUndefined();
+ expect(SetWorksheetRowHeightMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ranges, rowHeight: 33 })).toBe(true);
+ expect(rows[1].h).toBe(33);
+ expect(rows[2].h).toBe(33);
+
+ expect(SetWorksheetRowIsAutoHeightMutationFactory({ unitId: 'unit-1', subUnitId: 'sheet-1', ranges, autoHeightInfo: BooleanNumber.FALSE }, worksheet as never)).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ranges,
+ autoHeightInfo: { 1: BooleanNumber.TRUE, 2: undefined },
+ });
+ expect(SetWorksheetRowIsAutoHeightMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ranges, autoHeightInfo: { 1: BooleanNumber.FALSE, 2: null } })).toBe(true);
+ expect(rows[1].ia).toBe(BooleanNumber.FALSE);
+ expect(rows[2].ia).toBeUndefined();
+ expect(SetWorksheetRowIsAutoHeightMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ranges, autoHeightInfo: BooleanNumber.TRUE })).toBe(true);
+ expect(rows[1].ia).toBe(BooleanNumber.TRUE);
+ expect(rows[2].ia).toBe(BooleanNumber.TRUE);
+
+ expect(SetWorksheetRowAutoHeightMutationFactory({ unitId: 'unit-1', subUnitId: 'sheet-1', rowsAutoHeightInfo: [{ row: 1, autoHeight: 50 }, { row: 2, autoHeight: 60 }] }, worksheet as never)).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rowsAutoHeightInfo: [{ row: 1, autoHeight: 28 }, { row: 2, autoHeight: 19 }],
+ });
+ expect(SetWorksheetRowAutoHeightMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rowsAutoHeightInfo: [{ row: 1, autoHeight: 51 }, { row: 3, autoHeight: 61 }] })).toBe(true);
+ expect(rows[1].ah).toBe(51);
+ expect(rows[3].ah).toBe(61);
+
+ expect(SetWorksheetRowHeightMutation.handler(createAccessor({ getUnit: vi.fn(() => null) }), { unitId: 'missing', subUnitId: 'sheet-1', ranges, rowHeight: 20 })).toBe(false);
+ expect(SetWorksheetRowIsAutoHeightMutation.handler(createAccessor({ getUnit: vi.fn(() => null) }), { unitId: 'missing', subUnitId: 'sheet-1', ranges, autoHeightInfo: BooleanNumber.TRUE })).toBe(false);
+ expect(SetWorksheetRowAutoHeightMutation.handler(createAccessor({ getUnit: vi.fn(() => null) }), { unitId: 'missing', subUnitId: 'sheet-1', rowsAutoHeightInfo: [] })).toBe(false);
+ });
});
diff --git a/packages/sheets/src/commands/mutations/__tests__/worksheet-protection-and-theme.mutation.spec.ts b/packages/sheets/src/commands/mutations/__tests__/worksheet-protection-and-theme.mutation.spec.ts
new file mode 100644
index 0000000000..942204a8ec
--- /dev/null
+++ b/packages/sheets/src/commands/mutations/__tests__/worksheet-protection-and-theme.mutation.spec.ts
@@ -0,0 +1,308 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, IRange } from '@univerjs/core';
+import type { IRangeProtectionRule } from '../../../models/range-protection-rule.model';
+import type { IRangeThemeStyleJSON, RangeThemeStyle } from '../../../models/range-theme-util';
+import { BooleanNumber, IUniverInstanceService } from '@univerjs/core';
+import { UnitObject } from '@univerjs/protocol';
+import { describe, expect, it } from 'vitest';
+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../models/range-protection-rule.model';
+import { SheetRangeThemeModel } from '../../../models/range-theme-model';
+import { WorksheetProtectionPointModel } from '../../../services/permission/worksheet-permission';
+import { WorksheetProtectionRuleModel } from '../../../services/permission/worksheet-permission/worksheet-permission-rule.model';
+import { AddRangeProtectionMutation, FactoryAddRangeProtectionMutation } from '../add-range-protection.mutation';
+import { AddRangeThemeMutation } from '../add-range-theme.mutation';
+import { DeleteRangeProtectionMutation, FactoryDeleteRangeProtectionMutation } from '../delete-range-protection.mutation';
+import { EmptyMutation } from '../empty.mutation';
+import { MarkDirtyFilterChangeMutation } from '../mark-dirty-filter-change.mutation';
+import { RemoveRangeThemeMutation } from '../remove-range-theme.mutation';
+import { ReorderRangeMutation, ReorderRangeUndoMutationFactory } from '../reorder-range.mutation';
+import { FactorySetRangeProtectionMutation, SetRangeProtectionMutation } from '../set-range-protection.mutation';
+import { SetRangeThemeMutation } from '../set-range-theme.mutation';
+import { SetWorksheetColumnCountMutation, SetWorksheetColumnCountUndoMutationFactory } from '../set-worksheet-column-count.mutation';
+import { SetWorksheetPermissionPointsMutation } from '../set-worksheet-permission-points.mutation';
+import { SetWorksheetProtectionMutation } from '../set-worksheet-protection.mutation';
+import { SetWorksheetRightToLeftMutation, SetWorksheetRightToLeftUndoMutationFactory } from '../set-worksheet-right-to-left.mutation';
+import { SetWorksheetRowCountMutation, SetWorksheetRowCountUndoMutationFactory } from '../set-worksheet-row-count.mutation';
+import { UnregisterWorksheetRangeThemeStyleMutation } from '../unregister-range-theme-style.mutation';
+
+function createAccessor(records: Map<unknown, unknown>): IAccessor {
+ return {
+ get: (token: unknown) => records.get(token) as never,
+ has: (token: unknown) => records.has(token),
+ } as IAccessor;
+}
+
+function createRangeRule(id: string, range: IRange = { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }): IRangeProtectionRule {
+ return {
+ id,
+ permissionId: `permission-${id}`,
+ ranges: [range],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ unitType: UnitObject.SelectRange,
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
+}
+
+describe('range protection mutations', () => {
+ it('adds, updates, deletes rules and builds undo mutation payloads from model state', () => {
+ const model = new RangeProtectionRuleModel();
+ const accessor = createAccessor(new Map<unknown, unknown>([[RangeProtectionRuleModel, model]]));
+ const firstRule = createRangeRule('rule-1');
+ const secondRule = createRangeRule('rule-2', { startRow: 3, endRow: 3, startColumn: 2, endColumn: 4 });
+
+ expect(AddRangeProtectionMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [firstRule, secondRule] })).toBe(true);
+ expect(model.getSubunitRuleList('unit-1', 'sheet-1')).toEqual([firstRule, secondRule]);
+ expect(FactoryAddRangeProtectionMutation({ unitId: 'unit-1', subUnitId: 'sheet-1', rules: [firstRule, secondRule] })).toEqual({
+ id: DeleteRangeProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [firstRule, secondRule], ruleIds: ['rule-1', 'rule-2'] },
+ });
+
+ const updatedRule = { ...firstRule, description: 'locked for planning' };
+ expect(FactorySetRangeProtectionMutation(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ruleId: 'rule-1', rule: updatedRule })).toEqual({
+ id: SetRangeProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', ruleId: 'rule-1', rule: firstRule },
+ });
+ expect(SetRangeProtectionMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ruleId: 'rule-1', rule: updatedRule })).toBe(true);
+ expect(model.getRule('unit-1', 'sheet-1', 'rule-1')).toEqual(updatedRule);
+
+ expect(FactoryDeleteRangeProtectionMutation(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: ['rule-1', 'missing'] })).toEqual({
+ id: AddRangeProtectionMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', rules: [updatedRule] },
+ });
+ expect(DeleteRangeProtectionMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ruleIds: ['rule-1', 'rule-2'] })).toBe(true);
+ expect(model.getSubunitRuleListLength('unit-1', 'sheet-1')).toBe(0);
+ expect(FactorySetRangeProtectionMutation(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', ruleId: 'rule-1', rule: updatedRule })).toBeNull();
+ });
+});
+
+describe('worksheet protection mutations', () => {
+ it('stores worksheet protection rules and permission point rules in their models', () => {
+ const ruleModel = new WorksheetProtectionRuleModel();
+ const pointModel = new WorksheetProtectionPointModel();
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [WorksheetProtectionRuleModel, ruleModel],
+ [WorksheetProtectionPointModel, pointModel],
+ ]));
+ const rule = {
+ permissionId: 'permission-sheet-1',
+ unitType: UnitObject.Worksheet,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.NoOneElseCanView,
+ editState: EditStateEnum.DesignedUserCanEdit,
+ };
+
+ ruleModel.addRule('unit-1', { ...rule, description: 'initial' });
+ expect(SetWorksheetProtectionMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rule })).toBe(true);
+ expect(ruleModel.getRule('unit-1', 'sheet-1')).toEqual(rule);
+
+ expect(SetWorksheetPermissionPointsMutation.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rule: { unitId: 'unit-1', subUnitId: 'sheet-1', permissionId: 'permission-point-1' },
+ })).toBe(true);
+ expect(pointModel.getRule('unit-1', 'sheet-1')).toEqual({ unitId: 'unit-1', subUnitId: 'sheet-1', permissionId: 'permission-point-1' });
+ });
+});
+
+describe('worksheet count and direction mutations', () => {
+ it('changes worksheet row and column counts and creates undo payloads from old dimensions', () => {
+ const worksheet = {
+ rowCount: 12,
+ columnCount: 8,
+ getRowCount() { return this.rowCount; },
+ setRowCount(rowCount: number) { this.rowCount = rowCount; },
+ getColumnCount() { return this.columnCount; },
+ setColumnCount(columnCount: number) { this.columnCount = columnCount; },
+ };
+ const workbook = {
+ getSheetBySheetId: (subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null,
+ };
+ const univerInstanceService = {
+ getUnit: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([[IUniverInstanceService, univerInstanceService]]));
+
+ expect(SetWorksheetRowCountUndoMutationFactory(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 20 })).toEqual({ unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 12 });
+ expect(SetWorksheetRowCountMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rowCount: 20 })).toBe(true);
+ expect(worksheet.rowCount).toBe(20);
+
+ expect(SetWorksheetColumnCountUndoMutationFactory(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 14 })).toEqual({ unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 8 });
+ expect(SetWorksheetColumnCountMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', columnCount: 14 })).toBe(true);
+ expect(worksheet.columnCount).toBe(14);
+
+ expect(SetWorksheetRowCountMutation.handler(accessor, { unitId: 'missing', subUnitId: 'sheet-1', rowCount: 30 })).toBe(false);
+ expect(SetWorksheetColumnCountMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'missing', columnCount: 30 })).toBe(false);
+ expect(() => SetWorksheetRowCountUndoMutationFactory(accessor, { unitId: 'missing', subUnitId: 'sheet-1', rowCount: 1 })).toThrowError('[SetWorksheetRowCountUndoMutationFactory]: worksheet is null error!');
+ expect(() => SetWorksheetColumnCountUndoMutationFactory(accessor, { unitId: 'unit-1', subUnitId: 'missing', columnCount: 1 })).toThrowError('[SetWorksheetColumnCountUndoMutationFactory]: worksheet is null error!');
+ });
+
+ it('updates right-to-left state and returns previous state for undo', () => {
+ const config = { rightToLeft: BooleanNumber.FALSE };
+ const worksheet = {
+ getConfig: () => config,
+ };
+ const workbook = {
+ getSheetBySheetId: (subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null,
+ };
+ const univerInstanceService = {
+ getUniverSheetInstance: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([[IUniverInstanceService, univerInstanceService]]));
+
+ expect(SetWorksheetRightToLeftUndoMutationFactory(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.TRUE })).toEqual({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rightToLeft: BooleanNumber.FALSE,
+ });
+ expect(SetWorksheetRightToLeftMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.TRUE })).toBe(true);
+ expect(config.rightToLeft).toBe(BooleanNumber.TRUE);
+ expect(SetWorksheetRightToLeftMutation.handler(accessor, { unitId: 'missing', subUnitId: 'sheet-1', rightToLeft: BooleanNumber.FALSE })).toBe(false);
+ expect(SetWorksheetRightToLeftMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'missing', rightToLeft: BooleanNumber.FALSE })).toBe(false);
+ });
+});
+
+describe('range theme mutations', () => {
+ it('registers, edits, and removes custom range theme styles', () => {
+ const registered = new Map<string, RangeThemeStyle>();
+ const rangeThemeModel = {
+ registerRangeThemeStyle: (_unitId: string, style: RangeThemeStyle) => registered.set(style.getName(), style),
+ unregisterRangeThemeStyle: (_unitId: string, styleName: string) => registered.delete(styleName),
+ getRangeThemeStyle: (_unitId: string, styleName: string) => registered.get(styleName),
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([[SheetRangeThemeModel, rangeThemeModel]]));
+ const styleJSON: IRangeThemeStyleJSON = {
+ name: 'sales',
+ headerRowStyle: { bg: { rgb: '#eef2ff' } },
+ firstRowStyle: { bg: { rgb: '#ffffff' } },
+ };
+
+ expect(AddRangeThemeMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', styleJSON })).toBe(true);
+ expect(registered.get('sales')?.getHeaderRowStyle()).toEqual({ bg: { rgb: '#eef2ff' } });
+
+ expect(SetRangeThemeMutation.handler(accessor, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ styleName: 'sales',
+ style: {
+ headerRowStyle: { bg: { rgb: '#111111' } },
+ firstRowStyle: { bg: { rgb: '#222222' } },
+ secondRowStyle: { bg: { rgb: '#333333' } },
+ lastRowStyle: { bg: { rgb: '#444444' } },
+ },
+ })).toBe(true);
+ expect(registered.get('sales')?.getHeaderRowStyle()).toEqual({ bg: { rgb: '#111111' } });
+ expect(registered.get('sales')?.getLastRowStyle()).toEqual({ bg: { rgb: '#444444' } });
+
+ expect(RemoveRangeThemeMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', styleName: 'sales' })).toBe(true);
+ expect(registered.has('sales')).toBe(false);
+ expect(AddRangeThemeMutation.handler(accessor, null as never)).toBe(false);
+ expect(SetRangeThemeMutation.handler(accessor, null as never)).toBe(false);
+ expect(SetRangeThemeMutation.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1', styleName: 'missing', style: { headerRowStyle: { bg: { rgb: '#000000' } } } })).toBe(true);
+ expect(RemoveRangeThemeMutation.handler(accessor, null as never)).toBe(false);
+ });
+
+ it('unregisters a worksheet theme style only when the workbook target exists', () => {
+ const removed: string[] = [];
+ const rangeThemeModel = {
+ unregisterRangeThemeStyle: (unitId: string, themeName: string) => removed.push(`${unitId}:${themeName}`),
+ };
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ };
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => worksheet,
+ };
+ const univerInstanceService = {
+ getUnit: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ getCurrentUnitOfType: () => workbook,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [SheetRangeThemeModel, rangeThemeModel],
+ [IUniverInstanceService, univerInstanceService],
+ ]));
+
+ expect(UnregisterWorksheetRangeThemeStyleMutation.handler(accessor, { unitId: 'unit-1', themeName: 'sales' })).toBe(true);
+ expect(removed).toEqual(['unit-1:sales']);
+
+ const missingAccessor = createAccessor(new Map<unknown, unknown>([
+ [SheetRangeThemeModel, rangeThemeModel],
+ [IUniverInstanceService, { ...univerInstanceService, getUnit: () => null }],
+ ]));
+ expect(UnregisterWorksheetRangeThemeStyleMutation.handler(missingAccessor, { unitId: 'missing', themeName: 'sales' })).toBe(false);
+ });
+});
+
+describe('empty mutation', () => {
+ it('returns success so command chains can use it as a no-op mutation', () => {
+ expect(EmptyMutation.handler(createAccessor(new Map()), {})).toBe(true);
+ });
+});
+
+describe('filter dirty and reorder mutations', () => {
+ it('acknowledges filter range dirty markers for downstream listeners', () => {
+ expect(MarkDirtyFilterChangeMutation.handler(createAccessor(new Map()), {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ filterRange: { startRow: 0, endRow: 4, startColumn: 0, endColumn: 3 },
+ })).toBe(true);
+ });
+
+ it('reorders range rows from the requested source rows and creates inverse order for undo', () => {
+ const writes: Array<{ row: number; col: number; value: unknown }> = [];
+ const worksheet = {
+ getCellRaw: (row: number, col: number) => ({ v: `${row}:${col}` }),
+ getCellMatrix: () => ({
+ setValue: (row: number, col: number, value: unknown) => writes.push({ row, col, value }),
+ }),
+ };
+ const workbook = {
+ getSheetBySheetId: (subUnitId: string) => subUnitId === 'sheet-1' ? worksheet : null,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([[IUniverInstanceService, {
+ getUnit: (unitId: string) => unitId === 'unit-1' ? workbook : null,
+ }]]));
+ const params = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },
+ order: { 0: 2, 1: 0, 2: 1 },
+ };
+
+ expect(ReorderRangeUndoMutationFactory(params)).toEqual({
+ ...params,
+ order: { 0: 1, 1: 2, 2: 0 },
+ });
+ expect(ReorderRangeMutation.handler(accessor, params)).toBe(true);
+ expect(writes).toEqual([
+ { row: 0, col: 0, value: { v: '2:0' } },
+ { row: 0, col: 1, value: { v: '2:1' } },
+ { row: 1, col: 0, value: { v: '0:0' } },
+ { row: 1, col: 1, value: { v: '0:1' } },
+ { row: 2, col: 0, value: { v: '1:0' } },
+ { row: 2, col: 1, value: { v: '1:1' } },
+ ]);
+
+ expect(ReorderRangeMutation.handler(createAccessor(new Map<unknown, unknown>([[IUniverInstanceService, {
+ getUnit: () => ({ getSheetBySheetId: () => null }),
+ }]])), params)).toBe(false);
+ });
+});
diff --git a/packages/sheets/src/commands/operations/__tests__/simple-operations.spec.ts b/packages/sheets/src/commands/operations/__tests__/simple-operations.spec.ts
new file mode 100644
index 0000000000..e45ed96473
--- /dev/null
+++ b/packages/sheets/src/commands/operations/__tests__/simple-operations.spec.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { CancelMarkDirtyRowAutoHeightOperation, MarkDirtyRowAutoHeightOperation } from '../mark-dirty-auto-height.operation';
+import { ScrollToCellOperation } from '../scroll-to-cell.operation';
+
+describe('simple sheet operations', () => {
+ it('acknowledges row auto-height dirty markers and cancellation markers', () => {
+ expect(MarkDirtyRowAutoHeightOperation.handler(null as never, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ id: 'auto-height-1',
+ ranges: [{ startRow: 1, endRow: 3, startColumn: 0, endColumn: 4 }],
+ })).toBe(true);
+ expect(CancelMarkDirtyRowAutoHeightOperation.handler(null as never, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ id: 'auto-height-1',
+ })).toBe(true);
+ });
+
+ it('acknowledges scroll requests for a concrete cell range', () => {
+ expect(ScrollToCellOperation.handler(null as never, {
+ unitId: 'unit-1',
+ range: { startRow: 8, endRow: 8, startColumn: 2, endColumn: 2 },
+ })).toBe(true);
+ });
+});
diff --git a/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts b/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts
index c7f9fe4f50..becd21aa2d 100644
--- a/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-defined-name.spec.ts
@@ -131,12 +131,17 @@ describe('Test FDefinedName', () => {
expect(regionalRevenue.getFormulaOrRefString()).toBe('=SUM(B2:B3)');
regionalRevenue.setRef('C2:C3');
expect(regionalRevenue.getFormulaOrRefString()).toBe('C2:C3');
+ regionalRevenue.setRefByRange(4, 4, 2, 1);
+ expect(regionalRevenue.getFormulaOrRefString()).toBe('E5:E6');
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([]);
+ regionalRevenue.setScopeToWorksheet(sheet);
+ expect(regionalRevenue.isWorkbookScope()).toBe(false);
+ expect(sheet.getDefinedNames().map((name) => name.getName())).toEqual(['RegionalRevenue']);
const updatedParam = regionalRevenue.toBuilder()
.setName('ApprovedRevenue')
@@ -153,4 +158,15 @@ describe('Test FDefinedName', () => {
expect(workbook.getDefinedName('ApprovedRevenue')).toBeNull();
expect(workbook.deleteDefinedName('missing-name')).toBe(false);
});
+
+ it('generates a default name when an existing defined name is renamed to blank', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ workbook.insertDefinedName('Name1', 'A1');
+ const definedName = workbook.getDefinedName('Name1')!;
+
+ definedName.setName('');
+
+ expect(definedName.getName()).not.toBe('');
+ expect(workbook.getDefinedNames().map((name) => name.getName())).toContain(definedName.getName());
+ });
});
diff --git a/packages/sheets/src/facade/__tests__/f-permission.spec.ts b/packages/sheets/src/facade/__tests__/f-permission.spec.ts
index bef966932b..700251f3ba 100644
--- a/packages/sheets/src/facade/__tests__/f-permission.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-permission.spec.ts
@@ -23,7 +23,7 @@ import {
DeleteWorksheetProtectionMutation,
SetRangeProtectionMutation,
} from '@univerjs/sheets';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createFacadeTestBed } from './create-test-bed';
describe('sheets facade permissions', () => {
@@ -110,22 +110,40 @@ describe('sheets facade permissions', () => {
await rule.setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false);
await rule.setPoint(univerAPI.Enum.RangePermissionPoint.View, true);
+ await rule.setPoint(univerAPI.Enum.RangePermissionPoint.ManageCollaborator, false);
+ await rule.setPoint(univerAPI.Enum.RangePermissionPoint.Delete, false);
expect(rule.canEdit()).toBe(false);
expect(rule.canView()).toBe(true);
+ expect(rule.canManageCollaborator()).toBe(false);
+ expect(rule.canDelete()).toBe(false);
expect(rule.getSnapshot()[univerAPI.Enum.RangePermissionPoint.Edit]).toBe(false);
expect(worksheetPermission.canEditCell(0, 0)).toBe(false);
expect(worksheetPermission.canEditCell(5, 5)).toBe(true);
+ await expect(rule.updateRanges([])).rejects.toThrow('Ranges cannot be empty');
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]);
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const collaboratorRule = await worksheet.getRange('E1:E2').getRangePermission().protect({
+ name: 'Missing collaborator range',
+ allowedUsers: ['missing-user'],
+ });
+ consoleErrorSpy.mockRestore();
+ expect(collaboratorRule.options.name).toBe('Missing collaborator range');
+
+ await expect(rule.updateRanges([worksheet.getRange('E2:E3')]))
+ .rejects
+ .toThrow('Range protection cannot intersect with other protection rules');
+
await expect(worksheet.getRange('C2:D3').getRangePermission().protect({ name: 'Overlapping range' }))
.rejects
.toThrow('Range is already protected');
+ expect(await collaboratorRule.remove()).toBe(true);
expect(await rule.remove()).toBe(true);
expect(await rangePermission.unprotect()).toBe(true);
expect(worksheet.getRange('C1').getRangePermission().isProtected()).toBe(false);
@@ -201,4 +219,18 @@ describe('sheets facade permissions', () => {
expect(await worksheetPermission.unprotect()).toBe(true);
expect(worksheetPermission.isProtected()).toBe(false);
});
+
+ it('reports a failed range unprotect when the delete mutation cannot run', async () => {
+ const { univerAPI, get } = testBed;
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ const rangePermission = worksheet.getRange('G1:G2').getRangePermission();
+
+ await rangePermission.protect({ name: 'Locked scenario cells' });
+ get(ICommandService).unregisterCommand(DeleteRangeProtectionMutation.id);
+
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ await expect(rangePermission.unprotect()).rejects.toThrow('is not registered');
+ consoleErrorSpy.mockRestore();
+ expect(rangePermission.isProtected()).toBe(true);
+ });
});
diff --git a/packages/sheets/src/facade/__tests__/f-range.spec.ts b/packages/sheets/src/facade/__tests__/f-range.spec.ts
index 833f8fbb24..8288a833ee 100644
--- a/packages/sheets/src/facade/__tests__/f-range.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-range.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';
+import type { ICellData, IDocumentData, Injector, IStyleData, Nullable, RichTextValue } from '@univerjs/core';
import type { FUniver } from '@univerjs/core/facade';
import {
AbsoluteRefType,
@@ -31,13 +31,25 @@ import {
} from '@univerjs/core';
import {
AddWorksheetMergeCommand,
+ AddWorksheetMergeMutation,
ClearSelectionAllCommand,
ClearSelectionContentCommand,
ClearSelectionFormatCommand,
+ DeleteRangeMoveLeftCommand,
+ DeleteRangeMoveUpCommand,
DeleteWorksheetRangeThemeStyleCommand,
DeleteWorksheetRangeThemeStyleMutation,
+ InsertColMutation,
+ InsertRangeMoveDownCommand,
+ InsertRangeMoveRightCommand,
+ InsertRowMutation,
+ MoveRangeMutation,
RegisterWorksheetRangeThemeStyleCommand,
RegisterWorksheetRangeThemeStyleMutation,
+ RemoveColMutation,
+ RemoveRowMutation,
+ RemoveWorksheetMergeCommand,
+ RemoveWorksheetMergeMutation,
SetHorizontalTextAlignCommand,
SetRangeCustomMetadataCommand,
SetRangeValuesCommand,
@@ -92,6 +104,18 @@ describe('Test FRange', () => {
commandService.registerCommand(SetHorizontalTextAlignCommand);
commandService.registerCommand(SetTextWrapCommand);
commandService.registerCommand(AddWorksheetMergeCommand);
+ commandService.registerCommand(RemoveWorksheetMergeCommand);
+ commandService.registerCommand(AddWorksheetMergeMutation);
+ commandService.registerCommand(RemoveWorksheetMergeMutation);
+ commandService.registerCommand(InsertRangeMoveDownCommand);
+ commandService.registerCommand(InsertRangeMoveRightCommand);
+ commandService.registerCommand(DeleteRangeMoveUpCommand);
+ commandService.registerCommand(DeleteRangeMoveLeftCommand);
+ commandService.registerCommand(InsertRowMutation);
+ commandService.registerCommand(InsertColMutation);
+ commandService.registerCommand(RemoveRowMutation);
+ commandService.registerCommand(RemoveColMutation);
+ commandService.registerCommand(MoveRangeMutation);
commandService.registerCommand(SetRangeCustomMetadataCommand);
commandService.registerCommand(SetTextRotationCommand);
commandService.registerCommand(ClearSelectionAllCommand);
@@ -689,8 +713,88 @@ describe('Test FRange', () => {
}
expect(hasError).toBeTruthy();
});
+
+ it('Range merge variants and breakApart update merged ranges', async () => {
+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet()!;
+
+ const across = activeSheet.getRange('A10:C11').mergeAcross();
+ await Promise.resolve();
+ expect(across.isPartOfMerge()).toBe(true);
+ expect(activeSheet.getRange('A10:C10').isMerged()).toBe(true);
+ expect(activeSheet.getRange('A11:C11').isMerged()).toBe(true);
+ across.breakApart();
+ expect(across.isPartOfMerge()).toBe(false);
+
+ const vertical = activeSheet.getRange('E10:F12').mergeVertically();
+ await Promise.resolve();
+ expect(activeSheet.getRange('E10:E12').isMerged()).toBe(true);
+ expect(activeSheet.getRange('F10:F12').isMerged()).toBe(true);
+ vertical.breakApart();
+ expect(vertical.isPartOfMerge()).toBe(false);
+ });
//#endregion
+ it('Range supports rich text values and per-cell writes', () => {
+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet()!;
+ const richText = univerAPI.newRichTextValue({ body: { dataStream: 'Hello\r\n' } } as IDocumentData);
+ const docData = { body: { dataStream: 'World\r\n' } } as IDocumentData;
+
+ activeSheet.getRange('H1:I1').setRichTextValues([[richText, docData]]);
+ const values = activeSheet.getRange('H1:I1').getValues(true);
+ expect((values[0][0] as RichTextValue).toPlainText()).toBe('Hello');
+ expect((values[0][1] as RichTextValue).toPlainText()).toBe('World');
+
+ activeSheet.getRange('H2:I2').setValueForCell('only first');
+ expect(activeSheet.getRange('H2').getValue()).toBe('only first');
+ expect(activeSheet.getRange('I2').getValue()).toBeNull();
+
+ activeSheet.getRange('H3:I3').setRichTextValueForCell(richText);
+ expect((activeSheet.getRange('H3').getValue(true) as RichTextValue).toPlainText()).toBe('Hello');
+ expect(activeSheet.getRange('I3').getValue(true)).toBeUndefined();
+ });
+
+ it('Range inserts and deletes cells along both dimensions', async () => {
+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet()!;
+ activeSheet.getRange('A20:D23').setValues([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12],
+ [13, 14, 15, 16],
+ ]);
+
+ activeSheet.getRange('A20:B21').insertCells(Dimension.COLUMNS);
+ await Promise.resolve();
+ expect(activeSheet.getRange('A20:D21').getValues()).toEqual([
+ [null, null, 1, 2],
+ [null, null, 5, 6],
+ ]);
+
+ activeSheet.getRange('A20:B21').deleteCells(Dimension.COLUMNS);
+ await Promise.resolve();
+ expect(activeSheet.getRange('A20:D21').getValues()).toEqual([
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ ]);
+
+ activeSheet.getRange('A20:B21').insertCells(Dimension.ROWS);
+ await Promise.resolve();
+ expect(activeSheet.getRange('A20:B23').getValues()).toEqual([
+ [null, null],
+ [null, null],
+ [1, 2],
+ [5, 6],
+ ]);
+
+ activeSheet.getRange('A20:B21').deleteCells(Dimension.ROWS);
+ await Promise.resolve();
+ expect(activeSheet.getRange('A20:B23').getValues()).toEqual([
+ [1, 2],
+ [5, 6],
+ [9, 10],
+ [13, 14],
+ ]);
+ });
+
// Add these new test cases
it('Range getRow, getColumn, getWidth, getHeight with A1 notation', () => {
const activeSheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
diff --git a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts
index 89ddee8465..58b77c687d 100644
--- a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts
+++ b/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts
@@ -29,6 +29,7 @@ import {
import {
AddWorksheetMergeCommand,
AddWorksheetMergeMutation,
+ AppendRowCommand,
CancelFrozenCommand,
ClearSelectionAllCommand,
ClearSelectionContentCommand,
@@ -74,11 +75,21 @@ import {
SetStyleCommand,
SetTextWrapCommand,
SetVerticalTextAlignCommand,
+ SetWorksheetActiveOperation,
+ SetWorksheetColumnCountCommand,
+ SetWorksheetColumnCountMutation,
SetWorksheetColWidthMutation,
SetWorksheetDefaultStyleMutation,
+ SetWorksheetHideCommand,
+ SetWorksheetHideMutation,
+ SetWorksheetNameCommand,
+ SetWorksheetNameMutation,
+ SetWorksheetRowCountCommand,
+ SetWorksheetRowCountMutation,
SetWorksheetRowHeightMutation,
SetWorksheetRowIsAutoHeightCommand,
SetWorksheetRowIsAutoHeightMutation,
+ SetWorksheetShowCommand,
SheetSkeletonService,
SheetsSelectionsService,
} from '@univerjs/sheets';
@@ -107,10 +118,21 @@ describe('Test FWorksheet', () => {
commandService.registerCommand(SetVerticalTextAlignCommand);
commandService.registerCommand(SetHorizontalTextAlignCommand);
commandService.registerCommand(SetTextWrapCommand);
+ commandService.registerCommand(AppendRowCommand);
commandService.registerCommand(ClearSelectionAllCommand);
commandService.registerCommand(ClearSelectionContentCommand);
commandService.registerCommand(ClearSelectionFormatCommand);
commandService.registerCommand(SetWorksheetDefaultStyleMutation);
+ commandService.registerCommand(SetWorksheetRowCountCommand);
+ commandService.registerCommand(SetWorksheetRowCountMutation);
+ commandService.registerCommand(SetWorksheetColumnCountCommand);
+ commandService.registerCommand(SetWorksheetColumnCountMutation);
+ commandService.registerCommand(SetWorksheetHideCommand);
+ commandService.registerCommand(SetWorksheetHideMutation);
+ commandService.registerCommand(SetWorksheetShowCommand);
+ commandService.registerCommand(SetWorksheetActiveOperation);
+ commandService.registerCommand(SetWorksheetNameCommand);
+ commandService.registerCommand(SetWorksheetNameMutation);
get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');
// row
@@ -604,6 +626,43 @@ describe('Test FWorksheet', () => {
warnSpy.mockRestore();
});
+ it('Worksheet appends rows and updates sheet dimensions through facade APIs', () => {
+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+
+ const initialLastRow = activeSheet.getLastRow();
+ activeSheet.appendRow(['North', 100, true]);
+ expect(activeSheet.getRange(initialLastRow + 1, 0, 1, 3).getValues()).toEqual([['North', 100, 1]]);
+ expect(activeSheet.getDataRange().getA1Notation()).toBe(`A1:C${initialLastRow + 2}`);
+
+ activeSheet.setRowCount(120);
+ activeSheet.setColumnCount(80);
+ expect(activeSheet.getMaxRows()).toBe(120);
+ expect(activeSheet.getMaxColumns()).toBe(80);
+ });
+
+ it('Worksheet exposes merge, active range, visibility, name, and equality state', () => {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const activeSheet = workbook.getActiveSheet();
+ const sameSheet = workbook.getSheetByName(activeSheet.getSheetName())!;
+
+ expect(activeSheet.equalTo(sameSheet)).toBe(true);
+ activeSheet.getRange('J1:K2').merge();
+ expect(activeSheet.getMergeData().map((range) => range.getA1Notation())).toContain('J1:K2');
+ expect(activeSheet.getMergedRanges().map((range) => range.getA1Notation())).toContain('J1:K2');
+ expect(activeSheet.getCellMergeData(0, 9)?.getA1Notation()).toBe('J1:K2');
+
+ activeSheet.setActiveRange(activeSheet.getRange('C3:D4'));
+ expect(activeSheet.getActiveRange()?.getA1Notation()).toBe('C3:D4');
+ expect(activeSheet.getActiveCell()?.getA1Notation()).toBe('C3');
+
+ expect(() => activeSheet.hideSheet()).toThrow('Cannot hide the only visible sheet');
+ expect(activeSheet.isSheetHidden()).toBe(false);
+
+ activeSheet.setName('Renamed');
+ expect(activeSheet.getSheetName()).toBe('Renamed');
+ expect(activeSheet.getIndex()).toBe(0);
+ });
+
// #endregion
it('Worksheet freeze', async () => {
diff --git a/packages/sheets/src/facade/__tests__/utils.spec.ts b/packages/sheets/src/facade/__tests__/utils.spec.ts
index 53dc23343a..6b964991b5 100644
--- a/packages/sheets/src/facade/__tests__/utils.spec.ts
+++ b/packages/sheets/src/facade/__tests__/utils.spec.ts
@@ -14,8 +14,18 @@
* limitations under the License.
*/
-import { covertCellValue, covertCellValues } from '@univerjs/core';
+import { covertCellValue, covertCellValues, HorizontalAlign, RANGE_TYPE, VerticalAlign } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import {
+ covertToColRange,
+ covertToRowRange,
+ isCellMerged,
+ isSingleCell,
+ transformCoreHorizontalAlignment,
+ transformCoreVerticalAlignment,
+ transformFacadeHorizontalAlignment,
+ transformFacadeVerticalAlignment,
+} from '../utils';
describe('Test utils', () => {
it('function covertCellValue', () => {
@@ -81,4 +91,56 @@ describe('Test utils', () => {
2: { 1: { v: 3 }, 2: { v: 4 } },
});
});
+
+ it('transforms facade alignment values to core values and back', () => {
+ expect(transformFacadeHorizontalAlignment('left')).toBe(HorizontalAlign.LEFT);
+ expect(transformFacadeHorizontalAlignment('center')).toBe(HorizontalAlign.CENTER);
+ expect(transformFacadeHorizontalAlignment('normal')).toBe(HorizontalAlign.RIGHT);
+ expect(() => transformFacadeHorizontalAlignment('invalid' as never)).toThrowError('Invalid horizontal alignment: invalid');
+
+ expect(transformCoreHorizontalAlignment(HorizontalAlign.LEFT)).toBe('left');
+ expect(transformCoreHorizontalAlignment(HorizontalAlign.CENTER)).toBe('center');
+ expect(transformCoreHorizontalAlignment(HorizontalAlign.RIGHT)).toBe('normal');
+ expect(transformCoreHorizontalAlignment('invalid' as never)).toBe('general');
+
+ expect(transformFacadeVerticalAlignment('top')).toBe(VerticalAlign.TOP);
+ expect(transformFacadeVerticalAlignment('middle')).toBe(VerticalAlign.MIDDLE);
+ expect(transformFacadeVerticalAlignment('bottom')).toBe(VerticalAlign.BOTTOM);
+ expect(() => transformFacadeVerticalAlignment('invalid' as never)).toThrowError('Invalid vertical alignment: invalid');
+
+ expect(transformCoreVerticalAlignment(VerticalAlign.TOP)).toBe('top');
+ expect(transformCoreVerticalAlignment(VerticalAlign.MIDDLE)).toBe('middle');
+ expect(transformCoreVerticalAlignment(VerticalAlign.BOTTOM)).toBe('bottom');
+ expect(transformCoreVerticalAlignment('invalid' as never)).toBe('general');
+ });
+
+ it('identifies merged cells and converts ranges to full row or column ranges', () => {
+ const singleCell = { startRow: 2, endRow: 2, startColumn: 3, endColumn: 3, startX: 30, startY: 20, endX: 40, endY: 30 };
+ const mergedCell = { startRow: 2, endRow: 4, startColumn: 3, endColumn: 5, startX: 30, startY: 20, endX: 60, endY: 50 };
+ const worksheet = {
+ getColumnCount: () => 12,
+ getRowCount: () => 20,
+ };
+
+ expect(isSingleCell(singleCell, { startRow: 2, endRow: 2, startColumn: 3, endColumn: 3 })).toBe(true);
+ expect(isSingleCell(singleCell, { startRow: 2, endRow: 2, startColumn: 4, endColumn: 4 })).toBe(false);
+ expect(isCellMerged(mergedCell, { startRow: 2, endRow: 4, startColumn: 3, endColumn: 5 })).toBe(true);
+ expect(isCellMerged(singleCell, { startRow: 2, endRow: 2, startColumn: 3, endColumn: 3 })).toBe(false);
+ expect(isCellMerged(mergedCell, { startRow: 2, endRow: 2, startColumn: 3, endColumn: 3 })).toBe(false);
+
+ expect(covertToRowRange({ startRow: 5, endRow: 7, startColumn: 2, endColumn: 4 }, worksheet as never)).toEqual({
+ startRow: 5,
+ endRow: 7,
+ startColumn: 0,
+ endColumn: 11,
+ rangeType: RANGE_TYPE.ROW,
+ });
+ expect(covertToColRange({ startRow: 5, endRow: 7, startColumn: 2, endColumn: 4 }, worksheet as never)).toEqual({
+ startRow: 0,
+ endRow: 19,
+ startColumn: 2,
+ endColumn: 4,
+ rangeType: RANGE_TYPE.COLUMN,
+ });
+ });
});
diff --git a/packages/sheets/src/services/__tests__/range-theme.service.spec.ts b/packages/sheets/src/services/__tests__/range-theme.service.spec.ts
index 2018eefd1c..a376c5b86c 100644
--- a/packages/sheets/src/services/__tests__/range-theme.service.spec.ts
+++ b/packages/sheets/src/services/__tests__/range-theme.service.spec.ts
@@ -14,34 +14,67 @@
* limitations under the License.
*/
-import { Injector } from '@univerjs/core';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ DesktopLogService,
+ ILogService,
+ Injector,
+ IResourceManagerService,
+ IUniverInstanceService,
+ ResourceManagerService,
+} from '@univerjs/core';
+import { EMPTY } from 'rxjs';
+import { beforeEach, describe, expect, it } from 'vitest';
import { SheetRangeThemeModel } from '../../models/range-theme-model';
import { RangeThemeStyle } from '../../models/range-theme-util';
import { SheetRangeThemeService } from '../range-theme.service';
+import { SheetInterceptorService } from '../sheet-interceptor/sheet-interceptor.service';
describe('SheetRangeThemeService', () => {
let service: SheetRangeThemeService;
- let model: {
- registerRangeThemeStyle: ReturnType<typeof vi.fn>;
- getALLRegisteredTheme: ReturnType<typeof vi.fn>;
- registerRangeThemeRule: ReturnType<typeof vi.fn>;
- getRegisteredRangeThemeStyle: ReturnType<typeof vi.fn>;
- removeRangeThemeRule: ReturnType<typeof vi.fn>;
- getRegisteredRangeThemes: ReturnType<typeof vi.fn>;
- };
+
+ class TestWorksheet {
+ getRowCount() {
+ return 20;
+ }
+
+ getRowManager() {
+ return {
+ getRowHeight: () => 24,
+ };
+ }
+
+ getRowVisible() {
+ return true;
+ }
+ }
+
+ class TestWorkbook {
+ getSheetBySheetId(sheetId: string) {
+ return sheetId === 'sheet-1' ? new TestWorksheet() : null;
+ }
+ }
+
+ class TestUniverInstanceService {
+ getTypeOfUnitAdded$() {
+ return EMPTY;
+ }
+
+ getTypeOfUnitDisposed$() {
+ return EMPTY;
+ }
+
+ getUnit(unitId: string) {
+ return unitId === 'book-1' ? new TestWorkbook() : null;
+ }
+ }
beforeEach(() => {
- model = {
- registerRangeThemeStyle: vi.fn(),
- getALLRegisteredTheme: vi.fn(() => ['sales']),
- registerRangeThemeRule: vi.fn(),
- getRegisteredRangeThemeStyle: vi.fn(() => 'sales'),
- removeRangeThemeRule: vi.fn(),
- getRegisteredRangeThemes: vi.fn(() => new Map([['default', new RangeThemeStyle('default')]])),
- };
const injector = new Injector();
- injector.add([SheetRangeThemeModel, { useValue: model as unknown as SheetRangeThemeModel }]);
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([IResourceManagerService, { useClass: ResourceManagerService }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetRangeThemeModel]);
injector.add([SheetRangeThemeService]);
service = injector.get(SheetRangeThemeService);
});
@@ -53,16 +86,17 @@ describe('SheetRangeThemeService', () => {
service.registerRangeTheme('book-1', theme);
service.registerRangeThemeStyle('sales', rangeInfo);
- expect(model.registerRangeThemeStyle).toHaveBeenCalledWith('book-1', theme);
- expect(model.registerRangeThemeRule).toHaveBeenCalledWith('sales', rangeInfo);
+ expect(service.getALLRegisterThemes('book-1')).toEqual(['sales']);
expect(service.getAppliedRangeThemeStyle(rangeInfo)).toBe('sales');
});
it('removes a theme rule from the requested range', () => {
const rangeInfo = { unitId: 'book-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 } };
+ service.registerRangeTheme('book-1', new RangeThemeStyle('sales'));
+ service.registerRangeThemeStyle('sales', rangeInfo);
service.removeRangeThemeRule('sales', rangeInfo);
- expect(model.removeRangeThemeRule).toHaveBeenCalledWith('sales', rangeInfo);
+ expect(service.getAppliedRangeThemeStyle(rangeInfo)).toBeUndefined();
});
});
diff --git a/packages/sheets/src/services/auto-fill/__tests__/rules.spec.ts b/packages/sheets/src/services/auto-fill/__tests__/rules.spec.ts
index edf1330681..4dd9119b3d 100644
--- a/packages/sheets/src/services/auto-fill/__tests__/rules.spec.ts
+++ b/packages/sheets/src/services/auto-fill/__tests__/rules.spec.ts
@@ -61,6 +61,16 @@ describe('auto-fill rules', () => {
expect(rightResult?.map((c) => c?.v)).toEqual([3, 4, 5]);
expect(leftResult?.map((c) => c?.v)).toEqual([-2, -1, 0]);
expect(dateRule.isContinue({ type: AUTO_FILL_DATA_TYPE.DATE, cellData: { v: 1 } }, { v: 2 })).toBe(true);
+ expect(dateRule.isContinue({ type: AUTO_FILL_DATA_TYPE.NUMBER, cellData: { v: 1 } }, { v: 2 })).toBe(false);
+
+ expect(dateRule.match({ v: 45292, s: 'date-style' }, {
+ get: () => ({
+ getCurrentUnitOfType: () => ({
+ getStyles: () => ({ get: () => ({ n: { pattern: 'yyyy-mm-dd' } }) }),
+ }),
+ }),
+ } as any)).toBe(true);
+ expect(dateRule.match({ v: 45292, s: 'date-style' }, { get: () => ({ getCurrentUnitOfType: () => null }) } as any)).toBe(false);
});
it('number rule should match numeric cells and generate series', () => {
@@ -76,6 +86,15 @@ describe('auto-fill rules', () => {
{} as any
);
expect(result?.map((cell) => cell?.v)).toEqual([6, 8, 10]);
+
+ const reverse = numberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: 10 }, { v: 12 }], index: [0, 1] },
+ 2,
+ Direction.UP,
+ {} as any
+ );
+ expect(reverse?.map((cell) => cell?.v)).toEqual([6, 8]);
+ expect(numberRule.isContinue({ type: AUTO_FILL_DATA_TYPE.OTHER, cellData: { v: 1 } }, { v: 2 })).toBe(false);
});
it('extend-number rule should support continue and copy fallback', () => {
@@ -120,6 +139,15 @@ describe('auto-fill rules', () => {
{} as any
);
expect(multipleCellsWithPadStart0?.map((c) => `${c?.v}`)).toEqual(['A2B3C003D', 'A2B3C004D', 'A2B3C005D', 'A2B3C006D']);
+ expect(extendNumberRule.isContinue({ type: AUTO_FILL_DATA_TYPE.EXTEND_NUMBER, cellData: { v: 'A-001-Z' } }, { v: 'B-002-Z' })).toBe(false);
+
+ const reverse = extendNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: 'A-003' }, { v: 'A-004' }], index: [0, 1] },
+ 2,
+ Direction.LEFT,
+ {} as any
+ );
+ expect(reverse?.map((c) => `${c?.v}`)).toEqual(['A-001', 'A-002']);
});
it('chinese-number rule should handle normal numbers and week cycle', () => {
@@ -142,6 +170,22 @@ describe('auto-fill rules', () => {
{} as any
);
expect(week?.map((c) => c?.v)).toEqual(['一', '二', '三']);
+
+ const reverseNormal = chnNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: '三' }, { v: '四' }], index: [0, 1] },
+ 2,
+ Direction.LEFT,
+ {} as any
+ );
+ expect(reverseNormal?.map((c) => c?.v)).toEqual(['一', '二']);
+
+ const copyFallback = chnNumberRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: '一' }, { v: '三' }, { v: '四' }], index: [0, 1, 2] },
+ 2,
+ Direction.DOWN,
+ {} as any
+ );
+ expect(copyFallback?.map((c) => c?.v)).toEqual(['一', '三']);
});
it('chinese week rules should produce weekday sequence', () => {
@@ -158,6 +202,22 @@ describe('auto-fill rules', () => {
);
expect(week2?.map((c) => c?.v)).toEqual(['周一', '周二']);
+ const week2OneReverse = chnWeek2Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: '周一' }], index: [0] },
+ 2,
+ Direction.UP,
+ {} as any
+ );
+ expect(week2OneReverse?.map((c) => c?.v)).toEqual(['周六', '周日']);
+
+ const week2Fallback = chnWeek2Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: '周一' }, { v: '周三' }, { v: '周四' }], index: [0, 1, 2] },
+ 2,
+ Direction.DOWN,
+ {} as any
+ );
+ expect(week2Fallback?.map((c) => c?.v)).toEqual(['周一', '周三']);
+
const week3 = chnWeek3Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
{ data: [{ v: '星期六' }], index: [0] },
2,
@@ -165,6 +225,22 @@ describe('auto-fill rules', () => {
{} as any
);
expect(week3?.map((c) => c?.v)).toEqual(['星期日', '星期一']);
+
+ const week3Multi = chnWeek3Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: '星期六' }, { v: '星期日' }], index: [0, 1] },
+ 2,
+ Direction.DOWN,
+ {} as any
+ );
+ expect(week3Multi?.map((c) => c?.v)).toEqual(['星期一', '星期二']);
+
+ const week3Fallback = chnWeek3Rule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: '星期一' }, { v: '星期三' }, { v: '星期四' }], index: [0, 1, 2] },
+ 2,
+ Direction.DOWN,
+ {} as any
+ );
+ expect(week3Fallback?.map((c) => c?.v)).toEqual(['星期一', '星期三']);
});
it('loop-series rule should match and fill cyclic values', () => {
@@ -192,6 +268,15 @@ describe('auto-fill rules', () => {
{} as any
);
expect(reversed?.length).toBe(2);
+ expect(loopSeriesRule.isContinue({ type: AUTO_FILL_DATA_TYPE.NUMBER, cellData: { v: 'Mon' } }, { v: 'Tue' })).toBe(false);
+
+ const fallback = loopSeriesRule.applyFunctions?.[AUTO_FILL_APPLY_TYPE.SERIES]?.(
+ { data: [{ v: 'Mon' }, { v: 'Wed' }, { v: 'Thu' }], index: [0, 1, 2] },
+ 2,
+ Direction.DOWN,
+ {} as any
+ );
+ expect(fallback?.map((c) => c?.v)).toEqual(['Mon', 'Wed']);
});
it('other rule should always match and continue only from OTHER', () => {
diff --git a/packages/sheets/src/services/permission/__tests__/permission-util.spec.ts b/packages/sheets/src/services/permission/__tests__/permission-util.spec.ts
new file mode 100644
index 0000000000..3e8a1beab1
--- /dev/null
+++ b/packages/sheets/src/services/permission/__tests__/permission-util.spec.ts
@@ -0,0 +1,115 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, IRange } from '@univerjs/core';
+import { IPermissionService } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+import { describe, expect, it } from 'vitest';
+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../models/range-protection-rule.model';
+import { WorkbookEditablePermission, WorksheetEditPermission } from '../permission-point';
+import { RangeProtectionPermissionEditPoint } from '../permission-point/range/edit';
+import { baseProtectionActions, getAllRangePermissionPoint, getDefaultRangePermission } from '../range-permission/util';
+import { checkRangesEditablePermission } from '../util';
+
+function createAccessor(records: Map<unknown, unknown>): IAccessor {
+ return {
+ get: (token: unknown) => records.get(token) as never,
+ has: (token: unknown) => records.has(token),
+ } as IAccessor;
+}
+
+describe('range permission util', () => {
+ it('builds default permission values for every range protection action', () => {
+ expect(getAllRangePermissionPoint().map((F) => new F('unit-1', 'sheet-1', 'permission-1').subType)).toEqual([
+ UnitAction.View,
+ UnitAction.Edit,
+ UnitAction.ManageCollaborator,
+ UnitAction.Delete,
+ ]);
+ expect(baseProtectionActions).toEqual([
+ UnitAction.Edit,
+ UnitAction.View,
+ UnitAction.ManageCollaborator,
+ UnitAction.Delete,
+ ]);
+ expect(getDefaultRangePermission('unit-1', 'sheet-1', 'permission-1')).toEqual({
+ [UnitAction.View]: false,
+ [UnitAction.Edit]: true,
+ [UnitAction.ManageCollaborator]: true,
+ [UnitAction.Delete]: true,
+ });
+ });
+});
+
+describe('checkRangesEditablePermission', () => {
+ const targetRange: IRange = { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 };
+
+ function setup(values: Record<string, boolean | undefined>) {
+ const ruleModel = new RangeProtectionRuleModel();
+ const permissionService = {
+ getPermissionPoint: (id: string) => id in values ? { id, value: values[id] } : undefined,
+ };
+ const accessor = createAccessor(new Map<unknown, unknown>([
+ [IPermissionService, permissionService],
+ [RangeProtectionRuleModel, ruleModel],
+ ]));
+ return { accessor, ruleModel };
+ }
+
+ it('requires workbook and worksheet edit permissions before checking protected ranges', () => {
+ const workbookPermissionId = new WorkbookEditablePermission('unit-1').id;
+ const worksheetPermissionId = new WorksheetEditPermission('unit-1', 'sheet-1').id;
+
+ expect(checkRangesEditablePermission(setup({ [workbookPermissionId]: false, [worksheetPermissionId]: true }).accessor, 'unit-1', 'sheet-1', [targetRange])).toBe(false);
+ expect(checkRangesEditablePermission(setup({ [workbookPermissionId]: true, [worksheetPermissionId]: false }).accessor, 'unit-1', 'sheet-1', [targetRange])).toBe(false);
+ });
+
+ it('allows unprotected ranges and requires edit permission for intersecting protected rules', () => {
+ const workbookPermissionId = new WorkbookEditablePermission('unit-1').id;
+ const worksheetPermissionId = new WorksheetEditPermission('unit-1', 'sheet-1').id;
+ const rangePermissionId = new RangeProtectionPermissionEditPoint('unit-1', 'sheet-1', 'permission-1').id;
+
+ const noProtection = setup({ [workbookPermissionId]: true, [worksheetPermissionId]: true });
+ expect(checkRangesEditablePermission(noProtection.accessor, 'unit-1', 'sheet-1', [targetRange])).toBe(true);
+
+ const denied = setup({ [workbookPermissionId]: true, [worksheetPermissionId]: true, [rangePermissionId]: false });
+ denied.ruleModel.addRule('unit-1', 'sheet-1', {
+ id: 'rule-1',
+ permissionId: 'permission-1',
+ ranges: [targetRange],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ unitType: UnitObject.SelectRange,
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ });
+ expect(checkRangesEditablePermission(denied.accessor, 'unit-1', 'sheet-1', [targetRange])).toBe(false);
+
+ const allowed = setup({ [workbookPermissionId]: true, [worksheetPermissionId]: true, [rangePermissionId]: true });
+ allowed.ruleModel.addRule('unit-1', 'sheet-1', {
+ id: 'rule-1',
+ permissionId: 'permission-1',
+ ranges: [targetRange],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ unitType: UnitObject.SelectRange,
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ });
+ expect(checkRangesEditablePermission(allowed.accessor, 'unit-1', 'sheet-1', [targetRange])).toBe(true);
+ expect(checkRangesEditablePermission(allowed.accessor, 'unit-1', 'sheet-1', [{ startRow: 5, endRow: 5, startColumn: 5, endColumn: 5 }])).toBe(true);
+ });
+});
diff --git a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts
index 65821f59c9..4ff05bbdc5 100644
--- a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts
+++ b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts
@@ -24,6 +24,7 @@ import { AddRangeProtectionMutation } from '../../../../commands/mutations/add-r
import { DeleteRangeProtectionMutation } from '../../../../commands/mutations/delete-range-protection.mutation';
import { InsertColMutation, InsertRowMutation } from '../../../../commands/mutations/insert-row-col.mutation';
import { MoveColsMutation, MoveRowsMutation } from '../../../../commands/mutations/move-rows-cols.mutation';
+import { RemoveColMutation, RemoveRowMutation } from '../../../../commands/mutations/remove-row-col.mutation';
import { SetRangeProtectionMutation } from '../../../../commands/mutations/set-range-protection.mutation';
import { RangeProtectionRenderModel } from '../../../../models/range-protection-render.model';
import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../../models/range-protection-rule.model';
@@ -90,6 +91,8 @@ describe('RangeProtectionRefRangeService', () => {
SetRangeProtectionMutation,
InsertColMutation,
InsertRowMutation,
+ RemoveColMutation,
+ RemoveRowMutation,
MoveRowsMutation,
MoveColsMutation,
].forEach((command) => commandService.registerCommand(command));
@@ -157,6 +160,34 @@ describe('RangeProtectionRefRangeService', () => {
expect(fullResult.redos.some((redo: any) => redo.id === DeleteRangeProtectionMutation.id)).toBe(true);
});
+ it('shrinks protected ranges when protected rows are removed', () => {
+ const rule = createRule({
+ ranges: [{ startRow: 1, endRow: 5, startColumn: 2, endColumn: 4 }],
+ });
+ ruleModel.addRule(unitId, subUnitId, rule);
+
+ const result = service.refRangeHandle({
+ id: 'sheet.command.remove-row',
+ params: { range: { startRow: 3, endRow: 4, startColumn: 0, endColumn: 10 } },
+ } as any, unitId, subUnitId);
+
+ expect(result.redos).toEqual([{
+ id: SetRangeProtectionMutation.id,
+ params: {
+ unitId,
+ subUnitId,
+ ruleId: rule.id,
+ rule: expect.objectContaining({
+ ranges: [{ startRow: 1, endRow: 3, startColumn: 2, endColumn: 4 }],
+ }),
+ },
+ }]);
+ expect(result.undos[0]).toEqual({
+ id: SetRangeProtectionMutation.id,
+ params: { unitId, subUnitId, rule, ruleId: rule.id },
+ });
+ });
+
it('should generate insert and move mutations for overlap rules', () => {
const rule = createRule({
ranges: [{ startRow: 5, endRow: 8, startColumn: 5, endColumn: 8 }],
@@ -212,6 +243,68 @@ describe('RangeProtectionRefRangeService', () => {
expect(rebuildSpy).toHaveBeenCalledWith(unitId, subUnitId);
});
+ it('keeps range protection aligned when rows and columns are inserted or removed before it', async () => {
+ const rule = createRule({
+ ranges: [{ startRow: 5, endRow: 6, startColumn: 5, endColumn: 6 }],
+ });
+ ruleModel.addRule(unitId, subUnitId, rule);
+
+ await commandService.executeCommand(InsertRowMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 2, endRow: 3, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 7, endRow: 8 });
+
+ await commandService.executeCommand(RemoveRowMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 6, endRow: 7 });
+
+ await commandService.executeCommand(InsertColMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 0, endRow: 10, startColumn: 2, endColumn: 3 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startColumn: 7, endColumn: 8 });
+
+ await commandService.executeCommand(RemoveColMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 0, endRow: 10, startColumn: 1, endColumn: 1 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startColumn: 6, endColumn: 7 });
+ });
+
+ it('keeps non-intersecting protected ranges aligned after row and column moves', async () => {
+ const rowRule = createRule({
+ ranges: [{ startRow: 5, endRow: 6, startColumn: 1, endColumn: 2 }],
+ });
+ const colRule = createRule({
+ ranges: [{ startRow: 1, endRow: 2, startColumn: 5, endColumn: 6 }],
+ });
+ ruleModel.addRule(unitId, subUnitId, rowRule);
+ ruleModel.addRule(unitId, subUnitId, colRule);
+
+ await commandService.executeCommand(MoveRowsMutation.id, {
+ unitId,
+ subUnitId,
+ sourceRange: { startRow: 1, endRow: 2, startColumn: 0, endColumn: 10 },
+ targetRange: { startRow: 8, endRow: 9, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rowRule.id)?.ranges[0]).toMatchObject({ startRow: 3, endRow: 4 });
+
+ await commandService.executeCommand(MoveColsMutation.id, {
+ unitId,
+ subUnitId,
+ sourceRange: { startRow: 0, endRow: 10, startColumn: 1, endColumn: 2 },
+ targetRange: { startRow: 0, endRow: 10, startColumn: 8, endColumn: 9 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, colRule.id)?.ranges[0]).toMatchObject({ startColumn: 3, endColumn: 4 });
+ });
+
it('should register ref ranges after range protection mutation', async () => {
const registerSpy = vi.spyOn(refRangeService, 'registerRefRange');
const rule = createRule({
diff --git a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.service.spec.ts b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.service.spec.ts
index abe6d5d50e..6f4d0e2f45 100644
--- a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.service.spec.ts
+++ b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.service.spec.ts
@@ -14,43 +14,167 @@
* limitations under the License.
*/
-import { Injector, IPermissionService, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';
-import { Subject } from 'rxjs';
+import type { IDisposable, IPermissionPoint, IRange, Workbook } from '@univerjs/core';
+import type { IRangeProtectionRule } from '../../../../models/range-protection-rule.model';
+import { Injector, IPermissionService, IResourceManagerService, IUniverInstanceService, PermissionStatus } from '@univerjs/core';
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+import { of, Subject } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { RangeProtectionRuleModel } from '../../../../models/range-protection-rule.model';
+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../../models/range-protection-rule.model';
import { RangeProtectionCache } from '../../../../models/range-protection.cache';
import { RangeProtectionService } from '../range-protection.service';
+class TestPermissionService {
+ readonly permissionPointUpdate$ = new Subject<unknown>();
+ readonly addedPermissionIds: string[] = [];
+ readonly deletedPermissionIds: string[] = [];
+
+ addPermissionPoint(point: { id: string }) {
+ this.addedPermissionIds.push(point.id);
+ return true;
+ }
+
+ deletePermissionPoint(id: string) {
+ this.deletedPermissionIds.push(id);
+ }
+
+ updatePermissionPoint() {
+ return true;
+ }
+
+ getPermissionPoint(permissionId: string): IPermissionPoint<boolean> {
+ return { id: permissionId, value: true, type: UnitObject.SelectRange, subType: UnitAction.Edit, status: PermissionStatus.DONE };
+ }
+
+ getPermissionPoint$(permissionId: string) {
+ return of(this.getPermissionPoint(permissionId));
+ }
+
+ clearPermissionMap() {
+ this.addedPermissionIds.length = 0;
+ this.deletedPermissionIds.length = 0;
+ }
+
+ composePermission(permissionIds: string[]) {
+ return permissionIds.map((id) => this.getPermissionPoint(id));
+ }
+
+ composePermission$(permissionIds: string[]) {
+ return of(this.composePermission(permissionIds));
+ }
+
+ getAllPermissionPoint() {
+ return new Map();
+ }
+
+ getShowComponents() {
+ return true;
+ }
+
+ setShowComponents() {
+ return undefined;
+ }
+}
+
+class TestResourceManagerService {
+ registeredResource!: {
+ toJson: (unitId: string) => string;
+ parseJson: (json: string) => unknown;
+ onLoad: (unitId: string, resources: Record<string, IRangeProtectionRule[]>) => void;
+ onUnLoad: (unitId: string) => void;
+ };
+
+ registerPluginResource(resource: TestResourceManagerService['registeredResource']): IDisposable {
+ this.registeredResource = resource;
+ return { dispose: vi.fn() };
+ }
+}
+
+class TestUniverInstanceService {
+ getAllUnitsForType(): Workbook[] {
+ return [];
+ }
+
+ getUnit(): Workbook | null {
+ return null;
+ }
+}
+
describe('RangeProtectionService', () => {
- let ruleChange$: Subject<unknown>;
- let addedPermissionIds: string[];
- let deletedPermissionIds: string[];
+ let ruleModel: RangeProtectionRuleModel;
+ let permissionService: TestPermissionService;
+ let resourceManagerService: TestResourceManagerService;
+ let cache: RangeProtectionCache;
+
+ const createRule = (id: string, permissionId: string, ranges: IRange[] = [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }]): IRangeProtectionRule => ({
+ id,
+ permissionId,
+ ranges,
+ unitType: UnitObject.SelectRange,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ });
beforeEach(() => {
- ruleChange$ = new Subject();
- addedPermissionIds = [];
- deletedPermissionIds = [];
const injector = new Injector();
- injector.add([RangeProtectionRuleModel, { useValue: { ruleChange$, toObject: () => ({}), fromObject: vi.fn(), getSubunitRuleList: () => [] } as unknown as RangeProtectionRuleModel }]);
- injector.add([IPermissionService, { useValue: {
- addPermissionPoint: (point: { id: string }) => {
- addedPermissionIds.push(point.id);
- return true;
- },
- deletePermissionPoint: (id: string) => deletedPermissionIds.push(id),
- } as unknown as IPermissionService }]);
- injector.add([IResourceManagerService, { useValue: { registerPluginResource: vi.fn(() => ({ dispose: vi.fn() })) } as unknown as IResourceManagerService }]);
- injector.add([RangeProtectionCache, { useValue: { reBuildCache: vi.fn(), deleteUnit: vi.fn() } as unknown as RangeProtectionCache }]);
- injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);
+ injector.add([IPermissionService, { useClass: TestPermissionService as never }]);
+ injector.add([IResourceManagerService, { useClass: TestResourceManagerService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([RangeProtectionCache]);
injector.add([RangeProtectionService]);
+
+ permissionService = injector.get(IPermissionService) as unknown as TestPermissionService;
+ resourceManagerService = injector.get(IResourceManagerService) as unknown as TestResourceManagerService;
+ ruleModel = injector.get(RangeProtectionRuleModel);
+ cache = injector.get(RangeProtectionCache);
+ vi.spyOn(cache, 'reBuildCache');
+ vi.spyOn(cache, 'deleteUnit');
injector.get(RangeProtectionService);
});
it('adds and removes range permission points when protection rules change', () => {
- ruleChange$.next({ type: 'add', unitId: 'book-1', subUnitId: 'sheet-1', rule: { permissionId: 'perm-1' } });
- ruleChange$.next({ type: 'delete', unitId: 'book-1', subUnitId: 'sheet-1', rule: { permissionId: 'perm-1' } });
+ const rule = createRule('rule-1', 'perm-1');
+
+ ruleModel.addRule('book-1', 'sheet-1', rule);
+ ruleModel.deleteRule('book-1', 'sheet-1', 'rule-1');
+
+ expect(permissionService.addedPermissionIds.every((id) => id.includes('perm-1'))).toBe(true);
+ expect(permissionService.deletedPermissionIds).toEqual(permissionService.addedPermissionIds);
+ });
+
+ it('replaces permission points when a range rule moves to a new permission id', () => {
+ const oldRule = createRule('rule-1', 'old-perm');
+ const newRule = createRule('rule-1', 'new-perm');
+
+ ruleModel.addRule('book-1', 'sheet-1', oldRule);
+ permissionService.addedPermissionIds.length = 0;
+ ruleModel.setRule('book-1', 'sheet-1', 'rule-1', newRule);
+
+ expect(permissionService.deletedPermissionIds.every((id) => id.includes('old-perm'))).toBe(true);
+ expect(permissionService.addedPermissionIds.every((id) => id.includes('new-perm'))).toBe(true);
+ });
+
+ it('restores range protection snapshot and rebuilds cache for loaded sheets', () => {
+ const loadedRule = createRule('loaded-rule', 'perm-loaded');
+ ruleModel.addRule('book-1', 'sheet-1', createRule('json-rule', 'perm-json'));
+
+ expect(resourceManagerService.registeredResource.toJson('book-1')).toContain('perm-json');
+ expect(resourceManagerService.registeredResource.toJson('missing')).toBe('');
+ expect(resourceManagerService.registeredResource.parseJson('')).toEqual({});
+ expect(resourceManagerService.registeredResource.parseJson('{bad json')).toEqual({});
+ expect(resourceManagerService.registeredResource.parseJson('{"sheet-1":[]}')).toEqual({ 'sheet-1': [] });
+
+ permissionService.addedPermissionIds.length = 0;
+ resourceManagerService.registeredResource.onLoad('book-2', { 'sheet-2': [loadedRule] });
+
+ expect(ruleModel.getRule('book-2', 'sheet-2', 'loaded-rule')).toEqual(loadedRule);
+ expect(permissionService.addedPermissionIds.every((id) => id.includes('perm-loaded'))).toBe(true);
+ expect(cache.reBuildCache).toHaveBeenCalledWith('book-2', 'sheet-2');
- expect(addedPermissionIds.every((id) => id.includes('perm-1'))).toBe(true);
- expect(deletedPermissionIds).toEqual(addedPermissionIds);
+ resourceManagerService.registeredResource.onUnLoad('book-2');
+ expect(cache.deleteUnit).toHaveBeenCalledWith('book-2');
});
});
diff --git a/packages/sheets/src/services/permission/workbook-permission/__tests__/workbook-permission.service.spec.ts b/packages/sheets/src/services/permission/workbook-permission/__tests__/workbook-permission.service.spec.ts
index 89509f2412..042b2a9c33 100644
--- a/packages/sheets/src/services/permission/workbook-permission/__tests__/workbook-permission.service.spec.ts
+++ b/packages/sheets/src/services/permission/workbook-permission/__tests__/workbook-permission.service.spec.ts
@@ -14,48 +14,93 @@
* limitations under the License.
*/
+import type { Workbook } from '@univerjs/core';
+import type { IRangeProtectionRule } from '../../../../models/range-protection-rule.model';
import { Injector, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { UnitObject } from '@univerjs/protocol';
import { Subject } from 'rxjs';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { RangeProtectionRuleModel } from '../../../../models/range-protection-rule.model';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../../models/range-protection-rule.model';
import { WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '../../worksheet-permission';
import { WorkbookPermissionService } from '../workbook-permission.service';
+class TestPermissionService {
+ readonly addedPermissionIds: string[] = [];
+ readonly deletedPermissionIds: string[] = [];
+
+ addPermissionPoint(point: { id: string }) {
+ this.addedPermissionIds.push(point.id);
+ return true;
+ }
+
+ deletePermissionPoint(id: string) {
+ this.deletedPermissionIds.push(id);
+ }
+}
+
+class TestUniverInstanceService {
+ readonly sheetAdded$ = new Subject<{ unit: Workbook }>();
+ readonly sheetDisposed$ = new Subject<Workbook>();
+
+ getAllUnitsForType(): Workbook[] {
+ return [];
+ }
+
+ getTypeOfUnitAdded$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this.sheetAdded$ : new Subject<{ unit: Workbook }>();
+ }
+
+ getTypeOfUnitDisposed$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this.sheetDisposed$ : new Subject<Workbook>();
+ }
+}
+
describe('WorkbookPermissionService', () => {
let service: WorkbookPermissionService;
- let addedPermissionIds: string[];
- let sheetAdded$: Subject<unknown>;
- let sheetDisposed$: Subject<unknown>;
+ let permissionService: TestPermissionService;
+ let univerInstanceService: TestUniverInstanceService;
+ let rangeRuleModel: RangeProtectionRuleModel;
+ let worksheetRuleModel: WorksheetProtectionRuleModel;
+ let worksheetPointModel: WorksheetProtectionPointModel;
+
+ const createWorkbook = (unitId = 'book-1') => ({
+ getUnitId: () => unitId,
+ getSheets: () => [{ getSheetId: () => 'sheet-1' }],
+ }) as unknown as Workbook;
+
+ const rangeRule: IRangeProtectionRule = {
+ id: 'range-rule-1',
+ permissionId: 'range-perm-1',
+ ranges: [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }],
+ unitType: UnitObject.SelectRange,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
beforeEach(() => {
- addedPermissionIds = [];
- sheetAdded$ = new Subject();
- sheetDisposed$ = new Subject();
const injector = new Injector();
- injector.add([IPermissionService, { useValue: {
- addPermissionPoint: (point: { id: string }) => {
- addedPermissionIds.push(point.id);
- return true;
- },
- deletePermissionPoint: vi.fn(),
- } as unknown as IPermissionService }]);
- injector.add([IUniverInstanceService, { useValue: {
- getAllUnitsForType: () => [],
- getTypeOfUnitAdded$: (type: UniverInstanceType) => type === UniverInstanceType.UNIVER_SHEET ? sheetAdded$ : new Subject(),
- getTypeOfUnitDisposed$: (type: UniverInstanceType) => type === UniverInstanceType.UNIVER_SHEET ? sheetDisposed$ : new Subject(),
- } as unknown as IUniverInstanceService }]);
- injector.add([RangeProtectionRuleModel, { useValue: { getSubunitRuleList: () => [], deleteUnitModel: vi.fn() } as unknown as RangeProtectionRuleModel }]);
- injector.add([WorksheetProtectionRuleModel, { useValue: { deleteUnitModel: vi.fn() } as unknown as WorksheetProtectionRuleModel }]);
- injector.add([WorksheetProtectionPointModel, { useValue: { deleteUnitModel: vi.fn() } as unknown as WorksheetProtectionPointModel }]);
+ injector.add([IPermissionService, { useClass: TestPermissionService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([WorksheetProtectionRuleModel]);
+ injector.add([WorksheetProtectionPointModel]);
injector.add([WorkbookPermissionService]);
+
+ permissionService = injector.get(IPermissionService) as unknown as TestPermissionService;
+ univerInstanceService = injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService;
+ rangeRuleModel = injector.get(RangeProtectionRuleModel);
+ worksheetRuleModel = injector.get(WorksheetProtectionRuleModel);
+ worksheetPointModel = injector.get(WorksheetProtectionPointModel);
service = injector.get(WorkbookPermissionService);
});
it('registers workbook permission points when a workbook is added', () => {
- sheetAdded$.next({ unit: { getUnitId: () => 'book-1' } });
+ univerInstanceService.sheetAdded$.next({ unit: createWorkbook() });
- expect(addedPermissionIds.length).toBeGreaterThan(0);
- expect(addedPermissionIds.every((id) => id.includes('book-1'))).toBe(true);
+ expect(permissionService.addedPermissionIds.length).toBeGreaterThan(0);
+ expect(permissionService.addedPermissionIds.every((id) => id.includes('book-1'))).toBe(true);
});
it('publishes workbook permission initialization state changes', () => {
@@ -66,4 +111,26 @@ describe('WorkbookPermissionService', () => {
expect(states).toEqual([false, true]);
});
+
+ it('deletes workbook, worksheet, and range permission points when a workbook is disposed', () => {
+ rangeRuleModel.addRule('book-1', 'sheet-1', rangeRule);
+ worksheetRuleModel.addRule('book-1', {
+ permissionId: 'worksheet-rule-perm',
+ unitType: UnitObject.Worksheet,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ });
+ worksheetPointModel.addRule({ unitId: 'book-1', subUnitId: 'sheet-1', permissionId: 'worksheet-point-perm' });
+
+ univerInstanceService.sheetDisposed$.next(createWorkbook());
+
+ expect(permissionService.deletedPermissionIds.some((id) => id.includes('range-perm-1'))).toBe(true);
+ expect(permissionService.deletedPermissionIds.some((id) => id.includes('sheet-1'))).toBe(true);
+ expect(permissionService.deletedPermissionIds.some((id) => id.includes('book-1'))).toBe(true);
+ expect(rangeRuleModel.getSubunitRuleList('book-1', 'sheet-1')).toEqual([]);
+ expect(worksheetRuleModel.getRule('book-1', 'sheet-1')).toBeUndefined();
+ expect(worksheetPointModel.getRule('book-1', 'sheet-1')).toBeUndefined();
+ });
});
diff --git a/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission-models.spec.ts b/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission-models.spec.ts
new file mode 100644
index 0000000000..ef86f97145
--- /dev/null
+++ b/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission-models.spec.ts
@@ -0,0 +1,107 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { UnitAction, UnitObject } from '@univerjs/protocol';
+import { describe, expect, it } from 'vitest';
+import { EditStateEnum, ViewStateEnum } from '../../../../models/range-protection-rule.model';
+import { defaultSheetActions } from '../type';
+import { WorksheetProtectionPointModel } from '../worksheet-permission-point.model';
+import { WorksheetProtectionRuleModel } from '../worksheet-permission-rule.model';
+
+describe('worksheet protection defaults', () => {
+ it('uses edit and copy as the default actions protected by a worksheet rule', () => {
+ expect(defaultSheetActions).toEqual([UnitAction.Edit, UnitAction.Copy]);
+ });
+});
+
+describe('WorksheetProtectionRuleModel', () => {
+ it('adds, updates, deletes, serializes, and restores worksheet rules', () => {
+ const model = new WorksheetProtectionRuleModel();
+ const changes: string[] = [];
+ const refreshes: string[] = [];
+ let resetCount = 0;
+ model.ruleChange$.subscribe((change) => changes.push(`${change.type}:${change.subUnitId}:${change.rule.permissionId}`));
+ model.ruleRefresh$.subscribe((permissionId) => refreshes.push(permissionId));
+ model.resetOrder$.subscribe(() => resetCount++);
+ const originalRule = {
+ permissionId: 'permission-1',
+ unitType: UnitObject.Worksheet,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
+
+ expect(model.getSheetRuleInitState()).toBe(false);
+ model.changeRuleInitState(true);
+ expect(model.getSheetRuleInitState()).toBe(true);
+
+ model.addRule('unit-1', originalRule);
+ expect(model.getRule('unit-1', 'sheet-1')).toEqual(originalRule);
+
+ const updatedRule = { ...originalRule, permissionId: 'permission-2' };
+ model.setRule('unit-1', 'sheet-1', updatedRule);
+ model.setRule('unit-1', 'missing', { ...updatedRule, subUnitId: 'missing' });
+ expect(model.getRule('unit-1', 'sheet-1')).toEqual(updatedRule);
+ expect(model.getTargetByPermissionId('unit-1', 'permission-2')).toEqual(['unit-1', 'sheet-1']);
+ expect(model.getTargetByPermissionId('unit-1', 'missing')).toBeUndefined();
+ expect(model.getTargetByPermissionId('missing', 'permission-2')).toBeNull();
+ expect(model.toObject()).toEqual({ 'unit-1': [updatedRule] });
+
+ model.ruleRefresh('permission-2');
+ model.resetOrder();
+ expect(refreshes).toEqual(['permission-2']);
+ expect(resetCount).toBe(1);
+
+ const restored = new WorksheetProtectionRuleModel();
+ restored.fromObject({ 'unit-2': [{ ...updatedRule, unitId: 'unit-2', subUnitId: 'sheet-2' }] });
+ expect(restored.getRule('unit-2', 'sheet-2')).toEqual({ ...updatedRule, unitId: 'unit-2', subUnitId: 'sheet-2' });
+ restored.deleteUnitModel('unit-2');
+ expect(restored.toObject()).toEqual({});
+
+ model.deleteRule('unit-1', 'sheet-1');
+ model.deleteRule('unit-1', 'sheet-1');
+ expect(model.getRule('unit-1', 'sheet-1')).toBeUndefined();
+ expect(changes).toEqual(['add:sheet-1:permission-1', 'set:sheet-1:permission-2', 'delete:sheet-1:permission-2']);
+ });
+});
+
+describe('WorksheetProtectionPointModel', () => {
+ it('adds, deletes, serializes, and restores worksheet point rules', () => {
+ const model = new WorksheetProtectionPointModel();
+ const changes: string[] = [];
+ model.pointChange$.subscribe((change) => changes.push(`${change.subUnitId}:${change.permissionId}`));
+ const firstRule = { unitId: 'unit-1', subUnitId: 'sheet-1', permissionId: 'permission-1' };
+
+ model.addRule(firstRule);
+ expect(model.getRule('unit-1', 'sheet-1')).toEqual(firstRule);
+ expect(model.toObject()).toEqual({ 'unit-1': [firstRule] });
+ expect(model.getTargetByPermissionId('unit-1', 'permission-1')).toEqual(['unit-1', 'sheet-1']);
+ expect(model.getTargetByPermissionId('unit-1', 'missing')).toBeUndefined();
+ expect(model.getTargetByPermissionId('missing', 'permission-1')).toBeNull();
+
+ const restored = new WorksheetProtectionPointModel();
+ restored.fromObject({ 'unit-2': [{ unitId: 'unit-2', subUnitId: 'sheet-2', permissionId: 'permission-2' }] });
+ expect(restored.getRule('unit-2', 'sheet-2')).toEqual({ unitId: 'unit-2', subUnitId: 'sheet-2', permissionId: 'permission-2' });
+ restored.deleteUnitModel('unit-2');
+ expect(restored.toObject()).toEqual({});
+
+ model.deleteRule('unit-1', 'sheet-1');
+ model.deleteRule('unit-1', 'sheet-1');
+ expect(model.getRule('unit-1', 'sheet-1')).toBeUndefined();
+ expect(changes).toEqual(['sheet-1:permission-1', 'sheet-1:permission-1']);
+ });
+});
diff --git a/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission.service.spec.ts b/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission.service.spec.ts
index 3095a72cf5..f19f73b86d 100644
--- a/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission.service.spec.ts
+++ b/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission.service.spec.ts
@@ -14,55 +14,213 @@
* limitations under the License.
*/
-import { DesktopLogService, ILogService, Injector, IPermissionService, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';
+import type { IDisposable, Workbook, Worksheet } from '@univerjs/core';
+import type {
+ IRangeProtectionRule,
+ EditStateEnum as RangeEditStateEnum,
+} from '../../../../models/range-protection-rule.model';
+import type { IObjectModel, IObjectPointModel } from '../../type';
+import {
+ DesktopLogService,
+ ILogService,
+ Injector,
+ IPermissionService,
+ IResourceManagerService,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { UnitObject } from '@univerjs/protocol';
import { Subject } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { RangeProtectionRuleModel } from '../../../../models/range-protection-rule.model';
+import {
+ EditStateEnum,
+ RangeProtectionRuleModel,
+ ViewStateEnum,
+} from '../../../../models/range-protection-rule.model';
import { WorksheetProtectionPointModel } from '../worksheet-permission-point.model';
import { WorksheetProtectionRuleModel } from '../worksheet-permission-rule.model';
import { WorksheetPermissionService } from '../worksheet-permission.service';
+class TestPermissionService {
+ readonly addedPermissionIds: string[] = [];
+ readonly deletedPermissionIds: string[] = [];
+ readonly updatedPermissionPoints: Array<{ id: string; value: unknown }> = [];
+
+ addPermissionPoint(point: { id: string }) {
+ this.addedPermissionIds.push(point.id);
+ return true;
+ }
+
+ deletePermissionPoint(id: string) {
+ this.deletedPermissionIds.push(id);
+ }
+
+ updatePermissionPoint(id: string, value: unknown) {
+ this.updatedPermissionPoints.push({ id, value });
+ return true;
+ }
+}
+
+class TestResourceManagerService {
+ readonly resources: Array<{
+ pluginName: string;
+ toJson: () => string;
+ parseJson: (json: string) => IObjectModel | IObjectPointModel;
+ onLoad: (unitId: string, resources: IObjectModel | IObjectPointModel) => void;
+ onUnLoad: (unitId: string) => void;
+ }> = [];
+
+ registerPluginResource(resource: TestResourceManagerService['resources'][number]): IDisposable {
+ this.resources.push(resource);
+ return { dispose: vi.fn() };
+ }
+}
+
+class TestUniverInstanceService {
+ readonly unitAdded$ = new Subject<{ unit: Workbook }>();
+ readonly unitDisposed$ = new Subject<Workbook>();
+ workbook!: Workbook;
+
+ getAllUnitsForType(): Workbook[] {
+ return [this.workbook];
+ }
+
+ getTypeOfUnitAdded$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this.unitAdded$ : new Subject<{ unit: Workbook }>();
+ }
+
+ getTypeOfUnitDisposed$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SHEET ? this.unitDisposed$ : new Subject<Workbook>();
+ }
+
+ getUnit(unitId: string): Workbook | undefined {
+ return this.workbook.getUnitId() === unitId ? this.workbook : undefined;
+ }
+}
+
describe('WorksheetPermissionService', () => {
- let addedPermissionIds: string[];
- let ruleChange$: Subject<unknown>;
+ let permissionService: TestPermissionService;
+ let resourceManagerService: TestResourceManagerService;
+ let univerInstanceService: TestUniverInstanceService;
+ let worksheetRuleModel: WorksheetProtectionRuleModel;
+ let worksheetPointModel: WorksheetProtectionPointModel;
+ let rangeRuleModel: RangeProtectionRuleModel;
+ let sheetCreated$: Subject<Worksheet>;
+ let sheetDisposed$: Subject<Worksheet>;
- beforeEach(() => {
- addedPermissionIds = [];
- ruleChange$ = new Subject();
- const sheetCreated$ = new Subject();
- const sheetDisposed$ = new Subject();
- const workbook = {
+ const createWorksheet = (sheetId: string) => ({ getSheetId: () => sheetId }) as unknown as Worksheet;
+ const createWorkbook = (sheetIds = ['sheet-1']) => {
+ sheetCreated$ = new Subject<Worksheet>();
+ sheetDisposed$ = new Subject<Worksheet>();
+ return {
getUnitId: () => 'book-1',
- getSheets: () => [{ getSheetId: () => 'sheet-1' }],
+ getSheets: () => sheetIds.map(createWorksheet),
sheetCreated$,
sheetDisposed$,
- };
+ } as unknown as Workbook;
+ };
+
+ beforeEach(() => {
const injector = new Injector();
- injector.add([IPermissionService, { useValue: {
- addPermissionPoint: (point: { id: string }) => {
- addedPermissionIds.push(point.id);
- return true;
- },
- deletePermissionPoint: vi.fn(),
- updatePermissionPoint: vi.fn(),
- } as unknown as IPermissionService }]);
- injector.add([IUniverInstanceService, { useValue: {
- getAllUnitsForType: () => [workbook],
- getTypeOfUnitAdded$: () => new Subject(),
- getTypeOfUnitDisposed$: () => new Subject(),
- getUnit: () => workbook,
- } as unknown as IUniverInstanceService }]);
- injector.add([WorksheetProtectionRuleModel, { useValue: { ruleChange$, toObject: () => ({}), fromObject: vi.fn(), changeRuleInitState: vi.fn(), deleteUnitModel: vi.fn() } as unknown as WorksheetProtectionRuleModel }]);
- injector.add([WorksheetProtectionPointModel, { useValue: { toObject: () => ({}), fromObject: vi.fn(), deleteUnitModel: vi.fn() } as unknown as WorksheetProtectionPointModel }]);
- injector.add([IResourceManagerService, { useValue: { registerPluginResource: vi.fn(() => ({ dispose: vi.fn() })) } as unknown as IResourceManagerService }]);
- injector.add([RangeProtectionRuleModel, { useValue: { getSubunitRuleList: () => [] } as unknown as RangeProtectionRuleModel }]);
+ injector.add([IPermissionService, { useClass: TestPermissionService as never }]);
+ injector.add([IResourceManagerService, { useClass: TestResourceManagerService as never }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([WorksheetProtectionRuleModel]);
+ injector.add([WorksheetProtectionPointModel]);
+ injector.add([RangeProtectionRuleModel]);
injector.add([ILogService, { useClass: DesktopLogService }]);
injector.add([WorksheetPermissionService]);
+
+ permissionService = injector.get(IPermissionService) as unknown as TestPermissionService;
+ resourceManagerService = injector.get(IResourceManagerService) as unknown as TestResourceManagerService;
+ univerInstanceService = injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService;
+ worksheetRuleModel = injector.get(WorksheetProtectionRuleModel);
+ worksheetPointModel = injector.get(WorksheetProtectionPointModel);
+ rangeRuleModel = injector.get(RangeProtectionRuleModel);
+ univerInstanceService.workbook = createWorkbook();
injector.get(WorksheetPermissionService);
});
- it('registers worksheet permission points for existing sheets', () => {
- expect(addedPermissionIds.length).toBeGreaterThan(0);
- expect(addedPermissionIds.every((id) => id.includes('book-1') && id.includes('sheet-1'))).toBe(true);
+ it('registers worksheet permission points for existing and newly created sheets', () => {
+ expect(permissionService.addedPermissionIds.length).toBeGreaterThan(0);
+ expect(permissionService.addedPermissionIds.every((id) => id.includes('book-1') && id.includes('sheet-1'))).toBe(true);
+
+ permissionService.addedPermissionIds.length = 0;
+ sheetCreated$.next(createWorksheet('sheet-2'));
+
+ expect(permissionService.addedPermissionIds.length).toBeGreaterThan(0);
+ expect(permissionService.addedPermissionIds.every((id) => id.includes('book-1') && id.includes('sheet-2'))).toBe(true);
+ });
+
+ it('removes worksheet and range permission points when a worksheet is disposed', () => {
+ const rangeRule: IRangeProtectionRule = {
+ id: 'range-rule-1',
+ permissionId: 'range-perm-1',
+ ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],
+ unitType: UnitObject.SelectRange,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView as ViewStateEnum,
+ editState: EditStateEnum.OnlyMe as RangeEditStateEnum,
+ };
+ rangeRuleModel.addRule('book-1', 'sheet-1', rangeRule);
+
+ sheetDisposed$.next(createWorksheet('sheet-1'));
+
+ expect(permissionService.deletedPermissionIds.some((id) => id.includes('range-perm-1'))).toBe(true);
+ expect(permissionService.deletedPermissionIds.some((id) => id.includes('book-1') && id.includes('sheet-1'))).toBe(true);
+ });
+
+ it('updates worksheet permission points when protection rules are changed or removed', () => {
+ const rule = {
+ permissionId: 'worksheet-perm-1',
+ unitType: UnitObject.Worksheet,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
+
+ worksheetRuleModel.addRule('book-1', rule);
+ worksheetRuleModel.setRule('book-1', 'sheet-1', { ...rule, permissionId: 'worksheet-perm-2' });
+ worksheetRuleModel.deleteRule('book-1', 'sheet-1');
+
+ expect(permissionService.updatedPermissionPoints.some((item) => item.value === true)).toBe(true);
+ expect(permissionService.updatedPermissionPoints.some((item) => item.value !== true)).toBe(true);
+ });
+
+ it('restores worksheet rule and point snapshots and removes resources on unload', () => {
+ const ruleResource = resourceManagerService.resources[0];
+ const pointResource = resourceManagerService.resources[1];
+ const worksheetRule = {
+ permissionId: 'worksheet-perm-1',
+ unitType: UnitObject.Worksheet,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ viewState: ViewStateEnum.OthersCanView,
+ editState: EditStateEnum.OnlyMe,
+ };
+ const worksheetPoint = { unitId: 'book-1', subUnitId: 'sheet-1', permissionId: 'worksheet-point-1' };
+
+ worksheetRuleModel.addRule('book-1', worksheetRule);
+ worksheetPointModel.addRule(worksheetPoint);
+ expect(ruleResource.toJson()).toContain('worksheet-perm-1');
+ expect(pointResource.toJson()).toContain('worksheet-point-1');
+ expect(ruleResource.parseJson('')).toEqual({});
+ expect(pointResource.parseJson('{bad json')).toEqual({});
+
+ permissionService.addedPermissionIds.length = 0;
+ ruleResource.onLoad('book-1', { 'book-1': [{ ...worksheetRule, subUnitId: 'sheet-2' }] });
+ pointResource.onLoad('book-1', { 'book-1': [{ unitId: 'book-1', subUnitId: 'sheet-2', permissionId: 'worksheet-point-2' }] });
+
+ expect(worksheetRuleModel.getRule('book-1', 'sheet-2')?.permissionId).toBe('worksheet-perm-1');
+ expect(worksheetPointModel.getRule('book-1', 'sheet-2')?.permissionId).toBe('worksheet-point-2');
+ expect(permissionService.addedPermissionIds.some((id) => id.includes('book-1'))).toBe(true);
+
+ ruleResource.onUnLoad('book-1');
+ pointResource.onUnLoad('book-1');
+ expect(worksheetRuleModel.getRule('book-1', 'sheet-1')).toBeUndefined();
+ expect(worksheetPointModel.getRule('book-1', 'sheet-2')).toBeUndefined();
+ expect(permissionService.deletedPermissionIds.some((id) => id.includes('book-1') && id.includes('sheet-1'))).toBe(true);
});
});
diff --git a/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts b/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts
new file mode 100644
index 0000000000..5473dd7234
--- /dev/null
+++ b/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts
@@ -0,0 +1,643 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, ICommandInfo, IRange } from '@univerjs/core';
+import type {
+ IInsertColMutationParams,
+ IInsertRowMutationParams,
+ IRemoveColMutationParams,
+ IRemoveRowsMutationParams,
+} from '../../../basics';
+import type { IMoveRangeMutationParams } from '../../../commands/mutations/move-range.mutation';
+import type { IMoveColumnsMutationParams } from '../../../commands/mutations/move-rows-cols.mutation';
+import { Direction, IUniverInstanceService, MAX_COLUMN_COUNT, MAX_ROW_COUNT, RANGE_TYPE } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { InsertColMutation, InsertRowMutation } from '../../../commands/mutations/insert-row-col.mutation';
+import { MoveRangeMutation } from '../../../commands/mutations/move-range.mutation';
+import { MoveColsMutation } from '../../../commands/mutations/move-rows-cols.mutation';
+import { RemoveColMutation, RemoveRowMutation } from '../../../commands/mutations/remove-row-col.mutation';
+import { EffectRefRangId } from '../type';
+import {
+ adjustRangeOnMutation,
+ getEffectedRangesOnCommand,
+ getEffectedRangesOnMutation,
+ getSeparateEffectedRangesOnCommand,
+ handleCommonDefaultRangeChangeWithEffectRefCommands,
+ handleCommonRangeChangeWithEffectRefCommandsSkipNoInterests,
+ handleDefaultRangeChangeWithEffectRefCommands,
+ handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests,
+ handleDeleteRangeMoveLeftCommon,
+ handleDeleteRangeMoveUpCommon,
+ handleInsertColCommon,
+ handleInsertRangeMoveDownCommon,
+ handleInsertRangeMoveRightCommon,
+ handleInsertRowCommon,
+ handleIRemoveRow,
+ handleMoveCols,
+ handleMoveColsCommon,
+ handleMoveRangeCommon,
+ handleMoveRowsCommon,
+ handleRangeTypeInput,
+ handleRangeTypeOutput,
+ handleReorderRange,
+ handleReorderRangeCommon,
+ rotateRange,
+ runRefRangeMutations,
+} from '../util';
+
+const r = (startRow: number, endRow: number, startColumn: number, endColumn: number, rangeType?: RANGE_TYPE): IRange => ({
+ startRow,
+ endRow,
+ startColumn,
+ endColumn,
+ ...(rangeType === undefined ? {} : { rangeType }),
+});
+
+const formatRanges = (ranges: IRange[]) =>
+ ranges
+ .map((range) => [range.startRow, range.endRow, range.startColumn, range.endColumn] as const)
+ .sort((prev, aft) => prev[0] - aft[0] || prev[2] - aft[2] || prev[1] - aft[1] || prev[3] - aft[3]);
+
+const selectionDeps = (range?: IRange) => ({
+ selectionManagerService: {
+ getCurrentSelections: () => range ? [{ range }] : [],
+ },
+} as any);
+
+describe('ref range util behavior coverage', () => {
+ describe('range type normalization', () => {
+ it('expands typed and inferred column/row/all ranges for internal calculation', () => {
+ expect(handleRangeTypeInput(r(Number.NaN, Number.NaN, 2, 4))).toEqual(r(0, MAX_ROW_COUNT - 1, 2, 4));
+ expect(handleRangeTypeInput(r(2, 4, Number.NaN, Number.NaN))).toEqual(r(2, 4, 0, MAX_COLUMN_COUNT - 1));
+ expect(handleRangeTypeInput(r(0, 0, 3, 5, RANGE_TYPE.COLUMN))).toEqual(r(0, MAX_ROW_COUNT - 1, 3, 5, RANGE_TYPE.COLUMN));
+ expect(handleRangeTypeInput(r(3, 5, 0, 0, RANGE_TYPE.ROW))).toEqual(r(3, 5, 0, MAX_COLUMN_COUNT - 1, RANGE_TYPE.ROW));
+ expect(handleRangeTypeInput(r(4, 6, 7, 9, RANGE_TYPE.ALL))).toEqual(r(0, MAX_ROW_COUNT - 1, 0, MAX_COLUMN_COUNT - 1, RANGE_TYPE.ALL));
+ });
+
+ it('clips concrete ranges and restores typed ranges to the current sheet size', () => {
+ expect(handleRangeTypeOutput(r(-2, 12, -3, 15), 10, 8)).toEqual(r(0, 10, 0, 8));
+ expect(handleRangeTypeOutput(r(2, 4, 3, 5, RANGE_TYPE.COLUMN), 99, 20)).toEqual(r(0, 99, 3, 5, RANGE_TYPE.COLUMN));
+ expect(handleRangeTypeOutput(r(2, 4, 3, 5, RANGE_TYPE.ROW), 99, 20)).toEqual(r(2, 4, 0, 20, RANGE_TYPE.ROW));
+ expect(handleRangeTypeOutput(r(2, 4, 3, 5, RANGE_TYPE.ALL), 99, 20)).toEqual(r(0, 99, 0, 20, RANGE_TYPE.ALL));
+ });
+
+ it('rotates row and column range types with their coordinates', () => {
+ expect(rotateRange(r(2, 4, 5, 8, RANGE_TYPE.COLUMN))).toEqual(r(5, 8, 2, 4, RANGE_TYPE.ROW));
+ expect(rotateRange(r(2, 4, 5, 8, RANGE_TYPE.ROW))).toEqual(r(5, 8, 2, 4, RANGE_TYPE.COLUMN));
+ });
+ });
+
+ describe('column movement and reordered rows', () => {
+ it('moves a watched column range when columns are moved across it', () => {
+ const targetRange = r(0, 5, 6, 7);
+ const operators = handleMoveCols({
+ id: EffectRefRangId.MoveColsCommandId,
+ params: {
+ fromRange: r(0, 20, 2, 3),
+ toRange: r(0, 20, 8, 9),
+ },
+ }, targetRange);
+
+ expect(runRefRangeMutations(operators, targetRange)).toEqual(r(0, 5, 4, 5));
+ });
+
+ it('uses the matrix path to split a watched range after column moves', () => {
+ const result = handleMoveColsCommon({
+ id: EffectRefRangId.MoveColsCommandId,
+ params: {
+ fromRange: r(0, 3, 1, 2),
+ toRange: r(0, 3, 5, 6),
+ },
+ }, r(0, 1, 0, 5));
+
+ expect(formatRanges(result)).toEqual(formatRanges([
+ r(0, 1, 0, 5),
+ ]));
+ });
+
+ it('keeps a row watch attached to the row that was reordered into it', () => {
+ const targetRange = r(2, 2, 0, 3);
+ const operators = handleReorderRange({
+ id: EffectRefRangId.ReorderRangeCommandId,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ range: r(0, 3, 0, 3),
+ order: { 0: 2, 2: 0 },
+ },
+ }, targetRange);
+
+ expect(runRefRangeMutations(operators, targetRange)).toEqual(r(0, 0, 0, 3));
+ });
+
+ it('rewrites reordered range cells with the common matrix path', () => {
+ const result = handleReorderRangeCommon({
+ id: EffectRefRangId.ReorderRangeCommandId,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ range: r(0, 2, 0, 2),
+ order: { 0: 2, 2: 0 },
+ },
+ }, r(0, 0, 0, 2));
+
+ expect(formatRanges(result)).toEqual([[2, 2, 0, 2]]);
+ });
+ });
+
+ describe('insert/delete common range transformations', () => {
+ it('moves only the inserted-over rows or columns and keeps the rest of the watched range', () => {
+ expect(formatRanges(handleInsertRangeMoveDownCommon({
+ id: EffectRefRangId.InsertRangeMoveDownCommandId,
+ params: { range: r(3, 4, 1, 2) },
+ }, r(2, 5, 0, 3)))).toEqual(formatRanges([
+ r(2, 2, 0, 3),
+ r(3, 5, 0, 0),
+ r(3, 5, 3, 3),
+ r(5, 7, 1, 2),
+ ]));
+
+ expect(formatRanges(handleInsertRangeMoveRightCommon({
+ id: EffectRefRangId.InsertRangeMoveRightCommandId,
+ params: { range: r(1, 2, 2, 3) },
+ }, r(0, 3, 1, 4)))).toEqual(formatRanges([
+ r(0, 0, 1, 4),
+ r(1, 2, 1, 1),
+ r(1, 2, 4, 6),
+ r(3, 3, 1, 4),
+ ]));
+ });
+
+ it('removes deleted cells and moves the trailing cells into the gap', () => {
+ expect(formatRanges(handleDeleteRangeMoveLeftCommon({
+ id: EffectRefRangId.DeleteRangeMoveLeftCommandId,
+ params: { range: r(1, 2, 2, 3) },
+ }, r(0, 3, 1, 5)))).toEqual(formatRanges([
+ r(0, 3, 1, 3),
+ r(0, 0, 4, 5),
+ r(3, 3, 4, 5),
+ ]));
+
+ expect(formatRanges(handleDeleteRangeMoveUpCommon({
+ id: EffectRefRangId.DeleteRangeMoveUpCommandId,
+ params: { range: r(2, 3, 1, 2) },
+ }, r(1, 5, 0, 3)))).toEqual(formatRanges([
+ r(1, 3, 0, 3),
+ r(4, 5, 0, 0),
+ r(4, 5, 3, 3),
+ ]));
+ });
+
+ it('handles row/column insertion direction at the right and bottom boundaries', () => {
+ expect(handleInsertRowCommon({
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(9, 10, 0, 10), direction: Direction.DOWN },
+ }, r(5, 7, 2, 4))).toEqual([r(5, 7, 2, 4)]);
+
+ expect(handleInsertRowCommon({
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(8, 9, 0, 10), direction: Direction.DOWN },
+ }, r(5, 8, 2, 4))).toEqual([r(5, 10, 2, 4)]);
+
+ expect(handleInsertColCommon({
+ id: EffectRefRangId.InsertColCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 9, 10), direction: Direction.RIGHT },
+ }, r(2, 4, 5, 7))).toEqual([r(2, 4, 5, 7)]);
+
+ expect(handleInsertColCommon({
+ id: EffectRefRangId.InsertColCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 8, 9), direction: Direction.RIGHT },
+ }, r(2, 4, 5, 8))).toEqual([r(2, 4, 5, 10)]);
+ });
+
+ it('skips filtered rows when removing a row range', () => {
+ const targetRange = r(3, 8, 0, 3);
+ const operators = handleIRemoveRow({
+ id: EffectRefRangId.RemoveRowCommandId,
+ params: { range: r(3, 8, 0, 3) },
+ }, targetRange, [4, 6]);
+
+ expect(runRefRangeMutations(operators, targetRange)).toEqual(r(3, 4, 0, 3));
+ });
+ });
+
+ describe('default command dispatchers', () => {
+ it('adjusts ranges through the command dispatcher for each command family', () => {
+ const cases: Array<[ICommandInfo, IRange, IRange | null]> = [
+ [{
+ id: EffectRefRangId.DeleteRangeMoveLeftCommandId,
+ params: { range: r(2, 4, 3, 4) },
+ }, r(2, 4, 6, 7), r(2, 4, 4, 5)],
+ [{
+ id: EffectRefRangId.DeleteRangeMoveUpCommandId,
+ params: { range: r(3, 4, 2, 4) },
+ }, r(6, 7, 2, 4), r(4, 5, 2, 4)],
+ [{
+ id: EffectRefRangId.InsertColCommandId,
+ params: { range: r(0, 10, 3, 4) },
+ }, r(2, 4, 6, 7), r(2, 4, 8, 9)],
+ [{
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { range: r(3, 4, 0, 10) },
+ }, r(6, 7, 2, 4), r(8, 9, 2, 4)],
+ [{
+ id: EffectRefRangId.InsertRangeMoveDownCommandId,
+ params: { range: r(3, 4, 2, 4) },
+ }, r(6, 7, 2, 4), r(8, 9, 2, 4)],
+ [{
+ id: EffectRefRangId.InsertRangeMoveRightCommandId,
+ params: { range: r(2, 4, 3, 4) },
+ }, r(2, 4, 6, 7), r(2, 4, 8, 9)],
+ [{
+ id: EffectRefRangId.MoveColsCommandId,
+ params: { fromRange: r(0, 10, 2, 3), toRange: r(0, 10, 7, 8) },
+ }, r(2, 4, 5, 6), r(2, 4, 3, 4)],
+ [{
+ id: EffectRefRangId.MoveRowsCommandId,
+ params: { fromRange: r(2, 3, 0, 10), toRange: r(7, 8, 0, 10) },
+ }, r(5, 6, 2, 4), r(3, 4, 2, 4)],
+ [{
+ id: EffectRefRangId.MoveRangeCommandId,
+ params: { fromRange: r(2, 4, 2, 4), toRange: r(8, 10, 7, 9) },
+ }, r(3, 3, 3, 3), r(9, 9, 8, 8)],
+ [{
+ id: EffectRefRangId.RemoveColCommandId,
+ params: { range: r(0, 10, 3, 4) },
+ }, r(2, 4, 6, 7), r(2, 4, 4, 5)],
+ [{
+ id: EffectRefRangId.RemoveRowCommandId,
+ params: { range: r(3, 4, 0, 10) },
+ }, r(6, 7, 2, 4), r(4, 5, 2, 4)],
+ [{
+ id: EffectRefRangId.ReorderRangeCommandId,
+ params: { range: r(0, 2, 0, 4), order: { 0: 2, 2: 0 } },
+ }, r(0, 0, 1, 2), r(2, 2, 1, 2)],
+ ];
+
+ cases.forEach(([command, targetRange, expected]) => {
+ expect(handleDefaultRangeChangeWithEffectRefCommands(targetRange, command)).toEqual(expected);
+ });
+ });
+
+ it('uses common range transformations for split range operations', () => {
+ expect(formatRanges(handleCommonDefaultRangeChangeWithEffectRefCommands(r(0, 3, 1, 5), {
+ id: EffectRefRangId.DeleteRangeMoveLeftCommandId,
+ params: { range: r(1, 2, 2, 3) },
+ }))).toEqual(formatRanges([
+ r(0, 3, 1, 3),
+ r(0, 0, 4, 5),
+ r(3, 3, 4, 5),
+ ]));
+
+ expect(handleCommonDefaultRangeChangeWithEffectRefCommands(r(4, 5, 1, 2), {
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { range: r(3, 3, 0, 10), direction: Direction.DOWN },
+ })).toEqual([r(5, 6, 1, 2)]);
+ });
+
+ it('skips commands outside the watched range but still applies commands that always affect selection-local cells', () => {
+ const targetRange = r(10, 12, 10, 12);
+ expect(handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests(targetRange, {
+ id: EffectRefRangId.InsertColCommandId,
+ params: { range: r(0, 20, 2, 2) },
+ }, selectionDeps())).toEqual(targetRange);
+
+ expect(handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests(targetRange, {
+ id: EffectRefRangId.DeleteRangeMoveLeftCommandId,
+ params: { range: r(10, 12, 8, 9) },
+ }, selectionDeps())).toEqual(r(10, 12, 8, 10));
+
+ expect(handleCommonRangeChangeWithEffectRefCommandsSkipNoInterests(targetRange, {
+ id: EffectRefRangId.InsertRangeMoveRightCommandId,
+ params: { range: r(10, 12, 8, 9) },
+ }, selectionDeps())).toEqual([r(10, 12, 12, 14)]);
+ });
+ });
+
+ describe('mutation dispatchers and affected ranges', () => {
+ it('adjusts ranges for mutation families that mirror sheet edits', () => {
+ expect(adjustRangeOnMutation(r(2, 4, 5, 6), {
+ id: MoveColsMutation.id,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ sourceRange: r(0, 10, 1, 2),
+ targetRange: r(0, 10, 8, 9),
+ } satisfies IMoveColumnsMutationParams,
+ })).toEqual(r(2, 4, 3, 4));
+
+ expect(adjustRangeOnMutation(r(2, 4, 5, 6), {
+ id: RemoveColMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 3, 4) } satisfies IRemoveColMutationParams,
+ })).toEqual(r(2, 4, 3, 4));
+
+ expect(adjustRangeOnMutation(r(5, 7, 2, 4), {
+ id: RemoveRowMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(3, 4, 0, 10) } satisfies IRemoveRowsMutationParams,
+ })).toEqual(r(3, 5, 2, 4));
+
+ expect(adjustRangeOnMutation(r(5, 7, 2, 4), {
+ id: InsertRowMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(3, 4, 0, 10) } satisfies IInsertRowMutationParams,
+ })).toEqual(r(7, 9, 2, 4));
+
+ expect(adjustRangeOnMutation(r(2, 4, 5, 6), {
+ id: InsertColMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 3, 4) } satisfies IInsertColMutationParams,
+ })).toEqual(r(2, 4, 7, 8));
+
+ expect(adjustRangeOnMutation(r(2, 2, 2, 2), {
+ id: MoveRangeMutation.id,
+ params: {
+ unitId: 'unit',
+ fromRange: r(1, 3, 1, 3),
+ toRange: r(6, 8, 5, 7),
+ from: { subUnitId: 'sheet', value: {} },
+ to: { subUnitId: 'sheet', value: {} },
+ } satisfies IMoveRangeMutationParams,
+ })).toEqual(r(7, 7, 6, 6));
+ });
+
+ it('reports affected command ranges including selection fallbacks and reordered rows', () => {
+ const selectedRange = r(6, 7, 3, 4);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.MoveColsCommandId,
+ params: { fromRange: r(0, 10, 2, 3), toRange: r(0, 10, 8, 9) },
+ }, selectionDeps())).toEqual([
+ r(0, 10, 2, 3),
+ r(0, 10, 7.5, 8.5),
+ ]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.MoveRowsCommandId,
+ params: { fromRange: r(2, 3, 0, 10), toRange: r(8, 9, 0, 10) },
+ }, selectionDeps())).toEqual([
+ r(2, 3, 0, 10),
+ r(7.5, 7.5, 0, 10),
+ ]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.MoveRangeCommandId,
+ params: { fromRange: r(1, 2, 1, 2), toRange: r(5, 6, 5, 6) },
+ }, selectionDeps())).toEqual([r(1, 2, 1, 2), r(5, 6, 5, 6)]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(5, 6, 0, 10), direction: Direction.DOWN },
+ }, selectionDeps())).toEqual([r(4.5, 5.5, 0, 10)]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.InsertColCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 5, 6), direction: Direction.RIGHT },
+ }, selectionDeps())).toEqual([r(0, 10, 4.5, 5.5)]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.RemoveRowCommandId,
+ params: { range: r(5, 6, 0, 10) },
+ }, selectionDeps())).toEqual([r(5, 6, 0, 10)]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.RemoveColCommandId,
+ params: { range: r(0, 10, 5, 6) },
+ }, selectionDeps())).toEqual([r(0, 10, 5, 6)]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.DeleteRangeMoveUpCommandId,
+ params: undefined,
+ }, selectionDeps(selectedRange))).toEqual([selectedRange]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.DeleteRangeMoveLeftCommandId,
+ params: undefined,
+ }, selectionDeps(selectedRange))).toEqual([selectedRange]);
+
+ expect(getEffectedRangesOnCommand({
+ id: EffectRefRangId.ReorderRangeCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 3, 2, 4), order: { 1: 3, 3: 1 } },
+ }, selectionDeps())).toEqual([
+ r(1, 1, 2, 4),
+ r(3, 3, 2, 4),
+ ]);
+ });
+
+ it('reports affected mutation ranges for move, insert, remove, and cell move mutations', () => {
+ expect(getEffectedRangesOnMutation({
+ id: MoveColsMutation.id,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ sourceRange: r(0, 10, 2, 3),
+ targetRange: r(0, 10, 8, 9),
+ } satisfies IMoveColumnsMutationParams,
+ })).toEqual([
+ r(0, 10, 2, 3),
+ r(0, 10, 7.5, 7.5),
+ ]);
+
+ expect(getEffectedRangesOnMutation({
+ id: InsertColMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 5, 6) } satisfies IInsertColMutationParams,
+ })).toEqual([r(0, 10, 4.5, 4.5)]);
+
+ expect(getEffectedRangesOnMutation({
+ id: InsertRowMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(5, 6, 0, 10) } satisfies IInsertRowMutationParams,
+ })).toEqual([r(4.5, 4.5, 0, 10)]);
+
+ expect(getEffectedRangesOnMutation({
+ id: RemoveColMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 5, 6) } satisfies IRemoveColMutationParams,
+ })).toEqual([r(0, 10, 5, 6)]);
+
+ expect(getEffectedRangesOnMutation({
+ id: RemoveRowMutation.id,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(5, 6, 0, 10) } satisfies IRemoveRowsMutationParams,
+ })).toEqual([r(5, 6, 0, 10)]);
+
+ expect(getEffectedRangesOnMutation({
+ id: MoveRangeMutation.id,
+ params: {
+ unitId: 'unit',
+ fromRange: r(0, 0, 0, 0),
+ toRange: r(0, 0, 0, 0),
+ from: { subUnitId: 'sheet', value: { 1: { 2: { v: 'from' } } } },
+ to: { subUnitId: 'sheet', value: { 5: { 6: { v: 'to' } } } },
+ } satisfies IMoveRangeMutationParams,
+ })).toEqual([r(0, 1, 0, 2), r(0, 5, 0, 6)]);
+ });
+ });
+
+ describe('separate affected ranges with real target resolution shape', () => {
+ const createAccessor = () => {
+ const worksheet = {
+ getRowCount: () => 20,
+ getColumnCount: () => 12,
+ getSheetId: () => 'sheet',
+ };
+ const workbook = {
+ getUnitId: () => 'unit',
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: () => worksheet,
+ };
+ const univerInstanceService = {
+ getUnit: () => workbook,
+ getCurrentUnitOfType: () => workbook,
+ };
+
+ return {
+ get: (identifier: unknown) => identifier === IUniverInstanceService ? univerInstanceService : undefined,
+ } as unknown as IAccessor;
+ };
+
+ it('resolves command affected ranges against the workbook and worksheet target', () => {
+ const accessor = createAccessor();
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.MoveColsCommandId,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ fromRange: r(0, 10, 2, 3),
+ toRange: r(0, 10, 8, 9),
+ },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(0, 10, 2, 3), r(0, 10, 4, 8)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.MoveRowsCommandId,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ fromRange: r(8, 9, 0, 10),
+ toRange: r(2, 3, 0, 10),
+ },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(8, 9, 0, 10), r(2, 7, 0, 10)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.MoveRangeCommandId,
+ params: {
+ fromRange: r(1, 2, 1, 2),
+ toRange: r(5, 6, 5, 6),
+ },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(1, 2, 1, 2), r(5, 6, 5, 6)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.InsertRowCommandId,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ range: r(5, 6, 0, 10),
+ direction: Direction.DOWN,
+ },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(4, 5, 0, 10), r(5, 19, 0, 10)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.InsertColCommandId,
+ params: {
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ range: r(0, 10, 5, 6),
+ direction: Direction.RIGHT,
+ },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(0, 10, 4, 5), r(0, 10, 5, 11)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.RemoveRowCommandId,
+ params: { range: r(5, 6, 0, 10) },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(5, 6, 0, 10), r(7, 19, 0, 10)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.RemoveColCommandId,
+ params: { range: r(0, 10, 5, 6) },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(0, 10, 5, 6), r(0, 10, 7, 11)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.InsertRangeMoveDownCommandId,
+ params: { range: r(5, 6, 2, 4) },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(5, 6, 2, 4), r(7, 19, 2, 4)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.InsertRangeMoveRightCommandId,
+ params: { range: r(5, 6, 2, 4) },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(5, 6, 2, 4), r(5, 6, 5, 11)],
+ });
+
+ expect(getSeparateEffectedRangesOnCommand(accessor, {
+ id: EffectRefRangId.ReorderRangeCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 3, 2, 4), order: { 1: 3, 3: 1 } },
+ })).toEqual({
+ unitId: 'unit',
+ subUnitId: 'sheet',
+ ranges: [r(1, 1, 2, 4), r(3, 3, 2, 4)],
+ });
+ });
+ });
+
+ describe('common matrix operations keep shape across move ranges', () => {
+ it('keeps an unaffected watched range as-is when moved blocks do not touch it', () => {
+ const targetRange = r(10, 12, 10, 12);
+ expect(handleMoveRowsCommon({
+ id: EffectRefRangId.MoveRowsCommandId,
+ params: {
+ fromRange: r(1, 2, 0, 20),
+ toRange: r(5, 6, 0, 20),
+ },
+ }, targetRange)).toEqual([targetRange]);
+
+ expect(handleMoveRangeCommon({
+ id: EffectRefRangId.MoveRangeCommandId,
+ params: {
+ fromRange: r(1, 2, 1, 2),
+ toRange: r(5, 6, 5, 6),
+ },
+ }, targetRange)).toEqual([targetRange]);
+ });
+ });
+});
diff --git a/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts b/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts
index 9a7b80f8fe..7c85c17185 100644
--- a/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts
+++ b/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts
@@ -20,13 +20,19 @@ import type { IInsertColCommandParams, IInsertRowCommandParams } from '../../../
import type { IRemoveRowColCommandInterceptParams } from '../../../commands/commands/remove-row-col.command';
import type { IMoveRowsMutationParams } from '../../../commands/mutations/move-rows-cols.mutation';
import type { IRemoveRowColCommand } from '../type';
-import { Direction } from '@univerjs/core';
+import { Direction, RANGE_TYPE } from '@univerjs/core';
import { beforeEach, describe, expect, it } from 'vitest';
-import { MoveRowsMutation } from '../../../commands/mutations/move-rows-cols.mutation';
+import { InsertColMutation, InsertRowMutation } from '../../../commands/mutations/insert-row-col.mutation';
+import { MoveColsMutation, MoveRowsMutation } from '../../../commands/mutations/move-rows-cols.mutation';
+import { RemoveColMutation, RemoveRowMutation } from '../../../commands/mutations/remove-row-col.mutation';
import { RemoveSheetMutation } from '../../../commands/mutations/remove-sheet.mutation';
import { EffectRefRangId } from '../type';
import {
adjustRangeOnMutation,
+ getEffectedRangesOnCommand,
+ getEffectedRangesOnMutation,
+ handleDefaultRangeChangeWithEffectRefCommands,
+ handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests,
handleDeleteRangeMoveLeft,
handleDeleteRangeMoveLeftCommon,
handleDeleteRangeMoveUp,
@@ -41,11 +47,18 @@ import {
handleInsertRowCommon,
handleIRemoveCol,
handleIRemoveRow,
+ handleMoveCols,
+ handleMoveColsCommon,
handleMoveRange,
handleMoveRangeCommon,
handleMoveRows,
handleMoveRowsCommon,
+ handleRangeTypeInput,
+ handleRangeTypeOutput,
handleRemoveRowCommon,
+ handleReorderRange,
+ handleReorderRangeCommon,
+ rotateRange,
runRefRangeMutations,
} from '../util';
@@ -54,6 +67,91 @@ const countRange = ([a, b, c, d]: readonly [number, number, number, number]) =>
const formatRanges = (ranges: IRange[]) => ranges.map((range) => [range.startRow, range.endRow, range.startColumn, range.endColumn] as const).sort((prev, aft) => countRange(prev) - countRange(aft));
describe('test ref-range move', () => {
+ describe('range type and effect-range helpers', () => {
+ it('normalizes row, column, all, and NaN range coordinates', () => {
+ expect(handleRangeTypeInput({ startRow: Number.NaN, endRow: Number.NaN, startColumn: 2, endColumn: 4 })).toMatchObject({
+ startRow: 0,
+ startColumn: 2,
+ endColumn: 4,
+ });
+ expect(handleRangeTypeInput({ startRow: 3, endRow: 5, startColumn: Number.NaN, endColumn: Number.NaN })).toMatchObject({
+ startRow: 3,
+ endRow: 5,
+ startColumn: 0,
+ });
+ expect(handleRangeTypeInput({ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.ALL })).toMatchObject({
+ startRow: 0,
+ startColumn: 0,
+ });
+ expect(handleRangeTypeOutput({ startRow: -3, endRow: 20, startColumn: -4, endColumn: 30 }, 10, 12)).toEqual({
+ startRow: 0,
+ endRow: 10,
+ startColumn: 0,
+ endColumn: 12,
+ });
+ expect(handleRangeTypeOutput({ startRow: 2, endRow: 4, startColumn: 1, endColumn: 3, rangeType: RANGE_TYPE.ROW }, 10, 12)).toMatchObject({
+ startColumn: 0,
+ endColumn: 12,
+ });
+ expect(rotateRange({ startRow: 1, endRow: 3, startColumn: 5, endColumn: 7, rangeType: RANGE_TYPE.ROW })).toEqual({
+ startRow: 5,
+ endRow: 7,
+ startColumn: 1,
+ endColumn: 3,
+ rangeType: RANGE_TYPE.COLUMN,
+ });
+ });
+
+ it('handles column movement and row reorder common transformations', () => {
+ const fromRange = { startRow: 0, endRow: 99, startColumn: 2, endColumn: 3 };
+ const toRange = { startRow: 0, endRow: 99, startColumn: 7, endColumn: 8 };
+ const targetRange = { startRow: 1, endRow: 2, startColumn: 4, endColumn: 5 };
+
+ const operators = handleMoveCols({ id: EffectRefRangId.MoveColsCommandId, params: { fromRange, toRange } }, targetRange);
+ expect(runRefRangeMutations(operators, targetRange)).toEqual({ startRow: 1, endRow: 2, startColumn: 2, endColumn: 3 });
+ expect(formatRanges(handleMoveColsCommon({ id: EffectRefRangId.MoveColsCommandId, params: { fromRange, toRange } }, targetRange))).toEqual([[1, 2, 2, 3]]);
+ expect(handleMoveCols({ id: EffectRefRangId.MoveColsCommandId, params: undefined }, targetRange)).toEqual([]);
+ expect(handleMoveColsCommon({ id: EffectRefRangId.MoveColsCommandId, params: undefined }, targetRange)).toEqual([targetRange]);
+
+ const reorderRange = { startRow: 1, endRow: 3, startColumn: 0, endColumn: 1 };
+ const order = { 1: 3, 2: 1, 3: 2 };
+ const reorderOperators = handleReorderRange({ id: EffectRefRangId.ReorderRangeCommandId, params: { unitId: 'unit', subUnitId: 'sheet', range: reorderRange, order } }, { startRow: 2, endRow: 2, startColumn: 0, endColumn: 1 });
+ expect(runRefRangeMutations(reorderOperators, { startRow: 2, endRow: 2, startColumn: 0, endColumn: 1 })).toEqual({ startRow: 3, endRow: 3, startColumn: 0, endColumn: 1 });
+ expect(formatRanges(handleReorderRangeCommon({ id: EffectRefRangId.ReorderRangeCommandId, params: { unitId: 'unit', subUnitId: 'sheet', range: reorderRange, order } }, reorderRange))).toEqual([[1, 3, 0, 1]]);
+ expect(handleReorderRangeCommon({ id: EffectRefRangId.ReorderRangeCommandId, params: undefined }, reorderRange)).toEqual([reorderRange]);
+ });
+
+ it('finds command and mutation effect ranges and skips unrelated commands', () => {
+ const selectionManagerService = {
+ getCurrentSelections: () => [{ range: { startRow: 5, endRow: 6, startColumn: 5, endColumn: 6 } }],
+ } as never;
+ const targetRange = { startRow: 10, endRow: 11, startColumn: 10, endColumn: 11 };
+
+ expect(getEffectedRangesOnCommand({ id: EffectRefRangId.InsertRangeMoveDownCommandId }, { selectionManagerService })).toEqual([
+ { startRow: 5, endRow: 6, startColumn: 5, endColumn: 6 },
+ ]);
+ expect(getEffectedRangesOnCommand({ id: EffectRefRangId.InsertRangeMoveRightCommandId, params: { range: targetRange } }, { selectionManagerService })).toEqual([targetRange]);
+ expect(getEffectedRangesOnCommand({ id: EffectRefRangId.ReorderRangeCommandId, params: { unitId: 'unit', subUnitId: 'sheet', range: { startRow: 1, endRow: 3, startColumn: 0, endColumn: 1 }, order: { 2: 1 } } }, { selectionManagerService })).toEqual([
+ { startRow: 2, endRow: 2, startColumn: 0, endColumn: 1 },
+ ]);
+ expect(handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests(targetRange, { id: EffectRefRangId.InsertRowCommandId, params: { range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 9 }, direction: Direction.DOWN, unitId: 'u', subUnitId: 's' } } as never, { selectionManagerService })).toEqual(targetRange);
+ expect(handleDefaultRangeChangeWithEffectRefCommands(targetRange, { id: EffectRefRangId.InsertRowCommandId, params: { range: { startRow: 9, endRow: 9, startColumn: 0, endColumn: 9 }, direction: Direction.DOWN, unitId: 'u', subUnitId: 's' } } as never)).toEqual({
+ startRow: 10,
+ endRow: 11,
+ startColumn: 10,
+ endColumn: 11,
+ });
+
+ expect(getEffectedRangesOnMutation({ id: MoveColsMutation.id, params: { sourceRange: { startRow: 0, endRow: 9, startColumn: 1, endColumn: 1 }, targetRange: { startRow: 0, endRow: 9, startColumn: 4, endColumn: 4 } } as never })).toHaveLength(2);
+ expect(getEffectedRangesOnMutation({ id: MoveRowsMutation.id, params: { sourceRange: { startRow: 1, endRow: 1, startColumn: 0, endColumn: 9 }, targetRange: { startRow: 4, endRow: 4, startColumn: 0, endColumn: 9 } } as never })).toHaveLength(2);
+ expect(getEffectedRangesOnMutation({ id: InsertColMutation.id, params: { range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 3 } } as never })).toEqual([{ startRow: 0, endRow: 9, startColumn: 1.5, endColumn: 1.5 }]);
+ expect(getEffectedRangesOnMutation({ id: InsertRowMutation.id, params: { range: { startRow: 2, endRow: 3, startColumn: 0, endColumn: 9 } } as never })).toEqual([{ startRow: 1.5, endRow: 1.5, startColumn: 0, endColumn: 9 }]);
+ expect(getEffectedRangesOnMutation({ id: RemoveColMutation.id, params: { range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 3 } } as never })).toEqual([{ startRow: 0, endRow: 9, startColumn: 2, endColumn: 3 }]);
+ expect(getEffectedRangesOnMutation({ id: RemoveRowMutation.id, params: { range: { startRow: 2, endRow: 3, startColumn: 0, endColumn: 9 } } as never })).toEqual([{ startRow: 2, endRow: 3, startColumn: 0, endColumn: 9 }]);
+ expect(getEffectedRangesOnMutation({ id: 'unknown', params: {} as never })).toBeUndefined();
+ });
+ });
+
describe('handleMoveRows', () => {
// see docs/tldr/handMoveRowsCols.tldr
const startCol = 0;
diff --git a/packages/sheets/src/services/selections/__tests__/selection.service.spec.ts b/packages/sheets/src/services/selections/__tests__/selection.service.spec.ts
index f0c1417c72..331abb6013 100644
--- a/packages/sheets/src/services/selections/__tests__/selection.service.spec.ts
+++ b/packages/sheets/src/services/selections/__tests__/selection.service.spec.ts
@@ -17,15 +17,20 @@
import {
ContextService,
DesktopLogService,
+ Direction,
IContextService,
ILogService,
Injector,
IUniverInstanceService,
+ ObjectMatrix,
UniverInstanceService,
Workbook,
} from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import { getNextPrimaryCell } from '../move-active-cell-util';
+import { WorkbookSelectionModel } from '../selection-data-model';
import { SheetsSelectionsService } from '../selection.service';
+import { SelectionMoveType } from '../type';
function createService() {
const injector = new Injector();
@@ -75,4 +80,152 @@ describe('SheetsSelectionsService', () => {
expect(service.isOverlapping()).toBe(true);
});
+
+ it('adds explicit worksheet selections and clears all workbook selections', () => {
+ const service = createService();
+ const selection = {
+ range: { startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 },
+ primary: { actualRow: 3, actualColumn: 4, startRow: 3, endRow: 3, startColumn: 4, endColumn: 4 },
+ };
+
+ service.addSelections('unit-1', 'sheet-1', [selection] as never);
+ expect(service.getCurrentLastSelection()).toEqual(selection);
+ expect(service.getWorkbookSelections('unit-1').getSelectionsOfWorksheet('sheet-1')).toEqual([selection]);
+
+ service.clear();
+ expect(service.getCurrentSelections()).toEqual([]);
+ });
+
+ it('summarizes common cell style values and detects mixed values', () => {
+ 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'],
+ });
+ const worksheet = workbook.getSheetBySheetId('sheet-1')!;
+ const styles = new Map<string, unknown>([
+ ['0_0', { cl: { rgb: '#f00' } }],
+ ['0_1', { cl: { rgb: '#f00' } }],
+ ['1_0', { cl: { rgb: '#0f0' } }],
+ ]);
+ worksheet.getComposedCellStyle = ((row: number, col: number) => styles.get(`${row}_${col}`) || {}) as never;
+ univerInstanceService.__addUnit(workbook);
+ univerInstanceService.focusUnit('unit-1');
+ const service = injector.get(SheetsSelectionsService);
+
+ service.setSelections([{ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }, primary: null }] as never);
+ expect(service.getCellStylesProperty('cl')).toEqual({ isAllValuesSame: true, value: { rgb: '#f00' } });
+
+ service.setSelections([{ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }, primary: null }] as never);
+ expect(service.getCellStylesProperty('cl')).toEqual({ isAllValuesSame: false, value: null });
+ });
+});
+
+describe('WorkbookSelectionModel', () => {
+ it('emits selection events by move type and remembers the last primary cell per worksheet', () => {
+ const workbook = {
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ };
+ const model = new WorkbookSelectionModel(workbook as never);
+ const moveStarts: unknown[] = [];
+ const moving: unknown[] = [];
+ const moveEnds: unknown[] = [];
+ const sets: unknown[] = [];
+ model.selectionMoveStart$.subscribe((value) => moveStarts.push(value));
+ model.selectionMoving$.subscribe((value) => moving.push(value));
+ model.selectionMoveEnd$.subscribe((value) => moveEnds.push(value));
+ model.selectionSet$.subscribe((value) => sets.push(value));
+ const selection = {
+ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ primary: { actualRow: 1, actualColumn: 1, startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ };
+
+ model.setSelections('sheet-1', [selection] as never, SelectionMoveType.MOVE_START);
+ model.setSelections('sheet-1', [selection] as never, SelectionMoveType.MOVING);
+ model.setSelections('sheet-1', [selection] as never, SelectionMoveType.MOVE_END);
+ model.addSelections('sheet-1', [selection] as never);
+
+ expect(moveStarts).toEqual([[selection]]);
+ expect(moving).toEqual([[selection]]);
+ expect(moveEnds.at(-1)).toEqual([selection]);
+ expect(sets.at(-1)).toEqual([selection, selection]);
+ expect(model.getCurrentLastSelection()).toEqual(selection);
+ expect(model.getLastSelectionPrimaryCellOfWorksheet('sheet-1')).toEqual(selection.primary);
+
+ model.deleteSheetSelection('sheet-1');
+ expect(model.getSelectionsOfWorksheet('sheet-1')).toEqual([]);
+ model.dispose();
+ });
+});
+
+describe('getNextPrimaryCell', () => {
+ function createWorksheet() {
+ return {
+ getMaxRows: () => 10,
+ getMaxColumns: () => 10,
+ getRowVisible: (row: number) => row !== 2,
+ getColVisible: (col: number) => col !== 2,
+ getMergedCell: (row: number, col: number) => row === 1 && col === 1 ? { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } : null,
+ getMatrixWithMergedCells: (startRow: number, startColumn: number) => {
+ const matrix = new ObjectMatrix();
+ matrix.setValue(startRow, startColumn, {});
+ return matrix;
+ },
+ };
+ }
+
+ it('moves the primary cell through visible rows and columns', () => {
+ const worksheet = createWorksheet();
+ const selection = {
+ range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 3 },
+ primary: { actualRow: 0, actualColumn: 0, startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ };
+
+ expect(getNextPrimaryCell([selection] as never, Direction.RIGHT, worksheet as never)).toEqual({
+ startRow: 0,
+ endRow: 0,
+ startColumn: 1,
+ endColumn: 1,
+ });
+ expect(getNextPrimaryCell([{ ...selection, primary: { ...selection.primary, startColumn: 3, endColumn: 3 } }] as never, Direction.DOWN, worksheet as never)).toEqual({
+ startRow: 1,
+ endRow: 1,
+ startColumn: 3,
+ endColumn: 3,
+ });
+ expect(getNextPrimaryCell([] as never, Direction.RIGHT, worksheet as never)).toBeNull();
+ });
+
+ it('jumps between selections when the active selection is a single cell', () => {
+ const worksheet = createWorksheet();
+ const selections = [
+ {
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ primary: { actualRow: 0, actualColumn: 0, startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ },
+ {
+ range: { startRow: 4, endRow: 4, startColumn: 4, endColumn: 4 },
+ primary: null,
+ },
+ ];
+
+ expect(getNextPrimaryCell(selections as never, Direction.RIGHT, worksheet as never)).toEqual({
+ startRow: 4,
+ endRow: 4,
+ startColumn: 4,
+ endColumn: 4,
+ });
+ expect(getNextPrimaryCell(selections as never, Direction.LEFT, worksheet as never)).toEqual({
+ startRow: 4,
+ endRow: 4,
+ startColumn: 4,
+ endColumn: 4,
+ });
+ });
});
diff --git a/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts b/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts
index a6ba2e09ae..1a2a0f7bfc 100644
--- a/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts
+++ b/packages/sheets/src/services/sheet-interceptor/__tests__/sheet-interceptor.service.spec.ts
@@ -19,7 +19,7 @@ import type { ISheetLocation } from '../utils/interceptor';
import { createInterceptorKey, InterceptorEffectEnum, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { INTERCEPTOR_POINT } from '../interceptor-const';
-import { SheetInterceptorService } from '../sheet-interceptor.service';
+import { AFTER_CELL_EDIT, SheetInterceptorService, VALIDATE_CELL } from '../sheet-interceptor.service';
import { createSheetTestBed } from './create-core-test-bed';
describe('Test SheetInterceptorService', () => {
@@ -187,6 +187,104 @@ describe('Test SheetInterceptorService', () => {
});
describe('Test intercept in general case', () => {
+ it('collects command, after-command, range, auto-height, and before-command interceptor results in priority order', async () => {
+ const interceptorService = get(SheetInterceptorService);
+ const high = {
+ priority: 100,
+ getMutations: () => ({
+ preRedos: [{ id: 'high-pre-redo', params: {} }],
+ redos: [{ id: 'high-redo', params: {} }],
+ preUndos: [{ id: 'high-pre-undo', params: {} }],
+ undos: [{ id: 'high-undo', params: {} }],
+ }),
+ };
+ const low = {
+ priority: 0,
+ getMutations: () => ({
+ redos: [{ id: 'low-redo', params: {} }],
+ undos: [{ id: 'low-undo', params: {} }],
+ }),
+ };
+
+ const commandDisposable = interceptorService.interceptCommand(low);
+ interceptorService.interceptCommand(high);
+ expect(interceptorService.onCommandExecute({ id: 'cmd', params: {} })).toEqual({
+ preRedos: [{ id: 'high-pre-redo', params: {} }],
+ redos: [{ id: 'high-redo', params: {} }, { id: 'low-redo', params: {} }],
+ preUndos: [{ id: 'high-pre-undo', params: {} }],
+ undos: [{ id: 'high-undo', params: {} }, { id: 'low-undo', params: {} }],
+ });
+ expect(() => interceptorService.interceptCommand(high)).toThrow('Interceptor already exists');
+ commandDisposable.dispose();
+
+ const afterDisposable = interceptorService.interceptAfterCommand(high);
+ interceptorService.interceptAfterCommand(low);
+ expect(interceptorService.afterCommandExecute({ id: 'cmd', params: {} })).toEqual({
+ redos: [{ id: 'high-redo', params: {} }, { id: 'low-redo', params: {} }],
+ undos: [{ id: 'high-undo', params: {} }, { id: 'low-undo', params: {} }],
+ });
+ expect(() => interceptorService.interceptAfterCommand(high)).toThrow('Interceptor already exists');
+ afterDisposable.dispose();
+
+ const rangeDisposable = interceptorService.interceptRanges(high);
+ interceptorService.interceptRanges(low);
+ expect(interceptorService.generateMutationsByRanges({ unitId: 'unit', subUnitId: 'sheet', ranges: [] })).toEqual({
+ preRedos: [{ id: 'high-pre-redo', params: {} }],
+ redos: [{ id: 'high-redo', params: {} }, { id: 'low-redo', params: {} }],
+ preUndos: [{ id: 'high-pre-undo', params: {} }],
+ undos: [{ id: 'high-undo', params: {} }, { id: 'low-undo', params: {} }],
+ });
+ expect(() => interceptorService.interceptRanges(high)).toThrow('Interceptor already exists');
+ rangeDisposable.dispose();
+
+ const autoHeightDisposable = interceptorService.interceptAutoHeight(high);
+ interceptorService.interceptAutoHeight(low);
+ expect(interceptorService.generateMutationsOfAutoHeight({ unitId: 'unit', subUnitId: 'sheet', ranges: [] })).toEqual({
+ preRedos: [{ id: 'high-pre-redo', params: {} }],
+ redos: [{ id: 'high-redo', params: {} }, { id: 'low-redo', params: {} }],
+ preUndos: [{ id: 'high-pre-undo', params: {} }],
+ undos: [{ id: 'high-undo', params: {} }, { id: 'low-undo', params: {} }],
+ });
+ expect(() => interceptorService.interceptAutoHeight(high)).toThrow('Interceptor already exists');
+ autoHeightDisposable.dispose();
+
+ const before = { priority: 10, performCheck: vi.fn(async () => true) };
+ interceptorService.interceptBeforeCommand(before);
+ interceptorService.interceptBeforeCommand({ priority: 0, performCheck: async () => false });
+ await expect(interceptorService.beforeCommandExecute({ id: 'cmd', params: {} })).resolves.toBe(false);
+ expect(before.performCheck).toHaveBeenCalledWith({ id: 'cmd', params: {} });
+ expect(() => interceptorService.interceptBeforeCommand(before)).toThrow('Interceptor already exists');
+ });
+
+ it('runs write-cell and validation interceptors with workbook context', async () => {
+ const interceptorService = get(SheetInterceptorService);
+ const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ interceptorService.writeCellInterceptor.intercept(AFTER_CELL_EDIT, {
+ priority: 100,
+ handler(value, location, next) {
+ expect(location.unitId).toBe(workbook.getUnitId());
+ expect(location.subUnitId).toBe(worksheet.getSheetId());
+ expect(location.origin).toEqual({ v: 'origin' });
+ return next({ ...value, v: `${value?.v} edited` });
+ },
+ });
+
+ interceptorService.writeCellInterceptor.intercept(VALIDATE_CELL, {
+ priority: 100,
+ handler(value, location, next) {
+ if (location.row === 3 && location.col === 4) {
+ return Promise.resolve(false);
+ }
+ return next(value);
+ },
+ });
+
+ expect(interceptorService.onWriteCell(workbook, worksheet, 1, 2, { v: 'origin' })).toEqual({ v: 'origin edited' });
+ await expect(interceptorService.onValidateCell(workbook, worksheet, 3, 4)).resolves.toBe(false);
+ });
+
it('should intercept BEFORE_CELL_EDIT and sum the values', () => {
get(SheetInterceptorService).intercept(numberIntercept, {
priority: 0,
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.ts
index 9cb04f3e4b..8dc7d782ec 100644
--- 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.ts
@@ -16,6 +16,7 @@
import type { IPageElement, ISlideData, ISlidePage, SlideDataModel } from '@univerjs/slides';
import { ICommandService, IUniverInstanceService, LocaleService, Univer, UniverInstanceType } from '@univerjs/core';
+import { IImageIoService, ImageSourceType, ImageUploadStatusType } from '@univerjs/drawing';
import { ObjectType } from '@univerjs/engine-render';
import { BasicShapes, PageElementType, PageType, UniverSlidesPlugin } from '@univerjs/slides';
import { DesktopSidebarService, ILocalFileService, ISidebarService } from '@univerjs/ui';
@@ -34,6 +35,7 @@ import {
} from '../insert-shape.operation';
import { SlideAddTextCommand, SlideAddTextOperation } from '../insert-text.operation';
import { SetSlidePageThumbOperation } from '../set-thumb.operation';
+import { SetTextEditArrowOperation } from '../text-edit.operation';
import { UpdateSlideElementOperation } from '../update-element.operation';
const unitId = 'slide-command-unit';
@@ -109,8 +111,14 @@ class TestCanvasView {
}
class TestLocalFileService implements ILocalFileService {
+ static files: File[] = [];
+
+ static reset() {
+ this.files = [];
+ }
+
openFile(): Promise<File[]> {
- return Promise.resolve([]);
+ return Promise.resolve(TestLocalFileService.files);
}
downloadFile(): void {
@@ -118,6 +126,29 @@ class TestLocalFileService implements ILocalFileService {
}
}
+class TestImageIoService {
+ saveImage(): Promise<unknown> {
+ return Promise.resolve({
+ imageId: 'image-1',
+ imageSourceType: ImageSourceType.BASE64,
+ source: 'data:image/png;base64,ZmFrZQ==',
+ base64Cache: 'data:image/png;base64,ZmFrZQ==',
+ status: ImageUploadStatusType.SUCCUSS,
+ });
+ }
+}
+
+class TestImage {
+ width = 64;
+ height = 32;
+ onload: (() => void) | null = null;
+ onerror: ((error: unknown) => void) | null = null;
+
+ set src(_value: string) {
+ queueMicrotask(() => this.onload?.());
+ }
+}
+
function createSlideSnapshot(): Partial<ISlideData> {
return {
id: unitId,
@@ -206,16 +237,21 @@ describe('slide element operations', () => {
let univer: Univer;
let commandService: ICommandService;
let slide: SlideDataModel;
+ let originalImage: typeof Image;
beforeEach(() => {
univer = new Univer();
univer.registerPlugin(UniverSlidesPlugin);
TestCanvasView.reset();
+ TestLocalFileService.reset();
+ originalImage = globalThis.Image;
+ (globalThis as unknown as { Image: typeof Image }).Image = TestImage as unknown as typeof Image;
const injector = univer.__getInjector();
injector.add([CanvasView, { useClass: TestCanvasView as never }]);
injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
injector.add([ILocalFileService, { useClass: TestLocalFileService }]);
+ injector.add([IImageIoService, { useClass: TestImageIoService as never }]);
slide = univer.createUnit<ISlideData, SlideDataModel>(UniverInstanceType.UNIVER_SLIDE, createSlideSnapshot());
injector.get(IUniverInstanceService).focusUnit(unitId);
@@ -233,10 +269,12 @@ describe('slide element operations', () => {
commandService.registerCommand(SetSlidePageThumbOperation);
commandService.registerCommand(InsertSlideFloatImageCommand);
commandService.registerCommand(ToggleSlideEditSidebarOperation);
+ commandService.registerCommand(SetTextEditArrowOperation);
injector.get(LocaleService).load({});
});
afterEach(() => {
+ (globalThis as unknown as { Image: typeof Image }).Image = originalImage;
univer.dispose();
});
@@ -383,6 +421,37 @@ describe('slide element operations', () => {
expect(getElementIds(page)).toEqual(beforeIds);
});
+ it('adds the selected image to the active slide and selects the created object', async () => {
+ const page = getActivePage(slide);
+ const beforeIds = getElementIds(page);
+ TestCanvasView.activateCreatedObject = true;
+ TestLocalFileService.files = [new File(['fake image'], 'chart.png', { type: 'image/png' })];
+
+ const result = await commandService.executeCommand(InsertSlideFloatImageCommand.id);
+
+ expect(result).toBe(true);
+ const element = findElementAddedAfter(page, beforeIds);
+ expect(element).toMatchObject({
+ id: 'image-1',
+ zIndex: 3,
+ width: 64,
+ height: 32,
+ type: PageElementType.IMAGE,
+ image: {
+ imageProperties: {
+ imageSourceType: ImageSourceType.BASE64,
+ source: 'data:image/png;base64,ZmFrZQ==',
+ base64Cache: 'data:image/png;base64,ZmFrZQ==',
+ },
+ },
+ });
+ expect(TestCanvasView.activeObjectIds).toEqual(['created-object']);
+ });
+
+ it('keeps the current text-edit arrow operation as a no-op success', async () => {
+ await expect(commandService.executeCommand(SetTextEditArrowOperation.id, { direction: 'left' })).resolves.toBe(true);
+ });
+
it('opens and closes the slide edit sidebar for the selected object type', async () => {
const sidebarService = univer.__getInjector().get(ISidebarService);
const objectTypes = [
diff --git a/packages/slides-ui/src/services/__tests__/slide-editor-bridge.service.spec.ts b/packages/slides-ui/src/services/__tests__/slide-editor-bridge.service.spec.ts
index ad6bce3683..50066354f1 100644
--- a/packages/slides-ui/src/services/__tests__/slide-editor-bridge.service.spec.ts
+++ b/packages/slides-ui/src/services/__tests__/slide-editor-bridge.service.spec.ts
@@ -14,21 +14,52 @@
* limitations under the License.
*/
-import { IContextService, Injector } from '@univerjs/core';
+import { ContextService, IContextService, Injector } from '@univerjs/core';
import { IEditorService } from '@univerjs/docs-ui';
import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
import { beforeEach, describe, expect, it } from 'vitest';
+import { SLIDE_EDITOR_ID } from '../../const';
import { ISlideEditorBridgeService, SlideEditorBridgeService } from '../slide-editor-bridge.service';
+class TestEditorService {
+ readonly focusedEditors: string[] = [];
+ focusedEditor: unknown = {};
+
+ getFocusEditor() {
+ return this.focusedEditor;
+ }
+
+ focus(editorId: string) {
+ this.focusedEditors.push(editorId);
+ }
+}
+
+class TestRenderManagerService {
+ getRenderById(unitId: string) {
+ if (unitId !== 'slide-1') {
+ return null;
+ }
+
+ return {
+ scene: {
+ getViewport: () => ({ viewportScrollX: 5, viewportScrollY: 10 }),
+ getObject: () => ({ left: 30, top: 45 }),
+ },
+ };
+ }
+}
+
describe('SlideEditorBridgeService', () => {
let service: ISlideEditorBridgeService;
+ let editorService: TestEditorService;
beforeEach(() => {
const injector = new Injector();
- injector.add([IEditorService, { useValue: { getFocusEditor: () => ({}) } as unknown as IEditorService }]);
- injector.add([IContextService, { useValue: { setContextValue: () => {} } as unknown as IContextService }]);
- injector.add([IRenderManagerService, { useValue: { getRenderById: () => null } as unknown as IRenderManagerService }]);
+ injector.add([IEditorService, { useClass: TestEditorService as never }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
injector.add([ISlideEditorBridgeService, { useClass: SlideEditorBridgeService }]);
+ editorService = injector.get(IEditorService) as unknown as TestEditorService;
service = injector.get(ISlideEditorBridgeService);
});
@@ -43,4 +74,59 @@ describe('SlideEditorBridgeService', () => {
expect(service.getEditorDirty()).toBe(false);
expect(states.at(-1)).toEqual({ visible: true, eventType: DeviceInputEventType.Dblclick, unitId: 'slide-1' });
});
+
+ it('calculates editor geometry from the selected rich text object and focuses the slide editor when needed', () => {
+ const states: unknown[] = [];
+ service.currentEditRectState$.subscribe((state) => states.push(state));
+ editorService.focusedEditor = null;
+
+ const editorInfo = {
+ unitId: 'slide-1',
+ pageId: 'page-1',
+ scene: {} as never,
+ engine: {} as never,
+ richTextObj: {
+ left: 100,
+ top: 80,
+ width: 240,
+ height: 60,
+ documentData: {
+ id: 'old-editor-id',
+ body: {
+ dataStream: 'Text\r\n',
+ },
+ documentStyle: {
+ pageSize: { width: 10, height: 10 },
+ },
+ },
+ },
+ };
+
+ service.setEditorRect(editorInfo as never);
+
+ expect(service.getEditorRect()).toBe(editorInfo);
+ expect(service.getCurrentEditorId()).toBe(SLIDE_EDITOR_ID);
+ expect(editorService.focusedEditors).toEqual([SLIDE_EDITOR_ID]);
+ expect(service.getEditRectState()).toMatchObject({
+ unitId: 'slide-1',
+ editorUnitId: SLIDE_EDITOR_ID,
+ position: {
+ startX: 100,
+ startY: 80,
+ endX: 340,
+ endY: 140,
+ },
+ slideCardOffset: {
+ left: 25,
+ top: 35,
+ },
+ documentLayoutObject: {
+ documentModel: expect.any(Object),
+ },
+ });
+ expect(states.at(-1)).toMatchObject({
+ unitId: 'slide-1',
+ editorUnitId: SLIDE_EDITOR_ID,
+ });
+ });
});
diff --git a/packages/slides-ui/src/services/__tests__/slide-editor-manager.service.spec.ts b/packages/slides-ui/src/services/__tests__/slide-editor-manager.service.spec.ts
index ddebafb7a0..40dcd5ec4f 100644
--- a/packages/slides-ui/src/services/__tests__/slide-editor-manager.service.spec.ts
+++ b/packages/slides-ui/src/services/__tests__/slide-editor-manager.service.spec.ts
@@ -40,7 +40,33 @@ describe('SlideEditorManagerService', () => {
service.setFocus(true);
expect(states.at(-1)).toEqual({ show: true, startX: 12, startY: 24 });
+ expect(service.getState()).toEqual({ show: true, startX: 12, startY: 24 });
expect(rects.at(-1)).toEqual({ left: 12, top: 24, width: 120, height: 32 });
+ expect(service.getRect()).toEqual({ left: 12, top: 24, width: 120, height: 32 });
expect(focus).toEqual([false, true]);
});
+
+ it('clears editor state and rect when disposed', () => {
+ const states: unknown[] = [];
+ const rects: unknown[] = [];
+ let statesCompleted = false;
+ let rectsCompleted = false;
+ service.state$.subscribe({ next: (state) => states.push(state), complete: () => {
+ statesCompleted = true;
+ } });
+ service.rect$.subscribe({ next: (rect) => rects.push(rect), complete: () => {
+ rectsCompleted = true;
+ } });
+
+ service.setState({ show: true, startX: 1 });
+ service.setRect({ left: 1, top: 2, width: 3, height: 4 });
+ service.dispose();
+
+ expect(service.getState()).toBeNull();
+ expect(service.getRect()).toBeNull();
+ expect(states).toEqual([null, { show: true, startX: 1 }]);
+ expect(rects).toEqual([null, { left: 1, top: 2, width: 3, height: 4 }]);
+ expect(statesCompleted).toBe(true);
+ expect(rectsCompleted).toBe(true);
+ });
});
diff --git a/packages/slides-ui/src/services/__tests__/slide-popup-manager.service.spec.ts b/packages/slides-ui/src/services/__tests__/slide-popup-manager.service.spec.ts
index 16b20dfa71..97fa245b28 100644
--- a/packages/slides-ui/src/services/__tests__/slide-popup-manager.service.spec.ts
+++ b/packages/slides-ui/src/services/__tests__/slide-popup-manager.service.spec.ts
@@ -17,23 +17,89 @@
import { ICommandService, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { ICanvasPopupService } from '@univerjs/ui';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { SlideCanvasPopMangerService } from '../slide-popup-manager.service';
+import { beforeEach, describe, expect, it } from 'vitest';
+import {
+ SlideCanvasPopMangerService,
+ transformBound2OffsetBound,
+ transformPosition2Offset,
+} from '../slide-popup-manager.service';
+
+class TestCanvasPopupService {
+ readonly addedPopups: unknown[] = [];
+ readonly removedPopupIds: string[] = [];
+
+ addPopup(popup: unknown) {
+ this.addedPopups.push(popup);
+ return 'popup-1';
+ }
+
+ removePopup(id: string) {
+ this.removedPopupIds.push(id);
+ }
+}
+
+class TestRenderManagerService {
+ static hasRender = false;
+
+ static reset() {
+ this.hasRender = false;
+ }
+
+ getRenderById(unitId: string) {
+ if (!TestRenderManagerService.hasRender || unitId !== 'slide-1') {
+ return null;
+ }
+
+ const canvasElement = document.createElement('canvas');
+ canvasElement.style.width = '200px';
+ canvasElement.getBoundingClientRect = () => ({
+ left: 10,
+ top: 20,
+ width: 400,
+ height: 300,
+ right: 410,
+ bottom: 320,
+ x: 10,
+ y: 20,
+ toJSON: () => ({}),
+ });
+
+ return {
+ mainComponent: { width: 300, height: 200 },
+ engine: {
+ getCanvasElement: () => canvasElement,
+ },
+ scene: {
+ width: 500,
+ height: 400,
+ getAncestorScale: () => ({ scaleX: 2, scaleY: 3 }),
+ getViewport: () => ({ viewportScrollX: 5, viewportScrollY: 10 }),
+ },
+ };
+ }
+}
+
+class TestUniverInstanceService {
+ getCurrentUnitOfType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SLIDE ? { getUnitId: () => 'slide-1' } : null;
+ }
+}
+
+class TestCommandService {}
describe('SlideCanvasPopMangerService', () => {
let service: SlideCanvasPopMangerService;
- let addPopup: ReturnType<typeof vi.fn>;
- let removePopup: ReturnType<typeof vi.fn>;
+ let popupService: TestCanvasPopupService;
beforeEach(() => {
- addPopup = vi.fn(() => 'popup-1');
- removePopup = vi.fn();
+ TestRenderManagerService.reset();
const injector = new Injector();
- injector.add([ICanvasPopupService, { useValue: { addPopup, removePopup } as unknown as ICanvasPopupService }]);
- injector.add([IRenderManagerService, { useValue: { getRenderById: () => null } as unknown as IRenderManagerService }]);
- injector.add([IUniverInstanceService, { useValue: { getCurrentUnitOfType: (type: UniverInstanceType) => type === UniverInstanceType.UNIVER_SLIDE ? { getUnitId: () => 'slide-1' } : null } as unknown as IUniverInstanceService }]);
- injector.add([ICommandService, { useValue: {} as ICommandService }]);
+ 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([SlideCanvasPopMangerService]);
+ popupService = injector.get(ICanvasPopupService) as unknown as TestCanvasPopupService;
service = injector.get(SlideCanvasPopMangerService);
});
@@ -42,7 +108,50 @@ describe('SlideCanvasPopMangerService', () => {
disposable.dispose();
- expect(addPopup).not.toHaveBeenCalled();
- expect(removePopup).not.toHaveBeenCalled();
+ expect(popupService.addedPopups).toEqual([]);
+ expect(popupService.removedPopupIds).toEqual([]);
+ });
+
+ it('attaches a popup to the rendered slide object and removes it on dispose', () => {
+ TestRenderManagerService.hasRender = true;
+
+ const disposable = service.attachPopupToObject({ left: 15, top: 20, width: 30, height: 10 } as never, {
+ componentKey: 'slide-comment',
+ direction: 'horizontal',
+ });
+
+ expect(popupService.addedPopups).toHaveLength(1);
+ expect(popupService.addedPopups[0]).toMatchObject({
+ unitId: 'slide-1',
+ subUnitId: 'default',
+ componentKey: 'slide-comment',
+ direction: 'horizontal',
+ anchorRect: {
+ left: 190,
+ right: 430,
+ top: 300,
+ bottom: 480,
+ },
+ canvasElement: expect.any(HTMLCanvasElement),
+ });
+
+ disposable.dispose();
+
+ expect(popupService.removedPopupIds).toEqual(['popup-1']);
+ });
+
+ it('converts slide coordinates to viewport offsets with scroll and scale applied', () => {
+ const scene = {
+ getAncestorScale: () => ({ scaleX: 2, scaleY: 3 }),
+ getViewport: () => ({ viewportScrollX: 5, viewportScrollY: 10 }),
+ };
+
+ expect(transformPosition2Offset(15, 20, scene as never)).toEqual({ x: 20, y: 30 });
+ expect(transformBound2OffsetBound({ left: 15, top: 20, right: 45, bottom: 30 }, scene as never)).toEqual({
+ left: 20,
+ top: 30,
+ right: 80,
+ bottom: 60,
+ });
});
});
diff --git a/packages/slides-ui/src/services/__tests__/slide-render.service.spec.ts b/packages/slides-ui/src/services/__tests__/slide-render.service.spec.ts
index c250cd9a38..b4f2f5933c 100644
--- a/packages/slides-ui/src/services/__tests__/slide-render.service.spec.ts
+++ b/packages/slides-ui/src/services/__tests__/slide-render.service.spec.ts
@@ -14,48 +14,79 @@
* limitations under the License.
*/
-import { IContextService, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { ContextService, IContextService, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { Subject } from 'rxjs';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it } from 'vitest';
import { SlideRenderService } from '../slide-render.service';
+function createSlide(unitId: string) {
+ return {
+ getUnitId: () => unitId,
+ };
+}
+
+class TestUniverInstanceService {
+ readonly slideAdded$ = new Subject<{ unit: ReturnType<typeof createSlide> }>();
+ readonly slideDisposed$ = new Subject<ReturnType<typeof createSlide>>();
+ private readonly _initialSlides = [createSlide('existing-slide')];
+
+ getTypeOfUnitAdded$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SLIDE ? this.slideAdded$.asObservable() : new Subject().asObservable();
+ }
+
+ getTypeOfUnitDisposed$(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SLIDE ? this.slideDisposed$.asObservable() : new Subject().asObservable();
+ }
+
+ getAllUnitsForType(type: UniverInstanceType) {
+ return type === UniverInstanceType.UNIVER_SLIDE ? this._initialSlides : [];
+ }
+
+ getUnit(unitId: string) {
+ return createSlide(unitId);
+ }
+}
+
+class TestRenderManagerService {
+ readonly createdRenderers: string[] = [];
+ readonly removedRenderers: string[] = [];
+
+ createRender(unitId: string) {
+ this.createdRenderers.push(unitId);
+ }
+
+ removeRender(unitId: string) {
+ this.removedRenderers.push(unitId);
+ }
+}
+
describe('SlideRenderService', () => {
- let slideAdded$: Subject<unknown>;
- let slideDisposed$: Subject<unknown>;
- let createRender: ReturnType<typeof vi.fn>;
- let removeRender: ReturnType<typeof vi.fn>;
+ let instanceService: TestUniverInstanceService;
+ let renderManagerService: TestRenderManagerService;
beforeEach(() => {
- slideAdded$ = new Subject();
- slideDisposed$ = new Subject();
- createRender = vi.fn();
- removeRender = vi.fn();
const injector = new Injector();
- injector.add([IContextService, { useValue: {} as IContextService }]);
- injector.add([IUniverInstanceService, { useValue: {
- getTypeOfUnitAdded$: (type: UniverInstanceType) => type === UniverInstanceType.UNIVER_SLIDE ? slideAdded$ : new Subject(),
- getTypeOfUnitDisposed$: (type: UniverInstanceType) => type === UniverInstanceType.UNIVER_SLIDE ? slideDisposed$ : new Subject(),
- getAllUnitsForType: () => [{ getUnitId: () => 'existing-slide' }],
- getUnit: (unitId: string) => ({ getUnitId: () => unitId }),
- } as unknown as IUniverInstanceService }]);
- injector.add([IRenderManagerService, { useValue: { createRender, removeRender } as unknown as IRenderManagerService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);
+ injector.add([IRenderManagerService, { useClass: TestRenderManagerService as never }]);
injector.add([SlideRenderService]);
+ instanceService = injector.get(IUniverInstanceService) as unknown as TestUniverInstanceService;
+ renderManagerService = injector.get(IRenderManagerService) as unknown as TestRenderManagerService;
injector.get(SlideRenderService);
});
it('creates renderers for existing and newly added slide units', async () => {
await Promise.resolve();
- slideAdded$.next({ unit: { getUnitId: () => 'new-slide' } });
+ instanceService.slideAdded$.next({ unit: createSlide('new-slide') });
- expect(createRender).toHaveBeenCalledWith('existing-slide');
- expect(createRender).toHaveBeenCalledWith('new-slide');
+ expect(renderManagerService.createdRenderers).toEqual(['existing-slide', 'new-slide']);
});
it('removes the renderer when a slide unit is disposed', async () => {
await Promise.resolve();
- slideDisposed$.next({ getUnitId: () => 'old-slide' });
+ instanceService.slideDisposed$.next(createSlide('old-slide'));
- expect(removeRender).toHaveBeenCalledWith('old-slide');
+ expect(renderManagerService.removedRenderers).toEqual(['old-slide']);
});
});
diff --git a/packages/slides-ui/src/views/panels/__tests__/TransformPanel.spec.tsx b/packages/slides-ui/src/views/panels/__tests__/TransformPanel.spec.tsx
new file mode 100644
index 0000000000..1bdf01e765
--- /dev/null
+++ b/packages/slides-ui/src/views/panels/__tests__/TransformPanel.spec.tsx
@@ -0,0 +1,263 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Subject } from 'rxjs';
+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 TransformPanel from '../TransformPanel';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'transform-panel-unit';
+const PAGE_ID = 'page-1';
+const SELECTED_ID = 'selected-shape';
+
+class TestSlideObject {
+ public refreshCount = 0;
+
+ constructor(
+ readonly oKey: string,
+ public width: number,
+ public height: number,
+ public left: number,
+ public top: number,
+ public angle: number
+ ) {}
+
+ resize(width: number, height: number) {
+ this.width = width;
+ this.height = height;
+ }
+
+ translate(left: number, top: number) {
+ this.left = left;
+ this.top = top;
+ }
+
+ transformByState(state: { angle?: number }) {
+ if (typeof state.angle === 'number') {
+ this.angle = state.angle;
+ }
+ }
+}
+
+class TestTransformer {
+ readonly changeStart$ = new Subject<{ objects: Map<string, TestSlideObject> }>();
+ readonly changing$ = new Subject<{ objects: Map<string, TestSlideObject> }>();
+
+ constructor(private readonly _object: TestSlideObject) {}
+
+ getSelectedObjectMap() {
+ return new Map([[this._object.oKey, this._object]]);
+ }
+
+ refreshControls() {
+ this._object.refreshCount += 1;
+ }
+}
+
+class TestScene {
+ private readonly _transformer: TestTransformer;
+
+ constructor(selectedObject: TestSlideObject) {
+ this._transformer = new TestTransformer(selectedObject);
+ }
+
+ getTransformer() {
+ return this._transformer;
+ }
+}
+
+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: 'Transform 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: 120,
+ width: 160,
+ height: 90,
+ angle: 15,
+ 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() {
+ const selectedObject = new TestSlideObject(SELECTED_ID, 160, 90, 100, 120, 15);
+ TestCanvasView.scene = new TestScene(selectedObject);
+
+ return selectedObject;
+}
+
+function renderTransformPanel(root: Root, testBed: ReturnType<typeof createPanelTestBed>) {
+ act(() => {
+ root.render(
+ <RediContext.Provider value={{ injector: testBed.injector }}>
+ <TransformPanel pageId={PAGE_ID} unitId={UNIT_ID} />
+ </RediContext.Provider>
+ );
+ });
+}
+
+function setInputValue(input: HTMLInputElement, value: number) {
+ const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+
+ act(() => {
+ valueSetter?.call(input, String(value));
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+function getInputs(container: HTMLElement) {
+ const inputs = Array.from(container.querySelectorAll('input'));
+ if (inputs.length !== 5) {
+ throw new Error(`Expected five transform inputs, received ${inputs.length}`);
+ }
+
+ return inputs;
+}
+
+describe('TransformPanel', () => {
+ 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('updates the selected slide element when dimension controls change', () => {
+ currentTestBed = createPanelTestBed();
+ const selectedObject = createRenderScene();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderTransformPanel(root, currentTestBed);
+
+ const [widthInput, heightInput] = getInputs(container);
+ setInputValue(widthInput, 240);
+ setInputValue(heightInput, 135);
+
+ expect(selectedObject).toMatchObject({
+ width: 240,
+ height: 135,
+ refreshCount: 2,
+ });
+ });
+
+ it('updates the selected slide element when position and rotation controls change', () => {
+ currentTestBed = createPanelTestBed();
+ const selectedObject = createRenderScene();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ renderTransformPanel(root, currentTestBed);
+
+ const [, , xInput, yInput, rotationInput] = getInputs(container);
+ setInputValue(xInput, 210);
+ setInputValue(yInput, 180);
+ setInputValue(rotationInput, 45);
+
+ expect(selectedObject).toMatchObject({
+ left: 210,
+ top: 180,
+ angle: 45,
+ refreshCount: 3,
+ });
+ });
+});
diff --git a/packages/slides/src/views/render/adaptors/__tests__/slide-adaptor.spec.ts b/packages/slides/src/views/render/adaptors/__tests__/slide-adaptor.spec.ts
new file mode 100644
index 0000000000..7385078f08
--- /dev/null
+++ b/packages/slides/src/views/render/adaptors/__tests__/slide-adaptor.spec.ts
@@ -0,0 +1,156 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Rect } from '@univerjs/engine-render';
+import type { IPageElement, ISlideData } from '../../../../types/interfaces/i-slide-data';
+import { ConfigService, ContextService, IConfigService, IContextService, Injector, LocaleService } from '@univerjs/core';
+import { Scene, SceneViewer } from '@univerjs/engine-render';
+import { describe, expect, it } from 'vitest';
+import { BasicShapes } from '../../../../types/enum/prst-geom-type';
+import { PageElementType, PageType } from '../../../../types/interfaces/i-slide-data';
+import { SlideAdaptor } from '../slide-adaptor';
+
+function createRenderTestBed() {
+ const injector = new Injector();
+
+ injector.add([LocaleService, { useClass: LocaleService }]);
+ injector.add([IContextService, { useClass: ContextService }]);
+ injector.add([IConfigService, { useClass: ConfigService }]);
+
+ return {
+ injector,
+ slideAdaptor: injector.createInstance(SlideAdaptor),
+ };
+}
+
+function createMainScene() {
+ return new Scene(
+ 'main-scene',
+ new SceneViewer('main-viewer', {
+ width: 960,
+ height: 540,
+ })
+ );
+}
+
+function createDeckElement(): IPageElement {
+ return {
+ id: 'embedded-deck',
+ zIndex: 9,
+ left: 16,
+ top: 24,
+ width: 720,
+ height: 405,
+ title: 'Embedded sales deck',
+ description: 'Deck inside a page element',
+ type: PageElementType.SLIDE,
+ slide: createEmbeddedSlideData(),
+ };
+}
+
+function createEmbeddedSlideData(): ISlideData {
+ return {
+ id: 'sales-deck',
+ title: 'Sales update',
+ pageSize: { width: 720, height: 405 },
+ body: {
+ pageOrder: ['summary', 'pipeline'],
+ pages: {
+ summary: {
+ id: 'summary',
+ pageType: PageType.SLIDE,
+ zIndex: 1,
+ title: 'Summary',
+ description: 'Executive summary',
+ pageBackgroundFill: { rgb: '#112233' },
+ pageElements: {
+ 'sales-box': {
+ id: 'sales-box',
+ zIndex: 3,
+ left: 40,
+ top: 32,
+ width: 180,
+ height: 72,
+ title: 'Revenue card',
+ description: 'Revenue highlight',
+ type: PageElementType.SHAPE,
+ shape: {
+ shapeType: BasicShapes.RoundRect,
+ text: '',
+ shapeProperties: {
+ shapeBackgroundFill: { rgb: '#44aa88' },
+ radius: 12,
+ outline: {
+ outlineFill: { rgb: '#0b3128' },
+ weight: 2,
+ },
+ },
+ },
+ },
+ },
+ },
+ pipeline: {
+ id: 'pipeline',
+ pageType: PageType.SLIDE,
+ zIndex: 2,
+ title: 'Pipeline',
+ description: 'Next page',
+ pageBackgroundFill: { rgb: '#ffeecc' },
+ pageElements: {},
+ },
+ },
+ },
+ };
+}
+
+describe('SlideAdaptor', () => {
+ it('converts slide pages in source order with page backgrounds and child shape styling', () => {
+ const { slideAdaptor } = createRenderTestBed();
+ const deck = slideAdaptor.convert(createDeckElement(), createMainScene())!;
+
+ expect(deck.left).toBe(16);
+ expect(deck.top).toBe(24);
+ expect(deck.width).toBe(720);
+ expect(deck.height).toBe(405);
+ expect(deck.zIndex).toBe(9);
+ expect([...deck.getSubScenes().keys()]).toEqual(['summary', 'pipeline']);
+ expect(deck.getActiveSubScene()?.sceneKey).toBe('summary');
+
+ const summaryScene = deck.getSubScene('summary')!;
+ const summaryBackground = summaryScene.getObject('canvas') as Rect;
+ expect(summaryBackground.fill).toBe('#112233');
+ expect(summaryBackground.width).toBe(720);
+ expect(summaryBackground.height).toBe(405);
+ expect(summaryBackground.evented).toBe(false);
+
+ const salesBox = summaryScene.getObject('sales-box') as Rect;
+ expect(salesBox.left).toBe(40);
+ expect(salesBox.top).toBe(32);
+ expect(salesBox.width).toBe(180);
+ expect(salesBox.height).toBe(72);
+ expect(salesBox.zIndex).toBe(3);
+ expect(salesBox.fill).toBe('#44aa88');
+ expect(salesBox.stroke).toBe('#0b3128');
+ expect(salesBox.strokeWidth).toBe(2);
+ expect(salesBox.getPropByKey('radius')).toBe(12);
+
+ const pipelineScene = deck.getSubScene('pipeline')!;
+ expect((pipelineScene.getObject('canvas') as Rect).fill).toBe('#ffeecc');
+
+ deck.changePage('pipeline');
+ expect(deck.getActiveSubScene()?.sceneKey).toBe('pipeline');
+ });
+});
diff --git a/packages/thread-comment-ui/src/views/thread-comment-tree/__tests__/index.spec.tsx b/packages/thread-comment-ui/src/views/thread-comment-tree/__tests__/index.spec.tsx
new file mode 100644
index 0000000000..993d240fe6
--- /dev/null
+++ b/packages/thread-comment-ui/src/views/thread-comment-tree/__tests__/index.spec.tsx
@@ -0,0 +1,596 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ThreadCommentTree, ThreadCommentTreeLocation } from '../../ThreadCommentTree';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const UNIT_ID = 'unit-1';
+const SHEET_ID = 'sheet-1';
+const REPLY_LABEL = 'thread-comment-ui.editor.reply';
+const IRenderManagerService = createIdentifier<TestRenderManagerService>('engine-render.render-manager.service');
+
+interface IEditorRecord {
+ id: string;
+ data: IDocumentData;
+ selections: ISuccinctDocRangeParam[];
+ focused: boolean;
+}
+
+class TestState {
+ static addedComments: IThreadComment[] = [];
+ static resolveStates: boolean[] = [];
+
+ static reset() {
+ this.addedComments = [];
+ this.resolveStates = [];
+ }
+}
+
+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 ?? 'thread-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 createTreeTestBed() {
+ 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,
+ editorService: injector.get(IEditorService),
+ panelService: injector.get(ThreadCommentPanelService),
+ threadCommentModel: injector.get(ThreadCommentModel),
+ };
+}
+
+function renderTree(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 renderDefaultTree(injector: Injector, commentId: string) {
+ return renderTree(
+ injector,
+ <ThreadCommentTree
+ id={commentId}
+ unitId={UNIT_ID}
+ subUnitId={SHEET_ID}
+ refStr="A1"
+ type={UniverInstanceType.UNIVER_SHEET}
+ getSubUnitName={(subUnitId) => subUnitId}
+ location={ThreadCommentTreeLocation.PANEL}
+ onAddComment={(comment) => {
+ TestState.addedComments.push(comment);
+ return true;
+ }}
+ onResolve={(resolved) => {
+ TestState.resolveStates.push(resolved);
+ }}
+ />
+ );
+}
+
+function getTree(container: HTMLElement, commentId: string) {
+ const item = container.querySelector(`#PANEL-${UNIT_ID}-${SHEET_ID}-${commentId}`);
+ if (!item) {
+ throw new Error(`Tree item "${commentId}" was not found.`);
+ }
+
+ return item as HTMLElement;
+}
+
+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 getResolveAction(container: HTMLElement, commentId: string) {
+ const tree = getTree(container, commentId);
+ const header = tree.firstElementChild as HTMLElement | null;
+ const controls = header?.lastElementChild as HTMLElement | null;
+ const action = controls?.firstElementChild;
+ if (!action) {
+ throw new Error('Resolve action was not found.');
+ }
+
+ return action as HTMLElement;
+}
+
+function getRootCommentItem(container: HTMLElement, commentId: string) {
+ const scroller = getTree(container, commentId).children[1];
+ const item = scroller?.firstElementChild;
+ if (!item) {
+ throw new Error('Root comment item was not found.');
+ }
+
+ return item as HTMLElement;
+}
+
+function getReplyAction(container: HTMLElement, commentId: string) {
+ const item = getRootCommentItem(container, commentId);
+ const nameRow = item.children[1] as HTMLElement | undefined;
+ const controls = nameRow?.lastElementChild as HTMLElement | undefined;
+ const action = controls?.firstElementChild;
+ if (!action) {
+ throw new Error('Reply action was not found.');
+ }
+
+ return action as HTMLElement;
+}
+
+function getOnlyEditor(testBed: ReturnType<typeof createTreeTestBed>) {
+ const editors = Array.from(testBed.editorService.getAllEditor().values());
+ if (editors.length !== 1) {
+ throw new Error(`Expected one editor, received ${editors.length}.`);
+ }
+
+ return editors[0];
+}
+
+function addRootComment(model: ThreadCommentModel, comment: IThreadComment) {
+ model.addComment(comment.unitId, comment.subUnitId, comment);
+}
+
+function waitForTreeRefresh() {
+ return new Promise((resolve) => setTimeout(resolve, 40));
+}
+
+function waitForFrame() {
+ return new Promise((resolve) => setTimeout(resolve, 16));
+}
+
+describe('ThreadCommentTree', () => {
+ let root: Root | undefined;
+ let container: HTMLElement | undefined;
+
+ beforeEach(() => {
+ document.body.innerHTML = '';
+ TestState.reset();
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => root!.unmount());
+ }
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ });
+
+ it('adds a reply through the tree editor and stores it under the root thread', async () => {
+ const testBed = createTreeTestBed();
+ addRootComment(testBed.threadCommentModel, createComment({ id: 'root-thread', ref: 'A1' }));
+
+ const rendered = renderDefaultTree(testBed.injector, 'root-thread');
+ root = rendered.root;
+ container = rendered.container;
+
+ await act(async () => {
+ getRootCommentItem(container!, 'root-thread').dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
+ await waitForFrame();
+ });
+
+ await act(async () => {
+ getReplyAction(container!, 'root-thread').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await waitForFrame();
+ });
+
+ act(() => {
+ getOnlyEditor(testBed).replaceText('Reply from tree');
+ });
+
+ await act(async () => {
+ getButton(container!, REPLY_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await waitForTreeRefresh();
+ });
+
+ const thread = testBed.threadCommentModel.getCommentWithChildren(UNIT_ID, SHEET_ID, 'root-thread');
+ expect(thread?.children).toHaveLength(1);
+ expect(thread?.children[0].parentId).toBe('root-thread');
+ expect(thread?.children[0].threadId).toBe('root-thread');
+ expect(thread?.children[0].personId).toBe('owner');
+ expect(thread?.children[0].text.dataStream).toBe('Reply from tree\r\n');
+ expect(TestState.addedComments).toHaveLength(1);
+ expect(TestState.addedComments[0].parentId).toBe('root-thread');
+ });
+
+ it('toggles the resolved state and updates the active comment target', async () => {
+ const testBed = createTreeTestBed();
+ addRootComment(testBed.threadCommentModel, createComment({ id: 'root-thread', ref: 'A1' }));
+ testBed.panelService.setActiveComment({
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ commentId: 'root-thread',
+ });
+
+ const rendered = renderDefaultTree(testBed.injector, 'root-thread');
+ root = rendered.root;
+ container = rendered.container;
+
+ await act(async () => {
+ getResolveAction(container!, 'root-thread').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await waitForTreeRefresh();
+ });
+
+ expect(testBed.threadCommentModel.getComment(UNIT_ID, SHEET_ID, 'root-thread')?.resolved).toBe(true);
+ expect(testBed.panelService.activeCommentId).toBeUndefined();
+ expect(TestState.resolveStates).toEqual([true]);
+
+ await act(async () => {
+ getResolveAction(container!, 'root-thread').dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await waitForTreeRefresh();
+ });
+
+ expect(testBed.threadCommentModel.getComment(UNIT_ID, SHEET_ID, 'root-thread')?.resolved).toBe(false);
+ expect(testBed.panelService.activeCommentId).toEqual({
+ unitId: UNIT_ID,
+ subUnitId: SHEET_ID,
+ commentId: 'root-thread',
+ });
+ expect(TestState.resolveStates).toEqual([true, false]);
+ });
+});
diff --git a/packages/ui/src/facade/__tests__/f-ui.spec.ts b/packages/ui/src/facade/__tests__/f-ui.spec.ts
index 6120434921..d532300d17 100644
--- a/packages/ui/src/facade/__tests__/f-ui.spec.ts
+++ b/packages/ui/src/facade/__tests__/f-ui.spec.ts
@@ -14,7 +14,15 @@
* limitations under the License.
*/
-import { CommandType, ICommandService, ILogService, LogLevel, Univer } from '@univerjs/core';
+import {
+ CommandType,
+ ICommandService,
+ ILogService,
+ Injector,
+ IUniverInstanceService,
+ 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';
@@ -42,8 +50,38 @@ import {
UIPartsService,
} from '@univerjs/ui';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { FShortcut } from '../f-shortcut';
import '@univerjs/ui/facade';
+class FakeShortcutService {
+ static dispatched: KeyboardEvent[] = [];
+
+ forceDisable() {
+ return { dispose: () => {} };
+ }
+
+ dispatch(event: KeyboardEvent) {
+ FakeShortcutService.dispatched.push(event);
+ return { id: 'fake.shortcut', binding: event.keyCode };
+ }
+}
+
+class FakeRenderManagerService {
+ static renderUnit: unknown;
+
+ getRenderById(_unitId: string) {
+ return FakeRenderManagerService.renderUnit;
+ }
+}
+
+class FakeUniverInstanceService {
+ static workbook: unknown;
+
+ getCurrentUnitOfType() {
+ return FakeUniverInstanceService.workbook;
+ }
+}
+
describe('ui facade', () => {
let univer: Univer;
let univerAPI: FUniver;
@@ -209,4 +247,34 @@ describe('ui facade', () => {
disposable.dispose();
expect(componentManager.get('custom-component')).toBeUndefined();
});
+
+ it('triggers shortcuts through the active workbook render canvas', () => {
+ const injector = new Injector();
+ injector.add([IShortcutService, { useClass: FakeShortcutService as never }]);
+ injector.add([IRenderManagerService, { useClass: FakeRenderManagerService as never }]);
+ injector.add([IUniverInstanceService, { useClass: FakeUniverInstanceService as never }]);
+ const shortcut = injector.createInstance(FShortcut);
+ const event = new KeyboardEvent('keydown', { key: 'k', keyCode: KeyCode.K });
+ const canvasEvents: KeyboardEvent[] = [];
+
+ FakeShortcutService.dispatched = [];
+ FakeUniverInstanceService.workbook = undefined;
+ FakeRenderManagerService.renderUnit = undefined;
+ expect(shortcut.triggerShortcut(event)).toBeUndefined();
+
+ FakeUniverInstanceService.workbook = { getUnitId: () => 'sheet-1' };
+ expect(shortcut.triggerShortcut(event)).toBeUndefined();
+
+ FakeRenderManagerService.renderUnit = {
+ engine: {
+ getCanvasElement: () => ({
+ dispatchEvent: (dispatchedEvent: KeyboardEvent) => canvasEvents.push(dispatchedEvent),
+ }),
+ },
+ };
+
+ expect(shortcut.triggerShortcut(event)?.id).toBe('fake.shortcut');
+ expect(canvasEvents).toEqual([event]);
+ expect(FakeShortcutService.dispatched).toEqual([event]);
+ });
});
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.ts
index 3a9ec09472..af04b3ef09 100644
--- 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.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+import type { IDisposable } from '@univerjs/core';
+import type { INotificationOptions } from '../../../views/notification/Notification';
import { Injector } from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { DesktopNotificationService } from '../../notification/desktop-notification.service';
@@ -21,10 +23,19 @@ import { INotificationService } from '../../notification/notification.service';
import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../../parts/parts.service';
import { DesktopBeforeCloseService, IBeforeCloseService } from '../before-close.service';
+class FakeNotificationService extends DesktopNotificationService {
+ static notifications: INotificationOptions[] = [];
+
+ override show(params: INotificationOptions): IDisposable {
+ FakeNotificationService.notifications.push(params);
+ return { dispose: () => {} };
+ }
+}
+
function createService(): IBeforeCloseService {
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
- injector.add([INotificationService, { useClass: DesktopNotificationService }]);
+ injector.add([INotificationService, { useClass: FakeNotificationService }]);
injector.add([IBeforeCloseService, { useClass: DesktopBeforeCloseService }]);
return injector.get(IBeforeCloseService);
}
@@ -32,6 +43,31 @@ function createService(): IBeforeCloseService {
describe('DesktopBeforeCloseService', () => {
afterEach(() => {
vi.unstubAllGlobals();
+ FakeNotificationService.notifications = [];
+ });
+
+ it('blocks unload with combined messages and clears handlers on dispose', () => {
+ const windowTarget = new EventTarget();
+ vi.stubGlobal('window', windowTarget);
+ const service = createService();
+ service.registerBeforeClose(() => 'Unsaved sheet');
+ const disposable = service.registerBeforeClose(() => 'Pending upload');
+
+ const event = new Event('beforeunload') as BeforeUnloadEvent;
+ windowTarget.dispatchEvent(event);
+
+ expect(event.returnValue).toBe('Unsaved sheet\nPending upload');
+ expect(FakeNotificationService.notifications).toEqual([{
+ type: 'error',
+ title: 'Some changes are not saved',
+ content: 'Unsaved sheet\nPending upload',
+ }]);
+
+ disposable.dispose();
+ (service as DesktopBeforeCloseService).dispose();
+ const nextEvent = new Event('beforeunload') as BeforeUnloadEvent;
+ windowTarget.dispatchEvent(nextEvent);
+ expect(nextEvent.returnValue).toBeUndefined();
});
it('runs close callbacks when the page unloads and stops after disposal', () => {
@@ -53,7 +89,7 @@ describe('DesktopBeforeCloseService', () => {
vi.stubGlobal('window', windowTarget);
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
- injector.add([INotificationService, { useClass: DesktopNotificationService }]);
+ injector.add([INotificationService, { useClass: FakeNotificationService }]);
injector.add([IBeforeCloseService, { useClass: DesktopBeforeCloseService }]);
injector.get(IBeforeCloseService);
diff --git a/packages/ui/src/services/clipboard/__tests__/clipboard-utils.spec.ts b/packages/ui/src/services/clipboard/__tests__/clipboard-utils.spec.ts
new file mode 100644
index 0000000000..5902ac7712
--- /dev/null
+++ b/packages/ui/src/services/clipboard/__tests__/clipboard-utils.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 { afterEach, describe, expect, it, vi } from 'vitest';
+import { supportClipboardAPI } from '../clipboard-utils';
+
+describe('clipboard-utils', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('detects whether text clipboard reads are available in the browser', () => {
+ vi.stubGlobal('navigator', { clipboard: { readText: () => Promise.resolve('copied') } });
+ expect(supportClipboardAPI()).toBe(true);
+
+ vi.stubGlobal('navigator', { clipboard: {} });
+ expect(supportClipboardAPI()).toBe(false);
+ });
+});
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.ts
index 23f64e068e..b4497418f8 100644
--- a/packages/ui/src/services/confirm/__tests__/desktop-confirm.service.spec.ts
+++ b/packages/ui/src/services/confirm/__tests__/desktop-confirm.service.spec.ts
@@ -41,6 +41,27 @@ describe('DesktopConfirmService', () => {
sub.unsubscribe();
});
+ it('updates duplicate confirm ids and resolves close callbacks as cancellation', async () => {
+ const service = createService();
+ const snapshots: IConfirmPartMethodOptions[][] = [];
+ const sub = service.confirmOptions$.subscribe((options) => snapshots.push(options));
+
+ const disposable = service.open({ id: 'save-confirm', children: 'Save changes?' });
+ service.open({ id: 'save-confirm', children: 'Discard changes?' });
+ service.close('save-confirm');
+
+ expect(snapshots.at(-2)?.[0]).toMatchObject({ id: 'save-confirm', children: 'Discard changes?', visible: true });
+ expect(snapshots.at(-1)?.[0]).toMatchObject({ id: 'save-confirm', visible: false });
+
+ const promise = service.confirm({ id: 'cancel-confirm', children: 'Cancel?' });
+ snapshots.at(-1)?.find((item) => item.id === 'cancel-confirm')?.onClose?.();
+ await expect(promise).resolves.toBe(false);
+
+ disposable.dispose();
+ expect(snapshots.at(-1)).toEqual([]);
+ sub.unsubscribe();
+ });
+
it('registers the global confirm UI part when constructed', () => {
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
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.ts
index dddc03c43e..9fce3d2d1f 100644
--- 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.ts
@@ -62,4 +62,20 @@ describe('CanvasFloatDomService', () => {
expect(snapshots[2][0][1].domId).toBe('runtime-dom-1');
sub.unsubscribe();
});
+
+ it('ignores missing updates and publishes remove-all changes', () => {
+ const service = createService();
+ const sizes: number[] = [];
+ const sub = service.domLayers$.subscribe((layers) => sizes.push(layers.length));
+
+ service.updateFloatDom('missing', { domId: 'ignored' });
+ service.addFloatDom(createFloatDom('dom-1'));
+ service.addFloatDom(createFloatDom('dom-2'));
+ service.removeFloatDom('missing');
+ service.removeAll();
+
+ expect(service.domLayers).toEqual([]);
+ expect(sizes).toEqual([0, 1, 2, 0]);
+ sub.unsubscribe();
+ });
});
diff --git a/packages/ui/src/services/font.service.spec.ts b/packages/ui/src/services/font.service.spec.ts
index cda7183447..8fea146850 100644
--- a/packages/ui/src/services/font.service.spec.ts
+++ b/packages/ui/src/services/font.service.spec.ts
@@ -14,18 +14,39 @@
* limitations under the License.
*/
+import type { IUniverUIConfig } from '../config/config';
import { ConfigService, IConfigService, Injector } from '@univerjs/core';
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { UI_PLUGIN_CONFIG_KEY } from '../config/config';
import { FontService, IFontService } from './font.service';
-function createService(): IFontService {
+class CustomFontConfigService extends ConfigService {
+ override getConfig<T>(key: string): T {
+ if (key === UI_PLUGIN_CONFIG_KEY) {
+ return {
+ customFontFamily: {
+ override: true,
+ list: [{ value: 'OnlyCustom', label: 'Only Custom', category: 'display' }],
+ },
+ } as IUniverUIConfig as T;
+ }
+
+ return super.getConfig<T>(key);
+ }
+}
+
+function createService(configService: new (...args: any[]) => IConfigService = ConfigService): IFontService {
const injector = new Injector();
- injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([IConfigService, { useClass: configService }]);
injector.add([IFontService, { useClass: FontService }]);
return injector.get(IFontService);
}
describe('FontService', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
it('maintains the font catalog used by font family pickers', () => {
const service = createService();
@@ -43,4 +64,42 @@ describe('FontService', () => {
expect(() => service.addFont(arial)).toThrow('[FontService]: Font with value "Arial" already exists.');
});
+
+ it('loads override font configuration and rejects updates to missing fonts', () => {
+ const service = createService(CustomFontConfigService);
+
+ expect(service.getFonts()).toEqual([{ value: 'OnlyCustom', label: 'Only Custom', category: 'display' }]);
+ expect(() => service.updateFont('Arial', { label: 'Missing' })).toThrow('Font with value "Arial" not found.');
+ expect(service.removeFont('Arial')).toBe(false);
+ });
+
+ it('checks font support by comparing measured text widths', () => {
+ const measured: string[] = [];
+ vi.stubGlobal('document', {
+ createElement: () => ({
+ getContext: () => ({
+ font: '',
+ measureText() {
+ measured.push(this.font);
+ return { width: this.font.includes('"CustomFont"') ? 120 : 100 };
+ },
+ }),
+ }),
+ });
+ const service = createService();
+
+ expect(service.isFontSupported('CustomFont')).toBe(true);
+ expect(measured).toContain('72px "CustomFont", monospace');
+ });
+
+ it('returns false when the canvas context is unavailable', () => {
+ vi.stubGlobal('document', {
+ createElement: () => ({
+ getContext: () => null,
+ }),
+ });
+ const service = createService();
+
+ expect(service.isFontSupported('MissingFont')).toBe(false);
+ });
});
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.ts
index 6d90360fab..9374000638 100644
--- a/packages/ui/src/services/gallery/__tests__/desktop-gallery.service.spec.ts
+++ b/packages/ui/src/services/gallery/__tests__/desktop-gallery.service.spec.ts
@@ -44,6 +44,17 @@ describe('DesktopGalleryService', () => {
sub.unsubscribe();
});
+ it('completes gallery state when the open handle is disposed', () => {
+ const service = createService();
+ let completed = false;
+ service.gallery$.subscribe({ complete: () => completed = true });
+
+ const disposable = service.open({ images: ['a.png'] });
+ disposable.dispose();
+
+ expect(completed).toBe(true);
+ });
+
it('registers the global gallery UI part when constructed', () => {
const injector = new Injector();
injector.add([IUIPartsService, { useClass: UIPartsService }]);
diff --git a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts b/packages/ui/src/services/layout/__tests__/layout.service.spec.ts
index 3c4a71fe5e..97130b791e 100644
--- a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts
+++ b/packages/ui/src/services/layout/__tests__/layout.service.spec.ts
@@ -17,6 +17,7 @@
import {
ContextService,
DesktopLogService,
+ FOCUSING_UNIVER_EDITOR,
IContextService,
ILogService,
Injector,
@@ -27,7 +28,7 @@ import {
} from '@univerjs/core';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { DesktopLayoutService, ILayoutService } from '../layout.service';
+import { DesktopLayoutService, FOCUSING_UNIVER, ILayoutService } from '../layout.service';
class TestSlideUnit extends UnitModel {
override type = UniverInstanceType.UNIVER_SLIDE;
@@ -58,12 +59,33 @@ class TestSlideUnit extends UnitModel {
function createElement(name: string, containsSelf = true) {
return {
dataset: { uComp: name },
- contains: (target: unknown) => containsSelf && target != null,
+ contains: (target: unknown) => containsSelf && target != null && (target as HTMLElement).dataset?.uComp !== 'outside',
} as unknown as HTMLElement;
}
+function dispatchFocusIn(target: HTMLElement): void {
+ const event = new Event('focusin');
+ Object.defineProperty(event, 'target', {
+ configurable: true,
+ value: target,
+ });
+ window.dispatchEvent(event);
+}
+
function createService() {
- vi.stubGlobal('window', new EventTarget());
+ const listeners = new Map<string, EventListener[]>();
+ vi.stubGlobal('window', {
+ addEventListener(type: string, listener: EventListener) {
+ listeners.set(type, [...(listeners.get(type) ?? []), listener]);
+ },
+ removeEventListener(type: string, listener: EventListener) {
+ listeners.set(type, (listeners.get(type) ?? []).filter((item) => item !== listener));
+ },
+ dispatchEvent(event: Event) {
+ (listeners.get(event.type) ?? []).forEach((listener) => listener(event));
+ return true;
+ },
+ });
vi.stubGlobal('document', { activeElement: null });
const injector = new Injector();
injector.add([ILogService, { useClass: DesktopLogService }]);
@@ -75,7 +97,9 @@ function createService() {
univerInstanceService.__addUnit(slide);
univerInstanceService.focusUnit('slide-1');
return {
+ injector,
service: injector.get(ILayoutService),
+ contextService: injector.get(IContextService),
};
}
@@ -87,7 +111,7 @@ describe('DesktopLayoutService', () => {
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 content = createElement('custom-content');
const focused: string[] = [];
const rootDisposable = service.registerRootContainerElement(root);
@@ -106,4 +130,57 @@ describe('DesktopLayoutService', () => {
rootDisposable.dispose();
expect(service.rootContainerElement).toBeNull();
});
+
+ it('rejects duplicate registrations that would make focus ownership ambiguous', () => {
+ const { service } = createService();
+ const root = createElement('app-layout');
+ const content = createElement('custom-content');
+ const container = createElement('dialog');
+
+ service.registerRootContainerElement(root);
+ service.registerContentElement(content);
+ service.registerContainerElement(container);
+ service.registerFocusHandler(UniverInstanceType.UNIVER_SLIDE, () => {});
+
+ expect(() => service.registerRootContainerElement(createElement('other-root'))).toThrow('[DesktopLayoutService]: root container already registered!');
+ expect(() => service.registerContentElement(content)).toThrow('[DesktopLayoutService]: content container already registered!');
+ expect(() => service.registerContainerElement(container)).toThrow('[LayoutService]: container already registered!');
+ expect(() => service.registerFocusHandler(UniverInstanceType.UNIVER_SLIDE, () => {})).toThrow('[DesktopLayoutService]: handler of type 3 bas been registered!');
+ });
+
+ it('updates focus context from window focus events and editor active state', async () => {
+ const { service, contextService } = createService();
+ const focused: string[] = [];
+ const root = createElement('app-layout');
+ const content = createElement('custom-content');
+ const outside = createElement('outside', false);
+ const editor = createElement('editor');
+ const button = createElement('button');
+
+ service.registerRootContainerElement(root);
+ service.registerContentElement(content);
+ service.registerFocusHandler(UniverInstanceType.UNIVER_SLIDE, (unitId) => focused.push(unitId));
+
+ Object.defineProperty(globalThis.document, 'activeElement', {
+ configurable: true,
+ get: () => editor,
+ });
+ dispatchFocusIn(outside);
+ expect(service.isFocused).toBe(false);
+ expect(contextService.getContextValue(FOCUSING_UNIVER)).toBe(false);
+ expect(contextService.getContextValue(FOCUSING_UNIVER_EDITOR)).toBe(true);
+
+ Object.defineProperty(globalThis.document, 'activeElement', {
+ configurable: true,
+ get: () => content,
+ });
+ dispatchFocusIn(content);
+ expect(service.isFocused).toBe(true);
+ expect(contextService.getContextValue(FOCUSING_UNIVER)).toBe(true);
+ expect(contextService.getContextValue(FOCUSING_UNIVER_EDITOR)).toBe(false);
+
+ dispatchFocusIn(button);
+ await Promise.resolve();
+ expect(focused).toEqual(['slide-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.ts
index efe8414bc0..6f019db37f 100644
--- 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.ts
@@ -57,4 +57,16 @@ describe('DesktopLocalStorageService', () => {
await service.removeItem('sidebar');
await expect(service.getItem('sidebar')).resolves.toBeNull();
});
+
+ it('reads key positions and clears stored values', async () => {
+ vi.stubGlobal('localStorage', createMemoryLocalStorage());
+ const service = createService();
+
+ await service.setItem('first', 1);
+ await expect(service.key(0)).resolves.toBe('first');
+
+ await service.clear();
+ await expect(service.keys()).resolves.toEqual([]);
+ await expect(service.key(0)).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.ts
index a948db40bc..e065c98481 100644
--- a/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts
+++ b/packages/ui/src/services/menu/__tests__/menu-manager.service.spec.ts
@@ -17,6 +17,7 @@
import type { MenuSchemaType } from '../menu-manager.service';
import { ConfigService, IConfigService, Injector } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import { isMenuButtonSelectorItem, isMenuSelectorItem, MenuItemType } from '../menu';
import { IMenuManagerService, MenuManagerService } from '../menu-manager.service';
function createService(): IMenuManagerService {
@@ -53,4 +54,11 @@ describe('MenuManagerService', () => {
expect(changes.length).toBeGreaterThanOrEqual(2);
sub.unsubscribe();
});
+
+ it('identifies selector menu item variants used by menu renderers', () => {
+ expect(isMenuSelectorItem({ id: 'font-family', type: MenuItemType.SELECTOR })).toBe(true);
+ expect(isMenuSelectorItem({ id: 'more-actions', type: MenuItemType.SUBITEMS })).toBe(true);
+ expect(isMenuSelectorItem({ id: 'copy', type: MenuItemType.BUTTON })).toBe(false);
+ expect(isMenuButtonSelectorItem({ id: 'fill-color', type: MenuItemType.BUTTON_SELECTOR })).toBe(true);
+ });
});
diff --git a/packages/ui/src/services/popup/__tests__/canvas-popup.service.spec.ts b/packages/ui/src/services/popup/__tests__/canvas-popup.service.spec.ts
index 8a9397e55d..458836a790 100644
--- a/packages/ui/src/services/popup/__tests__/canvas-popup.service.spec.ts
+++ b/packages/ui/src/services/popup/__tests__/canvas-popup.service.spec.ts
@@ -44,6 +44,46 @@ describe('CanvasPopupService', () => {
expect(service.activePopupId).toBeNull();
});
+ it('keeps the active popup when another popup is deactivated', () => {
+ const firstPopupId = service.addPopup({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ componentKey: 'first-comment',
+ anchorRect$: new BehaviorSubject({ left: 0, top: 0, right: 10, bottom: 10 }),
+ canvasElement: {} as HTMLCanvasElement,
+ });
+ service.addPopup({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ componentKey: 'second-comment',
+ anchorRect$: new BehaviorSubject({ left: 20, top: 20, right: 30, bottom: 30 }),
+ canvasElement: {} as HTMLCanvasElement,
+ });
+
+ service.popups[0][1].onActiveChange?.(true);
+ service.popups[1][1].onActiveChange?.(false);
+
+ expect(service.activePopupId).toBe(firstPopupId);
+ });
+
+ it('clears all popups for canvas teardown', () => {
+ const sizes: number[] = [];
+ const sub = service.popups$.subscribe((popups) => sizes.push(popups.length));
+ service.addPopup({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ componentKey: 'cell-comment',
+ anchorRect$: new BehaviorSubject({ left: 0, top: 0, right: 10, bottom: 10 }),
+ canvasElement: {} as HTMLCanvasElement,
+ });
+
+ service.removeAll();
+
+ expect(service.popups).toEqual([]);
+ expect(sizes).toEqual([0, 1, 0]);
+ sub.unsubscribe();
+ });
+
it('notifies renderers when popup entries are added or removed', () => {
const sizes: number[] = [];
service.popups$.subscribe((popups) => sizes.push(popups.length));
diff --git a/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts b/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts
index f0813b398d..f5441128ed 100644
--- a/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts
+++ b/packages/ui/src/services/ribbon/__tests__/ribbon.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { MenuSchemaType } from '../../menu/menu-manager.service';
+import type { IMenuSchema, MenuSchemaType } from '../../menu/menu-manager.service';
import {
ConfigService,
ContextService,
@@ -26,7 +26,9 @@ import {
IUniverInstanceService,
UniverInstanceService,
} from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
import { describe, expect, it } from 'vitest';
+import { MenuItemType } from '../../menu/menu';
import { IMenuManagerService, MenuManagerService } from '../../menu/menu-manager.service';
import { MenuManagerPosition, RibbonPosition } from '../../menu/types';
import { DesktopRibbonService, IRibbonService } from '../ribbon.service';
@@ -90,4 +92,61 @@ describe('DesktopRibbonService', () => {
collapsedSub.unsubscribe();
fakeToolbarSub.unsubscribe();
});
+
+ it('filters hidden ribbon commands and restores activation when contextual tabs disappear', () => {
+ const { service, menuManagerService } = createService();
+ const hidden$ = new BehaviorSubject(false);
+ const ribbons: IMenuSchema[][] = [];
+ const activated: string[] = [];
+ const ribbonSub = service.ribbon$.subscribe((ribbon) => ribbons.push(ribbon));
+ const activeSub = service.activatedTab$.subscribe((tab) => activated.push(tab));
+
+ menuManagerService.appendRootMenu({
+ [MenuManagerPosition.RIBBON]: {
+ [RibbonPosition.START]: {
+ order: 0,
+ [`${RibbonPosition.START}.visible-group`]: {
+ order: 0,
+ visibleCommand: {
+ order: 0,
+ menuItemFactory: () => ({ id: 'visible-command', type: MenuItemType.BUTTON }),
+ },
+ hiddenCommand: {
+ order: 1,
+ menuItemFactory: () => ({ id: 'hidden-command', type: MenuItemType.BUTTON, hidden$ }),
+ },
+ },
+ },
+ 'picture-tools': {
+ order: 99,
+ contextual: true,
+ [`${RibbonPosition.START}.picture-group`]: {
+ order: 0,
+ command: {
+ order: 0,
+ menuItemFactory: () => ({ id: 'picture-command', type: MenuItemType.BUTTON }),
+ },
+ },
+ },
+ },
+ } as MenuSchemaType);
+
+ service.setActivatedTab(RibbonPosition.START);
+ service.showContextualTab('picture-tools', { activate: true });
+ hidden$.next(true);
+ service.hideAllContextualTabs();
+ service.hideAllContextualTabs();
+ service.hideContextualTab('missing-tools');
+
+ const startRibbon = ribbons.at(-1)!
+ .find((group) => group.key === RibbonPosition.START);
+ const commandKeys = startRibbon?.children?.flatMap((group) => group.children ?? []).map((child) => child.key);
+ expect(commandKeys).toContain('visibleCommand');
+ expect(commandKeys).not.toContain('hiddenCommand');
+ expect(ribbons.at(-1)?.map((item) => item.key)).not.toContain('picture-tools');
+ expect(activated.at(-1)).toBe(RibbonPosition.START);
+
+ ribbonSub.unsubscribe();
+ activeSub.unsubscribe();
+ });
});
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.ts
index 5b67b711c1..f3b60f30db 100644
--- 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.ts
@@ -63,4 +63,42 @@ describe('ThemeSwitcherService', () => {
expect(appended[0].textContent).toContain('--univer-primary-color: red;');
expect(appended[0].textContent).toContain('--univer-radius: 4;');
});
+
+ it('injects a theme when no previous style element exists', () => {
+ const appended: Array<{ textContent?: string }> = [];
+ vi.stubGlobal('document', {
+ getElementById: () => null,
+ createElement: () => ({
+ setAttribute: vi.fn(),
+ textContent: '',
+ }),
+ head: {
+ appendChild: (element: { textContent?: string }) => appended.push(element),
+ },
+ });
+ const service = createService();
+
+ service.injectThemeToHead({ color: { text: '#111' } } as unknown as Theme);
+
+ expect(appended[0].textContent).toContain('--univer-color-text: #111;');
+ });
+
+ it('disposes without removing the active theme style element', () => {
+ const existing = { remove: vi.fn() };
+ vi.stubGlobal('document', {
+ getElementById: () => existing,
+ createElement: () => ({
+ setAttribute: vi.fn(),
+ textContent: '',
+ }),
+ head: {
+ appendChild: vi.fn(),
+ },
+ });
+ const service = createService();
+
+ service.dispose();
+
+ expect(existing.remove).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx b/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx
new file mode 100644
index 0000000000..4cea50c919
--- /dev/null
+++ b/packages/ui/src/views/components/confirm-part/__tests__/ConfirmPart.spec.tsx
@@ -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 { ReactElement } from 'react';
+import type { IConfirmChildrenProps, IConfirmPartMethodOptions } from '../interface';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { DesktopLogService, IConfirmService, ILogService, Injector, LocaleService } from '@univerjs/core';
+import { useEffect } from 'react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ComponentManager, IconManager } from '../../../../common';
+import { DesktopConfirmService } from '../../../../services/confirm/desktop-confirm.service';
+import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
+import { RediProvider } from '../../../../utils/di';
+import { ConfirmPart } from '../ConfirmPart';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestState {
+ static confirmAttempts = 0;
+ static confirmResults: Array<Record<string, unknown> | undefined> = [];
+
+ static reset(): void {
+ this.confirmAttempts = 0;
+ this.confirmResults = [];
+ }
+}
+
+function GuardedConfirmContent({ hooks }: { hooks?: IConfirmChildrenProps['hooks'] }) {
+ useEffect(() => {
+ if (!hooks) return;
+
+ hooks.beforeConfirm = () => {
+ TestState.confirmAttempts += 1;
+
+ if (TestState.confirmAttempts === 1) {
+ return { cancel: true };
+ }
+
+ return { cancel: false, rowCount: 3 };
+ };
+
+ return () => {
+ delete hooks.beforeConfirm;
+ };
+ }, [hooks]);
+
+ return <span>Rows selected</span>;
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector();
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IConfirmService, { useClass: DesktopConfirmService as never }]);
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([LocaleService]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+
+ injector.get(ComponentManager).register('guarded-confirm-content', GuardedConfirmContent);
+
+ const result = render(
+ <RediProvider value={{ injector }}>
+ {element}
+ </RediProvider>
+ );
+
+ return {
+ ...result,
+ injector,
+ dispose: () => {
+ result.unmount();
+ cleanup();
+ },
+ };
+}
+
+describe('ConfirmPart', () => {
+ afterEach(() => {
+ cleanup();
+ TestState.reset();
+ });
+
+ it('resolves confirmation and clears the active confirm state after the user confirms', async () => {
+ const rendered = renderWithDependencies(<ConfirmPart />);
+ const confirmService = rendered.injector.get(IConfirmService) as IConfirmService<IConfirmPartMethodOptions>;
+ const snapshots: IConfirmPartMethodOptions[][] = [];
+ const subscription = confirmService.confirmOptions$.subscribe((options) => snapshots.push(options));
+ let answer!: Promise<boolean>;
+
+ act(() => {
+ answer = confirmService.confirm({
+ id: 'remove-sheet',
+ title: { title: <span>Remove sheet</span> },
+ children: { title: <span>This action cannot be undone.</span> },
+ cancelText: 'Keep',
+ confirmText: 'Remove',
+ });
+ });
+
+ expect(await screen.findByText('This action cannot be undone.')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
+
+ await expect(answer).resolves.toBe(true);
+ await waitFor(() => {
+ expect(screen.queryByText('This action cannot be undone.')).toBeNull();
+ });
+ expect(snapshots.at(-1)).toEqual([]);
+
+ subscription.unsubscribe();
+ rendered.dispose();
+ });
+
+ it('lets child hooks veto the first confirm and pass data to the final confirm callback', async () => {
+ const rendered = renderWithDependencies(<ConfirmPart />);
+ const confirmService = rendered.injector.get(IConfirmService) as IConfirmService<IConfirmPartMethodOptions>;
+
+ let disposable!: ReturnType<IConfirmService<IConfirmPartMethodOptions>['open']>;
+
+ act(() => {
+ disposable = confirmService.open({
+ id: 'guarded-delete',
+ title: { title: <span>Delete rows</span> },
+ children: { label: 'guarded-confirm-content' },
+ cancelText: 'Cancel',
+ confirmText: 'Delete',
+ onConfirm: (result) => {
+ TestState.confirmResults.push(result);
+ },
+ });
+ });
+
+ expect(await screen.findByText('Rows selected')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+
+ expect(TestState.confirmAttempts).toBe(1);
+ expect(TestState.confirmResults).toEqual([]);
+ expect(screen.getByText('Rows selected')).toBeTruthy();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
+
+ expect(TestState.confirmAttempts).toBe(2);
+ expect(TestState.confirmResults).toEqual([{ cancel: false, rowCount: 3 }]);
+
+ disposable.dispose();
+ rendered.dispose();
+ });
+});
diff --git a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
new file mode 100644
index 0000000000..3bc1ffe5d0
--- /dev/null
+++ b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
@@ -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 { ReactElement } from 'react';
+import type { IDialogPartMethodOptions } from '../interface';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { DesktopLogService, ILogService, Injector, LocaleService } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ComponentManager, IconManager } from '../../../../common';
+import { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
+import { IDialogService } from '../../../../services/dialog/dialog.service';
+import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
+import { RediProvider } from '../../../../utils/di';
+import { DialogPart } from '../DialogPart';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector();
+ injector.add([IUIPartsService, { useClass: UIPartsService }]);
+ injector.add([IDialogService, { useClass: DesktopDialogService }]);
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([LocaleService]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+
+ const result = render(
+ <RediProvider value={{ injector }}>
+ {element}
+ </RediProvider>
+ );
+
+ return {
+ ...result,
+ injector,
+ dispose: () => {
+ result.unmount();
+ cleanup();
+ },
+ };
+}
+
+describe('DialogPart', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('renders service-opened dialog labels and clears the requested dialog when service closes it', async () => {
+ const rendered = renderWithDependencies(<DialogPart />);
+ const dialogService = rendered.injector.get(IDialogService);
+ const snapshots: IDialogPartMethodOptions[][] = [];
+ const subscription = dialogService.getDialogs$().subscribe((options) => snapshots.push(options));
+
+ act(() => {
+ dialogService.open({
+ id: 'permission-dialog',
+ title: { title: <span>Permission needed</span> },
+ children: { title: <span>Grant access before editing.</span> },
+ width: 320,
+ });
+ });
+
+ expect(await screen.findByText('Permission needed')).toBeTruthy();
+ expect(screen.getByText('Grant access before editing.')).toBeTruthy();
+
+ act(() => {
+ dialogService.close('permission-dialog');
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('Grant access before editing.')).toBeNull();
+ });
+ expect(snapshots.at(-1)).toMatchObject([{ id: 'permission-dialog', open: false }]);
+
+ subscription.unsubscribe();
+ rendered.dispose();
+ });
+
+ it('keeps excepted dialogs visible when service closes the rest', async () => {
+ const rendered = renderWithDependencies(<DialogPart />);
+ const dialogService = rendered.injector.get(IDialogService);
+ const snapshots: IDialogPartMethodOptions[][] = [];
+ const subscription = dialogService.getDialogs$().subscribe((options) => snapshots.push(options));
+
+ act(() => {
+ dialogService.open({
+ id: 'first-dialog',
+ title: { title: <span>First dialog</span> },
+ children: { title: <span>Draft changes</span> },
+ });
+ dialogService.open({
+ id: 'second-dialog',
+ title: { title: <span>Second dialog</span> },
+ children: { title: <span>Keep this open</span> },
+ });
+ });
+
+ expect(await screen.findByText('Draft changes')).toBeTruthy();
+ expect(screen.getByText('Keep this open')).toBeTruthy();
+
+ act(() => {
+ dialogService.closeAll(['second-dialog']);
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('Draft changes')).toBeNull();
+ });
+ expect(screen.getByText('Keep this open')).toBeTruthy();
+ expect(snapshots.at(-1)).toMatchObject([
+ { id: 'first-dialog', open: false },
+ { id: 'second-dialog', open: true },
+ ]);
+
+ subscription.unsubscribe();
+ rendered.dispose();
+ });
+});
diff --git a/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx
new file mode 100644
index 0000000000..360aeac512
--- /dev/null
+++ b/packages/ui/src/views/components/popup/__tests__/CanvasPopup.spec.tsx
@@ -0,0 +1,145 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ReactElement } from 'react';
+import type { IPopup } from '../../../../services/popup/canvas-popup.service';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { ConfigService, IConfigService, Injector, LocaleService } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { ComponentManager } from '../../../../common';
+import { CanvasPopupService, ICanvasPopupService } from '../../../../services/popup/canvas-popup.service';
+import { RediProvider } from '../../../../utils/di';
+import { CanvasPopup } from '../CanvasPopup';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestResizeObserver {
+ observe(): void {}
+ disconnect(): void {}
+}
+
+let previousResizeObserver: typeof ResizeObserver | undefined;
+let previousAnimationFrame: typeof requestAnimationFrame | undefined;
+
+function TestPopup({ popup }: { popup: IPopup<{ label: string }> }) {
+ return <button type="button">{popup.extraProps?.label}</button>;
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector();
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([LocaleService]);
+ injector.add([ComponentManager]);
+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);
+
+ injector.get(ComponentManager).register('test-popup', TestPopup);
+
+ const result = render(
+ <RediProvider value={{ injector }}>
+ {element}
+ </RediProvider>
+ );
+
+ return {
+ ...result,
+ injector,
+ dispose: () => {
+ result.unmount();
+ cleanup();
+ },
+ };
+}
+
+function createCanvasElement(rect: DOMRect): HTMLCanvasElement {
+ const canvasElement = document.createElement('canvas');
+ Object.defineProperty(canvasElement, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => rect,
+ });
+ return canvasElement;
+}
+
+describe('CanvasPopup', () => {
+ beforeEach(() => {
+ previousResizeObserver = globalThis.ResizeObserver;
+ previousAnimationFrame = globalThis.requestAnimationFrame;
+ globalThis.ResizeObserver = TestResizeObserver as unknown as typeof ResizeObserver;
+ globalThis.requestAnimationFrame = ((callback: FrameRequestCallback) => {
+ callback(0);
+ return 0;
+ }) as typeof requestAnimationFrame;
+ });
+
+ afterEach(() => {
+ cleanup();
+ if (previousResizeObserver) {
+ globalThis.ResizeObserver = previousResizeObserver;
+ } else {
+ delete (globalThis as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver;
+ }
+
+ if (previousAnimationFrame) {
+ globalThis.requestAnimationFrame = previousAnimationFrame;
+ } else {
+ delete (globalThis as { requestAnimationFrame?: typeof requestAnimationFrame }).requestAnimationFrame;
+ }
+ });
+
+ it('positions service popups from canvas anchors and tracks hover ownership', async () => {
+ const rendered = renderWithDependencies(<CanvasPopup />);
+ const popupService = rendered.injector.get(ICanvasPopupService);
+ const anchorRect$ = new BehaviorSubject({ left: 40, top: 50, right: 90, bottom: 70 });
+ let popupId = '';
+
+ act(() => {
+ popupId = popupService.addPopup({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ componentKey: 'test-popup',
+ anchorRect$,
+ canvasElement: createCanvasElement(new DOMRect(0, 0, 400, 300)),
+ direction: 'bottom-left',
+ offset: [4, 6],
+ extraProps: { label: 'Cell comment' },
+ });
+ });
+
+ expect(await screen.findByRole('button', { name: 'Cell comment' })).toBeTruthy();
+
+ const popupElement = document.querySelector('[data-u-comp="rect-popup"]') as HTMLElement;
+ await waitFor(() => {
+ expect(popupElement.style.left).toBe('36px');
+ expect(popupElement.style.top).toBe('76px');
+ });
+
+ fireEvent.pointerEnter(popupElement);
+ expect(popupService.activePopupId).toBe(popupId);
+
+ fireEvent.pointerLeave(popupElement);
+ expect(popupService.activePopupId).toBeNull();
+
+ act(() => {
+ popupService.removePopup(popupId);
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByRole('button', { name: 'Cell comment' })).toBeNull();
+ });
+
+ rendered.dispose();
+ });
+});
diff --git a/packages/ui/src/views/components/shortcut-panel/__tests__/ShortcutPanel.spec.tsx b/packages/ui/src/views/components/shortcut-panel/__tests__/ShortcutPanel.spec.tsx
new file mode 100644
index 0000000000..8d6b41fb4a
--- /dev/null
+++ b/packages/ui/src/views/components/shortcut-panel/__tests__/ShortcutPanel.spec.tsx
@@ -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 type { IDisposable } from '@univerjs/core';
+import type { ReactElement } from 'react';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { ICommandService, IContextService, Injector, LocaleService, LocaleType } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { IPlatformService } from '../../../../services/platform/platform.service';
+import { KeyCode, MetaKeys } from '../../../../services/shortcut/keycode';
+import { IShortcutService, ShortcutService } from '../../../../services/shortcut/shortcut.service';
+import { RediProvider } from '../../../../utils/di';
+import { ShortcutPanel } from '../ShortcutPanel';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestCommandService {
+ executeCommand(): boolean {
+ return true;
+ }
+}
+
+class TestContextService {}
+
+class TestPlatformService {
+ readonly isMac = false;
+ readonly isWindows = true;
+ readonly isLinux = false;
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector();
+ injector.add([ICommandService, { useClass: TestCommandService as never }]);
+ injector.add([IContextService, { useClass: TestContextService as never }]);
+ injector.add([IPlatformService, { useClass: TestPlatformService }]);
+ injector.add([IShortcutService, { useClass: ShortcutService }]);
+ injector.add([LocaleService]);
+
+ injector.get(LocaleService).load({
+ [LocaleType.ZH_CN]: {
+ ui: {
+ shortcutGroup: {
+ edit: 'Edit actions',
+ view: 'View actions',
+ },
+ shortcutItem: {
+ copy: 'Copy cells',
+ paste: 'Paste cells',
+ zoom: 'Zoom panel',
+ },
+ },
+ },
+ });
+
+ const result = render(
+ <RediProvider value={{ injector }}>
+ {element}
+ </RediProvider>
+ );
+
+ return {
+ ...result,
+ injector,
+ dispose: () => {
+ result.unmount();
+ (injector.get(IShortcutService) as IShortcutService & { dispose(): void }).dispose();
+ },
+ };
+}
+
+describe('ShortcutPanel', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it('refreshes grouped shortcuts when the shortcut service registers and releases items', () => {
+ const rendered = renderWithDependencies(<ShortcutPanel />);
+ const shortcutService = rendered.injector.get(IShortcutService);
+ const disposables: IDisposable[] = [];
+
+ act(() => {
+ disposables.push(shortcutService.registerShortcut({
+ id: 'test.command.zoom',
+ description: 'ui.shortcutItem.zoom',
+ binding: KeyCode.BACK_SLASH | MetaKeys.CTRL_COMMAND,
+ group: '20_view',
+ groupTitle: 'ui.shortcutGroup.view',
+ }));
+ disposables.push(shortcutService.registerShortcut({
+ id: 'test.command.copy',
+ description: 'ui.shortcutItem.copy',
+ binding: KeyCode.C | MetaKeys.CTRL_COMMAND,
+ group: '10_edit',
+ groupTitle: 'ui.shortcutGroup.edit',
+ }));
+ disposables.push(shortcutService.registerShortcut({
+ id: 'test.command.paste',
+ description: 'ui.shortcutItem.paste',
+ binding: KeyCode.V | MetaKeys.CTRL_COMMAND,
+ group: '10_edit',
+ groupTitle: 'ui.shortcutGroup.edit',
+ }));
+ });
+
+ expect(screen.getByText('Edit actions').compareDocumentPosition(screen.getByText('View actions'))).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(screen.getByText('Copy cells')).not.toBeNull();
+ expect(screen.getAllByText('Ctrl')).toHaveLength(3);
+ expect(screen.getByText('C')).not.toBeNull();
+ expect(screen.getByText('Paste cells')).not.toBeNull();
+ expect(screen.getByText('Zoom panel')).not.toBeNull();
+
+ act(() => {
+ disposables[1].dispose();
+ });
+
+ expect(screen.queryByText('Copy cells')).toBeNull();
+ expect(screen.getByText('Paste cells')).not.toBeNull();
+ expect(shortcutService.getAllShortcuts().map((item) => item.id)).toEqual([
+ 'test.command.zoom',
+ 'test.command.paste',
+ ]);
+
+ disposables[0].dispose();
+ disposables[2].dispose();
+ rendered.dispose();
+ });
+});
diff --git a/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx b/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx
new file mode 100644
index 0000000000..bbc6bf52c4
--- /dev/null
+++ b/packages/ui/src/views/components/sidebar/__tests__/Sidebar.spec.tsx
@@ -0,0 +1,113 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { DesktopLogService, ILogService, Injector, LocaleService } from '@univerjs/core';
+import { afterEach, describe, expect, it } from 'vitest';
+import { ComponentManager, IconManager } from '../../../../common';
+import { DesktopSidebarService } from '../../../../services/sidebar/desktop-sidebar.service';
+import { ISidebarService } from '../../../../services/sidebar/sidebar.service';
+import { RediProvider } from '../../../../utils/di';
+import { Sidebar } from '../Sidebar';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+class TestState {
+ static closes = 0;
+
+ static reset(): void {
+ this.closes = 0;
+ }
+}
+
+function renderWithDependencies(element: ReactElement) {
+ const injector = new Injector();
+ injector.add([ISidebarService, { useClass: DesktopSidebarService }]);
+ injector.add([ILogService, { useClass: DesktopLogService }]);
+ injector.add([LocaleService]);
+ injector.add([ComponentManager]);
+ injector.add([IconManager]);
+
+ const result = render(
+ <RediProvider value={{ injector }}>
+ {element}
+ </RediProvider>
+ );
+
+ return {
+ ...result,
+ injector,
+ dispose: () => {
+ result.unmount();
+ injector.get(ISidebarService).close();
+ },
+ };
+}
+
+describe('Sidebar', () => {
+ afterEach(() => {
+ cleanup();
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ TestState.reset();
+ });
+
+ it('closes the active panel through the close button and reports the service state', () => {
+ const rendered = renderWithDependencies(<Sidebar />);
+ const sidebarService = rendered.injector.get(ISidebarService);
+
+ act(() => {
+ sidebarService.open({
+ id: 'inspector',
+ header: { title: <span>Inspector</span> },
+ children: { title: <span>Cell details</span> },
+ onClose: () => {
+ TestState.closes += 1;
+ },
+ });
+ });
+
+ expect(sidebarService.visible).toBe(true);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close sidebar' }));
+
+ expect(sidebarService.visible).toBe(false);
+ expect(TestState.closes).toBe(1);
+ expect(screen.getByRole('complementary', { name: 'Sidebar panel' }).getAttribute('aria-expanded')).toBe('false');
+ rendered.dispose();
+ });
+
+ it('persists the clamped drag width in the sidebar service', () => {
+ const rendered = renderWithDependencies(<Sidebar />);
+ const sidebarService = rendered.injector.get(ISidebarService);
+
+ act(() => {
+ sidebarService.open({
+ id: 'formatting',
+ header: { title: <span>Formatting</span> },
+ width: 384,
+ });
+ });
+
+ fireEvent.mouseDown(screen.getByRole('separator', { name: 'Resize sidebar' }));
+ fireEvent.mouseMove(document, { clientX: -960 });
+ fireEvent.mouseUp(document);
+
+ expect(sidebarService.width).toBe(800);
+ rendered.dispose();
+ });
+});
diff --git a/packages/uniscript/src/views/components/ScriptEditorPanel.spec.tsx b/packages/uniscript/src/views/components/ScriptEditorPanel.spec.tsx
new file mode 100644
index 0000000000..9809e1a1c6
--- /dev/null
+++ b/packages/uniscript/src/views/components/ScriptEditorPanel.spec.tsx
@@ -0,0 +1,430 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { IShortcutItem } from '@univerjs/ui';
+import type { Root } from 'react-dom/client';
+import {
+ ConfigService,
+ IConfigService,
+ Injector,
+ LocaleService,
+ LocaleType,
+ ThemeService,
+ toDisposable,
+} from '@univerjs/core';
+import { MessageType } from '@univerjs/design';
+import { IMessageService, IShortcutService, RediContext } from '@univerjs/ui';
+import { editor as monacoEditor } from 'monaco-editor';
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { Observable } from 'rxjs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import enUS from '../../locale/en-US';
+import { ScriptEditorService } from '../../services/script-editor.service';
+import { IUniscriptExecutionService } from '../../services/script-execution.service';
+import { ScriptEditorPanel } from './ScriptEditorPanel';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+type EditorListener = () => void;
+
+class TestEditorModel {
+ constructor(private _value = '') {}
+
+ setValue(value: string) {
+ this._value = value;
+ }
+
+ getValue() {
+ return this._value;
+ }
+}
+
+class TestCodeEditor {
+ private readonly _model = new TestEditorModel();
+ private readonly _focusListeners: EditorListener[] = [];
+ private readonly _blurListeners: EditorListener[] = [];
+ readonly layouts: Array<{ width: number; height: number }> = [];
+
+ setValue(value: string) {
+ this._model.setValue(value);
+ }
+
+ getModel() {
+ return this._model;
+ }
+
+ layout(size: { width: number; height: number }) {
+ this.layouts.push(size);
+ }
+
+ onDidFocusEditorWidget(listener: EditorListener): IDisposable {
+ this._focusListeners.push(listener);
+ return toDisposable(() => {
+ const index = this._focusListeners.indexOf(listener);
+ if (index >= 0) {
+ this._focusListeners.splice(index, 1);
+ }
+ });
+ }
+
+ onDidBlurEditorWidget(listener: EditorListener): IDisposable {
+ this._blurListeners.push(listener);
+ return toDisposable(() => {
+ const index = this._blurListeners.indexOf(listener);
+ if (index >= 0) {
+ this._blurListeners.splice(index, 1);
+ }
+ });
+ }
+
+ focus() {
+ this._focusListeners.forEach((listener) => listener());
+ }
+
+ blur() {
+ this._blurListeners.forEach((listener) => listener());
+ }
+
+ dispose() {
+ TestEditorState.disposed += 1;
+ }
+}
+
+class TestEditorState {
+ static created: TestCodeEditor | null = null;
+ static disposed = 0;
+
+ static reset() {
+ this.created = null;
+ this.disposed = 0;
+ }
+}
+
+class TestExecutionState {
+ static codes: string[] = [];
+ static failNext = false;
+
+ static reset() {
+ this.codes = [];
+ this.failNext = false;
+ }
+}
+
+class TestExecutionService implements IUniscriptExecutionService {
+ execute(code: string): Promise<boolean> {
+ TestExecutionState.codes.push(code);
+ return TestExecutionState.failNext ? Promise.reject(new Error('Execution stopped')) : Promise.resolve(true);
+ }
+}
+
+class TestMessageState {
+ static messages: IMessageProps[] = [];
+
+ static reset() {
+ this.messages = [];
+ }
+}
+
+class TestMessageService implements IMessageService {
+ show(options: IMessageProps): IDisposable {
+ TestMessageState.messages.push(options);
+ return toDisposable(() => undefined);
+ }
+
+ remove(): void {
+ // Not part of this panel behavior.
+ }
+
+ removeAll(): void {
+ TestMessageState.messages = [];
+ }
+}
+
+class TestShortcutState {
+ static activeEscapes = 0;
+ static startedEscapes = 0;
+ static releasedEscapes = 0;
+
+ static reset() {
+ this.activeEscapes = 0;
+ this.startedEscapes = 0;
+ this.releasedEscapes = 0;
+ }
+}
+
+class TestShortcutService implements IShortcutService {
+ readonly shortcutChanged$ = new Observable<void>();
+
+ forceEscape(): IDisposable {
+ TestShortcutState.activeEscapes += 1;
+ TestShortcutState.startedEscapes += 1;
+ let released = false;
+
+ return toDisposable(() => {
+ if (!released) {
+ released = true;
+ TestShortcutState.activeEscapes -= 1;
+ TestShortcutState.releasedEscapes += 1;
+ }
+ });
+ }
+
+ forceDisable(): IDisposable {
+ return toDisposable(() => undefined);
+ }
+
+ dispatch(): IShortcutItem<object> | undefined {
+ return undefined;
+ }
+
+ registerShortcut(): IDisposable {
+ return toDisposable(() => undefined);
+ }
+
+ getShortcutDisplay(): string | null {
+ return null;
+ }
+
+ getShortcutDisplayOfCommand(): string | null {
+ return null;
+ }
+
+ getAllShortcuts(): IShortcutItem[] {
+ return [];
+ }
+}
+
+class TestResizeObserver {
+ constructor(private readonly _listener: ResizeObserverCallback) {}
+
+ observe(target: Element) {
+ setTimeout(() => {
+ this._listener([{ target }] as ResizeObserverEntry[], this as unknown as ResizeObserver);
+ }, 0);
+ }
+
+ unobserve(): void {
+ // No external observer resources are allocated in this test.
+ }
+
+ disconnect(): void {
+ // No external observer resources are allocated in this test.
+ }
+}
+
+function createPanelTestBed() {
+ const injector = new Injector();
+
+ injector.add([IConfigService, { useClass: ConfigService }]);
+ injector.add([LocaleService]);
+ injector.add([ThemeService]);
+ injector.add([IMessageService, { useClass: TestMessageService as never }]);
+ injector.add([IShortcutService, { useClass: TestShortcutService as never }]);
+ injector.add([ScriptEditorService]);
+ injector.add([IUniscriptExecutionService, { useClass: TestExecutionService }]);
+
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: enUS });
+ localeService.setLocale(LocaleType.EN_US);
+
+ return {
+ injector,
+ editorService: injector.get(ScriptEditorService),
+ };
+}
+
+async function renderPanel(root: Root, injector: Injector) {
+ await act(async () => {
+ root.render(
+ <RediContext.Provider value={{ injector }}>
+ <ScriptEditorPanel />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+}
+
+function getEditor() {
+ if (!TestEditorState.created) {
+ throw new Error('The editor was not created.');
+ }
+
+ return TestEditorState.created;
+}
+
+function getExecuteButton(container: HTMLElement) {
+ const button = Array.from(container.querySelectorAll<HTMLButtonElement>('[data-u-comp="button"]'))
+ .find((item) => item.textContent === 'Execute Script');
+
+ if (!button) {
+ throw new Error('The execute action was not rendered.');
+ }
+
+ return button;
+}
+
+function installBrowserAPIs() {
+ const resizeObserverDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'ResizeObserver');
+ const idleDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'requestIdleCallback');
+ const createDescriptor = Object.getOwnPropertyDescriptor(monacoEditor, 'create');
+
+ Object.defineProperty(globalThis, 'ResizeObserver', {
+ configurable: true,
+ value: TestResizeObserver,
+ });
+ Object.defineProperty(globalThis, 'requestIdleCallback', {
+ configurable: true,
+ value: (task: IdleRequestCallback) => {
+ setTimeout(() => {
+ task({ didTimeout: false, timeRemaining: () => 50 });
+ }, 0);
+ return 1;
+ },
+ });
+ Object.defineProperty(monacoEditor, 'create', {
+ configurable: true,
+ value: () => {
+ const editor = new TestCodeEditor();
+ TestEditorState.created = editor;
+ return editor;
+ },
+ });
+
+ return () => {
+ if (resizeObserverDescriptor) {
+ Object.defineProperty(globalThis, 'ResizeObserver', resizeObserverDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, 'ResizeObserver');
+ }
+
+ if (idleDescriptor) {
+ Object.defineProperty(globalThis, 'requestIdleCallback', idleDescriptor);
+ } else {
+ Reflect.deleteProperty(globalThis, 'requestIdleCallback');
+ }
+
+ if (createDescriptor) {
+ Object.defineProperty(monacoEditor, 'create', createDescriptor);
+ }
+ };
+}
+
+describe('ScriptEditorPanel', () => {
+ let root: Root | undefined;
+ let container: HTMLDivElement | undefined;
+ let restoreAPIs: (() => void) | undefined;
+ let currentTestBed: ReturnType<typeof createPanelTestBed> | undefined;
+
+ beforeEach(() => {
+ TestEditorState.reset();
+ TestExecutionState.reset();
+ TestMessageState.reset();
+ TestShortcutState.reset();
+ restoreAPIs = installBrowserAPIs();
+ });
+
+ afterEach(() => {
+ act(() => {
+ root?.unmount();
+ });
+ currentTestBed?.editorService.dispose();
+ restoreAPIs?.();
+ Reflect.deleteProperty(window, 'MonacoEnvironment');
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ restoreAPIs = undefined;
+ currentTestBed = undefined;
+ });
+
+ it('executes the edited editor content and reports success', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderPanel(root, currentTestBed.injector);
+ getEditor().setValue('const total = 1 + 2;');
+
+ await act(async () => {
+ getExecuteButton(container!).dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(TestExecutionState.codes).toEqual(['const total = 1 + 2;']);
+ expect(TestMessageState.messages).toMatchObject([
+ { content: 'Execution Success', type: MessageType.Success },
+ ]);
+ expect(currentTestBed.editorService.getEditorInstance()).toBe(getEditor());
+ });
+
+ it('reports an execution failure when the execution service rejects the script', async () => {
+ TestExecutionState.failNext = true;
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderPanel(root, currentTestBed.injector);
+ getEditor().setValue('throw new Error("boom");');
+
+ await act(async () => {
+ getExecuteButton(container!).dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(TestExecutionState.codes).toEqual(['throw new Error("boom");']);
+ expect(TestMessageState.messages).toMatchObject([
+ { content: 'Execution Failed', type: MessageType.Error },
+ ]);
+ });
+
+ it('holds shortcut escape while the editor is focused and releases it after blur or unmount', async () => {
+ currentTestBed = createPanelTestBed();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await renderPanel(root, currentTestBed.injector);
+
+ act(() => {
+ getEditor().focus();
+ });
+ expect(TestShortcutState.startedEscapes).toBe(1);
+ expect(TestShortcutState.activeEscapes).toBe(1);
+
+ act(() => {
+ getEditor().blur();
+ });
+ expect(TestShortcutState.activeEscapes).toBe(0);
+ expect(TestShortcutState.releasedEscapes).toBe(1);
+
+ act(() => {
+ getEditor().focus();
+ });
+ expect(TestShortcutState.activeEscapes).toBe(1);
+
+ act(() => {
+ root?.unmount();
+ });
+ expect(TestShortcutState.activeEscapes).toBe(0);
+ expect(TestShortcutState.releasedEscapes).toBe(2);
+ expect(currentTestBed.editorService.getEditorInstance()).toBeNull();
+ });
+});
diff --git a/packages/watermark/src/facade/f-univer.spec.ts b/packages/watermark/src/facade/f-univer.spec.ts
index c2a18be74c..bf457ef723 100644
--- a/packages/watermark/src/facade/f-univer.spec.ts
+++ b/packages/watermark/src/facade/f-univer.spec.ts
@@ -14,92 +14,91 @@
* limitations under the License.
*/
-import { describe, expect, it, vi } from 'vitest';
-
-const mocked = vi.hoisted(() => ({
- extendUniver: vi.fn(),
- extendEnum: vi.fn(),
- IWatermarkTypeEnum: {
- Text: 'text',
- Image: 'image',
- },
-}));
-
-vi.mock('@univerjs/core/facade', () => {
- class FUniver {
- static extend = mocked.extendUniver;
- }
- class FEnum {
- static extend = mocked.extendEnum;
+import { Injector } from '@univerjs/core';
+import { FEnum, FUniver } from '@univerjs/core/facade';
+import { IWatermarkTypeEnum } from '@univerjs/engine-render';
+import { WatermarkService, WatermarkTextBaseConfig } from '@univerjs/watermark';
+import { describe, expect, it } from 'vitest';
+import { FUniverWatermarkMixin, FWatermarkEnumMixin } from './f-univer';
+
+class TestWatermarkService {
+ readonly updatedConfigs: unknown[] = [];
+ deleteCount = 0;
+
+ updateWatermarkConfig(config: unknown): void {
+ this.updatedConfigs.push(config);
}
- return {
- FUniver,
- FEnum,
- };
-});
-
-vi.mock('@univerjs/engine-render', () => ({
- IWatermarkTypeEnum: mocked.IWatermarkTypeEnum,
-}));
-
-class MockWatermarkService {}
-
-vi.mock('@univerjs/watermark', () => ({
- WatermarkTextBaseConfig: { content: '', repeat: true },
- WatermarkImageBaseConfig: { url: '', width: 100 },
- WatermarkService: MockWatermarkService,
-}));
+ deleteWatermarkConfig(): void {
+ this.deleteCount += 1;
+ }
+}
describe('watermark facade', () => {
- it('should register facade mixins and support add/delete watermark', async () => {
- const module = await import('./f-univer');
-
- expect(mocked.extendUniver).toHaveBeenCalledWith(module.FUniverWatermarkMixin);
- expect(mocked.extendEnum).toHaveBeenCalledWith(module.FWatermarkEnumMixin);
-
- const updateWatermarkConfig = vi.fn();
- const deleteWatermarkConfig = vi.fn();
+ it('adds text and image watermarks through the injected watermark service', () => {
+ const injector = new Injector();
+ injector.add([WatermarkService, { useClass: TestWatermarkService as never }]);
+ const service = injector.get(WatermarkService) as unknown as TestWatermarkService;
const thisArg = {
- _injector: {
- get: vi.fn(() => ({ updateWatermarkConfig, deleteWatermarkConfig })),
- },
+ _injector: injector,
};
+ const addWatermark = FUniverWatermarkMixin.prototype.addWatermark as (
+ this: typeof thisArg,
+ type: IWatermarkTypeEnum,
+ config: unknown
+ ) => FUniver;
- const textResult = module.FUniverWatermarkMixin.prototype.addWatermark.call(
+ expect(addWatermark.call(
thisArg,
- mocked.IWatermarkTypeEnum.Text as never,
- { content: 'hello' } as never
- );
- expect(textResult).toBe(thisArg);
- expect(updateWatermarkConfig).toHaveBeenCalledWith({
- type: mocked.IWatermarkTypeEnum.Text,
- config: { text: { content: 'hello', repeat: true } },
+ IWatermarkTypeEnum.Text,
+ { content: 'Confidential' } as never
+ )).toBe(thisArg);
+ expect(service.updatedConfigs.at(-1)).toEqual({
+ type: IWatermarkTypeEnum.Text,
+ config: {
+ text: {
+ ...WatermarkTextBaseConfig,
+ content: 'Confidential',
+ },
+ },
});
- module.FUniverWatermarkMixin.prototype.addWatermark.call(
+ addWatermark.call(
thisArg,
- mocked.IWatermarkTypeEnum.Image as never,
- { url: 'https://img' } as never
+ IWatermarkTypeEnum.Image,
+ { url: 'https://example.com/watermark.png', width: 320 } as never
);
- expect(updateWatermarkConfig).toHaveBeenCalledWith({
- type: mocked.IWatermarkTypeEnum.Image,
- config: { image: { url: 'https://img', width: 100 } },
+ expect(service.updatedConfigs.at(-1)).toMatchObject({
+ type: IWatermarkTypeEnum.Image,
+ config: {
+ image: {
+ url: 'https://example.com/watermark.png',
+ width: 320,
+ },
+ },
});
+ });
+
+ it('deletes watermark config, rejects unknown types and exposes watermark enum on real facade classes', () => {
+ const injector = new Injector();
+ injector.add([WatermarkService, { useClass: TestWatermarkService as never }]);
+ const service = injector.get(WatermarkService) as unknown as TestWatermarkService;
+ const thisArg = {
+ _injector: injector,
+ };
+ const addWatermark = FUniverWatermarkMixin.prototype.addWatermark as (
+ this: typeof thisArg,
+ type: IWatermarkTypeEnum,
+ config: unknown
+ ) => FUniver;
expect(() =>
- module.FUniverWatermarkMixin.prototype.addWatermark.call(thisArg, 'unknown' as never, {} as never)
+ addWatermark.call(thisArg, 'unknown' as never, {} as never)
).toThrow('Unknown watermark type');
-
- const deleteResult = module.FUniverWatermarkMixin.prototype.deleteWatermark.call(thisArg);
- expect(deleteResult).toBe(thisArg);
- expect(deleteWatermarkConfig).toHaveBeenCalledTimes(1);
-
- const enumObj = new module.FWatermarkEnumMixin();
- expect(enumObj.IWatermarkTypeEnum).toBe(mocked.IWatermarkTypeEnum);
- });
-
- it('should run facade entry export', async () => {
- await expect(import('./index')).resolves.toBeDefined();
+ expect(FUniverWatermarkMixin.prototype.deleteWatermark.call(thisArg as never)).toBe(thisArg);
+ expect(service.deleteCount).toBe(1);
+ expect(FEnum.get().IWatermarkTypeEnum).toBe(IWatermarkTypeEnum);
+ expect(Object.create(FWatermarkEnumMixin.prototype).IWatermarkTypeEnum).toBe(IWatermarkTypeEnum);
+ expect(typeof FUniver.prototype.addWatermark).toBe('function');
});
});