Skip to content

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

test: add unit tests (#6662)

白熱b31c6e26f326
diff --git a/codecov.yml b/codecov.yml
index 0f275c7703..36fe6673f1 100644
--- a/codecov.yml
+++ b/codecov.yml
@@ -3,7 +3,7 @@ coverage:
project:
default:
# basic
- target: 50%
+ target: 60%
threshold: 0
base: auto
# advanced settings
diff --git a/common/shared/vitest/index.js b/common/shared/vitest/index.js
index 6f101302ea..61c3720ee2 100644
--- a/common/shared/vitest/index.js
+++ b/common/shared/vitest/index.js
@@ -54,6 +54,9 @@ function createConfig(options) {
'**/*/tailwind.config.ts',
'packages/slides/**',
'packages/slides-ui/**',
+ '**/src/plugin.ts',
+ '**/src/mobile-plugin.ts',
+ '**/src/config/config.ts',
],
},
},
diff --git a/eslint.config.ts b/eslint.config.ts
index 8cd137ae1a..06dea18c1b 100644
--- a/eslint.config.ts
+++ b/eslint.config.ts
@@ -18,6 +18,7 @@ export default antfu(
'mockdata/**/*.json',
'pnpm-lock.yaml',
'examples/src/demos.ts',
+ 'examples/public',
],
stylistic: {
indent: 4,
diff --git a/packages/core/src/__tests__/univer-skeleton.spec.ts b/packages/core/src/__tests__/univer-skeleton.spec.ts
index c59087aa34..fd50786397 100644
--- a/packages/core/src/__tests__/univer-skeleton.spec.ts
+++ b/packages/core/src/__tests__/univer-skeleton.spec.ts
@@ -18,11 +18,8 @@ import type { ILocales } from '../shared/locale';
import { defaultTheme } from '@univerjs/themes';
import { describe, expect, it, vi } from 'vitest';
import { Injector } from '../common/di';
-import { UniverInstanceType } from '../common/unit';
import { COMMAND_LOG_EXECUTION_CONFIG_KEY } from '../services/command/command.service';
import { IConfigService } from '../services/config/config.service';
-import { LifecycleStages } from '../services/lifecycle/lifecycle';
-import { LifecycleService } from '../services/lifecycle/lifecycle.service';
import { LocaleService } from '../services/locale/locale.service';
import { LogLevel } from '../services/log/log.service';
import { Skeleton } from '../skeleton';
@@ -91,26 +88,6 @@ describe('Univer', () => {
expect(activeCallback).toHaveBeenCalledTimes(1);
});
- it('should create units via deprecated and current APIs', () => {
- const univer = new Univer();
- const injector = univer.__getInjector();
-
- const sheetA = univer.createUniverSheet({ id: 'sheet-a' });
- const sheetB = univer.createUnit(UniverInstanceType.UNIVER_SHEET, { id: 'sheet-b' });
- const sheetC = univer.createUnit(UniverInstanceType.UNIVER_SHEET, { id: 'sheet-c' });
- const doc = univer.createUniverDoc({ id: 'doc-a' });
- const slide = univer.createUniverSlide({ id: 'slide-a' });
-
- expect(sheetA.getUnitId()).toBe('sheet-a');
- expect(sheetB.getUnitId()).toBe('sheet-b');
- expect(sheetC.getUnitId()).toBe('sheet-c');
- expect(doc.getUnitId()).toBe('doc-a');
- expect(slide.getUnitId()).toBe('slide-a');
- expect(injector.get(LifecycleService).stage).toBe(LifecycleStages.Ready);
-
- univer.dispose();
- });
-
it('should delegate plugin registration for tuple-style APIs and support parent injector', () => {
const parentInjector = new Injector([]);
const univer = new Univer({}, parentInjector);
diff --git a/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
new file mode 100644
index 0000000000..479cd5d287
--- /dev/null
+++ b/packages/core/src/docs/data-model/__tests__/document-modeling.integration.spec.ts
@@ -0,0 +1,204 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData } from '../../../types/interfaces/i-document-data';
+import { describe, expect, it } from 'vitest';
+import { BooleanNumber, HorizontalAlign, TextDecoration, TextDirection } from '../../../types/enum/text-style';
+import { DocumentDataModel } from '../document-data-model';
+import { JSONX } from '../json-x/json-x';
+import { ParagraphStyleBuilder, RichTextBuilder, TextDecorationBuilder, TextStyleBuilder } from '../rich-text-builder';
+
+function createDocSnapshot(id = 'doc-main'): IDocumentData {
+ return {
+ id,
+ title: 'Main Doc',
+ documentStyle: {
+ pageSize: { width: 300, height: 400 },
+ marginTop: 1,
+ marginBottom: 2,
+ marginLeft: 3,
+ marginRight: 4,
+ },
+ body: {
+ dataStream: 'Hello World\r\n',
+ paragraphs: [{ startIndex: 0 }],
+ textRuns: [{ st: 0, ed: 5, ts: { ff: 'Arial', fs: 12 } }],
+ customRanges: [],
+ customDecorations: [],
+ },
+ headers: {
+ header1: {
+ headerId: 'header1',
+ body: {
+ dataStream: 'Header\r\n',
+ paragraphs: [{ startIndex: 0 }],
+ textRuns: [],
+ },
+ },
+ },
+ footers: {
+ footer1: {
+ footerId: 'footer1',
+ body: {
+ dataStream: 'Footer\r\n',
+ paragraphs: [{ startIndex: 0 }],
+ textRuns: [],
+ },
+ },
+ },
+ drawings: {
+ drawing1: {
+ drawingId: 'drawing1',
+ docTransform: {
+ size: { width: 10, height: 10 },
+ positionH: { posOffset: 0 },
+ positionV: { posOffset: 0 },
+ },
+ },
+ } as any,
+ drawingsOrder: ['drawing1'],
+ };
+}
+
+describe('DocumentDataModel + RichTextBuilder integration', () => {
+ it('should perform typical editing operations and reflect them in the document snapshot', () => {
+ const model = new DocumentDataModel(createDocSnapshot());
+ expect(model.getUnitId()).toBe('doc-main');
+ expect(model.getTitle()).toBe('Main Doc');
+
+ model.setName('Renamed');
+ expect(model.getTitle()).toBe('Renamed');
+
+ model.updateDocumentDataMargin({ t: 10, l: 20 });
+ model.updateDocumentDataPageSize(500, 600);
+ expect(model.getDocumentStyle().marginTop).toBe(10);
+ expect(model.getDocumentStyle().marginLeft).toBe(20);
+ expect(model.getDocumentStyle().pageSize).toEqual({ width: 500, height: 600 });
+
+ model.updateDocumentRenderConfig({
+ locale: 'enUS',
+ } as any);
+ model.updateDocumentStyle({
+ renderConfig: { direction: TextDirection.LEFT_TO_RIGHT },
+ } as any);
+
+ model.updateDrawing('drawing1', { width: 100, height: 50, left: 12, top: 34 });
+ expect(model.getDrawings()?.drawing1.docTransform.size).toEqual({ width: 100, height: 50 });
+
+ model.setZoomRatio(1.5);
+ model.setDisabled(true);
+ expect(model.zoomRatio).toBe(1.5);
+ expect(model.getDisabled()).toBe(true);
+
+ const headerModel = model.getSelfOrHeaderFooterModel('header1');
+ const footerModel = model.getSelfOrHeaderFooterModel('footer1');
+ expect(headerModel.getUnitId()).toBe(model.getUnitId());
+ expect(footerModel.getUnitId()).toBe(model.getUnitId());
+
+ const richText = RichTextBuilder.create(RichTextBuilder.newEmptyData());
+ richText
+ .insertText('Hello')
+ .insertParagraph(
+ ParagraphStyleBuilder.create({
+ horizontalAlign: HorizontalAlign.CENTER,
+ direction: TextDirection.RIGHT_TO_LEFT,
+ })
+ )
+ .insertLink(' Univer', 'https://univer.ai')
+ .setStyle(0, 5, TextStyleBuilder.create({ ff: 'Inter', fs: 14, bl: BooleanNumber.TRUE }))
+ .setLink(0, 5, 'https://example.com');
+
+ const firstLinkId = richText.getLinks()[0].rangeId;
+ richText.updateLink(firstLinkId, 'https://updated.example.com');
+
+ expect(richText.toPlainText()).toContain('Hello');
+ expect(richText.getLinks()).toHaveLength(2);
+
+ const sliced = richText.slice(0, 5);
+ expect(sliced.toPlainText()).toContain('Hello');
+
+ const decoration = TextDecorationBuilder.create({ s: BooleanNumber.TRUE })
+ .setLineType(TextDecoration.SINGLE)
+ .setFollowFontColor(false)
+ .build();
+
+ const styled = new TextStyleBuilder({}).setUnderline(TextDecorationBuilder.create(decoration)).build();
+ expect(styled.ul?.s).toBe(BooleanNumber.TRUE);
+
+ const docData = richText.getData();
+ expect(docData.body?.dataStream).toContain('Hello');
+
+ const jsonx = JSONX.getInstance();
+ model.apply(jsonx.replaceOp(['title'], 'Renamed', 'Applied Title') as any);
+ model.apply(jsonx.replaceOp(['settings', 'zoomRatio'], 1.5, 2) as any);
+ expect(model.getTitle()).toBe('Applied Title');
+
+ expect(model.getPlainText()).toContain('Hello World');
+ expect(model.sliceBody(0, 5)?.dataStream).toContain('Hello');
+
+ model.resetDrawing({} as any, []);
+ expect(model.getDrawingsOrder()).toEqual([]);
+ model.dispose();
+ });
+
+ it('should manage reset, noop apply and header-footer reinitialization for realistic document state changes', () => {
+ const snapshot = createDocSnapshot('doc-reset');
+ const model = new DocumentDataModel(snapshot);
+ const jsonx = JSONX.getInstance();
+ const initialChangeCount = model.change$.getValue();
+
+ expect(model.getCustomRanges()).toEqual([]);
+ expect(model.getCustomDecorations()).toEqual([]);
+ expect(model.getSettings()).toBeUndefined();
+ expect(model.apply(null as never)).toBeUndefined();
+ expect(model.change$.getValue()).toBe(initialChangeCount);
+
+ model.setZoomRatio(2);
+ expect(model.getSettings()).toEqual({ zoomRatio: 2 });
+
+ model.apply(jsonx.replaceOp(['headers'], model.getSnapshot().headers, {
+ ...model.getSnapshot().headers,
+ header2: {
+ headerId: 'header2',
+ body: {
+ dataStream: 'Another Header\r\n',
+ paragraphs: [{ startIndex: 0 }],
+ },
+ },
+ }) as never);
+
+ expect(model.getSnapshot().headers?.header2?.body.dataStream).toBe('Another Header\r\n');
+ expect(model.change$.getValue()).toBeGreaterThan(initialChangeCount);
+
+ expect(() => model.reset({ id: 'other-doc' })).toThrow('Cannot reset a document model with a different unit id!');
+
+ model.reset({
+ id: 'doc-reset',
+ title: 'Reset Title',
+ body: {
+ dataStream: 'Reset\r\n',
+ paragraphs: [{ startIndex: 5 }],
+ },
+ documentStyle: {},
+ });
+
+ expect(model.getTitle()).toBe('Reset Title');
+ expect(model.getBody()?.dataStream).toBe('Reset\r\n');
+ expect(model.getUnitId()).toBe('doc-reset');
+ expect(model.sliceBody(0, 5)?.dataStream).toContain('Reset');
+ model.dispose();
+ });
+});
diff --git a/packages/core/src/docs/data-model/__tests__/utils.spec.ts b/packages/core/src/docs/data-model/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..a45399f1a1
--- /dev/null
+++ b/packages/core/src/docs/data-model/__tests__/utils.spec.ts
@@ -0,0 +1,64 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { DEFAULT_STYLES } from '../../../types/const';
+import { BaselineOffset, BooleanNumber } from '../../../types/enum';
+import { convertTextRotation, DEFAULT_FONTFACE_PLANE, getBaselineOffsetInfo, getFontStyleString } from '../utils';
+
+describe('document data-model utils', () => {
+ it('should build font strings from default and styled text', () => {
+ const defaultStyle = getFontStyleString();
+ const superscriptStyle = getFontStyleString({
+ ff: 'Noto Sans',
+ fs: 12.2,
+ it: BooleanNumber.TRUE,
+ bl: BooleanNumber.TRUE,
+ va: BaselineOffset.SUPERSCRIPT,
+ });
+ const normalStyle = getFontStyleString({
+ ff: '"Ping Fang"',
+ fs: 14,
+ it: BooleanNumber.FALSE,
+ bl: BooleanNumber.FALSE,
+ });
+
+ expect(defaultStyle).toEqual({
+ fontCache: `${DEFAULT_STYLES.fs}pt ${DEFAULT_STYLES.ff}`,
+ fontString: `${DEFAULT_STYLES.fs}pt ${DEFAULT_STYLES.ff}`,
+ fontSize: DEFAULT_STYLES.fs,
+ originFontSize: DEFAULT_STYLES.fs,
+ fontFamily: DEFAULT_STYLES.ff,
+ });
+ expect(superscriptStyle.fontFamily).toBe('"Noto Sans"');
+ expect(superscriptStyle.originFontSize).toBe(13);
+ expect(superscriptStyle.fontSize).toBeCloseTo(7.8);
+ expect(superscriptStyle.fontString).toContain(DEFAULT_FONTFACE_PLANE);
+ expect(normalStyle.fontCache).toBe('normal normal 14pt "Ping Fang"');
+ });
+
+ it('should expose baseline offsets and convert text rotation', () => {
+ expect(getBaselineOffsetInfo('Inter', 11)).toEqual({
+ sbr: 0.6,
+ sbo: 11,
+ spr: 0.6,
+ spo: 11,
+ });
+ expect(convertTextRotation({ a: 30 })).toEqual({ centerAngle: 0, vertexAngle: 30 });
+ expect(convertTextRotation({ a: 30, v: BooleanNumber.TRUE })).toEqual({ centerAngle: 90, vertexAngle: 90 });
+ expect(convertTextRotation()).toEqual({ centerAngle: 0, vertexAngle: 0 });
+ });
+});
diff --git a/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts b/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts
index 773103211c..7a83439db3 100644
--- a/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts
+++ b/packages/core/src/docs/data-model/json-x/__tests__/json-x.spec.ts
@@ -14,13 +14,65 @@
* limitations under the License.
*/
+import type { IDocumentData } from '../../../../types/interfaces';
import { describe, expect, it } from 'vitest';
+import { TextX } from '../../text-x/text-x';
import { JSONX } from '../json-x';
+function createDoc(id = 'doc-json-x'): IDocumentData {
+ return {
+ id,
+ body: {
+ dataStream: 'Hello\r\n',
+ paragraphs: [{ startIndex: 5 }],
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
describe('Basic use of json-x', () => {
describe('Static methods', () => {
it('Should return true when the action is null', () => {
expect(JSONX.isNoop(null)).toBe(true);
});
+
+ it('should apply insert, replace and remove operations to document snapshots', () => {
+ const jsonX = JSONX.getInstance();
+ const doc = createDoc();
+ const inserted = JSONX.apply(doc, jsonX.insertOp(['settings'], { zoomRatio: 2 })) as unknown as IDocumentData;
+ const replaced = JSONX.apply(inserted, jsonX.replaceOp(['id'], 'doc-json-x', 'doc-json-x-2')) as unknown as IDocumentData;
+ const removed = JSONX.apply(replaced, jsonX.removeOp(['settings'], { zoomRatio: 2 })) as unknown as IDocumentData;
+
+ expect(inserted.settings).toEqual({ zoomRatio: 2 });
+ expect(replaced.id).toBe('doc-json-x-2');
+ expect(removed.settings).toBeUndefined();
+ });
+
+ it('should compose rich-text edits and transform positions through text-x subtype operations', () => {
+ const jsonX = JSONX.getInstance();
+ const first = new TextX().retain(5).insert(1, { dataStream: '!' }).serialize();
+ const second = new TextX().retain(6).insert(1, { dataStream: '?' }).serialize();
+ const firstEdit = jsonX.editOp(first);
+ const secondEdit = jsonX.editOp(second);
+ const composed = JSONX.compose(firstEdit, secondEdit);
+ const transformed = JSONX.transform(firstEdit, secondEdit, 'left');
+ const doc = createDoc();
+ const edited = JSONX.apply(doc, composed) as unknown as IDocumentData;
+ const inverted = JSONX.invertWithDoc(firstEdit, doc);
+ const restored = JSONX.apply(JSONX.apply(createDoc(), firstEdit) as unknown as IDocumentData, inverted) as unknown as IDocumentData;
+
+ expect(JSONX.transformPosition(firstEdit, 5, 'right')).toBe(6);
+ expect(JSONX.transformPosition(secondEdit, 6, 'left')).toBe(6);
+ expect(transformed).toBeTruthy();
+ expect(edited.body?.dataStream).toBe('Hello!?\r\n');
+ expect(restored).toMatchObject(createDoc());
+ expect(restored.body).toMatchObject({ dataStream: 'Hello\r\n', paragraphs: [{ startIndex: 5 }] });
+ });
});
});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-decoration.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-decoration.spec.ts
new file mode 100644
index 0000000000..a62feea518
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/custom-decoration.spec.ts
@@ -0,0 +1,89 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { CustomDecorationType } from '../../../../../types/interfaces';
+import { DocumentDataModel } from '../../../document-data-model';
+import { TextXActionType } from '../../action-types';
+import { addCustomDecorationTextX, deleteCustomDecorationTextX } from '../custom-decoration';
+
+describe('custom decoration text-x helpers', () => {
+ it('should build decoration retain actions for multiple ranges', () => {
+ const textX = addCustomDecorationTextX({
+ id: 'comment-1',
+ type: CustomDecorationType.COMMENT,
+ ranges: [
+ { startOffset: 1, endOffset: 4, collapsed: false },
+ { startOffset: 6, endOffset: 8, collapsed: false },
+ ],
+ });
+
+ expect(textX.serialize()).toEqual([
+ { t: TextXActionType.RETAIN, len: 1 },
+ {
+ t: TextXActionType.RETAIN,
+ len: 3,
+ body: {
+ dataStream: '',
+ customDecorations: [{ id: 'comment-1', type: CustomDecorationType.COMMENT, startIndex: 0, endIndex: 2 }],
+ },
+ },
+ { t: TextXActionType.RETAIN, len: 2 },
+ {
+ t: TextXActionType.RETAIN,
+ len: 2,
+ body: {
+ dataStream: '',
+ customDecorations: [{ id: 'comment-1', type: CustomDecorationType.COMMENT, startIndex: 0, endIndex: 1 }],
+ },
+ },
+ ]);
+ });
+
+ it('should mark an existing decoration as deleted and guard missing bodies', () => {
+ const doc = new DocumentDataModel({
+ id: 'doc-decoration',
+ body: {
+ dataStream: 'Hello\r\n',
+ customDecorations: [{ id: 'comment-1', type: CustomDecorationType.COMMENT, startIndex: 1, endIndex: 3 }],
+ },
+ });
+
+ const textX = deleteCustomDecorationTextX({
+ id: 'comment-1',
+ documentDataModel: doc,
+ });
+
+ expect(textX).not.toBe(false);
+ if (textX === false) {
+ throw new Error('Expected deleteCustomDecorationTextX to return a TextX instance');
+ }
+
+ expect(textX.serialize()).toEqual([
+ { t: TextXActionType.RETAIN, len: 1 },
+ {
+ t: TextXActionType.RETAIN,
+ len: 3,
+ body: {
+ dataStream: '',
+ customDecorations: [{ id: 'comment-1', type: CustomDecorationType.DELETED, startIndex: 0, endIndex: 2 }],
+ },
+ },
+ ]);
+ expect(deleteCustomDecorationTextX({ id: 'missing', documentDataModel: doc })).toBe(false);
+ expect(deleteCustomDecorationTextX({ id: 'missing', documentDataModel: new DocumentDataModel({ id: 'doc-without-body' }) })).toBe(false);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts
new file mode 100644
index 0000000000..e65de1100c
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/drawings.spec.ts
@@ -0,0 +1,121 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { DocumentDataModel } from '../../../document-data-model';
+import { addDrawing, getCustomBlockIdsInSelections, getRichTextEditPath } from '../drawings';
+
+describe('drawing build utils', () => {
+ it('should resolve custom blocks and replace selected drawings in the document body', () => {
+ const doc = new DocumentDataModel({
+ id: 'doc-drawing',
+ body: {
+ dataStream: 'A\bB\r\n',
+ paragraphs: [{ startIndex: 4 }],
+ customBlocks: [{ startIndex: 1, blockId: 'drawing-old' }],
+ },
+ drawings: {
+ 'drawing-old': {
+ unitId: 'doc-drawing',
+ subUnitId: '',
+ drawingId: 'drawing-old',
+ drawingType: 0,
+ title: 'Old drawing',
+ description: 'Old drawing',
+ docTransform: {
+ size: { width: 10, height: 10 },
+ positionH: { relativeFrom: 0, posOffset: 0 },
+ positionV: { relativeFrom: 0, posOffset: 0 },
+ },
+ layoutType: 0,
+ } as never,
+ },
+ drawingsOrder: ['drawing-old'],
+ headers: {
+ 'header-1': {
+ headerId: 'header-1',
+ body: {
+ dataStream: 'Header\r\n',
+ },
+ },
+ },
+ });
+
+ expect(getCustomBlockIdsInSelections(doc.getBody()!, [{ startOffset: 1, endOffset: 2, collapsed: false }])).toEqual(['drawing-old']);
+ expect(getRichTextEditPath(doc)).toEqual(['body']);
+ expect(getRichTextEditPath(doc, 'header-1')).toEqual(['headers', 'header-1', 'body']);
+ expect(() => getRichTextEditPath(doc, 'missing-segment')).toThrow('Segment id not found in headers or footers');
+ expect(() => getRichTextEditPath(new DocumentDataModel({ id: 'doc-no-segment', body: { dataStream: 'Body\r\n' } }), 'missing')).toThrow(
+ 'Document data model must have headers or footers when update by segment id'
+ );
+
+ const actions = addDrawing({
+ selection: { startOffset: 1, endOffset: 2, collapsed: false },
+ documentDataModel: doc,
+ drawings: [{
+ unitId: 'doc-drawing',
+ subUnitId: '',
+ drawingId: 'drawing-new',
+ drawingType: 0,
+ title: 'New drawing',
+ description: 'New drawing',
+ docTransform: {
+ size: { width: 20, height: 20 },
+ positionH: { relativeFrom: 0, posOffset: 0 },
+ positionV: { relativeFrom: 0, posOffset: 0 },
+ },
+ layoutType: 0,
+ } as never],
+ });
+
+ expect(actions).toBeTruthy();
+ if (!actions) {
+ throw new Error('Expected addDrawing to return JSONX actions');
+ }
+ doc.apply(actions);
+
+ expect(doc.getDrawingsOrder()).toEqual(['drawing-new']);
+ expect(doc.getDrawings()).toMatchObject({
+ 'drawing-new': { drawingId: 'drawing-new', title: 'New drawing' },
+ });
+ expect(doc.getDrawings()).not.toHaveProperty('drawing-old');
+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 1, blockId: 'drawing-new' }]);
+ expect(doc.getBody()?.dataStream).toBe('A\bB\r\n');
+ });
+
+ it('should return false when drawing insertion targets a missing body', () => {
+ const result = addDrawing({
+ selection: { startOffset: 0, endOffset: 0, collapsed: true },
+ documentDataModel: new DocumentDataModel({ id: 'doc-without-body' }),
+ drawings: [{
+ unitId: 'doc-without-body',
+ subUnitId: '',
+ drawingId: 'drawing-new',
+ drawingType: 0,
+ title: 'New drawing',
+ description: 'New drawing',
+ docTransform: {
+ size: { width: 20, height: 20 },
+ positionH: { relativeFrom: 0, posOffset: 0 },
+ positionV: { relativeFrom: 0, posOffset: 0 },
+ },
+ layoutType: 0,
+ } as never],
+ });
+
+ expect(result).toBe(false);
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/paragraph.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/paragraph.spec.ts
new file mode 100644
index 0000000000..49af977ad1
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/paragraph.spec.ts
@@ -0,0 +1,192 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentBody, IParagraph } from '../../../../../types/interfaces';
+import { describe, expect, it } from 'vitest';
+import { HorizontalAlign } from '../../../../../types/enum';
+import { DocumentDataModel } from '../../../document-data-model';
+import { PresetListType } from '../../../preset-list-type';
+import { TextX } from '../../text-x';
+import {
+ changeParagraphBulletNestLevel,
+ hasParagraphInTable,
+ setParagraphBullet,
+ setParagraphStyle,
+ switchParagraphBullet,
+ toggleChecklistParagraph,
+} from '../paragraph';
+
+function createParagraphBody(): IDocumentBody {
+ return {
+ dataStream: 'Alpha\rBeta\rGamma\r\n',
+ paragraphs: [
+ {
+ startIndex: 5,
+ paragraphStyle: { horizontalAlign: HorizontalAlign.LEFT },
+ bullet: {
+ listId: 'bullet-prev',
+ listType: PresetListType.BULLET_LIST,
+ nestingLevel: 0,
+ textStyle: { fs: 12 },
+ },
+ },
+ {
+ startIndex: 10,
+ paragraphStyle: { horizontalAlign: HorizontalAlign.LEFT },
+ bullet: {
+ listId: 'check-1',
+ listType: PresetListType.CHECK_LIST,
+ nestingLevel: 1,
+ textStyle: { fs: 16 },
+ },
+ },
+ {
+ startIndex: 16,
+ paragraphStyle: { horizontalAlign: HorizontalAlign.RIGHT },
+ },
+ ],
+ tables: [
+ {
+ startIndex: 8,
+ endIndex: 12,
+ tableId: 'table-1',
+ },
+ ],
+ };
+}
+
+function createDocModel() {
+ return new DocumentDataModel({
+ id: 'paragraph-doc',
+ body: createParagraphBody(),
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ });
+}
+
+describe('paragraph build utils', () => {
+ it('should switch bullets using adjacent paragraph context and remove an existing list when toggled again', () => {
+ const doc = createDocModel();
+ const body = doc.getBody()!;
+ const secondParagraph = body.paragraphs![1] as IParagraph;
+ const firstParagraph = body.paragraphs![0] as IParagraph;
+
+ const adoptBullet = switchParagraphBullet({
+ paragraphs: [secondParagraph],
+ listType: PresetListType.BULLET_LIST,
+ document: doc,
+ });
+ TextX.apply(body, adoptBullet.serialize());
+
+ expect(body.paragraphs?.[1].bullet).toMatchObject({
+ listType: PresetListType.BULLET_LIST,
+ listId: 'bullet-prev',
+ });
+
+ const removeBullet = switchParagraphBullet({
+ paragraphs: [firstParagraph],
+ listType: PresetListType.BULLET_LIST,
+ document: doc,
+ });
+ TextX.apply(body, removeBullet.serialize());
+
+ expect(body.paragraphs?.[0]).toMatchObject({
+ startIndex: 5,
+ paragraphStyle: { horizontalAlign: HorizontalAlign.LEFT },
+ });
+ expect(body.paragraphs?.[0].bullet).toBeUndefined();
+ });
+
+ it('should set bullets, toggle checklist state and change nesting with table-aware limits', () => {
+ const doc = createDocModel();
+ const body = doc.getBody()!;
+ const [, secondParagraph, thirdParagraph] = body.paragraphs! as IParagraph[];
+
+ const setBulletTextX = setParagraphBullet({
+ paragraphs: [thirdParagraph],
+ listType: PresetListType.ORDER_LIST,
+ document: doc,
+ });
+ expect(setParagraphBullet({ paragraphs: [thirdParagraph], listType: PresetListType.ORDER_LIST, segmentId: 'missing', document: new DocumentDataModel({ id: 'missing-segment' }) })).toBe(false);
+ if (setBulletTextX === false) {
+ throw new Error('Expected setParagraphBullet to return TextX actions');
+ }
+ TextX.apply(body, setBulletTextX.serialize());
+ expect(body.paragraphs?.[2].bullet).toMatchObject({
+ listType: PresetListType.ORDER_LIST,
+ nestingLevel: 0,
+ textStyle: { fs: 20 },
+ });
+
+ const toggled = toggleChecklistParagraph({ paragraphIndex: secondParagraph.startIndex, document: doc });
+ expect(toggleChecklistParagraph({ paragraphIndex: 999, document: doc })).toBe(false);
+ expect(toggled).not.toBe(false);
+ if (toggled === false) {
+ throw new Error('Expected toggleChecklistParagraph to return TextX actions');
+ }
+ TextX.apply(body, toggled.serialize());
+ expect(body.paragraphs?.[1].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);
+
+ const changedNest = changeParagraphBulletNestLevel({
+ paragraphs: [body.paragraphs![1] as IParagraph, body.paragraphs![2] as IParagraph],
+ type: 1,
+ document: doc,
+ });
+ TextX.apply(body, changedNest.serialize());
+
+ expect(hasParagraphInTable(body.paragraphs![1] as IParagraph, body.tables!)).toBe(true);
+ expect(hasParagraphInTable(body.paragraphs![2] as IParagraph, body.tables!)).toBe(false);
+ expect(body.paragraphs?.[1].bullet?.nestingLevel).toBe(2);
+ expect(body.paragraphs?.[2].bullet?.nestingLevel).toBe(1);
+ });
+
+ it('should set paragraph styles across selected ranges and optionally add text runs', () => {
+ const doc = createDocModel();
+ const body = doc.getBody()!;
+ const textX = setParagraphStyle({
+ textRanges: [{ startOffset: 6, endOffset: 9, collapsed: false }],
+ document: doc,
+ style: {
+ horizontalAlign: HorizontalAlign.CENTER,
+ },
+ paragraphTextRun: {
+ fs: 18,
+ },
+ });
+
+ expect(textX.serialize()).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ body: expect.objectContaining({
+ textRuns: [expect.objectContaining({ ts: { fs: 18 } })],
+ }),
+ }),
+ ]));
+
+ TextX.apply(body, textX.serialize());
+
+ expect(body.paragraphs?.[1]).toMatchObject({
+ startIndex: 10,
+ paragraphStyle: {
+ horizontalAlign: HorizontalAlign.CENTER,
+ },
+ });
+ });
+});
diff --git a/packages/core/src/docs/data-model/text-x/build-utils/__test__/parse.spec.ts b/packages/core/src/docs/data-model/text-x/build-utils/__test__/parse.spec.ts
new file mode 100644
index 0000000000..792c4b2a3b
--- /dev/null
+++ b/packages/core/src/docs/data-model/text-x/build-utils/__test__/parse.spec.ts
@@ -0,0 +1,55 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { DataStreamTreeTokenType } from '../../../types';
+import { fromPlainText, getPlainText, isEmptyDocument } from '../parse';
+
+describe('parse build utils', () => {
+ it('should strip non-flow tokens and detect empty documents', () => {
+ const dataStream = `${DataStreamTreeTokenType.TABLE_START}Hello${DataStreamTreeTokenType.TABLE_END}\r\n`;
+
+ expect(getPlainText(dataStream)).toBe('Hello');
+ expect(isEmptyDocument(`${DataStreamTreeTokenType.TABLE_START}\r${DataStreamTreeTokenType.TABLE_END}`)).toBe(true);
+ expect(isEmptyDocument('Hello\r\n')).toBe(false);
+ expect(isEmptyDocument()).toBe(true);
+ });
+
+ it('should convert plain text into paragraphs and hyperlink ranges', () => {
+ const body = fromPlainText('https://univer.ai\nSecond line');
+ const singleCharBody = fromPlainText('A');
+
+ expect(body).toMatchObject({
+ dataStream: 'https://univer.ai\rSecond line',
+ paragraphs: [{ startIndex: 17 }],
+ customRanges: [
+ {
+ startIndex: 0,
+ endIndex: 16,
+ rangeType: 0,
+ properties: {
+ url: 'https://univer.ai\nSecond line',
+ },
+ },
+ ],
+ });
+ expect(singleCharBody).toEqual({
+ dataStream: 'A',
+ paragraphs: [],
+ customRanges: [],
+ });
+ });
+});
diff --git a/packages/core/src/facade/__tests__/f-univer.integration.spec.ts b/packages/core/src/facade/__tests__/f-univer.integration.spec.ts
new file mode 100644
index 0000000000..90fe9c1266
--- /dev/null
+++ b/packages/core/src/facade/__tests__/f-univer.integration.spec.ts
@@ -0,0 +1,219 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommand, IDisposable, IDocumentData } from '@univerjs/core';
+import { CommandType, HorizontalAlign, ICommandService, IUndoRedoService, IUniverInstanceService, LocaleService, ThemeService, Univer, UniverInstanceType } from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { FUniver } from '../f-univer';
+
+const TEST_COMMAND_ID = 'test.facade.command';
+const TEST_MUTATION_ID = 'test.facade.mutation';
+
+function createDocData(id: string): Partial<IDocumentData> {
+ return {
+ id,
+ body: {
+ dataStream: 'Hello\r\n',
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
+describe('FUniver integration', () => {
+ let univer: Univer;
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ univer = new Univer();
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, {
+ id: 'sheet-for-facade',
+ name: 'Sheet',
+ styles: {},
+ sheetOrder: ['sheet-1'],
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Sheet1',
+ cellData: {},
+ rowCount: 5,
+ columnCount: 5,
+ },
+ },
+ });
+ univerAPI = FUniver.newAPI(univer);
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should bridge lifecycle, locale, unit and command flows through the facade api', async () => {
+ const injector = univer.__getInjector();
+ const commandService = injector.get(ICommandService);
+ const localeService = injector.get(LocaleService);
+ const themeService = injector.get(ThemeService);
+ const logs: string[] = [];
+ const disposables: IDisposable[] = [];
+
+ commandService.registerCommand({
+ id: TEST_COMMAND_ID,
+ type: CommandType.COMMAND,
+ handler: (_accessor, params?: { value: string }) => params?.value === 'ok',
+ } as ICommand<{ value: string }, boolean>);
+
+ disposables.push(
+ univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => logs.push(`lifecycle:${stage}`)),
+ univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, ({ id }) => logs.push(`before:${id}`)),
+ univerAPI.addEvent(univerAPI.Event.CommandExecuted, ({ id }) => logs.push(`after:${id}`)),
+ univerAPI.addEvent(univerAPI.Event.DocCreated, ({ unitId }) => logs.push(`doc-created:${unitId}`)),
+ univerAPI.addEvent(univerAPI.Event.DocDisposed, ({ unitId }) => logs.push(`doc-disposed:${unitId}`))
+ );
+
+ univerAPI.loadLocales('esES', {
+ facade: { hello: 'Hola {0}' },
+ } as never);
+ univerAPI.setLocale('esES');
+ univerAPI.toggleDarkMode(true);
+
+ expect(localeService.getCurrentLocale()).toBe('esES');
+ expect(localeService.t('facade.hello', 'Univer')).toBe('Hola Univer');
+ expect(themeService.darkMode).toBe(true);
+
+ expect(await univerAPI.executeCommand(TEST_COMMAND_ID, { value: 'ok' })).toBe(true);
+ expect(univerAPI.syncExecuteCommand(TEST_COMMAND_ID, { value: 'ok' })).toBe(true);
+
+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-from-facade'));
+ expect(univerAPI.getCurrentLifecycleStage()).toBeGreaterThanOrEqual(1);
+ expect(univerAPI.disposeUnit(doc.getUnitId())).toBe(true);
+
+ const user = univerAPI.getUserManager().getCurrentUser();
+ expect(user).toBeDefined();
+
+ const blob = univerAPI.newBlob()
+ .setDataFromString('facade-data', 'text/plain')
+ .getAs('text/csv');
+
+ expect(await blob.getDataAsString()).toBe('facade-data');
+ expect(blob.getContentType()).toBe('text/csv');
+ expect((await blob.copyBlob().getBytes()).length).toBeGreaterThan(0);
+
+ const textStyle = univerAPI.newTextStyle({
+ ff: 'Inter',
+ fs: 12,
+ }).build();
+ const paragraph = univerAPI.newParagraphStyle({
+ horizontalAlign: HorizontalAlign.CENTER,
+ textStyle,
+ }).build();
+
+ expect(textStyle.ff).toBe('Inter');
+ expect(paragraph.horizontalAlign).toBe(HorizontalAlign.CENTER);
+ expect(univerAPI.newTextDecoration({ s: univerAPI.Enum.BooleanNumber.TRUE }).build().s).toBe(univerAPI.Enum.BooleanNumber.TRUE);
+ expect(univerAPI.newRichTextValue(createDocData('facade-rich-text') as IDocumentData).getData().body?.dataStream).toBe('Hello\r\n');
+ expect(univerAPI.Util.tools.deleteBlank(' f a c a d e ')).toBe('facade');
+ expect(univerAPI.Util.rectangle.intersects(
+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ { startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }
+ )).toBe(true);
+ expect(univerAPI.Util.numfmt.format('#,##0.00', 1234.5)).toBe('1,234.50');
+
+ expect(logs).toEqual(expect.arrayContaining([
+ `before:${TEST_COMMAND_ID}`,
+ `after:${TEST_COMMAND_ID}`,
+ 'doc-created:doc-from-facade',
+ 'doc-disposed:doc-from-facade',
+ ]));
+
+ disposables.forEach((disposable) => disposable.dispose());
+ });
+
+ it('should support cancelable commands and undo-redo facade events', async () => {
+ const injector = univer.__getInjector();
+ const commandService = injector.get(ICommandService);
+ const undoRedoService = injector.get(IUndoRedoService);
+ injector.get(IUniverInstanceService).focusUnit('sheet-for-facade');
+ const executed: string[] = [];
+ const undoRedoLogs: string[] = [];
+
+ commandService.registerCommand({
+ id: TEST_COMMAND_ID,
+ type: CommandType.COMMAND,
+ handler: () => {
+ executed.push('command');
+ return true;
+ },
+ } as ICommand);
+ commandService.registerCommand({
+ id: TEST_MUTATION_ID,
+ type: CommandType.MUTATION,
+ handler: (_accessor, params?: { label: string }) => {
+ executed.push(params?.label ?? 'mutation');
+ return true;
+ },
+ } as ICommand<{ label: string }, boolean>);
+
+ const cancelCommand = univerAPI.addEvent(univerAPI.Event.BeforeCommandExecute, (event) => {
+ if (event.id === TEST_COMMAND_ID) {
+ event.cancel = true;
+ }
+ });
+
+ expect(await univerAPI.executeCommand(TEST_COMMAND_ID)).toBe(false);
+ expect(executed).toEqual([]);
+ cancelCommand.dispose();
+
+ undoRedoService.pushUndoRedo({
+ unitID: 'sheet-for-facade',
+ id: 'undo-item',
+ undoMutations: [{ id: TEST_MUTATION_ID, params: { label: 'undo' } }],
+ redoMutations: [{ id: TEST_MUTATION_ID, params: { label: 'redo' } }],
+ });
+
+ const beforeUndo = univerAPI.addEvent(univerAPI.Event.BeforeUndo, (event) => {
+ undoRedoLogs.push(`before-undo:${event.id}`);
+ event.cancel = true;
+ });
+
+ expect(await univerAPI.undo()).toBe(false);
+ expect(executed).toEqual([]);
+
+ beforeUndo.dispose();
+
+ const beforeRedo = univerAPI.addEvent(univerAPI.Event.BeforeRedo, ({ id }) => undoRedoLogs.push(`before-redo:${id}`));
+ const undoEvent = univerAPI.addEvent(univerAPI.Event.Undo, ({ id }) => undoRedoLogs.push(`undo:${id}`));
+ const redoEvent = univerAPI.addEvent(univerAPI.Event.Redo, ({ id }) => undoRedoLogs.push(`redo:${id}`));
+
+ expect(await univerAPI.undo()).toBe(true);
+ expect(await univerAPI.redo()).toBe(true);
+ expect(executed).toEqual(['undo', 'redo']);
+ expect(undoRedoLogs).toEqual(expect.arrayContaining([
+ 'before-undo:univer.command.undo',
+ 'undo:univer.command.undo',
+ 'before-redo:univer.command.redo',
+ 'redo:univer.command.redo',
+ ]));
+
+ beforeRedo.dispose();
+ undoEvent.dispose();
+ redoEvent.dispose();
+ });
+});
diff --git a/packages/core/src/facade/f-univer.ts b/packages/core/src/facade/f-univer.ts
index 43a4386e26..ed9d0c2367 100644
--- a/packages/core/src/facade/f-univer.ts
+++ b/packages/core/src/facade/f-univer.ts
@@ -519,7 +519,7 @@ export class FUniver extends Disposable {
* ```
*/
newBlob(): FBlob {
- return this._injector.createInstance(FBlob);
+ return this._injector.createInstance(FBlob, null);
}
/**
diff --git a/packages/core/src/services/__tests__/authz-resource.integration.spec.ts b/packages/core/src/services/__tests__/authz-resource.integration.spec.ts
new file mode 100644
index 0000000000..24f913417d
--- /dev/null
+++ b/packages/core/src/services/__tests__/authz-resource.integration.spec.ts
@@ -0,0 +1,180 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Univer } from '../../univer';
+import { UnitAction, UnitObject, UnitRole } from '@univerjs/protocol';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { UniverInstanceType } from '../../common/unit';
+import { IAuthzIoService } from '../authz-io/type';
+import { IUniverInstanceService } from '../instance/instance.service';
+import { IMentionIOService } from '../mention-io/type';
+import { IResourceLoaderService } from '../resource-loader/type';
+import { UserManagerService } from '../user-manager/user-manager.service';
+import { createTestBed } from './create-test-bed';
+
+describe('Authz/resource integration', () => {
+ let univer: Univer;
+ let unitId: string;
+
+ beforeEach(() => {
+ const instance = createTestBed();
+ univer = instance.univer;
+ unitId = instance.unitId;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should persist and reload permission resources through a real workbook lifecycle', async () => {
+ const injector = univer.__getInjector();
+ const authzIoService = injector.get(IAuthzIoService);
+ const resourceLoaderService = injector.get(IResourceLoaderService);
+ const userManagerService = injector.get(UserManagerService);
+
+ userManagerService.setCurrentUser({
+ userID: 'Owner_real-user',
+ name: 'Owner User',
+ avatar: '',
+ });
+
+ const objectID = await authzIoService.create({
+ objectType: UnitObject.SelectRange,
+ selectRangeObject: {
+ unitID: unitId,
+ name: 'Protected range',
+ collaborators: [],
+ scope: undefined,
+ },
+ });
+
+ expect(await authzIoService.allowed({ unitID: unitId, objectID, objectType: UnitObject.SelectRange, actions: [UnitAction.Edit] })).toEqual([
+ { action: UnitAction.Edit, allowed: true },
+ ]);
+
+ await authzIoService.update({
+ objectType: UnitObject.SelectRange,
+ objectID,
+ unitID: unitId,
+ share: undefined,
+ name: 'Protected range',
+ strategies: [{ action: UnitAction.Edit, role: UnitRole.Reader }],
+ scope: undefined,
+ collaborators: undefined,
+ });
+
+ expect(await authzIoService.allowed({ unitID: unitId, objectID, objectType: UnitObject.SelectRange, actions: [UnitAction.Edit] })).toEqual([
+ { action: UnitAction.Edit, allowed: false },
+ ]);
+
+ const listed = await authzIoService.list({
+ unitID: unitId,
+ objectIDs: [objectID],
+ actions: [UnitAction.Edit, UnitAction.View],
+ });
+
+ expect(listed).toHaveLength(1);
+ expect(listed[0].name).toBe('Protected range');
+ expect(listed[0].actions).toContainEqual({ action: UnitAction.Edit, allowed: false });
+
+ const batched = await authzIoService.batchAllowed([
+ { unitID: unitId, objectID, objectType: UnitObject.SelectRange, actions: [UnitAction.Edit] },
+ { unitID: unitId, objectID: 'missing', objectType: UnitObject.SelectRange, actions: [UnitAction.View] },
+ ]);
+
+ expect(batched[0].actions).toEqual([{ action: UnitAction.Edit, allowed: false }]);
+ expect(batched[1].actions).toEqual([{ action: UnitAction.View, allowed: true }]);
+
+ expect(await authzIoService.listCollaborators({ unitID: unitId, objectID })).toEqual([]);
+ expect(await authzIoService.listRoles({ objectType: UnitObject.SelectRange })).toEqual({ roles: [], actions: [] });
+ await expect(authzIoService.createCollaborator({ unitID: unitId, objectID } as never)).resolves.toBeUndefined();
+ await expect(authzIoService.updateCollaborator({ unitID: unitId, objectID } as never)).resolves.toBeUndefined();
+ await expect(authzIoService.deleteCollaborator({ unitID: unitId, objectID } as never)).resolves.toBeUndefined();
+ await expect(authzIoService.putCollaborators({ unitID: unitId, objectID, collaborators: [] })).resolves.toBeUndefined();
+
+ const snapshot = resourceLoaderService.saveUnit(unitId);
+ const authzResource = snapshot?.resources.find((resource) => resource.name === 'SHEET_AuthzIoMockService_PLUGIN');
+
+ expect(authzResource?.data).toContain(objectID);
+
+ injector.get(IUniverInstanceService).disposeUnit(unitId);
+
+ const unloaded = await authzIoService.list({
+ unitID: unitId,
+ objectIDs: [objectID],
+ actions: [UnitAction.Edit],
+ });
+
+ expect(unloaded[0].name).toBe('');
+ expect(unloaded[0].actions).toEqual([{ action: UnitAction.Edit, allowed: false }]);
+
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, snapshot!);
+
+ const reloaded = await authzIoService.list({
+ unitID: unitId,
+ objectIDs: [objectID],
+ actions: [UnitAction.Edit],
+ });
+
+ expect(reloaded[0].name).toBe('Protected range');
+ expect(reloaded[0].actions).toEqual([{ action: UnitAction.Edit, allowed: false }]);
+ });
+
+ it('should expose current user data consistently through mention and user services', async () => {
+ const injector = univer.__getInjector();
+ const userManagerService = injector.get(UserManagerService);
+ const mentionIOService = injector.get(IMentionIOService);
+ const userEvents: string[] = [];
+
+ userManagerService.userChange$.subscribe((event) => {
+ userEvents.push(event.type);
+ });
+
+ userManagerService.setCurrentUser({
+ userID: 'Owner_alice',
+ name: 'Alice',
+ avatar: 'alice.png',
+ });
+ userManagerService.addUser({ userID: 'Editor_bob', name: 'Bob' });
+
+ expect(userManagerService.getCurrentUser().name).toBe('Alice');
+ expect(userManagerService.getUser('Editor_bob')?.name).toBe('Bob');
+ expect(userManagerService.list()).toHaveLength(2);
+
+ const mentionResult = await mentionIOService.list({ page: 2, size: 5 });
+ expect(mentionResult.page).toBe(2);
+ expect(mentionResult.size).toBe(5);
+ expect(mentionResult.list[0].mentions[0]).toMatchObject({
+ objectId: 'Owner_alice',
+ label: 'Alice',
+ metadata: {
+ icon: 'alice.png',
+ },
+ });
+
+ let callbackCalled = false;
+ expect(userManagerService.getUser('missing-user', () => {
+ callbackCalled = true;
+ })).toBeUndefined();
+ expect(callbackCalled).toBe(true);
+
+ userManagerService.delete('Editor_bob');
+ userManagerService.clear();
+
+ expect(userManagerService.list()).toEqual([]);
+ expect(userEvents).toEqual(['add', 'add', 'delete', 'clear']);
+ });
+});
diff --git a/packages/core/src/services/__tests__/permission.spec.ts b/packages/core/src/services/__tests__/permission.spec.ts
index 32a0683196..71aec6ec82 100644
--- a/packages/core/src/services/__tests__/permission.spec.ts
+++ b/packages/core/src/services/__tests__/permission.spec.ts
@@ -15,11 +15,12 @@
*/
import type { Univer } from '../../univer';
-import type { IPermissionPoint, PermissionStatus } from '../permission/type';
+import type { IPermissionPoint } from '../permission/type';
import { UnitAction, UnitObject } from '@univerjs/protocol';
-import { firstValueFrom } from 'rxjs';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { BehaviorSubject, firstValueFrom } from 'rxjs';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { PermissionService } from '../permission/permission.service';
+import { PermissionStatus } from '../permission/type';
import { createTestBed } from './create-test-bed';
class TestPermissionPoint implements IPermissionPoint {
@@ -34,15 +35,17 @@ class TestPermissionPoint implements IPermissionPoint {
}
}
-describe('Test array util function', () => {
+describe('Test permission service', () => {
let univer: Univer;
let permissionService: PermissionService;
+
beforeEach(() => {
univer?.dispose();
const instance = createTestBed([[PermissionService]]);
univer = instance.univer;
permissionService = instance.get(PermissionService);
});
+
it('test get permission from permissionService', () => {
const point = new TestPermissionPoint('test');
permissionService.addPermissionPoint(point);
@@ -79,4 +82,50 @@ describe('Test array util function', () => {
const v = await firstValueFrom(result$);
expect(v).toEqual([point1, point2]);
});
+
+ it('should manage permission updates, duplicates and visibility flags', () => {
+ const point = new TestPermissionPoint('subject');
+ const pointSubject = new BehaviorSubject<IPermissionPoint<boolean>>(point);
+ const updates: string[] = [];
+ const warningSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
+ const subscription = permissionService.permissionPointUpdate$.subscribe((permission) => {
+ updates.push(`${permission.id}:${String(permission.value)}`);
+ });
+
+ expect(permissionService.getShowComponents()).toBe(true);
+ permissionService.setShowComponents(false);
+ expect(permissionService.getShowComponents()).toBe(false);
+
+ expect(permissionService.addPermissionPoint(pointSubject)).toBe(true);
+ expect(permissionService.addPermissionPoint(point)).toBe(false);
+
+ permissionService.updatePermissionPoint(point.id, true);
+
+ expect(permissionService.getPermissionPoint(point.id)).toMatchObject({
+ value: true,
+ status: PermissionStatus.DONE,
+ });
+ expect(updates).toEqual([
+ `${point.id}:false`,
+ `${point.id}:true`,
+ ]);
+
+ const snapshot = permissionService.getAllPermissionPoint();
+ snapshot.clear();
+ expect(permissionService.getAllPermissionPoint().size).toBe(1);
+
+ permissionService.deletePermissionPoint(point.id);
+ expect(permissionService.getPermissionPoint(point.id)).toBeUndefined();
+
+ permissionService.clearPermissionMap();
+ expect(permissionService.getAllPermissionPoint().size).toBe(0);
+
+ subscription.unsubscribe();
+ warningSpy.mockRestore();
+ });
+
+ it('should throw clear errors when composing missing permission points', () => {
+ expect(() => permissionService.composePermission(['missing.permission'])).toThrow('[PermissionService]: missing.permission permissionPoint does not exist!');
+ expect(() => permissionService.composePermission$(['missing.permission'])).toThrow('[PermissionService]: missing.permission permissionPoint does not exist!');
+ });
});
diff --git a/packages/core/src/services/__tests__/resources.spec.ts b/packages/core/src/services/__tests__/resources.spec.ts
index 7b9c9ab31c..0aeb13df89 100644
--- a/packages/core/src/services/__tests__/resources.spec.ts
+++ b/packages/core/src/services/__tests__/resources.spec.ts
@@ -14,13 +14,33 @@
* limitations under the License.
*/
+import type { IDocumentData } from '../../types/interfaces';
import type { Univer } from '../../univer';
-import { beforeEach, describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '../../common/const';
import { UniverInstanceType } from '../../common/unit';
+import { IUniverInstanceService } from '../instance/instance.service';
import { IResourceLoaderService } from '../resource-loader/type';
import { IResourceManagerService } from '../resource-manager/type';
import { createTestBed } from './create-test-bed';
+function createDocData(id: string, resources?: NonNullable<IDocumentData['resources']>): Partial<IDocumentData> {
+ return {
+ id,
+ resources,
+ body: {
+ dataStream: 'Hello\r\n',
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
describe('Test resources service', () => {
let univer: Univer;
@@ -34,7 +54,7 @@ describe('Test resources service', () => {
const resourceManagerService = univer.__getInjector().get(IResourceManagerService);
const resourceLoaderService = univer.__getInjector().get(IResourceLoaderService);
const pluginName = 'SHEET_test_PLUGIN';
- const model: Record<string, any> = {};
+ const model: Record<string, unknown> = {};
resourceManagerService.registerPluginResource({
pluginName,
businesses: [UniverInstanceType.UNIVER_SHEET],
@@ -47,7 +67,6 @@ describe('Test resources service', () => {
const resource = snapshot?.resources.find((item) => item.name === pluginName);
expect(!!resource).toBeTruthy();
expect(resource?.data).toBe(JSON.stringify(model));
- // update model
model.a = 123;
const snapshotRev1 = resourceLoaderService.saveUnit('test');
const resourceRev1 = snapshotRev1?.resources.find((item) => item.name === pluginName);
@@ -57,17 +76,76 @@ describe('Test resources service', () => {
it('test resources load', () => {
const resourceManagerService = univer.__getInjector().get(IResourceManagerService);
const pluginName = 'SHEET_test_PLUGIN';
- const model: Record<string, any> = {};
+ const model: Record<string, unknown> = {};
let result = '';
resourceManagerService.registerPluginResource({
pluginName,
businesses: [UniverInstanceType.UNIVER_SHEET],
- onLoad: (v, r) => { result = r; },
+ onLoad: (_unitId, resource) => { result = resource; },
onUnLoad: () => { },
toJson: () => JSON.stringify(model),
parseJson: (bytes) => JSON.parse(bytes),
});
- // The value in the snapshot
expect(result).toEqual({ a: 123 });
});
+
+ it('should load and unload workbook/doc resources through the real unit lifecycle', () => {
+ const injector = univer.__getInjector();
+ const resourceManagerService = injector.get(IResourceManagerService);
+ const resourceLoaderService = injector.get(IResourceLoaderService);
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ const loads: Array<[string, string]> = [];
+ const unloads: string[] = [];
+
+ resourceManagerService.registerPluginResource({
+ pluginName: 'DOC_test_PLUGIN',
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ onLoad: (unitId, model: { kind: string }) => loads.push([unitId, model.kind]),
+ onUnLoad: (unitId) => unloads.push(unitId),
+ toJson: (unitId) => JSON.stringify({ unitId, kind: 'saved' }),
+ parseJson: (bytes) => JSON.parse(bytes),
+ });
+
+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-resource', [
+ { name: 'DOC_test_PLUGIN', data: '{"kind":"doc"}' },
+ ]));
+ const internalDoc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, [
+ { name: 'DOC_test_PLUGIN', data: '{"kind":"internal"}' },
+ ]));
+
+ expect(loads).toContainEqual(['doc-resource', 'doc']);
+ expect(loads).not.toContainEqual([DOCS_NORMAL_EDITOR_UNIT_ID_KEY, 'internal']);
+ expect(resourceLoaderService.saveUnit('missing-unit')).toBeNull();
+ expect(resourceLoaderService.saveUnit<IDocumentData>('doc-resource')?.resources).toEqual([
+ { name: 'DOC_test_PLUGIN', data: JSON.stringify({ unitId: 'doc-resource', kind: 'saved' }) },
+ ]);
+
+ expect(univerInstanceService.disposeUnit(doc.getUnitId())).toBe(true);
+ expect(univerInstanceService.disposeUnit(internalDoc.getUnitId())).toBe(true);
+ expect(unloads).toEqual(expect.arrayContaining(['doc-resource', DOCS_NORMAL_EDITOR_UNIT_ID_KEY]));
+ });
+
+ it('should ignore malformed persisted resource payloads when hooks are registered later', () => {
+ const resourceManagerService = univer.__getInjector().get(IResourceManagerService);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ const onLoad = vi.fn();
+
+ univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-bad-resource', [
+ { name: 'DOC_BAD_PLUGIN', data: '{bad json}' },
+ ]));
+
+ resourceManagerService.registerPluginResource({
+ pluginName: 'DOC_BAD_PLUGIN',
+ businesses: [UniverInstanceType.UNIVER_DOC],
+ onLoad,
+ onUnLoad: () => undefined,
+ toJson: () => '{}',
+ parseJson: (bytes) => JSON.parse(bytes),
+ });
+
+ expect(onLoad).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith('Load Document{doc-bad-resource} Resources{DOC_BAD_PLUGIN} Data Error.');
+
+ errorSpy.mockRestore();
+ });
});
diff --git a/packages/core/src/services/command/__tests__/command.service.spec.ts b/packages/core/src/services/command/__tests__/command.service.spec.ts
index 88164c5171..fda92c5534 100644
--- a/packages/core/src/services/command/__tests__/command.service.spec.ts
+++ b/packages/core/src/services/command/__tests__/command.service.spec.ts
@@ -161,7 +161,7 @@ describe('Test CommandService', () => {
commandService.syncExecuteCommand(anotherCommandID);
}).toThrowError(`[CommandService]: command "${anotherCommandID}" is not registered.`);
- expect(commandService.executeCommand(anotherCommandID)).rejects.toThrowError(
+ await expect(commandService.executeCommand(anotherCommandID)).rejects.toThrowError(
`[CommandService]: command "${anotherCommandID}" is not registered.`
);
});
@@ -249,7 +249,7 @@ describe('Test CommandService', () => {
expect(str).toEqual(['A', 'B', 'B']);
secondDisposable.dispose();
- expect(commandService.executeCommand(commandID)).rejects.toThrowError(
+ await expect(commandService.executeCommand(commandID)).rejects.toThrowError(
`[CommandService]: command "${commandID}" is not registered.`
);
});
diff --git a/packages/core/src/shared/__tests__/r-tree.integration.spec.ts b/packages/core/src/shared/__tests__/r-tree.integration.spec.ts
new file mode 100644
index 0000000000..49af727b62
--- /dev/null
+++ b/packages/core/src/shared/__tests__/r-tree.integration.spec.ts
@@ -0,0 +1,77 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRange } from '../../sheets/typedef';
+import { describe, expect, it } from 'vitest';
+import { RTree } from '../r-tree';
+
+describe('RTree integration', () => {
+ it('should index both single-cell and ranged items and support removal and serialization', () => {
+ const tree = new RTree(true);
+
+ const unitId = 'unit-1';
+ const sheetId = 'sheet-1';
+
+ const oneCellRange: IRange = { startRow: 1, endRow: 1, startColumn: 2, endColumn: 2 };
+ const blockRange: IRange = { startRow: 0, endRow: 3, startColumn: 0, endColumn: 4 };
+ const nanRange: IRange = { startRow: Number.NaN, endRow: Number.NaN, startColumn: Number.NaN, endColumn: Number.NaN };
+
+ tree.bulkInsert([
+ { id: 1, unitId, sheetId, range: oneCellRange },
+ { id: 2, unitId, sheetId, range: blockRange },
+ { id: 3, unitId, sheetId, range: nanRange },
+ ]);
+
+ // Without kd-tree, one-cell items are intentionally skipped.
+ expect(Array.from(tree.searchGenerator({ unitId, sheetId, range: oneCellRange }))).toEqual([2, 3]);
+
+ tree.openKdTree();
+ expect(Array.from(tree.searchGenerator({ unitId, sheetId, range: oneCellRange }))).toEqual([1, 2, 3]);
+
+ const result = tree.bulkSearch([
+ { unitId, sheetId, range: oneCellRange },
+ { unitId, sheetId, range: blockRange },
+ ]);
+
+ expect(Array.from(result.values()).sort()).toEqual([1, 2, 3]);
+
+ const excepted = tree.bulkSearch([{ unitId, sheetId, range: blockRange }], new Set([2]));
+ expect(Array.from(excepted.values()).sort()).toEqual([1, 3]);
+
+ tree.remove({ id: 1, unitId, sheetId, range: oneCellRange });
+ expect(Array.from(tree.searchGenerator({ unitId, sheetId, range: oneCellRange }))).toEqual([2, 3]);
+
+ tree.remove({ id: 2, unitId, sheetId, range: blockRange });
+ expect(Array.from(tree.searchGenerator({ unitId, sheetId, range: blockRange }))).toEqual([3]);
+
+ tree.closeKdTree();
+ expect(Array.from(tree.searchGenerator({ unitId, sheetId, range: oneCellRange }))).toEqual([3]);
+
+ tree.removeById(unitId, sheetId);
+ expect(Array.from(tree.searchGenerator({ unitId, sheetId, range: blockRange }))).toEqual([]);
+
+ tree.insert({ id: 4, unitId, sheetId, range: blockRange });
+ const serialized = tree.toJSON();
+ const restored = new RTree();
+ restored.fromJSON(serialized);
+
+ expect(Array.from(restored.searchGenerator({ unitId, sheetId, range: oneCellRange }))).toEqual([4]);
+
+ restored.removeById(unitId);
+ expect(Array.from(restored.searchGenerator({ unitId, sheetId, range: blockRange }))).toEqual([]);
+ restored.dispose();
+ });
+});
diff --git a/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts b/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts
new file mode 100644
index 0000000000..0c2b44b747
--- /dev/null
+++ b/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts
@@ -0,0 +1,286 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Injector } from '../../common/di';
+import type { IDocumentData, IDocumentRenderConfig, IPaddingData } from '../../types/interfaces';
+import type { IWorkbookData } from '../typedef';
+import { afterEach, describe, expect, it } from 'vitest';
+import { IConfigService } from '../../services/config/config.service';
+import { IContextService } from '../../services/context/context.service';
+import { LocaleService } from '../../services/locale/locale.service';
+import { BooleanNumber, HorizontalAlign } from '../../types/enum';
+import { LocaleType } from '../../types/enum/locale-type';
+import { SheetSkeleton } from '../sheet-skeleton';
+import { RANGE_TYPE } from '../typedef';
+import { createCoreTestBed } from './create-core-test-bed';
+
+const workbookDataFactory = (): IWorkbookData => ({
+ id: 'styled-workbook',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'Styled workbook',
+ sheetOrder: ['sheet-1'],
+ styles: {},
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Styled sheet',
+ rowCount: 8,
+ columnCount: 6,
+ defaultColumnWidth: 72,
+ defaultRowHeight: 24,
+ mergeData: [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL }],
+ cellData: {
+ 0: {
+ 3: { v: 'Stop overflow' },
+ },
+ 1: {
+ 1: { v: 'Merged main' },
+ },
+ },
+ rowData: {
+ 0: { h: 28 },
+ 4: { hd: BooleanNumber.TRUE },
+ },
+ columnData: {
+ 1: { w: 120 },
+ 4: { hd: BooleanNumber.TRUE },
+ },
+ rowHeader: { width: 46 },
+ columnHeader: { height: 28 },
+ },
+ },
+});
+
+class TestableSheetSkeleton extends SheetSkeleton {
+ getOverflowBoundPublic(row: number, startColumn: number, endColumn: number, contentWidth: number, horizontalAlign = HorizontalAlign.LEFT) {
+ return this._getOverflowBound(row, startColumn, endColumn, contentWidth, horizontalAlign);
+ }
+
+ hasUnMergedCellInRowPublic(rowIndex: number, startColumn: number, endColumn: number) {
+ return this._hasUnMergedCellInRow(rowIndex, startColumn, endColumn);
+ }
+
+ updateConfigAndGetDocumentModelPublic(
+ documentData: IDocumentData,
+ horizontalAlign: HorizontalAlign,
+ paddingData: IPaddingData,
+ renderConfig?: IDocumentRenderConfig
+ ) {
+ return this._updateConfigAndGetDocumentModel(documentData, horizontalAlign, paddingData, renderConfig);
+ }
+}
+
+describe('SheetSkeleton integration', () => {
+ const disposables: Array<() => void> = [];
+
+ afterEach(() => {
+ while (disposables.length) {
+ disposables.pop()?.();
+ }
+ });
+
+ it('should calculate merged layout coordinates and offsets from a worksheet snapshot', () => {
+ const testBed = createCoreTestBed(workbookDataFactory());
+ const injector = testBed.univer.__getInjector();
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const skeleton = new SheetSkeleton(
+ worksheet,
+ testBed.sheet.getStyles(),
+ injector.get(LocaleService),
+ injector.get(IContextService),
+ injector.get(IConfigService),
+ injector as Injector
+ ).calculate()! as TestableSheetSkeleton;
+
+ disposables.push(() => testBed.univer.dispose());
+
+ expect(skeleton.getLocation()).toEqual(['styled-workbook', 'sheet-1']);
+ expect(skeleton.rowHeightAccumulation).toEqual([28, 52, 76, 100, 100, 124, 148, 172]);
+ expect(skeleton.columnWidthAccumulation).toEqual([72, 192, 264, 336, 336, 408]);
+ expect(skeleton.rowTotalHeight).toBe(172);
+ expect(skeleton.columnTotalWidth).toBe(408);
+ expect(skeleton.rowHeaderWidth).toBe(46);
+ expect(skeleton.columnHeaderHeight).toBe(28);
+ expect(skeleton.getRowCount()).toBe(8);
+ expect(skeleton.getColumnCount()).toBe(6);
+
+ expect(skeleton.expandRangeByMerge({ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2, rangeType: RANGE_TYPE.NORMAL })).toEqual({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ });
+ expect(skeleton.expandRangeByMerge({ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2, rangeType: RANGE_TYPE.NORMAL }, true)).toEqual({
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ });
+
+ expect(skeleton.getNoMergeCellWithCoordByIndex(1, 1, false)).toEqual({
+ startY: 28,
+ endY: 52,
+ startX: 72,
+ endX: 192,
+ });
+ expect(skeleton.getCellWithCoordByIndex(1, 1)).toEqual({
+ actualRow: 1,
+ actualColumn: 1,
+ startY: 56,
+ endY: 80,
+ startX: 118,
+ endX: 238,
+ isMerged: false,
+ isMergedMainCell: true,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ startY: 56,
+ endY: 104,
+ startX: 118,
+ endX: 310,
+ },
+ });
+
+ expect(skeleton.getOffsetByColumn(1)).toBe(238);
+ expect(skeleton.getOffsetByColumn(-1)).toBe(46);
+ expect(skeleton.getOffsetByColumn(99)).toBe(454);
+ expect(skeleton.getOffsetByRow(1)).toBe(80);
+ expect(skeleton.getOffsetByRow(-1)).toBe(28);
+ expect(skeleton.getOffsetByRow(99)).toBe(200);
+ expect(skeleton.getOffsetRelativeToRowCol(100, 50)).toEqual({
+ row: 1,
+ column: 1,
+ rowOffset: 22,
+ columnOffset: 28,
+ });
+ });
+
+ it('should resolve viewport offsets back to visible cells across hidden rows and columns', () => {
+ const testBed = createCoreTestBed(workbookDataFactory());
+ const injector = testBed.univer.__getInjector();
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const skeleton = new SheetSkeleton(
+ worksheet,
+ testBed.sheet.getStyles(),
+ injector.get(LocaleService),
+ injector.get(IContextService),
+ injector.get(IConfigService),
+ injector as Injector
+ ).calculate()! as TestableSheetSkeleton;
+
+ disposables.push(() => testBed.univer.dispose());
+
+ expect(skeleton.getCellIndexByOffset(150, 60, 1, 1, { x: 0, y: 0 })).toEqual({ row: 1, column: 1 });
+ expect(skeleton.getCellByOffset(150, 60, 1, 1, { x: 0, y: 0 })).toMatchObject({
+ actualRow: 1,
+ actualColumn: 1,
+ isMergedMainCell: true,
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ });
+ expect(skeleton.getCellWithCoordByOffset(150, 60, 1, 1, { x: 0, y: 0 })).toMatchObject({
+ actualRow: 1,
+ actualColumn: 1,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 2,
+ },
+ });
+
+ expect(skeleton.getCellIndexByOffset(382, 128, 1, 1, { x: 0, y: 0 }, { firstMatch: true })).toEqual({ row: 5, column: 5 });
+ expect(skeleton.getCellIndexByOffset(252, 96, 2, 2, { x: 24, y: 12 })).toEqual({ row: 1, column: 1 });
+ expect(skeleton.getRowIndexByOffsetY(128, 1, { x: 0, y: 0 }, { firstMatch: true })).toBe(5);
+ expect(skeleton.getColumnIndexByOffsetX(382, 1, { x: 0, y: 0 }, { firstMatch: true })).toBe(5);
+ });
+
+ it('should compute overflow bounds and document render config through the real skeleton instance', () => {
+ const testBed = createCoreTestBed(workbookDataFactory());
+ const injector = testBed.univer.__getInjector();
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const skeleton = new TestableSheetSkeleton(
+ worksheet,
+ testBed.sheet.getStyles(),
+ injector.get(LocaleService),
+ injector.get(IContextService),
+ injector.get(IConfigService),
+ injector as Injector
+ ).calculate()! as TestableSheetSkeleton;
+
+ disposables.push(() => testBed.univer.dispose());
+
+ expect(skeleton.getOverflowBoundPublic(0, 0, 3, 100)).toBe(1);
+ expect(skeleton.getOverflowBoundPublic(0, 0, 3, 500)).toBe(2);
+ expect(skeleton.hasUnMergedCellInRowPublic(1, 1, 2)).toBe(false);
+ expect(skeleton.hasUnMergedCellInRowPublic(1, 0, 2)).toBe(true);
+
+ const docData: IDocumentData = {
+ id: 'doc-in-skeleton',
+ body: {
+ dataStream: 'Hello\r\n',
+ paragraphs: [{ startIndex: 5 }],
+ },
+ documentStyle: {
+ marginTop: 9,
+ marginBottom: 9,
+ marginLeft: 9,
+ marginRight: 9,
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.LEFT,
+ },
+ },
+ };
+ const updatedModel = skeleton.updateConfigAndGetDocumentModelPublic(
+ docData,
+ HorizontalAlign.CENTER,
+ { t: 1, r: 4, b: 3, l: 2 },
+ { horizontalAlign: HorizontalAlign.CENTER }
+ );
+
+ expect(skeleton.updateConfigAndGetDocumentModelPublic({ id: 'no-body' } as IDocumentData, HorizontalAlign.CENTER, { t: 0, r: 0, b: 0, l: 0 }, { horizontalAlign: HorizontalAlign.CENTER })).toBeUndefined();
+ expect(skeleton.updateConfigAndGetDocumentModelPublic(docData, HorizontalAlign.CENTER, { t: 0, r: 0, b: 0, l: 0 })).toBeUndefined();
+ expect(updatedModel?.getSnapshot()).toMatchObject({
+ documentStyle: {
+ marginTop: 1,
+ marginBottom: 3,
+ marginLeft: 2,
+ marginRight: 4,
+ pageSize: {
+ width: Number.POSITIVE_INFINITY,
+ height: Number.POSITIVE_INFINITY,
+ },
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.CENTER,
+ },
+ },
+ body: {
+ paragraphs: [{
+ startIndex: 5,
+ paragraphStyle: {
+ horizontalAlign: HorizontalAlign.CENTER,
+ },
+ }],
+ },
+ });
+ });
+});
diff --git a/packages/core/src/sheets/__tests__/util.spec.ts b/packages/core/src/sheets/__tests__/util.spec.ts
new file mode 100644
index 0000000000..220ce3db35
--- /dev/null
+++ b/packages/core/src/sheets/__tests__/util.spec.ts
@@ -0,0 +1,140 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { BaselineOffset, BooleanNumber, HorizontalAlign, VerticalAlign, WrapStrategy } from '../../types/enum';
+import { CustomRangeType } from '../../types/interfaces';
+import {
+ addLinkToDocumentModel,
+ createDocumentModelWithStyle,
+ extractOtherStyle,
+ getEmptyCell,
+ getFontFormat,
+ isNotNullOrUndefined,
+ isRangesEqual,
+ isUnitRangesEqual,
+} from '../util';
+
+describe('sheet util helpers', () => {
+ it('should create document models with cell styles and render config', () => {
+ const documentModel = createDocumentModelWithStyle('Cell', { ff: 'Inter', fs: 12, va: BaselineOffset.SUPERSCRIPT }, {
+ textRotation: { a: 35 },
+ horizontalAlign: HorizontalAlign.CENTER,
+ verticalAlign: VerticalAlign.MIDDLE,
+ wrapStrategy: WrapStrategy.WRAP,
+ paddingData: { t: 1, r: 4, b: 3, l: 2 },
+ });
+
+ expect(documentModel.getBody()).toMatchObject({
+ dataStream: 'Cell\r\n',
+ textRuns: [{ st: 0, ed: 4, ts: { ff: 'Inter', fs: 12, va: BaselineOffset.SUPERSCRIPT } }],
+ paragraphs: [{ startIndex: 4, paragraphStyle: { horizontalAlign: HorizontalAlign.CENTER } }],
+ });
+ expect(documentModel.getSnapshot().documentStyle).toMatchObject({
+ marginTop: 1,
+ marginRight: 4,
+ marginBottom: 3,
+ marginLeft: 2,
+ renderConfig: {
+ horizontalAlign: HorizontalAlign.CENTER,
+ verticalAlign: VerticalAlign.MIDDLE,
+ centerAngle: 0,
+ vertexAngle: 35,
+ wrapStrategy: WrapStrategy.WRAP,
+ },
+ });
+ expect(documentModel.getDrawingsOrder()).toEqual([]);
+ });
+
+ it('should extract cell style fragments and enrich document links once', () => {
+ const style = {
+ ff: 'Inter',
+ fs: 14,
+ it: BooleanNumber.TRUE,
+ bl: BooleanNumber.TRUE,
+ ul: { s: BooleanNumber.TRUE },
+ st: { s: BooleanNumber.TRUE },
+ ol: { s: BooleanNumber.TRUE },
+ cl: { rgb: '#123456' },
+ tr: { a: 45 },
+ td: 1,
+ ht: HorizontalAlign.RIGHT,
+ vt: VerticalAlign.BOTTOM,
+ tb: WrapStrategy.WRAP,
+ pd: { t: 1, r: 2, b: 3, l: 4 },
+ } as const;
+ const documentModel = createDocumentModelWithStyle('Link', { ff: 'Inter' }, {});
+
+ expect(extractOtherStyle(style)).toEqual({
+ textRotation: { a: 45 },
+ textDirection: 1,
+ horizontalAlign: HorizontalAlign.RIGHT,
+ verticalAlign: VerticalAlign.BOTTOM,
+ wrapStrategy: WrapStrategy.WRAP,
+ paddingData: { t: 1, r: 2, b: 3, l: 4 },
+ });
+ expect(getFontFormat(style)).toEqual({
+ ff: 'Inter',
+ fs: 14,
+ it: BooleanNumber.TRUE,
+ bl: BooleanNumber.TRUE,
+ ul: { s: BooleanNumber.TRUE },
+ st: { s: BooleanNumber.TRUE },
+ ol: { s: BooleanNumber.TRUE },
+ cl: { rgb: '#123456' },
+ });
+
+ addLinkToDocumentModel(documentModel, 'https://univer.ai', 'link-1');
+ addLinkToDocumentModel(documentModel, 'https://univer.ai/ignored', 'link-2');
+
+ expect(documentModel.getBody()?.customRanges).toHaveLength(1);
+ expect(documentModel.getBody()?.customRanges?.[0]).toMatchObject({
+ rangeType: CustomRangeType.HYPERLINK,
+ properties: { url: 'https://univer.ai', refId: 'link-1' },
+ });
+ });
+
+ it('should compare ranges and expose empty-cell helpers', () => {
+ expect(isRangesEqual(
+ [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],
+ [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }]
+ )).toBe(true);
+ expect(isRangesEqual(
+ [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }],
+ [{ startRow: 1, endRow: 1, startColumn: 0, endColumn: 1 }]
+ )).toBe(false);
+ expect(isUnitRangesEqual(
+ [{ unitId: 'u1', sheetId: 's1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }],
+ [{ unitId: 'u1', sheetId: 's1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }]
+ )).toBe(true);
+ expect(isUnitRangesEqual(
+ [{ unitId: 'u1', sheetId: 's1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }],
+ [{ unitId: 'u2', sheetId: 's1', range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 } }]
+ )).toBe(false);
+ expect(isNotNullOrUndefined(0)).toBe(true);
+ expect(isNotNullOrUndefined(undefined)).toBe(false);
+ expect(getEmptyCell()).toEqual({
+ p: null,
+ s: null,
+ v: null,
+ t: null,
+ f: null,
+ si: null,
+ ref: null,
+ xf: null,
+ });
+ });
+});
diff --git a/packages/core/src/sheets/__tests__/worksheet-range.integration.spec.ts b/packages/core/src/sheets/__tests__/worksheet-range.integration.spec.ts
new file mode 100644
index 0000000000..a7af2da194
--- /dev/null
+++ b/packages/core/src/sheets/__tests__/worksheet-range.integration.spec.ts
@@ -0,0 +1,454 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IWorkbookData } from '../typedef';
+import { afterEach, describe, expect, it } from 'vitest';
+import { InterceptorEffectEnum } from '../../common/interceptor';
+import { CellValueType } from '../../types/enum';
+import { LocaleType } from '../../types/enum/locale-type';
+import { BooleanNumber, FontItalic, FontWeight, HorizontalAlign, TextDirection, VerticalAlign, WrapStrategy } from '../../types/enum/text-style';
+import { CellModeEnum, RANGE_TYPE } from '../typedef';
+import { createCoreTestBed } from './create-core-test-bed';
+
+const workbookDataFactory = (): IWorkbookData => ({
+ id: 'styled-workbook',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'Styled workbook',
+ sheetOrder: ['sheet-1'],
+ styles: {
+ default: {
+ bg: { rgb: '#ffffff' },
+ cl: { rgb: '#111111' },
+ ff: 'Arial',
+ fs: 10,
+ ht: HorizontalAlign.LEFT,
+ vt: VerticalAlign.TOP,
+ tb: WrapStrategy.CLIP,
+ tr: { a: 0 },
+ td: TextDirection.LEFT_TO_RIGHT,
+ },
+ rowStyle: {
+ cl: { rgb: '#00aa00' },
+ bl: BooleanNumber.TRUE,
+ },
+ colStyle: {
+ bg: { rgb: '#ffeeee' },
+ it: BooleanNumber.TRUE,
+ },
+ cellStyle: {
+ bg: { rgb: '#654321' },
+ cl: { rgb: '#123456' },
+ ff: 'Inter',
+ fs: 14,
+ ol: { s: BooleanNumber.TRUE },
+ ht: HorizontalAlign.CENTER,
+ vt: VerticalAlign.MIDDLE,
+ tb: WrapStrategy.WRAP,
+ tr: { a: 45 },
+ td: TextDirection.RIGHT_TO_LEFT,
+ },
+ },
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Styled sheet',
+ rowCount: 8,
+ columnCount: 6,
+ defaultStyle: 'default',
+ freeze: { xSplit: 1, ySplit: 1, startRow: 1, startColumn: 1 },
+ zoomRatio: 1.25,
+ scrollLeft: 15,
+ scrollTop: 10,
+ defaultColumnWidth: 72,
+ defaultRowHeight: 24,
+ hidden: BooleanNumber.FALSE,
+ mergeData: [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL }],
+ cellData: {
+ 0: {
+ 1: { v: 'Composed' },
+ },
+ 1: {
+ 1: {
+ v: 'Rich',
+ t: CellValueType.STRING,
+ s: 'cellStyle',
+ p: {
+ id: 'cell-doc',
+ body: {
+ dataStream: 'Rich\r\n',
+ textRuns: [{ st: 0, ed: 4, ts: { fs: 18, it: BooleanNumber.TRUE, bl: BooleanNumber.TRUE, ul: { s: BooleanNumber.TRUE }, st: { s: BooleanNumber.TRUE } } }],
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ },
+ },
+ },
+ 3: {
+ 3: { v: true, t: CellValueType.BOOLEAN },
+ },
+ 4: {
+ 1: { f: '=SUM(A1:A2)', v: 3, t: CellValueType.NUMBER },
+ },
+ },
+ rowData: {
+ 0: { h: 28, s: 'rowStyle' },
+ 4: { hd: BooleanNumber.TRUE },
+ },
+ columnData: {
+ 1: { w: 120, s: 'colStyle' },
+ 4: { hd: BooleanNumber.TRUE },
+ },
+ rowHeader: { width: 46 },
+ columnHeader: { height: 28 },
+ showGridlines: BooleanNumber.FALSE,
+ gridlinesColor: '#d0d0d0',
+ rightToLeft: BooleanNumber.TRUE,
+ tabColor: '#abcdef',
+ custom: { owner: 'qa' },
+ },
+ },
+});
+
+describe('Worksheet/range integration', () => {
+ const disposables: Array<() => void> = [];
+
+ afterEach(() => {
+ while (disposables.length) {
+ disposables.pop()?.();
+ }
+ });
+
+ it('should read worksheet metadata, merged cells and formatted ranges from a realistic snapshot', () => {
+ const testBed = createCoreTestBed(workbookDataFactory());
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ disposables.push(() => testBed.univer.dispose());
+
+ expect(worksheet.getFreeze()).toEqual({ xSplit: 1, ySplit: 1, startRow: 1, startColumn: 1 });
+ expect(worksheet.getZoomRatio()).toBe(1.25);
+ expect(worksheet.getConfig().name).toBe('Styled sheet');
+ expect(worksheet.getMaxRows()).toBe(8);
+ expect(worksheet.getMaxColumns()).toBe(6);
+ expect(worksheet.getRowCount()).toBe(8);
+ expect(worksheet.getColumnCount()).toBe(6);
+ expect(worksheet.isSheetHidden()).toBe(BooleanNumber.FALSE);
+ expect(worksheet.hasHiddenGridlines()).toBe(true);
+ expect(worksheet.getGridlinesColor()).toBe('#d0d0d0');
+ expect(worksheet.getTabColor()).toBe('#abcdef');
+ expect(worksheet.getColumnWidth(1)).toBe(120);
+ expect(worksheet.getRowHeight(0)).toBe(28);
+ expect(worksheet.getRowVisible(4)).toBe(false);
+ expect(worksheet.getRowRawVisible(4)).toBe(false);
+ expect(worksheet.getColVisible(4)).toBe(false);
+ expect(worksheet.getHiddenRows()).toEqual([
+ expect.objectContaining({ startRow: 4, endRow: 4, startColumn: 0, endColumn: 5 }),
+ ]);
+ expect(worksheet.getHiddenCols()).toEqual([
+ expect.objectContaining({ startRow: 0, endRow: 7, startColumn: 4, endColumn: 4 }),
+ ]);
+ expect(worksheet.getVisibleRows()).toEqual(expect.arrayContaining([
+ expect.objectContaining({ startRow: 0, endRow: 3 }),
+ expect.objectContaining({ startRow: 5, endRow: 7 }),
+ ]));
+ expect(worksheet.getVisibleCols()).toEqual(expect.arrayContaining([
+ expect.objectContaining({ startColumn: 0, endColumn: 3 }),
+ expect.objectContaining({ startColumn: 5, endColumn: 5 }),
+ ]));
+ expect(worksheet.isRightToLeft()).toBe(BooleanNumber.TRUE);
+ expect(worksheet.getLastRowWithContent()).toBe(4);
+ expect(worksheet.getLastColumnWithContent()).toBe(3);
+ expect(worksheet.getDataRealRange()).toEqual({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 });
+ expect(worksheet.getDataRangeScope()).toEqual({ startRow: 0, endRow: 4, startColumn: 1, endColumn: 3 });
+
+ expect(worksheet.getCustomMetadata()).toEqual({ owner: 'qa' });
+ worksheet.setCustomMetadata({ owner: 'core' });
+ expect(worksheet.getCustomMetadata()).toEqual({ owner: 'core' });
+
+ const mergeMainCell = worksheet.getCellInfoInMergeData(1, 1);
+ const mergeInnerCell = worksheet.getCellInfoInMergeData(2, 2);
+ expect(worksheet.getMergedCell(2, 2)).toEqual({ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL });
+ expect(worksheet.getMergedCellRange(1, 1, 2, 2)).toEqual([{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2, rangeType: RANGE_TYPE.NORMAL }]);
+ expect(worksheet.isRowContainsMergedCell(1)).toBe(true);
+ expect(worksheet.isColumnContainsMergedCell(1)).toBe(true);
+ expect(mergeMainCell.isMergedMainCell).toBe(true);
+ expect(mergeInnerCell.isMerged).toBe(true);
+
+ const composedStyle = worksheet.getComposedCellStyle(0, 1);
+ expect(composedStyle.ff).toBe('Arial');
+ expect(composedStyle.cl?.rgb).toBe('#00aa00');
+ expect(composedStyle.bg?.rgb).toBe('#ffeeee');
+ expect(composedStyle.it).toBe(BooleanNumber.TRUE);
+ expect(composedStyle.bl).toBe(BooleanNumber.TRUE);
+
+ expect(worksheet.getCell(-1, 0)).toBeNull();
+ expect(worksheet.getCellValueOnly(-1, 0)).toBeNull();
+ expect(worksheet.getCellStyleOnly(-1, 0)).toBeNull();
+ expect(worksheet.getRangeFilterRows({ startRow: 0, endRow: 7, startColumn: 0, endColumn: 5, rangeType: RANGE_TYPE.NORMAL })).toEqual([]);
+ expect(worksheet.cellHasValue({})).toBe(false);
+ expect(worksheet.cellHasValue({ v: 0 })).toBe(true);
+
+ const richCell = worksheet.getRange(1, 1);
+ expect(richCell.getValue()?.v).toBe('Rich');
+ expect(richCell.getA1Notation()).toBe('B2');
+ expect(richCell.getBackground()).toBe('#654321');
+ expect(richCell.getFontColor()).toBe('#123456');
+ expect(richCell.getFontFamily()).toBe('Inter');
+ expect(richCell.getFontSize()).toBe(18);
+ expect(richCell.getFontStyle()).toBe(FontItalic.ITALIC);
+ expect(richCell.getFontWeight()).toBe(FontWeight.BOLD);
+ expect(richCell.getUnderline()).toEqual({ s: BooleanNumber.TRUE });
+ expect(richCell.getOverline()).toEqual({ s: BooleanNumber.TRUE });
+ expect(richCell.getStrikeThrough()).toEqual({ s: BooleanNumber.TRUE });
+ expect(richCell.getHorizontalAlignment()).toBe(HorizontalAlign.CENTER);
+ expect(richCell.getVerticalAlignment()).toBe(VerticalAlign.MIDDLE);
+ expect(richCell.getTextDirection()).toBe(TextDirection.RIGHT_TO_LEFT);
+ expect(richCell.getTextRotation()).toEqual({ a: 45 });
+ expect(richCell.getWrap()).toBe(BooleanNumber.TRUE);
+ expect(richCell.getWrapStrategy()).toBe(WrapStrategy.WRAP);
+ expect(richCell.getRichTextValue()).toMatchObject({
+ id: 'cell-doc',
+ body: {
+ dataStream: 'Rich\r\n',
+ textRuns: [{ st: 0, ed: 4, ts: { fs: 18, it: BooleanNumber.TRUE, bl: BooleanNumber.TRUE, ul: { s: BooleanNumber.TRUE }, st: { s: BooleanNumber.TRUE } } }],
+ },
+ });
+ expect(richCell.getTextStyle()?.ff).toBe('Inter');
+
+ const mergedRange = worksheet.getRange(1, 1, 2, 2);
+ expect(mergedRange.getRangeData()).toEqual({ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 });
+ expect(mergedRange.getValues()).toHaveLength(2);
+ expect(mergedRange.getMatrix().getValue(1, 1)?.v).toBe('Rich');
+ expect(mergedRange.getMatrixObject().getValue(0, 0)?.v).toBe('Rich');
+ expect(mergedRange.getObjectValue({ isIncludeStyle: true })?.s).toMatchObject({ ff: 'Inter' });
+ expect(mergedRange.getObjectValues({ isIncludeStyle: true })?.[0]?.[0]?.s).toMatchObject({ ff: 'Inter' });
+ expect(mergedRange.getGridId()).toBe('sheet-1');
+ expect(mergedRange.getSheet().getSheetId()).toBe('sheet-1');
+ expect(mergedRange.getColumn()).toBe(1);
+ expect(mergedRange.getRowIndex()).toBe(1);
+ expect(mergedRange.getLastColumn()).toBe(2);
+ expect(mergedRange.getLastRow()).toBe(2);
+ expect(mergedRange.getNumColumns()).toBe(2);
+ expect(mergedRange.getNumRows()).toBe(2);
+
+ const visited: Array<[number, number]> = [];
+ mergedRange.forEach((row, column) => {
+ visited.push([row, column]);
+ });
+ expect(visited).toEqual([
+ [1, 1],
+ [1, 2],
+ [2, 1],
+ [2, 2],
+ ]);
+ expect(mergedRange.getCell(0, 0).getA1Notation()).toBe('B2');
+
+ const widthHeightRange = worksheet.getRange(0, 0, 1, 1);
+ expect(widthHeightRange.getWidth()).toBe(192);
+ expect(widthHeightRange.getHeight()).toBe(52);
+
+ expect(worksheet.getCellDocumentModelWithFormula({ f: '=SUM(A1:A2)', v: 3, t: CellValueType.NUMBER }, 4, 1)?.documentModel).toBeDefined();
+ expect(worksheet.getBlankCellDocumentModel(null, 6, 5).documentModel).toBeDefined();
+
+ worksheet.setRowCount(10);
+ worksheet.setColumnCount(7);
+ expect(worksheet.getRowCount()).toBe(10);
+ expect(worksheet.getColumnCount()).toBe(7);
+ });
+
+ it('should mutate row and column managers through real worksheet state', () => {
+ const testBed = createCoreTestBed(workbookDataFactory());
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ const rowManager = worksheet.getRowManager();
+ const columnManager = worksheet.getColumnManager();
+ disposables.push(() => testBed.univer.dispose());
+
+ expect(rowManager.getRowData()[0]).toMatchObject({ h: 28, s: 'rowStyle' });
+ expect(rowManager.getRowStyle(0)).toBe('rowStyle');
+ rowManager.setRowStyle(2, 'rowStyle');
+ expect(rowManager.getRowStyle(2)).toBe('rowStyle');
+ expect(rowManager.getRowDatas(0, 3)).toEqual({
+ 0: { h: 28, s: 'rowStyle' },
+ 1: { h: 24, hd: BooleanNumber.FALSE },
+ 2: { s: 'rowStyle' },
+ });
+ expect(rowManager.getRowHeight(0, 2)).toBe(52);
+
+ rowManager.setRowHeight(6, 4000);
+ expect(rowManager.getRowHeight(6)).toBe(2000);
+ rowManager.setRowHeight(6, 24);
+ expect(rowManager.getRow(6)).toBeUndefined();
+
+ rowManager.insertRowsWithData(1, 2, {
+ 0: { h: 40, custom: { label: 'inserted-row' } },
+ 1: { hd: BooleanNumber.TRUE },
+ });
+ expect(rowManager.getRow(1)).toMatchObject({ h: 40, custom: { label: 'inserted-row' } });
+ expect(rowManager.getRowRawVisible(2)).toBe(false);
+ expect(rowManager.getHiddenRows(0, 8)).toEqual(expect.arrayContaining([
+ expect.objectContaining({ startRow: 2, endRow: 2, rangeType: RANGE_TYPE.ROW }),
+ expect.objectContaining({ startRow: 6, endRow: 6, rangeType: RANGE_TYPE.ROW }),
+ ]));
+ expect(rowManager.getVisibleRows(0, 8)).toEqual(expect.arrayContaining([
+ expect.objectContaining({ startRow: 0, endRow: 1, rangeType: RANGE_TYPE.ROW }),
+ expect.objectContaining({ startRow: 3, endRow: 5, rangeType: RANGE_TYPE.ROW }),
+ expect.objectContaining({ startRow: 7, endRow: 8, rangeType: RANGE_TYPE.ROW }),
+ ]));
+ rowManager.removeRow(1);
+ expect(rowManager.getRow(1)).toBeUndefined();
+
+ rowManager.getRowOrCreate(3);
+ rowManager.setCustomMetadata(3, { tag: 'row-meta' });
+ expect(rowManager.getCustomMetadata(3)).toEqual({ tag: 'row-meta' });
+ expect(rowManager.getRowOrCreate(5)).toMatchObject({});
+ expect(rowManager.getSize()).toBeGreaterThanOrEqual(7);
+
+ expect(columnManager.getColumnData()[1]).toMatchObject({ w: 120, s: 'colStyle' });
+ expect(columnManager.getColumnStyle(1)).toBe('colStyle');
+ columnManager.setColumnStyle(2, 'colStyle');
+ expect(columnManager.getColumnStyle(2)).toBe('colStyle');
+ expect(columnManager.getColumnDatas(0, 3)).toEqual({
+ 0: { w: 72, hd: BooleanNumber.FALSE },
+ 1: { w: 120, s: 'colStyle' },
+ 2: { s: 'colStyle' },
+ });
+
+ columnManager.setColumnWidth(5, 90);
+ expect(columnManager.getColumnWidth(5)).toBe(90);
+ columnManager.setColumnWidth(5, 72);
+ expect(columnManager.getColumn(5)).toBeUndefined();
+
+ columnManager.insertColumnsWithData(1, 2, {
+ 0: { w: 88, custom: { label: 'inserted-column' } },
+ 1: { hd: BooleanNumber.TRUE },
+ });
+ expect(columnManager.getColumn(1)).toMatchObject({ w: 88, custom: { label: 'inserted-column' } });
+ expect(columnManager.getColVisible(2)).toBe(false);
+ expect(columnManager.getHiddenCols(0, 7)).toEqual(expect.arrayContaining([
+ expect.objectContaining({ startColumn: 2, endColumn: 2, rangeType: RANGE_TYPE.COLUMN }),
+ expect.objectContaining({ startColumn: 6, endColumn: 6, rangeType: RANGE_TYPE.COLUMN }),
+ ]));
+ expect(columnManager.getVisibleCols(0, 7)).toEqual(expect.arrayContaining([
+ expect.objectContaining({ startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.COLUMN }),
+ expect.objectContaining({ startColumn: 3, endColumn: 5, rangeType: RANGE_TYPE.COLUMN }),
+ expect.objectContaining({ startColumn: 7, endColumn: 7, rangeType: RANGE_TYPE.COLUMN }),
+ ]));
+ columnManager.removeColumn(1);
+ expect(columnManager.getColumn(1)).toBeUndefined();
+
+ columnManager.getColumnOrCreate(3);
+ columnManager.setCustomMetadata(3, { tag: 'column-meta' });
+ expect(columnManager.getCustomMetadata(3)).toEqual({ tag: 'column-meta' });
+ expect(columnManager.getColumn(6)).toMatchObject({ hd: BooleanNumber.TRUE });
+ expect(columnManager.getColumnOrCreate(8)).toMatchObject({});
+ expect(columnManager.getSize()).toBeGreaterThanOrEqual(7);
+ });
+
+ it('should expose worksheet utility apis through real style, interceptor and matrix flows', () => {
+ const testBed = createCoreTestBed(workbookDataFactory());
+ const worksheet = testBed.sheet.getActiveSheet()!;
+ disposables.push(() => testBed.univer.dispose());
+
+ const getCellHeightDisposable = worksheet.__registerGetCellHeight((row, column) => row + column + 100);
+ expect(worksheet.getCellHeight(2, 3)).toBe(105);
+ getCellHeightDisposable.dispose();
+ expect(worksheet.getCellHeight(2, 3)).toBe(24);
+
+ const styleHash = worksheet.setStyleData({ ff: 'Manrope', fs: 16, bg: { rgb: '#101010' } })!;
+ expect(worksheet.getStyleDataByHash(styleHash)).toMatchObject({ ff: 'Manrope', fs: 16 });
+
+ worksheet.setColumnStyle(3, styleHash);
+ worksheet.setRowStyle(3, styleHash);
+ expect(worksheet.getColumnStyle(3, true)).toBe(styleHash);
+ expect(worksheet.getColumnStyle(3)).toMatchObject({ ff: 'Manrope' });
+ expect(worksheet.getRowStyle(3, true)).toBe(styleHash);
+ expect(worksheet.getRowStyle(3)).toMatchObject({ ff: 'Manrope' });
+
+ expect(worksheet.getDefaultCellStyle()).toBe('default');
+ worksheet.setDefaultCellStyle(styleHash);
+ expect(worksheet.getDefaultCellStyle()).toBe(styleHash);
+ expect(worksheet.getDefaultCellStyleInternal()).toMatchObject({ ff: 'Manrope' });
+ expect(worksheet.getCellStyle(1, 1)).toMatchObject({ ff: 'Inter' });
+
+ const rawCell = worksheet.getCellRaw(1, 1);
+ expect(rawCell?.v).toBe('Rich');
+ expect(worksheet.getComposedCellStyleByCellData(1, 1, rawCell)).toMatchObject({ ff: 'Inter', bg: { rgb: '#654321' } });
+ expect(worksheet.getComposedCellStyleWithoutSelf(1, 1, rawCell)).toMatchObject({});
+
+ worksheet.setIsRowStylePrecedeColumnStyle(true);
+ expect(worksheet.getComposedCellStyle(0, 1).cl?.rgb).toBe('#00aa00');
+ worksheet.setIsRowStylePrecedeColumnStyle(false);
+
+ worksheet.__interceptViewModel((viewModel) => {
+ disposables.push(() => viewModel.dispose());
+ const cellContentDisposable = viewModel.registerCellContentInterceptor({
+ getCell(row, col, effect) {
+ const cell = worksheet.getCellRaw(row, col);
+ if (!cell) {
+ return null;
+ }
+
+ if (effect === InterceptorEffectEnum.Style) {
+ return { ...cell, interceptorStyle: { bg: { rgb: '#abcdef' } } };
+ }
+
+ if (effect === InterceptorEffectEnum.Value) {
+ return { ...cell, v: `value-${row}-${col}` };
+ }
+
+ return { ...cell, v: `both-${row}-${col}`, interceptorStyle: { bg: { rgb: '#fedcba' } } };
+ },
+ });
+ const rowFilteredDisposable = viewModel.registerRowFilteredInterceptor({
+ getRowFiltered(row) {
+ return row === 1;
+ },
+ });
+ disposables.push(() => cellContentDisposable.dispose());
+ disposables.push(() => rowFilteredDisposable.dispose());
+ });
+
+ expect(worksheet.getCell(1, 1)?.v).toBe('both-1-1');
+ expect(worksheet.getCellValueOnly(1, 1)?.v).toBe('value-1-1');
+ expect(worksheet.getCellStyleOnly(1, 1)?.interceptorStyle).toEqual({ bg: { rgb: '#abcdef' } });
+ expect(worksheet.getCellWithFilteredInterceptors(1, 1, 'demo', () => true)?.v).toBe('both-1-1');
+ expect(worksheet.getRowFiltered(1)).toBe(true);
+ expect(worksheet.getRangeFilterRows({ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2, rangeType: RANGE_TYPE.NORMAL })).toEqual([1]);
+
+ const mergedMatrix = worksheet.getMatrixWithMergedCells(1, 1, 2, 2, CellModeEnum.Both);
+ expect(mergedMatrix.getValue(1, 1)).toMatchObject({ rowSpan: 2, colSpan: 2, v: 'Rich' });
+ expect(mergedMatrix.getValue(2, 2)).toBeUndefined();
+
+ const objectRange = worksheet.getRange({ startRow: 0, startColumn: 1, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL });
+ expect(objectRange.getA1Notation()).toBe('B1');
+ expect(worksheet.getScrollLeftTopFromSnapshot()).toEqual({ scrollLeft: 15, scrollTop: 10 });
+ expect(worksheet.getUnitId()).toBe('styled-workbook');
+ expect(worksheet.getSheetId()).toBe('sheet-1');
+ expect(worksheet.getName()).toBe('Styled sheet');
+
+ const clone = worksheet.clone();
+ expect(clone).not.toBe(worksheet);
+ expect(clone.getSnapshot()).toEqual(worksheet.getSnapshot());
+
+ worksheet.setMergeData([{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL }]);
+ expect(worksheet.getMergeData()).toEqual([{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL }]);
+ expect(worksheet.getSpanModel().getMergedCell(0, 1)).toEqual({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL });
+ });
+});
diff --git a/packages/core/src/slides/__tests__/slide-model.spec.ts b/packages/core/src/slides/__tests__/slide-model.spec.ts
new file mode 100644
index 0000000000..93f23933af
--- /dev/null
+++ b/packages/core/src/slides/__tests__/slide-model.spec.ts
@@ -0,0 +1,154 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISlideData, ISlidePage } from '../../types/interfaces';
+import type { SlideDataModel } from '../slide-model';
+import { afterEach, describe, expect, it } from 'vitest';
+import { UniverInstanceType } from '../../common/unit';
+import { PageElementType, PageType } from '../../types/interfaces';
+import { Univer } from '../../univer';
+
+const slideSnapshotFactory = (): Partial<ISlideData> => ({
+ id: 'slide-unit',
+ title: 'Quarterly review',
+ pageSize: { width: 960, height: 540 },
+ body: {
+ pageOrder: ['page-1', 'page-2'],
+ pages: {
+ 'page-1': {
+ id: 'page-1',
+ pageType: PageType.SLIDE,
+ zIndex: 1,
+ title: 'Overview',
+ description: 'Overview slide',
+ pageBackgroundFill: { rgb: '#ffffff' },
+ pageElements: {
+ 'element-1': {
+ id: 'element-1',
+ zIndex: 1,
+ title: 'Intro',
+ description: 'Hero copy',
+ type: PageElementType.TEXT,
+ richText: { text: 'Hello Univer' },
+ },
+ },
+ },
+ 'page-2': {
+ id: 'page-2',
+ pageType: PageType.SLIDE,
+ zIndex: 2,
+ title: 'Roadmap',
+ description: 'Roadmap slide',
+ pageBackgroundFill: { rgb: '#f5f5f5' },
+ pageElements: {},
+ },
+ },
+ },
+});
+
+describe('SlideDataModel', () => {
+ let univer: Univer;
+
+ afterEach(() => {
+ univer?.dispose();
+ });
+
+ it('should manage pages and active-page state through the real unit creation flow', () => {
+ univer = new Univer();
+ const slide = univer.createUnit<Partial<ISlideData>, SlideDataModel>(UniverInstanceType.UNIVER_SLIDE, slideSnapshotFactory());
+ const activePages: string[] = [];
+ const names: string[] = [];
+ const activePageSubscription = slide.activePage$.subscribe((page) => {
+ if (page) {
+ activePages.push(page.id);
+ }
+ });
+ const nameSubscription = slide.name$.subscribe((name) => names.push(name));
+
+ expect(slide.getUnitId()).toBe('slide-unit');
+ expect(slide.getSnapshot().title).toBe('Quarterly review');
+ expect(slide.getPages()).toHaveProperty('page-1');
+ expect(slide.getPageOrder()).toEqual(['page-1', 'page-2']);
+ expect(slide.getPage('page-1')?.title).toBe('Overview');
+ expect(slide.getElementsByPage('page-1')).toHaveProperty('element-1');
+ expect(slide.getElement('page-1', 'element-1')).toMatchObject({
+ id: 'element-1',
+ type: PageElementType.TEXT,
+ });
+ expect(slide.getPageSize()).toEqual({ width: 960, height: 540 });
+ expect(slide.getActivePage()?.id).toBe('page-1');
+ expect(slide.getRev()).toBe(0);
+
+ slide.incrementRev();
+ slide.setRev(5);
+ expect(slide.getRev()).toBe(0);
+
+ slide.setActivePage(slide.getPage('page-2')!);
+ expect(slide.getActivePage()?.id).toBe('page-2');
+ expect(activePages).toEqual(['page-2']);
+
+ const blankPage = slide.getBlankPage();
+ expect(blankPage).toMatchObject({
+ pageType: PageType.SLIDE,
+ zIndex: 10,
+ pageBackgroundFill: { rgb: 'rgb(255,255,255)' },
+ });
+
+ slide.appendPage(blankPage);
+ expect(slide.getPageOrder()).toEqual(['page-1', 'page-2', blankPage.id]);
+ expect(slide.getPage(blankPage.id)).toEqual(blankPage);
+
+ const updatedPage: ISlidePage = {
+ ...blankPage,
+ title: 'Agenda',
+ description: 'Agenda slide',
+ };
+ slide.updatePage(blankPage.id, updatedPage);
+ expect(slide.getPage(blankPage.id)).toEqual(updatedPage);
+
+ slide.setName('Quarterly review - updated');
+ expect(slide.getSnapshot().title).toBe('Quarterly review - updated');
+ expect(slide.getUnitId()).toBe('slide-unit');
+ expect(names.at(-1)).toBe('Quarterly review - updated');
+
+ activePageSubscription.unsubscribe();
+ nameSubscription.unsubscribe();
+ });
+
+ it('should keep empty slide snapshots stable when page collections are absent', () => {
+ univer = new Univer();
+ const slide = univer.createUnit<Partial<ISlideData>, SlideDataModel>(UniverInstanceType.UNIVER_SLIDE, {
+ id: 'empty-slide',
+ title: 'Empty deck',
+ });
+
+ const blankPage = slide.getBlankPage();
+
+ expect(slide.getActivePage()).toBeNull();
+ expect(slide.getPages()).toBeUndefined();
+ expect(slide.getPageOrder()).toBeUndefined();
+ expect(slide.getPage(blankPage.id)).toBeUndefined();
+
+ slide.appendPage(blankPage);
+ slide.updatePage(blankPage.id, blankPage);
+
+ expect(slide.getPages()).toBeUndefined();
+ expect(slide.getSnapshot()).toMatchObject({
+ id: 'empty-slide',
+ title: 'Empty deck',
+ });
+ });
+});
diff --git a/packages/data-validation/src/__tests__/data-validation.integration.spec.ts b/packages/data-validation/src/__tests__/data-validation.integration.spec.ts
new file mode 100644
index 0000000000..ad3b6abd61
--- /dev/null
+++ b/packages/data-validation/src/__tests__/data-validation.integration.spec.ts
@@ -0,0 +1,313 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ILogService, Injector, ISheetDataValidationRule, IWorkbookData, Workbook } from '@univerjs/core';
+import {
+ DataValidationOperator,
+ DataValidationType,
+ ICommandService,
+ IResourceLoaderService,
+ IResourceManagerService,
+ LocaleType,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AddDataValidationMutation, RemoveDataValidationMutation, UpdateDataValidationMutation } from '../commands/mutations/data-validation.mutation';
+import { DataValidationResourceController } from '../controllers/dv-resource.controller';
+import { DataValidationModel } from '../models/data-validation-model';
+import { UpdateRuleType } from '../types/enum/update-rule-type';
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: 'unit-1',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'Workbook',
+ sheetOrder: ['sheet-1', 'sheet-2'],
+ styles: {},
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Sheet1',
+ cellData: {},
+ },
+ 'sheet-2': {
+ id: 'sheet-2',
+ name: 'Sheet2',
+ cellData: {},
+ },
+ },
+ };
+}
+
+function createRule(uid: string, overrides: Partial<ISheetDataValidationRule> = {}): ISheetDataValidationRule {
+ return {
+ uid,
+ type: DataValidationType.DECIMAL,
+ operator: DataValidationOperator.BETWEEN,
+ formula1: '1',
+ formula2: '5',
+ allowBlank: true,
+ showErrorMessage: true,
+ error: `Rule ${uid} failed`,
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+ ...overrides,
+ } as ISheetDataValidationRule;
+}
+
+describe('data validation integration', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let resourceManagerService: IResourceManagerService;
+ let resourceLoaderService: IResourceLoaderService;
+ let dataValidationModel: DataValidationModel;
+
+ beforeEach(() => {
+ univer = new Univer();
+
+ const injector = univer.__getInjector();
+ get = injector.get.bind(injector);
+
+ injector.add([DataValidationModel]);
+ injector.add([DataValidationResourceController]);
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(AddDataValidationMutation);
+ commandService.registerCommand(RemoveDataValidationMutation);
+ commandService.registerCommand(UpdateDataValidationMutation);
+
+ dataValidationModel = get(DataValidationModel);
+ resourceManagerService = get(IResourceManagerService);
+ resourceLoaderService = get(IResourceLoaderService);
+
+ get(DataValidationResourceController);
+ univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('applies add, update, and remove mutations through the real command service', async () => {
+ const changes: Array<{ type: string; ruleId: string; source: string }> = [];
+ const sub = dataValidationModel.ruleChange$.subscribe((change) => {
+ changes.push({ type: change.type, ruleId: change.rule.uid, source: change.source });
+ });
+
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rule: createRule('rule-1'),
+ });
+
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ index: 0,
+ rule: [createRule('rule-2'), createRule('rule-1'), createRule('rule-3')],
+ });
+
+ await commandService.executeCommand(UpdateDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ruleId: 'rule-1',
+ payload: {
+ type: UpdateRuleType.SETTING,
+ payload: {
+ type: DataValidationType.TEXT_LENGTH,
+ operator: DataValidationOperator.GREATER_THAN,
+ formula1: '3',
+ formula2: undefined,
+ allowBlank: false,
+ },
+ },
+ });
+
+ await commandService.executeCommand(UpdateDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ruleId: 'rule-1',
+ payload: {
+ type: UpdateRuleType.OPTIONS,
+ payload: {
+ prompt: 'Type a longer value',
+ promptTitle: 'Length rule',
+ showErrorMessage: false,
+ bizInfo: {
+ source: 'integration-spec',
+ },
+ },
+ },
+ });
+
+ await commandService.executeCommand(UpdateDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ruleId: 'rule-2',
+ payload: {
+ type: UpdateRuleType.RANGE,
+ payload: [{ startRow: 2, endRow: 3, startColumn: 1, endColumn: 2 }],
+ },
+ });
+
+ await commandService.executeCommand(UpdateDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ruleId: 'rule-3',
+ payload: {
+ type: UpdateRuleType.ALL,
+ payload: createRule('rule-3', {
+ type: DataValidationType.LIST,
+ operator: undefined,
+ formula1: 'Yes,No',
+ formula2: undefined,
+ showDropDown: false,
+ ranges: [{ startRow: 4, endRow: 4, startColumn: 0, endColumn: 1 }],
+ }),
+ },
+ });
+
+ await commandService.executeCommand(RemoveDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ruleId: ['rule-2', 'rule-3'],
+ });
+
+ const rules = dataValidationModel.getRules('unit-1', 'sheet-1');
+ expect(rules.map((rule) => rule.uid)).toEqual(['rule-1']);
+ expect(dataValidationModel.getRuleIndex('unit-1', 'sheet-1', 'rule-1')).toBe(0);
+ expect(dataValidationModel.getRuleById('unit-1', 'sheet-1', 'rule-1')).toMatchObject({
+ type: DataValidationType.TEXT_LENGTH,
+ operator: DataValidationOperator.GREATER_THAN,
+ formula1: '3',
+ allowBlank: false,
+ prompt: 'Type a longer value',
+ promptTitle: 'Length rule',
+ showErrorMessage: false,
+ bizInfo: {
+ source: 'integration-spec',
+ },
+ });
+
+ expect(changes.map((change) => change.type)).toEqual([
+ 'add',
+ 'add',
+ 'add',
+ 'update',
+ 'update',
+ 'update',
+ 'update',
+ 'remove',
+ 'remove',
+ ]);
+ expect(changes.every((change) => change.source === 'command')).toBe(true);
+
+ sub.unsubscribe();
+ });
+
+ it('serializes, unloads, and loads rule resources through the resource manager', async () => {
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rule: createRule('sheet-1-rule'),
+ });
+ await commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-2',
+ rule: createRule('sheet-2-rule', {
+ ranges: [{ startRow: 9, endRow: 9, startColumn: 0, endColumn: 0 }],
+ }),
+ });
+
+ const snapshot = resourceLoaderService.saveUnit('unit-1');
+ const resource = snapshot?.resources.find((item) => item.name === 'SHEET_DATA_VALIDATION_PLUGIN');
+
+ expect(resource).toBeDefined();
+ expect(JSON.parse(resource!.data)).toEqual({
+ 'sheet-1': [createRule('sheet-1-rule')],
+ 'sheet-2': [createRule('sheet-2-rule', {
+ ranges: [{ startRow: 9, endRow: 9, startColumn: 0, endColumn: 0 }],
+ })],
+ });
+
+ resourceManagerService.unloadResources('unit-1', UniverInstanceType.UNIVER_SHEET);
+ expect(dataValidationModel.getUnitRules('unit-1')).toEqual([]);
+
+ resourceManagerService.loadResources('unit-1', [{
+ name: 'SHEET_DATA_VALIDATION_PLUGIN',
+ data: JSON.stringify({
+ 'sheet-1': [createRule('loaded-rule')],
+ 'sheet-2': [createRule('loaded-rule-2', {
+ type: DataValidationType.LIST,
+ formula1: 'A,B',
+ operator: undefined,
+ })],
+ }),
+ }]);
+
+ expect(dataValidationModel.getRules('unit-1', 'sheet-1')).toEqual([createRule('loaded-rule')]);
+ expect(dataValidationModel.getRules('unit-1', 'sheet-2')).toEqual([
+ createRule('loaded-rule-2', {
+ type: DataValidationType.LIST,
+ formula1: 'A,B',
+ operator: undefined,
+ }),
+ ]);
+
+ resourceManagerService.loadResources('unit-1', [{
+ name: 'SHEET_DATA_VALIDATION_PLUGIN',
+ data: '{invalid-json',
+ }]);
+
+ expect(dataValidationModel.getSubUnitIds('unit-1')).toEqual(['sheet-1', 'sheet-2']);
+ });
+
+ it('reports model errors and exposes unit level getters without changing source code', () => {
+ const logService = {
+ error: vi.fn(),
+ } as unknown as ILogService;
+ const model = new DataValidationModel(logService);
+
+ model.addRule('unit-2', 'sheet-x', createRule('rule-a'), 'patched');
+ model.addRule('unit-2', 'sheet-y', createRule('rule-b'), 'patched');
+
+ expect(model.getSubUnitIds('unit-2')).toEqual(['sheet-x', 'sheet-y']);
+ expect(model.getUnitRules('unit-2')).toEqual([
+ ['sheet-x', [createRule('rule-a')]],
+ ['sheet-y', [createRule('rule-b')]],
+ ]);
+ expect(model.getAll()).toContainEqual([
+ 'unit-2',
+ [
+ ['sheet-x', [createRule('rule-a')]],
+ ['sheet-y', [createRule('rule-b')]],
+ ],
+ ]);
+
+ model.updateRule('unit-2', 'sheet-x', 'missing-rule', {
+ type: UpdateRuleType.ALL,
+ payload: createRule('missing-rule'),
+ }, 'patched');
+
+ expect(logService.error).toHaveBeenCalled();
+
+ model.deleteUnitRules('unit-2');
+ expect(model.getUnitRules('unit-2')).toEqual([]);
+ model.dispose();
+ });
+});
diff --git a/packages/data-validation/src/__tests__/data-validator.behavior.spec.ts b/packages/data-validation/src/__tests__/data-validator.behavior.spec.ts
new file mode 100644
index 0000000000..e071be23d6
--- /dev/null
+++ b/packages/data-validation/src/__tests__/data-validator.behavior.spec.ts
@@ -0,0 +1,282 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDataValidationRule, Injector } from '@univerjs/core';
+import type { IFormulaResult, IFormulaValidResult, IValidatorCellInfo } from '../validators/base-data-validator';
+import {
+ DataValidationOperator,
+ DataValidationType,
+ LocaleService,
+ LocaleType,
+ Univer,
+} from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { DataValidatorRegistryScope, DataValidatorRegistryService } from '../services/data-validator-registry.service';
+import { BaseDataValidator } from '../validators/base-data-validator';
+
+function createRule(overrides: Partial<IDataValidationRule> = {}): IDataValidationRule {
+ return {
+ uid: 'rule-1',
+ type: DataValidationType.DECIMAL,
+ operator: DataValidationOperator.BETWEEN,
+ formula1: '1',
+ formula2: '5',
+ allowBlank: true,
+ showErrorMessage: true,
+ error: 'Explicit error',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+ ...overrides,
+ } as IDataValidationRule;
+}
+
+function createCellInfo(value: unknown): IValidatorCellInfo {
+ return {
+ value: value as never,
+ interceptValue: null,
+ row: 0,
+ column: 0,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ worksheet: null as never,
+ workbook: null as never,
+ t: null,
+ };
+}
+
+class TestDataValidator extends BaseDataValidator {
+ id = 'validator.number';
+ title = 'validator.number';
+ operators = [
+ DataValidationOperator.BETWEEN,
+ DataValidationOperator.EQUAL,
+ DataValidationOperator.GREATER_THAN,
+ DataValidationOperator.GREATER_THAN_OR_EQUAL,
+ DataValidationOperator.LESS_THAN,
+ DataValidationOperator.LESS_THAN_OR_EQUAL,
+ DataValidationOperator.NOT_BETWEEN,
+ DataValidationOperator.NOT_EQUAL,
+ ];
+
+ scopes = [DataValidatorRegistryScope.SHEET, 'custom-scope'];
+ order = 1;
+
+ formulaResult: IFormulaResult<number | undefined> = {
+ formula1: 1,
+ formula2: 5,
+ isFormulaValid: true,
+ };
+
+ validType = true;
+
+ override async parseFormula(rule: IDataValidationRule, _unitId: string, _subUnitId: string, _row: number, _column: number): Promise<IFormulaResult<number | undefined>> {
+ return {
+ ...this.formulaResult,
+ formula1: Number(rule.formula1 ?? this.formulaResult.formula1),
+ formula2: rule.formula2 == null ? undefined : Number(rule.formula2),
+ };
+ }
+
+ override validatorFormula(rule: IDataValidationRule, _unitId: string, _subUnitId: string): IFormulaValidResult {
+ return {
+ success: true,
+ formula1: rule.formula1,
+ formula2: rule.formula2,
+ };
+ }
+
+ override async isValidType(): Promise<boolean> {
+ return this.validType;
+ }
+
+ override transform(cellInfo: IValidatorCellInfo): IValidatorCellInfo<number> {
+ return {
+ ...cellInfo,
+ value: Number(cellInfo.value),
+ };
+ }
+}
+
+describe('data validator behavior', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let localeService: LocaleService;
+ let registryService: DataValidatorRegistryService;
+ let validator: TestDataValidator;
+
+ beforeEach(() => {
+ univer = new Univer();
+ const injector = univer.__getInjector();
+ get = injector.get.bind(injector);
+
+ injector.add([DataValidatorRegistryService]);
+
+ localeService = get(LocaleService);
+ localeService.load({
+ [LocaleType.EN_US]: {
+ validator: {
+ number: 'Number',
+ },
+ dataValidation: {
+ operators: {
+ between: 'between',
+ equal: 'equal',
+ greaterThan: 'greater than',
+ greaterThanOrEqual: 'greater than or equal',
+ lessThan: 'less than',
+ lessThanOrEqual: 'less than or equal',
+ notBetween: 'not between',
+ notEqual: 'not equal',
+ },
+ ruleName: {
+ between: 'between {FORMULA1} and {FORMULA2}',
+ equal: 'equal to {FORMULA1}',
+ greaterThan: 'greater than {FORMULA1}',
+ greaterThanOrEqual: 'greater than or equal to {FORMULA1}',
+ lessThan: 'less than {FORMULA1}',
+ lessThanOrEqual: 'less than or equal to {FORMULA1}',
+ notBetween: 'not between {FORMULA1} and {FORMULA2}',
+ notEqual: 'not equal to {FORMULA1}',
+ legal: 'Legal {TYPE}',
+ },
+ errorMsg: {
+ between: 'Value must be between {FORMULA1} and {FORMULA2}',
+ equal: 'Value must equal {FORMULA1}',
+ greaterThan: 'Value must be greater than {FORMULA1}',
+ greaterThanOrEqual: 'Value must be greater than or equal to {FORMULA1}',
+ lessThan: 'Value must be less than {FORMULA1}',
+ lessThanOrEqual: 'Value must be less than or equal to {FORMULA1}',
+ notBetween: 'Value must not be between {FORMULA1} and {FORMULA2}',
+ notEqual: 'Value must not equal {FORMULA1}',
+ legal: 'Value must satisfy {TYPE}',
+ },
+ },
+ },
+ });
+ localeService.setLocale(LocaleType.EN_US);
+
+ registryService = get(DataValidatorRegistryService);
+ validator = new TestDataValidator(localeService, injector);
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('registers validators by scope and removes them with the returned disposable', () => {
+ const changes: number[] = [];
+ const sub = registryService.validatorsChange$.subscribe(() => changes.push(changes.length));
+
+ const disposable = registryService.register(validator);
+
+ expect(registryService.getValidatorItem(validator.id)).toBe(validator);
+ expect(registryService.getValidatorsByScope(DataValidatorRegistryScope.SHEET)).toContain(validator);
+ expect(registryService.getValidatorsByScope('custom-scope')).toContain(validator);
+
+ expect(() => registryService.register(new TestDataValidator(localeService, get as never))).toThrow(/same id/);
+
+ disposable.dispose();
+
+ expect(registryService.getValidatorItem(validator.id)).toBeUndefined();
+ expect(registryService.getValidatorsByScope(DataValidatorRegistryScope.SHEET)).toEqual([]);
+ expect(changes.length).toBeGreaterThanOrEqual(3);
+
+ sub.unsubscribe();
+ });
+
+ it('generates translated rule labels and validates values through the main validator flow', async () => {
+ expect(validator.operatorNames).toEqual([
+ 'between',
+ 'equal',
+ 'greater than',
+ 'greater than or equal',
+ 'less than',
+ 'less than or equal',
+ 'not between',
+ 'not equal',
+ ]);
+ expect(validator.titleStr).toBe('Number');
+ expect(validator.generateRuleName(createRule())).toBe('Number between 1 and 5');
+ expect(validator.generateRuleName(createRule({ operator: undefined }))).toBe('Legal Number');
+ expect(validator.generateRuleErrorMessage(createRule({ operator: DataValidationOperator.LESS_THAN, formula1: '10' }), {
+ row: 0,
+ col: 0,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ })).toBe('Value must be less than 10');
+
+ expect(validator.getRuleFinalError(createRule(), {
+ row: 0,
+ col: 0,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ })).toBe('Explicit error');
+ expect(validator.getRuleFinalError(createRule({ showErrorMessage: false, error: 'ignored' }), {
+ row: 0,
+ col: 0,
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ })).toBe('Value must be between 1 and 5');
+
+ expect(validator.isEmptyCellValue('')).toBe(true);
+ expect(validator.isEmptyCellValue(null)).toBe(true);
+ expect(validator.isEmptyCellValue(0)).toBe(false);
+ expect(validator.normalizeFormula(createRule({ formula1: '=A1', formula2: '=B1' }), 'unit-1', 'sheet-1')).toEqual({
+ formula1: '=A1',
+ formula2: '=B1',
+ });
+ expect(validator.validatorFormula(createRule({ formula1: '7', formula2: '9' }), 'unit-1', 'sheet-1')).toEqual({
+ success: true,
+ formula1: '7',
+ formula2: '9',
+ });
+
+ await expect(validator.validator(createCellInfo(''), createRule({ allowBlank: false }))).resolves.toBe(false);
+
+ validator.formulaResult = {
+ formula1: 1,
+ formula2: 5,
+ isFormulaValid: false,
+ };
+ await expect(validator.validator(createCellInfo(3), createRule())).resolves.toBe(false);
+
+ validator.formulaResult = {
+ formula1: 1,
+ formula2: 5,
+ isFormulaValid: true,
+ };
+ validator.validType = false;
+ await expect(validator.validator(createCellInfo(3), createRule())).resolves.toBe(false);
+
+ validator.validType = true;
+ await expect(validator.validator(createCellInfo(3), createRule({ operator: undefined }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(3), createRule({ operator: DataValidationOperator.BETWEEN }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(9), createRule({ operator: DataValidationOperator.NOT_BETWEEN }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(5), createRule({ operator: DataValidationOperator.EQUAL, formula1: '5' }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(5), createRule({ operator: DataValidationOperator.NOT_EQUAL, formula1: '6' }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(6), createRule({ operator: DataValidationOperator.GREATER_THAN, formula1: '5' }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(5), createRule({ operator: DataValidationOperator.GREATER_THAN_OR_EQUAL, formula1: '5' }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(4), createRule({ operator: DataValidationOperator.LESS_THAN, formula1: '5' }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(5), createRule({ operator: DataValidationOperator.LESS_THAN_OR_EQUAL, formula1: '5' }))).resolves.toBe(true);
+
+ validator.formulaResult = {
+ formula1: Number.NaN,
+ formula2: Number.NaN,
+ isFormulaValid: true,
+ };
+ await expect(validator.validator(createCellInfo(10), createRule({ operator: DataValidationOperator.BETWEEN, formula1: 'NaN', formula2: 'NaN' }))).resolves.toBe(true);
+ await expect(validator.validator(createCellInfo(10), createRule({ operator: 'unexpected' as DataValidationOperator }))).rejects.toThrow('Unknown operator.');
+ });
+});
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
new file mode 100644
index 0000000000..09d7c5406f
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
@@ -0,0 +1,195 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ArrangeTypeEnum, Direction, ICommandService, IUniverInstanceService, JSONX, PositionedObjectLayoutType } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { IDocDrawingService } from '@univerjs/docs-drawing';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { describe, expect, it, vi } from 'vitest';
+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']),
+ };
+ 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 } },
+ },
+ },
+ }),
+ })),
+ };
+ const docSelectionManagerService = {
+ getActiveTextRange: vi.fn(() => ({ collapsed: true, startOffset: 1, segmentId: '' })),
+ };
+
+ return {
+ accessor: {
+ get(token: unknown) {
+ if (token === ICommandService) {
+ return commandService;
+ }
+
+ if (token === IDocDrawingService) {
+ return docDrawingService;
+ }
+
+ if (token === IRenderManagerService) {
+ return renderManagerService;
+ }
+
+ if (token === IUniverInstanceService) {
+ return univerInstanceService;
+ }
+
+ if (token === DocSelectionManagerService) {
+ return docSelectionManagerService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor,
+ commandService,
+ currentDocument,
+ docDrawingService,
+ docSelectionManagerService,
+ };
+}
+
+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();
+
+ expect(SetDocDrawingArrangeCommand.handler(accessor, {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingIds: ['shape-1'],
+ arrangeType: ArrangeTypeEnum.forward,
+ })).toBe(true);
+ expect(composeSpy).toHaveBeenCalled();
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(RichTextEditingMutation.id, {
+ unitId: 'doc-1',
+ actions: ['composed'],
+ textRanges: null,
+ });
+ });
+
+ 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' }],
+ });
+
+ docDrawingService.getFocusDrawings.mockReturnValue([]);
+ expect(await DeleteDocDrawingsCommand.handler(accessor)).toBe(false);
+ });
+
+ 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('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('returns false when inserting drawings without an active text range', () => {
+ const { accessor, commandService, docSelectionManagerService } = createAccessor();
+ docSelectionManagerService.getActiveTextRange.mockReturnValue(null as never);
+
+ expect(InsertDocDrawingCommand.handler(accessor, {
+ drawings: [{ drawingId: 'shape-2', unitId: 'doc-1', subUnitId: 'doc-1' }],
+ } as never)).toBe(false);
+ expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/utils.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..83e06fc422
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/utils.spec.ts
@@ -0,0 +1,94 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DrawingTypeEnum } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { groupToUngroup, ungroupToGroup } from '../utils';
+
+vi.mock('@univerjs/engine-render', () => ({
+ getGroupState: vi.fn(() => ({ left: 10, top: 20, width: 100, height: 50 })),
+ transformObjectOutOfGroup: vi.fn((transform, groupTransform) => ({
+ left: (transform.left ?? 0) + (groupTransform.left ?? 0),
+ top: (transform.top ?? 0) + (groupTransform.top ?? 0),
+ width: transform.width,
+ height: transform.height,
+ })),
+}));
+
+describe('docs drawing command utils', () => {
+ it('rebuilds group metadata from ungrouped drawings', () => {
+ expect(ungroupToGroup([
+ {
+ parent: { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'group-1' },
+ children: [
+ { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'child-1', transform: { left: 2, top: 3 } },
+ { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'child-2', transform: { left: 4, top: 5 } },
+ ],
+ },
+ ] as never)).toEqual([
+ {
+ parent: {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'group-1',
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: { left: 10, top: 20, width: 100, height: 50 },
+ groupBaseBound: { left: 10, top: 20, width: 100, height: 50 },
+ },
+ children: [
+ { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'child-1', transform: { left: 2, top: 3 }, groupId: 'group-1' },
+ { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'child-2', transform: { left: 4, top: 5 }, groupId: 'group-1' },
+ ],
+ },
+ ]);
+ });
+
+ it('projects grouped children back out of the group transform', () => {
+ expect(groupToUngroup([
+ {
+ parent: {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'group-1',
+ transform: { left: 10, top: 20, width: 100, height: 50 },
+ groupBaseBound: { left: 10, top: 20, width: 100, height: 50 },
+ },
+ children: [
+ { unitId: 'doc-1', subUnitId: 'doc-1', drawingId: 'child-1', transform: { left: 2, top: 3, width: 4, height: 5 } },
+ ],
+ },
+ ] as never)).toEqual([
+ {
+ parent: {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'group-1',
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: { left: 0, top: 0 },
+ },
+ children: [
+ {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ drawingId: 'child-1',
+ transform: { left: 12, top: 23, width: 4, height: 5 },
+ groupId: undefined,
+ },
+ ],
+ },
+ ]);
+ });
+});
diff --git a/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts b/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
new file mode 100644
index 0000000000..a36f687ff9
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
@@ -0,0 +1,69 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { LocaleService } from '@univerjs/core';
+import { IDrawingManagerService } from '@univerjs/drawing';
+import { ISidebarService } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { COMPONENT_DOC_DRAWING_PANEL } from '../../../views/doc-image-panel/component-name';
+import { SidebarDocDrawingOperation } from '../open-drawing-panel.operation';
+
+function createAccessor() {
+ const sidebarService = { open: vi.fn(), close: vi.fn() };
+ const drawingManagerService = { focusDrawing: vi.fn() };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ISidebarService) {
+ return sidebarService;
+ }
+
+ if (token === LocaleService) {
+ return { t: (key: string) => key };
+ }
+
+ if (token === IDrawingManagerService) {
+ return drawingManagerService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return { accessor, sidebarService, drawingManagerService };
+}
+
+describe('SidebarDocDrawingOperation', () => {
+ it('opens the doc drawing sidebar and clears focus when closed', async () => {
+ const { accessor, sidebarService, drawingManagerService } = createAccessor();
+ await expect(SidebarDocDrawingOperation.handler(accessor, { value: 'open' })).resolves.toBe(true);
+ expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ header: { title: 'docImage.panel.title' },
+ children: { label: COMPONENT_DOC_DRAWING_PANEL },
+ width: 360,
+ }));
+ const onClose = sidebarService.open.mock.calls[0][0].onClose;
+ onClose();
+ expect(drawingManagerService.focusDrawing).toHaveBeenCalledWith(null);
+ });
+
+ it('closes the sidebar for close and default actions', async () => {
+ const { accessor, sidebarService } = createAccessor();
+ await expect(SidebarDocDrawingOperation.handler(accessor, { value: 'close' })).resolves.toBe(true);
+ await expect(SidebarDocDrawingOperation.handler(accessor, { value: 'anything-else' })).resolves.toBe(true);
+ expect(sidebarService.close).toHaveBeenCalledTimes(2);
+ });
+});
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
new file mode 100644
index 0000000000..48ed9b0e6a
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-notification.controller.spec.ts
@@ -0,0 +1,131 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { 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
new file mode 100644
index 0000000000..8eb3b92e54
--- /dev/null
+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing.controller.spec.ts
@@ -0,0 +1,43 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import 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-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.ts b/packages/docs-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.ts
new file mode 100644
index 0000000000..dfe454690b
--- /dev/null
+++ b/packages/docs-drawing-ui/src/services/__tests__/doc-refresh-drawings.service.spec.ts
@@ -0,0 +1,33 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { DocRefreshDrawingsService } from '../doc-refresh-drawings.service';
+
+describe('DocRefreshDrawingsService', () => {
+ it('emits the latest document skeleton refresh request', () => {
+ const service = new DocRefreshDrawingsService();
+ const values: unknown[] = [];
+ const sub = service.refreshDrawings$.subscribe((value) => values.push(value));
+ const skeleton = { id: 'skeleton-1' };
+
+ service.refreshDrawings(skeleton as never);
+ service.refreshDrawings(null);
+
+ expect(values).toEqual([null, skeleton, null]);
+ sub.unsubscribe();
+ });
+});
diff --git a/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts b/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts
new file mode 100644
index 0000000000..53ea849e95
--- /dev/null
+++ b/packages/docs-drawing/src/controllers/__tests__/doc-drawing.controller.spec.ts
@@ -0,0 +1,87 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { UniverInstanceType } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { DocDrawingController, DOCS_DRAWING_PLUGIN } from '../doc-drawing.controller';
+
+describe('DocDrawingController', () => {
+ it('should serialize snapshot and load resources into drawing services', () => {
+ const registerDrawingData = vi.fn();
+ const registerDrawingDataForManager = vi.fn();
+
+ let snapshot: any = {
+ drawings: { d1: { id: 'd1', drawingType: 'image' } },
+ drawingsOrder: ['d1'],
+ };
+
+ const doc = {
+ getSnapshot: () => snapshot,
+ resetDrawing: (data: any, order: any) => {
+ snapshot = { ...snapshot, drawings: data, drawingsOrder: order };
+ },
+ getDrawings: () => snapshot.drawings,
+ getDrawingsOrder: () => snapshot.drawingsOrder,
+ };
+
+ const univerInstanceService = {
+ getUnit: vi.fn((_unitId: string, _type?: UniverInstanceType) => doc),
+ };
+
+ let capturedResource: any;
+ const resourceManagerService = {
+ registerPluginResource: vi.fn((resource: any) => {
+ capturedResource = resource;
+ return { dispose: vi.fn() };
+ }),
+ };
+
+ const controller = new DocDrawingController(
+ { registerDrawingData } as any,
+ { registerDrawingData: registerDrawingDataForManager } as any,
+ resourceManagerService as any,
+ univerInstanceService as any
+ );
+
+ expect(resourceManagerService.registerPluginResource).toHaveBeenCalledTimes(1);
+ expect(capturedResource.pluginName).toBe(DOCS_DRAWING_PLUGIN);
+ expect(capturedResource.businesses).toEqual([UniverInstanceType.UNIVER_DOC]);
+
+ const json = capturedResource.toJson('doc-1');
+ const parsed = JSON.parse(json);
+ expect(parsed.data).toEqual(snapshot.drawings);
+ expect(parsed.order).toEqual(snapshot.drawingsOrder);
+
+ expect(capturedResource.parseJson('')).toEqual({ data: {}, order: [] });
+ expect(capturedResource.parseJson('{bad json')).toEqual({ data: {}, order: [] });
+
+ capturedResource.onLoad('doc-1', { data: { d2: { id: 'd2' } }, order: ['d2'] });
+ expect(registerDrawingData).toHaveBeenCalledWith('doc-1', expect.any(Object));
+ expect(registerDrawingDataForManager).toHaveBeenCalledWith('doc-1', expect.any(Object));
+
+ capturedResource.onUnLoad('doc-1');
+ expect(registerDrawingData).toHaveBeenLastCalledWith('doc-1', {
+ 'doc-1': {
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ data: {},
+ order: [],
+ },
+ });
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
new file mode 100644
index 0000000000..fe9b727ad4
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/add-doc-comment.command.spec.ts
@@ -0,0 +1,120 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData } from '@univerjs/core';
+import { CommandType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';
+import { AddCommentMutation, IThreadCommentDataSourceService, ThreadCommentDataSourceService } from '@univerjs/thread-comment';
+import { SetActiveCommentOperation } from '@univerjs/thread-comment-ui';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AddDocCommentComment } from '../add-doc-comment.command';
+
+function createDocData(id: string): IDocumentData {
+ return {
+ id,
+ body: {
+ dataStream: 'Hello world\r\n',
+ customDecorations: [],
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
+describe('AddDocCommentComment', () => {
+ let univer: Univer;
+ let injector: ReturnType<Univer['__getInjector']>;
+
+ beforeEach(() => {
+ univer = new Univer();
+ injector = univer.__getInjector();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should add comment and attach decoration via sequenceExecute', async () => {
+ const dataSource = new ThreadCommentDataSourceService();
+ vi.spyOn(dataSource, 'addComment').mockImplementation(async (c) => ({ ...c, id: 'comment-1', threadId: 'thread-1' }));
+
+ injector.add([IThreadCommentDataSourceService, { useValue: dataSource }]);
+ injector.add([DocSelectionManagerService]);
+
+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-1'));
+ injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());
+
+ const selectionManager = injector.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({ unitId: doc.getUnitId(), subUnitId: doc.getUnitId() });
+ selectionManager.__TEST_ONLY_add([{ startOffset: 0, endOffset: 5, collapsed: false, isActive: true }] as never);
+
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand({
+ id: AddCommentMutation.id,
+ type: CommandType.MUTATION,
+ handler: (_accessor, params) => {
+ executed.push({ id: AddCommentMutation.id, params });
+ return true;
+ },
+ });
+ commandService.registerCommand({
+ id: RichTextEditingMutation.id,
+ type: CommandType.MUTATION,
+ handler: (_accessor, params) => {
+ executed.push({ id: RichTextEditingMutation.id, params });
+ return true;
+ },
+ });
+ commandService.registerCommand({
+ id: SetActiveCommentOperation.id,
+ type: CommandType.OPERATION,
+ handler: (_accessor, params) => {
+ executed.push({ id: SetActiveCommentOperation.id, params });
+ return true;
+ },
+ });
+
+ const ok = await AddDocCommentComment.handler(injector as any, {
+ unitId: 'doc-1',
+ range: { startOffset: 1, endOffset: 2, collapsed: false },
+ comment: { id: '', threadId: '', unitId: 'doc-1', subUnitId: 'default_doc', ref: '' } as any,
+ });
+
+ expect(ok).toBe(true);
+ expect(dataSource.addComment).toHaveBeenCalled();
+ expect(executed.map((command) => command.id)).toEqual([
+ AddCommentMutation.id,
+ RichTextEditingMutation.id,
+ SetActiveCommentOperation.id,
+ ]);
+ expect(executed[0].params).toEqual(expect.objectContaining({
+ unitId: 'doc-1',
+ comment: expect.objectContaining({ id: 'comment-1', threadId: 'thread-1' }),
+ }));
+ expect(executed[1].params).toEqual(expect.objectContaining({ unitId: 'doc-1' }));
+ });
+
+ it('should return false when missing params', async () => {
+ const ok = await AddDocCommentComment.handler({ get: vi.fn() } as any, undefined as any);
+ expect(ok).toBe(false);
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.ts b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.ts
new file mode 100644
index 0000000000..67615ca1cb
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/commands/commands/__tests__/delete-doc-comment.command.spec.ts
@@ -0,0 +1,79 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData } from '@univerjs/core';
+import { CommandType, ICommandService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';
+import { RichTextEditingMutation } from '@univerjs/docs';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DeleteDocCommentComment } from '../delete-doc-comment.command';
+
+function createDocData(id: string): IDocumentData {
+ return {
+ id,
+ body: {
+ dataStream: 'Hello world\r\n',
+ customDecorations: [{ id: 'c1', startIndex: 0, endIndex: 5, type: 1 as never }],
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
+describe('DeleteDocCommentComment', () => {
+ let univer: Univer;
+ let injector: ReturnType<Univer['__getInjector']>;
+
+ beforeEach(() => {
+ univer = new Univer();
+ injector = univer.__getInjector();
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('should delete decoration via sequenceExecute', async () => {
+ const doc = univer.createUnit(UniverInstanceType.UNIVER_DOC, createDocData('doc-1'));
+ injector.get(IUniverInstanceService).focusUnit(doc.getUnitId());
+
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const commandService = injector.get(ICommandService);
+ commandService.registerCommand({
+ id: RichTextEditingMutation.id,
+ type: CommandType.MUTATION,
+ handler: (_accessor, params) => {
+ executed.push({ id: RichTextEditingMutation.id, params });
+ return true;
+ },
+ });
+
+ const ok = await DeleteDocCommentComment.handler(injector as any, { unitId: 'doc-1', commentId: 'c1' });
+ expect(ok).toBe(true);
+ expect(executed).toHaveLength(1);
+ expect(executed[0]).toEqual(expect.objectContaining({ id: RichTextEditingMutation.id }));
+ expect(executed[0].params).toEqual(expect.objectContaining({ unitId: 'doc-1' }));
+ });
+
+ it('should return false when missing params', async () => {
+ const ok = await DeleteDocCommentComment.handler({ get: vi.fn() } as any, undefined as any);
+ expect(ok).toBe(false);
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.ts b/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.ts
new file mode 100644
index 0000000000..aa0e69eba7
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/commands/operations/__tests__/show-comment-panel.operation.spec.ts
@@ -0,0 +1,89 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { DocThreadCommentPanel } from '../../../views/doc-thread-comment-panel';
+import { ShowCommentPanelOperation, ToggleCommentPanelOperation } from '../show-comment-panel.operation';
+
+describe('ShowCommentPanelOperation', () => {
+ it('should open sidebar and set active comment', () => {
+ const setPanelVisible = vi.fn();
+ const setActiveComment = vi.fn();
+ const panelService = {
+ panelVisible: false,
+ setPanelVisible,
+ setActiveComment,
+ };
+
+ const open = vi.fn();
+ const sidebarService = {
+ options: {},
+ open,
+ };
+
+ const accessor = {
+ get: (token: any) => {
+ if (token.name === 'ThreadCommentPanelService') return panelService;
+ return sidebarService;
+ },
+ } as any;
+
+ const ok = ShowCommentPanelOperation.handler(accessor, {
+ activeComment: { unitId: 'doc-1', subUnitId: 'default', commentId: 'c1' },
+ });
+
+ expect(ok).toBe(true);
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({
+ children: { label: DocThreadCommentPanel.componentKey },
+ width: 320,
+ }));
+ expect(setPanelVisible).toHaveBeenCalledWith(true);
+ expect(setActiveComment).toHaveBeenCalledWith({ unitId: 'doc-1', subUnitId: 'default', commentId: 'c1' });
+ });
+});
+
+describe('ToggleCommentPanelOperation', () => {
+ it('should close sidebar and reset state when already opened', () => {
+ const setPanelVisible = vi.fn();
+ const setActiveComment = vi.fn();
+ const panelService = {
+ panelVisible: true,
+ setPanelVisible,
+ setActiveComment,
+ };
+
+ const close = vi.fn();
+ const sidebarService = {
+ options: { children: { label: DocThreadCommentPanel.componentKey } },
+ open: vi.fn(),
+ close,
+ };
+
+ const accessor = {
+ get: (token: any) => {
+ if (token.name === 'ThreadCommentPanelService') return panelService;
+ return sidebarService;
+ },
+ } as any;
+
+ const ok = ToggleCommentPanelOperation.handler(accessor);
+ expect(ok).toBe(true);
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(setPanelVisible).toHaveBeenCalledWith(false);
+ expect(setActiveComment).toHaveBeenCalledWith(null);
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts
new file mode 100644
index 0000000000..faad5b405d
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-selection.controller.spec.ts
@@ -0,0 +1,128 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { SetTextSelectionsOperation } from '@univerjs/docs';
+import { SetActiveCommentOperation } from '@univerjs/thread-comment-ui';
+
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { ShowCommentPanelOperation } from '../../commands/operations/show-comment-panel.operation';
+import { DEFAULT_DOC_SUBUNIT_ID } from '../../common/const';
+import { DocThreadCommentSelectionController } from '../doc-thread-comment-selection.controller';
+
+describe('DocThreadCommentSelectionController', () => {
+ it('should show comment panel when selection enters a comment decoration', () => {
+ const activeCommentId$ = new Subject<any>();
+ const threadCommentPanelService = {
+ activeCommentId: null,
+ activeCommentId$,
+ };
+
+ const doc = {
+ getBody: () => ({ customDecorations: [{ id: 'c1', startIndex: 0, endIndex: 5 }] }),
+ };
+
+ const univerInstanceService = {
+ getUnit: vi.fn(() => doc),
+ };
+
+ let onExecutedHandler: any;
+ const executeCommand = vi.fn();
+ const commandService = {
+ onCommandExecuted: vi.fn((fn) => {
+ onExecutedHandler = fn;
+ return { dispose: vi.fn() };
+ }),
+ executeCommand,
+ };
+
+ const docThreadCommentService = { addingComment: null, endAdd: vi.fn() };
+ const renderManagerService = { getRenderById: vi.fn(() => null) };
+ const threadCommentModel = { getComment: vi.fn(() => ({ resolved: false })) };
+
+ const controller = new DocThreadCommentSelectionController(
+ threadCommentPanelService as any,
+ univerInstanceService as any,
+ commandService as any,
+ docThreadCommentService as any,
+ renderManagerService as any,
+ threadCommentModel as any
+ );
+
+ onExecutedHandler({
+ id: SetTextSelectionsOperation.id,
+ params: {
+ unitId: 'doc-1',
+ ranges: [{ startOffset: 1, endOffset: 2, collapsed: true }],
+ },
+ });
+
+ expect(executeCommand).toHaveBeenCalledWith(ShowCommentPanelOperation.id, {
+ activeComment: { unitId: 'doc-1', subUnitId: DEFAULT_DOC_SUBUNIT_ID, commentId: 'c1' },
+ });
+
+ controller.dispose();
+ });
+
+ it('should reset active comment when selection moves out', () => {
+ const activeCommentId$ = new Subject<any>();
+ const threadCommentPanelService = {
+ activeCommentId: { unitId: 'doc-1', subUnitId: DEFAULT_DOC_SUBUNIT_ID, commentId: 'c1' },
+ activeCommentId$,
+ };
+
+ const doc = {
+ getBody: () => ({ customDecorations: [{ id: 'c1', startIndex: 0, endIndex: 5 }] }),
+ };
+
+ const univerInstanceService = { getUnit: vi.fn(() => doc) };
+
+ let onExecutedHandler: any;
+ const executeCommand = vi.fn();
+ const commandService = {
+ onCommandExecuted: vi.fn((fn) => {
+ onExecutedHandler = fn;
+ return { dispose: vi.fn() };
+ }),
+ executeCommand,
+ };
+
+ const docThreadCommentService = { addingComment: null, endAdd: vi.fn() };
+ const renderManagerService = { getRenderById: vi.fn(() => null) };
+ const threadCommentModel = { getComment: vi.fn(() => ({ resolved: false })) };
+
+ const controller = new DocThreadCommentSelectionController(
+ threadCommentPanelService as any,
+ univerInstanceService as any,
+ commandService as any,
+ docThreadCommentService as any,
+ renderManagerService as any,
+ threadCommentModel as any
+ );
+
+ onExecutedHandler({
+ id: SetTextSelectionsOperation.id,
+ params: {
+ unitId: 'doc-1',
+ ranges: [{ startOffset: 10, endOffset: 10, collapsed: true }],
+ },
+ });
+
+ expect(executeCommand).toHaveBeenCalledWith(SetActiveCommentOperation.id);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-ui.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-ui.controller.spec.ts
new file mode 100644
index 0000000000..7e7410c97f
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/controllers/__tests__/doc-thread-comment-ui.controller.spec.ts
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { DocThreadCommentPanel } from '../../views/doc-thread-comment-panel';
+import { DocThreadCommentUIController } from '../doc-thread-comment-ui.controller';
+
+describe('DocThreadCommentUIController', () => {
+ it('should register commands, menus and components', () => {
+ const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));
+ const mergeMenu = vi.fn();
+ const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));
+
+ const controller = new DocThreadCommentUIController(
+ { registerCommand } as any,
+ { mergeMenu } as any,
+ { register: registerComponent } as any
+ );
+
+ expect(registerCommand).toHaveBeenCalled();
+ expect(mergeMenu).toHaveBeenCalled();
+ expect(registerComponent).toHaveBeenCalledWith(DocThreadCommentPanel.componentKey, DocThreadCommentPanel);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts b/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
new file mode 100644
index 0000000000..45ee710320
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/controllers/render-controllers/__tests__/render.controller.spec.ts
@@ -0,0 +1,146 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CustomDecorationType } from '@univerjs/core';
+import { DOC_INTERCEPTOR_POINT, RichTextEditingMutation } from '@univerjs/docs';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+
+import { DEFAULT_DOC_SUBUNIT_ID } from '../../../common/const';
+import { DocThreadCommentRenderController } from '../render.controller';
+
+describe('DocThreadCommentRenderController', () => {
+ it('should intercept decoration view-model based on active comment and resolved status', () => {
+ let handler: any;
+ const docInterceptorService = {
+ intercept: vi.fn((point, config) => {
+ if (point === DOC_INTERCEPTOR_POINT.CUSTOM_DECORATION) {
+ handler = config.handler;
+ }
+ return { dispose: vi.fn() };
+ }),
+ };
+
+ const reRender = vi.fn();
+ const docRenderController = { reRender };
+
+ const activeCommentId$ = new Subject<any>();
+ const threadCommentPanelService = {
+ activeCommentId: { unitId: 'doc-1', subUnitId: DEFAULT_DOC_SUBUNIT_ID, commentId: 'c2' },
+ activeCommentId$,
+ };
+
+ const univerInstanceService = {
+ getCurrentUnitForType: vi.fn(() => ({ getUnitId: () => 'doc-1' })),
+ };
+
+ const commentUpdate$ = new Subject<any>();
+ const threadCommentModel = {
+ commentUpdate$,
+ getComment: vi.fn((_unitId: string, _subUnitId: string, id: string) => (id === 'c1' ? null : { id, resolved: false })),
+ addComment: vi.fn(),
+ syncThreadComments: vi.fn(),
+ };
+
+ let onCommandExecuted: any;
+ const commandService = {
+ onCommandExecuted: vi.fn((fn) => {
+ onCommandExecuted = fn;
+ return { dispose: vi.fn() };
+ }),
+ };
+
+ const unit = {
+ getUnitId: () => 'doc-1',
+ getBody: () => ({ customDecorations: [{ id: 'c1', type: CustomDecorationType.COMMENT }, { id: 'c2', type: CustomDecorationType.COMMENT }] }),
+ };
+ const context = { unit };
+
+ const controller = new DocThreadCommentRenderController(
+ context as any,
+ docInterceptorService as any,
+ threadCommentPanelService as any,
+ docRenderController as any,
+ univerInstanceService as any,
+ threadCommentModel as any,
+ commandService as any
+ );
+
+ const next = (v: any) => v;
+ const outActive = handler(
+ { id: 'c2' },
+ {
+ unitId: 'doc-1',
+ index: 3,
+ customDecorations: [{ id: 'c2', startIndex: 0, endIndex: 5 }],
+ },
+ next
+ );
+ expect(outActive.active).toBe(true);
+ expect(outActive.show).toBe(true);
+
+ const outResolved = handler(
+ { id: 'c1' },
+ {
+ unitId: 'doc-1',
+ index: 3,
+ customDecorations: [{ id: 'c2', startIndex: 0, endIndex: 5 }],
+ },
+ next
+ );
+ expect(outResolved.show).toBe(false);
+
+ // resolved branch triggers rerender
+ threadCommentModel.getComment.mockImplementation((_unitId: string, _subUnitId: string, id: string) => {
+ if (id === 'c1') return null;
+ return { id, resolved: id === 'c2' };
+ });
+ const outResolvedComment = handler(
+ { id: 'c2' },
+ {
+ unitId: 'doc-1',
+ index: 3,
+ customDecorations: [{ id: 'c2', startIndex: 0, endIndex: 5 }],
+ },
+ next
+ );
+ expect(outResolvedComment.show).toBe(false);
+
+ // rerender on active comment changes
+ activeCommentId$.next({ unitId: 'doc-1', subUnitId: DEFAULT_DOC_SUBUNIT_ID, commentId: 'c1' });
+ expect(reRender).toHaveBeenCalledWith('doc-1');
+
+ // rerender on resolve updates
+ commentUpdate$.next({ type: 'resolve', unitId: 'doc-1' });
+ expect(reRender).toHaveBeenCalledWith('doc-1');
+
+ // trigger sync on rich text mutations (add new decoration)
+ // NOTE: `_initSyncComments` compares sorted thread ids. We emulate that the doc body returns a stable
+ // list that changes when mutation happens.
+ unit.getBody = () => ({
+ customDecorations: [
+ { id: 'c1', type: CustomDecorationType.COMMENT },
+ { id: 'c2', type: CustomDecorationType.COMMENT },
+ { id: 'c3', type: CustomDecorationType.COMMENT },
+ ],
+ });
+
+ onCommandExecuted({ id: RichTextEditingMutation.id, params: { unitId: 'doc-1' } });
+ expect(threadCommentModel.syncThreadComments).toHaveBeenCalledWith('doc-1', DEFAULT_DOC_SUBUNIT_ID, ['c3']);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/docs-thread-comment-ui/src/menu/__tests__/menu.spec.ts b/packages/docs-thread-comment-ui/src/menu/__tests__/menu.spec.ts
new file mode 100644
index 0000000000..94eef4790d
--- /dev/null
+++ b/packages/docs-thread-comment-ui/src/menu/__tests__/menu.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DocumentEditArea } from '@univerjs/engine-render';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AddDocCommentMenuItemFactory, shouldDisableAddComment, ToolbarDocCommentMenuItemFactory } from '../menu';
+
+vi.mock('@univerjs/engine-render', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/engine-render')>('@univerjs/engine-render');
+ return {
+ ...actual,
+ withCurrentTypeOfRenderer: vi.fn(() => ({
+ getSkeleton: () => ({
+ getViewModel: () => ({
+ getEditArea: () => DocumentEditArea.BODY,
+ }),
+ }),
+ })),
+ };
+});
+
+vi.mock('@univerjs/ui', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');
+ return {
+ ...actual,
+ getMenuHiddenObservable: vi.fn(() => null),
+ };
+});
+
+describe('docs-thread-comment-ui menu', () => {
+ it('shouldDisableAddComment returns true when selection is collapsed', () => {
+ const accessor = {
+ get: vi.fn((token) => {
+ if (token.name === 'IRenderManagerService') return {};
+ if (token.name === 'DocSelectionManagerService') {
+ return { getActiveTextRange: () => ({ collapsed: true }) };
+ }
+ if (token.name === 'IUniverInstanceService') return {};
+ return {};
+ }),
+ } as any;
+
+ expect(shouldDisableAddComment(accessor)).toBe(true);
+ });
+
+ it('menu factories should return correct ids', () => {
+ const accessor = { get: vi.fn(() => ({ textSelection$: { pipe: () => ({ subscribe: () => ({ unsubscribe: vi.fn() }) }) } })) } as any;
+
+ const addItem = AddDocCommentMenuItemFactory(accessor);
+ const toolbarItem = ToolbarDocCommentMenuItemFactory(accessor);
+ expect(addItem.id).toBe('docs.operation.start-add-comment');
+ expect(toolbarItem.id).toBe('docs.operation.toggle-comment-panel');
+ });
+});
diff --git a/packages/core/src/__tests__/entry.spec.ts b/packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.ts
similarity index 53%
rename from packages/core/src/__tests__/entry.spec.ts
rename to packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.ts
index 2582faa46e..c537328786 100644
--- a/packages/core/src/__tests__/entry.spec.ts
+++ b/packages/docs-thread-comment-ui/src/services/__tests__/doc-thread-comment.service.spec.ts
@@ -16,13 +16,21 @@
import { describe, expect, it } from 'vitest';
-describe('core entry', () => {
- it('should expose major APIs from index', async () => {
- const mod = await import('../index');
+import { DocThreadCommentService } from '../doc-thread-comment.service';
- expect(typeof mod.Univer).toBe('function');
- expect(typeof mod.Skeleton).toBe('function');
- expect(typeof mod.Workbook).toBe('function');
- expect(typeof mod.Range).toBe('function');
+describe('DocThreadCommentService', () => {
+ it('should track adding comment lifecycle', () => {
+ const service = new DocThreadCommentService({} as any, {} as any);
+
+ expect(service.addingComment).toBeUndefined();
+
+ const comment = { id: 'c1', startOffset: 1, endOffset: 2 };
+ service.startAdd(comment as any);
+ expect(service.addingComment).toEqual(comment);
+
+ service.endAdd();
+ expect(service.addingComment).toBeUndefined();
+
+ service.dispose();
});
});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts
new file mode 100644
index 0000000000..14a2f09501
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/break-line.command.spec.ts
@@ -0,0 +1,99 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { BreakLineCommand } from '../break-line.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function getDocumentData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Title\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 5,
+ ts: {},
+ }],
+ paragraphs: [{
+ startIndex: 5,
+ paragraphStyle: {
+ headingId: 'heading-1',
+ namedStyleType: NamedStyleType.HEADING_1,
+ },
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('break line command', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ function getParagraphs() {
+ const univerInstanceService = get(IUniverInstanceService);
+ return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody()?.paragraphs ?? [];
+ }
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(getDocumentData());
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(BreakLineCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ selectionManager.__TEST_ONLY_add([{ startOffset: 5, endOffset: 5, collapsed: true, isActive: true, segmentId: '', style: null as never }]);
+ });
+
+ afterEach(() => univer.dispose());
+
+ it('splits a heading paragraph and resets heading style for the new paragraph', async () => {
+ await commandService.executeCommand(BreakLineCommand.id);
+
+ await waitNextTick();
+
+ expect(getParagraphs()).toHaveLength(2);
+ expect(getParagraphs()[0].paragraphStyle?.namedStyleType).toBe(NamedStyleType.HEADING_1);
+ expect(getParagraphs()[1].paragraphStyle?.namedStyleType).toBeUndefined();
+ expect(getParagraphs()[1].paragraphStyle?.headingId).toBeUndefined();
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts
index 3f89472658..8aaaa0ec58 100644
--- a/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts
+++ b/packages/docs-ui/src/commands/commands/__tests__/core-editing.command.spec.ts
@@ -14,31 +14,161 @@
* limitations under the License.
*/
-import type { Injector, Univer } from '@univerjs/core';
-import { ICommandService } from '@univerjs/core';
+import type { DocumentDataModel, ICommand, IDocumentData, Injector, IStyleBase, Univer } from '@univerjs/core';
+import {
+ BooleanNumber,
+ CustomRangeType,
+ ICommandService,
+ IUniverInstanceService,
+ UniverInstanceType,
+ UpdateDocsAttributeType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { SetInlineFormatBoldCommand } from '../inline-format.command';
+import { DeleteDirection } from '../../../types/delete-direction';
+import { DeleteCommand, InsertCommand, UpdateCommand } from '../core-editing.command';
import { createCommandTestBed } from './create-command-test-bed';
-describe('example', () => {
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function getDocumentData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 11,
+ ts: {
+ bl: BooleanNumber.FALSE,
+ },
+ }],
+ customRanges: [{
+ startIndex: 6,
+ endIndex: 10,
+ rangeId: 'range-world',
+ rangeType: CustomRangeType.HYPERLINK,
+ wholeEntity: true,
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('core editing commands', () => {
let univer: Univer;
let get: Injector['get'];
let commandService: ICommandService;
+ function getBody() {
+ const univerInstanceService = get(IUniverInstanceService);
+ return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody();
+ }
+
+ function getDataStream() {
+ return getBody()?.dataStream ?? '';
+ }
+
+ function getFormatValueAt(key: keyof IStyleBase, pos: number) {
+ for (const textRun of getBody()?.textRuns ?? []) {
+ const { st, ed, ts = {} } = textRun;
+
+ if (st <= pos && ed >= pos) {
+ return ts[key];
+ }
+ }
+ }
+
beforeEach(() => {
- const testBed = createCommandTestBed();
+ const testBed = createCommandTestBed(getDocumentData());
univer = testBed.univer;
get = testBed.get;
commandService = get(ICommandService);
- commandService.registerCommand(SetInlineFormatBoldCommand);
+ commandService.registerCommand(InsertCommand);
+ commandService.registerCommand(DeleteCommand);
+ commandService.registerCommand(UpdateCommand);
+ 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());
- describe('XXX', () => {
- it('Should XXX', async () => {
- expect(true).toBe(true);
+ it('inserts text through the real mutation chain and moves the caret', async () => {
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_add([{ startOffset: 5, endOffset: 5, collapsed: true, isActive: true, segmentId: '', style: null as never }]);
+
+ await commandService.executeCommand(InsertCommand.id, {
+ unitId: 'test-doc',
+ segmentId: '',
+ range: { startOffset: 5, endOffset: 5, collapsed: true },
+ body: {
+ dataStream: ', brave',
+ },
});
+
+ await waitNextTick();
+
+ expect(getDataStream()).toBe('Hello, brave world\r\n');
+ });
+
+ it('deletes an entire custom range when the selection hits a whole entity', async () => {
+ await commandService.executeCommand(DeleteCommand.id, {
+ unitId: 'test-doc',
+ segmentId: '',
+ range: { startOffset: 7, endOffset: 7, collapsed: true },
+ direction: DeleteDirection.RIGHT,
+ });
+
+ await waitNextTick();
+
+ expect(getDataStream()).toBe('Hello \r\n');
+ expect(getBody()?.customRanges).toEqual([]);
+ });
+
+ it('updates text styles through the shared rich text mutation flow', async () => {
+ await commandService.executeCommand(UpdateCommand.id, {
+ unitId: 'test-doc',
+ segmentId: '',
+ range: { startOffset: 0, endOffset: 5, collapsed: false },
+ coverType: UpdateDocsAttributeType.REPLACE,
+ updateBody: {
+ dataStream: 'Hello',
+ textRuns: [{
+ st: 0,
+ ed: 5,
+ ts: {
+ bl: BooleanNumber.TRUE,
+ },
+ }],
+ },
+ textRanges: [{
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ }],
+ });
+
+ await waitNextTick();
+
+ expect(getDataStream()).toBe('Hello world\r\n');
+ expect(getFormatValueAt('bl', 1)).toBe(BooleanNumber.TRUE);
});
});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts
new file mode 100644
index 0000000000..96f51a4bbe
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/list.command.spec.ts
@@ -0,0 +1,189 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, PRESET_LIST_TYPE, PresetListType, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import {
+ BulletListCommand,
+ ChangeListNestingLevelCommand,
+ ChangeListNestingLevelType,
+ ChangeListTypeCommand,
+ CheckListCommand,
+ findNearestSectionBreak,
+ getParagraphsRelative,
+ ListOperationCommand,
+ QuickListCommand,
+} from '../list.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function getDocumentData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Alpha\rBeta\r\n',
+ paragraphs: [
+ { startIndex: 5 },
+ { startIndex: 10 },
+ ],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('list commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ function getBody() {
+ const univerInstanceService = get(IUniverInstanceService);
+ return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody();
+ }
+
+ function setSelections(ranges: Array<{ startOffset: number; endOffset: number; collapsed: boolean }>) {
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ selectionManager.__TEST_ONLY_add(ranges.map((range, index) => ({
+ ...range,
+ isActive: index === 0,
+ segmentId: '',
+ style: null as never,
+ })));
+ }
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(getDocumentData());
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(ListOperationCommand);
+ commandService.registerCommand(ChangeListTypeCommand);
+ commandService.registerCommand(ChangeListNestingLevelCommand);
+ commandService.registerCommand(BulletListCommand);
+ commandService.registerCommand(CheckListCommand);
+ commandService.registerCommand(QuickListCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ });
+
+ afterEach(() => univer.dispose());
+
+ it('toggles bullet lists on selected paragraphs through the public command chain', async () => {
+ setSelections([
+ { startOffset: 0, endOffset: 4, collapsed: false },
+ { startOffset: 6, endOffset: 9, collapsed: false },
+ ]);
+
+ await commandService.executeCommand(BulletListCommand.id);
+ await waitNextTick();
+
+ const paragraphs = getBody()?.paragraphs ?? [];
+ expect(paragraphs[0].bullet?.listType).toBe(PresetListType.BULLET_LIST);
+ expect(paragraphs[1].bullet?.listType).toBe(PresetListType.BULLET_LIST);
+ expect(paragraphs[0].bullet?.listId).toBe(paragraphs[1].bullet?.listId);
+ });
+
+ it('changes checklist type and nesting level on an existing list', async () => {
+ setSelections([
+ { startOffset: 0, endOffset: 4, collapsed: false },
+ { startOffset: 6, endOffset: 9, collapsed: false },
+ ]);
+
+ await commandService.executeCommand(CheckListCommand.id);
+ await commandService.executeCommand(ChangeListTypeCommand.id, {
+ listType: PresetListType.CHECK_LIST_CHECKED,
+ });
+ await commandService.executeCommand(ChangeListNestingLevelCommand.id, {
+ type: ChangeListNestingLevelType.increase,
+ });
+ await waitNextTick();
+
+ const paragraphs = getBody()?.paragraphs ?? [];
+ expect(paragraphs[0].bullet?.listType).toBe(PresetListType.CHECK_LIST_CHECKED);
+ expect(paragraphs[0].bullet?.nestingLevel).toBeGreaterThanOrEqual(1);
+ });
+
+ it('creates quick list from a markdown-like paragraph', async () => {
+ setSelections([{ startOffset: 0, endOffset: 4, collapsed: false }]);
+
+ await commandService.executeCommand(CheckListCommand.id);
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.CHECK_LIST);
+
+ const paragraph = {
+ ...(getBody()?.paragraphs?.[0] as NonNullable<NonNullable<ReturnType<typeof getBody>>['paragraphs']>[number]),
+ paragraphStart: 0,
+ paragraphEnd: 5,
+ };
+
+ setSelections([{ startOffset: 2, endOffset: 2, collapsed: true }]);
+ await commandService.executeCommand(QuickListCommand.id, {
+ listType: PresetListType.ORDER_LIST,
+ paragraph,
+ });
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].bullet?.listType).toBe(PresetListType.ORDER_LIST);
+ expect(getBody()?.paragraphs?.[0].bullet?.listId).toBeDefined();
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.textStyle).toMatchObject(
+ PRESET_LIST_TYPE[PresetListType.ORDER_LIST].nestingLevel[0].paragraphProperties?.textStyle ?? {}
+ );
+ });
+
+ it('extends selected paragraphs to adjacent items in the same list and finds nearest section breaks', () => {
+ const paragraphs = [
+ { startIndex: 5, bullet: { listType: PresetListType.BULLET_LIST, listId: 'list-1', nestingLevel: 0 } },
+ { startIndex: 10, bullet: { listType: PresetListType.BULLET_LIST, listId: 'list-1', nestingLevel: 0 } },
+ { startIndex: 16 },
+ { startIndex: 22, bullet: { listType: PresetListType.BULLET_LIST, listId: 'list-2', nestingLevel: 0 } },
+ ] as NonNullable<NonNullable<ReturnType<typeof getBody>>['paragraphs']>;
+
+ const relative = getParagraphsRelative(
+ [{ startOffset: 6, endOffset: 9, collapsed: false, segmentId: '' }],
+ paragraphs,
+ 'Alpha\rBeta\rGamma\r\n'
+ );
+
+ expect(relative.map((paragraph) => paragraph.startIndex)).toContain(5);
+ expect(relative.at(-1)?.startIndex).toBe(10);
+ expect(relative.length).toBeGreaterThanOrEqual(2);
+ expect(findNearestSectionBreak(11, [
+ { startIndex: 3 } as never,
+ { startIndex: 15 } as never,
+ { startIndex: 25 } as never,
+ ])?.startIndex).toBe(15);
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
new file mode 100644
index 0000000000..7275555cda
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/misc.command.spec.ts
@@ -0,0 +1,475 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
+import type { IAutoFormat } from '../../../services/doc-auto-format.service';
+import {
+ CommandType,
+ CustomRangeType,
+ HorizontalAlign,
+ ICommandService,
+ IUniverInstanceService,
+ NamedStyleType,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { afterEach, describe, expect, it } from 'vitest';
+import { DocAutoFormatService } from '../../../services/doc-auto-format.service';
+import { SetDocZoomRatioOperation } from '../../operations/set-doc-zoom-ratio.operation';
+import { AfterSpaceCommand, EnterCommand, TabCommand } from '../auto-format.command';
+import { BreakLineCommand } from '../break-line.command';
+import { HorizontalLineCommand, InsertHorizontalLineBellowCommand } from '../doc-horizontal-line.command';
+import { DocParagraphSettingCommand } from '../doc-paragraph-setting.command';
+import { DocSelectAllCommand } from '../doc-select-all.command';
+import { InsertCustomRangeCommand } from '../insert-custom-range.command';
+import { AlignCenterCommand, AlignJustifyCommand, AlignOperationCommand } from '../paragraph-align.command';
+import { ReplaceSelectionCommand } from '../replace-content.command';
+import { SetDocZoomRatioCommand } from '../set-doc-zoom-ratio.command';
+import { genEmptyTable } from '../table/table';
+import { createCommandTestBed } from './create-command-test-bed';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function createBaseDoc(dataStream = 'Hello world\r\n'): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream,
+ textRuns: [{
+ st: 0,
+ ed: dataStream.length - 2,
+ ts: {},
+ }],
+ paragraphs: [{
+ startIndex: dataStream.length - 2,
+ }],
+ sectionBreaks: [{
+ startIndex: dataStream.length - 1,
+ }],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function createMultiParagraphDoc(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Title\rBody\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 10,
+ ts: {},
+ }],
+ paragraphs: [{
+ startIndex: 5,
+ paragraphStyle: {
+ namedStyleType: NamedStyleType.HEADING_1,
+ headingId: 'heading-1',
+ },
+ }, {
+ startIndex: 10,
+ }],
+ sectionBreaks: [{
+ startIndex: 11,
+ }],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function createTableDoc(): IDocumentData {
+ const table = genEmptyTable(2, 2);
+ const prefix = 'AB';
+ const suffix = 'CD\r\n';
+ const dataStream = `${prefix}${table.dataStream}${suffix}`;
+
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream,
+ textRuns: [{
+ st: 0,
+ ed: dataStream.length - 2,
+ ts: {},
+ }],
+ paragraphs: [
+ ...table.paragraphs.map((paragraph) => ({
+ ...paragraph,
+ startIndex: paragraph.startIndex + prefix.length,
+ })),
+ {
+ startIndex: dataStream.length - 2,
+ },
+ ],
+ sectionBreaks: [
+ ...table.sectionBreaks.map((sectionBreak) => ({
+ ...sectionBreak,
+ startIndex: sectionBreak.startIndex + prefix.length,
+ })),
+ {
+ startIndex: dataStream.length - 1,
+ },
+ ],
+ tables: [{
+ startIndex: prefix.length,
+ endIndex: prefix.length + table.dataStream.length,
+ tableId: 'table-1',
+ }],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('misc document commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ function getDoc() {
+ return get(IUniverInstanceService).getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC);
+ }
+
+ function getBody() {
+ return getDoc()?.getBody();
+ }
+
+ function setCollapsedSelection(startOffset: number, endOffset = startOffset) {
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset,
+ endOffset,
+ collapsed: startOffset === endOffset,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+ }
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('inserts a custom range through the real replace-selection mutation flow', async () => {
+ ({ univer, get } = createCommandTestBed(createBaseDoc('Hello\r\n')));
+ commandService = get(ICommandService);
+ commandService.registerCommand(InsertCustomRangeCommand);
+ commandService.registerCommand(ReplaceSelectionCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(5);
+
+ await commandService.executeCommand(InsertCustomRangeCommand.id, {
+ unitId: 'test-doc',
+ rangeId: 'custom-range-1',
+ text: '@OpenAI',
+ properties: {
+ source: 'test',
+ },
+ wholeEntity: true,
+ });
+
+ await waitNextTick();
+
+ expect(getBody()?.dataStream).toBe('Hello@OpenAI\r\n');
+ expect(getBody()?.customRanges).toEqual([expect.objectContaining({
+ startIndex: 5,
+ endIndex: 11,
+ rangeId: 'custom-range-1',
+ rangeType: CustomRangeType.CUSTOM,
+ wholeEntity: true,
+ properties: {
+ source: 'test',
+ },
+ })]);
+ });
+
+ it('updates paragraph styles across selected paragraphs', async () => {
+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DocParagraphSettingCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(0, 10);
+
+ await commandService.executeCommand(DocParagraphSettingCommand.id, {
+ paragraph: {
+ spaceAbove: { v: 24 },
+ indentFirstLine: { v: 12 },
+ },
+ });
+
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].paragraphStyle).toEqual(expect.objectContaining({
+ namedStyleType: NamedStyleType.HEADING_1,
+ headingId: 'heading-1',
+ spaceAbove: { v: 24 },
+ indentFirstLine: { v: 12 },
+ }));
+ expect(getBody()?.paragraphs?.[1].paragraphStyle).toEqual(expect.objectContaining({
+ spaceAbove: { v: 24 },
+ indentFirstLine: { v: 12 },
+ }));
+ });
+
+ it('selects the whole body when no tables are present', async () => {
+ ({ univer, get } = createCommandTestBed(createBaseDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DocSelectAllCommand);
+ setCollapsedSelection(1);
+
+ const selectionManager = get(DocSelectionManagerService);
+ const refreshEvents: Array<unknown> = [];
+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {
+ if (event) {
+ refreshEvents.push(event);
+ }
+ });
+
+ const result = await commandService.executeCommand(DocSelectAllCommand.id);
+ await waitNextTick();
+
+ expect(result).toBe(true);
+ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ isEditing: false,
+ docRanges: [expect.objectContaining({
+ startOffset: 0,
+ endOffset: 11,
+ })],
+ }));
+
+ subscription.unsubscribe();
+ });
+
+ it('selects text and table ranges when tables are present', async () => {
+ ({ univer, get } = createCommandTestBed(createTableDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(DocSelectAllCommand);
+ setCollapsedSelection(1);
+
+ const selectionManager = get(DocSelectionManagerService);
+ const refreshEvents: Array<unknown> = [];
+ const subscription = selectionManager.refreshSelection$.subscribe((event) => {
+ if (event) {
+ refreshEvents.push(event);
+ }
+ });
+
+ const result = await commandService.executeCommand(DocSelectAllCommand.id);
+ await waitNextTick();
+
+ expect(result).toBe(true);
+ expect(refreshEvents.at(-1)).toEqual(expect.objectContaining({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ isEditing: false,
+ docRanges: [
+ expect.objectContaining({
+ startOffset: 0,
+ endOffset: 1,
+ }),
+ expect.objectContaining({
+ startOffset: 5,
+ endOffset: 19,
+ rangeType: 'RECT',
+ }),
+ expect.objectContaining({
+ startOffset: 24,
+ endOffset: 26,
+ rangeType: 'TEXT',
+ }),
+ ],
+ }));
+
+ subscription.unsubscribe();
+ });
+
+ it('inserts a horizontal line by reusing the break-line command chain', async () => {
+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(HorizontalLineCommand);
+ commandService.registerCommand(BreakLineCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(5);
+
+ await commandService.executeCommand(HorizontalLineCommand.id, {
+ insertRange: {
+ startOffset: 5,
+ endOffset: 5,
+ },
+ });
+
+ await waitNextTick();
+ expect(getBody()?.paragraphs).toHaveLength(3);
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.borderBottom).toEqual(expect.objectContaining({
+ width: 1,
+ }));
+ });
+
+ it('inserts a horizontal line below the current paragraph', async () => {
+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(InsertHorizontalLineBellowCommand);
+ commandService.registerCommand(HorizontalLineCommand);
+ commandService.registerCommand(BreakLineCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(2);
+
+ await commandService.executeCommand(InsertHorizontalLineBellowCommand.id);
+
+ await waitNextTick();
+ expect(getBody()?.paragraphs).toHaveLength(3);
+ expect(getBody()?.paragraphs?.[1].paragraphStyle?.borderBottom).toEqual(expect.objectContaining({
+ width: 1,
+ }));
+ });
+
+ it('aligns selected paragraphs through the wrapper and toggles an existing alignment', async () => {
+ ({ univer, get } = createCommandTestBed(createMultiParagraphDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(AlignOperationCommand);
+ commandService.registerCommand(AlignCenterCommand);
+ commandService.registerCommand(AlignJustifyCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+ setCollapsedSelection(0, 10);
+
+ await commandService.executeCommand(AlignCenterCommand.id);
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);
+ expect(getBody()?.paragraphs?.[1].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.CENTER);
+
+ await commandService.executeCommand(AlignCenterCommand.id);
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.UNSPECIFIED);
+ expect(getBody()?.paragraphs?.[1].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.UNSPECIFIED);
+
+ await commandService.executeCommand(AlignJustifyCommand.id);
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.JUSTIFIED);
+ expect(getBody()?.paragraphs?.[1].paragraphStyle?.horizontalAlign).toBe(HorizontalAlign.JUSTIFIED);
+ });
+
+ it('updates the current document zoom ratio through the command and operation chain', async () => {
+ ({ univer, get } = createCommandTestBed(createBaseDoc()));
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetDocZoomRatioCommand);
+ commandService.registerCommand(SetDocZoomRatioOperation);
+
+ expect((getDoc()?.getSnapshot().settings?.zoomRatio) ?? 1).toBe(1);
+
+ await commandService.executeCommand(SetDocZoomRatioCommand.id, {
+ zoomRatio: 1.5,
+ });
+
+ expect(getDoc()?.getSnapshot().settings?.zoomRatio).toBe(1.5);
+ expect(await commandService.executeCommand(SetDocZoomRatioCommand.id, {
+ documentId: 'missing-doc',
+ zoomRatio: 0.8,
+ })).toBe(false);
+ });
+
+ it('runs registered auto-format mutations for tab, after-space, and enter commands', async () => {
+ ({ univer, get } = createCommandTestBed(createBaseDoc()));
+ univer.__getInjector().add([DocAutoFormatService]);
+ commandService = get(ICommandService);
+ commandService.registerCommand(TabCommand);
+ commandService.registerCommand(AfterSpaceCommand);
+ commandService.registerCommand(EnterCommand);
+
+ const executed: string[] = [];
+ const autoFormatService = get(DocAutoFormatService);
+ const recordOperation: ICommand<{ kind: string }> = {
+ id: 'test.command.auto-format-record',
+ type: CommandType.OPERATION,
+ handler: (_accessor, params) => {
+ executed.push(params?.kind ?? 'unknown');
+ return true;
+ },
+ };
+
+ commandService.registerCommand(recordOperation);
+ setCollapsedSelection(2);
+
+ const register = (id: string, kind: string, match?: IAutoFormat['match']) => autoFormatService.registerAutoFormat({
+ id,
+ priority: 1,
+ match: match ?? (() => true),
+ getMutations: () => [{
+ id: recordOperation.id,
+ params: { kind },
+ }],
+ });
+
+ const disposables = [
+ register(TabCommand.id, 'tab', (context) => context.commandParams === null || (context.commandParams as { shift?: boolean }).shift !== true),
+ register(AfterSpaceCommand.id, 'space'),
+ register(EnterCommand.id, 'enter'),
+ ];
+
+ await commandService.executeCommand(TabCommand.id, { shift: false });
+ await commandService.executeCommand(AfterSpaceCommand.id);
+ await commandService.executeCommand(EnterCommand.id);
+
+ expect(executed).toEqual(['tab', 'space', 'enter']);
+
+ disposables.forEach((disposable) => disposable.dispose());
+ });
+});
diff --git a/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts
new file mode 100644
index 0000000000..864e3da285
--- /dev/null
+++ b/packages/docs-ui/src/commands/commands/__tests__/set-heading.command.spec.ts
@@ -0,0 +1,144 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { DocumentDataModel, ICommand, IDocumentData, Injector, Univer } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, NamedStyleType, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, RichTextEditingMutation, SetTextSelectionsOperation } from '@univerjs/docs';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { H1HeadingCommand, QuickHeadingCommand, SetParagraphNamedStyleCommand } from '../set-heading.command';
+import { createCommandTestBed } from './create-command-test-bed';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function getHeadingDocumentData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Heading\r\n',
+ paragraphs: [{
+ startIndex: 7,
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+function getQuickHeadingDocumentData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: '# Heading\r\n',
+ paragraphs: [{
+ startIndex: 9,
+ }],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('set heading commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ function getBody() {
+ const univerInstanceService = get(IUniverInstanceService);
+ return univerInstanceService.getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)?.getBody();
+ }
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed(getHeadingDocumentData());
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetParagraphNamedStyleCommand);
+ commandService.registerCommand(H1HeadingCommand);
+ commandService.registerCommand(QuickHeadingCommand);
+ 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());
+
+ it('applies a named paragraph style via the public heading command', async () => {
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_add([{ startOffset: 0, endOffset: 3, collapsed: false, isActive: true, segmentId: '', style: null as never }]);
+
+ await commandService.executeCommand(H1HeadingCommand.id);
+
+ await waitNextTick();
+
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.namedStyleType).toBe(NamedStyleType.HEADING_1);
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.headingId).toBeDefined();
+ });
+
+ it('converts markdown-like quick headings through the real command chain', async () => {
+ univer.dispose();
+
+ const testBed = createCommandTestBed(getQuickHeadingDocumentData());
+ univer = testBed.univer;
+ get = testBed.get;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetParagraphNamedStyleCommand);
+ commandService.registerCommand(QuickHeadingCommand);
+ commandService.registerCommand(SetTextSelectionsOperation);
+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);
+
+ const selectionManager = get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ selectionManager.__TEST_ONLY_add([{ startOffset: 2, endOffset: 2, collapsed: true, isActive: true, segmentId: '', style: null as never }]);
+
+ await commandService.executeCommand(QuickHeadingCommand.id, {
+ value: NamedStyleType.HEADING_2,
+ });
+
+ await waitNextTick();
+
+ expect(getBody()?.dataStream.startsWith('Heading')).toBe(true);
+ expect(getBody()?.paragraphs?.[0].paragraphStyle?.namedStyleType).toBe(NamedStyleType.HEADING_2);
+ });
+});
diff --git a/packages/docs-ui/src/controllers/__tests__/doc-auto-format.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/doc-auto-format.controller.spec.ts
new file mode 100644
index 0000000000..fe8eb1715a
--- /dev/null
+++ b/packages/docs-ui/src/controllers/__tests__/doc-auto-format.controller.spec.ts
@@ -0,0 +1,166 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { QuickListTypeMap } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { AfterSpaceCommand, EnterCommand, TabCommand } from '../../commands/commands/auto-format.command';
+import { BreakLineCommand } from '../../commands/commands/break-line.command';
+import { ChangeListNestingLevelCommand, ChangeListNestingLevelType, ListOperationCommand, QuickListCommand } from '../../commands/commands/list.command';
+import { QUICK_HEADING_MAP, QuickHeadingCommand } from '../../commands/commands/set-heading.command';
+import { DocTableTabCommand } from '../../commands/commands/table/doc-table-tab.command';
+import { DocAutoFormatController } from '../doc-auto-format.controller';
+
+interface IAutoFormatRule {
+ id: string;
+ priority?: number;
+ match: (context: unknown) => boolean;
+ getMutations: (context: unknown) => Array<Record<string, unknown>>;
+}
+
+describe('doc auto format controller', () => {
+ it('registers five auto-format rules and maps list, table, heading, and enter behaviors', () => {
+ const rules: IAutoFormatRule[] = [];
+ const service = {
+ registerAutoFormat: vi.fn((rule) => {
+ rules.push(rule);
+ return { dispose: vi.fn() };
+ }),
+ };
+ const renderManagerService = {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => ({
+ getSkeleton: () => ({ id: 'skeleton' }),
+ })),
+ })),
+ };
+
+ const controller = new DocAutoFormatController(service as never, renderManagerService as never);
+
+ expect(controller).toBeInstanceOf(DocAutoFormatController);
+ expect(service.registerAutoFormat).toHaveBeenCalledTimes(5);
+
+ const listTabRule = rules.find((rule) => rule.id === TabCommand.id && rule.priority === 100)!;
+ const tableTabRule = rules.find((rule) => rule.id === TabCommand.id && rule.priority === 99)!;
+ const spaceRule = rules.find((rule) => rule.id === AfterSpaceCommand.id)!;
+ const exitListRule = rules.find((rule) => rule.id === EnterCommand.id && rule.priority == null)!;
+ const defaultEnterRule = rules.find((rule) => rule.id === EnterCommand.id && rule.priority === -9999)!;
+
+ expect(listTabRule.match({
+ selection: { startOffset: 4 },
+ paragraphs: [{
+ paragraphStart: 4,
+ startIndex: 4,
+ bullet: { listId: 'list-1' },
+ }],
+ unit: {
+ getBody: () => ({
+ paragraphs: [
+ { startIndex: 1, bullet: { listId: 'list-1' } },
+ { startIndex: 4, bullet: { listId: 'list-1' } },
+ ],
+ }),
+ },
+ })).toBe(true);
+ expect(listTabRule.getMutations({ commandParams: { shift: true } })).toEqual([{
+ id: ChangeListNestingLevelCommand.id,
+ params: {
+ type: ChangeListNestingLevelType.decrease,
+ },
+ }]);
+
+ expect(tableTabRule.match({
+ selection: {
+ startNodePosition: { path: ['pages', 0, 'cells', 0] },
+ },
+ unit: {
+ getUnitId: () => 'test-doc',
+ },
+ })).toBe(true);
+ expect(tableTabRule.getMutations({ commandParams: { shift: true } })).toEqual([{
+ id: DocTableTabCommand.id,
+ params: { shift: true },
+ }]);
+
+ const quickListText = Object.keys(QuickListTypeMap)[0];
+ expect(spaceRule.match({
+ selection: { collapsed: true, startOffset: quickListText.length + 1 },
+ paragraphs: [{ paragraphStart: 0 }],
+ unit: {
+ getBody: () => ({ dataStream: `${quickListText} \r\n` }),
+ },
+ })).toBe(true);
+ expect(spaceRule.getMutations({
+ selection: { startOffset: quickListText.length + 1 },
+ paragraphs: [{ paragraphStart: 0, startIndex: 0 }],
+ unit: {
+ getBody: () => ({ dataStream: `${quickListText} \r\n` }),
+ },
+ })).toEqual([{
+ id: QuickListCommand.id,
+ params: {
+ listType: QuickListTypeMap[quickListText as keyof typeof QuickListTypeMap],
+ paragraph: { paragraphStart: 0, startIndex: 0 },
+ },
+ }]);
+
+ const quickHeadingText = Object.keys(QUICK_HEADING_MAP)[0];
+ expect(spaceRule.getMutations({
+ selection: { startOffset: quickHeadingText.length + 1 },
+ paragraphs: [{ paragraphStart: 0 }],
+ unit: {
+ getBody: () => ({ dataStream: `${quickHeadingText} \r\n` }),
+ },
+ })).toEqual([{
+ id: QuickHeadingCommand.id,
+ params: {
+ value: QUICK_HEADING_MAP[quickHeadingText as keyof typeof QUICK_HEADING_MAP],
+ },
+ }]);
+
+ expect(exitListRule.match({
+ paragraphs: [{
+ bullet: { listType: 'bullet', nestingLevel: 0 },
+ paragraphStart: 0,
+ paragraphEnd: 0,
+ }],
+ })).toBe(true);
+ expect(exitListRule.getMutations({
+ paragraphs: [{
+ bullet: { listType: 'bullet', nestingLevel: 1 },
+ }],
+ })).toEqual([{
+ id: ChangeListNestingLevelCommand.id,
+ params: {
+ type: ChangeListNestingLevelType.decrease,
+ },
+ }]);
+ expect(exitListRule.getMutations({
+ paragraphs: [{
+ bullet: { listType: 'bullet', nestingLevel: 0 },
+ }],
+ })).toEqual([{
+ id: ListOperationCommand.id,
+ params: {
+ listType: 'bullet',
+ },
+ }]);
+
+ expect(defaultEnterRule.match({})).toBe(true);
+ expect(defaultEnterRule.getMutations({})).toEqual([{
+ id: BreakLineCommand.id,
+ }]);
+ });
+});
diff --git a/packages/docs-ui/src/controllers/__tests__/ui-controllers.spec.ts b/packages/docs-ui/src/controllers/__tests__/ui-controllers.spec.ts
new file mode 100644
index 0000000000..f1167dba52
--- /dev/null
+++ b/packages/docs-ui/src/controllers/__tests__/ui-controllers.spec.ts
@@ -0,0 +1,178 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BuiltInUIPart } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { AppUIController } from '../app-ui-controller';
+import { DocContainerUIController } from '../doc-container-ui-controller';
+import { DocParagraphSettingController } from '../doc-paragraph-setting.controller';
+import { DocUIController } from '../doc-ui.controller';
+
+function createDisposable() {
+ return {
+ dispose: vi.fn(),
+ };
+}
+
+describe('docs ui controllers', () => {
+ it('creates the doc container controller through the injector in app ui controller', () => {
+ const docContainerController = {};
+ const injector = {
+ createInstance: vi.fn(() => docContainerController),
+ };
+
+ const controller = new AppUIController(injector as never);
+
+ expect(controller).toBeInstanceOf(AppUIController);
+ expect(injector.createInstance).toHaveBeenCalledWith(DocContainerUIController);
+ });
+
+ it('stores the mounted doc container and exposes locale/config helpers', () => {
+ const contentRef = { current: { id: 'content' } };
+ const docContainer = {
+ getContentRef: vi.fn(() => contentRef),
+ };
+ const localeService = {
+ setLocale: vi.fn(),
+ };
+ const injector = { id: 'injector' };
+ const configService = {
+ getConfig: vi.fn(() => ({ toolbar: true })),
+ };
+
+ const controller = new DocContainerUIController(
+ localeService as never,
+ injector as never,
+ configService as never
+ );
+ const uiConfig = controller.getUIConfig();
+
+ expect(uiConfig.injector).toBe(injector);
+ expect(uiConfig.config).toEqual({ toolbar: true });
+
+ uiConfig.changeLocale('zhCN');
+ uiConfig.getComponent(docContainer as never);
+
+ expect(localeService.setLocale).toHaveBeenCalledWith('zhCN');
+ expect(controller.getDocContainer()).toBe(docContainer);
+ expect(controller.getContentRef()).toBe(contentRef);
+ expect(controller.UIDidMount((mounted: unknown) => mounted)).toBe(docContainer);
+ });
+
+ it('throws when the doc container content ref is not ready', () => {
+ const controller = new DocContainerUIController(
+ { setLocale: vi.fn() } as never,
+ {} as never,
+ { getConfig: vi.fn() } as never
+ );
+
+ expect(() => controller.getComponent({
+ getContentRef: () => ({ current: null }),
+ } as never)).toThrowError('container is not ready');
+ });
+
+ it('registers the paragraph setting view and controls the sidebar panel', () => {
+ const componentManager = {
+ register: vi.fn(() => createDisposable()),
+ };
+ const sidebarService = {
+ open: vi.fn(),
+ close: vi.fn(),
+ };
+
+ const controller = new DocParagraphSettingController(
+ {} as never,
+ componentManager as never,
+ sidebarService as never
+ );
+
+ controller.openPanel();
+ controller.closePanel();
+
+ expect(componentManager.register).toHaveBeenCalledTimes(1);
+ expect(componentManager.register).toHaveBeenCalledWith('doc_ui_paragraph-setting-panel', expect.anything());
+ expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ header: { title: 'doc.slider.paragraphSetting' },
+ children: { label: 'doc_ui_paragraph-setting-panel' },
+ width: 300,
+ }));
+ expect(sidebarService.close).toHaveBeenCalledWith(undefined);
+ });
+
+ it('registers doc ui components, commands, shortcuts, ui parts, and focus handlers', () => {
+ const componentManager = {
+ register: vi.fn(() => createDisposable()),
+ };
+ const registeredFocusHandlers: Array<(unitId: string) => void> = [];
+ const commandService = {
+ registerCommand: vi.fn(() => createDisposable()),
+ };
+ const layoutService = {
+ registerFocusHandler: vi.fn((_type, handler) => {
+ registeredFocusHandlers.push(handler);
+ return createDisposable();
+ }),
+ };
+ const menuManagerService = {
+ mergeMenu: vi.fn(),
+ };
+ const uiPartsService = {
+ registerComponent: vi.fn(() => createDisposable()),
+ };
+ const shortcutService = {
+ registerShortcut: vi.fn(() => createDisposable()),
+ };
+ const selectionRenderService = {
+ focus: vi.fn(),
+ };
+ const renderManagerService = {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => selectionRenderService),
+ })),
+ };
+ const injector = {
+ get: vi.fn(() => renderManagerService),
+ };
+
+ const controller = new DocUIController(
+ injector as never,
+ componentManager as never,
+ commandService as never,
+ layoutService as never,
+ menuManagerService as never,
+ uiPartsService as never,
+ {} as never,
+ shortcutService as never,
+ {} as never
+ );
+
+ expect(controller).toBeInstanceOf(DocUIController);
+ expect(componentManager.register).toHaveBeenCalledTimes(7);
+ expect(commandService.registerCommand).toHaveBeenCalledTimes(3);
+ expect(menuManagerService.mergeMenu).toHaveBeenCalledTimes(1);
+ expect(uiPartsService.registerComponent).toHaveBeenCalledTimes(2);
+ expect(uiPartsService.registerComponent).toHaveBeenNthCalledWith(1, BuiltInUIPart.FOOTER, expect.any(Function));
+ expect(uiPartsService.registerComponent).toHaveBeenNthCalledWith(2, BuiltInUIPart.CONTENT, expect.any(Function));
+ expect(shortcutService.registerShortcut).toHaveBeenCalledTimes(13);
+ expect(layoutService.registerFocusHandler).toHaveBeenCalledTimes(1);
+
+ expect(registeredFocusHandlers).toHaveLength(1);
+ registeredFocusHandlers.at(0)?.('doc-1');
+
+ expect(renderManagerService.getRenderById).toHaveBeenCalledWith('doc-1');
+ expect(selectionRenderService.focus).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/docs-ui/src/services/__tests__/doc-services.spec.ts b/packages/docs-ui/src/services/__tests__/doc-services.spec.ts
new file mode 100644
index 0000000000..95acd5eed6
--- /dev/null
+++ b/packages/docs-ui/src/services/__tests__/doc-services.spec.ts
@@ -0,0 +1,264 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IDocumentData, Injector, ITextStyle, Univer } from '@univerjs/core';
+import { CustomRangeType, IUniverInstanceService } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { DocumentEditArea } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createCommandTestBed } from '../../commands/commands/__tests__/create-command-test-bed';
+import { DocAutoFormatService } from '../doc-auto-format.service';
+import { DocMenuStyleService } from '../doc-menu-style.service';
+import { DocPrintInterceptorService } from '../doc-print-interceptor-service';
+import { DocsRenderService } from '../docs-render.service';
+
+function createDocData(): IDocumentData {
+ return {
+ id: 'test-doc',
+ body: {
+ dataStream: 'Hello world\rSecond line\r\n',
+ textRuns: [{
+ st: 0,
+ ed: 22,
+ ts: {},
+ }],
+ paragraphs: [{
+ startIndex: 11,
+ }, {
+ startIndex: 23,
+ }],
+ sectionBreaks: [{
+ startIndex: 24,
+ }],
+ customRanges: [{
+ startIndex: 6,
+ endIndex: 10,
+ rangeId: 'range-world',
+ rangeType: CustomRangeType.HYPERLINK,
+ wholeEntity: true,
+ }],
+ customBlocks: [],
+ },
+ documentStyle: {
+ pageSize: {
+ width: 594.3,
+ height: 840.51,
+ },
+ marginTop: 72,
+ marginBottom: 72,
+ marginRight: 90,
+ marginLeft: 90,
+ },
+ };
+}
+
+describe('docs ui services', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+
+ afterEach(() => {
+ univer?.dispose();
+ });
+
+ it('matches auto-format handlers by priority and builds context from the current selection', () => {
+ ({ univer, get } = createCommandTestBed(createDocData()));
+ const selectionManager = get(DocSelectionManagerService);
+ const univerInstanceService = get(IUniverInstanceService);
+ const service = new DocAutoFormatService(univerInstanceService, selectionManager);
+ let highPriorityContext: Record<string, unknown> | null = null;
+
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: 'test-doc',
+ subUnitId: 'test-doc',
+ });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 12,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ const lowPriority = service.registerAutoFormat({
+ id: 'doc.command.tab',
+ priority: 1,
+ match: () => true,
+ getMutations: () => [{ id: 'low-priority' }],
+ });
+ const highPriority = service.registerAutoFormat({
+ id: 'doc.command.tab',
+ priority: 10,
+ match: (context) => {
+ highPriorityContext = {
+ isBody: context.isBody,
+ paragraphCount: context.paragraphs.length,
+ customRangeCount: context.customRanges.length,
+ commandParams: context.commandParams,
+ };
+ return true;
+ },
+ getMutations: () => [{ id: 'high-priority' }],
+ });
+
+ expect(service.onAutoFormat('doc.command.tab', { shift: false })).toEqual([{ id: 'high-priority' }]);
+ expect(highPriorityContext).toEqual({
+ isBody: true,
+ paragraphCount: 2,
+ customRangeCount: 1,
+ commandParams: { shift: false },
+ });
+
+ highPriority.dispose();
+ expect(service.onAutoFormat('doc.command.tab', null)).toEqual([{ id: 'low-priority' }]);
+
+ lowPriority.dispose();
+ expect(service.onAutoFormat('doc.command.tab', null)).toEqual([]);
+ });
+
+ it('returns no auto-format mutations when the current selection is unavailable', () => {
+ ({ univer, get } = createCommandTestBed(createDocData()));
+ const service = new DocAutoFormatService(get(IUniverInstanceService), get(DocSelectionManagerService));
+
+ expect(service.onAutoFormat('doc.command.tab', null)).toEqual([]);
+ });
+
+ it('merges cached menu styles, clears them on selection changes, and derives body/header defaults', () => {
+ ({ univer, get } = createCommandTestBed(createDocData()));
+ const selectionManager = get(DocSelectionManagerService);
+ const univerInstanceService = get(IUniverInstanceService);
+ const bodyRenderManagerService = {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => ({
+ getViewModel: () => ({
+ getEditArea: () => DocumentEditArea.BODY,
+ }),
+ })),
+ })),
+ };
+ const headerRenderManagerService = {
+ getRenderById: vi.fn(() => ({
+ with: vi.fn(() => ({
+ getViewModel: () => ({
+ getEditArea: () => DocumentEditArea.HEADER,
+ }),
+ })),
+ })),
+ };
+ const bodyService = new DocMenuStyleService(
+ selectionManager,
+ univerInstanceService,
+ bodyRenderManagerService as never
+ );
+ const headerService = new DocMenuStyleService(
+ selectionManager,
+ univerInstanceService,
+ headerRenderManagerService as never
+ );
+ const fallbackService = new DocMenuStyleService(
+ selectionManager,
+ {
+ getCurrentUnitForType: () => null,
+ } as never,
+ {
+ getRenderById: vi.fn(() => null),
+ } as never
+ );
+
+ bodyService.setStyleCache({ bl: 1 } as ITextStyle);
+ bodyService.setStyleCache({ it: 1 } as ITextStyle);
+
+ expect(bodyService.getStyleCache()).toEqual({ bl: 1, it: 1 });
+ expect(bodyService.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 11 });
+ expect(headerService.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 9 });
+ expect(fallbackService.getDefaultStyle()).toEqual({ ff: 'Arial', fs: 11 });
+
+ (selectionManager as unknown as { _textSelection$: { next: (value: unknown) => void } })._textSelection$.next({});
+
+ expect(bodyService.getStyleCache()).toBeNull();
+ });
+
+ it('creates and disposes renderers for current, added, and removed docs', () => {
+ const createRender$ = new Subject<string>();
+ const created$ = new Subject<Record<string, unknown>>();
+ const added$ = new Subject<Record<string, unknown>>();
+ const disposed$ = new Subject<Record<string, unknown>>();
+ const existingDoc = { getUnitId: () => 'doc-1' };
+ const addedDoc = { getUnitId: () => 'doc-2' };
+ const removedDoc = { getUnitId: () => 'doc-3' };
+ const canvas = { setId: vi.fn() };
+ const context = { setId: vi.fn() };
+ const renderManagerService = {
+ createRender$,
+ created$,
+ has: vi.fn(() => false),
+ createRender: vi.fn(),
+ removeRender: vi.fn(),
+ };
+ const instanceService = {
+ getAllUnitsForType: vi.fn(() => [existingDoc]),
+ getCurrentUnitForType: vi.fn(() => existingDoc),
+ getTypeOfUnitAdded$: vi.fn(() => added$),
+ getTypeOfUnitDisposed$: vi.fn(() => disposed$),
+ };
+
+ const service = new DocsRenderService(instanceService as never, renderManagerService as never);
+
+ expect(service).toBeInstanceOf(DocsRenderService);
+ expect(renderManagerService.createRender).toHaveBeenCalledWith('doc-1');
+
+ created$.next({
+ unitId: 'doc-1',
+ engine: {
+ getCanvas: () => ({
+ ...canvas,
+ getContext: () => context,
+ }),
+ },
+ });
+
+ expect(canvas.setId).toHaveBeenCalledWith('univer-doc-main-canvas');
+ expect(context.setId).toHaveBeenCalledWith('univer-doc-main-canvas');
+
+ added$.next(addedDoc);
+ createRender$.next('doc-4');
+ disposed$.next(removedDoc);
+
+ expect(renderManagerService.createRender).toHaveBeenCalledWith('doc-2');
+ expect(renderManagerService.createRender).toHaveBeenCalledWith('doc-4');
+ expect(renderManagerService.removeRender).toHaveBeenCalledWith('doc-3');
+ });
+
+ it('keeps print interceptor defaults as pass-through and stores component mappings', () => {
+ const service = new DocPrintInterceptorService();
+ const interceptPoints = service.interceptor.getInterceptPoints();
+ const domCollection = { dispose: vi.fn() };
+
+ service.registerPrintComponent('doc-component', 'print-doc-component');
+
+ const collectComponents = service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_COMPONENT_COLLECT);
+ const collectDom = service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_DOM_COLLECT);
+
+ expect(service.getPrintComponent('doc-component')).toBe('print-doc-component');
+ expect(collectComponents(undefined, {
+ unitId: 'test-doc',
+ } as never)).toBeUndefined();
+ expect(collectDom(domCollection as never, {
+ unitId: 'test-doc',
+ } as never)).toBe(domCollection);
+ });
+});
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
new file mode 100644
index 0000000000..c0c0d830fe
--- /dev/null
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-rect-range.spec.ts
@@ -0,0 +1,85 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ compareNodePositionInTable,
+ isInSameTableCell,
+ isInSameTableCellData,
+ isValidRectRange,
+} from '../convert-rect-range';
+
+function createNodePosition(path: Array<string | number>) {
+ return {
+ page: 0,
+ section: 0,
+ column: 0,
+ line: 0,
+ divide: 0,
+ glyph: 0,
+ path,
+ } as never;
+}
+
+describe('selection rect range helpers', () => {
+ it('validates rectangle selections across table cells', () => {
+ const sameCell = createNodePosition(['pages', 0, 'skeTables', 'table#-#0', 'rows', 0, 'cells', 0]);
+ const otherCell = createNodePosition(['pages', 0, 'skeTables', 'table#-#0', 'rows', 0, 'cells', 1]);
+ const otherTable = createNodePosition(['pages', 0, 'skeTables', 'table-2#-#0', 'rows', 0, 'cells', 0]);
+ const nonTable = createNodePosition(['pages', 0, 'sections', 0]);
+
+ expect(isValidRectRange(sameCell, otherCell)).toBe(true);
+ expect(isValidRectRange(sameCell, sameCell)).toBe(false);
+ expect(isValidRectRange(sameCell, otherTable)).toBe(false);
+ expect(isValidRectRange(sameCell, nonTable)).toBe(false);
+ expect(isInSameTableCell(sameCell, createNodePosition(['pages', 0, 'skeTables', 'table#-#0', 'rows', 0, 'cells', 0]))).toBe(true);
+ expect(isInSameTableCell(sameCell, otherCell)).toBe(false);
+ });
+
+ it('detects same table-cell data across pages and compares table order', () => {
+ const anchor = createNodePosition(['pages', 0, 'skeTables', 'table#-#0', 'rows', 1, 'cells', 2]);
+ const focus = createNodePosition(['pages', 1, 'skeTables', 'table#-#1', 'rows', 1, 'cells', 2]);
+
+ const anchorCellPage: Record<string, unknown> = {};
+ const focusCellPage: Record<string, unknown> = {};
+ const anchorRow = { index: 1, cells: [null, null, anchorCellPage] };
+ const focusRow = { index: 1, cells: [null, null, focusCellPage] };
+
+ const skeleton = {
+ findGlyphByPosition: (position: unknown) => ({
+ parent: {
+ parent: {
+ parent: {
+ parent: {
+ parent: position === anchor ? { ...anchorCellPage, parent: anchorRow } : { ...focusCellPage, parent: focusRow },
+ },
+ },
+ },
+ },
+ }),
+ } as never;
+
+ expect(isInSameTableCellData(skeleton, anchor, focus)).toBe(true);
+ expect(compareNodePositionInTable(
+ createNodePosition(['pages', 0, 'skeTables', 'table#-#0', 'rows', 0, 'cells', 0]),
+ createNodePosition(['pages', 0, 'skeTables', 'table#-#1', 'rows', 0, 'cells', 0])
+ )).toBe(true);
+ expect(compareNodePositionInTable(
+ createNodePosition(['pages', 0, 'skeTables', 'table#-#1', 'rows', 2, 'cells', 1]),
+ createNodePosition(['pages', 0, 'skeTables', 'table#-#1', 'rows', 2, 'cells', 0])
+ )).toBe(false);
+ });
+});
diff --git a/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
new file mode 100644
index 0000000000..ecb193f539
--- /dev/null
+++ b/packages/docs-ui/src/services/selection/__tests__/convert-text-range.spec.ts
@@ -0,0 +1,83 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { compareNodePosition, compareNodePositionLogic, getOneTextSelectionRange, pushToPoints } from '../convert-text-range';
+import { getAnchorBounding, getLineBounding } from '../text-range';
+
+describe('selection convert text range helpers', () => {
+ it('compares node positions in document order', () => {
+ const start = { page: 0, section: 0, column: 0, line: 0, divide: 0, glyph: 0 } as never;
+ const end = { page: 0, section: 0, column: 0, line: 1, divide: 0, glyph: 0 } as never;
+ const earlierPage = { page: 0, section: 1, column: 0, line: 0, divide: 0, glyph: 0 } as never;
+ const laterPage = { page: 1, section: 0, column: 0, line: 0, divide: 0, glyph: 0 } as never;
+
+ expect(compareNodePositionLogic(start, end)).toBe(true);
+ expect(compareNodePositionLogic(end, start)).toBe(false);
+ expect(compareNodePositionLogic(earlierPage, laterPage)).toBe(true);
+ expect(compareNodePosition(start, end)).toEqual({ start, end });
+ expect(compareNodePosition(end, start)).toEqual({ start, end });
+ });
+
+ it('merges cursor fragments into one text range', () => {
+ expect(getOneTextSelectionRange([])).toBeUndefined();
+ expect(getOneTextSelectionRange([
+ { startOffset: 2, endOffset: 2, collapsed: true },
+ ] as never)).toEqual({
+ startOffset: 2,
+ endOffset: 2,
+ collapsed: true,
+ });
+ expect(getOneTextSelectionRange([
+ { startOffset: 2, endOffset: 4, collapsed: false },
+ { startOffset: 5, endOffset: 8, collapsed: false },
+ ] as never)).toEqual({
+ startOffset: 2,
+ endOffset: 8,
+ collapsed: false,
+ });
+ });
+
+ it('converts positions into polygon points and bounding boxes', () => {
+ const points = pushToPoints({
+ startX: 10,
+ startY: 20,
+ endX: 30,
+ endY: 40,
+ });
+
+ expect(points).toEqual([
+ { x: 10, y: 20 },
+ { x: 30, y: 20 },
+ { x: 30, y: 40 },
+ { x: 10, y: 40 },
+ { x: 10, y: 20 },
+ ]);
+ expect(getAnchorBounding([points])).toEqual({
+ left: 10,
+ top: 20,
+ width: 20,
+ height: 20,
+ });
+ expect(getLineBounding([
+ points,
+ [{ x: 0, y: 0 }, { x: 4, y: 0 }, { x: 4, y: 2 }, { x: 0, y: 2 }],
+ ])).toEqual([
+ { left: 10, right: 30, top: 20, bottom: 40 },
+ { left: 0, right: 4, top: 0, bottom: 2 },
+ ]);
+ });
+});
diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
new file mode 100644
index 0000000000..2dad0d3876
--- /dev/null
+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
@@ -0,0 +1,470 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { Mock } from 'vitest';
+import { DataStreamTreeTokenType, DOC_RANGE_TYPE } from '@univerjs/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { DocSelectionRenderService } from '../doc-selection-render.service';
+import { TextRange } from '../text-range';
+
+const {
+ getCanvasOffsetByEngineMock,
+ getRangeListFromCharIndexMock,
+ getRectRangeFromCharIndexMock,
+ getTextRangeFromCharIndexMock,
+} = vi.hoisted(() => ({
+ getCanvasOffsetByEngineMock: vi.fn(),
+ getRangeListFromCharIndexMock: vi.fn(),
+ getRectRangeFromCharIndexMock: vi.fn(),
+ getTextRangeFromCharIndexMock: vi.fn(),
+}));
+
+vi.mock('../selection-utils', async () => {
+ const actual = await vi.importActual<typeof import('../selection-utils')>('../selection-utils');
+
+ return {
+ ...actual,
+ getCanvasOffsetByEngine: getCanvasOffsetByEngineMock,
+ getRangeListFromCharIndex: getRangeListFromCharIndexMock,
+ getRectRangeFromCharIndex: getRectRangeFromCharIndexMock,
+ getTextRangeFromCharIndex: getTextRangeFromCharIndexMock,
+ };
+});
+
+type VoidMock = Mock<() => void>;
+type BooleanMock = Mock<() => boolean>;
+type AnchorMock = Mock<() => { left: number; top: number; visible: boolean } | null>;
+type IntersectionMock = Mock<(range: unknown) => boolean>;
+
+interface IFakeTextRange {
+ activate: VoidMock;
+ deactivate: VoidMock;
+ dispose: VoidMock;
+ getAnchor: AnchorMock;
+ isActive: BooleanMock;
+ isIntersection: IntersectionMock;
+ collapsed?: boolean;
+ anchorNodePosition?: Record<string, unknown> | null;
+ focusNodePosition?: Record<string, unknown> | null;
+ style?: { strokeWidth: number };
+ segmentId?: string;
+ segmentPage?: number;
+}
+
+interface IFakeRectRange {
+ activate: VoidMock;
+ deactivate: VoidMock;
+ dispose: VoidMock;
+ isIntersection: IntersectionMock;
+}
+
+interface IServiceHarness {
+ _rangeList: IFakeTextRange[];
+ _rangeListCache: IFakeTextRange[];
+ _rectRangeList: IFakeRectRange[];
+ _rectRangeListCache: IFakeRectRange[];
+ _selectionStyle: { strokeWidth: number };
+ _textSelectionInner$: { next: Mock<(...args: unknown[]) => void> };
+ focus: Mock<() => void>;
+ _getAllTextRanges: Mock<() => string[]>;
+ _getAllRectRanges: Mock<() => string[]>;
+ _findNodeByCoord: Mock<(...args: unknown[]) => unknown>;
+ _getNodePosition: Mock<(...args: unknown[]) => unknown>;
+ _interactTextRanges(textRanges: IFakeTextRange[]): void;
+ _interactRectRanges(rectRanges: IFakeRectRange[]): void;
+ _removeAllRanges(): void;
+ _removeAllCacheRanges(): void;
+ _removeAllCollapsedTextRanges(): void;
+ _addTextRangesToCache(textRanges: IFakeTextRange[]): void;
+ _addTextRange(textRange: IFakeTextRange): void;
+ _addRectRangesToCache(rectRanges: IFakeRectRange[]): void;
+ _addRectRanges(rectRanges: IFakeRectRange[]): void;
+ _createTextRangeByAnchorPosition(position: Record<string, unknown>): void;
+ _isEmpty(): boolean;
+ _getCanvasOffset(): { left: number; top: number };
+ _updateInputPosition(): void;
+ addDocRanges(ranges: Array<Record<string, unknown>>, isEditing?: boolean, options?: Record<string, boolean>): void;
+ setCursorManually(evtOffsetX: number, evtOffsetY: number): void;
+}
+
+function createTextRange(overrides: Partial<IFakeTextRange> = {}): IFakeTextRange {
+ return {
+ activate: vi.fn(),
+ deactivate: vi.fn(),
+ dispose: vi.fn(),
+ getAnchor: vi.fn(() => ({ left: 12, top: 34, visible: true })),
+ isActive: vi.fn(() => false),
+ isIntersection: vi.fn(() => false),
+ collapsed: false,
+ anchorNodePosition: { glyph: 1 },
+ ...overrides,
+ };
+}
+
+function createRectRange(overrides: Partial<IFakeRectRange> = {}): IFakeRectRange {
+ return {
+ activate: vi.fn(),
+ deactivate: vi.fn(),
+ dispose: vi.fn(),
+ isIntersection: vi.fn(() => false),
+ ...overrides,
+ };
+}
+
+function createService() {
+ const engine = { name: 'engine' };
+ const skeleton = { name: 'skeleton' };
+ const mainComponent = { name: 'doc-component' };
+ const scene = {
+ getEngine: vi.fn(() => engine),
+ getViewports: vi.fn(() => []),
+ };
+
+ const service = Object.setPrototypeOf({
+ _rangeList: [],
+ _rangeListCache: [],
+ _rectRangeList: [],
+ _rectRangeListCache: [],
+ _selectionStyle: { strokeWidth: 1 },
+ _currentSegmentId: 'segment-1',
+ _currentSegmentPage: 2,
+ _context: {
+ scene,
+ mainComponent,
+ unitId: 'unit-1',
+ },
+ _docSkeletonManagerService: {
+ getSkeleton: vi.fn(() => skeleton),
+ },
+ _logService: {
+ error: vi.fn(),
+ },
+ _textSelectionInner$: {
+ next: vi.fn(),
+ },
+ _getAllTextRanges: vi.fn(() => ['serialized-text']),
+ _getAllRectRanges: vi.fn(() => ['serialized-rect']),
+ _findNodeByCoord: vi.fn(),
+ _getNodePosition: vi.fn(),
+ focus: vi.fn(),
+ }, DocSelectionRenderService.prototype) as IServiceHarness;
+
+ return {
+ engine,
+ mainComponent,
+ scene,
+ service,
+ skeleton,
+ };
+}
+
+describe('doc selection render service internals', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getCanvasOffsetByEngineMock.mockReturnValue({ left: 8, top: 16 });
+ getRangeListFromCharIndexMock.mockReturnValue(null);
+ getRectRangeFromCharIndexMock.mockReturnValue(null);
+ getTextRangeFromCharIndexMock.mockReturnValue(null);
+ vi.spyOn(TextRange.prototype as unknown as Record<'_anchorBlink', () => void>, '_anchorBlink').mockImplementation(() => {});
+ vi.spyOn(TextRange.prototype, 'refresh').mockImplementation(() => {});
+ });
+
+ it('drops intersecting text and rect ranges while keeping unrelated ones', () => {
+ const { service } = createService();
+ const overlappedText = createTextRange();
+ const preservedText = createTextRange();
+ const nextText = createTextRange();
+ const overlappedRect = createRectRange();
+ const preservedRect = createRectRange();
+ const nextRect = createRectRange();
+
+ nextText.isIntersection.mockImplementation((range) => range === overlappedText);
+ nextRect.isIntersection.mockImplementation((range) => range === overlappedRect);
+
+ service._rangeList = [overlappedText, preservedText];
+ service._rectRangeList = [overlappedRect, preservedRect];
+
+ service._interactTextRanges([nextText]);
+ service._interactRectRanges([nextRect]);
+
+ expect(overlappedText.dispose).toHaveBeenCalledTimes(1);
+ expect(preservedText.dispose).not.toHaveBeenCalled();
+ expect(service._rangeList).toEqual([preservedText]);
+ expect(overlappedRect.dispose).toHaveBeenCalledTimes(1);
+ expect(preservedRect.dispose).not.toHaveBeenCalled();
+ expect(service._rectRangeList).toEqual([preservedRect]);
+ });
+
+ it('adds cache and active ranges, then clears them through shared cleanup', () => {
+ const { service } = createService();
+ const currentText = createTextRange();
+ const currentRect = createRectRange();
+ const cachedText = createTextRange();
+ const cachedRect = createRectRange();
+ const appendedText = createTextRange();
+ const appendedRect = createRectRange();
+ const appendedRectLast = createRectRange();
+
+ service._rangeList = [currentText];
+ service._rectRangeList = [currentRect];
+
+ expect(service._isEmpty()).toBe(false);
+
+ service._addTextRangesToCache([cachedText]);
+ service._addRectRangesToCache([cachedRect]);
+ service._addTextRange(appendedText);
+ service._addRectRanges([appendedRect, appendedRectLast]);
+
+ expect(currentText.deactivate).toHaveBeenCalledTimes(1);
+ expect(appendedText.activate).toHaveBeenCalledTimes(1);
+ expect(currentRect.deactivate).toHaveBeenCalledTimes(1);
+ expect(appendedRect.activate).not.toHaveBeenCalled();
+ expect(appendedRectLast.activate).toHaveBeenCalledTimes(1);
+ expect(service._rangeListCache).toEqual([cachedText]);
+ expect(service._rectRangeListCache).toEqual([cachedRect]);
+ expect(service._rangeList).toEqual([currentText, appendedText]);
+ expect(service._rectRangeList).toEqual([currentRect, appendedRect, appendedRectLast]);
+
+ service._removeAllCacheRanges();
+
+ expect(cachedText.dispose).toHaveBeenCalledTimes(1);
+ expect(cachedRect.dispose).toHaveBeenCalledTimes(1);
+ expect(service._rangeListCache).toEqual([]);
+ expect(service._rectRangeListCache).toEqual([]);
+
+ service._removeAllRanges();
+
+ expect(currentText.dispose).toHaveBeenCalledTimes(1);
+ expect(appendedText.dispose).toHaveBeenCalledTimes(1);
+ expect(currentRect.dispose).toHaveBeenCalledTimes(1);
+ expect(appendedRect.dispose).toHaveBeenCalledTimes(1);
+ expect(appendedRectLast.dispose).toHaveBeenCalledTimes(1);
+ expect(service._rangeList).toEqual([]);
+ expect(service._rectRangeList).toEqual([]);
+ expect(service._isEmpty()).toBe(true);
+ });
+
+ it('removes only collapsed text ranges and focuses when input anchor is unavailable', () => {
+ const { service } = createService();
+ const collapsedRange = createTextRange({
+ collapsed: true,
+ getAnchor: vi.fn(() => null),
+ isActive: vi.fn(() => true),
+ });
+ const expandedRange = createTextRange({ collapsed: false });
+
+ service._rangeList = [collapsedRange, expandedRange];
+
+ service._removeAllCollapsedTextRanges();
+ service._updateInputPosition();
+
+ expect(collapsedRange.dispose).toHaveBeenCalledTimes(1);
+ expect(expandedRange.dispose).not.toHaveBeenCalled();
+ expect(service.focus).toHaveBeenCalledTimes(1);
+ });
+
+ it('creates a text range from anchor position with current skeleton and segment context', () => {
+ const { service } = createService();
+ const oldText = createTextRange();
+ const oldRect = createRectRange();
+ const position = { glyph: 9, line: 3 };
+
+ service._rangeList = [oldText];
+ service._rectRangeList = [oldRect];
+
+ service._createTextRangeByAnchorPosition(position);
+
+ expect(oldText.dispose).toHaveBeenCalledTimes(1);
+ expect(oldRect.dispose).toHaveBeenCalledTimes(1);
+ expect(service._rangeList[0]).toBeInstanceOf(TextRange);
+ expect(service._rangeList[0].anchorNodePosition).toEqual(position);
+ expect(service._rangeList[0].focusNodePosition).toBeUndefined();
+ expect(service._rangeList[0].style).toBe(service._selectionStyle);
+ expect(service._rangeList[0].segmentId).toBe('segment-1');
+ expect(service._rangeList[0].segmentPage).toBe(2);
+ expect(service._rangeList).toHaveLength(1);
+ expect(service._rangeList[0].isActive()).toBe(true);
+ });
+
+ it('adds document ranges across rect, text, and fallback branches without focusing', () => {
+ const { mainComponent, scene, service, skeleton } = createService();
+ const rectRange = createRectRange();
+ const textRange = createTextRange();
+ const fallbackTextRange = createTextRange();
+ const fallbackRectRange = createRectRange();
+ const generalTextRange = createTextRange();
+ const generalRectRange = createRectRange();
+ const updateInputPositionSpy = vi.fn();
+
+ service._updateInputPosition = updateInputPositionSpy;
+
+ getRectRangeFromCharIndexMock.mockReturnValueOnce(rectRange);
+ getTextRangeFromCharIndexMock
+ .mockReturnValueOnce(textRange)
+ .mockImplementationOnce(() => {
+ throw new Error('split across pages');
+ });
+ getRangeListFromCharIndexMock
+ .mockReturnValueOnce({
+ textRanges: [fallbackTextRange],
+ rectRanges: [fallbackRectRange],
+ })
+ .mockReturnValueOnce({
+ textRanges: [generalTextRange],
+ rectRanges: [generalRectRange],
+ });
+
+ service.addDocRanges([
+ { startOffset: 10, endOffset: 14, rangeType: DOC_RANGE_TYPE.RECT },
+ {
+ startOffset: 21,
+ endOffset: 25,
+ rangeType: DOC_RANGE_TYPE.TEXT,
+ startNodePosition: { isBack: false },
+ endNodePosition: { isBack: true },
+ },
+ { startOffset: 31, endOffset: 35, rangeType: DOC_RANGE_TYPE.TEXT },
+ { startOffset: 41, endOffset: 44, rangeType: 'other' },
+ ], false, {
+ fromToolbar: true,
+ shouldFocus: false,
+ });
+
+ expect(getRectRangeFromCharIndexMock).toHaveBeenCalledWith(
+ 10,
+ 14,
+ scene,
+ mainComponent,
+ skeleton,
+ service._selectionStyle,
+ 'segment-1',
+ 2
+ );
+ expect(getTextRangeFromCharIndexMock).toHaveBeenNthCalledWith(
+ 1,
+ 20,
+ 25,
+ scene,
+ mainComponent,
+ skeleton,
+ service._selectionStyle,
+ 'segment-1',
+ 2,
+ false,
+ true
+ );
+ expect(getTextRangeFromCharIndexMock).toHaveBeenNthCalledWith(
+ 2,
+ 31,
+ 35,
+ scene,
+ mainComponent,
+ skeleton,
+ service._selectionStyle,
+ 'segment-1',
+ 2
+ );
+ expect(getRangeListFromCharIndexMock).toHaveBeenNthCalledWith(
+ 1,
+ 31,
+ 35,
+ scene,
+ mainComponent,
+ skeleton,
+ service._selectionStyle,
+ 'segment-1',
+ 2
+ );
+ expect(getRangeListFromCharIndexMock).toHaveBeenNthCalledWith(
+ 2,
+ 41,
+ 44,
+ scene,
+ mainComponent,
+ skeleton,
+ service._selectionStyle,
+ 'segment-1',
+ 2
+ );
+ expect(service._textSelectionInner$.next).toHaveBeenCalledWith({
+ textRanges: ['serialized-text'],
+ rectRanges: ['serialized-rect'],
+ segmentId: 'segment-1',
+ segmentPage: 2,
+ style: service._selectionStyle,
+ isEditing: false,
+ options: {
+ fromToolbar: true,
+ shouldFocus: false,
+ },
+ });
+ expect(updateInputPositionSpy).not.toHaveBeenCalled();
+ expect(service._rangeList).toEqual([textRange, fallbackTextRange, generalTextRange]);
+ expect(service._rectRangeList).toEqual([rectRange, fallbackRectRange, generalRectRange]);
+ });
+
+ it('sets the cursor manually from the resolved paragraph node and emits selection state', () => {
+ const { service } = createService();
+ const position = { glyph: 3 };
+ const createTextRangeByAnchorPositionSpy = vi.fn();
+
+ service._createTextRangeByAnchorPosition = createTextRangeByAnchorPositionSpy;
+ service._findNodeByCoord.mockReturnValue({
+ node: {
+ streamType: DataStreamTreeTokenType.PARAGRAPH,
+ },
+ });
+ service._getNodePosition.mockReturnValue(position);
+
+ service.setCursorManually(12, 24);
+
+ expect(service._findNodeByCoord).toHaveBeenCalledWith(12, 24, {
+ strict: true,
+ segmentId: 'segment-1',
+ segmentPage: 2,
+ });
+ expect(position).toEqual({ glyph: 3, isBack: true });
+ expect(createTextRangeByAnchorPositionSpy).toHaveBeenCalledWith(position);
+ expect(service._textSelectionInner$.next).toHaveBeenCalledWith({
+ textRanges: ['serialized-text'],
+ rectRanges: ['serialized-rect'],
+ segmentId: 'segment-1',
+ segmentPage: 2,
+ style: service._selectionStyle,
+ isEditing: false,
+ });
+ });
+
+ it('clears ranges when manual cursor placement cannot resolve a node position', () => {
+ const { service } = createService();
+ const removeAllRangesSpy = vi.fn();
+
+ service._removeAllRanges = removeAllRangesSpy;
+ service._getNodePosition.mockReturnValue(null);
+
+ service.setCursorManually(4, 8);
+
+ expect(removeAllRangesSpy).toHaveBeenCalledTimes(1);
+ expect(service._textSelectionInner$.next).not.toHaveBeenCalled();
+ });
+
+ it('reads canvas offsets from the current engine', () => {
+ const { engine, service } = createService();
+
+ expect(service._getCanvasOffset()).toEqual({ left: 8, top: 16 });
+ expect(getCanvasOffsetByEngineMock).toHaveBeenCalledWith(engine);
+ });
+});
diff --git a/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts b/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts
new file mode 100644
index 0000000000..16d9ec9c7a
--- /dev/null
+++ b/packages/docs-ui/src/services/selection/__tests__/range-state.spec.ts
@@ -0,0 +1,172 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { RectRange } from '../rect-range';
+import { TextRange } from '../text-range';
+
+function getGetter<T extends object>(target: T, key: keyof T) {
+ return Object.getOwnPropertyDescriptor(target, key)?.get as () => unknown;
+}
+
+interface IFakeShape {
+ dispose: ReturnType<typeof vi.fn>;
+}
+
+interface IFakeTextRange {
+ _cursorList: Array<{ startOffset: number; endOffset: number; collapsed: boolean }>;
+ _segmentId: string;
+ _segmentPage: number;
+ _current: boolean;
+ _rangeShape: IFakeShape;
+ _anchorShape: IFakeShape;
+ _docSkeleton: Record<string, unknown>;
+ anchorNodePosition: Record<string, unknown>;
+ focusNodePosition: Record<string, unknown>;
+}
+
+interface IFakeRectRange {
+ _startRow: number;
+ _endRow: number;
+ _startCol: number;
+ _endCol: number;
+ _tableId: string;
+ _segmentId: string;
+ _segmentPage: number;
+ _current: boolean;
+ _rangeShape: IFakeShape;
+ _docSkeleton: Record<string, unknown>;
+ anchorNodePosition: Record<string, unknown>;
+ focusNodePosition: Record<string, unknown>;
+}
+
+describe('selection range state', () => {
+ it('derives text range offsets, direction, and active state from prototype getters', () => {
+ const fakeRange = Object.setPrototypeOf({
+ _cursorList: [{ startOffset: 9, endOffset: 9, collapsed: true }],
+ _segmentId: '',
+ _segmentPage: -1,
+ _current: false,
+ _rangeShape: { dispose: vi.fn() },
+ _anchorShape: { dispose: vi.fn() },
+ _docSkeleton: {
+ getViewModel: () => ({
+ getDataModel: () => ({
+ getSelfOrHeaderFooterModel: () => ({
+ getBody: () => ({ dataStream: 'Hello\r\n' }),
+ }),
+ }),
+ }),
+ },
+ anchorNodePosition: { page: 0, section: 0, column: 0, line: 1, divide: 0, glyph: 0 },
+ focusNodePosition: { page: 0, section: 0, column: 0, line: 0, divide: 0, glyph: 0 },
+ }, TextRange.prototype) as IFakeTextRange;
+
+ expect(getGetter(TextRange.prototype, 'startOffset').call(fakeRange)).toBe(5);
+ expect(getGetter(TextRange.prototype, 'endOffset').call(fakeRange)).toBe(5);
+ expect(getGetter(TextRange.prototype, 'collapsed').call(fakeRange)).toBe(true);
+ expect(getGetter(TextRange.prototype, 'startNodePosition').call(fakeRange)).toEqual(fakeRange.focusNodePosition);
+ expect(getGetter(TextRange.prototype, 'endNodePosition').call(fakeRange)).toEqual(fakeRange.anchorNodePosition);
+ expect(getGetter(TextRange.prototype, 'direction').call(fakeRange)).toBe('none');
+
+ expect(TextRange.prototype.isActive.call(fakeRange)).toBe(false);
+ TextRange.prototype.activate.call(fakeRange);
+ expect(TextRange.prototype.isActive.call(fakeRange)).toBe(true);
+ TextRange.prototype.deactivate.call(fakeRange);
+ expect(TextRange.prototype.isActive.call(fakeRange)).toBe(false);
+ const textRangeShape = fakeRange._rangeShape;
+ const textAnchorShape = fakeRange._anchorShape;
+ TextRange.prototype.dispose.call(fakeRange);
+ expect(textRangeShape.dispose).toHaveBeenCalled();
+ expect(textAnchorShape.dispose).toHaveBeenCalled();
+ });
+
+ it('derives rect range table bounds, ordering, intersections, and active state', () => {
+ const anchorNodePosition = {
+ page: 0,
+ section: 0,
+ column: 0,
+ line: 0,
+ divide: 0,
+ glyph: 0,
+ path: ['pages', 0, 'skeTables', 'table#-#0', 'rows', 0, 'cells', 0],
+ };
+ const focusNodePosition = {
+ page: 0,
+ section: 0,
+ column: 0,
+ line: 0,
+ divide: 0,
+ glyph: 0,
+ path: ['pages', 0, 'skeTables', 'table#-#0', 'rows', 1, 'cells', 1],
+ };
+ const fakeRange = Object.setPrototypeOf({
+ _startRow: 0,
+ _endRow: 1,
+ _startCol: 0,
+ _endCol: 1,
+ _tableId: 'table-1',
+ _segmentId: '',
+ _segmentPage: -1,
+ _current: false,
+ _rangeShape: { dispose: vi.fn() },
+ _docSkeleton: {
+ findCharIndexByPosition: vi.fn((position) => position === anchorNodePosition ? 1 : 4),
+ getViewModel: () => ({
+ getSnapshot: () => ({
+ tableSource: {
+ 'table-1': {
+ tableColumns: [{}, {}],
+ tableRows: [{}, {}],
+ },
+ },
+ }),
+ }),
+ },
+ anchorNodePosition,
+ focusNodePosition,
+ }, RectRange.prototype) as IFakeRectRange;
+
+ expect(getGetter(RectRange.prototype, 'startOffset').call(fakeRange)).toBe(1);
+ expect(getGetter(RectRange.prototype, 'endOffset').call(fakeRange)).toBe(4);
+ expect(getGetter(RectRange.prototype, 'collapsed').call(fakeRange)).toBe(false);
+ expect(getGetter(RectRange.prototype, 'startRow').call(fakeRange)).toBe(0);
+ expect(getGetter(RectRange.prototype, 'endColumn').call(fakeRange)).toBe(1);
+ expect(getGetter(RectRange.prototype, 'tableId').call(fakeRange)).toBe('table-1');
+ expect(getGetter(RectRange.prototype, 'spanEntireRow').call(fakeRange)).toBe(true);
+ expect(getGetter(RectRange.prototype, 'spanEntireColumn').call(fakeRange)).toBe(true);
+ expect(getGetter(RectRange.prototype, 'spanEntireTable').call(fakeRange)).toBe(true);
+ expect(getGetter(RectRange.prototype, 'startNodePosition').call(fakeRange)).toEqual(anchorNodePosition);
+ expect(getGetter(RectRange.prototype, 'endNodePosition').call(fakeRange)).toEqual(focusNodePosition);
+ expect(getGetter(RectRange.prototype, 'direction').call(fakeRange)).toBe('forward');
+
+ const compareRange = {
+ startRow: 1,
+ startColumn: 1,
+ endRow: 2,
+ endColumn: 2,
+ } as never;
+ expect(RectRange.prototype.isIntersection.call(fakeRange, compareRange)).toBe(true);
+
+ expect(RectRange.prototype.isActive.call(fakeRange)).toBe(false);
+ RectRange.prototype.activate.call(fakeRange);
+ expect(RectRange.prototype.isActive.call(fakeRange)).toBe(true);
+ RectRange.prototype.deactivate.call(fakeRange);
+ const rectShape = fakeRange._rangeShape;
+ RectRange.prototype.dispose.call(fakeRange);
+ expect(rectShape.dispose).toHaveBeenCalled();
+ });
+});
diff --git a/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
new file mode 100644
index 0000000000..daca1fb4aa
--- /dev/null
+++ b/packages/docs-ui/src/services/selection/__tests__/selection-utils.spec.ts
@@ -0,0 +1,289 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { getOffsetRectForDom } from '@univerjs/engine-render';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { NodePositionConvertToRectRange } from '../convert-rect-range';
+import { RectRange } from '../rect-range';
+import {
+ getCanvasOffsetByEngine,
+ getParagraphInfoByGlyph,
+ getRangeListFromSelection,
+ getRectRangeFromCharIndex,
+ getTextRangeFromCharIndex,
+ serializeRectRange,
+ serializeTextRange,
+} from '../selection-utils';
+import { TextRange } from '../text-range';
+
+vi.mock('@univerjs/engine-render', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/engine-render')>();
+
+ return {
+ ...actual,
+ getOffsetRectForDom: vi.fn(),
+ };
+});
+
+function createNodePosition(path: Array<string | number>, glyph = 0) {
+ return {
+ path,
+ page: 0,
+ section: 0,
+ column: 0,
+ line: 0,
+ divide: 0,
+ glyph,
+ isBack: false,
+ segmentPage: -1,
+ pageType: 0,
+ } as never;
+}
+
+function createGlyphInCell(cellPage: object) {
+ return {
+ parent: {
+ parent: {
+ parent: {
+ parent: {
+ parent: cellPage,
+ },
+ },
+ },
+ },
+ } as never;
+}
+
+function createDocument() {
+ return {
+ getOffsetConfig: () => ({
+ docsLeft: 0,
+ docsTop: 0,
+ }),
+ } as never;
+}
+
+describe('selection utils', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(TextRange.prototype as unknown as Record<'_anchorBlink', () => void>, '_anchorBlink').mockImplementation(() => {});
+ vi.spyOn(TextRange.prototype, 'refresh').mockImplementation(() => {});
+ vi.spyOn(RectRange.prototype, 'refresh').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('creates text and rect ranges from char indexes', () => {
+ const startPosition = { glyph: 0 };
+ const endPosition = { glyph: 1 };
+ const skeleton = {
+ findNodePositionByCharIndex: vi
+ .fn()
+ .mockReturnValueOnce(startPosition)
+ .mockReturnValueOnce(endPosition)
+ .mockReturnValueOnce(startPosition)
+ .mockReturnValueOnce(endPosition),
+ } as never;
+
+ const textRange = getTextRangeFromCharIndex(1, 2, {} as never, createDocument(), skeleton, {} as never, '', -1);
+ const rectRange = getRectRangeFromCharIndex(1, 2, {} as never, createDocument(), skeleton, {} as never, '', -1);
+
+ expect(textRange).toBeInstanceOf(TextRange);
+ expect(textRange?.anchorNodePosition).toEqual(startPosition);
+ expect(textRange?.focusNodePosition).toEqual(endPosition);
+ expect(rectRange).toBeInstanceOf(RectRange);
+ expect(rectRange?.anchorNodePosition).toEqual(startPosition);
+ expect(rectRange?.focusNodePosition).toEqual(endPosition);
+ });
+
+ it('routes same-cell and rect selections into the expected range buckets', () => {
+ const sameCellAnchor = createNodePosition(['skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0]);
+ const sameCellFocus = createNodePosition(['skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0], 1);
+ const crossPageFocus = createNodePosition(['skeTables', 'table-1#-#1', 'rows', 0, 'cells', 0], 1);
+ const rectAnchor = createNodePosition(['skeTables', 'table-1#-#0', 'rows', 0, 'cells', 0]);
+ const rectFocus = createNodePosition(['skeTables', 'table-1#-#0', 'rows', 1, 'cells', 0], 1);
+ const sameCellPage = {} as { parent?: unknown };
+ const sameCellRow = { index: 0, cells: [sameCellPage] };
+ sameCellPage.parent = sameCellRow;
+
+ const crossPageStartCell = {} as { parent?: unknown };
+ const crossPageStartRow = { index: 0, cells: [crossPageStartCell] };
+ crossPageStartCell.parent = crossPageStartRow;
+
+ const crossPageEndCell = {} as { parent?: unknown };
+ const crossPageEndRow = { index: 0, cells: [crossPageEndCell] };
+ crossPageEndCell.parent = crossPageEndRow;
+
+ const skeleton = {
+ findGlyphByPosition: vi
+ .fn()
+ .mockReturnValueOnce(createGlyphInCell(sameCellPage))
+ .mockReturnValueOnce(createGlyphInCell(sameCellPage))
+ .mockReturnValueOnce(createGlyphInCell(crossPageStartCell))
+ .mockReturnValueOnce(createGlyphInCell(crossPageEndCell))
+ .mockReturnValueOnce(null)
+ .mockReturnValueOnce(null),
+ } as never;
+ const document = createDocument();
+
+ vi.spyOn(NodePositionConvertToRectRange.prototype, 'getNodePositionGroup').mockReturnValue([
+ {
+ anchor: rectAnchor,
+ focus: rectFocus,
+ },
+ ] as never);
+
+ const sameCell = getRangeListFromSelection(sameCellAnchor, sameCellFocus, {} as never, document, skeleton, {} as never, '', -1);
+ expect(sameCell?.textRanges).toHaveLength(1);
+ expect(sameCell?.rectRanges).toHaveLength(0);
+ expect(sameCell?.textRanges[0]).toBeInstanceOf(TextRange);
+
+ const sameTable = getRangeListFromSelection(sameCellAnchor, crossPageFocus, {} as never, document, skeleton, {} as never, '', -1);
+ expect(sameTable?.textRanges).toHaveLength(0);
+ expect(sameTable?.rectRanges).toHaveLength(1);
+ expect(sameTable?.rectRanges[0]).toBeInstanceOf(RectRange);
+
+ const rectRange = getRangeListFromSelection(rectAnchor, rectFocus, {} as never, document, skeleton, {} as never, '', -1);
+ expect(rectRange?.textRanges).toHaveLength(0);
+ expect(rectRange?.rectRanges).toHaveLength(1);
+ expect(rectRange?.rectRanges[0]).toBeInstanceOf(RectRange);
+ });
+
+ it('builds normal text ranges outside tables and skips when offsets are missing', () => {
+ const startNode = { glyph: 10 };
+ const endNode = { glyph: 20 };
+ const paragraph = {
+ startIndex: 0,
+ endIndex: 10,
+ children: [],
+ };
+ const skeleton = {
+ findCharIndexByPosition: vi
+ .fn()
+ .mockReturnValueOnce(1)
+ .mockReturnValueOnce(4)
+ .mockReturnValueOnce(null)
+ .mockReturnValueOnce(4),
+ findNodePositionByCharIndex: vi
+ .fn()
+ .mockReturnValueOnce(startNode)
+ .mockReturnValueOnce(endNode),
+ getViewModel: () => ({
+ getSelfOrHeaderFooterViewModel: () => ({
+ getChildren: () => [{ children: [paragraph] }],
+ }),
+ }),
+ } as never;
+
+ const result = getRangeListFromSelection(
+ createNodePosition(['body']),
+ createNodePosition(['body'], 1),
+ {} as never,
+ createDocument(),
+ skeleton,
+ {} as never,
+ '',
+ -1
+ );
+ expect(result?.textRanges).toHaveLength(1);
+ expect(result?.rectRanges).toHaveLength(0);
+ expect(result?.textRanges[0]).toBeInstanceOf(TextRange);
+
+ const missing = getRangeListFromSelection(
+ createNodePosition(['body']),
+ createNodePosition(['body'], 1),
+ {} as never,
+ createDocument(),
+ skeleton,
+ {} as never,
+ '',
+ -1
+ );
+ expect(missing).toBeUndefined();
+ });
+
+ it('reads canvas offsets, paragraph glyph info, and serializes ranges', () => {
+ vi.mocked(getOffsetRectForDom).mockReturnValue({ left: 12, top: 34 } as never);
+
+ expect(getCanvasOffsetByEngine({ getCanvasElement: () => ({}) } as never)).toEqual({ left: 12, top: 34 });
+ expect(getCanvasOffsetByEngine(null)).toEqual({ left: 0, top: 0 });
+
+ const glyphA: Record<string, unknown> = { count: 1, content: 'A' };
+ const glyphB: Record<string, unknown> = { count: 2, content: 'BC' };
+ const paragraphLine1 = { paragraphIndex: 1, st: 3, divides: [{ glyphGroup: [glyphA] }] };
+ const paragraphLine2 = { paragraphIndex: 1, st: 3, divides: [{ glyphGroup: [glyphB] }] };
+ const column = { lines: [paragraphLine1, paragraphLine2] };
+ const line = { paragraphIndex: 1, parent: column };
+ glyphA.parent = { parent: line };
+ glyphB.parent = { parent: line };
+
+ expect(getParagraphInfoByGlyph(glyphB as never)).toEqual({
+ st: 3,
+ ed: 1,
+ content: 'ABC',
+ nodeIndex: 2,
+ });
+ expect(getParagraphInfoByGlyph({ parent: null } as never)).toBeUndefined();
+
+ const textRange = {
+ startOffset: 1,
+ endOffset: 3,
+ collapsed: false,
+ rangeType: 'TEXT',
+ startNodePosition: { glyph: 0 },
+ endNodePosition: { glyph: 1 },
+ direction: 'FORWARD',
+ segmentId: 'body',
+ segmentPage: -1,
+ isActive: () => true,
+ } as never;
+ expect(serializeTextRange(textRange)).toMatchObject({
+ startOffset: 1,
+ endOffset: 3,
+ isActive: true,
+ segmentId: 'body',
+ });
+
+ const rectRange = {
+ startOffset: 1,
+ endOffset: 3,
+ collapsed: false,
+ rangeType: 'RECT',
+ startNodePosition: { glyph: 0 },
+ endNodePosition: { glyph: 1 },
+ direction: 'FORWARD',
+ segmentId: 'body',
+ segmentPage: -1,
+ startRow: 0,
+ startColumn: 1,
+ endRow: 2,
+ endColumn: 3,
+ tableId: 'table-1',
+ spanEntireRow: true,
+ spanEntireColumn: false,
+ spanEntireTable: false,
+ isActive: () => false,
+ } as never;
+ expect(serializeRectRange(rectRange)).toMatchObject({
+ tableId: 'table-1',
+ startRow: 0,
+ endColumn: 3,
+ isActive: false,
+ });
+ });
+});
diff --git a/packages/docs/src/__tests__/docs.integration.spec.ts b/packages/docs/src/__tests__/docs.integration.spec.ts
new file mode 100644
index 0000000000..8abb93ccce
--- /dev/null
+++ b/packages/docs/src/__tests__/docs.integration.spec.ts
@@ -0,0 +1,393 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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, ICustomRangeForInterceptor, IDocumentData, IInterceptor } from '@univerjs/core';
+import type { IRenderContext } from '@univerjs/engine-render';
+
+import {
+ CustomRangeType,
+ ICommandService,
+ IUniverInstanceService,
+ LifecycleService,
+ LifecycleStages,
+ LocaleService,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { DocsRenameMutation } from '../commands/mutations/docs-rename.mutation';
+import { SetTextSelectionsOperation } from '../commands/operations/text-selection.operation';
+import { UniverDocsPlugin } from '../plugin';
+import { DocInterceptorService } from '../services/doc-interceptor/doc-interceptor.service';
+import { DOC_INTERCEPTOR_POINT } from '../services/doc-interceptor/interceptor-const';
+import { DocSelectionManagerService } from '../services/doc-selection-manager.service';
+import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
+import { DocStateEmitService } from '../services/doc-state-emit.service';
+import { DocViewModelManagerService } from '../services/doc-view-model-manager.service';
+import { addCustomRangeBySelectionFactory, deleteCustomRangeFactory } from '../utils/custom-range-factory';
+import { replaceSelectionFactory } from '../utils/replace-selection-factory';
+
+function waitNextTick() {
+ return new Promise<void>((resolve) => setTimeout(resolve, 0));
+}
+
+function registerRenderManagerForDoc(
+ injector: ReturnType<Univer['__getInjector']>,
+ doc: DocumentDataModel
+) {
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ const context: IRenderContext<DocumentDataModel> = {
+ unitId: doc.getUnitId(),
+ unit: doc,
+ } as never;
+
+ const skeletonManager = new DocSkeletonManagerService(
+ context,
+ injector.get(LocaleService),
+ univerInstanceService
+ );
+
+ injector.add([IRenderManagerService, {
+ useValue: {
+ getRenderById: (unitId: string) => unitId === doc.getUnitId()
+ ? ({
+ with: () => skeletonManager,
+ } as never)
+ : null,
+ } as never,
+ }]);
+
+ return skeletonManager;
+}
+
+function createTestDocData(id: string): IDocumentData {
+ return {
+ id,
+ body: {
+ dataStream: 'Hello\r\n',
+ customRanges: [{
+ startIndex: 0,
+ endIndex: 4,
+ rangeId: 'range-1',
+ rangeType: CustomRangeType.HYPERLINK,
+ wholeEntity: true,
+ properties: { url: 'https://example.invalid' },
+ }],
+ },
+ documentStyle: {
+ pageSize: { width: 100, height: 100 },
+ marginTop: 0,
+ marginBottom: 0,
+ marginLeft: 0,
+ marginRight: 0,
+ },
+ };
+}
+
+describe('docs integration', () => {
+ let univer: Univer;
+ let injector: ReturnType<Univer['__getInjector']>;
+
+ beforeEach(() => {
+ univer = new Univer();
+ injector = univer.__getInjector();
+ injector.get(LifecycleService).stage = LifecycleStages.Starting;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('renames doc through command service mutation', async () => {
+ univer.registerPlugin(UniverDocsPlugin);
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createTestDocData('doc-1')
+ );
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(doc.getUnitId());
+
+ const commandService = injector.get(ICommandService);
+ const ok = await commandService.executeCommand(DocsRenameMutation.id, {
+ unitId: doc.getUnitId(),
+ name: 'Renamed',
+ });
+
+ expect(ok).toBeTruthy();
+ expect(doc.getTitle()).toBe('Renamed');
+ });
+
+ it('manages selections and emits selection operations via real command flow', async () => {
+ univer.registerPlugin(UniverDocsPlugin);
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createTestDocData('doc-2')
+ );
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(doc.getUnitId());
+
+ const commandService = injector.get(ICommandService);
+
+ const selectionManager = injector.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: doc.getUnitId(),
+ subUnitId: doc.getUnitId(),
+ });
+
+ selectionManager.__TEST_ONLY_add([
+ {
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ },
+ {
+ startOffset: 0,
+ endOffset: 2,
+ collapsed: false,
+ isActive: false,
+ segmentId: '',
+ style: null as never,
+ },
+ ]);
+
+ expect(selectionManager.getActiveTextRange()?.startOffset).toBe(5);
+ expect(selectionManager.getDocRanges()?.map((r) => r.startOffset)).toEqual([0, 5]);
+
+ const refreshLogs: unknown[] = [];
+ const refreshSub = selectionManager.refreshSelection$.subscribe((v) => v && refreshLogs.push(v));
+ selectionManager.replaceDocRanges([
+ { startOffset: 1, endOffset: 1, collapsed: true, segmentId: '' },
+ ] as never);
+
+ expect(refreshLogs.length).toBeGreaterThan(0);
+ refreshSub.unsubscribe();
+
+ const executed: Array<{ id: string; params: unknown }> = [];
+ const dispose = commandService.onCommandExecuted((info) => executed.push({ id: info.id, params: info.params }));
+
+ selectionManager.__replaceTextRangesWithNoRefresh(
+ {
+ segmentId: '',
+ segmentPage: -1,
+ style: null as never,
+ textRanges: [{ startOffset: 2, endOffset: 3, collapsed: false, segmentId: '' }] as never,
+ rectRanges: [],
+ isEditing: true,
+ },
+ { unitId: doc.getUnitId(), subUnitId: doc.getUnitId() }
+ );
+
+ await waitNextTick();
+ expect(executed.some((e) => e.id === SetTextSelectionsOperation.id)).toBe(true);
+ dispose.dispose();
+ });
+
+ it('replaces a selection through the factory-generated rich text mutation', async () => {
+ univer.registerPlugin(UniverDocsPlugin);
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createTestDocData('doc-2a')
+ );
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(doc.getUnitId());
+ const skeletonManager = registerRenderManagerForDoc(injector, doc);
+
+ const selectionManager = injector.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: doc.getUnitId(),
+ subUnitId: doc.getUnitId(),
+ });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 5,
+ endOffset: 5,
+ collapsed: true,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ const docStateEmitService = injector.get(DocStateEmitService);
+ const stateChanges: unknown[] = [];
+ const sub = docStateEmitService.docStateChangeParams$.subscribe((value) => value && stateChanges.push(value));
+
+ const mutation = replaceSelectionFactory(injector as never, {
+ unitId: doc.getUnitId(),
+ body: {
+ dataStream: ' world',
+ },
+ });
+
+ expect(mutation).not.toBe(false);
+ if (mutation === false) {
+ throw new Error('Expected replaceSelectionFactory to create a mutation.');
+ }
+ expect(mutation.params.textRanges?.[0]?.startOffset).toBe(11);
+
+ const commandService = injector.get(ICommandService);
+ const ok = await commandService.executeCommand(mutation.id, {
+ ...mutation.params,
+ trigger: 'integration-spec' as never,
+ });
+
+ await waitNextTick();
+
+ expect(ok).toBeTruthy();
+ expect(doc.getBody()?.dataStream).toBe('Hello world\r\n');
+ expect(stateChanges).toHaveLength(1);
+
+ sub.unsubscribe();
+ skeletonManager.dispose();
+ });
+
+ it('adds and removes custom ranges through the same mutation pipeline', async () => {
+ univer.registerPlugin(UniverDocsPlugin);
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createTestDocData('doc-2b')
+ );
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(doc.getUnitId());
+ const skeletonManager = registerRenderManagerForDoc(injector, doc);
+
+ const selectionManager = injector.get(DocSelectionManagerService);
+ selectionManager.__TEST_ONLY_setCurrentSelection({
+ unitId: doc.getUnitId(),
+ subUnitId: doc.getUnitId(),
+ });
+ selectionManager.__TEST_ONLY_add([{
+ startOffset: 0,
+ endOffset: 4,
+ collapsed: false,
+ isActive: true,
+ segmentId: '',
+ style: null as never,
+ }]);
+
+ const commandService = injector.get(ICommandService);
+ const addMutation = addCustomRangeBySelectionFactory(injector as never, {
+ unitId: doc.getUnitId(),
+ rangeId: 'range-2',
+ rangeType: CustomRangeType.HYPERLINK,
+ wholeEntity: true,
+ properties: {
+ url: 'https://added.invalid',
+ },
+ });
+
+ expect(addMutation).not.toBe(false);
+ if (addMutation === false) {
+ throw new Error('Expected addCustomRangeBySelectionFactory to create a mutation.');
+ }
+ await commandService.executeCommand(addMutation.id, addMutation.params);
+
+ expect(doc.getBody()?.customRanges?.find((range) => range.rangeId === 'range-2')?.properties).toEqual({
+ url: 'https://added.invalid',
+ });
+
+ const deleteMutation = deleteCustomRangeFactory(injector as never, {
+ unitId: doc.getUnitId(),
+ rangeId: 'range-2',
+ });
+
+ expect(deleteMutation).not.toBe(false);
+ if (deleteMutation === false) {
+ throw new Error('Expected deleteCustomRangeFactory to create a mutation.');
+ }
+ await commandService.executeCommand(deleteMutation.id, deleteMutation.params);
+
+ expect(doc.getBody()?.customRanges?.some((range) => range.rangeId === 'range-2')).toBe(false);
+ skeletonManager.dispose();
+ });
+
+ it('builds skeleton/view-model and applies interceptors for custom ranges', () => {
+ const doc = univer.createUnit<IDocumentData, DocumentDataModel>(
+ UniverInstanceType.UNIVER_DOC,
+ createTestDocData('doc-3')
+ );
+
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(doc.getUnitId());
+
+ const context: IRenderContext<DocumentDataModel> = {
+ unitId: doc.getUnitId(),
+ unit: doc,
+ } as never;
+
+ const skeletonManager = new DocSkeletonManagerService(
+ context,
+ injector.get(LocaleService),
+ univerInstanceService
+ );
+
+ const viewModelManager = new DocViewModelManagerService(context, univerInstanceService);
+ expect(viewModelManager.getViewModel(doc.getUnitId())).toBeDefined();
+
+ const interceptorService = new DocInterceptorService(context, skeletonManager);
+ interceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {
+ priority: 10,
+ handler: (range, ctx, next) => {
+ const nextRange = next(range);
+ return nextRange ? { ...nextRange, properties: { ...nextRange.properties, unitId: ctx.unitId } } : nextRange;
+ },
+ } as IInterceptor<ICustomRangeForInterceptor, {
+ index: number;
+ unitId: string;
+ customRanges: ICustomRangeForInterceptor[];
+ }>);
+
+ interceptorService.intercept(DOC_INTERCEPTOR_POINT.CUSTOM_RANGE, {
+ priority: -10,
+ handler: (range, _ctx, next) => {
+ const nextRange = next(range);
+ return nextRange ? { ...nextRange, properties: { ...nextRange.properties, tagged: true } } : nextRange;
+ },
+ } as IInterceptor<ICustomRangeForInterceptor, {
+ index: number;
+ unitId: string;
+ customRanges: ICustomRangeForInterceptor[];
+ }>);
+
+ const range = skeletonManager.getViewModel().getCustomRange(1);
+ expect(range?.rangeId).toBe('range-1');
+ expect(range?.properties).toMatchObject({ unitId: doc.getUnitId(), tagged: true });
+
+ const docStateEmitService = new DocStateEmitService();
+ const values: unknown[] = [];
+ const sub = docStateEmitService.docStateChangeParams$.subscribe((v) => v && values.push(v));
+ docStateEmitService.emitStateChangeInfo({
+ commandId: 'test',
+ unitId: doc.getUnitId(),
+ trigger: null,
+ redoState: { actions: [], textRanges: null },
+ undoState: { actions: [], textRanges: null },
+ });
+ expect(values.length).toBe(1);
+ sub.unsubscribe();
+
+ interceptorService.dispose();
+ viewModelManager.dispose();
+ skeletonManager.dispose();
+ });
+});
diff --git a/packages/drawing-ui/src/controllers/__tests__/drawing-ui.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/drawing-ui.controller.spec.ts
new file mode 100644
index 0000000000..aaf2daa936
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/__tests__/drawing-ui.controller.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 type { ICommandService } from '@univerjs/core';
+import type { ComponentManager } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { COMPONENT_IMAGE_POPUP_MENU } from '../../views/image-popup-menu/component-name';
+import { DrawingUIController } from '../drawing-ui.controller';
+
+describe('DrawingUIController', () => {
+ it('registers popup components and drawing operations', () => {
+ const register = vi.fn(() => ({ dispose: vi.fn() }));
+ const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));
+
+ const controller = new DrawingUIController(
+ { register } as unknown as ComponentManager,
+ { registerCommand } as unknown as ICommandService
+ );
+
+ expect(controller).toBeTruthy();
+ expect(registerCommand).toHaveBeenCalledTimes(5);
+ expect(register).toHaveBeenCalledWith(COMPONENT_IMAGE_POPUP_MENU, expect.any(Function));
+ });
+});
diff --git a/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.ts
new file mode 100644
index 0000000000..47585769f6
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/__tests__/drawing-update.controller.spec.ts
@@ -0,0 +1,231 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo } from '@univerjs/core';
+import type { IDrawingGroupUpdateParam } from '@univerjs/drawing';
+import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';
+import { SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { AlignType, SetDrawingAlignOperation } from '../../commands/operations/drawing-align.operation';
+import { DrawingUpdateController } from '../drawing-update.controller';
+
+interface IDrawingNotification {
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+}
+
+interface IDrawingTransformObject {
+ oKey: string;
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ angle: number;
+ isInGroup?: boolean;
+}
+
+function createHarness() {
+ const add$ = new Subject<IDrawingNotification[]>();
+ const remove$ = new Subject<IDrawingNotification[]>();
+ const update$ = new Subject<IDrawingNotification[]>();
+ const refreshTransform$ = new Subject<IDrawingNotification[]>();
+ const visible$ = new Subject<Array<IDrawingNotification & { visible: boolean }>>();
+ const order$ = new Subject<{ unitId: string; subUnitId: string; drawingIds: string[] }>();
+ const group$ = new Subject<IDrawingGroupUpdateParam[]>();
+ const ungroup$ = new Subject<IDrawingGroupUpdateParam[]>();
+
+ const changeStart$ = new Subject<{ objects: Map<string, IDrawingTransformObject> }>();
+ const changeEnd$ = new Subject<{ objects: Map<string, IDrawingTransformObject> }>();
+ const transformer = {
+ changeStart$,
+ changeEnd$,
+ clearSelectedObjects: vi.fn(),
+ setSelectedControl: vi.fn(),
+ refreshControls: vi.fn(() => ({ changeNotification: vi.fn() })),
+ };
+
+ const debounceRefreshControls = vi.fn();
+ const sceneTransformer = {
+ debounceRefreshControls,
+ clearSelectedObjects: vi.fn(),
+ };
+
+ const zIndexShape = { setProps: vi.fn(), makeDirty: vi.fn() };
+ const disposeShape = { dispose: vi.fn() };
+ const showHideShape = { show: vi.fn(), hide: vi.fn() };
+ const transformShape = { transformByState: vi.fn() };
+
+ const scene = {
+ getTransformerByCreate: vi.fn(() => transformer),
+ getTransformer: vi.fn(() => sceneTransformer),
+ getObject: vi.fn((key: string) => {
+ if (key.includes('drawing-visible')) return showHideShape;
+ if (key.includes('drawing-transform')) return transformShape;
+ return null;
+ }),
+ getObjectIncludeInGroup: vi.fn(() => null),
+ fuzzyMathObjects: vi.fn((key: string) => {
+ if (key.includes('drawing-z')) return [zIndexShape];
+ if (key.includes('drawing-remove')) return [disposeShape];
+ return [];
+ }),
+ addObject: vi.fn(() => ({ attachTransformerTo: vi.fn() })),
+ addObjects: vi.fn(),
+ makeDirty: vi.fn(),
+ };
+
+ const renderManagerService = {
+ getRenderById: vi.fn(() => ({ scene })),
+ };
+
+ const drawingParams = new Map<string, { unitId: string; subUnitId: string; drawingId: string; drawingType: DrawingTypeEnum; transform: { left: number; top: number; width: number; height: number; angle: number } }>([
+ ['drawing-a', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 0, top: 0, width: 10, height: 10, angle: 0 } }],
+ ['drawing-b', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-b', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 20, top: 0, width: 10, height: 10, angle: 0 } }],
+ ['drawing-transform', { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-transform', drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 1, top: 2, width: 3, height: 4, angle: 0 } }],
+ ]);
+
+ const drawingManagerService = {
+ drawingManagerData: {},
+ add$,
+ remove$,
+ update$,
+ refreshTransform$,
+ visible$,
+ order$,
+ group$,
+ ungroup$,
+ getDrawingByParam: vi.fn(({ drawingId }: { drawingId: string }) => drawingParams.get(drawingId) ?? null),
+ getDrawingOKey: vi.fn((oKey: string) => ({ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: oKey, drawingType: DrawingTypeEnum.DRAWING_IMAGE, transform: { left: 0, top: 0, width: 10, height: 10, angle: 0 } })),
+ getDrawingOrder: vi.fn(() => ['drawing-z']),
+ getFocusDrawings: vi.fn(() => [
+ { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a', drawingType: DrawingTypeEnum.DRAWING_IMAGE },
+ { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-b', drawingType: DrawingTypeEnum.DRAWING_IMAGE },
+ ]),
+ featurePluginUpdateNotification: vi.fn(),
+ };
+
+ let commandExecuted: ((cmd: ICommandInfo) => void) | undefined;
+ const commandService = {
+ onCommandExecuted: vi.fn((handler: (cmd: ICommandInfo) => void) => {
+ commandExecuted = handler;
+ return { dispose: vi.fn() };
+ }),
+ syncExecuteCommand: vi.fn(),
+ };
+
+ const controller = new DrawingUpdateController(
+ {
+ getFocusedUnit: vi.fn(() => ({
+ type: UniverInstanceType.UNIVER_SHEET,
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ })),
+ } as never,
+ commandService as never,
+ renderManagerService as never,
+ drawingManagerService as never
+ );
+
+ return {
+ controller,
+ add$,
+ changeStart$,
+ changeEnd$,
+ commandExecuted: () => commandExecuted,
+ drawingManagerService,
+ order$,
+ refreshTransform$,
+ remove$,
+ scene,
+ showHideShape,
+ transformShape,
+ update$,
+ visible$,
+ zIndexShape,
+ disposeShape,
+ debounceRefreshControls,
+ transformer,
+ commandService,
+ };
+}
+
+describe('DrawingUpdateController', () => {
+ it('syncs selection on transform start and persists transform changes on end', () => {
+ const harness = createHarness();
+
+ harness.add$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a' }]);
+
+ const oKey = 'drawing-a';
+ const startObject = { oKey, left: 0, top: 0, width: 10, height: 10, angle: 0, isInGroup: false };
+ harness.changeStart$.next({ objects: new Map([[oKey, startObject]]) });
+
+ expect(harness.commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, [
+ { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a' },
+ ]);
+
+ const endObject = { ...startObject, left: 5 };
+ harness.changeEnd$.next({ objects: new Map([[oKey, endObject]]) });
+
+ expect(harness.drawingManagerService.featurePluginUpdateNotification).toHaveBeenCalledWith([
+ expect.objectContaining({ drawingId: 'drawing-a', transform: expect.objectContaining({ left: 5 }) }),
+ ]);
+
+ harness.controller.dispose();
+ });
+
+ it('applies drawing alignment changes for focused drawings', () => {
+ const harness = createHarness();
+
+ harness.add$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-a' }]);
+
+ harness.commandExecuted()?.({ id: SetDrawingAlignOperation.id, params: { alignType: AlignType.left } });
+
+ expect(harness.drawingManagerService.featurePluginUpdateNotification).toHaveBeenCalledWith([
+ expect.objectContaining({ drawingId: 'drawing-b', transform: { left: 0, top: 0 } }),
+ ]);
+
+ harness.controller.dispose();
+ });
+
+ it('updates zIndex, transforms, visibility, and disposes removed shapes', () => {
+ const harness = createHarness();
+
+ harness.order$.next({ unitId: 'unit-1', subUnitId: 'sheet-1', drawingIds: ['drawing-z'] });
+ expect(harness.zIndexShape.setProps).toHaveBeenCalledWith({ zIndex: 0 });
+ expect(harness.zIndexShape.makeDirty).toHaveBeenCalledTimes(1);
+
+ const drawingId = 'drawing-transform';
+ harness.update$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId }]);
+ expect(harness.transformShape.transformByState).toHaveBeenCalled();
+ expect(harness.debounceRefreshControls).toHaveBeenCalledTimes(1);
+
+ harness.refreshTransform$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId }]);
+ expect(harness.transformShape.transformByState).toHaveBeenCalledTimes(2);
+
+ harness.visible$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-visible', visible: false }]);
+ expect(harness.showHideShape.hide).toHaveBeenCalledTimes(1);
+
+ harness.visible$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-visible', visible: true }]);
+ expect(harness.showHideShape.show).toHaveBeenCalledTimes(1);
+
+ harness.remove$.next([{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-remove' }]);
+ expect(harness.disposeShape.dispose).toHaveBeenCalledTimes(1);
+
+ harness.controller.dispose();
+ });
+});
diff --git a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts
new file mode 100644
index 0000000000..5d6a1c37e1
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts
@@ -0,0 +1,200 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo } from '@univerjs/core';
+import { DrawingTypeEnum } from '@univerjs/core';
+import { MessageType } from '@univerjs/design';
+import { getDrawingShapeKeyByDrawingSearch, SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { ImageCropperObject } from '@univerjs/drawing-ui';
+import { CURSOR_TYPE, Image } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { AutoImageCropOperation, CloseImageCropOperation, CropType, OpenImageCropOperation } from '../../commands/operations/image-crop.operation';
+import { ImageCropperController } from '../image-cropper.controller';
+
+function createImage(id: string) {
+ const img = document.createElement('img');
+ Object.defineProperty(img, 'width', { value: 100, configurable: true });
+ Object.defineProperty(img, 'height', { value: 50, configurable: true });
+ return new Image(id, { image: img });
+}
+
+describe('ImageCropperController', () => {
+ it('auto crops focused image and opens crop panel', () => {
+ const focusDrawing = { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' };
+
+ const imageKey = getDrawingShapeKeyByDrawingSearch(focusDrawing);
+ const image = createImage(imageKey);
+ image.transformByState({ left: 0, top: 0, width: 100, height: 50, angle: 0 });
+
+ const existingCropper = new ImageCropperObject(`${imageKey}-crop`, { applyTransform: image.getState() });
+
+ const commandHandlers: Array<(cmd: ICommandInfo) => void> = [];
+ const commandService = {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ executeCommand: vi.fn(),
+ syncExecuteCommand: vi.fn(),
+ };
+
+ const drawingManagerService = {
+ getFocusDrawings: vi.fn(() => [focusDrawing]),
+ getDrawingByParam: vi.fn(() => ({ drawingType: DrawingTypeEnum.DRAWING_IMAGE })),
+ };
+
+ const transformer = {
+ changeStart$: new Subject(),
+ changeEnd$: new Subject(),
+ clearControl$: new Subject(),
+ clearCopperControl: vi.fn(),
+ createControlForCopper: vi.fn(),
+ };
+
+ const scene = {
+ getAllObjectsByOrder: vi.fn(() => [existingCropper]),
+ getObject: vi.fn(() => image),
+ getTransformerByCreate: vi.fn(() => transformer),
+ };
+ const renderManagerService = { getRenderById: vi.fn(() => ({ scene })) };
+
+ const controller = new ImageCropperController(
+ commandService as never,
+ drawingManagerService as never,
+ renderManagerService as never,
+ { getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn() } as never,
+ { show: vi.fn() } as never,
+ { t: vi.fn((key: string) => key) } as never
+ );
+
+ // handlers: [OpenImageCrop, CloseImageCrop, AutoImageCrop]
+ commandHandlers[2]({ id: AutoImageCropOperation.id, params: { cropType: CropType.R1_1 } } as never);
+
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(CloseImageCropOperation.id, { isAuto: true });
+ expect(image.srcRect).toEqual({ left: 25, top: 0, right: 25, bottom: 0 });
+ expect(commandService.executeCommand).toHaveBeenCalledWith(OpenImageCropOperation.id, focusDrawing);
+
+ controller.dispose();
+ });
+
+ it('shows error message when auto crop target is not an Image', () => {
+ const commandHandlers: Array<(cmd: ICommandInfo) => void> = [];
+ const messageService = { show: vi.fn() };
+ const commandService = {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ executeCommand: vi.fn(),
+ syncExecuteCommand: vi.fn(),
+ };
+
+ const drawingManagerService = {
+ getFocusDrawings: vi.fn(() => [{ unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' }]),
+ getDrawingByParam: vi.fn(() => ({ drawingType: DrawingTypeEnum.DRAWING_IMAGE })),
+ };
+
+ const scene = {
+ getAllObjectsByOrder: vi.fn(() => []),
+ getObject: vi.fn(() => ({ not: 'image' })),
+ getTransformerByCreate: vi.fn(() => ({ changeStart$: new Subject(), changeEnd$: new Subject(), clearControl$: new Subject() })),
+ };
+ const renderManagerService = { getRenderById: vi.fn(() => ({ scene })) };
+
+ const controller = new ImageCropperController(
+ commandService as never,
+ drawingManagerService as never,
+ renderManagerService as never,
+ { getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn() } as never,
+ messageService as never,
+ { t: vi.fn((key: string) => key) } as never
+ );
+
+ commandHandlers[2]({ id: AutoImageCropOperation.id, params: { cropType: CropType.R1_1 } } as never);
+
+ expect(messageService.show).toHaveBeenCalledWith(expect.objectContaining({
+ type: MessageType.Error,
+ }));
+
+ controller.dispose();
+ });
+
+ it('opens crop mode for image and applies hover cursor changes', () => {
+ const focusDrawing = { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' };
+ const imageKey = getDrawingShapeKeyByDrawingSearch(focusDrawing);
+ const image = createImage(imageKey);
+ image.transformByState({ left: 0, top: 0, width: 100, height: 50, angle: 0 });
+
+ const commandHandlers: Array<(cmd: ICommandInfo) => void> = [];
+ const commandService = {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandlers.push(handler);
+ return { dispose: vi.fn() };
+ }),
+ executeCommand: vi.fn(),
+ syncExecuteCommand: vi.fn(),
+ };
+
+ const drawingManagerService = {
+ getDrawingByParam: vi.fn(() => ({ drawingType: DrawingTypeEnum.DRAWING_IMAGE, srcRect: null, prstGeom: null })),
+ };
+
+ const transformer = {
+ clearControls: vi.fn(),
+ refreshControls: vi.fn(),
+ clearCopperControl: vi.fn(),
+ createControlForCopper: vi.fn(),
+ changeStart$: new Subject(),
+ changeEnd$: new Subject(),
+ clearControl$: new Subject(),
+ };
+
+ let createdCropper: ImageCropperObject | null = null;
+ const scene = {
+ getAllObjectsByOrder: vi.fn(() => createdCropper ? [createdCropper] : []),
+ getObject: vi.fn(() => image),
+ getTransformerByCreate: vi.fn(() => transformer),
+ getTransformer: vi.fn(() => transformer),
+ addObject: vi.fn((obj: any) => {
+ createdCropper = obj;
+ return { attachTransformerTo: vi.fn() };
+ }),
+ };
+ const renderManagerService = { getRenderById: vi.fn(() => ({ scene })) };
+
+ const controller = new ImageCropperController(
+ commandService as never,
+ drawingManagerService as never,
+ renderManagerService as never,
+ { getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn() } as never,
+ { show: vi.fn() } as never,
+ { t: vi.fn((key: string) => key) } as never
+ );
+
+ // OpenImageCrop handler
+ commandHandlers[0]({ id: OpenImageCropOperation.id, params: focusDrawing } as never);
+
+ expect(createdCropper).not.toBeNull();
+ createdCropper!.onPointerEnter$.emitEvent({} as never);
+ expect(createdCropper!.cursor).toBe(CURSOR_TYPE.MOVE);
+ createdCropper!.onPointerLeave$.emitEvent({} as never);
+ expect(createdCropper!.cursor).toBe(CURSOR_TYPE.DEFAULT);
+
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, [focusDrawing]);
+ controller.dispose();
+ });
+});
diff --git a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
new file mode 100644
index 0000000000..c025e6db6c
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
@@ -0,0 +1,144 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';
+import { SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ImageResetSizeOperation } from '../../commands/operations/image-reset-size.operation';
+import { ImageUpdateController } from '../image-update.controller';
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+function createSheetUnit(unitId = 'book-1', subUnitId = 'sheet-1') {
+ return {
+ type: UniverInstanceType.UNIVER_SHEET,
+ getUnitId: () => unitId,
+ getActiveSheet: () => ({ getSheetId: () => subUnitId }),
+ };
+}
+
+describe('ImageUpdateController', () => {
+ it('resets image size after command execution and pushes updated drawing state back', () => {
+ let commandHandler: ((command: { id: string; params?: unknown }) => void) | undefined;
+ const changeNotification = vi.fn();
+ const imageShape = {
+ resetSize: vi.fn(),
+ getNativeSize: vi.fn(() => ({ width: 320, height: 180 })),
+ };
+ const params = [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-1' }];
+ const drawingManagerService = {
+ add$: new Subject(),
+ update$: new Subject(),
+ getDrawingByParam: vi.fn(() => ({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'shape-1',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: { width: 100, height: 50, angle: 30 },
+ })),
+ featurePluginUpdateNotification: vi.fn(),
+ };
+ const commandService = {
+ onCommandExecuted: vi.fn((handler) => {
+ commandHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ syncExecuteCommand: vi.fn(),
+ };
+
+ const controller = new ImageUpdateController(
+ commandService as never,
+ {
+ getRenderById: vi.fn(() => ({
+ scene: {
+ getObject: vi.fn(() => imageShape),
+ getTransformerByCreate: vi.fn(() => ({
+ refreshControls: vi.fn(() => ({ changeNotification })),
+ })),
+ },
+ })),
+ } as never,
+ drawingManagerService as never,
+ {} as never,
+ {} as never,
+ { getUnit: vi.fn(() => createSheetUnit()), getFocusedUnit: vi.fn(() => createSheetUnit()) } as never,
+ { renderImages: vi.fn() } as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ commandHandler!({ id: ImageResetSizeOperation.id, params });
+
+ expect(imageShape.resetSize).toHaveBeenCalledTimes(1);
+ expect(drawingManagerService.featurePluginUpdateNotification).toHaveBeenCalledWith([
+ expect.objectContaining({
+ drawingId: 'shape-1',
+ srcRect: null,
+ prstGeom: null,
+ transform: expect.objectContaining({ width: 320, height: 180, angle: 0 }),
+ }),
+ ]);
+ expect(changeNotification).toHaveBeenCalledTimes(1);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, params);
+ });
+
+ it('deduplicates add notifications before rendering newly inserted images', async () => {
+ vi.useFakeTimers();
+ const add$ = new Subject<Array<{ unitId: string; subUnitId: string; drawingId: string }>>();
+ const update$ = new Subject();
+ const imageParam = {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'shape-2',
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ transform: { width: 100, height: 50, angle: 0 },
+ };
+ const drawingManagerService = {
+ add$,
+ update$,
+ getDrawingByParam: vi.fn(() => imageParam),
+ refreshTransform: vi.fn(),
+ };
+ const renderImages = vi.fn(async () => []);
+
+ const controller = new ImageUpdateController(
+ { onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })), syncExecuteCommand: vi.fn() } as never,
+ {
+ getRenderById: vi.fn(() => ({
+ scene: { getTransformerByCreate: vi.fn(), getObject: vi.fn() },
+ })),
+ } as never,
+ drawingManagerService as never,
+ {} as never,
+ {} as never,
+ { getUnit: vi.fn(() => createSheetUnit()), getFocusedUnit: vi.fn(() => createSheetUnit()) } as never,
+ { renderImages } as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ const duplicated = { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-2' };
+ add$.next([duplicated]);
+ add$.next([duplicated]);
+ await vi.advanceTimersByTimeAsync(40);
+
+ expect(renderImages).toHaveBeenCalledTimes(1);
+ expect(drawingManagerService.refreshTransform).toHaveBeenCalledWith([imageParam]);
+ });
+});
diff --git a/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts b/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..434cd45fc3
--- /dev/null
+++ b/packages/drawing-ui/src/controllers/__tests__/utils.spec.ts
@@ -0,0 +1,151 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { UniverInstanceType } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import { DrawingGroupObject, Group } from '@univerjs/engine-render';
+import { describe, expect, it, vi } from 'vitest';
+import { getCurrentUnitInfo, insertGroupObject } from '../utils';
+
+const { MockGroup } = vi.hoisted(() => {
+ class HoistedMockGroup {
+ oKey: string;
+ private _objects: Array<{ oKey: string }> = [];
+ setBaseBound = vi.fn();
+ transformByState = vi.fn();
+
+ constructor(oKey: string) {
+ this.oKey = oKey;
+ }
+
+ getObjects() {
+ return this._objects;
+ }
+
+ addObject(object: { oKey: string }) {
+ this._objects.push(object);
+ }
+ }
+
+ return {
+ MockGroup: HoistedMockGroup,
+ };
+});
+
+vi.mock('@univerjs/drawing', () => ({
+ getDrawingShapeKeyByDrawingSearch: vi.fn(({ drawingId }) => `group-${drawingId}`),
+}));
+
+vi.mock('@univerjs/engine-render', () => ({
+ DRAWING_OBJECT_LAYER_INDEX: 99,
+ Group: MockGroup,
+ DrawingGroupObject: MockGroup,
+}));
+
+describe('drawing controller utils', () => {
+ it('creates a new drawing group, attaches it to the scene, and avoids duplicate children', () => {
+ const object = { oKey: 'child-1' };
+ const attachTransformerTo = vi.fn();
+ const scene = {
+ objects: new Map<string, InstanceType<typeof MockGroup> | { oKey: string }>(),
+ getObject(key: string) {
+ return this.objects.get(key) ?? null;
+ },
+ addObject(group: InstanceType<typeof MockGroup>) {
+ this.objects.set(group.oKey, group);
+ return {
+ attachTransformerTo,
+ };
+ },
+ };
+ const drawingManagerService = {
+ getDrawingByParam: vi.fn(() => ({
+ transform: { left: 10, top: 20, width: 30, height: 40, angle: 15 },
+ groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },
+ })),
+ };
+
+ insertGroupObject({ drawingId: 'group-1' } as never, object as never, scene as never, drawingManagerService as never);
+
+ const group = scene.getObject('group-group-1') as InstanceType<typeof MockGroup>;
+ expect(getDrawingShapeKeyByDrawingSearch).toHaveBeenCalledWith({ drawingId: 'group-1' });
+ expect(group).toBeInstanceOf(DrawingGroupObject as unknown as typeof MockGroup);
+ expect(group.getObjects()).toEqual([object]);
+ expect(group.setBaseBound).toHaveBeenCalledWith({ left: 1, top: 2, width: 3, height: 4 });
+ expect(group.transformByState).toHaveBeenCalledWith({ left: 10, top: 20, width: 30, height: 40, angle: 15 });
+ expect(attachTransformerTo).toHaveBeenCalledWith(group);
+
+ insertGroupObject({ drawingId: 'group-1' } as never, object as never, scene as never, drawingManagerService as never);
+ expect(group.getObjects()).toEqual([object]);
+ });
+
+ it('skips invalid group targets and resolves current unit info for sheet, doc, and slide', () => {
+ const scene = {
+ getObject: vi.fn(() => ({ oKey: 'not-a-group' })),
+ };
+ const drawingManagerService = {
+ getDrawingByParam: vi.fn(() => ({ transform: { left: 0, top: 0, width: 10, height: 10 } })),
+ };
+
+ insertGroupObject({ drawingId: 'group-2' } as never, { oKey: 'child-2' } as never, scene as never, drawingManagerService as never);
+ expect(scene.getObject).toHaveBeenCalled();
+
+ const sheet = {
+ type: UniverInstanceType.UNIVER_SHEET,
+ getUnitId: () => 'workbook-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ };
+ const doc = {
+ type: UniverInstanceType.UNIVER_DOC,
+ getUnitId: () => 'doc-1',
+ };
+ const slide = {
+ type: UniverInstanceType.UNIVER_SLIDE,
+ getUnitId: () => 'slide-1',
+ };
+ const currentUniverService = {
+ getFocusedUnit: vi.fn()
+ .mockReturnValueOnce(sheet)
+ .mockReturnValueOnce(doc)
+ .mockReturnValueOnce(slide)
+ .mockReturnValueOnce(null),
+ getUnit: vi.fn(() => sheet),
+ };
+
+ expect(getCurrentUnitInfo(currentUniverService as never)).toEqual({
+ unitId: 'workbook-1',
+ subUnitId: 'sheet-1',
+ current: sheet,
+ });
+ expect(getCurrentUnitInfo(currentUniverService as never)).toEqual({
+ unitId: 'doc-1',
+ subUnitId: 'doc-1',
+ current: doc,
+ });
+ expect(getCurrentUnitInfo(currentUniverService as never)).toEqual({
+ unitId: 'slide-1',
+ subUnitId: 'slide-1',
+ current: slide,
+ });
+ expect(getCurrentUnitInfo(currentUniverService as never)).toBeUndefined();
+ expect(getCurrentUnitInfo(currentUniverService as never, 'workbook-1')).toEqual({
+ unitId: 'workbook-1',
+ subUnitId: 'sheet-1',
+ current: sheet,
+ });
+ expect(Group).toBeDefined();
+ });
+});
diff --git a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts
new file mode 100644
index 0000000000..8ba48946e7
--- /dev/null
+++ b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts
@@ -0,0 +1,126 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DrawingTypeEnum, UniverInstanceType } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch, ImageSourceType } from '@univerjs/drawing';
+import { describe, expect, it, vi } from 'vitest';
+import { DrawingRenderService } from '../drawing-render.service';
+
+vi.mock('@univerjs/drawing', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/drawing')>();
+ return {
+ ...actual,
+ getDrawingShapeKeyByDrawingSearch: vi.fn(() => 'shape-key'),
+ };
+});
+
+function createService(options?: { unitType?: UniverInstanceType; visible?: boolean; activeSheetId?: string }) {
+ const drawingManagerService = {
+ getDrawingVisible: vi.fn(() => options?.visible ?? true),
+ getDrawingEditable: vi.fn(() => true),
+ getDrawingOrder: vi.fn(() => ['drawing-1']),
+ };
+ const imageIoService = {
+ getImageSourceCache: vi.fn(),
+ getImage: vi.fn(),
+ addImageSourceCache: vi.fn(),
+ };
+ const urlImageService = {
+ getImage: vi.fn(),
+ };
+ const univerInstanceService = {
+ getUnitType: vi.fn(() => options?.unitType ?? UniverInstanceType.UNIVER_DOC),
+ getCurrentUnitOfType: vi.fn(() => ({
+ getActiveSheet: vi.fn(() => ({ getSheetId: vi.fn(() => options?.activeSheetId ?? 'sheet-1') })),
+ })),
+ };
+ const scene = {
+ getObject: vi.fn(() => null),
+ addObject: vi.fn(),
+ attachTransformerTo: vi.fn(),
+ };
+
+ return {
+ drawingManagerService,
+ imageIoService,
+ scene,
+ service: new DrawingRenderService(
+ drawingManagerService as never,
+ imageIoService as never,
+ {} as never,
+ urlImageService as never,
+ univerInstanceService as never
+ ),
+ univerInstanceService,
+ };
+}
+
+const baseImageParam = {
+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,
+ drawingId: 'drawing-1',
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ source: 'image-source',
+ imageSourceType: ImageSourceType.BASE64,
+ transform: { left: 10, top: 20, width: 30, height: 40, angle: 0, flipX: false, flipY: false, skewX: 0, skewY: 0 },
+};
+
+describe('DrawingRenderService', () => {
+ it('skips rendering when the drawing is not visible, not an image, on another sheet, or missing transform', async () => {
+ const hiddenCase = createService({ visible: false });
+ expect(await hiddenCase.service.renderImages(baseImageParam as never, hiddenCase.scene as never)).toBeUndefined();
+ expect(hiddenCase.scene.getObject).not.toHaveBeenCalled();
+
+ const nonImageCase = createService();
+ expect(await nonImageCase.service.renderImages({ ...baseImageParam, drawingType: DrawingTypeEnum.DRAWING_SHAPE } as never, nonImageCase.scene as never)).toBeUndefined();
+ expect(nonImageCase.scene.getObject).not.toHaveBeenCalled();
+
+ const inactiveSheetCase = createService({ unitType: UniverInstanceType.UNIVER_SHEET, activeSheetId: 'sheet-2' });
+ expect(await inactiveSheetCase.service.renderImages(baseImageParam as never, inactiveSheetCase.scene as never)).toBeUndefined();
+ expect(inactiveSheetCase.scene.getObject).not.toHaveBeenCalled();
+
+ const noTransformCase = createService();
+ expect(await noTransformCase.service.renderImages({ ...baseImageParam, transform: null } as never, noTransformCase.scene as never)).toBeUndefined();
+ expect(noTransformCase.scene.getObject).not.toHaveBeenCalled();
+ });
+
+ it('updates existing scene objects instead of recreating them', async () => {
+ const { scene, service } = createService();
+ const transformByState = vi.fn();
+ scene.getObject.mockReturnValue({ transformByState } as never);
+
+ const result = await service.renderImages(baseImageParam as never, scene as never);
+
+ expect(vi.mocked(getDrawingShapeKeyByDrawingSearch)).toHaveBeenCalledWith({
+ drawingId: 'drawing-1',
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ }, undefined);
+ expect(transformByState).toHaveBeenCalledWith({
+ left: 10,
+ top: 20,
+ width: 30,
+ height: 40,
+ angle: 0,
+ flipX: false,
+ flipY: false,
+ skewX: 0,
+ skewY: 0,
+ });
+ expect(scene.addObject).not.toHaveBeenCalled();
+ expect(result).toEqual([]);
+ });
+});
diff --git a/packages/engine-render/src/__tests__/drawing-group.spec.ts b/packages/engine-render/src/__tests__/drawing-group.spec.ts
new file mode 100644
index 0000000000..1566047f88
--- /dev/null
+++ b/packages/engine-render/src/__tests__/drawing-group.spec.ts
@@ -0,0 +1,283 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { CURSOR_TYPE, RENDER_CLASS_TYPE } from '../basics/const';
+import { Vector2 } from '../basics/vector2';
+import { DrawingGroupObject } from '../drawing-group';
+import { Group } from '../group';
+import { Rect } from '../shape/rect';
+
+function createContext() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ transform: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ rect: vi.fn(),
+ arc: vi.fn(),
+ translate: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ setLineDash: vi.fn(),
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 1,
+ lineCap: 'round',
+ lineDashOffset: 0,
+ lineJoin: 'round',
+ miterLimit: 0,
+ } as any;
+}
+
+function createSceneStub(objectMap: Record<string, Rect | undefined>) {
+ return {
+ classType: RENDER_CLASS_TYPE.SCENE,
+ getParent: () => null,
+ getObject: (key: string) => objectMap[key],
+ removeObject: vi.fn(),
+ setCursor: vi.fn(),
+ } as any;
+}
+
+describe('drawing group', () => {
+ it('handles base bound/ancestor transform and child hit detection', () => {
+ const parentGroup = new Group('parent');
+ parentGroup.transformByState({
+ left: 5,
+ top: 8,
+ width: 200,
+ height: 120,
+ });
+
+ const drawingGroup = new DrawingGroupObject('drawing-group');
+ drawingGroup.transformByState({
+ left: 20,
+ top: 30,
+ width: 120,
+ height: 80,
+ });
+ drawingGroup.setBaseBound({
+ left: 10,
+ top: 12,
+ width: 100,
+ height: 60,
+ });
+ expect(drawingGroup.getBaseBound()).toEqual({
+ left: 10,
+ top: 12,
+ width: 100,
+ height: 60,
+ });
+
+ const child = new Rect('child', {
+ left: 0,
+ top: 0,
+ width: 20,
+ height: 20,
+ fill: '#333333',
+ });
+ vi.spyOn(child, 'isHit').mockReturnValue(true);
+ vi.spyOn(child, 'render').mockImplementation(() => child);
+
+ drawingGroup.addObjects(child);
+ parentGroup.addObject(drawingGroup);
+
+ const ancestor = drawingGroup.ancestorTransform.getMatrix();
+ expect(ancestor).toHaveLength(6);
+ expect(ancestor[4]).toBeTypeOf('number');
+ expect(ancestor[5]).toBeTypeOf('number');
+
+ expect(drawingGroup.isHit(Vector2.FromArray([40, 50]))).toBe(true);
+ expect(drawingGroup.isHit(Vector2.FromArray([1000, 1000]))).toBe(false);
+ });
+
+ it('renders children with group-centered transform', () => {
+ const drawingGroup = new DrawingGroupObject('drawing-group-render');
+ drawingGroup.transformByState({
+ left: 10,
+ top: 10,
+ width: 100,
+ height: 60,
+ });
+ const child = new Rect('render-child', {
+ left: 0,
+ top: 0,
+ width: 10,
+ height: 10,
+ fill: '#666666',
+ });
+ const childRenderSpy = vi.spyOn(child, 'render').mockImplementation(() => child);
+ drawingGroup.addObject(child);
+
+ const ctx = createContext();
+ drawingGroup.render(ctx, {
+ cacheBound: { left: 0, top: 0, right: 500, bottom: 500 },
+ } as any);
+
+ expect(ctx.transform).toHaveBeenCalled();
+ expect(childRenderSpy).toHaveBeenCalled();
+ });
+
+ it('covers group object management, transform recalculation and dispose flow', () => {
+ const sceneChild = new Rect('scene-child', {
+ left: 5,
+ top: 8,
+ width: 20,
+ height: 16,
+ fill: '#224466',
+ });
+ sceneChild.zIndex = 1;
+
+ const directChild = new Rect('direct-child', {
+ left: 40,
+ top: 25,
+ width: 10,
+ height: 10,
+ fill: '#446622',
+ });
+ directChild.zIndex = 5;
+
+ const hiddenChild = new Rect('hidden-child', {
+ left: 2,
+ top: 3,
+ width: 8,
+ height: 8,
+ fill: '#663344',
+ });
+ hiddenChild.hide();
+
+ const nestedGroup = new Group('nested-group', new Rect('nested-rect', {
+ left: 1,
+ top: 1,
+ width: 4,
+ height: 4,
+ fill: '#111111',
+ }));
+ nestedGroup.transformByState({
+ left: 30,
+ top: 12,
+ width: 18,
+ height: 10,
+ });
+
+ const scene = createSceneStub({
+ 'scene-child': sceneChild,
+ });
+ const group = new Group('group-ops');
+ group.parent = scene;
+ group.transformByState({
+ left: 10,
+ top: 6,
+ });
+
+ group.addObject('scene-child');
+ group.addObject(directChild);
+ group.addObject(hiddenChild);
+ group.addObject(nestedGroup);
+ group.addObject('missing-child');
+
+ expect(group.getObjects().length).toBe(4);
+ expect(sceneChild.parent).toBe(group);
+ expect(sceneChild.isInGroup).toBe(true);
+ expect(sceneChild.groupKey).toBe(group.oKey);
+ expect(group.maxZIndex).toBe(5);
+
+ const visibleObjects = group.getObjectsByOrder();
+ expect(visibleObjects).not.toContain(hiddenChild);
+ expect(visibleObjects).toContain(directChild);
+
+ group.cursor = CURSOR_TYPE.POINTER;
+ expect(scene.setCursor).toHaveBeenCalledWith(CURSOR_TYPE.POINTER);
+
+ const preWidth = directChild.width;
+ const preHeight = directChild.height;
+ group.width = group.width + 6;
+ group.height = group.height + 4;
+ expect(directChild.width).toBeCloseTo(preWidth + 6, 6);
+ expect(directChild.height).toBeCloseTo(preHeight + 4, 6);
+
+ const directTransformSpy = vi.spyOn(directChild, 'transformByState');
+ group.openSelfSizeMode();
+ group.width = 33;
+ group.height = 21;
+ expect(group.width).toBe(33);
+ expect(group.height).toBe(21);
+ group.reCalculateObjects();
+ expect(directTransformSpy).not.toHaveBeenCalled();
+ group.closeSelfSizeMode();
+
+ group.reCalculateObjects();
+ expect(directTransformSpy).toHaveBeenCalled();
+
+ const detachedRect = new Rect('detached-rect', {
+ left: 4,
+ top: 4,
+ width: 6,
+ height: 6,
+ fill: '#333333',
+ });
+ const detachedGroup = new Group('detached-group', new Rect('nested-2', {
+ left: 0,
+ top: 0,
+ width: 2,
+ height: 2,
+ fill: '#999999',
+ }));
+ group.addObject(detachedRect);
+ group.addObject(detachedGroup);
+
+ const detachedRectTransformSpy = vi.spyOn(detachedRect, 'transformByState');
+ const detachedGroupTransformSpy = vi.spyOn(detachedGroup, 'transformByState');
+ group.removeSelfObjectAndTransform(detachedRect.oKey, undefined, undefined, true);
+ group.removeSelfObjectAndTransform(detachedGroup.oKey, undefined, undefined, true);
+ expect(detachedRectTransformSpy).toHaveBeenCalled();
+ expect(detachedGroupTransformSpy).toHaveBeenCalledWith(expect.objectContaining({
+ left: expect.any(Number),
+ top: expect.any(Number),
+ }));
+ expect(detachedRect.parent).toBe(scene);
+ expect(detachedRect.isInGroup).toBe(false);
+
+ group.removeObject('scene-child');
+ group.removeObject(hiddenChild);
+ expect(scene.removeObject).toHaveBeenCalled();
+
+ const renderTarget = new Rect('render-target', {
+ left: 0,
+ top: 0,
+ width: 10,
+ height: 10,
+ fill: '#555555',
+ });
+ const renderSpy = vi.spyOn(renderTarget, 'render').mockImplementation(() => renderTarget);
+ group.addObject(renderTarget);
+
+ const ctx = createContext();
+ group.render(ctx, {
+ cacheBound: { left: -50, top: -50, right: 200, bottom: 200 },
+ } as any);
+ expect(ctx.transform).toHaveBeenCalled();
+ expect(renderSpy).toHaveBeenCalled();
+
+ const disposeSpy = vi.spyOn(renderTarget, 'dispose');
+ group.dispose();
+ expect(disposeSpy).toHaveBeenCalled();
+ });
+});
diff --git a/packages/engine-render/src/__tests__/scene-viewer.spec.ts b/packages/engine-render/src/__tests__/scene-viewer.spec.ts
new file mode 100644
index 0000000000..4d6977bce1
--- /dev/null
+++ b/packages/engine-render/src/__tests__/scene-viewer.spec.ts
@@ -0,0 +1,127 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 } from 'vitest';
+import { Vector2 } from '../basics/vector2';
+import { Canvas } from '../canvas';
+import { Engine } from '../engine';
+import { MAIN_VIEW_PORT_KEY, Scene } from '../scene';
+import { SceneViewer } from '../scene-viewer';
+import { Rect } from '../shape/rect';
+import { Viewport } from '../viewport';
+import { setupRenderTestEnv } from './render-test-utils';
+
+function createSubScene(engine: Engine, key: string) {
+ const scene = new Scene(key, engine);
+ scene.transformByState({
+ width: 600,
+ height: 320,
+ scaleX: 1,
+ scaleY: 1,
+ });
+ new Viewport(MAIN_VIEW_PORT_KEY, scene, {
+ left: 0,
+ top: 0,
+ width: 420,
+ height: 220,
+ active: true,
+ allowCache: true,
+ bufferEdgeX: 8,
+ bufferEdgeY: 6,
+ });
+ scene.addObject(new Rect(`${key}-rect`, {
+ left: 12,
+ top: 16,
+ width: 120,
+ height: 60,
+ fill: '#66aa88',
+ stroke: '#222222',
+ }), 1);
+ return scene;
+}
+
+describe('scene viewer', () => {
+ let restoreEnv: () => void;
+ let container: HTMLDivElement;
+ let engine: Engine;
+ let mainCanvas: Canvas;
+
+ beforeEach(() => {
+ restoreEnv = setupRenderTestEnv().restore;
+ container = document.createElement('div');
+ container.style.width = '720px';
+ container.style.height = '420px';
+ document.body.appendChild(container);
+ engine = new Engine('scene-viewer-engine', { elementWidth: 700, elementHeight: 400, dpr: 1 });
+ engine.mount(container, false);
+ mainCanvas = new Canvas({ width: 720, height: 420, pixelRatio: 1 });
+ });
+
+ afterEach(() => {
+ mainCanvas.dispose();
+ engine.dispose();
+ restoreEnv();
+ container.remove();
+ document.body.innerHTML = '';
+ });
+
+ it('manages sub-scenes, render bounds and pick lifecycle', () => {
+ const sceneA = createSubScene(engine, 'sub-a');
+ const sceneB = createSubScene(engine, 'sub-b');
+
+ const viewer = new SceneViewer('viewer', {
+ left: 20,
+ top: 10,
+ width: 420,
+ height: 220,
+ });
+ viewer.addSubScene(sceneA);
+ viewer.addSubScene(sceneB);
+ expect(viewer.getSubScenes().size).toBe(2);
+
+ viewer.activeSubScene('sub-a');
+ expect(viewer.getActiveSubScene()?.sceneKey).toBe('sub-a');
+ expect(viewer.getSubScene('sub-b')?.sceneKey).toBe('sub-b');
+
+ viewer.enableSelectedClipElement();
+ expect(viewer.allowSelectedClipElement()).toBe(true);
+ viewer.disableSelectedClipElement();
+ expect(viewer.allowSelectedClipElement()).toBe(false);
+
+ const ctx = mainCanvas.getContext();
+ const outsideBounds = {
+ viewBound: { left: 1000, top: 1000, right: 1200, bottom: 1200 },
+ cacheBound: { left: 1000, top: 1000, right: 1200, bottom: 1200 },
+ } as any;
+ const insideBounds = {
+ viewBound: { left: 0, top: 0, right: 500, bottom: 300 },
+ cacheBound: { left: 0, top: 0, right: 500, bottom: 300 },
+ } as any;
+
+ expect(viewer.render(ctx, outsideBounds)).toBe(viewer);
+ expect(viewer.render(ctx, insideBounds)).toBe(viewer);
+
+ const picked = viewer.pick(Vector2.FromArray([60, 50]));
+ expect(picked).toBeTruthy();
+
+ viewer.removeSubScene('sub-a');
+ expect(viewer.getSubScenes().size).toBe(1);
+ expect(viewer.getActiveSubScene()?.sceneKey).toBe('sub-b');
+
+ viewer.activeSubScene(null);
+ viewer.dispose();
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/document-node-tools.spec.ts b/packages/engine-render/src/basics/__tests__/document-node-tools.spec.ts
new file mode 100644
index 0000000000..ec1c272715
--- /dev/null
+++ b/packages/engine-render/src/basics/__tests__/document-node-tools.spec.ts
@@ -0,0 +1,107 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DataStreamTreeTokenType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import {
+ getParagraphByGlyph,
+ hasListGlyph,
+ isFirstGlyph,
+ isIndentByGlyph,
+ isLastGlyph,
+ isPlaceholderOrSpace,
+ isSameLine,
+} from '../document-node-tools';
+import { GlyphType } from '../i-document-skeleton-cached';
+
+function createGlyphLine() {
+ const list = { glyphType: GlyphType.LIST, content: '•' } as any;
+ const g1 = { glyphType: GlyphType.WORD, content: 'A' } as any;
+ const g2 = { glyphType: GlyphType.WORD, content: 'B' } as any;
+
+ const divide = {
+ glyphGroup: [list, g1, g2],
+ } as any;
+ const line = {
+ divides: [divide],
+ paragraphIndex: 5,
+ } as any;
+
+ list.parent = divide;
+ g1.parent = divide;
+ g2.parent = divide;
+ divide.parent = line;
+
+ return { list, g1, g2, divide, line };
+}
+
+describe('document node tools', () => {
+ it('detects list/first/last glyphs and same-line relations', () => {
+ const { list, g1, g2, divide, line } = createGlyphLine();
+ expect(hasListGlyph(g1)).toBe(true);
+ expect(hasListGlyph(null)).toBe(false);
+
+ expect(isFirstGlyph(list)).toBe(true);
+ expect(isFirstGlyph(g1)).toBe(true);
+ expect(isFirstGlyph(g2)).toBe(false);
+
+ expect(isLastGlyph(g2)).toBe(true);
+ expect(isLastGlyph(g1)).toBe(false);
+ expect(isLastGlyph(null)).toBe(false);
+
+ const line2 = { divides: [divide], paragraphIndex: 7 } as any;
+ const g3 = { glyphType: GlyphType.WORD, content: 'C', parent: { parent: line2 } } as any;
+
+ expect(isSameLine(g1, g2)).toBe(true);
+ expect(isSameLine(g1, g3)).toBe(false);
+ expect(isSameLine(null, g3)).toBe(false);
+ });
+
+ it('resolves paragraph context and placeholder/space states', () => {
+ const { g1, line } = createGlyphLine();
+ const body = {
+ paragraphs: [
+ { startIndex: 2, paragraphStyle: {} },
+ { startIndex: 5, paragraphStyle: { indentStart: { v: 2 } } },
+ ],
+ } as any;
+
+ const paragraph = getParagraphByGlyph(g1, body);
+ expect(paragraph).toEqual(expect.objectContaining({
+ startIndex: 5,
+ paragraphStart: 3,
+ paragraphEnd: 5,
+ }));
+ expect(isIndentByGlyph(g1, body)).toBe(true);
+
+ line.paragraphIndex = 99;
+ expect(getParagraphByGlyph(g1, body)).toBeUndefined();
+ expect(isIndentByGlyph(g1, body)).toBe(false);
+
+ const placeholder = { streamType: DataStreamTreeTokenType.PARAGRAPH, content: '' } as any;
+ const tab = { streamType: DataStreamTreeTokenType.TAB, content: '' } as any;
+ const sectionBreak = { streamType: DataStreamTreeTokenType.SECTION_BREAK, content: '' } as any;
+ const space = { streamType: '', content: DataStreamTreeTokenType.SPACE } as any;
+ const text = { streamType: '', content: 'x' } as any;
+
+ expect(isPlaceholderOrSpace(placeholder)).toBe(true);
+ expect(isPlaceholderOrSpace(tab)).toBe(true);
+ expect(isPlaceholderOrSpace(sectionBreak)).toBe(true);
+ expect(isPlaceholderOrSpace(space)).toBe(true);
+ expect(isPlaceholderOrSpace(text)).toBe(false);
+ expect(isPlaceholderOrSpace(null)).toBe(false);
+ });
+});
diff --git a/packages/engine-render/src/basics/__tests__/group-transform.spec.ts b/packages/engine-render/src/basics/__tests__/group-transform.spec.ts
new file mode 100644
index 0000000000..af79b2d073
--- /dev/null
+++ b/packages/engine-render/src/basics/__tests__/group-transform.spec.ts
@@ -0,0 +1,114 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ getDrawingGroupState,
+ getGroupState,
+ getRenderTransformBaseOnParentBound,
+ getRotatedBoundInGroup,
+ transformObjectOutOfGroup,
+} from '../group-transform';
+
+describe('group transform', () => {
+ it('calculates group bounds from child states', () => {
+ const states = [
+ { left: 10, top: 20, width: 30, height: 40 },
+ { left: -5, top: 15, width: 12, height: 8 },
+ { left: 40, top: 3, width: 5, height: 10 },
+ ] as any[];
+
+ const normal = getGroupState(100, 50, states);
+ expect(normal).toEqual({
+ left: 95,
+ top: 53,
+ width: 50,
+ height: 57,
+ angle: 0,
+ scaleX: 1,
+ scaleY: 1,
+ });
+
+ const drawing = getDrawingGroupState(100, 50, states);
+ expect(drawing).toEqual({
+ left: -5,
+ top: 3,
+ width: 50,
+ height: 57,
+ angle: 0,
+ scaleX: 1,
+ scaleY: 1,
+ });
+ });
+
+ it('maps child bounds by parent/base bounds and rotates/flips out of group', () => {
+ const mapped = getRenderTransformBaseOnParentBound(
+ { left: 10, top: 20, width: 200, height: 100 },
+ { left: 100, top: 60, width: 400, height: 200 },
+ { left: 60, top: 45, width: 40, height: 20 }
+ );
+ expect(mapped).toEqual({
+ left: 200,
+ top: 110,
+ width: 80,
+ height: 40,
+ });
+
+ const passThrough = getRenderTransformBaseOnParentBound(
+ null as any,
+ { left: 100, top: 60, width: 400, height: 200 },
+ { left: 60, top: 45, width: 40, height: 20 }
+ );
+ expect(passThrough).toEqual({
+ left: 60,
+ top: 45,
+ width: 40,
+ height: 20,
+ });
+
+ const transformed = transformObjectOutOfGroup(
+ { left: 60, top: 45, width: 40, height: 20, angle: 30, flipX: false, flipY: true } as any,
+ { left: 100, top: 60, angle: 90, flipX: true, flipY: false } as any,
+ 400,
+ 200,
+ { left: 10, top: 20, width: 200, height: 100 }
+ );
+ expect(transformed.width).toBeGreaterThan(0);
+ expect(transformed.height).toBeGreaterThan(0);
+ expect(transformed.angle).toBe(120);
+ expect(transformed.flipX).toBe(true);
+ expect(transformed.flipY).toBe(true);
+ expect(Number.isFinite(transformed.left)).toBe(true);
+ expect(Number.isFinite(transformed.top)).toBe(true);
+ });
+
+ it('switches major axes for rotated bounds in group space', () => {
+ const bound = { left: 10, top: 20, width: 60, height: 30 };
+
+ const horizontal = getRotatedBoundInGroup(bound, 10);
+ expect(horizontal).toEqual(bound);
+
+ const vertical = getRotatedBoundInGroup(bound, 90);
+ expect(vertical.width).toBe(30);
+ expect(vertical.height).toBe(60);
+ expect(vertical.left).toBe(25);
+ expect(vertical.top).toBe(5);
+
+ const around360 = getRotatedBoundInGroup(bound, 450);
+ expect(around360.width).toBe(30);
+ expect(around360.height).toBe(60);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
new file mode 100644
index 0000000000..2c223eec62
--- /dev/null
+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts
@@ -0,0 +1,375 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { setupRenderTestEnv } from '../../../__tests__/render-test-utils';
+import { DocumentSkeletonPageType, GlyphType, LineType, PageLayoutType } from '../../../basics/i-document-skeleton-cached';
+import { Canvas } from '../../../canvas';
+import { Engine } from '../../../engine';
+import { MAIN_VIEW_PORT_KEY, Scene } from '../../../scene';
+import { Viewport } from '../../../viewport';
+import { DOCS_EXTENSION_TYPE } from '../doc-extension';
+import { Documents } from '../document';
+
+function createGlyph(content: string, left: number, width = 16) {
+ return {
+ glyphType: GlyphType.WORD,
+ streamType: 'word',
+ content,
+ raw: content,
+ count: content.length,
+ width,
+ left,
+ xOffset: 0,
+ isJustifiable: false,
+ bBox: {
+ width,
+ ba: 10,
+ bd: 2,
+ aba: 10,
+ abd: 2,
+ sp: 0,
+ sbr: 0.6,
+ sbo: 1,
+ spr: 0.6,
+ spo: 1,
+ },
+ ts: {
+ fs: 12,
+ ff: 'Arial',
+ cl: { rgb: '#222222' },
+ },
+ fontStyle: {
+ fontString: '12px Arial',
+ fontSize: 12,
+ originFontSize: 12,
+ fontFamily: 'Arial',
+ fontCache: '12px Arial',
+ },
+ adjustability: {
+ stretchability: [0, 0],
+ shrinkability: [0, 0],
+ },
+ } as any;
+}
+
+function createLine(type: LineType, top: number, withBorder = false) {
+ const glyphA = createGlyph('A', 0);
+ const glyphB = createGlyph('B', 18);
+ const divide = {
+ glyphGroup: [glyphA, glyphB],
+ width: 120,
+ left: 0,
+ paddingLeft: 0,
+ isFull: false,
+ st: 0,
+ ed: 2,
+ } as any;
+ const line = {
+ paragraphIndex: 0,
+ type,
+ divides: [divide],
+ divideLen: 1,
+ lineHeight: 20,
+ contentHeight: 12,
+ top,
+ asc: 10,
+ dsc: 2,
+ paddingTop: 2,
+ paddingBottom: 2,
+ marginTop: 1,
+ marginBottom: 0,
+ spaceBelowApply: 0,
+ st: 0,
+ ed: 2,
+ lineIndex: 0,
+ paragraphStart: true,
+ isBehindTable: false,
+ tableId: '',
+ borderBottom: withBorder
+ ? {
+ color: { rgb: '#cdd0d8' },
+ padding: 0,
+ }
+ : undefined,
+ } as any;
+
+ divide.parent = line;
+ glyphA.parent = divide;
+ glyphB.parent = divide;
+
+ return line;
+}
+
+function createPage(pageType: DocumentSkeletonPageType, segmentId: string) {
+ const lineBlock = createLine(LineType.BLOCK, 0);
+ const lineText = createLine(LineType.PARAGRAPH, 24, true);
+ const column = {
+ lines: [lineBlock, lineText],
+ left: 0,
+ width: 180,
+ height: 80,
+ spaceWidth: 0,
+ separator: 0,
+ st: 0,
+ ed: 2,
+ drawingLRIds: [],
+ isFull: false,
+ } as any;
+ const section = {
+ columns: [column],
+ colCount: 1,
+ height: 120,
+ top: 0,
+ st: 0,
+ ed: 2,
+ } as any;
+ const page = {
+ sections: [section],
+ headerId: 'header-main',
+ footerId: 'footer-main',
+ pageWidth: 200,
+ pageHeight: 420,
+ pageOrient: 0,
+ marginLeft: 10,
+ marginRight: 10,
+ originMarginTop: 12,
+ marginTop: 12,
+ originMarginBottom: 12,
+ marginBottom: 12,
+ left: 0,
+ pageNumber: 1,
+ pageNumberStart: 1,
+ verticalAlign: false,
+ angle: 0,
+ width: 180,
+ height: 120,
+ breakType: 0,
+ st: 0,
+ ed: 2,
+ skeDrawings: new Map(),
+ skeTables: new Map(),
+ segmentId,
+ type: pageType,
+ renderConfig: {
+ horizontalAlign: 2,
+ verticalAlign: 1,
+ centerAngle: 8,
+ vertexAngle: 35,
+ wrapStrategy: 2,
+ },
+ } as any;
+
+ section.parent = page;
+ column.parent = section;
+ lineBlock.parent = column;
+ lineText.parent = column;
+
+ return page;
+}
+
+function attachTable(page: any) {
+ const cellPage = createPage(DocumentSkeletonPageType.CELL, 'cell-seg');
+ cellPage.marginLeft = 0;
+ cellPage.marginTop = 0;
+ cellPage.marginRight = 0;
+ cellPage.marginBottom = 0;
+ cellPage.pageWidth = 120;
+ cellPage.pageHeight = 60;
+ cellPage.headerId = '';
+ cellPage.footerId = '';
+
+ const row = {
+ cells: [cellPage],
+ index: 0,
+ height: 60,
+ top: 0,
+ st: 0,
+ ed: 2,
+ isRepeatRow: false,
+ rowSource: {
+ tableCells: [{
+ borderTop: { color: { rgb: '#333333' } },
+ borderBottom: { color: { rgb: '#333333' } },
+ borderLeft: { color: { rgb: '#333333' } },
+ borderRight: { color: { rgb: '#333333' } },
+ backgroundColor: { rgb: '#ffeecc' },
+ }],
+ },
+ } as any;
+ const table = {
+ rows: [row],
+ width: 120,
+ height: 60,
+ top: 20,
+ left: 12,
+ st: 0,
+ ed: 2,
+ tableId: 'table-1',
+ tableSource: {},
+ parent: page,
+ } as any;
+
+ row.parent = table;
+ cellPage.parent = row;
+ page.skeTables.set('table-1', table);
+}
+
+describe('documents render', () => {
+ let restoreEnv: () => void;
+ let container: HTMLDivElement;
+ let engine: Engine;
+ let scene: Scene;
+ let canvas: Canvas;
+
+ beforeEach(() => {
+ restoreEnv = setupRenderTestEnv().restore;
+ container = document.createElement('div');
+ container.style.width = '820px';
+ container.style.height = '520px';
+ document.body.appendChild(container);
+
+ engine = new Engine('document-engine', { elementWidth: 800, elementHeight: 500, dpr: 1 });
+ engine.mount(container, false);
+
+ scene = new Scene('document-scene', engine);
+ scene.transformByState({
+ width: 1200,
+ height: 900,
+ scaleX: 1,
+ scaleY: 1,
+ });
+ new Viewport(MAIN_VIEW_PORT_KEY, scene, {
+ left: 0,
+ top: 0,
+ width: 600,
+ height: 400,
+ active: true,
+ allowCache: true,
+ bufferEdgeX: 10,
+ bufferEdgeY: 8,
+ });
+
+ canvas = new Canvas({ width: 800, height: 500, pixelRatio: 1 });
+ });
+
+ afterEach(() => {
+ canvas.dispose();
+ scene.dispose();
+ engine.dispose();
+ restoreEnv();
+ container.remove();
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+ });
+
+ it('draws body/header/footer/table flows with extension dispatch and page events', () => {
+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');
+ const headerPage = createPage(DocumentSkeletonPageType.HEADER, 'header-main');
+ const footerPage = createPage(DocumentSkeletonPageType.FOOTER, 'footer-main');
+ attachTable(bodyPage);
+
+ const skeletonData = {
+ pages: [bodyPage],
+ skeHeaders: new Map([['header-main', new Map([[bodyPage.pageWidth, headerPage]])]]),
+ skeFooters: new Map([['footer-main', new Map([[bodyPage.pageWidth, footerPage]])]]),
+ };
+ bodyPage.parent = skeletonData;
+ headerPage.parent = skeletonData;
+ footerPage.parent = skeletonData;
+
+ const skeleton = {
+ getSkeletonData: () => skeletonData,
+ } as any;
+
+ const documents = new Documents('docs-main', skeleton, {
+ pageLayoutType: PageLayoutType.VERTICAL,
+ pageMarginLeft: 6,
+ pageMarginTop: 8,
+ });
+ documents.transformByState({
+ left: 12,
+ top: 16,
+ width: 260,
+ height: 180,
+ });
+ scene.addObject(documents, 1);
+
+ const lineDraw = vi.fn();
+ const bgDraw = vi.fn();
+ const spanDraw = vi.fn();
+ const clearCache = vi.fn();
+
+ vi.spyOn(documents as any, 'getExtensionsByOrder').mockReturnValue([
+ {
+ uKey: 'DefaultDocsBackgroundExtension',
+ type: DOCS_EXTENSION_TYPE.SPAN,
+ extensionOffset: {},
+ clearCache,
+ draw: bgDraw,
+ },
+ {
+ uKey: 'DocsLineExtension',
+ type: DOCS_EXTENSION_TYPE.LINE,
+ extensionOffset: {},
+ clearCache,
+ draw: lineDraw,
+ },
+ {
+ uKey: 'DocsSpanExtension',
+ type: DOCS_EXTENSION_TYPE.SPAN,
+ extensionOffset: {},
+ clearCache,
+ draw: spanDraw,
+ },
+ ] as any);
+
+ const pageEvents: string[] = [];
+ documents.pageRender$.subscribe((event) => {
+ pageEvents.push(`${event.page.pageNumber}:${Math.round(event.pageTop)}`);
+ });
+
+ const offsetConfig = documents.getOffsetConfig();
+ expect(offsetConfig.pageMarginLeft).toBe(6);
+ expect(documents.getEngine()).toBe(engine);
+
+ documents.draw(canvas.getContext(), {
+ viewBound: { left: 0, top: 0, right: 900, bottom: 700 },
+ cacheBound: { left: 0, top: 0, right: 900, bottom: 700 },
+ } as any);
+
+ expect(pageEvents.length).toBe(1);
+ expect(clearCache).toHaveBeenCalled();
+ expect(lineDraw).toHaveBeenCalled();
+ expect(bgDraw).toHaveBeenCalled();
+ expect(spanDraw).toHaveBeenCalled();
+
+ documents.draw(canvas.getContext(), {
+ viewBound: { left: 2000, top: 2000, right: 2200, bottom: 2200 },
+ cacheBound: { left: 2000, top: 2000, right: 2200, bottom: 2200 },
+ } as any);
+ expect(pageEvents.length).toBe(1);
+
+ const newSkeleton = { getSkeletonData: () => skeletonData } as any;
+ expect(documents.changeSkeleton(newSkeleton as any)).toBe(documents);
+ (documents as any)._drawLiquid = null;
+ documents.draw(canvas.getContext(), {
+ viewBound: { left: 0, top: 0, right: 300, bottom: 300 },
+ } as any);
+
+ documents.dispose();
+ });
+});
diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
new file mode 100644
index 0000000000..e423b23f7d
--- /dev/null
+++ b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
@@ -0,0 +1,155 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BaselineOffset } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { GlyphType } from '../../../../basics/i-document-skeleton-cached';
+import { Vector2 } from '../../../../basics/vector2';
+import { CheckboxShape } from '../../../../shape';
+import { FontAndBaseLine } from '../font-and-base-line';
+
+function createContext() {
+ return {
+ fillStyle: '',
+ font: '10px Arial',
+ save: vi.fn(),
+ restore: vi.fn(),
+ fillText: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ } as any;
+}
+
+function createGlyph(content: string, overrides?: Partial<any>) {
+ return {
+ content,
+ width: 16,
+ left: 0,
+ xOffset: 0,
+ glyphType: GlyphType.WORD,
+ parent: {
+ parent: {},
+ },
+ bBox: {
+ aba: 10,
+ abd: 2,
+ sbo: 2,
+ spo: 3,
+ },
+ fontStyle: {
+ fontString: '12px Arial',
+ },
+ ts: {
+ fs: 12,
+ cl: { rgb: '#223344' },
+ },
+ ...overrides,
+ } as any;
+}
+
+describe('docs font and baseline extension', () => {
+ it('handles text drawing with baseline offsets and vertical text branch', () => {
+ const extension = new FontAndBaseLine();
+ const context = createContext();
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(12, 20),
+ spanStartPoint: Vector2.create(10, 10),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 0,
+ centerAngle: 0,
+ },
+ } as any;
+
+ extension.draw(context, { scaleX: 1, scaleY: 1 } as any, createGlyph('A'));
+ expect(context.fillText).toHaveBeenCalledWith('A', 12, 20);
+
+ const superscript = createGlyph('S', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ va: BaselineOffset.SUPERSCRIPT,
+ },
+ });
+ extension.draw(context, { scaleX: 1, scaleY: 1 } as any, superscript);
+ expect(context.fillText).toHaveBeenCalledWith('S', 12, 17);
+
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(12, 20),
+ spanStartPoint: Vector2.create(10, 10),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 0,
+ centerAngle: 0,
+ },
+ } as any;
+ const subscript = createGlyph('s', {
+ ts: {
+ fs: 12,
+ cl: { rgb: '#111111' },
+ va: BaselineOffset.SUBSCRIPT,
+ },
+ });
+ extension.draw(context, { scaleX: 1, scaleY: 1 } as any, subscript);
+ expect(context.fillText).toHaveBeenCalledWith('s', 12, 22);
+
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(16, 26),
+ spanStartPoint: Vector2.create(16, 26),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 90,
+ centerAngle: 90,
+ },
+ } as any;
+ extension.draw(context, { scaleX: 1, scaleY: 1 } as any, createGlyph('X'));
+ expect(context.rotate).toHaveBeenCalled();
+ });
+
+ it('renders checkbox list glyphs and clears cache', () => {
+ const extension = new FontAndBaseLine();
+ const context = createContext();
+ const checkSpy = vi.spyOn(CheckboxShape, 'drawWith').mockImplementation(() => undefined);
+
+ extension.extensionOffset = {
+ spanPointWithFont: Vector2.create(30, 50),
+ spanStartPoint: Vector2.create(24, 44),
+ centerPoint: Vector2.create(8, 8),
+ renderConfig: {
+ vertexAngle: 0,
+ centerAngle: 0,
+ },
+ } as any;
+
+ const checkedGlyph = createGlyph('\u2611', {
+ glyphType: GlyphType.LIST,
+ ts: {
+ fs: 10,
+ cl: { rgb: '#111111' },
+ },
+ });
+ extension.draw(context, { scaleX: 1, scaleY: 1 } as any, checkedGlyph);
+ expect(checkSpy).toHaveBeenCalled();
+
+ extension.clearCache();
+ extension.extensionOffset = {
+ renderConfig: {},
+ } as any;
+ context.fillText.mockClear();
+ extension.draw(context, { scaleX: 1, scaleY: 1 } as any, createGlyph('A', { parent: null }));
+ expect(context.fillText).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index bee1084944..728888ec90 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -14,10 +14,11 @@
* limitations under the License.
*/
-import { ColumnSeparatorType } from '@univerjs/core';
+import { ColumnSeparatorType, createDocumentModelWithStyle, LocaleService, Univer } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
import { DocumentSkeletonPageType, GlyphType, PageLayoutType } from '../../../../basics/i-document-skeleton-cached';
import { Vector2 } from '../../../../basics/vector2';
+import { DocumentViewModel } from '../../view-model/document-view-model';
import { DocumentSkeleton } from '../doc-skeleton';
function createPage(type: DocumentSkeletonPageType, st: number, tableId = '') {
@@ -340,4 +341,46 @@ describe('doc skeleton', () => {
const noNode = skeleton.findNodeByCharIndex(9999);
expect(noNode).toBeUndefined();
});
+
+ it('calculates real skeleton layout from document view model', () => {
+ const univer = new Univer();
+ const localeService = univer.__getInjector().get(LocaleService);
+
+ const documentModel = createDocumentModelWithStyle(
+ 'This is a long sentence to trigger wrapping in layout ruler.\rSecond paragraph with tabs\tand punctuation.\r',
+ {}
+ );
+ documentModel.updateDocumentDataPageSize(160, 220);
+
+ const viewModel = new DocumentViewModel(documentModel);
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
+ skeleton.calculate();
+
+ const skeletonData = skeleton.getSkeletonData();
+ expect(skeletonData?.pages.length).toBeGreaterThan(0);
+
+ const glyphGroup = skeletonData?.pages[0]
+ ?.sections[0]
+ ?.columns[0]
+ ?.lines[0]
+ ?.divides[0]
+ ?.glyphGroup;
+ const glyph = glyphGroup?.find((item) => item.content && item.content.trim().length > 0);
+ expect(glyph).toBeTruthy();
+
+ const position = skeleton.findPositionByGlyph(glyph as any, 0);
+ expect(position?.pageType).toBe(DocumentSkeletonPageType.BODY);
+
+ if (position) {
+ const index = skeleton.findCharIndexByPosition({
+ ...position,
+ isBack: true,
+ });
+ expect(typeof index).toBe('number');
+ expect(skeleton.findNodeByCharIndex(index as number)).toBeTruthy();
+ }
+
+ skeleton.dispose();
+ univer.dispose();
+ });
});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/bullet.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/bullet.spec.ts
new file mode 100644
index 0000000000..267478fb90
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/bullet.spec.ts
@@ -0,0 +1,118 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ListGlyphType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { dealWithBullet, getDefaultBulletSke } from '../bullet';
+
+describe('paragraph bullet', () => {
+ it('returns default bullet skeleton for missing list definitions', () => {
+ expect(dealWithBullet()).toBeUndefined();
+
+ const fallbackNoList = dealWithBullet(
+ { listId: 'l1', listType: 'decimal', nestingLevel: 0 } as any,
+ {} as any,
+ []
+ );
+ expect(fallbackNoList).toEqual(expect.objectContaining({
+ listId: 'l1',
+ symbol: '\u25CF',
+ }));
+
+ const fallbackNoNesting = dealWithBullet(
+ { listId: 'l2', listType: 'decimal', nestingLevel: 2 } as any,
+ {
+ decimal: {
+ nestingLevel: [{}],
+ },
+ } as any,
+ [{ startIndexItem: 2 } as any, null, { startIndexItem: 8 } as any]
+ );
+ expect(fallbackNoNesting?.startIndexItem).toBe(8);
+
+ expect(getDefaultBulletSke('lx', 3).startIndexItem).toBe(3);
+ });
+
+ it('builds ordered and unordered list symbols from nesting rules', () => {
+ const listLevelAncestors = [
+ { startIndexItem: 4 } as any,
+ { startIndexItem: 3 } as any,
+ ];
+ const lists = {
+ custom: {
+ nestingLevel: [
+ {
+ startNumber: 1,
+ glyphType: ListGlyphType.DECIMAL,
+ glyphFormat: '%1.',
+ paragraphProperties: {},
+ textStyle: {
+ ff: 'Times New Roman',
+ },
+ },
+ {
+ startNumber: 1,
+ glyphType: ListGlyphType.UPPER_LETTER,
+ glyphFormat: '%1.%2)',
+ paragraphProperties: {},
+ textStyle: {
+ ff: 'Arial',
+ fs: 11,
+ },
+ },
+ ],
+ },
+ unordered: {
+ nestingLevel: [
+ {
+ glyphSymbol: '•',
+ glyphFormat: '',
+ paragraphProperties: {},
+ textStyle: {},
+ },
+ ],
+ },
+ } as any;
+
+ const ordered = dealWithBullet(
+ {
+ listId: 'l-order',
+ listType: 'custom',
+ nestingLevel: 1,
+ textStyle: {
+ bl: 1,
+ },
+ } as any,
+ lists,
+ listLevelAncestors
+ );
+ expect(ordered?.symbol).toBe('4.D)');
+ expect(ordered?.startIndexItem).toBe(4);
+ expect(ordered?.bulletType).toBe(true);
+
+ const unordered = dealWithBullet(
+ {
+ listId: 'l-unorder',
+ listType: 'unordered',
+ nestingLevel: 0,
+ } as any,
+ lists,
+ listLevelAncestors
+ );
+ expect(unordered?.symbol).toBe('•');
+ expect(unordered?.bulletType).toBe(false);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
new file mode 100644
index 0000000000..7a1f49263d
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
@@ -0,0 +1,273 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BooleanNumber, ColumnSeparatorType, DataStreamTreeTokenType, GridType, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, SpacingRule } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { BreakPointType } from '../../../line-breaker/break';
+import { createSkeletonPage } from '../../../model/page';
+import { layoutParagraph, updateInlineDrawingPosition } from '../layout-ruler';
+
+function createGlyph(content: string, width = 16, streamType = 'text') {
+ return {
+ glyphType: 1,
+ streamType,
+ content,
+ raw: content,
+ count: content.length,
+ width,
+ left: 0,
+ xOffset: 0,
+ isJustifiable: false,
+ bBox: {
+ width,
+ ba: 10,
+ bd: 2,
+ aba: 10,
+ abd: 2,
+ sp: 0,
+ sbr: 0.6,
+ sbo: 2,
+ spr: 0.6,
+ spo: 3,
+ },
+ adjustability: {
+ stretchability: [0, 0],
+ shrinkability: [0, 0],
+ },
+ } as any;
+}
+
+function createLayoutContext() {
+ return {
+ viewModel: {
+ getSelfOrHeaderFooterViewModel: () => ({
+ getDataModel: () => ({
+ body: {},
+ }),
+ }),
+ },
+ dataModel: {
+ documentStyle: {},
+ },
+ docsConfig: {},
+ skeleton: {
+ pages: [],
+ left: 0,
+ top: 0,
+ st: 0,
+ },
+ layoutStartPointer: {},
+ isDirty: false,
+ skeletonResourceReference: {
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ skeListLevel: new Map(),
+ drawingAnchor: new Map(),
+ },
+ floatObjectsCache: new Map(),
+ paragraphConfigCache: new Map(),
+ sectionBreakConfigCache: new Map(),
+ paragraphsOpenNewPage: new Set(),
+ hyphen: {
+ hasPattern: () => true,
+ loadPattern: () => Promise.resolve(),
+ },
+ languageDetector: {
+ detect: () => 'en-us',
+ },
+ } as any;
+}
+
+function createSectionBreakConfig() {
+ return {
+ pageNumberStart: 1,
+ pageSize: {
+ width: 220,
+ height: 120,
+ },
+ pageOrient: 0,
+ marginTop: 8,
+ marginBottom: 8,
+ marginLeft: 8,
+ marginRight: 8,
+ marginHeader: 0,
+ marginFooter: 0,
+ renderConfig: {},
+ localeService: {} as any,
+ headerTreeMap: new Map(),
+ footerTreeMap: new Map(),
+ lists: {},
+ drawings: {},
+ columnProperties: [],
+ columnSeparatorType: ColumnSeparatorType.NONE,
+ gridType: GridType.DEFAULT,
+ linePitch: 18,
+ lineSpacing: 1.2,
+ spacingRule: SpacingRule.AUTO,
+ paragraphLineGapDefault: 1,
+ charSpace: 0,
+ defaultTabStop: 10.5,
+ autoHyphenation: BooleanNumber.TRUE,
+ consecutiveHyphenLimit: 0,
+ hyphenationZone: 5,
+ } as any;
+}
+
+describe('layout ruler', () => {
+ it('lays out paragraph glyphs into lines/columns/pages with overflow and hyphen break handling', () => {
+ const ctx = createLayoutContext();
+ const sectionBreakConfig = createSectionBreakConfig();
+ const paragraphConfig = {
+ paragraphIndex: 2,
+ paragraphStyle: {
+ snapToGrid: BooleanNumber.FALSE,
+ spaceAbove: { v: 4 },
+ spaceBelow: { v: 3 },
+ indentFirstLine: { v: 12 },
+ hanging: { v: 6 },
+ indentStart: { v: 4 },
+ indentEnd: { v: 2 },
+ },
+ skeHeaders: new Map(),
+ skeFooters: new Map(),
+ pDrawingAnchor: new Map(),
+ } as any;
+
+ const firstPage = createSkeletonPage(
+ ctx,
+ sectionBreakConfig,
+ {
+ skeHeaders: paragraphConfig.skeHeaders,
+ skeFooters: paragraphConfig.skeFooters,
+ },
+ 1
+ );
+ ctx.skeleton.pages = [firstPage];
+
+ const lineBreakerGroup = [
+ createGlyph('longword', 120),
+ createGlyph('piece', 90),
+ createGlyph(DataStreamTreeTokenType.PARAGRAPH, 0, DataStreamTreeTokenType.PARAGRAPH),
+ ];
+
+ layoutParagraph(
+ ctx,
+ lineBreakerGroup,
+ ctx.skeleton.pages,
+ sectionBreakConfig,
+ paragraphConfig,
+ true,
+ BreakPointType.Hyphen
+ );
+
+ for (let i = 0; i < 12; i++) {
+ layoutParagraph(
+ ctx,
+ [
+ createGlyph(`S${i}`, 40),
+ createGlyph('tail', 30),
+ ],
+ ctx.skeleton.pages,
+ sectionBreakConfig,
+ {
+ ...paragraphConfig,
+ paragraphIndex: i + 3,
+ },
+ i === 0,
+ BreakPointType.Normal
+ );
+ }
+
+ const lastPage = ctx.skeleton.pages[ctx.skeleton.pages.length - 1];
+ lastPage.sections[0].columns[0].isFull = true;
+ layoutParagraph(
+ ctx,
+ [createGlyph('newpage', 70)],
+ ctx.skeleton.pages,
+ sectionBreakConfig,
+ {
+ ...paragraphConfig,
+ paragraphIndex: 99,
+ },
+ true,
+ BreakPointType.Normal
+ );
+
+ expect(ctx.skeleton.pages.length).toBeGreaterThan(1);
+ expect(ctx.skeleton.pages[0].sections[0].columns[0].lines.length).toBeGreaterThan(0);
+ expect(ctx.skeleton.pages.some((page: any) => page.sections.length > 0)).toBe(true);
+ });
+
+ it('updates inline drawing positions and handles page-break detection fallback', () => {
+ const page = createSkeletonPage(
+ createLayoutContext(),
+ createSectionBreakConfig(),
+ { skeHeaders: new Map(), skeFooters: new Map() },
+ 1
+ );
+ const section = page.sections[0];
+ const column = section.columns[0];
+
+ const customGlyph = {
+ ...createGlyph('\u25A1', 20, 'custom'),
+ streamType: DataStreamTreeTokenType.CUSTOM_BLOCK,
+ drawingId: 'drawing-1',
+ } as any;
+ const divide = {
+ glyphGroup: [customGlyph],
+ left: 8,
+ paddingLeft: 4,
+ width: 120,
+ } as any;
+ const line = {
+ divides: [divide],
+ top: 24,
+ lineHeight: 18,
+ marginBottom: 2,
+ paragraphStart: false,
+ } as any;
+
+ divide.parent = line;
+ customGlyph.parent = divide;
+ line.parent = column;
+ column.lines = [line];
+
+ const inlineDrawings = new Map([
+ ['drawing-1', {
+ drawingId: 'drawing-1',
+ drawingOrigin: {
+ layoutType: PositionedObjectLayoutType.INLINE,
+ docTransform: {
+ positionH: { relativeFrom: ObjectRelativeFromH.COLUMN },
+ positionV: { relativeFrom: ObjectRelativeFromV.LINE },
+ size: { width: 20, height: 12 },
+ angle: 15,
+ },
+ },
+ }],
+ ]) as NonNullable<Parameters<typeof updateInlineDrawingPosition>[1]>;
+
+ updateInlineDrawingPosition(line, inlineDrawings, 7);
+ const placed = page.skeDrawings.get('drawing-1');
+ expect(placed).toBeTruthy();
+ expect(placed?.aLeft).toBeGreaterThan(0);
+ expect(placed?.aTop).toBeGreaterThan(0);
+ expect(placed?.lineTop).toBe(24);
+ expect(placed?.blockAnchorTop).toBe(7);
+
+ updateInlineDrawingPosition({ parent: null } as any, inlineDrawings, 0);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
new file mode 100644
index 0000000000..a2d147643d
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-cache.spec.ts
@@ -0,0 +1,177 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { FontCache } from '../font-cache';
+
+describe('font cache', () => {
+ beforeEach(() => {
+ (FontCache as any)._globalFontMeasureCache = new Map();
+ (FontCache as any)._fontDataMap = new Map();
+ (FontCache as any)._getTextHeightCache = {};
+ (FontCache as any)._context = null;
+ });
+
+ it('handles measure cache lifecycle and fallback metrics', () => {
+ const fakeContext = {
+ font: '',
+ textBaseline: 'middle',
+ measureText: vi.fn(() => ({
+ width: 20,
+ fontBoundingBoxAscent: Number.NaN,
+ fontBoundingBoxDescent: Number.NaN,
+ actualBoundingBoxAscent: 10,
+ actualBoundingBoxDescent: 5,
+ })),
+ };
+ (FontCache as any)._context = fakeContext;
+ const domSpy = vi.spyOn(FontCache, 'getTextSizeByDom').mockReturnValue({
+ width: 10,
+ height: 18,
+ });
+
+ const first = FontCache.getMeasureText('A', '12px Arial');
+ expect(first.fontBoundingBoxAscent).toBe(9);
+ expect(first.fontBoundingBoxDescent).toBe(9);
+ expect(domSpy).toHaveBeenCalled();
+
+ const second = FontCache.getMeasureText('A', '12px Arial');
+ expect(second).toEqual(first);
+ expect(fakeContext.measureText).toHaveBeenCalledTimes(1);
+
+ FontCache.setFontMeasureCache('12px Arial', 'B', {
+ width: 1,
+ fontBoundingBoxAscent: 1,
+ fontBoundingBoxDescent: 1,
+ actualBoundingBoxAscent: 1,
+ actualBoundingBoxDescent: 1,
+ });
+ expect(FontCache.getFontMeasureCache('12px Arial', 'B')).toBeTruthy();
+ expect(FontCache.clearFontMeasureCache('12px Arial/B')).toBe(true);
+ expect(FontCache.clearFontMeasureCache('12px Arial')).toBe(true);
+ });
+
+ it('auto-cleans overflow cache and computes baseline offsets', () => {
+ const cache = new Map<string, any>();
+ for (let i = 0; i < 10; i++) {
+ cache.set(`k-${i}`, {
+ width: i,
+ fontBoundingBoxAscent: 1,
+ fontBoundingBoxDescent: 1,
+ actualBoundingBoxAscent: 1,
+ actualBoundingBoxDescent: 1,
+ });
+ }
+ (FontCache as any)._globalFontMeasureCache = new Map([
+ ['12px Arial', cache],
+ ['12px Other', new Map(cache)],
+ ]);
+ expect(FontCache.autoCleanFontMeasureCache(5)).toBe(true);
+
+ expect(FontCache.getBaselineOffsetInfo('Unknown', 10)).toEqual({
+ sbr: 0.6,
+ sbo: 10,
+ spr: 0.6,
+ spo: 10,
+ });
+
+ (FontCache as any)._fontDataMap = new Map([
+ ['MyFont', {
+ subscriptSizeRatio: 0.5,
+ subscriptOffset: 0.2,
+ superscriptSizeRatio: 0.4,
+ superscriptOffset: 0.3,
+ }],
+ ]);
+ expect(FontCache.getBaselineOffsetInfo('MyFont', 20)).toEqual({
+ sbr: 0.5,
+ sbo: 4,
+ spr: 0.4,
+ spo: 6,
+ });
+ });
+
+ it('calculates text bounding box by font data and glyph info', () => {
+ (FontCache as any)._fontDataMap = new Map([
+ ['Local Font', {
+ notDefWidth: 0.6,
+ ascender: 0.8,
+ descender: 0.2,
+ typoAscender: 0.75,
+ typoDescender: 0.15,
+ strikeoutPosition: 0.35,
+ subscriptSizeRatio: 0.6,
+ subscriptOffset: 0.3,
+ superscriptSizeRatio: 0.5,
+ superscriptOffset: 0.4,
+ hdmxData: [12],
+ glyphHorizonMap: new Map([
+ ['A'.charCodeAt(0), {
+ width: 0.7,
+ lsb: 0,
+ pixelsPerEm: [0.65],
+ }],
+ ]),
+ }],
+ ]);
+
+ const byFont = FontCache.getTextSize('A', {
+ fontString: '12px Local Font',
+ fontSize: 12,
+ originFontSize: 12,
+ fontFamily: 'Local Font',
+ fontCache: '12px Local Font',
+ } as any);
+ expect(byFont.width).toBeGreaterThan(0);
+ expect(byFont.ba).toBeCloseTo(9.6);
+ expect(byFont.abd).toBeCloseTo(1.8);
+
+ const byMeasure = FontCache.getTextSize('Z', {
+ fontString: '11px Other Font',
+ fontSize: 11,
+ originFontSize: 11,
+ fontFamily: 'Other Font',
+ fontCache: '11px Other Font',
+ } as any);
+ expect(byMeasure.width).toBeGreaterThanOrEqual(0);
+
+ const fromGlyphInfo = FontCache.getBBoxFromGlyphInfo({
+ glyph: {
+ advanceWidth: 500,
+ },
+ font: {
+ unitsPerEm: 1000,
+ ascender: 800,
+ descender: -200,
+ },
+ boundingBox: {
+ x1: 0,
+ y1: -120,
+ x2: 510,
+ y2: 710,
+ },
+ } as any, {
+ fontString: '12px Arial',
+ fontSize: 12,
+ originFontSize: 12,
+ fontFamily: 'Arial',
+ fontCache: '12px Arial',
+ } as any);
+
+ expect(fromGlyphInfo.width).toBeGreaterThan(0);
+ expect(fromGlyphInfo.aba).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-library.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-library.spec.ts
new file mode 100644
index 0000000000..647d4b6af2
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/font-library.spec.ts
@@ -0,0 +1,90 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BooleanNumber } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { fontLibrary } from '../font-library';
+
+describe('font library', () => {
+ it('matches best local font variant by style distance', () => {
+ const book = new Map([
+ ['My Sans', new Map([
+ ['Regular', {
+ font: {
+ family: 'My Sans',
+ fullName: 'My Sans Regular',
+ postscriptName: 'MySans-Regular',
+ style: 'Regular',
+ },
+ buffer: new ArrayBuffer(8),
+ }],
+ ['Bold', {
+ font: {
+ family: 'My Sans',
+ fullName: 'My Sans Bold',
+ postscriptName: 'MySans-Bold',
+ style: 'Bold',
+ },
+ buffer: new ArrayBuffer(8),
+ }],
+ ['Italic', {
+ font: {
+ family: 'My Sans',
+ fullName: 'My Sans Italic',
+ postscriptName: 'MySans-Italic',
+ style: 'Italic',
+ },
+ buffer: new ArrayBuffer(8),
+ }],
+ ])],
+ ]);
+
+ (fontLibrary as any)._fontBook = book;
+
+ const regular = fontLibrary.findBestMatchFontByStyle({
+ ff: 'My Sans',
+ bl: BooleanNumber.FALSE,
+ it: BooleanNumber.FALSE,
+ });
+ expect(regular?.font.fullName).toBe('My Sans Regular');
+
+ const bold = fontLibrary.findBestMatchFontByStyle({
+ ff: 'My Sans',
+ bl: BooleanNumber.TRUE,
+ it: BooleanNumber.FALSE,
+ });
+ expect(bold?.font.fullName).toBe('My Sans Bold');
+
+ const italic = fontLibrary.findBestMatchFontByStyle({
+ ff: 'My Sans',
+ bl: BooleanNumber.FALSE,
+ it: BooleanNumber.TRUE,
+ });
+ expect(italic?.font.fullName).toBe('My Sans Italic');
+
+ expect(fontLibrary.findBestMatchFontByStyle({ ff: 'Unknown Family' })).toBeUndefined();
+ });
+
+ it('filters valid font families from current font book', () => {
+ (fontLibrary as any)._fontBook = new Map([
+ ['A', new Map()],
+ ['B', new Map()],
+ ]);
+
+ expect(fontLibrary.getValidFontFamilies(['A', 'C', 'B'])).toEqual(['A', 'B']);
+ expect(fontLibrary.getValidFontFamilies([])).toEqual([]);
+ });
+});
diff --git a/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts
new file mode 100644
index 0000000000..149828780a
--- /dev/null
+++ b/packages/engine-render/src/components/docs/layout/shaping-engine/__tests__/text-shaping-engine.spec.ts
@@ -0,0 +1,127 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BooleanNumber } from '@univerjs/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { textShape } from '../text-shaping';
+
+const h = vi.hoisted(() => {
+ const getKerningValue = vi.fn((prev: any, next: any) => (prev?.index === 1 && next?.index === 2 ? -20 : 0));
+ const mockFont = {
+ unitsPerEm: 1000,
+ stringToGlyphs: vi.fn((content: string) => {
+ return content.split('').map((char, index) => ({
+ index: char === '?' ? 0 : index + 1,
+ advanceWidth: 520,
+ getBoundingBox: () => ({
+ x1: 0,
+ y1: -120,
+ x2: 520,
+ y2: 720,
+ }),
+ }));
+ }),
+ getKerningValue,
+ };
+
+ return {
+ parse: vi.fn(() => mockFont),
+ fontLibrary: {
+ isReady: true,
+ getValidFontFamilies: vi.fn((families: string[]) => families),
+ findBestMatchFontByStyle: vi.fn(() => ({
+ font: {
+ family: 'Arial',
+ fullName: 'Arial Regular',
+ postscriptName: 'Arial-Regular',
+ style: 'Regular',
+ },
+ buffer: new ArrayBuffer(8),
+ })),
+ },
+ getKerningValue,
+ };
+});
+
+vi.mock('opentype.js/dist/opentype.module', () => ({
+ parse: h.parse,
+}));
+
+vi.mock('../font-library', () => ({
+ fontLibrary: h.fontLibrary,
+}));
+
+describe('text shaping runtime', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ h.fontLibrary.isReady = true;
+ h.fontLibrary.getValidFontFamilies.mockImplementation((families: string[]) => families);
+ h.fontLibrary.findBestMatchFontByStyle.mockReturnValue({
+ font: {
+ family: 'Arial',
+ fullName: 'Arial Regular',
+ postscriptName: 'Arial-Regular',
+ style: 'Regular',
+ },
+ buffer: new ArrayBuffer(8),
+ });
+ });
+
+ it('returns empty result when font library is not ready', () => {
+ h.fontLibrary.isReady = false;
+ const result = textShape({
+ dataStream: 'AB',
+ } as any);
+ expect(result).toEqual([]);
+ });
+
+ it('shapes text chunks with kerning and caches results', () => {
+ const body = {
+ dataStream: 'AB\r',
+ textRuns: [{
+ st: 0,
+ ed: 2,
+ ts: {
+ ff: 'Arial',
+ bl: BooleanNumber.FALSE,
+ it: BooleanNumber.FALSE,
+ },
+ }],
+ } as any;
+
+ const first = textShape(body);
+ expect(first.length).toBeGreaterThanOrEqual(2);
+ expect(first[0].glyph).toBeTruthy();
+ expect(first[1].kerning).toBe(-20);
+ expect(h.parse).toHaveBeenCalledTimes(1);
+
+ const second = textShape(body);
+ expect(second).toBe(first);
+ expect(h.parse).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to null glyph when no valid font family exists', () => {
+ h.fontLibrary.getValidFontFamilies.mockReturnValueOnce([]);
+ const result = textShape({
+ dataStream: 'A',
+ } as any);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].glyph).toBeNull();
+ expect(result[0].font).toBeNull();
+ });
+});
diff --git a/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts
new file mode 100644
index 0000000000..6f7d119e17
--- /dev/null
+++ b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts
@@ -0,0 +1,425 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IWorkbookData, Workbook } from '@univerjs/core';
+import type { IBoundRectNoAngle, IViewportInfo } from '../../../basics/vector2';
+import {
+ BooleanNumber,
+ BorderStyleTypes,
+ ILogService,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ ObjectMatrix,
+ RANGE_TYPE,
+ Univer,
+ UniverInstanceType,
+ WrapStrategy,
+} from '@univerjs/core';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';
+import { Vector2 } from '../../../basics/vector2';
+import { Canvas } from '../../../canvas';
+import { Engine } from '../../../engine';
+import { MAIN_VIEW_PORT_KEY, Scene } from '../../../scene';
+import { Viewport } from '../../../viewport';
+import { SHEET_VIEWPORT_KEY } from '../interfaces';
+import { convertTransformToOffsetX, convertTransformToOffsetY, SpreadsheetSkeleton } from '../sheet.render-skeleton';
+import { Spreadsheet } from '../spreadsheet';
+
+const workbookDataFactory = (): IWorkbookData => ({
+ id: 'sheet-render-workbook',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.EN_US,
+ name: 'sheet-render-workbook',
+ sheetOrder: ['sheet-1'],
+ styles: {
+ 'style-bg-border': {
+ bg: { rgb: '#f6f6cc' },
+ bd: {
+ t: { s: BorderStyleTypes.THIN, cl: { rgb: '#334455' } },
+ r: { s: BorderStyleTypes.THIN, cl: { rgb: '#334455' } },
+ b: { s: BorderStyleTypes.THIN, cl: { rgb: '#334455' } },
+ l: { s: BorderStyleTypes.THIN, cl: { rgb: '#334455' } },
+ },
+ tb: WrapStrategy.WRAP,
+ fs: 12,
+ ff: 'Arial',
+ },
+ 'style-rotate': {
+ tr: { a: 45 },
+ fs: 11,
+ ff: 'Arial',
+ cl: { rgb: '#111111' },
+ },
+ },
+ sheets: {
+ 'sheet-1': {
+ id: 'sheet-1',
+ name: 'Sheet-1',
+ rowCount: 20,
+ columnCount: 12,
+ defaultColumnWidth: 72,
+ defaultRowHeight: 24,
+ rowHeader: { width: 46 },
+ columnHeader: { height: 28 },
+ mergeData: [{ startRow: 2, endRow: 3, startColumn: 2, endColumn: 3, rangeType: RANGE_TYPE.NORMAL }],
+ rowData: {
+ 6: { hd: BooleanNumber.TRUE },
+ },
+ columnData: {
+ 5: { hd: BooleanNumber.TRUE },
+ 1: { w: 48 },
+ 2: { w: 64 },
+ },
+ cellData: {
+ 0: {
+ 0: { v: 'A1' },
+ 1: { v: 'very-long-text-for-overflow-path', s: 'style-bg-border' },
+ 2: { v: 'wrapped line text', s: 'style-bg-border' },
+ },
+ 1: {
+ 1: { v: 'rotate-text', s: 'style-rotate' },
+ 3: { v: '123', f: '=1+2' },
+ },
+ 2: {
+ 2: { v: 'merged-main', s: 'style-bg-border' },
+ },
+ },
+ },
+ },
+});
+
+interface IFixture {
+ univer: Univer;
+ workbook: Workbook;
+ skeleton: SpreadsheetSkeleton;
+ engine: Engine;
+ scene: Scene;
+ viewport: Viewport;
+ spreadsheet: Spreadsheet;
+ mainCanvas: Canvas;
+ cacheCanvas: Canvas;
+ restoreEnv: () => void;
+ container: HTMLDivElement;
+}
+
+function createBound(left: number, top: number, right: number, bottom: number): IBoundRectNoAngle {
+ return { left, top, right, bottom };
+}
+
+function createViewportInfo(scene: Scene, cacheCanvas: Canvas, overrides?: Partial<IViewportInfo>): IViewportInfo {
+ const viewBound = createBound(0, 0, 420, 240);
+ const cacheBound = createBound(0, 0, 460, 280);
+ const viewPortPosition = createBound(0, 0, 420, 240);
+
+ return {
+ viewBound,
+ cacheBound,
+ viewPortPosition,
+ cacheViewPortPosition: viewPortPosition,
+ diffBounds: [],
+ diffCacheBounds: [],
+ diffX: 0,
+ diffY: 0,
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_MAIN,
+ isDirty: 1,
+ isForceDirty: false,
+ allowCache: true,
+ shouldCacheUpdate: 1,
+ sceneTrans: scene.transform,
+ cacheCanvas,
+ leftOrigin: 0,
+ topOrigin: 0,
+ bufferEdgeX: 12,
+ bufferEdgeY: 8,
+ ...overrides,
+ };
+}
+
+function createFixture(): IFixture {
+ const renderEnv = setupRenderTestEnv();
+
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookDataFactory());
+ get(IUniverInstanceService).focusUnit('sheet-render-workbook');
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ const worksheet = workbook.getActiveSheet()!;
+ const skeleton = injector.createInstance(SpreadsheetSkeleton, worksheet, workbook.getStyles()).calculate() as SpreadsheetSkeleton;
+
+ const container = document.createElement('div');
+ container.style.width = '640px';
+ container.style.height = '360px';
+ document.body.appendChild(container);
+
+ const engine = new Engine('sheet-render-engine', { elementWidth: 620, elementHeight: 340, dpr: 1 });
+ engine.mount(container, false);
+ const scene = new Scene('sheet-render-scene', engine);
+ scene.transformByState({
+ width: 1800,
+ height: 1200,
+ scaleX: 1,
+ scaleY: 1,
+ });
+
+ const viewport = new Viewport(MAIN_VIEW_PORT_KEY, scene, {
+ left: 0,
+ top: 0,
+ width: 420,
+ height: 240,
+ active: true,
+ allowCache: true,
+ bufferEdgeX: 12,
+ bufferEdgeY: 8,
+ });
+ viewport.scrollToViewportPos({ viewportScrollX: 30, viewportScrollY: 18 });
+
+ skeleton.setScene(scene);
+ const spreadsheet = new Spreadsheet('sheet-component', skeleton, true);
+ scene.addObject(spreadsheet, 1);
+
+ const mainCanvas = new Canvas({ width: 640, height: 360, pixelRatio: 1 });
+ const cacheCanvas = new Canvas({ width: 700, height: 420, pixelRatio: 1 });
+
+ return {
+ univer,
+ workbook,
+ skeleton,
+ engine,
+ scene,
+ viewport,
+ spreadsheet,
+ mainCanvas,
+ cacheCanvas,
+ restoreEnv: renderEnv.restore,
+ container,
+ };
+}
+
+function disposeFixture(fixture: IFixture) {
+ fixture.spreadsheet.dispose();
+ fixture.viewport.dispose();
+ fixture.scene.dispose();
+ fixture.engine.dispose();
+ fixture.mainCanvas.dispose();
+ fixture.cacheCanvas.dispose();
+ fixture.univer.dispose();
+ fixture.restoreEnv();
+ fixture.container.remove();
+}
+
+describe('spreadsheet integration', () => {
+ let fixture: IFixture;
+
+ beforeEach(() => {
+ fixture = createFixture();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ disposeFixture(fixture);
+ document.body.innerHTML = '';
+ });
+
+ it('builds sheet skeleton cache through visible viewport and style/layout calculations', () => {
+ const { skeleton, scene, cacheCanvas } = fixture;
+ const vpInfo = createViewportInfo(scene, cacheCanvas);
+
+ expect(skeleton.updateVisibleRange(vpInfo)).toBe(true);
+ skeleton.setStylesCache(vpInfo);
+
+ const visibleMain = skeleton.getVisibleRangeByViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);
+ expect(visibleMain).toEqual(expect.objectContaining({
+ startRow: expect.any(Number),
+ endRow: expect.any(Number),
+ startColumn: expect.any(Number),
+ endColumn: expect.any(Number),
+ }));
+ expect(skeleton.rowColumnSegment.endRow).toBeGreaterThanOrEqual(0);
+ expect(skeleton.stylesCache.fontMatrix.getSizeOf()).toBeGreaterThan(0);
+
+ const autoHeights = skeleton.calculateAutoHeightInRange([{ startRow: 0, endRow: 6, startColumn: 0, endColumn: 3, rangeType: RANGE_TYPE.NORMAL }]);
+ expect(autoHeights.length).toBeGreaterThan(0);
+ expect(autoHeights.some((item) => (item.autoHeight ?? 0) >= 24)).toBe(true);
+
+ const currentCellHeights = new ObjectMatrix<number>();
+ currentCellHeights.setValue(0, 0, 6);
+ currentCellHeights.setValue(0, 1, 8);
+ const autoHeightsWithCurrent = skeleton.calculateAutoHeightInRange([
+ { startRow: 0, endRow: 3, startColumn: 0, endColumn: 2, rangeType: RANGE_TYPE.NORMAL },
+ ], currentCellHeights);
+ expect(autoHeightsWithCurrent.length).toBeGreaterThan(0);
+
+ const autoWidths = skeleton.calculateAutoWidthInRange([{ startRow: 0, endRow: 8, startColumn: 0, endColumn: 4, rangeType: RANGE_TYPE.NORMAL }]);
+ expect(autoWidths.length).toBeGreaterThan(0);
+ expect(autoWidths.every((item) => (item.width ?? 0) > 0)).toBe(true);
+
+ expect(skeleton.getFont(0, 1)).toBeTruthy();
+ expect(skeleton.getColWidth(2)).toBeGreaterThan(0);
+ expect(skeleton.getRowHeight(2)).toBeGreaterThan(0);
+ expect(skeleton.getDistanceFromTopLeft(2, 2)).toEqual({
+ x: expect.any(Number),
+ y: expect.any(Number),
+ });
+ expect(convertTransformToOffsetX(120, 2, { x: 20, y: 0 })).toBe(200);
+ expect(convertTransformToOffsetY(80, 1.5, { x: 0, y: 10 })).toBe(105);
+ expect(skeleton.getCellWithMergeInfoByIndex(2, 2)).toEqual(expect.objectContaining({
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 3,
+ }));
+
+ expect(skeleton.getHiddenRowsInRange({ startRow: 0, endRow: 10 })).toContain(6);
+ expect(skeleton.getHiddenColumnsInRange({ startColumn: 0, endColumn: 8 })).toContain(5);
+
+ const overflowRange = skeleton.getOverflowPosition({ width: 260, height: 20 }, 0 as any, 0, 1, 12);
+ expect(overflowRange.endColumn).toBeGreaterThanOrEqual(overflowRange.startColumn);
+
+ skeleton.resetRangeCache([{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 2, rangeType: RANGE_TYPE.NORMAL }]);
+ skeleton.resetCache();
+ expect(skeleton.stylesCache.fontMatrix.getSizeOf()).toBe(0);
+ });
+
+ it('renders spreadsheet with cache refresh and scrolling diff paths in scene viewport', () => {
+ const { spreadsheet, skeleton, scene, cacheCanvas, mainCanvas } = fixture;
+ const mainCtx = mainCanvas.getContext();
+
+ const baseVpInfo = createViewportInfo(scene, cacheCanvas, {
+ isDirty: 1,
+ isForceDirty: false,
+ });
+
+ spreadsheet.render(mainCtx as any, baseVpInfo);
+ expect(spreadsheet.allowCache).toBe(true);
+ expect(spreadsheet.getSelectionBounding(2, 2, 2, 2)).toEqual(expect.objectContaining({
+ startRow: 2,
+ endRow: 3,
+ startColumn: 2,
+ endColumn: 3,
+ }));
+
+ spreadsheet.makeDirty(false);
+ const scrollingVpInfo = createViewportInfo(scene, cacheCanvas, {
+ isDirty: 0,
+ isForceDirty: false,
+ diffBounds: [createBound(120, 72, 220, 142)],
+ diffCacheBounds: [createBound(120, 72, 220, 142)],
+ diffX: 16,
+ diffY: 8,
+ shouldCacheUpdate: 1,
+ });
+ spreadsheet.render(mainCtx as any, scrollingVpInfo);
+
+ spreadsheet.makeForceDirty(true);
+ spreadsheet.render(mainCtx as any, createViewportInfo(scene, cacheCanvas, { isDirty: 0, isForceDirty: true }));
+ expect(spreadsheet.isForceDirty()).toBe(true);
+
+ spreadsheet.setForceDisableGridlines(true);
+ spreadsheet.makeForceDirty(false);
+ spreadsheet.render(mainCtx as any, createViewportInfo(scene, cacheCanvas, {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,
+ isDirty: 1,
+ }));
+
+ expect(spreadsheet.getNoMergeCellPositionByIndex(1, 1)).toEqual(expect.objectContaining({
+ startX: expect.any(Number),
+ endX: expect.any(Number),
+ startY: expect.any(Number),
+ endY: expect.any(Number),
+ }));
+ expect(spreadsheet.isHit(Vector2.FromArray([100, 100]))).toBe(true);
+ expect(spreadsheet.getScrollXYByRelativeCoords(Vector2.FromArray([20, 20]))).toEqual({
+ x: expect.any(Number),
+ y: expect.any(Number),
+ });
+
+ skeleton.dispose();
+ });
+
+ it('covers spreadsheet draw helpers and utility branches', () => {
+ const { spreadsheet, skeleton, scene, cacheCanvas, mainCanvas } = fixture;
+ const context = mainCanvas.getContext() as any;
+ const viewportInfo = createViewportInfo(scene, cacheCanvas, {
+ diffBounds: [createBound(100, 60, 220, 140)],
+ diffCacheBounds: [createBound(100, 60, 220, 140)],
+ diffX: 4,
+ diffY: 3,
+ shouldCacheUpdate: 1,
+ isDirty: 0,
+ isForceDirty: false,
+ });
+
+ const extensionDraw = vi.fn();
+ vi.spyOn(spreadsheet as any, 'getExtensionsByOrder').mockReturnValue([{
+ uKey: 'MockSheetExtension',
+ draw: extensionDraw,
+ }]);
+
+ spreadsheet.draw(context, viewportInfo);
+ expect(extensionDraw).toHaveBeenCalled();
+
+ spreadsheet.paintNewAreaForScrolling(viewportInfo, {
+ cacheCanvas,
+ cacheCtx: cacheCanvas.getContext() as any,
+ mainCtx: context,
+ topOrigin: 0,
+ leftOrigin: 0,
+ bufferEdgeX: 8,
+ bufferEdgeY: 6,
+ rowHeaderWidth: skeleton.rowHeaderWidth,
+ columnHeaderHeight: skeleton.columnHeaderHeight,
+ scaleX: 1,
+ scaleY: 1,
+ } as any);
+
+ spreadsheet.refreshCacheCanvas(viewportInfo, {
+ cacheCanvas,
+ cacheCtx: cacheCanvas.getContext() as any,
+ mainCtx: context,
+ topOrigin: 0,
+ leftOrigin: 0,
+ bufferEdgeX: 8,
+ bufferEdgeY: 6,
+ });
+
+ (spreadsheet as any)._applyCache(cacheCanvas, null);
+ spreadsheet.testShowRuler(cacheCanvas.getContext() as any, viewportInfo);
+ const random = spreadsheet.testGetRandomLightColor();
+ expect(random).toMatch(/^#[A-F]{6}$/);
+
+ expect(spreadsheet.backgroundExtension).toBe(spreadsheet.backgroundExtension);
+ expect(spreadsheet.borderExtension).toBe(spreadsheet.borderExtension);
+ expect(spreadsheet.fontExtension).toBe(spreadsheet.fontExtension);
+ expect(spreadsheet.getDocuments()).toBeDefined();
+ expect(spreadsheet.forceDisableGridlines).toBe(spreadsheet.forceDisableGridlines);
+
+ const noSkeletonSpreadsheet = new Spreadsheet('no-skeleton');
+ expect(noSkeletonSpreadsheet.draw(context, viewportInfo)).toBeUndefined();
+ expect(noSkeletonSpreadsheet.isHit(Vector2.FromArray([10, 10]))).toBe(false);
+ expect(noSkeletonSpreadsheet.getNoMergeCellPositionByIndex(0, 0)).toEqual({
+ startX: 0,
+ startY: 0,
+ endX: 0,
+ endY: 0,
+ });
+ noSkeletonSpreadsheet.dispose();
+ });
+});
diff --git a/packages/engine-render/src/components/slides/__tests__/slide.spec.ts b/packages/engine-render/src/components/slides/__tests__/slide.spec.ts
new file mode 100644
index 0000000000..56da8e21bd
--- /dev/null
+++ b/packages/engine-render/src/components/slides/__tests__/slide.spec.ts
@@ -0,0 +1,126 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { setupRenderTestEnv } from '../../../__tests__/render-test-utils';
+import { Canvas } from '../../../canvas';
+import { Engine } from '../../../engine';
+import { MAIN_VIEW_PORT_KEY, Scene } from '../../../scene';
+import { Rect } from '../../../shape/rect';
+import { Viewport } from '../../../viewport';
+import { Slide, SLIDE_NAVIGATION_KEY } from '../slide';
+
+function createPageScene(engine: Engine, key: string, color: string) {
+ const scene = new Scene(key, engine);
+ scene.transformByState({
+ width: 640,
+ height: 360,
+ scaleX: 1,
+ scaleY: 1,
+ });
+ new Viewport(MAIN_VIEW_PORT_KEY, scene, {
+ left: 0,
+ top: 0,
+ width: 420,
+ height: 240,
+ active: true,
+ allowCache: true,
+ bufferEdgeX: 8,
+ bufferEdgeY: 6,
+ });
+ scene.addObject(new Rect(`${key}-rect`, {
+ left: 24,
+ top: 24,
+ width: 120,
+ height: 70,
+ fill: color,
+ stroke: '#222222',
+ }), 1);
+ return scene;
+}
+
+describe('slide', () => {
+ let restoreEnv: () => void;
+ let container: HTMLDivElement;
+ let engine: Engine;
+
+ beforeEach(() => {
+ restoreEnv = setupRenderTestEnv().restore;
+ container = document.createElement('div');
+ container.style.width = '760px';
+ container.style.height = '460px';
+ document.body.appendChild(container);
+ engine = new Engine('slide-engine', { elementWidth: 700, elementHeight: 420, dpr: 1 });
+ engine.mount(container, false);
+ });
+
+ afterEach(() => {
+ engine.dispose();
+ restoreEnv();
+ container.remove();
+ document.body.innerHTML = '';
+ });
+
+ it('changes pages through navigation objects and supports thumbnail rendering', () => {
+ const slide = new Slide('slide-main', {
+ width: 640,
+ height: 360,
+ } as any);
+ slide.enableNav();
+
+ const pageA = createPageScene(engine, 'page-a', '#cc8844');
+ const pageB = createPageScene(engine, 'page-b', '#4488cc');
+ slide.addPageScene(pageA);
+ slide.addPageScene(pageB);
+
+ expect(slide.hasPage('page-a')).toBeTruthy();
+ expect(slide.hasPage('page-b')).toBeTruthy();
+
+ slide.activeFirstPage();
+ expect(slide.getActiveSubScene()?.sceneKey).toBe('page-a');
+
+ slide.showNav();
+ slide.hiddenNav();
+ slide.showNav();
+
+ const changed: string[] = [];
+ slide.slideChangePageByNavigation$.subscribeEvent((key) => {
+ if (key) {
+ changed.push(key);
+ }
+ });
+
+ const rightArrow = slide.getActiveSubScene()?.getObject(SLIDE_NAVIGATION_KEY.RIGHT) as any;
+ expect(rightArrow).toBeTruthy();
+ rightArrow.onPointerDown$.emitEvent({} as any);
+ expect(slide.getActiveSubScene()?.sceneKey).toBe('page-b');
+
+ const leftArrow = slide.getActiveSubScene()?.getObject(SLIDE_NAVIGATION_KEY.LEFT) as any;
+ expect(leftArrow).toBeTruthy();
+ leftArrow.onPointerDown$.emitEvent({} as any);
+ expect(slide.getActiveSubScene()?.sceneKey).toBe('page-a');
+ expect(changed).toContain('page-b');
+ expect(changed).toContain('page-a');
+
+ const thumbCanvas = new Canvas({ width: 320, height: 180, pixelRatio: 1 });
+ slide.renderToThumb(thumbCanvas.getContext(), 'page-a', 0.5, 0.5);
+ thumbCanvas.dispose();
+
+ slide.disableNav();
+ slide.removeNavigation();
+ slide.dispose();
+ });
+});
diff --git a/packages/engine-render/src/floating/__tests__/util.spec.ts b/packages/engine-render/src/floating/__tests__/util.spec.ts
new file mode 100644
index 0000000000..ac5723d6a6
--- /dev/null
+++ b/packages/engine-render/src/floating/__tests__/util.spec.ts
@@ -0,0 +1,136 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { observeClientRect } from '../util';
+
+vi.mock('@floating-ui/dom', () => ({
+ getOverflowAncestors: vi.fn(() => [window]),
+}));
+
+describe('floating util', () => {
+ const originalIntersectionObserver = globalThis.IntersectionObserver;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ globalThis.IntersectionObserver = originalIntersectionObserver;
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ });
+
+ it('observes client rect changes from ancestor events and cleans up', () => {
+ let throwWithRoot = true;
+ class IntersectionObserverMock {
+ constructor(private _callback: IntersectionObserverCallback, options?: IntersectionObserverInit) {
+ if (options?.root && throwWithRoot) {
+ throwWithRoot = false;
+ throw new Error('root not supported');
+ }
+ }
+
+ observe(_target: Element) {
+ this._callback([{ intersectionRatio: 1 } as IntersectionObserverEntry], this as unknown as IntersectionObserver);
+ }
+
+ disconnect() {}
+ takeRecords() { return []; }
+ root: Element | Document | null = null;
+ rootMargin = '';
+ thresholds = [1];
+ unobserve() {}
+ }
+ globalThis.IntersectionObserver = IntersectionObserverMock as unknown as typeof IntersectionObserver;
+
+ const element = document.createElement('div');
+ document.body.appendChild(element);
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
+ x: 10,
+ y: 20,
+ left: 10,
+ top: 20,
+ right: 130,
+ bottom: 100,
+ width: 120,
+ height: 80,
+ toJSON: () => ({}),
+ } as DOMRect);
+
+ const calls: number[] = [];
+ const sub = observeClientRect(element).subscribe(() => {
+ calls.push(Date.now());
+ });
+
+ expect(calls.length).toBeGreaterThan(0);
+
+ window.dispatchEvent(new Event('scroll'));
+ window.dispatchEvent(new Event('resize'));
+ expect(calls.length).toBeGreaterThan(2);
+
+ sub.unsubscribe();
+ const before = calls.length;
+ window.dispatchEvent(new Event('scroll'));
+ window.dispatchEvent(new Event('resize'));
+ vi.runOnlyPendingTimers();
+ expect(calls.length).toBe(before);
+ });
+
+ it('handles zero-sized element without creating move observer loop', () => {
+ class IntersectionObserverMock {
+ constructor(private _callback: IntersectionObserverCallback) {}
+
+ observe(_target: Element) {
+ this._callback([{ intersectionRatio: 1 } as IntersectionObserverEntry], this as unknown as IntersectionObserver);
+ }
+
+ disconnect() {}
+
+ takeRecords() { return []; }
+
+ root: Element | Document | null = null;
+ rootMargin = '';
+ thresholds = [1];
+
+ unobserve() {}
+ }
+ globalThis.IntersectionObserver = IntersectionObserverMock as unknown as typeof IntersectionObserver;
+
+ const element = document.createElement('div');
+ document.body.appendChild(element);
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({
+ x: 0,
+ y: 0,
+ left: 0,
+ top: 0,
+ right: 0,
+ bottom: 0,
+ width: 0,
+ height: 0,
+ toJSON: () => ({}),
+ } as DOMRect);
+
+ let count = 0;
+ const sub = observeClientRect(element).subscribe(() => {
+ count += 1;
+ });
+
+ expect(count).toBe(1);
+ sub.unsubscribe();
+ });
+});
diff --git a/packages/engine-render/src/render-manager/__tests__/render-unit.spec.ts b/packages/engine-render/src/render-manager/__tests__/render-unit.spec.ts
new file mode 100644
index 0000000000..6e55f151b2
--- /dev/null
+++ b/packages/engine-render/src/render-manager/__tests__/render-unit.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 type { IRenderContext, IRenderModule } from '../render-unit';
+import { Disposable, Injector, UniverInstanceType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { RenderUnit } from '../render-unit';
+
+class RenderModuleA extends Disposable implements IRenderModule {
+ static calls = 0;
+
+ constructor(readonly context: IRenderContext) {
+ super();
+ RenderModuleA.calls += 1;
+ }
+}
+
+class RenderModuleToken extends Disposable implements IRenderModule {}
+
+class RenderModuleB extends Disposable implements IRenderModule {
+ static calls = 0;
+
+ constructor(readonly context: IRenderContext) {
+ super();
+ RenderModuleB.calls += 1;
+ }
+}
+
+function createRenderUnit() {
+ const parentInjector = new Injector();
+ const unit = {
+ getUnitId: () => 'unit-1',
+ type: UniverInstanceType.UNIVER_SHEET,
+ } as any;
+
+ const renderUnit = parentInjector.createInstance(RenderUnit, {
+ engine: {} as any,
+ scene: {} as any,
+ isMainScene: true,
+ unit,
+ });
+
+ return renderUnit;
+}
+
+describe('render unit', () => {
+ it('initializes context and toggles activation stream', () => {
+ const renderUnit = createRenderUnit();
+ const states: boolean[] = [];
+ const sub = renderUnit.activated$.subscribe((v) => states.push(v));
+
+ renderUnit.deactivate();
+ renderUnit.activate();
+
+ expect(renderUnit.unitId).toBe('unit-1');
+ expect(renderUnit.type).toBe(UniverInstanceType.UNIVER_SHEET);
+ expect(states).toEqual([true, false, true]);
+
+ sub.unsubscribe();
+ renderUnit.dispose();
+ });
+
+ it('registers render dependencies by class and useClass mapping', () => {
+ RenderModuleA.calls = 0;
+ RenderModuleB.calls = 0;
+ const renderUnit = createRenderUnit();
+
+ renderUnit.addRenderDependencies([RenderModuleA as any] as any);
+ expect(RenderModuleA.calls).toBe(1);
+ expect(renderUnit.with(RenderModuleA)).toBeInstanceOf(RenderModuleA);
+
+ renderUnit.addRenderDependencies([
+ [RenderModuleToken, { useClass: RenderModuleB }],
+ ] as any);
+ expect(RenderModuleB.calls).toBe(1);
+ expect(renderUnit.with(RenderModuleToken)).toBeInstanceOf(RenderModuleB);
+
+ expect(() => {
+ renderUnit.addRenderDependencies([
+ [RenderModuleToken, { useValue: new RenderModuleB({} as any) }],
+ ] as any);
+ }).toThrow('[RenderUnit]: render dependency could only be an class!');
+
+ renderUnit.components.set('main', {} as any);
+ renderUnit.dispose();
+ expect(renderUnit.components.size).toBe(0);
+ });
+});
diff --git a/packages/engine-render/src/shape/__tests__/dashedrect.spec.ts b/packages/engine-render/src/shape/__tests__/dashedrect.spec.ts
new file mode 100644
index 0000000000..8092354f9b
--- /dev/null
+++ b/packages/engine-render/src/shape/__tests__/dashedrect.spec.ts
@@ -0,0 +1,110 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { DashedRect } from '../dashedrect';
+
+function createContext() {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ closePath: vi.fn(),
+ rect: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ setLineDash: vi.fn(),
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 0,
+ lineCap: 'round',
+ lineDashOffset: 0,
+ lineJoin: 'round',
+ miterLimit: 0,
+ } as any;
+}
+
+describe('dashed rect', () => {
+ it('draws dashed rect paths with and without rounded corners', () => {
+ const ctx = createContext();
+
+ DashedRect.drawWith(ctx, {
+ left: 0,
+ top: 0,
+ width: 60,
+ height: 30,
+ strokeDashArray: [4, 2],
+ stroke: '#222222',
+ strokeWidth: 1,
+ fill: '#dddddd',
+ } as any);
+ expect(ctx.rect).toHaveBeenCalledWith(0, 0, 60, 30);
+ expect(ctx.setLineDash).toHaveBeenCalledWith([4, 2]);
+
+ DashedRect.drawWith(ctx, {
+ left: 0,
+ top: 0,
+ width: 40,
+ height: 20,
+ radius: 6,
+ strokeDashArray: [3, 1],
+ stroke: '#111111',
+ strokeWidth: 1,
+ fill: '#eeeeee',
+ } as any);
+ expect(ctx.arc).toHaveBeenCalled();
+ });
+
+ it('clips draw region by viewport bounds for selection overlay rendering', () => {
+ const ctx = createContext();
+ const drawSpy = vi.spyOn(DashedRect, 'drawWith').mockImplementation(() => undefined);
+ const rect = new DashedRect('dashed-selection', {
+ width: 80,
+ height: 40,
+ strokeDashArray: [2, 2],
+ stroke: '#555555',
+ strokeWidth: 1,
+ } as any);
+
+ (rect as any).parent = {
+ transform: {
+ getMatrix: () => [1, 0, 0, 1, 10, 20],
+ },
+ };
+
+ (rect as any)._draw(ctx, {
+ cacheBound: {
+ left: 20,
+ top: 30,
+ right: 60,
+ bottom: 50,
+ },
+ });
+
+ expect(drawSpy).toHaveBeenCalledWith(
+ ctx,
+ expect.objectContaining({
+ width: 40,
+ height: 20,
+ left: 10,
+ top: 10,
+ })
+ );
+ });
+});
diff --git a/packages/engine-render/src/shape/__tests__/text.spec.ts b/packages/engine-render/src/shape/__tests__/text.spec.ts
index 12d3c53b84..1bcec2837e 100644
--- a/packages/engine-render/src/shape/__tests__/text.spec.ts
+++ b/packages/engine-render/src/shape/__tests__/text.spec.ts
@@ -16,12 +16,13 @@
import { CellValueType, HorizontalAlign, TextDecoration, VerticalAlign } from '@univerjs/core';
import { describe, expect, it, vi } from 'vitest';
-import { Text, TEXT_OBJECT_ARRAY } from '../text';
+import { Text } from '../text';
function createCtx() {
return {
save: vi.fn(),
restore: vi.fn(),
+ transform: vi.fn(),
beginPath: vi.fn(),
moveTo: vi.fn(),
lineTo: vi.fn(),
@@ -44,9 +45,7 @@ function createSkeleton(lines: Array<{ text: string; width: number; height: numb
}
describe('text shape', () => {
- it('contains expected serialized keys and draws center/right alignment', () => {
- expect(TEXT_OBJECT_ARRAY).toEqual(expect.arrayContaining(['text', 'fontStyle', 'hAlign', 'vAlign']));
-
+ it('draws center/right alignment', () => {
const ctx = createCtx();
const skeleton = createSkeleton([{ text: 'abcd', width: 20, height: 10, baseline: 8 }]);
@@ -101,6 +100,42 @@ describe('text shape', () => {
expect(ctx.fillText).toHaveBeenCalledWith('123456', 0, 8);
});
+ it('builds skeleton internally and supports middle/bottom vertical alignment', () => {
+ const middleCtx = createCtx();
+ const middleHeight = Text.drawWith(
+ middleCtx,
+ {
+ text: 'line',
+ fontStyle: '12px Arial',
+ width: 100,
+ height: 40,
+ warp: false,
+ hAlign: HorizontalAlign.LEFT,
+ vAlign: VerticalAlign.MIDDLE,
+ } as any
+ );
+ expect(middleHeight).toBeGreaterThanOrEqual(0);
+ expect(middleCtx.fillText).toHaveBeenCalledTimes(1);
+
+ const bottomCtx = createCtx();
+ const bottomHeight = Text.drawWith(
+ bottomCtx,
+ {
+ text: 'line',
+ fontStyle: '12px Arial',
+ width: 100,
+ height: 40,
+ warp: false,
+ hAlign: HorizontalAlign.LEFT,
+ vAlign: VerticalAlign.BOTTOM,
+ underline: true,
+ strokeLine: true,
+ } as any
+ );
+ expect(bottomHeight).toBeGreaterThanOrEqual(0);
+ expect(bottomCtx.beginPath).toHaveBeenCalled();
+ });
+
it('draws underline and strike line decorations', () => {
const ctx = createCtx();
const skeleton = createSkeleton([{ text: 'abc', width: 6, height: 10, baseline: 8 }]);
@@ -127,6 +162,45 @@ describe('text shape', () => {
expect(ctx.lineTo.mock.calls.length).toBeGreaterThan(3);
});
+ it('applies each supported underline style through the business rendering path', () => {
+ const styleCases: Array<{ style: TextDecoration; expectedLineWidth: number; expectedDash?: number[] }> = [
+ { style: TextDecoration.DOTTED, expectedLineWidth: 1, expectedDash: [2] },
+ { style: TextDecoration.DASH, expectedLineWidth: 1, expectedDash: [3] },
+ { style: TextDecoration.DASHED_HEAVY, expectedLineWidth: 2, expectedDash: [3] },
+ { style: TextDecoration.DASH_LONG_HEAVY, expectedLineWidth: 2, expectedDash: [6] },
+ { style: TextDecoration.DOT_DASH, expectedLineWidth: 1, expectedDash: [2, 5, 2] },
+ { style: TextDecoration.DASH_DOT_HEAVY, expectedLineWidth: 2, expectedDash: [2, 5, 2] },
+ { style: TextDecoration.DOT_DOT_DASH, expectedLineWidth: 1, expectedDash: [2, 2, 5, 2, 2] },
+ { style: TextDecoration.THICK, expectedLineWidth: 2, expectedDash: [0] },
+ { style: TextDecoration.WAVY_DOUBLE, expectedLineWidth: 1 },
+ { style: TextDecoration.WAVY_HEAVY, expectedLineWidth: 2 },
+ ];
+
+ for (const { style, expectedLineWidth, expectedDash } of styleCases) {
+ const ctx = createCtx();
+ const skeleton = createSkeleton([{ text: 'abc', width: 8, height: 10, baseline: 8 }]);
+ Text.drawWith(
+ ctx,
+ {
+ text: 'abc',
+ fontStyle: '12px Arial',
+ width: 30,
+ height: 20,
+ hAlign: HorizontalAlign.LEFT,
+ vAlign: VerticalAlign.TOP,
+ underline: true,
+ underlineType: style,
+ } as any,
+ skeleton
+ );
+
+ expect(ctx.lineWidth).toBe(expectedLineWidth);
+ if (expectedDash) {
+ expect(ctx.setLineDash).toHaveBeenCalledWith(expectedDash);
+ }
+ }
+ });
+
it('covers line type setup and line drawing helpers', () => {
const ctx = createCtx();
const setLineType = (Text as any)._setLineType.bind(Text);
diff --git a/packages/find-replace/src/controllers/__tests__/find-replace.controller.spec.ts b/packages/find-replace/src/controllers/__tests__/find-replace.controller.spec.ts
new file mode 100644
index 0000000000..c02d4310be
--- /dev/null
+++ b/packages/find-replace/src/controllers/__tests__/find-replace.controller.spec.ts
@@ -0,0 +1,64 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+
+import { FindReplaceController } from '../find-replace.controller';
+
+describe('FindReplaceController', () => {
+ it('should open dialog when revealed and close when focus changes', () => {
+ const focused$ = new Subject<any>();
+ const univerInstanceService = {
+ focused$,
+ getUniverSheetInstance: vi.fn(() => null),
+ };
+
+ const menuManagerService = { mergeMenu: vi.fn() };
+ const shortcutService = { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) };
+ const commandService = { registerCommand: vi.fn(() => ({ dispose: vi.fn() })) };
+ const stateUpdates$ = new Subject<any>();
+ const findReplaceService = {
+ stateUpdates$,
+ terminate: vi.fn(),
+ };
+ const dialogService = { open: vi.fn(), close: vi.fn() };
+ const layoutService = { focus: vi.fn() };
+ const localeService = { t: (k: string) => k };
+ const componentManager = { register: vi.fn(() => ({ dispose: vi.fn() })) };
+
+ const controller = new FindReplaceController(
+ univerInstanceService as any,
+ menuManagerService as any,
+ shortcutService as any,
+ commandService as any,
+ findReplaceService as any,
+ dialogService as any,
+ layoutService as any,
+ localeService as any,
+ componentManager as any
+ );
+
+ stateUpdates$.next({ revealed: true });
+ expect(dialogService.open).toHaveBeenCalled();
+
+ focused$.next(null);
+ expect(dialogService.close).toHaveBeenCalled();
+ expect(findReplaceService.terminate).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/find-replace/src/services/__tests__/find-replace-model.replace-all.spec.ts b/packages/find-replace/src/services/__tests__/find-replace-model.replace-all.spec.ts
new file mode 100644
index 0000000000..9e79ce34cc
--- /dev/null
+++ b/packages/find-replace/src/services/__tests__/find-replace-model.replace-all.spec.ts
@@ -0,0 +1,63 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { FindModel, IFindMatch } from '../find-replace.service';
+import { Subject } from 'rxjs';
+
+import { describe, expect, it, vi } from 'vitest';
+import { FindReplaceModel, FindReplaceState } from '../find-replace.service';
+
+describe('FindReplaceModel', () => {
+ it('replaceAll should stop searching when all succeed', async () => {
+ const state = new FindReplaceState();
+ state.changeState({ findString: 'a', replaceString: 'b', revealed: true });
+
+ const univerInstanceService = { getFocusedUnit: vi.fn(() => ({ getUnitId: () => 'u1' })) };
+ const commandService = { onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })) };
+
+ const matchesUpdate$ = new Subject<IFindMatch[]>();
+ const activelyChangingMatch$ = new Subject<IFindMatch>();
+ const match1: IFindMatch = { provider: 'p', unitId: 'u1', range: 1, replaceable: true } as any;
+
+ const model: FindModel = {
+ unitId: 'u1',
+ matchesUpdate$,
+ activelyChangingMatch$,
+ getMatches: () => [match1],
+ moveToNextMatch: vi.fn(() => match1),
+ moveToPreviousMatch: vi.fn(() => match1),
+ replace: vi.fn(async () => true),
+ replaceAll: vi.fn(async () => ({ success: 1, failure: 0 })),
+ focusSelection: vi.fn(),
+ dispose: vi.fn(),
+ } as any;
+
+ const provider = {
+ find: vi.fn(async () => [model]),
+ terminate: vi.fn(),
+ };
+
+ const providers = new Set([provider as any]);
+ const findReplaceModel = new FindReplaceModel(state, providers, univerInstanceService as any, commandService as any);
+
+ await findReplaceModel.start();
+ const res = await findReplaceModel.replaceAll();
+ expect(res).toEqual({ success: 1, failure: 0 });
+ expect(provider.terminate).toHaveBeenCalled();
+
+ findReplaceModel.dispose();
+ });
+});
diff --git a/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts b/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts
new file mode 100644
index 0000000000..064b6728cf
--- /dev/null
+++ b/packages/find-replace/src/services/__tests__/find-replace.service.spec.ts
@@ -0,0 +1,96 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { FindModel, IFindMatch } from '../find-replace.service';
+import { Subject } from 'rxjs';
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { FindBy, FindDirection, FindReplaceModel, FindReplaceService, FindScope } from '../find-replace.service';
+
+describe('FindReplaceService', () => {
+ beforeEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('should start session and move to next match', async () => {
+ const contextService = { setContextValue: vi.fn() };
+
+ const focused$ = new Subject<any>();
+ const univerInstanceService = {
+ getFocusedUnit: vi.fn(() => ({ getUnitId: () => 'u1' })),
+ focused$,
+ };
+
+ const commandService = {
+ onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })),
+ };
+
+ const matchesUpdate$ = new Subject<IFindMatch[]>();
+ const activelyChangingMatch$ = new Subject<IFindMatch>();
+ const match1: IFindMatch = { provider: 'p', unitId: 'u1', range: { i: 1 }, replaceable: true } as any;
+ const match2: IFindMatch = { provider: 'p', unitId: 'u1', range: { i: 2 }, replaceable: false } as any;
+
+ const model: FindModel = {
+ unitId: 'u1',
+ matchesUpdate$,
+ activelyChangingMatch$,
+ getMatches: () => [match1, match2],
+ moveToNextMatch: vi.fn(() => match1),
+ moveToPreviousMatch: vi.fn(() => match2),
+ replace: vi.fn(async () => true),
+ replaceAll: vi.fn(async () => ({ success: 2, failure: 0 })),
+ focusSelection: vi.fn(),
+ dispose: vi.fn(),
+ } as any;
+
+ const provider = {
+ find: vi.fn(async () => [model]),
+ terminate: vi.fn(),
+ };
+
+ const injector = {
+ createInstance: vi.fn((_cls: any, _state: any, _providers: any) => {
+ return new FindReplaceModel(_state, _providers, univerInstanceService as any, commandService as any);
+ }),
+ };
+
+ const service = new FindReplaceService(injector as any, contextService as any);
+ service.registerFindReplaceProvider(provider as any);
+ expect(service.start(false)).toBe(true);
+
+ service.changeFindString('hello');
+ service.changeFindDirection(FindDirection.ROW);
+ service.changeFindScope(FindScope.SUBUNIT);
+ service.changeFindBy(FindBy.VALUE);
+
+ service.find();
+ // wait for provider find to resolve
+ await new Promise((r) => setTimeout(r, 0));
+
+ service.moveToNextMatch();
+ expect(service.getCurrentMatch()).toEqual(match1);
+
+ const replaceables = await new Promise<IFindMatch[]>((resolve) => {
+ service.replaceables$.subscribe((r) => {
+ if (r.length) resolve(r);
+ });
+ });
+ expect(replaceables).toEqual([match1]);
+
+ service.terminate();
+ service.dispose();
+ });
+});
diff --git a/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts b/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts
new file mode 100644
index 0000000000..7d1f4a6d86
--- /dev/null
+++ b/packages/network/src/services/http/implementations/__tests__/fetch.spec.ts
@@ -0,0 +1,96 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { HTTPHeaders } from '../../headers';
+import { HTTPRequest } from '../../request';
+import { FetchHTTPImplementation } from '../fetch';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('FetchHTTPImplementation', () => {
+ it('should emit HTTPResponse for json response', async () => {
+ const body = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode(JSON.stringify({ ok: true })));
+ controller.close();
+ },
+ });
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(body, {
+ status: 200,
+ headers: {
+ 'content-type': 'application/json',
+ 'content-length': '12',
+ },
+ })));
+
+ const impl = new FetchHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+ const req = new HTTPRequest('GET', 'https://example.com', {
+ responseType: 'json',
+ headers: new HTTPHeaders(),
+ withCredentials: false,
+ } as any);
+
+ const result = await new Promise<any>((resolve, reject) => {
+ impl.send(req).subscribe({
+ next: (e) => resolve(e),
+ error: reject,
+ });
+ });
+
+ expect(result.status).toBe(200);
+ expect(result.body).toEqual({ ok: true });
+ });
+
+ it('should emit HTTPProgress when reportProgress enabled for text', async () => {
+ const body = new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('a'));
+ controller.enqueue(new TextEncoder().encode('b'));
+ controller.close();
+ },
+ });
+
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(body, {
+ status: 200,
+ headers: { 'content-type': 'text/plain', 'content-length': '2' },
+ })));
+
+ const impl = new FetchHTTPImplementation({ debug: vi.fn(), error: vi.fn() } as any);
+ const req = new HTTPRequest('GET', 'https://example.com', {
+ responseType: 'text',
+ reportProgress: true,
+ headers: new HTTPHeaders(),
+ withCredentials: false,
+ } as any);
+
+ const events: any[] = [];
+ await new Promise<void>((resolve, reject) => {
+ impl.send(req).subscribe({
+ next: (e) => events.push(e),
+ error: reject,
+ complete: () => resolve(),
+ });
+ });
+
+ expect(events.some((e) => e.type === 0)).toBe(true);
+ expect(events.at(-1).body).toBe('ab');
+ });
+});
diff --git a/packages/rpc/src/services/rpc/__tests__/rpc.service.spec.ts b/packages/rpc/src/services/rpc/__tests__/rpc.service.spec.ts
index 85e69aee2e..5d98d30d32 100644
--- a/packages/rpc/src/services/rpc/__tests__/rpc.service.spec.ts
+++ b/packages/rpc/src/services/rpc/__tests__/rpc.service.spec.ts
@@ -14,8 +14,6 @@
* limitations under the License.
*/
-/* eslint-disable ts/no-explicit-any */
-
import type { Observable } from 'rxjs';
import type { IMessageProtocol } from '../rpc.service';
import { awaitTime } from '@univerjs/core';
@@ -70,7 +68,7 @@ describe('test ChannelClient & ChannelServer', () => {
server = new ChannelServer(serverProtocol);
});
- describe('test fromModule and toModule', async () => {
+ describe('test fromModule and toModule', () => {
it('should remote call work', async () => {
interface INameService {
getName(): Promise<string>;
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
new file mode 100644
index 0000000000..0144262db2
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/commands/commands/__tests__/add-conditional-formatting.command.spec.ts
@@ -0,0 +1,321 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, IRange } from '@univerjs/core';
+import { 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 { 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,
+ endRow: 3,
+ startColumn: 2,
+ 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,
+ },
+ });
+ });
+ });
+
+ it('supports both between and scalar number rules and rejects invalid inputs', () => {
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
+
+ const betweenAccessor = createAccessor();
+ expect(AddNumberCfCommand.handler(betweenAccessor.accessor, {
+ 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],
+ },
+ },
+ });
+
+ const scalarAccessor = createAccessor();
+ expect(AddNumberCfCommand.handler(scalarAccessor.accessor, {
+ 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',
+ rule: {
+ ranges: [range],
+ cfId: 'cf-1',
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ style: { cl: { rgb: '#222' } },
+ value: 99,
+ },
+ },
+ });
+
+ const invalidBetweenAccessor = createAccessor();
+ expect(AddNumberCfCommand.handler(invalidBetweenAccessor.accessor, {
+ ranges: [range],
+ operator: CFNumberOperator.between,
+ style: {},
+ value: [10],
+ } as never)).toBe(false);
+ expect(invalidBetweenAccessor.commandService.executeCommand).not.toHaveBeenCalled();
+
+ const invalidScalarAccessor = createAccessor();
+ expect(AddNumberCfCommand.handler(invalidScalarAccessor.accessor, {
+ ranges: [range],
+ operator: CFNumberOperator.lessThan,
+ style: {},
+ value: [1, 2],
+ } as never)).toBe(false);
+ expect(invalidScalarAccessor.commandService.executeCommand).not.toHaveBeenCalled();
+ });
+
+ it('returns false when params are missing or no active sheet target exists', () => {
+ const { accessor, commandService } = createAccessor();
+
+ expect(AddAverageCfCommand.handler(accessor, null as never)).toBe(false);
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+
+ mockedGetSheetCommandTarget.mockReturnValue(null as never);
+ expect(AddUniqueValuesCfCommand.handler(accessor, {
+ ranges: [range],
+ style: {},
+ } as never)).toBe(false);
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts b/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
new file mode 100644
index 0000000000..da7fd524b3
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
@@ -0,0 +1,197 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
+import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { ConditionalFormattingRuleModel } from '../../../models/conditional-formatting-rule-model';
+import { DeleteConditionalRuleMutation } from '../../mutations/delete-conditional-rule.mutation';
+import { SetConditionalRuleMutation } from '../../mutations/set-conditional-rule.mutation';
+import { ClearRangeCfCommand } from '../clear-range-cf.command';
+import { ClearWorksheetCfCommand } from '../clear-worksheet-cf.command';
+
+vi.mock('@univerjs/sheets', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets')>();
+
+ return {
+ ...actual,
+ getSheetCommandTarget: vi.fn(),
+ };
+});
+
+const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
+
+function createRuleModel() {
+ const ruleModel = new ConditionalFormattingRuleModel();
+
+ ruleModel.addRule('unit-1', 'sheet-1', {
+ cfId: 'rule-keep',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }],
+ stopIfTrue: false,
+ rule: {
+ type: 'highlightCell',
+ subType: 'text',
+ operator: 'containsText',
+ style: {},
+ value: 'todo',
+ },
+ } as never);
+
+ ruleModel.addRule('unit-1', 'sheet-1', {
+ cfId: 'rule-delete',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 }],
+ stopIfTrue: false,
+ rule: {
+ type: 'highlightCell',
+ subType: 'text',
+ operator: 'containsText',
+ style: {},
+ value: 'todo',
+ },
+ } as never);
+
+ return ruleModel;
+}
+
+function createAccessor(ruleModel: ConditionalFormattingRuleModel) {
+ const commandService = {
+ syncExecuteCommand: vi.fn(() => true),
+ };
+ const undoRedoService = {
+ pushUndoRedo: vi.fn(),
+ };
+ const selectionManagerService = {
+ getCurrentSelections: vi.fn(() => [{
+ range: { startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 },
+ }]),
+ };
+ const univerInstanceService = {};
+
+ const accessor = {
+ get(token: unknown) {
+ if (token === ConditionalFormattingRuleModel) {
+ return ruleModel;
+ }
+
+ if (token === ICommandService) {
+ return commandService;
+ }
+
+ if (token === IUndoRedoService) {
+ return undoRedoService;
+ }
+
+ if (token === SheetsSelectionsService) {
+ return selectionManagerService;
+ }
+
+ if (token === IUniverInstanceService) {
+ return univerInstanceService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return {
+ accessor,
+ commandService,
+ undoRedoService,
+ selectionManagerService,
+ };
+}
+
+describe('clear conditional formatting commands', () => {
+ it('clears the selected range, updates overlapping rules, and records undo/redo', () => {
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
+
+ const ruleModel = createRuleModel();
+ const { accessor, commandService, undoRedoService } = createAccessor(ruleModel);
+
+ expect(ClearRangeCfCommand.handler(accessor, { ranges: [{ startRow: 0, endRow: 0, startColumn: 2, endColumn: 2 }] })).toBe(true);
+
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(2);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, DeleteConditionalRuleMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cfId: 'rule-delete',
+ }, undefined);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, SetConditionalRuleMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ rule: {
+ cfId: 'rule-keep',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }],
+ stopIfTrue: false,
+ rule: {
+ type: 'highlightCell',
+ subType: 'text',
+ operator: 'containsText',
+ style: {},
+ value: 'todo',
+ },
+ },
+ }, undefined);
+ expect(undoRedoService.pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'unit-1',
+ redoMutations: expect.arrayContaining([
+ expect.objectContaining({ id: DeleteConditionalRuleMutation.id }),
+ expect.objectContaining({ id: SetConditionalRuleMutation.id }),
+ ]),
+ }));
+ });
+
+ it('clears every rule on the worksheet and records one delete per rule', () => {
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
+
+ const ruleModel = createRuleModel();
+ const { accessor, commandService, undoRedoService } = createAccessor(ruleModel);
+
+ expect(ClearWorksheetCfCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(true);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, DeleteConditionalRuleMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cfId: 'rule-delete',
+ }, undefined);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, DeleteConditionalRuleMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ cfId: 'rule-keep',
+ }, undefined);
+ expect(undoRedoService.pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'unit-1',
+ redoMutations: [
+ { id: DeleteConditionalRuleMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', cfId: 'rule-delete' } },
+ { id: DeleteConditionalRuleMutation.id, params: { unitId: 'unit-1', subUnitId: 'sheet-1', cfId: 'rule-keep' } },
+ ],
+ }));
+ });
+
+ it('returns false when the target, selection, or rules are missing', () => {
+ const ruleModel = new ConditionalFormattingRuleModel();
+ const { accessor, commandService, selectionManagerService } = createAccessor(ruleModel);
+
+ mockedGetSheetCommandTarget.mockReturnValue(null as never);
+ expect(ClearRangeCfCommand.handler(accessor, { ranges: [] })).toBe(false);
+ expect(ClearWorksheetCfCommand.handler(accessor, { unitId: 'unit-1', subUnitId: 'sheet-1' })).toBe(false);
+
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'unit-1', subUnitId: 'sheet-1' } as never);
+ selectionManagerService.getCurrentSelections.mockReturnValue([]);
+ expect(ClearRangeCfCommand.handler(accessor, { ranges: [] })).toBe(false);
+ expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts b/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts
new file mode 100644
index 0000000000..fc29cc1b3a
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/commands/commands/__tests__/data-validation-ui.command.spec.ts
@@ -0,0 +1,93 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+import { AddSheetDataValidationCommand, createDefaultNewRule } from '@univerjs/sheets-data-validation';
+import { describe, expect, it, vi } from 'vitest';
+import { OpenValidationPanelOperation } from '../../operations/data-validation.operation';
+import { AddSheetDataValidationAndOpenCommand } from '../data-validation-ui.command';
+
+vi.mock('@univerjs/sheets', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets')>();
+ return { ...actual, getSheetCommandTarget: vi.fn() };
+});
+
+vi.mock('@univerjs/sheets-data-validation', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets-data-validation')>();
+ return { ...actual, createDefaultNewRule: vi.fn() };
+});
+
+const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
+const mockedCreateDefaultNewRule = vi.mocked(createDefaultNewRule);
+
+function createAccessor() {
+ const commandService = { syncExecuteCommand: vi.fn(() => true) };
+ const accessor = {
+ get(token: unknown) {
+ if (token === IUniverInstanceService) {
+ return {};
+ }
+
+ if (token === ICommandService) {
+ return commandService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return { accessor, commandService };
+}
+
+describe('AddSheetDataValidationAndOpenCommand', () => {
+ it('adds a default rule for the current sheet and opens the panel for that rule', () => {
+ mockedCreateDefaultNewRule.mockReturnValue({ uid: 'rule-1' } as never);
+ mockedGetSheetCommandTarget.mockReturnValue({
+ workbook: { getUnitId: () => 'book-1' },
+ worksheet: { getSheetId: () => 'sheet-1' },
+ } as never);
+ const { accessor, commandService } = createAccessor();
+
+ expect(AddSheetDataValidationAndOpenCommand.handler(accessor)).toBe(true);
+ expect(mockedCreateDefaultNewRule).toHaveBeenCalledWith(accessor);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, AddSheetDataValidationCommand.id, {
+ rule: { uid: 'rule-1' },
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ });
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, OpenValidationPanelOperation.id, {
+ ruleId: 'rule-1',
+ isAdd: true,
+ });
+ });
+
+ it('returns false when there is no active target or adding the rule fails', () => {
+ const { accessor, commandService } = createAccessor();
+ mockedCreateDefaultNewRule.mockReturnValue({ uid: 'rule-2' } as never);
+ mockedGetSheetCommandTarget.mockReturnValue(null as never);
+ expect(AddSheetDataValidationAndOpenCommand.handler(accessor)).toBe(false);
+
+ mockedGetSheetCommandTarget.mockReturnValue({
+ workbook: { getUnitId: () => 'book-1' },
+ worksheet: { getSheetId: () => 'sheet-1' },
+ } as never);
+ commandService.syncExecuteCommand.mockReturnValue(false);
+ expect(AddSheetDataValidationAndOpenCommand.handler(accessor)).toBe(false);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts b/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts
new file mode 100644
index 0000000000..41e9ee081b
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/commands/operations/__tests__/data-validation.operation.spec.ts
@@ -0,0 +1,146 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import type { IDataValidationDropdownParam } from '../../../services/dropdown-manager.service';
+import { ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { DataValidationModel } from '@univerjs/data-validation';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+import { ISidebarService } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { DataValidationPanelService } from '../../../services/data-validation-panel.service';
+import { DataValidationDropdownManagerService } from '../../../services/dropdown-manager.service';
+import {
+ CloseValidationPanelOperation,
+ DATA_VALIDATION_PANEL,
+ HideDataValidationDropdown,
+ OpenValidationPanelOperation,
+ ShowDataValidationDropdown,
+ ToggleValidationPanelOperation,
+} from '../data-validation.operation';
+
+vi.mock('@univerjs/sheets', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets')>();
+ return { ...actual, getSheetCommandTarget: vi.fn() };
+});
+
+const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
+
+function createAccessor() {
+ const commandService = { executeCommand: vi.fn() };
+ const panelService = {
+ open: vi.fn(),
+ close: vi.fn(),
+ setActiveRule: vi.fn(),
+ setCloseDisposable: vi.fn(),
+ isOpen: false,
+ };
+ const rule = { uid: 'rule-1' };
+ const dropdownService: {
+ activeDropdown: IDataValidationDropdownParam | null;
+ showDataValidationDropdown: ReturnType<typeof vi.fn>;
+ hideDropdown: ReturnType<typeof vi.fn>;
+ } = {
+ activeDropdown: null,
+ showDataValidationDropdown: vi.fn(),
+ hideDropdown: vi.fn(),
+ };
+ const sidebarService = {
+ open: vi.fn(() => ({ dispose: vi.fn() })),
+ };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ICommandService) return commandService;
+ if (token === DataValidationPanelService) return panelService;
+ if (token === DataValidationModel) return { getRuleById: vi.fn(() => rule) };
+ if (token === IUniverInstanceService) return {};
+ if (token === ISidebarService) return sidebarService;
+ if (token === DataValidationDropdownManagerService) return dropdownService;
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return { accessor, commandService, panelService, dropdownService, sidebarService, rule };
+}
+
+describe('data validation operations', () => {
+ it('opens the validation panel for the active sheet rule and wires close disposal', () => {
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'book-1', subUnitId: 'sheet-1' } as never);
+ const { accessor, panelService, sidebarService, rule } = createAccessor();
+
+ expect(OpenValidationPanelOperation.handler(accessor, { ruleId: 'rule-1', isAdd: true })).toBe(true);
+ expect(panelService.open).toHaveBeenCalledTimes(1);
+ expect(panelService.setActiveRule).toHaveBeenCalledWith({ unitId: 'book-1', subUnitId: 'sheet-1', rule });
+ expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ id: DATA_VALIDATION_PANEL,
+ header: { title: 'dataValidation.panel.addTitle' },
+ children: { label: DATA_VALIDATION_PANEL },
+ width: 312,
+ }));
+ expect(panelService.setCloseDisposable).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes and toggles the panel through the command service', () => {
+ const { accessor, panelService, commandService } = createAccessor();
+
+ expect(CloseValidationPanelOperation.handler(accessor)).toBe(true);
+ expect(panelService.close).toHaveBeenCalledTimes(1);
+
+ panelService.isOpen = true;
+ expect(ToggleValidationPanelOperation.handler(accessor)).toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(CloseValidationPanelOperation.id);
+
+ panelService.isOpen = false;
+ ToggleValidationPanelOperation.handler(accessor);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(OpenValidationPanelOperation.id);
+ });
+
+ it('shows and hides dropdowns only when location changes, and guards invalid params', () => {
+ const { accessor, dropdownService } = createAccessor();
+
+ expect(ShowDataValidationDropdown.handler(accessor, null as never)).toBe(false);
+ expect(HideDataValidationDropdown.handler(accessor, null as never)).toBe(false);
+
+ expect(ShowDataValidationDropdown.handler(accessor, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ column: 2,
+ })).toBe(true);
+ expect(dropdownService.showDataValidationDropdown).toHaveBeenCalledWith('book-1', 'sheet-1', 1, 2);
+
+ dropdownService.activeDropdown = { location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2 } } as unknown as IDataValidationDropdownParam;
+ ShowDataValidationDropdown.handler(accessor, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ column: 2,
+ });
+ expect(dropdownService.showDataValidationDropdown).toHaveBeenCalledTimes(1);
+
+ expect(HideDataValidationDropdown.handler(accessor, { ok: true } as never)).toBe(true);
+ expect(dropdownService.hideDropdown).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns false when there is no active sheet target or no params', () => {
+ const { accessor, panelService } = createAccessor();
+ mockedGetSheetCommandTarget.mockReturnValue(null as never);
+
+ expect(OpenValidationPanelOperation.handler(accessor, { ruleId: 'rule-1' })).toBe(false);
+ expect(OpenValidationPanelOperation.handler(accessor, null as never)).toBe(false);
+ expect(panelService.open).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts
new file mode 100644
index 0000000000..1a5a578c7e
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-alert.controller.spec.ts
@@ -0,0 +1,95 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DataValidationStatus } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DataValidationAlertController } from '../dv-alert.controller';
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('DataValidationAlertController', () => {
+ it('shows an alert for invalid hovered cells and clears it when repeated or zen mode opens', async () => {
+ vi.useFakeTimers();
+ const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
+ const visible$ = new Subject<boolean>();
+ const currentAlert = new Map<string, { alert: { location: { unitId: string; subUnitId: string; row: number; col: number } } }>();
+ const showAlert = vi.fn((alert) => currentAlert.set('SHEET_DATA_VALIDATION_ALERT', { alert }));
+ const removeAlert = vi.fn((key: string) => currentAlert.delete(key));
+ const dataValidationModel = {
+ getRuleByLocation: vi.fn(() => ({ uid: 'rule-1', type: 'list' })),
+ validator: vi.fn(() => DataValidationStatus.INVALID),
+ getValidator: vi.fn(() => ({ getRuleFinalError: vi.fn(() => 'invalid list value') })),
+ };
+
+ const controller = new DataValidationAlertController(
+ { currentCell$ } as never,
+ { currentAlert, removeAlert, showAlert } as never,
+ { getUnit: vi.fn(() => ({ getSheetBySheetId: vi.fn(() => ({ getSheetId: () => 'sheet-1' })) })) } as never,
+ { t: (key: string) => key } as never,
+ { visible$ } as never,
+ dataValidationModel as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ const location = { unitId: 'book-1', subUnitId: 'sheet-1', row: 1, col: 2 };
+ currentCell$.next({ location });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(showAlert).toHaveBeenCalledWith(expect.objectContaining({
+ key: 'SHEET_DATA_VALIDATION_ALERT',
+ title: 'dataValidation.error.title',
+ message: 'invalid list value',
+ location,
+ }));
+
+ currentCell$.next({ location });
+ await vi.advanceTimersByTimeAsync(120);
+ expect(removeAlert).toHaveBeenCalledWith('SHEET_DATA_VALIDATION_ALERT');
+
+ visible$.next(true);
+ expect(removeAlert).toHaveBeenCalledWith('SHEET_DATA_VALIDATION_ALERT');
+ });
+
+ it('removes alerts when the hovered cell has no validation rule', async () => {
+ vi.useFakeTimers();
+ const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
+ const removeAlert = vi.fn();
+
+ const controller = new DataValidationAlertController(
+ { currentCell$ } as never,
+ { currentAlert: new Map(), removeAlert, showAlert: vi.fn() } as never,
+ { getUnit: vi.fn(() => ({ getSheetBySheetId: vi.fn(() => ({ getSheetId: () => 'sheet-1' })) })) } as never,
+ { t: (key: string) => key } as never,
+ { visible$: new Subject<boolean>() } as never,
+ {
+ getRuleByLocation: vi.fn(() => null),
+ validator: vi.fn(),
+ getValidator: vi.fn(),
+ } as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ currentCell$.next({ location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 3, col: 4 } });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(removeAlert).toHaveBeenCalledWith('SHEET_DATA_VALIDATION_ALERT');
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts
new file mode 100644
index 0000000000..38d9137ecd
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts
@@ -0,0 +1,133 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DataValidationType } from '@univerjs/core';
+import { AUTO_FILL_APPLY_TYPE, AutoFillTools } from '@univerjs/sheets';
+import { DATA_VALIDATION_PLUGIN_NAME, getDataValidationDiffMutations } from '@univerjs/sheets-data-validation';
+import { virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { DataValidationAutoFillController } from '../dv-auto-fill.controller';
+
+vi.mock('@univerjs/sheets-ui', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets-ui')>();
+ return {
+ ...actual,
+ virtualizeDiscreteRanges: vi.fn(() => ({
+ ranges: [
+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },
+ { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1 },
+ ],
+ mapFunc: (row: number, col: number) => ({ row, col }),
+ })),
+ };
+});
+
+vi.mock('@univerjs/sheets-data-validation', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets-data-validation')>();
+ return {
+ ...actual,
+ getDataValidationDiffMutations: vi.fn(() => ({ redoMutations: ['redo-dv'], undoMutations: ['undo-dv'] })),
+ };
+});
+
+vi.mock('@univerjs/sheets', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets')>();
+ return {
+ ...actual,
+ AutoFillTools: {
+ ...actual.AutoFillTools,
+ getAutoFillRepeatRange: vi.fn(() => [{
+ repeatStartCell: { row: 1, col: 1 },
+ relativeRange: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ }]),
+ },
+ };
+});
+
+describe('DataValidationAutoFillController', () => {
+ it('registers a hook and disables series fill when checkbox validation exists in source cells', () => {
+ let hook: { id: string; onBeforeFillData: (location: { unitId: string; subUnitId: string; source: { rows: number[]; cols: number[] } }) => void } | undefined;
+ const autoFillService = {
+ addHook: vi.fn((registeredHook) => {
+ hook = registeredHook;
+ return { dispose: vi.fn() };
+ }),
+ setDisableApplyType: vi.fn(),
+ };
+
+ const controller = new DataValidationAutoFillController(
+ autoFillService as never,
+ {
+ getRuleByLocation: vi.fn(() => ({ type: DataValidationType.CHECKBOX })),
+ } as never,
+ {} as never
+ );
+
+ expect(controller).toBeTruthy();
+ expect(hook?.id).toBe(DATA_VALIDATION_PLUGIN_NAME);
+
+ hook!.onBeforeFillData({
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ source: { rows: [0], cols: [0] },
+ });
+
+ expect(autoFillService.setDisableApplyType).toHaveBeenCalledWith(AUTO_FILL_APPLY_TYPE.SERIES, true);
+ });
+
+ it('builds diff mutations for copy and format autofill, and skips unsupported apply types', () => {
+ let hook: { onFillData: (location: { unitId: string; subUnitId: string; source: { rows: number[]; cols: number[]; startRow: number; endRow: number; startColumn: number; endColumn: number }; target: { rows: number[]; cols: number[]; startRow: number; endRow: number; startColumn: number; endColumn: number } }, direction: unknown, applyType: AUTO_FILL_APPLY_TYPE) => { redos: unknown[]; undos: unknown[] } } | undefined;
+ const ruleMatrixCopy = {
+ addRangeRules: vi.fn(),
+ diff: vi.fn(() => 'diffs'),
+ };
+
+ const controller = new DataValidationAutoFillController(
+ {
+ addHook: vi.fn((registeredHook) => {
+ hook = registeredHook;
+ return { dispose: vi.fn() };
+ }),
+ setDisableApplyType: vi.fn(),
+ } as never,
+ {
+ getRuleByLocation: vi.fn(() => null),
+ getRuleObjectMatrix: vi.fn(() => ({ clone: vi.fn(() => ruleMatrixCopy) })),
+ getRuleIdByLocation: vi.fn(() => 'rule-1'),
+ getRules: vi.fn(() => ['existing-rule']),
+ } as never,
+ {} as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ const location = {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ source: { rows: [0], cols: [0], startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },
+ target: { rows: [1], cols: [1], startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ };
+ const result = hook!.onFillData(location, 'down', AUTO_FILL_APPLY_TYPE.ONLY_FORMAT);
+
+ expect(vi.mocked(virtualizeDiscreteRanges)).toHaveBeenCalledWith([location.source, location.target]);
+ expect(vi.mocked(AutoFillTools.getAutoFillRepeatRange)).toHaveBeenCalled();
+ expect(ruleMatrixCopy.addRangeRules).toHaveBeenCalledWith([{ id: 'rule-1', ranges: [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }] }]);
+ expect(vi.mocked(getDataValidationDiffMutations)).toHaveBeenCalledWith('book-1', 'sheet-1', 'diffs', {}, 'patched', true);
+ expect(result).toEqual({ redos: ['redo-dv'], undos: ['undo-dv'] });
+
+ expect(hook!.onFillData(location, 'down', AUTO_FILL_APPLY_TYPE.NO_FORMAT)).toEqual({ redos: [], undos: [] });
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-permission.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-permission.controller.spec.ts
new file mode 100644
index 0000000000..e9c481ba82
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-permission.controller.spec.ts
@@ -0,0 +1,62 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { AddSheetDataValidationCommand, UpdateSheetDataValidationRangeCommand } from '@univerjs/sheets-data-validation';
+import { describe, expect, it, vi } from 'vitest';
+import { DataValidationPermissionController } from '../dv-permission.controller';
+
+describe('DataValidationPermissionController', () => {
+ it('blocks add/update commands when range permissions fail', () => {
+ let beforeCommandExecutedHandler: ((command: { id: string; params: unknown }) => void) | undefined;
+ const permissionCheckWithRanges = vi.fn()
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(false);
+ const blockExecuteWithoutPermission = vi.fn();
+
+ const controller = new DataValidationPermissionController(
+ { t: (key: string) => key } as never,
+ {
+ beforeCommandExecuted: vi.fn((handler) => {
+ beforeCommandExecutedHandler = handler;
+ return { dispose: vi.fn() };
+ }),
+ } as never,
+ { permissionCheckWithRanges, blockExecuteWithoutPermission } as never
+ );
+
+ expect(controller).toBeTruthy();
+ beforeCommandExecutedHandler!({
+ id: AddSheetDataValidationCommand.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ rule: { ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 }] },
+ },
+ });
+ beforeCommandExecutedHandler!({
+ id: UpdateSheetDataValidationRangeCommand.id,
+ params: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ ranges: [{ startRow: 2, endRow: 3, startColumn: 0, endColumn: 1 }],
+ },
+ });
+
+ expect(permissionCheckWithRanges).toHaveBeenCalledTimes(2);
+ expect(blockExecuteWithoutPermission).toHaveBeenCalledTimes(2);
+ expect(blockExecuteWithoutPermission).toHaveBeenCalledWith('permission.dialog.setStyleErr');
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts
new file mode 100644
index 0000000000..9c57289e15
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-reject-input.controller.spec.ts
@@ -0,0 +1,93 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { LocaleService } from '@univerjs/core';
+import type { DataValidatorRegistryService } from '@univerjs/data-validation';
+import type { SheetInterceptorService } from '@univerjs/sheets';
+import type { SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
+import type { IDialogService } from '@univerjs/ui';
+import { DataValidationErrorStyle, DataValidationStatus } from '@univerjs/core';
+import { VALIDATE_CELL } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { DataValidationRejectInputController } from '../dv-reject-input.controller';
+
+interface IInterceptContext {
+ row: number;
+ col: number;
+ unitId: string;
+ subUnitId: string;
+}
+
+describe('DataValidationRejectInputController', () => {
+ it('intercepts invalid STOP rules and opens a reject dialog, while allowing valid cases through', async () => {
+ let interceptedHandler:
+ | ((lastResult: Promise<boolean>, context: IInterceptContext, next: (value: Promise<boolean>) => Promise<boolean>) => Promise<boolean>)
+ | undefined;
+ const open = vi.fn();
+ const close = vi.fn();
+ const getRuleById = vi.fn(() => ({ type: 'list', errorStyle: DataValidationErrorStyle.STOP }));
+ const model = {
+ getRuleIdByLocation: vi.fn(() => 'rule-1'),
+ getRuleById,
+ };
+ const validator = { getRuleFinalError: vi.fn(() => 'Invalid value') };
+ const controller = new DataValidationRejectInputController(
+ {
+ writeCellInterceptor: {
+ intercept: vi.fn((name, config) => {
+ expect(name).toBe(VALIDATE_CELL);
+ interceptedHandler = config.handler;
+ return { dispose: vi.fn() };
+ }),
+ },
+ } as unknown as SheetInterceptorService,
+ model as unknown as SheetDataValidationModel,
+ { getValidatorItem: vi.fn(() => validator) } as unknown as DataValidatorRegistryService,
+ { open, close } as unknown as IDialogService,
+ { t: (key: string) => key } as LocaleService,
+ {
+ validatorCell: vi.fn()
+ .mockResolvedValueOnce(DataValidationStatus.INVALID)
+ .mockResolvedValueOnce(DataValidationStatus.VALID),
+ } as unknown as SheetsDataValidationValidatorService
+ );
+
+ expect(controller).toBeTruthy();
+ expect(interceptedHandler).toBeDefined();
+
+ const next = (value: Promise<boolean>) => value;
+ const context: IInterceptContext = { row: 1, col: 2, unitId: 'book-1', subUnitId: 'sheet-1' };
+
+ await expect(interceptedHandler!(Promise.resolve(false), context, next)).resolves.toBe(false);
+ expect(open).not.toHaveBeenCalled();
+
+ await expect(interceptedHandler!(Promise.resolve(true), context, next)).resolves.toBe(false);
+ expect(open).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'reject-input-dialog',
+ children: { title: 'Invalid value' },
+ }));
+
+ await expect(interceptedHandler!(Promise.resolve(true), context, next)).resolves.toBe(true);
+
+ getRuleById.mockReturnValue({ type: 'list', errorStyle: DataValidationErrorStyle.WARNING });
+ await expect(interceptedHandler!(Promise.resolve(true), context, next)).resolves.toBe(true);
+
+ controller.showReject('Bad input');
+ expect(open).toHaveBeenLastCalledWith(expect.objectContaining({
+ children: { title: 'Bad input' },
+ }));
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-rerender.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-rerender.controller.spec.ts
new file mode 100644
index 0000000000..81ce416017
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-rerender.controller.spec.ts
@@ -0,0 +1,51 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsDataValidationReRenderController } from '../dv-rerender.controller';
+
+describe('SheetsDataValidationReRenderController', () => {
+ it('marks affected skeletons dirty and forces a rerender when validation status changes', async () => {
+ const validStatusChange$ = new Subject<{ subUnitId: string }>();
+ const makeDirty1 = vi.fn();
+ const makeDirty2 = vi.fn();
+ const makeForceDirty = vi.fn();
+
+ const controller = new SheetsDataValidationReRenderController(
+ { mainComponent: { makeForceDirty } } as never,
+ { validStatusChange$ } as never,
+ {
+ getSkeletonParam: vi.fn((sheetId: string) => {
+ if (sheetId === 'sheet-1') return { skeleton: { makeDirty: makeDirty1 } };
+ if (sheetId === 'sheet-2') return { skeleton: { makeDirty: makeDirty2 } };
+ return undefined;
+ }),
+ } as never
+ );
+
+ validStatusChange$.next({ subUnitId: 'sheet-1' });
+ validStatusChange$.next({ subUnitId: 'sheet-2' });
+ validStatusChange$.next({ subUnitId: 'sheet-1' });
+ expect(controller).toBeTruthy();
+
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ expect(makeDirty1).toHaveBeenCalledTimes(1);
+ expect(makeDirty2).toHaveBeenCalledTimes(1);
+ expect(makeForceDirty).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-ui.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-ui.controller.spec.ts
new file mode 100644
index 0000000000..7634b1ff05
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-ui.controller.spec.ts
@@ -0,0 +1,88 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Injector } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { DATA_VALIDATION_PANEL } from '../../commands/operations/data-validation.operation';
+import {
+ BASE_FORMULA_INPUT_NAME,
+ CHECKBOX_FORMULA_INPUT_NAME,
+ CUSTOM_FORMULA_INPUT_NAME,
+ LIST_FORMULA_INPUT_NAME,
+} from '../../views/components/formula-input';
+import { SheetsDataValidationUIController } from '../dv-ui.controller';
+
+vi.hoisted(() => {
+ Object.assign(globalThis, {
+ Path2D: class Path2D {},
+ });
+});
+
+const FORMULA_INPUT_KEYS = [
+ CUSTOM_FORMULA_INPUT_NAME,
+ BASE_FORMULA_INPUT_NAME,
+ LIST_FORMULA_INPUT_NAME,
+ CHECKBOX_FORMULA_INPUT_NAME,
+];
+
+function createView(id: string) {
+ return {
+ id,
+ formulaInput: `${id}-formula`,
+ canvasRender: `${id}-canvas`,
+ dropdownType: `${id}-dropdown`,
+ optionsInput: `${id}-options`,
+ };
+}
+
+describe('SheetsDataValidationUIController', () => {
+ it('registers panel components and wires validator views into the registry', () => {
+ const register = vi.fn((_key: string) => ({ dispose: vi.fn() }));
+ const validators = new Map<string, Record<string, unknown>>();
+ const createInstance = vi.fn((viewCtor: { name: string }) => createView(viewCtor.name));
+ const getValidatorItem = vi.fn((id: string) => {
+ if (!validators.has(id)) {
+ validators.set(id, {});
+ }
+ return validators.get(id);
+ });
+
+ const controller = new SheetsDataValidationUIController(
+ { createInstance } as unknown as Injector,
+ { register } as never,
+ { getValidatorItem } as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ const registeredKeys = register.mock.calls.map((args) => args[0]);
+ expect(registeredKeys).toContain('DataValidationIcon');
+ expect(registeredKeys).toContain(DATA_VALIDATION_PANEL);
+ expect(registeredKeys).toContain('LIST_RENDER_MODE_OPTION_INPUT');
+ expect(registeredKeys).toContain('DATE_SHOW_TIME_OPTION');
+ FORMULA_INPUT_KEYS.forEach((key) => expect(registeredKeys).toContain(key));
+
+ ['DecimalValidatorView', 'WholeValidatorView', 'TextLengthValidatorView', 'DateValidatorView', 'CheckboxValidatorView', 'ListValidatorView', 'ListMultipleValidatorView', 'CustomFormulaValidatorView'].forEach((viewName) => {
+ expect(createInstance).toHaveBeenCalledWith(expect.objectContaining({ name: viewName }));
+ expect(validators.get(viewName)).toEqual({
+ formulaInput: `${viewName}-formula`,
+ canvasRender: `${viewName}-canvas`,
+ dropdownType: `${viewName}-dropdown`,
+ optionsInput: `${viewName}-options`,
+ });
+ });
+ });
+});
diff --git a/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts b/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts
new file mode 100644
index 0000000000..5675ebc10c
--- /dev/null
+++ b/packages/sheets-data-validation-ui/src/services/__tests__/dropdown-manager.service.spec.ts
@@ -0,0 +1,193 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISelectionWithStyle, SheetsSelectionsService } from '@univerjs/sheets';
+import type { SheetDataValidationModel } from '@univerjs/sheets-data-validation';
+import type { IDropdownParam, IEditorBridgeService } from '@univerjs/sheets-ui';
+import { DataValidationRenderMode } from '@univerjs/core';
+import { DataValidatorDropdownType } from '@univerjs/data-validation';
+import { SetRangeValuesCommand } from '@univerjs/sheets';
+import { serializeListOptions } from '@univerjs/sheets-data-validation';
+import { SetCellEditVisibleOperation } from '@univerjs/sheets-ui';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { OpenValidationPanelOperation } from '../../commands/operations/data-validation.operation';
+import { SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
+import { DataValidationDropdownManagerService } from '../dropdown-manager.service';
+
+describe('DataValidationDropdownManagerService', () => {
+ it('shows a list dropdown, saves the selection, opens the editor, and reacts to hide triggers', async () => {
+ const zenVisible$ = new Subject<boolean>();
+ const selectionMoveEnd$ = new Subject<ISelectionWithStyle[]>();
+ const popupDispose = vi.fn();
+ let dropdownParam: IDropdownParam | undefined;
+ const onHide = vi.fn();
+
+ const worksheet = {
+ getSheetId: () => 'sheet-1',
+ getCellRaw: () => ({ v: 'Open' }),
+ };
+ const workbook = {
+ getUnitId: () => 'book-1',
+ getSheetBySheetId: () => worksheet,
+ };
+ const rule = {
+ uid: 'rule-1',
+ type: 'list',
+ renderMode: DataValidationRenderMode.CUSTOM,
+ };
+
+ const service = new DataValidationDropdownManagerService(
+ {
+ getUnit: () => workbook,
+ } as never,
+ {
+ getValidatorItem: vi.fn(() => ({
+ dropdownType: DataValidatorDropdownType.LIST,
+ getListWithColor: vi.fn(() => [
+ { label: 'Open', color: '#0f0' },
+ { label: 'Closed', color: '#f00' },
+ ]),
+ })),
+ } as never,
+ {
+ visible$: zenVisible$,
+ } as never,
+ {
+ getRuleByLocation: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {
+ if (unitId === 'book-1' && subUnitId === 'sheet-1' && row === 1 && col === 2) {
+ return rule;
+ }
+
+ return null;
+ }),
+ } as never,
+ {
+ selectionMoveEnd$,
+ } as unknown as SheetsSelectionsService,
+ {
+ showDropdown: vi.fn((param: IDropdownParam) => {
+ dropdownParam = param;
+
+ return {
+ dispose: popupDispose,
+ };
+ }),
+ } as never,
+ {
+ getRuleByLocation: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {
+ if (unitId === 'book-1' && subUnitId === 'sheet-1' && row === 1 && col === 2) {
+ return rule;
+ }
+
+ return null;
+ }),
+ } as unknown as SheetDataValidationModel,
+ {
+ executeCommand: vi.fn(() => Promise.resolve(true)),
+ } as never,
+ {
+ isVisible: () => ({ visible: true }),
+ } as IEditorBridgeService,
+ {
+ has: () => false,
+ } as never,
+ {
+ getConfig: vi.fn((key: string) => key === SHEETS_DATA_VALIDATION_UI_PLUGIN_CONFIG_KEY
+ ? { showEditOnDropdown: true, showSearchOnDropdown: false }
+ : undefined),
+ } as never
+ );
+
+ service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2, onHide);
+
+ expect(dropdownParam).toEqual(expect.objectContaining({
+ type: 'list',
+ location: expect.objectContaining({
+ row: 1,
+ col: 2,
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ workbook,
+ worksheet,
+ }),
+ props: expect.objectContaining({
+ defaultValue: 'Open',
+ multiple: false,
+ showEdit: true,
+ showSearch: false,
+ options: [
+ { label: 'Open', value: 'Open', color: '#0f0' },
+ { label: 'Closed', value: 'Closed', color: '#f00' },
+ ],
+ }),
+ }));
+ expect(service.activeDropdown).toEqual(expect.objectContaining({ location: expect.objectContaining({ row: 1, col: 2 }) }));
+
+ const listProps = dropdownParam?.props as {
+ onChange?: (value: string[]) => Promise<boolean>;
+ onEdit?: () => void;
+ } | undefined;
+
+ await listProps?.onChange?.(['Closed']);
+
+ const commandService = (service as unknown as { _commandService: { executeCommand: ReturnType<typeof vi.fn> } })._commandService;
+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(1, SetRangeValuesCommand.id, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ range: {
+ startColumn: 2,
+ endColumn: 2,
+ startRow: 1,
+ endRow: 1,
+ },
+ value: {
+ v: serializeListOptions(['Closed']),
+ p: null,
+ f: null,
+ si: null,
+ },
+ });
+ expect(commandService.executeCommand).toHaveBeenNthCalledWith(2, SetCellEditVisibleOperation.id, expect.objectContaining({
+ visible: false,
+ unitId: 'book-1',
+ }));
+
+ listProps?.onEdit?.();
+ expect(commandService.executeCommand).toHaveBeenCalledWith(OpenValidationPanelOperation.id, { ruleId: 'rule-1' });
+ expect(popupDispose).toHaveBeenCalledTimes(1);
+
+ selectionMoveEnd$.next([
+ {
+ primary: {
+ unitId: 'book-1',
+ sheetId: 'sheet-1',
+ actualRow: 9,
+ actualColumn: 9,
+ },
+ },
+ ] as never);
+ expect(service.activeDropdown).toBeNull();
+
+ service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2, onHide);
+ zenVisible$.next(true);
+ expect(service.activeDropdown).toBeNull();
+
+ service.showDataValidationDropdown('book-1', 'sheet-1', 1, 2, onHide);
+ service.hideDropdown();
+ expect(onHide).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.ts
new file mode 100644
index 0000000000..fb631917f3
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/delete-drawings.command.spec.ts
@@ -0,0 +1,58 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import { ISheetDrawingService } from '@univerjs/sheets-drawing';
+import { describe, expect, it, vi } from 'vitest';
+import { DeleteDrawingsCommand } from '../delete-drawings.command';
+import { RemoveSheetDrawingCommand } from '../remove-sheet-drawing.command';
+
+describe('DeleteDrawingsCommand', () => {
+ it('forwards focused drawings to the remove command', async () => {
+ const commandService = { executeCommand: vi.fn(() => true) };
+ const drawingManagerService = {
+ getFocusDrawings: vi.fn(() => [
+ { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1', drawingType: 'image' },
+ ]),
+ };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ICommandService) return commandService;
+ if (token === ISheetDrawingService) return drawingManagerService;
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ expect(await DeleteDrawingsCommand.handler(accessor)).toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(RemoveSheetDrawingCommand.id, {
+ unitId: 'book-1',
+ drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1', drawingType: 'image' }],
+ });
+ });
+
+ it('returns false when nothing is focused', async () => {
+ const accessor = {
+ get(token: unknown) {
+ if (token === ICommandService) return { executeCommand: vi.fn() };
+ if (token === ISheetDrawingService) return { getFocusDrawings: () => [] };
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ expect(await DeleteDrawingsCommand.handler(accessor)).toBe(false);
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
new file mode 100644
index 0000000000..104ce0662b
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts
@@ -0,0 +1,270 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ArrangeTypeEnum, Direction, DrawingTypeEnum, ICommandService, IUndoRedoService } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SheetInterceptorService } from '@univerjs/sheets';
+import { DrawingApplyType, ISheetDrawingService, SetDrawingApplyMutation } from '@univerjs/sheets-drawing';
+import { ISheetSelectionRenderService } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { ClearSheetDrawingTransformerOperation } from '../../operations/clear-drawing-transformer.operation';
+import { FlipSheetDrawingCommand } from '../flip-drawings.command';
+import { InsertSheetDrawingCommand } from '../insert-sheet-drawing.command';
+import { MoveDrawingsCommand } from '../move-drawings.command';
+import { RemoveSheetDrawingCommand } from '../remove-sheet-drawing.command';
+import { SetDrawingArrangeCommand } from '../set-drawing-arrange.command';
+import { SetSheetDrawingCommand } from '../set-sheet-drawing.command';
+
+function createSelectionRenderService() {
+ return {
+ getCellWithCoordByOffset(left: number, top: number) {
+ const actualColumn = Math.floor(left / 10);
+ const actualRow = Math.floor(top / 10);
+
+ return {
+ actualColumn,
+ actualRow,
+ startX: actualColumn * 10,
+ startY: actualRow * 10,
+ };
+ },
+ };
+}
+
+function createAccessor() {
+ const commandService = { syncExecuteCommand: vi.fn(() => true) };
+ const pushUndoRedo = vi.fn();
+ const selectionRenderService = createSelectionRenderService();
+ const sheetDrawingService = {
+ getForwardDrawingsOp: vi.fn(() => ({ redo: ['redo-forward'], undo: ['undo-forward'], objects: ['shape-1'] })),
+ getBackwardDrawingOp: vi.fn(() => ({ redo: ['redo-backward'], undo: ['undo-backward'], objects: ['shape-1'] })),
+ getFrontDrawingsOp: vi.fn(() => ({ redo: ['redo-front'], undo: ['undo-front'], objects: ['shape-1'] })),
+ getBackDrawingsOp: vi.fn(() => ({ redo: ['redo-back'], undo: ['undo-back'], objects: ['shape-1'] })),
+ getBatchRemoveOp: vi.fn(() => ({ unitId: 'book-1', subUnitId: 'sheet-1', redo: ['remove-redo'], undo: ['remove-undo'], objects: ['shape-1'] })),
+ getBatchAddOp: vi.fn(() => ({ unitId: 'book-1', subUnitId: 'sheet-1', redo: ['add-redo'], undo: ['add-undo'], objects: ['shape-2'] })),
+ getBatchUpdateOp: vi.fn(() => ({ unitId: 'book-1', subUnitId: 'sheet-1', redo: ['update-redo'], undo: ['update-undo'], objects: ['shape-1'] })),
+ getDrawingData: vi.fn(() => ({
+ 'shape-1': {
+ drawingId: 'shape-1',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ transform: { left: 10, top: 20, flipX: false, flipY: false },
+ },
+ })),
+ getFocusDrawings: vi.fn(() => [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-1', transform: { left: 10, top: 20 } }]),
+ };
+ const renderManagerService = {
+ getRenderById: vi.fn(() => ({
+ scene: null,
+ with: vi.fn((token: unknown) => (token === ISheetSelectionRenderService ? selectionRenderService : null)),
+ })),
+ };
+ const sheetInterceptorService = {
+ onCommandExecute: vi.fn(() => ({
+ preRedos: [{ id: 'pre-redo', params: { ok: true } }],
+ redos: [{ id: 'redo-extra', params: { ok: true } }],
+ preUndos: [{ id: 'pre-undo', params: { ok: true } }],
+ undos: [{ id: 'undo-extra', params: { ok: true } }],
+ })),
+ };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ICommandService) {
+ return commandService;
+ }
+
+ if (token === IUndoRedoService) {
+ return { pushUndoRedo };
+ }
+
+ if (token === ISheetDrawingService) {
+ return sheetDrawingService;
+ }
+
+ if (token === SheetInterceptorService) {
+ return sheetInterceptorService;
+ }
+
+ if (token === ISheetSelectionRenderService) {
+ return selectionRenderService;
+ }
+
+ if (token === IRenderManagerService) {
+ return renderManagerService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return { accessor, commandService, pushUndoRedo, renderManagerService, sheetDrawingService, sheetInterceptorService };
+}
+
+describe('sheet drawing commands', () => {
+ it('arranges drawing order and records undo/redo mutations', () => {
+ const { accessor, commandService, pushUndoRedo } = createAccessor();
+ expect(SetDrawingArrangeCommand.handler(accessor, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingIds: ['shape-1'],
+ arrangeType: ArrangeTypeEnum.front,
+ })).toBe(true);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingApplyMutation.id, {
+ op: ['redo-front'],
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ objects: ['shape-1'],
+ type: DrawingApplyType.ARRANGE,
+ });
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'book-1',
+ undoMutations: [expect.objectContaining({ id: SetDrawingApplyMutation.id })],
+ redoMutations: [expect.objectContaining({ id: SetDrawingApplyMutation.id })],
+ }));
+ });
+
+ it('removes drawings through the interceptor pipeline and clears transformers in undo/redo', () => {
+ const { accessor, commandService, pushUndoRedo, sheetInterceptorService } = createAccessor();
+ expect(RemoveSheetDrawingCommand.handler(accessor, {
+ drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-1' }],
+ } as never)).toBe(true);
+ expect(sheetInterceptorService.onCommandExecute).toHaveBeenCalled();
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, 'pre-redo', { ok: true }, undefined);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, SetDrawingApplyMutation.id, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ op: ['remove-redo'],
+ objects: ['shape-1'],
+ type: DrawingApplyType.REMOVE,
+ }, undefined);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ undoMutations: expect.arrayContaining([expect.objectContaining({ id: ClearSheetDrawingTransformerOperation.id })]),
+ redoMutations: expect.arrayContaining([expect.objectContaining({ id: ClearSheetDrawingTransformerOperation.id })]),
+ }));
+ });
+
+ it('moves focused drawings, recalculates sheet anchors, and clears transformers', () => {
+ const { accessor, commandService, sheetDrawingService } = createAccessor();
+ expect(MoveDrawingsCommand.handler(accessor, { direction: Direction.LEFT })).toBe(true);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, SetSheetDrawingCommand.id, {
+ unitId: 'book-1',
+ drawings: [expect.objectContaining({
+ transform: { left: 9, top: 20 },
+ sheetTransform: {
+ from: { column: 0, columnOffset: 9, row: 2, rowOffset: 0 },
+ to: { column: 0, columnOffset: 9, row: 2, rowOffset: 0 },
+ flipX: false,
+ flipY: false,
+ angle: 0,
+ skewX: 0,
+ skewY: 0,
+ },
+ axisAlignSheetTransform: {
+ from: { column: 0, columnOffset: 9, row: 2, rowOffset: 0 },
+ to: { column: 0, columnOffset: 9, row: 2, rowOffset: 0 },
+ flipX: false,
+ flipY: false,
+ angle: 0,
+ skewX: 0,
+ skewY: 0,
+ },
+ })],
+ });
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, ClearSheetDrawingTransformerOperation.id, ['book-1']);
+
+ sheetDrawingService.getFocusDrawings.mockReturnValue([]);
+ expect(MoveDrawingsCommand.handler(accessor, { direction: Direction.RIGHT })).toBe(false);
+ });
+
+ it('inserts drawings through sheet interceptors and records undo/redo mutations', () => {
+ const { accessor, commandService, pushUndoRedo, sheetInterceptorService } = createAccessor();
+ const params = {
+ drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-2' }],
+ };
+
+ expect(InsertSheetDrawingCommand.handler(accessor, params as never)).toBe(true);
+ expect(sheetInterceptorService.onCommandExecute).toHaveBeenCalledWith({ id: InsertSheetDrawingCommand.id, params });
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(1, 'pre-redo', { ok: true }, undefined);
+ expect(commandService.syncExecuteCommand).toHaveBeenNthCalledWith(2, SetDrawingApplyMutation.id, {
+ op: ['add-redo'],
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ objects: ['shape-2'],
+ type: DrawingApplyType.INSERT,
+ }, undefined);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ unitID: 'book-1',
+ undoMutations: expect.arrayContaining([expect.objectContaining({ id: ClearSheetDrawingTransformerOperation.id, params: ['book-1'] })]),
+ redoMutations: expect.arrayContaining([expect.objectContaining({ id: ClearSheetDrawingTransformerOperation.id, params: ['book-1'] })]),
+ }));
+
+ expect(InsertSheetDrawingCommand.handler(accessor, undefined)).toBe(false);
+ });
+
+ it('flips drawing transforms, rebuilds anchors, and pushes transformer cleanup', () => {
+ const { accessor, commandService, pushUndoRedo, sheetDrawingService } = createAccessor();
+
+ expect(FlipSheetDrawingCommand.handler(accessor, {
+ unitId: 'book-1',
+ drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'shape-1' }],
+ flipH: true,
+ flipV: true,
+ })).toBe(true);
+ expect(sheetDrawingService.getBatchUpdateOp).toHaveBeenCalledWith([
+ expect.objectContaining({
+ drawingId: 'shape-1',
+ drawingType: DrawingTypeEnum.DRAWING_SHAPE,
+ transform: expect.objectContaining({ left: 10, top: 20, flipX: true, flipY: true }),
+ sheetTransform: {
+ from: { column: 1, columnOffset: 0, row: 2, rowOffset: 0 },
+ to: { column: 1, columnOffset: 0, row: 2, rowOffset: 0 },
+ flipX: true,
+ flipY: true,
+ angle: 0,
+ skewX: 0,
+ skewY: 0,
+ },
+ axisAlignSheetTransform: {
+ from: { column: 1, columnOffset: 0, row: 2, rowOffset: 0 },
+ to: { column: 1, columnOffset: 0, row: 2, rowOffset: 0 },
+ flipX: true,
+ flipY: true,
+ angle: 0,
+ skewX: 0,
+ skewY: 0,
+ },
+ }),
+ ]);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingApplyMutation.id, {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ op: ['update-redo'],
+ objects: ['shape-1'],
+ type: DrawingApplyType.UPDATE,
+ }, undefined);
+ expect(pushUndoRedo).toHaveBeenCalledWith(expect.objectContaining({
+ undoMutations: expect.arrayContaining([expect.objectContaining({ id: ClearSheetDrawingTransformerOperation.id, params: ['book-1'] })]),
+ redoMutations: expect.arrayContaining([expect.objectContaining({ id: ClearSheetDrawingTransformerOperation.id, params: ['book-1'] })]),
+ }));
+
+ sheetDrawingService.getDrawingData.mockReturnValue({} as never);
+ expect(FlipSheetDrawingCommand.handler(accessor, {
+ unitId: 'book-1',
+ drawings: [{ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'missing' }],
+ flipH: true,
+ })).toBe(false);
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..f6bb0bb94d
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/utils.spec.ts
@@ -0,0 +1,103 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DrawingTypeEnum } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { groupToUngroup, ungroupToGroup } from '../utils';
+
+vi.mock('@univerjs/engine-render', () => ({
+ getGroupState: vi.fn(() => ({ left: 30, top: 40, width: 80, height: 60 })),
+ transformObjectOutOfGroup: vi.fn((transform, groupTransform) => ({
+ left: (transform.left ?? 0) + (groupTransform.left ?? 0),
+ top: (transform.top ?? 0) + (groupTransform.top ?? 0),
+ width: transform.width,
+ height: transform.height,
+ })),
+}));
+
+describe('sheets drawing command utils', () => {
+ it('restores grouped sheet drawings with the original base bound', () => {
+ expect(ungroupToGroup([
+ {
+ parent: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'group-1',
+ groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },
+ },
+ children: [
+ { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'child-1', transform: { left: 2, top: 3 } },
+ ],
+ },
+ ] as never)).toEqual([
+ {
+ parent: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'group-1',
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },
+ transform: { left: 30, top: 40, width: 80, height: 60 },
+ },
+ children: [
+ {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'child-1',
+ transform: { left: 2, top: 3 },
+ groupId: 'group-1',
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('ungroups sheet drawings back into standalone transforms', () => {
+ expect(groupToUngroup([
+ {
+ parent: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'group-1',
+ transform: { left: 30, top: 40, width: 80, height: 60 },
+ groupBaseBound: { left: 1, top: 2, width: 3, height: 4 },
+ },
+ children: [
+ { unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'child-1', transform: { left: 5, top: 6, width: 7, height: 8 } },
+ ],
+ },
+ ] as never)).toEqual([
+ {
+ parent: {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'group-1',
+ drawingType: DrawingTypeEnum.DRAWING_GROUP,
+ transform: { left: 0, top: 0 },
+ },
+ children: [
+ {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'child-1',
+ transform: { left: 35, top: 46, width: 7, height: 8 },
+ groupId: undefined,
+ },
+ ],
+ },
+ ]);
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.ts b/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.ts
new file mode 100644
index 0000000000..2b33a25df6
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/__tests__/edit-sheet-drawing.operation.spec.ts
@@ -0,0 +1,69 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, IDrawingSearch } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import { SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { describe, expect, it, vi } from 'vitest';
+import { EditSheetDrawingOperation } from '../edit-sheet-drawing.operation';
+import { SidebarSheetDrawingOperation } from '../open-drawing-panel.operation';
+
+describe('EditSheetDrawingOperation', () => {
+ it('returns false when there is no selected drawing', () => {
+ const commandService = {
+ syncExecuteCommand: vi.fn(),
+ executeCommand: vi.fn(),
+ };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ICommandService) {
+ return commandService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ expect(EditSheetDrawingOperation.handler(accessor, null as never)).toBe(false);
+ expect(commandService.syncExecuteCommand).not.toHaveBeenCalled();
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+ });
+
+ it('selects the drawing and opens the sheet sidebar editor', () => {
+ const commandService = {
+ syncExecuteCommand: vi.fn(() => true),
+ executeCommand: vi.fn(),
+ };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ICommandService) {
+ return commandService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+ const drawing: IDrawingSearch = {
+ unitId: 'book-1',
+ subUnitId: 'sheet-1',
+ drawingId: 'drawing-1',
+ };
+
+ expect(EditSheetDrawingOperation.handler(accessor, drawing)).toBe(true);
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, [drawing]);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(SidebarSheetDrawingOperation.id, { value: 'open' });
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts b/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
new file mode 100644
index 0000000000..857bc9d2f0
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+import { ISidebarService } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { COMPONENT_SHEET_DRAWING_PANEL } from '../../../views/sheet-image-panel/component-name';
+import { SidebarSheetDrawingOperation } from '../open-drawing-panel.operation';
+
+vi.mock('@univerjs/sheets', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/sheets')>();
+ return { ...actual, getSheetCommandTarget: vi.fn() };
+});
+
+const mockedGetSheetCommandTarget = vi.mocked(getSheetCommandTarget);
+
+function createAccessor() {
+ const sidebarService = { open: vi.fn(), close: vi.fn() };
+ const commandService = { syncExecuteCommand: vi.fn() };
+ const accessor = {
+ get(token: unknown) {
+ if (token === ISidebarService) return sidebarService;
+ if (token === LocaleService) return { t: (key: string) => key };
+ if (token === IUniverInstanceService) return {};
+ if (token === ICommandService) return commandService;
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return { accessor, sidebarService, commandService };
+}
+
+describe('SidebarSheetDrawingOperation', () => {
+ it('opens the sheet drawing panel and clears the selection on close', async () => {
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'book-1', subUnitId: 'sheet-1' } as never);
+ const { accessor, sidebarService, commandService } = createAccessor();
+
+ await expect(SidebarSheetDrawingOperation.handler(accessor, { value: 'open' })).resolves.toBe(true);
+ expect(sidebarService.open).toHaveBeenCalledWith(expect.objectContaining({
+ header: { title: 'sheetImage.panel.title' },
+ children: { label: COMPONENT_SHEET_DRAWING_PANEL },
+ width: 360,
+ }));
+ const onClose = sidebarService.open.mock.calls[0][0].onClose;
+ onClose();
+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, []);
+ });
+
+ it('returns false without a sheet target and closes on non-open actions', async () => {
+ const { accessor, sidebarService } = createAccessor();
+ mockedGetSheetCommandTarget.mockReturnValue(null as never);
+ await expect(SidebarSheetDrawingOperation.handler(accessor, { value: 'open' })).resolves.toBe(false);
+
+ mockedGetSheetCommandTarget.mockReturnValue({ unitId: 'book-1', subUnitId: 'sheet-1' } as never);
+ await expect(SidebarSheetDrawingOperation.handler(accessor, { value: 'close' })).resolves.toBe(true);
+ expect(sidebarService.close).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.ts b/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.ts
new file mode 100644
index 0000000000..4dc118f017
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/services/__tests__/batch-save-images.service.spec.ts
@@ -0,0 +1,131 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ImageSourceType, UniverInstanceType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import { BatchSaveImagesService, FileNamePart } from '../batch-save-images.service';
+
+function createService() {
+ const cells = new Map<string, unknown>([
+ ['0:0', {
+ p: {
+ drawingsOrder: ['img-a1'],
+ drawings: {
+ 'img-a1': {
+ drawingId: 'img-a1',
+ source: 'data:image/png;base64,aaa',
+ imageSourceType: ImageSourceType.BASE64,
+ },
+ },
+ },
+ }],
+ ['1:1', {
+ p: {
+ drawingsOrder: ['img-b2'],
+ drawings: {
+ 'img-b2': {
+ drawingId: 'img-b2',
+ source: 'https://cdn.example.com/photo.jpeg?version=1',
+ imageSourceType: ImageSourceType.URL,
+ },
+ },
+ },
+ }],
+ ['0:3', { v: 'Report:Q1' }],
+ ['1:0', { v: 'Client/Name' }],
+ ['1:3', { p: { body: { dataStream: 'Summary' } } }],
+ ]);
+
+ const cellMatrix = {
+ getValue: (row: number, col: number) => cells.get(`${row}:${col}`) as never,
+ getDataRange: () => ({ startRow: 0, endRow: 2, startColumn: 0, endColumn: 3 }),
+ };
+ const worksheet = {
+ getCellMatrix: () => cellMatrix,
+ };
+ const workbook = {
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: () => worksheet,
+ };
+ const selections = [
+ { range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 } },
+ { range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 } },
+ ];
+
+ return new BatchSaveImagesService(
+ {
+ getCurrentUnitForType: (type: UniverInstanceType) => (type === UniverInstanceType.UNIVER_SHEET ? workbook : null),
+ getUnit: () => workbook,
+ } as never,
+ {
+ getCurrentSelections: () => selections,
+ } as never,
+ {} as never,
+ {} as never
+ );
+}
+
+describe('BatchSaveImagesService', () => {
+ it('collects cell images from current selections and exposes selection metadata', () => {
+ const service = createService();
+
+ expect(service.getCellImagesInSelection()).toEqual([
+ {
+ row: 0,
+ col: 0,
+ cellAddress: 'A1',
+ source: 'data:image/png;base64,aaa',
+ imageSourceType: ImageSourceType.BASE64,
+ imageId: 'img-a1',
+ },
+ {
+ row: 1,
+ col: 1,
+ cellAddress: 'B2',
+ source: 'https://cdn.example.com/photo.jpeg?version=1',
+ imageSourceType: ImageSourceType.URL,
+ imageId: 'img-b2',
+ },
+ ]);
+ expect(service.getSelectionRangeNotation()).toBe('A1:B1, B2');
+ expect(service.getSelectionRowRange()).toEqual({ startRow: 0, endRow: 1 });
+ expect(Array.from(service.getSelectionColumnIndices()).sort((a, b) => a - b)).toEqual([0, 1]);
+ });
+
+ it('finds data columns outside the selection and builds sanitized file names', () => {
+ const service = createService();
+ const imageInfo = {
+ row: 1,
+ col: 1,
+ cellAddress: 'B2',
+ source: 'https://cdn.example.com/photo.jpeg?version=1',
+ imageSourceType: ImageSourceType.URL,
+ imageId: 'img-b2',
+ };
+
+ expect(service.getDataColumns()).toEqual([
+ { index: 3, label: 'D' },
+ ]);
+ expect(service.generateFileName(imageInfo, {
+ fileNameParts: [FileNamePart.COLUMN_VALUE, FileNamePart.CELL_ADDRESS],
+ columnIndex: 0,
+ })).toBe('Client_Name_B2.jpeg');
+ expect(service.generateFileNameWithContext(imageInfo, {
+ fileNameParts: [FileNamePart.CELL_ADDRESS, FileNamePart.COLUMN_VALUE],
+ columnIndex: 3,
+ }, 'book-1', 'sheet-1')).toBe('B2_Summary.jpeg');
+ });
+});
diff --git a/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.ts b/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.ts
new file mode 100644
index 0000000000..7291bf956b
--- /dev/null
+++ b/packages/sheets-find-replace/src/commands/commands/__tests__/sheet-replace.command.spec.ts
@@ -0,0 +1,52 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ICommandService, IUndoRedoService } from '@univerjs/core';
+
+import { describe, expect, it, vi } from 'vitest';
+import { SheetReplaceCommand } from '../sheet-replace.command';
+
+describe('SheetReplaceCommand', () => {
+ it('should batch undo/redo and execute SetRangeValues for replacements', async () => {
+ const dispose = vi.fn();
+ const undoRedoService = {
+ __tempBatchingUndoRedo: vi.fn(() => ({ dispose })),
+ };
+
+ const executeCommand = vi.fn(async () => true);
+ const commandService = { executeCommand };
+
+ const accessor = {
+ get: vi.fn((token: any) => {
+ if (token === IUndoRedoService) return undoRedoService;
+ if (token === ICommandService) return commandService;
+ return null;
+ }),
+ } as any;
+
+ const res = await SheetReplaceCommand.handler(accessor, {
+ unitId: 'u1',
+ replacements: [
+ { subUnitId: 's1', count: 2, value: { 0: { 0: { v: 'a' } } } as any },
+ { subUnitId: 's2', count: 1, value: { 1: { 1: { v: 'b' } } } as any },
+ ],
+ });
+
+ expect(executeCommand).toHaveBeenCalledTimes(2);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(res).toEqual({ success: 3, failure: 0 });
+ });
+});
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts
new file mode 100644
index 0000000000..d80924fa33
--- /dev/null
+++ b/packages/sheets-find-replace/src/controllers/__tests__/hit-cell.spec.ts
@@ -0,0 +1,68 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IFindQuery } from '@univerjs/find-replace';
+import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
+import { describe, expect, it } from 'vitest';
+import { hitCell } from '../sheet-find-replace.controller';
+
+describe('hitCell', () => {
+ const baseQuery: IFindQuery = {
+ replaceRevealed: false,
+ findString: 'abc',
+ caseSensitive: false,
+ matchesTheWholeCell: false,
+ findDirection: FindDirection.ROW,
+ findScope: FindScope.SUBUNIT,
+ findBy: FindBy.VALUE,
+ };
+
+ it('should mark formula matches replaceable only in formula mode', () => {
+ const worksheet = {
+ getCellRaw: () => ({ f: '=ABC()' }),
+ };
+
+ const formulaQuery: IFindQuery = { ...baseQuery, findBy: FindBy.FORMULA, findString: '=abc' };
+ const res1 = hitCell(worksheet as any, 0, 0, formulaQuery, { v: 'xxx' } as any);
+ expect(res1.hit).toBe(true);
+ expect(res1.replaceable).toBe(true);
+ expect(res1.isFormula).toBe(true);
+
+ const valueQuery: IFindQuery = { ...baseQuery, findBy: FindBy.VALUE, findString: 'xxx' };
+ const res2 = hitCell(worksheet as any, 0, 0, valueQuery, { v: 'xxx' } as any);
+ expect(res2.hit).toBe(true);
+ expect(res2.replaceable).toBe(false);
+ expect(res2.isFormula).toBe(true);
+ });
+
+ it('should mark non-formula matches replaceable only when rawData exists', () => {
+ const worksheetWithRaw = {
+ getCellRaw: () => ({ v: 'abc' }),
+ };
+
+ const res1 = hitCell(worksheetWithRaw as any, 0, 0, baseQuery, { v: 'abc' } as any);
+ expect(res1.hit).toBe(true);
+ expect(res1.replaceable).toBe(true);
+
+ const worksheetNoRaw = {
+ getCellRaw: () => null,
+ };
+
+ const res2 = hitCell(worksheetNoRaw as any, 0, 0, baseQuery, { v: 'abc' } as any);
+ expect(res2.hit).toBe(true);
+ expect(res2.replaceable).toBe(false);
+ });
+});
diff --git a/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts
new file mode 100644
index 0000000000..0b3ac0c0a0
--- /dev/null
+++ b/packages/sheets-find-replace/src/controllers/__tests__/sheet-find-model.navigation.spec.ts
@@ -0,0 +1,112 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { IFindQuery } from '@univerjs/find-replace';
+import { FindBy, FindDirection, FindScope } from '@univerjs/find-replace';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+
+import { SheetFindModel, SheetsFindReplaceController } from '../sheet-find-replace.controller';
+
+describe('SheetFindModel navigation', () => {
+ it('should move to next match based on current selection (no focus)', () => {
+ const activeSheet = { getSheetId: () => 's1', getRowCount: () => 10, getColumnCount: () => 10, iterateByRow: () => [], iterateByColumn: () => [], isSheetHidden: () => false };
+ const workbook = {
+ getUnitId: () => 'u1',
+ getActiveSheet: () => activeSheet,
+ activeSheet$: new Subject<any>(),
+ };
+
+ const skeletonService = {
+ currentSkeleton$: new Subject<any>(),
+ getCurrent: () => null,
+ };
+
+ const renderManagerService = { getRenderById: vi.fn(() => null) };
+ const commandService = { executeCommand: vi.fn(), onCommandExecuted: vi.fn(() => ({ dispose: vi.fn() })) };
+ const contextService = { setContextValue: vi.fn() };
+ const themeService = { getColorFromTheme: vi.fn(() => '#fff') };
+
+ const selections = [{ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }];
+ const workbookSelections = {
+ getCurrentSelections: () => selections,
+ getCurrentLastSelection: () => selections[0],
+ };
+
+ const selectionService = {
+ getWorkbookSelections: vi.fn(() => workbookSelections),
+ };
+
+ const model = new SheetFindModel(
+ workbook as any,
+ skeletonService as any,
+ {} as any,
+ renderManagerService as any,
+ commandService as any,
+ contextService as any,
+ themeService as any,
+ selectionService as any
+ );
+
+ (model as any)._matches = [
+ { unitId: 'u1', provider: 'sheets-find-replace-provider', isFormula: false, replaceable: true, range: { subUnitId: 's1', range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1 } } },
+ { unitId: 'u1', provider: 'sheets-find-replace-provider', isFormula: false, replaceable: true, range: { subUnitId: 's1', range: { startRow: 2, startColumn: 1, endRow: 2, endColumn: 1 } } },
+ ];
+
+ (model as any)._query = {
+ replaceRevealed: false,
+ findString: 'a',
+ caseSensitive: false,
+ matchesTheWholeCell: false,
+ findDirection: FindDirection.ROW,
+ findScope: FindScope.SUBUNIT,
+ findBy: FindBy.VALUE,
+ } satisfies IFindQuery;
+
+ const match = model.moveToNextMatch({ noFocus: true });
+ expect(match?.range.range.startRow).toBe(1);
+ expect(commandService.executeCommand).not.toHaveBeenCalled();
+
+ model.dispose();
+ });
+});
+
+describe('SheetsFindReplaceController', () => {
+ it('should register provider and close on editor activated', () => {
+ const injector = { createInstance: vi.fn(() => ({ dispose: vi.fn() })) };
+ const findReplaceController = { closePanel: vi.fn() };
+ const subscribeContextValue$ = vi.fn(() => ({ pipe: () => ({ subscribe: (fn: any) => {
+ fn(true);
+ return { unsubscribe: vi.fn() };
+ } }) }));
+ const contextService = { subscribeContextValue$ };
+ const findReplaceService = { registerFindReplaceProvider: vi.fn(() => ({ dispose: vi.fn() })) };
+ const commandService = { registerCommand: vi.fn(() => ({ dispose: vi.fn() })) };
+
+ new SheetsFindReplaceController(
+ injector as any,
+ findReplaceController as any,
+ contextService as any,
+ findReplaceService as any,
+ commandService as any
+ );
+
+ expect(findReplaceController.closePanel).toHaveBeenCalledTimes(1);
+ // Do not call `dispose` here: the controller stores rx subscriptions in a DisposableCollection,
+ // and our simplified stubs don't fully implement the IDisposable contract.
+ expect(findReplaceService.registerFindReplaceProvider).toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-find-replace/src/facade/__tests__/f-text-finder.spec.ts b/packages/sheets-find-replace/src/facade/__tests__/f-text-finder.spec.ts
new file mode 100644
index 0000000000..91139e3022
--- /dev/null
+++ b/packages/sheets-find-replace/src/facade/__tests__/f-text-finder.spec.ts
@@ -0,0 +1,86 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { BehaviorSubject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { FTextFinder } from '../f-text-finder';
+
+describe('FTextFinder', () => {
+ it('should return matches after ensureCompleteAsync and navigate next/previous', async () => {
+ const matches = [
+ { provider: 'p', unitId: 'u1', range: { subUnitId: 's1', range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 } }, replaceable: true },
+ { provider: 'p', unitId: 'u1', range: { subUnitId: 's1', range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 0 } }, replaceable: true },
+ ];
+
+ const model = {
+ currentMatch$: new BehaviorSubject<any>(matches[0]),
+ start: vi.fn(async () => ({ results: matches })),
+ moveToNextMatch: vi.fn(() => matches[1]),
+ moveToPreviousMatch: vi.fn(() => matches[0]),
+ replaceAll: vi.fn(async () => ({ success: 2, failure: 0 })),
+ replace: vi.fn(async () => true),
+ };
+
+ const workbook = {
+ getSheetBySheetId: vi.fn(() => ({})),
+ };
+
+ const injector = {
+ createInstance: vi.fn((cls: any, ...args: any[]) => {
+ if (cls.name === 'FindReplaceModel') return model;
+ // FRange
+ return { cls, args };
+ }),
+ };
+
+ const univerInstanceService = {
+ getUnit: vi.fn(() => workbook),
+ };
+
+ const findReplaceService = {
+ getProviders: vi.fn(() => new Set()),
+ };
+
+ const finder = new FTextFinder({ findString: 'a' }, injector as any, univerInstanceService as any, findReplaceService as any);
+ await finder.ensureCompleteAsync();
+
+ // ensure internal state is marked completed
+ (finder as any)._state.changeState({ findCompleted: true });
+
+ expect(finder.findAll()).toHaveLength(2);
+ expect(finder.findNext()).toBeTruthy();
+ expect(finder.findPrevious()).toBeTruthy();
+ expect(finder.getCurrentMatch()).toBeTruthy();
+
+ const count = await finder.replaceAllWithAsync('b');
+ expect(count).toBe(2);
+
+ const ok = await finder.replaceWithAsync('c');
+ expect(ok).toBe(true);
+
+ const p1 = finder.matchCaseAsync(true);
+ (finder as any)._state.changeState({ findCompleted: true });
+ await p1;
+
+ const p2 = finder.matchEntireCellAsync(true);
+ (finder as any)._state.changeState({ findCompleted: true });
+ await p2;
+
+ const p3 = finder.matchFormulaTextAsync(true);
+ (finder as any)._state.changeState({ findCompleted: true });
+ await p3;
+ });
+});
diff --git a/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts b/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts
new file mode 100644
index 0000000000..b48d63fb77
--- /dev/null
+++ b/packages/sheets-find-replace/src/views/shapes/__tests__/find-replace-highlight.shape.spec.ts
@@ -0,0 +1,61 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISheetFindReplaceHighlightShapeProps } from '../find-replace-highlight.shape';
+import { Rect } from '@univerjs/engine-render';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetFindReplaceHighlightShape } from '../find-replace-highlight.shape';
+
+vi.mock('@univerjs/engine-render', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/engine-render')>('@univerjs/engine-render');
+ return {
+ ...actual,
+ Rect: {
+ drawWith: vi.fn(),
+ },
+ Shape: class {
+ width = 0;
+ height = 0;
+ constructor(_key?: string, _props?: unknown) {}
+ transformByState(state: { width?: number; height?: number }) {
+ if (state.width) this.width = state.width;
+ if (state.height) this.height = state.height;
+ }
+ },
+ };
+});
+
+describe('SheetFindReplaceHighlightShape', () => {
+ it('should update props and draw activated border', () => {
+ const shape = new SheetFindReplaceHighlightShape('k', {
+ inHiddenRange: false,
+ color: { r: 1, g: 2, b: 3 },
+ width: 10,
+ height: 20,
+ } satisfies ISheetFindReplaceHighlightShapeProps);
+
+ const drawableShape = shape as SheetFindReplaceHighlightShape & {
+ _draw(ctx: CanvasRenderingContext2D): void;
+ };
+
+ shape.setShapeProps({ activated: true, width: 10, height: 20 });
+ drawableShape._draw({} as CanvasRenderingContext2D);
+
+ expect(Rect.drawWith).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ strokeWidth: 2,
+ }));
+ });
+});
diff --git a/packages/sheets-formula-ui/src/commands/commands/__tests__/formula-clipboard.command.spec.ts b/packages/sheets-formula-ui/src/commands/commands/__tests__/formula-clipboard.command.spec.ts
new file mode 100644
index 0000000000..2a09431b99
--- /dev/null
+++ b/packages/sheets-formula-ui/src/commands/commands/__tests__/formula-clipboard.command.spec.ts
@@ -0,0 +1,53 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ICommandService } from '@univerjs/core';
+import { ISheetClipboardService, PREDEFINED_HOOK_NAME_COPY, PREDEFINED_HOOK_NAME_PASTE, SheetPasteCommand } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetCopyFormulaOnlyCommand, SheetOnlyPasteFormulaCommand } from '../formula-clipboard.command';
+
+describe('formula clipboard commands', () => {
+ it('copies only formulas through the clipboard hook', async () => {
+ const sheetClipboardService = { copy: vi.fn(() => true) };
+ const accessor = {
+ get: (token: unknown) => {
+ if (token === ISheetClipboardService) return sheetClipboardService;
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ await expect(SheetCopyFormulaOnlyCommand.handler(accessor)).resolves.toBe(true);
+ expect(sheetClipboardService.copy).toHaveBeenCalledWith({
+ copyHookType: PREDEFINED_HOOK_NAME_COPY.SPECIAL_COPY_FORMULA_ONLY,
+ });
+ });
+
+ it('pastes only formulas through the paste command', async () => {
+ const commandService = { executeCommand: vi.fn(() => true) };
+ const accessor = {
+ get: (token: unknown) => {
+ if (token === ICommandService) return commandService;
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ await expect(SheetOnlyPasteFormulaCommand.handler(accessor)).resolves.toBe(true);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(SheetPasteCommand.id, {
+ value: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA,
+ });
+ });
+});
diff --git a/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.ts b/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.ts
new file mode 100644
index 0000000000..111de8f2ab
--- /dev/null
+++ b/packages/sheets-formula-ui/src/commands/operations/__tests__/formula-ui.operation.spec.ts
@@ -0,0 +1,66 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@univerjs/core';
+import { ISidebarService } from '@univerjs/ui';
+import { describe, expect, it, vi } from 'vitest';
+import { IFormulaPromptService } from '../../../services/prompt.service';
+import { MORE_FUNCTIONS_COMPONENT } from '../../../views/more-functions/interface';
+import { HelpFunctionOperation } from '../help-function.operation';
+import { MoreFunctionsOperation } from '../more-functions.operation';
+import { SearchFunctionOperation } from '../search-function.operation';
+
+function createAccessor() {
+ const promptService = { help: vi.fn(), search: vi.fn() };
+ const sidebarService = { open: vi.fn() };
+ const accessor = {
+ get(token: unknown) {
+ if (token === IFormulaPromptService) {
+ return promptService;
+ }
+
+ if (token === ISidebarService) {
+ return sidebarService;
+ }
+
+ throw new Error(`Unknown dependency: ${String(token)}`);
+ },
+ } as IAccessor;
+
+ return { accessor, promptService, sidebarService };
+}
+
+describe('formula UI operations', () => {
+ it('delegates help and search actions to the prompt service', async () => {
+ const { accessor, promptService } = createAccessor();
+
+ await expect(HelpFunctionOperation.handler(accessor, { functionName: 'SUM' } as never)).resolves.toBe(true);
+ await expect(SearchFunctionOperation.handler(accessor, { searchText: 'count' } as never)).resolves.toBe(true);
+
+ expect(promptService.help).toHaveBeenCalledWith({ functionName: 'SUM' });
+ expect(promptService.search).toHaveBeenCalledWith({ searchText: 'count' });
+ });
+
+ it('opens the more-functions sidebar with the expected component', async () => {
+ const { accessor, sidebarService } = createAccessor();
+
+ await expect(MoreFunctionsOperation.handler(accessor)).resolves.toBe(true);
+ expect(sidebarService.open).toHaveBeenCalledWith({
+ header: { title: 'formula.insert.tooltip' },
+ children: { label: MORE_FUNCTIONS_COMPONENT },
+ });
+ });
+});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts
new file mode 100644
index 0000000000..da07aba567
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-alert-render.controller.spec.ts
@@ -0,0 +1,98 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ErrorType, extractFormulaError } from '@univerjs/engine-formula';
+import { Subject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FormulaAlertRenderController } from '../formula-alert-render.controller';
+
+vi.mock('@univerjs/engine-formula', async (importActual) => {
+ const actual = await importActual<typeof import('@univerjs/engine-formula')>();
+ return {
+ ...actual,
+ extractFormulaError: vi.fn(() => actual.ErrorType.DIV_BY_ZERO),
+ };
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('FormulaAlertRenderController', () => {
+ it('shows formula alerts for hovered cells and hides them for repeated hovers or zen mode', async () => {
+ vi.useFakeTimers();
+ const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
+ const visible$ = new Subject<boolean>();
+ const currentAlert = new Map<string, { alert: { location: { unitId: string; subUnitId: string; row: number; col: number } } }>();
+ const showAlert = vi.fn((alert) => currentAlert.set('SHEET_FORMULA_ALERT', { alert }));
+ const removeAlert = vi.fn((key: string) => currentAlert.delete(key));
+ const worksheet = { getCell: vi.fn(() => ({ v: '#DIV/0!' })) };
+
+ const controller = new FormulaAlertRenderController(
+ { unit: { getActiveSheet: vi.fn(() => worksheet) } } as never,
+ { currentCell$ } as never,
+ { currentAlert, removeAlert, showAlert } as never,
+ { t: (key: string) => key } as never,
+ { getArrayFormulaCellData: vi.fn(() => null) } as never,
+ { visible$ } as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ const location = { unitId: 'book-1', subUnitId: 'sheet-1', row: 2, col: 1 };
+ currentCell$.next({ location });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(showAlert).toHaveBeenCalledWith(expect.objectContaining({
+ key: 'SHEET_FORMULA_ALERT',
+ title: 'formula.error.title',
+ message: 'formula.error.divByZero',
+ location,
+ }));
+
+ currentCell$.next({ location });
+ await vi.advanceTimersByTimeAsync(120);
+ expect(removeAlert).toHaveBeenCalledWith('SHEET_FORMULA_ALERT');
+
+ visible$.next(true);
+ expect(removeAlert).toHaveBeenCalledWith('SHEET_FORMULA_ALERT');
+ });
+
+ it('hides alerts when there is no extractable formula error', async () => {
+ vi.useFakeTimers();
+ vi.mocked(extractFormulaError).mockReturnValueOnce(null as never);
+ const currentCell$ = new Subject<{ location: { unitId: string; subUnitId: string; row: number; col: number } }>();
+ const removeAlert = vi.fn();
+
+ const controller = new FormulaAlertRenderController(
+ { unit: { getActiveSheet: vi.fn(() => ({ getCell: vi.fn(() => ({ v: 'plain-text' })) })) } } as never,
+ { currentCell$ } as never,
+ { currentAlert: new Map(), removeAlert, showAlert: vi.fn() } as never,
+ { t: (key: string) => key } as never,
+ { getArrayFormulaCellData: vi.fn(() => null) } as never,
+ { visible$: new Subject<boolean>() } as never
+ );
+
+ expect(controller).toBeTruthy();
+
+ currentCell$.next({ location: { unitId: 'book-1', subUnitId: 'sheet-1', row: 0, col: 0 } });
+ await vi.advanceTimersByTimeAsync(120);
+
+ expect(removeAlert).toHaveBeenCalledWith('SHEET_FORMULA_ALERT');
+ expect(vi.mocked(extractFormulaError)).toHaveBeenCalledWith({ v: 'plain-text' }, false);
+ expect(ErrorType.DIV_BY_ZERO).toBeTruthy();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts
new file mode 100644
index 0000000000..3a6ab5c485
--- /dev/null
+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-ui.controller.spec.ts
@@ -0,0 +1,54 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandService, Injector } from '@univerjs/core';
+import type { IRenderManagerService } from '@univerjs/engine-render';
+import type { ComponentManager, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';
+import { UniverInstanceType } from '@univerjs/core';
+import { SheetsUIPart } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { MORE_FUNCTIONS_COMPONENT } from '../../views/more-functions/interface';
+import { FormulaUIController } from '../formula-ui.controller';
+
+describe('FormulaUIController', () => {
+ it('registers formula commands, menus, shortcuts, UI parts, and render modules', () => {
+ const mergeMenu = vi.fn();
+ const registerCommand = vi.fn(() => ({ dispose: vi.fn() }));
+ const registerShortcut = vi.fn(() => ({ dispose: vi.fn() }));
+ const registerComponent = vi.fn(() => ({ dispose: vi.fn() }));
+ const registerRenderModule = vi.fn(() => ({ dispose: vi.fn() }));
+ const componentRegister = vi.fn();
+ const injector = {};
+
+ const controller = new FormulaUIController(
+ injector as Injector,
+ { mergeMenu } as unknown as IMenuManagerService,
+ { registerCommand } as unknown as ICommandService,
+ { registerShortcut } as unknown as IShortcutService,
+ { registerComponent } as unknown as IUIPartsService,
+ { registerRenderModule } as unknown as IRenderManagerService,
+ { register: componentRegister } as unknown as ComponentManager
+ );
+
+ expect(controller).toBeTruthy();
+ expect(mergeMenu).toHaveBeenCalledTimes(1);
+ expect(registerCommand).toHaveBeenCalledTimes(8);
+ expect(registerShortcut.mock.calls.length).toBeGreaterThan(3);
+ expect(registerComponent).toHaveBeenCalledWith(SheetsUIPart.FORMULA_AUX, expect.any(Function));
+ expect(componentRegister).toHaveBeenCalledWith(MORE_FUNCTIONS_COMPONENT, expect.any(Function));
+ expect(registerRenderModule).toHaveBeenCalledWith(UniverInstanceType.UNIVER_SHEET, [expect.any(Function)]);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/services/__tests__/utils.spec.ts b/packages/sheets-formula-ui/src/services/__tests__/utils.spec.ts
new file mode 100644
index 0000000000..b0e6aca1ee
--- /dev/null
+++ b/packages/sheets-formula-ui/src/services/__tests__/utils.spec.ts
@@ -0,0 +1,61 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { LocaleService } from '@univerjs/core';
+import type { IFunctionInfo } from '@univerjs/engine-formula';
+import { FunctionType } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { generateParam, getFunctionName, getFunctionTypeValues } from '../utils';
+
+describe('formula service utils', () => {
+ const localeService = {
+ t: (key: string) => {
+ const dictionary: Record<string, string> = {
+ 'formula.functionType.math': 'Math',
+ 'formula.functionType.logical': 'Logical',
+ 'formula.alias.sum': '求和',
+ };
+
+ return dictionary[key] ?? key;
+ },
+ } as LocaleService;
+
+ it('builds function type options and excludes unsupported groups for built-in formulas', () => {
+ const values = getFunctionTypeValues(localeService, false);
+ const labels = new Set(values.map((item) => item.label));
+ const builtInValues = new Set(values.map((item) => item.value));
+
+ expect(labels.has('Math')).toBe(true);
+ expect(labels.has('Logical')).toBe(true);
+ expect(builtInValues.has(`${FunctionType.User}`)).toBe(false);
+ expect(builtInValues.has(`${FunctionType.DefinedName}`)).toBe(false);
+ expect(builtInValues.has(`${FunctionType.Table}`)).toBe(false);
+ expect(getFunctionTypeValues(localeService, true).some((item) => item.value === `${FunctionType.User}`)).toBe(true);
+ });
+
+ it('prefers localized aliases but falls back to the raw function name', () => {
+ expect(getFunctionName({ functionName: 'SUM', aliasFunctionName: 'formula.alias.sum' } as IFunctionInfo, localeService)).toBe('求和');
+ expect(getFunctionName({ functionName: 'COUNTIF', aliasFunctionName: 'formula.alias.unknown' } as IFunctionInfo, localeService)).toBe('COUNTIF');
+ expect(getFunctionName({ functionName: 'MAX' } as IFunctionInfo, localeService)).toBe('MAX');
+ });
+
+ it('formats required, optional, and repeated parameters for the function helper UI', () => {
+ expect(generateParam({ name: 'number1', require: false, repeat: false } as never)).toBe('[number1]');
+ expect(generateParam({ name: 'number1', require: true, repeat: false } as never)).toBe('number1');
+ expect(generateParam({ name: 'criteria', require: false, repeat: true } as never)).toBe('[criteria,...]');
+ expect(generateParam({ name: 'value', require: true, repeat: true } as never)).toBe('value,...');
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts b/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts
new file mode 100644
index 0000000000..14b993ea38
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/range-selector/utils/__tests__/range-utils.spec.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { matchToken, sequenceNodeType } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { filterReferenceNode, isComma, isReference } from '../filter-reference-node';
+import { verifyRange } from '../verify-range';
+
+const referenceNode = { nodeType: sequenceNodeType.REFERENCE, token: 'A1' };
+const functionNode = { nodeType: sequenceNodeType.FUNCTION, token: 'SUM' };
+
+describe('range selector utils', () => {
+ it('keeps only commas and reference nodes when extracting ranges from a parsed formula', () => {
+ expect(isComma(matchToken.COMMA)).toBe(true);
+ expect(isComma(';')).toBe(false);
+ expect(isReference(referenceNode as never)).toBe(true);
+ expect(isReference(functionNode as never)).toBe(false);
+ expect(filterReferenceNode([functionNode as never, matchToken.COMMA, referenceNode as never])).toEqual([
+ matchToken.COMMA,
+ referenceNode,
+ ]);
+ });
+
+ it('accepts only reference-and-comma sequences as a valid range selection', () => {
+ expect(verifyRange([referenceNode as never, matchToken.COMMA, referenceNode as never])).toBe(true);
+ expect(verifyRange([referenceNode as never, functionNode as never])).toBe(false);
+ expect(verifyRange([referenceNode as never, ';'])).toBe(false);
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts b/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts
new file mode 100644
index 0000000000..4aeefb3556
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/commands/operations/__tests__/popup.operations.spec.ts
@@ -0,0 +1,161 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IOpenHyperLinkEditPanelOperationParams } from '../popup.operations';
+import { DOCS_ZEN_EDITOR_UNIT_ID_KEY, ICommandService, IUniverInstanceService } from '@univerjs/core';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { IEditorBridgeService } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsHyperLinkPopupService } from '../../../services/popup.service';
+import { HyperLinkEditSourceType } from '../../../types/enums/edit-source';
+import {
+ CloseHyperLinkPopupOperation,
+ InsertHyperLinkOperation,
+ InsertHyperLinkToolbarOperation,
+ OpenHyperLinkEditPanelOperation,
+} from '../popup.operations';
+
+function createAccessor(pairs: Array<[unknown, unknown]>) {
+ const map = new Map<unknown, unknown>(pairs);
+ return {
+ get(token: unknown) {
+ if (!map.has(token)) {
+ throw new Error(`Unknown token: ${String(token)}`);
+ }
+ return map.get(token);
+ },
+ has(token: unknown) {
+ return map.has(token);
+ },
+ } as never;
+}
+
+function createWorksheet(cell: Record<string, unknown> | null = null) {
+ return {
+ getSheetId: () => 's1',
+ getUnitId: () => 'u1',
+ getCell: vi.fn(() => cell),
+ };
+}
+
+function createWorkbook(worksheet: ReturnType<typeof createWorksheet>) {
+ return {
+ getUnitId: () => 'u1',
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: () => worksheet,
+ };
+}
+
+function createUniverInstanceService(options?: {
+ workbook?: ReturnType<typeof createWorkbook> | null;
+ focusedUnitId?: string;
+}) {
+ return {
+ getCurrentUnitOfType: () => options?.workbook ?? null,
+ getCurrentUnitForType: () => options?.workbook ?? null,
+ getFocusedUnit: () => options?.focusedUnitId ? { getUnitId: () => options.focusedUnitId } : null,
+ };
+}
+
+describe('hyper-link popup operations', () => {
+ it('starts add and edit flows through the popup service', () => {
+ const startAddEditing = vi.fn();
+ const startEditing = vi.fn();
+ const popupService = { startAddEditing, startEditing };
+ const accessor = createAccessor([[SheetsHyperLinkPopupService, popupService]]);
+ const startAddParams: IOpenHyperLinkEditPanelOperationParams = {
+ unitId: 'u1',
+ subUnitId: 's1',
+ row: 1,
+ col: 2,
+ type: HyperLinkEditSourceType.VIEWING,
+ };
+ const startEditParams: IOpenHyperLinkEditPanelOperationParams = {
+ ...startAddParams,
+ customRangeId: 'range-1',
+ type: HyperLinkEditSourceType.EDITING,
+ };
+
+ expect(OpenHyperLinkEditPanelOperation.handler(accessor, undefined)).toBe(false);
+ expect(OpenHyperLinkEditPanelOperation.handler(accessor, startAddParams)).toBe(true);
+ expect(OpenHyperLinkEditPanelOperation.handler(accessor, startEditParams)).toBe(true);
+
+ expect(startAddEditing).toHaveBeenCalledTimes(1);
+ expect(startEditing).toHaveBeenCalledTimes(1);
+ });
+
+ it('closes the popup edit session', () => {
+ const endEditing = vi.fn();
+ const accessor = createAccessor([[SheetsHyperLinkPopupService, { endEditing }]]);
+
+ expect(CloseHyperLinkPopupOperation.handler(accessor)).toBe(true);
+ expect(endEditing).toHaveBeenCalledTimes(1);
+ });
+
+ it('derives the correct edit source from the current sheet selection state', () => {
+ const executeCommand = vi.fn(() => true);
+ const worksheet = createWorksheet();
+ const workbook = createWorkbook(worksheet);
+
+ const createInsertAccessor = (visible: boolean, focusedUnitId?: string, hasSelection = true, activeWorkbook: ReturnType<typeof createWorkbook> | null = workbook) => createAccessor([
+ [IUniverInstanceService, createUniverInstanceService({ workbook: activeWorkbook, focusedUnitId })],
+ [ICommandService, { executeCommand }],
+ [SheetsSelectionsService, { getCurrentLastSelection: () => (hasSelection ? { range: { startRow: 3, startColumn: 4 } } : null) }],
+ [IEditorBridgeService, { isVisible: () => ({ visible }) }],
+ ]);
+
+ expect(InsertHyperLinkOperation.handler(createInsertAccessor(false))).toBe(true);
+ expect(InsertHyperLinkOperation.handler(createInsertAccessor(true))).toBe(true);
+ expect(InsertHyperLinkOperation.handler(createInsertAccessor(false, DOCS_ZEN_EDITOR_UNIT_ID_KEY))).toBe(true);
+
+ expect(executeCommand).toHaveBeenNthCalledWith(1, OpenHyperLinkEditPanelOperation.id, expect.objectContaining({ type: HyperLinkEditSourceType.VIEWING }));
+ expect(executeCommand).toHaveBeenNthCalledWith(2, OpenHyperLinkEditPanelOperation.id, expect.objectContaining({ type: HyperLinkEditSourceType.EDITING }));
+ expect(executeCommand).toHaveBeenNthCalledWith(3, OpenHyperLinkEditPanelOperation.id, expect.objectContaining({ type: HyperLinkEditSourceType.ZEN_EDITOR }));
+
+ expect(InsertHyperLinkOperation.handler(createInsertAccessor(false, undefined, true, null))).toBe(false);
+
+ expect(InsertHyperLinkOperation.handler(createInsertAccessor(false, undefined, false))).toBe(false);
+ });
+
+ it('respects disabled cells and toggles between insert and close commands from the toolbar', () => {
+ const executeCommand = vi.fn(() => true);
+ const disabledWorksheet = createWorksheet({ f: '=A1' });
+ const enabledWorksheet = createWorksheet({ v: 'cell' });
+
+ expect(InsertHyperLinkToolbarOperation.handler(createAccessor([
+ [IUniverInstanceService, createUniverInstanceService({ workbook: createWorkbook(disabledWorksheet) })],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, startColumn: 1 } }] }],
+ [ICommandService, { executeCommand }],
+ [SheetsHyperLinkPopupService, { currentEditing: null }],
+ ]))).toBe(false);
+
+ expect(InsertHyperLinkToolbarOperation.handler(createAccessor([
+ [IUniverInstanceService, createUniverInstanceService({ workbook: createWorkbook(enabledWorksheet) })],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, startColumn: 1 } }] }],
+ [ICommandService, { executeCommand }],
+ [SheetsHyperLinkPopupService, { currentEditing: { row: 1 } }],
+ ]))).toBe(true);
+ expect(InsertHyperLinkToolbarOperation.handler(createAccessor([
+ [IUniverInstanceService, createUniverInstanceService({ workbook: createWorkbook(enabledWorksheet) })],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 1, startColumn: 1 } }] }],
+ [ICommandService, { executeCommand }],
+ [SheetsHyperLinkPopupService, { currentEditing: null }],
+ ]))).toBe(true);
+
+ expect(executeCommand).toHaveBeenCalledWith(CloseHyperLinkPopupOperation.id);
+ expect(executeCommand).toHaveBeenCalledWith(InsertHyperLinkOperation.id);
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/common/__tests__/util.spec.ts b/packages/sheets-hyper-link-ui/src/common/__tests__/util.spec.ts
new file mode 100644
index 0000000000..8a36e2d1d0
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/common/__tests__/util.spec.ts
@@ -0,0 +1,42 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { hasProtocol, isEmail, serializeUrl } from '../util';
+
+describe('hyper-link common util', () => {
+ it('should detect protocols and email addresses', () => {
+ expect(hasProtocol('https://univer.ai')).toBe(true);
+ expect(hasProtocol('univer.ai')).toBe(false);
+ expect(isEmail('[email protected]')).toBe(true);
+ expect(isEmail('not-an-email')).toBe(false);
+ });
+
+ it('should normalize external URLs and keep same-page anchors compact', () => {
+ Object.defineProperty(globalThis, 'location', {
+ configurable: true,
+ value: {
+ hostname: 'localhost',
+ port: '',
+ protocol: 'http:',
+ pathname: '/sheet',
+ },
+ });
+
+ expect(serializeUrl('https://univer.ai')).toBe('https://univer.ai');
+ expect(serializeUrl('not a legal link')).toBe('not a legal link');
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/controllers/__tests__/auto-fill.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/__tests__/auto-fill.controller.spec.ts
new file mode 100644
index 0000000000..70275782f9
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/__tests__/auto-fill.controller.spec.ts
@@ -0,0 +1,91 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { AUTO_FILL_APPLY_TYPE } from '@univerjs/sheets';
+import { AddHyperLinkMutation, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsHyperLinkAutoFillController } from '../auto-fill.controller';
+
+describe('SheetsHyperLinkAutoFillController', () => {
+ it('should generate add/remove link mutations when copying', () => {
+ let capturedHook: any;
+ const addHook = vi.fn((hook) => {
+ capturedHook = hook;
+ return { dispose: vi.fn() };
+ });
+
+ const autoFillService = {
+ addHook,
+ } as any;
+
+ const hyperLinkModel = {
+ getHyperLinkByLocation: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {
+ if (unitId !== 'u1' || subUnitId !== 's1') return null;
+ if (row === 0 && col === 0) {
+ return { id: 'link-1', payload: '#gid=sheet&range=A1', row, column: col };
+ }
+ if (row === 1 && col === 0) {
+ return { id: 'current-link', payload: '#gid=sheet&range=A2', row, column: col };
+ }
+ return null;
+ }),
+ } as any;
+
+ // init registers hook
+ const controller = new SheetsHyperLinkAutoFillController(autoFillService, hyperLinkModel);
+ expect(addHook).toHaveBeenCalledTimes(1);
+
+ const res = capturedHook.onFillData({
+ unitId: 'u1',
+ subUnitId: 's1',
+ source: { rows: [0], cols: [0] },
+ // target should be the filled destination range, not including source
+ target: { rows: [1], cols: [0] },
+ }, 'DOWN', AUTO_FILL_APPLY_TYPE.COPY);
+
+ expect(res.redos.map((m: any) => m.id)).toEqual([RemoveHyperLinkMutation.id, AddHyperLinkMutation.id]);
+ expect(res.undos.map((m: any) => m.id)).toEqual([RemoveHyperLinkMutation.id, AddHyperLinkMutation.id]);
+
+ controller.dispose();
+ });
+
+ it('should return noop mutations for non-copy apply type', () => {
+ let capturedHook: any;
+ const autoFillService = {
+ addHook: vi.fn((hook) => {
+ capturedHook = hook;
+ return { dispose: vi.fn() };
+ }),
+ } as any;
+
+ const hyperLinkModel = {
+ getHyperLinkByLocation: vi.fn(() => null),
+ } as any;
+
+ const controller = new SheetsHyperLinkAutoFillController(autoFillService, hyperLinkModel);
+
+ const res = capturedHook.onFillData({
+ unitId: 'u1',
+ subUnitId: 's1',
+ source: { rows: [0], cols: [0] },
+ target: { rows: [0, 1], cols: [0] },
+ }, 'DOWN', AUTO_FILL_APPLY_TYPE.NO_FORMAT);
+
+ expect(res).toEqual({ redos: [], undos: [] });
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/controllers/__tests__/copy-paste.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/__tests__/copy-paste.controller.spec.ts
new file mode 100644
index 0000000000..26b1a9142f
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/__tests__/copy-paste.controller.spec.ts
@@ -0,0 +1,103 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { AddHyperLinkMutation, RemoveHyperLinkMutation } from '@univerjs/sheets-hyper-link';
+import { COPY_TYPE, PREDEFINED_HOOK_NAME_PASTE } from '@univerjs/sheets-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsHyperLinkCopyPasteController } from '../copy-paste.controller';
+
+describe('SheetsHyperLinkCopyPasteController', () => {
+ it('should generate remove/add mutations when pasting a copied hyperlink cell', () => {
+ let hook: any;
+ const addClipboardHook = vi.fn((h) => {
+ hook = h;
+ });
+
+ const sheetClipboardService = {
+ addClipboardHook,
+ } as any;
+
+ const hyperLinkModel = {
+ getHyperLinkByLocation: vi.fn((unitId: string, subUnitId: string, row: number, col: number) => {
+ if (unitId === 'u1' && subUnitId === 's1' && row === 0 && col === 0) {
+ return { id: 'old-id', payload: '#gid=s1&range=A1', row, column: col };
+ }
+
+ if (unitId === 'u2' && subUnitId === 's2' && row === 1 && col === 1) {
+ return { id: 'current-id', payload: '#gid=s2&range=B2', row, column: col };
+ }
+
+ return null;
+ }),
+ getHyperLink: vi.fn((unitId: string, subUnitId: string, id: string) => {
+ if (unitId === 'u1' && subUnitId === 's1' && id === 'old-id') {
+ return { id, payload: '#gid=s1&range=A1', row: 0, column: 0 };
+ }
+ return null;
+ }),
+ } as any;
+
+ const injector = {
+ invoke: vi.fn(() => ({ rows: [0], cols: [0] })),
+ } as any;
+
+ const resolverService = {} as any;
+
+ const controller = new SheetsHyperLinkCopyPasteController(sheetClipboardService, hyperLinkModel, injector, resolverService);
+ expect(addClipboardHook).toHaveBeenCalledTimes(1);
+
+ // Simulate copy stage
+ hook.onBeforeCopy('u1', 's1', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 });
+
+ const res = hook.onPasteCells(
+ { range: { rows: [0], cols: [0] } },
+ { unitId: 'u2', subUnitId: 's2', range: { rows: [1], cols: [1] } },
+ null,
+ { copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE, copyRange: { rows: [0], cols: [0] } }
+ );
+
+ expect(res.redos.map((m: any) => m.id)).toEqual([RemoveHyperLinkMutation.id, AddHyperLinkMutation.id]);
+ expect(res.undos.map((m: any) => m.id)).toEqual([RemoveHyperLinkMutation.id, AddHyperLinkMutation.id]);
+
+ controller.dispose();
+ });
+
+ it('should ignore special paste types', () => {
+ let hook: any;
+ const sheetClipboardService = {
+ addClipboardHook: vi.fn((h) => {
+ hook = h;
+ }),
+ } as any;
+ const hyperLinkModel = { getHyperLinkByLocation: vi.fn(), getHyperLink: vi.fn() } as any;
+ const injector = { invoke: vi.fn(() => ({ rows: [0], cols: [0] })) } as any;
+ const resolverService = {} as any;
+
+ const controller = new SheetsHyperLinkCopyPasteController(sheetClipboardService, hyperLinkModel, injector, resolverService);
+ hook.onBeforeCopy('u1', 's1', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 });
+
+ const res = hook.onPasteCells(
+ { range: { rows: [0], cols: [0] } },
+ { unitId: 'u2', subUnitId: 's2', range: { rows: [1], cols: [1] } },
+ null,
+ { copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE, copyRange: { rows: [0], cols: [0] } }
+ );
+
+ expect(res).toEqual({ redos: [], undos: [] });
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/controllers/__tests__/hyper-link-permission.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/__tests__/hyper-link-permission.controller.spec.ts
new file mode 100644
index 0000000000..d670fb95b1
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/__tests__/hyper-link-permission.controller.spec.ts
@@ -0,0 +1,75 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { InsertLinkShortcut } from '../../menu/menu';
+import { SheetsHyperLinkPermissionController } from '../hyper-link-permission.controller';
+
+describe('SheetsHyperLinkPermissionController', () => {
+ let beforeCommandExecuted: any;
+
+ beforeEach(() => {
+ beforeCommandExecuted = undefined;
+ });
+
+ it('should block shortcut execution when permission fails', () => {
+ const localeService = { t: (key: string) => key } as any;
+
+ const commandService = {
+ beforeCommandExecuted: vi.fn((fn) => {
+ beforeCommandExecuted = fn;
+ return { dispose: vi.fn() };
+ }),
+ } as any;
+
+ const blockExecuteWithoutPermission = vi.fn();
+ const sheetPermissionCheckController = {
+ permissionCheckWithRanges: vi.fn(() => false),
+ blockExecuteWithoutPermission,
+ } as any;
+
+ const controller = new SheetsHyperLinkPermissionController(localeService, commandService, sheetPermissionCheckController);
+
+ beforeCommandExecuted({ id: InsertLinkShortcut.id });
+ expect(blockExecuteWithoutPermission).toHaveBeenCalledWith('permission.dialog.hyperLinkErr');
+
+ controller.dispose();
+ });
+
+ it('should not block when permission passes', () => {
+ const localeService = { t: (key: string) => key } as any;
+
+ const commandService = {
+ beforeCommandExecuted: vi.fn((fn) => {
+ beforeCommandExecuted = fn;
+ return { dispose: vi.fn() };
+ }),
+ } as any;
+
+ const blockExecuteWithoutPermission = vi.fn();
+ const sheetPermissionCheckController = {
+ permissionCheckWithRanges: vi.fn(() => true),
+ blockExecuteWithoutPermission,
+ } as any;
+
+ const controller = new SheetsHyperLinkPermissionController(localeService, commandService, sheetPermissionCheckController);
+ beforeCommandExecuted({ id: InsertLinkShortcut.id });
+ expect(blockExecuteWithoutPermission).not.toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/controllers/__tests__/render.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/__tests__/render.controller.spec.ts
new file mode 100644
index 0000000000..dfca7e81c8
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/__tests__/render.controller.spec.ts
@@ -0,0 +1,98 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+
+import { SheetsHyperLinkRenderController, SheetsHyperLinkRenderManagerController } from '../render-controllers/render.controller';
+
+describe('SheetsHyperLinkRenderController', () => {
+ it('should mark skeleton dirty when link updates', async () => {
+ const makeForceDirty = vi.fn();
+ const linkUpdate$ = new Subject<void>();
+
+ const controller = new SheetsHyperLinkRenderController({
+ mainComponent: { makeForceDirty },
+ } as any, { linkUpdate$ } as any);
+
+ linkUpdate$.next();
+
+ // debounced by 16ms
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ expect(makeForceDirty).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+});
+
+describe('SheetsHyperLinkRenderManagerController', () => {
+ it('should inject link fields into cell content interceptor', () => {
+ let interceptorHandler: any;
+
+ const sheetInterceptorService = {
+ intercept: vi.fn((_point: any, config: any) => {
+ interceptorHandler = config.handler;
+ return { dispose: vi.fn() };
+ }),
+ } as any;
+
+ const hyperLinkModel = {
+ getHyperLinkByLocation: vi.fn(() => ({ id: 'l1', payload: '#gid=s1&range=A1' })),
+ } as any;
+
+ const controller = new SheetsHyperLinkRenderManagerController(sheetInterceptorService, hyperLinkModel);
+ expect(sheetInterceptorService.intercept).toHaveBeenCalledTimes(1);
+
+ const next = vi.fn((v) => v);
+ const rawData = { v: 1 };
+ const cell = rawData;
+ const result = interceptorHandler(cell, { row: 0, col: 0, unitId: 'u1', subUnitId: 's1', rawData }, next);
+
+ expect(result).toEqual(expect.objectContaining({
+ linkUrl: '#gid=s1&range=A1',
+ linkId: 'l1',
+ }));
+ expect(next).toHaveBeenCalledTimes(1);
+ // should not mutate rawData
+ expect(rawData).toEqual({ v: 1 });
+
+ controller.dispose();
+ });
+
+ it('should passthrough when cell is empty or has no link', () => {
+ let interceptorHandler: any;
+
+ const sheetInterceptorService = {
+ intercept: vi.fn((_point: any, config: any) => {
+ interceptorHandler = config.handler;
+ return { dispose: vi.fn() };
+ }),
+ } as any;
+
+ const hyperLinkModel = {
+ getHyperLinkByLocation: vi.fn(() => null),
+ } as any;
+
+ const controller = new SheetsHyperLinkRenderManagerController(sheetInterceptorService, hyperLinkModel);
+
+ const next = vi.fn((v) => v);
+ const out = interceptorHandler(null, { row: 0, col: 0, unitId: 'u1', subUnitId: 's1', rawData: null }, next);
+ expect(out).toBe(null);
+ expect(next).toHaveBeenCalledWith(null);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/sheets-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts
new file mode 100644
index 0000000000..61065da495
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/controllers/__tests__/ui.controller.spec.ts
@@ -0,0 +1,44 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { SheetsHyperLinkUIController } from '../ui.controller';
+
+describe('SheetsHyperLinkUIController', () => {
+ it('should register components, commands, menu and shortcut', () => {
+ const componentManager = { register: vi.fn() } as any;
+ const commandService = { registerCommand: vi.fn() } as any;
+ const menuManagerService = { mergeMenu: vi.fn() } as any;
+ const injector = {} as any;
+ const shortcutService = { registerShortcut: vi.fn() } as any;
+
+ const controller = new SheetsHyperLinkUIController(
+ componentManager,
+ commandService,
+ menuManagerService,
+ injector,
+ shortcutService
+ );
+
+ expect(componentManager.register).toHaveBeenCalled();
+ expect(commandService.registerCommand).toHaveBeenCalled();
+ expect(menuManagerService.mergeMenu).toHaveBeenCalled();
+ expect(shortcutService.registerShortcut).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.ts
new file mode 100644
index 0000000000..04cb60c58f
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/popup.service.spec.ts
@@ -0,0 +1,237 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CustomRangeType, DOCS_ZEN_EDITOR_UNIT_ID_KEY, Injector } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { HyperLinkEditSourceType } from '../../types/enums/edit-source';
+import { SheetsHyperLinkPopupService } from '../popup.service';
+
+function createDisposable() {
+ return {
+ dispose: vi.fn(),
+ canDispose: vi.fn(() => true),
+ };
+}
+
+function createService(options?: {
+ workbook?: unknown;
+ document?: unknown;
+ zenVisible?: boolean;
+}) {
+ const cellDisposable = createDisposable();
+ const positionDisposable = createDisposable();
+ const absoluteDisposable = createDisposable();
+ const docDisposable = createDisposable();
+
+ const sheetCanvasPopManagerService = {
+ attachPopupToCell: vi.fn(() => cellDisposable),
+ attachPopupByPosition: vi.fn(() => positionDisposable),
+ attachPopupToAbsolutePosition: vi.fn(() => absoluteDisposable),
+ };
+ const docCanvasPopManagerService = {
+ attachPopupToRange: vi.fn(() => docDisposable),
+ };
+ const textSelectionManagerService = {
+ getActiveTextRange: vi.fn(() => ({ startOffset: 1, endOffset: 3, collapsed: false })),
+ replaceDocRanges: vi.fn(),
+ replaceTextRanges: vi.fn(),
+ };
+ const univerInstanceService = {
+ getUnit: vi.fn((unitId: string) => {
+ if (unitId === DOCS_ZEN_EDITOR_UNIT_ID_KEY) {
+ return options?.document ?? null;
+ }
+ return options?.workbook ?? null;
+ }),
+ };
+
+ return {
+ service: new SheetsHyperLinkPopupService(
+ sheetCanvasPopManagerService as never,
+ new Injector(),
+ univerInstanceService as never,
+ { isVisible: () => ({ visible: false }), getEditCellState: vi.fn() } as never,
+ textSelectionManagerService as never,
+ docCanvasPopManagerService as never,
+ { visible: options?.zenVisible ?? false } as never
+ ),
+ sheetCanvasPopManagerService,
+ docCanvasPopManagerService,
+ textSelectionManagerService,
+ cellDisposable,
+ };
+}
+
+describe('SheetsHyperLinkPopupService', () => {
+ it('shows and hides cell popups without recreating the same viewing popup', () => {
+ const { service, sheetCanvasPopManagerService, cellDisposable } = createService();
+
+ service.showPopup({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 2,
+ showAll: true,
+ editPermission: true,
+ copyPermission: true,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+
+ expect(sheetCanvasPopManagerService.attachPopupToCell).toHaveBeenCalledTimes(1);
+ expect(service.currentPopup).toEqual(expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 2,
+ showAll: true,
+ type: HyperLinkEditSourceType.VIEWING,
+ }));
+
+ service.showPopup({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 2,
+ showAll: true,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+
+ expect(sheetCanvasPopManagerService.attachPopupToCell).toHaveBeenCalledTimes(1);
+
+ service.hideCurrentPopup();
+ expect(cellDisposable.dispose).toHaveBeenCalledTimes(1);
+ expect(service.currentPopup).toBeNull();
+ });
+
+ it('routes popups by source type and blocks sheet popups while zen mode is visible', () => {
+ const blocked = createService({ zenVisible: true });
+
+ blocked.service.showPopup({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 0,
+ col: 0,
+ customRange: { rangeId: 'r1', startIndex: 1, endIndex: 3, rangeType: CustomRangeType.HYPERLINK },
+ customRangeRect: { left: 0, top: 0, right: 10, bottom: 10 },
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ expect(blocked.service.currentPopup).toBeNull();
+
+ const active = createService({ zenVisible: false });
+
+ active.service.showPopup({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 0,
+ col: 0,
+ customRange: { rangeId: 'r1', startIndex: 1, endIndex: 3, rangeType: CustomRangeType.HYPERLINK },
+ customRangeRect: { left: 0, top: 0, right: 10, bottom: 10 },
+ type: HyperLinkEditSourceType.EDITING,
+ });
+ expect(active.sheetCanvasPopManagerService.attachPopupToAbsolutePosition).toHaveBeenCalledTimes(1);
+
+ active.service.showPopup({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 0,
+ col: 0,
+ customRange: { rangeId: 'r2', startIndex: 2, endIndex: 4, rangeType: CustomRangeType.HYPERLINK },
+ customRangeRect: { left: 1, top: 1, right: 9, bottom: 9 },
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ expect(active.sheetCanvasPopManagerService.attachPopupByPosition).toHaveBeenCalledTimes(1);
+
+ active.service.showPopup({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 0,
+ col: 0,
+ customRange: { rangeId: 'r3', startIndex: 0, endIndex: 2, rangeType: CustomRangeType.HYPERLINK },
+ type: HyperLinkEditSourceType.ZEN_EDITOR,
+ });
+ expect(active.docCanvasPopManagerService.attachPopupToRange).toHaveBeenCalledWith({
+ startOffset: 0,
+ endOffset: 3,
+ collapsed: false,
+ }, expect.any(Object), DOCS_ZEN_EDITOR_UNIT_ID_KEY);
+ expect(blocked.sheetCanvasPopManagerService.attachPopupByPosition).not.toHaveBeenCalled();
+ });
+
+ it('starts viewing edits from cell content and preserves editor state while keep-visible is enabled', () => {
+ const workbook = {
+ getSheetBySheetId: () => ({
+ getCellRaw: () => ({ v: 'Cell Value' }),
+ }),
+ };
+ const { service, sheetCanvasPopManagerService } = createService({ workbook });
+
+ service.startAddEditing({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 1,
+ type: HyperLinkEditSourceType.VIEWING,
+ });
+ expect(sheetCanvasPopManagerService.attachPopupToCell).toHaveBeenCalledTimes(1);
+ expect(service.currentEditing).toEqual(expect.objectContaining({
+ label: 'Cell Value',
+ type: HyperLinkEditSourceType.VIEWING,
+ }));
+
+ service.setIsKeepVisible(true);
+ service.endEditing();
+ expect(service.currentEditing).toEqual(expect.objectContaining({ type: HyperLinkEditSourceType.VIEWING }));
+
+ service.setIsKeepVisible(false);
+ service.endEditing(HyperLinkEditSourceType.VIEWING);
+ expect(service.currentEditing).toBeNull();
+ });
+
+ it('starts zen editor editing from the real custom range in the zen document', () => {
+ const document = {
+ getBody: () => ({
+ dataStream: 'abcdef',
+ customRanges: [{ rangeId: 'range-3', startIndex: 1, endIndex: 3, rangeType: CustomRangeType.HYPERLINK }],
+ }),
+ };
+ const { service, docCanvasPopManagerService, textSelectionManagerService } = createService({ document });
+
+ service.startEditing({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 1,
+ col: 1,
+ customRangeId: 'range-3',
+ type: HyperLinkEditSourceType.ZEN_EDITOR,
+ });
+
+ expect(textSelectionManagerService.replaceTextRanges).toHaveBeenCalledWith([
+ {
+ startOffset: 1,
+ endOffset: 4,
+ },
+ ]);
+ expect(docCanvasPopManagerService.attachPopupToRange).toHaveBeenCalledWith({
+ startOffset: 1,
+ endOffset: 3,
+ collapsed: false,
+ }, expect.any(Object), DOCS_ZEN_EDITOR_UNIT_ID_KEY);
+ expect(service.currentEditing).toEqual(expect.objectContaining({
+ label: 'bcd',
+ type: HyperLinkEditSourceType.ZEN_EDITOR,
+ }));
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts
new file mode 100644
index 0000000000..b02a0a82b0
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/resolver.service.spec.ts
@@ -0,0 +1,182 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { SetSelectionsOperation, SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
+import { ScrollToRangeOperation } from '@univerjs/sheets-ui';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { SheetsHyperLinkResolverService } from '../resolver.service';
+
+describe('SheetsHyperLinkResolverService', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('should navigate to sheet ranges and execute selection and scroll commands', async () => {
+ const executeCommand = vi.fn(async (id: string) => id === SetWorksheetActiveOperation.id);
+ const worksheet = {
+ getSheetId: () => 'sheet-2',
+ getMergeData: () => [{ startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 }],
+ getMaxColumns: () => 10,
+ getMaxRows: () => 10,
+ };
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ getSheetBySheetId: (sheetId: string) => (sheetId === 'sheet-2' ? worksheet : null),
+ getHiddenWorksheets: () => [],
+ };
+
+ const resolver = new SheetsHyperLinkResolverService(
+ {
+ getCurrentUnitForType: () => workbook,
+ getUnit: () => workbook,
+ } as any,
+ { executeCommand } as any,
+ {
+ getValueById: vi.fn(),
+ getWorksheetByRef: vi.fn(),
+ focusRange: vi.fn(),
+ } as any,
+ { show: vi.fn() } as any,
+ { t: (key: string) => key } as any,
+ { getConfig: vi.fn(() => undefined) } as any
+ );
+
+ await resolver.navigateToRange('unit-1', 'sheet-2', { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }, true);
+
+ expect(executeCommand).toHaveBeenCalledWith(SetWorksheetActiveOperation.id, { unitId: 'unit-1', subUnitId: 'sheet-2' });
+ expect(executeCommand).toHaveBeenCalledWith(SetSelectionsOperation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-2',
+ selections: [{ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 }, primary: null }],
+ });
+ expect(executeCommand).toHaveBeenCalledWith(ScrollToRangeOperation.id, {
+ range: { startRow: 1, endRow: 1, startColumn: 1, endColumn: 1 },
+ forceTop: true,
+ });
+ });
+
+ it('should show user-facing errors when target sheets or defined names are invalid', async () => {
+ const show = vi.fn();
+ const focusRange = vi.fn();
+ const getWorksheetByRef = vi.fn()
+ .mockReturnValueOnce(null)
+ .mockReturnValueOnce({ isSheetHidden: () => true })
+ .mockReturnValueOnce({ isSheetHidden: () => false });
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ getSheetBySheetId: () => null,
+ getHiddenWorksheets: () => ['sheet-hidden'],
+ };
+ const executeCommand = vi.fn(async () => false);
+
+ const resolver = new SheetsHyperLinkResolverService(
+ {
+ getCurrentUnitForType: () => workbook,
+ getUnit: () => workbook,
+ } as any,
+ { executeCommand } as any,
+ {
+ getValueById: (_unitId: string, rangeId: string) => (rangeId === 'named-range' ? { formulaOrRefString: 'Sheet1!A1' } : undefined),
+ getWorksheetByRef,
+ focusRange,
+ } as any,
+ { show } as any,
+ { t: (key: string) => key } as any,
+ { getConfig: vi.fn(() => undefined) } as any
+ );
+
+ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'named-range' } } as any);
+ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'named-range' } } as any);
+ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { rangeid: 'named-range' } } as any);
+
+ await resolver.navigateToSheetById('unit-1', 'sheet-missing');
+ await resolver.navigateToSheetById('unit-1', 'sheet-hidden');
+
+ expect(show).toHaveBeenCalledWith({ content: 'hyperLink.message.refError', type: 'error' });
+ expect(show).toHaveBeenCalledWith({ content: 'hyperLink.message.hiddenSheet', type: 'error' });
+ expect(show).toHaveBeenCalledWith({ content: 'hyperLink.message.noSheet', type: 'error' });
+ expect(focusRange).toHaveBeenCalledWith('unit-1', 'named-range');
+ });
+
+ it('should open external links via configured handlers or fallback window.open', async () => {
+ const navigateToOtherWebsite = vi.fn();
+ const open = vi.fn();
+ vi.stubGlobal('window', { open });
+
+ const resolver = new SheetsHyperLinkResolverService(
+ {
+ getCurrentUnitForType: () => null,
+ getUnit: () => null,
+ } as any,
+ { executeCommand: vi.fn() } as any,
+ {
+ getValueById: vi.fn(),
+ getWorksheetByRef: vi.fn(),
+ focusRange: vi.fn(),
+ } as any,
+ { show: vi.fn() } as any,
+ { t: (key: string) => key } as any,
+ {
+ getConfig: vi.fn()
+ .mockReturnValueOnce({ urlHandler: { navigateToOtherWebsite } })
+ .mockReturnValueOnce(undefined),
+ } as any
+ );
+
+ await resolver.navigateToOtherWebsite('https://univer.ai');
+ await resolver.navigateToOtherWebsite('https://openai.com');
+
+ expect(navigateToOtherWebsite).toHaveBeenCalledWith('https://univer.ai');
+ expect(open).toHaveBeenCalledWith('https://openai.com', '_blank', 'noopener noreferrer');
+ });
+
+ it('should interpret workbook-style links through the public navigate entry', () => {
+ const executeCommand = vi.fn(async () => true);
+ const workbook = {
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ getSheetBySheetId: () => ({
+ getSheetId: () => 'sheet-2',
+ getMergeData: () => [],
+ getMaxColumns: () => 10,
+ getMaxRows: () => 10,
+ }),
+ getHiddenWorksheets: () => [],
+ };
+ const resolver = new SheetsHyperLinkResolverService(
+ {
+ getCurrentUnitForType: () => workbook,
+ getUnit: () => workbook,
+ } as any,
+ { executeCommand } as any,
+ {
+ getValueById: vi.fn(),
+ getWorksheetByRef: vi.fn(),
+ focusRange: vi.fn(),
+ } as any,
+ { show: vi.fn() } as any,
+ { t: (key: string) => key } as any,
+ { getConfig: vi.fn(() => undefined) } as any
+ );
+
+ resolver.navigate({ type: SheetHyperLinkType.SHEET, searchObj: { gid: 'sheet-2', range: 'B2:C3' } } as any);
+
+ expect(executeCommand).toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.ts b/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.ts
new file mode 100644
index 0000000000..c820c5e9f6
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/services/__tests__/side-panel.service.spec.ts
@@ -0,0 +1,47 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { SheetHyperLinkType } from '@univerjs/sheets-hyper-link';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsHyperLinkSidePanelService } from '../side-panel.service';
+
+describe('SheetsHyperLinkSidePanelService', () => {
+ it('should register, resolve and remove custom hyperlink views', () => {
+ const service = new SheetsHyperLinkSidePanelService();
+ const customView = {
+ type: 'sheet-anchor',
+ option: { label: 'Sheet Anchor', value: 'sheet-anchor' },
+ Form: vi.fn(),
+ convert: vi.fn(() => ({ display: 'A1', payload: '#A1', type: 'sheet-anchor' })),
+ match: vi.fn((link) => link.payload === '#A1'),
+ };
+
+ expect(service.isBuiltInLinkType(SheetHyperLinkType.URL)).toBe(false);
+ expect(service.isBuiltInLinkType('custom')).toBe(true);
+
+ service.registerCustomHyperLink(customView as any);
+ expect(service.getOptions()).toEqual([customView.option]);
+ expect(service.getCustomHyperLink('sheet-anchor')).toBe(customView);
+ expect(service.findCustomHyperLink({ payload: '#A1' } as any)).toBe(customView);
+
+ service.removeCustomHyperLink('sheet-anchor');
+ expect(service.getCustomHyperLink('sheet-anchor')).toBeUndefined();
+
+ service.registerCustomHyperLink(customView as any);
+ service.dispose();
+ expect(service.getOptions()).toEqual([]);
+ });
+});
diff --git a/packages/sheets-hyper-link-ui/src/utils/__tests__/index.spec.ts b/packages/sheets-hyper-link-ui/src/utils/__tests__/index.spec.ts
new file mode 100644
index 0000000000..8b65f0dd8e
--- /dev/null
+++ b/packages/sheets-hyper-link-ui/src/utils/__tests__/index.spec.ts
@@ -0,0 +1,94 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { DataValidationType, IUniverInstanceService } from '@univerjs/core';
+import { DocSelectionManagerService } from '@univerjs/docs';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { SheetDataValidationModel } from '@univerjs/sheets-data-validation';
+import { describe, expect, it } from 'vitest';
+import { DisableLinkType, getShouldDisableCellLink, getShouldDisableCurrentCellLink, shouldDisableAddLink } from '../index';
+
+function createAccessor(map: Array<[unknown, unknown]>) {
+ const tokenMap = new Map(map);
+ return {
+ get: (token: unknown) => tokenMap.get(token),
+ has: (token: unknown) => tokenMap.has(token),
+ } as any;
+}
+
+describe('hyper-link utils', () => {
+ it('should disable cell links for formulas, custom blocks and data validation rules', () => {
+ const worksheet = {
+ getCell: () => ({ f: '=SUM(A1:A2)' }),
+ getUnitId: () => 'unit-1',
+ getSheetId: () => 'sheet-1',
+ };
+
+ expect(getShouldDisableCellLink(createAccessor([]), worksheet as any, 0, 0)).toBe(DisableLinkType.DISABLED_BY_CELL);
+
+ const worksheetWithBlocks = {
+ ...worksheet,
+ getCell: () => ({ p: { body: { customBlocks: [{}] } } }),
+ };
+ expect(getShouldDisableCellLink(createAccessor([]), worksheetWithBlocks as any, 0, 0)).toBe(DisableLinkType.DISABLED_BY_CELL);
+
+ const accessor = createAccessor([
+ [SheetDataValidationModel, { getRuleByLocation: () => ({ type: DataValidationType.CHECKBOX }) }],
+ ]);
+ const plainWorksheet = {
+ ...worksheet,
+ getCell: () => ({}),
+ };
+
+ expect(getShouldDisableCellLink(accessor, plainWorksheet as any, 1, 1)).toBe(true);
+ });
+
+ it('should allow editing-only links for drawing cells and inspect the current selection', () => {
+ const worksheet = {
+ getCell: () => ({ p: { drawingsOrder: ['drawing-1'] } }),
+ getUnitId: () => 'unit-1',
+ getSheetId: () => 'sheet-1',
+ };
+
+ expect(getShouldDisableCellLink(createAccessor([]), worksheet as any, 0, 0)).toBe(DisableLinkType.ALLOW_ON_EDITING);
+
+ const currentAccessor = createAccessor([
+ [IUniverInstanceService, { getCurrentUnitForType: () => ({ getActiveSheet: () => worksheet }) }],
+ [SheetsSelectionsService, { getCurrentSelections: () => [{ range: { startRow: 0, startColumn: 0 } }] }],
+ ]);
+
+ expect(getShouldDisableCurrentCellLink(currentAccessor)).toBe(false);
+ });
+
+ it('should disable add-link when editor selection is missing and allow it with valid rich text context', () => {
+ const noSelectionAccessor = createAccessor([
+ [DocSelectionManagerService, { getTextRanges: () => [] }],
+ [IUniverInstanceService, { getCurrentUnitForType: () => null }],
+ ]);
+ expect(shouldDisableAddLink(noSelectionAccessor)).toBe(true);
+
+ const validAccessor = createAccessor([
+ [DocSelectionManagerService, { getTextRanges: () => [{ collapsed: false, segmentId: 'body' }] }],
+ [IUniverInstanceService, {
+ getCurrentUnitForType: () => ({
+ getSelfOrHeaderFooterModel: () => ({ getBody: () => ({ dataStream: 'hello\r\n' }) }),
+ }),
+ }],
+ ]);
+
+ expect(shouldDisableAddLink(validAccessor)).toBe(false);
+ });
+});
diff --git a/packages/sheets-note/package.json b/packages/sheets-note/package.json
index 185b31b577..dd376b2ae9 100644
--- a/packages/sheets-note/package.json
+++ b/packages/sheets-note/package.json
@@ -75,6 +75,9 @@
},
"devDependencies": {
"@univerjs-infra/shared": "workspace:*",
+ "@univerjs/engine-formula": "workspace:*",
+ "@univerjs/engine-render": "workspace:*",
+ "@univerjs/network": "workspace:*",
"rxjs": "^7.8.2",
"typescript": "^5.9.3",
"vite": "^7.3.1",
diff --git a/packages/sheets-note/src/commands/commands/__tests__/note.command.spec.ts b/packages/sheets-note/src/commands/commands/__tests__/note.command.spec.ts
new file mode 100644
index 0000000000..05bc9539db
--- /dev/null
+++ b/packages/sheets-note/src/commands/commands/__tests__/note.command.spec.ts
@@ -0,0 +1,222 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IWorkbookData } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import type { ISheetNote } from '../../../models/sheets-note.model';
+import {
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ RANGE_TYPE,
+ touchDependencies,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { SheetsNoteModel } from '../../../models/sheets-note.model';
+import { RemoveNoteMutation, ToggleNotePopupMutation, UpdateNoteMutation } from '../../mutations/note.mutation';
+import { SheetDeleteNoteCommand, SheetToggleNotePopupCommand, SheetUpdateNoteCommand } from '../note.command';
+
+const unitId = 'test';
+const subUnitId = 'sheet1';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: unitId,
+ sheetOrder: [subUnitId],
+ name: '',
+ appVersion: '0.15.4',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheets: {
+ [subUnitId]: {
+ id: subUnitId,
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 10,
+ cellData: {},
+ },
+ },
+};
+
+function createCommandTestBed() {
+ 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 {
+ // Ensure undo/redo exists and registers commands.
+ this._injector.get(IUndoRedoService);
+
+ this._injector.add([SheetsSelectionsService]);
+ this._injector.add([SheetsNoteModel]);
+
+ touchDependencies(this._injector, [
+ [SheetsSelectionsService],
+ [SheetsNoteModel],
+ ]);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, TEST_WORKBOOK_DATA);
+ get(IUniverInstanceService).focusUnit(unitId);
+
+ const logService = get(ILogService);
+ logService.setLogLevel(LogLevel.SILENT);
+
+ const commandService = get(ICommandService);
+ commandService.registerCommand(UpdateNoteMutation);
+ commandService.registerCommand(RemoveNoteMutation);
+ commandService.registerCommand(ToggleNotePopupMutation);
+ commandService.registerCommand(SheetUpdateNoteCommand);
+ commandService.registerCommand(SheetDeleteNoteCommand);
+ commandService.registerCommand(SheetToggleNotePopupCommand);
+
+ return {
+ univer,
+ get,
+ injector,
+ commandService,
+ };
+}
+
+function setSingleCellSelection(get: Injector['get'], row: number, col: number) {
+ const selections = get(SheetsSelectionsService);
+ const selection: ISelectionWithStyle = {
+ range: {
+ startRow: row,
+ endRow: row + 1,
+ startColumn: col,
+ endColumn: col + 1,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: {
+ startRow: row,
+ endRow: row + 1,
+ startColumn: col,
+ endColumn: col + 1,
+ actualRow: row,
+ actualColumn: col,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ };
+
+ selections.setSelections([selection]);
+}
+
+describe('sheets-note commands', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ const testBed = createCommandTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = testBed.commandService;
+ });
+
+ afterEach(() => univer.dispose());
+
+ it('SheetUpdateNoteCommand pushes undo correctly (new note -> undo removes)', async () => {
+ const note: ISheetNote = { id: 'n1', row: 1, col: 2, width: 160, height: 72, note: 'hello' };
+
+ const res = commandService.syncExecuteCommand(SheetUpdateNoteCommand.id, {
+ unitId,
+ sheetId: subUnitId,
+ row: 1,
+ col: 2,
+ note,
+ });
+ expect(res).toBeTruthy();
+
+ const model = get(SheetsNoteModel);
+ expect(model.getNote(unitId, subUnitId, { row: 1, col: 2 })?.note).toBe('hello');
+
+ // Undo should remove the note.
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 1, col: 2 })).toBeUndefined();
+ });
+
+ it('SheetUpdateNoteCommand pushes undo correctly (existing note -> undo restores)', async () => {
+ const model = get(SheetsNoteModel);
+ model.updateNote(unitId, subUnitId, 1, 2, { id: 'n2', row: 1, col: 2, width: 160, height: 72, note: 'old' });
+
+ const note: ISheetNote = { id: 'n2', row: 1, col: 2, width: 160, height: 72, note: 'new' };
+ const res = commandService.syncExecuteCommand(SheetUpdateNoteCommand.id, {
+ unitId,
+ sheetId: subUnitId,
+ row: 1,
+ col: 2,
+ note,
+ });
+ expect(res).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 1, col: 2 })?.note).toBe('new');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 1, col: 2 })?.note).toBe('old');
+ });
+
+ it('SheetDeleteNoteCommand removes note at current selection and supports undo', async () => {
+ const model = get(SheetsNoteModel);
+ model.updateNote(unitId, subUnitId, 2, 3, { id: 'n3', row: 2, col: 3, width: 160, height: 72, note: 'to delete' });
+ setSingleCellSelection(get, 2, 3);
+
+ const res = commandService.syncExecuteCommand(SheetDeleteNoteCommand.id);
+ expect(res).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 2, col: 3 })).toBeUndefined();
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 2, col: 3 })?.note).toBe('to delete');
+ });
+
+ it('SheetToggleNotePopupCommand toggles show state at current selection and supports undo', async () => {
+ const model = get(SheetsNoteModel);
+ model.updateNote(unitId, subUnitId, 4, 4, { id: 'n4', row: 4, col: 4, width: 160, height: 72, note: 'toggle', show: false });
+ setSingleCellSelection(get, 4, 4);
+
+ const res = commandService.syncExecuteCommand(SheetToggleNotePopupCommand.id);
+ expect(res).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 4, col: 4 })?.show).toBe(true);
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 4, col: 4 })?.show).toBe(false);
+ });
+
+ // Avoid directly asserting pure exports without business value.
+});
diff --git a/packages/sheets-note/src/controllers/__tests__/sheets-note-resource.controller.spec.ts b/packages/sheets-note/src/controllers/__tests__/sheets-note-resource.controller.spec.ts
new file mode 100644
index 0000000000..e479ed1efe
--- /dev/null
+++ b/packages/sheets-note/src/controllers/__tests__/sheets-note-resource.controller.spec.ts
@@ -0,0 +1,258 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES 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 { ICopySheetCommandParams, IRemoveSheetCommandParams } from '@univerjs/sheets';
+import type { ISheetNote } from '../../models/sheets-note.model';
+import {
+ ICommandService,
+ ILogService,
+ Inject,
+ Injector,
+ IResourceManagerService,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LocaleService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ touchDependencies,
+ UndoCommand,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ CopySheetCommand,
+ CopyWorksheetEndMutation,
+ InsertColByRangeCommand,
+ InsertColMutation,
+ InsertRowByRangeCommand,
+ InsertRowMutation,
+ InsertSheetMutation,
+ RemoveColByRangeCommand,
+ RemoveColMutation,
+ RemoveRowByRangeCommand,
+ RemoveRowMutation,
+ RemoveSheetCommand,
+ RemoveSheetMutation,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetActivateCommand,
+ SetWorksheetActiveOperation,
+ SheetInterceptorService,
+ SheetLazyExecuteScheduleService,
+ SheetsSelectionsService,
+} from '@univerjs/sheets';
+import enUS from '@univerjs/sheets/locale/en-US';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+// Note mutations are registered by SheetsNoteController.
+import { PLUGIN_NAME } from '../../const';
+import { SheetsNoteModel } from '../../models/sheets-note.model';
+import { SheetsNoteResourceController } from '../sheets-note-resource.controller';
+import { SheetsNoteController } from '../sheets.note.controller';
+
+const unitId = 'test';
+const subUnitId = 'sheet1';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: unitId,
+ sheetOrder: [subUnitId],
+ name: '',
+ appVersion: '0.15.4',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheets: {
+ [subUnitId]: {
+ id: subUnitId,
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 10,
+ cellData: {},
+ },
+ },
+};
+
+function createTestBed(resources?: Array<{ name: string; data: string }>) {
+ 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 {
+ // Ensure undo/redo exists and registers commands.
+ this._injector.get(IUndoRedoService);
+
+ ([
+ [SheetInterceptorService],
+ [SheetsSelectionsService],
+ [SheetLazyExecuteScheduleService],
+ [SheetsNoteModel],
+ [SheetsNoteController],
+ [SheetsNoteResourceController],
+ ] as Dependency[]).forEach((d) => this._injector.add(d));
+
+ touchDependencies(this._injector, [
+ [SheetsNoteModel],
+ [SheetsNoteController],
+ [SheetsNoteResourceController],
+ ]);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, {
+ ...TEST_WORKBOOK_DATA,
+ resources: resources ?? [],
+ });
+
+ get(IUniverInstanceService).focusUnit(unitId);
+
+ const logService = get(ILogService);
+ logService.setLogLevel(LogLevel.SILENT);
+
+ const localeService = get(LocaleService);
+ localeService.load({ enUS });
+ localeService.setLocale(LocaleType.EN_US);
+
+ const commandService = get(ICommandService);
+ // Register sheet structure commands/mutations that resource controller intercepts.
+ commandService.registerCommand(RemoveSheetCommand);
+ commandService.registerCommand(CopySheetCommand);
+ commandService.registerCommand(RemoveSheetMutation);
+ commandService.registerCommand(InsertSheetMutation);
+ commandService.registerCommand(CopyWorksheetEndMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(SetWorksheetActivateCommand);
+ commandService.registerCommand(SetWorksheetActiveOperation);
+ // Keep parity with existing ref-range test bed (some sheet commands expect these).
+ commandService.registerCommand(InsertRowByRangeCommand);
+ commandService.registerCommand(InsertColByRangeCommand);
+ commandService.registerCommand(RemoveRowByRangeCommand);
+ commandService.registerCommand(RemoveColByRangeCommand);
+ commandService.registerCommand(InsertRowMutation);
+ commandService.registerCommand(InsertColMutation);
+ commandService.registerCommand(RemoveRowMutation);
+ commandService.registerCommand(RemoveColMutation);
+ // Note mutations are registered by SheetsNoteController.
+
+ return {
+ univer,
+ get,
+ injector,
+ commandService,
+ };
+}
+
+describe('SheetsNoteResourceController', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ // Create empty bed by default.
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = testBed.commandService;
+ });
+
+ afterEach(() => univer.dispose());
+
+ it('loads notes from snapshot resources', () => {
+ univer.dispose();
+ const note: ISheetNote = { id: 'n1', row: 1, col: 1, width: 160, height: 72, note: 'from snapshot' };
+ const resources = [{
+ name: PLUGIN_NAME,
+ data: JSON.stringify({ [subUnitId]: { 1: { 1: note } } }),
+ }];
+
+ const testBed = createTestBed(resources);
+ univer = testBed.univer;
+ get = testBed.get;
+
+ const model = get(SheetsNoteModel);
+ expect(model.getNote(unitId, subUnitId, { row: 1, col: 1 })?.note).toBe('from snapshot');
+ });
+
+ it('clears unit notes on resource unload', () => {
+ const model = get(SheetsNoteModel);
+ model.updateNote(unitId, subUnitId, 2, 2, { id: 'n2', row: 2, col: 2, width: 160, height: 72, note: 'note' });
+ expect(model.getSheetNotes(unitId, subUnitId)?.size).toBe(1);
+
+ const resourceManager = get(IResourceManagerService);
+ resourceManager.unloadResources(unitId, UniverInstanceType.UNIVER_SHEET);
+ expect(model.getUnitNotes(unitId)).toBeUndefined();
+ });
+
+ it('intercepts RemoveSheetCommand to remove notes and supports undo', async () => {
+ const model = get(SheetsNoteModel);
+ model.updateNote(unitId, subUnitId, 3, 4, { id: 'n3', row: 3, col: 4, width: 160, height: 72, note: 'note' });
+
+ // Need at least 2 sheets for RemoveSheetCommand to pass.
+ const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ workbook.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Sheet2', rowCount: 10, columnCount: 10, cellData: {} });
+
+ expect(await commandService.executeCommand(SetWorksheetActivateCommand.id, { unitId, subUnitId })).toBeTruthy();
+
+ const params: IRemoveSheetCommandParams = { unitId, subUnitId };
+ expect(commandService.syncExecuteCommand(RemoveSheetCommand.id, params)).toBeTruthy();
+ expect(model.getSheetNotes(unitId, subUnitId)?.size).toBe(0);
+
+ // Undo should restore the sheet and its notes via UpdateNoteMutation in undo list.
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(model.getNote(unitId, subUnitId, { row: 3, col: 4 })?.id).toBe('n3');
+ });
+
+ it('intercepts CopySheetCommand to copy notes to target sheet and supports undo', async () => {
+ const model = get(SheetsNoteModel);
+ model.updateNote(unitId, subUnitId, 1, 2, { id: 'n4', row: 1, col: 2, width: 160, height: 72, note: 'note' });
+
+ // Need at least 2 sheets for RemoveSheetCommand used by undo in CopySheetCommand to pass.
+ const workbook = get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ workbook.addWorksheet('sheet2', 1, { id: 'sheet2', name: 'Sheet2', rowCount: 10, columnCount: 10, cellData: {} });
+
+ expect(await commandService.executeCommand(SetWorksheetActivateCommand.id, { unitId, subUnitId })).toBeTruthy();
+
+ const params: ICopySheetCommandParams = { unitId, subUnitId };
+ expect(commandService.syncExecuteCommand(CopySheetCommand.id, params)).toBeTruthy();
+
+ const copiedSheetId = workbook.getSheets()[1].getSheetId();
+ expect(copiedSheetId).not.toBe(subUnitId);
+
+ expect(model.getSheetNotes(unitId, copiedSheetId)?.size).toBe(1);
+
+ const copiedNotes = Array.from(model.getSheetNotes(unitId, copiedSheetId)!.values());
+ expect(copiedNotes[0].row).toBe(1);
+ expect(copiedNotes[0].col).toBe(2);
+ expect(copiedNotes[0].note).toBe('note');
+ // Copied note should have a new id.
+ expect(copiedNotes[0].id).not.toBe('n4');
+
+ expect(await commandService.executeCommand(UndoCommand.id)).toBeTruthy();
+ expect(model.getSheetNotes(unitId, copiedSheetId)?.size).toBe(0);
+ });
+});
diff --git a/packages/sheets-note/src/controllers/sheets-note-resource.controller.ts b/packages/sheets-note/src/controllers/sheets-note-resource.controller.ts
index e3cca5f28f..b4e6258a24 100644
--- a/packages/sheets-note/src/controllers/sheets-note-resource.controller.ts
+++ b/packages/sheets-note/src/controllers/sheets-note-resource.controller.ts
@@ -77,7 +77,7 @@ export class SheetsNoteResourceController extends Disposable {
}
try {
return JSON.parse(json);
- } catch (err) {
+ } catch {
return {};
}
};
diff --git a/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts b/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts
new file mode 100644
index 0000000000..ff2a8bdb6b
--- /dev/null
+++ b/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts
@@ -0,0 +1,179 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';
+import type { FUniver } from '@univerjs/core/facade';
+import type { ISheetNote } from '../../models/sheets-note.model';
+import {
+ ILogService,
+ Inject,
+ Injector,
+ IUndoRedoService,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ Plugin,
+ touchDependencies,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { FUniver as FUniverFactory } from '@univerjs/core/facade';
+import {
+ DefinedNamesService,
+ FormulaDataModel,
+ FunctionService,
+ IDefinedNamesService,
+ IFunctionService,
+ LexerTreeBuilder,
+} from '@univerjs/engine-formula';
+import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
+import { ISocketService, WebSocketService } from '@univerjs/network';
+import {
+ RangeProtectionRuleModel,
+ RefRangeService,
+ SheetInterceptorService,
+ SheetLazyExecuteScheduleService,
+ SheetsSelectionsService,
+ WorkbookPermissionService,
+ WorksheetPermissionService,
+ WorksheetProtectionPointModel,
+ WorksheetProtectionRuleModel,
+} from '@univerjs/sheets';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { SheetsNoteController } from '../../controllers/sheets.note.controller';
+import { SheetsNoteModel } from '../../models/sheets-note.model';
+import '@univerjs/sheets/facade';
+import '../../facade';
+
+const unitId = 'test';
+const subUnitId = 'sheet1';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: unitId,
+ sheetOrder: [subUnitId],
+ name: '',
+ appVersion: '0.15.4',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheets: {
+ [subUnitId]: {
+ id: subUnitId,
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 10,
+ cellData: {},
+ },
+ },
+};
+
+function createFacadeTestBed(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 {
+ // Ensure undo/redo exists.
+ this._injector.get(IUndoRedoService);
+
+ (dependencies ?? []).forEach((d) => this._injector.add(d));
+
+ // Minimal set of dependencies required by Sheets facade classes.
+ this._injector.add([SheetsSelectionsService]);
+ this._injector.add([SheetInterceptorService]);
+ this._injector.add([IFunctionService, { useClass: FunctionService }]);
+ this._injector.add([ISocketService, { useClass: WebSocketService }]);
+ this._injector.add([IRenderingEngine, { useFactory: () => new Engine() }]);
+ this._injector.add([IRenderManagerService, { useClass: RenderManagerService }]);
+ this._injector.add([FormulaDataModel]);
+ this._injector.add([LexerTreeBuilder]);
+ this._injector.add([RefRangeService]);
+ this._injector.add([WorksheetPermissionService]);
+ this._injector.add([WorkbookPermissionService]);
+ this._injector.add([WorksheetProtectionPointModel]);
+ this._injector.add([RangeProtectionRuleModel]);
+ this._injector.add([WorksheetProtectionRuleModel]);
+ this._injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+ this._injector.add([SheetLazyExecuteScheduleService]);
+
+ ([
+ [SheetsNoteModel],
+ [SheetsNoteController],
+ ] as Dependency[]).forEach((d) => this._injector.add(d));
+
+ touchDependencies(this._injector, [
+ [SheetsSelectionsService],
+ [SheetInterceptorService],
+ [SheetsNoteModel],
+ [SheetsNoteController],
+ ]);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData ?? TEST_WORKBOOK_DATA);
+ const univerInstanceService = injector.get(IUniverInstanceService);
+ univerInstanceService.focusUnit(unitId);
+
+ const logService = injector.get(ILogService);
+ logService.setLogLevel(LogLevel.SILENT);
+
+ const univerAPI = FUniverFactory.newAPI(injector);
+
+ return {
+ univer,
+ injector,
+ sheet,
+ univerAPI,
+ };
+}
+
+describe('sheets-note facade mixins', () => {
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ const testBed = createFacadeTestBed();
+ univerAPI = testBed.univerAPI;
+ });
+
+ it('creates/reads/deletes note through FRange and reads all notes via FWorksheet', () => {
+ const workbook = univerAPI.getActiveWorkbook();
+ expect(workbook).toBeTruthy();
+ const sheet = workbook!.getActiveSheet();
+
+ const range = sheet.getRange(1, 1, 1, 1);
+ expect(range.getNote()).toBeUndefined();
+
+ const note: ISheetNote = { id: 'ignored-id', row: 1, col: 1, width: 160, height: 72, note: 'hello', show: true };
+ range.createOrUpdateNote(note);
+
+ expect(range.getNote()?.note).toBe('hello');
+ expect(sheet.getNotes()).toHaveLength(1);
+
+ range.deleteNote();
+ expect(range.getNote()).toBeUndefined();
+ expect(sheet.getNotes()).toHaveLength(0);
+ });
+});
diff --git a/packages/sheets-note/src/models/__tests__/sheets-note.model.spec.ts b/packages/sheets-note/src/models/__tests__/sheets-note.model.spec.ts
new file mode 100644
index 0000000000..0949fabd9a
--- /dev/null
+++ b/packages/sheets-note/src/models/__tests__/sheets-note.model.spec.ts
@@ -0,0 +1,160 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISheetNote } from '../sheets-note.model';
+import { Injector } from '@univerjs/core';
+import { filter, firstValueFrom, take, toArray } from 'rxjs';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { SheetsNoteModel } from '../sheets-note.model';
+
+describe('SheetsNoteModel', () => {
+ let injector: Injector;
+ let model: SheetsNoteModel;
+
+ const unitId = 'unit-1';
+ const subUnitId = 'sheet-1';
+
+ beforeEach(() => {
+ injector = new Injector([
+ [SheetsNoteModel],
+ ]);
+ model = injector.get(SheetsNoteModel);
+ });
+
+ it('updates a note and emits change events', async () => {
+ const noteInput: ISheetNote = {
+ id: 'note-1',
+ row: 0,
+ col: 0,
+ width: 160,
+ height: 72,
+ note: 'hello',
+ show: false,
+ };
+
+ const firstChangePromise = firstValueFrom(model.change$.pipe(take(1)));
+ model.updateNote(unitId, subUnitId, 0, 0, noteInput);
+ const firstChange = await firstChangePromise;
+
+ expect(firstChange.type).toBe('update');
+ expect(firstChange.oldNote == null).toBe(true);
+ expect(firstChange.newNote?.note).toBe('hello');
+
+ const secondChangePromise = firstValueFrom(model.change$.pipe(take(1)));
+ model.updateNote(unitId, subUnitId, 0, 0, { ...noteInput, note: 'updated' });
+ const secondChange = await secondChangePromise;
+
+ expect(secondChange.type).toBe('update');
+ expect(secondChange.oldNote?.note).toBe('hello');
+ expect(secondChange.newNote?.note).toBe('updated');
+
+ const stored = model.getNote(unitId, subUnitId, { row: 0, col: 0 });
+ expect(stored?.note).toBe('updated');
+ });
+
+ it('toggles note popup state and exposes show notes stream', async () => {
+ const noteInput: ISheetNote = {
+ id: 'note-2',
+ row: 2,
+ col: 3,
+ width: 160,
+ height: 72,
+ note: 'note',
+ show: false,
+ };
+
+ model.updateNote(unitId, subUnitId, 2, 3, noteInput);
+
+ const showNotesPromise = firstValueFrom(
+ model.getSheetShowNotes$(unitId, subUnitId).pipe(
+ take(2),
+ toArray()
+ )
+ );
+
+ model.toggleNotePopup(unitId, subUnitId, { row: 2, col: 3 });
+ model.toggleNotePopup(unitId, subUnitId, { row: 2, col: 3 });
+
+ const [afterShow, afterHide] = await showNotesPromise;
+ expect(afterShow).toHaveLength(1);
+ expect(afterShow[0].note.show).toBe(true);
+ expect(afterShow[0].loc.row).toBe(2);
+ expect(afterShow[0].loc.col).toBe(3);
+
+ expect(afterHide).toHaveLength(0);
+ });
+
+ it('updates note position and emits ref change', async () => {
+ const noteInput: ISheetNote = {
+ id: 'note-3',
+ row: 1,
+ col: 1,
+ width: 160,
+ height: 72,
+ note: 'note',
+ };
+
+ model.updateNote(unitId, subUnitId, 1, 1, noteInput);
+
+ const refChangePromise = firstValueFrom(
+ model.change$.pipe(
+ filter((c) => c.type === 'ref'),
+ take(1)
+ )
+ );
+
+ model.updateNotePosition(unitId, subUnitId, { row: 1, col: 1, newRow: 4, newCol: 5 });
+ const refChange = await refChangePromise;
+
+ expect(refChange.oldNote?.row).toBe(1);
+ expect(refChange.oldNote?.col).toBe(1);
+ expect(refChange.newNote.row).toBe(4);
+ expect(refChange.newNote.col).toBe(5);
+
+ expect(model.getNote(unitId, subUnitId, { row: 1, col: 1 })).toBeUndefined();
+ expect(model.getNote(unitId, subUnitId, { row: 4, col: 5 })?.id).toBe('note-3');
+ });
+
+ it('removes notes and does nothing if note is missing', async () => {
+ const noteInput: ISheetNote = {
+ id: 'note-4',
+ row: 6,
+ col: 7,
+ width: 160,
+ height: 72,
+ note: 'note',
+ };
+ model.updateNote(unitId, subUnitId, 6, 7, noteInput);
+
+ const removeChangePromise = firstValueFrom(model.change$.pipe(take(1)));
+ model.removeNote(unitId, subUnitId, { row: 6, col: 7 });
+ const removeChange = await removeChangePromise;
+
+ expect(removeChange.type).toBe('update');
+ expect(removeChange.oldNote?.id).toBe('note-4');
+ expect(removeChange.newNote).toBeNull();
+ expect(model.getNote(unitId, subUnitId, { row: 6, col: 7 })).toBeUndefined();
+
+ let emitted = false;
+ const subscription = model.change$.subscribe(() => {
+ emitted = true;
+ });
+
+ model.removeNote(unitId, subUnitId, { row: 99, col: 99 });
+ expect(emitted).toBe(false);
+ subscription.unsubscribe();
+ });
+});
diff --git a/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts
index 501a021b81..42ff5c8e46 100644
--- a/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts
+++ b/packages/sheets-table-ui/src/commands/operations/__tests__/open-table-selector.operation.spec.ts
@@ -73,6 +73,27 @@ describe('open-table-selector operation', () => {
expect(close).toHaveBeenCalled();
});
+ it('openRangeSelector should resolve null on cancel and close callbacks', async () => {
+ const close = vi.fn();
+ const dialogService = {
+ open: vi.fn((props: any) => {
+ props.children.label.props.onCancel();
+ props.onClose();
+ }),
+ close,
+ };
+
+ const accessor = createAccessor([
+ [IDialogService, dialogService],
+ [LocaleService, { t: () => 'Select range' }],
+ ]);
+
+ const result = await openRangeSelector(accessor, 'u1', 's1', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, 't1');
+
+ expect(result).toBeNull();
+ expect(close).toHaveBeenCalledTimes(2);
+ });
+
it('OpenTableSelectorOperation should return false without sheet target', async () => {
sheetsMocks.getSheetCommandTarget.mockReturnValue(null);
@@ -134,4 +155,38 @@ describe('open-table-selector operation', () => {
range: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 },
});
});
+
+ it('OpenTableSelectorOperation should keep multi-cell selections unchanged and stop when dialog is cancelled', async () => {
+ sheetsMocks.expandToContinuousRange.mockClear();
+ sheetsMocks.getSheetCommandTarget.mockReturnValue({
+ unitId: 'u1',
+ subUnitId: 's1',
+ worksheet: { id: 'sheet' },
+ });
+ sheetsMocks.isSingleCellSelection.mockReturnValue(false);
+
+ const executeCommand = vi.fn();
+ const dialogService = {
+ open: vi.fn((props: any) => {
+ props.children.label.props.onCancel();
+ }),
+ close: vi.fn(),
+ };
+
+ const accessor = createAccessor([
+ [IUniverInstanceService, {}],
+ [ICommandService, { executeCommand }],
+ [SheetsSelectionsService, {
+ getCurrentLastSelection: () => ({
+ range: { startRow: 2, endRow: 4, startColumn: 2, endColumn: 5 },
+ }),
+ }],
+ [IDialogService, dialogService],
+ [LocaleService, { t: () => 'Select range' }],
+ ]);
+
+ await expect(OpenTableSelectorOperation.handler(accessor)).resolves.toBe(false);
+ expect(sheetsMocks.expandToContinuousRange).not.toHaveBeenCalled();
+ expect(executeCommand).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableFilterPanel.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableFilterPanel.spec.tsx
new file mode 100644
index 0000000000..805db54ce0
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableFilterPanel.spec.tsx
@@ -0,0 +1,314 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+
+import { ICommandService, IPermissionService, LocaleService } from '@univerjs/core';
+import { SortRangeCommand, SortType } from '@univerjs/sheets-sort';
+import { SheetsTableSortStateEnum, TableColumnFilterTypeEnum, TableConditionTypeEnum, TableDateCompareTypeEnum, TableManager } from '@univerjs/sheets-table';
+import { createElement } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SheetsTableComponentController } from '../../../controllers/sheet-table-component.controller';
+import { SheetsTableUiService } from '../../../services/sheets-table-ui-service';
+import { FilterByEnum } from '../../../types';
+import { SheetTableFilterPanel } from '../SheetTableFilterPanel';
+
+const mocks = vi.hoisted(() => ({
+ useDependency: vi.fn(),
+ stateValues: [] as any[],
+ stateCursor: 0,
+}));
+
+const design = vi.hoisted(() => ({
+ Button: (_props: any) => null,
+ ButtonGroup: (_props: any) => null,
+ Segmented: (_props: any) => null,
+}));
+
+vi.mock('react', async () => {
+ const actual = await vi.importActual<typeof import('react')>('react');
+ return {
+ ...actual,
+ useMemo: (fn: any) => fn(),
+ useState: (initialValue: unknown) => {
+ const index = mocks.stateCursor++;
+ if (!(index in mocks.stateValues)) {
+ mocks.stateValues[index] = typeof initialValue === 'function'
+ ? (initialValue as () => unknown)()
+ : initialValue;
+ }
+ return [
+ mocks.stateValues[index],
+ (value: unknown) => {
+ mocks.stateValues[index] = typeof value === 'function'
+ ? (value as (prev: unknown) => unknown)(mocks.stateValues[index])
+ : value;
+ },
+ ];
+ },
+ };
+});
+
+vi.mock('@univerjs/ui', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');
+ return {
+ ...actual,
+ useDependency: mocks.useDependency,
+ };
+});
+
+vi.mock('@univerjs/design', () => ({
+ Button: design.Button,
+ ButtonGroup: design.ButtonGroup,
+ Segmented: design.Segmented,
+ borderClassName: 'border',
+ clsx: (...args: any[]) => args.filter(Boolean).join(' '),
+}));
+
+vi.mock('@univerjs/icons', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/icons')>('@univerjs/icons');
+ return {
+ ...actual,
+ AscendingIcon: () => null,
+ DescendingIcon: () => null,
+ };
+});
+
+vi.mock('../SheetTableItemsFilterPanel', () => ({
+ SheetTableItemsFilterPanel: (props: any) => createElement('items-filter-panel', props),
+}));
+
+vi.mock('../SheetTableConditionPanel', () => ({
+ SheetTableConditionPanel: (props: any) => createElement('condition-panel', props),
+}));
+
+function renderPanel() {
+ mocks.stateCursor = 0;
+ return SheetTableFilterPanel() as any;
+}
+
+function findAll(root: any, predicate: (node: any) => boolean): any[] {
+ const found: any[] = [];
+ const visit = (node: any) => {
+ if (!node) return;
+ if (Array.isArray(node)) {
+ node.forEach(visit);
+ return;
+ }
+ if (typeof node !== 'object') return;
+ if (predicate(node)) found.push(node);
+ const children = node.props?.children;
+ if (Array.isArray(children)) children.forEach(visit);
+ else visit(children);
+ };
+ visit(root);
+ return found;
+}
+
+describe('SheetTableFilterPanel', () => {
+ const localeService = {
+ t: (key: string) => key,
+ getCurrentLocale: () => 'en',
+ };
+
+ beforeEach(() => {
+ mocks.stateValues = [];
+ mocks.stateCursor = 0;
+ vi.clearAllMocks();
+ });
+
+ it('should apply a manual filter and close panel', () => {
+ const closeFilterPanel = vi.fn();
+ const setTableFilter = vi.fn();
+
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === LocaleService) return localeService;
+ if (token === SheetsTableUiService) {
+ return {
+ getTableFilterPanelInitProps: () => ({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: undefined,
+ currentFilterBy: FilterByEnum.Items,
+ }),
+ getTableFilterItems: () => ({
+ data: [{ title: 'A' }, { title: 'B' }],
+ }),
+ getTableFilterCheckedItems: () => ['A'],
+ setTableFilter,
+ };
+ }
+ if (token === TableManager) {
+ return {
+ getTable: () => ({
+ getTableFilters: () => ({
+ getSortState: () => ({ columnIndex: -1, sortState: SheetsTableSortStateEnum.None }),
+ setSortState: vi.fn(),
+ }),
+ getTableFilterColumn: () => undefined,
+ }),
+ };
+ }
+ if (token === ICommandService) return { executeCommand: vi.fn() };
+ if (token === IPermissionService) return { getPermissionPoint: () => ({ value: false }) };
+ if (token === SheetsTableComponentController) {
+ return {
+ getCurrentTableFilterInfo: () => ({ unitId: 'u1', subUnitId: 's1', tableId: 't1', column: 0 }),
+ closeFilterPanel,
+ };
+ }
+ return null;
+ });
+
+ const tree = renderPanel();
+ const [confirm] = findAll(tree, (n) => n.type === design.Button && n.props?.children === 'sheets-table.filter.confirm');
+
+ confirm.props.onClick();
+
+ expect(setTableFilter).toHaveBeenCalledWith('u1', 't1', 0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['A'],
+ });
+ expect(closeFilterPanel).toHaveBeenCalledTimes(1);
+ });
+
+ it('should apply sort and update table sort state', () => {
+ const closeFilterPanel = vi.fn();
+ const setSortState = vi.fn();
+ const executeCommand = vi.fn();
+
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === LocaleService) return localeService;
+ if (token === SheetsTableUiService) {
+ return {
+ getTableFilterPanelInitProps: () => ({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 2,
+ tableFilter: undefined,
+ currentFilterBy: FilterByEnum.Items,
+ }),
+ getTableFilterItems: () => ({ data: [] }),
+ getTableFilterCheckedItems: () => [],
+ setTableFilter: vi.fn(),
+ };
+ }
+ if (token === TableManager) {
+ return {
+ getTable: () => ({
+ getTableFilters: () => ({
+ getSortState: () => ({ columnIndex: 2, sortState: SheetsTableSortStateEnum.Desc }),
+ setSortState,
+ }),
+ getTableFilterRange: () => ({ startRow: 0, endRow: 5, startColumn: 5, endColumn: 6 }),
+ getTableFilterColumn: () => undefined,
+ }),
+ };
+ }
+ if (token === ICommandService) return { executeCommand };
+ if (token === IPermissionService) return { getPermissionPoint: () => ({ value: true }) };
+ if (token === SheetsTableComponentController) {
+ return {
+ getCurrentTableFilterInfo: () => ({ unitId: 'u1', subUnitId: 's1', tableId: 't1', column: 0 }),
+ closeFilterPanel,
+ };
+ }
+ return null;
+ });
+
+ const tree = renderPanel();
+ const [sortAsc] = findAll(tree, (n) => n.type === design.Button && n.props?.children?.includes?.('sheets-sort.general.sort-asc'));
+
+ sortAsc.props.onClick();
+
+ expect(executeCommand).toHaveBeenCalledWith(SortRangeCommand.id, expect.objectContaining({
+ unitId: 'u1',
+ subUnitId: 's1',
+ range: expect.objectContaining({ startColumn: 5 }),
+ orderRules: [{ colIndex: 7, type: SortType.ASC }],
+ hasTitle: false,
+ }));
+ expect(setSortState).toHaveBeenCalledWith(2, SheetsTableSortStateEnum.Asc);
+ expect(closeFilterPanel).toHaveBeenCalledTimes(1);
+ });
+
+ it('should apply condition filter for quarter compare', () => {
+ const closeFilterPanel = vi.fn();
+ const setTableFilter = vi.fn();
+
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === LocaleService) return localeService;
+ if (token === SheetsTableUiService) {
+ return {
+ getTableFilterPanelInitProps: () => ({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: {
+ filterType: 'condition',
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Q2,
+ },
+ },
+ currentFilterBy: FilterByEnum.Condition,
+ }),
+ getTableFilterItems: () => ({ data: [] }),
+ getTableFilterCheckedItems: () => [],
+ setTableFilter,
+ };
+ }
+ if (token === TableManager) {
+ return {
+ getTable: () => ({
+ getTableFilters: () => ({
+ getSortState: () => ({ columnIndex: -1, sortState: SheetsTableSortStateEnum.None }),
+ setSortState: vi.fn(),
+ }),
+ getTableFilterColumn: () => undefined,
+ }),
+ };
+ }
+ if (token === ICommandService) return { executeCommand: vi.fn() };
+ if (token === IPermissionService) return { getPermissionPoint: () => ({ value: false }) };
+ if (token === SheetsTableComponentController) {
+ return {
+ getCurrentTableFilterInfo: () => ({ unitId: 'u1', subUnitId: 's1', tableId: 't1', column: 0 }),
+ closeFilterPanel,
+ };
+ }
+ return null;
+ });
+
+ const tree = renderPanel();
+ const [confirm] = findAll(tree, (n) => n.type === design.Button && n.props?.children === 'sheets-table.filter.confirm');
+
+ confirm.props.onClick();
+
+ expect(setTableFilter).toHaveBeenCalledWith('u1', 't1', 0, expect.objectContaining({
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: expect.objectContaining({
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Q2,
+ }),
+ }));
+ expect(closeFilterPanel).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableItemsFilterPanel.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableItemsFilterPanel.spec.tsx
new file mode 100644
index 0000000000..1472cd23fa
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableItemsFilterPanel.spec.tsx
@@ -0,0 +1,256 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+
+import { LocaleService } from '@univerjs/core';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SheetsTableUiService } from '../../../services/sheets-table-ui-service';
+import { SheetTableItemsFilterPanel } from '../SheetTableItemsFilterPanel';
+
+const mocks = vi.hoisted(() => ({
+ useDependency: vi.fn(),
+ stateValues: [] as any[],
+ stateCursor: 0,
+}));
+
+const design = vi.hoisted(() => ({
+ Input: (_props: any) => null,
+ Checkbox: (_props: any) => null,
+}));
+
+vi.mock('react', async () => {
+ const actual = await vi.importActual<typeof import('react')>('react');
+ return {
+ ...actual,
+ useCallback: (fn: any) => fn,
+ useMemo: (fn: any) => fn(),
+ useState: (initialValue: unknown) => {
+ const index = mocks.stateCursor++;
+ if (!(index in mocks.stateValues)) {
+ mocks.stateValues[index] = typeof initialValue === 'function'
+ ? (initialValue as () => unknown)()
+ : initialValue;
+ }
+ return [
+ mocks.stateValues[index],
+ (value: unknown) => {
+ mocks.stateValues[index] = typeof value === 'function'
+ ? (value as (prev: unknown) => unknown)(mocks.stateValues[index])
+ : value;
+ },
+ ];
+ },
+ };
+});
+
+vi.mock('@univerjs/ui', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');
+ return {
+ ...actual,
+ useDependency: mocks.useDependency,
+ };
+});
+
+vi.mock('@univerjs/design', () => ({
+ borderClassName: 'border',
+ scrollbarClassName: 'scrollbar',
+ clsx: (...args: any[]) => args.filter(Boolean).join(' '),
+ Input: design.Input,
+ Checkbox: design.Checkbox,
+}));
+
+function renderPanel(props: Parameters<typeof SheetTableItemsFilterPanel>[0]) {
+ mocks.stateCursor = 0;
+ return SheetTableItemsFilterPanel(props) as any;
+}
+
+function findAllByComponent(root: any, component: unknown): any[] {
+ const found: any[] = [];
+ const visit = (node: any) => {
+ if (Array.isArray(node)) {
+ node.forEach(visit);
+ return;
+ }
+ if (!node || typeof node !== 'object') return;
+ if (node.type === component) found.push(node);
+ const children = node.props?.children;
+ if (Array.isArray(children)) children.forEach(visit);
+ else visit(children);
+ };
+ visit(root);
+ return found;
+}
+
+describe('SheetTableItemsFilterPanel', () => {
+ const localeService = {
+ t: (key: string) => key,
+ };
+
+ beforeEach(() => {
+ mocks.stateValues = [];
+ mocks.stateCursor = 0;
+ vi.clearAllMocks();
+ });
+
+ it('should toggle all items selection and support searching', () => {
+ const items = [
+ { key: '0', title: 'A' },
+ { key: '1', title: 'B' },
+ { key: '2', title: 'C' },
+ ];
+ const itemsCountMap = new Map<string, number>([
+ ['A', 2],
+ ['B', 1],
+ ['C', 3],
+ ]);
+ const allItemsCount = 6;
+
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === LocaleService) return localeService;
+ if (token === SheetsTableUiService) {
+ return {
+ getTableFilterItems: () => ({ data: items, itemsCountMap, allItemsCount }),
+ };
+ }
+ return null;
+ });
+
+ const checkedItemSet = new Set<string>(['A', 'B', 'C']);
+ const setCheckedItemSet = vi.fn();
+
+ let tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: undefined,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+
+ const [searchInput] = findAllByComponent(tree, design.Input);
+ const [checkAllBox] = findAllByComponent(tree, design.Checkbox);
+ expect(checkAllBox.props.checked).toBe(true);
+
+ checkAllBox.props.onChange();
+ tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: undefined,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+ const [checkAllAfterClear] = findAllByComponent(tree, design.Checkbox);
+ expect(checkAllAfterClear.props.checked).toBe(false);
+ expect(setCheckedItemSet).toHaveBeenCalledWith(expect.any(Set));
+
+ searchInput.props.onChange('b');
+ tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: undefined,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+
+ const checkboxesAfterSearch = findAllByComponent(tree, design.Checkbox);
+ expect(checkboxesAfterSearch).toHaveLength(2);
+
+ checkboxesAfterSearch[0].props.onChange();
+ tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: undefined,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+ const checkboxesAfterSelectAll = findAllByComponent(tree, design.Checkbox);
+ expect(checkboxesAfterSelectAll[0].props.checked).toBe(true);
+
+ searchInput.props.onChange('');
+ tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: undefined,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+ const checkboxesAfterReset = findAllByComponent(tree, design.Checkbox);
+ expect(checkboxesAfterReset[0].props.checked).toBe(true);
+ expect(checkboxesAfterReset).toHaveLength(4);
+ });
+
+ it('should toggle an item when partially selected', () => {
+ const items = [
+ { key: '0', title: 'A' },
+ { key: '1', title: 'B' },
+ ];
+ const itemsCountMap = new Map<string, number>([
+ ['A', 1],
+ ['B', 2],
+ ]);
+
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === LocaleService) return localeService;
+ if (token === SheetsTableUiService) {
+ return {
+ getTableFilterItems: () => ({ data: items, itemsCountMap, allItemsCount: 3 }),
+ };
+ }
+ return null;
+ });
+
+ const checkedItemSet = new Set<string>(['A']);
+ const setCheckedItemSet = vi.fn();
+
+ let tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: { filterType: 1 } as any,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+
+ const checkboxes = findAllByComponent(tree, design.Checkbox);
+ const itemB = checkboxes[2];
+ expect(itemB.props.checked).toBe(false);
+
+ itemB.props.onChange();
+ tree = renderPanel({
+ unitId: 'u1',
+ subUnitId: 's1',
+ tableId: 't1',
+ columnIndex: 0,
+ tableFilter: { filterType: 1 } as any,
+ checkedItemSet,
+ setCheckedItemSet,
+ });
+
+ const checkboxesAfterToggle = findAllByComponent(tree, design.Checkbox);
+ expect(checkboxesAfterToggle[2].props.checked).toBe(true);
+ });
+});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/SheetTableSelector.spec.tsx b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableSelector.spec.tsx
new file mode 100644
index 0000000000..c03c66bcda
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/SheetTableSelector.spec.tsx
@@ -0,0 +1,246 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+
+import { IUniverInstanceService, LocaleService } from '@univerjs/core';
+import { TableManager } from '@univerjs/sheets-table';
+import { createElement } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SheetTableSelector } from '../SheetTableSelector';
+
+const mocks = vi.hoisted(() => ({
+ useDependency: vi.fn(),
+ stateValues: [] as any[],
+ stateCursor: 0,
+}));
+
+vi.mock('react', async () => {
+ const actual = await vi.importActual<typeof import('react')>('react');
+ return {
+ ...actual,
+ useState: (initialValue: unknown) => {
+ const index = mocks.stateCursor++;
+ if (!(index in mocks.stateValues)) {
+ mocks.stateValues[index] = initialValue;
+ }
+ return [
+ mocks.stateValues[index],
+ (value: unknown) => {
+ mocks.stateValues[index] = typeof value === 'function'
+ ? (value as (prev: unknown) => unknown)(mocks.stateValues[index])
+ : value;
+ },
+ ];
+ },
+ };
+});
+
+vi.mock('@univerjs/ui', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/ui')>('@univerjs/ui');
+ return {
+ ...actual,
+ useDependency: mocks.useDependency,
+ };
+});
+
+vi.mock('@univerjs/sheets-formula-ui', () => ({
+ RangeSelector: (props: any) => createElement('range-selector', props),
+}));
+
+vi.mock('@univerjs/design', () => ({
+ Button: (props: any) => createElement('button', props, props.children),
+}));
+
+function renderSelector(props: Parameters<typeof SheetTableSelector>[0]) {
+ mocks.stateCursor = 0;
+ return SheetTableSelector(props) as any;
+}
+
+function getRangeSelector(tree: any) {
+ return tree.props.children[0];
+}
+
+function getErrorText(tree: any) {
+ const errorNode = tree.props.children[1];
+ return errorNode && errorNode !== false ? errorNode.props.children : null;
+}
+
+function getButtons(tree: any) {
+ return tree.props.children[2].props.children;
+}
+
+describe('SheetTableSelector', () => {
+ const localeService = { t: (key: string) => key };
+
+ const buildDependencies = (tableManagerOverrides: Record<string, unknown> = {}) => {
+ const tableManager = {
+ getTablesBySubunitId: () => [],
+ getTableById: () => null,
+ ...tableManagerOverrides,
+ };
+
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === TableManager) {
+ return tableManager;
+ }
+ if (token === LocaleService) {
+ return localeService;
+ }
+ if (token === IUniverInstanceService) {
+ return {
+ getUnit: vi.fn(() => ({
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: () => ({ getSheetId: () => 'sheet-1', getMergeData: () => [] }),
+ })),
+ };
+ }
+ return null;
+ });
+ };
+
+ beforeEach(() => {
+ mocks.stateValues = [];
+ mocks.stateCursor = 0;
+ vi.clearAllMocks();
+ });
+
+ it('blocks selecting a range that overlaps merged cells or other tables', () => {
+ const onConfirm = vi.fn();
+ const props = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 },
+ onConfirm,
+ onCancel: vi.fn(),
+ };
+
+ buildDependencies({
+ getTablesBySubunitId: () => [{ getId: () => 'table-2', getRange: () => ({ startRow: 5, endRow: 8, startColumn: 0, endColumn: 2 }) }],
+ });
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === TableManager) {
+ return {
+ getTablesBySubunitId: () => [{ getId: () => 'table-2', getRange: () => ({ startRow: 5, endRow: 8, startColumn: 0, endColumn: 2 }) }],
+ getTableById: () => null,
+ };
+ }
+ if (token === LocaleService) {
+ return localeService;
+ }
+ if (token === IUniverInstanceService) {
+ return {
+ getUnit: () => ({
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: () => ({ getSheetId: () => 'sheet-1', getMergeData: () => [{ startRow: 1, endRow: 2, startColumn: 1, endColumn: 2 }] }),
+ }),
+ };
+ }
+ return null;
+ });
+
+ let tree = renderSelector(props);
+ getRangeSelector(tree).props.onChange(undefined, 'B2:C4');
+ tree = renderSelector(props);
+ expect(getErrorText(tree)).toBe('sheets-table.tableRangeWithMergeError');
+
+ getRangeSelector(tree).props.onChange(undefined, 'A6:C9');
+ tree = renderSelector(props);
+ expect(getErrorText(tree)).toBe('sheets-table.tableRangeWithOtherTableError');
+
+ getButtons(tree)[1].props.onClick();
+ expect(onConfirm).not.toHaveBeenCalled();
+ });
+
+ it('rejects invalid single-row ranges and confirms valid ranges for a new table', () => {
+ const onConfirm = vi.fn();
+ const onCancel = vi.fn();
+ const props = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 1 },
+ onConfirm,
+ onCancel,
+ };
+
+ buildDependencies();
+
+ let tree = renderSelector(props);
+ getRangeSelector(tree).props.onChange(undefined, 'A2:B2');
+ tree = renderSelector(props);
+ expect(getErrorText(tree)).toBe('sheets-table.tableRangeSingleRowError');
+
+ getRangeSelector(tree).props.onChange(undefined, 'A2:B5');
+ tree = renderSelector(props);
+ getButtons(tree)[1].props.onClick();
+ expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: expect.objectContaining({ startRow: 1, endRow: 4, startColumn: 0, endColumn: 1 }),
+ }));
+
+ getButtons(tree)[0].props.onClick();
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('only allows in-place table updates when the header row stays aligned', () => {
+ const onConfirm = vi.fn();
+ const props = {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ tableId: 'table-1',
+ range: { startRow: 2, endRow: 5, startColumn: 0, endColumn: 1 },
+ onConfirm,
+ onCancel: vi.fn(),
+ };
+
+ buildDependencies({
+ getTableById: () => ({ getRange: () => ({ startRow: 2, endRow: 5, startColumn: 0, endColumn: 1 }) }),
+ });
+ mocks.useDependency.mockImplementation((token: unknown) => {
+ if (token === TableManager) {
+ return {
+ getTablesBySubunitId: () => [],
+ getTableById: () => ({ getRange: () => ({ startRow: 2, endRow: 5, startColumn: 0, endColumn: 1 }) }),
+ };
+ }
+ if (token === LocaleService) {
+ return localeService;
+ }
+ if (token === IUniverInstanceService) {
+ return {
+ getUnit: () => ({
+ getUnitId: () => 'unit-1',
+ getSheetBySheetId: () => ({ getSheetId: () => 'sheet-1', getMergeData: () => [] }),
+ }),
+ };
+ }
+ return null;
+ });
+
+ let tree = renderSelector(props);
+ getRangeSelector(tree).props.onChange(undefined, 'A4:B8');
+ tree = renderSelector(props);
+ expect(getErrorText(tree)).toBe('sheets-table.updateError');
+
+ getRangeSelector(tree).props.onChange(undefined, 'A3:B7');
+ expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ range: expect.objectContaining({ startRow: 2, endRow: 6, startColumn: 0, endColumn: 1 }),
+ }));
+ });
+});
diff --git a/packages/sheets-table-ui/src/views/components/__tests__/util.spec.ts b/packages/sheets-table-ui/src/views/components/__tests__/util.spec.ts
new file mode 100644
index 0000000000..cbe26ff69a
--- /dev/null
+++ b/packages/sheets-table-ui/src/views/components/__tests__/util.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 { TableConditionTypeEnum, TableDateCompareTypeEnum, TableNumberCompareTypeEnum, TableStringCompareTypeEnum } from '@univerjs/sheets-table';
+import { describe, expect, it } from 'vitest';
+import { ConditionSubComponentEnum } from '../type';
+import { getCascaderListOptions, getConditionDateSelect, getInitConditionInfo, getSubComponentType } from '../util';
+
+const injector = {
+ get: () => ({
+ t: (key: string) => `t:${key}`,
+ }),
+} as any;
+
+describe('table filter util', () => {
+ it('should build translated cascader/date options for string, number and date filters', () => {
+ const cascaderOptions = getCascaderListOptions(injector);
+ const quarterOptions = getConditionDateSelect(injector, TableDateCompareTypeEnum.Quarter);
+ const monthOptions = getConditionDateSelect(injector, TableDateCompareTypeEnum.Month);
+
+ expect(cascaderOptions).toHaveLength(3);
+ expect(cascaderOptions[0]).toEqual(expect.objectContaining({
+ value: TableConditionTypeEnum.String,
+ label: 't:sheets-table.condition.string',
+ }));
+ expect(cascaderOptions[1]?.children).toEqual(expect.arrayContaining([
+ expect.objectContaining({ value: TableNumberCompareTypeEnum.Between }),
+ expect.objectContaining({ value: TableNumberCompareTypeEnum.Above }),
+ ]));
+ expect(cascaderOptions[2]?.children).toEqual(expect.arrayContaining([
+ expect.objectContaining({ value: TableDateCompareTypeEnum.Quarter }),
+ expect.objectContaining({ value: TableDateCompareTypeEnum.Month }),
+ ]));
+ expect(quarterOptions.map((item) => item.value)).toEqual([
+ TableDateCompareTypeEnum.Q1,
+ TableDateCompareTypeEnum.Q2,
+ TableDateCompareTypeEnum.Q3,
+ TableDateCompareTypeEnum.Q4,
+ ]);
+ expect(monthOptions).toHaveLength(12);
+ expect(getConditionDateSelect(injector)).toEqual([]);
+ });
+
+ it('should select the right condition sub component for common filtering scenarios', () => {
+ expect(getSubComponentType(TableConditionTypeEnum.String, TableStringCompareTypeEnum.Contains)).toBe(ConditionSubComponentEnum.Input);
+ expect(getSubComponentType(TableConditionTypeEnum.Number, TableNumberCompareTypeEnum.Between)).toBe(ConditionSubComponentEnum.Inputs);
+ expect(getSubComponentType(TableConditionTypeEnum.Number, TableNumberCompareTypeEnum.GreaterThan)).toBe(ConditionSubComponentEnum.Input);
+ expect(getSubComponentType(TableConditionTypeEnum.Date, TableDateCompareTypeEnum.Between)).toBe(ConditionSubComponentEnum.DateRange);
+ expect(getSubComponentType(TableConditionTypeEnum.Date, TableDateCompareTypeEnum.Quarter)).toBe(ConditionSubComponentEnum.Select);
+ expect(getSubComponentType(TableConditionTypeEnum.Date, TableDateCompareTypeEnum.After)).toBe(ConditionSubComponentEnum.DatePicker);
+ expect(getSubComponentType(TableConditionTypeEnum.Date, TableDateCompareTypeEnum.Today)).toBe(ConditionSubComponentEnum.None);
+ expect(getSubComponentType(TableConditionTypeEnum.String)).toBe(ConditionSubComponentEnum.None);
+ });
+
+ it('should normalize saved filter conditions back to the form state', () => {
+ expect(getInitConditionInfo()).toEqual({
+ type: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ info: {},
+ });
+
+ const dateBetween = getInitConditionInfo({
+ filterType: 'condition',
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Between,
+ expectedValue: ['2025-01-01', '2025-01-31'],
+ },
+ } as any);
+ expect(dateBetween).toEqual({
+ type: TableConditionTypeEnum.Date,
+ compare: TableDateCompareTypeEnum.Between,
+ info: {
+ dateRange: [new Date('2025-01-01'), new Date('2025-01-31')],
+ },
+ });
+
+ const dateQuarter = getInitConditionInfo({
+ filterType: 'condition',
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Date,
+ compareType: TableDateCompareTypeEnum.Q2,
+ },
+ } as any);
+ expect(dateQuarter).toEqual({
+ type: TableConditionTypeEnum.Date,
+ compare: TableDateCompareTypeEnum.Quarter,
+ info: { dateSelect: TableDateCompareTypeEnum.Q2 },
+ });
+
+ const numberBetween = getInitConditionInfo({
+ filterType: 'condition',
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.NotBetween,
+ expectedValue: [1, 10],
+ },
+ } as any);
+ expect(numberBetween).toEqual({
+ type: TableConditionTypeEnum.Number,
+ compare: TableNumberCompareTypeEnum.NotBetween,
+ info: { numberRange: [1, 10] },
+ });
+
+ const stringEquals = getInitConditionInfo({
+ filterType: 'condition',
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.String,
+ compareType: TableStringCompareTypeEnum.Equal,
+ expectedValue: 'OpenAI',
+ },
+ } as any);
+ expect(stringEquals).toEqual({
+ type: TableConditionTypeEnum.String,
+ compare: TableStringCompareTypeEnum.Equal,
+ info: { string: 'OpenAI' },
+ });
+ });
+});
diff --git a/packages/sheets-table/src/model/__tests__/table-model.spec.ts b/packages/sheets-table/src/model/__tests__/table-model.spec.ts
new file mode 100644
index 0000000000..1cad1607a7
--- /dev/null
+++ b/packages/sheets-table/src/model/__tests__/table-model.spec.ts
@@ -0,0 +1,166 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CellValueType } from '@univerjs/core';
+import { describe, expect, it } from 'vitest';
+import {
+ SheetsTableButtonStateEnum,
+ SheetsTableSortStateEnum,
+ TableColumnDataTypeEnum,
+ TableColumnFilterTypeEnum,
+ TableConditionTypeEnum,
+ TableNumberCompareTypeEnum,
+} from '../../types/enum';
+import { Table } from '../table';
+import { TableColumn } from '../table-column';
+import { TableFilters } from '../table-filter';
+
+describe('Table model', () => {
+ it('builds a table from headers, tracks metadata, and serializes user changes', () => {
+ const table = new Table(
+ 'table-1',
+ 'QuarterlySales',
+ { startRow: 0, endRow: 4, startColumn: 0, endColumn: 1 },
+ ['Region', 'Amount'],
+ {
+ showHeader: true,
+ tableStyleId: 'theme-2',
+ columns: [
+ { id: 'column-region', displayName: 'Region', dataType: TableColumnDataTypeEnum.String, formula: '', meta: {}, style: {} },
+ { id: 'column-amount', displayName: 'Amount', dataType: TableColumnDataTypeEnum.String, formula: '', meta: {}, style: {} },
+ ],
+ }
+ );
+
+ table.setSubunitId('sheet-1');
+ table.setTableMeta({ owner: 'ops' });
+ table.insertColumn(2, new TableColumn('column-margin', 'Margin'));
+ table.removeColumn(2);
+ table.setDisplayName('FY Sales');
+ table.setRange({ startRow: 1, endRow: 6, startColumn: 0, endColumn: 1 });
+
+ expect(table.getTableFilterRange()).toEqual({
+ startRow: 2,
+ endRow: 6,
+ startColumn: 0,
+ endColumn: 1,
+ });
+ expect(table.getColumnsCount()).toBe(2);
+ expect(table.getColumnNameByIndex(1)).toBe('Amount');
+ expect(table.getTableInfo()).toEqual(expect.objectContaining({
+ id: 'table-1',
+ subUnitId: 'sheet-1',
+ name: 'FY Sales',
+ range: { startRow: 1, endRow: 6, startColumn: 0, endColumn: 1 },
+ meta: { owner: 'ops' },
+ showHeader: true,
+ columns: expect.arrayContaining([
+ expect.objectContaining({ id: 'column-region', displayName: 'Region' }),
+ expect.objectContaining({ id: 'column-amount', displayName: 'Amount' }),
+ ]),
+ }));
+ expect(table.getTableConfig()).toEqual({
+ name: 'FY Sales',
+ range: { startRow: 1, endRow: 6, startColumn: 0, endColumn: 1 },
+ options: {
+ showHeader: true,
+ showFooter: false,
+ },
+ tableStyleId: 'theme-2',
+ });
+
+ const snapshot = table.toJSON();
+ const restored = new Table('placeholder', 'Placeholder', { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }, []);
+ restored.fromJSON(snapshot);
+
+ expect(restored.getDisplayName()).toBe('FY Sales');
+ expect(restored.getRangeInfo()).toEqual({ startRow: 1, endRow: 6, startColumn: 0, endColumn: 1 });
+ expect(restored.getTableMeta()).toEqual({ owner: 'ops' });
+ expect(restored.toJSON().columns).toEqual(expect.arrayContaining([
+ expect.objectContaining({ id: 'column-region', displayName: 'Region' }),
+ expect.objectContaining({ id: 'column-amount', displayName: 'Amount' }),
+ ]));
+
+ restored.dispose();
+ expect(restored.getColumnsCount()).toBe(0);
+ });
+});
+
+describe('TableFilters', () => {
+ it('filters rows by manual lists and condition rules like a real table filter popup', () => {
+ const filters = new TableFilters();
+ const sheet = {
+ getCell(row: number, column: number) {
+ const cells = [
+ [{ v: 'East' }, { v: 12, t: CellValueType.NUMBER }],
+ [{ v: 'West' }, { v: 5, t: CellValueType.NUMBER }],
+ [{ v: 'East' }, { v: 20, t: CellValueType.NUMBER }],
+ ];
+
+ return cells[row]?.[column] ?? null;
+ },
+ getCellRaw(row: number, column: number) {
+ return this.getCell(row, column);
+ },
+ };
+ const range = { startRow: 0, endRow: 2, startColumn: 0, endColumn: 1 };
+
+ filters.setColumnFilter(0, {
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['East'],
+ } as never);
+ filters.setColumnFilter(1, {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.GreaterThan,
+ expectedValue: [10],
+ },
+ } as never);
+ filters.setSortState(0, SheetsTableSortStateEnum.Asc);
+
+ const filteredOutRows = filters.doFilter(sheet as never, range);
+
+ expect([...filteredOutRows]).toEqual([1]);
+ expect(filters.getColumnFilter(0)).toEqual({
+ filterType: TableColumnFilterTypeEnum.manual,
+ values: ['East'],
+ });
+ expect(filters.getFilterState(0)).toBe(SheetsTableButtonStateEnum.FilteredSortAsc);
+ expect(filters.getFilterStates(range)).toEqual([
+ SheetsTableButtonStateEnum.FilteredSortAsc,
+ SheetsTableButtonStateEnum.FilteredSortNone,
+ ]);
+ expect(filters.getFilterOutRows()).toBe(filteredOutRows);
+ expect(filters.toJSON()).toEqual({
+ tableColumnFilterList: [
+ { filterType: TableColumnFilterTypeEnum.manual, values: ['East'] },
+ {
+ filterType: TableColumnFilterTypeEnum.condition,
+ filterInfo: {
+ conditionType: TableConditionTypeEnum.Number,
+ compareType: TableNumberCompareTypeEnum.GreaterThan,
+ expectedValue: [10],
+ },
+ },
+ ],
+ tableSortInfo: { columnIndex: 0, sortState: SheetsTableSortStateEnum.Asc },
+ });
+
+ filters.dispose();
+ expect(filters.toJSON().tableColumnFilterList).toEqual([]);
+ });
+});
diff --git a/packages/sheets-thread-comment/src/controllers/__tests__/sheets-thread-comment-ref-range.controller.spec.ts b/packages/sheets-thread-comment/src/controllers/__tests__/sheets-thread-comment-ref-range.controller.spec.ts
new file mode 100644
index 0000000000..867ee5ad6d
--- /dev/null
+++ b/packages/sheets-thread-comment/src/controllers/__tests__/sheets-thread-comment-ref-range.controller.spec.ts
@@ -0,0 +1,232 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { AddCommentMutation, DeleteCommentMutation, UpdateCommentRefMutation } from '@univerjs/thread-comment';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsThreadCommentRefRangeController } from '../sheets-thread-comment-ref-range.controller';
+
+const sheetsMocks = vi.hoisted(() => ({
+ handleRangeChange: vi.fn(),
+}));
+
+vi.mock('@univerjs/sheets', async () => {
+ const actual = await vi.importActual<typeof import('@univerjs/sheets')>('@univerjs/sheets');
+ return {
+ ...actual,
+ handleCommonRangeChangeWithEffectRefCommandsSkipNoInterests: sheetsMocks.handleRangeChange,
+ };
+});
+
+function createRoot(ref = 'A1', overrides: Record<string, unknown> = {}) {
+ return {
+ id: 'comment-1',
+ threadId: 'thread-1',
+ ref,
+ dT: '2025-01-01T00:00:00.000Z',
+ personId: 'user-1',
+ text: { dataStream: 'hello\r\n', textRuns: [] },
+ attachments: [],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ ...overrides,
+ } as any;
+}
+
+describe('SheetsThreadCommentRefRangeController', () => {
+ it('should register initial comments and transform ref changes into undo/redo mutations', async () => {
+ const registerDisposes: Array<ReturnType<typeof vi.fn>> = [];
+ const watchDisposes: Array<ReturnType<typeof vi.fn>> = [];
+ const registerCalls: Array<{ callback: (commandInfo: unknown) => unknown }> = [];
+ const watchCalls: Array<{ callback: (before: unknown, after: any) => void }> = [];
+ const executeCommand = vi.fn(async () => true);
+ const root = createRoot('A1', { row: 0, column: 0 });
+ const updates$ = new Subject<any>();
+
+ const controller = new SheetsThreadCommentRefRangeController(
+ {
+ registerRefRange: (_range: unknown, callback: (commandInfo: unknown) => unknown) => {
+ const dispose = vi.fn();
+ registerDisposes.push(dispose);
+ registerCalls.push({ callback });
+ return { dispose };
+ },
+ watchRange: (_unitId: string, _subUnitId: string, _range: unknown, callback: (before: unknown, after: any) => void) => {
+ const dispose = vi.fn();
+ watchDisposes.push(dispose);
+ watchCalls.push({ callback });
+ return { dispose };
+ },
+ } as any,
+ {
+ commentUpdate$: updates$,
+ getComment: vi.fn(),
+ } as any,
+ {
+ getAll: () => [{ threads: [{ unitId: 'unit-1', subUnitId: 'sheet-1', root }] }],
+ } as any,
+ {} as any,
+ { executeCommand } as any
+ );
+
+ expect(registerCalls).toHaveLength(1);
+ expect(watchCalls).toHaveLength(1);
+
+ sheetsMocks.handleRangeChange.mockReturnValueOnce({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 });
+ expect(registerCalls[0].callback({})).toEqual({ redos: [], undos: [] });
+
+ sheetsMocks.handleRangeChange.mockReturnValueOnce({ startRow: 2, endRow: 2, startColumn: 2, endColumn: 2 });
+ expect(registerCalls[0].callback({})).toEqual({
+ redos: [{
+ id: UpdateCommentRefMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ payload: { ref: 'C3', commentId: 'comment-1' },
+ silent: false,
+ },
+ }],
+ undos: [{
+ id: UpdateCommentRefMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ payload: { ref: 'A1', commentId: 'comment-1' },
+ silent: false,
+ },
+ }],
+ });
+
+ sheetsMocks.handleRangeChange.mockReturnValueOnce(null);
+ expect(registerCalls[0].callback({})).toEqual({
+ redos: [{
+ id: DeleteCommentMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', commentId: 'comment-1' },
+ }],
+ undos: [{
+ id: AddCommentMutation.id,
+ params: expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ comment: expect.objectContaining(root),
+ sync: true,
+ }),
+ }],
+ });
+
+ await watchCalls[0].callback(null, { startRow: 4, endRow: 4, startColumn: 1, endColumn: 1 });
+ expect(executeCommand).toHaveBeenCalledWith(UpdateCommentRefMutation.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ payload: { ref: 'B5', commentId: 'comment-1' },
+ silent: true,
+ }, { onlyLocal: true });
+
+ controller.dispose();
+ });
+
+ it('should react to add, delete and updateRef comment updates by maintaining watchers', () => {
+ const registerDisposes: Array<ReturnType<typeof vi.fn>> = [];
+ const watchDisposes: Array<ReturnType<typeof vi.fn>> = [];
+ const updates$ = new Subject<any>();
+ const movedComment = createRoot('D4');
+ const getComment = vi.fn(() => movedComment);
+
+ const controller = new SheetsThreadCommentRefRangeController(
+ {
+ registerRefRange: vi.fn(() => {
+ const dispose = vi.fn();
+ registerDisposes.push(dispose);
+ return { dispose };
+ }),
+ watchRange: vi.fn(() => {
+ const dispose = vi.fn();
+ watchDisposes.push(dispose);
+ return { dispose };
+ }),
+ } as any,
+ {
+ commentUpdate$: updates$,
+ getComment,
+ } as any,
+ {
+ getAll: () => [],
+ } as any,
+ {} as any,
+ { executeCommand: vi.fn() } as any
+ );
+
+ updates$.next({
+ type: 'add',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 0,
+ column: 0,
+ payload: createRoot('A1'),
+ });
+ expect(registerDisposes).toHaveLength(1);
+ expect(watchDisposes).toHaveLength(1);
+
+ updates$.next({
+ type: 'add',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 0,
+ column: 0,
+ payload: createRoot('A1', { parentId: 'root-1' }),
+ });
+ expect(registerDisposes).toHaveLength(1);
+
+ updates$.next({
+ type: 'updateRef',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 3,
+ column: 3,
+ silent: false,
+ payload: { commentId: 'comment-1' },
+ });
+ expect(getComment).toHaveBeenCalledWith('unit-1', 'sheet-1', 'comment-1');
+ expect(registerDisposes[0]).toHaveBeenCalledTimes(1);
+ expect(watchDisposes[0]).toHaveBeenCalledTimes(1);
+ expect(registerDisposes).toHaveLength(2);
+ expect(watchDisposes).toHaveLength(2);
+
+ updates$.next({
+ type: 'updateRef',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ row: 3,
+ column: 3,
+ silent: true,
+ payload: { commentId: 'comment-1' },
+ });
+ expect(watchDisposes[1]).toHaveBeenCalledTimes(0);
+ expect(watchDisposes).toHaveLength(2);
+ expect(registerDisposes).toHaveLength(3);
+
+ updates$.next({
+ type: 'delete',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ payload: { commentId: 'comment-1' },
+ });
+ expect(registerDisposes[2]).toHaveBeenCalledTimes(1);
+ expect(watchDisposes[1]).toHaveBeenCalledTimes(1);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-thread-comment/src/controllers/__tests__/sheets-thread-comment-resource.controller.spec.ts b/packages/sheets-thread-comment/src/controllers/__tests__/sheets-thread-comment-resource.controller.spec.ts
new file mode 100644
index 0000000000..6ed04d5f16
--- /dev/null
+++ b/packages/sheets-thread-comment/src/controllers/__tests__/sheets-thread-comment-resource.controller.spec.ts
@@ -0,0 +1,152 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { CopySheetCommand, RemoveSheetCommand } from '@univerjs/sheets';
+import { AddCommentMutation, DeleteCommentMutation } from '@univerjs/thread-comment';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetsThreadCommentResourceController } from '../sheets-thread-comment-resource.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', textRuns: [] },
+ attachments: [],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ children: [{ id: 'reply-1', parentId: 'comment-1' }],
+ } as any;
+}
+
+describe('SheetsThreadCommentResourceController', () => {
+ it('should create undo/redo mutations when removing a sheet', () => {
+ let interceptorConfig: any;
+ const rootComment = createRootComment();
+
+ const controller = new SheetsThreadCommentResourceController(
+ {
+ getCurrentUnitOfType: () => ({
+ getUnitId: () => 'unit-1',
+ getActiveSheet: () => ({ getSheetId: () => 'sheet-1' }),
+ }),
+ } as any,
+ {
+ interceptCommand: (config: any) => {
+ interceptorConfig = config;
+ return { dispose: vi.fn() };
+ },
+ } as any,
+ {
+ ensureMap: () => new Map([
+ [rootComment.id, rootComment],
+ ['reply-1', { id: 'reply-1', parentId: rootComment.id }],
+ ]),
+ } as any,
+ {
+ syncUpdateMutationToColla: true,
+ } as any
+ );
+
+ const result = interceptorConfig.getMutations({
+ id: RemoveSheetCommand.id,
+ params: {},
+ });
+
+ expect(result.redos).toEqual([
+ {
+ id: DeleteCommentMutation.id,
+ params: { unitId: 'unit-1', subUnitId: 'sheet-1', commentId: 'comment-1' },
+ },
+ ]);
+ expect(result.undos).toEqual([
+ {
+ id: AddCommentMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ comment: rootComment,
+ sync: false,
+ },
+ },
+ ]);
+
+ controller.dispose();
+ });
+
+ it('should clone root comments onto the copied sheet and omit children when sync is disabled', () => {
+ let interceptorConfig: any;
+ const rootComment = createRootComment();
+
+ const controller = new SheetsThreadCommentResourceController(
+ {} as any,
+ {
+ interceptCommand: (config: any) => {
+ interceptorConfig = config;
+ return { dispose: vi.fn() };
+ },
+ } as any,
+ {
+ ensureMap: () => new Map([
+ [rootComment.id, rootComment],
+ ['reply-1', { id: 'reply-1', parentId: rootComment.id }],
+ ]),
+ } as any,
+ {
+ syncUpdateMutationToColla: false,
+ } as any
+ );
+
+ const result = interceptorConfig.getMutations({
+ id: CopySheetCommand.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ targetSubUnitId: 'sheet-2',
+ },
+ });
+
+ expect(result.redos).toHaveLength(1);
+ expect(result.redos[0]).toEqual(expect.objectContaining({
+ id: AddCommentMutation.id,
+ params: expect.objectContaining({
+ unitId: 'unit-1',
+ subUnitId: 'sheet-2',
+ sync: true,
+ }),
+ }));
+ expect(result.redos[0].params.comment).toEqual(expect.objectContaining({
+ subUnitId: 'sheet-2',
+ children: undefined,
+ }));
+ expect(result.redos[0].params.comment.id).not.toBe(rootComment.id);
+ expect(result.redos[0].params.comment.threadId).not.toBe(rootComment.threadId);
+ expect(result.undos).toEqual([
+ {
+ id: DeleteCommentMutation.id,
+ params: {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-2',
+ commentId: result.redos[0].params.comment.id,
+ },
+ },
+ ]);
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-thread-comment.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-thread-comment.spec.ts
new file mode 100644
index 0000000000..4df16fb095
--- /dev/null
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-thread-comment.spec.ts
@@ -0,0 +1,202 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { RichTextValue, UniverInstanceType } from '@univerjs/core';
+import { AddCommentCommand, DeleteCommentCommand, DeleteCommentTreeCommand, ResolveCommentCommand, UpdateCommentCommand } from '@univerjs/thread-comment';
+import { describe, expect, it, vi } from 'vitest';
+import { FTheadCommentBuilder, FTheadCommentItem, FThreadComment } from '../f-thread-comment';
+import { FWorksheetCommentMixin } from '../f-worksheet';
+
+function createBody(text: string) {
+ return RichTextValue.create({
+ id: 'doc-1',
+ body: {
+ dataStream: `${text}\r\n`,
+ textRuns: [],
+ },
+ documentStyle: {},
+ });
+}
+
+function createThread(overrides: Record<string, unknown> = {}) {
+ return {
+ id: 'comment-1',
+ threadId: 'thread-1',
+ ref: 'A1',
+ dT: '2025-01-01T00:00:00.000Z',
+ personId: 'user-1',
+ text: createBody('hello').getData().body!,
+ attachments: [],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ resolved: false,
+ children: [],
+ ...overrides,
+ } as any;
+}
+
+describe('thread comment facade', () => {
+ it('should build comment payloads with rich text and keep copies isolated', () => {
+ const richText = createBody('hello univer');
+ const builder = FTheadCommentBuilder.create()
+ .setContent(richText)
+ .setPersonId('user-2')
+ .setDateTime(new Date('2025-02-21T14:22:22.000Z'))
+ .setId('comment-2')
+ .setThreadId('thread-2');
+
+ const cloned = builder.copy().setPersonId('user-3');
+
+ expect(builder.content.getData().body).toEqual(richText.getData().body);
+ expect(builder.personId).toBe('user-2');
+ expect(builder.id).toBe('comment-2');
+ expect(builder.threadId).toBe('thread-2');
+ expect(builder.dateTime).toBe(builder.build().dT);
+ expect(cloned.personId).toBe('user-3');
+ expect(builder.personId).toBe('user-2');
+
+ const item = FTheadCommentItem.create(builder.build());
+ expect(item.content.getData().body).toEqual(builder.build().text);
+ });
+
+ it('should expose thread comment behaviors and execute comment commands with business payloads', async () => {
+ const commandService = {
+ executeCommand: vi.fn(async () => true),
+ };
+ const child = createThread({ id: 'reply-1', parentId: 'comment-1', ref: '' });
+ const root = createThread({ children: [child] });
+ const injector = {
+ createInstance: vi.fn((cls: unknown, ...args: any[]) => {
+ if ((cls as { name?: string }).name === 'FRange') {
+ return { workbook: args[0], worksheet: args[1], range: args[2] };
+ }
+ if (cls === FThreadComment) {
+ return { comment: args[0] };
+ }
+ return null;
+ }),
+ };
+ const workbook = {
+ getSheetBySheetId: (sheetId: string) => (sheetId === 'sheet-1' ? { getSheetId: () => 'sheet-1' } : null),
+ };
+ const univerInstanceService = {
+ getUnit: (_unitId: string, type: UniverInstanceType) => (type === UniverInstanceType.UNIVER_SHEET ? workbook : null),
+ };
+ const threadCommentModel = {
+ getCommentWithChildren: () => ({ ...root, children: [child] }),
+ };
+ const userManagerService = {
+ getCurrentUser: () => ({ userID: 'current-user' }),
+ };
+
+ const rootComment = new FThreadComment(
+ root,
+ undefined,
+ injector as any,
+ commandService as any,
+ univerInstanceService as any,
+ threadCommentModel as any,
+ userManagerService as any
+ );
+ const replyComment = new FThreadComment(
+ child,
+ root,
+ injector as any,
+ commandService as any,
+ univerInstanceService as any,
+ threadCommentModel as any,
+ userManagerService as any
+ );
+
+ expect(rootComment.getIsRoot()).toBe(true);
+ expect(replyComment.getIsRoot()).toBe(false);
+ expect(rootComment.getCommentData()).not.toHaveProperty('children');
+ expect(rootComment.getReplies()).toEqual([{ comment: child }]);
+ expect(rootComment.getRange()).toEqual(expect.objectContaining({
+ workbook,
+ worksheet: { getSheetId: expect.any(Function) },
+ range: expect.objectContaining({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }),
+ }));
+ expect(rootComment.getRichText().getData().body).toEqual(root.text);
+
+ await rootComment.deleteAsync();
+ await replyComment.deleteAsync();
+ await rootComment.updateAsync(createBody('updated'));
+ await rootComment.resolveAsync();
+ await rootComment.resolveAsync(true);
+ await rootComment.replyAsync(FTheadCommentBuilder.create().setContent(createBody('reply')));
+
+ expect(commandService.executeCommand).toHaveBeenCalledWith(DeleteCommentTreeCommand.id, expect.objectContaining({ commentId: root.id }));
+ expect(commandService.executeCommand).toHaveBeenCalledWith(DeleteCommentCommand.id, expect.objectContaining({ commentId: child.id }));
+ expect(commandService.executeCommand).toHaveBeenCalledWith(UpdateCommentCommand.id, expect.objectContaining({
+ payload: expect.objectContaining({
+ commentId: root.id,
+ updated: true,
+ text: createBody('updated').getData().body,
+ }),
+ }));
+ expect(commandService.executeCommand).toHaveBeenCalledWith(ResolveCommentCommand.id, expect.objectContaining({ resolved: true }));
+ expect(commandService.executeCommand).toHaveBeenCalledWith(ResolveCommentCommand.id, expect.objectContaining({ resolved: true }));
+ expect(commandService.executeCommand).toHaveBeenCalledWith(AddCommentCommand.id, expect.objectContaining({
+ comment: expect.objectContaining({
+ parentId: root.id,
+ threadId: root.threadId,
+ ref: root.ref,
+ personId: 'current-user',
+ }),
+ }));
+ });
+
+ it('worksheet facade should list, clear and subscribe to sheet comments', async () => {
+ const root = createThread();
+ const deleteAsync = vi.fn(async () => true);
+ const commandListeners: Array<(command: { id: string; params: unknown }) => void> = [];
+
+ const instance = Object.create(FWorksheetCommentMixin.prototype) as any;
+ instance._workbook = { getUnitId: () => 'unit-1' };
+ instance._worksheet = { getSheetId: () => 'sheet-1' };
+ instance._injector = {
+ get: (token: unknown) => {
+ if (typeof token === 'function' && token.name === 'SheetsThreadCommentModel') {
+ return {
+ getSubUnitAll: () => [root],
+ getComment: (_unitId: string, _subUnitId: string, commentId: string) => (commentId === root.id ? root : undefined),
+ };
+ }
+ return {
+ onCommandExecuted: (listener: (command: { id: string; params: unknown }) => void) => {
+ commandListeners.push(listener);
+ return { dispose: vi.fn() };
+ },
+ };
+ },
+ createInstance: vi.fn(() => ({ deleteAsync })),
+ };
+
+ expect(instance.getComments()).toHaveLength(1);
+ expect(await instance.clearComments()).toBe(true);
+ expect(deleteAsync).toHaveBeenCalledTimes(1);
+
+ const callback = vi.fn();
+ instance.onCommented(callback);
+ commandListeners.forEach((listener) => listener({ id: AddCommentCommand.id, params: { comment: root } }));
+ commandListeners.forEach((listener) => listener({ id: UpdateCommentCommand.id, params: { comment: root } }));
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(instance.getCommentById(root.id)).toEqual({ deleteAsync });
+ expect(instance.getCommentById('missing')).toBeUndefined();
+ });
+});
diff --git a/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts b/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts
new file mode 100644
index 0000000000..302c9d9c9f
--- /dev/null
+++ b/packages/sheets-thread-comment/src/facade/__tests__/f-workbook.spec.ts
@@ -0,0 +1,40 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { FWorkbookThreadCommentMixin } from '../f-workbook';
+
+describe('FWorkbookThreadCommentMixin', () => {
+ it('should lazily resolve the thread comment model and create workbook comment facades', async () => {
+ const rootComment = { id: 'comment-1' };
+ const deleteAsync = vi.fn(async () => true);
+ const getUnit = vi.fn(() => [{ root: rootComment }]);
+ const createInstance = vi.fn(() => ({ deleteAsync }));
+ const get = vi.fn(() => ({ getUnit }));
+
+ const instance = Object.create(FWorkbookThreadCommentMixin.prototype) as any;
+ instance._injector = { get, createInstance };
+ instance._workbook = { getUnitId: () => 'unit-1' };
+
+ instance._initialize();
+
+ expect(instance._threadCommentModel.getUnit('unit-1')).toEqual([{ root: rootComment }]);
+ expect(instance.getComments()).toEqual([{ deleteAsync }]);
+ expect(await instance.clearComments()).toBe(true);
+ expect(deleteAsync).toHaveBeenCalledTimes(1);
+ expect(createInstance).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/sheets-thread-comment/src/models/__tests__/sheets-thread-comment.model.spec.ts b/packages/sheets-thread-comment/src/models/__tests__/sheets-thread-comment.model.spec.ts
new file mode 100644
index 0000000000..b9c61e091e
--- /dev/null
+++ b/packages/sheets-thread-comment/src/models/__tests__/sheets-thread-comment.model.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 { UniverInstanceType } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { SheetsThreadCommentModel } from '../sheets-thread-comment.model';
+
+function createComment(overrides: Record<string, unknown> = {}) {
+ return {
+ id: 'comment-1',
+ threadId: 'thread-1',
+ ref: 'A1',
+ dT: '2025-01-01T00:00:00.000Z',
+ personId: 'user-1',
+ text: { dataStream: 'hello\r\n', textRuns: [] },
+ attachments: [],
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ resolved: false,
+ ...overrides,
+ } as any;
+}
+
+describe('SheetsThreadCommentModel', () => {
+ it('should build location indexes from existing root comments and expose thread data', () => {
+ const root = createComment();
+ const reply = createComment({ id: 'reply-1', parentId: root.id, ref: '', resolved: false });
+ const thread = { ...root, children: [reply] };
+ const updates$ = new Subject<any>();
+ const threadCommentModel = {
+ getAll: () => [{ threads: [{ unitId: 'unit-1', subUnitId: 'sheet-1', root }] }],
+ commentUpdate$: updates$,
+ getComment: (_unitId: string, _subUnitId: string, commentId: string) => {
+ if (commentId === root.id) {
+ return root;
+ }
+ if (commentId === reply.id) {
+ return reply;
+ }
+ return null;
+ },
+ getThread: () => thread,
+ getUnit: () => [{ subUnitId: 'sheet-1', root }],
+ };
+ const univerInstanceService = {
+ getUnitType: () => UniverInstanceType.UNIVER_SHEET,
+ };
+
+ const model = new SheetsThreadCommentModel(threadCommentModel as any, univerInstanceService as any);
+
+ expect(model.getByLocation('unit-1', 'sheet-1', 0, 0)).toBe(root.id);
+ expect(model.getAllByLocation('unit-1', 'sheet-1', 0, 0)).toEqual([root]);
+ expect(model.getCommentWithChildren('unit-1', 'sheet-1', 0, 0)).toEqual(thread);
+ expect(model.showCommentMarker('unit-1', 'sheet-1', 0, 0)).toBe(true);
+ expect(model.getSubUnitAll('unit-1', 'sheet-1')).toEqual([root]);
+
+ model.dispose();
+ });
+
+ it('should transform thread updates into sheet-aware locations and keep indexes in sync', () => {
+ const addComment = createComment();
+ const movedComment = createComment({ ref: 'D4' });
+ const updates$ = new Subject<any>();
+ const commentStore = new Map<string, any>();
+
+ const threadCommentModel = {
+ getAll: () => [],
+ commentUpdate$: updates$,
+ getComment: (_unitId: string, _subUnitId: string, commentId: string) => commentStore.get(commentId),
+ getThread: () => null,
+ getUnit: () => [],
+ };
+ const univerInstanceService = {
+ getUnitType: (unitId: string) => (unitId === 'doc-unit' ? UniverInstanceType.UNIVER_DOC : UniverInstanceType.UNIVER_SHEET),
+ };
+
+ const model = new SheetsThreadCommentModel(threadCommentModel as any, univerInstanceService as any);
+ const received: Array<any> = [];
+ const subscription = model.commentUpdate$.subscribe((update) => received.push(update));
+
+ commentStore.set(addComment.id, addComment);
+ updates$.next({ type: 'add', unitId: 'unit-1', subUnitId: 'sheet-1', payload: addComment });
+
+ expect(model.getByLocation('unit-1', 'sheet-1', 0, 0)).toBe(addComment.id);
+ expect(received.at(-1)).toEqual(expect.objectContaining({ type: 'add', row: 0, column: 0, isRoot: true }));
+
+ updates$.next({ type: 'update', unitId: 'unit-1', subUnitId: 'sheet-1', payload: { commentId: addComment.id } });
+ expect(received.at(-1)).toEqual(expect.objectContaining({ type: 'update', row: 0, column: 0 }));
+
+ commentStore.set(addComment.id, movedComment);
+ updates$.next({ type: 'updateRef', unitId: 'unit-1', subUnitId: 'sheet-1', payload: { commentId: addComment.id, ref: 'D4' } });
+
+ expect(model.getByLocation('unit-1', 'sheet-1', 0, 0)).toBeUndefined();
+ expect(model.getByLocation('unit-1', 'sheet-1', 3, 3)).toBe(addComment.id);
+ expect(received.at(-1)).toEqual(expect.objectContaining({ type: 'updateRef', row: 3, column: 3 }));
+
+ commentStore.set(addComment.id, { ...movedComment, resolved: true });
+ updates$.next({ type: 'resolve', unitId: 'unit-1', subUnitId: 'sheet-1', payload: { commentId: addComment.id, resolved: true } });
+
+ expect(received.at(-1)).toEqual(expect.objectContaining({ type: 'resolve', row: 3, column: 3 }));
+ expect(model.getByLocation('unit-1', 'sheet-1', 3, 3)).toBeUndefined();
+ expect(model.showCommentMarker('unit-1', 'sheet-1', 3, 3)).toBe(false);
+
+ updates$.next({
+ type: 'delete',
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ payload: { isRoot: true, comment: movedComment },
+ });
+
+ expect(model.getAllByLocation('unit-1', 'sheet-1', 3, 3)).toEqual([]);
+ expect(received.at(-1)).toEqual(expect.objectContaining({ type: 'delete', row: 3, column: 3 }));
+
+ updates$.next({ type: 'add', unitId: 'doc-unit', subUnitId: 'sheet-1', payload: createComment({ id: 'doc-comment', ref: 'B2' }) });
+ expect(model.getByLocation('doc-unit', 'sheet-1', 1, 1)).toBeUndefined();
+
+ subscription.unsubscribe();
+ model.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/basics/editor/__tests__/get-editor-object.spec.ts b/packages/sheets-ui/src/basics/editor/__tests__/get-editor-object.spec.ts
new file mode 100644
index 0000000000..e0973ea2ee
--- /dev/null
+++ b/packages/sheets-ui/src/basics/editor/__tests__/get-editor-object.spec.ts
@@ -0,0 +1,55 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRenderManagerService } from '@univerjs/engine-render';
+import { DOCS_VIEW_KEY } from '@univerjs/docs-ui';
+import { describe, expect, it } from 'vitest';
+import { getEditorObject } from '../get-editor-object';
+
+describe('getEditorObject', () => {
+ it('returns undefined when unitId is null or render is missing', () => {
+ const renderManagerService = {
+ getRenderById: () => null,
+ } as unknown as IRenderManagerService;
+
+ expect(getEditorObject(null, renderManagerService)).toBeUndefined();
+ expect(getEditorObject('u-1', renderManagerService)).toBeUndefined();
+ });
+
+ it('returns editor render parts from render manager', () => {
+ const document = { id: 'doc' };
+ const docBackground = { id: 'bg' };
+ const scene = { id: 'scene' };
+ const engine = { id: 'engine' };
+
+ const renderManagerService = {
+ getRenderById: () => ({
+ mainComponent: document,
+ scene,
+ engine,
+ components: new Map([[DOCS_VIEW_KEY.BACKGROUND, docBackground]]),
+ }),
+ } as unknown as IRenderManagerService;
+
+ const res = getEditorObject('u-1', renderManagerService);
+ expect(res).toEqual({
+ document,
+ docBackground,
+ scene,
+ engine,
+ });
+ });
+});
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
index 11a4eee126..9195141262 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-frozen.command.spec.ts
@@ -22,6 +22,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
import {
SetColumnFrozenCommand,
+ SetFirstColumnFrozenCommand,
+ SetFirstRowFrozenCommand,
SetRowFrozenCommand,
SetSelectionFrozenCommand,
} from '../set-frozen.command';
@@ -124,7 +126,7 @@ describe('Test commands used for change selections', () => {
expect(config?.startRow === 2 && config.startColumn === 2).toBeTruthy();
});
- it('Should cancel all freeze', async () => {
+ it('Should keep default freeze config when selection is invalid', async () => {
await commandService.executeCommand(CancelFrozenCommand.id);
const config = getFreeze();
@@ -170,6 +172,55 @@ describe('Test commands used for change selections', () => {
expect(config?.xSplit).toBe(1);
});
+ it('Should freeze first row and first column based on current viewport', async () => {
+ scrollTo(4, 6);
+
+ await commandService.executeCommand(SetFirstRowFrozenCommand.id);
+ let config = getFreeze();
+ expect(config?.startRow).toBe(5);
+ expect(config?.startColumn).toBe(-1);
+ expect(config?.ySplit).toBe(1);
+
+ await commandService.executeCommand(SetFirstColumnFrozenCommand.id);
+ config = getFreeze();
+ expect(config?.startRow).toBe(-1);
+ expect(config?.startColumn).toBe(7);
+ expect(config?.xSplit).toBe(1);
+ });
+
+ it('Should not freeze when the whole sheet is selected', async () => {
+ selectionManagerService.setSelections([
+ {
+ range: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 19,
+ endColumn: 19,
+ rangeType: RANGE_TYPE.ALL,
+ },
+ primary: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 19,
+ endColumn: 19,
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand(SetSelectionFrozenCommand.id)).resolves.toBe(false);
+ expect(getFreeze()).toEqual({
+ startRow: -1,
+ startColumn: -1,
+ xSplit: 0,
+ ySplit: 0,
+ });
+ });
+
it('Should cancel all freeze', async () => {
await commandService.executeCommand(CancelFrozenCommand.id);
diff --git a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts
index 8ed0f3dd72..3e61232613 100644
--- a/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts
+++ b/packages/sheets-ui/src/commands/commands/__tests__/set-selections.command.spec.ts
@@ -18,9 +18,11 @@ import type { Injector, IWorkbookData, Univer, Workbook } from '@univerjs/core';
import type {
IExpandSelectionCommandParams,
IMoveSelectionCommandParams,
+ IMoveSelectionEnterAndTabCommandParams,
ISelectAllCommandParams,
} from '../set-selection.command';
import { Direction, ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
import {
SetColHiddenCommand,
SetColHiddenMutation,
@@ -30,10 +32,14 @@ import {
SetRowVisibleMutation,
SetSelectedColsVisibleCommand,
SetSelectedRowsVisibleCommand,
+ SheetInterceptorService,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand, SelectAllCommand } from '../set-selection.command';
+import { KeyCode } from '@univerjs/ui';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { SelectAllService } from '../../../services/select-all/select-all.service';
+import { ISheetSelectionRenderService } from '../../../services/selection/base-selection-render.service';
+import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand, MoveSelectionEnterAndTabCommand, SelectAllCommand } from '../set-selection.command';
import {
createSelectionCommandTestBed,
SELECTION_WITH_EMPTY_CELLS_DATA,
@@ -360,6 +366,199 @@ describe('Test commands used for change selections', () => {
});
});
+ describe('Formula editor movement semantics', () => {
+ it('should use merged range bounds when moving in formula editor without a primary cell', async () => {
+ prepareSelectionsTestBed(SELECTION_WITH_MERGED_CELLS_DATA);
+
+ selectionManagerService.clear();
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ extra: 'formula-editor',
+ });
+
+ expectSelectionToBe(0, 2, 0, 2);
+ });
+
+ it('should reuse remembered primary cell in formula editor for move and expand', async () => {
+ prepareSelectionsTestBed();
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 1,
+ startColumn: 1,
+ endRow: 1,
+ endColumn: 1,
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ },
+ ]);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ extra: 'formula-editor',
+ });
+ expectSelectionToBe(1, 2, 1, 2);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await commandService.executeCommand<IExpandSelectionCommandParams>(ExpandSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ extra: 'formula-editor',
+ });
+ expectSelectionToBe(0, 0, 1, 2);
+ });
+
+ it('should expand from merged bounds in formula editor', async () => {
+ prepareSelectionsTestBed(SELECTION_WITH_MERGED_CELLS_DATA);
+
+ selectionManagerService.clear();
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await commandService.executeCommand<IExpandSelectionCommandParams>(ExpandSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ extra: 'formula-editor',
+ });
+
+ const selection = selectionManagerService.getCurrentLastSelection()!.range;
+ expect(selection.startRow).toBe(0);
+ expect(selection.startColumn).toBe(1);
+ expect(selection.endColumn).toBe(2);
+ });
+
+ it('should preserve remembered primary when expanding a merged formula reference', async () => {
+ prepareSelectionsTestBed(SELECTION_WITH_MERGED_CELLS_DATA);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 1, startColumn: 1, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 1,
+ startColumn: 1,
+ endRow: 1,
+ endColumn: 1,
+ actualRow: 1,
+ actualColumn: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ },
+ ]);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 0, startColumn: 1, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await commandService.executeCommand<IExpandSelectionCommandParams>(ExpandSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ extra: 'formula-editor',
+ });
+
+ expectSelectionToBe(0, 1, 1, 2);
+ });
+ });
+
+ describe('Guard branches', () => {
+ beforeEach(() => {
+ prepareSelectionsTestBed();
+ commandService.registerCommand(MoveSelectionEnterAndTabCommand);
+ });
+
+ it('should return false for movement commands when params are missing', async () => {
+ await expect(commandService.executeCommand(MoveSelectionCommand.id, undefined)).resolves.toBe(false);
+ await expect(commandService.executeCommand(ExpandSelectionCommand.id, undefined)).resolves.toBe(false);
+ await expect(commandService.executeCommand(MoveSelectionEnterAndTabCommand.id, undefined)).resolves.toBe(false);
+ });
+
+ it('should return false when there is no current selection', async () => {
+ selectionManagerService.clear();
+
+ await expect(commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ })).resolves.toBe(false);
+ await expect(commandService.executeCommand<IExpandSelectionCommandParams>(ExpandSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ })).resolves.toBe(false);
+ await expect(commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
+ loop: false,
+ expandToGapFirst: true,
+ })).resolves.toBe(false);
+ });
+
+ it('should return false when there is no active workbook target', async () => {
+ const univerInstanceService = get(IUniverInstanceService);
+ vi.spyOn(univerInstanceService, 'getCurrentUnitForType').mockReturnValue(null as never);
+
+ await expect(commandService.executeCommand<IMoveSelectionCommandParams>(MoveSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ })).resolves.toBe(false);
+ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ })).resolves.toBe(false);
+ await expect(commandService.executeCommand<IExpandSelectionCommandParams>(ExpandSelectionCommand.id, {
+ direction: Direction.RIGHT,
+ })).resolves.toBe(false);
+ await expect(commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
+ loop: true,
+ expandToGapFirst: true,
+ })).resolves.toBe(false);
+ });
+
+ it('should return false when enter/tab flow has no active primary selection', async () => {
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: null,
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ })).resolves.toBe(false);
+ });
+ });
+
describe('Expand to next selection or shrink to previous selection', () => {
beforeEach(() => prepareSelectionsTestBed(SELECTION_WITH_EMPTY_CELLS_DATA));
@@ -504,6 +703,170 @@ describe('Test commands used for change selections', () => {
});
});
+ describe('Move selection for enter/tab in editing flow', () => {
+ beforeEach(() => {
+ prepareSelectionsTestBed();
+ commandService.registerCommand(MoveSelectionEnterAndTabCommand);
+ });
+
+ it('should move active cell inside multi-selections and wrap to the next selection', async () => {
+ const refreshSelectionMoveEnd = vi.fn();
+ const renderManagerService = get(IRenderManagerService);
+ vi.spyOn(renderManagerService, 'getRenderById').mockReturnValue({
+ with: (identifier: unknown) => {
+ if (identifier === ISheetSelectionRenderService) {
+ return { refreshSelectionMoveEnd };
+ }
+
+ return null;
+ },
+ } as never);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 0, startColumn: 0, endRow: 0, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ },
+ {
+ range: { startRow: 1, startColumn: 0, endRow: 1, endColumn: 1, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 1,
+ startColumn: 0,
+ endRow: 1,
+ endColumn: 0,
+ actualRow: 1,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ },
+ ]);
+
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ });
+
+ let activeSelection = selectionManagerService.getCurrentSelections().find((selection) => selection.primary);
+ expect(activeSelection?.range).toEqual({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 1,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+ expect(activeSelection?.primary?.startColumn).toBe(1);
+
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ });
+
+ activeSelection = selectionManagerService.getCurrentSelections().find((selection) => selection.primary);
+ expect(activeSelection?.range).toEqual({
+ startRow: 1,
+ startColumn: 0,
+ endRow: 1,
+ endColumn: 1,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+ expect(activeSelection?.primary?.startRow).toBe(1);
+ expect(activeSelection?.primary?.startColumn).toBe(0);
+
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.LEFT,
+ keycode: KeyCode.TAB,
+ });
+
+ activeSelection = selectionManagerService.getCurrentSelections().find((selection) => selection.primary);
+ expect(activeSelection?.range).toEqual({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 1,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+ expect(activeSelection?.primary?.startRow).toBe(0);
+ expect(activeSelection?.primary?.startColumn).toBe(1);
+ expect(refreshSelectionMoveEnd).toHaveBeenCalledTimes(3);
+ });
+
+ it('should remember tab origin for enter and stop at sheet boundaries', async () => {
+ selectTopLeft();
+
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ });
+ expectSelectionToBe(0, 1, 0, 1);
+
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.DOWN,
+ keycode: KeyCode.ENTER,
+ });
+ expectSelectionToBe(1, 0, 1, 0);
+
+ selectionManagerService.setSelections([
+ {
+ range: { startRow: 19, startColumn: 19, endRow: 19, endColumn: 19, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 19,
+ startColumn: 19,
+ endRow: 19,
+ endColumn: 19,
+ actualRow: 19,
+ actualColumn: 19,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ },
+ ]);
+
+ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ })).resolves.toBe(false);
+ expectSelectionToBe(19, 19, 19, 19);
+
+ await expect(commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.DOWN,
+ keycode: KeyCode.ENTER,
+ })).resolves.toBe(false);
+ expectSelectionToBe(19, 19, 19, 19);
+ });
+
+ it('should keep the original tab anchor across repeated tab moves before enter', async () => {
+ selectTopLeft();
+
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ });
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.RIGHT,
+ keycode: KeyCode.TAB,
+ });
+ await commandService.executeCommand<IMoveSelectionEnterAndTabCommandParams>(MoveSelectionEnterAndTabCommand.id, {
+ direction: Direction.DOWN,
+ keycode: KeyCode.ENTER,
+ });
+
+ expectSelectionToBe(1, 0, 1, 0);
+ });
+ });
+
describe('Select all', () => {
beforeEach(() => prepareSelectionsTestBed());
@@ -589,6 +952,28 @@ describe('Test commands used for change selections', () => {
});
});
+ it('should use default select-all params when none are provided', async () => {
+ selectTopLeft();
+
+ await commandService.executeCommand(SelectAllCommand.id);
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 1,
+ endColumn: 1,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+
+ await commandService.executeCommand(SelectAllCommand.id);
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 19,
+ endColumn: 19,
+ rangeType: RANGE_TYPE.ALL,
+ });
+ });
+
it('Should not loop selection when `loop` is false', async () => {
selectTopLeft();
@@ -617,6 +1002,98 @@ describe('Test commands used for change selections', () => {
});
});
+ it('should append interceptor redos to select-all execution', async () => {
+ selectTopLeft();
+
+ get(SheetInterceptorService).interceptCommand({
+ getMutations: (command) => {
+ if (command.id !== SelectAllCommand.id) {
+ return { undos: [], redos: [] };
+ }
+
+ return {
+ undos: [],
+ redos: [
+ {
+ id: 'sheet.operation.set-selections',
+ params: {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ reveal: true,
+ selections: [
+ {
+ range: {
+ startRow: 2,
+ startColumn: 2,
+ endRow: 2,
+ endColumn: 2,
+ rangeType: RANGE_TYPE.NORMAL,
+ },
+ primary: {
+ startRow: 2,
+ startColumn: 2,
+ endRow: 2,
+ endColumn: 2,
+ actualRow: 2,
+ actualColumn: 2,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ },
+ ],
+ },
+ },
+ ],
+ };
+ },
+ });
+
+ await commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
+ loop: false,
+ expandToGapFirst: false,
+ });
+
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
+ startRow: 2,
+ startColumn: 2,
+ endRow: 2,
+ endColumn: 2,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+ });
+
+ it('should stop looping when the current whole-sheet selection is not the last stacked range', async () => {
+ const selectAllService = get(SelectAllService);
+
+ selectTopLeft();
+
+ await commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
+ loop: true,
+ expandToGapFirst: false,
+ });
+
+ selectAllService.rangesStack.push({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 0,
+ endColumn: 0,
+ rangeType: RANGE_TYPE.NORMAL,
+ });
+
+ await expect(commandService.executeCommand<ISelectAllCommandParams>(SelectAllCommand.id, {
+ loop: true,
+ expandToGapFirst: false,
+ })).resolves.toBe(false);
+
+ expect(selectionManagerService.getCurrentLastSelection()!.range).toEqual({
+ startRow: 0,
+ startColumn: 0,
+ endRow: 19,
+ endColumn: 19,
+ rangeType: RANGE_TYPE.ALL,
+ });
+ });
+
describe('Expand to different directions', () => {
it('Should expand to left', async () => {
select(0, 1, 0, 1, 0, 1, false, false);
diff --git a/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts
new file mode 100644
index 0000000000..b0cf7b294b
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/__tests__/auto-height.controller.spec.ts
@@ -0,0 +1,115 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IConfigService, IUniverInstanceService, Workbook } from '@univerjs/core';
+import type { RenderManagerService } from '@univerjs/engine-render';
+import type { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ CancelMarkDirtyRowAutoHeightMutation,
+ MarkDirtyRowAutoHeightMutation,
+} from '@univerjs/sheets';
+import { describe, expect, it } from 'vitest';
+import { AutoHeightController } from '../auto-height.controller';
+
+type AnyFn = (...args: unknown[]) => unknown;
+
+describe('AutoHeightController', () => {
+ it('intercepts auto height and appends lazy mark-dirty redo/undo', () => {
+ const worksheet = {
+ getSheetId: () => 's-1',
+ } as unknown;
+
+ const workbook = {
+ getUnitId: () => 'u-1',
+ getActiveSheet: () => worksheet,
+ getSheetBySheetId: (sheetId: string) => (sheetId === 's-1' ? worksheet : null),
+ } as unknown as Workbook;
+
+ const univerInstanceService = {
+ getCurrentUnitForType: () => workbook,
+ getUnit: () => workbook,
+ } as unknown as IUniverInstanceService;
+
+ const renderManagerService = {
+ getRenderById: () => ({
+ with: () => ({
+ ensureSkeleton: () => null,
+ }),
+ }),
+ } as unknown as RenderManagerService;
+
+ let getMutations: AnyFn | null = null;
+ const sheetInterceptorService = {
+ interceptAutoHeight: (config: { getMutations: AnyFn }) => {
+ getMutations = config.getMutations;
+ return { dispose: () => { } };
+ },
+ } as unknown as SheetInterceptorService;
+
+ const controller = new AutoHeightController(
+ renderManagerService,
+ sheetInterceptorService,
+ { } as unknown as SheetsSelectionsService,
+ univerInstanceService,
+ {} as IConfigService
+ );
+
+ expect(controller).toBeTruthy();
+ expect(getMutations).not.toBeNull();
+
+ const result = getMutations!({
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }],
+ lazyAutoHeightRanges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }],
+ }) as { redos: unknown[]; undos: unknown[] };
+
+ const redo = result.redos[0] as { params: { id: string } };
+ const undo = result.undos[0] as { params: { id: string } };
+ expect(redo.params.id).toEqual(expect.any(String));
+ expect(undo.params.id).toBe(redo.params.id);
+
+ // If our inline execution happened, we should have redo/undo mutations appended.
+ expect(result.redos).toEqual([
+ {
+ id: MarkDirtyRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ ranges: [{ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }],
+ id: redo.params.id,
+ },
+ options: {
+ onlyLocal: true,
+ },
+ },
+ ]);
+
+ expect(result.undos).toEqual([
+ {
+ id: CancelMarkDirtyRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ id: redo.params.id,
+ },
+ options: {
+ onlyLocal: true,
+ },
+ },
+ ]);
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/__tests__/status-bar.controller.spec.ts b/packages/sheets-ui/src/controllers/__tests__/status-bar.controller.spec.ts
new file mode 100644
index 0000000000..a90f5ec3ef
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/__tests__/status-bar.controller.spec.ts
@@ -0,0 +1,186 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency, Injector, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { CellValueType, ICommandService, ILogService, Inject, IUniverInstanceService, LocaleType, LogLevel, Plugin, RANGE_TYPE, touchDependencies, Univer, Injector as UniverInjector, UniverInstanceType } from '@univerjs/core';
+import { FormulaDataModel, FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL } from '@univerjs/engine-formula';
+import { INumfmtService, SetRangeValuesMutation, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { IStatusBarService, StatusBarService } from '../../services/status-bar.service';
+import { StatusBarController } from '../status-bar.controller';
+
+const unitId = 'test';
+const sheetId = 'sheet1';
+
+const TEST_WORKBOOK_DATA: IWorkbookData = {
+ id: unitId,
+ sheetOrder: [sheetId],
+ name: '',
+ appVersion: '0.15.4',
+ locale: LocaleType.EN_US,
+ styles: {},
+ sheets: {
+ [sheetId]: {
+ id: sheetId,
+ name: 'Sheet1',
+ rowCount: 10,
+ columnCount: 10,
+ cellData: {
+ 0: {
+ 0: { t: CellValueType.NUMBER, v: 1 },
+ },
+ 1: {
+ 0: { t: CellValueType.NUMBER, v: 2 },
+ },
+ },
+ },
+ },
+};
+
+function createTestBed() {
+ 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(UniverInjector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ ([
+ [SheetsSelectionsService],
+ [IStatusBarService, { useClass: StatusBarService }],
+ [INumfmtService, { useValue: { getValue: () => ({ pattern: '0.00' }) } }],
+ [FormulaDataModel, { useValue: { getArrayFormulaCellData: () => undefined } }],
+ [StatusBarController],
+ ] as Dependency[]).forEach((d) => this._injector.add(d));
+
+ touchDependencies(this._injector, [
+ [StatusBarController],
+ ]);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ univer.createUnit(UniverInstanceType.UNIVER_SHEET, TEST_WORKBOOK_DATA);
+ get(SheetsSelectionsService);
+ get(StatusBarController);
+
+ // Trigger SheetsSelectionsService's current workbook stream.
+ get(IUniverInstanceService).focusUnit(unitId);
+
+ get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ const commandService = get(ICommandService);
+ commandService.registerCommand(SetSelectionsOperation);
+ commandService.registerCommand(SetRangeValuesMutation);
+
+ return {
+ univer,
+ get,
+ commandService,
+ };
+}
+
+describe('StatusBarController', () => {
+ let univer: Univer;
+ let get: Injector['get'];
+ let commandService: ICommandService;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ const testBed = createTestBed();
+ univer = testBed.univer;
+ get = testBed.get;
+ commandService = testBed.commandService;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ univer.dispose();
+ });
+
+ it('updates status bar values on selection changes and cell updates within selection', () => {
+ const workbook = get(IUniverInstanceService).getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const worksheet = workbook.getActiveSheet()!;
+
+ const statusBarService = get(IStatusBarService);
+
+ const selection: ISelectionWithStyle = {
+ range: { startRow: 0, startColumn: 0, endRow: 1, endColumn: 0, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow: 0,
+ endRow: 2,
+ startColumn: 0,
+ endColumn: 1,
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ };
+
+ expect(commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId: workbook.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ selections: [selection],
+ })).toBeTruthy();
+
+ vi.advanceTimersByTime(150);
+ vi.runOnlyPendingTimers();
+
+ const state1 = statusBarService.getState();
+ expect(state1?.pattern).toBe('0.00');
+ expect(state1?.values.find((v) => v.func === FUNCTION_NAMES_MATH.SUM)?.value).toBe(3);
+ expect(state1?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.MAX)?.value).toBe(2);
+ expect(state1?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.MIN)?.value).toBe(1);
+ expect(state1?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.COUNT)?.value).toBe(2);
+ expect(state1?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.COUNTA)?.value).toBe(2);
+ expect(state1?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.AVERAGE)?.value).toBe(1.5);
+
+ // Update a cell inside the current selection; controller should recalc via commandExecuted hook.
+ expect(commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: workbook.getUnitId(),
+ subUnitId: worksheet.getSheetId(),
+ cellValue: {
+ 0: {
+ 0: { t: CellValueType.NUMBER, v: 10 },
+ },
+ },
+ })).toBeTruthy();
+
+ vi.advanceTimersByTime(150);
+ vi.runOnlyPendingTimers();
+
+ const state2 = statusBarService.getState();
+ expect(state2?.values.find((v) => v.func === FUNCTION_NAMES_MATH.SUM)?.value).toBe(12);
+ expect(state2?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.MAX)?.value).toBe(10);
+ expect(state2?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.MIN)?.value).toBe(2);
+ expect(state2?.values.find((v) => v.func === FUNCTION_NAMES_STATISTICAL.AVERAGE)?.value).toBe(6);
+
+ // Business sanity: workbook data actually updated.
+ expect(workbook.getActiveSheet()!.getCellRaw(0, 0)?.v).toBe(10);
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts
new file mode 100644
index 0000000000..7e6c7ee6fd
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/freeze.render-controller.spec.ts
@@ -0,0 +1,228 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ICommandService } from '@univerjs/core';
+import { SHEET_VIEWPORT_KEY, TRANSFORM_CHANGE_OBSERVABLE_TYPE } from '@univerjs/engine-render';
+import { SetWorksheetActiveOperation } from '@univerjs/sheets';
+import { BehaviorSubject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
+import { HeaderFreezeRenderController } from '../freeze.render-controller';
+import { createRenderTestBed } from './render-test-bed';
+
+describe('HeaderFreezeRenderController', () => {
+ it('refreshes viewports when switching sheets and freeze is enabled', () => {
+ const validViewportScrollInfo$ = new BehaviorSubject<any>(null);
+ const scrollManagerService = {
+ validViewportScrollInfo$,
+ getCurrentScrollState: () => ({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ }),
+ };
+
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [SheetScrollManagerService, { useValue: scrollManagerService }],
+ ],
+ });
+
+ const { sheet, injector, viewportMap, sheetSkeletonManagerService, context } = testBed;
+
+ // Ensure active worksheet has a freeze config (freeze first 2 rows).
+ const worksheet = sheet.getActiveSheet();
+ const config = worksheet.getConfig();
+ config.freeze = { startRow: 2, startColumn: -1, ySplit: 2, xSplit: 0 };
+
+ injector.get(ICommandService);
+
+ injector.createInstance(HeaderFreezeRenderController, context as any);
+
+ // Switching sheet tabs triggers currentSkeleton$ with SetWorksheetActiveOperation.id,
+ // and the controller should re-apply the freeze layout.
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ commandId: SetWorksheetActiveOperation.id,
+ });
+
+ const viewMainTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) as any;
+ const viewRowTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP) as any;
+ const viewMain = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) as any;
+
+ expect(viewMainTop.isActive).toBe(true);
+ expect(viewRowTop.isActive).toBe(true);
+ expect(viewMain.top).toBeGreaterThan(0);
+
+ testBed.univer.dispose();
+ });
+
+ it('applies different freeze layouts when sheet freeze config changes', () => {
+ const validViewportScrollInfo$ = new BehaviorSubject<any>(null);
+ const scrollManagerService = {
+ validViewportScrollInfo$,
+ getCurrentScrollState: () => ({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ }),
+ };
+
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [SheetScrollManagerService, { useValue: scrollManagerService }],
+ ],
+ });
+
+ const { sheet, injector, viewportMap, sheetSkeletonManagerService, context } = testBed;
+
+ injector.createInstance(HeaderFreezeRenderController, context as any);
+
+ const worksheet = sheet.getActiveSheet();
+ const applyFreeze = (freeze: any) => {
+ worksheet.getConfig().freeze = freeze;
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ commandId: SetWorksheetActiveOperation.id,
+ });
+ };
+
+ const viewMainLeftTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP) as any;
+ const viewMainTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) as any;
+ const viewMainLeft = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) as any;
+ const viewRowTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP) as any;
+ const viewColumnLeft = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT) as any;
+
+ applyFreeze({ startRow: 2, startColumn: -1, ySplit: 2, xSplit: 0 });
+ expect(viewMainTop.isActive).toBe(true);
+ expect(viewRowTop.isActive).toBe(true);
+ expect(viewMainLeft.isActive).toBe(false);
+ expect(viewColumnLeft.isActive).toBe(false);
+
+ applyFreeze({ startRow: -1, startColumn: 2, ySplit: 0, xSplit: 2 });
+ expect(viewMainTop.isActive).toBe(false);
+ expect(viewRowTop.isActive).toBe(false);
+ expect(viewMainLeft.isActive).toBe(true);
+ expect(viewColumnLeft.isActive).toBe(true);
+
+ applyFreeze({ startRow: 2, startColumn: 2, ySplit: 2, xSplit: 2 });
+ expect(viewMainLeftTop.isActive).toBe(true);
+ expect(viewMainTop.isActive).toBe(true);
+ expect(viewMainLeft.isActive).toBe(true);
+ expect(viewRowTop.isActive).toBe(true);
+ expect(viewColumnLeft.isActive).toBe(true);
+
+ applyFreeze({ startRow: -1, startColumn: -1, ySplit: 0, xSplit: 0 });
+ expect(viewMainLeftTop.isActive).toBe(false);
+ expect(viewMainTop.isActive).toBe(false);
+ expect(viewMainLeft.isActive).toBe(false);
+ expect(viewRowTop.isActive).toBe(false);
+ expect(viewColumnLeft.isActive).toBe(false);
+
+ testBed.univer.dispose();
+ });
+
+ it('syncs freeze-side viewports with valid viewport scroll state', () => {
+ const validViewportScrollInfo$ = new BehaviorSubject<any>(null);
+ const scrollManagerService = {
+ validViewportScrollInfo$,
+ getCurrentScrollState: () => ({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ }),
+ };
+
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [SheetScrollManagerService, { useValue: scrollManagerService }],
+ ],
+ });
+
+ const { sheet, injector, viewportMap, context, sheetSkeletonManagerService } = testBed;
+ injector.createInstance(HeaderFreezeRenderController, context as any);
+
+ sheet.getActiveSheet().getConfig().freeze = { startRow: 2, startColumn: 2, ySplit: 2, xSplit: 2 };
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ commandId: SetWorksheetActiveOperation.id,
+ });
+
+ validViewportScrollInfo$.next({
+ scrollX: 36,
+ scrollY: 48,
+ viewportScrollX: 320,
+ viewportScrollY: 260,
+ });
+
+ const viewRowBottom = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM) as any;
+ const viewColumnRight = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT) as any;
+ const viewMainLeft = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) as any;
+ const viewMainTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) as any;
+
+ expect(viewRowBottom.scrollY).toBe(48);
+ expect(viewRowBottom.viewportScrollY).toBe(260);
+ expect(viewColumnRight.scrollX).toBe(36);
+ expect(viewColumnRight.viewportScrollX).toBe(320);
+ expect(viewMainLeft.viewportScrollY).toBe(260);
+ expect(viewMainTop.viewportScrollX).toBe(320);
+
+ testBed.univer.dispose();
+ });
+
+ it('refreshes freeze layout on scene scale transform changes', () => {
+ const validViewportScrollInfo$ = new BehaviorSubject<any>(null);
+ const scrollManagerService = {
+ validViewportScrollInfo$,
+ getCurrentScrollState: () => ({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ }),
+ };
+
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [SheetScrollManagerService, { useValue: scrollManagerService }],
+ ],
+ });
+
+ const { sheet, injector, viewportMap, context, scene, sheetSkeletonManagerService } = testBed;
+ injector.createInstance(HeaderFreezeRenderController, context as any);
+
+ const worksheet = sheet.getActiveSheet();
+ worksheet.getConfig().freeze = { startRow: -1, startColumn: -1, ySplit: 0, xSplit: 0 };
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ commandId: SetWorksheetActiveOperation.id,
+ });
+
+ const viewMainTop = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP) as any;
+ const viewMainLeft = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT) as any;
+ expect(viewMainTop.isActive).toBe(false);
+ expect(viewMainLeft.isActive).toBe(false);
+
+ worksheet.getConfig().freeze = { startRow: 1, startColumn: 1, ySplit: 1, xSplit: 1 };
+ scene.onTransformChange$.emit({
+ type: TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale,
+ }, { stopPropagation: () => { } });
+
+ expect(viewMainTop.isActive).toBe(true);
+ expect(viewMainLeft.isActive).toBe(true);
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-move.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-move.render-controller.spec.ts
new file mode 100644
index 0000000000..d0401ba125
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-move.render-controller.spec.ts
@@ -0,0 +1,76 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { ICommandService, RANGE_TYPE } from '@univerjs/core';
+import { MoveRowsCommand, SheetsSelectionsService } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import { HeaderMoveRenderController } from '../header-move.render-controller';
+import { createRenderTestBed } from './render-test-bed';
+
+describe('HeaderMoveRenderController', () => {
+ it('moves selected rows by dragging row header and triggers command', () => {
+ const testBed = createRenderTestBed();
+ const { context, injector, sheetSkeletonManagerService } = testBed;
+
+ // Prepare a row selection (row 1) as a realistic precondition.
+ const selectionManagerService = injector.get(SheetsSelectionsService);
+ const skeleton = sheetSkeletonManagerService.getCurrentSkeleton();
+ const endColumn = skeleton.worksheet.getColumnCount() - 1;
+ const selection: ISelectionWithStyle = {
+ range: { startRow: 1, endRow: 1, startColumn: 0, endColumn, rangeType: RANGE_TYPE.ROW },
+ primary: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 0,
+ endColumn,
+ actualColumn: 0,
+ actualRow: 1,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ };
+ selectionManagerService.addSelections([selection]);
+
+ const commandService = injector.get(ICommandService);
+ const executeSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as any);
+
+ const controller = injector.createInstance(HeaderMoveRenderController, context as any);
+ controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_MOVE_PERMISSION_CHECK, {
+ handler: () => true,
+ });
+
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as any;
+ // Pointer down on row header at row 1.
+ rowHeader.onPointerDown$.emit({ offsetX: 10, offsetY: 25, button: 0 }, { isStopPropagation: false });
+ // Drag upward to before row 0.
+ (context.scene as any).onPointerMove$.emit({ offsetX: 10, offsetY: 5, button: 0 }, {});
+ // Release.
+ (context.scene as any).onPointerUp$.emit({ offsetX: 10, offsetY: 5, button: 0 }, {});
+
+ expect(executeSpy).toHaveBeenCalledWith(
+ MoveRowsCommand.id,
+ expect.objectContaining({
+ fromRange: expect.objectContaining({ startRow: 1, endRow: 1, rangeType: RANGE_TYPE.ROW }),
+ toRange: expect.objectContaining({ startRow: 0 }),
+ })
+ );
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts
new file mode 100644
index 0000000000..161eaefaf5
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/header-resize.render-controller.spec.ts
@@ -0,0 +1,57 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { ICommandService } from '@univerjs/core';
+import { DeltaRowHeightCommand } from '@univerjs/sheets';
+import { describe, expect, it, vi } from 'vitest';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import { HeaderResizeRenderController } from '../header-resize.render-controller';
+import { createRenderTestBed } from './render-test-bed';
+
+describe('HeaderResizeRenderController', () => {
+ it('resizes row by dragging the resize handle and triggers DeltaRowHeightCommand', () => {
+ const testBed = createRenderTestBed();
+ const { context, injector } = testBed;
+
+ const commandService = injector.get(ICommandService);
+ const executeSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as any);
+
+ const controller = injector.createInstance(HeaderResizeRenderController, context as any);
+ controller.interceptor.intercept(controller.interceptor.getInterceptPoints().HEADER_RESIZE_PERMISSION_CHECK, {
+ handler: () => true,
+ });
+
+ // Hover near the bottom edge of the first row to show the row resize handle.
+ const rowHeader = context.components.get(SHEET_VIEW_KEY.ROW) as any;
+ rowHeader.onPointerMove$.emit({ offsetX: 10, offsetY: 19, button: 0 }, {});
+
+ const rowResizeRect = (controller as any)._rowResizeRect;
+ // Start dragging the resize handle downward.
+ rowResizeRect.onPointerDown$.emitEvent({ offsetX: 10, offsetY: 19, button: 0 } as any);
+ (context.scene as any).onPointerMove$.emit({ offsetX: 10, offsetY: 35, button: 0 }, {});
+ (context.scene as any).onPointerUp$.emit({ offsetX: 10, offsetY: 35, button: 0 }, {});
+
+ expect(executeSpy).toHaveBeenCalledWith(
+ DeltaRowHeightCommand.id,
+ expect.objectContaining({
+ anchorRow: expect.any(Number),
+ deltaY: expect.any(Number),
+ })
+ );
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/render-test-bed.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/render-test-bed.ts
new file mode 100644
index 0000000000..fcad83481b
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/render-test-bed.ts
@@ -0,0 +1,551 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Dependency, IDisposable, Injector, IWorkbookData, Workbook } from '@univerjs/core';
+import type { IRenderContext, Vector2 } from '@univerjs/engine-render';
+import type { Observable } from 'rxjs';
+import { ICommandService, IContextService, ILogService, Inject, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Tools, Univer, Injector as UniverInjector, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { SHEET_VIEW_KEY } from '../../../common/keys';
+import enUS from '../../../locale/en-US';
+import { SheetSkeletonManagerService } from '../../../services/sheet-skeleton-manager.service';
+
+export interface ITestEvent<TEvent, TState = { stopPropagation: () => void }> {
+ subscribeEvent(handler: (evt: TEvent, state: TState) => void): IDisposable;
+ emit(evt: TEvent, state: TState): void;
+}
+
+export function createTestEvent<TEvent, TState = { stopPropagation: () => void }>(): ITestEvent<TEvent, TState> {
+ const handlers = new Set<(evt: TEvent, state: TState) => void>();
+ return {
+ subscribeEvent(handler) {
+ handlers.add(handler);
+ const dispose = () => handlers.delete(handler);
+ return { dispose, unsubscribe: dispose } as unknown as IDisposable;
+ },
+ emit(evt, state) {
+ handlers.forEach((handler) => handler(evt, state));
+ },
+ };
+}
+
+export interface IFakeViewport {
+ viewportKey: string;
+ viewportScrollX: number;
+ viewportScrollY: number;
+ scrollX: number;
+ scrollY: number;
+ isActive: boolean;
+ left: number;
+ top: number;
+ width: number;
+ height: number;
+ scrollAnimationFrameId: number | null;
+ isWheelPreventDefaultX: boolean;
+ isWheelPreventDefaultY: boolean;
+ padding?: { startX: number; endX: number; startY: number; endY: number };
+ limitedScroll(x: number, y: number): { isLimitedX: boolean; isLimitedY: boolean };
+ scrollToViewportPos(params: { viewportScrollX: number; viewportScrollY: number }): void;
+ updateScrollVal(params: { scrollX?: number; scrollY?: number; viewportScrollX?: number; viewportScrollY?: number }): void;
+ scrollByViewportDeltaVal(params: { viewportScrollX: number; viewportScrollY: number }): boolean;
+ transScroll2ViewportScrollValue(viewportScrollX: number, viewportScrollY: number): { x: number; y: number };
+ enable(): void;
+ disable(): void;
+ setPadding(padding: { startX: number; endX: number; startY: number; endY: number }): void;
+ resetPadding(): void;
+ resizeWhenFreezeChange(params: { left?: number; top?: number; right?: number; bottom?: number; width?: number; height?: number }): void;
+ calcViewportInfo(): { viewBound: unknown };
+ getScrollBar(): { horizonScrollTrack?: { height: number }; verticalScrollTrack?: { width: number } } | null;
+ onScrollAfter$: ITestEvent<any>;
+ onScrollByBar$: ITestEvent<any>;
+}
+
+export function createFakeViewport(viewportKey: string, options?: Partial<IFakeViewport> & { canvasWidth?: number; canvasHeight?: number }): IFakeViewport {
+ const canvasWidth = options?.canvasWidth ?? 800;
+ const canvasHeight = options?.canvasHeight ?? 600;
+ const viewport: IFakeViewport = {
+ viewportKey,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ scrollX: 0,
+ scrollY: 0,
+ isActive: true,
+ left: 0,
+ top: 0,
+ width: 800,
+ height: 600,
+ scrollAnimationFrameId: null,
+ isWheelPreventDefaultX: false,
+ isWheelPreventDefaultY: false,
+ onScrollAfter$: createTestEvent<any>(),
+ onScrollByBar$: createTestEvent<any>(),
+ limitedScroll: () => ({ isLimitedX: false, isLimitedY: false }),
+ scrollToViewportPos: ({ viewportScrollX, viewportScrollY }) => {
+ viewport.viewportScrollX = viewportScrollX;
+ viewport.viewportScrollY = viewportScrollY;
+ },
+ updateScrollVal: ({ scrollX, scrollY, viewportScrollX, viewportScrollY }) => {
+ if (typeof scrollX === 'number') viewport.scrollX = scrollX;
+ if (typeof scrollY === 'number') viewport.scrollY = scrollY;
+ if (typeof viewportScrollX === 'number') viewport.viewportScrollX = viewportScrollX;
+ if (typeof viewportScrollY === 'number') viewport.viewportScrollY = viewportScrollY;
+ },
+ scrollByViewportDeltaVal: ({ viewportScrollX, viewportScrollY }) => {
+ viewport.viewportScrollX += viewportScrollX;
+ viewport.viewportScrollY += viewportScrollY;
+ return true;
+ },
+ transScroll2ViewportScrollValue: (viewportScrollX, viewportScrollY) => ({ x: viewportScrollX, y: viewportScrollY }),
+ enable: () => {
+ viewport.isActive = true;
+ },
+ disable: () => {
+ viewport.isActive = false;
+ },
+ setPadding: (padding) => {
+ viewport.padding = padding;
+ },
+ resetPadding: () => {
+ viewport.padding = { startX: 0, endX: 0, startY: 0, endY: 0 };
+ },
+ resizeWhenFreezeChange: ({ left, top, right, bottom, width, height }) => {
+ if (typeof left === 'number') viewport.left = left;
+ if (typeof top === 'number') viewport.top = top;
+
+ if (typeof width === 'number') viewport.width = width;
+ if (typeof height === 'number') viewport.height = height;
+
+ if (typeof right === 'number') {
+ viewport.width = Math.max(0, canvasWidth - (viewport.left ?? 0) - right);
+ }
+ if (typeof bottom === 'number') {
+ viewport.height = Math.max(0, canvasHeight - (viewport.top ?? 0) - bottom);
+ }
+ },
+ calcViewportInfo: () => ({ viewBound: null }),
+ getScrollBar: () => null,
+ ...options,
+ };
+
+ return viewport;
+}
+
+export interface IFakeScene {
+ scaleX: number;
+ scaleY: number;
+ onMouseWheel$: ITestEvent<any>;
+ onTransformChange$: ITestEvent<any>;
+ addObjects(objs: unknown[], layer?: number): void;
+ enableLayerCache(...layers: number[]): void;
+ makeDirty(dirty: boolean): void;
+ getViewport(key: unknown): IFakeViewport | null;
+ getViewports(): IFakeViewport[];
+ getActiveViewportByCoord(_coord: Vector2): IFakeViewport | null;
+ findViewportByPosToScene(_coord: Vector2): IFakeViewport | null;
+ getViewportScrollXY(viewport: IFakeViewport): { x: number; y: number };
+ getParent(): { classType: string };
+ getCoordRelativeToViewport(vec: any): { x: number; y: number };
+ getScrollXYInfoByViewport(_coords: any, viewport?: IFakeViewport | null): { x: number; y: number };
+ getAncestorScale(): { scaleX: number; scaleY: number };
+ setCursor(cursor: string): void;
+ resetCursor(): void;
+ getEngine(): { width: number; height: number };
+ addObject(obj: unknown, layer?: number): void;
+ removeObject(obj: unknown): void;
+ addLayer(layer: unknown): void;
+ findLayerByZIndex(zIndex: number): unknown | null;
+ disableObjectsEvent(): void;
+ enableObjectsEvent(): void;
+ transformByState(params: { width: number; height: number }): void;
+ scale(x: number, y: number): void;
+ onPointerMove$: ITestEvent<any>;
+ onPointerUp$: ITestEvent<any>;
+}
+
+export function createFakeScene(
+ viewportMap: Map<any, IFakeViewport>,
+ options?: { parentClassType?: string; engine?: IFakeEngine }
+): IFakeScene {
+ const layers = new Map<number, unknown>();
+ const scene: IFakeScene = {
+ scaleX: 1,
+ scaleY: 1,
+ onMouseWheel$: createTestEvent<any, { stopPropagation: () => void }>(),
+ onTransformChange$: createTestEvent<any>(),
+ onPointerMove$: createTestEvent<any>(),
+ onPointerUp$: createTestEvent<any>(),
+ addObjects: (objs) => {
+ objs.forEach((obj) => {
+ (obj as any).parent = scene;
+ });
+ },
+ addObject: (obj) => {
+ (obj as any).parent = scene;
+ },
+ removeObject: () => { },
+ addLayer: (layer) => {
+ // We only need zIndex tracking for tests; render pipeline is not exercised here.
+ const zIndex = (layer as any)?.zIndex;
+ if (typeof zIndex === 'number') layers.set(zIndex, layer);
+ },
+ findLayerByZIndex: (zIndex) => layers.get(zIndex) ?? null,
+ disableObjectsEvent: () => { },
+ enableObjectsEvent: () => { },
+ enableLayerCache: () => { },
+ makeDirty: () => { },
+ getViewport: (key) => viewportMap.get(key) ?? null,
+ getViewports: () => Array.from(viewportMap.values()),
+ getActiveViewportByCoord: () => viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) ?? null,
+ findViewportByPosToScene: () => viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) ?? null,
+ getViewportScrollXY: (viewport) => ({ x: viewport.viewportScrollX, y: viewport.viewportScrollY }),
+ getParent: () => ({ classType: options?.parentClassType ?? 'SCENE' }),
+ setCursor: () => { },
+ resetCursor: () => { },
+ getEngine: () => (options?.engine as any) ?? ({ width: 800, height: 600 }),
+ getCoordRelativeToViewport: (vec: any) => ({ x: vec?.x ?? vec?.[0] ?? 0, y: vec?.y ?? vec?.[1] ?? 0 }),
+ getScrollXYInfoByViewport: (_coords, viewport) => ({ x: viewport?.viewportScrollX ?? 0, y: viewport?.viewportScrollY ?? 0 }),
+ getAncestorScale: () => ({ scaleX: scene.scaleX, scaleY: scene.scaleY }),
+ transformByState: () => { },
+ scale: (x, y) => {
+ scene.scaleX = x;
+ scene.scaleY = y;
+ },
+ };
+ return scene;
+}
+
+export interface IFakeEngine {
+ width: number;
+ height: number;
+ runRenderLoop(cb: () => void): void;
+ stopRenderLoop(cb: () => void): void;
+ beginFrame$: Observable<void>;
+ endFrame$: Observable<any>;
+ renderFrameTimeMetric$: Observable<[string, number]>;
+ renderFrameTags$: Observable<[string, any]>;
+}
+
+export function createFakeEngine(): IFakeEngine {
+ const beginFrame$ = new Subject<void>();
+ const endFrame$ = new Subject<any>();
+ const renderFrameTimeMetric$ = new Subject<[string, number]>();
+ const renderFrameTags$ = new Subject<[string, any]>();
+
+ return {
+ width: 800,
+ height: 600,
+ beginFrame$,
+ endFrame$,
+ renderFrameTimeMetric$,
+ renderFrameTags$,
+ runRenderLoop: (cb) => {
+ cb();
+ beginFrame$.next();
+ endFrame$.next({ FPS: 60, elapsedTime: 1, frameTime: 16 });
+ },
+ stopRenderLoop: () => { },
+ };
+}
+
+export interface IFakeSkeleton {
+ rowHeaderWidth: number;
+ columnHeaderHeight: number;
+ rowTotalHeight: number;
+ columnTotalWidth: number;
+ rowHeaderWidthAndMarginLeft: number;
+ columnHeaderHeightAndMarginTop: number;
+ rowHeightAccumulation: number[];
+ columnWidthAccumulation: number[];
+ getCellWithCoordByIndex(row: number, col: number, _ignoreMerge?: boolean): { startX: number; startY: number; endX: number; endY: number };
+ getNoMergeCellWithCoordByIndex(row: number, col: number): { startX: number; startY: number; endX: number; endY: number };
+ getCellIndexByOffset(
+ x: number,
+ y: number,
+ scaleX: number,
+ scaleY: number,
+ scrollXY: { x: number; y: number },
+ _options?: { closeFirst?: boolean }
+ ): { row: number; column: number };
+ getOffsetByRow(row: number): number;
+ getOffsetByColumn(col: number): number;
+ getOffsetRelativeToRowCol(viewportScrollX: number, viewportScrollY: number): { row: number; column: number; rowOffset: number; columnOffset: number };
+ getRangeByViewBound(_viewBound: unknown): { startRow: number; startColumn: number; endRow: number; endColumn: number };
+ getWorksheetConfig(): { freeze: any };
+ getLocation(): [string, string];
+ worksheet: {
+ getRowCount: () => number;
+ getColumnCount: () => number;
+ getSheetId: () => string;
+ getCellInfoInMergeData: (row: number, col: number) => {
+ startRow: number;
+ startColumn: number;
+ endRow: number;
+ endColumn: number;
+ isMerged: boolean;
+ isMergedMainCell: boolean;
+ };
+ };
+}
+
+export function createFakeSkeleton(options?: Partial<IFakeSkeleton>): IFakeSkeleton {
+ const rowHeight = 20;
+ const colWidth = 100;
+
+ const skeleton: IFakeSkeleton = {
+ rowHeaderWidth: 46,
+ columnHeaderHeight: 20,
+ rowTotalHeight: rowHeight * 200,
+ columnTotalWidth: colWidth * 50,
+ rowHeaderWidthAndMarginLeft: 46,
+ columnHeaderHeightAndMarginTop: 20,
+ rowHeightAccumulation: Array.from({ length: 200 }, (_, i) => (i + 1) * rowHeight),
+ columnWidthAccumulation: Array.from({ length: 50 }, (_, i) => (i + 1) * colWidth),
+ getCellWithCoordByIndex: (row, col) => ({
+ startX: col * colWidth,
+ startY: row * rowHeight,
+ endX: col * colWidth + colWidth,
+ endY: row * rowHeight + rowHeight,
+ }),
+ getNoMergeCellWithCoordByIndex: (row, col) => ({
+ startX: col * colWidth,
+ startY: row * rowHeight,
+ endX: col * colWidth + colWidth,
+ endY: row * rowHeight + rowHeight,
+ }),
+ getCellIndexByOffset: (x, y, scaleX, scaleY, scrollXY) => {
+ const actualX = x / (scaleX || 1) + (scrollXY?.x ?? 0);
+ const actualY = y / (scaleY || 1) + (scrollXY?.y ?? 0);
+ return {
+ row: Math.max(0, Math.floor(actualY / rowHeight)),
+ column: Math.max(0, Math.floor(actualX / colWidth)),
+ };
+ },
+ getOffsetByRow: (row) => row * rowHeight,
+ getOffsetByColumn: (col) => col * colWidth,
+ getOffsetRelativeToRowCol: (viewportScrollX, viewportScrollY) => {
+ const column = Math.max(0, Math.floor(viewportScrollX / colWidth));
+ const row = Math.max(0, Math.floor(viewportScrollY / rowHeight));
+ return {
+ row,
+ column,
+ rowOffset: viewportScrollY - row * rowHeight,
+ columnOffset: viewportScrollX - column * colWidth,
+ };
+ },
+ getRangeByViewBound: () => ({ startRow: 0, startColumn: 0, endRow: 20, endColumn: 10 }),
+ getWorksheetConfig: () => ({ freeze: { startRow: 0, startColumn: 0, xSplit: 0, ySplit: 0 } }),
+ getLocation: () => ['test', 'sheet1'],
+ worksheet: {
+ getRowCount: () => 200,
+ getColumnCount: () => 50,
+ getSheetId: () => 'sheet1',
+ getCellInfoInMergeData: (row: number, col: number) => ({
+ startRow: row,
+ startColumn: col,
+ endRow: row,
+ endColumn: col,
+ isMerged: false,
+ isMergedMainCell: false,
+ }),
+ },
+ ...options,
+ };
+
+ return skeleton;
+}
+
+export interface IRenderTestBed {
+ univer: Univer;
+ injector: Injector;
+ get: Injector['get'];
+ sheet: Workbook;
+ context: IRenderContext<Workbook>;
+ viewportMap: Map<any, IFakeViewport>;
+ scene: IFakeScene;
+ engine: IFakeEngine;
+ skeleton: IFakeSkeleton;
+ commandService: ICommandService;
+ contextService: IContextService;
+ sheetSkeletonManagerService: {
+ currentSkeleton$: Observable<any>;
+ currentSkeletonBefore$: Observable<any>;
+ getCurrentParam: () => { unitId: string; sheetId: string; skeleton: IFakeSkeleton };
+ getCurrentSkeleton: () => IFakeSkeleton;
+ getSkeletonParam: (sheetId: string) => { skeleton: IFakeSkeleton } | null;
+ attachRangeWithCoord: (range: { startRow: number; startColumn: number; endRow: number; endColumn: number; rangeType?: unknown }) => any;
+ emitCurrentSkeleton: (value: any) => void;
+ emitCurrentSkeletonBefore: (value: any) => void;
+ };
+ renderManagerService: IRenderManagerService;
+}
+
+// eslint-disable-next-line max-lines-per-function
+export function createRenderTestBed(options?: { workbookData?: IWorkbookData; dependencies?: Dependency[]; parentClassType?: string }): IRenderTestBed {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+
+ class TestPlugin extends Plugin {
+ static override pluginName = 'render-test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ constructor(
+ _config: undefined,
+ @Inject(UniverInjector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ this._injector.add([SheetsSelectionsService]);
+ this._injector.add([SheetInterceptorService]);
+ options?.dependencies?.forEach((d) => this._injector.add(d));
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+
+ const snapshot = Tools.deepClone(options?.workbookData ?? {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {},
+ },
+ },
+ } satisfies IWorkbookData);
+
+ const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, snapshot);
+ injector.get(IUniverInstanceService).focusUnit(snapshot.id);
+
+ const localeService = injector.get(LocaleService);
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.load({ enUS });
+
+ injector.get(ILogService).setLogLevel(LogLevel.SILENT);
+
+ const contextService = injector.get(IContextService);
+ const commandService = injector.get(ICommandService);
+
+ const engine = createFakeEngine();
+
+ const viewportMap = new Map<any, IFakeViewport>();
+ const viewportFactory = (key: string) => createFakeViewport(key, { canvasWidth: engine.width, canvasHeight: engine.height });
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_MAIN, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_MAIN));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_ROW_TOP));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP));
+ viewportMap.set(SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP, viewportFactory(SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP));
+
+ const scene = createFakeScene(viewportMap, { parentClassType: options?.parentClassType, engine });
+
+ const components = new Map<any, any>();
+ components.set(SHEET_VIEW_KEY.ROW, { onPointerDown$: createTestEvent<any>(), onPointerMove$: createTestEvent<any>(), onPointerLeave$: createTestEvent<any>() });
+ components.set(SHEET_VIEW_KEY.COLUMN, { onPointerDown$: createTestEvent<any>(), onPointerMove$: createTestEvent<any>(), onPointerLeave$: createTestEvent<any>() });
+ components.set(SHEET_VIEW_KEY.LEFT_TOP, { onPointerDown$: createTestEvent<any>() });
+
+ const mainComponent = {
+ zIndex: 1,
+ makeForceDirty: () => { },
+ onPointerDown$: createTestEvent<any>(),
+ };
+
+ const context: IRenderContext<Workbook> = {
+ unitId: sheet.getUnitId(),
+ unit: sheet,
+ type: UniverInstanceType.UNIVER_SHEET,
+ engine: engine as any,
+ scene: scene as any,
+ mainComponent: mainComponent as any,
+ components,
+ isMainScene: true,
+ activated$: new BehaviorSubject(true),
+ activate: () => { },
+ deactivate: () => { },
+ } as unknown as IRenderContext<Workbook>;
+
+ const skeleton = createFakeSkeleton();
+ const currentSkeleton$ = new BehaviorSubject<any>(null);
+ const currentSkeletonBefore$ = new BehaviorSubject<any>(null);
+ const sheetSkeletonManagerService = {
+ currentSkeleton$: currentSkeleton$.asObservable(),
+ currentSkeletonBefore$: currentSkeletonBefore$.asObservable(),
+ getCurrentParam: () => ({ unitId: sheet.getUnitId(), sheetId: 'sheet1', skeleton }),
+ getCurrentSkeleton: () => skeleton,
+ getSkeletonParam: (_sheetId: string) => ({ skeleton }),
+ attachRangeWithCoord: (range: { startRow: number; startColumn: number; endRow: number; endColumn: number; rangeType?: unknown }) => {
+ const { startRow, startColumn, endRow, endColumn, rangeType } = range;
+ const startCell = skeleton.getNoMergeCellWithCoordByIndex(startRow, startColumn);
+ const endCell = skeleton.getNoMergeCellWithCoordByIndex(endRow, endColumn);
+ return {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ rangeType,
+ startX: startCell?.startX ?? 0,
+ startY: startCell?.startY ?? 0,
+ endX: endCell?.endX ?? 0,
+ endY: endCell?.endY ?? 0,
+ };
+ },
+ emitCurrentSkeleton: (value: any) => currentSkeleton$.next(value),
+ emitCurrentSkeletonBefore: (value: any) => currentSkeletonBefore$.next(value),
+ };
+
+ injector.add([SheetSkeletonManagerService, { useValue: sheetSkeletonManagerService as any }]);
+
+ const renderManagerService: IRenderManagerService = {
+ getRenderById: (unitId: string) => {
+ if (unitId !== sheet.getUnitId()) return null as any;
+ return {
+ unitId,
+ engine,
+ scene,
+ mainComponent,
+ components,
+ } as any;
+ },
+ } as IRenderManagerService;
+
+ injector.add([IRenderManagerService, { useValue: renderManagerService as any }]);
+
+ return {
+ univer,
+ injector,
+ get: injector.get.bind(injector),
+ sheet,
+ context,
+ viewportMap,
+ scene,
+ engine,
+ skeleton,
+ commandService,
+ contextService,
+ sheetSkeletonManagerService,
+ renderManagerService,
+ };
+}
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.ts
new file mode 100644
index 0000000000..a99b55c0ea
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/scroll.render-controller.spec.ts
@@ -0,0 +1,217 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { FOCUSING_SHEET, ICommandService } from '@univerjs/core';
+import { RENDER_CLASS_TYPE, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { Subject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { ScrollCommand, SetScrollRelativeCommand } from '../../../commands/commands/set-scroll.command';
+import { SheetScrollManagerService } from '../../../services/scroll-manager.service';
+import { SheetsScrollRenderController } from '../scroll.render-controller';
+import { createRenderTestBed } from './render-test-bed';
+
+function createScrollManagerServiceMock() {
+ const rawScrollInfo$ = new Subject<any>();
+
+ const service: any = {
+ rawScrollInfo$,
+ currentSkeletonBefore$: { subscribe: vi.fn(() => ({ unsubscribe: vi.fn() })) },
+ setValidScrollStateToCurrSheet: vi.fn(),
+ validViewportScrollInfo$: { next: vi.fn() },
+ setSearchParam: vi.fn(),
+ getScrollStateByParam: vi.fn(() => null),
+ calcViewportScrollFromRowColOffset: vi.fn(() => ({ viewportScrollX: 0, viewportScrollY: 0 })),
+ getCurrentScrollState: vi.fn(() => ({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ })),
+ };
+
+ return service;
+}
+
+describe('SheetsScrollRenderController', () => {
+ it('executes relative scroll command on mousewheel when focused', () => {
+ const scrollManagerService = createScrollManagerServiceMock();
+
+ const testBed = createRenderTestBed({
+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],
+ });
+ const { context, scene, contextService } = testBed;
+ const commandService = testBed.get(ICommandService);
+ const executeSpy = vi.spyOn(commandService, 'executeCommand');
+
+ contextService.setContextValue(FOCUSING_SHEET, true);
+
+ const _controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);
+
+ const preventDefault = vi.fn();
+ scene.onMouseWheel$.emit(
+ { ctrlKey: false, shiftKey: false, deltaX: 5, deltaY: 10, preventDefault },
+ { stopPropagation: () => { } }
+ );
+
+ expect(executeSpy).toHaveBeenCalledWith(SetScrollRelativeCommand.id, { offsetX: 5, offsetY: 10 });
+
+ // Avoid disposing here: faked render context does not implement all IDisposable contracts.
+ void _controller;
+ });
+
+ it('uses shift-wheel horizontal scrolling and prevents default on scrollable viewport', () => {
+ const scrollManagerService = createScrollManagerServiceMock();
+ const testBed = createRenderTestBed({
+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],
+ parentClassType: RENDER_CLASS_TYPE.SCENE_VIEWER,
+ });
+ const { context, scene, contextService, viewportMap } = testBed;
+ const commandService = testBed.get(ICommandService);
+ const executeSpy = vi.spyOn(commandService, 'executeCommand');
+
+ contextService.setContextValue(FOCUSING_SHEET, true);
+
+ const controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);
+ const viewMain = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) as any;
+ viewMain.limitedScroll = vi.fn(() => ({ isLimitedX: false, isLimitedY: false }));
+
+ const preventDefault = vi.fn();
+ const stopPropagation = vi.fn();
+
+ scene.onMouseWheel$.emit(
+ { ctrlKey: false, shiftKey: true, deltaX: 3, deltaY: 7, preventDefault },
+ { stopPropagation }
+ );
+
+ expect(executeSpy).toHaveBeenCalledWith(SetScrollRelativeCommand.id, { offsetX: 21, offsetY: 0 });
+ expect(preventDefault).toHaveBeenCalled();
+ expect(stopPropagation).toHaveBeenCalled();
+
+ void controller;
+ });
+
+ it('updates scroll state from viewport events and executes ScrollCommand when scrolling bar', () => {
+ const scrollManagerService = createScrollManagerServiceMock();
+ const testBed = createRenderTestBed({
+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],
+ });
+ const { context, viewportMap } = testBed;
+ const commandService = testBed.get(ICommandService);
+ const executeSpy = vi.spyOn(commandService, 'executeCommand');
+
+ const controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);
+ const viewMain = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) as any;
+
+ viewMain.onScrollAfter$.emit({ isTrigger: true, viewportScrollX: 250, viewportScrollY: 45, scrollX: 250, scrollY: 45 }, {});
+ expect(scrollManagerService.setValidScrollStateToCurrSheet).toHaveBeenCalledWith({
+ sheetViewStartRow: 2,
+ sheetViewStartColumn: 2,
+ offsetX: 50,
+ offsetY: 5,
+ viewportScrollX: 250,
+ viewportScrollY: 45,
+ scrollX: 250,
+ scrollY: 45,
+ });
+ expect(scrollManagerService.validViewportScrollInfo$.next).toHaveBeenCalled();
+
+ viewMain.onScrollByBar$.emit({ isTrigger: true, viewportScrollX: 250, viewportScrollY: 45 }, {});
+ expect(executeSpy).toHaveBeenCalledWith(ScrollCommand.id, {
+ sheetViewStartRow: 2,
+ sheetViewStartColumn: 2,
+ offsetX: 50,
+ offsetY: 5,
+ });
+
+ void controller;
+ });
+
+ it('handles skeleton switch sync and raw scroll updates', () => {
+ const scrollManagerService = createScrollManagerServiceMock();
+ (scrollManagerService as any).getScrollStateByParam = vi.fn(() => ({
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 4,
+ offsetX: 10,
+ offsetY: 6,
+ }));
+ (scrollManagerService as any).calcViewportScrollFromRowColOffset = vi.fn(() => ({ viewportScrollX: 410, viewportScrollY: 66 }));
+
+ const testBed = createRenderTestBed({
+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],
+ });
+ const { context, viewportMap, sheet, sheetSkeletonManagerService } = testBed;
+ const controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);
+ const viewMain = viewportMap.get(SHEET_VIEWPORT_KEY.VIEW_MAIN) as any;
+
+ scrollManagerService.rawScrollInfo$.next({
+ sheetViewStartRow: 1,
+ sheetViewStartColumn: 2,
+ offsetX: 5,
+ offsetY: 7,
+ });
+ expect(viewMain.viewportScrollX).toBe(205);
+ expect(viewMain.viewportScrollY).toBe(27);
+
+ sheetSkeletonManagerService.emitCurrentSkeletonBefore({
+ unitId: sheet.getUnitId(),
+ sheetId: 'sheet1',
+ });
+ expect(scrollManagerService.setSearchParam).toHaveBeenCalledWith({
+ unitId: sheet.getUnitId(),
+ sheetId: 'sheet1',
+ });
+ expect(viewMain.viewportScrollX).toBe(410);
+ expect(viewMain.viewportScrollY).toBe(66);
+
+ void controller;
+ });
+
+ it('scrolls to cell with freeze offset and supports range-based scroll', () => {
+ const scrollManagerService = createScrollManagerServiceMock();
+ const testBed = createRenderTestBed({
+ dependencies: [[SheetScrollManagerService, { useValue: scrollManagerService }]],
+ });
+ const { context, sheet } = testBed;
+ const commandService = testBed.get(ICommandService);
+ const syncSpy = vi.spyOn(commandService, 'syncExecuteCommand').mockReturnValue(true as any);
+
+ (testBed.skeleton as any).getHiddenColumnsInRange = vi.fn(() => []);
+ (testBed.skeleton as any).getHiddenRowsInRange = vi.fn(() => []);
+
+ const worksheet = sheet.getActiveSheet();
+ worksheet.getConfig().freeze = { startRow: 2, startColumn: 1, ySplit: 2, xSplit: 1 };
+
+ const controller = testBed.injector.createInstance(SheetsScrollRenderController, context as any);
+
+ expect(controller.scrollToCell(5, 7, 300)).toBe(true);
+ expect(syncSpy).toHaveBeenCalledWith(ScrollCommand.id, {
+ sheetViewStartRow: 3,
+ sheetViewStartColumn: 6,
+ offsetX: 0,
+ offsetY: 0,
+ duration: 300,
+ });
+
+ const scrolled = controller.scrollToRange(
+ { startRow: 30, endRow: 30, startColumn: 2, endColumn: 2 },
+ true,
+ false
+ );
+ expect(scrolled).toBe(true);
+
+ void controller;
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
new file mode 100644
index 0000000000..e19ef86efa
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/zoom.render-controller.spec.ts
@@ -0,0 +1,80 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { FOCUSING_SHEET, ICommandService } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { SetZoomRatioCommand } from '../../../commands/commands/set-zoom-ratio.command';
+import { SheetsZoomRenderController } from '../zoom.render-controller';
+import { createRenderTestBed } from './render-test-bed';
+
+describe('SheetsZoomRenderController', () => {
+ it('executes zoom command only when ctrl+wheels and sheet is focused', () => {
+ const testBed = createRenderTestBed();
+ const { context, scene, contextService } = testBed;
+ contextService.setContextValue(FOCUSING_SHEET, true);
+
+ const commandService = testBed.get(ICommandService);
+
+ const executeSpy = vi.spyOn(commandService, 'executeCommand');
+
+ const controller = testBed.injector.createInstance(SheetsZoomRenderController, context as any);
+
+ const sheet = testBed.sheet.getActiveSheet();
+ expect(sheet).toBeTruthy();
+
+ const preventDefault = vi.fn();
+ scene.onMouseWheel$.emit(
+ { ctrlKey: false, deltaX: 10, deltaY: -10, preventDefault },
+ { stopPropagation: () => { } }
+ );
+ expect(executeSpy).not.toHaveBeenCalled();
+
+ scene.onMouseWheel$.emit(
+ { ctrlKey: true, deltaX: 10, deltaY: -10, preventDefault },
+ { stopPropagation: () => { } }
+ );
+
+ expect(executeSpy).toHaveBeenCalledWith(
+ SetZoomRatioCommand.id,
+ expect.objectContaining({
+ unitId: testBed.sheet.getUnitId(),
+ subUnitId: sheet!.getSheetId(),
+ zoomRatio: expect.any(Number),
+ })
+ );
+
+ expect(preventDefault).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+
+ it('updates active worksheet zoom in-place', () => {
+ const testBed = createRenderTestBed();
+ const { context, scene } = testBed;
+ const scaleSpy = vi.spyOn(scene, 'scale');
+ const makeDirtySpy = vi.spyOn(context.mainComponent as any, 'makeForceDirty');
+
+ const controller = testBed.injector.createInstance(SheetsZoomRenderController, context as any);
+
+ const sheetId = testBed.sheet.getActiveSheet()!.getSheetId();
+ const ok = controller.updateZoom(sheetId, 1.5);
+ expect(ok).toBe(true);
+ expect(scaleSpy).toHaveBeenCalledWith(1.5, 1.5);
+ expect(makeDirtySpy).toHaveBeenCalled();
+
+ controller.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts
index 1afc8b76dc..fbca962d0e 100644
--- a/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts
+++ b/packages/sheets-ui/src/facade/__tests__/f-univer.spec.ts
@@ -14,16 +14,71 @@
* limitations under the License.
*/
-import { ICommandService, IPermissionService } from '@univerjs/core';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, IPermissionService, IUniverInstanceService, LifecycleService, LifecycleStages } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { EditorService, IEditorService } from '@univerjs/docs-ui';
import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';
import { IRefSelectionsService, RefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';
-import { EditorBridgeService, IEditorBridgeService, ISheetClipboardService, SheetPasteShortKeyCommand, SheetPermissionRenderManagerService } from '@univerjs/sheets-ui';
+import { DragManagerService, EditorBridgeService, HoverManagerService, IEditorBridgeService, ISheetClipboardService, SheetPasteShortKeyCommand, SheetPermissionRenderManagerService } from '@univerjs/sheets-ui';
import { IClipboardInterfaceService } from '@univerjs/ui';
+import { Subject } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
import { createFacadeTestBed } from './create-test-bed';
+import '../f-event';
import '../f-univer';
+import '../f-workbook';
+import '../f-worksheet';
+
+interface ITestClipboardParam {
+ html?: string;
+ text?: string;
+}
+
+interface ITestPasteParam {
+ htmlContent?: string;
+ textContent?: string;
+}
+
+interface ITestHoverCell {
+ location: {
+ unitId: string;
+ subUnitId: string;
+ row: number;
+ col: number;
+ };
+ position: {
+ startX: number;
+ startY: number;
+ endX: number;
+ endY: number;
+ };
+}
+
+interface ITestHeaderEvent {
+ unitId: string;
+ subUnitId: string;
+ index: number;
+}
+
+interface ITestDragCell extends ITestHoverCell {
+ dataTransfer: DataTransfer;
+}
+
+type ITestUniverAPI = typeof createFacadeTestBed extends (...args: never[]) => infer TResult
+ ? TResult extends { univerAPI: infer TApi }
+ ? TApi & {
+ _generateClipboardCopyParam: () => ITestClipboardParam | undefined;
+ _generateClipboardPasteParam: (params: ITestPasteParam) => ITestClipboardParam | undefined;
+ _beforeClipboardPaste: (params: ITestPasteParam) => void;
+ _clipboardPaste: (params: ITestPasteParam) => void;
+ _generateClipboardPasteParamAsync: () => Promise<unknown>;
+ _beforeClipboardPasteAsync: () => Promise<void>;
+ _clipboardPasteAsync: () => Promise<void>;
+ fireEvent: (...args: unknown[]) => void;
+ }
+ : never
+ : never;
describe('Test FUniver UI mixin', () => {
const clipboardService = {
@@ -57,7 +112,7 @@ describe('Test FUniver UI mixin', () => {
[SheetsSelectionsService],
]);
- const univerAPI = testBed.univerAPI as any;
+ const univerAPI = testBed.univerAPI as ITestUniverAPI;
const commandService = testBed.get(ICommandService);
const sheet = testBed.univerAPI.getActiveWorkbook()!.getActiveSheet();
const activeWorkbookMock = {
@@ -106,4 +161,146 @@ describe('Test FUniver UI mixin', () => {
expect(eventTypes.includes(univerAPI.Event.BeforeClipboardPaste)).toBe(true);
expect(eventTypes.includes(univerAPI.Event.ClipboardPasted)).toBe(true);
});
+
+ it('should bridge sheet edit lifecycle events through workbook editing flows', async () => {
+ const testBed = createFacadeTestBed(undefined, [
+ [IEditorBridgeService, { useClass: EditorBridgeService }],
+ [IEditorService, { useClass: EditorService }],
+ [DocSelectionManagerService],
+ [IDefinedNamesService, { useClass: DefinedNamesService }],
+ [IRefSelectionsService, { useClass: RefSelectionsService }],
+ [SheetsSelectionsService],
+ ]);
+
+ const commandService = testBed.get(ICommandService);
+ commandService.registerCommand(SetCellEditVisibleOperation);
+
+ const workbook = testBed.univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+ const editorBridgeService = testBed.get(IEditorBridgeService);
+ const univerInstanceService = testBed.get(IUniverInstanceService);
+ const getUnit = univerInstanceService.getUnit.bind(univerInstanceService);
+ vi.spyOn(editorBridgeService, 'getEditLocation').mockReturnValue({
+ unitId: workbook.getId(),
+ sheetId: worksheet.getSheetId(),
+ row: 2,
+ column: 3,
+ editorUnitId: 'editor-unit',
+ documentLayoutObject: {} as never,
+ });
+ vi.spyOn(univerInstanceService, 'getUnit').mockImplementation(((unitId: string) => {
+ if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
+ return {
+ getSnapshot: () => ({ body: { dataStream: 'edit\r\n' } }),
+ } as never;
+ }
+
+ return getUnit(unitId as never);
+ }) as never);
+
+ const logs: string[] = [];
+ const disposables = [
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.BeforeSheetEditStart, ({ row, column }) => logs.push(`before-start:${row},${column}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SheetEditStarted, ({ row, column }) => logs.push(`start:${row},${column}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.BeforeSheetEditEnd, ({ isConfirm, row, column }) => logs.push(`before-end:${isConfirm}:${row},${column}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.SheetEditEnded, ({ isConfirm, row, column }) => logs.push(`end:${isConfirm}:${row},${column}`)),
+ ];
+
+ expect(workbook.startEditing()).toBe(true);
+ await workbook.endEditingAsync(true);
+ expect(workbook.startEditing()).toBe(true);
+ await workbook.abortEditingAsync();
+
+ expect(logs).toEqual(expect.arrayContaining([
+ 'before-start:2,3',
+ 'start:2,3',
+ 'before-end:true:2,3',
+ 'end:true:2,3',
+ 'before-end:false:2,3',
+ 'end:false:2,3',
+ ]));
+
+ disposables.forEach((disposable) => disposable.dispose());
+ });
+
+ it('should bridge render-layer hover and drag events', () => {
+ const currentClickedCell$ = new Subject<ITestHoverCell>();
+ const currentHoveredRowHeader$ = new Subject<ITestHeaderEvent>();
+ const currentColHeaderPointerDown$ = new Subject<ITestHeaderEvent>();
+ const currentDragCell$ = new Subject<ITestDragCell>();
+ const endDragCell$ = new Subject<ITestDragCell>();
+
+ const hoverManagerService = {
+ currentClickedCell$,
+ currentRichText$: new Subject<unknown>(),
+ currentPointerDownCell$: new Subject<unknown>(),
+ currentPointerUpCell$: new Subject<unknown>(),
+ currentCellPosWithEvent$: new Subject<unknown>(),
+ currentRowHeaderClick$: new Subject<unknown>(),
+ currentRowHeaderPointerDown$: new Subject<unknown>(),
+ currentRowHeaderPointerUp$: new Subject<unknown>(),
+ currentHoveredRowHeader$,
+ currentColHeaderClick$: new Subject<unknown>(),
+ currentColHeaderPointerDown$,
+ currentColHeaderPointerUp$: new Subject<unknown>(),
+ currentHoveredColHeader$: new Subject<unknown>(),
+ };
+
+ const dragManagerService = {
+ currentCell$: currentDragCell$,
+ endCell$: endDragCell$,
+ };
+
+ const testBed = createFacadeTestBed(undefined, [
+ [HoverManagerService, { useValue: hoverManagerService }],
+ [DragManagerService, { useValue: dragManagerService }],
+ [IEditorBridgeService, { useClass: EditorBridgeService }],
+ [IEditorService, { useClass: EditorService }],
+ [DocSelectionManagerService],
+ [IDefinedNamesService, { useClass: DefinedNamesService }],
+ [IRefSelectionsService, { useClass: RefSelectionsService }],
+ [SheetsSelectionsService],
+ ]);
+
+ const workbook = testBed.univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+ const logs: string[] = [];
+ const disposables = [
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.CellClicked, ({ row, column }) => logs.push(`cell:${row},${column}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.RowHeaderHover, ({ row }) => logs.push(`row-hover:${row}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.ColumnHeaderPointerDown, ({ column }) => logs.push(`col-down:${column}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.DragOver, ({ row, column }) => logs.push(`drag:${row},${column}`)),
+ testBed.univerAPI.addEvent(testBed.univerAPI.Event.Drop, ({ row, column }) => logs.push(`drop:${row},${column}`)),
+ ];
+
+ const lifecycleService = testBed.get(LifecycleService);
+ lifecycleService.stage = LifecycleStages.Rendered;
+
+ currentClickedCell$.next({
+ location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 1, col: 2 },
+ position: { startX: 0, startY: 0, endX: 10, endY: 10 },
+ });
+ currentHoveredRowHeader$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 5 });
+ currentColHeaderPointerDown$.next({ unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), index: 6 });
+ currentDragCell$.next({
+ location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 3, col: 4 },
+ position: { startX: 0, startY: 0, endX: 10, endY: 10 },
+ dataTransfer: {} as DataTransfer,
+ });
+ endDragCell$.next({
+ location: { unitId: workbook.getId(), subUnitId: worksheet.getSheetId(), row: 7, col: 8 },
+ position: { startX: 0, startY: 0, endX: 10, endY: 10 },
+ dataTransfer: {} as DataTransfer,
+ });
+
+ expect(logs).toEqual(expect.arrayContaining([
+ 'cell:1,2',
+ 'row-hover:5',
+ 'col-down:6',
+ 'drag:3,4',
+ 'drop:7,8',
+ ]));
+
+ disposables.forEach((disposable) => disposable.dispose());
+ });
});
diff --git a/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts
index bd43cc9a7a..3301777f2a 100644
--- a/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts
+++ b/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts
@@ -18,8 +18,11 @@ import { ICommandService } from '@univerjs/core';
import { DocSelectionManagerService } from '@univerjs/docs';
import { EditorService, IEditorService } from '@univerjs/docs-ui';
import { DefinedNamesService, IDefinedNamesService } from '@univerjs/engine-formula';
-import { IRefSelectionsService, RefSelectionsService, SheetsSelectionsService } from '@univerjs/sheets';
+import { IRenderManagerService, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { IRefSelectionsService, RefSelectionsService, SetWorksheetRowIsAutoHeightCommand, SheetsSelectionsService } from '@univerjs/sheets';
+import { ISheetSelectionRenderService, SetColumnHeaderHeightCommand, SetRowHeaderWidthCommand, SHEET_VIEW_KEY, SheetScrollManagerService, SheetSkeletonManagerService, SheetsScrollRenderController } from '@univerjs/sheets-ui';
import { describe, expect, it, vi } from 'vitest';
+import { SetWorksheetColAutoWidthCommand } from '../../commands/commands/set-worksheet-auto-col-width.command';
import { SetCellEditVisibleOperation } from '../../commands/operations/cell-edit.operation';
import { EditorBridgeService, IEditorBridgeService } from '../../services/editor-bridge.service';
import { createFacadeTestBed } from './create-test-bed';
@@ -77,4 +80,163 @@ describe('Test FWorkbook/FWorksheet UI mixin', () => {
const skeleton = worksheet.getSkeleton();
expect(skeleton == null || typeof skeleton === 'object').toBe(true);
});
+
+ it('workbook and worksheet render facade methods should use render services and command ids consistently', async () => {
+ const sheetSize = 100;
+ const rowHeader = { setCustomHeader: vi.fn() };
+ const columnHeader = { setCustomHeader: vi.fn() };
+ const mainComponent = { makeDirty: vi.fn() };
+ const visibleRange = { startRow: 1, endRow: 4, startColumn: 2, endColumn: 6 };
+ const visibleRanges = new Map([[SHEET_VIEWPORT_KEY.VIEW_MAIN, visibleRange]]);
+ const skeleton = {
+ getVisibleRangeByViewport: vi.fn(() => visibleRange),
+ getVisibleRanges: vi.fn(() => visibleRanges),
+ };
+ const worksheetSkeleton = { skeleton: { id: 'sheet-skeleton' } };
+ const skeletonManager = {
+ reCalculate: vi.fn(),
+ getCurrentSkeleton: vi.fn(() => skeleton),
+ getWorksheetSkeleton: vi.fn(() => worksheetSkeleton),
+ setColumnHeaderSize: vi.fn(),
+ setRowHeaderSize: vi.fn(),
+ };
+ const scrollState = {
+ offsetX: 12,
+ offsetY: 24,
+ sheetViewStartColumn: 3,
+ sheetViewStartRow: 5,
+ };
+ const validViewportScrollInfo$ = {
+ subscribe: vi.fn((callback: (params: typeof scrollState) => void) => {
+ callback(scrollState);
+ return { unsubscribe: vi.fn() };
+ }),
+ };
+ const scrollManager = {
+ getScrollStateByParam: vi.fn(() => scrollState),
+ validViewportScrollInfo$,
+ };
+ const scrollRenderController = { scrollToCell: vi.fn() };
+ const selectionRenderService = {
+ disableSelection: vi.fn(),
+ enableSelection: vi.fn(),
+ transparentSelection: vi.fn(),
+ showSelection: vi.fn(),
+ };
+ const render = {
+ components: new Map([
+ [SHEET_VIEW_KEY.ROW, rowHeader],
+ [SHEET_VIEW_KEY.COLUMN, columnHeader],
+ ]),
+ mainComponent,
+ with: vi.fn((service: unknown) => {
+ if (service === SheetSkeletonManagerService) {
+ return skeletonManager;
+ }
+
+ if (service === SheetsScrollRenderController) {
+ return scrollRenderController;
+ }
+
+ if (service === SheetScrollManagerService) {
+ return scrollManager;
+ }
+
+ if (service === ISheetSelectionRenderService) {
+ return selectionRenderService;
+ }
+
+ throw new Error(`Unexpected render service: ${String(service)}`);
+ }),
+ };
+ const testBed = createFacadeTestBed(undefined, [
+ [IEditorBridgeService, { useClass: EditorBridgeService }],
+ [IEditorService, { useClass: EditorService }],
+ [DocSelectionManagerService],
+ [IDefinedNamesService, { useClass: DefinedNamesService }],
+ [IRefSelectionsService, { useClass: RefSelectionsService }],
+ [SheetsSelectionsService],
+ ]);
+
+ const workbook = testBed.univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet()!;
+ const renderManagerService = testBed.get(IRenderManagerService);
+ vi.spyOn(renderManagerService, 'getRenderById').mockReturnValue(render as never);
+ const commandService = testBed.get(ICommandService);
+ const executeSpy = vi.spyOn(commandService, 'executeCommand').mockResolvedValue(true as never);
+ const syncExecuteSpy = vi.spyOn(commandService, 'syncExecuteCommand').mockReturnValue(true as never);
+ const onScrollSpy = vi.fn();
+
+ expect(worksheet.refreshCanvas()).toBe(worksheet);
+ expect(skeletonManager.reCalculate).toHaveBeenCalledTimes(1);
+ expect(mainComponent.makeDirty).toHaveBeenCalledTimes(1);
+
+ expect(worksheet.getVisibleRange()).toEqual(visibleRange);
+ expect(worksheet.getVisibleRangesOfAllViewports()).toEqual(visibleRanges);
+
+ expect(worksheet.scrollToCell(9, 8, 120)).toBe(worksheet);
+ expect(scrollRenderController.scrollToCell).toHaveBeenCalledWith(9, 8, 120);
+
+ expect(worksheet.getScrollState()).toEqual(scrollState);
+
+ const onScrollDisposable = worksheet.onScroll(onScrollSpy);
+ expect(onScrollSpy).toHaveBeenCalledWith(scrollState);
+ expect(onScrollDisposable).toBeTruthy();
+
+ expect(worksheet.getSkeleton()).toEqual(worksheetSkeleton.skeleton);
+
+ expect(worksheet.autoResizeColumn(2)).toBe(worksheet);
+ expect(worksheet.setColumnAutoWidth(4, 3)).toBe(worksheet);
+ expect(worksheet.autoResizeRows(1, 2)).toBe(worksheet);
+ expect(syncExecuteSpy).toHaveBeenCalledWith(SetWorksheetColAutoWidthCommand.id, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startColumn: 2, endColumn: 2, startRow: 0, endRow: sheetSize - 1 }],
+ });
+ expect(syncExecuteSpy).toHaveBeenCalledWith(SetWorksheetColAutoWidthCommand.id, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startColumn: 4, endColumn: 6, startRow: 0, endRow: sheetSize - 1 }],
+ });
+ expect(syncExecuteSpy).toHaveBeenCalledWith(SetWorksheetRowIsAutoHeightCommand.id, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ ranges: [{ startRow: 1, endRow: 2, startColumn: 0, endColumn: sheetSize - 1 }],
+ });
+
+ workbook.customizeColumnHeader({ columnsCfg: { 0: 'A' } });
+ workbook.customizeRowHeader({ rowsCfg: { 0: '1' } });
+ worksheet.customizeColumnHeader({ headerStyle: { size: 28 } });
+ worksheet.customizeRowHeader({ headerStyle: { size: 18 } });
+
+ expect(columnHeader.setCustomHeader).toHaveBeenCalledWith({ columnsCfg: { 0: 'A' } });
+ expect(rowHeader.setCustomHeader).toHaveBeenCalledWith({ rowsCfg: { 0: '1' } });
+ expect(skeletonManager.setColumnHeaderSize).toHaveBeenCalledWith(render, worksheet.getSheetId(), 28);
+ expect(skeletonManager.setRowHeaderSize).toHaveBeenCalledWith(render, worksheet.getSheetId(), 18);
+ expect(columnHeader.setCustomHeader).toHaveBeenCalledWith({ headerStyle: { size: 28 } }, worksheet.getSheetId());
+ expect(rowHeader.setCustomHeader).toHaveBeenCalledWith({ headerStyle: { size: 18 } }, worksheet.getSheetId());
+
+ expect(worksheet.setColumnHeaderHeight(36)).toBe(worksheet);
+ expect(worksheet.setRowHeaderWidth(22)).toBe(worksheet);
+ expect(executeSpy).toHaveBeenCalledWith(SetColumnHeaderHeightCommand.id, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ size: 36,
+ });
+ expect(executeSpy).toHaveBeenCalledWith(SetRowHeaderWidthCommand.id, {
+ unitId: workbook.getId(),
+ subUnitId: worksheet.getSheetId(),
+ size: 22,
+ });
+
+ expect(workbook.getScrollStateBySheetId(worksheet.getSheetId())).toEqual(scrollState);
+ expect(workbook.disableSelection()).toBe(workbook);
+ expect(workbook.enableSelection()).toBe(workbook);
+ expect(workbook.transparentSelection()).toBe(workbook);
+ expect(workbook.showSelection()).toBe(workbook);
+ expect(selectionRenderService.disableSelection).toHaveBeenCalledTimes(1);
+ expect(selectionRenderService.enableSelection).toHaveBeenCalledTimes(1);
+ expect(selectionRenderService.transparentSelection).toHaveBeenCalledTimes(1);
+ expect(selectionRenderService.showSelection).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/sheets-ui/src/menu/__tests__/menu-factories.spec.ts b/packages/sheets-ui/src/menu/__tests__/menu-factories.spec.ts
index 7e4c49a542..f051f5af90 100644
--- a/packages/sheets-ui/src/menu/__tests__/menu-factories.spec.ts
+++ b/packages/sheets-ui/src/menu/__tests__/menu-factories.spec.ts
@@ -14,14 +14,34 @@
* limitations under the License.
*/
-import type { Univer } from '@univerjs/core';
+import type { IRange, Univer, Workbook } from '@univerjs/core';
+import type { Observable } from 'rxjs';
import {
+ BooleanNumber,
+ BorderStyleTypes,
+ FOCUSING_COMMON_DRAWINGS,
ICommandService,
+ IContextService,
Injector,
+
+ IUniverInstanceService,
RANGE_TYPE,
+ UniverInstanceType,
} from '@univerjs/core';
-import { SetSelectionsOperation, SetWorksheetHideCommand, SheetsSelectionsService } from '@univerjs/sheets';
-import { firstValueFrom, take } from 'rxjs';
+import {
+ BorderStyleManagerService,
+ IExclusiveRangeService,
+ MergeCellController,
+ SetBorderBasicCommand,
+ SetBorderCommand,
+ SetRangeValuesMutation,
+ SetSelectionsOperation,
+ SetWorksheetHideCommand,
+ SheetsSelectionsService,
+ ToggleGridlinesCommand,
+ ToggleGridlinesMutation,
+} from '@univerjs/sheets';
+import { firstValueFrom, of, skip, take } from 'rxjs';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
SetRangeFontDecreaseCommand,
@@ -29,11 +49,13 @@ import {
SetRangeFontSizeCommand,
} from '../../commands/commands/inline-format.command';
import { ShowMenuListCommand } from '../../commands/commands/unhide.command';
+import { CellBorderSelectorMenuItemFactory } from '../border.menu';
import {
FontSizeDecreaseMenuItemFactory,
FontSizeIncreaseMenuItemFactory,
FontSizeSelectorMenuItemFactory,
} from '../font.menu';
+import { ToggleGridlinesMenuFactory } from '../gridlines.menu';
import {
ColInsertMenuItemFactory,
InsertColAfterMenuItemFactory,
@@ -50,6 +72,7 @@ import {
InsertRowBeforeMenuItemFactory,
RowInsertMenuItemFactory,
} from '../insert.menu';
+import { CellMergeMenuItemFactory } from '../merge.menu';
import {
ChangeColorSheetMenuItemFactory,
CopySheetMenuItemFactory,
@@ -63,7 +86,7 @@ import { createMenuTestBed } from './create-menu-test-bed';
describe('menu factories', () => {
let univer: Univer;
- let get: any;
+ let get: Injector['get'];
let commandService: ICommandService;
let selectionService: SheetsSelectionsService;
@@ -80,23 +103,29 @@ describe('menu factories', () => {
univer.dispose();
});
- function setSingleSelection(startRow: number, startColumn: number, endRow: number, endColumn: number) {
- selectionService.setSelections([
- {
- range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
- primary: {
- startRow,
- startColumn,
- endRow,
- endColumn,
- actualRow: startRow,
- actualColumn: startColumn,
- isMerged: false,
- isMergedMainCell: false,
- },
- style: null,
+ function createSelection(startRow: number, startColumn: number, endRow: number, endColumn: number) {
+ return {
+ range: { startRow, startColumn, endRow, endColumn, rangeType: RANGE_TYPE.NORMAL },
+ primary: {
+ startRow,
+ startColumn,
+ endRow,
+ endColumn,
+ actualRow: startRow,
+ actualColumn: startColumn,
+ isMerged: false,
+ isMergedMainCell: false,
},
- ]);
+ style: null,
+ };
+ }
+
+ function setSelections(ranges: IRange[]) {
+ selectionService.setSelections(ranges.map((range) => createSelection(range.startRow, range.startColumn, range.endRow, range.endColumn)), 2);
+ }
+
+ function setSingleSelection(startRow: number, startColumn: number, endRow: number, endColumn: number) {
+ setSelections([{ startRow, startColumn, endRow, endColumn }]);
}
it('creates base insert selectors and header insert commands', async () => {
@@ -169,7 +198,82 @@ describe('menu factories', () => {
expect(await firstValueFrom(hideSheet.disabled$!.pipe(take(1)))).toBe(true);
expect(await firstValueFrom(unhideSheet.disabled$!.pipe(take(1)))).toBe(true);
expect(await firstValueFrom(showMenu.disabled$!.pipe(take(1)))).toBe(true);
- expect(await firstValueFrom((unhideSheet.selections as any).pipe(take(1)))).toEqual([]);
+ expect(await firstValueFrom((unhideSheet.selections as Observable<unknown[]>).pipe(take(1)))).toEqual([]);
+ });
+
+ it('updates gridlines menu activation after toggling sheet gridlines', async () => {
+ const injector = get(Injector);
+ const instanceService = get(IUniverInstanceService);
+ commandService.registerCommand(ToggleGridlinesCommand);
+ commandService.registerCommand(ToggleGridlinesMutation);
+
+ const menuItem = injector.invoke(ToggleGridlinesMenuFactory);
+ const worksheet = instanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getActiveSheet();
+ const initial = await firstValueFrom(menuItem.activated$!.pipe(take(1)));
+ expect(await firstValueFrom(menuItem.disabled$!.pipe(take(1)))).toBeTypeOf('boolean');
+
+ expect(await commandService.executeCommand(ToggleGridlinesCommand.id)).toBe(true);
+ const activatedAfterToggle = await firstValueFrom(menuItem.activated$!.pipe(take(1)));
+ expect(activatedAfterToggle).toBe(worksheet.getConfig().showGridlines === BooleanNumber.TRUE);
+ expect(activatedAfterToggle).not.toBe(initial);
+ });
+
+ it('updates border menu icon and hidden state from real border commands', async () => {
+ const injector = get(Injector);
+ const contextService = get(IContextService);
+ setSingleSelection(0, 0, 1, 1);
+
+ injector.add([BorderStyleManagerService]);
+ commandService.registerCommand(SetBorderBasicCommand);
+ commandService.registerCommand(SetBorderCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+
+ const menuItem = injector.invoke(CellBorderSelectorMenuItemFactory);
+ expect(await firstValueFrom((menuItem.icon as Observable<string>).pipe(take(1)))).toBe('AllBorderIcon');
+ expect(await firstValueFrom(menuItem.disabled$!.pipe(take(1)))).toBe(false);
+
+ const nextIcon = firstValueFrom((menuItem.icon as Observable<string>).pipe(skip(1), take(1)));
+ expect(await commandService.executeCommand(SetBorderBasicCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 }],
+ value: { type: 'top', color: '#123456', style: BorderStyleTypes.DASHED },
+ })).toBe(true);
+ expect(await nextIcon).toBe('UpBorderDoubleIcon');
+ expect(get(BorderStyleManagerService).getBorderInfo().type).toBe('top');
+
+ const hiddenState = firstValueFrom(menuItem.hidden$!.pipe(skip(1), take(1)));
+ contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+ expect(await hiddenState).toBe(true);
+ });
+
+ it('disables merge menu for overlapping multi-selections and hides it while drawing is focused', async () => {
+ const injector = get(Injector);
+ const contextService = get(IContextService);
+ injector.add([IExclusiveRangeService, { useValue: {
+ exclusiveRangesChange$: of({ unitId: 'test', subUnitId: 'sheet1', ranges: [] }),
+ addExclusiveRange: () => {},
+ getExclusiveRanges: () => undefined,
+ clearExclusiveRanges: () => {},
+ clearExclusiveRangesByGroupId: () => {},
+ getInterestGroupId: () => [],
+ } }]);
+ injector.add([MergeCellController]);
+
+ setSingleSelection(0, 0, 1, 1);
+ const menuItem = injector.invoke(CellMergeMenuItemFactory);
+ expect(await firstValueFrom(menuItem.disabled$!.pipe(take(1)))).toBe(false);
+ expect(await firstValueFrom(menuItem.hidden$!.pipe(take(1)))).toBeTypeOf('boolean');
+
+ setSelections([
+ { startRow: 0, startColumn: 0, endRow: 1, endColumn: 1 },
+ { startRow: 1, startColumn: 1, endRow: 2, endColumn: 2 },
+ ]);
+ expect(await firstValueFrom(menuItem.disabled$!.pipe(take(1)))).toBe(true);
+
+ const hiddenState = firstValueFrom(menuItem.hidden$!.pipe(skip(1), take(1)));
+ contextService.setContextValue(FOCUSING_COMMON_DRAWINGS, true);
+ expect(await hiddenState).toBe(true);
});
it('creates font-size menu items and exposes selector current value stream', async () => {
diff --git a/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts b/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts
new file mode 100644
index 0000000000..e6b0f0456f
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/auto-height.service.spec.ts
@@ -0,0 +1,196 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICommandInfo, ICommandService as ICommandServiceType, Workbook } from '@univerjs/core';
+import type { Engine, IRenderContext, Scene } from '@univerjs/engine-render';
+import { ICommandService, Injector, UniverInstanceType } from '@univerjs/core';
+import { MarkDirtyRowAutoHeightMutation, SetWorksheetRowAutoHeightMutation } from '@univerjs/sheets';
+import { BehaviorSubject } from 'rxjs';
+import { describe, expect, it, vi } from 'vitest';
+import { AutoHeightService, taskRowsFromRanges } from '../auto-height.service';
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+
+interface IIdleGlobals {
+ requestIdleCallback: (callback: IdleRequestCallback, options?: IdleRequestOptions) => number;
+}
+
+function createRenderContext(unitId: string): IRenderContext<Workbook> {
+ const activated$ = new BehaviorSubject(true);
+ const unit = {
+ getUnitId: () => unitId,
+ type: UniverInstanceType.UNIVER_SHEET,
+ } as unknown as Workbook;
+
+ return {
+ unit,
+ unitId,
+ type: UniverInstanceType.UNIVER_SHEET,
+ engine: {} as unknown as Engine,
+ scene: {} as unknown as Scene,
+ mainComponent: null,
+ components: new Map(),
+ isMainScene: true,
+ activated$,
+ activate: () => activated$.next(true),
+ deactivate: () => activated$.next(false),
+ };
+}
+
+describe('taskRowsFromRanges', () => {
+ it('splits ranges by max rows and keeps remains', () => {
+ const { result, lasts } = taskRowsFromRanges(
+ [{ startRow: 0, endRow: 9, startColumn: 0, endColumn: 0 }],
+ 3
+ );
+
+ expect(result).toEqual([{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 }]);
+ expect(lasts).toEqual([{ startRow: 3, endRow: 9, startColumn: 0, endColumn: 0 }]);
+ });
+
+ it('returns all ranges when max rows is enough', () => {
+ const { result, lasts } = taskRowsFromRanges(
+ [
+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 },
+ { startRow: 5, endRow: 5, startColumn: 0, endColumn: 0 },
+ ],
+ 10
+ );
+
+ expect(result).toHaveLength(2);
+ expect(lasts).toEqual([]);
+ });
+});
+
+describe('AutoHeightService', () => {
+ it('starts auto height task and executes row-height mutation with calculated values', () => {
+ const calculateAutoHeightInRange = vi.fn(() => [
+ { row: 0, autoHeight: 30 },
+ { row: 1, autoHeight: 0 },
+ { row: 2, autoHeight: 20 },
+ ]);
+ const getRowHeight = vi.fn((row: number) => (row === 2 ? 20 : 10));
+ const skeleton = {
+ calculateAutoHeightInRange,
+ getRowHeight,
+ } as unknown;
+
+ const sheetSkeletonManagerService = {
+ getSkeleton: () => skeleton,
+ } as unknown;
+
+ const syncExecuteCommand = vi.fn();
+ const onCommandExecuted = vi.fn(() => ({ dispose: () => { } }));
+ const commandService = {
+ syncExecuteCommand,
+ onCommandExecuted,
+ } as unknown;
+
+ // Make requestIdleCallback run "once" synchronously.
+ // `AutoHeightService` schedules another idle callback after processing; if we
+ // call callbacks immediately every time, it becomes infinite recursion.
+ let ran = false;
+ const idleGlobals = globalThis as unknown as IIdleGlobals;
+ const requestIdleCallbackSpy = vi
+ .spyOn(idleGlobals, 'requestIdleCallback')
+ .mockImplementation((cb) => {
+ if (!ran) {
+ ran = true;
+ cb({ timeRemaining: () => 100, didTimeout: false } as IdleDeadline);
+ }
+ return 1;
+ });
+
+ const context = createRenderContext('u-1');
+ const injector = new Injector();
+ injector.add([SheetSkeletonManagerService, { useValue: sheetSkeletonManagerService as unknown as SheetSkeletonManagerService }]);
+ injector.add([ICommandService, { useValue: commandService as unknown as ICommandServiceType }]);
+ const service = injector.createInstance(AutoHeightService, context);
+
+ service.startAutoHeightTask({
+ id: 't-1',
+ sheetId: 's-1',
+ ranges: [{ startRow: 0, endRow: 2, startColumn: 5, endColumn: 8 }],
+ });
+
+ // Only rows with changed autoHeight should be synced.
+ expect(syncExecuteCommand).toHaveBeenCalledWith(SetWorksheetRowAutoHeightMutation.id, {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ rowsAutoHeightInfo: [{ row: 0, autoHeight: 30 }],
+ });
+
+ // Ensures it "normalizes" ranges to column 0 in the task.
+ expect(calculateAutoHeightInRange).toHaveBeenCalledWith([
+ { startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 },
+ ]);
+
+ service.dispose();
+ requestIdleCallbackSpy.mockRestore();
+ });
+
+ it('wires command executed listener for mark-dirty mutation', () => {
+ const sheetSkeletonManagerService = {
+ getSkeleton: () => ({
+ calculateAutoHeightInRange: () => [],
+ getRowHeight: () => 10,
+ }),
+ } as unknown;
+
+ const commandHandlers: Array<(info: ICommandInfo) => void> = [];
+ const commandService = {
+ syncExecuteCommand: vi.fn(),
+ onCommandExecuted: (cb: (info: ICommandInfo) => void) => {
+ commandHandlers.push(cb);
+ return { dispose: () => { } };
+ },
+ } as unknown;
+
+ let ran = false;
+ const idleGlobals = globalThis as unknown as IIdleGlobals;
+ const requestIdleCallbackSpy = vi
+ .spyOn(idleGlobals, 'requestIdleCallback')
+ .mockImplementation((cb) => {
+ if (!ran) {
+ ran = true;
+ cb({ timeRemaining: () => 0, didTimeout: false } as IdleDeadline);
+ }
+ return 1;
+ });
+
+ const context = createRenderContext('u-1');
+ const injector = new Injector();
+ injector.add([SheetSkeletonManagerService, { useValue: sheetSkeletonManagerService as unknown as SheetSkeletonManagerService }]);
+ injector.add([ICommandService, { useValue: commandService as unknown as ICommandServiceType }]);
+ const service = injector.createInstance(AutoHeightService, context);
+
+ expect(commandHandlers).toHaveLength(1);
+ commandHandlers[0]({
+ id: MarkDirtyRowAutoHeightMutation.id,
+ params: {
+ unitId: 'u-1',
+ subUnitId: 's-1',
+ ranges: [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 1 }],
+ id: 'task',
+ },
+ });
+
+ // It should not throw, and should eventually schedule a loop.
+ expect(requestIdleCallbackSpy).toHaveBeenCalled();
+
+ service.dispose();
+ requestIdleCallbackSpy.mockRestore();
+ });
+});
diff --git a/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts
new file mode 100644
index 0000000000..b68d697d5c
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/hover-manager.service.spec.ts
@@ -0,0 +1,286 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IUniverInstanceService } from '@univerjs/core';
+import type { IRenderManagerService } from '@univerjs/engine-render';
+import { SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';
+import { BehaviorSubject, Subject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { HoverManagerService } from '../hover-manager.service';
+import { SheetScrollManagerService } from '../scroll-manager.service';
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+
+describe('HoverManagerService', () => {
+ it('emits row/col header hover and click positions based on active viewport', () => {
+ const workbook = {
+ getUnitId: () => 'u-1',
+ getActiveSheet: () => ({
+ getSheetId: () => 'sheet1',
+ }),
+ };
+
+ const unitDisposed$ = new Subject<any>();
+ const currentSheet$ = new BehaviorSubject<any>(workbook);
+
+ const univerInstanceService: Partial<IUniverInstanceService> = {
+ getUnit: () => workbook as any,
+ getCurrentTypeOfUnit$: () => currentSheet$.asObservable() as any,
+ unitDisposed$: unitDisposed$.asObservable() as any,
+ };
+
+ const skeleton = {
+ getRowIndexByOffsetY: () => 5,
+ getColumnIndexByOffsetX: () => 3,
+ };
+
+ const rowViewport = {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_ROW_TOP,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ isHit: (vec: { x: number }) => vec.x < 50,
+ };
+
+ const colViewport = {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ isHit: (vec: { x: number }) => vec.x >= 50,
+ };
+
+ const render = {
+ scene: {
+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),
+ getViewports: () => [rowViewport, colViewport],
+ },
+ with: (token: unknown) => {
+ if (token === SheetSkeletonManagerService) {
+ return {
+ getSkeletonParam: () => ({ skeleton, sheetId: 'sheet1' }),
+ };
+ }
+ if (token === SheetScrollManagerService) {
+ return {
+ getCurrentScrollState: () => ({ sheetViewStartRow: 0, sheetViewStartColumn: 0, offsetX: 0, offsetY: 0 }),
+ };
+ }
+ return null;
+ },
+ };
+
+ const renderManagerService: Partial<IRenderManagerService> = {
+ getRenderById: () => render as any,
+ };
+
+ const service = new HoverManagerService(univerInstanceService as IUniverInstanceService, renderManagerService as IRenderManagerService);
+
+ let hoveredRow: any = null;
+ service.currentHoveredRowHeader$.subscribe((v) => {
+ hoveredRow = v;
+ });
+
+ let hoveredCol: any = null;
+ service.currentHoveredColHeader$.subscribe((v) => {
+ hoveredCol = v;
+ });
+
+ const rowClicks: any[] = [];
+ service.currentRowHeaderClick$.subscribe((v) => rowClicks.push(v));
+
+ const colClicks: any[] = [];
+ service.currentColHeaderClick$.subscribe((v) => colClicks.push(v));
+
+ service.triggerRowHeaderMouseMove('u-1', 10, 10);
+ expect(hoveredRow).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 5 });
+
+ service.triggerColHeaderMouseMove('u-1', 100, 10);
+ expect(hoveredCol).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 3 });
+
+ service.triggerRowHeaderClick('u-1', 10, 10);
+ expect(rowClicks[0]).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 5 });
+
+ service.triggerColHeaderClick('u-1', 100, 10);
+ expect(colClicks[0]).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 3 });
+
+ service.dispose();
+ });
+
+ it('emits cell hover/click/pointer events and supports header dbclick/pointer branches', () => {
+ const workbook = {
+ getUnitId: () => 'u-1',
+ getActiveSheet: () => ({
+ getSheetId: () => 'sheet1',
+ getCell: () => null,
+ }),
+ };
+
+ const unitDisposed$ = new Subject<any>();
+ const currentSheet$ = new BehaviorSubject<any>(workbook);
+
+ const univerInstanceService: Partial<IUniverInstanceService> = {
+ getUnit: () => workbook as any,
+ getCurrentTypeOfUnit$: () => currentSheet$.asObservable() as any,
+ unitDisposed$: unitDisposed$.asObservable() as any,
+ };
+
+ const mainViewport = {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_MAIN,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ isHit: () => true,
+ };
+
+ const skeleton = {
+ worksheet: {
+ getMergedCell: () => null,
+ },
+ overflowCache: {
+ forValue: (_handler: (r: number, c: number, range: any) => void) => { },
+ },
+ getCellIndexByOffset: () => ({ row: 1, column: 1 }),
+ getCellWithCoordByIndex: () => ({
+ actualRow: 1,
+ actualColumn: 1,
+ mergeInfo: {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 1,
+ endColumn: 1,
+ startX: 100,
+ endX: 200,
+ startY: 20,
+ endY: 40,
+ },
+ }),
+ getOffsetByColumn: (column: number) => (column + 1) * 100,
+ getOffsetByRow: (row: number) => (row + 1) * 20,
+ getFont: () => null,
+ getRowIndexByOffsetY: () => 5,
+ getColumnIndexByOffsetX: () => 3,
+ };
+
+ const rowViewport = {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_ROW_TOP,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ isHit: (vec: { x: number }) => vec.x < 50,
+ };
+
+ const colViewport = {
+ viewportKey: SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ isHit: (vec: { x: number }) => vec.x >= 50,
+ };
+
+ const render = {
+ scene: {
+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),
+ getViewports: () => [rowViewport, colViewport, mainViewport],
+ getActiveViewportByCoord: () => mainViewport,
+ },
+ with: (token: unknown) => {
+ if (token === SheetSkeletonManagerService) {
+ return {
+ getSkeletonParam: () => ({ skeleton, sheetId: 'sheet1' }),
+ };
+ }
+ if (token === SheetScrollManagerService) {
+ return {
+ getCurrentScrollState: () => ({ sheetViewStartRow: 0, sheetViewStartColumn: 0, offsetX: 0, offsetY: 0 }),
+ };
+ }
+ return null;
+ },
+ };
+
+ const renderManagerService: Partial<IRenderManagerService> = {
+ getRenderById: () => render as any,
+ };
+
+ const service = new HoverManagerService(univerInstanceService as IUniverInstanceService, renderManagerService as IRenderManagerService);
+
+ let currentCellWithEvent: any = null;
+ service.currentCellPosWithEvent$.subscribe((v) => {
+ currentCellWithEvent = v;
+ });
+
+ const pointerDowns: any[] = [];
+ service.currentPointerDownCell$.subscribe((v) => pointerDowns.push(v));
+ const pointerUps: any[] = [];
+ service.currentPointerUpCell$.subscribe((v) => pointerUps.push(v));
+ const clicks: any[] = [];
+ service.currentClickedCell$.subscribe((v) => clicks.push(v));
+ const dbClicks: any[] = [];
+ service.currentDbClickedCell$.subscribe((v) => dbClicks.push(v));
+
+ const rowDbClicks: any[] = [];
+ service.currentRowHeaderDbClick$.subscribe((v) => rowDbClicks.push(v));
+ const colDbClicks: any[] = [];
+ service.currentColHeaderDbClick$.subscribe((v) => colDbClicks.push(v));
+ const rowPointerDowns: any[] = [];
+ service.currentRowHeaderPointerDown$.subscribe((v) => rowPointerDowns.push(v));
+ const colPointerDowns: any[] = [];
+ service.currentColHeaderPointerDown$.subscribe((v) => colPointerDowns.push(v));
+ const rowPointerUps: any[] = [];
+ service.currentRowHeaderPointerUp$.subscribe((v) => rowPointerUps.push(v));
+ const colPointerUps: any[] = [];
+ service.currentColHeaderPointerUp$.subscribe((v) => colPointerUps.push(v));
+
+ const event = { offsetX: 150, offsetY: 30 } as any;
+ service.triggerMouseMove('u-1', event);
+ service.triggerPointerDown('u-1', event);
+ service.triggerPointerUp('u-1', event);
+ service.triggerClick('u-1', 150, 30);
+ service.triggerDbClick('u-1', 150, 30);
+
+ expect(currentCellWithEvent).toEqual(
+ expect.objectContaining({
+ unitId: 'u-1',
+ subUnitId: 'sheet1',
+ row: 1,
+ col: 1,
+ event,
+ })
+ );
+ expect(pointerDowns.at(-1)).toEqual(expect.objectContaining({ unitId: 'u-1', row: 1, col: 1 }));
+ expect(pointerUps.at(-1)).toEqual(expect.objectContaining({ unitId: 'u-1', row: 1, col: 1 }));
+ expect(clicks.at(-1)).toEqual(expect.objectContaining({ location: expect.objectContaining({ row: 1, col: 1 }) }));
+ expect(dbClicks.at(-1)).toEqual(expect.objectContaining({ location: expect.objectContaining({ row: 1, col: 1 }) }));
+
+ service.triggerRowHeaderDbClick('u-1', 10, 10);
+ service.triggerColHeaderDbClick('u-1', 100, 10);
+ service.triggerRowHeaderPoniterDown('u-1', 10, 10);
+ service.triggerColHeaderPoniterDown('u-1', 100, 10);
+ service.triggerRowHeaderPoniterUp('u-1', 10, 10);
+ service.triggerColHeaderPoniterUp('u-1', 100, 10);
+
+ expect(rowDbClicks.at(-1)).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 5 });
+ expect(colDbClicks.at(-1)).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 3 });
+ expect(rowPointerDowns.at(-1)).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 5 });
+ expect(colPointerDowns.at(-1)).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 3 });
+ expect(rowPointerUps.at(-1)).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 5 });
+ expect(colPointerUps.at(-1)).toEqual({ unitId: 'u-1', subUnitId: 'sheet1', index: 3 });
+
+ service.triggerScroll();
+ let currentPos: any;
+ service.currentPosition$.subscribe((v) => {
+ currentPos = v;
+ });
+ expect(currentPos).toBeNull();
+
+ service.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts
new file mode 100644
index 0000000000..1f13a67890
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/scroll-manager.service.spec.ts
@@ -0,0 +1,134 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Workbook } from '@univerjs/core';
+import type { Engine, IRenderContext, Scene } from '@univerjs/engine-render';
+import { Injector, UniverInstanceType } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { SheetScrollManagerService } from '../scroll-manager.service';
+import { SheetSkeletonManagerService } from '../sheet-skeleton-manager.service';
+
+function createRenderContext(unitId: string): IRenderContext<Workbook> {
+ const activated$ = new BehaviorSubject(true);
+ const unit = {
+ getUnitId: () => unitId,
+ type: UniverInstanceType.UNIVER_SHEET,
+ } as unknown as Workbook;
+
+ return {
+ unit,
+ unitId,
+ type: UniverInstanceType.UNIVER_SHEET,
+ engine: {} as unknown as Engine,
+ scene: {} as unknown as Scene,
+ mainComponent: null,
+ components: new Map(),
+ isMainScene: true,
+ activated$,
+ activate: () => activated$.next(true),
+ deactivate: () => activated$.next(false),
+ };
+}
+
+describe('SheetScrollManagerService', () => {
+ it('returns an empty scroll state when no search param is set', () => {
+ const injector = new Injector();
+ injector.add([SheetSkeletonManagerService, { useValue: { getCurrentSkeleton: () => null } as unknown as SheetSkeletonManagerService }]);
+ const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+
+ expect(service.getCurrentScrollState()).toEqual({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ });
+ });
+
+ it('stores and retrieves scroll state by sheet', () => {
+ const injector = new Injector();
+ injector.add([SheetSkeletonManagerService, { useValue: { getCurrentSkeleton: () => null } as unknown as SheetSkeletonManagerService }]);
+ const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+
+ service.setSearchParam({ unitId: 'u-1', sheetId: 's-1' });
+ service.setValidScrollState({
+ unitId: 'u-1',
+ sheetId: 's-1',
+ sheetViewStartRow: 5,
+ sheetViewStartColumn: 2,
+ offsetX: 10,
+ offsetY: 20,
+ });
+
+ expect(service.getCurrentScrollState()).toEqual({
+ sheetViewStartRow: 5,
+ sheetViewStartColumn: 2,
+ offsetX: 10,
+ offsetY: 20,
+ });
+
+ expect(service.getScrollStateByParam({ unitId: 'u-1', sheetId: 's-1' })).toEqual({
+ sheetViewStartRow: 5,
+ sheetViewStartColumn: 2,
+ offsetX: 10,
+ offsetY: 20,
+ });
+
+ expect(service.getScrollStateByParam({ unitId: 'u-1', sheetId: 's-2' })).toEqual({
+ sheetViewStartRow: 0,
+ sheetViewStartColumn: 0,
+ offsetX: 0,
+ offsetY: 0,
+ });
+ });
+
+ it('calculates viewport scroll based on skeleton accumulations', () => {
+ const injector = new Injector();
+ injector.add([
+ SheetSkeletonManagerService,
+ {
+ useValue: {
+ getCurrentSkeleton: () => ({
+ rowHeightAccumulation: [10, 25, 45],
+ columnWidthAccumulation: [100, 210, 330],
+ }),
+ } as unknown as SheetSkeletonManagerService,
+ },
+ ]);
+ const service = injector.createInstance(SheetScrollManagerService, createRenderContext('u-1'));
+
+ expect(service.calcViewportScrollFromRowColOffset(null)).toEqual({
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ });
+
+ expect(service.calcViewportScrollFromRowColOffset({
+ sheetViewStartRow: 2,
+ sheetViewStartColumn: 3,
+ offsetX: 7,
+ offsetY: 4,
+ scrollX: 0,
+ scrollY: 0,
+ viewportScrollX: 0,
+ viewportScrollY: 0,
+ })).toEqual({
+ // startRow-1 => rowHeightAccumulation[1] = 25
+ viewportScrollY: 29,
+ // startColumn-1 => columnWidthAccumulation[2] = 330
+ viewportScrollX: 337,
+ });
+ });
+});
diff --git a/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts b/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts
new file mode 100644
index 0000000000..c3d5bf65b6
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/sheet-bar.service.spec.ts
@@ -0,0 +1,62 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IScrollState } from '../../views/sheet-bar/sheet-bar-tabs/utils/slide-tab-bar';
+import { describe, expect, it, vi } from 'vitest';
+import { SheetBarService } from '../sheet-bar/sheet-bar.service';
+
+describe('SheetBarService', () => {
+ it('publishes sheet bar events and manages menu handler lifecycle', () => {
+ const service = new SheetBarService();
+
+ const renames: string[] = [];
+ const removes: string[] = [];
+ const scrolls: IScrollState[] = [];
+ const scrollXs: number[] = [];
+ const adds: number[] = [];
+
+ service.renameId$.subscribe((v) => renames.push(v));
+ service.removeId$.subscribe((v) => removes.push(v));
+ service.scroll$.subscribe((v) => scrolls.push(v));
+ service.scrollX$.subscribe((v) => scrollXs.push(v));
+ service.addSheet$.subscribe((v) => adds.push(v));
+
+ service.setRenameId('s1');
+ service.setRemoveId('s2');
+ service.setScroll({ leftEnd: false, rightEnd: true });
+ service.setScrollX(42);
+ service.setAddSheet(3);
+
+ expect(renames).toEqual(['s1']);
+ expect(removes).toEqual(['s2']);
+ expect(scrolls).toEqual([{ leftEnd: false, rightEnd: true }]);
+ expect(scrollXs).toEqual([42]);
+ expect(adds).toEqual([3]);
+
+ const handler = { handleSheetBarMenu: vi.fn() };
+ const disposable = service.registerSheetBarMenuHandler(handler);
+ service.triggerSheetBarMenu();
+ expect(handler.handleSheetBarMenu).toHaveBeenCalledTimes(1);
+
+ expect(() => service.registerSheetBarMenuHandler({ handleSheetBarMenu: vi.fn() })).toThrow(
+ 'There is already a context menu handler!'
+ );
+
+ disposable.dispose();
+ service.triggerSheetBarMenu();
+ expect(handler.handleSheetBarMenu).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.ts b/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.ts
new file mode 100644
index 0000000000..883d33b44d
--- /dev/null
+++ b/packages/sheets-ui/src/services/__tests__/status-bar.service.spec.ts
@@ -0,0 +1,80 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { FUNCTION_NAMES_MATH, FUNCTION_NAMES_STATISTICAL } from '@univerjs/engine-formula';
+import { describe, expect, it } from 'vitest';
+import { StatusBarService } from '../status-bar.service';
+
+describe('StatusBarService', () => {
+ it('filters status values based on count/counter rules', () => {
+ const service = new StatusBarService();
+
+ // With only one non-empty cell: should emit pattern but filter out all calculated metrics.
+ service.setState({
+ pattern: '0.00',
+ values: [
+ { func: FUNCTION_NAMES_STATISTICAL.COUNTA, value: 1 },
+ { func: FUNCTION_NAMES_STATISTICAL.COUNT, value: 1 },
+ { func: FUNCTION_NAMES_MATH.SUM, value: 10 },
+ { func: FUNCTION_NAMES_STATISTICAL.MIN, value: 10 },
+ { func: FUNCTION_NAMES_STATISTICAL.MAX, value: 10 },
+ ],
+ });
+
+ expect(service.getState()).toEqual({
+ pattern: '0.00',
+ values: [],
+ });
+
+ // With multiple cells but no numbers: only `COUNTA` should be kept.
+ service.setState({
+ pattern: null,
+ values: [
+ { func: FUNCTION_NAMES_STATISTICAL.COUNTA, value: 3 },
+ { func: FUNCTION_NAMES_STATISTICAL.COUNT, value: 0 },
+ { func: FUNCTION_NAMES_MATH.SUM, value: 0 },
+ { func: FUNCTION_NAMES_STATISTICAL.AVERAGE, value: 0 },
+ ],
+ });
+
+ expect(service.getState()).toEqual({
+ pattern: null,
+ values: [{ func: FUNCTION_NAMES_STATISTICAL.COUNTA, value: 3 }],
+ });
+
+ // With multiple numeric cells: all supported functions should be kept.
+ service.setState({
+ pattern: null,
+ values: [
+ { func: FUNCTION_NAMES_STATISTICAL.COUNTA, value: 3 },
+ { func: FUNCTION_NAMES_STATISTICAL.COUNT, value: 2 },
+ { func: FUNCTION_NAMES_MATH.SUM, value: 12 },
+ { func: FUNCTION_NAMES_STATISTICAL.MIN, value: 5 },
+ { func: FUNCTION_NAMES_STATISTICAL.MAX, value: 7 },
+ { func: FUNCTION_NAMES_STATISTICAL.AVERAGE, value: 6 },
+ ],
+ });
+
+ expect(service.getState()!.values.map((v) => v.func).sort()).toEqual([
+ FUNCTION_NAMES_STATISTICAL.AVERAGE,
+ FUNCTION_NAMES_STATISTICAL.COUNT,
+ FUNCTION_NAMES_STATISTICAL.COUNTA,
+ FUNCTION_NAMES_STATISTICAL.MAX,
+ FUNCTION_NAMES_STATISTICAL.MIN,
+ FUNCTION_NAMES_MATH.SUM,
+ ].sort());
+ });
+});
diff --git a/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-render-manager.service.spec.ts b/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-render-manager.service.spec.ts
new file mode 100644
index 0000000000..2ec6a92662
--- /dev/null
+++ b/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-render-manager.service.spec.ts
@@ -0,0 +1,100 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it, vi } from 'vitest';
+import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../../config/config';
+import { RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY, RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY } from '../../../views/permission/extensions/range-protection.render';
+import { worksheetProtectionKey } from '../../../views/permission/extensions/worksheet-permission.render';
+import { SheetPermissionRenderManagerService } from '../sheet-permission-render-manager.service';
+
+function createSpreadsheetWithExtensions(extensions: Record<string, unknown>) {
+ return {
+ getExtensionByKey: vi.fn((key: string) => extensions[key]),
+ makeDirty: vi.fn(),
+ };
+}
+
+describe('SheetPermissionRenderManagerService', () => {
+ it('updates all render extensions and marks spreadsheet dirty when strategy changes', () => {
+ const canViewExtension = { setShadowStrategy: vi.fn() };
+ const cannotViewExtension = { setShadowStrategy: vi.fn() };
+ const worksheetExtension = { setShadowStrategy: vi.fn() };
+ const spreadsheet = createSpreadsheetWithExtensions({
+ [RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY]: canViewExtension,
+ [RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY]: cannotViewExtension,
+ [worksheetProtectionKey]: worksheetExtension,
+ });
+
+ const configService = {
+ getConfig: vi.fn((key: string) => {
+ if (key === SHEETS_UI_PLUGIN_CONFIG_KEY) {
+ return {
+ protectedRangeShadow: 'non-viewable',
+ };
+ }
+ return null;
+ }),
+ };
+
+ const renderManagerService = {
+ getRenderAll: vi.fn(() => [{ mainComponent: spreadsheet }]),
+ };
+
+ const service = new SheetPermissionRenderManagerService(configService as any, renderManagerService as any);
+ const strategyValues: string[] = [];
+ service.getProtectedRangeShadowStrategy$().subscribe((v) => strategyValues.push(v));
+
+ expect(service.getProtectedRangeShadowStrategy()).toBe('non-viewable');
+
+ service.setProtectedRangeShadowStrategy('none');
+ expect(canViewExtension.setShadowStrategy).toHaveBeenCalledWith('none');
+ expect(cannotViewExtension.setShadowStrategy).toHaveBeenCalledWith('none');
+ expect(worksheetExtension.setShadowStrategy).toHaveBeenCalledWith('none');
+ expect(spreadsheet.makeDirty).toHaveBeenCalledWith(true);
+ expect(service.getProtectedRangeShadowStrategy()).toBe('none');
+ expect(strategyValues).toContain('none');
+
+ service.dispose();
+ });
+
+ it('keeps working when extensions do not implement shadow strategy', () => {
+ const spreadsheet = createSpreadsheetWithExtensions({
+ [RANGE_PROTECTION_CAN_VIEW_RENDER_EXTENSION_KEY]: {},
+ [RANGE_PROTECTION_CAN_NOT_VIEW_RENDER_EXTENSION_KEY]: null,
+ [worksheetProtectionKey]: undefined,
+ });
+
+ const configService = {
+ getConfig: vi.fn(() => ({
+ protectedRangeShadow: false,
+ })),
+ };
+
+ const renderManagerService = {
+ getRenderAll: vi.fn(() => [{ mainComponent: spreadsheet }]),
+ };
+
+ const service = new SheetPermissionRenderManagerService(configService as any, renderManagerService as any);
+
+ expect(service.getProtectedRangeShadowStrategy()).toBe('none');
+
+ service.setProtectedRangeShadowStrategy('non-editable');
+ expect(spreadsheet.makeDirty).not.toHaveBeenCalled();
+ expect(service.getProtectedRangeShadowStrategy()).toBe('non-editable');
+
+ service.dispose();
+ });
+});
diff --git a/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.ts b/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.ts
new file mode 100644
index 0000000000..de8cb17c28
--- /dev/null
+++ b/packages/sheets-ui/src/services/permission/__tests__/sheet-permission-user-list.service.spec.ts
@@ -0,0 +1,72 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ICollaborator } from '@univerjs/protocol';
+import { firstValueFrom, skip, take } from 'rxjs';
+import { describe, expect, it } from 'vitest';
+import { SheetPermissionUserManagerService } from '../sheet-permission-user-list.service';
+
+const OWNER: ICollaborator = {
+ id: 'u-owner',
+ role: 2,
+ subject: undefined,
+};
+
+const EDITOR: ICollaborator = {
+ id: 'u-editor',
+ role: 1,
+ subject: undefined,
+};
+
+describe('SheetPermissionUserManagerService', () => {
+ it('tracks editable users, selected users and historical collaborators', async () => {
+ const service = new SheetPermissionUserManagerService();
+
+ expect(service.userList).toEqual([]);
+ expect(service.oldCollaboratorList).toEqual([]);
+ expect(service.selectUserList).toEqual([]);
+ expect(await firstValueFrom(service.userList$.pipe(take(1)))).toEqual([]);
+ expect(await firstValueFrom(service.selectUserList$.pipe(take(1)))).toEqual([]);
+
+ const nextEditableUsers = firstValueFrom(service.userList$.pipe(skip(1), take(1)));
+ service.setCanEditUserList([OWNER, EDITOR]);
+ expect(service.userList).toEqual([OWNER, EDITOR]);
+ expect(await nextEditableUsers).toEqual([OWNER, EDITOR]);
+
+ service.setOldCollaboratorList([OWNER]);
+ expect(service.oldCollaboratorList).toEqual([OWNER]);
+
+ const nextSelectedUsers = firstValueFrom(service.selectUserList$.pipe(skip(1), take(1)));
+ service.setSelectUserList([EDITOR]);
+ expect(service.selectUserList).toEqual([EDITOR]);
+ expect(await nextSelectedUsers).toEqual([EDITOR]);
+ });
+
+ it('clears stored collaborator state on reset', async () => {
+ const service = new SheetPermissionUserManagerService();
+ service.setCanEditUserList([OWNER]);
+ service.setOldCollaboratorList([OWNER, EDITOR]);
+ service.setSelectUserList([EDITOR]);
+
+ const resetSelectedUsers = firstValueFrom(service.selectUserList$.pipe(skip(1), take(1)));
+ service.reset();
+
+ expect(service.userList).toEqual([]);
+ expect(service.oldCollaboratorList).toEqual([]);
+ expect(service.selectUserList).toEqual([]);
+ expect(await resetSelectedUsers).toEqual([]);
+ });
+});
diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts
new file mode 100644
index 0000000000..da4d701323
--- /dev/null
+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-control.spec.ts
@@ -0,0 +1,89 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { ThemeService } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { SelectionControl } from '../selection-control';
+
+function createFakeScene() {
+ return {
+ addObject: vi.fn(),
+ addObjects: vi.fn(),
+ getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),
+ onTransformChange$: { subscribeEvent: vi.fn(() => ({ dispose: vi.fn() })) },
+ } as any;
+}
+
+function createFakeThemeService() {
+ return {
+ getColorFromTheme: vi.fn((key: string) => (key === 'white' ? '#ffffff' : '#3b82f6')),
+ } as unknown as ThemeService;
+}
+
+describe('SelectionControl', () => {
+ it('updates range and shows/hides autofill based on primary', () => {
+ const scene = createFakeScene();
+ const themeService = createFakeThemeService();
+
+ const control = new SelectionControl(scene, 1, themeService, {
+ rowHeaderWidth: 46,
+ columnHeaderHeight: 20,
+ });
+
+ // No primary: should hide autofill.
+ control.updateRange(
+ {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ },
+ null
+ );
+ expect(control.fillControl.visible).toBe(false);
+
+ // With primary: should show autofill.
+ control.updateRange(
+ {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ },
+ {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ startX: 0,
+ startY: 0,
+ endX: 100,
+ endY: 20,
+ } as any
+ );
+ expect(control.fillControl.visible).toBe(true);
+
+ // Avoid disposing here: engine-render shapes expect a real Scene tree.
+ });
+});
diff --git a/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts
new file mode 100644
index 0000000000..76877c359e
--- /dev/null
+++ b/packages/sheets-ui/src/services/selection/__tests__/selection-render.service.spec.ts
@@ -0,0 +1,106 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRange } from '@univerjs/core';
+import type { ISelectionWithStyle } from '@univerjs/sheets';
+import { RANGE_TYPE } from '@univerjs/core';
+import { SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { IShortcutService } from '@univerjs/ui';
+import { describe, expect, it } from 'vitest';
+import { createRenderTestBed } from '../../../controllers/render-controllers/__tests__/render-test-bed';
+import { SheetSelectionRenderService } from '../selection-render.service';
+
+describe('SheetSelectionRenderService', () => {
+ it('renders selections from model changes and respects SELECTIONS_ENABLED', () => {
+ const testBed = createRenderTestBed({
+ dependencies: [
+ [IShortcutService, { useValue: {} }],
+ ],
+ });
+
+ const { injector, sheet, commandService, sheetSkeletonManagerService, skeleton, context } = testBed;
+ commandService.registerCommand(SetSelectionsOperation);
+
+ const renderService = injector.createInstance(SheetSelectionRenderService, context as any);
+
+ // Simulate initial skeleton ready (as if the sheet got rendered).
+ sheetSkeletonManagerService.emitCurrentSkeleton({
+ unitId: sheet.getUnitId(),
+ sheetId: 'sheet1',
+ skeleton: skeleton as any,
+ });
+
+ // The skeleton change listener ensures there is at least one selection.
+ expect(renderService.getSelectionControls().length).toBeGreaterThan(0);
+
+ const unitId = sheet.getUnitId();
+ const workbookSelections = injector.get(SheetsSelectionsService).getWorkbookSelections(unitId);
+ expect(workbookSelections.getCurrentSelections().length).toBeGreaterThan(0);
+
+ const range: IRange = {
+ startRow: 1,
+ endRow: 1,
+ startColumn: 2,
+ endColumn: 2,
+ rangeType: RANGE_TYPE.NORMAL,
+ };
+
+ const selection: ISelectionWithStyle = {
+ range,
+ primary: {
+ startRow: range.startRow,
+ endRow: range.endRow + 1,
+ startColumn: range.startColumn,
+ endColumn: range.endColumn + 1,
+ actualRow: range.startRow,
+ actualColumn: range.startColumn,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ };
+
+ // Update selections like a real command (keyboard / API / mouse drag end).
+ expect(commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: 'sheet1',
+ selections: [selection],
+ })).toBeTruthy();
+
+ expect(renderService.getSelectionControls().length).toBe(1);
+
+ renderService.disableSelection();
+ // When disabled, selection rendering should be cleared and should not create new selection controls.
+ expect(renderService.getSelectionControls().length).toBe(0);
+
+ expect(commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: 'sheet1',
+ selections: [selection, selection],
+ })).toBeTruthy();
+ expect(renderService.getSelectionControls().length).toBe(0);
+
+ renderService.enableSelection();
+ expect(commandService.syncExecuteCommand(SetSelectionsOperation.id, {
+ unitId,
+ subUnitId: 'sheet1',
+ selections: [selection],
+ })).toBeTruthy();
+ expect(renderService.getSelectionControls().length).toBe(1);
+
+ testBed.univer.dispose();
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6fdb17b5a3..a171232d18 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2331,6 +2331,15 @@ importers:
'@univerjs-infra/shared':
specifier: workspace:*
version: link:../../common/shared
+ '@univerjs/engine-formula':
+ specifier: workspace:*
+ version: link:../engine-formula
+ '@univerjs/engine-render':
+ specifier: workspace:*
+ version: link:../engine-render
+ '@univerjs/network':
+ specifier: workspace:*
+ version: link:../network
rxjs:
specifier: ^7.8.2
version: 7.8.2