Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
refactor: extract icon & component registration into dedicated controllers (#7091)
白熱3c35a9b36968
diff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.pngindex 878eb45f22..e46e723891 100644Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/dark-mode-ci-chromium-linux.png differdiff --git a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.pngindex c6242180d4..b136cda94b 100644Binary files a/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png and b/e2e/visual-comparison/sheets/sheets-visual-comparison.spec.ts-snapshots/default-sheet-fullpage-ci-chromium-linux.png differdiff --git a/examples/src/sheets/custom/custom-float-dom/component.tsx b/examples/src/sheets/custom/custom-float-dom/component.tsxindex 7eae5b20b1..e8056b5852 100644--- a/examples/src/sheets/custom/custom-float-dom/component.tsx+++ b/examples/src/sheets/custom/custom-float-dom/component.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-export const RangeLoading = () => {+export const CustomRangeLoading = () => {const divStyle = {width: '100%',height: '100%',@@ -30,7 +30,7 @@ export const RangeLoading = () => {return (<div style={divStyle}>- Loading...+ Custom Loading...</div>);};diff --git a/examples/src/sheets/custom/custom-float-dom/float-dom.ts b/examples/src/sheets/custom/custom-float-dom/float-dom.tsindex 9a9462381c..7f95657e70 100644--- a/examples/src/sheets/custom/custom-float-dom/float-dom.ts+++ b/examples/src/sheets/custom/custom-float-dom/float-dom.ts@@ -16,17 +16,17 @@import type { Univer } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';-import { RangeLoading } from './component';+import { CustomRangeLoading } from './component';export function insertFloatDom(univer: Univer, univerAPI: FUniver) {univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => {if (stage === univerAPI.Enum.LifecycleStages.Steady) {- univerAPI.registerComponent('RangeLoading', RangeLoading);+ univerAPI.registerComponent('CustomRangeLoading', CustomRangeLoading);const fWorkbook = univerAPI.getActiveWorkbook()!;const fWorksheet = fWorkbook.getActiveSheet();const fRange = fWorksheet.getRange('A1:C3');- const disposable = fWorksheet.addFloatDomToRange(fRange, { componentKey: 'RangeLoading' }, {}, 'myRangeLoading');+ const disposable = fWorksheet.addFloatDomToRange(fRange, { componentKey: 'CustomRangeLoading' }, {}, 'myRangeLoading');console.warn('Float DOM', disposable);// remove float dom// if (disposable) {diff --git a/packages/action-recorder/src/controllers/action-recorder.controller.spec.tsx b/packages/action-recorder/src/controllers/action-recorder.controller.spec.tsxdeleted file mode 100644index 6d707941b5..0000000000--- a/packages/action-recorder/src/controllers/action-recorder.controller.spec.tsx+++ /dev/null@@ -1,79 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import { BehaviorSubject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';-import { CompleteRecordingActionCommand, StartRecordingActionCommand, StopRecordingActionCommand } from '../commands/commands/record.command';-import { ReplayLocalRecordCommand, ReplayLocalRecordOnActiveCommand, ReplayLocalRecordOnNamesakeCommand } from '../commands/commands/replay.command';-import { CloseRecordPanelOperation, OpenRecordPanelOperation } from '../commands/operations/operation';-import { menuSchema, OpenRecorderMenuItemFactory, RECORD_MENU_ITEM_ID, RecordMenuItemFactory, ReplayLocalRecordMenuItemFactory, ReplayLocalRecordOnActiveMenuItemFactory, ReplayLocalRecordOnNamesakeMenuItemFactory } from '../menu/action-recorder.menu';-import { ActionRecorderController } from './action-recorder.controller';--describe('action-recorder controller/menu', () => {- it('should create menu items', () => {- const recordItem = RecordMenuItemFactory();- expect(recordItem.id).toBe(RECORD_MENU_ITEM_ID);-- const panelOpened$ = new BehaviorSubject(false);- const openItem = OpenRecorderMenuItemFactory({- get: vi.fn(() => ({ panelOpened$: panelOpened$.asObservable() })),- } as never);- expect(openItem.id).toBe(OpenRecordPanelOperation.id);- expect(openItem.disabled$).toBeDefined();-- expect(ReplayLocalRecordMenuItemFactory().id).toBe(ReplayLocalRecordCommand.id);- expect(ReplayLocalRecordOnNamesakeMenuItemFactory().id).toBe(ReplayLocalRecordOnNamesakeCommand.id);- expect(ReplayLocalRecordOnActiveMenuItemFactory().id).toBe(ReplayLocalRecordOnActiveCommand.id);- expect(Object.keys(menuSchema).length).toBeGreaterThan(0);- });-- it('should register commands/ui/menu and sheet-recorded commands', () => {- const registerCommand = vi.fn();- const registerComponent = vi.fn();- const mergeMenu = vi.fn();- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));- const registerRecordedCommand = vi.fn();-- const controller = new ActionRecorderController(- { registerCommand } as never,- { registerComponent } as never,- { mergeMenu } as never,- { register: registerIcon } as never,- { registerRecordedCommand } as never,- {} as never- );-- expect(registerCommand).toHaveBeenCalledWith(StartRecordingActionCommand);- expect(registerCommand).toHaveBeenCalledWith(StopRecordingActionCommand);- expect(registerCommand).toHaveBeenCalledWith(CompleteRecordingActionCommand);- expect(registerCommand).toHaveBeenCalledWith(OpenRecordPanelOperation);- expect(registerCommand).toHaveBeenCalledWith(CloseRecordPanelOperation);- expect(registerCommand).toHaveBeenCalledWith(ReplayLocalRecordCommand);- expect(registerCommand).toHaveBeenCalledWith(ReplayLocalRecordOnNamesakeCommand);- expect(registerCommand).toHaveBeenCalledWith(ReplayLocalRecordOnActiveCommand);-- expect(registerComponent).toHaveBeenCalledTimes(1);- const componentFactory = registerComponent.mock.calls[0][1] as () => unknown;- expect(componentFactory()).toBeDefined();-- expect(mergeMenu).toHaveBeenCalledWith(menuSchema);-- expect(registerRecordedCommand).toHaveBeenCalled();- expect(registerRecordedCommand.mock.calls.length).toBeGreaterThan(20);-- controller.dispose();- });-});diff --git a/packages/action-recorder/src/controllers/action-recorder.controller.ts b/packages/action-recorder/src/controllers/action-recorder.controller.tsindex f23efcb164..139ec638d0 100644--- a/packages/action-recorder/src/controllers/action-recorder.controller.ts+++ b/packages/action-recorder/src/controllers/action-recorder.controller.ts@@ -15,7 +15,6 @@*/import { Disposable, ICommandService, Inject, Injector } from '@univerjs/core';-import { RecordIcon } from '@univerjs/icons';import {AddWorksheetMergeAllCommand,AddWorksheetMergeCommand,@@ -72,7 +71,6 @@ import {import {BuiltInUIPart,connectInjector,- IconManager,IMenuManagerService,IUIPartsService,} from '@univerjs/ui';@@ -88,7 +86,6 @@ export class ActionRecorderController extends Disposable {@ICommandService private readonly _commandSrv: ICommandService,@IUIPartsService private readonly _uiPartsSrv: IUIPartsService,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,- @Inject(IconManager) private readonly _iconManager: IconManager,@Inject(ActionRecorderService) private readonly _actionRecorderService: ActionRecorderService,@Inject(Injector) private readonly _injector: Injector) {@@ -96,7 +93,6 @@ export class ActionRecorderController extends Disposable {this._initCommands();this._initUI();- this._registerIcons();this._initSheetsCommands();this._initDocsCommands();}@@ -119,12 +115,6 @@ export class ActionRecorderController extends Disposable {this._menuManagerService.mergeMenu(menuSchema);}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- RecordIcon,- }));- }-private _initSheetsCommands(): void {([// InsertColCommand,diff --git a/packages/action-recorder/src/controllers/components.controller.ts b/packages/action-recorder/src/controllers/components.controller.tsnew file mode 100644index 0000000000..fe5b01a3fb--- /dev/null+++ b/packages/action-recorder/src/controllers/components.controller.ts@@ -0,0 +1,36 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { RecordIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerIcons();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ RecordIcon,+ }));+ }+}diff --git a/packages/action-recorder/src/plugin.ts b/packages/action-recorder/src/plugin.tsindex 1ec480e059..428a7ad205 100644--- a/packages/action-recorder/src/plugin.ts+++ b/packages/action-recorder/src/plugin.ts@@ -20,6 +20,7 @@ import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core'import pkg from '../package.json';import { ACTION_RECORDER_PLUGIN_CONFIG_KEY, defaultPluginConfig } from './config/config';import { ActionRecorderController } from './controllers/action-recorder.controller';+import { ComponentsController } from './controllers/components.controller';import { ActionRecorderService } from './services/action-recorder.service';import { ActionReplayService } from './services/replay.service';@@ -52,6 +53,8 @@ export class UniverActionRecorderPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);const dependency = this._config.replayOnly? [[ActionReplayService]]: [diff --git a/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.ts b/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.tsnew file mode 100644index 0000000000..8a589783a5--- /dev/null+++ b/packages/core/src/services/authz-io/__tests__/authz-io-local.service.spec.ts@@ -0,0 +1,59 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { UnitObject } from '@univerjs/protocol';+import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { IResourceManagerService } from '../../resource-manager/type';+import { UserManagerService } from '../../user-manager/user-manager.service';+import { AuthzIoLocalService } from '../authz-io-local.service';++describe('AuthzIoLocalService', () => {+ let service: AuthzIoLocalService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IResourceManagerService, { useValue: { registerPluginResource: () => ({ dispose: () => {} }) } as unknown as IResourceManagerService }]);+ injector.add([UserManagerService]);+ injector.add([AuthzIoLocalService]);+ service = injector.get(AuthzIoLocalService);+ });++ it('creates range permission objects and evaluates default owner actions', async () => {+ const objectID = await service.create({+ objectType: UnitObject.SelectRange,+ selectRangeObject: { unitID: 'book-1', name: 'Protected range' },+ } as never);++ await expect(service.allowed({ unitID: 'book-1', objectID, actions: [6, 16] } as never)).resolves.toEqual([+ { action: 6, allowed: true },+ { action: 16, allowed: true },+ ]);+ });++ it('lists created permission objects with their range metadata', async () => {+ const objectID = await service.create({+ objectType: UnitObject.SelectRange,+ selectRangeObject: { unitID: 'book-1', name: 'Protected range' },+ } as never);++ const [permissionPoint] = await service.list({ unitID: 'book-1', objectIDs: [objectID], actions: [6] } as never);++ expect(permissionPoint.objectID).toBe(objectID);+ expect(permissionPoint.name).toBe('Protected range');+ expect(permissionPoint.unitID).toBe('book-1');+ });+});diff --git a/packages/core/src/services/config/config.service.ts b/packages/core/src/services/config/config.service.tsindex 811578b649..073dfa1df3 100644--- a/packages/core/src/services/config/config.service.ts+++ b/packages/core/src/services/config/config.service.ts@@ -15,7 +15,6 @@*/import type { IDisposable } from '../../common/di';-import type { Nullable } from '../../shared/types';import { filter, Observable, Subject } from 'rxjs';import { createIdentifier } from '../../common/di';import { merge } from '../../common/lodash';@@ -43,7 +42,7 @@ interface IConfigOptions {}export interface IConfigService {- getConfig<T>(id: string | symbol): Nullable<T>;+ getConfig<T>(id: string | symbol): T;setConfig(id: string | symbol, value: unknown, options?: IConfigOptions): void;deleteConfig(id: string): boolean;subscribeConfigValue$<T = unknown>(key: string): Observable<T>;@@ -61,7 +60,7 @@ export class ConfigService implements IConfigService, IDisposable {this._configChanged$.complete();}- getConfig<T>(id: string | symbol): Nullable<T> {+ getConfig<T>(id: string | symbol): T {return this._config.get(id) as T;}diff --git a/packages/core/src/services/error/__tests__/error.service.spec.ts b/packages/core/src/services/error/__tests__/error.service.spec.tsnew file mode 100644index 0000000000..dc9de41382--- /dev/null+++ b/packages/core/src/services/error/__tests__/error.service.spec.ts@@ -0,0 +1,39 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { ErrorService } from '../error.service';++describe('ErrorService', () => {+ let service: ErrorService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ErrorService]);+ service = injector.get(ErrorService);+ });++ it('emits business error keys to subscribers in order', () => {+ const errors: string[] = [];+ service.error$.subscribe((error) => errors.push(error.errorKey));++ service.emit('permission-denied');+ service.emit('network-timeout');++ expect(errors).toEqual(['permission-denied', 'network-timeout']);+ });+});diff --git a/packages/core/src/services/mention-io/__tests__/mention-io-local.service.spec.ts b/packages/core/src/services/mention-io/__tests__/mention-io-local.service.spec.tsnew file mode 100644index 0000000000..a26a4d3c1a--- /dev/null+++ b/packages/core/src/services/mention-io/__tests__/mention-io-local.service.spec.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { MentionType } from '../../../types/enum';+import { UserManagerService } from '../../user-manager/user-manager.service';+import { MentionIOLocalService } from '../mention-io-local.service';++describe('MentionIOLocalService', () => {+ let service: MentionIOLocalService;+ let userManagerService: UserManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([UserManagerService]);+ injector.add([MentionIOLocalService]);+ service = injector.get(MentionIOLocalService);+ userManagerService = injector.get(UserManagerService);+ });++ it('returns the current collaborator as the local mention candidate', async () => {+ userManagerService.setCurrentUser({ userID: 'u-1', name: 'Ada', avatar: 'avatar.png' });++ const response = await service.list({ page: 3, size: 20, search: 'Ada' });++ expect(response.page).toBe(3);+ expect(response.size).toBe(20);+ expect(response.total).toBe(1);+ expect(response.list[0].type).toBe(MentionType.PERSON);+ expect(response.list[0].mentions[0]).toMatchObject({+ objectType: MentionType.PERSON,+ objectId: 'u-1',+ label: 'Ada',+ metadata: { icon: 'avatar.png' },+ });+ });+});diff --git a/packages/core/src/services/permission/__tests__/permission.service.spec.ts b/packages/core/src/services/permission/__tests__/permission.service.spec.tsnew file mode 100644index 0000000000..0064a2401f--- /dev/null+++ b/packages/core/src/services/permission/__tests__/permission.service.spec.ts@@ -0,0 +1,62 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IPermissionPoint } from '../type';+import { UnitAction, UnitObject } from '@univerjs/protocol';+import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { PermissionService } from '../permission.service';+import { PermissionStatus } from '../type';++describe('PermissionService', () => {+ let service: PermissionService;++ const permissionPoint = (id: string, value: boolean, status: PermissionStatus): IPermissionPoint => ({+ id,+ value,+ status,+ type: UnitObject.Workbook,+ subType: UnitAction.Edit,+ });++ beforeEach(() => {+ const injector = new Injector();+ injector.add([PermissionService]);+ service = injector.get(PermissionService);+ });++ it('updates a permission point and composes the latest decision set', () => {+ const updates: string[] = [];+ service.permissionPointUpdate$.subscribe((point) => updates.push(`${point.id}:${String(point.value)}`));++ expect(service.addPermissionPoint(permissionPoint('sheet-edit', false, PermissionStatus.INIT))).toBe(true);+ expect(service.addPermissionPoint(permissionPoint('sheet-view', true, PermissionStatus.DONE))).toBe(true);++ service.updatePermissionPoint('sheet-edit', true);++ expect(service.composePermission(['sheet-edit', 'sheet-view']).map((point) => point.value)).toEqual([true, true]);+ expect(service.getPermissionPoint('sheet-edit')?.status).toBe(PermissionStatus.DONE);+ expect(updates).toEqual(['sheet-edit:false', 'sheet-view:true', 'sheet-edit:true']);+ });++ it('removes permission decisions that no longer apply to the current document', () => {+ service.addPermissionPoint(permissionPoint('range-lock', true, PermissionStatus.DONE));+ service.deletePermissionPoint('range-lock');++ expect(service.getPermissionPoint('range-lock')).toBeUndefined();+ expect(() => service.composePermission(['range-lock'])).toThrow('[PermissionService]: range-lock permissionPoint does not exist!');+ });+});diff --git a/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.ts b/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.tsnew file mode 100644index 0000000000..92c6a7b58a--- /dev/null+++ b/packages/core/src/services/resource-loader/__tests__/resource-loader.service.spec.ts@@ -0,0 +1,109 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Subject } from 'rxjs';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { Injector } from '../../../common/di';+import { UniverInstanceType } from '../../../common/unit';+import { IUniverInstanceService } from '../../instance/instance.service';+import { IResourceManagerService } from '../../resource-manager/type';+import { ResourceLoaderService } from '../resource-loader.service';++describe('ResourceLoaderService', () => {+ let service: ResourceLoaderService;+ let register$: Subject<never>;+ let sheetAdded$: Subject<unknown>;+ let docAdded$: Subject<unknown>;+ let slideAdded$: Subject<unknown>;+ let sheetDisposed$: Subject<unknown>;+ let docDisposed$: Subject<unknown>;+ let slideDisposed$: Subject<unknown>;+ let resourceManagerService: {+ getAllResourceHooks: ReturnType<typeof vi.fn>;+ register$: Subject<never>;+ loadResources: ReturnType<typeof vi.fn>;+ unloadResources: ReturnType<typeof vi.fn>;+ getResources: ReturnType<typeof vi.fn>;+ };+ let univerInstanceService: {+ getAllUnitsForType: ReturnType<typeof vi.fn>;+ getTypeOfUnitAdded$: ReturnType<typeof vi.fn>;+ getTypeOfUnitDisposed$: ReturnType<typeof vi.fn>;+ getUnit: ReturnType<typeof vi.fn>;+ };++ beforeEach(() => {+ register$ = new Subject();+ sheetAdded$ = new Subject();+ docAdded$ = new Subject();+ slideAdded$ = new Subject();+ sheetDisposed$ = new Subject();+ docDisposed$ = new Subject();+ slideDisposed$ = new Subject();+ resourceManagerService = {+ getAllResourceHooks: vi.fn(() => []),+ register$,+ loadResources: vi.fn(),+ unloadResources: vi.fn(),+ getResources: vi.fn(() => [{ name: 'plugin', data: '{}' }]),+ };+ univerInstanceService = {+ getAllUnitsForType: vi.fn(() => []),+ getTypeOfUnitAdded$: vi.fn((type) => {+ if (type === UniverInstanceType.UNIVER_SHEET) return sheetAdded$;+ if (type === UniverInstanceType.UNIVER_DOC) return docAdded$;+ return slideAdded$;+ }),+ getTypeOfUnitDisposed$: vi.fn((type) => {+ if (type === UniverInstanceType.UNIVER_SHEET) return sheetDisposed$;+ if (type === UniverInstanceType.UNIVER_DOC) return docDisposed$;+ return slideDisposed$;+ }),+ getUnit: vi.fn(),+ };+ const injector = new Injector();+ injector.add([IResourceManagerService, { useValue: resourceManagerService as unknown as IResourceManagerService }]);+ injector.add([IUniverInstanceService, { useValue: univerInstanceService as unknown as IUniverInstanceService }]);+ injector.add([ResourceLoaderService]);+ service = injector.get(ResourceLoaderService);+ });++ it('loads resources when a workbook unit is added and unloads them when disposed', () => {+ const workbook = {+ getUnitId: () => 'book-1',+ getSnapshot: () => ({ resources: [{ name: 'sheet-plugin', data: '{}' }] }),+ };++ sheetAdded$.next({ unit: workbook });+ sheetDisposed$.next(workbook);++ expect(resourceManagerService.loadResources).toHaveBeenCalledWith('book-1', [{ name: 'sheet-plugin', data: '{}' }]);+ expect(resourceManagerService.unloadResources).toHaveBeenCalledWith('book-1', UniverInstanceType.UNIVER_SHEET);+ });++ it('saves a unit snapshot with current plugin resources', () => {+ univerInstanceService.getUnit.mockReturnValue({+ type: UniverInstanceType.UNIVER_SHEET,+ getSnapshot: () => ({ id: 'book-1', sheets: {} }),+ });++ expect(service.saveUnit('book-1')).toEqual({+ id: 'book-1',+ sheets: {},+ resources: [{ name: 'plugin', data: '{}' }],+ });+ });+});diff --git a/packages/core/src/services/theme/__tests__/theme.service.spec.ts b/packages/core/src/services/theme/__tests__/theme.service.spec.tsnew file mode 100644index 0000000000..e717a12053--- /dev/null+++ b/packages/core/src/services/theme/__tests__/theme.service.spec.ts@@ -0,0 +1,56 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { defaultTheme } from '@univerjs/themes';+import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { ThemeService } from '../theme.service';++describe('ThemeService', () => {+ let service: ThemeService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ThemeService]);+ service = injector.get(ThemeService);+ });++ it('publishes theme and dark-mode changes used by UI renderers', () => {+ const darkModes: boolean[] = [];+ const primaryColors: string[] = [];+ service.darkMode$.subscribe((darkMode) => darkModes.push(darkMode));+ service.currentTheme$.subscribe((theme) => primaryColors.push(theme.primary[600]));++ service.setDarkMode(true);+ service.setTheme({+ ...defaultTheme,+ primary: {+ ...defaultTheme.primary,+ 600: '#123456',+ },+ });++ expect(darkModes).toEqual([false, true]);+ expect(primaryColors).toEqual([defaultTheme.primary[600], '#123456']);+ expect(service.getColorFromTheme('primary.600')).toBe('#123456');+ });++ it('validates only theme color tokens that exist in the active theme shape', () => {+ expect(service.isValidThemeColor('primary.600')).toBe(true);+ expect(service.isValidThemeColor('missing.600')).toBe(false);+ expect(service.isValidThemeColor('primary.999')).toBe(false);+ });+});diff --git a/packages/core/src/services/user-manager/__tests__/user-manager.service.spec.ts b/packages/core/src/services/user-manager/__tests__/user-manager.service.spec.tsnew file mode 100644index 0000000000..f667db839e--- /dev/null+++ b/packages/core/src/services/user-manager/__tests__/user-manager.service.spec.ts@@ -0,0 +1,53 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { beforeEach, describe, expect, it } from 'vitest';+import { Injector } from '../../../common/di';+import { UserManagerService } from '../user-manager.service';++describe('UserManagerService', () => {+ let service: UserManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([UserManagerService]);+ service = injector.get(UserManagerService);+ });++ it('keeps the current collaborator in the user directory', () => {+ const events: string[] = [];+ service.userChange$.subscribe((event) => events.push(event.type));++ service.setCurrentUser({ userID: 'u-1', name: 'Ada' });++ expect(service.getCurrentUser().userID).toBe('u-1');+ expect(service.getUser('u-1')).toEqual({ userID: 'u-1', name: 'Ada' });+ expect(service.list()).toEqual([{ userID: 'u-1', name: 'Ada' }]);+ expect(events).toEqual(['add']);+ });++ it('emits directory changes when collaborators leave or the document closes', () => {+ const events: string[] = [];+ service.userChange$.subscribe((event) => events.push(event.type));++ service.addUser({ userID: 'u-1', name: 'Ada' });+ service.delete('u-1');+ service.clear();++ expect(service.list()).toEqual([]);+ expect(events).toEqual(['add', 'delete', 'clear']);+ });+});diff --git a/packages/data-validation/src/services/__tests__/data-validator-registry.service.spec.ts b/packages/data-validation/src/services/__tests__/data-validator-registry.service.spec.tsnew file mode 100644index 0000000000..849eb7cec5--- /dev/null+++ b/packages/data-validation/src/services/__tests__/data-validator-registry.service.spec.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { DataValidatorRegistryScope, DataValidatorRegistryService } from '../data-validator-registry.service';++describe('DataValidatorRegistryService', () => {+ let service: DataValidatorRegistryService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([DataValidatorRegistryService]);+ service = injector.get(DataValidatorRegistryService);+ });++ it('registers validators by business scope and unregisters them with the disposable', () => {+ const changes: number[] = [];+ service.validatorsChange$.subscribe(() => changes.push(1));+ const validator = { id: 'decimal', scopes: DataValidatorRegistryScope.SHEET };++ const disposable = service.register(validator as never);++ expect(service.getValidatorItem('decimal')).toBe(validator);+ expect(service.getValidatorsByScope(DataValidatorRegistryScope.SHEET)).toEqual([validator]);++ disposable.dispose();++ expect(service.getValidatorItem('decimal')).toBeUndefined();+ expect(service.getValidatorsByScope(DataValidatorRegistryScope.SHEET)).toEqual([]);+ expect(changes.length).toBe(3);+ });++ it('rejects duplicate validators in the same scope', () => {+ service.register({ id: 'decimal', scopes: DataValidatorRegistryScope.SHEET } as never);++ expect(() => service.register({ id: 'decimal', scopes: DataValidatorRegistryScope.SHEET } as never)).toThrow(+ 'Validator item with the same id decimal has already been added!'+ );+ });+});diff --git a/packages/docs-drawing-ui/src/controllers/components.controller.ts b/packages/docs-drawing-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..abc487d9ae--- /dev/null+++ b/packages/docs-drawing-ui/src/controllers/components.controller.ts@@ -0,0 +1,34 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { ComponentManager } from '@univerjs/ui';+import { COMPONENT_DOC_DRAWING_PANEL } from '../views/doc-image-panel/component-name';+import { DocDrawingPanel } from '../views/doc-image-panel/DocDrawingPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ ) {+ super();++ this._registerComponents();+ }++ private _registerComponents(): void {+ this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_DRAWING_PANEL, DocDrawingPanel));+ }+}diff --git a/packages/docs-drawing-ui/src/controllers/ui.controller.ts b/packages/docs-drawing-ui/src/controllers/ui.controller.tsindex a775149e13..7f45ebca43 100644--- a/packages/docs-drawing-ui/src/controllers/ui.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/ui.controller.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { ComponentManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';+import { Disposable, ICommandService } from '@univerjs/core';+import { IMenuManagerService, IShortcutService } from '@univerjs/ui';import { DeleteDocDrawingsCommand } from '../commands/commands/delete-doc-drawing.command';import { GroupDocDrawingCommand } from '../commands/commands/group-doc-drawing.command';import { InsertDocDrawingCommand } from '../commands/commands/insert-doc-drawing.command';@@ -37,8 +37,6 @@ import { ClearDocDrawingTransformerOperation } from '../commands/operations/cleaimport { EditDocDrawingOperation } from '../commands/operations/edit-doc-drawing.operation';import { SidebarDocDrawingOperation } from '../commands/operations/open-drawing-panel.operation';import { menuSchema } from '../menu/schema';-import { COMPONENT_DOC_DRAWING_PANEL } from '../views/doc-image-panel/component-name';-import { DocDrawingPanel } from '../views/doc-image-panel/DocDrawingPanel';import {DeleteDrawingsShortcutItem,MoveDrawingDownShortcutItem,@@ -49,7 +47,6 @@ import {export class DocDrawingUIController extends Disposable {constructor(- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@ICommandService private readonly _commandService: ICommandService,@IShortcutService private readonly _shortcutService: IShortcutService@@ -60,8 +57,6 @@ export class DocDrawingUIController extends Disposable {}private _initCustomComponents(): void {- const componentManager = this._componentManager;- this.disposeWithMe(componentManager.register(COMPONENT_DOC_DRAWING_PANEL, DocDrawingPanel));}private _initMenus(): void {diff --git a/packages/docs-drawing-ui/src/plugin.ts b/packages/docs-drawing-ui/src/plugin.tsindex 04d06d114a..3baa2cbafa 100644--- a/packages/docs-drawing-ui/src/plugin.ts+++ b/packages/docs-drawing-ui/src/plugin.ts@@ -24,6 +24,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { UniverUIPlugin } from '@univerjs/ui';import pkg from '../package.json';import { defaultPluginConfig, DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DocDrawingAddRemoveController } from './controllers/doc-drawing-notification.controller';import { DocDrawingPrintingController } from './controllers/doc-drawing-printing.controller';import { DocDrawingTransformerController } from './controllers/doc-drawing-transformer-update.controller';@@ -60,6 +61,7 @@ export class UniverDocsDrawingUIPlugin extends Plugin {override onStarting(): void {const dependencies: Dependency[] = [+ [ComponentsController],[DocDrawingUIController],[DocDrawingPopupMenuController],[DocDrawingTransformerController],@@ -70,6 +72,7 @@ export class UniverDocsDrawingUIPlugin extends Plugin {];dependencies.forEach((dependency) => this._injector.add(dependency));+ this._injector.get(ComponentsController);}override onReady(): void {diff --git a/packages/docs-drawing/src/services/__tests__/doc-drawing.service.spec.ts b/packages/docs-drawing/src/services/__tests__/doc-drawing.service.spec.tsnew file mode 100644index 0000000000..0842bbfef8--- /dev/null+++ b/packages/docs-drawing/src/services/__tests__/doc-drawing.service.spec.ts@@ -0,0 +1,47 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { DocDrawingService, IDocDrawingService } from '../doc-drawing.service';++describe('DocDrawingService', () => {+ let service: IDocDrawingService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IDocDrawingService, { useClass: DocDrawingService }]);+ service = injector.get(IDocDrawingService);+ });++ it('initializes document drawing data and notifies renderers about existing drawings', () => {+ const added: unknown[] = [];+ service.add$.subscribe((items) => added.push(items));+ service.registerDrawingData('doc-1', {+ page1: {+ data: {+ image1: { drawingId: 'image1' },+ },+ order: ['image1'],+ },+ } as never);++ service.initializeNotification('doc-1');++ expect(service.getDrawingData('doc-1', 'page1')?.image1.drawingId).toBe('image1');+ expect(added).toEqual([[{ drawingId: 'image1', unitId: 'doc-1', subUnitId: 'page1' }]]);+ });+});diff --git a/packages/docs-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/docs-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index bbd5f9f098..0000000000--- a/packages/docs-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,47 +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 { FLOAT_TOOLBAR_MENU_POSITION } from '@univerjs/docs-ui';-import { describe, expect, it, vi } from 'vitest';-import { DocHyperLinkEdit } from '../../views/DocHyperLinkEdit';-import { DocHyperLinkUIController } from '../ui.controller';--describe('DocHyperLinkUIController', () => {- it('creates the docs floating toolbar root before merging hyperlink menus', () => {- const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));- const registerCommand = vi.fn();- const appendRootMenu = vi.fn();- const mergeMenu = vi.fn();- const registerShortcut = vi.fn();-- const controller = new DocHyperLinkUIController(- { register: registerComponent } as any,- { register: registerIcon } as any,- { registerCommand } as any,- { appendRootMenu, mergeMenu } as any,- { registerShortcut } as any- );-- expect(registerComponent).toHaveBeenCalledWith(DocHyperLinkEdit.componentKey, DocHyperLinkEdit);- expect(appendRootMenu).toHaveBeenCalledWith({ [FLOAT_TOOLBAR_MENU_POSITION]: {} });- expect(mergeMenu).toHaveBeenCalled();- expect(appendRootMenu.mock.invocationCallOrder[0]).toBeLessThan(mergeMenu.mock.invocationCallOrder[0]);- expect(registerShortcut).toHaveBeenCalled();-- controller.dispose();- });-});diff --git a/packages/docs-hyper-link-ui/src/controllers/components.controller.ts b/packages/docs-hyper-link-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..88b347c513--- /dev/null+++ b/packages/docs-hyper-link-ui/src/controllers/components.controller.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 { Disposable, Inject } from '@univerjs/core';+import { LinkIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { DocHyperLinkEdit } from '../views/DocHyperLinkEdit';+import { DocLinkPopup } from '../views/DocLinkPopup';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [DocHyperLinkEdit.componentKey, DocHyperLinkEdit],+ [DocLinkPopup.componentKey, DocLinkPopup],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ LinkIcon,+ }));+ }+}diff --git a/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts b/packages/docs-hyper-link-ui/src/controllers/ui.controller.tsindex 214699abcb..c78c621546 100644--- a/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts+++ b/packages/docs-hyper-link-ui/src/controllers/ui.controller.ts@@ -15,18 +15,15 @@*/import type { MenuConfig } from '@univerjs/ui';-import { Disposable, ICommandService, Inject } from '@univerjs/core';+import { Disposable, ICommandService } from '@univerjs/core';import { FLOAT_TOOLBAR_MENU_POSITION } from '@univerjs/docs-ui';-import { LinkIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';+import { IMenuManagerService, IShortcutService } from '@univerjs/ui';import { AddDocHyperLinkCommand } from '../commands/commands/add-link.command';import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';import { UpdateDocHyperLinkCommand } from '../commands/commands/update-link.command';import { ClickDocHyperLinkOperation, ShowDocHyperLinkEditPopupOperation, ToggleDocHyperLinkInfoPopupOperation } from '../commands/operations/popup.operation';import { addLinkShortcut } from '../menu/menu';import { menuSchema } from '../menu/schema';-import { DocHyperLinkEdit } from '../views/DocHyperLinkEdit';-import { DocLinkPopup } from '../views/DocLinkPopup';export interface IDocHyperLinkUIConfig {menu: MenuConfig;@@ -34,38 +31,16 @@ export interface IDocHyperLinkUIConfig {export class DocHyperLinkUIController extends Disposable {constructor(- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@ICommandService private readonly _commandService: ICommandService,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@IShortcutService private readonly _shortcutService: IShortcutService) {super();-- this._initComponents();- this._registerIcons();this._initCommands();this._initMenus();this._initShortcut();}- private _initComponents() {- ([- [DocHyperLinkEdit.componentKey, DocHyperLinkEdit],- [DocLinkPopup.componentKey, DocLinkPopup],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- LinkIcon,- }));- }-private _initCommands() {[AddDocHyperLinkCommand,diff --git a/packages/docs-hyper-link-ui/src/plugin.ts b/packages/docs-hyper-link-ui/src/plugin.tsindex 5ac1d7d661..c81aabc43c 100644--- a/packages/docs-hyper-link-ui/src/plugin.ts+++ b/packages/docs-hyper-link-ui/src/plugin.ts@@ -21,6 +21,7 @@ import { UniverDocsHyperLinkPlugin } from '@univerjs/docs-hyper-link';import { IRenderManagerService } from '@univerjs/engine-render';import pkg from '../package.json';import { defaultPluginConfig, DOCS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DocHyperLinkSelectionController } from './controllers/doc-hyper-link-selection.controller';import { DocHyperLinkEventRenderController } from './controllers/render-controllers/hyper-link-event.render-controller';import { DocHyperLinkRenderController } from './controllers/render-controllers/render.controller';@@ -56,6 +57,8 @@ export class UniverDocsHyperLinkUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);const deps: Dependency[] = [[DocHyperLinkPopupService],[DocHyperLinkUIController],diff --git a/packages/docs-mention-ui/src/controllers/components.controller.ts b/packages/docs-mention-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..d21207e521--- /dev/null+++ b/packages/docs-mention-ui/src/controllers/components.controller.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 { Disposable, Inject } from '@univerjs/core';+import { ComponentManager } from '@univerjs/ui';+import { MentionEditPopup } from '../views/MentionEditPopup';++const components = [[MentionEditPopup.componentKey, MentionEditPopup]] as const;++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ ) {+ super();++ this._registerComponents();+ }++ private _registerComponents(): void {+ components.forEach(([key, comp]) => {+ this.disposeWithMe(this._componentManager.register(key, comp));+ });+ }+}diff --git a/packages/docs-mention-ui/src/controllers/ui.controller.ts b/packages/docs-mention-ui/src/controllers/ui.controller.tsindex 7df9568ead..08826dc3f1 100644--- a/packages/docs-mention-ui/src/controllers/ui.controller.ts+++ b/packages/docs-mention-ui/src/controllers/ui.controller.ts@@ -14,8 +14,7 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { ComponentManager } from '@univerjs/ui';+import { Disposable, ICommandService } from '@univerjs/core';import { AddDocMentionCommand, DeleteDocMentionCommand } from '../commands/commands/doc-mention.command';import {CloseMentionEditPopupOperation,@@ -23,17 +22,14 @@ import {ShowMentionEditPopupOperation,ShowMentionInfoPopupOperation,} from '../commands/operations/mention-popup.operation';-import { MentionEditPopup } from '../views/MentionEditPopup';export class DocMentionUIController extends Disposable {constructor(- @ICommandService private readonly _commandService: ICommandService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ @ICommandService private readonly _commandService: ICommandService) {super();this._initCommands();- this._initComponents();}private _initCommands() {@@ -48,12 +44,4 @@ export class DocMentionUIController extends Disposable {this.disposeWithMe(this._commandService.registerCommand(operation));});}-- private _initComponents() {- const components = [[MentionEditPopup.componentKey, MentionEditPopup]] as const;-- components.forEach(([key, comp]) => {- this.disposeWithMe(this._componentManager.register(key, comp));- });- }}diff --git a/packages/docs-mention-ui/src/plugin.ts b/packages/docs-mention-ui/src/plugin.tsindex 24e705f7b2..745b8654cb 100644--- a/packages/docs-mention-ui/src/plugin.ts+++ b/packages/docs-mention-ui/src/plugin.ts@@ -19,6 +19,7 @@ import type { IUniverDocsMentionUIConfig } from './config/config';import { IConfigService, Inject, Injector, merge, Plugin, UniverInstanceType } from '@univerjs/core';import pkg from '../package.json';import { defaultPluginConfig, DOCS_MENTION_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DocMentionTriggerController } from './controllers/doc-mention-trigger.controller';import { DocMentionUIController } from './controllers/ui.controller';import { DocMentionPopupService } from './services/doc-mention-popup.service';@@ -52,6 +53,7 @@ export class UniverDocsMentionUIPlugin extends Plugin {override onStarting(): void {([+ [ComponentsController],[DocMentionService],[DocMentionPopupService],[DocMentionUIController],@@ -61,6 +63,7 @@ export class UniverDocsMentionUIPlugin extends Plugin {});this._injector.get(DocMentionUIController);+ this._injector.get(ComponentsController);}override onRendered(): void {diff --git a/packages/docs-quick-insert-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/docs-quick-insert-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index 31d96bda0a..0000000000--- a/packages/docs-quick-insert-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,55 +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 { QuickInsertButton } from '../../views/QuickInsertButton';-import { DocQuickInsertUIController } from '../ui.controller';--describe('DocQuickInsertUIController', () => {- it('registers commands, components and the built-in slash popup', () => {- const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));- const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));- const unregisterPopup = vi.fn();- const registerPopup = vi.fn(() => unregisterPopup);-- const controller = new DocQuickInsertUIController(- { registerCommand } as never,- { registerPopup } as never,- { register: registerComponent } as never,- { register: registerIcon } as never- );-- expect(registerCommand).toHaveBeenCalledTimes(3);- expect(registerComponent).toHaveBeenCalledWith(QuickInsertButton.componentKey, QuickInsertButton);-- expect(registerPopup).toHaveBeenCalledTimes(1);-- const firstRegisterPopupCall = registerPopup.mock.calls[0] as unknown[] | undefined;- expect(firstRegisterPopupCall).toBeDefined();-- const slashPopup = firstRegisterPopupCall?.[0] as unknown as {- keyword: string;- preconditions: (params: { range: { startNodePosition?: { glyph?: number } } }) => boolean;- };- expect(slashPopup.keyword).toBe('/');- expect(slashPopup.preconditions({ range: { startNodePosition: { glyph: 0 } } })).toBe(true);- expect(slashPopup.preconditions({ range: { startNodePosition: { glyph: 2 } } })).toBe(false);-- controller.dispose();- expect(unregisterPopup).toHaveBeenCalledTimes(1);- });-});diff --git a/packages/docs-quick-insert-ui/src/controllers/components.controller.ts b/packages/docs-quick-insert-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..01d1515193--- /dev/null+++ b/packages/docs-quick-insert-ui/src/controllers/components.controller.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { DividerIcon, TextIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { KeywordInputPlaceholder } from '../views/KeywordInputPlaceholder';+import { QuickInsertButton } from '../views/QuickInsertButton';+import { QuickInsertPlaceholder } from '../views/QuickInsertPlaceholder';+import { QuickInsertPopup } from '../views/QuickInsertPopup';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerIcons();+ this._registerComponents();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ DividerIcon,+ TextIcon,+ }));+ }++ private _registerComponents(): void {+ ([+ [QuickInsertPopup.componentKey, QuickInsertPopup],+ [KeywordInputPlaceholder.componentKey, KeywordInputPlaceholder],+ [QuickInsertPlaceholder.componentKey, QuickInsertPlaceholder],+ [QuickInsertButton.componentKey, QuickInsertButton],+ ] as const).forEach(([key, comp]) => {+ if (key) {+ this.disposeWithMe(this._componentManager.register(key, comp));+ }+ });+ }+}diff --git a/packages/docs-quick-insert-ui/src/controllers/ui.controller.ts b/packages/docs-quick-insert-ui/src/controllers/ui.controller.tsindex 20333d0640..6160be9314 100644--- a/packages/docs-quick-insert-ui/src/controllers/ui.controller.ts+++ b/packages/docs-quick-insert-ui/src/controllers/ui.controller.ts@@ -17,30 +17,21 @@import type { ITextRangeWithStyle } from '@univerjs/engine-render';import type { IDocPopup } from '../services/doc-quick-insert-popup.service';import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { DividerIcon, TextIcon } from '@univerjs/icons';-import { ComponentManager, IconManager } from '@univerjs/ui';import { of } from 'rxjs';import { DeleteSearchKeyCommand } from '../commands/commands/doc-quick-insert.command';import { CloseQuickInsertPopupOperation, ShowQuickInsertPopupOperation } from '../commands/operations/quick-insert-popup.operation';import { builtInMenus } from '../menu/menu';import { DocQuickInsertPopupService } from '../services/doc-quick-insert-popup.service';-import { KeywordInputPlaceholder } from '../views/KeywordInputPlaceholder';-import { QuickInsertButton } from '../views/QuickInsertButton';-import { QuickInsertPlaceholder } from '../views/QuickInsertPlaceholder';-import { QuickInsertPopup } from '../views/QuickInsertPopup';export class DocQuickInsertUIController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,- @Inject(DocQuickInsertPopupService) private readonly _docQuickInsertPopupService: DocQuickInsertPopupService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @Inject(DocQuickInsertPopupService) private readonly _docQuickInsertPopupService: DocQuickInsertPopupService) {super();this._initCommands();this._initComponents();- this._registerIcons();this._initMenus();}@@ -55,17 +46,6 @@ export class DocQuickInsertUIController extends Disposable {}private _initComponents() {- ([- [QuickInsertPopup.componentKey, QuickInsertPopup],- [KeywordInputPlaceholder.componentKey, KeywordInputPlaceholder],- [QuickInsertPlaceholder.componentKey, QuickInsertPlaceholder],- [QuickInsertButton.componentKey, QuickInsertButton],- ] as const).forEach(([key, comp]) => {- if (key) {- this.disposeWithMe(this._componentManager.register(key, comp));- }- });-const popups: IDocPopup[] = [{keyword: '/',@@ -83,11 +63,4 @@ export class DocQuickInsertUIController extends Disposable {private _initMenus() {}-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- DividerIcon,- TextIcon,- }));- }}diff --git a/packages/docs-quick-insert-ui/src/plugin.ts b/packages/docs-quick-insert-ui/src/plugin.tsindex 0825c88c0a..036d996c04 100644--- a/packages/docs-quick-insert-ui/src/plugin.ts+++ b/packages/docs-quick-insert-ui/src/plugin.ts@@ -25,6 +25,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { UniverUIPlugin } from '@univerjs/ui';import pkg from '../package.json';import { defaultPluginConfig, DOCS_QUICK_INSERT_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DocQuickInsertTriggerController } from './controllers/doc-quick-insert-trigger.controller';import { DocQuickInsertUIController } from './controllers/ui.controller';import { DocQuickInsertMenuController } from './menu/doc-quick-insert-menu.controller';@@ -58,6 +59,8 @@ export class UniverDocsQuickInsertUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);const dependencies: Dependency[] = [[DocQuickInsertUIController],[DocQuickInsertTriggerController],diff --git a/packages/docs-thread-comment-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index 7a4b9cc29f..0000000000--- a/packages/docs-thread-comment-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,46 +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 { FLOAT_TOOLBAR_MENU_POSITION } from '@univerjs/docs-ui';-import { describe, expect, it, vi } from 'vitest';-import { DOCS_THREAD_COMMENT_PANEL } from '../../common/const';-import { DocThreadCommentPanel } from '../../views/DocThreadCommentPanel';-import { DocThreadCommentUIController } from '../ui.controller';--describe('DocThreadCommentUIController', () => {- it('should register commands, menus and components', () => {- const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));- const mergeMenu = vi.fn();- const appendRootMenu = vi.fn();- const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));-- const controller = new DocThreadCommentUIController(- { registerCommand } as any,- { appendRootMenu, mergeMenu } as any,- { register: registerComponent } as any,- { register: registerIcon } as any- );-- expect(registerCommand).toHaveBeenCalled();- expect(appendRootMenu).toHaveBeenCalledWith({ [FLOAT_TOOLBAR_MENU_POSITION]: {} });- expect(mergeMenu).toHaveBeenCalled();- expect(appendRootMenu.mock.invocationCallOrder[0]).toBeLessThan(mergeMenu.mock.invocationCallOrder[0]);- expect(registerComponent).toHaveBeenCalledWith(DOCS_THREAD_COMMENT_PANEL, DocThreadCommentPanel);-- controller.dispose();- });-});diff --git a/packages/docs-thread-comment-ui/src/controllers/components.controller.ts b/packages/docs-thread-comment-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..2317faf2eb--- /dev/null+++ b/packages/docs-thread-comment-ui/src/controllers/components.controller.ts@@ -0,0 +1,49 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { CommentIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { DOCS_THREAD_COMMENT_PANEL } from '../common/const';+import { DocThreadCommentPanel } from '../views/DocThreadCommentPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [DOCS_THREAD_COMMENT_PANEL, DocThreadCommentPanel],+ ] as const).forEach(([id, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(id, comp)+ );+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ CommentIcon,+ }));+ }+}diff --git a/packages/docs-thread-comment-ui/src/controllers/ui.controller.ts b/packages/docs-thread-comment-ui/src/controllers/ui.controller.tsindex 0cea0a64bf..60d09b921e 100644--- a/packages/docs-thread-comment-ui/src/controllers/ui.controller.ts+++ b/packages/docs-thread-comment-ui/src/controllers/ui.controller.ts@@ -14,10 +14,9 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';+import { Disposable, ICommandService } from '@univerjs/core';import { FLOAT_TOOLBAR_MENU_POSITION } from '@univerjs/docs-ui';-import { CommentIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IMenuManagerService } from '@univerjs/ui';+import { IMenuManagerService } from '@univerjs/ui';import { AddDocCommentComment } from '../commands/commands/add-doc-comment.command';import { DeleteDocCommentComment } from '../commands/commands/delete-doc-comment.command';import {@@ -25,22 +24,16 @@ import {StartAddCommentOperation,ToggleCommentPanelOperation,} from '../commands/operations/show-comment-panel.operation';-import { DOCS_THREAD_COMMENT_PANEL } from '../common/const';import { menuSchema } from '../menu/schema';-import { DocThreadCommentPanel } from '../views/DocThreadCommentPanel';export class DocThreadCommentUIController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,- @IMenuManagerService private readonly _menuManagerService: IMenuManagerService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @IMenuManagerService private readonly _menuManagerService: IMenuManagerService) {super();this._initCommands();this._initMenus();- this._initComponents();- this._registerIcons();}private _initCommands() {@@ -59,20 +52,4 @@ export class DocThreadCommentUIController extends Disposable {this._menuManagerService.appendRootMenu({ [FLOAT_TOOLBAR_MENU_POSITION]: {} });this._menuManagerService.mergeMenu(menuSchema);}-- private _initComponents() {- ([- [DOCS_THREAD_COMMENT_PANEL, DocThreadCommentPanel],- ] as const).forEach(([id, comp]) => {- this.disposeWithMe(- this._componentManager.register(id, comp)- );- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- CommentIcon,- }));- }}diff --git a/packages/docs-thread-comment-ui/src/plugin.ts b/packages/docs-thread-comment-ui/src/plugin.tsindex 87c19f26f7..b53d01773a 100644--- a/packages/docs-thread-comment-ui/src/plugin.ts+++ b/packages/docs-thread-comment-ui/src/plugin.ts@@ -22,6 +22,7 @@ import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';import pkg from '../package.json';import { PLUGIN_NAME } from './common/const';import { defaultPluginConfig, DOCS_THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DocThreadCommentSelectionController } from './controllers/doc-thread-comment-selection.controller';import { DocThreadCommentRenderController } from './controllers/render-controllers/render.controller';import { DocThreadCommentUIController } from './controllers/ui.controller';@@ -55,6 +56,8 @@ export class UniverDocsThreadCommentUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[DocThreadCommentUIController],[DocThreadCommentSelectionController],diff --git a/packages/docs-ui/src/controllers/components.controller.ts b/packages/docs-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..68121638cd--- /dev/null+++ b/packages/docs-ui/src/controllers/components.controller.ts@@ -0,0 +1,150 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { AddImageIcon, AlignTextBothIcon, BoldIcon, CopyDoubleIcon, CutIcon, DeleteColumnDoubleIcon, DeleteIcon, DeleteRowDoubleIcon, DocSettingIcon, FontColorDoubleIcon, GridIcon, H1Icon, H2Icon, H3Icon, H4Icon, H5Icon, HeaderFooterIcon, HorizontallyIcon, InsertDoubleIcon, InsertRowAboveDoubleIcon, InsertRowBelowDoubleIcon, ItalicIcon, KeyboardIcon, LeftInsertColumnDoubleIcon, LeftJustifyingIcon, MenuIcon, MoreLeftIcon, MoreRightIcon, NoColorDoubleIcon, OrderIcon, PaintBucketDoubleIcon, PasteSpecialDoubleIcon, ReduceDoubleIcon, ReduceIcon, RightInsertColumnDoubleIcon, RightJustifyingIcon, ShapeIcon, StrikethroughIcon, SubscriptIcon, SuperscriptIcon, TextTypeIcon, TodoListDoubleIcon, UnderlineIcon, UnorderIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../views/header-footer/panel/component-name';+import { DocHeaderFooterPanel } from '../views/header-footer/panel/DocHeaderFooterPanel';+import { DefaultTextColorIcon, DocParagraphBackgroundColorSwatchIcon0, DocParagraphBackgroundColorSwatchIcon1, DocParagraphBackgroundColorSwatchIcon10, DocParagraphBackgroundColorSwatchIcon11, DocParagraphBackgroundColorSwatchIcon12, DocParagraphBackgroundColorSwatchIcon13, DocParagraphBackgroundColorSwatchIcon14, DocParagraphBackgroundColorSwatchIcon15, DocParagraphBackgroundColorSwatchIcon2, DocParagraphBackgroundColorSwatchIcon3, DocParagraphBackgroundColorSwatchIcon4, DocParagraphBackgroundColorSwatchIcon5, DocParagraphBackgroundColorSwatchIcon6, DocParagraphBackgroundColorSwatchIcon7, DocParagraphBackgroundColorSwatchIcon8, DocParagraphBackgroundColorSwatchIcon9, DocParagraphTextColorSwatchIcon0, DocParagraphTextColorSwatchIcon1, DocParagraphTextColorSwatchIcon2, DocParagraphTextColorSwatchIcon3, DocParagraphTextColorSwatchIcon4, DocParagraphTextColorSwatchIcon5, DocParagraphTextColorSwatchIcon6, HeaderTextColorIcon, SubtitleTypeIcon, TitleTypeIcon } from '../views/Icon';+import { BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker, ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker } from '../views/list-type-picker/index';+import { PAGE_SETTING_COMPONENT_ID, PageSettings } from '../views/PageSettings';+import { ParagraphSettingIndex } from '../views/paragraph-setting/index';+import { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, ParagraphMenu, TableBlockMenu } from '../views/ParagraphMenu';+import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../views/table/create/component-name';+import { DocCreateTableConfirm } from '../views/table/create/TableCreate';++const paragraphSettingIndexKey = 'doc_ui_paragraph-setting-panel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerComponents2();+ this._registerParts();+ this._registerIcons();+ this._registerComponents3();+ }++ private _registerComponents(): void {+ if (!this._componentManager.get(COMPONENT_DOC_HEADER_FOOTER_PANEL)) {+ this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_HEADER_FOOTER_PANEL, DocHeaderFooterPanel));+ }+ }++ private _registerComponents2(): void {+ this.disposeWithMe(this._componentManager.register(paragraphSettingIndexKey, ParagraphSettingIndex));+ }++ private _registerParts(): void {+ const componentManager = this._componentManager;+ this.disposeWithMe(componentManager.register(COMPONENT_DOC_CREATE_TABLE_CONFIRM, DocCreateTableConfirm));+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ AlignTextBothIcon,+ AddImageIcon,+ BoldIcon,+ CopyDoubleIcon,+ CutIcon,+ DeleteColumnDoubleIcon,+ DeleteIcon,+ DeleteRowDoubleIcon,+ DocSettingIcon,+ FontColorDoubleIcon,+ GridIcon,+ H1Icon,+ H2Icon,+ H3Icon,+ H4Icon,+ H5Icon,+ HeaderFooterIcon,+ HorizontallyIcon,+ InsertDoubleIcon,+ InsertRowAboveDoubleIcon,+ InsertRowBelowDoubleIcon,+ ItalicIcon,+ KeyboardIcon,+ LeftInsertColumnDoubleIcon,+ LeftJustifyingIcon,+ MenuIcon,+ TextTypeIcon,+ NoColorDoubleIcon,+ OrderIcon,+ PaintBucketDoubleIcon,+ PasteSpecialDoubleIcon,+ ReduceDoubleIcon,+ ReduceIcon,+ RightInsertColumnDoubleIcon,+ RightJustifyingIcon,+ ShapeIcon,+ StrikethroughIcon,+ SubscriptIcon,+ SuperscriptIcon,+ TitleTypeIcon,+ SubtitleTypeIcon,+ TodoListDoubleIcon,+ UnderlineIcon,+ UnorderIcon,+ DefaultTextColorIcon,+ HeaderTextColorIcon,+ MoreRightIcon,+ MoreLeftIcon,+ 'DocParagraphTextColorSwatchIcon.0': DocParagraphTextColorSwatchIcon0,+ 'DocParagraphTextColorSwatchIcon.1': DocParagraphTextColorSwatchIcon1,+ 'DocParagraphTextColorSwatchIcon.2': DocParagraphTextColorSwatchIcon2,+ 'DocParagraphTextColorSwatchIcon.3': DocParagraphTextColorSwatchIcon3,+ 'DocParagraphTextColorSwatchIcon.4': DocParagraphTextColorSwatchIcon4,+ 'DocParagraphTextColorSwatchIcon.5': DocParagraphTextColorSwatchIcon5,+ 'DocParagraphTextColorSwatchIcon.6': DocParagraphTextColorSwatchIcon6,+ 'DocParagraphBackgroundColorSwatchIcon.0': DocParagraphBackgroundColorSwatchIcon0,+ 'DocParagraphBackgroundColorSwatchIcon.1': DocParagraphBackgroundColorSwatchIcon1,+ 'DocParagraphBackgroundColorSwatchIcon.2': DocParagraphBackgroundColorSwatchIcon2,+ 'DocParagraphBackgroundColorSwatchIcon.3': DocParagraphBackgroundColorSwatchIcon3,+ 'DocParagraphBackgroundColorSwatchIcon.4': DocParagraphBackgroundColorSwatchIcon4,+ 'DocParagraphBackgroundColorSwatchIcon.5': DocParagraphBackgroundColorSwatchIcon5,+ 'DocParagraphBackgroundColorSwatchIcon.6': DocParagraphBackgroundColorSwatchIcon6,+ 'DocParagraphBackgroundColorSwatchIcon.7': DocParagraphBackgroundColorSwatchIcon7,+ 'DocParagraphBackgroundColorSwatchIcon.8': DocParagraphBackgroundColorSwatchIcon8,+ 'DocParagraphBackgroundColorSwatchIcon.9': DocParagraphBackgroundColorSwatchIcon9,+ 'DocParagraphBackgroundColorSwatchIcon.10': DocParagraphBackgroundColorSwatchIcon10,+ 'DocParagraphBackgroundColorSwatchIcon.11': DocParagraphBackgroundColorSwatchIcon11,+ 'DocParagraphBackgroundColorSwatchIcon.12': DocParagraphBackgroundColorSwatchIcon12,+ 'DocParagraphBackgroundColorSwatchIcon.13': DocParagraphBackgroundColorSwatchIcon13,+ 'DocParagraphBackgroundColorSwatchIcon.14': DocParagraphBackgroundColorSwatchIcon14,+ 'DocParagraphBackgroundColorSwatchIcon.15': DocParagraphBackgroundColorSwatchIcon15,+ }));+ }++ private _registerComponents3(): void {+ ([+ [BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker],+ [ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker],+ [DOC_PARAGRAPH_MENU_COMPONENT_KEY, ParagraphMenu],+ [DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, TableBlockMenu],+ [PAGE_SETTING_COMPONENT_ID, PageSettings],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }+}diff --git a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts b/packages/docs-ui/src/controllers/doc-header-footer.controller.tsindex 01ca8695a5..515092a10d 100644--- a/packages/docs-ui/src/controllers/doc-header-footer.controller.ts+++ b/packages/docs-ui/src/controllers/doc-header-footer.controller.ts@@ -30,13 +30,10 @@ import {} from '@univerjs/core';import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';import { DocumentEditArea, IRenderManagerService, PageLayoutType, Path, Rect, Vector2 } from '@univerjs/engine-render';-import { ComponentManager } from '@univerjs/ui';import { neoGetDocObject } from '../basics/component-tools';import { CloseHeaderFooterCommand, CoreHeaderFooterCommand } from '../commands/commands/doc-header-footer.command';import { IEditorService } from '../services/editor/editor-manager.service';import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';-import { COMPONENT_DOC_HEADER_FOOTER_PANEL } from '../views/header-footer/panel/component-name';-import { DocHeaderFooterPanel } from '../views/header-footer/panel/DocHeaderFooterPanel';import { TextBubbleShape } from '../views/header-footer/text-bubble';const HEADER_FOOTER_STROKE_COLOR = 'rgba(58, 96, 247, 1)';@@ -142,8 +139,7 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@Inject(DocSkeletonManagerService) private readonly _docSkeletonManagerService: DocSkeletonManagerService,@Inject(DocSelectionRenderService) private readonly _docSelectionRenderService: DocSelectionRenderService,- @Inject(LocaleService) private readonly _localeService: LocaleService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ @Inject(LocaleService) private readonly _localeService: LocaleService) {super();@@ -153,7 +149,6 @@ export class DocHeaderFooterController extends Disposable implements IRenderModuprivate _initialize() {this._init();this._drawHeaderFooterLabel();- this._initCustomComponents();this._listenSwitchMode();}@@ -199,12 +194,6 @@ export class DocHeaderFooterController extends Disposable implements IRenderModu);}- private _initCustomComponents(): void {- if (!this._componentManager.get(COMPONENT_DOC_HEADER_FOOTER_PANEL)) {- this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_HEADER_FOOTER_PANEL, DocHeaderFooterPanel));- }- }-private _init() {const { unitId } = this._context;const docObject = neoGetDocObject(this._context);diff --git a/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.ts b/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.tsindex 37ec8a34a4..b718b3ece1 100644--- a/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.ts+++ b/packages/docs-ui/src/controllers/doc-paragraph-setting.controller.ts@@ -15,8 +15,7 @@*/import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { ComponentManager, ISidebarService } from '@univerjs/ui';-import { ParagraphSettingIndex } from '../views/paragraph-setting/index';+import { ISidebarService } from '@univerjs/ui';const paragraphSettingIndexKey = 'doc_ui_paragraph-setting-panel';@@ -25,16 +24,10 @@ export class DocParagraphSettingController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,@Inject(ISidebarService) private _sidebarService: ISidebarService) {super();- this._init();- }-- private _init() {- this.disposeWithMe(this._componentManager.register(paragraphSettingIndexKey, ParagraphSettingIndex));}public openPanel() {diff --git a/packages/docs-ui/src/controllers/doc-table.controller.ts b/packages/docs-ui/src/controllers/doc-table.controller.tsindex c431b5c48a..8b704d26d2 100644--- a/packages/docs-ui/src/controllers/doc-table.controller.ts+++ b/packages/docs-ui/src/controllers/doc-table.controller.ts@@ -14,16 +14,12 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { ComponentManager } from '@univerjs/ui';+import { Disposable, ICommandService } from '@univerjs/core';import { DocCreateTableOperation } from '../commands/operations/doc-create-table.operation';-import { COMPONENT_DOC_CREATE_TABLE_CONFIRM } from '../views/table/create/component-name';-import { DocCreateTableConfirm } from '../views/table/create/TableCreate';export class DocTableController extends Disposable {constructor(- @ICommandService private readonly _commandService: ICommandService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ @ICommandService private readonly _commandService: ICommandService) {super();@@ -33,7 +29,6 @@ export class DocTableController extends Disposable {private _initialize() {this._init();this._registerCommands();- this._initCustomComponents();}private _registerCommands() {@@ -42,10 +37,5 @@ export class DocTableController extends Disposable {].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}- private _initCustomComponents(): void {- const componentManager = this._componentManager;- this.disposeWithMe(componentManager.register(COMPONENT_DOC_CREATE_TABLE_CONFIRM, DocCreateTableConfirm));- }-private _init() {}}diff --git a/packages/docs-ui/src/controllers/ui.controller.ts b/packages/docs-ui/src/controllers/ui.controller.tsindex 97a1bee818..b224592422 100644--- a/packages/docs-ui/src/controllers/ui.controller.ts+++ b/packages/docs-ui/src/controllers/ui.controller.ts@@ -24,57 +24,10 @@ import {UniverInstanceType,} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import {- AddImageIcon,- AlignTextBothIcon,- BoldIcon,- CopyDoubleIcon,- CutIcon,- DeleteColumnDoubleIcon,- DeleteIcon,- DeleteRowDoubleIcon,- DocSettingIcon,- FontColorDoubleIcon,- GridIcon,- H1Icon,- H2Icon,- H3Icon,- H4Icon,- H5Icon,- HeaderFooterIcon,- HorizontallyIcon,- InsertDoubleIcon,- InsertRowAboveDoubleIcon,- InsertRowBelowDoubleIcon,- ItalicIcon,- KeyboardIcon,- LeftInsertColumnDoubleIcon,- LeftJustifyingIcon,- MenuIcon,- MoreLeftIcon,- MoreRightIcon,- NoColorDoubleIcon,- OrderIcon,- PaintBucketDoubleIcon,- PasteSpecialDoubleIcon,- ReduceDoubleIcon,- ReduceIcon,- RightInsertColumnDoubleIcon,- RightJustifyingIcon,- ShapeIcon,- StrikethroughIcon,- SubscriptIcon,- SuperscriptIcon,- TextTypeIcon,- TodoListDoubleIcon,- UnderlineIcon,- UnorderIcon,-} from '@univerjs/icons';+import {BuiltInUIPart,- ComponentManager,connectInjector,- IconManager,ILayoutService,IMenuManagerService,IShortcutService,@@ -101,54 +54,10 @@ import {} from '../shortcuts/toolbar.shortcut';import { DocFooter } from '../views/doc-footer';import { DocSideMenu } from '../views/DocSideMenu';-import {- DefaultTextColorIcon,- DocParagraphBackgroundColorSwatchIcon0,- DocParagraphBackgroundColorSwatchIcon1,- DocParagraphBackgroundColorSwatchIcon10,- DocParagraphBackgroundColorSwatchIcon11,- DocParagraphBackgroundColorSwatchIcon12,- DocParagraphBackgroundColorSwatchIcon13,- DocParagraphBackgroundColorSwatchIcon14,- DocParagraphBackgroundColorSwatchIcon15,- DocParagraphBackgroundColorSwatchIcon2,- DocParagraphBackgroundColorSwatchIcon3,- DocParagraphBackgroundColorSwatchIcon4,- DocParagraphBackgroundColorSwatchIcon5,- DocParagraphBackgroundColorSwatchIcon6,- DocParagraphBackgroundColorSwatchIcon7,- DocParagraphBackgroundColorSwatchIcon8,- DocParagraphBackgroundColorSwatchIcon9,- DocParagraphTextColorSwatchIcon0,- DocParagraphTextColorSwatchIcon1,- DocParagraphTextColorSwatchIcon2,- DocParagraphTextColorSwatchIcon3,- DocParagraphTextColorSwatchIcon4,- DocParagraphTextColorSwatchIcon5,- DocParagraphTextColorSwatchIcon6,- HeaderTextColorIcon,- SubtitleTypeIcon,- TitleTypeIcon,-} from '../views/Icon';-import {- BULLET_LIST_TYPE_COMPONENT,- BulletListTypePicker,- ORDER_LIST_TYPE_COMPONENT,- OrderListTypePicker,-} from '../views/list-type-picker/index';-import { PAGE_SETTING_COMPONENT_ID, PageSettings } from '../views/PageSettings';-import {- DOC_PARAGRAPH_MENU_COMPONENT_KEY,- DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,- ParagraphMenu,- TableBlockMenu,-} from '../views/ParagraphMenu';export class DocUIController extends Disposable {constructor(@Inject(Injector) protected readonly _injector: Injector,- @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,- @Inject(IconManager) protected readonly _iconManager: IconManager,@ICommandService protected readonly _commandService: ICommandService,@ILayoutService protected readonly _layoutService: ILayoutService,@IMenuManagerService protected readonly _menuManagerService: IMenuManagerService,@@ -162,96 +71,6 @@ export class DocUIController extends Disposable {this._init();}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- AlignTextBothIcon,- AddImageIcon,- BoldIcon,- CopyDoubleIcon,- CutIcon,- DeleteColumnDoubleIcon,- DeleteIcon,- DeleteRowDoubleIcon,- DocSettingIcon,- FontColorDoubleIcon,- GridIcon,- H1Icon,- H2Icon,- H3Icon,- H4Icon,- H5Icon,- HeaderFooterIcon,- HorizontallyIcon,- InsertDoubleIcon,- InsertRowAboveDoubleIcon,- InsertRowBelowDoubleIcon,- ItalicIcon,- KeyboardIcon,- LeftInsertColumnDoubleIcon,- LeftJustifyingIcon,- MenuIcon,- TextTypeIcon,- NoColorDoubleIcon,- OrderIcon,- PaintBucketDoubleIcon,- PasteSpecialDoubleIcon,- ReduceDoubleIcon,- ReduceIcon,- RightInsertColumnDoubleIcon,- RightJustifyingIcon,- ShapeIcon,- StrikethroughIcon,- SubscriptIcon,- SuperscriptIcon,- TitleTypeIcon,- SubtitleTypeIcon,- TodoListDoubleIcon,- UnderlineIcon,- UnorderIcon,- DefaultTextColorIcon,- HeaderTextColorIcon,- MoreRightIcon,- MoreLeftIcon,- 'DocParagraphTextColorSwatchIcon.0': DocParagraphTextColorSwatchIcon0,- 'DocParagraphTextColorSwatchIcon.1': DocParagraphTextColorSwatchIcon1,- 'DocParagraphTextColorSwatchIcon.2': DocParagraphTextColorSwatchIcon2,- 'DocParagraphTextColorSwatchIcon.3': DocParagraphTextColorSwatchIcon3,- 'DocParagraphTextColorSwatchIcon.4': DocParagraphTextColorSwatchIcon4,- 'DocParagraphTextColorSwatchIcon.5': DocParagraphTextColorSwatchIcon5,- 'DocParagraphTextColorSwatchIcon.6': DocParagraphTextColorSwatchIcon6,- 'DocParagraphBackgroundColorSwatchIcon.0': DocParagraphBackgroundColorSwatchIcon0,- 'DocParagraphBackgroundColorSwatchIcon.1': DocParagraphBackgroundColorSwatchIcon1,- 'DocParagraphBackgroundColorSwatchIcon.2': DocParagraphBackgroundColorSwatchIcon2,- 'DocParagraphBackgroundColorSwatchIcon.3': DocParagraphBackgroundColorSwatchIcon3,- 'DocParagraphBackgroundColorSwatchIcon.4': DocParagraphBackgroundColorSwatchIcon4,- 'DocParagraphBackgroundColorSwatchIcon.5': DocParagraphBackgroundColorSwatchIcon5,- 'DocParagraphBackgroundColorSwatchIcon.6': DocParagraphBackgroundColorSwatchIcon6,- 'DocParagraphBackgroundColorSwatchIcon.7': DocParagraphBackgroundColorSwatchIcon7,- 'DocParagraphBackgroundColorSwatchIcon.8': DocParagraphBackgroundColorSwatchIcon8,- 'DocParagraphBackgroundColorSwatchIcon.9': DocParagraphBackgroundColorSwatchIcon9,- 'DocParagraphBackgroundColorSwatchIcon.10': DocParagraphBackgroundColorSwatchIcon10,- 'DocParagraphBackgroundColorSwatchIcon.11': DocParagraphBackgroundColorSwatchIcon11,- 'DocParagraphBackgroundColorSwatchIcon.12': DocParagraphBackgroundColorSwatchIcon12,- 'DocParagraphBackgroundColorSwatchIcon.13': DocParagraphBackgroundColorSwatchIcon13,- 'DocParagraphBackgroundColorSwatchIcon.14': DocParagraphBackgroundColorSwatchIcon14,- 'DocParagraphBackgroundColorSwatchIcon.15': DocParagraphBackgroundColorSwatchIcon15,- }));- }-- private _initCustomComponents(): void {- ([- [BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker],- [ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker],- [DOC_PARAGRAPH_MENU_COMPONENT_KEY, ParagraphMenu],- [DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, TableBlockMenu],- [PAGE_SETTING_COMPONENT_ID, PageSettings],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });- }-private _initUiParts() {this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.FOOTER, () => connectInjector(DocFooter, this._injector)));this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(DocSideMenu, this._injector)));@@ -283,8 +102,6 @@ export class DocUIController extends Disposable {}private _init(): void {- this._initCustomComponents();- this._registerIcons();this._initMenus();this._initFocusHandler();this._initCommands();diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.tsindex d7efdf5b6f..7a4b86f79d 100644--- a/packages/docs-ui/src/plugin.ts+++ b/packages/docs-ui/src/plugin.ts@@ -97,6 +97,7 @@ import { DocParagraphSettingPanelOperation } from './commands/operations/doc-parimport { DocOpenPageSettingCommand } from './commands/operations/open-page-setting.operation';import { SetDocZoomRatioOperation } from './commands/operations/set-doc-zoom-ratio.operation';import { defaultPluginConfig, DOCS_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DocAutoFormatController } from './controllers/doc-auto-format.controller';import { DocHeaderFooterController } from './controllers/doc-header-footer.controller';import { DocMoveCursorController } from './controllers/doc-move-cursor.controller';@@ -206,6 +207,7 @@ export class UniverDocsUIPlugin extends Plugin {[DocMoveCursorController],[DocParagraphSettingController],[DocTableController],+ [ComponentsController],// FIXME: LifecycleStages.Rendered must be used, otherwise the menu cannot be added to the DOM, but the sheet ui// plugin can be added in LifecycleStages.Ready@@ -353,6 +355,7 @@ export class UniverDocsUIPlugin extends Plugin {[DocPrintInterceptorService],[DocClipboardController],[DocEditorBridgeController],+ [ComponentsController],[DocUIController],[DocAutoFormatController],[DocTableController],diff --git a/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.tsnew file mode 100644index 0000000000..7e1ac66782--- /dev/null+++ b/packages/docs-ui/src/services/__tests__/doc-ime-state-change-interceptor.service.spec.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { IRenderManagerService } from '@univerjs/engine-render';+import { beforeEach, describe, expect, it } from 'vitest';+import { DocIMEInputManagerService } from '../doc-ime-input-manager.service';+import { DocIMEStateChangeInterceptorService } from '../doc-ime-state-change-interceptor.service';++describe('DocIMEStateChangeInterceptorService', () => {+ let service: DocIMEStateChangeInterceptorService;++ beforeEach(() => {+ const imeInputManagerService = {+ fetchComposedUndoRedoMutationParams: () => ({+ undoMutationParams: { actions: [{ p: ['body'], od: 'old' }] },+ redoMutationParams: { actions: [{ p: ['body'], oi: 'new' }] },+ previousActiveRange: { startOffset: 1, endOffset: 2 },+ }),+ };+ const injector = new Injector();+ injector.add([IRenderManagerService, { useValue: { getRenderUnitById: () => ({ with: (token: unknown) => token === DocIMEInputManagerService ? imeInputManagerService : null }) } as unknown as IRenderManagerService }]);+ injector.add([DocIMEStateChangeInterceptorService]);+ service = injector.get(DocIMEStateChangeInterceptorService);+ });++ it('replaces composition history with the composed IME undo and redo actions', () => {+ expect(service.transformChangeStateInfo({+ unitId: 'doc-1',+ isCompositionEnd: true,+ isSync: false,+ redoState: { actions: [] },+ undoState: { actions: [], textRanges: [] },+ } as never)).toMatchObject({+ redoState: { actions: [{ p: ['body'], oi: 'new' }] },+ undoState: {+ actions: [{ p: ['body'], od: 'old' }],+ textRanges: [{ startOffset: 1, endOffset: 2 }],+ },+ });+ });+});diff --git a/packages/docs/src/services/__tests__/doc-content-insert.service.spec.ts b/packages/docs/src/services/__tests__/doc-content-insert.service.spec.tsnew file mode 100644index 0000000000..95921ac90e--- /dev/null+++ b/packages/docs/src/services/__tests__/doc-content-insert.service.spec.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { DocContentInsertService } from '../doc-content-insert.service';++describe('DocContentInsertService', () => {+ let service: DocContentInsertService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([DocContentInsertService]);+ service = injector.get(DocContentInsertService);+ });++ it('consumes a pending insert range only for the matching document', () => {+ const range = { unitId: 'doc-1', startOffset: 2, endOffset: 5, segmentId: 'header' };++ service.setInsertRange(range);++ expect(service.consumeInsertRange('doc-2')).toBeNull();+ expect(service.consumeInsertRange('doc-1')).toEqual(range);+ expect(service.consumeInsertRange('doc-1')).toBeNull();+ });++ it('clears stale insert ranges when editing is cancelled', () => {+ service.setInsertRange({ unitId: 'doc-1', startOffset: 2, endOffset: 5 });+ service.clearInsertRange();++ expect(service.consumeInsertRange()).toBeNull();+ });+});diff --git a/packages/drawing-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index 06a09c6c6f..0000000000--- a/packages/drawing-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,41 +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 { ICommandService } from '@univerjs/core';-import type { ComponentManager, IconManager, IMenuManagerService } from '@univerjs/ui';-import { describe, expect, it, vi } from 'vitest';-import { COMPONENT_IMAGE_POPUP_MENU } from '../../views/image-popup-menu/component-name';-import { DrawingUIController } from '../ui.controller';--describe('DrawingUIController', () => {- it('registers popup components and drawing operations', () => {- const register = vi.fn(() => ({ dispose: vi.fn() }));- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));- const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));- const mergeMenu = vi.fn();-- const controller = new DrawingUIController(- { register } as unknown as ComponentManager,- { register: registerIcon } as unknown as IconManager,- { registerCommand } as unknown as ICommandService,- { mergeMenu } as unknown as IMenuManagerService- );-- expect(controller).toBeTruthy();- expect(registerCommand).toHaveBeenCalledTimes(20);- expect(register).toHaveBeenCalledWith(COMPONENT_IMAGE_POPUP_MENU, expect.any(Function));- });-});diff --git a/packages/drawing-ui/src/controllers/components.controller.ts b/packages/drawing-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..10937fd9a0--- /dev/null+++ b/packages/drawing-ui/src/controllers/components.controller.ts@@ -0,0 +1,52 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { BottomIcon, GroupIcon, MoveDownIcon, MoveUpIcon, TopmostIcon, UngroupIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { COMPONENT_IMAGE_POPUP_MENU } from '../views/image-popup-menu/component-name';+import { ImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [COMPONENT_IMAGE_POPUP_MENU, ImagePopupMenu],+ ] as const).forEach(([key, component]) => {+ this.disposeWithMe(this._componentManager.register(key, component));+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ BottomIcon,+ GroupIcon,+ MoveDownIcon,+ MoveUpIcon,+ TopmostIcon,+ UngroupIcon,+ }));+ }+}diff --git a/packages/drawing-ui/src/controllers/ui.controller.ts b/packages/drawing-ui/src/controllers/ui.controller.tsindex 3b0e4a2461..863501b030 100644--- a/packages/drawing-ui/src/controllers/ui.controller.ts+++ b/packages/drawing-ui/src/controllers/ui.controller.ts@@ -14,9 +14,8 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { BottomIcon, GroupIcon, MoveDownIcon, MoveUpIcon, TopmostIcon, UngroupIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IMenuManagerService } from '@univerjs/ui';+import { Disposable, ICommandService } from '@univerjs/core';+import { IMenuManagerService } from '@univerjs/ui';import {SetDrawingAlignBottomOperation,SetDrawingAlignCenterOperation,@@ -39,13 +38,9 @@ import { CancelDrawingGroupOperation, SetDrawingGroupOperation } from '../commanimport { AutoImageCropOperation, CloseImageCropOperation, OpenImageCropOperation } from '../commands/operations/image-crop.operation';import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';import { menuSchema } from '../menu/schema';-import { COMPONENT_IMAGE_POPUP_MENU } from '../views/image-popup-menu/component-name';-import { ImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';export class DrawingUIController extends Disposable {constructor(- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@ICommandService private readonly _commandService: ICommandService,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService) {@@ -57,8 +52,6 @@ export class DrawingUIController extends Disposable {private _init(): void {this._initMenus();this._initCommands();- this._initComponents();- this._registerIcons();}private _initMenus(): void {@@ -89,23 +82,4 @@ export class DrawingUIController extends Disposable {SetDrawingArrangeBackwardOperation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}-- private _initComponents(): void {- ([- [COMPONENT_IMAGE_POPUP_MENU, ImagePopupMenu],- ] as const).forEach(([key, component]) => {- this.disposeWithMe(this._componentManager.register(key, component));- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- BottomIcon,- GroupIcon,- MoveDownIcon,- MoveUpIcon,- TopmostIcon,- UngroupIcon,- }));- }}diff --git a/packages/drawing-ui/src/plugin.ts b/packages/drawing-ui/src/plugin.tsindex 9fc29df813..499fc6517c 100644--- a/packages/drawing-ui/src/plugin.ts+++ b/packages/drawing-ui/src/plugin.ts@@ -19,6 +19,7 @@ import type { IUniverDrawingUIConfig } from './config/config';import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';import pkg from '../package.json';import { defaultPluginConfig, DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DrawingUpdateController } from './controllers/drawing-update.controller';import { ImageCropperController } from './controllers/image-cropper.controller';import { ImageUpdateController } from './controllers/image-update.controller';@@ -51,6 +52,8 @@ export class UniverDrawingUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);this._initDependencies();}diff --git a/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.tsnew file mode 100644index 0000000000..703ac4f474--- /dev/null+++ b/packages/drawing-ui/src/services/__tests__/drawing-image-clip.service.spec.ts@@ -0,0 +1,50 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { DrawingImageClipService } from '../drawing-image-clip.service';++describe('DrawingImageClipService', () => {+ let service: DrawingImageClipService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([DrawingImageClipService]);+ service = injector.get(DrawingImageClipService);+ });++ it('delegates image clipping to the registered shape engine', () => {+ const bounds = { left: 0, top: 0, width: 20, height: 10 };+ const delegate = vi.fn(() => bounds);+ const disposable = service.registerClipDelegate(delegate);++ expect(service.applyShapeClip({} as never, 'rect', 20, 10, { adj: 1 })).toBe(bounds);+ expect(delegate).toHaveBeenCalledWith({}, 'rect', 20, 10, { adj: 1 });++ disposable.dispose();+ expect(service.applyShapeClip({} as never, 'rect', 20, 10)).toBe(false);+ });++ it('publishes whether shape clipping is available in the current runtime', () => {+ const values: boolean[] = [];+ service.canUseShapeClip$.subscribe((value) => values.push(value));++ service.setCanUseShapeClip(true);++ expect(values).toEqual([false, 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.tsnew file mode 100644index 0000000000..c0a6c8a6b1--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/active-dirty-manager.service.spec.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../active-dirty-manager.service';++describe('ActiveDirtyManagerService', () => {+ let service: IActiveDirtyManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);+ service = injector.get(IActiveDirtyManagerService);+ });++ it('registers command dirty converters used by recalculation', () => {+ const converter = {+ commandId: 'sheet.command.set-range-values',+ getDirtyData: () => ({ forceCalculation: true }),+ };++ service.register(converter.commandId, converter);++ expect(service.has(converter.commandId)).toBe(true);+ expect(service.get(converter.commandId)?.getDirtyData({ id: converter.commandId } as never)).toEqual({+ forceCalculation: true,+ });++ service.remove(converter.commandId);+ expect(service.has(converter.commandId)).toBe(false);+ });+});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.tsnew file mode 100644index 0000000000..b6fc746f0a--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/feature-calculation-manager.service.spec.ts@@ -0,0 +1,49 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { FeatureCalculationManagerService, IFeatureCalculationManagerService } from '../feature-calculation-manager.service';++describe('FeatureCalculationManagerService', () => {+ let service: IFeatureCalculationManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }]);+ service = injector.get(IFeatureCalculationManagerService);+ });++ it('stores feature executors per workbook and notifies recalculation listeners', () => {+ const changes: Array<{ unitId: string; subUnitId: string; featureIds: string[] }> = [];+ service.onChanged$.subscribe((change) => changes.push(change));+ const executor = {+ unitId: 'book-1',+ subUnitId: 'sheet-1',+ dependencyRanges: [{ unitId: 'book-1', sheetId: 'sheet-1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }],+ getDirtyData: () => ({ runtimeCellData: {}, dirtyRanges: {} }),+ };++ service.register('book-1', 'sheet-1', 'sparkline-1', executor as never);+ service.remove('book-1', 'sheet-1', ['sparkline-1']);++ expect(service.get('book-1', 'sheet-1', 'sparkline-1')).toBeUndefined();+ expect(changes).toEqual([+ { unitId: 'book-1', subUnitId: 'sheet-1', featureIds: ['sparkline-1'] },+ { unitId: 'book-1', subUnitId: 'sheet-1', featureIds: ['sparkline-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.tsnew file mode 100644index 0000000000..68f3ebb8ed--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/hyperlink-engine-formula.service.spec.ts@@ -0,0 +1,41 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector, IUniverInstanceService } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from '../hyperlink-engine-formula.service';++describe('HyperlinkEngineFormulaService', () => {+ let service: IHyperlinkEngineFormulaService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);+ injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);+ service = injector.get(IHyperlinkEngineFormulaService);+ });++ it('does not create hyperlink payload for blank labels', () => {+ expect(service.generateCellValue('https://example.com', ' ')).toEqual({ v: '' });+ });++ it('normalizes valid URLs before writing rich-text hyperlink payloads', () => {+ const cell = service.generateCellValue('example.com', 'Example');++ expect(JSON.stringify(cell.p)).toContain('https://example.com');+ expect(JSON.stringify(cell.p)).toContain('Example');+ });+});diff --git a/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.ts b/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.tsnew file mode 100644index 0000000000..dd5da947eb--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/other-formula-manager.service.spec.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../other-formula-manager.service';++describe('OtherFormulaManagerService', () => {+ let service: IOtherFormulaManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);+ service = injector.get(IOtherFormulaManagerService);+ });++ it('keeps plugin-owned formula data isolated by unit, sheet and formula id', () => {+ const item = { f: '=TABLE()', ranges: [] };++ service.register({ unitId: 'book-1', subUnitId: 'sheet-1', formulaId: 'table-1', item: item as never });++ expect(service.has({ unitId: 'book-1', subUnitId: 'sheet-1', formulaId: 'table-1' })).toBe(true);+ expect(service.get({ unitId: 'book-1', subUnitId: 'sheet-1', formulaId: 'table-1' })).toBe(item);+ expect(service.get({ unitId: 'book-1', subUnitId: 'sheet-2', formulaId: 'table-1' })).toBeUndefined();+ });++ it('batch removes only dirty formula ids reported by a feature plugin', () => {+ service.batchRegister({+ 'book-1': {+ 'sheet-1': {+ 'table-1': { f: '=TABLE(1)' } as never,+ 'table-2': { f: '=TABLE(2)' } as never,+ },+ },+ });++ service.batchRemove({ 'book-1': { 'sheet-1': { 'table-1': true } } } as never);++ expect(service.has({ unitId: 'book-1', subUnitId: 'sheet-1', formulaId: 'table-1' })).toBe(false);+ expect(service.has({ unitId: 'book-1', subUnitId: 'sheet-1', formulaId: 'table-2' })).toBe(true);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.spec.ts b/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.spec.tsnew file mode 100644index 0000000000..784721a0b0--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/sheet-row-filtered.service.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 { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ISheetRowFilteredService, SheetRowFilteredService } from '../sheet-row-filtered.service';++describe('SheetRowFilteredService', () => {+ let service: ISheetRowFilteredService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);+ service = injector.get(ISheetRowFilteredService);+ });++ it('delegates row visibility checks to the active filter feature', () => {+ service.register((unitId, subUnitId, row) => unitId === 'book-1' && subUnitId === 'sheet-1' && row === 3);++ expect(service.getRowFiltered('book-1', 'sheet-1', 3)).toBe(true);+ expect(service.getRowFiltered('book-1', 'sheet-1', 4)).toBe(false);+ expect(service.getRowFiltered('book-1', 'sheet-2', 3)).toBe(false);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/super-table.service.spec.ts b/packages/engine-formula/src/services/__tests__/super-table.service.spec.tsnew file mode 100644index 0000000000..2819b3cf29--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/super-table.service.spec.ts@@ -0,0 +1,56 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { TableOptionType } from '../../basics/common';+import { ISuperTableService, SuperTableService } from '../super-table.service';++describe('SuperTableService', () => {+ let service: ISuperTableService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ISuperTableService, { useClass: SuperTableService }]);+ service = injector.get(ISuperTableService);+ });++ it('registers workbook tables case-insensitively for structured references', () => {+ const table = { name: 'SalesTable' };++ service.registerTable('book-1', 'SalesTable', table as never);++ expect(service.hasTable('book-1', 'salestable')).toBe(true);+ expect(service.getTable('book-1', 'SalesTable')).toBe(table);+ });++ it('notifies subscribers when structured-reference tables change', () => {+ const changes: unknown[] = [];+ service.update$.subscribe((change) => changes.push(change));++ service.registerTable('book-1', 'SalesTable', { name: 'SalesTable' } as never);+ service.remove('book-1', 'SalesTable');++ expect(changes).toEqual([null, null]);+ expect(service.hasTable('book-1', 'SalesTable')).toBe(false);+ });++ it('keeps built-in table options available for formula parsing', () => {+ expect(service.getTableOptionMap().get(TableOptionType.DATA)).toBe(TableOptionType.DATA);+ service.registerTableOptionMap('自定义', TableOptionType.ALL);+ expect(service.getTableOptionMap().get('自定义')).toBe(TableOptionType.ALL);+ });+});diff --git a/packages/find-replace/src/controllers/__tests__/find-replace.controller.spec.ts b/packages/find-replace/src/controllers/__tests__/find-replace.controller.spec.tsdeleted file mode 100644index 6ff29f863d..0000000000--- a/packages/find-replace/src/controllers/__tests__/find-replace.controller.spec.ts+++ /dev/null@@ -1,68 +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 { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';--import { FindReplaceController } from '../find-replace.controller';--describe('FindReplaceController', () => {- it('should open dialog when revealed and close when focus changes', () => {- const focused$ = new Subject<any>();- const univerInstanceService = {- focused$,- getUniverSheetInstance: vi.fn(() => null),- };-- const menuManagerService = { mergeMenu: vi.fn() };- const shortcutService = { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) };- const commandService = { registerCommand: vi.fn(() => ({ dispose: vi.fn() })) };- const stateUpdates$ = new Subject<any>();- const findReplaceService = {- stateUpdates$,- terminate: vi.fn(),- };- const dialogService = { open: vi.fn(), close: vi.fn() };- const layoutService = { focus: vi.fn() };- const localeService = { t: (k: string) => k };- const componentManager = { register: vi.fn(() => ({ dispose: vi.fn() })) };- const iconManager = { register: vi.fn(() => ({ dispose: vi.fn() })) };-- const controller = new FindReplaceController(- univerInstanceService as any,- menuManagerService as any,- shortcutService as any,- commandService as any,- findReplaceService as any,- dialogService as any,- layoutService as any,- localeService as any,- componentManager as any,- iconManager as any- );-- expect(componentManager.register).toHaveBeenCalledWith('FindReplaceDialog', expect.anything());-- stateUpdates$.next({ revealed: true });- expect(dialogService.open).toHaveBeenCalled();-- focused$.next(null);- expect(dialogService.close).toHaveBeenCalled();- expect(findReplaceService.terminate).toHaveBeenCalled();-- controller.dispose();- });-});diff --git a/packages/find-replace/src/controllers/components.controller.ts b/packages/find-replace/src/controllers/components.controller.tsnew file mode 100644index 0000000000..ef4be2fa3d--- /dev/null+++ b/packages/find-replace/src/controllers/components.controller.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { SearchIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { FindReplaceDialog } from '../views/dialog/FindReplaceDialog';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerIcons();+ this._registerComponents();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ SearchIcon,+ }));+ }++ private _registerComponents(): void {+ ([+ ['FindReplaceDialog', FindReplaceDialog],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }+}diff --git a/packages/find-replace/src/controllers/find-replace.controller.ts b/packages/find-replace/src/controllers/find-replace.controller.tsindex f76459ad50..7d0b5dada2 100644--- a/packages/find-replace/src/controllers/find-replace.controller.ts+++ b/packages/find-replace/src/controllers/find-replace.controller.ts@@ -23,8 +23,7 @@ import {RxDisposable,toDisposable,} from '@univerjs/core';-import { SearchIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IDialogService, ILayoutService, IMenuManagerService, IShortcutService } from '@univerjs/ui';+import { IDialogService, ILayoutService, IMenuManagerService, IShortcutService } from '@univerjs/ui';import { takeUntil } from 'rxjs';import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../commands/commands/replace.command';import {@@ -36,7 +35,6 @@ import {} from '../commands/operations/find-replace.operation';import { menuSchema } from '../menu/schema';import { IFindReplaceService } from '../services/find-replace.service';-import { FindReplaceDialog } from '../views/dialog/FindReplaceDialog';import {FocusSelectionShortcutItem,GoToNextFindMatchShortcutItem,@@ -61,15 +59,12 @@ export class FindReplaceController extends RxDisposable {@IFindReplaceService private readonly _findReplaceService: IFindReplaceService,@IDialogService private readonly _dialogService: IDialogService,@ILayoutService private readonly _layoutService: ILayoutService,- @Inject(LocaleService) private readonly _localeService: LocaleService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @Inject(LocaleService) private readonly _localeService: LocaleService) {super();this._initCommands();this._initUI();- this._registerIcons();this._initShortcuts();}@@ -106,14 +101,6 @@ export class FindReplaceController extends RxDisposable {}private _initUI(): void {- ([- ['FindReplaceDialog', FindReplaceDialog],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });-this._menuManagerService.mergeMenu(menuSchema);// this controller is also responsible for toggling the FindReplaceDialog@@ -146,12 +133,6 @@ export class FindReplaceController extends RxDisposable {}));}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- SearchIcon,- }));- }-private _closingListenerDisposable: Nullable<IDisposable>;closePanel(): void {if (!this._closingListenerDisposable) {diff --git a/packages/find-replace/src/plugin.ts b/packages/find-replace/src/plugin.tsindex 89fbd4247e..13a5ad1997 100644--- a/packages/find-replace/src/plugin.ts+++ b/packages/find-replace/src/plugin.ts@@ -19,6 +19,7 @@ import type { IUniverFindReplaceConfig } from './config/config';import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';import pkg from '../package.json';import { defaultPluginConfig, FIND_REPLACE_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { FindReplaceController } from './controllers/find-replace.controller';import { FindReplaceService, IFindReplaceService } from './services/find-replace.service';@@ -44,6 +45,8 @@ export class UniverFindReplacePlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[FindReplaceController],[IFindReplaceService, { useClass: FindReplaceService }],diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.tsindex 76c3a9206c..14e9e44ea2 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.panel.controller.ts@@ -18,7 +18,6 @@ import type { IDisposable } from '@univerjs/core';import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';import { Disposable, generateRandomId, Inject, Injector, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';import { ComponentManager, ISidebarService } from '@univerjs/ui';-import { ConditionFormattingPanel } from '../views/ConditionFormattingPanel';const CF_PANEL_KEY = 'sheet.conditional.formatting.panel';@@ -34,8 +33,6 @@ export class ConditionalFormattingPanelController extends Disposable {) {super();- this._initPanel();-this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe((sheet) => {if (!sheet) this._sidebarDisposable?.dispose();@@ -66,10 +63,4 @@ export class ConditionalFormattingPanelController extends Disposable {this._sidebarDisposable = this._sidebarService.open(props);}-- private _initPanel() {- this.disposeWithMe(- this._componentManager.register(CF_PANEL_KEY, ConditionFormattingPanel)- );- }}diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..95847899f0--- /dev/null+++ b/packages/sheets-conditional-formatting-ui/src/controllers/components.controller.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { ConditionsDoubleIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { ConditionFormattingPanel } from '../views/ConditionFormattingPanel';++const CF_PANEL_KEY = 'sheet.conditional.formatting.panel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ this.disposeWithMe(+ this._componentManager.register(CF_PANEL_KEY, ConditionFormattingPanel)+ );+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ ConditionsDoubleIcon,+ }));+ }+}diff --git a/packages/sheets-conditional-formatting-ui/src/menu/cf.menu.controller.ts b/packages/sheets-conditional-formatting-ui/src/menu/cf.menu.controller.tsindex c29c44908e..d209521b11 100644--- a/packages/sheets-conditional-formatting-ui/src/menu/cf.menu.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/menu/cf.menu.controller.ts@@ -14,25 +14,16 @@* limitations under the License.*/-import type { IDisposable } from '@univerjs/core';-import { Disposable, Inject, Injector } from '@univerjs/core';-import { ConditionsDoubleIcon } from '@univerjs/icons';-import { IconManager, IMenuManagerService } from '@univerjs/ui';+import { Disposable } from '@univerjs/core';+import { IMenuManagerService } from '@univerjs/ui';import { menuSchema } from './schema';export class ConditionalFormattingMenuController extends Disposable {- private _sidebarDisposable: IDisposable | null = null;-constructor(- @Inject(Injector) private _injector: Injector,- @Inject(IconManager) private readonly _iconManager: IconManager,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService) {super();this._menuManagerService.mergeMenu(menuSchema);- this.disposeWithMe(this._iconManager.register({- ConditionsDoubleIcon,- }));}}diff --git a/packages/sheets-conditional-formatting-ui/src/plugin.ts b/packages/sheets-conditional-formatting-ui/src/plugin.tsindex 4c6fac3e4d..4db081e860 100644--- a/packages/sheets-conditional-formatting-ui/src/plugin.ts+++ b/packages/sheets-conditional-formatting-ui/src/plugin.ts@@ -52,6 +52,7 @@ import { ConditionalFormattingPanelController } from './controllers/cf.panel.conimport { ConditionalFormattingPermissionController } from './controllers/cf.permission.controller';import { SheetsCfRenderController } from './controllers/cf.render.controller';import { ConditionalFormattingViewportController } from './controllers/cf.viewport.controller';+import { ComponentsController } from './controllers/components.controller';import { ConditionalFormattingMenuController } from './menu/cf.menu.controller';@DependentOn(UniverSheetsConditionalFormattingPlugin, UniverSheetsFormulaPlugin)@@ -84,6 +85,8 @@ export class UniverSheetsConditionalFormattingUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, [[SheetsCfRenderController],[ConditionalFormattingCopyPasteController],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.tsnew file mode 100644index 0000000000..6f8352aee9--- /dev/null+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts@@ -0,0 +1,76 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { 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 { 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 formulaResults: Map<string, unknown>;++ beforeEach(() => {+ formulaResults = new Map();+ registerFormulaWithRange = vi.fn(() => 'formula-1');+ 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([ConditionalFormattingFormulaService]);+ service = injector.get(ConditionalFormattingFormulaService);+ });++ it('registers conditional-formatting formulas with a stable top-left anchor range', () => {+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0', [+ { startRow: 5, endRow: 5, startColumn: 5, endColumn: 5 },+ { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 },+ ]);++ expect(registerFormulaWithRange).toHaveBeenCalledWith(+ 'book-1',+ 'sheet-1',+ '=A1>0',+ [+ { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 },+ { startRow: 5, endRow: 5, startColumn: 5, endColumn: 5 },+ ],+ undefined,+ expect.any(String),+ 'cf-1'+ );+ });++ it('returns boolean formula results as business booleans for conditional checks', () => {+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0');+ formulaResults.set('formula-1', {+ status: FormulaResultStatus.SUCCESS,+ result: { 0: { 0: [[{ t: CellValueType.BOOLEAN, v: 1 }]] } },+ });++ expect(service.getFormulaResultWithCoords('book-1', 'sheet-1', 'cf-1', '=A1>0')).toEqual({+ status: FormulaResultStatus.SUCCESS,+ result: true,+ });+ });+});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.tsnew file mode 100644index 0000000000..55938d7624--- /dev/null+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts@@ -0,0 +1,64 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { CFRuleType } from '../../base/const';+import { ConditionalFormattingRuleModel } from '../../models/conditional-formatting-rule-model';+import { ConditionalFormattingViewModel } from '../../models/conditional-formatting-view-model';+import { ConditionalFormattingStyleComposer } from '../conditional-formatting-style-composer.service';++describe('ConditionalFormattingStyleComposer', () => {+ let service: ConditionalFormattingStyleComposer;+ const rules = new Map<string, unknown>();+ let cellCfs: Array<{ cfId: string; result: unknown; priority: number }>;++ 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([ConditionalFormattingStyleComposer]);+ service = injector.get(ConditionalFormattingStyleComposer);+ });++ it('merges matched conditional styles in rule priority order', () => {+ rules.set('color-scale', { stopIfTrue: false, rule: { type: CFRuleType.colorScale } });+ rules.set('highlight', { stopIfTrue: false, rule: { type: CFRuleType.highlightCell } });+ cellCfs = [+ { cfId: 'color-scale', result: '#ffeeaa', priority: 1 },+ { cfId: 'highlight', result: { cl: { rgb: '#333333' } }, priority: 2 },+ ];++ expect(service.composeStyle('book-1', 'sheet-1', 1, 1)).toEqual({+ style: { cl: { rgb: '#333333' }, bg: { rgb: '#ffeeaa' } },+ });+ });++ it('stops evaluating lower-priority rules after a matched stop-if-true rule', () => {+ rules.set('stop', { stopIfTrue: true, rule: { type: CFRuleType.highlightCell } });+ rules.set('ignored', { stopIfTrue: false, rule: { type: CFRuleType.colorScale } });+ cellCfs = [+ { cfId: 'stop', result: { bg: { rgb: '#ff0000' } }, priority: 1 },+ { cfId: 'ignored', result: '#00ff00', priority: 2 },+ ];++ expect(service.composeStyle('book-1', 'sheet-1', 1, 1)).toEqual({+ style: { bg: { rgb: '#ff0000' } },+ });+ });+});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.tsnew file mode 100644index 0000000000..78261df49a--- /dev/null+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts@@ -0,0 +1,49 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { ICommandService, Injector, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';+import { 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';+import { ConditionalFormattingViewModel } from '../../models/conditional-formatting-view-model';+import { ConditionalFormattingStyleComposer } from '../conditional-formatting-style-composer.service';+import { ConditionalFormattingService } from '../conditional-formatting.service';++describe('ConditionalFormattingService', () => {+ let service: ConditionalFormattingService;+ let composeStyle: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ composeStyle = vi.fn(() => ({ style: { bg: { rgb: '#fff000' } } }));+ 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([ConditionalFormattingService]);+ service = injector.get(ConditionalFormattingService);+ });++ it('composes the conditional style for the requested cell through the style composer', () => {+ expect(service.composeStyle('book-1', 'sheet-1', 2, 3)).toEqual({ style: { bg: { rgb: '#fff000' } } });+ expect(composeStyle).toHaveBeenCalledWith('book-1', 'sheet-1', 2, 3);+ });+});diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index b50b89ef72..0000000000--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,89 +0,0 @@-/**- * Copyright 2023-present DreamNum Co., Ltd.- *- * Licensed under the Apache License, Version 2.0 (the "License");- * you may not use this file except in compliance with the License.- * You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing, software- * distributed under the License is distributed on an "AS IS" BASIS,- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- * See the License for the specific language governing permissions and- * limitations under the License.- */--import type { Injector } from '@univerjs/core';-import { describe, expect, it, vi } from 'vitest';-import { DATA_VALIDATION_PANEL } from '../../commands/operations/data-validation.operation';-import {- BASE_FORMULA_INPUT_NAME,- CHECKBOX_FORMULA_INPUT_NAME,- CUSTOM_FORMULA_INPUT_NAME,- LIST_FORMULA_INPUT_NAME,-} from '../../views/components/formula-input';-import { SheetsDataValidationUIController } from '../ui.controller';--vi.hoisted(() => {- Object.assign(globalThis, {- Path2D: class Path2D {},- });-});--const FORMULA_INPUT_KEYS = [- CUSTOM_FORMULA_INPUT_NAME,- BASE_FORMULA_INPUT_NAME,- LIST_FORMULA_INPUT_NAME,- CHECKBOX_FORMULA_INPUT_NAME,-];--function createView(id: string) {- return {- id,- formulaInput: `${id}-formula`,- canvasRender: `${id}-canvas`,- dropdownType: `${id}-dropdown`,- optionsInput: `${id}-options`,- };-}--describe('SheetsDataValidationUIController', () => {- it('registers panel components and wires validator views into the registry', () => {- const register = vi.fn((_key: string) => ({ dispose: vi.fn() }));- const registerIcon = vi.fn((_key: string) => ({ dispose: vi.fn() }));- const validators = new Map<string, Record<string, unknown>>();- const createInstance = vi.fn((viewCtor: { name: string }) => createView(viewCtor.name));- const getValidatorItem = vi.fn((id: string) => {- if (!validators.has(id)) {- validators.set(id, {});- }- return validators.get(id);- });-- const controller = new SheetsDataValidationUIController(- { createInstance } as unknown as Injector,- { register } as never,- { register: registerIcon } as never,- { getValidatorItem } as never- );-- expect(controller).toBeTruthy();-- const registeredKeys = register.mock.calls.map((args) => args[0]);- expect(registeredKeys).toContain(DATA_VALIDATION_PANEL);- expect(registeredKeys).toContain('LIST_RENDER_MODE_OPTION_INPUT');- expect(registeredKeys).toContain('DATE_SHOW_TIME_OPTION');- FORMULA_INPUT_KEYS.forEach((key) => expect(registeredKeys).toContain(key));-- ['DecimalValidatorView', 'WholeValidatorView', 'TextLengthValidatorView', 'DateValidatorView', 'CheckboxValidatorView', 'ListValidatorView', 'ListMultipleValidatorView', 'CustomFormulaValidatorView'].forEach((viewName) => {- expect(createInstance).toHaveBeenCalledWith(expect.objectContaining({ name: viewName }));- expect(validators.get(viewName)).toEqual({- formulaInput: `${viewName}-formula`,- canvasRender: `${viewName}-canvas`,- dropdownType: `${viewName}-dropdown`,- optionsInput: `${viewName}-options`,- });- });- });-});diff --git a/packages/sheets-data-validation-ui/src/controllers/components.controller.ts b/packages/sheets-data-validation-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..691e53270e--- /dev/null+++ b/packages/sheets-data-validation-ui/src/controllers/components.controller.ts@@ -0,0 +1,36 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { DataValidationIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerIcons();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ DataValidationIcon,+ }));+ }+}diff --git a/packages/sheets-data-validation-ui/src/controllers/ui.controller.ts b/packages/sheets-data-validation-ui/src/controllers/ui.controller.tsindex dbe225096e..fa6e618390 100644--- a/packages/sheets-data-validation-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-data-validation-ui/src/controllers/ui.controller.ts@@ -18,8 +18,7 @@ import type { Ctor } from '@univerjs/core';import type { BaseSheetDataValidatorView } from '../views/validator-views/sheet-validator-view';import { Inject, Injector, RxDisposable } from '@univerjs/core';import { DataValidatorRegistryService } from '@univerjs/data-validation';-import { DataValidationIcon } from '@univerjs/icons';-import { ComponentManager, IconManager } from '@univerjs/ui';+import { ComponentManager } from '@univerjs/ui';import { DATA_VALIDATION_PANEL } from '../commands/operations/data-validation.operation';import { DataValidationPanel } from '../views/components';import { DateShowTimeOption } from '../views/components/DateShowTimeOption';@@ -38,13 +37,11 @@ export class SheetsDataValidationUIController extends RxDisposable {constructor(@Inject(Injector) private readonly _injector: Injector,@Inject(ComponentManager) private readonly _componentManger: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@Inject(DataValidatorRegistryService) private readonly _dataValidatorRegistryService: DataValidatorRegistryService) {super();this._initComponents();- this._registerIcons();this._registerValidatorViews();}@@ -62,12 +59,6 @@ export class SheetsDataValidationUIController extends RxDisposable {});}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- DataValidationIcon,- }));- }-private _registerValidatorViews(): void {([DecimalValidatorView,diff --git a/packages/sheets-data-validation-ui/src/mobile-plugin.ts b/packages/sheets-data-validation-ui/src/mobile-plugin.tsindex 0a5806891f..28952ca734 100644--- a/packages/sheets-data-validation-ui/src/mobile-plugin.ts+++ b/packages/sheets-data-validation-ui/src/mobile-plugin.ts@@ -28,6 +28,7 @@ import {ToggleValidationPanelOperation,} from './commands/operations/data-validation.operation';import { defaultPluginConfig, SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DataValidationAlertController } from './controllers/dv-alert.controller';import { DataValidationAutoFillController } from './controllers/dv-auto-fill.controller';import { DataValidationCopyPasteController } from './controllers/dv-copy-paste.controller';@@ -65,6 +66,8 @@ export class UniverSheetsDataValidationMobileUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[DataValidationPanelService],[DataValidationDropdownManagerService],diff --git a/packages/sheets-data-validation-ui/src/plugin.ts b/packages/sheets-data-validation-ui/src/plugin.tsindex 50adf59ffc..09fe5cf6d3 100644--- a/packages/sheets-data-validation-ui/src/plugin.ts+++ b/packages/sheets-data-validation-ui/src/plugin.ts@@ -29,6 +29,7 @@ import {ToggleValidationPanelOperation,} from './commands/operations/data-validation.operation';import { defaultPluginConfig, SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DataValidationAlertController } from './controllers/dv-alert.controller';import { DataValidationAutoFillController } from './controllers/dv-auto-fill.controller';import { DataValidationCopyPasteController } from './controllers/dv-copy-paste.controller';@@ -68,6 +69,8 @@ export class UniverSheetsDataValidationUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[DataValidationPanelService],[DataValidationDropdownManagerService],diff --git a/packages/sheets-drawing-ui/src/controllers/components.controller.ts b/packages/sheets-drawing-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..cd1247b5c4--- /dev/null+++ b/packages/sheets-drawing-ui/src/controllers/components.controller.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 { Disposable, Inject } from '@univerjs/core';+import { ComponentManager } from '@univerjs/ui';+import { BATCH_SAVE_IMAGES_DIALOG_ID, BatchSaveImagesDialog } from '../views/batch-save-images';+import { COMPONENT_SHEET_DRAWING_PANEL } from '../views/sheet-image-panel/component-name';+import { SheetDrawingPanel } from '../views/sheet-image-panel/SheetDrawingPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ ) {+ super();++ this._registerComponents();+ }++ private _registerComponents(): void {+ this.disposeWithMe(this._componentManager.register(COMPONENT_SHEET_DRAWING_PANEL, SheetDrawingPanel));++ this.disposeWithMe(this._componentManager.register(BATCH_SAVE_IMAGES_DIALOG_ID, BatchSaveImagesDialog));+ }+}diff --git a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts b/packages/sheets-drawing-ui/src/controllers/ui.controller.tsindex c245e4283a..bea7086d3b 100644--- a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-drawing-ui/src/controllers/ui.controller.ts@@ -14,8 +14,8 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { ComponentManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';+import { Disposable, ICommandService } from '@univerjs/core';+import { IMenuManagerService, IShortcutService } from '@univerjs/ui';import { DeleteDrawingsCommand } from '../commands/commands/delete-drawings.command';import { FlipSheetDrawingCommand } from '../commands/commands/flip-drawings.command';import { GroupSheetDrawingCommand } from '../commands/commands/group-sheet-drawing.command';@@ -26,9 +26,6 @@ import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-dimport { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';import { SidebarSheetDrawingOperation } from '../commands/operations/open-drawing-panel.operation';import { menuSchema } from '../menu/schema';-import { BATCH_SAVE_IMAGES_DIALOG_ID, BatchSaveImagesDialog } from '../views/batch-save-images';-import { COMPONENT_SHEET_DRAWING_PANEL } from '../views/sheet-image-panel/component-name';-import { SheetDrawingPanel } from '../views/sheet-image-panel/SheetDrawingPanel';import {DeleteDrawingsShortcutItem,MoveDrawingDownShortcutItem,@@ -39,7 +36,6 @@ import {export class SheetDrawingUIController extends Disposable {constructor(- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@ICommandService private readonly _commandService: ICommandService,@IShortcutService private readonly _shortcutService: IShortcutService@@ -50,9 +46,6 @@ export class SheetDrawingUIController extends Disposable {}private _initCustomComponents(): void {- const componentManager = this._componentManager;- this.disposeWithMe(componentManager.register(COMPONENT_SHEET_DRAWING_PANEL, SheetDrawingPanel));- this.disposeWithMe(componentManager.register(BATCH_SAVE_IMAGES_DIALOG_ID, BatchSaveImagesDialog));}private _initMenus(): void {diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.tsindex 4cd470f97f..ca574f36d8 100644--- a/packages/sheets-drawing-ui/src/plugin.ts+++ b/packages/sheets-drawing-ui/src/plugin.ts@@ -34,6 +34,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { DrawingContextMenuController } from './controllers/drawing-context-menu.controller';import { SheetCellImageHoverRenderController } from './controllers/render-controllers/sheet-celll-image-hover.render-controller';import { SheetsDrawingRenderController } from './controllers/render-controllers/sheet-drawing.render-controller';@@ -80,6 +81,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {override onStarting(): void {registerDependencies(this._injector, [+ [ComponentsController],[SheetCanvasFloatDomManagerService],[SheetDrawingUIController],[DrawingPopupMenuController],@@ -97,6 +99,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {touchDependencies(this._injector, [[SheetCanvasFloatDomManagerService],]);+ this._injector.get(ComponentsController);}override onReady(): void {diff --git a/packages/sheets-drawing/src/services/__tests__/sheet-drawing.service.spec.ts b/packages/sheets-drawing/src/services/__tests__/sheet-drawing.service.spec.tsnew file mode 100644index 0000000000..0ff0c86ce9--- /dev/null+++ b/packages/sheets-drawing/src/services/__tests__/sheet-drawing.service.spec.ts@@ -0,0 +1,47 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ISheetDrawingService, SheetDrawingService } from '../sheet-drawing.service';++describe('SheetDrawingService', () => {+ let service: ISheetDrawingService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ISheetDrawingService, { useClass: SheetDrawingService }]);+ service = injector.get(ISheetDrawingService);+ });++ it('initializes sheet drawing data and notifies renderers about existing drawings', () => {+ const added: unknown[] = [];+ service.add$.subscribe((items) => added.push(items));+ service.registerDrawingData('book-1', {+ sheet1: {+ data: {+ image1: { drawingId: 'image1' },+ },+ order: ['image1'],+ },+ } as never);++ service.initializeNotification('book-1');++ expect(service.getDrawingData('book-1', 'sheet1')?.image1.drawingId).toBe('image1');+ expect(added).toEqual([[{ drawingId: 'image1', unitId: 'book-1', subUnitId: 'sheet1' }]]);+ });+});diff --git a/packages/sheets-filter-ui/src/controllers/components.controller.ts b/packages/sheets-filter-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..5d8baa720c--- /dev/null+++ b/packages/sheets-filter-ui/src/controllers/components.controller.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { FilterIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { FILTER_PANEL_POPUP_KEY, FilterPanel } from '../views/components/SheetsFilterPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerIcons();+ this._registerComponents();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ FilterIcon,+ }));+ }++ private _registerComponents(): void {+ ([+ [FILTER_PANEL_POPUP_KEY, FilterPanel],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }+}diff --git a/packages/sheets-filter-ui/src/controllers/sheets-filter-permission.controller.ts b/packages/sheets-filter-ui/src/controllers/sheets-filter-permission.controller.tsindex edc9acb559..b3b54cfeb7 100644--- a/packages/sheets-filter-ui/src/controllers/sheets-filter-permission.controller.ts+++ b/packages/sheets-filter-ui/src/controllers/sheets-filter-permission.controller.ts@@ -28,8 +28,6 @@ export interface IUniverSheetsFilterUIConfig {export const DefaultSheetFilterUiConfig = {};-export const FILTER_PANEL_POPUP_KEY = 'FILTER_PANEL_POPUP';-/*** This controller controls the UI of "filter" features. Menus, commands and filter panel etc. Except for the rendering.*/diff --git a/packages/sheets-filter-ui/src/controllers/ui.controller.ts b/packages/sheets-filter-ui/src/controllers/ui.controller.tsindex 580241319d..b84f75806c 100644--- a/packages/sheets-filter-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-filter-ui/src/controllers/ui.controller.ts@@ -18,10 +18,9 @@ import type { IDisposable, Nullable } from '@univerjs/core';import { ICommandService, IContextService, Inject, Injector, LocaleService } from '@univerjs/core';import { MessageType } from '@univerjs/design';import { IRenderManagerService } from '@univerjs/engine-render';-import { FilterIcon } from '@univerjs/icons';import { SheetsFilterService, SmartToggleSheetsFilterCommand } from '@univerjs/sheets-filter';import { SheetCanvasPopManagerService, SheetsRenderService } from '@univerjs/sheets-ui';-import { ComponentManager, IconManager, IMenuManagerService, IMessageService, IShortcutService } from '@univerjs/ui';+import { IMenuManagerService, IMessageService, IShortcutService } from '@univerjs/ui';import { distinctUntilChanged } from 'rxjs';import {ChangeFilterByOperation,@@ -31,20 +30,16 @@ import {} from '../commands/operations/sheets-filter.operation';import { menuSchema } from '../menu/schema';import { SheetsFilterPanelService } from '../services/sheets-filter-panel.service';-import { FilterPanel } from '../views/components/SheetsFilterPanel';+import { FILTER_PANEL_POPUP_KEY } from '../views/components/SheetsFilterPanel';import { SmartToggleFilterShortcut } from './sheets-filter.shortcut';import { SheetsFilterUIMobileController } from './ui-mobile.controller';-export const FILTER_PANEL_POPUP_KEY = 'FILTER_PANEL_POPUP';-/*** This controller controls the UI of "filter" features. Menus, commands and filter panel etc. Except for the rendering.*/export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileController {constructor(@Inject(Injector) private readonly _injector: Injector,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@Inject(SheetsFilterPanelService) private readonly _sheetsFilterPanelService: SheetsFilterPanelService,@Inject(SheetCanvasPopManagerService) private _sheetCanvasPopupService: SheetCanvasPopManagerService,@Inject(SheetsFilterService) private _sheetsFilterService: SheetsFilterService,@@ -63,7 +58,6 @@ export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileControlthis._initShortcuts();this._initMenuItems();this._initUI();- this._registerIcons();}override dispose(): void {@@ -96,14 +90,6 @@ export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileControl}private _initUI(): void {- ([- [FILTER_PANEL_POPUP_KEY, FilterPanel],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });-this.disposeWithMe(this._contextService.subscribeContextValue$(FILTER_PANEL_OPENED_KEY).pipe(distinctUntilChanged()).subscribe((open) => {@@ -125,12 +111,6 @@ export class SheetsFilterUIDesktopController extends SheetsFilterUIMobileControlprivate _popupDisposable?: Nullable<IDisposable>;- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- FilterIcon,- }));- }-private _openFilterPopup(): void {const currentFilterModel = this._sheetsFilterPanelService.filterModel;if (!currentFilterModel) {diff --git a/packages/sheets-filter-ui/src/mobile-plugin.ts b/packages/sheets-filter-ui/src/mobile-plugin.tsindex b16951bef3..f9b63062b9 100644--- a/packages/sheets-filter-ui/src/mobile-plugin.ts+++ b/packages/sheets-filter-ui/src/mobile-plugin.ts@@ -20,6 +20,7 @@ import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInsimport { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_FILTER_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { SheetsFilterPermissionController } from './controllers/sheets-filter-permission.controller';import { SheetsFilterUIMobileController } from './controllers/ui-mobile.controller';@@ -50,6 +51,8 @@ export class UniverSheetsFilterMobileUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[SheetsFilterPermissionController],[SheetsFilterUIMobileController],diff --git a/packages/sheets-filter-ui/src/plugin.ts b/packages/sheets-filter-ui/src/plugin.tsindex 853aa8084b..1419333dff 100644--- a/packages/sheets-filter-ui/src/plugin.ts+++ b/packages/sheets-filter-ui/src/plugin.ts@@ -31,6 +31,7 @@ import { IRPCChannelService, toModule } from '@univerjs/rpc';import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_FILTER_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { SheetsFilterPermissionController } from './controllers/sheets-filter-permission.controller';import { SheetsFilterUIDesktopController } from './controllers/ui.controller';import { SheetsFilterPanelService } from './services/sheets-filter-panel.service';@@ -70,6 +71,8 @@ export class UniverSheetsFilterUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, [[SheetsFilterPanelService],[SheetsFilterPermissionController],diff --git a/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.tsx b/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.tsxindex 33d1790f98..d284d2d046 100644--- a/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.tsx+++ b/packages/sheets-filter-ui/src/views/components/SheetsFilterPanel.tsx@@ -129,6 +129,7 @@ export function FilterPanel() {</div>);}+export const FILTER_PANEL_POPUP_KEY = 'FILTER_PANEL_POPUP';function useFilterByOptions(localeService: LocaleService) {const locale = localeService.getCurrentLocale();diff --git a/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.ts b/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.tsnew file mode 100644index 0000000000..b104961bbd--- /dev/null+++ b/packages/sheets-filter-ui/src/worker/__tests__/generate-filter-values.service.spec.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DesktopLogService, ILogService, Injector, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { SheetsGenerateFilterValuesService } from '../generate-filter-values.service';++describe('SheetsGenerateFilterValuesService', () => {+ let service: SheetsGenerateFilterValuesService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([LocaleService]);+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([IUniverInstanceService, { useValue: { getUnit: () => null } as unknown as IUniverInstanceService }]);+ injector.add([SheetsGenerateFilterValuesService]);+ service = injector.get(SheetsGenerateFilterValuesService);+ });++ it('returns no filter value tree when the workbook or worksheet is unavailable', async () => {+ await expect(service.getFilterValues({+ unitId: 'missing-book',+ subUnitId: 'sheet-1',+ filteredOutRowsByOtherColumns: [],+ filterColumn: null,+ filters: false,+ blankChecked: true,+ iterateRange: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 0 },+ alreadyChecked: [],+ })).resolves.toEqual([]);+ });+});diff --git a/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts b/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.tsnew file mode 100644index 0000000000..b83f821644--- /dev/null+++ b/packages/sheets-filter/src/services/__tests__/sheet-filter-formula.service.spec.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector, IUniverInstanceService } from '@univerjs/core';+import { IActiveDirtyManagerService, ISheetRowFilteredService } from '@univerjs/engine-formula';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { SheetsFilterFormulaService } from '../sheet-filter-formula.service';+import { SheetsFilterService } from '../sheet-filter.service';++describe('SheetsFilterFormulaService', () => {+ let dirtyConverters: Map<string, { getDirtyData: (commandInfo: unknown) => unknown }>;+ let rowFilteredCallback: ((unitId: string, subUnitId: string, row: number) => boolean) | undefined;++ beforeEach(() => {+ dirtyConverters = new Map();+ const injector = new Injector();+ injector.add([IActiveDirtyManagerService, { useValue: { register: (commandId: string, converter: never) => dirtyConverters.set(commandId, converter) } as unknown as IActiveDirtyManagerService }]);+ injector.add([ISheetRowFilteredService, { useValue: { register: (callback: never) => (rowFilteredCallback = callback) } as unknown as ISheetRowFilteredService }]);+ injector.add([SheetsFilterService, { useValue: { getFilterModel: vi.fn(() => ({ getRange: () => ({ startRow: 2, endRow: 5 }), isRowFiltered: (row: number) => row === 3 })) } as unknown as SheetsFilterService }]);+ injector.add([IUniverInstanceService, { useValue: { getUnit: () => ({ getSheetBySheetId: () => ({ getColumnCount: () => 10 }) }) } as unknown as IUniverInstanceService }]);+ injector.add([SheetsFilterFormulaService]);+ injector.get(SheetsFilterFormulaService);+ });++ it('marks the filtered row span dirty for formula recalculation', () => {+ const converter = [...dirtyConverters.values()][0];++ expect(converter.getDirtyData({ params: { unitId: 'book-1', subUnitId: 'sheet-1' } })).toEqual({+ dirtyRanges: [{+ unitId: 'book-1',+ sheetId: 'sheet-1',+ range: { startRow: 2, startColumn: 0, endRow: 5, endColumn: 9 },+ }],+ clearDependencyTreeCache: { 'book-1': { 'sheet-1': '1' } },+ });+ });++ it('registers formula row-filter lookups against the active sheet filter model', () => {+ expect(rowFilteredCallback?.('book-1', 'sheet-1', 3)).toBe(true);+ expect(rowFilteredCallback?.('book-1', 'sheet-1', 4)).toBe(false);+ });+});diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index 851b251600..0000000000--- a/packages/sheets-formula-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,57 +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 { ICommandService, Injector } from '@univerjs/core';-import type { IRenderManagerService } from '@univerjs/engine-render';-import type { ComponentManager, IconManager, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';-import { UniverInstanceType } from '@univerjs/core';-import { SheetsUIPart } from '@univerjs/sheets-ui';-import { describe, expect, it, vi } from 'vitest';-import { MORE_FUNCTIONS_COMPONENT } from '../../views/more-functions/interface';-import { FormulaUIController } from '../ui.controller';--describe('FormulaUIController', () => {- it('registers formula commands, menus, shortcuts, UI parts, and render modules', () => {- const mergeMenu = vi.fn();- const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));- const registerShortcut = vi.fn(() => ({ dispose: vi.fn() }));- const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));- const registerRenderModule = vi.fn(() => ({ dispose: vi.fn() }));- const componentRegister = vi.fn();- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));- const injector = {};-- const controller = new FormulaUIController(- injector as Injector,- { mergeMenu } as unknown as IMenuManagerService,- { registerCommand } as unknown as ICommandService,- { registerShortcut } as unknown as IShortcutService,- { registerComponent } as unknown as IUIPartsService,- { registerRenderModule } as unknown as IRenderManagerService,- { register: componentRegister } as unknown as ComponentManager,- { register: registerIcon } as unknown as IconManager- );-- expect(controller).toBeTruthy();- expect(mergeMenu).toHaveBeenCalledTimes(1);- expect(registerCommand).toHaveBeenCalledTimes(7);- expect(registerShortcut.mock.calls.length).toBeLessThan(3);- expect(registerComponent).toHaveBeenCalledWith(SheetsUIPart.FORMULA_AUX, expect.any(Function));- expect(componentRegister).toHaveBeenCalledWith(MORE_FUNCTIONS_COMPONENT, expect.any(Function));- expect(registerIcon).toHaveBeenCalledWith({ FunctionIcon: expect.any(Object) });- expect(registerRenderModule).toHaveBeenCalledWith(UniverInstanceType.UNIVER_SHEET, [expect.any(Function)]);- });-});diff --git a/packages/sheets-formula-ui/src/controllers/components.controller.ts b/packages/sheets-formula-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..9c7ade4d89--- /dev/null+++ b/packages/sheets-formula-ui/src/controllers/components.controller.ts@@ -0,0 +1,53 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { FunctionIcon } from '@univerjs/icons';+import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { FormulaEditor } from '../views/formula-editor/index';+import { MORE_FUNCTIONS_COMPONENT } from '../views/more-functions/interface';+import { MoreFunctions } from '../views/more-functions/MoreFunctions';+import { RangeSelector } from '../views/range-selector';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents2();+ this._registerIcons();+ this._registerComponents();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ FunctionIcon,+ }));+ }++ private _registerComponents(): void {+ this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MoreFunctions);+ }++ private _registerComponents2(): void {+ this.disposeWithMe(this._componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, RangeSelector));++ this.disposeWithMe(this._componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, FormulaEditor));+ }+}diff --git a/packages/sheets-formula-ui/src/controllers/ui.controller.ts b/packages/sheets-formula-ui/src/controllers/ui.controller.tsindex 7a506be418..2f748059f4 100644--- a/packages/sheets-formula-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-formula-ui/src/controllers/ui.controller.ts@@ -17,9 +17,8 @@import type { Dependency } from '@univerjs/core';import { Disposable, ICommandService, Inject, Injector, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import { FunctionIcon } from '@univerjs/icons';import { SheetsUIPart } from '@univerjs/sheets-ui';-import { ComponentManager, connectInjector, IconManager, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';+import { connectInjector, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';import { SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand } from '../commands/commands/formula-clipboard.command';import { HelpFunctionOperation } from '../commands/operations/help-function.operation';import { InsertFunctionOperation } from '../commands/operations/insert-function.operation';@@ -28,8 +27,6 @@ import { ReferenceAbsoluteOperation } from '../commands/operations/reference-absimport { SearchFunctionOperation } from '../commands/operations/search-function.operation';import { menuSchema } from '../menu/schema';import { FormulaProgressBar } from '../views/formula-progress/FormulaProgress';-import { MORE_FUNCTIONS_COMPONENT } from '../views/more-functions/interface';-import { MoreFunctions } from '../views/more-functions/MoreFunctions';import { FormulaEditorShowController } from './formula-editor-show.controller';import { ChangeRefToAbsoluteShortcut } from './shortcuts/prompt.shortcut';import { QuickSumShortcut } from './shortcuts/quick-sum.shortcut';@@ -41,9 +38,7 @@ export class FormulaUIController extends Disposable {@ICommandService private readonly _commandService: ICommandService,@IShortcutService private readonly _shortcutService: IShortcutService,@IUIPartsService private readonly _uiPartsService: IUIPartsService,- @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @IRenderManagerService private readonly _renderManagerService: IRenderManagerService) {super();@@ -53,7 +48,6 @@ export class FormulaUIController extends Disposable {private _initialize(): void {this._registerCommands();this._registerMenus();- this._registerIcons();this._registerShortcuts();this._registerComponents();this._registerRenderModules();@@ -63,12 +57,6 @@ export class FormulaUIController extends Disposable {this._menuManagerService.mergeMenu(menuSchema);}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- FunctionIcon,- }));- }-private _registerCommands(): void {[SheetCopyFormulaOnlyCommand,@@ -92,8 +80,6 @@ export class FormulaUIController extends Disposable {private _registerComponents(): void {this.disposeWithMe(this._uiPartsService.registerComponent(SheetsUIPart.FORMULA_AUX, () => connectInjector(FormulaProgressBar, this._injector)));-- this._componentManager.register(MORE_FUNCTIONS_COMPONENT, MoreFunctions);}private _registerRenderModules(): void {diff --git a/packages/sheets-formula-ui/src/plugin.ts b/packages/sheets-formula-ui/src/plugin.tsindex 8ff8ea12b7..6930757071 100644--- a/packages/sheets-formula-ui/src/plugin.ts+++ b/packages/sheets-formula-ui/src/plugin.ts@@ -29,14 +29,14 @@ import {} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { UniverSheetsFormulaPlugin } from '@univerjs/sheets-formula';-import { EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, RANGE_SELECTOR_COMPONENT_KEY } from '@univerjs/sheets-ui';-import { BuiltInUIPart, ComponentManager, connectInjector, IUIPartsService } from '@univerjs/ui';+import { BuiltInUIPart, connectInjector, IUIPartsService } from '@univerjs/ui';import pkg from '../package.json';import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';import {defaultPluginConfig,PLUGIN_CONFIG_KEY_BASE,} from './config/config';+import { ComponentsController } from './controllers/components.controller';import { FormulaAlertRenderController } from './controllers/formula-alert-render.controller';import { FormulaClipboardController } from './controllers/formula-clipboard.controller';import { FormulaEditorShowController } from './controllers/formula-editor-show.controller';@@ -47,8 +47,6 @@ import { FormulaUIController } from './controllers/ui.controller';import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';import { GlobalRangeSelectorService } from './services/range-selector.service';import { RefSelectionsRenderService } from './services/render-services/ref-selections.render.service';-import { FormulaEditor } from './views/formula-editor/index';-import { RangeSelector } from './views/range-selector';import { GlobalRangeSelector } from './views/range-selector/Global';/**@@ -82,6 +80,8 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, [[IFormulaPromptService, { useClass: FormulaPromptService }],[GlobalRangeSelectorService],@@ -125,9 +125,6 @@ export class UniverSheetsFormulaUIPlugin extends Plugin {}private _initUIPart(): void {- const componentManager = this._injector.get(ComponentManager);- this.disposeWithMe(componentManager.register(RANGE_SELECTOR_COMPONENT_KEY, RangeSelector));- this.disposeWithMe(componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, FormulaEditor));this.disposeWithMe(this._uiPartsService.registerComponent(BuiltInUIPart.GLOBAL, () => connectInjector(GlobalRangeSelector, this._injector)));}}diff --git a/packages/sheets-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index 8e808178c8..0000000000--- a/packages/sheets-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,47 +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 { SheetsHyperLinkUIController } from '../ui.controller';--describe('SheetsHyperLinkUIController', () => {- it('should register components, commands, menu and shortcut', () => {- const componentManager = { register: vi.fn() } as any;- const iconManager = { register: vi.fn() } as any;- const commandService = { registerCommand: vi.fn() } as any;- const menuManagerService = { mergeMenu: vi.fn() } as any;- const injector = {} as any;- const shortcutService = { registerShortcut: vi.fn() } as any;-- const controller = new SheetsHyperLinkUIController(- componentManager,- iconManager,- commandService,- menuManagerService,- injector,- shortcutService- );-- expect(componentManager.register).toHaveBeenCalled();-- expect(commandService.registerCommand).toHaveBeenCalled();- expect(menuManagerService.mergeMenu).toHaveBeenCalled();- expect(shortcutService.registerShortcut).toHaveBeenCalled();-- controller.dispose();- });-});diff --git a/packages/sheets-hyper-link-ui/src/controllers/components.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..20cc3ac128--- /dev/null+++ b/packages/sheets-hyper-link-ui/src/controllers/components.controller.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { LinkIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { CellLinkEdit } from '../views/CellLinkEdit';+import { CellLinkPopup } from '../views/CellLinkPopup';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [CellLinkPopup.componentKey, CellLinkPopup],+ [CellLinkEdit.componentKey, CellLinkEdit],+ ] as const).forEach(([key, comp]) => {+ this._componentManager.register(key, comp);+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ LinkIcon,+ }));+ }+}diff --git a/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts b/packages/sheets-hyper-link-ui/src/controllers/ui.controller.tsindex b8b6214672..51370e254a 100644--- a/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-hyper-link-ui/src/controllers/ui.controller.ts@@ -15,13 +15,10 @@*/import { Disposable, ICommandService, Inject, Injector } from '@univerjs/core';-import { LinkIcon } from '@univerjs/icons';import { ComponentManager, IconManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';import { CloseHyperLinkPopupOperation, InsertHyperLinkOperation, InsertHyperLinkToolbarOperation, OpenHyperLinkEditPanelOperation } from '../commands/operations/popup.operations';import { InsertLinkShortcut } from '../menu/menu';import { menuSchema } from '../menu/schema';-import { CellLinkEdit } from '../views/CellLinkEdit';-import { CellLinkPopup } from '../views/CellLinkPopup';export class SheetsHyperLinkUIController extends Disposable {constructor(@@ -33,29 +30,11 @@ export class SheetsHyperLinkUIController extends Disposable {@Inject(IShortcutService) private _shortcutService: IShortcutService) {super();-- this._initComponents();- this._registerIcons();this._initCommands();this._initMenus();this._initShortCut();}- private _initComponents() {- ([- [CellLinkPopup.componentKey, CellLinkPopup],- [CellLinkEdit.componentKey, CellLinkEdit],- ] as const).forEach(([key, comp]) => {- this._componentManager.register(key, comp);- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- LinkIcon,- }));- }-private _initCommands() {[OpenHyperLinkEditPanelOperation,diff --git a/packages/sheets-hyper-link-ui/src/plugin.ts b/packages/sheets-hyper-link-ui/src/plugin.tsindex b4f1997b33..b4701b5652 100644--- a/packages/sheets-hyper-link-ui/src/plugin.ts+++ b/packages/sheets-hyper-link-ui/src/plugin.ts@@ -23,6 +23,7 @@ import { UniverSheetsHyperLinkPlugin } from '@univerjs/sheets-hyper-link';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_HYPER_LINK_UI_PLUGIN_CONFIG_KEY } from './config/config';import { SheetsHyperLinkAutoFillController } from './controllers/auto-fill.controller';+import { ComponentsController } from './controllers/components.controller';import { SheetsHyperLinkCopyPasteController } from './controllers/copy-paste.controller';import { SheetsHyperLinkPermissionController } from './controllers/hyper-link-permission.controller';import { SheetsHyperLinkPopupController } from './controllers/popup.controller';@@ -61,6 +62,8 @@ export class UniverSheetsHyperLinkUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);const dependencies: Dependency[] = [[SheetsHyperLinkResolverService],[SheetsHyperLinkPopupService],diff --git a/packages/sheets-note-ui/src/controllers/components.controller.ts b/packages/sheets-note-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..eb45c5776c--- /dev/null+++ b/packages/sheets-note-ui/src/controllers/components.controller.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { AddNoteIcon, DeleteNoteIcon, HideNoteIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { SHEET_NOTE_COMPONENT } from '../views/config';+import { SheetsNote } from '../views/Note';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [SHEET_NOTE_COMPONENT, SheetsNote],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ AddNoteIcon,+ DeleteNoteIcon,+ HideNoteIcon,+ }));+ }+}diff --git a/packages/sheets-note-ui/src/controllers/ui.controller.ts b/packages/sheets-note-ui/src/controllers/ui.controller.tsindex 66494aa376..fd081e25b0 100644--- a/packages/sheets-note-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-note-ui/src/controllers/ui.controller.ts@@ -15,46 +15,20 @@*/import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { AddNoteIcon, DeleteNoteIcon, HideNoteIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IMenuManagerService } from '@univerjs/ui';+import { IMenuManagerService } from '@univerjs/ui';import { AddNotePopupOperation } from '../commands/operations/add-note-popup.operation';import { menuSchema } from '../menu/schema';-import { SHEET_NOTE_COMPONENT } from '../views/config';-import { SheetsNote } from '../views/Note';export class SheetsNoteUIController extends Disposable {constructor(- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@Inject(IMenuManagerService) private readonly _menuManagerService: IMenuManagerService,@ICommandService private readonly _commandService: ICommandService) {super();-- this._initComponents();- this._registerIcons();this._initMenu();this._initCommands();}- private _initComponents() {- ([- [SHEET_NOTE_COMPONENT, SheetsNote],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- AddNoteIcon,- DeleteNoteIcon,- HideNoteIcon,- }));- }-private _initMenu() {this._menuManagerService.mergeMenu(menuSchema);}diff --git a/packages/sheets-note-ui/src/plugin.ts b/packages/sheets-note-ui/src/plugin.tsindex 2c98b9cf33..13659574e3 100644--- a/packages/sheets-note-ui/src/plugin.ts+++ b/packages/sheets-note-ui/src/plugin.ts@@ -29,6 +29,7 @@ import {import { UniverSheetsNotePlugin } from '@univerjs/sheets-note';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_NOTE_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { SheetsCellContentController } from './controllers/sheets-cell-content.controller';import { SheetsNoteAttachmentController } from './controllers/sheets-note-attachment.controller';import { SheetsNotePopupController } from './controllers/sheets-note-popup.controller';@@ -61,6 +62,8 @@ export class UniverSheetsNoteUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[SheetsNotePopupService],[SheetsCellContentController],diff --git a/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.ts b/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.tsnew file mode 100644index 0000000000..bae203e699--- /dev/null+++ b/packages/sheets-note-ui/src/services/__tests__/sheets-note-popup.service.spec.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { CellPopupManagerService } from '@univerjs/sheets-ui';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { SheetsNotePopupService } from '../sheets-note-popup.service';++describe('SheetsNotePopupService', () => {+ let service: SheetsNotePopupService;+ let popupDispose: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ popupDispose = vi.fn();+ const injector = new Injector();+ injector.add([CellPopupManagerService, { useValue: { showPopup: vi.fn(() => ({ dispose: popupDispose })) } }]);+ injector.add([SheetsNotePopupService]);+ service = injector.get(SheetsNotePopupService);+ });++ it('shows a temporary note popup and hides it when requested', () => {+ const active: unknown[] = [];+ service.activePopup$.subscribe((popup) => active.push(popup));++ service.showPopup({ unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2, noteId: 'note-1', temp: true });+ service.hidePopup();++ expect(service.activePopup).toBeNull();+ expect(active.at(-2)).toEqual({ unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2, noteId: 'note-1', temp: true });+ expect(active.at(-1)).toBeNull();+ expect(popupDispose).toHaveBeenCalledTimes(1);+ });++ it('persists an opened temporary note popup', () => {+ service.showPopup({ unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2, temp: true });++ service.persistPopup();++ expect(service.activePopup?.temp).toBe(false);+ });+});diff --git a/packages/sheets-numfmt-ui/src/controllers/components.controller.ts b/packages/sheets-numfmt-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..af448e2b02--- /dev/null+++ b/packages/sheets-numfmt-ui/src/controllers/components.controller.ts@@ -0,0 +1,65 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { AddDigitsIcon, DollarIcon, EuroIcon, PercentIcon, ReduceDigitsIcon, RmbIcon, RoubleIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { MORE_NUMFMT_TYPE_KEY, MoreNumfmtType, Options, OPTIONS_KEY } from '../views/components/MoreNumfmtType';+import { SheetNumfmtPanel } from '../views/SheetNumfmtPanel';++const SHEET_NUMFMT_PANEL = 'SHEET_NUMFMT_PANEL';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ this._registerComponents2();+ }++ private _registerComponents(): void {+ this.disposeWithMe(+ this._componentManager.register(SHEET_NUMFMT_PANEL, SheetNumfmtPanel)+ );+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ AddDigitsIcon,+ DollarIcon,+ EuroIcon,+ PercentIcon,+ ReduceDigitsIcon,+ RmbIcon,+ RoubleIcon,+ }));+ }++ private _registerComponents2(): void {+ ([+ [MORE_NUMFMT_TYPE_KEY, MoreNumfmtType],+ [OPTIONS_KEY, Options],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }+}diff --git a/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts b/packages/sheets-numfmt-ui/src/controllers/ui.controller.tsindex 36d87fecb8..b3df3e89b2 100644--- a/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-numfmt-ui/src/controllers/ui.controller.ts@@ -49,7 +49,6 @@ import { combineLatest, merge, Observable } from 'rxjs';import { debounceTime, map, switchMap, tap } from 'rxjs/operators';import { CloseNumfmtPanelOperator } from '../commands/operations/close.numfmt.panel.operation';import { OpenNumfmtPanelOperator } from '../commands/operations/open.numfmt.panel.operation';-import { SheetNumfmtPanel } from '../views/SheetNumfmtPanel';const SHEET_NUMFMT_PANEL = 'SHEET_NUMFMT_PANEL';@@ -77,7 +76,6 @@ export class SheetNumfmtUIController extends Disposable {super();this._initRealTimeRenderingInterceptor();- this._initPanel();this._initCommands();this._initCloseListener();this._commandExecutedListener();@@ -186,12 +184,6 @@ export class SheetNumfmtUIController extends Disposable {});}- private _initPanel() {- this.disposeWithMe(- this._componentManager.register(SHEET_NUMFMT_PANEL, SheetNumfmtPanel)- );- }-// eslint-disable-next-line max-lines-per-functionprivate _initRealTimeRenderingInterceptor() {const isPanelOpenObserver = new Observable<boolean>((subscriber) => {diff --git a/packages/sheets-numfmt-ui/src/menu/numfmt.menu.controller.ts b/packages/sheets-numfmt-ui/src/menu/numfmt.menu.controller.tsindex 5b525c2c47..4c06263e5d 100644--- a/packages/sheets-numfmt-ui/src/menu/numfmt.menu.controller.ts+++ b/packages/sheets-numfmt-ui/src/menu/numfmt.menu.controller.ts@@ -15,15 +15,12 @@*/import { Disposable, Inject } from '@univerjs/core';-import { AddDigitsIcon, DollarIcon, EuroIcon, PercentIcon, ReduceDigitsIcon, RmbIcon, RoubleIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IMenuManagerService } from '@univerjs/ui';-import { MORE_NUMFMT_TYPE_KEY, MoreNumfmtType, Options, OPTIONS_KEY } from '../views/components/MoreNumfmtType';+import { ComponentManager, IMenuManagerService } from '@univerjs/ui';import { menuSchema } from './schema';export class NumfmtMenuController extends Disposable {constructor(@Inject(ComponentManager) private _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService) {super();@@ -33,23 +30,5 @@ export class NumfmtMenuController extends Disposable {private _initMenu() {this._menuManagerService.mergeMenu(menuSchema);- this.disposeWithMe(this._iconManager.register({- AddDigitsIcon,- DollarIcon,- EuroIcon,- PercentIcon,- ReduceDigitsIcon,- RmbIcon,- RoubleIcon,- }));-- ([- [MORE_NUMFMT_TYPE_KEY, MoreNumfmtType],- [OPTIONS_KEY, Options],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });}}diff --git a/packages/sheets-numfmt-ui/src/plugin.ts b/packages/sheets-numfmt-ui/src/plugin.tsindex eb3a541358..1ccc3be1e9 100644--- a/packages/sheets-numfmt-ui/src/plugin.ts+++ b/packages/sheets-numfmt-ui/src/plugin.ts@@ -32,6 +32,7 @@ import { UniverSheetsNumfmtPlugin } from '@univerjs/sheets-numfmt';import { UniverSheetsUIPlugin } from '@univerjs/sheets-ui';import pkg from '../package.json';import { defaultPluginConfig } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { NumfmtAlertRenderController } from './controllers/numfmt-alert-render.controller';import { NumfmtRepeatLastActionController } from './controllers/numfmt-repeat-last-action.controller';import { NumfmtEditorController } from './controllers/numfmt.editor.controller';@@ -68,6 +69,8 @@ export class UniverSheetsNumfmtUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, [[SheetNumfmtUIController],[NumfmtEditorController],diff --git a/packages/sheets-sort-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/sheets-sort-ui/src/controllers/__tests__/ui.controller.spec.tsdeleted file mode 100644index 2b24993b9d..0000000000--- a/packages/sheets-sort-ui/src/controllers/__tests__/ui.controller.spec.ts+++ /dev/null@@ -1,138 +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 { IDisposable, Univer } from '@univerjs/core';-import { ICommandService, IConfirmService, Injector, RANGE_TYPE, TestConfirmService } from '@univerjs/core';-import { SheetsSelectionsService } from '@univerjs/sheets';-import { SheetsRenderService } from '@univerjs/sheets-ui';-import { ComponentManager, IconManager, IDialogService, ILayoutService, IMenuManagerService, IUIPartsService } from '@univerjs/ui';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';-import { SortRangeCustomCommand } from '../../commands/commands/sheets-sort.command';-import { SheetsSortUIService } from '../../services/sheets-sort-ui.service';-import { SheetsSortUIController } from '../ui.controller';--function createDisposable(): IDisposable {- return {- dispose: vi.fn(),- };-}--describe('SheetsSortUIController', () => {- let univer: Univer;- let get: Injector['get'];- let commandService: ICommandService;-- beforeEach(() => {- vi.stubGlobal('window', {- innerWidth: 1440,- });-- const menuManagerService = {- mergeMenu: vi.fn(),- };- const dialogService = {- open: vi.fn(() => createDisposable()),- close: vi.fn(),- };- const layoutService = {- focus: vi.fn(),- };- const uiPartsService = {- registerComponent: vi.fn(() => createDisposable()),- };- const sheetsRenderService = {- registerSkeletonChangingMutations: vi.fn(() => createDisposable()),- };- const componentManager = {- register: vi.fn(() => createDisposable()),- };- const iconManager = {- register: vi.fn(() => createDisposable()),- };-- const testBed = createCommandTestBed(undefined, [- [IConfirmService, { useClass: TestConfirmService }],- [IMenuManagerService, { useValue: menuManagerService as unknown as IMenuManagerService }],- [IDialogService, { useValue: dialogService as unknown as IDialogService }],- [ILayoutService, { useValue: layoutService as unknown as ILayoutService }],- [IUIPartsService, { useValue: uiPartsService as unknown as IUIPartsService }],- [SheetsRenderService, { useValue: sheetsRenderService as unknown as SheetsRenderService }],- [ComponentManager, { useValue: componentManager as unknown as ComponentManager }],- [IconManager, { useValue: iconManager as unknown as IconManager }],- ]);-- univer = testBed.univer;- get = testBed.get;- commandService = get(ICommandService);- get(Injector).createInstance(SheetsSortUIController);- });-- afterEach(() => {- vi.unstubAllGlobals();- univer.dispose();- });-- it('opens and closes the custom sort dialog from the real command and service state', async () => {- get(SheetsSelectionsService).addSelections([{- range: {- startRow: 0,- startColumn: 9,- endRow: 6,- endColumn: 11,- rangeType: RANGE_TYPE.NORMAL,- },- primary: {- actualRow: 0,- actualColumn: 9,- startRow: 0,- startColumn: 9,- endRow: 6,- endColumn: 11,- isMerged: false,- isMergedMainCell: false,- },- style: null,- }]);-- expect(await commandService.executeCommand(SortRangeCustomCommand.id)).toBe(true);-- const dialogService = get(IDialogService) as unknown as { open: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> };- const sortUIService = get(SheetsSortUIService);-- expect(dialogService.open).toHaveBeenCalledWith(expect.objectContaining({- id: 'custom-sort-dialog',- children: { label: 'CustomSortPanel' },- title: expect.objectContaining({- title: expect.stringContaining('J1:L7'),- }),- }));- expect(sortUIService.customSortState()).toEqual(expect.objectContaining({- show: true,- location: expect.objectContaining({- subUnitId: 'sheet1',- }),- }));-- sortUIService.closeCustomSortPanel();- await Promise.resolve();-- const layoutService = get(ILayoutService) as unknown as { focus: ReturnType<typeof vi.fn> };- expect(dialogService.close).toHaveBeenCalledWith('custom-sort-dialog');- expect(layoutService.focus).toHaveBeenCalled();- expect(sortUIService.customSortState()).toEqual({ show: false });- });-});diff --git a/packages/sheets-sort-ui/src/controllers/components.controller.ts b/packages/sheets-sort-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..4cf72fb866--- /dev/null+++ b/packages/sheets-sort-ui/src/controllers/components.controller.ts@@ -0,0 +1,52 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { AscendingIcon, CustomSortIcon, DescendingIcon, ExpandAscendingIcon, ExpandDescendingIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { CustomSortPanel } from '../views/CustomSortPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerIcons();+ this._registerComponents();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ AscendingIcon,+ ExpandAscendingIcon,+ DescendingIcon,+ ExpandDescendingIcon,+ CustomSortIcon,+ }));+ }++ private _registerComponents(): void {+ ([+ ['CustomSortPanel', CustomSortPanel],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }+}diff --git a/packages/sheets-sort-ui/src/controllers/ui.controller.ts b/packages/sheets-sort-ui/src/controllers/ui.controller.tsindex 1f0fce7238..5409c2dd55 100644--- a/packages/sheets-sort-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-sort-ui/src/controllers/ui.controller.ts@@ -18,13 +18,10 @@ import type { UIPartsService } from '@univerjs/ui';import type { ISheetSortLocation } from '../services/sheets-sort-ui.service';import { ICommandService, Inject, Injector, LocaleService, RxDisposable } from '@univerjs/core';import { serializeRange } from '@univerjs/engine-formula';-import { AscendingIcon, CustomSortIcon, DescendingIcon, ExpandAscendingIcon, ExpandDescendingIcon } from '@univerjs/icons';import { SortRangeCommand } from '@univerjs/sheets-sort';import { SheetsRenderService, SheetsUIPart } from '@univerjs/sheets-ui';import {- ComponentManager,connectInjector,- IconManager,IDialogService,ILayoutService,IMenuManagerService,@@ -45,7 +42,6 @@ import {} from '../commands/commands/sheets-sort.command';import { menuSchema } from '../menu/schema';import { SheetsSortUIService } from '../services/sheets-sort-ui.service';-import { CustomSortPanel } from '../views/CustomSortPanel';import EmbedSortBtn from '../views/EmbedSortBtn';const CUSTOM_SORT_DIALOG_ID = 'custom-sort-dialog';@@ -62,15 +58,12 @@ export class SheetsSortUIController extends RxDisposable {@Inject(SheetsRenderService) private _sheetRenderService: SheetsRenderService,@Inject(LocaleService) private readonly _localeService: LocaleService,@Inject(SheetsSortUIService) private readonly _sheetsSortUIService: SheetsSortUIService,- @Inject(Injector) private _injector: Injector,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @Inject(Injector) private _injector: Injector) {super();this._initCommands();this._initMenu();this._initUI();- this._registerIcons();}private _initMenu() {@@ -100,14 +93,6 @@ export class SheetsSortUIController extends RxDisposable {this._uiPartsService.registerComponent(SheetsUIPart.FILTER_PANEL_EMBED_POINT, () => connectInjector(EmbedSortBtn, this._injector)));- ([- ['CustomSortPanel', CustomSortPanel],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });-// this controller is also responsible for toggling the CustomSortDialogthis._sheetsSortUIService.customSortState$.pipe(takeUntil(this.dispose$)).subscribe((newState) => {if (newState && newState.show && newState.location) {@@ -138,16 +123,6 @@ export class SheetsSortUIController extends RxDisposable {queueMicrotask(() => this._layoutService.focus());}-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- AscendingIcon,- ExpandAscendingIcon,- DescendingIcon,- ExpandDescendingIcon,- CustomSortIcon,- }));- }}function getCustomSortDialogDefaultPosition(): { x: number; y: number } {diff --git a/packages/sheets-sort-ui/src/plugin.ts b/packages/sheets-sort-ui/src/plugin.tsindex cc9395253c..0deb46d28c 100644--- a/packages/sheets-sort-ui/src/plugin.ts+++ b/packages/sheets-sort-ui/src/plugin.ts@@ -28,6 +28,7 @@ import {import { UniverSheetsSortPlugin } from '@univerjs/sheets-sort';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_SORT_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { SheetsSortUIController } from './controllers/ui.controller';import { SheetsSortUIService } from './services/sheets-sort-ui.service';@@ -55,6 +56,8 @@ export class UniverSheetsSortUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[SheetsSortUIService],[SheetsSortUIController],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.tsnew file mode 100644index 0000000000..cc484aec7d--- /dev/null+++ b/packages/sheets-sort/src/services/__tests__/sheets-sort.service.spec.ts@@ -0,0 +1,49 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import 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 { SheetsSortService } from '../sheets-sort.service';++describe('SheetsSortService', () => {+ let service: SheetsSortService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);+ injector.add([ICommandService, { useValue: { executeCommand: async () => true } as unknown as ICommandService }]);+ injector.add([FormulaDataModel, { useValue: { getArrayFormulaRange: () => ({}) } as unknown as FormulaDataModel }]);+ injector.add([SheetsSortService]);+ service = injector.get(SheetsSortService);+ });++ it('requires multi-row ranges for sort actions', () => {+ expect(service.singleCheck({ unitId: 'book-1', subUnitId: 'sheet-1', range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 2 } })).toBe(false);+ expect(service.singleCheck({ unitId: 'book-1', subUnitId: 'sheet-1', range: { startRow: 2, endRow: 4, startColumn: 0, endColumn: 2 } })).toBe(true);+ });++ it('uses the most recently registered comparator first', () => {+ const first: ICellValueCompareFn = () => 1;+ const second: ICellValueCompareFn = () => -1;++ service.registerCompareFn(first);+ service.registerCompareFn(second);++ expect(service.getAllCompareFns()).toEqual([second, first]);+ });+});diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.tsdeleted file mode 100644index a058f9e159..0000000000--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-component.controller.spec.ts+++ /dev/null@@ -1,129 +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 { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';-import { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../../const';-import { SheetsTableComponentController } from '../sheet-table-component.controller';--describe('SheetsTableComponentController', () => {- it('should open and close popup based on context state', () => {- const context$ = new Subject<boolean | undefined>();- const setContextValue = vi.fn();-- const popupDispose = vi.fn();- const attachPopupToCell = vi.fn(() => ({ dispose: popupDispose }));- const dialogClose = vi.fn();-- const controller = new SheetsTableComponentController(- { register: vi.fn(() => ({ dispose: vi.fn() })) } as any,- {- subscribeContextValue$: () => context$,- getContextValue: () => false,- setContextValue,- } as any,- { attachPopupToCell } as any,- { close: dialogClose } as any- );-- controller.setCurrentTableFilterInfo({- unitId: 'u1',- subUnitId: 's1',- tableId: 't1',- column: 2,- row: 4,- });-- context$.next(true);-- expect(attachPopupToCell).toHaveBeenCalledWith(4, 2, expect.objectContaining({- componentKey: SHEETS_TABLE_FILTER_PANEL_OPENED_KEY,- direction: 'horizontal',- offset: [5, 0],- portal: true,- }));-- const popupCalls = attachPopupToCell.mock.calls as Array<Array<any>>;- const options = popupCalls[0]?.[2] as { onClickOutside: () => void } | undefined;- expect(options).toBeDefined();- options?.onClickOutside();- expect(dialogClose).toHaveBeenCalledWith(UNIVER_SHEET_TABLE_FILTER_PANEL_ID);- expect(setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);-- context$.next(false);- expect(popupDispose).toHaveBeenCalled();- expect(controller.getCurrentTableFilterInfo()).toBeNull();-- controller.closeFilterPanel();- expect(setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);-- controller.dispose();- });-- it('should toggle the same filter panel and switch directly to another column', () => {- const context$ = new Subject<boolean | undefined>();- let opened = false;- const setContextValue = vi.fn((_key, value) => {- opened = value;- });-- const firstPopupDispose = vi.fn();- const secondPopupDispose = vi.fn();- const attachPopupToCell = vi- .fn()- .mockReturnValueOnce({ dispose: firstPopupDispose })- .mockReturnValueOnce({ dispose: secondPopupDispose });-- const controller = new SheetsTableComponentController(- { register: vi.fn(() => ({ dispose: vi.fn() })) } as any,- {- subscribeContextValue$: () => context$,- getContextValue: () => opened,- setContextValue,- } as any,- { attachPopupToCell } as any,- { close: vi.fn() } as any- );-- const firstInfo = {- unitId: 'u1',- subUnitId: 's1',- tableId: 't1',- column: 2,- row: 4,- };- const secondInfo = {- ...firstInfo,- column: 3,- };-- controller.openOrToggleFilterPanel(firstInfo);- expect(setContextValue).toHaveBeenCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, true);-- context$.next(true);- expect(attachPopupToCell).toHaveBeenCalledWith(4, 2, expect.any(Object));-- controller.openOrToggleFilterPanel(secondInfo);- expect(firstPopupDispose).toHaveBeenCalledTimes(1);- expect(attachPopupToCell).toHaveBeenLastCalledWith(4, 3, expect.any(Object));- expect(controller.getCurrentTableFilterInfo()).toEqual(secondInfo);-- controller.openOrToggleFilterPanel(secondInfo);- expect(setContextValue).toHaveBeenLastCalledWith(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, false);-- controller.dispose();- });-});diff --git a/packages/sheets-table-ui/src/controllers/components.controller.ts b/packages/sheets-table-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..804c876177--- /dev/null+++ b/packages/sheets-table-ui/src/controllers/components.controller.ts@@ -0,0 +1,61 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { TableIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { SHEET_TABLE_RENAME_DIALOG, SHEET_TABLE_THEME_PANEL, SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, TABLE_SELECTOR_DIALOG } from '../const';+import { SheetTableFilterPanel } from '../views/components/SheetTableFilterPanel';+import { SheetTableRenameDialog } from '../views/components/SheetTableRenameDialog';+import { SheetTableSelector } from '../views/components/SheetTableSelector';+import { SheetTableThemePanel } from '../views/components/SheetTableThemePanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerComponents2();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, SheetTableFilterPanel],+ [SHEET_TABLE_RENAME_DIALOG, SheetTableRenameDialog],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(this._componentManager.register(key, comp));+ });+ }++ private _registerComponents2(): void {+ ([+ [TABLE_SELECTOR_DIALOG, SheetTableSelector],+ [SHEET_TABLE_THEME_PANEL, SheetTableThemePanel],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(this._componentManager.register(key, comp));+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ TableIcon,+ }));+ }+}diff --git a/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts b/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.tsindex 5ebab2ec6c..1dfc0cfbc7 100644--- a/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts+++ b/packages/sheets-table-ui/src/controllers/sheet-table-component.controller.ts@@ -17,11 +17,9 @@import type { IDisposable, Nullable } from '@univerjs/core';import { Disposable, IContextService, Inject } from '@univerjs/core';import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';-import { ComponentManager, IDialogService } from '@univerjs/ui';+import { IDialogService } from '@univerjs/ui';import { distinctUntilChanged, startWith } from 'rxjs';-import { SHEET_TABLE_RENAME_DIALOG, SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../const';-import { SheetTableFilterPanel } from '../views/components/SheetTableFilterPanel';-import { SheetTableRenameDialog } from '../views/components/SheetTableRenameDialog';+import { SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, UNIVER_SHEET_TABLE_FILTER_PANEL_ID } from '../const';interface ITableFilterPanelInfo {unitId: string;@@ -34,15 +32,12 @@ export class SheetsTableComponentController extends Disposable {private _popupDisposable?: Nullable<IDisposable>;private _currentTableFilterInfo: Nullable<ITableFilterPanelInfo> = null;constructor(-- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,@IContextService private readonly _contextService: IContextService,@Inject(SheetCanvasPopManagerService) private _sheetCanvasPopupService: SheetCanvasPopManagerService,@Inject(IDialogService) private readonly _dialogService: IDialogService) {super();- this._initComponents();this._initUIPopup();}@@ -78,15 +73,6 @@ export class SheetsTableComponentController extends Disposable {return this._currentTableFilterInfo;}- private _initComponents() {- ([- [SHEETS_TABLE_FILTER_PANEL_OPENED_KEY, SheetTableFilterPanel],- [SHEET_TABLE_RENAME_DIALOG, SheetTableRenameDialog],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(this._componentManager.register(key, comp));- });- }-private _initUIPopup() {this.disposeWithMe(this._contextService.subscribeContextValue$(SHEETS_TABLE_FILTER_PANEL_OPENED_KEY)diff --git a/packages/sheets-table-ui/src/menu/__tests__/sheet-table-menu.controller.spec.ts b/packages/sheets-table-ui/src/menu/__tests__/sheet-table-menu.controller.spec.tsdeleted file mode 100644index 4031af1db8..0000000000--- a/packages/sheets-table-ui/src/menu/__tests__/sheet-table-menu.controller.spec.ts+++ /dev/null@@ -1,42 +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 { SHEET_TABLE_THEME_PANEL, TABLE_SELECTOR_DIALOG } from '../../const';-import { menuSchema } from '../schema';-import { SheetTableMenuController } from '../sheet-table-menu.controller';--describe('SheetTableMenuController', () => {- it('should register table components and merge table menu schema', () => {- const register = vi.fn(() => ({ dispose: vi.fn() }));- const registerIcon = vi.fn(() => ({ dispose: vi.fn() }));- const mergeMenu = vi.fn();-- const controller = new SheetTableMenuController(- { register } as any,- { register: registerIcon } as any,- { mergeMenu } as any- );-- expect(register).toHaveBeenCalledTimes(2);- const calls = register.mock.calls as Array<Array<any>>;- expect(calls[0]?.[0]).toBe(TABLE_SELECTOR_DIALOG);- expect(calls[1]?.[0]).toBe(SHEET_TABLE_THEME_PANEL);- expect(mergeMenu).toHaveBeenCalledWith(menuSchema);-- controller.dispose();- });-});diff --git a/packages/sheets-table-ui/src/menu/sheet-table-menu.controller.ts b/packages/sheets-table-ui/src/menu/sheet-table-menu.controller.tsindex 3a98db2d00..d231eeba19 100644--- a/packages/sheets-table-ui/src/menu/sheet-table-menu.controller.ts+++ b/packages/sheets-table-ui/src/menu/sheet-table-menu.controller.ts@@ -15,11 +15,7 @@*/import { Disposable, Inject } from '@univerjs/core';-import { TableIcon } from '@univerjs/icons';import { ComponentManager, IconManager, IMenuManagerService } from '@univerjs/ui';-import { SHEET_TABLE_THEME_PANEL, TABLE_SELECTOR_DIALOG } from '../const';-import { SheetTableSelector } from '../views/components/SheetTableSelector';-import { SheetTableThemePanel } from '../views/components/SheetTableThemePanel';import { menuSchema } from './schema';export class SheetTableMenuController extends Disposable {@@ -29,26 +25,9 @@ export class SheetTableMenuController extends Disposable {@Inject(IMenuManagerService) private _menuManagerService: IMenuManagerService) {super();- this._initComponents();- this._registerIcons();this._initMenu();}- private _initComponents() {- ([- [TABLE_SELECTOR_DIALOG, SheetTableSelector],- [SHEET_TABLE_THEME_PANEL, SheetTableThemePanel],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(this._componentManager.register(key, comp));- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- TableIcon,- }));- }-private _initMenu() {this._menuManagerService.mergeMenu(menuSchema);}diff --git a/packages/sheets-table-ui/src/plugin.ts b/packages/sheets-table-ui/src/plugin.tsindex e085ab4ff1..f5285ac60a 100644--- a/packages/sheets-table-ui/src/plugin.ts+++ b/packages/sheets-table-ui/src/plugin.ts@@ -24,6 +24,7 @@ import { OpenTableFilterPanelOperation } from './commands/operations/open-table-import { OpenTableSelectorOperation } from './commands/operations/open-table-selector.operation';import { defaultPluginConfig, SHEETS_TABLE_UI_PLUGIN_CONFIG_KEY } from './config/config';import { PLUGIN_NAME } from './const';+import { ComponentsController } from './controllers/components.controller';import { SheetsTableComponentController } from './controllers/sheet-table-component.controller';import { SheetTableControlsRenderController } from './controllers/sheet-table-controls-render.controller';import { SheetsTableFilterButtonRenderController } from './controllers/sheet-table-filter-button-render.controller';@@ -63,6 +64,8 @@ export class UniverSheetsTableUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, [[SheetsTableComponentController],[SheetsTableUiService],diff --git a/packages/sheets-thread-comment-ui/src/controllers/components.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..58b34370d2--- /dev/null+++ b/packages/sheets-thread-comment-ui/src/controllers/components.controller.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { CommentIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { SHEETS_THREAD_COMMENT_MODAL, SHEETS_THREAD_COMMENT_PANEL } from '../types/const';+import { SheetsThreadCommentCell } from '../views/SheetsThreadCommentCell';+import { SheetsThreadCommentPanel } from '../views/SheetsThreadCommentPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents();+ this._registerIcons();+ }++ private _registerComponents(): void {+ ([+ [SHEETS_THREAD_COMMENT_MODAL, SheetsThreadCommentCell],+ [SHEETS_THREAD_COMMENT_PANEL, SheetsThreadCommentPanel],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ CommentIcon,+ }));+ }+}diff --git a/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment.controller.ts b/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment.controller.tsindex efb4e7674b..86bd922e55 100644--- a/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment.controller.ts+++ b/packages/sheets-thread-comment-ui/src/controllers/sheets-thread-comment.controller.ts@@ -14,27 +14,19 @@* limitations under the License.*/-import { Disposable, Inject } from '@univerjs/core';-import { CommentIcon } from '@univerjs/icons';-import { ComponentManager, IconManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';+import { Disposable } from '@univerjs/core';+import { IMenuManagerService, IShortcutService } from '@univerjs/ui';import { AddCommentShortcut } from '../menu/menu';import { menuSchema } from '../menu/schema';-import { SHEETS_THREAD_COMMENT_MODAL, SHEETS_THREAD_COMMENT_PANEL } from '../types/const';-import { SheetsThreadCommentCell } from '../views/SheetsThreadCommentCell';-import { SheetsThreadCommentPanel } from '../views/SheetsThreadCommentPanel';export class SheetsThreadCommentController extends Disposable {constructor(@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager,@IShortcutService private readonly _shortcutService: IShortcutService) {super();this._initMenu();this._initShortcut();- this._initComponent();- this._registerIcons();}private _initShortcut() {@@ -44,21 +36,4 @@ export class SheetsThreadCommentController extends Disposable {private _initMenu() {this._menuManagerService.mergeMenu(menuSchema);}-- private _initComponent() {- ([- [SHEETS_THREAD_COMMENT_MODAL, SheetsThreadCommentCell],- [SHEETS_THREAD_COMMENT_PANEL, SheetsThreadCommentPanel],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- CommentIcon,- }));- }}diff --git a/packages/sheets-thread-comment-ui/src/plugin.ts b/packages/sheets-thread-comment-ui/src/plugin.tsindex f5771a5840..3e0433ebe1 100644--- a/packages/sheets-thread-comment-ui/src/plugin.ts+++ b/packages/sheets-thread-comment-ui/src/plugin.ts@@ -22,6 +22,7 @@ import { UniverThreadCommentUIPlugin } from '@univerjs/thread-comment-ui';import pkg from '../package.json';import { ShowAddSheetCommentModalOperation, ToggleSheetCommentPanelOperation } from './commands/operations/comment.operation';import { defaultPluginConfig, SHEETS_THREAD_COMMENT_UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { SheetsThreadCommentRenderController } from './controllers/render-controllers/render.controller';import { SheetsThreadCommentCopyPasteController } from './controllers/sheets-thread-comment-copy-paste.controller';import { SheetsThreadCommentHoverController } from './controllers/sheets-thread-comment-hover.controller';@@ -59,6 +60,8 @@ export class UniverSheetsThreadCommentUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);([[SheetsThreadCommentController],[SheetsThreadCommentRenderController],diff --git a/packages/sheets-ui/src/controllers/cell-alert.controller.ts b/packages/sheets-ui/src/controllers/cell-alert.controller.tsindex 86a314fa15..679acd2777 100644--- a/packages/sheets-ui/src/controllers/cell-alert.controller.ts+++ b/packages/sheets-ui/src/controllers/cell-alert.controller.ts@@ -18,8 +18,6 @@ import type { Workbook } from '@univerjs/core';import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';import { Disposable, Inject } from '@univerjs/core';import { ComponentManager } from '@univerjs/ui';-import { CELL_ALERT_KEY } from '../views/cell-alert';-import { CellAlert } from '../views/cell-alert/CellAlertPopup';// FIXME@weird94: this should not be render module@@ -29,12 +27,5 @@ export class CellAlertRenderController extends Disposable implements IRenderModu@Inject(ComponentManager) private _componentManager: ComponentManager) {super();- this._initComponent();- }-- private _initComponent() {- this.disposeWithMe(- this._componentManager.register(CELL_ALERT_KEY, CellAlert)- );}}diff --git a/packages/sheets-ui/src/controllers/components.controller.ts b/packages/sheets-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..e25e186e9e--- /dev/null+++ b/packages/sheets-ui/src/controllers/components.controller.ts@@ -0,0 +1,192 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { IUniverSheetsUIConfig } from '../config/config';+import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core';+import { AddImageIcon, AdjustHeightDoubleIcon, AdjustWidthDoubleIcon, AlignBottomIcon, AlignTopIcon, AllBorderIcon, AutoHeightDoubleIcon, AutoWidthDoubleIcon, AutowrapIcon, BackSlashDoubleIcon, BoldIcon, BrushIcon, CancelFreezeIcon, CancelMergeIcon, CheckMarkIcon, ClearFormatDoubleIcon, CodeIcon, CopyDoubleIcon, CutIcon, DeleteCellShiftLeftDoubleIcon, DeleteCellShiftUpDoubleIcon, DeleteColumnDoubleIcon, DeleteIcon, DeleteRowDoubleIcon, DownBorderDoubleIcon, DownloadImageIcon, EyeOutlineIcon, FontColorDoubleIcon, FontSizeIncreaseIcon, FontSizeReduceIcon, FreezeColumnIcon, FreezeRowIcon, FreezeToSelectedIcon, HideDoubleIcon, HideGridlinesDoubleIcon, HorizontalBorderDoubleIcon, HorizontallyIcon, HorizontalMergeIcon, InnerBorderDoubleIcon, InsertCellDownDoubleIcon, InsertCellShiftRightDoubleIcon, InsertDoubleIcon, InsertRowAboveDoubleIcon, InsertRowBelowDoubleIcon, ItalicIcon, LeftBorderDoubleIcon, LeftDoubleDiagonalDoubleIcon, LeftInsertColumnDoubleIcon, LeftJustifyingIcon, LeftRotationFortyFiveDegreesIcon, LeftRotationNinetyDegreesIcon, LeftTridiagonalDoubleIcon, LockIcon, MergeAllIcon, NoBorderIcon, NoColorDoubleIcon, NoRotationIcon, OuterBorderDoubleIcon, OverflowIcon, PaintBucketDoubleIcon, PasteSpecialDoubleIcon, PipingIcon, ProtectIcon, ReduceDoubleIcon, RightBorderDoubleIcon, RightDoubleDiagonalDoubleIcon, RightInsertColumnDoubleIcon, RightJustifyingIcon, RightRotationFortyFiveDegreesIcon, RightRotationNinetyDegreesIcon, SlashDoubleIcon, StrikethroughIcon, SubscriptIcon, SuperscriptIcon, TruncationIcon, UnderlineIcon, UpBorderDoubleIcon, VerticalBorderDoubleIcon, VerticalCenterIcon, VerticalIntegrationIcon, VerticalTextIcon, WriteIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../config/config';+import { UNIVER_SHEET_PERMISSION_DIALOG, UNIVER_SHEET_PERMISSION_PANEL, UNIVER_SHEET_PERMISSION_USER_DIALOG, UNIVER_SHEET_PERMISSION_USER_PART } from '../consts/permission';+import { BorderPanel } from '../views/border-panel/BorderPanel';+import { BORDER_PANEL_COMPONENT } from '../views/border-panel/interface';+import { CELL_ALERT_KEY } from '../views/cell-alert';+import { CellAlert } from '../views/cell-alert/CellAlertPopup';+import { CELL_POPUP_COMPONENT_KEY } from '../views/cell-popup/config';+import { CellPopup } from '../views/CellPopup';+import { DEFINED_NAME_CONTAINER } from '../views/defined-name/component-name';+import { DefinedNameContainer } from '../views/defined-name/DefinedNameContainer';+import { MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen } from '../views/menu-item-frozen/index';+import { MENU_ITEM_INPUT_COMPONENT, MenuItemInput } from '../views/menu-item-input/index';+import { SheetPermissionDialog, SheetPermissionPanel, SheetPermissionUserDialog } from '../views/permission';+import { AlertDialog } from '../views/permission/AlertDialog';+import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG } from '../views/permission/error-msg-dialog/interface';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager,+ @Inject(Injector) private readonly _injector: Injector+ ) {+ super();++ this._registerComponents();+ this._registerParts();+ this._registerIcons2();+ this._registerComponents2();+ this._registerIcons();+ this._registerComponents3();+ }++ private _registerComponents(): void {+ this.disposeWithMe(+ this._componentManager.register(CELL_ALERT_KEY, CellAlert)+ );+ }++ private _registerComponents2(): void {+ ([+ [UNIVER_SHEET_PERMISSION_PANEL, SheetPermissionPanel],+ [UNIVER_SHEET_PERMISSION_USER_DIALOG, SheetPermissionUserDialog],+ [UNIVER_SHEET_PERMISSION_DIALOG, SheetPermissionDialog],+ [UNIVER_SHEET_PERMISSION_ALERT_DIALOG, AlertDialog],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(this._componentManager.register(+ key,+ comp+ ));+ });+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ ProtectIcon,+ DeleteIcon,+ WriteIcon,+ CheckMarkIcon,+ LockIcon,+ }));+ }++ private _registerComponents3(): void {+ const configService = this._injector.get(IConfigService);+ const config = configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);++ if (config?.protectedRangeUserSelector) {+ const { component, framework } = config.protectedRangeUserSelector;+ this.disposeWithMe(+ this._componentManager.register(UNIVER_SHEET_PERMISSION_USER_PART, component, {+ framework,+ })+ );+ }+ }++ private _registerParts(): void {+ const componentManager = this._componentManager;++ // init custom components+ this.disposeWithMe(componentManager.register(MENU_ITEM_INPUT_COMPONENT, MenuItemInput));+ this.disposeWithMe(componentManager.register(MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen));+ this.disposeWithMe(componentManager.register(BORDER_PANEL_COMPONENT, BorderPanel));+ this.disposeWithMe(componentManager.register(DEFINED_NAME_CONTAINER, DefinedNameContainer));+ this.disposeWithMe(componentManager.register(CELL_POPUP_COMPONENT_KEY, CellPopup));+ }++ // eslint-disable-next-line max-lines-per-function+ private _registerIcons2(): void {+ this.disposeWithMe(this._iconManager.register({+ AdjustHeightDoubleIcon,+ AdjustWidthDoubleIcon,+ AddImageIcon,+ AlignBottomIcon,+ AlignTopIcon,+ AllBorderIcon,+ AutoHeightDoubleIcon,+ AutoWidthDoubleIcon,+ AutowrapIcon,+ BackSlashDoubleIcon,+ BoldIcon,+ BrushIcon,+ CancelFreezeIcon,+ CancelMergeIcon,+ ClearFormatDoubleIcon,+ CodeIcon,+ CopyDoubleIcon,+ CutIcon,+ DeleteCellShiftLeftDoubleIcon,+ DeleteCellShiftUpDoubleIcon,+ DeleteColumnDoubleIcon,+ DeleteRowDoubleIcon,+ DownBorderDoubleIcon,+ DownloadImageIcon,+ EyeOutlineIcon,+ FontColorDoubleIcon,+ FontSizeIncreaseIcon,+ FontSizeReduceIcon,+ FreezeColumnIcon,+ FreezeRowIcon,+ FreezeToSelectedIcon,+ HideDoubleIcon,+ HideGridlinesDoubleIcon,+ HorizontalBorderDoubleIcon,+ HorizontalMergeIcon,+ HorizontallyIcon,+ InnerBorderDoubleIcon,+ InsertCellDownDoubleIcon,+ InsertCellShiftRightDoubleIcon,+ InsertDoubleIcon,+ InsertRowAboveDoubleIcon,+ InsertRowBelowDoubleIcon,+ ItalicIcon,+ LeftBorderDoubleIcon,+ LeftDoubleDiagonalDoubleIcon,+ LeftInsertColumnDoubleIcon,+ LeftJustifyingIcon,+ LeftRotationFortyFiveDegreesIcon,+ LeftRotationNinetyDegreesIcon,+ LeftTridiagonalDoubleIcon,+ LockIcon,+ MergeAllIcon,+ NoBorderIcon,+ NoColorDoubleIcon,+ NoRotationIcon,+ OuterBorderDoubleIcon,+ OverflowIcon,+ PaintBucketDoubleIcon,+ PasteSpecialDoubleIcon,+ PipingIcon,+ ProtectIcon,+ ReduceDoubleIcon,+ RightBorderDoubleIcon,+ RightDoubleDiagonalDoubleIcon,+ RightInsertColumnDoubleIcon,+ RightJustifyingIcon,+ RightRotationFortyFiveDegreesIcon,+ RightRotationNinetyDegreesIcon,+ SlashDoubleIcon,+ StrikethroughIcon,+ SubscriptIcon,+ SuperscriptIcon,+ TruncationIcon,+ UnderlineIcon,+ UpBorderDoubleIcon,+ VerticalBorderDoubleIcon,+ VerticalCenterIcon,+ VerticalIntegrationIcon,+ VerticalTextIcon,+ }));+ }+}diff --git a/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts b/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.tsindex b38ec55082..8626091d9e 100644--- a/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts+++ b/packages/sheets-ui/src/controllers/mobile/ui-mobile.controller.ts@@ -17,87 +17,7 @@import { Disposable, ICommandService, IConfigService, Inject, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';import { DocSelectionRenderService } from '@univerjs/docs-ui';import { getCurrentTypeOfRenderer, IRenderManagerService } from '@univerjs/engine-render';-import {- AddImageIcon,- AdjustHeightDoubleIcon,- AdjustWidthDoubleIcon,- AlignBottomIcon,- AlignTopIcon,- AllBorderIcon,- AutoHeightDoubleIcon,- AutoWidthDoubleIcon,- AutowrapIcon,- BackSlashDoubleIcon,- BoldIcon,- BrushIcon,- CancelFreezeIcon,- CancelMergeIcon,- ClearFormatDoubleIcon,- CodeIcon,- CopyDoubleIcon,- CutIcon,- DeleteCellShiftLeftDoubleIcon,- DeleteCellShiftUpDoubleIcon,- DeleteColumnDoubleIcon,- DeleteRowDoubleIcon,- DownBorderDoubleIcon,- DownloadImageIcon,- EyeOutlineIcon,- FontColorDoubleIcon,- FontSizeIncreaseIcon,- FontSizeReduceIcon,- FreezeColumnIcon,- FreezeRowIcon,- FreezeToSelectedIcon,- HideDoubleIcon,- HideGridlinesDoubleIcon,- HorizontalBorderDoubleIcon,- HorizontallyIcon,- HorizontalMergeIcon,- InnerBorderDoubleIcon,- InsertCellDownDoubleIcon,- InsertCellShiftRightDoubleIcon,- InsertDoubleIcon,- InsertRowAboveDoubleIcon,- InsertRowBelowDoubleIcon,- ItalicIcon,- LeftBorderDoubleIcon,- LeftDoubleDiagonalDoubleIcon,- LeftInsertColumnDoubleIcon,- LeftJustifyingIcon,- LeftRotationFortyFiveDegreesIcon,- LeftRotationNinetyDegreesIcon,- LeftTridiagonalDoubleIcon,- LockIcon,- MergeAllIcon,- NoBorderIcon,- NoColorDoubleIcon,- NoRotationIcon,- OuterBorderDoubleIcon,- OverflowIcon,- PaintBucketDoubleIcon,- PasteSpecialDoubleIcon,- PipingIcon,- ProtectIcon,- ReduceDoubleIcon,- RightBorderDoubleIcon,- RightDoubleDiagonalDoubleIcon,- RightInsertColumnDoubleIcon,- RightJustifyingIcon,- RightRotationFortyFiveDegreesIcon,- RightRotationNinetyDegreesIcon,- SlashDoubleIcon,- StrikethroughIcon,- SubscriptIcon,- SuperscriptIcon,- TruncationIcon,- UnderlineIcon,- UpBorderDoubleIcon,- VerticalBorderDoubleIcon,- VerticalCenterIcon,- VerticalIntegrationIcon,- VerticalTextIcon,-} from '@univerjs/icons';+import {SetBoldCommand,SetFontFamilyCommand,@@ -108,9 +28,7 @@ import {} from '@univerjs/sheets';import {BuiltInUIPart,- ComponentManager,connectInjector,- IconManager,ILayoutService,IMenuManagerService,IUIPartsService,@@ -174,22 +92,12 @@ import { SheetPermissionOpenDialogOperation } from '../../commands/operations/shimport { SheetPermissionOpenPanelOperation } from '../../commands/operations/sheet-permission-open-panel.operation';import { SidebarDefinedNameOperation } from '../../commands/operations/sidebar-defined-name.operation';import { menuSchema } from '../../menu/mobile-menu';-import { BorderPanel } from '../../views/border-panel/BorderPanel';-import { BORDER_PANEL_COMPONENT } from '../../views/border-panel/interface';-import { CELL_POPUP_COMPONENT_KEY } from '../../views/cell-popup/config';-import { CellPopup } from '../../views/CellPopup';-import { DEFINED_NAME_CONTAINER } from '../../views/defined-name/component-name';-import { DefinedNameContainer } from '../../views/defined-name/DefinedNameContainer';-import { MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen } from '../../views/menu-item-frozen/index';-import { MENU_ITEM_INPUT_COMPONENT, MenuItemInput } from '../../views/menu-item-input/index';import { MobileSheetBar } from '../../views/mobile/sheet-bar/MobileSheetBar';import { RenderSheetContent } from '../../views/sheet-container/SheetContainer';export class SheetUIMobileController extends Disposable {constructor(@Inject(Injector) protected readonly _injector: Injector,- @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,- @Inject(IconManager) protected readonly _iconManager: IconManager,@ILayoutService protected readonly _layoutService: ILayoutService,@ICommandService protected readonly _commandService: ICommandService,@IMenuManagerService protected readonly _menuManagerService: IMenuManagerService,@@ -202,110 +110,12 @@ export class SheetUIMobileController extends Disposable {}private _init(): void {- this._initComponents();- this._registerIcons();this._initCommands();this._initMenus();this._initWorkbenchParts();this._initFocusHandler();}- private _initComponents(): void {- const componentManager = this._componentManager;-- // init custom components- this.disposeWithMe(componentManager.register(MENU_ITEM_INPUT_COMPONENT, MenuItemInput));- this.disposeWithMe(componentManager.register(MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen));- this.disposeWithMe(componentManager.register(BORDER_PANEL_COMPONENT, BorderPanel));- this.disposeWithMe(componentManager.register(DEFINED_NAME_CONTAINER, DefinedNameContainer));- this.disposeWithMe(componentManager.register(CELL_POPUP_COMPONENT_KEY, CellPopup));- }-- // eslint-disable-next-line max-lines-per-function- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- AdjustHeightDoubleIcon,- AdjustWidthDoubleIcon,- AddImageIcon,- AlignBottomIcon,- AlignTopIcon,- AllBorderIcon,- AutoHeightDoubleIcon,- AutoWidthDoubleIcon,- AutowrapIcon,- BackSlashDoubleIcon,- BoldIcon,- BrushIcon,- CancelFreezeIcon,- CancelMergeIcon,- ClearFormatDoubleIcon,- CodeIcon,- CopyDoubleIcon,- CutIcon,- DeleteCellShiftLeftDoubleIcon,- DeleteCellShiftUpDoubleIcon,- DeleteColumnDoubleIcon,- DeleteRowDoubleIcon,- DownBorderDoubleIcon,- DownloadImageIcon,- EyeOutlineIcon,- FontColorDoubleIcon,- FontSizeIncreaseIcon,- FontSizeReduceIcon,- FreezeColumnIcon,- FreezeRowIcon,- FreezeToSelectedIcon,- HideDoubleIcon,- HideGridlinesDoubleIcon,- HorizontalBorderDoubleIcon,- HorizontalMergeIcon,- HorizontallyIcon,- InnerBorderDoubleIcon,- InsertCellDownDoubleIcon,- InsertCellShiftRightDoubleIcon,- InsertDoubleIcon,- InsertRowAboveDoubleIcon,- InsertRowBelowDoubleIcon,- ItalicIcon,- LeftBorderDoubleIcon,- LeftDoubleDiagonalDoubleIcon,- LeftInsertColumnDoubleIcon,- LeftJustifyingIcon,- LeftRotationFortyFiveDegreesIcon,- LeftRotationNinetyDegreesIcon,- LeftTridiagonalDoubleIcon,- LockIcon,- MergeAllIcon,- NoBorderIcon,- NoColorDoubleIcon,- NoRotationIcon,- OuterBorderDoubleIcon,- OverflowIcon,- PaintBucketDoubleIcon,- PasteSpecialDoubleIcon,- PipingIcon,- ProtectIcon,- ReduceDoubleIcon,- RightBorderDoubleIcon,- RightDoubleDiagonalDoubleIcon,- RightInsertColumnDoubleIcon,- RightJustifyingIcon,- RightRotationFortyFiveDegreesIcon,- RightRotationNinetyDegreesIcon,- SlashDoubleIcon,- StrikethroughIcon,- SubscriptIcon,- SuperscriptIcon,- TruncationIcon,- UnderlineIcon,- UpBorderDoubleIcon,- VerticalBorderDoubleIcon,- VerticalCenterIcon,- VerticalIntegrationIcon,- VerticalTextIcon,- }));- }-private _initCommands(): void {[ChangeZoomRatioCommand,diff --git a/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts b/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.tsindex dc3efe4d65..74483767b9 100644--- a/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts+++ b/packages/sheets-ui/src/controllers/permission/sheet-permission-render.controller.ts@@ -19,21 +19,12 @@ import type { MenuConfig } from '@univerjs/ui';import type { IUniverSheetsUIConfig } from '../../config/config';import { Disposable, IConfigService, Inject, Injector, IPermissionService } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';-import { CheckMarkIcon, DeleteIcon, LockIcon, ProtectIcon, WriteIcon } from '@univerjs/icons';import { RangeProtectionRuleModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { ComponentManager, IconManager } from '@univerjs/ui';import { merge, throttleTime } from 'rxjs';import { convertToShadowStrategy, SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';-import {- UNIVER_SHEET_PERMISSION_DIALOG,- UNIVER_SHEET_PERMISSION_PANEL,- UNIVER_SHEET_PERMISSION_USER_DIALOG,- UNIVER_SHEET_PERMISSION_USER_PART,-} from '../../consts/permission';+import { SheetSkeletonManagerService } from '../../services/sheet-skeleton-manager.service';-import { SheetPermissionDialog, SheetPermissionPanel, SheetPermissionUserDialog } from '../../views/permission';-import { AlertDialog } from '../../views/permission/AlertDialog';-import { UNIVER_SHEET_PERMISSION_ALERT_DIALOG } from '../../views/permission/error-msg-dialog/interface';import { RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY, RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY, RangeProtectionCanNotViewRenderExtension, RangeProtectionCanViewRenderExtension } from '../../views/permission/extensions/range-protection.render';import { worksheetProtectionKey, WorksheetProtectionRenderExtension } from '../../views/permission/extensions/worksheet-permission.render';@@ -52,47 +43,6 @@ export class SheetPermissionRenderManagerController extends Disposable {}private _init(): void {- this._initComponents();- this._registerIcons();- this._initUiPartComponents();- }-- private _initComponents(): void {- ([- [UNIVER_SHEET_PERMISSION_PANEL, SheetPermissionPanel],- [UNIVER_SHEET_PERMISSION_USER_DIALOG, SheetPermissionUserDialog],- [UNIVER_SHEET_PERMISSION_DIALOG, SheetPermissionDialog],- [UNIVER_SHEET_PERMISSION_ALERT_DIALOG, AlertDialog],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(this._componentManager.register(- key,- comp- ));- });- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- ProtectIcon,- DeleteIcon,- WriteIcon,- CheckMarkIcon,- LockIcon,- }));- }-- private _initUiPartComponents(): void {- const configService = this._injector.get(IConfigService);- const config = configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);-- if (config?.protectedRangeUserSelector) {- const { component, framework } = config.protectedRangeUserSelector;- this.disposeWithMe(- this._componentManager.register(UNIVER_SHEET_PERMISSION_USER_PART, component, {- framework,- })- );- }}}diff --git a/packages/sheets-ui/src/controllers/ui.controller.ts b/packages/sheets-ui/src/controllers/ui.controller.tsindex e473f90eda..790c45b949 100644--- a/packages/sheets-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-ui/src/controllers/ui.controller.ts@@ -25,87 +25,7 @@ import {} from '@univerjs/core';import { DocSelectionRenderService } from '@univerjs/docs-ui';import { getCurrentTypeOfRenderer, IRenderManagerService } from '@univerjs/engine-render';-import {- AddImageIcon,- AdjustHeightDoubleIcon,- AdjustWidthDoubleIcon,- AlignBottomIcon,- AlignTopIcon,- AllBorderIcon,- AutoHeightDoubleIcon,- AutoWidthDoubleIcon,- AutowrapIcon,- BackSlashDoubleIcon,- BoldIcon,- BrushIcon,- CancelFreezeIcon,- CancelMergeIcon,- ClearFormatDoubleIcon,- CodeIcon,- CopyDoubleIcon,- CutIcon,- DeleteCellShiftLeftDoubleIcon,- DeleteCellShiftUpDoubleIcon,- DeleteColumnDoubleIcon,- DeleteRowDoubleIcon,- DownBorderDoubleIcon,- DownloadImageIcon,- EyeOutlineIcon,- FontColorDoubleIcon,- FontSizeIncreaseIcon,- FontSizeReduceIcon,- FreezeColumnIcon,- FreezeRowIcon,- FreezeToSelectedIcon,- HideDoubleIcon,- HideGridlinesDoubleIcon,- HorizontalBorderDoubleIcon,- HorizontallyIcon,- HorizontalMergeIcon,- InnerBorderDoubleIcon,- InsertCellDownDoubleIcon,- InsertCellShiftRightDoubleIcon,- InsertDoubleIcon,- InsertRowAboveDoubleIcon,- InsertRowBelowDoubleIcon,- ItalicIcon,- LeftBorderDoubleIcon,- LeftDoubleDiagonalDoubleIcon,- LeftInsertColumnDoubleIcon,- LeftJustifyingIcon,- LeftRotationFortyFiveDegreesIcon,- LeftRotationNinetyDegreesIcon,- LeftTridiagonalDoubleIcon,- LockIcon,- MergeAllIcon,- NoBorderIcon,- NoColorDoubleIcon,- NoRotationIcon,- OuterBorderDoubleIcon,- OverflowIcon,- PaintBucketDoubleIcon,- PasteSpecialDoubleIcon,- PipingIcon,- ProtectIcon,- ReduceDoubleIcon,- RightBorderDoubleIcon,- RightDoubleDiagonalDoubleIcon,- RightInsertColumnDoubleIcon,- RightJustifyingIcon,- RightRotationFortyFiveDegreesIcon,- RightRotationNinetyDegreesIcon,- SlashDoubleIcon,- StrikethroughIcon,- SubscriptIcon,- SuperscriptIcon,- TruncationIcon,- UnderlineIcon,- UpBorderDoubleIcon,- VerticalBorderDoubleIcon,- VerticalCenterIcon,- VerticalIntegrationIcon,- VerticalTextIcon,-} from '@univerjs/icons';+import {SetBoldCommand,SetFontFamilyCommand,@@ -114,7 +34,7 @@ import {SetStrikeThroughCommand,SetUnderlineCommand,} from '@univerjs/sheets';-import { BuiltInUIPart, ComponentManager, connectInjector, IconManager, ILayoutService, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';+import { BuiltInUIPart, connectInjector, ILayoutService, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';import { DeleteRangeMoveLeftConfirmCommand } from '../commands/commands/delete-range-move-left-confirm.command';import { DeleteRangeMoveUpConfirmCommand } from '../commands/commands/delete-range-move-up-confirm.command';import { SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand } from '../commands/commands/headersize-changed.command';@@ -177,14 +97,6 @@ import { SheetPermissionOpenDialogOperation } from '../commands/operations/sheetimport { SheetPermissionOpenPanelOperation } from '../commands/operations/sheet-permission-open-panel.operation';import { SidebarDefinedNameOperation } from '../commands/operations/sidebar-defined-name.operation';import { menuSchema } from '../menu/schema';-import { BorderPanel } from '../views/border-panel/BorderPanel';-import { BORDER_PANEL_COMPONENT } from '../views/border-panel/interface';-import { CELL_POPUP_COMPONENT_KEY } from '../views/cell-popup/config';-import { CellPopup } from '../views/CellPopup';-import { DEFINED_NAME_CONTAINER } from '../views/defined-name/component-name';-import { DefinedNameContainer } from '../views/defined-name/DefinedNameContainer';-import { MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen } from '../views/menu-item-frozen/index';-import { MENU_ITEM_INPUT_COMPONENT, MenuItemInput } from '../views/menu-item-input/index';import { RenderSheetContent, RenderSheetFooter, RenderSheetHeader } from '../views/sheet-container/SheetContainer';import { CopyDownShortcutItem, CopyRightShortcutItem } from './shortcuts/copy-fill.shortcut';import {@@ -247,8 +159,6 @@ import {export class SheetUIController extends Disposable {constructor(@Inject(Injector) protected readonly _injector: Injector,- @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,- @Inject(IconManager) protected readonly _iconManager: IconManager,@ILayoutService protected readonly _layoutService: ILayoutService,@ICommandService protected readonly _commandService: ICommandService,@IShortcutService protected readonly _shortcutService: IShortcutService,@@ -262,8 +172,6 @@ export class SheetUIController extends Disposable {}private _init(): void {- this._initComponents();- this._registerIcons();this._initCommands();this._initMenus();this._initShortcuts();@@ -271,102 +179,6 @@ export class SheetUIController extends Disposable {this._initFocusHandler();}- private _initComponents(): void {- const componentManager = this._componentManager;-- // init custom components- this.disposeWithMe(componentManager.register(MENU_ITEM_INPUT_COMPONENT, MenuItemInput));- this.disposeWithMe(componentManager.register(MENU_ITEM_FROZEN_COMPONENT, MenuItemFrozen));- this.disposeWithMe(componentManager.register(BORDER_PANEL_COMPONENT, BorderPanel));- this.disposeWithMe(componentManager.register(DEFINED_NAME_CONTAINER, DefinedNameContainer));- this.disposeWithMe(componentManager.register(CELL_POPUP_COMPONENT_KEY, CellPopup));- }-- // eslint-disable-next-line max-lines-per-function- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- AdjustHeightDoubleIcon,- AdjustWidthDoubleIcon,- AddImageIcon,- AlignBottomIcon,- AlignTopIcon,- AllBorderIcon,- AutoHeightDoubleIcon,- AutoWidthDoubleIcon,- AutowrapIcon,- BackSlashDoubleIcon,- BoldIcon,- BrushIcon,- CancelFreezeIcon,- CancelMergeIcon,- ClearFormatDoubleIcon,- CodeIcon,- CopyDoubleIcon,- CutIcon,- DeleteCellShiftLeftDoubleIcon,- DeleteCellShiftUpDoubleIcon,- DeleteColumnDoubleIcon,- DeleteRowDoubleIcon,- DownBorderDoubleIcon,- DownloadImageIcon,- EyeOutlineIcon,- FontColorDoubleIcon,- FontSizeIncreaseIcon,- FontSizeReduceIcon,- FreezeColumnIcon,- FreezeRowIcon,- FreezeToSelectedIcon,- HideDoubleIcon,- HideGridlinesDoubleIcon,- HorizontalBorderDoubleIcon,- HorizontalMergeIcon,- HorizontallyIcon,- InnerBorderDoubleIcon,- InsertCellDownDoubleIcon,- InsertCellShiftRightDoubleIcon,- InsertDoubleIcon,- InsertRowAboveDoubleIcon,- InsertRowBelowDoubleIcon,- ItalicIcon,- LeftBorderDoubleIcon,- LeftDoubleDiagonalDoubleIcon,- LeftInsertColumnDoubleIcon,- LeftJustifyingIcon,- LeftRotationFortyFiveDegreesIcon,- LeftRotationNinetyDegreesIcon,- LeftTridiagonalDoubleIcon,- LockIcon,- MergeAllIcon,- NoBorderIcon,- NoColorDoubleIcon,- NoRotationIcon,- OuterBorderDoubleIcon,- OverflowIcon,- PaintBucketDoubleIcon,- PasteSpecialDoubleIcon,- PipingIcon,- ProtectIcon,- ReduceDoubleIcon,- RightBorderDoubleIcon,- RightDoubleDiagonalDoubleIcon,- RightInsertColumnDoubleIcon,- RightJustifyingIcon,- RightRotationFortyFiveDegreesIcon,- RightRotationNinetyDegreesIcon,- SlashDoubleIcon,- StrikethroughIcon,- SubscriptIcon,- SuperscriptIcon,- TruncationIcon,- UnderlineIcon,- UpBorderDoubleIcon,- VerticalBorderDoubleIcon,- VerticalCenterIcon,- VerticalIntegrationIcon,- VerticalTextIcon,- }));- }-private _initCommands(): void {[ChangeZoomRatioCommand,diff --git a/packages/sheets-ui/src/mobile-plugin.ts b/packages/sheets-ui/src/mobile-plugin.tsindex 5a47c677d5..0c7c00cbd7 100644--- a/packages/sheets-ui/src/mobile-plugin.ts+++ b/packages/sheets-ui/src/mobile-plugin.ts@@ -20,11 +20,10 @@ import type { IUniverSheetsUIConfig } from './config/config';import { DependentOn, IConfigService, Inject, Injector, IUniverInstanceService, merge, mergeOverrideWithDependencies, Plugin, registerDependencies, touchDependencies, UniverInstanceType } from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { IRefSelectionsService, RefSelectionsService, UniverSheetsPlugin } from '@univerjs/sheets';-import { ComponentManager, UI_PLUGIN_CONFIG_KEY, UniverMobileUIPlugin } from '@univerjs/ui';+import { UI_PLUGIN_CONFIG_KEY, UniverMobileUIPlugin } from '@univerjs/ui';import { filter } from 'rxjs/operators';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_UI_PLUGIN_CONFIG_KEY } from './config/config';-import { UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';import { AutoFillUIController } from './controllers/auto-fill-ui.controller';import { AutoHeightController } from './controllers/auto-height.controller';import { AutoWidthController } from './controllers/auto-width.controller';@@ -33,6 +32,7 @@ import { CellCustomRenderController } from './controllers/cell-custom-render.conimport { CellPopupEditorController } from './controllers/cell-popup-editor.controller';import { SheetCheckboxController } from './controllers/checkbox.controller';import { SheetClipboardController } from './controllers/clipboard/clipboard.controller';+import { ComponentsController } from './controllers/components.controller';import { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';import { DragRenderController } from './controllers/drag-render.controller';import { EditorDataSyncController } from './controllers/editor/data-sync.controller';@@ -107,8 +107,7 @@ export class UniverSheetsMobileUIPlugin extends Plugin {@Inject(Injector) override readonly _injector: Injector,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IConfigService private readonly _configService: IConfigService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService) {super();@@ -119,20 +118,6 @@ export class UniverSheetsMobileUIPlugin extends Plugin {this._config);- if (rest.protectedRangeUserSelector) {- const { component, framework } = rest.protectedRangeUserSelector;-- this.disposeWithMe(- this._componentManager.register(- UNIVER_SHEET_PERMISSION_USER_PART,- component,- {- framework,- }- )- );- }-if (menu) {this._configService.setConfig('menu', menu, { merge: true });}@@ -141,6 +126,8 @@ export class UniverSheetsMobileUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, mergeOverrideWithDependencies([[ShortcutExperienceService],[IEditorBridgeService, { useClass: EditorBridgeService }],diff --git a/packages/sheets-ui/src/plugin.ts b/packages/sheets-ui/src/plugin.tsindex a1402dda4f..13b9425d28 100644--- a/packages/sheets-ui/src/plugin.ts+++ b/packages/sheets-ui/src/plugin.ts@@ -32,11 +32,10 @@ import {} from '@univerjs/core';import { IRenderManagerService } from '@univerjs/engine-render';import { IRefSelectionsService, RefSelectionsService, UniverSheetsPlugin } from '@univerjs/sheets';-import { ComponentManager, UI_PLUGIN_CONFIG_KEY } from '@univerjs/ui';+import { UI_PLUGIN_CONFIG_KEY } from '@univerjs/ui';import { filter } from 'rxjs/operators';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_UI_PLUGIN_CONFIG_KEY } from './config/config';-import { UNIVER_SHEET_PERMISSION_USER_PART } from './consts/permission';import { AutoFillUIController } from './controllers/auto-fill-ui.controller';import { AutoHeightController } from './controllers/auto-height.controller';import { AutoWidthController } from './controllers/auto-width.controller';@@ -45,6 +44,7 @@ import { CellCustomRenderController } from './controllers/cell-custom-render.conimport { CellPopupEditorController } from './controllers/cell-popup-editor.controller';import { SheetCheckboxController } from './controllers/checkbox.controller';import { SheetClipboardController } from './controllers/clipboard/clipboard.controller';+import { ComponentsController } from './controllers/components.controller';import { SheetsDefinedNameController } from './controllers/defined-name/defined-name.controller';import { DragRenderController } from './controllers/drag-render.controller';import { EditorDataSyncController } from './controllers/editor/data-sync.controller';@@ -128,8 +128,7 @@ export class UniverSheetsUIPlugin extends Plugin {@Inject(Injector) override readonly _injector: Injector,@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IConfigService private readonly _configService: IConfigService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService) {super();@@ -140,20 +139,6 @@ export class UniverSheetsUIPlugin extends Plugin {this._config);- if (rest.protectedRangeUserSelector) {- const { component, framework } = rest.protectedRangeUserSelector;-- this.disposeWithMe(- this._componentManager.register(- UNIVER_SHEET_PERMISSION_USER_PART,- component,- {- framework,- }- )- );- }-if (menu) {this._configService.setConfig('menu', menu, { merge: true });}@@ -162,6 +147,8 @@ export class UniverSheetsUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);registerDependencies(this._injector, mergeOverrideWithDependencies([[ShortcutExperienceService],[IEditorBridgeService, { useClass: EditorBridgeService }],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.tsnew file mode 100644index 0000000000..6490ffe5b7--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts@@ -0,0 +1,36 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { SheetPrintInterceptorService } from '../print-interceptor.service';++describe('SheetPrintInterceptorService', () => {+ let service: SheetPrintInterceptorService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([SheetPrintInterceptorService]);+ service = injector.get(SheetPrintInterceptorService);+ });++ it('maps runtime components to printable component implementations', () => {+ service.registerPrintComponent('sheet-chart', 'print-sheet-chart');++ expect(service.getPrintComponent('sheet-chart')).toBe('print-sheet-chart');+ expect(service.getPrintComponent('unknown-component')).toBeUndefined();+ });+});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.tsnew file mode 100644index 0000000000..4f0e986e57--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/repeat-last-action.service.spec.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { ICommandService, Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { IRepeatLastActionService, RepeatLastActionPermission, RepeatLastActionService } from '../repeat-last-action.service';++describe('RepeatLastActionService', () => {+ let service: IRepeatLastActionService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ICommandService, { useValue: { executeCommand: async () => true } as unknown as ICommandService }]);+ injector.add([IRepeatLastActionService, { useClass: RepeatLastActionService }]);+ service = injector.get(IRepeatLastActionService);+ });++ it('records repeatable commands with the permission type needed by the current selection', () => {+ const disposable = service.registerRepeatableCommand(+ 'sheet.command.fill-series',+ () => ({ direction: 'down' }),+ RepeatLastActionPermission.CellValue+ );++ service.setAction({ id: 'sheet.command.fill-series' });++ expect(service.getRepeatableCommands().has('sheet.command.fill-series')).toBe(true);+ expect(service.getActionPermission()).toBe(RepeatLastActionPermission.CellValue);++ disposable.dispose();+ expect(service.getRepeatableCommands().has('sheet.command.fill-series')).toBe(false);+ });+});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.tsnew file mode 100644index 0000000000..3e74899b43--- /dev/null+++ b/packages/sheets-ui/src/services/__tests__/shortcut-experience.service.spec.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ShortcutExperienceService } from '../shortcut-experience.service';++describe('ShortcutExperienceService', () => {+ let service: ShortcutExperienceService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);+ injector.add([LocaleService, { useValue: {} as LocaleService }]);+ injector.add([ShortcutExperienceService]);+ service = injector.get(ShortcutExperienceService);+ });++ it('updates shortcut context for the same workbook, sheet and key combination', () => {+ const original = { unitId: 'book-1', sheetId: 'sheet-1', keycode: 13, selection: { startRow: 0 } };+ const next = { unitId: 'book-1', sheetId: 'sheet-1', keycode: 13, selection: { startRow: 1 } };++ expect(service.addOrUpdate(original as never)).toBeUndefined();+ expect(service.addOrUpdate(next as never)).toBe(original);+ expect(service.getCurrentBySearch({ unitId: 'book-1', sheetId: 'sheet-1', keycode: 13 as never })).toBe(next);+ });++ it('removes stale shortcut context after the optimized action is consumed', () => {+ const param = { unitId: 'book-1', sheetId: 'sheet-1', keycode: 9, selection: { startRow: 0 } };+ service.addOrUpdate(param as never);++ expect(service.remove({ unitId: 'book-1', sheetId: 'sheet-1', keycode: 9 as never })).toBe(param);+ expect(service.getCurrentBySearch({ unitId: 'book-1', sheetId: 'sheet-1', keycode: 9 as never })).toBeUndefined();+ });+});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.tsnew file mode 100644index 0000000000..c045c67fc3--- /dev/null+++ b/packages/sheets-ui/src/services/editor/__tests__/cell-editor-manager.service.spec.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { CellEditorManagerService, ICellEditorManagerService } from '../cell-editor-manager.service';++describe('CellEditorManagerService', () => {+ let service: ICellEditorManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ICellEditorManagerService, { useClass: CellEditorManagerService }]);+ service = injector.get(ICellEditorManagerService);+ });++ it('publishes editor visibility, bounds and focus state for the active sheet cell', () => {+ const states: unknown[] = [];+ const rects: unknown[] = [];+ const focus: boolean[] = [];+ service.state$.subscribe((state) => states.push(state));+ service.rect$.subscribe((rect) => rects.push(rect));+ service.focus$.subscribe((value) => focus.push(value));++ service.setState({ show: true, startX: 20, startY: 40, endX: 100, endY: 70 });+ service.setRect({ left: 10, top: 20, width: 100, height: 30 });+ service.setFocus(true);++ 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]);+ });+});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.tsnew file mode 100644index 0000000000..15b199f76b--- /dev/null+++ b/packages/sheets-ui/src/services/editor/__tests__/formula-editor-manager.service.spec.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { FormulaEditorManagerService, IFormulaEditorManagerService } from '../formula-editor-manager.service';++describe('FormulaEditorManagerService', () => {+ let service: IFormulaEditorManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IFormulaEditorManagerService, { useClass: FormulaEditorManagerService }]);+ service = injector.get(IFormulaEditorManagerService);+ });++ it('publishes formula editor position and toolbar button interactions', () => {+ const rect = { left: 1, top: 2, width: 300, height: 24 } as DOMRect;+ const positions: unknown[] = [];+ const focus: boolean[] = [];+ const fxClicks: boolean[] = [];+ const foldClicks: boolean[] = [];+ service.position$.subscribe((position) => positions.push(position));+ service.focus$.subscribe((value) => focus.push(value));+ service.fxBtnClick$.subscribe((value) => fxClicks.push(value));+ service.foldBtnStatus$.subscribe((value) => foldClicks.push(value));++ service.setPosition(rect);+ service.setFocus(true);+ service.handleFxBtnClick(true);+ service.handleFoldBtnClick(false);++ expect(positions.at(-1)).toBe(rect);+ expect(focus).toEqual([false, true]);+ expect(fxClicks).toEqual([true]);+ expect(foldClicks).toEqual([false]);+ });+});diff --git a/packages/sheets/src/services/__tests__/border-style-manager.service.spec.ts b/packages/sheets/src/services/__tests__/border-style-manager.service.spec.tsnew file mode 100644index 0000000000..7868602ceb--- /dev/null+++ b/packages/sheets/src/services/__tests__/border-style-manager.service.spec.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { BorderStyleTypes, BorderType, Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { BorderStyleManagerService } from '../border-style-manager.service';++describe('BorderStyleManagerService', () => {+ let service: BorderStyleManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([BorderStyleManagerService]);+ service = injector.get(BorderStyleManagerService);+ });++ it('publishes the border style selected from the toolbar', () => {+ const snapshots: Array<{ type: BorderType; color: string | undefined; style: BorderStyleTypes; activeBorderType: boolean }> = [];+ service.borderInfo$.subscribe((borderInfo) => snapshots.push({ ...borderInfo }));++ service.setType(BorderType.TOP);+ service.setColor('#ff0000');+ service.setStyle(BorderStyleTypes.DASHED);++ expect(snapshots.at(-1)).toEqual({+ type: BorderType.TOP,+ color: '#ff0000',+ style: BorderStyleTypes.DASHED,+ activeBorderType: true,+ });+ });+});diff --git a/packages/sheets/src/services/__tests__/range-theme.service.spec.ts b/packages/sheets/src/services/__tests__/range-theme.service.spec.tsnew file mode 100644index 0000000000..2018eefd1c--- /dev/null+++ b/packages/sheets/src/services/__tests__/range-theme.service.spec.ts@@ -0,0 +1,68 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { SheetRangeThemeModel } from '../../models/range-theme-model';+import { RangeThemeStyle } from '../../models/range-theme-util';+import { SheetRangeThemeService } from '../range-theme.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>;+ };++ 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([SheetRangeThemeService]);+ service = injector.get(SheetRangeThemeService);+ });++ it('registers and applies named table themes to sheet ranges', () => {+ const theme = new RangeThemeStyle('sales');+ const rangeInfo = { unitId: 'book-1', subUnitId: 'sheet-1', range: { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2 } };++ service.registerRangeTheme('book-1', theme);+ service.registerRangeThemeStyle('sales', rangeInfo);++ expect(model.registerRangeThemeStyle).toHaveBeenCalledWith('book-1', theme);+ expect(model.registerRangeThemeRule).toHaveBeenCalledWith('sales', rangeInfo);+ 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.removeRangeThemeRule('sales', rangeInfo);++ expect(model.removeRangeThemeRule).toHaveBeenCalledWith('sales', rangeInfo);+ });+});diff --git a/packages/sheets/src/services/exclusive-range/__tests__/exclusive-range.service.spec.ts b/packages/sheets/src/services/exclusive-range/__tests__/exclusive-range.service.spec.tsnew file mode 100644index 0000000000..b0a018dfc6--- /dev/null+++ b/packages/sheets/src/services/exclusive-range/__tests__/exclusive-range.service.spec.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ExclusiveRangeService, IExclusiveRangeService } from '../exclusive-range.service';++describe('ExclusiveRangeService', () => {+ let service: IExclusiveRangeService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IExclusiveRangeService, { useClass: ExclusiveRangeService }]);+ service = injector.get(IExclusiveRangeService);+ });++ it('tracks ranges reserved by sheet features and reports intersecting groups', () => {+ const changes: Array<{ unitId: string; subUnitId: string; ranges: unknown[] }> = [];+ service.exclusiveRangesChange$.subscribe((change) => changes.push(change as never));+ const protectedRange = { startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 };++ service.addExclusiveRange('book-1', 'sheet-1', 'data-validation', [{ groupId: 'rule-1', range: protectedRange }]);++ expect(service.getInterestGroupId([+ { range: { unitId: 'book-1', sheetId: 'sheet-1', startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 } },+ ] as never)).toEqual(['data-validation']);+ expect(changes).toEqual([{ unitId: 'book-1', subUnitId: 'sheet-1', ranges: [protectedRange] }]);+ });++ it('clears only the requested exclusive range group', () => {+ service.addExclusiveRange('book-1', 'sheet-1', 'feature', [+ { groupId: 'group-a', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } },+ { groupId: 'group-b', range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },+ ]);++ service.clearExclusiveRangesByGroupId('book-1', 'sheet-1', 'feature', 'group-a');++ expect(service.getExclusiveRanges('book-1', 'sheet-1', 'feature')).toEqual([+ { groupId: 'group-b', range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },+ ]);+ });+});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.tsnew file mode 100644index 0000000000..abe6d5d50e--- /dev/null+++ b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.service.spec.ts@@ -0,0 +1,56 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector, IPermissionService, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';+import { Subject } from 'rxjs';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RangeProtectionRuleModel } from '../../../../models/range-protection-rule.model';+import { RangeProtectionCache } from '../../../../models/range-protection.cache';+import { RangeProtectionService } from '../range-protection.service';++describe('RangeProtectionService', () => {+ let ruleChange$: Subject<unknown>;+ let addedPermissionIds: string[];+ let deletedPermissionIds: string[];++ 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([RangeProtectionService]);+ 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' } });++ expect(addedPermissionIds.every((id) => id.includes('perm-1'))).toBe(true);+ expect(deletedPermissionIds).toEqual(addedPermissionIds);+ });+});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.tsnew file mode 100644index 0000000000..89509f2412--- /dev/null+++ b/packages/sheets/src/services/permission/workbook-permission/__tests__/workbook-permission.service.spec.ts@@ -0,0 +1,69 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector, IPermissionService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';+import { Subject } from 'rxjs';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RangeProtectionRuleModel } from '../../../../models/range-protection-rule.model';+import { WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '../../worksheet-permission';+import { WorkbookPermissionService } from '../workbook-permission.service';++describe('WorkbookPermissionService', () => {+ let service: WorkbookPermissionService;+ let addedPermissionIds: string[];+ let sheetAdded$: Subject<unknown>;+ let sheetDisposed$: Subject<unknown>;++ 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([WorkbookPermissionService]);+ service = injector.get(WorkbookPermissionService);+ });++ it('registers workbook permission points when a workbook is added', () => {+ sheetAdded$.next({ unit: { getUnitId: () => 'book-1' } });++ expect(addedPermissionIds.length).toBeGreaterThan(0);+ expect(addedPermissionIds.every((id) => id.includes('book-1'))).toBe(true);+ });++ it('publishes workbook permission initialization state changes', () => {+ const states: boolean[] = [];+ service.unitPermissionInitStateChange$.subscribe((state) => states.push(state));++ service.changeUnitInitState(true);++ expect(states).toEqual([false, true]);+ });+});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.tsnew file mode 100644index 0000000000..3095a72cf5--- /dev/null+++ b/packages/sheets/src/services/permission/worksheet-permission/__tests__/worksheet-permission.service.spec.ts@@ -0,0 +1,68 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DesktopLogService, ILogService, Injector, IPermissionService, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';+import { Subject } from 'rxjs';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RangeProtectionRuleModel } 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';++describe('WorksheetPermissionService', () => {+ let addedPermissionIds: string[];+ let ruleChange$: Subject<unknown>;++ beforeEach(() => {+ addedPermissionIds = [];+ ruleChange$ = new Subject();+ const sheetCreated$ = new Subject();+ const sheetDisposed$ = new Subject();+ const workbook = {+ getUnitId: () => 'book-1',+ getSheets: () => [{ getSheetId: () => 'sheet-1' }],+ sheetCreated$,+ sheetDisposed$,+ };+ 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([ILogService, { useClass: DesktopLogService }]);+ injector.add([WorksheetPermissionService]);+ 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);+ });+});diff --git a/packages/slides-ui/src/controllers/components.controller.ts b/packages/slides-ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..fc29015481--- /dev/null+++ b/packages/slides-ui/src/controllers/components.controller.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { AddImageIcon, GraphIcon, TextIcon } from '@univerjs/icons';+import { ComponentManager, IconManager } from '@univerjs/ui';+import { COMPONENT_SLIDE_IMAGE_POPUP_MENU } from '../views/image-popup-menu/component-name';+import { SlideImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';+import Sidebar, { COMPONENT_SLIDE_SIDEBAR } from '../views/sidebar/Sidebar';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerParts();+ this._registerIcons();+ }++ private _registerParts(): void {+ const componentManager = this._componentManager;+ this.disposeWithMe(componentManager.register(COMPONENT_SLIDE_IMAGE_POPUP_MENU, SlideImagePopupMenu));+ this.disposeWithMe(componentManager.register(COMPONENT_SLIDE_SIDEBAR, Sidebar));+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ AddImageIcon,+ TextIcon,+ GraphIcon,+ }));+ }+}diff --git a/packages/slides-ui/src/controllers/ui.controller.ts b/packages/slides-ui/src/controllers/ui.controller.tsindex 14a526726a..54724a33b7 100644--- a/packages/slides-ui/src/controllers/ui.controller.ts+++ b/packages/slides-ui/src/controllers/ui.controller.ts@@ -15,8 +15,7 @@*/import { Disposable, ICommandService, Inject, Injector } from '@univerjs/core';-import { AddImageIcon, GraphIcon, TextIcon } from '@univerjs/icons';-import { BuiltInUIPart, ComponentManager, connectInjector, IconManager, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';+import { BuiltInUIPart, connectInjector, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';import { ActivateSlidePageOperation } from '../commands/operations/activate.operation';import { AppendSlideOperation } from '../commands/operations/append-slide.operation';import { DeleteSlideElementOperation } from '../commands/operations/delete-element.operation';@@ -34,9 +33,6 @@ import { SetTextEditArrowOperation } from '../commands/operations/text-edit.operimport { UpdateSlideElementOperation } from '../commands/operations/update-element.operation';import { menuSchema } from '../menu/schema';import { SlideEditorContainer } from '../views/editor-container';-import { COMPONENT_SLIDE_IMAGE_POPUP_MENU } from '../views/image-popup-menu/component-name';-import { SlideImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';-import Sidebar, { COMPONENT_SLIDE_SIDEBAR } from '../views/sidebar/Sidebar';import { SlideSideBar } from '../views/slide-bar/SlideBar';import { EditorDeleteLeftShortcut, generateArrowSelectionShortCutItem } from './shortcuts/editor.shortcuts';@@ -47,8 +43,6 @@ export class SlidesUIController extends Disposable {constructor(@Inject(Injector) protected readonly _injector: Injector,@IMenuManagerService protected readonly _menuManagerService: IMenuManagerService,- @Inject(ComponentManager) protected readonly _componentManager: ComponentManager,- @Inject(IconManager) protected readonly _iconManager: IconManager,@IUIPartsService protected readonly _uiPartsService: IUIPartsService,@ICommandService protected readonly _commandService: ICommandService,@IShortcutService protected readonly _shortcutService: IShortcutService@@ -56,8 +50,6 @@ export class SlidesUIController extends Disposable {super();this._initCommands();- this._initCustomComponents();- this._registerIcons();this._initUIComponents();this._initMenus();this._initShortcuts();@@ -67,20 +59,6 @@ export class SlidesUIController extends Disposable {this._menuManagerService.mergeMenu(menuSchema);}- private _initCustomComponents(): void {- const componentManager = this._componentManager;- this.disposeWithMe(componentManager.register(COMPONENT_SLIDE_IMAGE_POPUP_MENU, SlideImagePopupMenu));- this.disposeWithMe(componentManager.register(COMPONENT_SLIDE_SIDEBAR, Sidebar));- }-- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- AddImageIcon,- TextIcon,- GraphIcon,- }));- }-private _initCommands(): void {[AppendSlideOperation,diff --git a/packages/slides-ui/src/plugin.ts b/packages/slides-ui/src/plugin.tsindex 8afb8676b5..90c2f465d5 100644--- a/packages/slides-ui/src/plugin.ts+++ b/packages/slides-ui/src/plugin.ts@@ -31,6 +31,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import pkg from '../package.json';import { defaultPluginConfig, SLIDES_UI_PLUGIN_CONFIG_KEY } from './config/config';import { CanvasView } from './controllers/canvas-view';+import { ComponentsController } from './controllers/components.controller';import { SlideEditingRenderController } from './controllers/slide-editing.render-controller';import { SlideEditorBridgeRenderController } from './controllers/slide-editor-bridge.render-controller';import { SlideRenderController } from './controllers/slide.render-controller';@@ -69,6 +70,8 @@ export class UniverSlidesUIPlugin extends Plugin {}override onStarting(): void {+ this._injector.add([ComponentsController]);+ this._injector.get(ComponentsController);mergeOverrideWithDependencies([[SlideRenderService],[ISlideEditorBridgeService, { useClass: SlideEditorBridgeService }],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.tsnew file mode 100644index 0000000000..ad6bce3683--- /dev/null+++ b/packages/slides-ui/src/services/__tests__/slide-editor-bridge.service.spec.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { 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 { ISlideEditorBridgeService, SlideEditorBridgeService } from '../slide-editor-bridge.service';++describe('SlideEditorBridgeService', () => {+ let service: ISlideEditorBridgeService;++ 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([ISlideEditorBridgeService, { useClass: SlideEditorBridgeService }]);+ service = injector.get(ISlideEditorBridgeService);+ });++ it('publishes editor visibility changes and resets dirty state when editing starts', () => {+ const states: unknown[] = [];+ service.visible$.subscribe((state) => states.push(state));+ service.changeEditorDirty(true);++ service.changeVisible({ visible: true, eventType: DeviceInputEventType.Dblclick, unitId: 'slide-1' });++ expect(service.isVisible()).toBe(true);+ expect(service.getEditorDirty()).toBe(false);+ expect(states.at(-1)).toEqual({ visible: true, eventType: DeviceInputEventType.Dblclick, unitId: 'slide-1' });+ });+});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.tsnew file mode 100644index 0000000000..ddebafb7a0--- /dev/null+++ b/packages/slides-ui/src/services/__tests__/slide-editor-manager.service.spec.ts@@ -0,0 +1,46 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ISlideEditorManagerService, SlideEditorManagerService } from '../slide-editor-manager.service';++describe('SlideEditorManagerService', () => {+ let service: ISlideEditorManagerService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ISlideEditorManagerService, { useClass: SlideEditorManagerService }]);+ service = injector.get(ISlideEditorManagerService);+ });++ it('publishes slide text editor state, bounds and focus changes', () => {+ const states: unknown[] = [];+ const rects: unknown[] = [];+ const focus: boolean[] = [];+ service.state$.subscribe((state) => states.push(state));+ service.rect$.subscribe((rect) => rects.push(rect));+ service.focus$.subscribe((value) => focus.push(value));++ service.setState({ show: true, startX: 12, startY: 24 });+ service.setRect({ left: 12, top: 24, width: 120, height: 32 });+ service.setFocus(true);++ expect(states.at(-1)).toEqual({ show: true, startX: 12, startY: 24 });+ expect(rects.at(-1)).toEqual({ left: 12, top: 24, width: 120, height: 32 });+ expect(focus).toEqual([false, 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.tsnew file mode 100644index 0000000000..16b20dfa71--- /dev/null+++ b/packages/slides-ui/src/services/__tests__/slide-popup-manager.service.spec.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES 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, 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';++describe('SlideCanvasPopMangerService', () => {+ let service: SlideCanvasPopMangerService;+ let addPopup: ReturnType<typeof vi.fn>;+ let removePopup: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ addPopup = vi.fn(() => 'popup-1');+ removePopup = vi.fn();+ 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([SlideCanvasPopMangerService]);+ service = injector.get(SlideCanvasPopMangerService);+ });++ it('does not create a canvas popup when the current slide has no renderer', () => {+ const disposable = service.attachPopupToObject({ left: 0, top: 0, width: 10, height: 10 } as never, { componentKey: 'slide-comment' });++ disposable.dispose();++ expect(addPopup).not.toHaveBeenCalled();+ expect(removePopup).not.toHaveBeenCalled();+ });+});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.tsnew file mode 100644index 0000000000..c250cd9a38--- /dev/null+++ b/packages/slides-ui/src/services/__tests__/slide-render.service.spec.ts@@ -0,0 +1,61 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { 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 { SlideRenderService } from '../slide-render.service';++describe('SlideRenderService', () => {+ let slideAdded$: Subject<unknown>;+ let slideDisposed$: Subject<unknown>;+ let createRender: ReturnType<typeof vi.fn>;+ let removeRender: ReturnType<typeof vi.fn>;++ 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([SlideRenderService]);+ injector.get(SlideRenderService);+ });++ it('creates renderers for existing and newly added slide units', async () => {+ await Promise.resolve();+ slideAdded$.next({ unit: { getUnitId: () => 'new-slide' } });++ expect(createRender).toHaveBeenCalledWith('existing-slide');+ expect(createRender).toHaveBeenCalledWith('new-slide');+ });++ it('removes the renderer when a slide unit is disposed', async () => {+ await Promise.resolve();+ slideDisposed$.next({ getUnitId: () => 'old-slide' });++ expect(removeRender).toHaveBeenCalledWith('old-slide');+ });+});diff --git a/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts b/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.tsnew file mode 100644index 0000000000..4f7f831d69--- /dev/null+++ b/packages/thread-comment-ui/src/services/__tests__/thread-comment-panel.service.spec.ts@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ISidebarMethodOptions } from '@univerjs/ui';+import { Injector, IUniverInstanceService } from '@univerjs/core';+import { ISidebarService } from '@univerjs/ui';+import { of, Subject } from 'rxjs';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { ThreadCommentPanelService } from '../thread-comment-panel.service';++describe('ThreadCommentPanelService', () => {+ let service: ThreadCommentPanelService;+ let sidebarOptions$: Subject<ISidebarMethodOptions>;++ beforeEach(() => {+ sidebarOptions$ = new Subject();+ const injector = new Injector();+ injector.add([ISidebarService, { useValue: { sidebarOptions$, close: vi.fn() } as unknown as ISidebarService }]);+ injector.add([IUniverInstanceService, { useValue: { getCurrentTypeOfUnit$: () => of({}) } as unknown as IUniverInstanceService }]);+ injector.add([ThreadCommentPanelService]);+ service = injector.get(ThreadCommentPanelService);+ });++ it('hides the comment panel when the host sidebar closes', () => {+ const visibleStates: boolean[] = [];+ service.panelVisible$.subscribe((visible) => visibleStates.push(visible));++ service.setPanelVisible(true);+ sidebarOptions$.next({ visible: false });++ expect(service.panelVisible).toBe(false);+ expect(visibleStates).toEqual([false, true, false]);+ });++ it('publishes the active thread comment selected by the user', () => {+ const activeComments: unknown[] = [];+ service.activeCommentId$.subscribe((comment) => activeComments.push(comment));++ service.setActiveComment({ unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'c-1', trigger: 'cell' });++ expect(service.activeCommentId).toEqual({ unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'c-1', trigger: 'cell' });+ expect(activeComments.at(-1)).toEqual({ unitId: 'book-1', subUnitId: 'sheet-1', commentId: 'c-1', trigger: 'cell' });+ });+});diff --git a/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts b/packages/ui/src/controllers/__tests__/misc-controllers.spec.tsindex 25b9ad4c20..989b599fcf 100644--- a/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts+++ b/packages/ui/src/controllers/__tests__/misc-controllers.spec.ts@@ -58,10 +58,7 @@ describe('shortcut-display controllers', () => {});});- it('should register panel component, command and shortcut', () => {- const componentManager = {- register: vi.fn(() => ({ dispose: vi.fn() })),- };+ it('should register command and shortcut', () => {const shortcutService = {registerShortcut: vi.fn(() => ({ dispose: vi.fn() })),};@@ -70,14 +67,11 @@ describe('shortcut-display controllers', () => {};const controller = new ShortcutPanelController(- {} as any,- componentManager as any,shortcutService as any,{} as any,commandService as any);- expect(componentManager.register).toHaveBeenCalledTimes(1);expect(commandService.registerCommand).toHaveBeenCalledWith(ToggleShortcutPanelOperation);expect(shortcutService.registerShortcut).toHaveBeenCalledTimes(1);diff --git a/packages/ui/src/controllers/components.controller.ts b/packages/ui/src/controllers/components.controller.tsnew file mode 100644index 0000000000..b6fcd3022b--- /dev/null+++ b/packages/ui/src/controllers/components.controller.ts@@ -0,0 +1,73 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { ColorPicker } from '@univerjs/design';+import { IncreaseIcon, MoreDownIcon, RedoIcon, ReduceIcon, ShortcutIcon, UndoIcon } from '@univerjs/icons';+import { ShortcutPanelComponentName } from '../commands/operations/toggle-shortcut-panel.operation';+import { ComponentManager, IconManager } from '../common';+import { COLOR_PICKER_COMPONENT } from '../views/color-picker/interface';+import { COMMON_LABEL_COMPONENT, CommonLabel } from '../views/CommonLabel';+import { ShortcutPanel } from '../views/components/shortcut-panel/ShortcutPanel';+import { FontFamily, FontFamilyItem } from '../views/font-family/index';+import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../views/font-family/interface';+import { FontSize } from '../views/font-size/FontSize';+import { FONT_SIZE_COMPONENT } from '../views/font-size/interface';+import { HEADING_ITEM_COMPONENT, HeadingItem } from '../views/index';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager,+ @Inject(IconManager) private readonly _iconManager: IconManager+ ) {+ super();++ this._registerComponents2();+ this._registerIcons();+ this._registerComponents();+ }++ private _registerIcons(): void {+ this.disposeWithMe(this._iconManager.register({+ IncreaseIcon,+ MoreDownIcon,+ RedoIcon,+ ReduceIcon,+ ShortcutIcon,+ UndoIcon,+ }));+ }++ private _registerComponents(): void {+ ([+ [COMMON_LABEL_COMPONENT, CommonLabel],+ [HEADING_ITEM_COMPONENT, HeadingItem],+ [FONT_FAMILY_COMPONENT, FontFamily],+ [FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem],+ [FONT_SIZE_COMPONENT, FontSize],+ [COLOR_PICKER_COMPONENT, ColorPicker],+ ] as const).forEach(([key, comp]) => {+ this.disposeWithMe(+ this._componentManager.register(key, comp)+ );+ });+ }++ private _registerComponents2(): void {+ // register the panel+ this.disposeWithMe(this._componentManager.register(ShortcutPanelComponentName, ShortcutPanel));+ }+}diff --git a/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts b/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.tsindex b2eaeda566..8a0eb7e35d 100644--- a/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts+++ b/packages/ui/src/controllers/shortcut-display/shortcut-panel.controller.ts@@ -15,16 +15,13 @@*/import type { IShortcutItem } from '../../services/shortcut/shortcut.service';-import { Disposable, ICommandService, Inject, Injector } from '@univerjs/core';+import { Disposable, ICommandService } from '@univerjs/core';import {- ShortcutPanelComponentName,ToggleShortcutPanelOperation,} from '../../commands/operations/toggle-shortcut-panel.operation';-import { ComponentManager } from '../../common/component-manager';import { IMenuManagerService } from '../../services/menu/menu-manager.service';import { KeyCode, MetaKeys } from '../../services/shortcut/keycode';import { IShortcutService } from '../../services/shortcut/shortcut.service';-import { ShortcutPanel } from '../../views/components/shortcut-panel/ShortcutPanel';const ToggleShortcutPanelShortcut: IShortcutItem = {id: ToggleShortcutPanelOperation.id,@@ -39,16 +36,11 @@ const ToggleShortcutPanelShortcut: IShortcutItem = {*/export class ShortcutPanelController extends Disposable {constructor(- @Inject(Injector) injector: Injector,- @Inject(ComponentManager) componentManager: ComponentManager,@IShortcutService shortcutService: IShortcutService,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@ICommandService commandService: ICommandService) {super();-- // register the panel- this.disposeWithMe(componentManager.register(ShortcutPanelComponentName, ShortcutPanel));this.disposeWithMe(commandService.registerCommand(ToggleShortcutPanelOperation));// register the shortcutdiff --git a/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx b/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsxindex 81a7cd8fd4..6a8199121a 100644--- a/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx+++ b/packages/ui/src/controllers/ui/__tests__/ui-desktop-mobile.controller.spec.tsx@@ -58,9 +58,6 @@ function createCommonDeps() {focused$: new Subject<string>(),getFocusedUnit: vi.fn(() => null),},- iconManager: {- register: vi.fn(() => ({ dispose: vi.fn() })),- },};}@@ -87,7 +84,6 @@ describe('DesktopUIController', () => {registerComponent: vi.fn(() => ({ dispose: vi.fn() })),};const componentManager = {- register: vi.fn(() => ({ dispose: vi.fn() })),dispose: vi.fn(),};@@ -100,15 +96,13 @@ describe('DesktopUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);vi.advanceTimersByTime(3300);expect(menuManagerService.mergeMenu).toHaveBeenCalledTimes(1);expect(uiPartsService.registerComponent).toHaveBeenCalledTimes(3);- expect(componentManager.register).toHaveBeenCalledTimes(6);expect(render).toHaveBeenCalledWith(expect.any(Object), container);controller.dispose();@@ -124,7 +118,7 @@ describe('DesktopUIController', () => {const deps = createCommonDeps();const menuManagerService = { mergeMenu: vi.fn() };const uiPartsService = { registerComponent: vi.fn(() => ({ dispose: vi.fn() })) };- const componentManager = { register: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn() };+ const componentManager = { dispose: vi.fn() };const withMissingId = new DesktopUIController({ container: 'missing-container' } as any,@@ -135,8 +129,7 @@ describe('DesktopUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);const withDefault = new DesktopUIController(@@ -148,8 +141,7 @@ describe('DesktopUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);vi.advanceTimersByTime(3300);@@ -173,7 +165,7 @@ describe('DesktopUIController', () => {const mountContainer = document.createElement('div');const menuManagerService = { mergeMenu: vi.fn() };const uiPartsService = { registerComponent: vi.fn(() => ({ dispose: vi.fn() })) };- const componentManager = { register: vi.fn(() => ({ dispose: vi.fn() })), dispose: vi.fn() };+ const componentManager = { dispose: vi.fn() };const controller = new DesktopUIController({ container: mountContainer } as any,@@ -184,8 +176,7 @@ describe('DesktopUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);vi.advanceTimersByTime(3300);@@ -215,7 +206,6 @@ describe('MobileUIController', () => {registerComponent: vi.fn(() => ({ dispose: vi.fn() })),};const componentManager = {- register: vi.fn(() => ({ dispose: vi.fn() })),dispose: vi.fn(),};@@ -228,15 +218,13 @@ describe('MobileUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);vi.advanceTimersByTime(3300);expect(menuManagerService.mergeMenu).toHaveBeenCalledTimes(1);expect(uiPartsService.registerComponent).toHaveBeenCalledTimes(3);- expect(componentManager.register).toHaveBeenCalledTimes(6);expect(render).toHaveBeenCalledWith(expect.any(Object), expect.objectContaining({ id: 'missing-mobile' }));controller.dispose();@@ -262,7 +250,6 @@ describe('MobileUIController', () => {registerComponent: vi.fn(() => ({ dispose: vi.fn() })),};const componentManager = {- register: vi.fn(() => ({ dispose: vi.fn() })),dispose: vi.fn(),};@@ -275,8 +262,7 @@ describe('MobileUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);const byElement = new MobileUIController(@@ -288,8 +274,7 @@ describe('MobileUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);const byDefault = new MobileUIController(@@ -301,8 +286,7 @@ describe('MobileUIController', () => {deps.instanceService as any,menuManagerService as any,uiPartsService as any,- componentManager as any,- deps.iconManager as any+ componentManager as any);vi.advanceTimersByTime(3300);diff --git a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx b/packages/ui/src/controllers/ui/ui-desktop.controller.tsxindex db05dc479b..5e3206b915 100644--- a/packages/ui/src/controllers/ui/ui-desktop.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-desktop.controller.tsx@@ -20,25 +20,17 @@ import type { IUniverUIConfig } from '../../config/config';import type { IUniverWorkbenchProps } from '../../views/workbench/Workbench';import type { IWorkbenchOptions } from './ui.controller';import { Inject, Injector, IUniverInstanceService, LifecycleService, toDisposable } from '@univerjs/core';-import { ColorPicker, render as createRoot, unmount } from '@univerjs/design';+import { render as createRoot, unmount } from '@univerjs/design';import { IRenderManagerService } from '@univerjs/engine-render';-import { IncreaseIcon, MoreDownIcon, RedoIcon, ReduceIcon, ShortcutIcon, UndoIcon } from '@univerjs/icons';-import { ComponentManager, IconManager } from '../../common';+import { ComponentManager } from '../../common';import { menuSchema } from '../../menu/schema';import { ILayoutService } from '../../services/layout/layout.service';import { IMenuManagerService } from '../../services/menu/menu-manager.service';import { BuiltInUIPart, IUIPartsService } from '../../services/parts/parts.service';import { connectInjector } from '../../utils/di';-import { COLOR_PICKER_COMPONENT } from '../../views/color-picker/interface';-import { COMMON_LABEL_COMPONENT, CommonLabel } from '../../views/CommonLabel';import { FloatDom } from '../../views/components/dom/FloatDom';import { CanvasPopup } from '../../views/components/popup/CanvasPopup';import { Ribbon } from '../../views/components/ribbon/Ribbon';-import { FontFamily, FontFamilyItem } from '../../views/font-family/index';-import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../../views/font-family/interface';-import { FontSize } from '../../views/font-size/FontSize';-import { FONT_SIZE_COMPONENT } from '../../views/font-size/interface';-import { HEADING_ITEM_COMPONENT, HeadingItem } from '../../views/index';import { DesktopWorkbench } from '../../views/workbench/Workbench';import { SingleUnitUIController } from './ui-shared.controller';@@ -52,45 +44,16 @@ export class DesktopUIController extends SingleUnitUIController {@IUniverInstanceService instanceService: IUniverInstanceService,@IMenuManagerService menuManagerService: IMenuManagerService,@IUIPartsService uiPartsService: IUIPartsService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager) {super(injector, instanceService, layoutService, lifecycleService, renderManagerService);menuManagerService.mergeMenu(menuSchema);this._initBuiltinComponents(uiPartsService);- this._registerComponents();- this._registerIcons();this._bootstrapWorkbench();}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- IncreaseIcon,- MoreDownIcon,- RedoIcon,- ReduceIcon,- ShortcutIcon,- UndoIcon,- }));- }-- private _registerComponents() {- ([- [COMMON_LABEL_COMPONENT, CommonLabel],- [HEADING_ITEM_COMPONENT, HeadingItem],- [FONT_FAMILY_COMPONENT, FontFamily],- [FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem],- [FONT_SIZE_COMPONENT, FontSize],- [COLOR_PICKER_COMPONENT, ColorPicker],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });- }-override dispose(): void {super.dispose();this._componentManager.dispose();diff --git a/packages/ui/src/controllers/ui/ui-mobile.controller.tsx b/packages/ui/src/controllers/ui/ui-mobile.controller.tsxindex 5c371a5b70..11fbcca1f0 100644--- a/packages/ui/src/controllers/ui/ui-mobile.controller.tsx+++ b/packages/ui/src/controllers/ui/ui-mobile.controller.tsx@@ -20,25 +20,17 @@ import type { IUniverUIConfig } from '../../config/config';import type { IUniverWorkbenchProps } from '../../views/workbench/Workbench';import type { IUIController, IWorkbenchOptions } from './ui.controller';import { Inject, Injector, IUniverInstanceService, LifecycleService, toDisposable } from '@univerjs/core';-import { ColorPicker, render as createRoot, unmount } from '@univerjs/design';+import { render as createRoot, unmount } from '@univerjs/design';import { IRenderManagerService } from '@univerjs/engine-render';-import { IncreaseIcon, MoreDownIcon, RedoIcon, ReduceIcon, ShortcutIcon, UndoIcon } from '@univerjs/icons';-import { ComponentManager, IconManager } from '../../common';+import { ComponentManager } from '../../common';import { menuSchema } from '../../menu/schema';import { ILayoutService } from '../../services/layout/layout.service';import { IMenuManagerService } from '../../services/menu/menu-manager.service';import { BuiltInUIPart, IUIPartsService } from '../../services/parts/parts.service';import { connectInjector } from '../../utils/di';-import { COLOR_PICKER_COMPONENT } from '../../views/color-picker/interface';-import { COMMON_LABEL_COMPONENT, CommonLabel } from '../../views/CommonLabel';import { FloatDom } from '../../views/components/dom/FloatDom';import { CanvasPopup } from '../../views/components/popup/CanvasPopup';import { MobileRibbon } from '../../views/components/ribbon/MobileRibbon';-import { FontFamily, FontFamilyItem } from '../../views/font-family/index';-import { FONT_FAMILY_COMPONENT, FONT_FAMILY_ITEM_COMPONENT } from '../../views/font-family/interface';-import { FontSize } from '../../views/font-size/FontSize';-import { FONT_SIZE_COMPONENT } from '../../views/font-size/interface';-import { HEADING_ITEM_COMPONENT, HeadingItem } from '../../views/index';import { MobileWorkbench } from '../../views/mobile-workbench/MobileWorkbench';import { SingleUnitUIController } from './ui-shared.controller';@@ -52,29 +44,15 @@ export class MobileUIController extends SingleUnitUIController implements IUICon@IUniverInstanceService instanceService: IUniverInstanceService,@IMenuManagerService menuManagerService: IMenuManagerService,@IUIPartsService uiPartsService: IUIPartsService,- @Inject(ComponentManager) private readonly _componentManager: ComponentManager,- @Inject(IconManager) private readonly _iconManager: IconManager+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager) {super(injector, instanceService, layoutService, lifecycleService, renderManagerService);menuManagerService.mergeMenu(menuSchema);this._initBuiltinComponents(uiPartsService);- this._registerComponents();- this._registerIcons();this._bootstrapWorkbench();}- private _registerIcons(): void {- this.disposeWithMe(this._iconManager.register({- IncreaseIcon,- MoreDownIcon,- RedoIcon,- ReduceIcon,- ShortcutIcon,- UndoIcon,- }));- }-override dispose(): void {super.dispose();this._componentManager.dispose();@@ -84,21 +62,6 @@ export class MobileUIController extends SingleUnitUIController implements IUIConreturn bootstrap(this._injector, this._config, callback);}- private _registerComponents() {- ([- [COMMON_LABEL_COMPONENT, CommonLabel],- [HEADING_ITEM_COMPONENT, HeadingItem],- [FONT_FAMILY_COMPONENT, FontFamily],- [FONT_FAMILY_ITEM_COMPONENT, FontFamilyItem],- [FONT_SIZE_COMPONENT, FontSize],- [COLOR_PICKER_COMPONENT, ColorPicker],- ] as const).forEach(([key, comp]) => {- this.disposeWithMe(- this._componentManager.register(key, comp)- );- });- }-private _initBuiltinComponents(uiPartsService: IUIPartsService) {this.disposeWithMe(uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(CanvasPopup, this._injector)));this.disposeWithMe(uiPartsService.registerComponent(BuiltInUIPart.CONTENT, () => connectInjector(FloatDom, this._injector)));diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.tsindex f21e67d9bb..57bb61397c 100644--- a/packages/ui/src/mobile-plugin.ts+++ b/packages/ui/src/mobile-plugin.ts@@ -22,6 +22,7 @@ import { ComponentManager } from './common/component-manager';import { IconManager } from './common/icon-manager';import { ZIndexManager } from './common/z-index-manager';import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { ErrorController } from './controllers/error/error.controller';import { SharedController } from './controllers/shared-shortcut.controller';import { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';@@ -98,6 +99,7 @@ export class UniverMobileUIPlugin extends Plugin {registerDependencies(this._injector, mergeOverrideWithDependencies([[ComponentManager],[IconManager],+ [ComponentsController],[ThemeSwitcherService],[ZIndexManager],[ShortcutPanelService],@@ -136,6 +138,7 @@ export class UniverMobileUIPlugin extends Plugin {], this._config.override));touchDependencies(this._injector, [+ [ComponentsController],[IUIController],[ErrorController],]);diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.tsindex 68b9339728..ef0e6ba255 100644--- a/packages/ui/src/plugin.ts+++ b/packages/ui/src/plugin.ts@@ -22,6 +22,7 @@ import { ComponentManager } from './common/component-manager';import { IconManager } from './common/icon-manager';import { ZIndexManager } from './common/z-index-manager';import { defaultPluginConfig, UI_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { ErrorController } from './controllers/error/error.controller';import { SharedController } from './controllers/shared-shortcut.controller';import { ShortcutPanelController } from './controllers/shortcut-display/shortcut-panel.controller';@@ -98,6 +99,7 @@ export class UniverUIPlugin extends Plugin {registerDependencies(this._injector, mergeOverrideWithDependencies([[ComponentManager],[IconManager],+ [ComponentsController],[ThemeSwitcherService],[ZIndexManager],[ShortcutPanelService],@@ -132,6 +134,7 @@ export class UniverUIPlugin extends Plugin {], this._config.override));touchDependencies(this._injector, [+ [ComponentsController],[IUIController],[ErrorController],]);diff --git a/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.ts b/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.tsnew file mode 100644index 0000000000..d23896175c--- /dev/null+++ b/packages/ui/src/services/contextmenu/__tests__/contextmenu-host.service.spec.ts@@ -0,0 +1,52 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { ContextMenuHostService, IContextMenuHostService } from '../contextmenu-host.service';++describe('ContextMenuHostService', () => {+ let service: IContextMenuHostService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);+ service = injector.get(IContextMenuHostService);+ });++ it('hides the previously active menu when another menu becomes active', () => {+ const hideMainMenu = vi.fn();+ const hideFooterMenu = vi.fn();+ service.registerMenu('main', hideMainMenu);+ service.registerMenu('footer', hideFooterMenu);++ service.activateMenu('main');+ service.activateMenu('footer');++ expect(hideMainMenu).toHaveBeenCalledTimes(1);+ expect(hideFooterMenu).not.toHaveBeenCalled();+ expect(service.activeMenuId).toBe('footer');+ });++ it('clears active menu state when a registered menu is disposed', () => {+ const disposable = service.registerMenu('main', vi.fn());+ service.activateMenu('main');++ disposable.dispose();++ expect(service.activeMenuId).toBeNull();+ });+});diff --git a/packages/ui/src/services/parts/__tests__/parts.service.spec.ts b/packages/ui/src/services/parts/__tests__/parts.service.spec.tsnew file mode 100644index 0000000000..7cdce25e77--- /dev/null+++ b/packages/ui/src/services/parts/__tests__/parts.service.spec.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ComponentType } from '../../../common/component-manager';+import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { BuiltInUIPart, IUIPartsService, UIPartsService } from '../parts.service';++describe('UIPartsService', () => {+ let service: IUIPartsService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ service = injector.get(IUIPartsService);+ });++ it('registers UI components by screen region and removes them with the disposable', () => {+ const events: string[] = [];+ service.componentRegistered$.subscribe((part) => events.push(part));+ const Toolbar = (() => null) as ComponentType;++ const disposable = service.registerComponent(BuiltInUIPart.TOOLBAR, () => Toolbar);++ expect([...service.getComponents(BuiltInUIPart.TOOLBAR)]).toEqual([Toolbar]);+ disposable.dispose();+ expect([...service.getComponents(BuiltInUIPart.TOOLBAR)]).toEqual([]);+ expect(events).toEqual([BuiltInUIPart.TOOLBAR, BuiltInUIPart.TOOLBAR]);+ });++ it('publishes UI visibility changes for embedders that hide built-in chrome', () => {+ const changes: Array<{ ui: string; visible: boolean }> = [];+ service.uiVisibleChange$.subscribe((change) => changes.push(change));++ service.setUIVisible(BuiltInUIPart.HEADER, false);++ expect(service.isUIVisible(BuiltInUIPart.HEADER)).toBe(false);+ expect(service.isUIVisible(BuiltInUIPart.FOOTER)).toBe(true);+ expect(changes).toEqual([{ ui: BuiltInUIPart.HEADER, visible: false }]);+ });+});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.tsnew file mode 100644index 0000000000..8a9397e55d--- /dev/null+++ b/packages/ui/src/services/popup/__tests__/canvas-popup.service.spec.ts@@ -0,0 +1,62 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { BehaviorSubject } from 'rxjs';+import { beforeEach, describe, expect, it } from 'vitest';+import { CanvasPopupService, ICanvasPopupService } from '../canvas-popup.service';++describe('CanvasPopupService', () => {+ let service: ICanvasPopupService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ICanvasPopupService, { useClass: CanvasPopupService }]);+ service = injector.get(ICanvasPopupService);+ });++ it('tracks canvas popups and active popup ownership', () => {+ const popupId = 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.popups[0][1].onActiveChange?.(true);+ expect(service.activePopupId).toBe(popupId);++ service.popups[0][1].onActiveChange?.(false);+ expect(service.activePopupId).toBeNull();+ });++ it('notifies renderers when popup entries are added or removed', () => {+ const sizes: number[] = [];+ service.popups$.subscribe((popups) => sizes.push(popups.length));+ const popupId = 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.removePopup(popupId);++ expect(sizes).toEqual([0, 1, 0]);+ });+});diff --git a/packages/ui/src/views/custom-label/CustomLabel.tsx b/packages/ui/src/views/custom-label/CustomLabel.tsxindex afccd78863..1b7e412b4b 100644--- a/packages/ui/src/views/custom-label/CustomLabel.tsx+++ b/packages/ui/src/views/custom-label/CustomLabel.tsx@@ -90,8 +90,8 @@ export function CustomLabel(props: ICustomLabelProps) {return false;}, [realValue]);- if (icon) {- const Icon = iconManager.get(realIcon ?? '');+ if (realIcon) {+ const Icon = iconManager.get(realIcon);if (Icon) {nodes.push(diff --git a/packages/uniscript/src/controllers/components.controller.ts b/packages/uniscript/src/controllers/components.controller.tsnew file mode 100644index 0000000000..60a2782a6f--- /dev/null+++ b/packages/uniscript/src/controllers/components.controller.ts@@ -0,0 +1,34 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Disposable, Inject } from '@univerjs/core';+import { ComponentManager } from '@univerjs/ui';+import { ScriptPanelComponentName } from '../commands/operations/panel.operation';+import { ScriptEditorPanel } from '../views/components/ScriptEditorPanel';++export class ComponentsController extends Disposable {+ constructor(+ @Inject(ComponentManager) private readonly _componentManager: ComponentManager+ ) {+ super();++ this._registerComponents();+ }++ private _registerComponents(): void {+ this.disposeWithMe(this._componentManager.register(ScriptPanelComponentName, ScriptEditorPanel));+ }+}diff --git a/packages/uniscript/src/controllers/uniscript.controller.ts b/packages/uniscript/src/controllers/uniscript.controller.tsindex 17b3808691..521d189617 100644--- a/packages/uniscript/src/controllers/uniscript.controller.ts+++ b/packages/uniscript/src/controllers/uniscript.controller.ts@@ -14,23 +14,20 @@* limitations under the License.*/-import { Disposable, ICommandService, Inject } from '@univerjs/core';-import { ComponentManager, IMenuManagerService } from '@univerjs/ui';+import { Disposable, ICommandService } from '@univerjs/core';+import { IMenuManagerService } from '@univerjs/ui';-import { ScriptPanelComponentName, ToggleScriptPanelOperation } from '../commands/operations/panel.operation';+import { ToggleScriptPanelOperation } from '../commands/operations/panel.operation';import { menuSchema } from '../menu/schema';-import { ScriptEditorPanel } from '../views/components/ScriptEditorPanel';export class UniscriptController extends Disposable {constructor(@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,- @ICommandService commandService: ICommandService,- @Inject(ComponentManager) componentManager: ComponentManager+ @ICommandService commandService: ICommandService) {super();this._menuManagerService.mergeMenu(menuSchema);- this.disposeWithMe(componentManager.register(ScriptPanelComponentName, ScriptEditorPanel));this.disposeWithMe(commandService.registerCommand(ToggleScriptPanelOperation));}}diff --git a/packages/uniscript/src/plugin.ts b/packages/uniscript/src/plugin.tsindex 9f90d33f9f..57ead3358b 100644--- a/packages/uniscript/src/plugin.ts+++ b/packages/uniscript/src/plugin.ts@@ -19,6 +19,7 @@ import type { IUniverUniscriptConfig } from './config/config';import { IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';import pkg from '../package.json';import { defaultPluginConfig, UNISCRIPT_PLUGIN_CONFIG_KEY } from './config/config';+import { ComponentsController } from './controllers/components.controller';import { UniscriptController } from './controllers/uniscript.controller';import { ScriptEditorService } from './services/script-editor.service';import { IUniscriptExecutionService, UniscriptExecutionService } from './services/script-execution.service';@@ -51,6 +52,7 @@ export class UniverUniscriptPlugin extends Plugin {override onStarting(): void {const injector = this._injector;const dependencies: Dependency[] = [+ [ComponentsController],[UniscriptController],[ScriptEditorService],[ScriptPanelService],@@ -59,6 +61,7 @@ export class UniverUniscriptPlugin extends Plugin {dependencies.forEach((d) => injector.add(d));this.registerExecution();+ this._injector.get(ComponentsController);}override onSteady(): void {diff --git a/packages/uniscript/src/services/__tests__/script-editor.service.spec.ts b/packages/uniscript/src/services/__tests__/script-editor.service.spec.tsnew file mode 100644index 0000000000..bc496f617c--- /dev/null+++ b/packages/uniscript/src/services/__tests__/script-editor.service.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 { IConfigService, Injector } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { UNISCRIPT_PLUGIN_CONFIG_KEY } from '../../config/config';+import { ScriptEditorService } from '../script-editor.service';++describe('ScriptEditorService', () => {+ let service: ScriptEditorService;++ beforeEach(() => {+ vi.stubGlobal('window', globalThis);+ Reflect.deleteProperty(window, 'MonacoEnvironment');+ const injector = new Injector();+ injector.add([IConfigService, {+ useValue: {+ getConfig: (key: string) => key === UNISCRIPT_PLUGIN_CONFIG_KEY ? { getWorkerUrl: () => 'worker.js' } : undefined,+ } as unknown as IConfigService,+ }]);+ injector.add([ScriptEditorService]);+ service = injector.get(ScriptEditorService);+ });++ afterEach(() => {+ Reflect.deleteProperty(window, 'MonacoEnvironment');+ vi.unstubAllGlobals();+ });++ it('keeps the active Monaco editor instance until the registration is disposed', () => {+ const editor = { dispose: vi.fn() };++ const disposable = service.setEditorInstance(editor as never);++ expect(service.getEditorInstance()).toBe(editor);+ disposable.dispose();+ expect(service.getEditorInstance()).toBeNull();+ });++ it('initializes Monaco worker loading from plugin config', () => {+ service.requireVscodeEditor();++ expect(window.MonacoEnvironment?.getWorkerUrl?.('', '')).toBe('worker.js');+ });+});diff --git a/packages/uniscript/src/services/__tests__/script-execution.service.spec.ts b/packages/uniscript/src/services/__tests__/script-execution.service.spec.tsnew file mode 100644index 0000000000..56932edd0d--- /dev/null+++ b/packages/uniscript/src/services/__tests__/script-execution.service.spec.ts@@ -0,0 +1,57 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { DesktopLogService, ICommandService, ILogService, Injector, IUniverInstanceService, LifecycleService } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { IUniscriptExecutionService, UniscriptExecutionService } from '../script-execution.service';++type UniscriptGlobal = typeof globalThis & { __uniscriptResult?: boolean };++describe('UniscriptExecutionService', () => {+ let service: IUniscriptExecutionService;+ let logService: ILogService;++ beforeEach(() => {+ Reflect.deleteProperty(globalThis, '__uniscriptResult');+ const injector = new Injector();+ injector.add([ILogService, { useClass: DesktopLogService }]);+ injector.add([ICommandService, { useValue: {} as ICommandService }]);+ injector.add([IUniverInstanceService, { useValue: {} as IUniverInstanceService }]);+ injector.add([LifecycleService]);+ injector.add([IUniscriptExecutionService, { useClass: UniscriptExecutionService }]);+ service = injector.get(IUniscriptExecutionService);+ logService = injector.get(ILogService);+ });++ afterEach(() => {+ Reflect.deleteProperty(globalThis, '__uniscriptResult');+ vi.restoreAllMocks();+ });++ it('executes user script code with the Univer API argument available', async () => {+ await expect(service.execute('globalThis.__uniscriptResult = typeof univerAPI === "object";')).resolves.toBe(true);++ expect((globalThis as UniscriptGlobal).__uniscriptResult).toBe(true);+ });++ it('logs script runtime errors and reports failure', async () => {+ const errorSpy = vi.spyOn(logService, 'error');++ await expect(service.execute('throw new Error("boom");')).resolves.toBe(false);++ expect(errorSpy).toHaveBeenCalledWith(expect.any(Error));+ });+});diff --git a/packages/uniscript/src/services/__tests__/script-panel.service.spec.ts b/packages/uniscript/src/services/__tests__/script-panel.service.spec.tsnew file mode 100644index 0000000000..4364cb95e7--- /dev/null+++ b/packages/uniscript/src/services/__tests__/script-panel.service.spec.ts@@ -0,0 +1,41 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Injector } from '@univerjs/core';+import { beforeEach, describe, expect, it } from 'vitest';+import { ScriptPanelService } from '../script-panel.service';++describe('ScriptPanelService', () => {+ let service: ScriptPanelService;++ beforeEach(() => {+ const injector = new Injector();+ injector.add([ScriptPanelService]);+ service = injector.get(ScriptPanelService);+ });++ it('publishes panel open state changes for the Uniscript sidebar', () => {+ const states: boolean[] = [];+ service.open$.subscribe((state) => states.push(state));++ service.open();+ service.open();+ service.close();++ expect(service.isOpen).toBe(false);+ expect(states).toEqual([false, true, false]);+ });+});