Skip to content

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

refactor(docs-quick-insert-ui): reorganize menu-related files (#6764)

白熱0fda5442988d
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6349c53a82..b2ff2187ba 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -30,7 +30,7 @@ To better assist you, we recommend:
### Install dependencies
-Univer requires Node.js >= 18.17.0. We recommend using nvm or fnm to switch between different versions of Node.js.
+The development of Univer requires Node.js >= 22.18 and pnpm >= 10. Please make sure you have the correct versions installed.
```shell
git clone https://github.com/dream-num/univer
@@ -41,7 +41,6 @@ npm i -g pnpm
# install dependencies
pnpm install
-
```
### Start dev server
diff --git a/examples/esbuild.config.ts b/examples/esbuild.config.ts
index a02280e123..33347aa9d9 100644
--- a/examples/esbuild.config.ts
+++ b/examples/esbuild.config.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { BuildOptions, Plugin, SameShape } from 'esbuild';
+import type { BuildOptions, Plugin, PluginBuild, SameShape } from 'esbuild';
import { execSync } from 'node:child_process';
import path from 'node:path';
import process from 'node:process';
@@ -49,6 +49,138 @@ const monacoEditorEntryPoints = [
'vs/editor/editor.worker.js',
];
+const supportsColor = !!process.stdout.isTTY && process.env.NO_COLOR == null;
+const ansi = {
+ reset: '\x1B[0m',
+ bold: '\x1B[1m',
+ dim: '\x1B[2m',
+ red: '\x1B[31m',
+ green: '\x1B[32m',
+ yellow: '\x1B[33m',
+ blue: '\x1B[34m',
+ cyan: '\x1B[36m',
+ gray: '\x1B[90m',
+ underline: '\x1B[4m',
+} as const;
+
+type TLogLevel = 'error' | 'info' | 'ready' | 'recover' | 'watch';
+
+const levelStyleMap: Record<TLogLevel, string[]> = {
+ error: [ansi.bold, ansi.red],
+ info: [ansi.bold, ansi.blue],
+ ready: [ansi.bold, ansi.green],
+ recover: [ansi.bold, ansi.cyan],
+ watch: [ansi.bold, ansi.yellow],
+};
+
+function colorize(text: string, styles: string[]) {
+ if (!supportsColor || styles.length === 0) {
+ return text;
+ }
+
+ return `${styles.join('')}${text}${ansi.reset}`;
+}
+
+function formatLabel(level: TLogLevel) {
+ return colorize(`[${level}]`, levelStyleMap[level]);
+}
+
+function formatMuted(text: string) {
+ return colorize(text, [ansi.dim, ansi.gray]);
+}
+
+function formatUrl(url: string) {
+ return colorize(url, [ansi.bold, ansi.underline, ansi.cyan]);
+}
+
+function formatDuration(durationMs: number) {
+ if (durationMs < 1000) {
+ return `${durationMs}ms`;
+ }
+
+ return `${(durationMs / 1000).toFixed(durationMs < 10_000 ? 1 : 0)}s`;
+}
+
+function createLogger() {
+ function write(level: TLogLevel, message: string, method: 'error' | 'log' = 'log') {
+ console[method](`${formatLabel(level)} ${message}`);
+ }
+
+ return {
+ error(message: string) {
+ write('error', message, 'error');
+ },
+ info(message: string) {
+ write('info', message);
+ },
+ ready(message: string) {
+ write('ready', message);
+ },
+ recover(message: string) {
+ write('recover', message);
+ },
+ watch(message: string) {
+ write('watch', message);
+ },
+ muted(message: string) {
+ console.log(formatMuted(message));
+ },
+ url: formatUrl,
+ };
+}
+
+const logger = createLogger();
+
+function createWatchStatusPlugin() {
+ let serverUrl: string | null = null;
+ let hasSuccessfulBuild = false;
+ let lastBuildFailed = false;
+ let buildStartedAt = 0;
+
+ return {
+ plugin: {
+ name: 'watch-status',
+ setup(build: PluginBuild) {
+ build.onStart(() => {
+ buildStartedAt = Date.now();
+ });
+
+ build.onEnd((result) => {
+ const duration = formatDuration(Math.max(Date.now() - buildStartedAt, 0));
+
+ if (result.errors.length > 0) {
+ lastBuildFailed = true;
+ logger.error(`Build failed in ${duration} with ${result.errors.length} error(s). Waiting for changes...`);
+ return;
+ }
+
+ if (lastBuildFailed) {
+ lastBuildFailed = false;
+ hasSuccessfulBuild = true;
+ logger.recover(
+ serverUrl
+ ? `Build recovered in ${duration}. Local server: ${logger.url(serverUrl)}`
+ : `Build recovered in ${duration}.`
+ );
+ return;
+ }
+
+ if (!hasSuccessfulBuild) {
+ hasSuccessfulBuild = true;
+ logger.watch(`Initial build completed in ${duration}. Watching for changes...`);
+ return;
+ }
+
+ logger.watch(`Rebuilt in ${duration}.`);
+ });
+ },
+ } satisfies Plugin,
+ setServerUrl(url: string) {
+ serverUrl = url;
+ },
+ };
+}
+
function nodeBuildTask() {
return esbuild.build({
bundle: true,
@@ -150,9 +282,16 @@ if (isReact16) {
* Build the project
*/
async function main() {
+ if (args.watch) {
+ logger.info('Starting examples dev server...');
+ }
+
await monacoBuildTask();
if (args.watch) {
+ const watchStatus = createWatchStatusPlugin();
+ config.plugins?.push(watchStatus.plugin);
+
const ctx = await esbuild.context(config);
await nodeBuildTask();
await ctx.watch();
@@ -164,10 +303,16 @@ async function main() {
});
const url = `http://localhost:${port}`;
- console.log(`Local server: ${url}`);
+ watchStatus.setServerUrl(url);
+ logger.ready(`Local server: ${logger.url(url)}`);
+ logger.muted('Watching for file changes. Press Ctrl+C to stop.');
} else {
await esbuild.build(config);
}
}
-main();
+main().catch((error: unknown) => {
+ logger.error('Examples build exited unexpectedly.');
+ console.error(error);
+ process.exitCode = 1;
+});
diff --git a/examples/src/sheets/button.tsx b/examples/src/sheets/button.tsx
index 5cc7f4e874..74d736b654 100644
--- a/examples/src/sheets/button.tsx
+++ b/examples/src/sheets/button.tsx
@@ -15,7 +15,6 @@
*/
import type { Workbook } from '@univerjs/core';
-
import type { IRangeSelectorInstance } from '@univerjs/sheets-formula-ui';
import { ILogService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { Button } from '@univerjs/design';
diff --git a/packages/docs-drawing-ui/src/__tests__/create-doc-ui-test-bed.ts b/packages/docs-drawing-ui/src/__tests__/create-doc-ui-test-bed.ts
new file mode 100644
index 0000000000..d167617f03
--- /dev/null
+++ b/packages/docs-drawing-ui/src/__tests__/create-doc-ui-test-bed.ts
@@ -0,0 +1,184 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+
+import type { Ctor, Dependency, DependencyIdentifier, DocumentDataModel, IDocumentData, Nullable } from '@univerjs/core';
+import type { DocumentSkeleton, IRender, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import {
+ BooleanNumber,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ILogService,
+ Inject,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LogLevel,
+ Plugin,
+ RxDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService, DocStateEmitService } from '@univerjs/docs';
+import { DocIMEInputManagerService, DocSelectionRenderService, DocStateChangeManagerService } from '@univerjs/docs-ui';
+import { DocumentViewModel, IRenderManagerService } from '@univerjs/engine-render';
+import { BehaviorSubject, takeUntil } from 'rxjs';
+
+const DEFAULT_DOC_DATA: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 11,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ },
+ }],
+ paragraphs: [{ startIndex: 11 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+};
+
+export function createDocUiTestBed(docData?: IDocumentData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ this._injector.get(IUndoRedoService);
+ if (!dependencies?.some((dependency) => Array.isArray(dependency) && dependency[0] === IRenderManagerService)) {
+ this._injector.add([IRenderManagerService, { useClass: MockRenderManagerService as unknown as Ctor<IRenderManagerService> }]);
+ }
+ this._injector.add([DocSelectionManagerService]);
+ this._injector.add([DocStateEmitService]);
+ this._injector.add([DocStateChangeManagerService]);
+ this._injector.add([DocIMEInputManagerService]);
+ this._injector.add([DocSelectionRenderService]);
+ dependencies?.forEach((dependency) => this._injector.add(dependency));
+ }
+
+ override onReady(): void {
+ this._injector.get(DocStateChangeManagerService);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, docData || DEFAULT_DOC_DATA);
+ const univerInstanceService = get(IUniverInstanceService);
+ const fakeDocSkeletonManager = new MockDocSkeletonManagerService({
+ unit: doc,
+ unitId: doc.getUnitId(),
+ type: UniverInstanceType.UNIVER_DOC,
+ engine: null as any,
+ scene: null as any,
+ mainComponent: null as any,
+ components: null as any,
+ isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
+ }, univerInstanceService);
+
+ injector.add([DocSkeletonManagerService, { useValue: fakeDocSkeletonManager as unknown as DocSkeletonManagerService }]);
+ univerInstanceService.focusUnit(doc.getUnitId());
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ return {
+ univer,
+ injector,
+ get,
+ doc,
+ };
+}
+
+class MockRenderManagerService implements Pick<IRenderManagerService, 'getRenderById'> {
+ constructor(@Inject(Injector) private readonly _injector: Injector) {}
+
+ getRenderById(): Nullable<IRender> {
+ return {
+ with: <T>(identifier: DependencyIdentifier<T>) => this._injector.get(identifier),
+ } as unknown as IRender;
+ }
+}
+
+class MockDocSkeletonManagerService extends RxDisposable implements IRenderModule {
+ private _docViewModel!: DocumentViewModel;
+ private readonly _currentSkeleton$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);
+ readonly currentSkeleton$ = this._currentSkeleton$.asObservable();
+ private readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);
+ readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+ this._update();
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((documentModel) => {
+ if (documentModel?.getUnitId() === this._context.unitId) {
+ this._update();
+ }
+ });
+ }
+
+ private _update() {
+ const documentDataModel = this._context.unit;
+ const unitId = this._context.unitId;
+
+ if (documentDataModel.getBody() == null) {
+ return;
+ }
+
+ if (this._docViewModel && unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ this._docViewModel.reset(documentDataModel);
+ } else if (!this._docViewModel) {
+ this._docViewModel = new DocumentViewModel(documentDataModel);
+ }
+ }
+
+ getSkeleton(): DocumentSkeleton {
+ throw new Error('[MockDocSkeletonManagerService]: cannot access to doc skeleton in unit tests!');
+ }
+
+ getViewModel(): DocumentViewModel {
+ return this._docViewModel;
+ }
+}
diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
index 09d7c5406f..104fbfb700 100644
--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
@@ -14,182 +14,320 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
-import { ArrangeTypeEnum, Direction, ICommandService, IUniverInstanceService, JSONX, PositionedObjectLayoutType } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDocumentData, Injector } from '@univerjs/core';
+import {
+ Direction,
+ ICommandService,
+ IUniverInstanceService,
+ PositionedObjectLayoutType,
+ UniverInstanceType,
+ WrapTextType,
+} from '@univerjs/core';
import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
-import { IDocDrawingService } from '@univerjs/docs-drawing';
+import { DocDrawingController as CoreDocDrawingController, DocDrawingService, IDocDrawingService } from '@univerjs/docs-drawing';
+import { DocSelectionRenderService } from '@univerjs/docs-ui';
+import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';
import { IRenderManagerService } from '@univerjs/engine-render';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createDocUiTestBed } from '../../../__tests__/create-doc-ui-test-bed';
+import { DocDrawingAddRemoveController } from '../../../controllers/doc-drawing-notification.controller';
import { DeleteDocDrawingsCommand } from '../delete-doc-drawing.command';
import { InsertDocDrawingCommand } from '../insert-doc-drawing.command';
import { MoveDocDrawingsCommand } from '../move-drawings.command';
import { RemoveDocDrawingCommand } from '../remove-doc-drawing.command';
-import { SetDocDrawingArrangeCommand } from '../set-drawing-arrange.command';
-import { UpdateDrawingDocTransformCommand } from '../update-doc-drawing.command';
-
-function createAccessor() {
- const commandService = { syncExecuteCommand: vi.fn(() => true), executeCommand: vi.fn(() => true) };
- const docDrawingService = {
- getForwardDrawingsOp: vi.fn(() => ({ redo: ['r1', 'r2', 'r3', 'move-forward'], undo: ['undo'], objects: ['shape-1'] })),
- getBackwardDrawingOp: vi.fn(() => ({ redo: ['r1', 'r2', 'r3', 'move-backward'], undo: ['undo'], objects: ['shape-1'] })),
- getFrontDrawingsOp: vi.fn(() => ({ redo: ['r1', 'r2', 'r3', 'move-front'], undo: ['undo'], objects: ['shape-1'] })),
- getBackDrawingsOp: vi.fn(() => ({ redo: ['r1', 'r2', 'r3', 'move-back'], undo: ['undo'], objects: ['shape-1'] })),
- getFocusDrawings: vi.fn(() => [{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-1', drawingType: 'drawing' }]),
- };
- const renderManagerService = {
- getRenderById: vi.fn(() => ({
- scene: { getTransformerByCreate: () => ({ refreshControls: vi.fn() }) },
- with: () => ({ getSegment: () => '' }),
- })),
- };
- const currentDocument = {
- getUnitId: vi.fn(() => 'doc-1'),
- getSelfOrHeaderFooterModel: vi.fn(() => ({
- getBody: () => ({ customBlocks: [{ blockId: 'shape-1', startIndex: 3 }] }),
- })),
- getSnapshot: vi.fn(() => ({ drawingsOrder: ['shape-1'] })),
- getDrawings: vi.fn(() => ({ 'shape-1': { id: 'shape-1' } })),
- getDrawingsOrder: vi.fn(() => ['shape-1']),
+import { UpdateDocDrawingDistanceCommand, UpdateDocDrawingWrapTextCommand, UpdateDrawingDocTransformCommand } from '../update-doc-drawing.command';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function createBaseDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello\r\n',
+ customBlocks: [],
+ },
+ drawings: {},
+ drawingsOrder: [],
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
};
- const univerInstanceService = {
- getCurrentUniverDocInstance: vi.fn(() => currentDocument),
- getUniverDocInstance: vi.fn(() => ({
- getSnapshot: () => ({
- drawings: {
- 'shape-1': {
- layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
- docTransform: { positionH: { posOffset: 1 }, positionV: { posOffset: 2 } },
- },
- 'inline-1': {
- layoutType: PositionedObjectLayoutType.INLINE,
- docTransform: { positionH: { posOffset: 1 }, positionV: { posOffset: 2 } },
- },
+}
+
+function createDrawingDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: '\b\r\n',
+ customBlocks: [{
+ startIndex: 0,
+ blockId: 'shape-1',
+ }],
+ },
+ drawings: {
+ 'shape-1': {
+ drawingId: 'shape-1',
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawingType: 'image',
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ docTransform: {
+ positionH: { posOffset: 1 },
+ positionV: { posOffset: 2 },
},
- }),
- })),
- };
- const docSelectionManagerService = {
- getActiveTextRange: vi.fn(() => ({ collapsed: true, startOffset: 1, segmentId: '' })),
+ } as never,
+ },
+ drawingsOrder: ['shape-1'],
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
};
+}
- return {
- accessor: {
- get(token: unknown) {
- if (token === ICommandService) {
- return commandService;
+function setupDrawingTestBed(docData: IDocumentData) {
+ const refreshControls = vi.fn();
+ let injector!: Injector;
+ const renderManagerService = {
+ getRenderById: () => ({
+ scene: {
+ getTransformerByCreate: () => ({
+ refreshControls,
+ }),
+ },
+ with: <T>(token: T) => {
+ if (token === DocSelectionRenderService) {
+ return {
+ getSegment: () => '',
+ } as T;
}
- if (token === IDocDrawingService) {
- return docDrawingService;
- }
+ return injector.get(token as never);
+ },
+ }),
+ };
+ const testBed = createDocUiTestBed(docData, [
+ [IRenderManagerService, { useValue: renderManagerService }],
+ ]);
+ const { univer, get } = testBed;
+ injector = testBed.injector;
- if (token === IRenderManagerService) {
- return renderManagerService;
- }
+ injector.add([DocDrawingService]);
+ injector.add([IDocDrawingService, { useClass: DocDrawingService }]);
+ injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);
+ injector.add([CoreDocDrawingController]);
+ injector.add([DocDrawingAddRemoveController]);
- if (token === IUniverInstanceService) {
- return univerInstanceService;
- }
+ const commandService = get(ICommandService);
+ [
+ InsertDocDrawingCommand,
+ RemoveDocDrawingCommand,
+ DeleteDocDrawingsCommand,
+ MoveDocDrawingsCommand,
+ UpdateDocDrawingDistanceCommand,
+ UpdateDocDrawingWrapTextCommand,
+ UpdateDrawingDocTransformCommand,
+ RichTextEditingMutation as unknown as ICommand,
+ ].forEach((command) => commandService.registerCommand(command));
- if (token === DocSelectionManagerService) {
- return docSelectionManagerService;
- }
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
- throw new Error(`Unknown dependency: ${String(token)}`);
- },
- } as IAccessor,
+ const coreDocDrawingController = injector.get(CoreDocDrawingController);
+ injector.get(DocDrawingAddRemoveController);
+ coreDocDrawingController.loadDrawingDataForUnit('test-doc');
+
+ return {
+ univer,
+ get,
+ injector,
commandService,
- currentDocument,
- docDrawingService,
- docSelectionManagerService,
+ selectionManager,
+ docDrawingService: injector.get(IDocDrawingService),
+ drawingManagerService: injector.get(IDrawingManagerService),
+ refreshControls,
};
}
-describe('docs drawing commands', () => {
- it('arranges drawings by converting drawing order ops into rich-text mutations', () => {
- const composeSpy = vi.spyOn(JSONX, 'compose').mockReturnValue(['composed'] as never);
- const { accessor, commandService } = createAccessor();
+describe('docs drawing commands integration', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('inserts a drawing through the real mutation chain and synchronizes drawing services', async () => {
+ const testBed = setupDrawingTestBed(createBaseDocData());
+
+ testBed.selectionManager.__TEST_ONLY_add([{
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
- expect(SetDocDrawingArrangeCommand.handler(accessor, {
- unitId: 'doc-1',
- subUnitId: 'doc-1',
- drawingIds: ['shape-1'],
- arrangeType: ArrangeTypeEnum.forward,
+ expect(await testBed.commandService.executeCommand(InsertDocDrawingCommand.id, {
+ drawings: [{
+ drawingId: 'shape-1',
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawingType: 'image',
+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,
+ docTransform: {
+ positionH: { posOffset: 1 },
+ positionV: { posOffset: 2 },
+ },
+ }],
})).toBe(true);
- expect(composeSpy).toHaveBeenCalled();
- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(RichTextEditingMutation.id, {
- unitId: 'doc-1',
- actions: ['composed'],
- textRanges: null,
+ await waitNextTick();
+
+ const doc = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;
+
+ expect(doc.getBody()?.dataStream).toBe('Hello\b\r\n');
+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 5, blockId: 'shape-1' }]);
+ expect(doc.getSnapshot().drawingsOrder).toEqual(['shape-1']);
+ expect(doc.getSnapshot().drawings?.['shape-1']).toMatchObject({ drawingId: 'shape-1' });
+ expect(testBed.docDrawingService.getDrawingByParam({ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' })).toMatchObject({
+ drawingId: 'shape-1',
});
+ expect(testBed.drawingManagerService.getDrawingOrder('test-doc', 'test-doc')).toEqual(['shape-1']);
+
+ testBed.univer.dispose();
});
- it('removes focused drawings and delegates deletion to the remove command', async () => {
- const { accessor, commandService, docDrawingService } = createAccessor();
- expect(await DeleteDocDrawingsCommand.handler(accessor)).toBe(true);
- expect(commandService.executeCommand).toHaveBeenCalledWith('doc.command.remove-doc-image', {
- unitId: 'doc-1',
- drawings: [{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-1', drawingType: 'drawing' }],
- });
+ it('deletes a focused drawing through the command pipeline and removes it from the document and services', async () => {
+ const testBed = setupDrawingTestBed(createDrawingDocData());
+
+ testBed.docDrawingService.focusDrawing([{ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' }]);
- docDrawingService.getFocusDrawings.mockReturnValue([]);
- expect(await DeleteDocDrawingsCommand.handler(accessor)).toBe(false);
+ expect(await testBed.commandService.executeCommand(DeleteDocDrawingsCommand.id)).toBe(true);
+ await waitNextTick();
+
+ const doc = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;
+
+ expect(doc.getBody()?.dataStream).toBe('\r\n');
+ expect(doc.getBody()?.customBlocks).toEqual([]);
+ expect(doc.getSnapshot().drawings).toEqual({});
+ expect(doc.getSnapshot().drawingsOrder).toEqual([]);
+ expect(testBed.docDrawingService.getDrawingByParam({ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' })).toBeUndefined();
+ expect(testBed.drawingManagerService.getDrawingByParam({ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' })).toBeUndefined();
+
+ testBed.univer.dispose();
});
- it('builds rich-text removal mutations and moves floating drawings with keyboard nudges', () => {
- const { accessor, commandService, docDrawingService } = createAccessor();
- expect(RemoveDocDrawingCommand.handler(accessor, {
- unitId: 'doc-1',
- drawings: [{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-1' }],
- } as never)).toBe(true);
- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(RichTextEditingMutation.id, expect.objectContaining({
- unitId: 'doc-1',
- textRanges: [{ startOffset: 3, endOffset: 3 }],
- }));
-
- docDrawingService.getFocusDrawings.mockReturnValue([
- { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-1', drawingType: 'drawing' },
- { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'inline-1', drawingType: 'drawing' },
- ]);
- expect(MoveDocDrawingsCommand.handler(accessor, { direction: Direction.RIGHT })).toBe(true);
- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(UpdateDrawingDocTransformCommand.id, {
- unitId: 'doc-1',
- subUnitId: 'doc-1',
- drawings: [{ drawingId: 'shape-1', key: 'positionH', value: { posOffset: 3 } }],
- });
+ it('moves a focused floating drawing by updating the persisted doc transform', async () => {
+ const testBed = setupDrawingTestBed(createDrawingDocData());
+
+ testBed.docDrawingService.focusDrawing([{ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' }]);
+
+ expect(await testBed.commandService.executeCommand(MoveDocDrawingsCommand.id, {
+ direction: Direction.RIGHT,
+ })).toBe(true);
+ await waitNextTick();
+
+ const doc = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;
+
+ expect(doc.getSnapshot().drawings?.['shape-1'].docTransform.positionH).toEqual({ posOffset: 3 });
+ expect(testBed.refreshControls).toHaveBeenCalled();
+
+ testBed.univer.dispose();
});
- it('inserts drawing placeholders into the active document selection', () => {
- const composeSpy = vi.spyOn(JSONX, 'compose').mockReturnValue(['insert-composed'] as never);
- const editOp = vi.fn(() => ['edit-op']);
- const insertOp = vi.fn((path, value) => ({ path, value }));
- vi.spyOn(JSONX, 'getInstance').mockReturnValue({
- editOp,
- insertOp,
- removeOp: vi.fn(),
- } as never);
- const { accessor, commandService } = createAccessor();
-
- expect(InsertDocDrawingCommand.handler(accessor, {
- drawings: [{ drawingId: 'shape-2', unitId: 'doc-1', subUnitId: 'doc-1' }],
- } as never)).toBe(true);
- expect(editOp).toHaveBeenCalledTimes(1);
- expect(insertOp).toHaveBeenCalledWith(['drawings', 'shape-2'], expect.objectContaining({ drawingId: 'shape-2' }));
- expect(composeSpy).toHaveBeenCalled();
- expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(RichTextEditingMutation.id, {
- unitId: 'doc-1',
- actions: ['insert-composed'],
- textRanges: [],
+ it('updates drawing wrap distances through the command pipeline', async () => {
+ const testBed = setupDrawingTestBed(createDrawingDocData());
+
+ expect(await testBed.commandService.executeCommand(UpdateDocDrawingDistanceCommand.id, {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawings: [{
+ drawingId: 'shape-1',
+ }],
+ dist: {
+ distT: 12,
+ distB: 16,
+ distL: 8,
+ distR: 10,
+ },
+ })).toBe(true);
+ await waitNextTick();
+
+ const doc = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;
+
+ expect(doc.getSnapshot().drawings?.['shape-1']).toMatchObject({
+ distT: 12,
+ distB: 16,
+ distL: 8,
+ distR: 10,
});
+
+ testBed.univer.dispose();
+ });
+
+ it('updates drawing wrap text through the command pipeline', async () => {
+ const testBed = setupDrawingTestBed(createDrawingDocData());
+
+ expect(await testBed.commandService.executeCommand(UpdateDocDrawingWrapTextCommand.id, {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawings: [{
+ drawingId: 'shape-1',
+ }],
+ wrapText: WrapTextType.RIGHT,
+ })).toBe(true);
+ await waitNextTick();
+
+ const doc = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;
+
+ expect(doc.getSnapshot().drawings?.['shape-1'].wrapText).toBe(WrapTextType.RIGHT);
+
+ testBed.univer.dispose();
});
- it('returns false when inserting drawings without an active text range', () => {
- const { accessor, commandService, docSelectionManagerService } = createAccessor();
- docSelectionManagerService.getActiveTextRange.mockReturnValue(null as never);
+ it('updates drawing doc transform through the command pipeline', async () => {
+ const testBed = setupDrawingTestBed(createDrawingDocData());
+
+ expect(await testBed.commandService.executeCommand(UpdateDrawingDocTransformCommand.id, {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ drawings: [{
+ drawingId: 'shape-1',
+ key: 'positionV',
+ value: {
+ posOffset: 18,
+ },
+ }],
+ })).toBe(true);
+ await waitNextTick();
+
+ const doc = testBed.get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;
+
+ expect(doc.getSnapshot().drawings?.['shape-1'].docTransform.positionV).toEqual({ posOffset: 18 });
+ expect(testBed.refreshControls).toHaveBeenCalled();
- expect(InsertDocDrawingCommand.handler(accessor, {
- drawings: [{ drawingId: 'shape-2', unitId: 'doc-1', subUnitId: 'doc-1' }],
- } as never)).toBe(false);
- expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();
+ testBed.univer.dispose();
});
});
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
deleted file mode 100644
index 48ed9b0e6a..0000000000
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
+++ /dev/null
@@ -1,131 +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 { RedoCommand, UndoCommand } from '@univerjs/core';
-import { RichTextEditingMutation } from '@univerjs/docs';
-import { describe, expect, it, vi } from 'vitest';
-import { DocDrawingAddRemoveController } from '../doc-drawing-notification.controller';
-
-describe('DocDrawingAddRemoveController', () => {
- it('applies add and remove notifications before rich-text mutations execute', () => {
- let beforeHandler: ((command: { id: string; params: unknown }) => void) | undefined;
- const drawingManagerService = {
- applyJson1: vi.fn(),
- addNotification: vi.fn(),
- removeNotification: vi.fn(),
- };
- const docDrawingService = {
- getBatchAddOp: vi.fn(() => ({ subUnitId: 'doc-1', redo: ['add-redo'], objects: [{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-1' }] })),
- getBatchRemoveOp: vi.fn(() => ({ subUnitId: 'doc-1', redo: ['remove-redo'], objects: [{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-2' }] })),
- applyJson1: vi.fn(),
- addNotification: vi.fn(),
- removeNotification: vi.fn(),
- };
-
- const controller = new DocDrawingAddRemoveController(
- {} as never,
- {
- beforeCommandExecuted: vi.fn((handler) => {
- beforeHandler = handler;
- return { dispose: vi.fn() };
- }),
- onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),
- } as never,
- drawingManagerService as never,
- docDrawingService as never,
- {} as never
- );
-
- expect(controller).toBeTruthy();
-
- beforeHandler!({
- id: RichTextEditingMutation.id,
- params: {
- unitId: 'doc-1',
- actions: [['drawings', 'shape-1', { i: { drawingId: 'shape-1', unitId: 'doc-1', subUnitId: 'doc-1' } }]],
- },
- });
- beforeHandler!({
- id: RichTextEditingMutation.id,
- params: {
- unitId: 'doc-1',
- actions: [['drawings', 'shape-2', { d: { drawingId: 'shape-2' } }]],
- },
- });
-
- expect(docDrawingService.getBatchAddOp).toHaveBeenCalledWith([
- expect.objectContaining({ drawingId: 'shape-1', unitId: 'doc-1', subUnitId: 'doc-1' }),
- ]);
- expect(docDrawingService.getBatchRemoveOp).toHaveBeenCalledWith([
- { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-2' },
- ]);
- expect(drawingManagerService.applyJson1).toHaveBeenNthCalledWith(1, 'doc-1', 'doc-1', ['add-redo']);
- expect(docDrawingService.applyJson1).toHaveBeenNthCalledWith(2, 'doc-1', 'doc-1', ['remove-redo']);
- expect(drawingManagerService.addNotification).toHaveBeenCalledWith([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-1' }]);
- expect(docDrawingService.removeNotification).toHaveBeenCalledWith([{ unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'shape-2' }]);
- });
-
- it('updates drawing order after reorder mutations and refreshes transformers on undo redo', () => {
- const onHandlers: Array<(command: { id: string; params?: unknown }) => void> = [];
- const refreshControls = vi.fn();
- const drawingManagerService = {
- setDrawingOrder: vi.fn(),
- orderNotification: vi.fn(),
- getFocusDrawings: vi.fn(() => [{ drawingId: 'shape-1' }]),
- };
- const docDrawingService = {
- setDrawingOrder: vi.fn(),
- orderNotification: vi.fn(),
- };
-
- const controller = new DocDrawingAddRemoveController(
- {
- getUniverDocInstance: vi.fn(() => ({ getSnapshot: vi.fn(() => ({ drawingsOrder: ['shape-2', 'shape-1'] })) })),
- getCurrentUniverDocInstance: vi.fn(() => ({ getUnitId: vi.fn(() => 'doc-1') })),
- } as never,
- {
- beforeCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),
- onCommandExecuted: vi.fn((handler) => {
- onHandlers.push(handler);
- return { dispose: vi.fn() };
- }),
- } as never,
- drawingManagerService as never,
- docDrawingService as never,
- {
- getRenderById: vi.fn(() => ({
- scene: { getTransformerByCreate: vi.fn(() => ({ refreshControls })) },
- })),
- } as never
- );
-
- expect(controller).toBeTruthy();
-
- onHandlers.forEach((handler) => {
- handler({
- id: RichTextEditingMutation.id,
- params: { unitId: 'doc-1', actions: ['drawingsOrder', [0, { d: 0 }], [1, { p: 0 }]] },
- });
- });
-
- expect(drawingManagerService.setDrawingOrder).toHaveBeenCalledWith('doc-1', 'doc-1', ['shape-2', 'shape-1']);
- expect(docDrawingService.orderNotification).toHaveBeenCalledWith({ unitId: 'doc-1', subUnitId: 'doc-1', drawingIds: ['shape-2', 'shape-1'] });
-
- onHandlers.forEach((handler) => handler({ id: UndoCommand.id }));
- onHandlers.forEach((handler) => handler({ id: RedoCommand.id }));
- expect(refreshControls).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing.controller.spec.ts
deleted file mode 100644
index 8eb3b92e54..0000000000
--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing.controller.spec.ts
+++ /dev/null
@@ -1,43 +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, IMenuManagerService, IShortcutService } from '@univerjs/ui';
-import { describe, expect, it, vi } from 'vitest';
-import { COMPONENT_DOC_DRAWING_PANEL } from '../../views/doc-image-panel/component-name';
-import { DocDrawingUIController } from '../doc-drawing.controller';
-
-describe('DocDrawingUIController', () => {
- it('registers drawing commands, sidebar component, menus, and shortcuts', () => {
- const register = vi.fn(() => ({ dispose: vi.fn() }));
- const mergeMenu = vi.fn();
- const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));
- const registerShortcut = vi.fn(() => ({ dispose: vi.fn() }));
-
- const controller = new DocDrawingUIController(
- { register } as unknown as ComponentManager,
- { mergeMenu } as unknown as IMenuManagerService,
- { registerCommand } as unknown as ICommandService,
- { registerShortcut } as unknown as IShortcutService
- );
-
- expect(controller).toBeTruthy();
- expect(registerCommand).toHaveBeenCalledTimes(17);
- expect(register).toHaveBeenCalledWith(COMPONENT_DOC_DRAWING_PANEL, expect.any(Function));
- expect(mergeMenu).toHaveBeenCalledTimes(1);
- expect(registerShortcut).toHaveBeenCalledTimes(5);
- });
-});
diff --git a/packages/docs-hyper-link-ui/src/__tests__/create-doc-ui-test-bed.ts b/packages/docs-hyper-link-ui/src/__tests__/create-doc-ui-test-bed.ts
new file mode 100644
index 0000000000..d167617f03
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/__tests__/create-doc-ui-test-bed.ts
@@ -0,0 +1,184 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+
+import type { Ctor, Dependency, DependencyIdentifier, DocumentDataModel, IDocumentData, Nullable } from '@univerjs/core';
+import type { DocumentSkeleton, IRender, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import {
+ BooleanNumber,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ILogService,
+ Inject,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LogLevel,
+ Plugin,
+ RxDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService, DocStateEmitService } from '@univerjs/docs';
+import { DocIMEInputManagerService, DocSelectionRenderService, DocStateChangeManagerService } from '@univerjs/docs-ui';
+import { DocumentViewModel, IRenderManagerService } from '@univerjs/engine-render';
+import { BehaviorSubject, takeUntil } from 'rxjs';
+
+const DEFAULT_DOC_DATA: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 11,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ },
+ }],
+ paragraphs: [{ startIndex: 11 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+};
+
+export function createDocUiTestBed(docData?: IDocumentData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ this._injector.get(IUndoRedoService);
+ if (!dependencies?.some((dependency) => Array.isArray(dependency) && dependency[0] === IRenderManagerService)) {
+ this._injector.add([IRenderManagerService, { useClass: MockRenderManagerService as unknown as Ctor<IRenderManagerService> }]);
+ }
+ this._injector.add([DocSelectionManagerService]);
+ this._injector.add([DocStateEmitService]);
+ this._injector.add([DocStateChangeManagerService]);
+ this._injector.add([DocIMEInputManagerService]);
+ this._injector.add([DocSelectionRenderService]);
+ dependencies?.forEach((dependency) => this._injector.add(dependency));
+ }
+
+ override onReady(): void {
+ this._injector.get(DocStateChangeManagerService);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, docData || DEFAULT_DOC_DATA);
+ const univerInstanceService = get(IUniverInstanceService);
+ const fakeDocSkeletonManager = new MockDocSkeletonManagerService({
+ unit: doc,
+ unitId: doc.getUnitId(),
+ type: UniverInstanceType.UNIVER_DOC,
+ engine: null as any,
+ scene: null as any,
+ mainComponent: null as any,
+ components: null as any,
+ isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
+ }, univerInstanceService);
+
+ injector.add([DocSkeletonManagerService, { useValue: fakeDocSkeletonManager as unknown as DocSkeletonManagerService }]);
+ univerInstanceService.focusUnit(doc.getUnitId());
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ return {
+ univer,
+ injector,
+ get,
+ doc,
+ };
+}
+
+class MockRenderManagerService implements Pick<IRenderManagerService, 'getRenderById'> {
+ constructor(@Inject(Injector) private readonly _injector: Injector) {}
+
+ getRenderById(): Nullable<IRender> {
+ return {
+ with: <T>(identifier: DependencyIdentifier<T>) => this._injector.get(identifier),
+ } as unknown as IRender;
+ }
+}
+
+class MockDocSkeletonManagerService extends RxDisposable implements IRenderModule {
+ private _docViewModel!: DocumentViewModel;
+ private readonly _currentSkeleton$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);
+ readonly currentSkeleton$ = this._currentSkeleton$.asObservable();
+ private readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);
+ readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+ this._update();
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((documentModel) => {
+ if (documentModel?.getUnitId() === this._context.unitId) {
+ this._update();
+ }
+ });
+ }
+
+ private _update() {
+ const documentDataModel = this._context.unit;
+ const unitId = this._context.unitId;
+
+ if (documentDataModel.getBody() == null) {
+ return;
+ }
+
+ if (this._docViewModel && unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ this._docViewModel.reset(documentDataModel);
+ } else if (!this._docViewModel) {
+ this._docViewModel = new DocumentViewModel(documentDataModel);
+ }
+ }
+
+ getSkeleton(): DocumentSkeleton {
+ throw new Error('[MockDocSkeletonManagerService]: cannot access to doc skeleton in unit tests!');
+ }
+
+ getViewModel(): DocumentViewModel {
+ return this._docViewModel;
+ }
+}
diff --git a/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts b/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts
new file mode 100644
index 0000000000..61930e9ef7
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/__tests__/docs-hyper-link-ui.integration.spec.ts
@@ -0,0 +1,254 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand, IDisposable, IDocumentData, Injector } from '@univerjs/core';
+import {
+ CustomRangeType,
+ ICommandService,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { DocCanvasPopManagerService } from '@univerjs/docs-ui';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AddDocHyperLinkCommand } from '../commands/commands/add-link.command';
+import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
+import { UpdateDocHyperLinkCommand } from '../commands/commands/update-link.command';
+import { ClickDocHyperLinkOperation } from '../commands/operations/popup.operation';
+import { DocHyperLinkSelectionController } from '../controllers/doc-hyper-link-selection.controller';
+import { DocHyperLinkPopupService } from '../services/hyper-link-popup.service';
+import { createDocUiTestBed } from './create-doc-ui-test-bed';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function createDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ customRanges: [{
+ startIndex: 6,
+ endIndex: 10,
+ rangeId: 'link-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: {
+ url: 'https://before.invalid',
+ },
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function getBody(get: Injector['get']) {
+ return get(IUniverInstanceService)
+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)
+ ?.getBody();
+}
+
+function createPopupManagerStub() {
+ const disposables: IDisposable[] = [];
+
+ return {
+ disposables,
+ attachPopupToRange: vi.fn(() => {
+ const disposable = {
+ dispose: vi.fn(),
+ };
+
+ disposables.push(disposable);
+ return disposable;
+ }),
+ };
+}
+
+describe('docs-hyper-link-ui integration', () => {
+ let univer: ReturnType<typeof createDocUiTestBed>['univer'];
+ let get: Injector['get'];
+ let injector: Injector;
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createDocUiTestBed(createDocData());
+ univer = testBed.univer;
+ get = testBed.get;
+ injector = testBed.injector;
+ commandService = get(ICommandService);
+
+ commandService.registerCommand(AddDocHyperLinkCommand);
+ commandService.registerCommand(UpdateDocHyperLinkCommand);
+ commandService.registerCommand(DeleteDocHyperLinkCommand);
+ commandService.registerCommand(ClickDocHyperLinkOperation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ vi.restoreAllMocks();
+ });
+
+ it('adds a hyperlink through the real command pipeline', async () => {
+ const selectionManager = get(DocSelectionManagerService);
+
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 5,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ expect(await commandService.executeCommand(AddDocHyperLinkCommand.id, {
+ unitId: 'test-doc',
+ payload: 'https://added.invalid',
+ })).toBeTruthy();
+ await waitNextTick();
+
+ const addedLink = getBody(get)?.customRanges?.find((range) => range.properties?.url === 'https://added.invalid');
+ expect(addedLink).toBeDefined();
+ expect(addedLink?.rangeType).toBe(CustomRangeType.HYPERLINK);
+ });
+
+ it('updates hyperlink text and payload through the real command pipeline', async () => {
+ const selectionManager = get(DocSelectionManagerService);
+
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 6,
+ endOffset: 11,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ expect(await commandService.executeCommand(UpdateDocHyperLinkCommand.id, {
+ unitId: 'test-doc',
+ linkId: 'link-1',
+ payload: 'https://after.invalid',
+ label: 'planet',
+ segmentId: '',
+ })).toBeTruthy();
+ await waitNextTick();
+
+ expect(getBody(get)?.dataStream).toBe('Hello planet\r\n');
+ expect(getBody(get)?.customRanges?.find((range) => range.rangeId === 'link-1')?.properties).toEqual({
+ url: 'https://after.invalid',
+ });
+ });
+
+ it('deletes a hyperlink range while keeping the text content', async () => {
+ expect(getBody(get)?.dataStream).toBe('Hello world\r\n');
+
+ expect(await commandService.executeCommand(DeleteDocHyperLinkCommand.id, {
+ unitId: 'test-doc',
+ linkId: 'link-1',
+ })).toBeTruthy();
+ await waitNextTick();
+
+ expect(getBody(get)?.dataStream).toBe('Hello world\r\n');
+ expect(getBody(get)?.customRanges?.some((range) => range.rangeId === 'link-1')).toBe(false);
+ });
+
+ it('shows and hides the info popup when the executed selection enters and leaves a hyperlink', async () => {
+ const popupManagerStub = createPopupManagerStub();
+ injector.add([DocCanvasPopManagerService, { useValue: popupManagerStub as unknown as DocCanvasPopManagerService }]);
+ injector.add([DocHyperLinkPopupService]);
+ injector.add([DocHyperLinkSelectionController]);
+
+ const popupService = injector.get(DocHyperLinkPopupService);
+ injector.get(DocHyperLinkSelectionController);
+
+ expect(await commandService.executeCommand(SetTextSelectionsOperation.id, {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ segmentId: '',
+ isEditing: false,
+ style: null,
+ ranges: [{
+ startOffset: 7,
+ endOffset: 7,
+ collapsed: true,
+ segmentId: '',
+ }],
+ })).toBe(true);
+
+ expect(popupService.showing).toMatchObject({
+ unitId: 'test-doc',
+ linkId: 'link-1',
+ segmentId: '',
+ startIndex: 6,
+ endIndex: 10,
+ });
+ expect(popupManagerStub.attachPopupToRange).toHaveBeenCalledWith({
+ collapsed: false,
+ startOffset: 6,
+ endOffset: 11,
+ segmentId: '',
+ segmentPage: undefined,
+ }, expect.objectContaining({
+ componentKey: 'univer.doc.link-info-popup',
+ }), 'test-doc');
+
+ expect(await commandService.executeCommand(SetTextSelectionsOperation.id, {
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ segmentId: '',
+ isEditing: false,
+ style: null,
+ ranges: [{
+ startOffset: 0,
+ endOffset: 0,
+ collapsed: true,
+ segmentId: '',
+ }],
+ })).toBe(true);
+
+ expect(popupService.showing).toBeNull();
+ expect(popupManagerStub.disposables[0]?.dispose).toHaveBeenCalled();
+ });
+
+ it('opens the hyperlink URL when the click operation is executed', async () => {
+ const openSpy = vi.fn();
+ vi.stubGlobal('window', { open: openSpy });
+
+ expect(await commandService.executeCommand(ClickDocHyperLinkOperation.id, {
+ unitId: 'test-doc',
+ linkId: 'link-1',
+ segmentId: '',
+ })).toBe(true);
+
+ expect(openSpy).toHaveBeenCalledWith('https://before.invalid', '_blank', 'noopener noreferrer');
+ });
+});
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/__tests__/utils.spec.ts b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..46be5d6a9c
--- /dev/null
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/__tests__/utils.spec.ts
@@ -0,0 +1,27 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { isBlankInput } from '../utils';
+
+describe('DocHyperLinkEdit utils', () => {
+ it('treats whitespace-only input as blank', () => {
+ expect(isBlankInput('')).toBe(true);
+ expect(isBlankInput(' ')).toBe(true);
+ expect(isBlankInput('\n\t')).toBe(true);
+ expect(isBlankInput(' link ')).toBe(false);
+ });
+});
diff --git a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx
index 6948733301..47fa5b18dd 100644
--- a/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/index.tsx
@@ -23,6 +23,7 @@ import { useEffect, useState } from 'react';
import { AddDocHyperLinkCommand } from '../../commands/commands/add-link.command';
import { UpdateDocHyperLinkCommand } from '../../commands/commands/update-link.command';
import { DocHyperLinkPopupService } from '../../services/hyper-link-popup.service';
+import { isBlankInput } from './utils';
function hasProtocol(urlString: string) {
const pattern = /^[a-zA-Z]+:\/\//;
@@ -94,7 +95,7 @@ export const DocHyperLinkEdit = () => {
payload: linkFinal,
});
} else {
- if (!label) {
+ if (isBlankInput(label)) {
return;
}
@@ -125,7 +126,7 @@ export const DocHyperLinkEdit = () => {
? (
<FormLayout
label={localeService.t('docLink.edit.label')}
- error={showError && !label ? localeService.t('docLink.edit.labelError') : ''}
+ error={showError && isBlankInput(label) ? localeService.t('docLink.edit.labelError') : ''}
>
<Input
value={label}
@@ -162,7 +163,7 @@ export const DocHyperLinkEdit = () => {
</Button>
<Button
variant="primary"
- disabled={!link}
+ disabled={isBlankInput(link)}
onClick={handleConfirm}
>
{localeService.t('docLink.edit.confirm')}
diff --git a/packages/docs-quick-insert-ui/src/menu/const.ts b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/utils.ts
similarity index 87%
rename from packages/docs-quick-insert-ui/src/menu/const.ts
rename to packages/docs-hyper-link-ui/src/views/hyper-link-edit/utils.ts
index 16962a68a5..4c5a18028d 100644
--- a/packages/docs-quick-insert-ui/src/menu/const.ts
+++ b/packages/docs-hyper-link-ui/src/views/hyper-link-edit/utils.ts
@@ -14,4 +14,6 @@
* limitations under the License.
*/
-export const QuickInsertButtonComponentKey = 'doc.quick-insert.button';
+export function isBlankInput(value: string) {
+ return value.trim().length === 0;
+}
diff --git a/packages/docs-mention-ui/package.json b/packages/docs-mention-ui/package.json
index 6e8100f7b7..6c735145a3 100644
--- a/packages/docs-mention-ui/package.json
+++ b/packages/docs-mention-ui/package.json
@@ -72,6 +72,7 @@
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
"postcss": "^8.5.8",
"react": "18.3.1",
"rxjs": "^7.8.2",
diff --git a/packages/docs-mention-ui/src/__tests__/create-doc-ui-test-bed.ts b/packages/docs-mention-ui/src/__tests__/create-doc-ui-test-bed.ts
new file mode 100644
index 0000000000..d167617f03
--- /dev/null
+++ b/packages/docs-mention-ui/src/__tests__/create-doc-ui-test-bed.ts
@@ -0,0 +1,184 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+
+import type { Ctor, Dependency, DependencyIdentifier, DocumentDataModel, IDocumentData, Nullable } from '@univerjs/core';
+import type { DocumentSkeleton, IRender, IRenderContext, IRenderModule } from '@univerjs/engine-render';
+import {
+ BooleanNumber,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ ILogService,
+ Inject,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LogLevel,
+ Plugin,
+ RxDisposable,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService, DocStateEmitService } from '@univerjs/docs';
+import { DocIMEInputManagerService, DocSelectionRenderService, DocStateChangeManagerService } from '@univerjs/docs-ui';
+import { DocumentViewModel, IRenderManagerService } from '@univerjs/engine-render';
+import { BehaviorSubject, takeUntil } from 'rxjs';
+
+const DEFAULT_DOC_DATA: IDocumentData = {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 11,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ },
+ }],
+ paragraphs: [{ startIndex: 11 }],
+ sectionBreaks: [],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+};
+
+export function createDocUiTestBed(docData?: IDocumentData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ this._injector.get(IUndoRedoService);
+ if (!dependencies?.some((dependency) => Array.isArray(dependency) && dependency[0] === IRenderManagerService)) {
+ this._injector.add([IRenderManagerService, { useClass: MockRenderManagerService as unknown as Ctor<IRenderManagerService> }]);
+ }
+ this._injector.add([DocSelectionManagerService]);
+ this._injector.add([DocStateEmitService]);
+ this._injector.add([DocStateChangeManagerService]);
+ this._injector.add([DocIMEInputManagerService]);
+ this._injector.add([DocSelectionRenderService]);
+ dependencies?.forEach((dependency) => this._injector.add(dependency));
+ }
+
+ override onReady(): void {
+ this._injector.get(DocStateChangeManagerService);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, docData || DEFAULT_DOC_DATA);
+ const univerInstanceService = get(IUniverInstanceService);
+ const fakeDocSkeletonManager = new MockDocSkeletonManagerService({
+ unit: doc,
+ unitId: doc.getUnitId(),
+ type: UniverInstanceType.UNIVER_DOC,
+ engine: null as any,
+ scene: null as any,
+ mainComponent: null as any,
+ components: null as any,
+ isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => {},
+ deactivate: () => {},
+ }, univerInstanceService);
+
+ injector.add([DocSkeletonManagerService, { useValue: fakeDocSkeletonManager as unknown as DocSkeletonManagerService }]);
+ univerInstanceService.focusUnit(doc.getUnitId());
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ return {
+ univer,
+ injector,
+ get,
+ doc,
+ };
+}
+
+class MockRenderManagerService implements Pick<IRenderManagerService, 'getRenderById'> {
+ constructor(@Inject(Injector) private readonly _injector: Injector) {}
+
+ getRenderById(): Nullable<IRender> {
+ return {
+ with: <T>(identifier: DependencyIdentifier<T>) => this._injector.get(identifier),
+ } as unknown as IRender;
+ }
+}
+
+class MockDocSkeletonManagerService extends RxDisposable implements IRenderModule {
+ private _docViewModel!: DocumentViewModel;
+ private readonly _currentSkeleton$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);
+ readonly currentSkeleton$ = this._currentSkeleton$.asObservable();
+ private readonly _currentSkeletonBefore$ = new BehaviorSubject<Nullable<DocumentSkeleton>>(null);
+ readonly currentSkeletonBefore$ = this._currentSkeletonBefore$.asObservable();
+
+ constructor(
+ private readonly _context: IRenderContext<DocumentDataModel>,
+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService
+ ) {
+ super();
+ this._update();
+ this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)
+ .pipe(takeUntil(this.dispose$))
+ .subscribe((documentModel) => {
+ if (documentModel?.getUnitId() === this._context.unitId) {
+ this._update();
+ }
+ });
+ }
+
+ private _update() {
+ const documentDataModel = this._context.unit;
+ const unitId = this._context.unitId;
+
+ if (documentDataModel.getBody() == null) {
+ return;
+ }
+
+ if (this._docViewModel && unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ this._docViewModel.reset(documentDataModel);
+ } else if (!this._docViewModel) {
+ this._docViewModel = new DocumentViewModel(documentDataModel);
+ }
+ }
+
+ getSkeleton(): DocumentSkeleton {
+ throw new Error('[MockDocSkeletonManagerService]: cannot access to doc skeleton in unit tests!');
+ }
+
+ getViewModel(): DocumentViewModel {
+ return this._docViewModel;
+ }
+}
diff --git a/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts b/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts
new file mode 100644
index 0000000000..118075a316
--- /dev/null
+++ b/packages/docs-mention-ui/src/__tests__/docs-mention-ui.integration.spec.ts
@@ -0,0 +1,299 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDisposable, IDocumentData, Univer } from '@univerjs/core';
+import { CustomRangeType, Direction, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { DocCanvasPopManagerService, InsertCommand, MoveCursorOperation } from '@univerjs/docs-ui';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { AddDocMentionCommand, DeleteDocMentionCommand } from '../commands/commands/doc-mention.command';
+import {
+ CloseMentionEditPopupOperation,
+ ShowMentionEditPopupOperation,
+} from '../commands/operations/mention-popup.operation';
+import { DocMentionTriggerController } from '../controllers/doc-mention-trigger.controller';
+import { DocMentionPopupService } from '../services/doc-mention-popup.service';
+import { DocMentionService } from '../services/doc-mention.service';
+import { createDocUiTestBed } from './create-doc-ui-test-bed';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function createTriggerDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function createMentionDraftDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello @al\r\n',
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function createMentionDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello @Alice\r\n',
+ customRanges: [{
+ startIndex: 6,
+ endIndex: 11,
+ rangeId: 'mention-1',
+ rangeType: CustomRangeType.MENTION,
+ wholeEntity: true,
+ properties: {
+ id: 'mention-1',
+ label: 'Alice',
+ type: 'user',
+ },
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function createPopupManagerStub() {
+ const disposables: IDisposable[] = [];
+
+ return {
+ disposables,
+ attachPopupToRange: vi.fn(() => {
+ const disposable = {
+ dispose: vi.fn(),
+ };
+
+ disposables.push(disposable);
+ return disposable;
+ }),
+ };
+}
+
+function setupMentionTestBed(docData: IDocumentData) {
+ const testBed = createDocUiTestBed(docData);
+ const { univer, get, injector } = testBed;
+ const popupManagerStub = createPopupManagerStub();
+
+ injector.add([DocCanvasPopManagerService, { useValue: popupManagerStub as unknown as DocCanvasPopManagerService }]);
+ injector.add([DocMentionService]);
+ injector.add([DocMentionPopupService]);
+ injector.add([DocMentionTriggerController]);
+
+ const commandService = get(ICommandService);
+ commandService.registerCommand(InsertCommand);
+ commandService.registerCommand(MoveCursorOperation);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(ShowMentionEditPopupOperation);
+ commandService.registerCommand(CloseMentionEditPopupOperation);
+ commandService.registerCommand(AddDocMentionCommand);
+ commandService.registerCommand(DeleteDocMentionCommand);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ commandService.registerCommand({
+ id: 'doc.command.delete-left',
+ type: DeleteDocMentionCommand.type,
+ handler: () => true,
+ });
+
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+
+ const popupService = injector.get(DocMentionPopupService);
+ const mentionService = injector.get(DocMentionService);
+ injector.get(DocMentionTriggerController);
+
+ return {
+ univer,
+ get,
+ commandService,
+ selectionManager,
+ popupService,
+ mentionService,
+ popupManagerStub,
+ };
+}
+
+describe('docs-mention-ui integration', () => {
+ let univer: Univer | null = null;
+
+ afterEach(() => {
+ univer?.dispose();
+ univer = null;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ it('opens the mention edit popup after inserting @ through the command pipeline', async () => {
+ vi.useFakeTimers();
+ const testBed = setupMentionTestBed(createTriggerDocData());
+ univer = testBed.univer;
+
+ testBed.selectionManager.__TEST_ONLY_add([{
+ startOffset: 11,
+ endOffset: 11,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ expect(await testBed.commandService.executeCommand(InsertCommand.id, {
+ unitId: 'test-doc',
+ segmentId: '',
+ range: { startOffset: 11, endOffset: 11, collapsed: true },
+ body: {
+ dataStream: '@',
+ },
+ })).toBe(true);
+
+ await Promise.resolve();
+ await vi.runAllTimersAsync();
+
+ expect(testBed.mentionService.editing).toBeUndefined();
+ expect(testBed.popupService.editPopup?.unitId).toBe('test-doc');
+ expect(testBed.popupManagerStub.attachPopupToRange).toHaveBeenCalledWith({
+ startOffset: expect.any(Number),
+ endOffset: expect.any(Number),
+ collapsed: true,
+ }, expect.objectContaining({
+ componentKey: 'univer.popup.doc-mention-edit',
+ }), 'test-doc');
+ });
+
+ it('replaces the typed trigger text with a mention entity via AddDocMentionCommand', async () => {
+ const testBed = setupMentionTestBed(createMentionDraftDocData());
+ univer = testBed.univer;
+
+ testBed.selectionManager.__TEST_ONLY_add([{
+ startOffset: 6,
+ endOffset: 9,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ expect(await testBed.commandService.executeCommand(AddDocMentionCommand.id, {
+ unitId: 'test-doc',
+ startIndex: 6,
+ mention: {
+ id: 'mention-1',
+ label: 'Alice',
+ type: 'user',
+ metadata: {
+ source: 'directory',
+ },
+ },
+ })).toBeTruthy();
+ await waitNextTick();
+
+ const documentBody = testBed.get(IUniverInstanceService)
+ .getCurrentUniverDocInstance()
+ ?.getBody();
+
+ expect(documentBody?.dataStream).toBe('Hello @Alice\r\n');
+ expect(documentBody?.customRanges).toEqual([expect.objectContaining({
+ rangeId: 'mention-1',
+ rangeType: CustomRangeType.MENTION,
+ properties: expect.objectContaining({
+ id: 'mention-1',
+ label: 'Alice',
+ type: 'user',
+ source: 'directory',
+ }),
+ })]);
+ });
+
+ it('deletes a mention entity and closes the popup on cursor movement and delete-left events', async () => {
+ const testBed = setupMentionTestBed(createMentionDocData());
+ univer = testBed.univer;
+
+ expect(await testBed.commandService.executeCommand(ShowMentionEditPopupOperation.id, {
+ unitId: 'test-doc',
+ startIndex: 6,
+ })).toBe(true);
+ expect(testBed.popupService.editPopup).toMatchObject({ anchor: 6 });
+
+ expect(await testBed.commandService.executeCommand(MoveCursorOperation.id, { direction: Direction.RIGHT })).toBe(true);
+ expect(testBed.popupService.editPopup).toBeNull();
+
+ expect(await testBed.commandService.executeCommand(ShowMentionEditPopupOperation.id, {
+ unitId: 'test-doc',
+ startIndex: 6,
+ })).toBe(true);
+ testBed.selectionManager.__TEST_ONLY_add([{
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ expect(await testBed.commandService.executeCommand('doc.command.delete-left')).toBe(true);
+ expect(testBed.popupService.editPopup).toBeNull();
+
+ expect(await testBed.commandService.executeCommand(DeleteDocMentionCommand.id, {
+ unitId: 'test-doc',
+ mentionId: 'mention-1',
+ })).toBeTruthy();
+ await waitNextTick();
+
+ const docBody = testBed.get(IUniverInstanceService)
+ .getCurrentUniverDocInstance()
+ ?.getBody();
+ expect(docBody?.dataStream).toBe('Hello @Alice\r\n');
+ expect(docBody?.customRanges).toEqual([]);
+ });
+});
diff --git a/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts
index 1f235e2eff..311dce9d37 100644
--- a/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts
+++ b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-trigger.controller.spec.ts
@@ -20,7 +20,7 @@ import { DeleteCommand, DeleteLeftCommand, IMEInputCommand, InsertCommand, MoveC
import { KeyCode } from '@univerjs/ui';
import { describe, expect, it, vi } from 'vitest';
import { CloseQuickInsertPopupOperation, ShowQuickInsertPopupOperation } from '../../commands/operations/quick-insert-popup.operation';
-import { numberedListMenu, textMenu } from '../../menu/built-in-menus';
+import { numberedListMenu, textMenu } from '../../menu/menu';
import { DocQuickInsertTriggerController } from '../doc-quick-insert-trigger.controller';
function createCommandService() {
diff --git a/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts
index 5ba54788a2..c271bea581 100644
--- a/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts
+++ b/packages/docs-quick-insert-ui/src/controllers/__tests__/doc-quick-insert-ui.controller.spec.ts
@@ -15,7 +15,7 @@
*/
import { describe, expect, it, vi } from 'vitest';
-import { QuickInsertButton } from '../../menu';
+import { QuickInsertButton } from '../../views/QuickInsertButton';
import { DocQuickInsertUIController } from '../doc-quick-insert-ui.controller';
describe('DocQuickInsertUIController', () => {
diff --git a/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-trigger.controller.ts b/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-trigger.controller.ts
index 34c68e5fc2..bc4b9a0858 100644
--- a/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-trigger.controller.ts
+++ b/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-trigger.controller.ts
@@ -22,7 +22,7 @@ import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/d
import { DeleteCommand, DeleteLeftCommand, IMEInputCommand, InsertCommand, MoveCursorOperation } from '@univerjs/docs-ui';
import { IShortcutService, KeyCode } from '@univerjs/ui';
import { CloseQuickInsertPopupOperation, ShowQuickInsertPopupOperation } from '../commands/operations/quick-insert-popup.operation';
-import { builtInMenuCommandIds, textMenu } from '../menu/built-in-menus';
+import { builtInMenuCommandIds, textMenu } from '../menu/menu';
import { DocQuickInsertPopupService } from '../services/doc-quick-insert-popup.service';
export class DocQuickInsertTriggerController extends Disposable {
diff --git a/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-ui.controller.ts b/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-ui.controller.ts
index a3fa40a60b..7ab4e2a8d6 100644
--- a/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-ui.controller.ts
+++ b/packages/docs-quick-insert-ui/src/controllers/doc-quick-insert-ui.controller.ts
@@ -22,10 +22,10 @@ import { ComponentManager } 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 { QuickInsertButton } from '../menu';
-import { builtInMenus } from '../menu/built-in-menus';
+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';
diff --git a/packages/docs-quick-insert-ui/src/menu/doc-quick-insert-menu.controller.ts b/packages/docs-quick-insert-ui/src/menu/doc-quick-insert-menu.controller.ts
index 180b0a4ac0..c764dff4f3 100644
--- a/packages/docs-quick-insert-ui/src/menu/doc-quick-insert-menu.controller.ts
+++ b/packages/docs-quick-insert-ui/src/menu/doc-quick-insert-menu.controller.ts
@@ -20,7 +20,7 @@ import { Disposable, Inject } from '@univerjs/core';
import { DocCanvasPopManagerService, DocEventManagerService } from '@univerjs/docs-ui';
import { BehaviorSubject, combineLatest } from 'rxjs';
import { DocQuickInsertPopupService } from '../services/doc-quick-insert-popup.service';
-import { QuickInsertButtonComponentKey } from './const';
+import { QuickInsertButtonComponentKey } from '../views/QuickInsertButton';
export class DocQuickInsertMenuController extends Disposable implements IRenderModule {
private _popup$ = new BehaviorSubject<Nullable<{ startIndex: number; disposable: INeedCheckDisposable }>>(null);
diff --git a/packages/docs-quick-insert-ui/src/menu/built-in-menus.ts b/packages/docs-quick-insert-ui/src/menu/menu.ts
similarity index 94%
rename from packages/docs-quick-insert-ui/src/menu/built-in-menus.ts
rename to packages/docs-quick-insert-ui/src/menu/menu.ts
index 6be55e5794..534c500b54 100644
--- a/packages/docs-quick-insert-ui/src/menu/built-in-menus.ts
+++ b/packages/docs-quick-insert-ui/src/menu/menu.ts
@@ -16,7 +16,12 @@
import type { DocPopupMenu, IDocPopupMenuItem } from '../services/doc-quick-insert-popup.service';
import { InsertDocImageCommand } from '@univerjs/docs-drawing-ui';
-import { BulletListCommand, DocCreateTableOperation, HorizontalLineCommand, OrderListCommand } from '@univerjs/docs-ui';
+import {
+ BulletListCommand,
+ DocCreateTableOperation,
+ HorizontalLineCommand,
+ OrderListCommand,
+} from '@univerjs/docs-ui';
export enum QuickInsertMenuGroup {
Basic = 'quick.insert.group.basic',
diff --git a/packages/docs-quick-insert-ui/src/menu/index.tsx b/packages/docs-quick-insert-ui/src/views/QuickInsertButton.tsx
similarity index 92%
rename from packages/docs-quick-insert-ui/src/menu/index.tsx
rename to packages/docs-quick-insert-ui/src/views/QuickInsertButton.tsx
index 1e483e69d9..69cd4c4c3b 100644
--- a/packages/docs-quick-insert-ui/src/menu/index.tsx
+++ b/packages/docs-quick-insert-ui/src/views/QuickInsertButton.tsx
@@ -15,6 +15,7 @@
*/
import type { DocumentDataModel } from '@univerjs/core';
+import type { MouseEventHandler } from 'react';
import type { IDocPopup } from '../services/doc-quick-insert-popup.service';
import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { borderClassName, clsx } from '@univerjs/design';
@@ -24,15 +25,14 @@ import { IncreaseIcon } from '@univerjs/icons';
import { ILayoutService, useDependency, useEvent, useObservable } from '@univerjs/ui';
import { useMemo } from 'react';
import { combineLatest, map } from 'rxjs';
+import { DocQuickInsertMenuController } from '../menu/doc-quick-insert-menu.controller';
import { DocQuickInsertPopupService } from '../services/doc-quick-insert-popup.service';
-import { QuickInsertButtonComponentKey } from './const';
-import { DocQuickInsertMenuController } from './doc-quick-insert-menu.controller';
-interface IQuickInsertButtonProps {
- className?: string;
-}
+export const QuickInsertButtonComponentKey = 'doc.quick-insert.button';
-export const QuickInsertButton = ({ className = '' }: IQuickInsertButtonProps) => {
+export const QuickInsertButton = ({ className = '' }: {
+ className?: string;
+}) => {
const docQuickInsertPopupService = useDependency(DocQuickInsertPopupService);
const univerInstanceService = useDependency(IUniverInstanceService);
const renderManagerService = useDependency(IRenderManagerService);
@@ -43,7 +43,7 @@ export const QuickInsertButton = ({ className = '' }: IQuickInsertButtonProps) =
const docSelectionManagerService = useDependency(DocSelectionManagerService);
const editPopup = useObservable(docQuickInsertPopupService.editPopup$);
- const onClick: React.MouseEventHandler<HTMLDivElement> = useEvent((event) => {
+ const onClick: MouseEventHandler<HTMLDivElement> = useEvent(() => {
const p = docQuickInsertMenuController?.popup;
if (!p) {
return;
diff --git a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
index ed649c3894..e8e323c624 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -165,6 +165,7 @@ export function createCommandTestBed(docData?: IDocumentData, dependencies?: Dep
univer,
get,
doc,
+ injector,
};
}
diff --git a/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts b/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts
new file mode 100644
index 0000000000..c0983c15c0
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts
@@ -0,0 +1,251 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable max-lines-per-function */
+
+import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import {
+ BooleanNumber,
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ RANGE_TYPE,
+ Tools,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IActiveDirtyManagerService, RegisterOtherFormulaService } from '@univerjs/engine-formula';
+import {
+ BorderStyleManagerService,
+ RangeProtectionRuleModel,
+ SetRangeValuesCommand,
+ SetRangeValuesMutation,
+ SheetInterceptorService,
+ SheetLazyExecuteScheduleService,
+ SheetSkeletonService,
+ SheetsSelectionsService,
+ WorkbookPermissionService,
+ WorksheetPermissionService,
+ WorksheetProtectionPointModel,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
+import {
+ AddConditionalRuleMutation,
+ ClearRangeCfCommand,
+ ClearWorksheetCfCommand,
+ ConditionalFormattingFormulaService,
+ ConditionalFormattingRuleModel,
+ ConditionalFormattingViewModel,
+ DeleteConditionalRuleMutation,
+ MoveConditionalRuleMutation,
+ SetConditionalRuleMutation,
+} from '@univerjs/sheets-conditional-formatting';
+import { ISheetClipboardService } from '@univerjs/sheets-ui';
+import { ComponentManager, ISidebarService } from '@univerjs/ui';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { vi } from 'vitest';
+
+const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 'A1',
+ },
+ 1: {
+ v: 'A2',
+ },
+ },
+ },
+ columnData: {
+ 1: {
+ hd: BooleanNumber.FALSE,
+ },
+ },
+ rowData: {
+ 1: {
+ hd: BooleanNumber.FALSE,
+ },
+ },
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+};
+
+function createLocalSheetsTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ const injector = this._injector;
+
+ injector.add([WorksheetPermissionService]);
+ injector.add([WorksheetProtectionPointModel]);
+ injector.add([RangeProtectionRuleModel]);
+ injector.add([WorkbookPermissionService]);
+ injector.add([WorksheetProtectionRuleModel]);
+ injector.add([SheetsSelectionsService]);
+ injector.add([BorderStyleManagerService]);
+ injector.add([SheetInterceptorService]);
+ injector.add([SheetSkeletonService]);
+ injector.add([SheetLazyExecuteScheduleService]);
+
+ dependencies?.forEach((dependency) => injector.add(dependency));
+
+ injector.get(SheetInterceptorService);
+ injector.get(WorkbookPermissionService);
+ injector.get(WorksheetPermissionService);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const sheet = univer.createUnit<IWorkbookData, Workbook>(
+ UniverInstanceType.UNIVER_SHEET,
+ Tools.deepClone(workbookData || TEST_WORKBOOK_DATA_DEMO)
+ );
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit('test');
+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);
+ injector.get(LocaleService).load({
+ [LocaleType.EN_US]: {},
+ });
+ return {
+ univer,
+ injector,
+ get: injector.get.bind(injector),
+ sheet,
+ };
+}
+
+export function createCfUiTestBed() {
+ const testBed = createLocalSheetsTestBed();
+ const { univer, get, injector } = testBed;
+ const commandService = get(ICommandService);
+ const selectionsService = get(SheetsSelectionsService);
+
+ const formulaResult$ = new Subject<Record<string, Record<string, unknown[]>>>();
+ const componentManager = {
+ register: vi.fn((): IDisposable => ({
+ dispose: vi.fn(),
+ })),
+ };
+ const sidebarOptions$ = new BehaviorSubject({ id: '', visible: false } as any);
+ const sidebarService = {
+ open: vi.fn((): IDisposable => ({
+ dispose: vi.fn(),
+ })),
+ sidebarOptions$,
+ };
+ let clipboardHook: {
+ onBeforeCopy: (unitId: string, subUnitId: string, range: ISelectionWithStyle['range']) => void;
+ onPasteCells: (...args: any[]) => { redos: Array<{ id: string; params: unknown }>; undos: Array<{ id: string; params: unknown }> };
+ } | undefined;
+ const sheetClipboardService = {
+ addClipboardHook: vi.fn((hook) => {
+ clipboardHook = hook;
+ return {
+ dispose: vi.fn(),
+ };
+ }),
+ };
+
+ injector.add([RegisterOtherFormulaService, {
+ useValue: {
+ formulaResult$,
+ registerFormulaWithRange: vi.fn(() => 'formula-1'),
+ deleteFormula: vi.fn(),
+ getFormulaValueSync: vi.fn(() => null),
+ } as unknown as RegisterOtherFormulaService,
+ }]);
+ injector.add([IActiveDirtyManagerService, {
+ useValue: {
+ register: vi.fn(),
+ } as unknown as IActiveDirtyManagerService,
+ }]);
+ injector.add([ConditionalFormattingRuleModel]);
+ injector.add([ConditionalFormattingFormulaService]);
+ injector.add([ConditionalFormattingViewModel]);
+ injector.add([ComponentManager, { useValue: componentManager as unknown as ComponentManager }]);
+ injector.add([ISidebarService, { useValue: sidebarService as unknown as ISidebarService }]);
+ injector.add([ISheetClipboardService, { useValue: sheetClipboardService as unknown as ISheetClipboardService }]);
+
+ [
+ AddConditionalRuleMutation,
+ DeleteConditionalRuleMutation,
+ SetConditionalRuleMutation,
+ MoveConditionalRuleMutation,
+ ClearRangeCfCommand,
+ ClearWorksheetCfCommand,
+ SetRangeValuesCommand,
+ SetRangeValuesMutation,
+ ].forEach((command) => commandService.registerCommand(command));
+
+ const setSelection = (range: ISelectionWithStyle['range']) => {
+ selectionsService.addSelections([{
+ range: {
+ ...range,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: null,
+ style: null,
+ }]);
+ };
+
+ return {
+ univer,
+ get,
+ injector,
+ commandService,
+ selectionsService,
+ ruleModel: injector.get(ConditionalFormattingRuleModel),
+ viewModel: injector.get(ConditionalFormattingViewModel),
+ componentManager,
+ sidebarService,
+ sidebarOptions$,
+ sheetClipboardService,
+ getClipboardHook: () => clipboardHook,
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ setSelection,
+ };
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts b/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts
index 0144262db2..f3d3e8cd96 100644
--- a/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts
+++ b/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts
@@ -14,37 +14,13 @@
* limitations under the License.
*/
-import type { IAccessor, IRange } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService } from '@univerjs/core';
-import { getSheetCommandTarget } from '@univerjs/sheets';
-import {
- AddConditionalRuleMutation,
- CFNumberOperator,
- CFRuleType,
- CFSubRuleType,
- ConditionalFormattingRuleModel,
-} from '@univerjs/sheets-conditional-formatting';
-import { describe, expect, it, vi } from 'vitest';
-import { AddAverageCfCommand } from '../add-average-cf.command';
+import type { IRange } from '@univerjs/core';
+import { CFNumberOperator, CFRuleType, CFSubRuleType } from '@univerjs/sheets-conditional-formatting';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createCfUiTestBed } from '../../../__tests__/create-cf-ui-test-bed';
import { AddColorScaleConditionalRuleCommand } from '../add-color-scale-cf.command';
import { AddDataBarConditionalRuleCommand } from '../add-data-bar-cf.command';
-import { AddDuplicateValuesCfCommand } from '../add-duplicate-values-cf.command';
import { AddNumberCfCommand } from '../add-number-cf.command';
-import { AddRankCfCommand } from '../add-rank-cf.command';
-import { AddTextCfCommand } from '../add-text-cf.command';
-import { AddTimePeriodCfCommand } from '../add-time-period-cf.command';
-import { AddUniqueValuesCfCommand } from '../add-unique-values-cf.command';
-
-vi.mock('@univerjs/sheets', async (importActual) => {
- const actual = await importActual<typeof import('@univerjs/sheets')>();
-
- return {
- ...actual,
- getSheetCommandTarget: vi.fn(),
- };
-});
-
-const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
const range: IRange = {
startRow: 1,
@@ -53,269 +29,93 @@ const range: IRange = {
endColumn: 4,
};
-function createAccessor() {
- const commandService = {
- executeCommand: vi.fn(() => true),
- };
- const conditionalFormattingRuleModel = {
- createCfId: vi.fn(() => 'cf-1'),
- };
- const univerInstanceService = {};
-
- const accessor = {
- get(token: unknown) {
- if (token === ICommandService) {
- return commandService;
- }
-
- if (token === ConditionalFormattingRuleModel) {
- return conditionalFormattingRuleModel;
- }
-
- if (token === IUniverInstanceService) {
- return univerInstanceService;
- }
-
- throw new Error(`Unknown dependency: ${String(token)}`);
- },
- } as IAccessor;
-
- return {
- accessor,
- commandService,
- conditionalFormattingRuleModel,
- };
-}
-
describe('conditional formatting add commands', () => {
- it('creates highlight, scale, bar, and ranking rules from user input', () => {
- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
-
- const commandCases = [
- {
- command: AddAverageCfCommand,
- params: {
- ranges: [range],
- operator: 'aboveAverage',
- style: { bg: { rgb: '#ffeecc' } },
- stopIfTrue: true,
- },
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.average,
- operator: 'aboveAverage',
- style: { bg: { rgb: '#ffeecc' } },
- },
- },
- {
- command: AddColorScaleConditionalRuleCommand,
- params: {
- ranges: [range],
- config: [{ index: 0, color: '#f00' }, { index: 1, color: '#0f0' }],
- },
- rule: {
- type: CFRuleType.colorScale,
- config: [{ index: 0, color: '#f00' }, { index: 1, color: '#0f0' }],
- },
- },
- {
- command: AddDataBarConditionalRuleCommand,
- params: {
- ranges: [range],
- min: { type: 'min' },
- max: { type: 'max' },
- nativeColor: '#ddd',
- positiveColor: '#0f0',
- isGradient: true,
- isShowValue: false,
- },
- rule: {
- type: CFRuleType.dataBar,
- isShowValue: false,
- config: {
- min: { type: 'min' },
- max: { type: 'max' },
- nativeColor: '#ddd',
- positiveColor: '#0f0',
- isGradient: true,
- },
- },
- },
- {
- command: AddDuplicateValuesCfCommand,
- params: {
- ranges: [range],
- style: { cl: { rgb: '#f00' } },
- },
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.duplicateValues,
- style: { cl: { rgb: '#f00' } },
- },
- },
- {
- command: AddRankCfCommand,
- params: {
- ranges: [range],
- style: { cl: { rgb: '#00f' } },
- isPercent: true,
- isBottom: false,
- value: 10,
- },
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.rank,
- style: { cl: { rgb: '#00f' } },
- isPercent: true,
- isBottom: false,
- value: 10,
- },
- },
- {
- command: AddTextCfCommand,
- params: {
- ranges: [range],
- operator: 'containsText',
- style: { bg: { rgb: '#ff0' } },
- value: 'error',
- },
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: 'containsText',
- style: { bg: { rgb: '#ff0' } },
- value: 'error',
- },
- },
- {
- command: AddTimePeriodCfCommand,
- params: {
- ranges: [range],
- operator: 'yesterday',
- style: { bg: { rgb: '#ccc' } },
- },
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.timePeriod,
- operator: 'yesterday',
- style: { bg: { rgb: '#ccc' } },
- },
- },
- {
- command: AddUniqueValuesCfCommand,
- params: {
- ranges: [range],
- style: { cl: { rgb: '#090' } },
- stopIfTrue: true,
- },
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.uniqueValues,
- style: { cl: { rgb: '#090' } },
- },
- },
- ];
-
- commandCases.forEach(({ command, params, rule }) => {
- const { accessor, commandService, conditionalFormattingRuleModel } = createAccessor();
-
- expect(command.handler(accessor, params as never)).toBe(true);
- expect(conditionalFormattingRuleModel.createCfId).toHaveBeenCalledWith('unit-1', 'sheet-1');
- expect(commandService.executeCommand).toHaveBeenCalledWith(AddConditionalRuleMutation.id, {
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
- rule: {
- ranges: [range],
- cfId: 'cf-1',
- stopIfTrue: Boolean((params as { stopIfTrue?: boolean }).stopIfTrue),
- rule,
- },
- });
- });
+ afterEach(() => {
+ // each test disposes its own univer instance
});
- it('supports both between and scalar number rules and rejects invalid inputs', () => {
- mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
+ it('adds number highlight rules into the real rule model', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.commandService.registerCommand(AddNumberCfCommand);
- const betweenAccessor = createAccessor();
- expect(AddNumberCfCommand.handler(betweenAccessor.accessor, {
+ expect(await testBed.commandService.executeCommand(AddNumberCfCommand.id, {
ranges: [range],
operator: CFNumberOperator.between,
style: { bg: { rgb: '#aaf' } },
value: [10, 20],
stopIfTrue: true,
- } as never)).toBe(true);
- expect(betweenAccessor.commandService.executeCommand).toHaveBeenCalledWith(AddConditionalRuleMutation.id, {
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
- rule: {
- ranges: [range],
- cfId: 'cf-1',
- stopIfTrue: true,
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.between,
- style: { bg: { rgb: '#aaf' } },
- value: [10, 20],
- },
- },
- });
+ })).toBe(true);
- const scalarAccessor = createAccessor();
- expect(AddNumberCfCommand.handler(scalarAccessor.accessor, {
+ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);
+ expect(rules).toHaveLength(1);
+ expect(rules?.[0]).toMatchObject({
ranges: [range],
- operator: CFNumberOperator.greaterThan,
- style: { cl: { rgb: '#222' } },
- value: 99,
- } as never)).toBe(true);
- expect(scalarAccessor.commandService.executeCommand).toHaveBeenCalledWith(AddConditionalRuleMutation.id, {
- unitId: 'unit-1',
- subUnitId: 'sheet-1',
+ stopIfTrue: true,
rule: {
- ranges: [range],
- cfId: 'cf-1',
- stopIfTrue: false,
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.greaterThan,
- style: { cl: { rgb: '#222' } },
- value: 99,
- },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.between,
+ style: { bg: { rgb: '#aaf' } },
+ value: [10, 20],
},
});
- const invalidBetweenAccessor = createAccessor();
- expect(AddNumberCfCommand.handler(invalidBetweenAccessor.accessor, {
+ testBed.univer.dispose();
+ });
+
+ it('adds color scale rules into the real rule model', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.commandService.registerCommand(AddColorScaleConditionalRuleCommand);
+
+ expect(await testBed.commandService.executeCommand(AddColorScaleConditionalRuleCommand.id, {
ranges: [range],
- operator: CFNumberOperator.between,
- style: {},
- value: [10],
- } as never)).toBe(false);
- expect(invalidBetweenAccessor.commandService.executeCommand).not.toHaveBeenCalled();
+ config: [{ index: 0, color: '#f00' }, { index: 1, color: '#0f0' }],
+ })).toBe(true);
- const invalidScalarAccessor = createAccessor();
- expect(AddNumberCfCommand.handler(invalidScalarAccessor.accessor, {
+ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);
+ expect(rules).toHaveLength(1);
+ expect(rules?.[0]).toMatchObject({
ranges: [range],
- operator: CFNumberOperator.lessThan,
- style: {},
- value: [1, 2],
- } as never)).toBe(false);
- expect(invalidScalarAccessor.commandService.executeCommand).not.toHaveBeenCalled();
- });
+ rule: {
+ type: CFRuleType.colorScale,
+ config: [{ index: 0, color: '#f00' }, { index: 1, color: '#0f0' }],
+ },
+ });
- it('returns false when params are missing or no active sheet target exists', () => {
- const { accessor, commandService } = createAccessor();
+ testBed.univer.dispose();
+ });
- expect(AddAverageCfCommand.handler(accessor, null as never)).toBe(false);
- expect(commandService.executeCommand).not.toHaveBeenCalled();
+ it('adds data bar rules into the real rule model', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.commandService.registerCommand(AddDataBarConditionalRuleCommand);
- mockedGetSheetCommandTarget.mockReturnValue(null as never);
- expect(AddUniqueValuesCfCommand.handler(accessor, {
+ expect(await testBed.commandService.executeCommand(AddDataBarConditionalRuleCommand.id, {
+ ranges: [range],
+ min: { type: 'min' },
+ max: { type: 'max' },
+ nativeColor: '#ddd',
+ positiveColor: '#0f0',
+ isGradient: true,
+ isShowValue: false,
+ })).toBe(true);
+
+ const rules = testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId);
+ expect(rules).toHaveLength(1);
+ expect(rules?.[0]).toMatchObject({
ranges: [range],
- style: {},
- } as never)).toBe(false);
- expect(commandService.executeCommand).not.toHaveBeenCalled();
+ rule: {
+ type: CFRuleType.dataBar,
+ isShowValue: false,
+ config: {
+ min: { type: 'min' },
+ max: { type: 'max' },
+ nativeColor: '#ddd',
+ positiveColor: '#0f0',
+ isGradient: true,
+ },
+ },
+ });
+
+ testBed.univer.dispose();
});
});
diff --git a/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.ts b/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.ts
index dea2c838ef..cde7b36fb2 100644
--- a/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.ts
+++ b/packages/sheets-conditional-formatting-ui/src/commands/operations/__tests__/open-conditional-formatting-panel.spec.ts
@@ -14,89 +14,104 @@
* limitations under the License.
*/
-import type { IAccessor } from '@univerjs/core';
-import { ICommandService } from '@univerjs/core';
-import { SheetsSelectionsService } from '@univerjs/sheets';
-import { CFRuleType, CFSubRuleType, ClearRangeCfCommand, ClearWorksheetCfCommand } from '@univerjs/sheets-conditional-formatting';
-import { describe, expect, it, vi } from 'vitest';
+import type { IRange } from '@univerjs/core';
+import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
+import { AddConditionalRuleMutation, CFRuleType, CFSubRuleType, CFTextOperator } from '@univerjs/sheets-conditional-formatting';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createCfUiTestBed } from '../../../__tests__/create-cf-ui-test-bed';
import { ConditionalFormattingPanelController } from '../../../controllers/cf.panel.controller';
import { CF_MENU_OPERATION, OpenConditionalFormattingOperator } from '../open-conditional-formatting-panel';
-describe('OpenConditionalFormattingOperator', () => {
- const range = {
- startRow: 1,
- endRow: 2,
- startColumn: 3,
- endColumn: 4,
- };
-
- function createAccessor() {
- const controller = {
- openPanel: vi.fn(),
- };
- const selectionManagerService = {
- getCurrentSelections: vi.fn(() => [{ range }]),
- };
- const commandService = {
- executeCommand: vi.fn(),
- };
-
- const get: IAccessor['get'] = ((token: unknown) => {
- if (token === ConditionalFormattingPanelController) {
- return controller;
- }
-
- if (token === SheetsSelectionsService) {
- return selectionManagerService;
- }
-
- if (token === ICommandService) {
- return commandService;
- }
-
- throw new Error('Unknown dependency');
- }) as IAccessor['get'];
- const has: IAccessor['has'] = (() => false) as IAccessor['has'];
+const range: IRange = {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 3,
+ endColumn: 4,
+};
- const accessor: IAccessor = {
- get,
- has,
- };
-
- return { accessor, controller, commandService };
- }
-
- it('opens the panel with a formula rule seeded from the current selection', () => {
- const { accessor, controller } = createAccessor();
-
- expect(OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.formula })).toBe(true);
- expect(controller.openPanel).toHaveBeenCalledWith({
- ranges: [range],
- rule: {
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.formula,
- value: '=',
- },
- });
+describe('OpenConditionalFormattingOperator', () => {
+ afterEach(() => {
+ // each test disposes its own univer instance
});
- it('opens the panel without payload for the manage-rules action', () => {
- const { accessor, controller } = createAccessor();
-
- OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.viewRule });
-
- expect(controller.openPanel).toHaveBeenCalledWith();
+ it('opens the real sidebar panel with a rule seeded from the current selection', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.injector.add([ConditionalFormattingPanelController]);
+ testBed.injector.get(ConditionalFormattingPanelController);
+ testBed.commandService.registerCommand(OpenConditionalFormattingOperator);
+ testBed.setSelection(range);
+
+ expect(await testBed.commandService.executeCommand(OpenConditionalFormattingOperator.id, {
+ value: CF_MENU_OPERATION.formula,
+ })).toBe(true);
+
+ expect(testBed.sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'sheet.conditional.formatting.panel',
+ children: expect.objectContaining({
+ rule: {
+ ranges: [expect.objectContaining(range)],
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.formula,
+ value: '=',
+ },
+ },
+ }),
+ }));
+
+ testBed.univer.dispose();
});
- it('dispatches clear commands for range and worksheet actions', () => {
- const { accessor, commandService } = createAccessor();
-
- OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.clearRangeRules });
- OpenConditionalFormattingOperator.handler(accessor, { value: CF_MENU_OPERATION.clearWorkSheetRules });
+ it('clears range rules and worksheet rules through the real operator flow', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.injector.add([ConditionalFormattingPanelController]);
+ testBed.injector.get(ConditionalFormattingPanelController);
+ testBed.commandService.registerCommand(OpenConditionalFormattingOperator);
+ testBed.setSelection(range);
+
+ const addRule = async (cfId: string, ranges = [range]) => {
+ const rule: IConditionFormattingRule = {
+ cfId,
+ ranges,
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notContainsText,
+ value: 'A1',
+ style: { bg: { rgb: '#ff0' } },
+ },
+ };
+
+ await testBed.commandService.executeCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule,
+ });
+ };
- expect(commandService.executeCommand).toHaveBeenNthCalledWith(1, ClearRangeCfCommand.id, {
- ranges: [range],
- });
- expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, ClearWorksheetCfCommand.id);
+ await addRule('cf-range');
+ expect(testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId)).toHaveLength(1);
+
+ expect(await testBed.commandService.executeCommand(OpenConditionalFormattingOperator.id, {
+ value: CF_MENU_OPERATION.clearRangeRules,
+ })).toBe(true);
+ expect(testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId)).toEqual([]);
+
+ await addRule('cf-sheet-1');
+ await addRule('cf-sheet-2', [{
+ startRow: 5,
+ endRow: 5,
+ startColumn: 5,
+ endColumn: 5,
+ }]);
+ expect(testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId)).toHaveLength(2);
+
+ expect(await testBed.commandService.executeCommand(OpenConditionalFormattingOperator.id, {
+ value: CF_MENU_OPERATION.clearWorkSheetRules,
+ })).toBe(true);
+ expect(testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId)).toEqual([]);
+
+ testBed.univer.dispose();
});
});
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.clear.controller.spec.ts b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.clear.controller.spec.ts
new file mode 100644
index 0000000000..934f750933
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.clear.controller.spec.ts
@@ -0,0 +1,117 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
+import { ClearSelectionAllCommand, ClearSelectionFormatCommand } from '@univerjs/sheets';
+import { AddConditionalRuleMutation, CFRuleType, CFSubRuleType, CFTextOperator } from '@univerjs/sheets-conditional-formatting';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createCfUiTestBed } from '../../__tests__/create-cf-ui-test-bed';
+import { ConditionalFormattingClearController } from '../cf.clear.controller';
+
+describe('ConditionalFormattingClearController', () => {
+ afterEach(() => {
+ // each test disposes its own univer instance
+ });
+
+ it('clips intersecting conditional formatting ranges when clearing selection format', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.injector.add([ConditionalFormattingClearController]);
+ testBed.injector.get(ConditionalFormattingClearController);
+ testBed.commandService.registerCommand(ClearSelectionFormatCommand);
+
+ const rule: IConditionFormattingRule = {
+ cfId: 'cf-1',
+ ranges: [{
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 1,
+ }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notContainsText,
+ value: 'A',
+ style: { bg: { rgb: '#ff0' } },
+ },
+ };
+
+ await testBed.commandService.executeCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule,
+ });
+ testBed.setSelection({
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ });
+
+ expect(await testBed.commandService.executeCommand(ClearSelectionFormatCommand.id)).toBe(true);
+ expect(testBed.ruleModel.getRule(testBed.unitId, testBed.subUnitId, 'cf-1')?.ranges).toEqual([{
+ startRow: 0,
+ endRow: 0,
+ startColumn: 1,
+ endColumn: 1,
+ }]);
+
+ testBed.univer.dispose();
+ });
+
+ it('removes fully covered conditional formatting rules when clearing selection all', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.injector.add([ConditionalFormattingClearController]);
+ testBed.injector.get(ConditionalFormattingClearController);
+ testBed.commandService.registerCommand(ClearSelectionAllCommand);
+
+ const rule: IConditionFormattingRule = {
+ cfId: 'cf-2',
+ ranges: [{
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notContainsText,
+ value: 'A',
+ style: { bg: { rgb: '#ff0' } },
+ },
+ };
+
+ await testBed.commandService.executeCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule,
+ });
+ testBed.setSelection({
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ });
+
+ expect(await testBed.commandService.executeCommand(ClearSelectionAllCommand.id)).toBe(true);
+ expect(testBed.ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId)).toEqual([]);
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.copy-paste.controller.spec.ts b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.copy-paste.controller.spec.ts
new file mode 100644
index 0000000000..f3c2088012
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/__tests__/cf.copy-paste.controller.spec.ts
@@ -0,0 +1,148 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
+import {
+ AddConditionalRuleMutation,
+ CFRuleType,
+ CFSubRuleType,
+ CFTextOperator,
+ DeleteConditionalRuleMutation,
+ SetConditionalRuleMutation,
+} from '@univerjs/sheets-conditional-formatting';
+import { COPY_TYPE, PREDEFINED_HOOK_NAME_PASTE } from '@univerjs/sheets-ui';
+import { afterEach, describe, expect, it } from 'vitest';
+import { createCfUiTestBed } from '../../__tests__/create-cf-ui-test-bed';
+import { ConditionalFormattingCopyPasteController } from '../cf.copy-paste.controller';
+
+describe('ConditionalFormattingCopyPasteController', () => {
+ afterEach(() => {
+ // each test disposes its own univer instance
+ });
+
+ it('creates copy-paste mutations from the real rule model and view model', async () => {
+ const testBed = createCfUiTestBed();
+ testBed.injector.add([ConditionalFormattingCopyPasteController]);
+ testBed.injector.get(ConditionalFormattingCopyPasteController);
+
+ const sourceRule: IConditionFormattingRule = {
+ cfId: 'cf-source',
+ ranges: [{
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notContainsText,
+ value: 'A1',
+ style: { bg: { rgb: '#0f0' } },
+ },
+ };
+ const targetRule: IConditionFormattingRule = {
+ cfId: 'cf-target',
+ ranges: [{
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notContainsText,
+ value: 'B2',
+ style: { bg: { rgb: '#f00' } },
+ },
+ };
+
+ await testBed.commandService.executeCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule: sourceRule,
+ });
+ await testBed.commandService.executeCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule: targetRule,
+ });
+
+ const hook = testBed.getClipboardHook()!;
+ expect(hook).toBeDefined();
+
+ hook.onBeforeCopy(testBed.unitId, testBed.subUnitId, {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ });
+
+ const result = hook.onPasteCells(
+ {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ range: { rows: [0], cols: [0] },
+ },
+ {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ range: { rows: [1], cols: [1] },
+ },
+ null,
+ {
+ copyType: COPY_TYPE.COPY,
+ pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE,
+ }
+ ) as {
+ redos: Array<{ id: string; params: unknown }>;
+ undos: Array<{ id: string; params: unknown }>;
+ };
+
+ const redoIds = result.redos.map((item: { id: string }) => item.id);
+ expect(redoIds).toContain(DeleteConditionalRuleMutation.id);
+ expect(redoIds.some((id: string) => id === AddConditionalRuleMutation.id || id === SetConditionalRuleMutation.id)).toBe(true);
+ expect(result.undos.length).toBeGreaterThan(0);
+
+ const copiedRuleRedo = result.redos.find((item) => {
+ const params = item.params as {
+ rule?: {
+ cfId?: string;
+ ranges?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;
+ };
+ };
+
+ return (item.id === AddConditionalRuleMutation.id || item.id === SetConditionalRuleMutation.id) &&
+ params.rule?.cfId === 'cf-source';
+ });
+ const copiedRuleParams = copiedRuleRedo?.params as {
+ rule?: {
+ ranges?: Array<{ startRow: number; endRow: number; startColumn: number; endColumn: number }>;
+ };
+ } | undefined;
+ expect(copiedRuleParams?.rule?.ranges?.some((range: { startRow: number; endRow: number; startColumn: number; endColumn: number }) =>
+ range.startRow <= 1 &&
+ range.endRow >= 1 &&
+ range.startColumn <= 1 &&
+ range.endColumn >= 1
+ )).toBe(true);
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-drawing/package.json b/packages/sheets-drawing/package.json
index 88508a9df4..60e5469c4c 100644
--- a/packages/sheets-drawing/package.json
+++ b/packages/sheets-drawing/package.json
@@ -71,11 +71,11 @@
"dependencies": {
"@univerjs/core": "workspace:*",
"@univerjs/drawing": "workspace:*",
- "@univerjs/engine-render": "workspace:*",
"@univerjs/sheets": "workspace:*"
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
"typescript": "^6.0.2",
"vitest": "^4.1.1"
}
diff --git a/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.ts b/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.ts
new file mode 100644
index 0000000000..b70d7ed93f
--- /dev/null
+++ b/packages/sheets-drawing/src/__tests__/create-sheets-drawing-test-bed.ts
@@ -0,0 +1,152 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
+import {
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ Tools,
+ touchDependencies,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DrawingManagerService, IDrawingManagerService } from '@univerjs/drawing';
+import {
+ CopySheetCommand,
+ CopyWorksheetEndMutation,
+ InsertSheetMutation,
+ RemoveSheetCommand,
+ RemoveSheetMutation,
+ SetRangeValuesMutation,
+ SetWorksheetActivateCommand,
+ SetWorksheetActiveOperation,
+ SheetInterceptorService,
+ SheetLazyExecuteScheduleService,
+} from '@univerjs/sheets';
+import enUS from '@univerjs/sheets/locale/en-US';
+import { SheetsDrawingLoadController } from '../controllers/sheet-drawing.controller';
+import { ISheetDrawingService, SheetDrawingService } from '../services/sheet-drawing.service';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: ['sheet1', 'sheet2'],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {},
+ },
+ sheet2: {
+ id: 'sheet2',
+ name: 'Sheet2',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {},
+ },
+ },
+};
+
+export interface ISheetsDrawingTestBed {
+ univer: Univer;
+ get: Injector['get'];
+ injector: Injector;
+ workbook: Workbook;
+ commandService: ICommandService;
+}
+
+export function createSheetsDrawingTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ISheetsDrawingTestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ this._injector.get(IUndoRedoService);
+
+ ([
+ [SheetInterceptorService],
+ [SheetLazyExecuteScheduleService],
+ [IDrawingManagerService, { useClass: DrawingManagerService }],
+ [ISheetDrawingService, { useClass: SheetDrawingService }],
+ [SheetsDrawingLoadController],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+
+ dependencies?.forEach((dependency) => this._injector.add(dependency));
+
+ touchDependencies(this._injector, [
+ [SheetsDrawingLoadController],
+ ]);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(
+ UniverInstanceType.UNIVER_SHEET,
+ Tools.deepClone(workbookData ?? TEST_WORKBOOK_DATA)
+ );
+
+ get(IUniverInstanceService).focusUnit(workbook.getUnitId());
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ const localeService = get(LocaleService);
+ localeService.load({ enUS });
+ localeService.setLocale(LocaleType.EN_US);
+
+ const commandService = get(ICommandService);
+ [
+ CopySheetCommand,
+ CopyWorksheetEndMutation,
+ InsertSheetMutation,
+ RemoveSheetCommand,
+ RemoveSheetMutation,
+ SetRangeValuesMutation,
+ SetWorksheetActivateCommand,
+ SetWorksheetActiveOperation,
+ ].forEach((command) => commandService.registerCommand(command));
+
+ return {
+ univer,
+ get,
+ injector,
+ workbook,
+ commandService,
+ };
+}
diff --git a/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.ts b/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.ts
new file mode 100644
index 0000000000..2b5f617b17
--- /dev/null
+++ b/packages/sheets-drawing/src/commands/commands/__tests__/sheet-drawing.integration.spec.ts
@@ -0,0 +1,203 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandService, Injector, Univer } from '@univerjs/core';
+import type { ISheetDrawing } from '../../../services/sheet-drawing.service';
+import { DrawingTypeEnum, ImageSourceType, IUniverInstanceService, UndoCommand } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { CopySheetCommand, RemoveSheetCommand, SetWorksheetActivateCommand } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createSheetsDrawingTestBed } from '../../../__tests__/create-sheets-drawing-test-bed';
+import { ISheetDrawingService } from '../../../services/sheet-drawing.service';
+import { InsertSheetDrawingCommand } from '../insert-sheet-drawing.command';
+import { RemoveSheetDrawingCommand } from '../remove-sheet-drawing.command';
+
+function createSheetDrawing(drawingId: string, subUnitId = 'sheet1'): ISheetDrawing {
+ return {
+ unitId: 'test',
+ subUnitId,
+ drawingId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ imageSourceType: ImageSourceType.URL,
+ source: `https://example.com/${drawingId}.png`,
+ sheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: {
+ row: 1,
+ rowOffset: 0,
+ column: 1,
+ columnOffset: 0,
+ },
+ to: {
+ row: 4,
+ rowOffset: 0,
+ column: 3,
+ columnOffset: 0,
+ },
+ },
+ axisAlignSheetTransform: {
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ from: {
+ row: 1,
+ rowOffset: 0,
+ column: 1,
+ columnOffset: 0,
+ },
+ to: {
+ row: 4,
+ rowOffset: 0,
+ column: 3,
+ columnOffset: 0,
+ },
+ },
+ };
+}
+
+describe('sheet drawing integration', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createSheetsDrawingTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = testBed.commandService;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('inserts a drawing through the real command pipeline and syncs both drawing services', async () => {
+ const drawing = createSheetDrawing('drawing-1');
+
+ expect(await commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [drawing],
+ })).toBe(true);
+
+ const sheetDrawingService = get(ISheetDrawingService);
+ const drawingManagerService = get(IDrawingManagerService);
+
+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-1' })).toMatchObject({
+ drawingId: 'drawing-1',
+ subUnitId: 'sheet1',
+ });
+ expect(drawingManagerService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-1' })).toMatchObject({
+ drawingId: 'drawing-1',
+ subUnitId: 'sheet1',
+ });
+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual(['drawing-1']);
+ });
+
+ it('removes an inserted drawing through the real command pipeline', async () => {
+ const drawing = createSheetDrawing('drawing-2');
+
+ await commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [drawing],
+ });
+
+ expect(await commandService.executeCommand(RemoveSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [{
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ drawingId: 'drawing-2',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ }],
+ })).toBe(true);
+
+ const sheetDrawingService = get(ISheetDrawingService);
+ const drawingManagerService = get(IDrawingManagerService);
+
+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-2' })).toBeUndefined();
+ expect(drawingManagerService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-2' })).toBeUndefined();
+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual([]);
+ });
+
+ it('copies sheet drawings when a worksheet is duplicated', async () => {
+ await commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ });
+ await commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [createSheetDrawing('drawing-3')],
+ });
+
+ expect(commandService.syncExecuteCommand(CopySheetCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ })).toBe(true);
+
+ const workbook = get(IUniverInstanceService).getUniverSheetInstance('test')!;
+ const copiedSheetId = workbook.getSheets()
+ .map((sheet) => sheet.getSheetId())
+ .find((sheetId) => sheetId !== 'sheet1' && sheetId !== 'sheet2')!;
+ const copiedDrawings = Object.values(get(ISheetDrawingService).getDrawingData('test', copiedSheetId));
+
+ expect(copiedDrawings).toHaveLength(1);
+ expect(copiedDrawings[0]).toMatchObject({
+ unitId: 'test',
+ subUnitId: copiedSheetId,
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ });
+ expect(copiedDrawings[0].drawingId).not.toBe('drawing-3');
+ expect(get(IDrawingManagerService).getDrawingOrder('test', copiedSheetId)).toHaveLength(1);
+ });
+
+ it('removes and restores sheet drawings when a worksheet is deleted and undone', async () => {
+ await commandService.executeCommand(SetWorksheetActivateCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ });
+ await commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: 'test',
+ drawings: [createSheetDrawing('drawing-4')],
+ });
+
+ expect(commandService.syncExecuteCommand(RemoveSheetCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ })).toBe(true);
+
+ const sheetDrawingService = get(ISheetDrawingService);
+ const drawingManagerService = get(IDrawingManagerService);
+
+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-4' })).toBeUndefined();
+ expect(drawingManagerService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-4' })).toBeUndefined();
+ expect(sheetDrawingService.getDrawingOrder('test', 'sheet1')).toEqual([]);
+ expect(drawingManagerService.getDrawingOrder('test', 'sheet1')).toEqual([]);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBe(true);
+ expect(sheetDrawingService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-4' })).toMatchObject({
+ drawingId: 'drawing-4',
+ });
+ expect(drawingManagerService.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-4' })).toMatchObject({
+ drawingId: 'drawing-4',
+ });
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/__tests__/utils.spec.ts b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..7f33176dc0
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/__tests__/utils.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 { describe, expect, it } from 'vitest';
+import { isBlankInput, resolveRangePayload } from '../utils';
+
+describe('CellLinkEdit utils', () => {
+ it('treats whitespace-only labels as blank input', () => {
+ expect(isBlankInput('')).toBe(true);
+ expect(isBlankInput(' ')).toBe(true);
+ expect(isBlankInput('\n\t')).toBe(true);
+ expect(isBlankInput(' label ')).toBe(false);
+ });
+
+ it('returns an empty payload for invalid range text', () => {
+ expect(resolveRangePayload('', 'Sheet1')).toBe('');
+ expect(resolveRangePayload('not-a-range', 'Sheet1')).toBe('');
+ });
+
+ it('normalizes valid range text and falls back to the active sheet name', () => {
+ expect(resolveRangePayload('A1:B2', 'Sheet1')).toBe('Sheet1!A1:B2');
+ expect(resolveRangePayload('Sheet2!A1:B2', 'Sheet1')).toBe('Sheet2!A1:B2');
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
index 549061d359..b2b16256b8 100644
--- a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/index.tsx
@@ -27,7 +27,6 @@ import {
generateRandomId,
ICommandService,
IContextService,
- isValidRange,
IUniverInstanceService,
LocaleService,
ThemeService,
@@ -37,7 +36,7 @@ import {
import { borderClassName, Button, clsx, FormLayout, Input, Select } from '@univerjs/design';
import { DocSelectionManagerService } from '@univerjs/docs';
import { DocBackScrollRenderController, DocSelectionRenderService } from '@univerjs/docs-ui';
-import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeToRefString, serializeRangeWithSheet } from '@univerjs/engine-formula';
+import { deserializeRangeWithSheet, IDefinedNamesService, serializeRange, serializeRangeWithSheet } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { RangeSelector } from '@univerjs/sheets-formula-ui';
@@ -51,6 +50,7 @@ import { SheetsHyperLinkPopupService } from '../../services/popup.service';
import { SheetsHyperLinkResolverService } from '../../services/resolver.service';
import { SheetsHyperLinkSidePanelService } from '../../services/side-panel.service';
import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
+import { isBlankInput, resolveRangePayload } from './utils';
export const CellLinkEdit = () => {
const [id, setId] = useState('');
@@ -91,11 +91,11 @@ export const CellLinkEdit = () => {
const [showError, setShowError] = useState(false);
- const [isFocusRangeSelector, isFocusRangeSelectorSet] = useState(false);
+ const [isFocusRangeSelector, setIsFocusRangeSelector] = useState(false);
const setByPayload = useRef(false);
- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
const subUnitId = workbook?.getActiveSheet().getSheetId() || '';
// to polyfill the display value on old version data
@@ -245,7 +245,7 @@ export const CellLinkEdit = () => {
}, [editing, markSelectionService, themeService, univerInstanceService]);
useEffect(() => {
- isFocusRangeSelectorSet(type === SheetHyperLinkType.RANGE);
+ setIsFocusRangeSelector(type === SheetHyperLinkType.RANGE);
}, [type]);
useEffect(() => {
@@ -349,15 +349,12 @@ export const CellLinkEdit = () => {
};
const handleRangeChange = useEvent((rangeText: string) => {
- const newValue = rangeText.split(',').map(deserializeRangeWithSheet);
- const range = newValue[0];
- if (!range || !isValidRange(range.range)) {
+ const newPayload = resolveRangePayload(rangeText, workbook.getActiveSheet()?.getName() || '');
+ if (!newPayload) {
+ setPayload('');
return;
}
- if (!range.sheetName) {
- range.sheetName = workbook.getActiveSheet()?.getName() || '';
- }
- const newPayload = serializeRangeToRefString(range);
+
setPayload(newPayload);
if (newPayload && (setByPayload.current || !display)) {
@@ -367,7 +364,7 @@ export const CellLinkEdit = () => {
});
const handleSubmit = async () => {
- if ((showLabel && !display) || !payload || (type === SheetHyperLinkType.URL && !isLegalLink(payload))) {
+ if ((showLabel && isBlankInput(display)) || !payload || (type === SheetHyperLinkType.URL && !isLegalLink(payload))) {
setShowError(true);
return;
}
@@ -442,7 +439,7 @@ export const CellLinkEdit = () => {
? (
<FormLayout
label={localeService.t('hyperLink.form.label')}
- error={showError && !display ? localeService.t('hyperLink.form.inputError') : ''}
+ error={showError && isBlankInput(display) ? localeService.t('hyperLink.form.inputError') : ''}
>
<Input
value={display}
@@ -539,7 +536,7 @@ export const CellLinkEdit = () => {
setHide(false);
}
}}
- onFocusChange={(focus) => isFocusRangeSelectorSet(focus)}
+ onFocusChange={(focus) => setIsFocusRangeSelector(focus)}
/>
</FormLayout>
)}
diff --git a/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/utils.ts b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/utils.ts
new file mode 100644
index 0000000000..51c01593e9
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/views/CellLinkEdit/utils.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 { isValidRange } from '@univerjs/core';
+import { deserializeRangeWithSheet, serializeRangeToRefString } from '@univerjs/engine-formula';
+
+export function isBlankInput(value: string) {
+ return value.trim().length === 0;
+}
+
+export function resolveRangePayload(rangeText: string, defaultSheetName: string) {
+ const [range] = rangeText.split(',').map(deserializeRangeWithSheet);
+
+ if (!range || !isValidRange(range.range)) {
+ return '';
+ }
+
+ if (!range.sheetName) {
+ range.sheetName = defaultSheetName;
+ }
+
+ return serializeRangeToRefString(range);
+}
diff --git a/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.ts b/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.ts
new file mode 100644
index 0000000000..e1a44a6d20
--- /dev/null
+++ b/packages/sheets-sort-ui/src/commands/commands/__tests__/sheets-sort.command.spec.ts
@@ -0,0 +1,122 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICellData, Injector, Nullable, Univer } from '@univerjs/core';
+import { ICommandService, IConfirmService, RANGE_TYPE, TestConfirmService } from '@univerjs/core';
+import { ReorderRangeCommand, ReorderRangeMutation, SetRangeValuesMutation, SheetsSelectionsService } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SortRangeAscCommand, SortRangeDescCommand } from '../sheets-sort.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+describe('Sheets sort commands integration', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let getValues: (
+ startRow: number,
+ startColumn: number,
+ endRow: number,
+ endColumn: number
+ ) => Array<Array<Nullable<ICellData>>> | undefined;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(undefined, [
+ [IConfirmService, { useClass: TestConfirmService }],
+ ]);
+
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = get(ICommandService);
+
+ [
+ ReorderRangeCommand,
+ ReorderRangeMutation,
+ SetRangeValuesMutation,
+ SortRangeAscCommand,
+ SortRangeDescCommand,
+ ].forEach((command) => commandService.registerCommand(command));
+
+ getValues = (startRow, startColumn, endRow, endColumn) =>
+ testBed.sheet
+ .getSheetBySheetId('sheet1')
+ ?.getRange(startRow, startColumn, endRow, endColumn)
+ .getValues();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('sorts the selected range ascending through executeCommand', 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(SortRangeAscCommand.id)).toBe(true);
+
+ expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(1);
+ expect(getValues(6, 9, 6, 9)?.[0]?.[0]?.v).toBe(7);
+ expect(getValues(0, 11, 0, 11)?.[0]?.[0]?.f).toBe('=J1/K1');
+ expect(getValues(6, 11, 6, 11)?.[0]?.[0]?.f).toBe('=SUM(J7:K8)');
+ });
+
+ it('sorts the selected range descending through executeCommand and rewrites formulas', async () => {
+ get(SheetsSelectionsService).addSelections([{
+ range: {
+ startRow: 0,
+ startColumn: 9,
+ endRow: 6,
+ endColumn: 11,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: {
+ actualRow: 0,
+ actualColumn: 9,
+ startRow: 0,
+ startColumn: 9,
+ endRow: 6,
+ endColumn: 11,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ }]);
+
+ expect(await commandService.executeCommand(SortRangeDescCommand.id)).toBe(true);
+
+ expect(getValues(0, 9, 0, 9)?.[0]?.[0]?.v).toBe(7);
+ expect(getValues(6, 9, 6, 9)?.[0]?.[0]?.v).toBe(1);
+ expect(getValues(0, 11, 0, 11)?.[0]?.[0]?.f).toBe('=SUM(J1:K2)');
+ expect(getValues(6, 11, 6, 11)?.[0]?.[0]?.f).toBe('=J7/K7');
+ });
+});
diff --git a/packages/sheets-sort-ui/src/controllers/__tests__/sheets-sort-ui.controller.spec.ts b/packages/sheets-sort-ui/src/controllers/__tests__/sheets-sort-ui.controller.spec.ts
new file mode 100644
index 0000000000..88798eeaf1
--- /dev/null
+++ b/packages/sheets-sort-ui/src/controllers/__tests__/sheets-sort-ui.controller.spec.ts
@@ -0,0 +1,134 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { 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, 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 '../sheets-sort-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 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 }],
+ ]);
+
+ 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-thread-comment-ui/src/__tests__/create-thread-comment-ui-test-bed.ts b/packages/sheets-thread-comment-ui/src/__tests__/create-thread-comment-ui-test-bed.ts
new file mode 100644
index 0000000000..f7d77a1de2
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/__tests__/create-thread-comment-ui-test-bed.ts
@@ -0,0 +1,148 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import {
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LifecycleService,
+ LifecycleStages,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ Tools,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { SheetsThreadCommentModel } from '@univerjs/sheets-thread-comment';
+import { CellPopupManagerService, ISheetClipboardService, SheetCanvasPopManagerService } from '@univerjs/sheets-ui';
+import { AddCommentMutation, DeleteCommentMutation, IThreadCommentDataSourceService, ThreadCommentDataSourceService, ThreadCommentModel } from '@univerjs/thread-comment';
+import { IZenZoneService } from '@univerjs/ui';
+import { BehaviorSubject } from 'rxjs';
+import { vi } from 'vitest';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: '',
+ sheetOrder: ['sheet1', 'sheet2'],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'Sheet1',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {},
+ },
+ sheet2: {
+ id: 'sheet2',
+ name: 'Sheet2',
+ rowCount: 20,
+ columnCount: 20,
+ cellData: {},
+ },
+ },
+};
+
+export function createThreadCommentUiTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ let clipboardHook: {
+ onBeforeCopy: (unitId: string, subUnitId: string, range: ISelectionWithStyle['range']) => void;
+ onPasteCells: (...args: any[]) => { redos: Array<{ id: string; params: unknown }>; undos: Array<{ id: string; params: unknown }> };
+ } | undefined;
+
+ const popupDisposable = {
+ dispose: vi.fn(),
+ };
+ const cellPopupManagerService = {
+ showPopup: vi.fn(() => popupDisposable),
+ };
+ const zenVisible$ = new BehaviorSubject(false);
+ const zenZoneService = {
+ visible$: zenVisible$,
+ get visible() {
+ return zenVisible$.getValue();
+ },
+ };
+ const sheetClipboardService = {
+ addClipboardHook: vi.fn((hook) => {
+ clipboardHook = hook;
+ return {
+ dispose: vi.fn(),
+ };
+ }),
+ };
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ ([
+ [IThreadCommentDataSourceService, { useClass: ThreadCommentDataSourceService }],
+ [ThreadCommentModel],
+ [SheetsThreadCommentModel],
+ [ISheetClipboardService, { useValue: sheetClipboardService as unknown as ISheetClipboardService }],
+ [CellPopupManagerService, { useValue: cellPopupManagerService as unknown as CellPopupManagerService }],
+ [SheetCanvasPopManagerService, { useValue: {} as SheetCanvasPopManagerService }],
+ [IZenZoneService, { useValue: zenZoneService as unknown as IZenZoneService }],
+ ] as Dependency[]).forEach((dependency) => this._injector.add(dependency));
+
+ dependencies?.forEach((dependency) => this._injector.add(dependency));
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(
+ UniverInstanceType.UNIVER_SHEET,
+ Tools.deepClone(workbookData ?? TEST_WORKBOOK_DATA)
+ );
+
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+ get(IUniverInstanceService).focusUnit(workbook.getUnitId());
+ get(LifecycleService).stage = LifecycleStages.Rendered;
+ get(ICommandService).registerCommand(AddCommentMutation);
+ get(ICommandService).registerCommand(DeleteCommentMutation);
+
+ return {
+ univer,
+ injector,
+ get,
+ workbook,
+ commandService: get(ICommandService),
+ cellPopupManagerService,
+ popupDisposable,
+ zenVisible$,
+ getClipboardHook: () => clipboardHook,
+ };
+}
diff --git a/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-copy-paste.controller.spec.ts b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-copy-paste.controller.spec.ts
new file mode 100644
index 0000000000..79a6cc8073
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/controllers/__tests__/sheets-thread-comment-copy-paste.controller.spec.ts
@@ -0,0 +1,132 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { COPY_TYPE } from '@univerjs/sheets-ui';
+import { AddCommentMutation, DeleteCommentMutation } from '@univerjs/thread-comment';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { createThreadCommentUiTestBed } from '../../__tests__/create-thread-comment-ui-test-bed';
+import { SheetsThreadCommentCopyPasteController } from '../sheets-thread-comment-copy-paste.controller';
+
+function createRootComment() {
+ return {
+ id: 'comment-1',
+ threadId: 'thread-1',
+ ref: 'A1',
+ dT: '2025-01-01T00:00:00.000Z',
+ personId: 'user-1',
+ text: { dataStream: 'hello\r\n' },
+ attachments: [],
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ };
+}
+
+describe('SheetsThreadCommentCopyPasteController', () => {
+ let testBed: ReturnType<typeof createThreadCommentUiTestBed>;
+
+ beforeEach(() => {
+ testBed = createThreadCommentUiTestBed();
+ });
+
+ afterEach(() => {
+ testBed.univer.dispose();
+ });
+
+ it('creates delete/add mutations when cutting comments to another sheet', async () => {
+ await testBed.commandService.executeCommand(AddCommentMutation.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ comment: createRootComment(),
+ });
+
+ const controller = testBed.injector.createInstance(SheetsThreadCommentCopyPasteController);
+ const hook = testBed.getClipboardHook();
+
+ expect(hook).toBeDefined();
+
+ hook!.onBeforeCopy('test', 'sheet1', {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ });
+
+ const result = hook!.onPasteCells(
+ null,
+ {
+ unitId: 'test',
+ subUnitId: 'sheet2',
+ range: {
+ rows: [2],
+ cols: [3],
+ },
+ },
+ null,
+ {
+ copyType: COPY_TYPE.CUT,
+ }
+ );
+
+ expect(result.redos).toEqual([
+ {
+ id: DeleteCommentMutation.id,
+ params: {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ commentId: 'comment-1',
+ },
+ },
+ {
+ id: AddCommentMutation.id,
+ params: expect.objectContaining({
+ unitId: 'test',
+ subUnitId: 'sheet2',
+ sync: true,
+ comment: expect.objectContaining({
+ id: 'comment-1',
+ ref: expect.stringContaining('D3'),
+ unitId: 'test',
+ subUnitId: 'sheet2',
+ }),
+ }),
+ },
+ ]);
+ expect(result.undos).toEqual([
+ {
+ id: DeleteCommentMutation.id,
+ params: {
+ unitId: 'test',
+ subUnitId: 'sheet2',
+ commentId: 'comment-1',
+ },
+ },
+ {
+ id: AddCommentMutation.id,
+ params: expect.objectContaining({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ sync: true,
+ comment: expect.objectContaining({
+ id: 'comment-1',
+ ref: 'A1',
+ }),
+ }),
+ },
+ ]);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.ts b/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.ts
new file mode 100644
index 0000000000..1ef8511128
--- /dev/null
+++ b/packages/sheets-thread-comment-ui/src/services/__tests__/sheets-thread-comment-popup.service.spec.ts
@@ -0,0 +1,101 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createThreadCommentUiTestBed } from '../../__tests__/create-thread-comment-ui-test-bed';
+import { SHEETS_THREAD_COMMENT_MODAL } from '../../types/const';
+import { SheetsThreadCommentPopupService } from '../sheets-thread-comment-popup.service';
+
+describe('SheetsThreadCommentPopupService', () => {
+ const onHide = vi.fn();
+ let testBed: ReturnType<typeof createThreadCommentUiTestBed>;
+
+ beforeEach(() => {
+ onHide.mockReset();
+ vi.stubGlobal('document', {
+ querySelectorAll: vi.fn(() => []),
+ getElementById: vi.fn(() => null),
+ });
+ testBed = createThreadCommentUiTestBed();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ testBed.univer.dispose();
+ });
+
+ it('shows, persists and hides the active popup through the popup manager boundary', () => {
+ const service = testBed.injector.createInstance(SheetsThreadCommentPopupService);
+
+ service.showPopup({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ row: 1,
+ col: 2,
+ commentId: 'comment-1',
+ temp: true,
+ trigger: 'hover',
+ }, onHide);
+
+ expect(service.activePopup).toEqual({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ row: 1,
+ col: 2,
+ commentId: 'comment-1',
+ temp: true,
+ trigger: 'hover',
+ });
+ expect(testBed.cellPopupManagerService.showPopup).toHaveBeenCalledWith({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ row: 1,
+ col: 2,
+ }, expect.objectContaining({
+ componentKey: SHEETS_THREAD_COMMENT_MODAL,
+ direction: 'horizontal',
+ }));
+
+ service.persistPopup();
+ expect(service.activePopup).toEqual(expect.objectContaining({
+ temp: false,
+ }));
+
+ service.hidePopup();
+ expect(service.activePopup).toBeNull();
+ expect(testBed.popupDisposable.dispose).toHaveBeenCalled();
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+
+ it('hides the popup when zen mode becomes visible', () => {
+ const service = testBed.injector.createInstance(SheetsThreadCommentPopupService);
+
+ service.showPopup({
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ row: 4,
+ col: 5,
+ commentId: 'comment-2',
+ });
+ expect(service.activePopup).toEqual(expect.objectContaining({
+ commentId: 'comment-2',
+ }));
+
+ testBed.zenVisible$.next(true);
+
+ expect(service.activePopup).toBeNull();
+ });
+});
diff --git a/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts
index 68932bbd59..edc9c0c71d 100644
--- a/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts
+++ b/packages/sheets/src/commands/commands/__tests__/create-command-test-bed.ts
@@ -78,6 +78,7 @@ const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {
export interface ITestBed {
univer: Univer;
get: Injector['get'];
+ injector: Injector;
sheet: Workbook;
}
@@ -132,6 +133,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?
return {
univer,
get: injector.get.bind(injector),
+ injector,
sheet,
};
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 849e160ef9..3ed88cdcd5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1107,6 +1107,9 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
postcss:
specifier: ^8.5.8
version: 8.5.8
@@ -1793,9 +1796,6 @@ importers:
'@univerjs/drawing':
specifier: workspace:*
version: link:../drawing
- '@univerjs/engine-render':
- specifier: workspace:*
- version: link:../engine-render
'@univerjs/sheets':
specifier: workspace:*
version: link:../sheets
@@ -1803,6 +1803,9 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
typescript:
specifier: ^6.0.2
version: 6.0.2